+ 2

Homework Python

Hi, I have to write a function which takes list of numbers >=0 and gives me back the second max number in the list. I cannot sort, change the list or import methods. If the list contains <2 elements it should give me 0 I have to iterate every element only once. Example: secondmax([2, 5, 1, 6, 3]) -> 5 secondmax([2]) -> 0 secondmax([]) -> 0 My Attempt: I tried to do smth but it is not much, thanks Def secondmax(*args): If type(args) is list: For x in args:

16th Jun 2020, 9:37 AM
Nikkie
Nikkie - avatar
12 ответов
+ 10
I think you should try with finding the max() first. Then, find a min() and assign it to a variable. Then iterate through the list and keep re-assigning the value if it is greater than the last one, but still lower than the max. After the iteration is done, you will get the second max :)
16th Jun 2020, 9:43 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 8
1. Find the max number of the list 2. Iterate through the list returning numbers smaller than the max number 3. Print the new max number
16th Jun 2020, 10:03 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 6
O(n) without any built-in features: https://code.sololearn.com/czalRkLqGa3W/?ref=app
18th Jun 2020, 6:56 AM
Tibor Santa
Tibor Santa - avatar
+ 3
The function max iterates too. Is it allowed to use it?
18th Jun 2020, 6:51 AM
Oma Falk
Oma Falk - avatar
+ 2
Thank you!
16th Jun 2020, 1:33 PM
Nikkie
Nikkie - avatar
17th Jun 2020, 4:22 PM
vamsisaikrishna
vamsisaikrishna - avatar
+ 2
I think this is still a bit underspecified. What is the expected result when the list contains 2 or more elements that are all equal?
18th Jun 2020, 3:41 AM
Tibor Santa
Tibor Santa - avatar
+ 2
Mostapha Amenchar your code is good but does not seem to solve the above problem. Thanks.
18th Jun 2020, 6:39 AM
Marcel Magero
Marcel Magero - avatar
+ 2
Tibor Santa thats it
18th Jun 2020, 7:42 AM
Oma Falk
Oma Falk - avatar
+ 2
Thank you for your comment Marcel. Would you explain to me why? maybe i can improve the code.
18th Jun 2020, 11:32 AM
Mostapha Amenchar
Mostapha Amenchar - avatar
+ 1
Sorry, I forgot to tell that I should iterate through every element only once
16th Jun 2020, 9:46 AM
Nikkie
Nikkie - avatar
17th Jun 2020, 9:44 PM
Mostapha Amenchar
Mostapha Amenchar - avatar