Home > front end >  Max function doesn't seem to work properly?
Max function doesn't seem to work properly?

Time:05-22

Ok so kinda confuse with the max function, warning, very messy (just started learning yesterday using youtube and programiz)

m=input()
k=m.split()
k=list(k)
h1=(max(k))
print (h1)
k.remove(max(k))
h2 =(max(k))
print (h2)
k.remove(max(k))
h3 =(max(k))
print (h3)
k.remove(max(k))
h4 =(max(k))
print (h4)
k.remove(max(k))
h5 =(max(k))
print (h5)
k.remove(max(k))
h1=int(h1)
h2=int(h2)
h3=int(h3)
h4=int(h4)
h5=int(h5)
total=h1 h2 h3 h4 h5
print (total)

given input is : 60 80 100 40 40 0 70 60 90 100 40 0

surely the max 5 value should be ; 100 100 90 80 70

but somehow my code got 90 80 70 60 60

is there somewhere I messed up?

CodePudding user response:

First, it's really cool that you are starting with python! I believe what you've missed is that the function input returns a string.

If we look at the result after the lines:

m=input()
k=m.split()
k=list(k)  # (This is redundent by the way, split already returns a list)

k = ['60', '80', '100', '40', '40', '0', '70', '60', '90', '100', '40', '0']

If we look at k we see that this is a result of strings - and the function max will find you the max value in the list, but lexicographicaly ('9' is larger than '1', so '90' is larger than '100').

In order to receive the actual integer max number you have to convert the values inside the list to integers:

[int(x) for x in k]
Out: [60, 80, 100, 40, 40, 0, 70, 60, 90, 100, 40, 0]

Hope it helps :)

CodePudding user response:

You're applying the max function to a list of strings, as opposed to a list of integers. When you do that, it goes through each letter and compares them, stopping when there is a winner. "9", as in, the letter "9", is ordered greater than "1". This is why it ranks "90" as greater than "100". If you convert the elements in the list to integers before comparing, the values should be as expected.

You can fix by doing

m=input()
k=m.split()
k=[int(l) for l in k]
h1=(max(k))
# ...

This uses a list comprehension, in case you aren't familiar with it yet.

CodePudding user response:

You should familiarise yourself with loops, exception handling and how to properly manage / validate user input.

Here's how you could implement this in a more structured rather than "straight line" manner.

Note:

The output of this code will show the appropriate list of maximum values entered by the user but not necessarily in the order they were input.

NINPUTS = 5

while True:
    inval = input(f'Enter at least {NINPUTS} numbers separated by whitespace: ')
    try:
        if len(numList := list(map(int, inval.split()))) < NINPUTS:
            raise ValueError('Not enough numbers')
        print(sorted(numList)[-NINPUTS:])
        break
    except ValueError as e:
        print(f'{e}. Please try again')

For an input string of '60 80 100 40 40 0 70 60 90 100 40 0' this will output:

[70, 80, 90, 100, 100]
  • Related