+ 2

Write a program to find second largest number from a list of number .

3rd Oct 2018, 2:21 PM
partha
partha - avatar
15 Antworten
+ 8
a = [89,17,69,5,24,48] print(sorted(a)[-2]) Kevin Dietrichstein Ackchyually... that makes me wonder if we're looking for the second largest unique number in the list, because I think this is what your code does. If you add more 4s to your list, it will ignore them all and return 3. But maybe this is exactly what is wanted? 🤔
3rd Oct 2018, 2:57 PM
Anna
Anna - avatar
+ 6
lst = [1,2,3,4] print(max(x for x in lst if x != max(lst)))
3rd Oct 2018, 2:42 PM
Kevin Dietrichstein
Kevin Dietrichstein - avatar
+ 6
aahh i see... sorry Kishalaya Saha,i dont know anything about python ...soo I didn't understand😅
3rd Oct 2018, 4:05 PM
Nimit Sandeep Jhunjhunwala
Nimit Sandeep Jhunjhunwala - avatar
+ 6
Kishalaya Saha Ohh i see!! will catch up with others ASAP🤗
3rd Oct 2018, 4:17 PM
Nimit Sandeep Jhunjhunwala
Nimit Sandeep Jhunjhunwala - avatar
+ 5
would it work if we did bubble sorting or something of all the numbers entered by the user then assign the each value in a sepeeate array and print the second index of that array?🤔
3rd Oct 2018, 3:02 PM
Nimit Sandeep Jhunjhunwala
Nimit Sandeep Jhunjhunwala - avatar
+ 3
Deadpool No problem, we're all learning! By the way, sorting is a little more work than necessary. We only need the top two. The fastest sorting algorithm is O(n log n), finding max is O(n).
3rd Oct 2018, 4:10 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 3
you guys are talking about stuff I don't have a clue about yet😅
3rd Oct 2018, 4:11 PM
partha
partha - avatar
+ 2
If i've got it right: a=[1,4,5,8,22,34] a.remove(max(a)) print(max(a)) Note that this code will alter the source list.
3rd Oct 2018, 2:37 PM
strawdog
strawdog - avatar
+ 2
Find max. Remove max. Find max again. 😂 There's a method that requires fewer comparisons. But it requires extra memory, and is a bit trickier.
3rd Oct 2018, 2:37 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 2
Kevin Dietrichstein Nice! I always upvote pythonian approaches like this.
3rd Oct 2018, 3:17 PM
strawdog
strawdog - avatar
+ 2
Anna yeah that was my guess, but no matter what his problem was, we provided him with all possible solutions 😄
3rd Oct 2018, 3:36 PM
Kevin Dietrichstein
Kevin Dietrichstein - avatar
+ 2
Deadpool , sure! In Python, you don't even have to sort yourself. That's kind of what Anna did.
3rd Oct 2018, 3:57 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 2
max1, max2 = nums[:2] if max1<max2: max1, max2 = max2, max1 for p in nums: if p>max2: max2 = max1 if max1<max2: max1, max2 = max2, max1 return max2
3rd Oct 2018, 11:39 PM
Flandre Scarlet
Flandre Scarlet - avatar
+ 2
Here is a similar one that needs only one iteration and doesn't sort the list: https://code.sololearn.com/cuHLqwdwu34M/?ref=app
4th Oct 2018, 2:05 AM
Anna
Anna - avatar
3rd Oct 2018, 2:57 PM
partha
partha - avatar