Find the maximum and minimum number in list in a string

3

I have the following file:

a = '1 0 10 2 3'

I want to print the highest and lowest values, so I used max() and min() but it only counts the unit. I did this:

a='joao 1 0 10 2 3'
b=a.split()
c=max(b[1:])
print(c)
c=min(b[1:])
print(c)

output:

3
0

output I want:

10
0
    
asked by anonymous 29.11.2018 / 22:17

2 answers

7

The problem is that you are comparing strings and not numbers, so when you compare "10" to "3" the first is less, because analysis is done character by character, so the comparison is the character "1" with the character "3", and of course "3" is larger. This does not work, and to function as you will have to do strings in% with% s.

But there is a problem, you can not guarantee that all items can be converted. You'll have to treat the exception that will be generated by turning the text into an integer, so the code gets a bit more complicated.

a = 'joao 1 0 10 2 3'
b = a.split()
c = []
for i in b:
    try:
        c.append(int(i))
    except ValueError:
        pass
print(max(c))
print(min(c))

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

Obviously the question does not clarify what to do with string s, I had the understanding that should ignore and not generate error, after all the code would not be useful, and would not give the result that the AP asked in the question with input, and I considered that the input example cited is just to facilitate, that could or may not have texts even in the middle of the numbers in any position.     

29.11.2018 / 22:33
6

The problem is that when you divide a string you get a list of strings . The maximum and minimum function will use the same sort ordering logic to identify the highest and lowest value respectively.

The point is that the ordering of strings is done in an alphanumeric way. If you have '1', '0', '10', '2' and '3' strings, the value 3 will be the maximum, because in alphanumeric order, 3 comes after 1 As the comparison is character, the Python interpreter does not treat 10 as an integer, but as two characters.

Before setting the maximum and minimum, you need to convert the values to numeric:

b = [int(n) for n in a.split()]
    
29.11.2018 / 22:25