Python,最大的奇数

时间:2014-11-18 22:34:33

标签: python

我是编码的新手,现在已经学习了几天。我在Python中编写了这个程序,同时还参加了一些MIT OpenCourseware讲座和一些书籍。反正有没有更容易表达的程序?

  

手指练习:编写一个程序,要求用户输入10个整数,然后打印输入的最大奇数。如果没有输入奇数,则应该打印一条消息。

a = int(raw_input('Enter your first integer: '))
b = int(raw_input('Enter your second integer: '))
c = int(raw_input('Enter your third integer: '))
d = int(raw_input('Enter your fourth integer: '))
e = int(raw_input('Enter your fifth integer: '))
f = int(raw_input('Enter your sixth integer: '))
g = int(raw_input('Enter your seventh integer: '))
h = int(raw_input('Enter your eighth integer: '))
i = int(raw_input('Enter your ninth integer: '))
j = int(raw_input('Enter your tenth integer: '))

if a%2 ==0:
    a = 0  
else:
    a = a 
if b%2 ==0:
    b = 0 
else:
    b = b
if c%2 ==0:
    c = 0
else:
    c = c 
if d%2 ==0:
    d = 0
else:
    d = d
if e%2 ==0:
    e = 0
else:
    e = e
if f%2 ==0:
    f = 0
else:
    f = f
if g%2 ==0:
    g = 0
else:
    g = g
if h%2 ==0:
    h = 0
else:
    h = h
if i%2 ==0:
    i = 0 
else:
    i = i 
if j%2 ==0:
    j = 0  
else:
    j = j

value = a, b, c, d, e, f, g, h, i, j
max = max(value)
if max ==0:
    print 'There are no odd numbers.'
else: 
    print max, 'is the largest odd integer.'

18 个答案:

答案 0 :(得分:5)

更紧凑的形式是:

largest = None

for i in range(1, 11):
    number = int(raw_input('Enter integer #%d: ' % i))
    if number % 2 != 0 and (not largest or number > largest):
        largest = number

if largest is None:
    print "You didn't enter any odd numbers"
else:
    print "Your largest odd number was:", largest

这使用一个简单的循环来跟踪输入的整数,但只存储到目前为止遇到的最大奇数。

答案 1 :(得分:2)

numbers = [input('Enter a number: ') for i in range(10)]
odds = [x for x in numbers if x % 2 == 1]
if odds:
    print max(odds)
else:
    print 'No odd numbers input'

说明:

numbers = [input('Enter a number: ') for i in range(10)]

此行使用list comprehension向用户询问10个号码。这些数字将位于列表对象numbers

odds = [x for x in numbers if x % 2 == 1]

接下来,我们使用另一个列表推导来过滤掉numbers中不奇怪的所有数字。由于奇数modulo 2总是等于1,我们会得到一个只包含奇数的新列表(odd)。

if odds:

这是使用python的truthy测试方法。特别是,如果列表为空,则为False。如果列表不为空,则为True

print max(odds)

最后,如果上述内容为True,我们会在odds列表中打印max

else:
    print 'No odd numbers input'

如果if声明为False(没有赔率),我们会告诉用户


正在运行的副本如下所示:

Enter a number: 10
Enter a number: 12
Enter a number: 14
Enter a number: 15
Enter a number: 16
Enter a number: 17
Enter a number: 1
Enter a number: 2
Enter a number: 19
Enter a number: 2
19

答案 2 :(得分:2)

Python具有名为listtuple的对象,它们代表一系列数字 - 它们与其他编程语言中的“数组”具有许多相同的用途。 list的示例是[1,2,3,4,5]

与大多数流行的编程语言一样,Python也有for循环的概念。

myList = [1,2,3,4,5]
for x in myList:
    print(x)

Python也有一个不同寻常但非常有用的结构叫做“列表理解”,它将for循环,list和一个可选的条件结合在一个简洁的语法中 - 查看这些示例并查看是否你可以理解结果与代码的关系

myNewList = [x+1 for x in myList]
myNewSelectiveList = [x+1 for x in myList if x >= 3]

这是一个在练习中特别有用的例子:

userInputs = [int(raw_input('Enter a number:')) for i in range(10)]

最后,有一个函数max可以将list作为参数,并返回列表中最大的项。一旦你在列表中有10个输入,你应该能够使用这些成分在一个相当短的行中找到最高的奇数(max比列表理解if有条件的)

答案 3 :(得分:1)

这个问题在本书的早期提出,并且假设不了解列表,或者确实不了解 Nonetype(它已经提到它但没有解释它是如何使用的)。此外,如果最高奇数为负,这里的某些解决方案将不起作用,因为它们在循环之前初始化了 maximum = 0。

这有效:

iters = 10
largest = "spam"

while iters != 0:
    user_num = int(input("Enter an integer: "))
    if user_num % 2 != 0:
        if largest == "spam" or user_num > largest:
            largest = user_num
    iters -= 1
    
if largest == "spam":
    print("You did not enter an odd integer")
else:
    print("The largest odd integer was", largest)

答案 4 :(得分:1)

我只是在寻找其他问题的同时找到了这个问题,这是我的代码:

注意:我稍微更改了代码,以便可以决定要输入多少个数字

alist=[]
olist=[]
num=int(input("how many numbers ? :  "))

for n in range(num):
        numbers=int(input())
        alist.append(numbers)

for n in range(len(alist)):
    while alist[n]%2 != 0 :
        olist.append(alist[n])
        break
    else:
        n +=1

olist.sort()
if len(olist) != 0:
    print("biggest odd number:  ",olist[-1])
else:
    print("there is no odd number ")

答案 5 :(得分:1)

我也在研究Guttag的书,该解决方案使用了上​​面的一些代码,但可能会有所不同。我立即过滤掉了用户输入,仅包括奇数整数输入。如果所有输入均为偶数,则列表为空,代码检查是否为空列表,然后对剩下的所有内容进行排序(奇数整数)并返回最后一个。请让我知道其中是否存在任何隐藏的问题(我对编写算法也很陌生)。

arr = []
max = 0

while max < 10:
  userNum = int(input('enter an int: '))
  if userNum %2 != 0:
    arr.append(userNum)
  max = max + 1

if len(arr) == 0:
  print('all are even')

oddArr = sorted(arr)
print(oddArr[-1])

答案 6 :(得分:1)

我也在从零开始研究古塔格的书。我提供了以下解决方案:

list = []
odds = False

print('You will be asked to enter 10 integer numbers, one at a time.')

for i in range(1,11):
    i = int(input('Number: ')) 
    list.append(i)

list = sorted(list, reverse = True)

for j in list:
    if j%2 == 1:
        print('The largest odd number is', j, 'from', list)
        odds = True
        break

if odds == False:
    print('There is no odd number from', list)

我经历了一个较长的版本,类似于OP,但是由于MIT 6.00x的阅读清单明确建议在第2章旁研究主题3.2,所以我认为清单是可以接受的答案。

上面的代码应允许使用负数和零。

答案 7 :(得分:0)

比较10个输入并打印最高奇数

y = 0
for counter in range(10):
    x = int(input("Enter a number: "))
    if (x%2 == 1 and x > y):
        y = x

if (y == 0):
    print("All are even")
else:
   print(y, "is the largest odd number")

答案 8 :(得分:0)

尝试以下-

def largest_odd():
    q = int(input('Please enter a number: '))
    w = int(input('Please enter a number: '))
    e = int(input('Please enter a number: '))
    lis = []
    if q%2 != 0:
        lis.insert (q,q)
    if w%2 != 0:
        lis.insert (w,w)
    if e%2 != 0:
        lis.insert (e,e)
    Great = max(lis)
    print(Great)

答案 9 :(得分:0)

我现在正在进行相同的练习,并提出了以下解决方案,该解决方案似乎很好用,并且与迄今为止该书中讲授的主题(变量赋值,条件和while循环)相符:

锻炼: 编写一个程序,要求用户输入10个整数,然后 然后打印输入的最大奇数。如果未输入奇数,则应打印一条消息。

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Surname,FirstName,Email")] PassengerViewModel model)
{
    if (ModelState.IsValid)
    {
        Passenger passenger = new Passenger
        {
            Id = model.Id,
            FirstName = model.FirstName,
            Email = model.Email
        };
        await _context.Passengers.AddAsync(passenger);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    return View(passenger);
}

任何评论将不胜感激。

谢谢, A

答案 10 :(得分:0)

一个简单的答案是:

x = 0
result = None;
while(x < 10):
  inputx = raw_input('Enter integer #%d: ' % x)
  inputx = int(inputx)
  if (inputx % 2 == 1):
    if(inputx > result):
       result = inputx
  x += 1
if result is None:
  print 'no odd number was entered'
else:
  print result

注意:如果输入类似“ 3f”的字符串,则会抛出ValueError:

invalid literal for int() with base 10: '3f'

最后,最好的答案是

result = None
x = 0
while(x < 10):
  inputx = raw_input('Enter integer #%d: ' % x)
  try:
    inputx = int(inputx)
  except ValueError:
    print'you enter value ',inputx,' is not a Integer. please try again!'
    continue
  if (inputx % 2 == 1):
    if(inputx > result):
       result = inputx
  x+=1
if result is None:
  print 'no odd number was entered'
else:
  print 'the largest odd number is: ',result

答案 11 :(得分:0)

在书中介绍如果条件迭代时语句之后,是否将问题引入书中。

尽管在python中可以使用许多数据类型来获得简单的解决方案,但我们只需要使用非常基本的原语即可。

下面的代码需要10个用户输入(仅奇数),并输出10个数字中的最大数字。

答案:(代码)

a1= int(input("Enter the number1: "))
while a1%2 ==0:
    print("Entered number is not an odd number.")
    a1= int(input("Enter the number1: "))
a2= int(input("Enter the number2: "))
while a2%2 ==0:
    print("Entered number is not an odd number.")
    a2= int(input("Enter the number2: "))
a3= int(input("Enter the number3: "))
while a3%2 ==0:
    print("Entered number is not an odd number.")
    a3= int(input("Enter the number3: "))
a4= int(input("Enter the number4: "))
while a4%2 ==0:
    print("Entered number is not an odd number.")
    a4= int(input("Enter the number4: "))
a5= int(input("Enter the number5: "))
while a5%2 ==0:
    print("Entered number is not an odd number.")
    a5= int(input("Enter the number5: "))
a6= int(input("Enter the number6: "))
while a6%2 ==0:
    print("Entered number is not an odd number.")
    a6= int(input("Enter the number6: "))
a7= int(input("Enter the number7: "))
while a7%2 ==0:
    print("Entered number is not an odd number.")
    a7= int(input("Enter the number7: "))
a8= int(input("Enter the number8: "))
while a8%2 ==0:
    print("Entered number is not an odd number.")
    a8= int(input("Enter the number8: "))
a9= int(input("Enter the number9: "))
while a9%2 ==0:
    print("Entered number is not an odd number.")
    a9= int(input("Enter the number9: "))
a10= int(input("Enter the number10: "))
while a10%2 ==0:
    print("Entered number is not an odd number.")
    a10= int(input("Enter the number10: "))

if a1>a2 and a1>a3 and a1>a4 and a1>a5 and a1>a6 and a1>a7 and a1>a8 and a1>a9 and a1>a10:
    print(str(a1) +" is the largest odd number.")
elif a2>a1 and a2>a3 and a2>a4 and a2>a5 and a2>a6 and a2>a7 and a2>a8 and a2>a9 and a2>a10:
    print(str(a2) +" is the largest odd number.")
elif a3>a1 and a3>a2 and a3>a4 and a3>a5 and a3>a6 and a3>a7 and a3>a8 and a3>a9 and a3>a10:
    print(str(a3) +" is the largest odd number.")
elif a4>a1 and a4>a2 and a4>a3 and a4>a5 and a4>a6 and a4>a7 and a4>a8 and a4>a9 and a4>a10:
    print(str(a4) +" is the largest odd number.")
elif a5>a1 and a5>a2 and a5>a3 and a5>a4 and a5>a6 and a5>a7 and a5>a8 and a5>a9 and a5>a10:
    print(str(a5) +" is the largest odd number.")
elif a6>a1 and a6>a2 and a6>a3 and a6>a4 and a6>a5 and a6>a7 and a6>a8 and a6>a9 and a6>a10:
    print(str(a6) +" is the largest odd number.")
elif a7>a1 and a7>a2 and a7>a3 and a7>a4 and a7>a5 and a7>a6 and a7>a8 and a7>a9 and a7>a10:
    print(str(a7) +" is the largest odd number.")
elif a8>a1 and a8>a2 and a8>a3 and a8>a4 and a8>a5 and a8>a6 and a8>a7 and a8>a9 and a8>a10:
    print(str(a8) +" is the largest odd number.")
elif a9>a1 and a9>a2 and a9>a3 and a9>a4 and a9>a5 and a9>a6 and a9>a7 and a9>a8 and a9>a10:
    print(str(a9) +" is the largest odd number.")
else:
    print(str(a10) +" is the largest odd number.")

希望这会有所帮助。

答案 12 :(得分:0)

以我的经验,使用函数可以更轻松地表达程序。 这应该是我在针对Python 3.7.6测试的语法中的答案:

'''
Finger exercise: 
    Write a program that asks the user to input 10 integers, 
    and then prints the largest odd number that was entered. 
    If no odd number was entered, it should print a message to that effect.
'''

def LargestOdd(numbers=[]):
    '''
    Parameters
    ----------
    numbers : list, whcih should contain 10 integers.
        DESCRIPTION. The default is [].

    Returns
    -------
    The largest odd integer in the list number.

    '''
    odd_numbers=[]
    if len(numbers)==10:
        for n in numbers:
            
            if n%2 != 0:
                odd_numbers.append(n)
                max_numb=max(odd_numbers)
        print('The largest odd number is '+str(max_numb))
    else:
        print('Please, enter 10 numbers')
        
        
    
LargestOdd([1,2,3,7,45,8,9,10,30,33]) 

输出:最大奇数是45

答案 13 :(得分:0)

n = int(input("Enter the no of integers:"))
lst = []
count = 1
while count <=n:
    no = int(input("Enter an integer:"))
    count = count +1
    if (no%2!=0):
        lst.append(no)
print ("The list of odd numbers",lst)
print("The maximum number from the list of odd number is:",max(lst))        
    

答案 14 :(得分:0)

这是我的解决方案:

def max_odd():
    """Returns largest odd number from given 10 numbers by the use.
    if the input is not valid, the message is displayed to enter valid numbers"""
    x = [input('Enter a value: ') for i in range(10)]
    x = [int(i) for i in x if i]
    if x:
        try:
            x = [i for i in x if i%2 != 0]
            return(max(x))
        except:
            return('All even numbers provided.')
    else:
        return('Please enter a valid input')

答案 15 :(得分:0)

我从 Guttag 的书中开始学习编码。由于这是在第 2 章中,因此解决方案仅遵循基本的 if 条件和 while 循环

#input 10 integers
n1 = int(input('Enter 1st integer: '))
n2 = int(input('Enter 2nd integer: '))
n3 = int(input('Enter 3rd integer: '))
n4 = int(input('Enter 4th integer: '))
n5 = int(input('Enter 5th integer: '))
n6 = int(input('Enter 6th integer: '))
n7 = int(input('Enter 7th integer: '))
n8 = int(input('Enter 8th integer: '))
n9 = int(input('Enter 9th integer: '))
n10 = int(input('Enter 10th integer: '))

#create list from input
list = [n1,n2,n3,n4,n5,n6,n7,n8,n9,n10]
largest = list[0] #Assign largest to the first integer
x = 1 #index starts at 1
while x < len(list):
  if list[x]%2 != 0:
    if list[x] > largest:
      largest = list[x]
  x += 1
if largest%2 == 0:
  print('All numbers are even')
else:
  print('Largest odd number is', largest)

答案 16 :(得分:0)

其他答案和评论表明列表和循环更好,但它们不是改变和缩短代码的唯一方法。

在您的测试中,else: a = a部分无效,将a分配给自身没有变化,因此可以删除它们,并将if个测试分别带到一行:

a = int(raw_input('Enter your first integer: '))
b = int(raw_input('Enter your second integer: '))
c = int(raw_input('Enter your third integer: '))
d = int(raw_input('Enter your fourth integer: '))
e = int(raw_input('Enter your fifth integer: '))
f = int(raw_input('Enter your sixth integer: '))
g = int(raw_input('Enter your seventh integer: '))
h = int(raw_input('Enter your eighth integer: '))
i = int(raw_input('Enter your ninth integer: '))
j = int(raw_input('Enter your tenth integer: '))

if a%2 == 0: a = 0  
if b%2 == 0: b = 0 
if c%2 == 0: c = 0
if d%2 == 0: d = 0
if e%2 == 0: e = 0
if f%2 == 0: f = 0
if g%2 == 0: g = 0
if h%2 == 0: h = 0
if i%2 == 0: i = 0 
if j%2 == 0: j = 0  

value = a, b, c, d, e, f, g, h, i, j
max = max(value)
if max ==0:
    print 'There are no odd numbers.'

这是最明显的变化,使其更容易遵循,而不会从根本上改变您正在做的模式。

之后,有一些方法可以重写它 - 例如,只保留数学,偶数除以2,余数为0,奇数除数为1.因此,(x % 2) * x将偶数数改为0 ,但保持奇数相同。

所以你可以替换所有的if测试,没有测试,只需要一个赋值:

a = (a % 2) * a  
b = (b % 2) * b
c = (c % 2) * c
...
if e%2 == 0: e = 0
if f%2 == 0: f = 0

这些行会稍微短一些,如果你对它的工作方式没有问题,可以将它们合并到value行,然后将其直接放到max中以获取:

a = int(raw_input('Enter your first integer: '))
b = int(raw_input('Enter your second integer: '))
c = int(raw_input('Enter your third integer: '))
d = int(raw_input('Enter your fourth integer: '))
e = int(raw_input('Enter your fifth integer: '))
f = int(raw_input('Enter your sixth integer: '))
g = int(raw_input('Enter your seventh integer: '))
h = int(raw_input('Enter your eighth integer: '))
i = int(raw_input('Enter your ninth integer: '))
j = int(raw_input('Enter your tenth integer: '))

largest = max(a%2*a, b%2*b, c%2*c, d%2*d, e%2*e, f%2*f, g%2*g, h%2*h, i%2*i, j%2*j)

if largest == 0:
    print 'There are no odd numbers.'
else: 
    print largest, 'is the largest odd integer.'

在没有某种循环的情况下,没有办法缩短分配十个变量,并且可以说这是否“更容易表达程序”,但它确实需要将58行减少到17,删除10条件测试,10个其他/无操作分配和1个变量,同时保持大致相同的结构/工作。

PS。我改变了max = max(),因为调用你的变量与函数同名是一个坏主意 - 你不能再次使用该函数,而且对于那些已经知道'max'是什么的读取你的代码的Python程序员来说很困惑,如果你把这个名字用于别的东西。

编辑:评论员认为负数很重要。上面的文字回答“这是我的代码,我怎么能更容易地表达它?”没有引入任何新的Python或改变行为,但它不能处理负奇数; max()将始终在负奇数上选择零,并且程序将错误地回答“没有奇数”。

如果不引入任何新概念,我认为这是不可修复的。如果正在引入新概念,使用列表和循环。安迪建议建立一个仅包含奇数的列表,然后取其最大值,例如。

但是,做一些没有列表处理它们的东西 - 还有另一种方法几乎不改变代码的形状,引入了布尔OR操作,它比较两个真/假值并返回false,如果他们都是假的,否则都是真的。

Python做了很多自动化的幕后转换为true / false,使逻辑运算符运行良好。没有值的变量(零,空容器,空字符串)都是“假”,具有某些值的变量都是“真”。

从早些时候开始,我们有一位将偶数数字调到零(a%2*a),现在我们想完全从数字线上敲零:

-3 or None -> -3
-1 or None -> -1
 0 or None -> None
 1 or None ->  1
 3 or None ->  3
 5 or None ->  5

简介:a%2*a or None。它是神奇的,丑陋的,难以理解,但有效的Python - 我很喜欢因为它就像解决一个谜题而且它有效,你知道吗?将最大行和测试更改为:

largest = max(a%2*a or None, b%2*b or None, c%2*c or None, d%2*d or None, e%2*e or None,
              f%2*f or None, g%2*g or None, h%2*h or None, i%2*i or None, j%2*j or None)

if largest == None:

Evens被压得零,零被压得零,赔率不变。 Max现在只有奇数可以使用,所以它现在可以选择一个负奇数作为答案。案件结案。顺便说一句。使用清单。

答案 17 :(得分:-1)

此代码也可以正常工作。为python 2.7测试的语法

 def tenX():  #define function
    ten = [] #empty list for user input
    odds = [] #empty list for odd numbers only
    counter = 10
    ui = 0
    while counter > 0 :
        ui = raw_input('Enter a number: ')
        ten.append(int(ui)) #add every user input to list after int conversion
        counter -= 1
    for i in ten:
        if i % 2 != 0:
        odds.append(i)
    print "The highest number is", max(odds) #max() returns highest value in a list

>>> tenX() #call function
相关问题