Skipping Elements In A List Python
Solution 1:
One tricky thing to notice is something like this: [1, 13, 13, 2, 3]
You need to skip 2
too
defgetSum(l):
sum = 0
skip = Falsefor i in l:
if i == 13:
skip = Truecontinueif skip:
skip = Falsecontinuesum += i
returnsum
Explanation:
You go through the items in the list one by one
Each time you
- First check if it's 13, if it is, then you mark
skip
asTrue
, so that you can also skip next item. - Second, you check if
skip
isTrue
, if it is, which means it's a item right after 13, so you need to skip this one too, and you also need to setskip
back toFalse
so that you don't skip next item. - Finally, if it's not either case above, you add the value up to
sum
Solution 2:
You can use the zip function to loop the values in pairs:
def special_sum(numbers):
s =0for (prev, current) in zip([None] + numbers[:-1], numbers):
if prev !=13and current != 13:
s += current
return s
or you can do a oneliner:
defspecial_sum(numbers):
returnsum(current for (prev, current) inzip([None] + numbers[:-1], numbers)
if prev != 13and current != 13)
You can also use iterators:
from itertools import izip, chain
defspecial_sum(numbers):
returnsum(current for (prev, current) in izip(chain([None], numbers), numbers)
if prev != 13and current != 13)
(the first list in the izip is longer than the second, zip and izip ignore the extra values).
Solution 3:
Use a while loop to walk through the list, incrementing i
manually. On each iteration, if you encounter a 13, increment i
twice; otherwise, add the value to a running sum and increment i
once.
defskip13s(l):
i = 0
s = 0while (i < len(l)):
if l[i] == 13:
i += 1else:
s += l[i]
i += 1return s
Solution 4:
Some FP-style :)
defadd_but_skip_13_and_next(acc, x):
prev, sum_ = acc
if prev != 13and x != 13:
sum_ += x
return x, sum_
filter_and_sum = lambda l: reduce(add_but_skip_13_and_next, l, (0,0))[1]
>>> print filter_and_sum([13,13,1,4])
4>>> print filter_and_sum([1,2,13,5,13,13,-9,13,13,13,13,13,1,1])
4
This code works for any iterator, even it not provide the random access (direct indexing) - socket for example :)
Oneliner :)
>>>filter_and_sum = lambda l: reduce(...lambda acc, x: (x, acc[1] + (x if x != 13and acc[0] != 13else0)),... l, (0,0))[1]>>>print filter_and_sum([1,2,13,5,13,13,-9,13,13,13,13,13,1,1])
4
Solution 5:
I think this is the most compact solution:
deftriskaidekaphobicSum(sequence):
returnsum(sequence[i] for i inrange(len(sequence))
if sequence[i] != 13and (i == 0or sequence[i-1] != 13))
This uses the builtin sum() function on a generator expression. The generator produces all the elements in the sequence as long as they are not 13, or immediately following a 13. The extra "or" condition is to handle the first item in the sequence (which has no previous item).
Post a Comment for "Skipping Elements In A List Python"