![](/img/trans.png)
[英]python string format with negative sign for negative number, but space for positive number
[英]python positive and negative number list possibilities
我正在嘗試在Python中創建一個函數,它將整數列表作為輸入,並返回一個包含這些數字的所有正面和負面可能性的更大列表。
假裝'+'是正數,' - '是負數
輸出應符合:
foo([-4])
>>> [ [4], [-4] ]
foo([+, +])
>>> [ [+,+], [+,-], [-,+], [-,-] ]
foo([-, +])
>>> [ [+,+], [+,-], [-,+], [-,-] ]
foo([-1, 3])
>>> [ [1,3], [1,-3], [-1,3], [-1,-3] ]
foo( [+,-,+] )
>>> [ [-,-,-],[+,-,-],[-,+,-],[-,-,+],[+,+,-],[+,-,+],[-,+,+],[+,+,+] ]
對於只是數字,您可以在生成包含正數和負數的列表后使用itertools.product
創建所有組合:
from itertools import product
def foo(nums):
return list(product(*((x, -x) for x in nums)))
演示:
>>> 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)]
list(itertools.product(*([x, -x] for x in input)))
您希望以一種可能的方式為輸入中的每個數字選擇數字或其負數。 對於輸入中的每個x[i]
,這是{x[i], -x[i]}
的笛卡爾積 。 itertools.product
可以為您做到這一點,然后list
列出所有輸出。
你可以使用itetools.product
,根據輸入列表的長度找到[1, -1]
的笛卡爾積,然后將它們與輸入列表中的項一起多個。
>>> 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]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.