The first line should give the number of cases, after that the lines following would be the cases and among those cases, you must be able to print out the maximum number, the minimum number, and the range. I have this code so far but it's only taking the first two cases into account and completely ignores the first line denoting the number of cases. Can someone tell me what's wrong with it? Thanks!
cases = int(input())
index = 1
inp = int(input())
minimum = inp
maximum = inp
while index<=cases:
inp = int(input())
if input>maximum:
maximum = inp
elif input<minimum:
minimum = inp
index = index + 1
print('Maximum: '+str(maximum))
print('Minimum: '+str(minimum))
print('Range: '+str(maximum-minimum))
This is a typical off-by-one error. A generic solution for those is to just try out your algorithm with some small numbers like 1 or 3 and check if they fit your expectations.
Let's say the 1st input is 1, so cases
gets initialized to 1. The while
condition index<=cases
evaluates to 1<=1
, so it enters the loop one more time, although you already registered a case on line 3.
Just replace the loop condition to index<cases
and you will be fine. Also, you need to unindent the print
calls to write them once after all the inputs have been read.
Also, a good advice is to use a debugger to see if the actual flow of the program and the values in the variables match your expectations if you face more difficult problems that you cannot fix just by looking at the code. PyCharm is a pretty solid IDE for debugging python code.
This will help solve your question:
cases = int(input())
arr = [int(input()) for i in range(cases)]
min_e, max_e = min(arr), max(arr)
print("Min:{} Max:{} Range:{}".format(min_e, max_e, max_e-min_e))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.