请问我下面的回答是否正确可行或者有什么改进的地方谢谢。 问题:检查 x y 和 z 是否为奇数或偶数的程序检查数字是否是所有三个中最大的。 在我的回答下方:
x = 4
y = 7
z = 9
#first condition where 3 numbers are all odd.
if x%2 == 1 and y%2 == 1 and z%2 == 1:
if x > y and x > z:
print "x is the biggest odd number."
elif x > y and z > x:
print "z is the biggest odd number."
else:
print "y is the biggest odd number."
#second condition where 2 of the numbers are odd
elif x%2 == 0 and y%2 == 1 and z%2 == 1:
if y > z:
print "y is the biggest odd number."
else:
print "y is the biggest odd number."
elif x%2 == 1 and y%2 == 0 and z%2 == 1:
if x > z:
print "x is the biggest odd number."
else:
print "z is the biggest odd number."
elif x%2 == 1 and y%2 == 1 and z%2 == 0:
if x > y:
print "x is the biggest odd number."
else:
print "y is the biggest odd number."
#third condition where only one of the numbers is odd.
elif x%2 == 0 and y%2 == 0 and z%2 == 1:
print "z is the biggest odd number."
elif x%2 == 1 and y%2 == 0 and z%2 == 0:
print "x is the biggest odd number."
elif x%2 == 0 and y%2 == 1 and z%2 == 0:
print "y is the biggest odd number."
#last condition if none of the numer are odd or not numbers.
else:
print " None of the numbers are odd or not a number."
最佳答案
哇!那是一大堆代码。为什么不直接将 x
,y
,z
放入列表中。使用列表理解删除偶数。然后使用 max 函数选择最大值。像这样
arr = [x,y,z]
arr = [i for i in arr if i%2!=0] #select only odd numbers
print(max(arr)) #display the maximum number
然后您可以使用max(arr)
找出包含最大奇数的变量。
关于奇数的Python逻辑测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22130032/