最近编程时经常要用到排序组合的代码,想当年还抱着一些情况买了一本《组合数学》,不过现在这货也不知道被自己放哪里了,估计不会是垫桌子腿了吧。

由于去年去东北大学考博面试的时候遇到过可能涉及排列组合的编程题,要我当时很是十分的下不来台,所以现在遇到这货比较敏感,虽然用到的时候直接调用库就万事大吉,不过细细想来总觉不妥,遂把库函数的说明文档调了出来。

https://docs.python.org/dev/library/itertools.html#itertools.combinations

itertools.combinations(iterable, r)

Return r length subsequences of elements from the input iterable.

Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each combination.

Roughly equivalent to:

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)

初看这个代码感觉比较震惊,感觉这是什么鬼,代码量不是很大,不过实现的功能倒是要人感觉很强大。

以上代码虽然是等价代码,但是毕竟为源语言实现的,由此看看还是有些帮助的,估计真实库文件可能是使用C语言写的吧,这一点就不深入研究了。

pool = tuple(iterable) 该行代码则是将输入的可迭代对象转换为元组类型。

    n = len(pool)
if r > n:
return

该段代码则是 得到元组长度n,  如果排序数 r 大于总长n, 则无意义,因此直接返回。

indices = list(range(r))
indices 为排序的索引, 也是每次迭代返回组合的索引号。
yield tuple(pool[i] for i in indices)

返回 默认的组合。如: pool 为(0,1,2,3,4), n=5, r=3, 默认的返回就是 (0,1,2) 。
        for i in reversed(range(r)):
if indices[i] != i + n - r:
break
判断返回的组合序号 是否为 终止的序号, 即(2,3,4)。

        indices[i] += 1
返回的序号中如果那个位置的序号不等于终止序列中的对应该位置的序号则将该位置序号加一。
(0,1,2) =》 (0,1,3)
(0,1,3) =》 (0,1,4) (0,1,4) =》 (0,2, 4)

 for j in range(i+1, r):
indices[j] = indices[j-1] + 1
不同的序号位置加一后,其后续的位置依次在其前一位置上加一。即,(0,2,4)=》(0,2,3), (0,3,4)=》(1,3,4)=》(1,2,4)=》(1,2,3)

https://docs.python.org/dev/library/itertools.html#itertools.permutations
itertools.permutations(iterable, r=None)

Return successive r length permutations of elements in the iterable.

If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length permutations are generated.

Permutations are emitted in lexicographic sort order. So, if the input iterable is sorted, the permutation tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each permutation.

Roughly equivalent to:

 
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.combinations 和 itertools.permutations 等价代码实现的更多相关文章

  1. 【Python】排列组合itertools & 集合set

    ■itertools 利用python的itertools可以轻松地进行排列组合运算 itertools的方法基本上都返回迭代器 比如 •itertools.combinations('abcd',2 ...

  2. python排列组合之itertools模块

    1. 参考 几个有用的python函数 (笛卡尔积, 排列, 组合) 9.7. itertools — Functions creating iterators for efficient loopi ...

  3. 调用list(itertools.combinations(keys,3))出现MemoryError的解决办法

    在python3.6中,如下例子: keys = list(newKeywords.keys()) resultkeys = list(itertools.combinations(keys,3)) ...

  4. [转] 三种Python下载url并保存文件的代码

    原文 三种Python下载url并保存文件的代码 利用程序自己编写下载文件挺有意思的. Python中最流行的方法就是通过Http利用urllib或者urllib2模块. 当然你也可以利用ftplib ...

  5. 使用python制作ArcGIS插件(2)代码编写

    使用python制作ArcGIS插件(2)代码编写 by 李远祥 上一章节已经介绍了如何去搭建AddIn的界面,接下来要实现具体的功能,则到了具体的编程环节.由于使用的是python语言进行编程,则开 ...

  6. Python 爬虫的工具列表 附Github代码下载链接

    Python爬虫视频教程零基础小白到scrapy爬虫高手-轻松入门 https://item.taobao.com/item.htm?spm=a1z38n.10677092.0.0.482434a6E ...

  7. Python中生成器和迭代器的区别(代码在Python3.5下测试):

    https://blog.csdn.net/u014745194/article/details/70176117 Python中生成器和迭代器的区别(代码在Python3.5下测试):Num01–& ...

  8. (转)Python新手写出漂亮的爬虫代码2——从json获取信息

    https://blog.csdn.net/weixin_36604953/article/details/78592943 Python新手写出漂亮的爬虫代码2——从json获取信息好久没有写关于爬 ...

  9. (转)Python新手写出漂亮的爬虫代码1——从html获取信息

    https://blog.csdn.net/weixin_36604953/article/details/78156605 Python新手写出漂亮的爬虫代码1初到大数据学习圈子的同学可能对爬虫都有 ...

随机推荐

  1. mysql索引之哈希索引

    哈希算法 哈希算法时间复杂度为O(1),且不只存在于索引中,每个数据库应用中都存在该数据结构. 哈希表 哈希表也为散列表,又直接寻址改进而来.在哈希的方式下,一个元素k处于h(k)中,即利用哈希函数h ...

  2. try with resources简洁的异常捕获机制

    通过前篇的<Java文件IO流的操作总结>,我们知道了基本输入输出流的使用方式,但是每次都需要在finally处关闭流资源,这样操作起来既啰嗦又麻烦,有没有更简洁的方式呢?本篇就来讲解jd ...

  3. 一次org.springframework.jdbc.BadSqlGrammarException ### Error querying database Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException问题排查过程

    先说结论: 因为在表设计中有一个商品描述字段被设置为desc,但desc是mysql中的关键字,如select id,name,desc,price from product;这条sql语句在查询时的 ...

  4. 2018-2019 ICPC, NEERC, Southern Subregional Contest (Online Mirror, ACM-ICPC Rules, Teams Preferred) Solution

    A. Find a Number Solved By 2017212212083 题意:$找一个最小的n使得n % d == 0 并且 n 的每一位数字加起来之和为s$ 思路: 定义一个二元组$< ...

  5. G.Finding the Radius for an Inserted Circle 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛

    地址:https://nanti.jisuanke.com/t/17314 题目: Three circles C_{a}C​a​​, C_{b}C​b​​, and C_{c}C​c​​, all ...

  6. Arthur and Brackets

    n<605设计出n对夸号  给出n个条件每个条件为[l,r] 表示第i对夸号右夸号离左夸号的距离,然后夸号的右夸号出现的顺序必须按照给的顺序 出现, 那么如果存在就输出否则输出impossilb ...

  7. 从Linux服务器下载文件到本地命令

    从Linux服务器下载文件夹到本地1.使用scp命令 scp /home/work/source.txt work@192.168.0.10:/home/work/ #把本地的source.txt文件 ...

  8. Python:数字的格式化输出

    >>> 'The value is {:0,.2f}'.format(x) 'The value is 1,234.57' 需要将数字格式化后输出,并控制数字的位数.对齐.千位分隔符 ...

  9. nginx重启 failed (98: Address already in use)

    启动nginx服务,无法正常启动,一查log日志,发现如题错误信息. 问题描述:地址已被使用.可能nginx服务卡死了,导致端口占用,出现此错误. 查看端口 netstat -ntpl 杀掉进程   ...

  10. P1122 最大子树和(树形dp)

    P1122 最大子树和 大水题 随便找一个点做根,蓝后累计子树和. 子树和<0的话不取就行了 顺便找个最大值输出 end. #include<iostream> #include&l ...