Python 奇数的逻辑测试
我在想我下面的回答是否正确可行,或者有没有什么可以改进的地方,谢谢大家。
问题是:写一个程序来检查 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."
4 个回答
nums = x, y, z
try:
print max([n for n in nums if n%2 == 1])
except ValueError:
print 'No odd numbers'
如果在 nums
里没有奇数,这段代码会输出 '没有奇数'
。
如果你尝试用 print(max(some_list))
来打印一个空的 some_list
,会出现错误,所以这段代码没有处理没有奇数的情况。
你的解决方案可能有点太复杂和具体了。如果你需要找出最大的奇数,而这个序列里有四个奇数?或者一百个呢?
一个更好的方法是使用Python的max函数,来查看一个过滤掉偶数的序列。
你可以把要检查的数字放在一个像列表这样的序列里:
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="序列中没有奇数")
。
这个内容是受到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
哇!这段代码真不少。你为什么不把 x
、y
、z
放到一个列表里呢?然后用列表推导式来去掉偶数。接着用最大值函数来找出最大的数。大概可以这样做:
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)
来找出哪个变量是最大的奇数。