在列表中查找公共子序列
假设我有两个列表,比如:
list1 = ['cat', 'sat', 'on', 'mat', 'xx', 'yy'] ,
list2 = ['cow', 'sat', 'on', 'carpet', 'xx', 'yy']
我会遍历这两个列表:当我看到两个元素匹配时,就开始计数。当我看到一对不匹配的元素时,就停止当前的计数,然后开始新的计数。
(sat, sat) I = 1
(on, on) I = 2
(mat, carpet) J = 1
(xx, xx) k = 1
(yy, yy) k = 2
i = 0
for x in list1:
for y in list2:
if x == y:
print (x, y)
i += 1
else:
j = 0
j += 1
print (x, y)
2 个回答
0
关于以下内容:
def doit(list1, list2):
lastmatch = -1
lastunmatch = -1
for i, x in enumerate(zip(list1, list2)):
if x[0] == x[1]:
lastmatch = i
else:
lastunmatch = i
print abs(lastmatch - lastunmatch)
0
在编程中,有时候我们需要处理一些数据,而这些数据可能会有很多不同的格式。比如说,我们可能会从一个文件里读取数据,或者从网络上获取信息。这些数据在使用之前,往往需要进行一些处理,才能变得更好用。
处理数据的过程就像是把原材料变成成品。我们需要先了解这些原材料是什么样的,然后才能决定怎么加工它们。比如,如果你有一堆数字,你可能需要把它们排序,或者计算它们的平均值。
在这个过程中,编程语言提供了很多工具和方法,帮助我们更方便地处理数据。就像厨房里的刀具和锅具,使用得当可以让我们做出美味的菜肴。
总之,处理数据是编程中非常重要的一部分,掌握了这项技能,你就能更好地利用各种信息,做出更有价值的应用。
>>> from collections import defaultdict
>>>
>>> list1 = ['cat', 'sat', 'on', 'mat', 'xx', 'yy']
>>> list2 = ['cow', 'sat', 'on', 'carpet', 'xx', 'yy']
>>>
>>> var_it = iter('IJKLMNOPQRSTUVWXYZ') # variable candidates
>>> counters = defaultdict(int)
>>> c = next(var_it)
>>> for word1, word2 in zip(list1, list2):
... if word1 == word2:
... counters[c] += 1
... else:
... if counters: # Prevent counting until first match
... counters[next(var_it)] = 1
... c = next(var_it)
...
>>> for var in sorted(counters):
... print('{}: {}'.format(var, counters[var]))
...
I: 2
J: 1
K: 2