0

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.

Mahi
22.5k23 gold badges92 silver badges130 bronze badges
asked Apr 30, 2017 at 7:31
2
  • 1
    Can we see what the input string is? Give us some input and output examples... Commented Apr 30, 2017 at 7:42
  • input: 1 2 3 4 5 output: 4 Commented May 1, 2017 at 4:34

3 Answers 3

2

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

answered Apr 30, 2017 at 7:59
Sign up to request clarification or add additional context in comments.

Comments

1

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

answered Apr 30, 2017 at 7:44

Comments

1

You could use the heapq module and map, change to ints first then get the second largest;

new = heapq.nlargest(2, map(int, new))
answered Apr 30, 2017 at 7:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.