简体   繁体   English

根据列表列表检查列表中组合的存在

[英]Checking existence of combination in a list against a list of lists

If i have a list of list of integers S: [[1,2,3],[3,4,5],[5,6,7]] , and a single list T: [2,3,1] . 如果我有一个整数列表S: [[1,2,3],[3,4,5],[5,6,7]]的列表S: [[1,2,3],[3,4,5],[5,6,7]]和一个列表T: [2,3,1] I want to return true if T as a combination is contained in S. Assuming each element of S has same length as that of T . 如果S中包含T作为组合,我想返回true。假设S每个元素的长度与T长度相同。

In this case, I want to return true. 在这种情况下,我想返回true。

Restrictions: No sorting of any kind, and note S has all unique lists, but within a list, it can have duplicate elements. 限制:不能进行任何排序,并且音符S具有所有唯一列表,但是在列表内,它可以具有重复的元素。

How can I do this as efficiently as possible. 我如何才能尽可能有效地做到这一点。 I can iterate through each element of S and turn it into a set and compare it with set(T) , but that seems very slow if size of S and length of each element of S gets bigger. 我可以通过的每个元素迭代S ,把它变成一组,并将其与比较set(T)但似乎如果大小非常缓慢S的每一个元素和长度S变大。

Using itertools? 使用itertools?

from itertools import combinations
for i in combinations(t, len(t)): if i in s: return True;

Or using sorted: 或使用排序:

t = sorted(t)
for i in s: if sorted(i)==t: return True

You can use sorted : 您可以使用sorted

>>> S = [[1,2,3],[3,4,5],[5,6,7]]
>>> T = [2,3,1]
>>> any(sorted(T) == sorted(x) for x in S)
True

Collections and counter? 收款柜台? It'll run in O(n), whereas sorting will run in roughly O(n log n), and raw comparison will be O(n²) 它以O(n)运行,而排序将以O(n log n)进行,原始比较将为O(n²)

import collections
T = collections.Counter([2,3,1])
any(T == collections.Counter(x) for x in S)

If a stipulation is without sorting, you might want to look into an order-independent hash function for the combinations. 如果规定没有排序,则可能需要查看组合的与顺序无关的哈希函数。 Two starting points I liked were (1) the sum of the hashes of the individual elements of the combination, and (2) a tuple (sum(combination), product(combination)) . 我喜欢的两个起点是(1)组合中各个元素的哈希值之和,和(2)一个元组(sum(combination), product(combination))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM