6

我正在尝试用 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 的帖子,我现在有:

  # 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
4

28 回答 28

10

方法

避免使用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

参考

于 2013-03-31T19:19:24.797 回答
6

万一有人正在寻找使用条件语句的简单解决方案

x,y,z = 4,1,6
largest = None
if x%2:
 largest = x
if y%2:
 if y > largest:
  largest = y
if z%2:
 if z > largest:
  largest = z
if largest:
 print "largest number is" largest
else
 print "there are no odd numbers"
于 2013-10-25T17:03:07.550 回答
4
try:
    largest = max(val for val in (x,y,z) if val % 2)
    print(largest)
except ValueError:
    print('Even')

注意 thatsorted是一个O(n log n)操作,whilemaxO(n)。对于这么短的序列,速度差异可能无关紧要,但最好使用最好的工具来完成这项工作。

于 2013-03-31T18:24:34.303 回答
4

这是来自 John V. Guttag 的 Python 计算和编程简介第 2 章的手指练习。这是 MITx 的推荐文本:6.00x Introduction to Computer Science and Programming。本书是为与 Python 2.7 一起使用而编写的。

'编写一个程序,检查三个变量 x、y 和 z,并打印其中最大的奇数。如果它们都不奇怪,它应该打印一条消息。

至此,本书只介绍了变量赋值和条件分支程序以及打印函数。我知道我正在努力。为此,这是我编写的代码:

if x%2 == 0:
    if y%2 == 0:
        if z%2 == 0:
            print "None of them are odd"
        else:
            print z
    elif y > z or z%2 == 0:
        print y
    else:
        print z
elif y%2 == 0:
    if z%2 == 0 or x > z:
        print x
    else:
        print z
elif z%2 == 0:
    if x > y:
        print x
    else:
        print y
else:
    if x > y and x > z:
        print x
    elif y > z:
        print y
    else:
        print z

它似乎适用于我尝试过的所有组合,但记住我在第三段中的观点,知道它是否可以缩短会很有用。我很欣赏它已经被回答了,但是通过提供这个答案,其他用户在搜索书中问题的答案时更有可能遇到它。

于 2013-11-08T23:05:19.117 回答
3

像这样的东西:

def get_max_odd(*lis):
    try:
         return sorted(i for i in lis if i%2)[-1] #IndexError if no odd item found
    except IndexError:    
         return "even"


In [8]: get_max_odd(1,2,3)
Out[8]: 3

In [9]: get_max_odd(2,4,6)
Out[9]: 'even'

In [10]: get_max_odd(2,5,6)
Out[10]: 5

In [11]: get_max_odd(2,4,6,8,9,10,20)
Out[11]: 9
于 2013-03-31T18:41:21.793 回答
2

最好过滤数字,然后对它们进行排序。

numbers = [x, y, z]

sorted_odd_nums = sorted((x for x in enumerate(numbers) if x[1]%2), 
                         key = lambda x:x[1], 
                         reverse=True)

if not sorted_odd_nums:
   # all numbers were even and filtered out.
elif sorted_odd_nums[0][0] == 0:
   # x is the biggest odd number
elif sorted_odd_nums[0][0] == 1:
   # y is the biggest odd number
elif sorted_odd_nums[0][0] == 2:
   # z is the biggest odd number

它能做什么:

enumerate(numbers)返回一个对序列(index, item)。由于原始列表是,因此即使在过滤和排序之后[x, y, z],我们也可以跟踪x, 。yz

(x for x in enumerate(numbers) if x[1]%2)如果给定元组中的第二项不是偶数,则在枚举上方过滤。

sort( ... , key=lambda x:x[1], reverse=True)使用它们的第二个索引项目的值(即原始数字)按降序对过滤的项目进行排序。

用户输入

要从用户那里读取,最简单的方法是使用raw_input(py2) / input(py3k)。

number = int(raw_input('enter a number: '))

仅使用 if 语句

你必须嵌套 if 语句。像:

if x%2: # x is odd
  if y%2: # y is odd
    if z%2: #z is odd
      if x>y and x>z: #x is the biggest odd number
      elif y>z and y>x: #y is the biggest odd number
      elif z>x and z>y: #z is the biggest odd number

    else: #z is even
      if x>y: #x is the biggest odd number
      else: #y is the biggest odd number
  else: #y is even
    if z%2: #z is odd
...
于 2013-03-31T18:24:08.650 回答
2

我正在阅读 Guttag(和 Python 2.7)的同一本书。其他阅读它的人可能会意识到尚未引入列表(或切片),尽管我在我的解决方案中使用了一个(我认为它工作正常!?!)。如果您宁愿从列表的末尾而不是列表的开头进行切片,那么您实际上不需要反转列表顺序。

首先,我创建了一个空列表(lst)。但在我使用它之前,我会检查是否所有的 x、y 和 z 都不是奇数(Guttag 询问“它们是否都不奇数”)。然后,依次检查每个变量以查看其是否为奇数,如果是,则将其添加到列表中。我按降序对列表进行了排序(即最大的奇数排在前面)。然后检查以确保它至少有一个元素(打印空列表没有意义),然后打印第一个元素。

x,y,z = 111,45,67

lst = []
if x%2==0 and y%2==0 and z%2==0:
    print 'none of x,y or z is an odd number'
else:
    if x%2!=0:
        lst.append(x)
    if y%2!=0:
        lst.append(y)
    if z%2!=0:
        lst.append(z)
lst.sort(reverse = True)
if len(lst)!=0:
    print lst[:1]
于 2014-03-26T12:56:56.043 回答
2

这是我的解决方案:

def get_max_odd(x, y, z):
    odd_nums = []

    if x % 2 == 1:
        odd_nums.append(x)
    if y % 2 == 1:
        odd_nums.append(y)
    if z % 2 == 1:
        odd_nums.append(z)

    if odd_nums == []:
        return 'None of x, y, z are odd numbers'
    else:
        return max(odd_nums)

print(get_max_odd(120, 111, 23))

我无法仅使用书中迄今为止提供的材料来完成这项练习。事实上,我认为如果没有超过 100 行,就不可能有一个工作程序。请让我知道您是否已经找到一种方法使其仅适用于迄今为止提供的材料

于 2017-09-03T21:24:23.263 回答
2

在前 4 行代码中,我们要求用户输入一个数字并将该数字转换为整数

x = input("enter a number:")

y = input("enter another number: ")

z = input("enter another number: ")

x,y,z = int(x),int(y),int(z)


if x %2 !=0: # check whether x is odd

    if y%2 !=0: # if x is odd check y

        if z%2 != 0: # if y is odd then check z
            if x>z and x > y: # comparing the 3 numbers as all are odd to get largest
                print("x is largest")
            elif y>z:
                print("y is largest")
            else:
                print("z is largest")
        else: # if z is not an odd number then the above comparisons cannot be done #
    #so we placed this else if z is not odd then the below comparisons will be executed
            if x>z and x > y:
                print("x is largest")
            elif y>z:
                print("y is largest")
    else: # if y is also not an even and x is odd then x is largest irrespective of others
        print("x is largest")

elif y%2 != 0: # similar way if x is not odd then the above loop will not run so this gets executed when x is even

    if z%2 != 0:
        if y>z:
            print("y is largest")
    else:
        print("z is largest")
elif z%2 !=0:

    print("z is largest")
else:

    print("all the numbers are even")
于 2018-02-26T08:28:30.670 回答
2
def odd(x,y,z):
    l=[x,y,z]
    even=[]
    for e in l:
        if e%2!=0:
            even.append(e)
    even.sort()
    if len(even)==0:
        return(print('No odd numbers'))
    else:
        return(even[-1])

odd(1,2,3)
于 2018-03-29T07:57:50.623 回答
2

根据评论,如果 x 是偶数,AfDev 和其他人的帖子将抛出 TypeError,因为它会尝试

if y > None:

编辑:如果最高奇数为负,评论者的解决方案(初始化最大 = 0 而不是最大 = 无)也不起作用。

书中的问题假设不了解列表或循环,所以这是我的解决方案:

x, y, z = 2, -5, -9
largest = None

if x % 2 != 0:
    largest = x
if y % 2 != 0:
    if largest == None or y > largest: # if None it will not attempt 2nd conditional
        largest = y
if z % 2 != 0:
    if largest == None or z > largest:
        largest = z

print(largest) # prints -5 
于 2021-07-07T13:36:40.053 回答
1

这是我从昨天晚上开始考虑之后写的第一个剧本。

实际上,我一直在寻找可以参考的答案,因为我经常遇到错误但找不到任何令人满意的东西,这是我的一个:)

x = 333312
y = 221569
z = 163678

if x%2 ==0 and y%2==0 and z%2==0:
    print "Only even numbers provided."

elif x%2==0:
    if y%2!=0 and z%2!=0:
        if y > z:
            print y
        else:
            print z
    else:
        if y%2!=0:
            print y
        if z%2!=0:
            print z


elif y%2==0:
    if x%2!=0 and z%2!=0:
        if x > z:
            print x
        else:
            print z
    else:
        if x%2!=0:
            print x
        if z%2!=0:
            print z



elif z%2==0:
    if x%2!=0 and y%2!=0:
                if x > y:
                    print x
                else:
                    print y
    else:
        if x%2!=0:
                print x
        if y%2!=0:
                print y

else:
    if x>y and x>z:
        print x
    elif y>z:
        print y   
    else:
        print z
于 2015-01-11T08:31:14.430 回答
1

我目前也在浏览这本书并遇到了这个问题。我使用了类似于上述一些解决方案的方法。但是,程序不仅打印最大值,还打印包含最大值的变量。

这里的区别在于,除了检查 if x > yx > z等之外,程序还检查是否相等(即x >= yx >= z等)。对于多个相等的值,程序将打印所有共享最高奇数值的变量。

手指练习 2.2

编写一个程序,检查三个变量——x、y 和 z——并打印其中最大的奇数。如果它们都不奇怪,它应该打印一条消息。

x, y, z = 5,7,7

if x%2 == 1 or y%2 == 1 or z%2 == 1: #at least one of the variables is odd
    if x%2 == 1:
        if y%2 == 1:
            if z%2 == 1: #x, y, and z are all odd
                if x >= y and x >= z:
                    print "x =", x, "is the largest odd number!"
                if y >= x and y >=z:
                    print "y =",y, "is the largest odd number!"
                if z >= x and z >= y:
                    print "z =", z, "is the largest odd number!"
            else: #z is even, but x and y are still odd
                if x >= y:
                    print "x =", x, "is the largest odd number!"
                if y >= x:
                    print "y =",y, "is the largest odd number!"
        elif z%2 == 1: #y is even, but x and z are odd
            if x >= z:
                print "x =", x, "is the largest odd number!"
            if z >= x:
                print "z =", z, "is the largest odd number!"
        else: #x is the only odd number
            print "x = ", x, "is the largest odd number!"
    if x%2 != 1 and y %2 == 1: #x is not odd but y is odd
    #could have done an elif here. But this makes the code easier to follow
        if z%2 == 1:#z is also odd
            if y >=z:
                print "y =",y, "is the largest odd number!"
            if z >= y:
                print "z =", z, "is the largest odd number!"
        else: #z is even. Hence, y is the only odd number
            print "y =", y, "is the largest odd number!"
    if x%2 != 1 and y%2 != 1 and z%2 == 1:#z is the only odd number
        print "z =", z, "is the largest odd number!"             
