HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Python address index +1 with list comprehension

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
comprehensionaddresswithpythonindexlist

Problem

Task from CodingBat:


Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.

My original answer to the problem:

def sum13(nums):
  sum = 0
  for idx,val in enumerate(nums):
    if val == 13 or (idx != 0 and nums[idx-1] == 13):
      pass
    else:
      sum = sum + val

  return sum


Doing this with list comprehension, I came up with

return sum([x if x!=13 and nums[idx-1 if idx >0 else 0] !=13 else 0 for idx,x in enumerate(nums)])


Is there a way to make this cleaner?

Solution

EDIT: As pointed out by an anonymous user, my first version did not skip numbers that follow an even number of 13's.

Use an iterator. While you for loop over an iterator you can skip items with next.

def lucky_nums(nums):
    nums = iter(nums)
    for i in nums:
        if i == 13:
            while next(nums) == 13:
                pass
        else:
            yield i

print sum(lucky_nums([12,13,14,15]))

Code Snippets

def lucky_nums(nums):
    nums = iter(nums)
    for i in nums:
        if i == 13:
            while next(nums) == 13:
                pass
        else:
            yield i

print sum(lucky_nums([12,13,14,15]))

Context

StackExchange Code Review Q#49744, answer score: 12

Revisions (0)

No revisions yet.