我试图用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
最好先过滤数字,然后再分类。
它的作用:
enumerate(numbers)
返回一个由(index, item)
对组成的序列。由于原始列表是[x, y, z]
,因此即使经过筛选和排序,我们也可以跟踪x
、y
、z
。如果给定元组中的第二个项不是偶数,则
(x for x in enumerate(numbers) if x[1]%2)
过滤上述枚举。sort( ... , key=lambda x:x[1], reverse=True)
使用已筛选项的第二个索引项(原始编号)的值按降序排序。用户输入
要从用户读取,最简单的方法是使用
raw_input
(py2)/input
(py3k)。仅使用if语句
你必须嵌套if语句。比如:
接近
避免使用
if-stmts
查找最大值。使用python内置max
。使用生成器或filter
只查找奇数。使用这样的内置代码更安全/更可靠,因为编写它们更简单,代码经过了很好的测试,并且代码主要在C语言(而不是多字节代码指令)中执行。
代码
或:
测试
以及:
如果您传递一个空序列或只提供偶数,您将得到一个
ValueError
:参考文献
注意
sorted
是一个O(n log n)
操作,而max
是O(n)
。对于如此短的序列,速度差可能无关紧要,但使用最佳工具进行作业是一种良好的做法。相关问题 更多 >
编程相关推荐