Twil
Twil

Reputation: 107

Loop with i-1 doesn't find correct value

Task:

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.

Test sample, expected:

  1. sum13([1, 2, 13, 2, 1, 13]) → 4
  2. sum13([1, 2, 2, 1, 13]) → 6

My code yield following results:

  #sum13([1, 2, 13, 2, 1, 13]) → 3
  #sum13([1, 2, 2, 1, 13]) → 5

  def sum13(nums):
  s = 0
  if not nums:
    return 0
  for i in range(len(nums)):
    if nums[i]==13 or nums[i-1]==13:
      s += 0
    else:
      s += nums[i]
  return s

Why it doesn't count number before last 13 num ?

UPD:

Thanks for comments, understand the problem. Correct like this:

  def sum13(nums):
  s = 0
  if not nums:
    return 0
  for i in range(len(nums)):
    if nums[i]==13 or (nums[i-1]==13 and i-1>=0):
      s += 0
    else:
      s += nums[i]
  return s

Upvotes: 1

Views: 249

Answers (2)

PyPingu
PyPingu

Reputation: 1747

This is happening because for your first pass of the loop, i is -1.

I think you can try this version to give you what you want:

def sum13(nums):
    s = 0
    if nums:
        prev = False
        for i in range(len(nums)):
            if not prev and nums[i] != 13:
                s += nums[i]
            prev = nums[i] == 13
    return s

Upvotes: 1

Pratik Dekate
Pratik Dekate

Reputation: 44

Your loop is starting from 0 index so in first iteration you are checking if nums[0] == 13 or nums[-1] == 13 (in python -1 index will give you the last element of the list). So in both test case condition is true because last element is 13, that is the reason 1 is not being added in s. Solution is to start your index from 1.

Upvotes: 0

Related Questions