使用Python辅助函数:循环排数与无青少年值求和实现
Got it, let's break this down with clean, modular code as requested—splitting the logic into two functions avoids repeating the teen-value check multiple times, which keeps things maintainable.
Step 1: The fix_teen Helper Function
First, we'll build the helper that handles the teen-value rule. It takes an integer n and returns 0 if n is a qualifying teen value (13-19 inclusive, excluding 15 and 16), otherwise it returns the original number.
def fix_teen(n): # Check if n falls in the teen range but isn't 15 or 16 if 13 <= n <= 19 and n not in (15, 16): return 0 return n
Step 2: The no_teen_sum Main Function
The main function is simple from here—we just apply the fix_teen helper to each input integer and sum up the corrected values.
def no_teen_sum(a, b, c): return fix_teen(a) + fix_teen(b) + fix_teen(c)
Test It With Examples
Let's run a few test cases to confirm it works as expected:
no_teen_sum(13, 15, 19)returns0 + 15 + 0 = 15no_teen_sum(2, 16, 17)returns2 + 16 + 0 = 18no_teen_sum(14, 15, 16)returns0 + 15 + 16 = 31
This modular approach means if you ever need to tweak the teen-value rules later, you only have to update the fix_teen function instead of editing three separate checks!
内容的提问来源于stack exchange,提问作者Samir Tendulkar

