You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无需使用if定义多参数函数?creepy函数编写问题求助

Hey there! Let's break down your two tech questions with practical, straightforward solutions:

1. Defining multi-parameter functions without if statements

if statements are useful, but they’re not the only way to handle conditional logic in functions. Here are a few clean alternatives tailored to different scenarios:

  • Dictionary mapping for action-based logic
    If your function needs to run different operations based on a parameter value, map those operations to a dictionary. For example, a calculator function that uses an operator parameter:

    def calculate(a, b, op):
        operations = {
            "add": lambda x, y: x + y,
            "subtract": lambda x, y: x - y,
            "multiply": lambda x, y: x * y,
            "divide": lambda x, y: x / y if y != 0 else None
        }
        return operations[op](a, b)
    
  • Ternary expressions for simple binary returns
    For straightforward "either/or" return values, use a ternary expression to keep code concise:

    def get_admission_status(score):
        return "Accepted" if score >= 75 else "Rejected"
    
  • Boolean indexing for fixed result sets
    Since Booleans in Python evaluate to 1 (True) and 0 (False), you can use them as indexes for a list of possible results:

    def get_task_outcome(succeeded):
        return ["Failed", "Completed"][succeeded]
    
  • Direct logical/mathematical expressions
    If your condition boils down to a simple boolean check, just return the expression's result directly—this is exactly what we'll do for your creepy function below.

2. Correct implementation of the creepy function

First, let's clarify the requirement: return True if the age pair violates the acceptable dating rule, False if it’s allowed. The core acceptable rule translates to: the younger person’s age must be at least half the older person’s age plus 7.

Here’s a clean, if-free implementation that meets all your needs:

def creepy(age1, age2):
    older_age = max(age1, age2)
    younger_age = min(age1, age2)
    # Return True if the younger person is too young relative to the older one
    return younger_age < (older_age / 2) + 7

Or even more concise (same logic, just condensed):

def creepy(age1, age2):
    return min(age1, age2) < max(age1, age2) / 2 + 7

How this works:

  • We first grab the larger and smaller of the two ages using max() and min().
  • We check if the younger age falls below the threshold (older_age/2 +7). If it does, the pair is "creepy" so we return True; otherwise, we return False. No if statements required!

内容的提问来源于stack exchange,提问作者Yungpythonnoob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:37:23