Python编程练习.全排列和全组合
2018-12-23 17:04
134 查看
利用Python实现经典算法:全排列和全组合
1.全排列
根据python文档中的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 = 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
2.全组合
(1)根据python文档中的itertools.combinations方法进行排列
def combinations(iterable, r): # combinations('ABCD', 2) --> AB AC AD BC BD CD # combinations(range(4), 3) --> 012 013 023 123 pool = tuple(iterable) n = len(pool) if r > n: return indices = list(range(r)) yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != i + n - r: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 yield tuple(pool[i] for i in indices)
(2)根据位运算进行组合
def combinations(str): n=2**len(str) for i in range(n): bits=[i>>offset&1 for offset in range(len(str)-1,-1,-1)] current=[str[index] for (index,bit) in enumerate(bits) if bit==1] print(''.join(current));
- 参考:
【Python: 实现全组合】(https://www.polarxiong.com/archives/Python-实现全组合.html)
【itertools函数】(https://docs.python.org/3/library/itertools.html?highlight=itertools)
相关文章推荐
- python基础编程_1_数字的组合排列
- Python编程之黑板上排列组合,你舍得解开吗
- Dave Python 练习十九 -- 网络客户端编程
- 《Python核心编程》第二版第36页第二章练习 续一 -Python核心编程答案-自己做的-
- 《Python核心编程》第二版第36页第二章练习 续二 -Python核心编程答案-自己做的-
- 简单明了的Python 排列组合功能
- 《Python核心编程》第二版第36页第二章练习 续三 -Python核心编程答案-自己做的-
- 刚接触编程的同学可以看看的几个编程练习(python实现)(四)
- python编程练习之四——获取系统内存、CPU、磁盘、平均负载信息并保存到数据库中
- 《Python核心编程》第二版第209页第八章练习 续一 -Python核心编程答案-自己做的-
- python编程练习之二
- 编程技巧:Java面向对象的排列组合算法
- python核心编程 第六章练习6-2
- python 排列组合
- 编程实现1到N个数的所有排列组合
- python基础编程_18_比赛顺序组合
- Python2.7基于笛卡尔积算法实现N个数组的排列组合运算示例
- Dave Python 练习十九 -- 网络客户端编程
- python 排列组合之itertools
- Python核心编程 练习 第六章