Atul - 1 year ago 85
Python Question

# How to generate this sequence using python

For example if q = 2, then i have to generate all sequence between [1,1] to [2,2].
if q = 3, then generate sequence between [1,1,1] to [3,3,3]. for q = 4, then generate sequence between [1,1,1,1] to [4,4,4,4], etc..

example of sequence .
for q = 3

``````(1, 1, 1)
(1, 1, 2)
(1, 1, 3)
(1, 2, 1)
(1, 2, 2)
(1, 2, 3)
(1, 3, 1)
(1, 3, 2)
(1, 3, 3)
(2, 1, 1)
(2, 1, 2)
(2, 1, 3)
(2, 2, 1)
(2, 2, 2)
(2, 2, 3)
(2, 3, 1)
(2, 3, 2)
(2, 3, 3)
(3, 1, 1)
(3, 1, 2)
(3, 1, 3)
(3, 2, 1)
(3, 2, 2)
(3, 2, 3)
(3, 3, 1)
(3, 3, 2)
(3, 3, 3)
``````

i have tried this "Python generating all nondecreasing sequences" but not getting the required output.

currently i am using this code,

``````import itertools

def generate(q):
k = range(1, q+1) * q
ola = set(i for i in itertools.permutations(k, q))
for i in sorted(ola):
print i

generate(3)
``````

i need another and good way to generate this sequence.

Use itertools.product with the repeat parameter:

``````q = 2
list(itertools.product(range(1, q + 1), repeat=q))
Out: [(1, 1), (1, 2), (2, 1), (2, 2)]

q = 3

list(itertools.product(range(1, q + 1), repeat=q))
Out:
[(1, 1, 1),
(1, 1, 2),
(1, 1, 3),
(1, 2, 1),
(1, 2, 2),
...
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download