-
Notifications
You must be signed in to change notification settings - Fork 0
/
L27Q6_LongestRepitition.py
38 lines (31 loc) · 1015 Bytes
/
L27Q6_LongestRepitition.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 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):
bestElement = None
current = None
length = 0
current_length = 0
for element in input_list:
if current != element:
current = element
current_length = 1
else:
current_length += 1
if current_length > length:
bestElement = current
length = current_length
return bestElement
#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