gpt4 book ai didi

python - 选择最大的奇数python

转载 作者:太空狗 更新时间:2023-10-30 01:40:10 26 4
gpt4 key购买 nike

我正在尝试用 Python 编写一个简单的程序来计算值 x、y、z 中的最大奇数。如何让用户选择 x、y 和 z 的值?

所以程序会询问 x、y 和 z 是什么,然后说“x、y、z 是最大的奇数”或者这些数字都是偶数。

我目前所拥有的如下。这至少是一个不错的开始吗?

  # This program exmamines variables x, y, and z 
# and prints the largest odd number among them

if x%2 !== 0 and x > y and y > z:
print 'x is the largest odd among x, y, and z'
elif y%2 !== 0 and y > z and z > x:
print 'y is the largest odd among x, y, and z'
elif z%2 !== 0 and z > y and y > x:
print 'z is the largest odd among x, y, and z'
elif x%2 == 0 or y%2 == 0 or z%2 == 0:
print 'even'

有了 thkang post,我现在有:

  # This program exmamines variables x, y, and z 
# and prints the largest odd number among them

if x%2 !== 0:
if y%2 !== 0:
if z%2 !== 0:
if x > y and x > z: #x is the biggest odd
elif y > z and y > x: #y is the biggest odd
elif z > x and z > y: #z is the biggest odd

else: #z is even
if x > y: #x is the biggest odd
else: #y is the biggest odd

else: #y is even
if z%2 != 0: #z is odd
if x > z: #x is the biggest odd
else: #z is the biggest odd
else: #y,z are even and x is the biggest odd

else: #x is even
if y%2 != 0 and z%2 != 0; #y,z is odd
if y > z: #y is the biggest odd
else: #z is the biggest odd
else: #x and y is even
if z%2 != 0: #z is the biggest odd

最佳答案

方法

避免使用 if-stmts 来查找最大值。使用 python 内置 max。使用生成器或 filter 仅查找奇数。

像这样使用内置函数更安全/更可靠,因为它们的组合更简单,代码经过良好测试,并且代码主要在 C 中执行(而不是多字节代码指令)。

代码

def find_largest_odd(*args):
return max(arg for arg in args if arg & 1)

或:

def find_largest_odd(*args):
return max(filter(lambda x: x & 1, args))

测试

>>> def find_largest_odd(*args):
... return max(arg for arg in args if arg & 1)
...
>>> print find_largest_odd(1, 3, 5, 7)
7
>>> print find_largest_odd(1, 2, 4, 6)
1

和:

>>> def find_largest_odd(*args):
... return max(filter(lambda x: x & 1, args))
>>> print find_largest_odd(1, 3, 5, 7)
7
>>> print find_largest_odd(1, 2, 4, 6)
1

如果您传递一个空序列或仅提供偶数,您将得到一个ValueError:

>>> find_largest_odd(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in find_largest_odd
ValueError: max() arg is an empty sequence

引用资料

关于python - 选择最大的奇数python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15732805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com