检查元组内的负重复项

Check negative duplicates inside a tuple

我是 python 的新手,我编写了这段极度未优化的代码,用于返回从 -(number) 到 (number) 的所有排列,不包括零。问题是,结果包含我不想要的条目,例如 (-2,2)。返回的元组不应包含相同的正数和负数。下面的代码通过将两个值相加并检查它是否等于零来工作,但是当输入数字(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))

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

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)