我想知道下面的答案是否正确可行或是否有任何改进谢谢。 问题:一个程序,检查x和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."
答案 0 :(得分:3)
哇!这是一大堆代码。为什么不把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)
找出哪个变量包含最大奇数。
答案 1 :(得分:2)
您的解决方案可能有点过于冗长和具体。如果您需要找到最大的奇数并且有四个,该怎么办?还是一百?
更好的想法是使用Python的max函数来检查过滤偶数的序列。
您可以按照list:
之类的顺序收集要检查的数字A = [53, 31, 59, 75, 25, 32, 99, 15, 63, 35]
然后你可以用列表理解来过滤那个序列:
A_odd = [n for n in A if n % 2 != 0]
然后你可以找到该序列的最大值:
max_odd = max(A_odd)
假设序列中没有奇数。如果max
函数的参数为空,则会引发异常。因此,我们可以使用条件表达式来检查A_odd
是否为空:
if A_odd:
max_odd = max(A_odd)
else:
max_odd = "No odd numbers in sequence"
然后,当我们用print(A_odd)
打印答案时,我们会得到结果或消息。
Python 3.4(尚未发布)包含对max函数的补充,使其更加紧凑 - 您可以跳过条件并执行max(A_odd, default="No odd numbers in sequence")
答案 2 :(得分:2)
这是受到Eric的回答的启发,但满足了打印x,y和z而不是值的需求。
>>>val={'x':x,'y':y,'z':z}
>>>newval=dict(k,d for k,d in val.items() if d%2==1)
我个人更愿意写if d%2
,但那只是我,这取决于你。
>>>if newval:
print(max(newval.items(),key=lambda x:x[1]),'is maximum')
else:
print('No odd numbers')
它使用了具有Eric列表理解思想的词典。
编辑:我只是认为使用函数会更酷。
>>>def findmax(**x):
new=dict((k,d) for k,d in x.items() if d%2)
if new:
print(max(new.items(),key=lambda x:x[1]),'is maximum')
else:
print('No odd numbers')
试运行,
>>>findmax(x=1,y=37,z=208,a=193)
(a,193) is maximum
答案 3 :(得分:1)
nums = x, y, z
try:
print max([n for n in nums if n%2 == 1])
except ValueError:
print 'No odd numbers'
如果'No odd numbers'
nums
在print(max(some_list))
为空的情况下执行some_list
会返回错误,因此不会处理没有奇数存在的情况