Sorting a list with negative numbers as strings produces unexpected result

Viewed 149

I made a program to calculate the second largest number from a list. Input is a string that is sliced into a list. Here's the code

score1 = input()
score = score1.split()
score.sort()
maximum = max(score)
count = score.count(maximum)
for i in range(0,count):
    score.pop()
print(max(score))

And it is working fine for positive numbers but if the list contains a negative number my program fails to produce the correct answer.

For Input -7 -7 -7 -7 -6

Output is -6 instead of -7

Any way to improve it?

5 Answers

Since the input is a string, when you call sort and max they're working lexicographically, not numerically. You need to convert to integers first:

score = [int(item) for item in score1.split()]

The reason your code does not work for negative numbers (btw it also does not work for numbers with more than 1 digits as well) is that you are not sorting numbers, you are sorting strings. input()'s return value is always a string since no implicit conversion takes place. Therefore, in order to get the result you want you have to cast them to some number form first.

score = [int(x) for x in input().split()]
score.sort()

after that you can do whatever you want with it.

Note that wrapping the list-comprehension in a try-except block would also be a good idea to avoid bad input.

score1 = input()
score = score1.split()

#converting the list of strings into list of integers
score = [int(i) for i in score]

#removing duplicates
score = list(set(score))

#sorting the list
score.sort()

#printing the second largest number

print(score[-2])

You can get your expected answer by doing this :

score = input().split()
li = []

for value in score:
    x = int(value) # converting to int
    li.append(x) # appending to empty list
final = set(li) # removing duplicates values
print(max(final)) # getting the maximum value

Hope that it will help you ..

Try this maybe:

score1 = input()
score = score1.split()
score = sorted(set(map(int, score)))
second_max=score[-2]
Related