Skip to content
Advertisement

python: codingbat no_teen_sum – why my function isn’t working as expected?

Below is the code I used for the no_teen_sum and subsequent fixed_teen functions.

The first code is what I submitted – and worked for all test cases:

def no_teen_sum(a, b, c):
  # checks if value is a teen then child conditional checks whether
  # fix_teen passes the value, otherwise initialize the value as 0
  if 13 <= a <= 19:
    if fix_teen(a):
      a = a
    else:
      a = 0
  if 13 <= b <= 19:
    if fix_teen(b):
      b = b
    else:
      b = 0
  if 13 <= c <= 19:
    if fix_teen(c):
      c = c
    else:
      c = 0

  return a + b + c

And the fix_teen function that is called:

def fix_teen(n):
  # checks if n is 15 or 16 but checking if it is found in the set 
  # written this way to be expandable without becoming verbose
  if n in {15, 16}:
    return True

However, looking at this I saw a lot of repitition and realized maybe I had misread what the question was asking. It was valid in terms of finding a solution but not as clean as it could be. So I tried to work on an improvement.

Improved code:

def no_teen_sum(a, b, c):
    fix_teen(a)
    fix_teen(b)
    fix_teen(c)

    return a + b + c

And the modified fix_teen function:

def fix_teen(n):

    # checks if n is a teen
    if 13 <= n <= 19:

        # checks if n is 15 or 16 but checking if it is found in the set
        # if True then leave n as it is
        if n in {15, 16}:
            n = n
            return n

        # if it fails then n = 0
        else:
            n = 0
            return n

    # if n is not in the teens return it as is
    return n

The issue I am having for example a test case of (1, 2, 18) is that it returns 21. It should return 3. I tried putting print statements in between each ‘fix_teen’ call in the main function to see what value it had for a, b, c and it just left them as is (1, 2, 18) rather than (1, 2, 0)

The weird part is if I called fixed_teen(18) independently it returns 0.

Advertisement

Answer

Your no_teen_sum(a, b, c) function is returning a + b + c (which is literally what gets passed to the function)! You should make a, b and c equal to the result from the fix_teen function to get the desired result!

def no_teen_sum(a, b, c):
    a = fix_teen(a)
    b = fix_teen(b)
    c = fix_teen(c)

    return a + b + c
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement