2

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?

Georgy
  • 12,464
  • 7
  • 65
  • 73
Mohit
  • 31
  • 4

5 Answers5

7

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()]
tzaman
  • 46,925
  • 11
  • 90
  • 115
2

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.

Ma0
  • 15,057
  • 4
  • 35
  • 65
1
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])
Chandresh
  • 140
  • 7
0

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 ..

barii
  • 339
  • 3
  • 12
-2

Try this maybe:

score1 = input()
score = score1.split()
score = sorted(set(map(int, score)))
second_max=score[-2]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
kubatucka
  • 555
  • 5
  • 15
  • why the `set` and `list` calls? 1) you don't need them and 2) using `set` removes the duplicates which might be a mistake in this case. – Ma0 Jun 29 '20 at 13:39
  • 1
    This goes too far in anticipating what the OP might want to do with the list. It's one thing to remove all occurrences of the maximum element; it's quite another to assume that all duplicates should be removed as well. – chepner Jun 29 '20 at 13:40
  • Well if i didn't misunderstand OP he want to get the second largest distinct number from his input right? – kubatucka Jun 29 '20 at 13:45