For getting unique elements. Instead of for loop. You can directly convert the original list into a set. And, then again convert set into a list. The remaining code can be kept as it is. You can store the resulting output in new_list.
While using index -3 also works. An alternate approach could be new_list.sort(reverse=True). Now, the new_list would contain elements in descending order and you can pick 3rd index from the beginning. And store it in your result variable.
Well, I just reduced some lines of your code by mentioning the above points. Your approach also works :). But, you need to be careful while using sort(). List.sort() built-in has a time complexity of O(nlogn). It would make the code considerably slower. While the approach I shared has the time complexity of O(n). It was mentioned in the problem statement that the time complexity of the solution needs to be O(n).
Thanks for your adivces ! It's helpful!
My new version, is it better?
def thirdMax(lister):
result = None
dicolist = set(lister)
new_list = list(dicolist)
if len(new_list) > 3:
for i in range(0,2):
new_list.remove(max(new_list))
result = max(new_list)
elif len(new_list)==3:
result = min(new_list)
else:
result = max(new_list)
del dicolist
del new_list
return result
Cool! IMO still there is no need to create a new_list. Can you test the below code for some inputs? Should work.
def thirdMax(lister):
lister = list(set(lister))
if len(lister) > 3:
for i in range(0,2):
lister.remove(max(lister))
result = max(lister)
elif len(lister)==3:
result = min(lister)
else:
result = max(lister)
return result
Hi Alex,
Well, I just reduced some lines of your code by mentioning the above points. Your approach also works :). But, you need to be careful while using sort(). List.sort() built-in has a time complexity of O(nlogn). It would make the code considerably slower. While the approach I shared has the time complexity of O(n). It was mentioned in the problem statement that the time complexity of the solution needs to be O(n).
I hope this helps. :)
Thanks for your adivces ! It's helpful!
My new version, is it better?
Cool! IMO still there is no need to create a new_list. Can you test the below code for some inputs? Should work.
Great !!! Thanks for your share...
I keep this. Best regards