4
votes

I'm trying to make a function in Python that takes a list of integers as input and returns a greater list containing all positive and negative possibilities of those numbers.

Pretend '+' is a positive number and '-' is a negative number

The output should match up with:

foo([-4])
>>> [ [4], [-4] ]

foo([+, +])
>>> [ [+,+], [+,-], [-,+], [-,-] ]

foo([-, +])
>>> [ [+,+], [+,-], [-,+], [-,-] ]

foo([-1, 3])
>>> [ [1,3], [1,-3], [-1,3], [-1,-3] ]

foo( [+,-,+] )
>>> [ [-,-,-],[+,-,-],[-,+,-],[-,-,+],[+,+,-],[+,-,+],[-,+,+],[+,+,+] ]
3
@MartijnPieters I think he's using + and - as an informal stand in for actual positive and negative numbers. - Brionius
Is the order of the output list important? - Brionius

3 Answers

10
votes

For just numbers, you can use itertools.product to create all combos, after generating a list with both positive and negative numbers:

from itertools import product

def foo(nums):
    return list(product(*((x, -x) for x in nums)))

Demo:

>>> foo([-4])
[(4,), (-4,)]
>>> foo([-1, 3])
[(1, 3), (1, -3), (-1, 3), (-1, -3)]
>>> foo([1, 3])
[(1, 3), (1, -3), (-1, 3), (-1, -3)]
>>> foo([1, -3, 4])
[(1, 3, 4), (1, 3, -4), (1, -3, 4), (1, -3, -4), (-1, 3, 4), (-1, 3, -4), (-1, -3, 4), (-1, -3, -4)]
6
votes
list(itertools.product(*([x, -x] for x in input)))

You want every possible way to pick either a number or its negative, for each number in the input. That's the Cartesian product of {x[i], -x[i]} for each x[i] in the input. itertools.product can do that for you, and then list makes a list of all the output.

0
votes

You can use itetools.product, find the cartesian product of [1, -1] depending on the length of the input list and then multiple them with the items in the input list.

>>> from operator import mul
>>> from itertools import product
def solve(lis):
    for prod in product([-1, 1], repeat=len(lis)):
        yield [mul(*x) for x in  zip(prod, lis)]
...         
>>> list(solve([-4]))
[[4], [-4]]
>>> list(solve([-1, 3]))
[[1, -3], [1, 3], [-1, -3], [-1, 3]]