-1

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.

0

2 Answers 2

6

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),
 ...
Sign up to request clarification or add additional context in comments.

1 Comment

So clean and simple!
2

I think you want itertools.product(), which does all possible combinations of the iterable elements. itertools.permutations() does not repeat elements, and itertools.combinations() or itertools.combinations_with_replacement() only goes in sorted order (e.g. the first element of the input iterable won't be the last element of the result).

from itertools import product

def generate(q):
    assert q > 0  # not defined for <= 0
    return list(product(range(1,q+1), repeat=q))

generate(3)  # [(1,1,1), (1,1,2), ..., (3,3,2), (3,3,3)]

See: https://docs.python.org/3/library/itertools.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.