Reputation: 35
I need to find a way (in python) to produce all permutations of integers of (+1)s and (-1)s according to given x legnth. For example if x=1, it should be [(+1),(-1)]; x = 2 -->[[(+1)(+1)],[(+1)(-1)],[(-1)(+1)],[(-1)(-1)]] and so on.
Actually, itertools.product() function does this work for string permutations. This is what I can do:
import itertools
def binary_sequence(k):
L1 = [''.join(x) for x in itertools.product('+-', repeat=k)]
L2 = list()
for i in L1:
L2.append([i])
L2 = np.array(L2)
return (L2)
However, I found no way to assign integers to strings afterwards. Is that possible to do this for integers using itertools or something else?
Upvotes: 0
Views: 59
Reputation: 18628
You can really do string permutions :
In [338]: list(itertools.product(["-1","+1"],repeat=3))
Out[338]:
[('-1', '-1', '-1'),
('-1', '-1', '+1'),
('-1', '+1', '-1'),
('-1', '+1', '+1'),
('+1', '-1', '-1'),
('+1', '-1', '+1'),
('+1', '+1', '-1'),
('+1', '+1', '+1')]
Upvotes: 1
Reputation: 61910
If I understood correctly you could do:
import itertools
import numpy as np
def binary_sequence(k):
return np.array([x for x in itertools.product([-1, 1], repeat=k)])
for seq in binary_sequence(2):
print(seq)
Output
[-1 -1]
[-1 1]
[ 1 -1]
[1 1]
The product function receives an iterable, from the documentation:
Cartesian product of input iterables.
Upvotes: 1