Harel Levy
Harel Levy

Reputation: 9

Python: sum with if statement

The next exercise from CodingBat:

Given 2 ints, a and b, return their sum. However, sums in the range 10..19 inclusive, are forbidden, so in that case just return 20.

sorta_sum(3, 4) → 7

sorta_sum(9, 4) → 20

sorta_sum(10, 11) → 21

Here's my answer:

def sorta_sum(a, b):
  if a + b == range(10, 20):
    return 20
  else:
    return a + b

They said when a = 9 and b = 4 it should return 20 but mine return 13.

How come my if statement didn't apply and the else statement did? 9+4 is 13 and in my if statement everything in range from 10 to 19 should return 20.

Upvotes: 0

Views: 12399

Answers (3)

Ami Tavory
Ami Tavory

Reputation: 76297

IMHO, a Pythonic way to do so would be:

def sorta_sum(a, b):
    s = a + b
    return 20 if 10 <= s < 20 else s

Upvotes: 1

StephenTG
StephenTG

Reputation: 2647

range(10, 20) actually produces a list of numbers, which the sum a+b will not equal, being a single number. You should instead check if a+b in range(10,20):, to see if a+b is contained within the list of numbers in that range.

Alternatively, check if 10 <= a+b < 20:, to see if a+b is between 10 and 20

Upvotes: 0

skyking
skyking

Reputation: 14390

That's because you use a+b == range(10,20) instead of a+b in range(10,20).

The range(10,20) means a list of all integers in the specified range (under python2, in python3 it's just an iterator yielding those integers). This means that a+b which is normally an integer will not equal range(10,20).

To check this you could try sorta_sum([10,11,12,13,14], [15,16,17,18,19]) which should return 20 since adding the lists would produce the list of integers in the range which should equal range(10,20)

Also note that your approach is inefficient since it will result in comparing the result in comparing the result to each of the integers in the range. Instead you should probably check for the range using if 10 <= a+b < 20, perhaps you should also avoid repeating the addition:

def sorta_sum(a, b):
  s = a+b
  if 10 <= s < 20:
    return 20
  else:
    return s

Upvotes: 2

Related Questions