I put together this code to for the Udacity cs101 exam. It passes the test, but I feel their must be a more elegant way to manage this problem. Some help from a module (like itertools).
Question 8: Longest Repetition
Define a procedure, longest_repetition, that takes as input a list, and returns the element in the list that has the most consecutive repetitions. If there are multiple elements that have the same number of longest repetitions, the result should be the one that appears first. If the input list is empty, it should return None.
def longest_repetition(alist):
alist.reverse()
largest = []
contender = []
if not alist:
return None
for element in alist:
if element in contender:
contender.append(element)
if len(contender) >= len(largest):
largest = contender
else:
contender = []
contender.append(element)
if not largest:
return contender[0]
else:
return largest[0]
#For example,
print longest_repetition([1, 2, 2, 3, 3, 3, 2, 2, 1])
# 3
print longest_repetition(['a', 'b', 'b', 'b', 'c', 'd', 'd', 'd'])
# b
print longest_repetition([1,2,3,4,5])
# 1
print longest_repetition([])
# None