I tried list
new=[]
new=input()
print(new)
gives me a string as default. How to find the second largest integer from that? I have tried other answers that was found in this site but nothing worked for me.
-
1Can we see what the input string is? Give us some input and output examples...Mahi– Mahi2017年04月30日 07:42:10 +00:00Commented Apr 30, 2017 at 7:42
-
input: 1 2 3 4 5 output: 4Amrith– Amrith2017年05月01日 04:34:37 +00:00Commented May 1, 2017 at 4:34
3 Answers 3
do not compare strings when you want to compare integers! you need to convert those strings to integers:
in_str = '243 3443 6543 43 546'
ints = [int(i) for i in in_str.split()]
ints.sort(reverse=True)
print(ints[1]) # 3443
('9' > '10' is True when comparing strings).
Comments
You can do it like this:
new = []
new = list(map(int, input().split(' ')))
new.sort()
print(new[-2])
It assumes that your input values are separeted by ' '. For example:
6 5 4 3 7 8
map() maps your strings into integers, which returns map-object. Then you can invoke a list() on it to get a list. After sorting you can get penultimate element by accessing [-2].
Comments
You could use the heapq module and map, change to ints first then get the second largest;
new = heapq.nlargest(2, map(int, new))