Finding longest run in a list

  • A+
Category:Languages

Given a list of data, I'm trying to create a new list in which the value at position i is the length of the longest run starting from position i in the original list. For instance, given

x_list = [1, 1, 2, 3, 3, 3] 

Should return:

run_list = [2, 1, 1, 3, 2, 1] 

My solution:

freq_list = [] current = x_list[0] count = 0 for num in x_list:     if num == current:         count += 1     else:         freq_list.append((current,count))         current = num         count = 1 freq_list.append((current,count))  run_list = [] for i in freq_list:     z = i[1]     while z > 0:         run_list.append(z)         z -= 1  

Firstly I create a list freq_list of tuples, where every tuple's first element is the element from x_list, and where the second element is the number of the total run.

In this case:

freq_list = [(1, 2), (2, 1), (3, 3)] 

Having this, I create a new list and append appropriate values.

However, I was wondering if there is a shorter way/another way to do this?


Here's a simple solution that iterates over the list backwards and increments a counter each time a number is repeated:

last_num = None result = [] for num in reversed(x_list):     if num != last_num:         # if the number changed, reset the counter to 1         counter = 1         last_num = num     else:         # if the number is the same, increment the counter         counter += 1      result.append(counter)  # reverse the result result = list(reversed(result)) 

Result:

[2, 1, 1, 3, 2, 1] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: