python算法习题(一): 排列组合

版权声明:本文为博主原创文章,欢迎转载,但请注明原文出处。 https://blog.csdn.net/GiveMeFive_Y/article/details/79745723

排列组合的常见算法应该是枚举,但是对于长度较长的集合并不适用。网上也有用递归实现的方式,暂时不做介绍。这里想法是位置交换。

def permutation(inpt):
    length = len(inpt)
    tmp = inpt.copy()
    while True:
        for i in range(0, length-1):
            tmp[i], tmp[i+1] = tmp[i+1], tmp[i]
            yield tmp
        if tmp == inpt:
            break

for i in permutation([1,2,3]):
    print(i)

当然万能的python已经有模块可以实现:

import itertools

list(itertools.permutations([1,2,3,4]))

猜你喜欢

转载自blog.csdn.net/GiveMeFive_Y/article/details/79745723