I am trying to trace to what extent is listA, listB, listC… similar to the original list. How do I print the number of elements that occur in the same sequence
in listA
as they occur in the original list?
JavaScript
x
16
16
1
original_list = ['I', 'live', 'in', 'space', 'with', 'my', 'dog']
2
3
listA = ['my', 'name', 'my', 'dog', 'is', 'two', 'years', 'old']
4
5
listB = ['how', 'where', 'I', 'live', 'in', 'space', 'with']
6
7
listC = ['I', 'live', 'to', 'the' 'in', 'space', 'with', 'my', 'football', 'my','dog']
8
9
Output:
10
listA: Count = 2 #'my', 'dog'
11
12
listB: Count = 5 #'I', 'live', 'in', 'space', 'with'
13
14
listC: Count = 2,4,2 #'I', 'live'
15
#'in', 'space', 'with', 'my'
16
#'my', 'dog'
Advertisement
Answer
I wrote a function that does the job I think. It might be a bit too complex, but I can’t see an easier way at the moment:
JavaScript
1
45
45
1
original = ['I', 'live', 'in', 'space', 'with', 'my', 'dog']
2
3
listA = ['my', 'name', 'my', 'dog', 'is', 'two', 'years', 'old']
4
listB = ['how', 'where', 'I', 'live', 'in', 'space', 'with']
5
listC = ['I', 'live', 'to', 'the', 'in', 'space', 'with', 'my', 'football', 'my', 'dog']
6
7
8
def get_sequence_lengths(original_list, comparative_list):
9
10
original_options = []
11
for i in range(len(original_list)):
12
for j in range(i + 1, len(original_list)):
13
original_options.append(original_list[i:j + 1])
14
15
comparative_options = []
16
for i in range(len(comparative_list)):
17
for j in range(i+1, len(comparative_list)):
18
comparative_options.append(comparative_list[i:j+1])
19
comparative_options.sort(key=len, reverse=True)
20
21
matches = []
22
while comparative_options:
23
for option in comparative_options:
24
if option in original_options:
25
matches.append(option)
26
new_comparative_options = comparative_options.copy()
27
for l in comparative_options:
28
counter = 0
29
for v in option:
30
counter = counter + 1 if v in l else 0
31
if counter == len(l):
32
new_comparative_options.remove(l)
33
break
34
comparative_options = new_comparative_options
35
break
36
if option == comparative_options[-1]:
37
break
38
39
matches = [option for option in original_options if option in matches]
40
lengths = [len(option) for option in matches]
41
print(lengths)
42
print(matches)
43
44
return lengths
45
If you call it with the original list and example lists, it prints the following.
get_sequence_lengths(original, listA)
prints [2] [['my', 'dog']]
.
get_sequence_lengths(original, listB)
prints [5] [['I', 'live', 'in', 'space', 'with']]
.
get_sequence_lengths(original, listC)
prints [2, 4, 2] [['I', 'live'], ['in', 'space', 'with', 'my'], ['my', 'dog']]
.