python positive and negative number list possibilities

匿名 (未验证) 提交于 2019-12-03 01:34:02

问题:

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( [+,-,+] ) >>> [ [-,-,-],[+,-,-],[-,+,-],[-,-,+],[+,+,-],[+,-,+],[-,+,+],[+,+,+] ] 

回答1:

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


回答2:

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.



回答3:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!