奇数的Python逻辑测试

标签 python comparison logical-operators

请问我下面的回答是否正确可行或者有什么改进的地方谢谢。 问题:检查 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/

相关文章:

javascript - 在 Typescript 中处理 null >= 0

c++ - 二项分布压缩

r - 无法从逻辑上解决 rasterToPoints 提取的 x,y 值

python - 列表小部件项数据对象上的槽从未被调用(在 PyQt 5.7 中)

python - 读取远程文件时回车丢失

python - OAuth API Google 云端硬盘 Python

Python对数组或列表中的元素进行成对比较

python - 是什么导致 'int' 对象没有属性 'has_key' ?

comparison - 仅复制差异(kdiff、winmerge、任何类似工具的差异)

javascript - 如何检查函数是否已执行?