I recently started coding and I love it. I'm currently working on a few tasks (for beginners lol) and just came up with the following: 'Find the second greatest element in a list'
I did the following:
def second_greatest(list):
length = len(list)
if length <= 1:
return(list)
else:
greatest = max(list[0], list[1])
s_greatest = min(list[0], list[1])
for i in range (2, length):
if list[i] > greatest:
s_greatest = greatest
greatest = list[i]
elif list[i] > s_greatest and greatest != list[i]:
s_greatest= list[i]
return(s_greatest)
I found this solution on the web:
def example(example_list, k):
for i in range(k-1):
example_list.remove(max(example_list))
return (max(example_list))
I feel like an idiot, because my code looks too complicated compared to the second one... If we have a relatively large number (e.g. find 1438th greatest), I would definitely go with solution 2.. But I'm wondering which solution is better (faster) for this particular question (find second greatest value)?
source https://stackoverflow.com/questions/71832779/is-my-code-okay-or-did-i-make-it-way-too-complicated
Comments
Post a Comment