patternpythonMinor
Print the largest odd number entered
Viewed 0 times
numberthelargestprintenteredodd
Problem
I wrote this code to solve a problem from a John Vuttag book:
Ask the user to input 10 integers, and then print the largest odd number that was entered. If no odd number was entered, it should print a message to that effect.
Can my code be optimized or made more concise? Any tips or errors found?
Ask the user to input 10 integers, and then print the largest odd number that was entered. If no odd number was entered, it should print a message to that effect.
Can my code be optimized or made more concise? Any tips or errors found?
{
a = int (raw_input("enter num: "))
b = int (raw_input("enter num: "))
c = int (raw_input("enter num: "))
d = int (raw_input("enter num: "))
e = int (raw_input("enter num: "))
f = int (raw_input("enter num: "))
g = int (raw_input("enter num: "))
h = int (raw_input("enter num: "))
i = int (raw_input("enter num: "))
j = int (raw_input("enter num: "))
num_List = {a,b,c,d,e,f,g,h,i,j }
mylist=[]
## Use for loop to search for odd numbers
for i in num_List:
if i&1 :
mylist.insert(0,i)
pass
elif i&1 is not True:
continue
if not mylist:
print 'no odd integers were entered'
else:
print max (mylist)
}Solution
This is a solution that doesn't use lists, and only goes through the input once.
maxOdd = None
for _ in range(10):
num = int (raw_input("enter num: "))
if num & 1:
if maxOdd is None or maxOdd < num:
maxOdd = num
if maxOdd:
print "The max odd number is", maxOdd
else:
print "There were no odd numbers entered"Code Snippets
maxOdd = None
for _ in range(10):
num = int (raw_input("enter num: "))
if num & 1:
if maxOdd is None or maxOdd < num:
maxOdd = num
if maxOdd:
print "The max odd number is", maxOdd
else:
print "There were no odd numbers entered"Context
StackExchange Code Review Q#26992, answer score: 5
Revisions (0)
No revisions yet.