I'm reviewing a python exercise which does the following :
reads list of numbers til "done" gets entered.
When "done" is inputted, print largest and smallest of the nu开发者_如何学JAVAmbers.
And it should be without directly using the built-in functions, max() and min().
Here is my source. Traceback says, "'float' object is not iterable"
I think my errors are coming from not using the list properly to calculate smallest and largest. Any tips and help will be greatly appreciated!
while True:
inp = raw_input('Enter a number: ')
if inp == 'done' :
break
try:
num = float(inp)
except:
print 'Invalid input'
continue
numbers = list(num)
minimum = None
maximum = None
for num in numbers :
if minimum == None or num < minimum :
minimum = num
for num in numbers :
if maximum == None or maximum < num :
maximum = num
print 'Maximum:', maximum
print 'Minimum:', minimum
Thank you!
You shouldn't need a list. You should only need to keep track of the current minimum and maximum as you go.
minimum = None
maximum = None
while True:
inp = raw_input('Enter a number: ')
if inp == 'done':
break
try:
num = float(inp)
except:
print 'Invalid input'
continue
if minimum is None or num < minimum:
minimum = num
if maximum is None or num > maximum:
maximum = num
print 'Maximum:', maximum
print 'Minimum:', minimum
With num = float(inp)
you only assign a single number and overwrite it each time a new one is assigned. You have to create the list first, then add numbers to it each time. Something like this:
nums = []
while True:
...
nums.append(float(inp))
input_set = []
input_num = 0
while (input_num >= 0):
input_num = int(input("Please enter a number or -1 to finish"))
if (input_num < 0):
break
input_set.append(input_num)
print(input_set)
largest = input_set[0]
for i in range(len(input_set)):
if input_set[i] > largest:
greatest = input_set[i]
print("Largest number is", greatest)
smallest = input_set[0]
for i in range(len(input_set)):
if input_set[i] < largest:
smallest = input_set[i]
print("Smallest number is", smallest)
Try this code :
def max(data):
l = data[0]
s = data[0]
for num in data:
if num > l:
l = num
elif num < s:
s = num
return l, s
print(max([0, 10, 15, 40, -5, 42, 17, 28, 75]))
精彩评论