Does Python find a duplicate sequence in a list of integers?

I have a list of lists, and each list has a repeating sequence. I am trying to count the length of a repeating sequence of integers in a list:

list_a = [111,0,3,1,111,0,3,1,111,0,3,1] list_b = [67,4,67,4,67,4,67,4,2,9,0] list_c = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,23,18,10] 

What will be returned:

 list_a count = 4 (for [111,0,3,1]) list_b count = 2 (for [67,4]) list_c count = 10 (for [1,2,3,4,5,6,7,8,9,0]) 

Any advice or advice would be welcome. I am trying to work with re.compile right now, but, this is not entirely correct.

+4
source share
2 answers

Guess the length of the sequence, iterating through guesses between 2 and half the length of the sequence. If no pattern is found, return 1 by default.

 def guess_seq_len(seq): guess = 1 max_len = len(seq) / 2 for x in range(2, max_len): if seq[0:x] == seq[x:2*x] : return x return guess list_a = [111,0,3,1,111,0,3,1,111,0,3,1] list_b = [67,4,67,4,67,4,67,4,2,9,0] list_c = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,23,18,10] print guess_seq_len(list_a) print guess_seq_len(list_b) print guess_seq_len(list_c) print guess_seq_len(range(500)) # test of no repetition 

This gives (as expected):

 4 2 10 1 

As requested, this alternative gives the longest repeating sequence. Therefore, it will return 4 for list_b. The only change: guess = x instead of return x

 def guess_seq_len(seq): guess = 1 max_len = len(seq) / 2 for x in range(2, max_len): if seq[0:x] == seq[x:2*x] : guess = x return guess 
+9
source

It worked for me.

 def repeated(L): '''Reduce the input list to a list of all repeated integers in the list.''' return [item for item in list(set(L)) if L.count(item) > 1] def print_result(L, name): '''Print the output for one list.''' output = repeated(L) print '%s count = %i (for %s)' % (name, len(output), output) list_a = [111, 0, 3, 1, 111, 0, 3, 1, 111, 0, 3, 1] list_b = [67, 4, 67, 4, 67, 4, 67, 4, 2, 9, 0] list_c = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 23, 18, 10 ] print_result(list_a, 'list_a') print_result(list_b, 'list_b') print_result(list_c, 'list_c') 

The Python function set() converts a list into a set, a data type that can contain only one of any given value, like a set in algebra. I converted the input list to a set, and then returned to the list, reducing the list to its unique values. Then I checked the source list for each of these values ​​to see if it contains this value more than once. I returned a list of all duplicates. The rest of the code is for demo purposes only to show that it works.

Edit: syntax highlighting did not like the apostrophe in my docstory.

-1
source

All Articles