栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python

从Python 2.6(如果你使用的是Python 3)开始,你可以使用标准库工具:itertools.permutations。

import itertoolslist(itertools.permutations([1, 2, 3]))

如果你出于某种原因使用旧版Python(

<2.6
),或者只是想知道它的工作原理,那么这是一种不错的方法,取自 http://pre.activestate.com/recipes/252178/:

def all_perms(elements):    if len(elements) <=1:        yield elements    else:        for perm in all_perms(elements[1:]): for i in range(len(elements)):     # nb elements[0:1] works in both string and list contexts     yield perm[:i] + elements[0:1] + perm[i:]

的文档中列出了几种替代方法

itertools.permutations
。这是一个:

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 = range(n)    cycles = 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

另一个基于

itertools.product

def permutations(iterable, r=None):    pool = tuple(iterable)    n = len(pool)    r = n if r is None else r    for indices in product(range(n), repeat=r):        if len(set(indices)) == r: yield tuple(pool[i] for i in indices)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/370220.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号