Python实现三个数最大值求解及相等数值判断功能问询
求解三个数最大值并提示相等数值的Python函数优化方案
首先得指出你当前代码的逻辑漏洞:当输入的数值里存在相等的最大值时,你的代码无法同时输出最大值和相等提示。比如测试biggest(2,8,8)时,因为b>c不成立,所以不会进入elif b>a and b>c分支,只会走到elif b==c输出"b=c",漏掉了最大值的输出,这不符合需求。
我们可以调整逻辑顺序,先确定最大值,再检查所有两两相等的情况,这样就能同时满足输出最大值和提示相等数值的要求。下面是修正后的代码:
def biggest(a, b, c): # 先计算三个数的最大值 max_num = max(a, b, c) print(f"Biggest Number= {max_num}") # 检查所有两两相等的情况并提示 if a == b: print("a and b are equal") if a == c: print("a and c are equal") if b == c: print("b and c are equal") # 测试案例1:b和c相等且为最大值 biggest(2, 8, 8) # 输出: # Biggest Number= 8 # b and c are equal # 测试案例2:三个数都相等 biggest(5,5,5) # 输出: # Biggest Number= 5 # a and b are equal # a and c are equal # b and c are equal # 测试案例3:a和b相等且为最大值 biggest(10,10,7) # 输出: # Biggest Number= 10 # a and b are equal
如果想要更简洁的提示(比如当多个相等时合并提示),也可以优化提示逻辑:
def biggest(a, b, c): max_num = max(a, b, c) print(f"Biggest Number= {max_num}") equal_pairs = [] if a == b: equal_pairs.append("a and b") if a == c: equal_pairs.append("a and c") if b == c: equal_pairs.append("b and c") if equal_pairs: print("; ".join(equal_pairs) + " are equal") # 测试三个数相等的情况 biggest(5,5,5) # 输出: # Biggest Number= 5 # a and b; a and c; b and c are equal
这样不管是哪种相等情况,都能正确输出最大值和对应的相等提示,逻辑更清晰也更健壮。
内容的提问来源于stack exchange,提问作者Bishnu Dudhraj
相关产品推荐
相关产品推荐

