Skip to content

Instantly share code, notes, and snippets.

@Per48edjes
Last active January 27, 2017 20:01
Show Gist options
  • Save Per48edjes/8306dfe5c874678ffeca344d91e67ac3 to your computer and use it in GitHub Desktop.
Save Per48edjes/8306dfe5c874678ffeca344d91e67ac3 to your computer and use it in GitHub Desktop.
Find the element in a list that has the most consecutive repetitions
# 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(input_list):
if len(input_list) == 0:
return None
u_elements = unique_elements(input_list)
counter_list = []
for element in u_elements:
i = 0
freq, in_a_row = 1, 1
while i < len(input_list) - 1:
if element == input_list[i] and input_list[i] == input_list[i+1]:
freq = freq + 1
in_a_row = freq
else:
freq = 1
i = i + 1
counter_list.append([element, in_a_row])
return get_first_highest(counter_list)
# Finds the unique elements of a list
def unique_elements(input_list):
unique_elements = [input_list[0]]
for element in input_list:
if element not in unique_elements:
unique_elements.append(element)
return unique_elements
# Returns the most frequent element in 'counter' list in form [[element,frequency],...]; if multiple, returns the first, "maximum" frequency element.
def get_first_highest(counter_list):
last_highest_freq = 0
for key_value_pair in counter_list:
if key_value_pair[1] > last_highest_freq:
last_highest_freq = key_value_pair[1]
highest_freq_element = key_value_pair[0]
return highest_freq_element
#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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment