Reputation: 156
I have to do an exercise that ask me to do a function that find the frequency of consecutive values on a list and return a list of tuples where I have to show how many times it was the repetition.
Input:
[1, 1, 1, 3, 5, 1, 1, 3, 3]
Output:
[(1,3) , (3,1) , (5,1) , (1,2) , (3,2)]
Code:
def empaquetar(l):
lista = []
for i in range(len(l)-1):
cont = 0
j = i + 1
while l[i] == l[j] and j<len(l)-1:
cont += 1
i += 1
j += 1
if cont > 0:
lista.append((l[i], cont + 1))
else:
lista.append((l[i],1))
return lista
Well, what I wrote does not quite exactly return what I want and I can't find a solution but I search a lot, for example the tool Counter from collection or something like. I need help, any suggestion?
Upvotes: 1
Views: 69
Reputation: 1538
Use a second for loop to check how many times the number is there consecutively.
def empaquetar(l):
lista = []
for i in l:
cont = 1
for j in range(i+1, len(l)):
If l[j]==i:
cont += 1
else:
break
lista.append((i, cont))
return lista
Upvotes: 1
Reputation: 1925
I have developed an algorithm with a time complexity of O(n)
for this.
def consecutive(lst):
lst.append(0)
count = 1
result = []
for i, value in enumerate(lst):
if value == lst[min(len(lst) - 1, i + 1)]:
count += 1
else:
result.append((value, count))
count = 1
return result
Let's try a few test cases for this function.
>>> lst = [1, 1, 1, 3, 5, 1, 1, 3, 3]
>>> consecutive(lst)
[(1, 3), (3, 1), (5, 1), (1, 2), (3, 2)]
Here is another test case to verify the code.
>>> lst = [1, 2, 5, 5, 3, 2, 2, 1]
>>> consecutive(lst)
[(1, 1), (2, 1), (5, 2), (3, 1), (2, 2), (1, 1)]
Upvotes: 1
Reputation: 2727
from itertools import groupby
lista = [group[0], len(list(group[1])) for group in groupby(l)]
Upvotes: 1
Reputation: 255
Not thoroughly tested, but here is a try
prev_val = None
counter = 1
for curr_val in input_list:
if prev_val is not None:
if prev_val != curr_val:
output_list.append((prev_val, counter))
counter = 1
else:
counter += 1
prev_val = curr_val
output_list.append((prev_val, counter))
print (output_list)
Upvotes: 1