选择最大的奇数python

时间:2013-03-31 18:18:25

标签: python

我正在尝试用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

27 个答案:

答案 0 :(得分:9)

方法

避免使用if-stmts来查找最大值。使用python builtin 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

参考

答案 1 :(得分:4)

try:
    largest = max(val for val in (x,y,z) if val % 2)
    print(largest)
except ValueError:
    print('Even')

请注意,sortedO(n log n)操作,而maxO(n)。对于这么短的序列,速度差异可能无关紧要,但最好使用最好的工具来完成工作。

答案 2 :(得分:4)

任何人都在寻找使用条件陈述的简单解决方案

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"

答案 3 :(得分: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 

答案 4 :(得分:2)

这是John V. Guttag撰写的“使用Python计算和编程简介”第2章中的手指练习。这是MITx的推荐文本:6.00x计算机科学与编程简介。本书是为与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

它似乎适用于我尝试过的所有组合,但是要知道它是否可以缩短是有用的,同时铭记我对第3段的观点。我很感激它已被解决,但通过提供这个答案,其他用户在搜索书中问题的答案时更有可能遇到它。

答案 5 :(得分:2)

类似的东西:

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

答案 6 :(得分:1)

我正在通过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]

答案 7 :(得分:1)

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)

答案 8 :(得分:1)

这是我的解决方案:

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行的工作程序。如果你,请告诉我 已找到一种方法,使其仅适用于目前提供的材料

答案 9 :(得分:0)

这是怎么回答的?太长了吗?希望能帮助到你。任何反馈都表示赞赏。

 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')

答案 10 :(得分:0)

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

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],因此即使在过滤和排序后,我们也可以跟踪xyz

如果给定元组中的第二项不是偶数,则

(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
...

答案 11 :(得分:0)

这是我的 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")

答案 12 :(得分:0)

这是我的解释,我正在做同一本书使用Python计算和编程简介,第二版,John Guttag

中的一部分。
Sub compareList()
Dim sh As Worksheet, lastR As Long, lastR2 As Long, i As Long, j As Long, arr, arrFin

Set sh = ActiveSheet
 lastR = sh.Range("A" & rows.count).End(xlUp).row
 lastR2 = sh.Range("D" & rows.count).End(xlUp).row
 arr = sh.Range("A2:B" & lastR).Value
 arrFin = sh.Range("D2:E" & lastR2).Value
 
 For i = 1 To UBound(arrFin)
    For j = 1 To UBound(arr)
        If arrFin(i, 1) = arr(j, 1) Then arrFin(i, 2) = arr(j, 2): Exit For
    Next j
 Next i
 sh.Range("D2:E" & lastR2).Value = arrFin
End Sub

答案 13 :(得分: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)

答案 14 :(得分:0)

这是我的解决方案“新手”版本。基本上,该问题需要根据用户输入来分析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)')

答案 15 :(得分:0)

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

仅使用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"

据我所知,它适用于负数,数字,大数字......如果不让我知道的话!

答案 16 :(得分:0)

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)

答案 17 :(得分:0)

实际上,我更容易用更多的值而不是3(x,y,z)来思考这个问题。假设我给你看一个单词Apple,dog,Banana,cat,monkey,Zebra,elephant ...等等。假设有26个单词由变量a,b,c,d,e,f ...表示,y和z。

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

我只是从列表的前面开始,然后逐步完成它。我第一次找到一个以小写字母开头的单词...我记住它然后读取,直到我得到另一个小写单词 - 然后我检查哪个更大并且记住那个单词......我永远不必去回来检查其他任何一个。列表中的一个通过,我已经完成了。在上面的列表中...我的大脑立即丢弃“斑马”,因为案件是错误的。

答案 18 :(得分:0)

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)

答案 19 :(得分:0)

我也在学习Python和编程。我对此练习的答案如下。使用John V. Guttag编写的“计算和编程简介”第2章中的手指练习。

"3206","Broom","1.00"

答案 20 :(得分:0)

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

程序可以通过详尽地编写奇数或偶数的所有可能组合来完成。由于存在3个变量,并且在任何时候这些变量可以是奇数或甚至是2 ^ 3 = 8个组合/条件。 这可以通过使用真值表来显示,但不是使用True和False,我们使用'O'表示奇数,'E'表示偶数。 该表格如下Odd-Even Table

每行都是检查'奇数/均匀度'的代码中的条件。在每个条件中,您将使用嵌套条件检查哪些变量是最大的奇数。

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个变量,但所需条件的复杂性和数量会随着添加更多变量而急剧上升。

答案 21 :(得分:0)

这回答了John Guttag教授在之前的帖子中提到的书中第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)

答案 22 :(得分:0)

我目前正在阅读这本书并遇到了这个问题。我使用了类似于上面某些解决方案的方法。但是,程序不是仅打印最大值,而是打印保持最大值的变量。

这里的区别在于,而不是检查是否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!"

答案 23 :(得分:0)

这是我昨天晚上考虑之后在我的职业生涯中写过的第一个剧本。

其实我一直在寻找答案,因为我经常遇到错误,但找不到任何令人满意的答案,这里有一个来自我:)

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

答案 24 :(得分:0)

假设我们不打算使用花哨的东西:-)就像python中的max和sort函数一样......我认为说“分配”声明是公平的游戏是安全的....我们毕竟是这样做的必须分配x,y和z。

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

这可以用来从用户读取任意数字(可能是10)的值,并在输入所有值后打印最大的奇数值。只需检查当前“最大”值所输入的每个值。

是的,你需要小心支持负奇数 - 你需要处理第一个奇数的“最大”赋值,无论它是否大于零。

答案 25 :(得分:-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')

答案 26 :(得分:-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"

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