繁体   English   中英

不使用 itertools 的不重复排列

[英]Permutations without repetition without using itertools

我需要在蛮力算法中获得长度为n的迭代的所有排列。 我不想使用itertools或任何其他外部包。

我想我可以使用堆算法,但我的代码只返回一个重复 n: 次的排列:

def permutations(l):
    n = len(l)
    result = []
    c = n * [0]
    result.append(l)
    i = 0;
    while i < n:
        if c[i] < i:
            if i % 2 == 0:
                tmp = l[0]
                l[0] = l[i]
                l[i] = tmp
            else:
                tmp = l[c[i]]
                l[c[i]] = l[i]
                l[i] = tmp
            result.append(l)
            c[i] += 1
            i = 0
        else:
            c[i] = 0
            i += 1
    return result

我不明白为什么会这样。 我也想弄清楚是否有更有效的方法来做到这一点,也许是递归 function。

您可以使用以下内容,这是不使用其他内部 function 但它使用递归:

def permutation(lst):
    if len(lst) == 0:
        return []
    if len(lst) == 1:
        return [lst]

    l = [] # empty list that will store current permutation

    for i in range(len(lst)):
       m = lst[i]

       # Extract lst[i] or m from the list. remainderLst is remaining list
       remainderLst = lst[:i] + lst[i+1:]

       # Generating all permutations where m is first element
       for p in permutation(remainderLst):
           l.append([m] + p)
    return l


data = list('12345')
for p in permutation(data):
    print(p)

我会使用@David S 的答案。或者您可以使用以下代码:

def permutate(ls):
    if len(ls) == 0: return []
    elif len(ls) == 1: return [ls]
    else:
        ls1 = []
        for i in range(len(ls)):
            x = ls[i]
            y = ls[:i] + ls[i+1:]
            for p in permutate(y): ls1.append([x]+p)
        return ls1

a = str(input("To permutate? ")).split(" ")
for i in permutate(a): print(" ".join(i))

但它基本上是一样的:D

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM