Skip to content

Instantly share code, notes, and snippets.

@colinmcintosh
Last active November 10, 2015 19:27
Show Gist options
  • Save colinmcintosh/6def3fb8cf67970ec842 to your computer and use it in GitHub Desktop.
Save colinmcintosh/6def3fb8cf67970ec842 to your computer and use it in GitHub Desktop.
Second Largest
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