Last active
November 10, 2015 19:27
-
-
Save colinmcintosh/6def3fb8cf67970ec842 to your computer and use it in GitHub Desktop.
Second Largest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def second_largest(list_of_numbers): | |
return sorted(set(list_of_numbers))[-2] | |
def second_largest_two(list_of_numbers): | |
x = None | |
for i in list_of_numbers: | |
if x is None or i > x: | |
x, y = i, x | |
return y | |
def second_largest_three(list_of_numbers): | |
x = None | |
for i in list_of_numbers: | |
if x is None or i > x: | |
y = x | |
x = i | |
return y | |
Thought Process: | |
>>> def second_largest_two(list_of_numbers): | |
x, y = list_of_numbers.pop(), list_of_numbers.pop() | |
if x > y: x, y = y, x | |
for i in list_of_numbers: | |
if i > y: x, y = y, i | |
return x | |
>>> second_largest_two([1,2,3,3,4,4,5,6,6,7,7]) | |
7 | |
>>> def second_largest_two(list_of_numbers): | |
x, y = list_of_numbers.pop(), list_of_numbers.pop() | |
if x > y: x, y = y, x | |
for i in list_of_numbers: | |
if i > y: x, y = y, i | |
elif x < i < y: x = i | |
return x | |
>>> def second_largest_two(list_of_numbers): | |
x, y = list_of_numbers.pop(), list_of_numbers.pop() | |
if x > y: x, y = y, x | |
for i in list_of_numbers: | |
if i > y: x, y = y, i | |
elif x < i < y: x = i | |
return x | |
>>> second_largest_two([1,2,3,3,4,4,5,6,6,7,7]) | |
7 | |
>>> def second_largest_two(list_of_numbers): | |
x, y = None | |
for i in list_of_numbers: | |
if x is None or i > x: | |
x, y = i, x | |
return x | |
>>> second_largest_two([1,2,3,3,4,4,5,6,6,7,7]) | |
Traceback (most recent call last): | |
File "<pyshell#10>", line 1, in <module> | |
second_largest_two([1,2,3,3,4,4,5,6,6,7,7]) | |
File "<pyshell#9>", line 2, in second_largest_two | |
x, y = None | |
TypeError: 'NoneType' object is not iterable | |
>>> def second_largest_two(list_of_numbers): | |
x = None | |
for i in list_of_numbers: | |
if x is None or i > x: | |
x, y = i, x | |
return x | |
>>> second_largest_two([1,2,3,3,4,4,5,6,6,7,7]) | |
7 | |
>>> def second_largest_two(list_of_numbers): | |
x = None | |
for i in list_of_numbers: | |
if x is None or i > x: | |
x, y = i, x | |
return y | |
>>> second_largest_two([1,2,3,3,4,4,5,6,6,7,7]) | |
6 | |
>>> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment