+ 2
Write a program to find second largest number from a list of number .
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? 🤔
+ 6
lst = [1,2,3,4]
print(max(x for x in lst if x != max(lst)))
+ 6
aahh i see... sorry Kishalaya Saha,i dont know anything about python ...soo I didn't understand😅
+ 6
Kishalaya Saha Ohh i see!! will catch up with others ASAP🤗
+ 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?🤔
+ 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).
+ 3
you guys are talking about stuff I don't have a clue about yet😅
+ 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.
+ 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.
+ 2
Kevin Dietrichstein Nice! I always upvote pythonian approaches like this.
+ 2
Anna yeah that was my guess, but no matter what his problem was, we provided him with all possible solutions 😄
+ 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
+ 2
Here is a similar one that needs only one iteration and doesn't sort the list:
https://code.sololearn.com/cuHLqwdwu34M/?ref=app
+ 1