算法py 数字排列可能性

python

输入一个n长度, 代表n个位置,每个位置有3种可能, 求出所有排序方式。求解

例如:n = 2

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

额,不是有自带的排列组合模块吗。。。

from itertools import product
n = int(input())
for i in product([1,2,3], repeat=n):
    print(*i)

当n=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

自带不香吗

import itertools
n = int(input("n="))
res = list(itertools.product([1,2,3], repeat=2))
print(res)


或者实现类似自带的功能

def Permutations(*args, **kwds):
    def wrapper(values, L):
        for i in L:
            for current in values:
                yield i + (current,)
    res = (),
    for level in tuple(map(tuple, args)) * kwds.get('repeat', 1):
        res = wrapper(level, res)  # build stack of iterators
    return res

p = list(Permutations([1,2,3], repeat=2))
print(p)

思路主要就是借助itertools模块的一些用法,具体编程如下:

import itertools

n = int(input())
paths = list(itertools.product([1,2,3], repeat=n))
print(paths)

测试结果:

img

如有帮助,还请采纳!谢谢!

典型的排列呀,参考以下我以前写的这个:

#法一:遍历全部可能,把有重复的剃掉。
total = 0
num_list = [1,2,3,4]
for i in num_list:
    for j in num_list:
        for k in num_list:
            if (i!=j) and (i!=k) and (j!=k):
                print(i,j,k)
                total += 1
print(total)

#法二:⽤itertools中的permutations(表示排列)即可。
import itertools
total = 0
num_list = [1,2,3,4]
for i in itertools.permutations(num_list,3):
    print(i[0],i[1],i[2])
    total = total+1
print(total)
import itertools
n = int(input("n="))
print(list(itertools.product([1,2,3], repeat=2)))

建议用自带的itertools,简单实用,代码上面大同小异,有了就不写了