Harsh
Harsh

Reputation: 1

Output should be Sum of numbers in array but not counting 13 and number following it

The Question

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.

this is a problem from coding bat.

my code**:**

def sum13(nums): 
    nums.append(0) 
    nums = [0 if nums[nums.index(x)-1] == 13 else x for x in nums] 
    nums = [0 if x == 13 else x for x in nums] 
    return (sum(nums))

where it's failing:

sum13[1, 2, 13, 2, 1, 13] should give output as 4 but my code is outputting 6.

sum13[13, 1, 2, 13, 2, 1, 13] should give output as 3 but my code is outputting 4.

Please help me.

Upvotes: 0

Views: 99

Answers (3)

TrebledJ
TrebledJ

Reputation: 9007

list.index() is not a reliable way of keeping track of the index in list-comprehensions.

Instead of relying on the index, and directly accessing the list in the comprehension, this could be solved by "looking into the future" (or "looking into the past", depending on perspective). We can do this by using zip().

>>> def f(nums): 
...   return [b for a, b in zip(nums, nums[1:]) if a != 13 and b != 13]
...
>>> f([0, 1, 2, 13, 2, 1, 13])
[1, 2, 1]
>>> f([0, 13, 1, 2, 13, 2, 1, 13])
[2, 1]

The comprehension above creates pairs of the previous (a) and current (b) value, then includes the current value if neither the previous nor current value are 13.

Hence, the solution

def sum13(nums): 
    nums = [0] + nums
    return sum(( b for a, b in zip(nums, nums[1:]) if a != 13 and b != 13 ))

Note that I replaced the list syntax [...] with generator syntax (...) for efficiency.

Another way of solving this (with list-comprehensions) is with enumerate().

def sum13(nums):
    nums = [0] + nums
    return sum(( x for i, x in enumerate(nums) if i > 0 and nums[i-1] != 13 and x != 13 ))

IMHO the first solution is more beautiful because all the necessary information is contained within the zip iterable whereas in the second solution, we need to access information outside the enumerate iterable (i.e. nums[i-1]).

Upvotes: 0

Chandresh
Chandresh

Reputation: 140

Easy to understand:

def sum13(nums):
    result = 0
    nums.insert(0,0)
    for i in range(len(nums)):
        if nums[i] != 13 and nums[i-1] != 13:
            result += nums[i]
    return result
l = sum13([13, 1, 2, 13, 2, 1, 13])
print(l)

output:

3

Upvotes: 0

Balaji Ambresh
Balaji Ambresh

Reputation: 5012

Here you go:

def sum13(nums):
    total = 0
    i = 0
    while i < len(nums):
        if nums[i] == 13:
            i += 2
            continue
        total += nums[i]
        i += 1
    return total

Upvotes: 1

Related Questions