我想知道列表m
中的哪些项目完全由列表w
的项目组成。
如果我将它们添加到集合中并进行拦截,嵌入式结构将变得不可见,这正是我想要避免的。
案例:
w= [
['sta'],
['co', 'si'],
['non'],
['si'],
['puo'],
['ap', 'ri', 're'],
['ve', 'dia', 'mo'],
['co', 'sa'],
['ci'],
['pot', 'reb', 'be']
]
m=[
['sta', 'co'],
['puo', 'ap', 'ri', 're'],
['ve'],
['dia', 'mo'],
['co'],
['sa'],
['ci', 'pot', 'reb', 'be']
]
期望的输出:
[['puo', 'ap', 'ri', 're'], ['ci', 'pot', 'reb', 'be']]
(例如来自['puo', 'ap', 'ri', 're']
的{{1}}由m
w
}中的两项组成。
谢谢大家!
答案 0 :(得分:2)
列表“list”的每个元素“elem”的算法递归检查if(列表elem [1:]和列表elem [:1])或(列表elem [2:]和elem [: 2])或......由列表w中包含的元素组成。 我还使用地图“memory”来使用memoization技术优化算法。
def listInList(a, list, memory):
if not list:
return False
elif str(list) in memory:
return memory[str(list)]
else:
if list in a:
memory[str(list)] = True
return True
else:
for i in range(1,len(list)):
if listInList(a, list[i:], memory) and listInList(a, list[:i], memory):
memory[str(list)] = True
return True
memory[str(list)] = False
return False
def check(a, b):
res = []
for elem in b:
if listInList(a, elem, {}):
res += [elem]
return res
w= [
['sta'],
['co', 'si'],
['non'],
['si'],
['puo'],
['ap', 'ri', 're'],
['ve', 'dia', 'mo'],
['co', 'sa'],
['ci'],
['pot', 'reb', 'be']
]
m=[
['sta', 'co'],
['puo', 'ap', 'ri', 're'],
['ve'],
['dia', 'mo'],
['co'],
['sa'],
['ci', 'pot', 'reb', 'be']
]
print check(w,m)
输出:
[['puo', 'ap', 'ri', 're'], ['ci', 'pot', 'reb', 'be']]