【问题标题】:Check negative duplicates inside a tuple检查元组内的负重复项
【发布时间】:2022-02-05 04:05:13
【问题描述】:

我是 python 新手,我编写了这个非常未优化的代码,用于返回从 -(number) 到 (number) 的所有排列,不包括零。问题是,结果包含我不想要的条目,例如 (-2,2)。返回的元组不应包含相同的正数和负数。下面的代码通过将两个值相加并检查其是否等于 0 来工作,但是输入数字(num 值)大于 2 时会变得复杂。而且,正如您可能会说的那样,代码非常未优化(大约需要 10 分钟) num=6) 我怎样才能使它更优化?谢谢!

from itertools import permutations
num = 2
result = []
l = []
stuff = [i for i in range(-num,num+1)]
for i in range(0, len(stuff)+1):
        for subset in permutations(stuff, i):
            if 0 not in subset:
                if len(subset)==num:
                    if sum(subset[:]) != 0:
                        with open('geneorder.txt','a') as txt_file:
                            txt_file.write('\n'+str(subset).replace('(','').replace(')','').replace(', ',' '))
                        result.append(subset)
print(result)
print(len(result))

【问题讨论】:

  • 你能分享一个输入和预期输出的例子吗?很难理解您要做什么
  • 并且还解释了n = 3不需要的排列部分
  • 什么排列?
  • 您是否有理由附加到文件而不是在循环之前打开文件一次然后在循环中写入?注意:在 Windows 上循环打开/附加/关闭文本文件比打开文件/循环写入/关闭文件慢,例如Append I/O Performance on Windows

标签: python list optimization tuples permutation


【解决方案1】:

一个比较有效的解决方案是简单地从1n 的数字列表开始,然后生成正/负项的所有组合,然后置换每个组合。

from itertools import permutations
def generate_positive_negatives(num):
    def collect(curr, idx, results):
        if idx == len(curr):
            results.append(curr.copy())
            return

        collect(curr, idx + 1, results)
        # toggle, recurse, backtrack
        curr[idx] *= -1
        collect(curr, idx + 1, results)
        curr[idx] *= -1
        results

    results = []
    curr = list(range(1, num + 1))
    collect(curr, 0, results)
    return list(tuple(choice) for combo in results for choice in permutations(combo))

for perm in generate_positive_negatives(2):
    print(perm)

输出

(1, 2)
(2, 1)
(1, -2)
(-2, 1)
(-1, 2)
(2, -1)
(-1, -2)
(-2, -1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 2021-08-07
    • 2020-11-21
    • 1970-01-01
    • 2018-09-17
    相关资源
    最近更新 更多