else:
    print "No odd number was input!"
于 2015-10-18T00:34:11.933 回答
1

这回答了 John Guttag 教授在之前的帖子中提到的本书 Ch.02 中的最后一个手指练习。使用列表对我来说似乎很有帮助。相同的方法可以用于同一章的前面的手指练习。

import math



a=int(input("Enter first integer: ")) # Manual entering of ten integers#
b=int(input("Enter second integer: "))
c=int(input("Enter third integer: "))
d=int(input("Enter fourth integer: "))
e=int(input("Enter fifth integer: "))
f=int(input("Enter sixth integer: "))
g=int(input("Enter seventh integer: "))
h=int(input("Enter eighth integer: "))
i=int(input("Enter ninth integer: "))
j=int(input("Enter tenth integer: "))

master=[a,b,c,d,e,f,g,h,i,j]



def ifalleven(a): # Finding whether every integer in the list if even or not.#

    i=0
    list=[]
    while i<len(a):
        if a[i]%2==0:
            list.append(a[i])
        i=i+1
    return len(list)==len(a)



def findodd(a): # Finding the greatest odd integer on the list.#
    i=0
    list=[]
    while i<len(a):
        if a[i]%2!=0:
            list.append(a[i])
        i=i+1
    print (max(list))



def greatoddoreven(list): # Finding the greatest odd integer on the list or if none are odd, print a message to that effect.#
    if ifalleven(list)==True:
        print ('No odd numbers found!')
    else:
        findodd(list)



greatoddoreven(master)
于 2016-04-17T06:35:07.447 回答
1

我也在学习 Python 和编程。我对这个练习的回答如下。通过 John V. Guttag 的《使用 Python 进行计算和编程简介》第 2 章的手指练习。

x, y, z = 55, 90, 87

if x%2 == 1 and y%2 == 1 and z%2 == 1:
   if x > y and x > z:
        print (x)
   elif y > z and y >x:
        print (y)
   else:
        print (z)
else:   
    print ('none of them are odd')
于 2016-10-06T18:42:26.563 回答
1
num1 = 7
num2 = 16
num3 = 300
x1=0
x2=0
x3=0

if num1%2 != 0:
    x1=1
if num2%2 != 0:
    x2=1
if num3%2 != 0:
    x3=1

if (num1*x1 > num2*x2) and (num1*x1 > num3*x3):
   largest = num1
elif (num2*x2 > num1*x1) and (num2*x2 > num3*x3):
   largest = num2
elif (x3):
   largest = num3
else:
    print("no one is odd")
if(x1!=0 or x2!=0 or x3!=0):
    print("The largest odd number between",num1,",",num2,"and",num3,"is",largest)
于 2017-01-02T03:56:46.530 回答
1

这个怎么回答?是不是太长了?

 x, y, z = eval(input('Please enter the numbers for x, y, z: '))#allows you to enter three numbers each separated by a comma
print('x =', x)#Shows you what the value of x is
print('y =', y)#Shows you what the value of y is
print('z =', z)#Shows you what the value of z is
if x%2 != 0:#Checks to see if x is odd is true 
    if y%2 != 0:#Checks to see if y is odd is true
        if z%2 != 0:#Checks to see if z is odd is true
            if x > y and x > z:# Now in this situation since all the numbers are odd, all we have to do is compare them to see which is the largest in the following lines
                print('x is the largest odd number')
            elif y > z:    
                print('y is the largest odd number')
            else:    
                print('z is the largest odd number')
        elif x > y:# we refer back to the line if z%2 != 0 and in this new situation, it is false therefore z is not odd in this case and x and y are the only odd numbers here
                print('x is the largest odd number')  # we check to see if x is the largest odd number, if x is not largest odd number then proceed to the next line      
        else: 
                print('y is the largest odd number')  # here, y is the largest odd number                                                  
    elif z%2 != 0:# refer back to the sixth line at the beginning, if y%2 = 0.In this new situation, y is not odd so the only variables we're comparing now are x and z only
        if x > z:
            print('x is the largest odd number')
        else:
            print('z is the largest odd number')
    else:
            print('x is the largest odd number')# when both y and z are not odd, by default x is the largest odd number here
elif y%2 != 0:# Refer back to the fifth line, if x%2 != 0, in this new situation, the statement if x%2 != 0 is false therefore we proceed to checking if the next variable y is odd right here
            if z%2 != 0:#Since y is odd, check to see if z is odd,
                if y > z:#then if previous statement is true check to see now if y is bigger and print('y is the largest odd number') if so
                    print('y is the largest odd number')
                else:
                    print('z is the largest odd number')# here y is not largest odd number so by default z is the largest

            else:# this line occurs when z is not odd which pretty much leaves y to be the only odd number and is therefore largest odd number by default
                print('y is the largest odd number')
elif z%2 != 0:# this line occurs when both x and y is not odd which leaves z to be the largest odd number
            print('z is the largest odd number')
else:# this line occurs when all the numbers are not odd; they are even. Remember in this program, our main objective is to determine the largest number only among the odd numbers if there are any odd numbers at all, and if there are no odd numbers we show that there are none. (We do not take into account even numbers at all since that's not what the question is about) 
    print('There are no odd numbers')
于 2017-02-21T16:28:10.260 回答
1
x=input('x= ')
y=input('y= ')
z=input('z= ')
largest = None
if x%2 == 0 and y%2 == 0 and z%2 == 0:
    print('none of them is odd')
else:
    if x%2 != 0:
        largest = x
    if y%2 != 0:
        if y > largest:
            largest = y
    if z%2 != 0:
        if z > largest:
            largest = z
    print(largest)
于 2017-02-25T05:33:16.547 回答
1

刚刚完成同样的问题。我的答案似乎与其他答案不同,但似乎工作正常。(或者我错过了什么?!)所以这里有一个替代方案:

仅使用 if/else:

    x = 4
    y = 7
    z = 7

    if x%2 and y%2 and z%2 == 1:
        if x > y and x > z:
            print x
        elif y > z:
            print y
        else:
            print z
    elif x%2 and y%2 == 1:
        if x > y:
            print x
        else:
            print y
    elif x%2 and z%2 == 1 :
        if x > z:
            print x
        else:
            print z
    elif y%2 and z%2 == 1:
        if y > z:
            print y
        else:
            print z
    elif x%2 == 1:
        print x
    elif y%2 == 1:
        print y
    elif z%2 == 1:
        print z
    else:
        print "there are no odd numbers"

据我所知,它适用于负数、数字、大数……如果不告诉我!

于 2017-03-08T05:46:22.897 回答
1

这是我的“菜鸟”版本的解决方案。基本上,该问题需要根据用户输入分析所有可能的 X、Y、Z 组合(例如,一个奇数和两个偶数等情况)。

我首先消除了两个最明显的情况,即所有数字都是偶数并且至少有一个数字为零。该代码仅缺少至少两个数字相等的部分。其余的很简单...

肯定有一种更精细的方法来解决这个问题(有关使用排序和反向比较的更多成分变量组合的案例,请参见下文),但这是我可以通过我的 Python 基础知识完成的。

print('This program will find the largest odd number among the three entered.\nSo, let\'s start...\n')

x = int(input('Enter the 1st number: '))
y = int(input('Enter the 2nd number: '))
z = int(input('Enter the 3rd number: '))
strToPrint = ' is the largest odd number.'

if x==0 or y==0 or z==0:
    print('\nNo zeroes, please. Re-run the program.')
    exit()
if x % 2 == 0 and y % 2 == 0 and z % 2 == 0:
    print('\nAll numbers are even.')
