Python 如何使这段代码在时间上更加优化?
我已经在这里写了一段代码,但是它需要很多时间。我需要进一步优化它。这里的k值不同,可以是2、3或4,具体取决于用户。请帮帮我Python 如何使这段代码在时间上更加优化?,python,time-complexity,combinations,itertools,Python,Time Complexity,Combinations,Itertools,我已经在这里写了一段代码,但是它需要很多时间。我需要进一步优化它。这里的k值不同,可以是2、3或4,具体取决于用户。请帮帮我 from itertools import combinations def get_all_combinations(input_list, k): for item in combinations(input_list, k): yield list(set(list(item))) input_list = [1, 2, 1, 2, 3]
from itertools import combinations
def get_all_combinations(input_list, k):
for item in combinations(input_list, k):
yield list(set(list(item)))
input_list = [1, 2, 1, 2, 3]
k = 3
lst = []
for i in range(1, k + 1):
for item in get_all_combinations(input_list, i):
if len(item) > i - 1:
lst.append(item)
print(len(lst))
>>17
#[[1], [2], [1], [2], [3], [1, 2], [1, 2], [1, 3], [1, 2], [2, 3], [1, 2], [1, 3], [2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
测试这一点:
from itertools import combinations
def get_all_combinations(input_list,k):
l = []
for item in combinations(input_list, k):
l.append( list(set(list(item))))
return l
input_list = [1, 2, 1, 2, 3]
k = 3
lst = []
for i in range(1,k+1):
gac = []
gac = get_all_combinations(input_list, i)
for item in gac:
if len(item) > i-1:
lst.append(item)
print(len(lst))
根据使用以下版本,您的处理速度将几乎是的两倍:
from itertools import combinations
def get_all_combinations(input_list, k):
for i in range(1, k + 1):
for item in combinations(input_list, i):
s = set(item)
if len(s) >= i:
yield list(s)
input_list = [1, 2, 1, 2, 3]
k = 3
lst = list(get_all_combinations(input_list, k))
print(lst)
输出保持不变:
[[1], [2], [1], [2], [3], [1, 2], [1, 2], [1, 3], [1, 2], [2, 3], [1, 2], [1, 3], [2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
试试这个:
>>输入列表=[1,2,1,2,3]
>>>k=3
>>>[itertools中el的(1,k+1)范围内的i的列表(集合(el))。如果len(集合(el))>i-1,则组合(输入列表,i)]
[[1], [2], [1], [2], [3], [1, 2], [1, 2], [1, 3], [1, 2], [2, 3], [1, 2], [1, 3], [2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
如果这是作业,您的讲师可能正在寻找
lst = [list(c) for i in range(k) for c in combinations(input_list, i+1) if len(set(c)) > i]
根据OP的逻辑-每个项目都需要一个集合我很抱歉浪费你的时间。。。但我在查询代码中编辑了一个小东西。。。你能调查一下并帮我优化解决方案吗。。。谢谢你@GrzegorzSkibinskiI抱歉@RomanPerekhrest,浪费你的时间。。。但我在查询代码中编辑了一个小东西。。。你能调查一下并帮我优化解决方案吗。。。感谢You@Remus,我的方法仍然相关-为什么不使用它?问题是什么?我的意思是我现在可以打印len(lst),但我认为在列表中获取序列是在某种程度上使用时间,这可能与O(n)有关。。。我们能不能用更多的语言,比如说数数之类的?…@Remus,基本条件已经涵盖并有了答案。对于新的情况-创造新的问题我会记住。。。非常感谢你的帮助我很抱歉浪费了你的时间。。。但我在查询代码中编辑了一个小东西。。。你能调查一下并帮我优化解决方案吗。。。多谢各位@ShahabRahnama@Remus试试看!