How to find which items in list of lists is equal to another list

若如初见. 提交于 2021-01-29 02:19:16

问题


I have a list of lists that looks like this:

[[0],
[0, 1, 2],
[2],
[3],
[4],
[5],
[0, 1, 2, 3, 4, 5, 6, 7],
[7],
[8],
[9],
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
[11],
[11, 12, 13, 14, 15, 16, 17, 18],
[13],
[14],
[14, 15, 16, 17, 18],
[16, 17, 18],
[17],
[17, 18]]

I am trying to find the least number of items in the list, when concatenated, that equal the full range of the list. In this case, the full range of the list is this:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

So in this case, these two items from the list of lists would equal the full range:

[0]
[0, 1, 2]
[2]
[3]
[4]
[5]
---> [0, 1, 2, 3, 4, 5, 6, 7]
[7]
[8]
[9]
---> [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
[11]
[11, 12, 13, 14, 15, 16, 17, 18]
[13]
[14]
[14, 15, 16, 17, 18]
[16, 17, 18]
[17]
[17, 18]

回答1:


One way using itertools.permutations and chain:

from itertools import permutations, chain

starget = sorted(target)
for i in range(2, len(target)):
    for perm in permutations(l, i):
        if sorted(chain(*perm)) == starget:
            print(i, perm)
            break
    break

Output:

2 ([0, 1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18])


来源:https://stackoverflow.com/questions/62765897/how-to-find-which-items-in-list-of-lists-is-equal-to-another-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!