Home > other >  Check negative duplicates inside a tuple
Check negative duplicates inside a tuple

Time:02-06

I'm new to python and I've written this extremely unoptimized code for returning all permutations ranging from -(number) to (number) excluding zero. The problem is, the result contains entries such as (-2,2) which I do not want. The returning tuple should not contain the same number positive and negative. The code below works by adding both the values and checking if its equal to zero, but it gets complicated with input numbers (num value) greater than 2. And also, as you can probably tell the code is extremely unoptimized (takes ~10mins for num=6) how can I make it more optimized? Thanks!

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))

CodePudding user response:

A somewhat efficient solution is to simply start with a list of numbers from 1 to n inclusive, then generate all combinations of positive/negative terms, then permute each combination.

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)

Output

(1, 2)
(2, 1)
(1, -2)
(-2, 1)
(-1, 2)
(2, -1)
(-1, -2)
(-2, -1)
  •  Tags:  
  • Related