elif x % 2 != 0 and y % 2 != 0 and z % 2 != 0:  # all numbers are odd; start analysis...
    if x > y and x > z:
        print(str(x) + strToPrint)
    if y > x and y > z:
        print(str(y) + strToPrint)
    if z > y and z > x:
        print(str(z) + strToPrint)
elif x % 2 != 0 and y % 2 == 0 and z % 2 == 0:  # only X is odd.
    print(str(x) + strToPrint)
elif y % 2 != 0 and x % 2 == 0 and z % 2 == 0:  # only Y is odd.
    print(str(y) + strToPrint)
elif z % 2 != 0 and x % 2 == 0 and y % 2 == 0:  # only Z is odd.
    print(str(z) + strToPrint)
elif x % 2 != 0 and y % 2 != 0 and z % 2 == 0:  # only X and Y are odd.
    if x > y:
        print(str(x) + strToPrint)
    else:
        print(str(y) + strToPrint)
elif x % 2 != 0 and y % 2 == 0 and z % 2 != 0:  # only X and Z are odd.
    if x > z:
        print(str(x) + strToPrint)
    else:
        print(str(z) + strToPrint)
elif x % 2 == 0 and y % 2 != 0 and z % 2 != 0:  # only Z and Y are odd.
    if y > z:
        print(str(y) + strToPrint)
    else:
        print(str(z) + strToPrint)

下面是同一程序的“非新手”版本,适用于任何(合理的)整数,与之前的版本相比,它更短、更紧凑。我使用了一个由十个整数组成的列表仅用于演示,但该列表可以扩展。

int_list = [100, 2, 64, 98, 89, 25, 70, 76, 23, 5]
i = len(int_list) - 1           # we'll start from the end of a sorted (!) list
int_list.sort()                 # sort the list first

# print(int_list)               # just to check that the list is indeed sorted. You can uncomment to print the sorted list, too.

while i >= 0:                   # prevent 'out of range' error
    if int_list[i] % 2 != 0:    # check if the list item is an odd number
        break                   # since the list is sorted, break at the first occurence of an odd number
    i -= 1                      # continue reading list items if odd number isn't found

print('The largest odd number is: ' + str(int_list[i]) + ' (item #' + str(i) + ' in the sorted list)')
于 2018-09-27T11:26:47.697 回答
1

这是我的解释,我正在执行与使用 Python 进行计算和编程简介(第 2 版,John Guttag )一书相同的任务

# edge cases 100, 2, 3 and 100,2,-3 and 2,2,2
x = 301
y = 2
z = 1

# what if the largest number is not odd? We need to discard any non-odd numbers

# if none of them are odd - go straight to else
if (x % 2 != 0) or (y % 2 != 0) or (z % 2 != 0):
    #codeblock if we have some odd numbers
    print("ok")
    
    # initialising the variable with one odd number, so we check each in turn
    if (x % 2 != 0):
        largest = x
    elif (y % 2 != 0):
        largest = y
    elif (z % 2 != 0):
        largest = z

    # here we check each against the largest
    # no need to check for x as we did already

    if (y % 2 != 0):
        if y > largest:
            largest = y
    
    if (z % 2 != 0):
        if z > largest:
            largest = z
    
    print("The largest odd number is:", largest)
    print("The numbers were", x, y, z)
        
