I have written the following program that asks the user to enter a number and takes in that many values. The goal here is to determine what the minimum and maximum values are based on the user input. Most use cases work, but when you enter a sequence, i.e. 1, 2, 3, 4
or 2, 3, 4, 5
the output for minimum is always min: 0
. I can't figure out a way to handle this situation. Can anyone help guide me in the correct direction?
num_of_iters = int(input("Enter a number: "))
print(f"Please enter {num_of_iters} number.")
maximum = 0
minimum = 0
for i in range(0, num_of_iters):
num = int(input())
if num >= maximum:
maximum = num
if num <= minimum:
minimum = num
print("min: ", minimum)
print("max: ", maximum)
CodePudding user response:
None of the numbers you've input are less than 0
, so the minimum is never updated.
You should modify that condition so that it updates on the first number.
if i == 0 or num <= minimum:
minimum = num
Functional Approach
Alternatively, if you want to get fancy, we can do this as a one-liner using functools.reduce
and the :=
operator. I'm going to draw it out a bit more for demonstration.
from functools import reduce
init_min = float("inf")
init_max = float("-inf")
init = (init_min, init_max)
num_inputs = 5
min, max = reduce((lambda init, _: (init[0], n) if (n := int(input())) > init[1] else (n, init[1]) if n < init[0] else init), range(num_inputs), init)
We only want the input number once, so we use :=
to bind the result of int(input())
to n
and return the value so it can be used.
We test this value against our initial min and max and modify the tuple at each iteration accordingly. In the end, the tuple we get has the min and max values.
CodePudding user response:
You're initialising minimum
to zero, and when a sequence is entered that contains only numbers larger than zero, that value never changes (because the if num <= minimum:
block never gets executed). What you can do is to initialise minimum
to a number that you know will be higher than any number ever entered, e.g. 1000. That would be analogous to initialising maximum
to zero, a number that's lower than any number that will ever be entered, but that's error-proof and not very Pythonic. A safer bet might be to initialise minimum
and maximum
to None
and to test, in the if
blocks, if minimum
is less than the existing minimum
or to zero, and to set it to the current num
if so (analogous for maximum
).