Python生成n个元素的全排列

本文将使用Python语言编写程序生成n个元素的全排列,代码不使用第三方库;

生成全排列

def permute(nums):

    length = len(nums)

    permutations = []

    def _permute(index=0):

        if index == length:
            permutations.append(nums[0:length])
        
        for i in range(index,length):
            nums[i],nums[index] = nums[index],nums[i]
            _permute(index+1)
            nums[i],nums[index] = nums[index],nums[i]
            
    _permute()

    return permutations

nums = [i for i in range(1,4)] #[1,2,3]

print("Input:\n",nums)
P = permute(nums)
print("Permutations:")
for p in P:
    print(p)

运行效果

Input:
 [1, 2, 3]
Permutations:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]

原创内容,如需转载,请注明出处;

本文地址: https://www.perfcode.com/p/python-generate-full-permutation.html

分类: 计算机技术
推荐阅读:
Windows和Linux系统启用IP转发 在Windows系统下启用IP转发,需要通过修改注册表来实现;Linux系统只需将系统下的/proc/sys/net/ipv4/ip_forward文件值修改为1;
Python list()函数 在Python中,list()函数用于将一个可迭代对象(如字符串、元组、字典、集合、生成器等)转换为列表。如果不传入任何参数,list()函数会创建一个空列表。
C语言生成范围内的随机数 给定一个范围,当前时间做为随机种子,使用C语言生成范围内的随机数;
OpenSSL1.x和OpenSSL3.x的区别 OpenSSL 1.x和OpenSSL 3.x是两个不同版本的OpenSSL库,其中有很多重要的区别:
TypeError: __format__ must return a str, not NoneType 在 Python 中,如__format__()方法必须返回一个字符串,否则将触发类似TypeError: __format__ must return a str, not NoneType的错误;
C语言memcpy()函数:复制内存中的内容 memcpy()是C语言标准库中的一个函数,用于将一段内存的内容复制到另一段内存中;