For the record, I think your original answer is quite clean and readable. My only suggestion would be to consider using if not (predicate): (do something)
, as opposed to if (predicate): pass; else: (do something)
:
def sum13(nums):
sum = 0
for idx,val in enumerate(nums):
if not (val == 13 or (idx != 0 and nums[idx-1] == 13)):
sum += val
return sum
I like @Josay's suggestion of iterating over pairs of consecutive items. The easiest way to do this is by zip
ping the list with the list starting from index 1 -- i.e., zip(L, L[1:])
. From there, it's just a matter of taking the second item of each pair, unless either of the items == 13. In order to consider the very first item in the list, we'll prepend 0
onto the beginning of the list, so that the first pair is [0, first-item]
. In other words, we are going to zip
together [0] + L
(the list with 0 prepended) and L
(the list itself). Here are two slightly different versions of this approach:
Version 1, which is more similar to your original answer:
def sum13(nums):
sum = 0
for first, second in zip([0] + nums, nums):
if not 13 in (first, second):
sum += second
return sum
Version 2, a functional approach using a list comprehension:
def sum13(nums):
pairs = zip([0] + nums, nums)
allowed = lambda x, y: 13 not in (x, y) # not 13 or following a 13
return sum(y for x, y in pairs if allowed(x, y))
pass
in your code, something is wrong. Python doesn't really need apass
, it's there as a place holder for the "empty group", which is utterly useless except from a purely syntactical point of view. Any code that contains apass
can be trivially changed to something that doesn't have it and is more readable. \$\endgroup\$