求释疑 itertools.permutations的原理

30 views
Skip to first unread message

Ha

unread,
Nov 11, 2020, 6:14:21 AM11/11/20
to Tornado Web Server
def permutations(iterable, r=None):
    # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
    # permutations(range(3)) --> 012 021 102 120 201 210
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = list(range(n))
    cycles = list(range(n, n-r, -1))
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return

这个是python官网关于itertools.permutations的原语实现,没多少行代码,看着也不像字典序的搞法,完全看不明白其中的原理,求个解释

YS.Zou

unread,
Nov 11, 2020, 9:33:02 PM11/11/20
to python-...@googlegroups.com
Should post it to China Python User Group's Mailing List.

Ha <haowei...@gmail.com> 于2020年11月11日周三 下午7:14写道:
--
You received this message because you are subscribed to the Google Groups "Tornado Web Server" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python-tornad...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/python-tornado/85b25279-722a-4867-8faf-48a2810d969an%40googlegroups.com.


--
进出自由才是游戏者的生存之道。

http://www.zouyesheng.com
Reply all
Reply to author
Forward
0 new messages