繁体   English   中英

选择最大的奇数python

[英]Choose largest odd number 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

方法

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

参考

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

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"
try:
    largest = max(val for val in (x,y,z) if val % 2)
    print(largest)
except ValueError:
    print('Even')

请注意, sorted是一个O(n log n)操作,而maxO(n) 对于这么短的序列,速度差异可能无关紧要,但使用最佳工具进行工作是一种很好的做法。

像这样:

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

这是 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

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

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

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 , 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)。

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

我正在阅读 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]

这是我的解决方案:

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 行的工作程序是不可能的。 请让我知道您是否找到了一种方法使其仅使用目前提供的材料

在前 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")
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)

根据评论,如果 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 

这是我从昨天晚上开始思考后,在我的职业生涯中写的第一个剧本。

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

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

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

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

这回答了 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)

我也在学习 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')
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)

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

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

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

仅当/否则:

    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"

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

这是我的“新手”版本的解决方案。 基本上,该问题需要根据用户输入(例如,一个奇数和两个偶数等情况等)分析 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)')

这是我的解释,我正在做同样的任务,这是使用 Python 进行计算和编程介绍,第二版,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")`

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

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

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

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

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

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

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

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

这个问题要求从 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 个变量,但随着添加更多变量,所需条件的复杂性和数量会急剧增加。

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

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)

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

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"

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

我刚刚阅读了 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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM