[英]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]. 例如,如果q = 2,则我必须生成[1,1]到[2,2]之间的所有序列。 if q = 3, then generate sequence between [1,1,1] to [3,3,3]. 如果q = 3,则生成[1,1,1]至[3,3,3]之间的序列。 for q = 4, then generate sequence between [1,1,1,1] to [4,4,4,4], etc.. 对于q = 4,则生成[1,1,1,1]至[4,4,4,4]等之间的序列。
example of sequence . 序列的例子。 for q = 3 对于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. 我已经尝试过“ Python生成所有不递减的序列 ”,但没有获得所需的输出。
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: 使用带有重复参数的itertools.product:
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),
...
I think you want itertools.product()
, which does all possible combinations of the iterable elements. 我认为您需要itertools.product()
,它可以对可迭代元素进行所有可能的组合。 itertools.permutations()
does not repeat elements, and itertools.combinations()
or itertools.combinations_with_replacement()
only goes in sorted order (eg the first element of the input iterable won't be the last element of the result). itertools.permutations()
不会重复元素,并且itertools.combinations()
或itertools.combinations_with_replacement()
仅按排序顺序进行(例如,输入iterable的第一个元素将不是结果的最后一个元素)。
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 参见: https : //docs.python.org/3/library/itertools.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.