patternpythonModerate
Return sum of three values, excluding values within a specified range
Viewed 0 times
threereturnrangeexcludingwithinsumvaluesspecified
Problem
Is there a way to make my code simpler?
Given three
values is a teen -- in the range
counts as 0, except 15 and 16 do not count as a teens. Write a
separate helper (
returns that value fixed for the teen rule. In this way, you avoid
repeating the teen code three times (i.e. "decomposition"). Define the
helper below and at the same indent level as the main
Given three
int values, (a, b, c) return their sum. However, if any of thevalues is a teen -- in the range
13..19 inclusive -- then that valuecounts as 0, except 15 and 16 do not count as a teens. Write a
separate helper (
def fix_teen(n)) that takes in an int value andreturns that value fixed for the teen rule. In this way, you avoid
repeating the teen code three times (i.e. "decomposition"). Define the
helper below and at the same indent level as the main
no_teen_sum(). no_teen_sum(1, 2, 3) → \$6\$no_teen_sum(2, 13, 1) → \$3\$no_teen_sum(2, 1, 14) → \$3\$def no_teen_sum(a, b, c):
if fix_teen(a) == 0 and fix_teen(b) == 0 and fix_teen(c) == 0:
return 0
elif fix_teen(a) != 0 and fix_teen(b) != 0 and fix_teen(c) != 0:
return a + b + c
elif (fix_teen(a) and fix_teen(b)) != 0:
return a + b
elif (fix_teen(b) and fix_teen(c)) != 0:
return b + c
elif (fix_teen(a) and fix_teen(c)) != 0:
return a + c
elif fix_teen(a) != 0:
return a
elif fix_teen(b) != 0:
return b
elif fix_teen(c) != 0:
return c
def fix_teen(n):
if n in [13, 14, 17, 18, 19]:
return 0
else:
return nSolution
I may be off the mark here as I didn't test my code (no access to a Python environment), but this is the way I'd 'start' to work at it.
Quite simple.
def no_teen_sum(a, b, c):
return fix_teen(a) + fix_teen(b) + fix_teen(c)
def fix_teen(n):
if n in [13, 14, 17, 18, 19]:
return 0
else:
return nQuite simple.
Code Snippets
def no_teen_sum(a, b, c):
return fix_teen(a) + fix_teen(b) + fix_teen(c)
def fix_teen(n):
if n in [13, 14, 17, 18, 19]:
return 0
else:
return nContext
StackExchange Code Review Q#97920, answer score: 12
Revisions (0)
No revisions yet.