else: 
    print("No odd number found")`
于 2020-11-13T14:57:35.600 回答
1

这是我的 Guttag 手指练习 2 的代码:

def is_odd(x):
    """returns True if x is odd else returns False"""
    if x % 2 != 0:
        return(True)
    else:
        return(False)

def is_even(x):
    """returns True if x is even else returns False"""
    if x % 2 == 0:
        return(True)
    else:
        return(False)

def largest_odd(x, y, z):
    """Returns the largest odd among the three given numbers"""
    if is_odd(x) and is_odd(y) and is_odd(z):
        return(max(x, y, z))
    elif is_odd(x) and is_odd(y) and is_even(z):
        return(max(x, y))
    elif is_odd(x) and is_even(y) and is_odd(z):
        return(max(x, z))
    elif is_even(x) and is_odd(y) and is_odd(z):
        return(max(y, z))
    elif is_odd(x) and is_even(y) and is_even(z):
        return(x)
    elif is_even(x) and is_odd(y) and is_even(z):
        return(y)
    elif is_even(x) and is_even(y) and is_odd(z):
        return(z)
    else:
        return("There is no odd number in the input")
于 2020-12-25T06:54:50.333 回答
0

假设我们不打算使用一些花哨的东西 :-) 像 python 中的 max 和 sort 函数......我认为可以肯定地说“赋值”语句是公平的游戏......我们毕竟必须赋值x、y 和 z。

因此:我创建了自己的变量,称为“最大”,初始化为零。我将该变量分配给 x,y,z 的第一个奇数(按该顺序询问)。然后我只检查剩余的值,如果每个值都大于“最大”并且也是奇数,那么我将其设为“最大”的值 - 并检查下一个值。检查完所有值后,“最大”将保存最大奇数或零的值(这意味着我从未找到奇数,因此我打印了一条消息。

这与您可以用来从用户读取任意数量(可能 10 个)值并在输入所有值后打印最大奇数的方法相同。只需对照当前“最大”值检查输入的每个值。

是的,您确实需要小心支持负奇数——您需要处理将“最大”分配给第一个奇数,无论它是否大于零。

于 2013-10-06T04:29:00.763 回答
0

实际上,我更容易用更多的值而不是只有 3 (x,y,z) 来考虑这个问题。假设我向您展示了一个单词列表 Apple、dog、Banana、cat、monkey、Zebra、ephant... 等。假设有 26 个单词由变量 a,b,c,d,e,f...x 表示,y 和 z。

如果您需要查找以小写字母开头的“最大单词”(按字典顺序),则无需将每个单词与其他单词进行比较。我们的大脑通常不会对整个列表进行排序,然后从最后选择......好吧......我的无论如何也不会。

我只是从列表的前面开始,然后逐步完成。我第一次找到一个以小写字母开头的单词时……我记住它,然后阅读,直到我得到另一个小写单词——然后我检查哪个更大,只记住那个单词……我永远不必去回来并检查任何其他人。在名单上一通,我就完成了。在上面的列表中......我的大脑立即丢弃了“Zebra”,因为情况是错误的。

于 2013-10-06T05:01:10.200 回答
0

这个问题要求从 3 个变量 -x、y 和 z 中打印出最大的奇数,因为它是第 2 章,它只描​​述了条件,我猜 ans 应该只使用条件来提供。

该程序可以通过详尽地编写所有可能的奇数或偶数组合来完成。由于有 3 个变量,并且在任何时候这些变量都可以是奇数或偶数,因此有 2^3 = 8 个组合/条件。这可以通过使用真值表来显示,但我们不使用 True 和 False,而是使用“O”表示奇数,使用“E”表示偶数。该表看起来像这个奇偶表

每行都是代码中检查“奇数/均匀性”的条件。然后,在这些条件中的每一个中,您将使用嵌套条件检查哪些变量是最大的奇数。

x = int(input('Enter an integer: '))
y = int(input('Enter another integer: '))
z = int(input('Enter a final integer: '))

print('x is:', x)
print('y is:', y)
print('z is:', z)
print('\n')

if x % 2 == 1 and y % 2 == 1 and z % 2 == 1:
    print('First conditional triggered.')
    if x > y and x > z:
        print(x, 'is the largest odd number.')
    elif y > x and y > z:
        print(y, 'is the largest odd number.')
    elif z > x and z > y:
        print(z, 'is the largest odd number.')
    else:
        print(x, 'is the largest odd number.')
    # This else clause covers the case in which all variables are equal.
    # As such, it doesn't matter which variable you use to output the 
    # largest as all are the largest.
elif x % 2 == 1 and y % 2 == 1 and z % 2 == 0:
    print('Second conditional is triggered.')
    if x > y:
        print(x, 'is the largest odd number.')
    elif y > x:
        print(y, 'is the largest odd number.')
    else:
        print(x, 'is the largest odd number.')
elif x % 2 == 1 and y % 2 == 0 and z % 2 == 1:
    print('Third conditional is triggered.')
    if x > z:
        print(x, 'is the largest odd number.')
    elif z > x:
        print(z, 'is the largest odd number.')
    else:
        print(x, 'is the largest odd number.')
elif x % 2 == 1 and y % 2 == 0 and z % 2 == 0:
    print('Fourth conditional is triggered.')
    print(x, 'is the largest odd number.')
elif x % 2 == 0 and y % 2 == 1 and z % 2 == 1:
    print('Fifth conditional is triggered.')
    if y > z:
        print(y, 'is the largest odd number.')
    elif z > y:
        print(z, 'is the largest odd number.')
    else:
        print(y, 'is the largest odd number.')
elif x % 2 == 0 and y % 2 == 1 and z % 2 == 0:
    print('Sixth conditional is triggered.')
    print(y, 'is the largest odd number.')
elif x % 2 == 0 and y % 2 == 0 and z % 2 == 1:
    print('Seventh conditional is triggered.')
    print(z, 'is the largest odd number.')
else:
    print('Eight conditional is triggered.')
    print('There is no largest odd number as all numbers are even.')

此方法适用于 3 个变量,但随着添加更多变量,所需条件的复杂性和数量会急剧上升。

于 2016-09-13T03:36:51.193 回答
0

刚刚完成了这个练习,这似乎是一种有效的方法,尽管它似乎不能处理负数(虽然我认为它不应该在这个级别):

x, y, z = 7, 6, 12
xo = 0
yo = 0
zo = 0

if x%2 == 0 and y%2 == 0 and z%2 == 0:
    print("None of the numbers are odd.")

if x%2 == 1:
    xo = x

if y%2 == 1:
    yo = y

if z%2 == 1:
    zo = z

if xo > yo and xo > zo:
    print(xo)

if yo > xo and yo > zo:
    print(yo)

if zo > xo and zo > yo:
    print(zo)
于 2019-12-07T15:01:58.270 回答
-1

我就是这样做的..希望它有所帮助。

x = 2
y =4
z=6

# Conditional program to print the smallest odd number

if x %2 == 1 or y% 2 == 1 or z% 2 == 1 : #checks if at least one is odd
    if x<y and x< z:  # checks if x is least
        print x
    elif y<z:         # x is not least,so proceeds to check if y is least
        print y
    else:
        print z       #prints z, the least number
else:
    print "None of the numbers are odd"

如果您想要最大的奇数,只需反转符号即可。

于 2015-05-11T11:53:16.913 回答
-1

我刚刚阅读了 Python 文本的开头,我很确定我找到了解决这个问题的最详尽的方法:

if x%2!=0 and y%2!=0 and z%2!=0 and x>y and x>z:
    print(x)
elif x%2!=0 and y%2!=0 and z%2!=0 and y>x and y>z:
    print(y)
elif x%2!=0 and y%2!=0 and z%2!=0 and z>x and z>y:
    print(z)
elif x%2==0 and y%2!=0 and z%2!=0 and y>z:
    print(y)
elif x%2==0 and y%2!=0 and z%2!=0 and z>y:
    print(z)
elif x%2!=0 and y%2!=0 and z%2==0 and y>x:
    print(y)
elif x%2!=0 and y%2!=0 and z%2==0 and x>y:
    print(x)
elif x%2!=0 and y%2==0 and z%2!=0 and x>z:
    print(x)
elif x%2!=0 and y%2==0 and z%2!=0 and z>x:
    print(z)
else:
    print('none of them are odd')
于 2017-09-08T06:13:25.800 回答