Python 基础——排列组合的实现
来源:互联网 发布:sql replace用法 编辑:程序博客网 时间:2024/05/29 18:48
考虑这样一个问题,给定一个矩阵(多维数组,numpy.ndarray()
),如何shuffle
这个矩阵(也就是对其行进行全排列),如何随机地选择其中的k
行,这叫组合,实现一种某一维度空间的切片。例如五列中选三列(全部三列的排列数),便从原有的五维空间中降维到三维空间,因为是全部的排列数,故不会漏掉任何一种可能性。
涉及的函数主要有:
np.random.permutation()
itertools.combinations()
itertools.permutations()
# 1. 对0-5之间的数进行一次全排列>>>np.random.permutation(6)array([3, 1, 5, 4, 0, 2])# 2. 创建待排矩阵>>>A = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])# 3. shuffle矩阵A>>>p = np.random.permutation(A.shape[0])>>>parray([1, 2, 0])>>>A[p, :] array([[ 5, 6, 7, 8], [ 9, 10, 11, 12], [ 1, 2, 3, 4]])
C25 的实现
>>>from itertools import combinations>>>combins = [c for c in combinations(range(5), 2)]>>>len(combins)10>>>combins # 而且是按序排列[(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
A25 的实现
>>>from itertools import permutations>>>pertumations(range(5), 2)<itertools.permutations object at 0x0233E360>>>>perms = permutations(range(5), 2)>>>perms[(0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 3), (2, 4), (3, 0), (3, 1), (3, 2), (3, 4), (4, 0), (4, 1), (4, 2), (4, 3)]>>>len(perms)20
# 5. 任取其中的k(k=2)行>>>c = [c for c in combinations(range(A.shape[0]), 2)]>>>A[c[0], :] # 一种排列array([[1, 2, 3, 4], [5, 6, 7, 8]])
0 0
- Python 基础——排列组合的实现
- 递归—排列组合的实现
- Python.排列组合实现方法
- 用python实现排列组合
- C++实现——排列组合
- Python Tricks(二十一)—— 排列组合的计算
- python的排列组合
- Python的排列组合运用
- Python 排列组合的计算
- python itertools模块实现排列组合
- Python使用combinations实现排列组合
- 排列组合的实现
- 排列组合的实现
- 排列组合的实现
- 排列组合的递归实现
- 简单明了的Python 排列组合功能
- 轻松用python实现排列组合功能
- 基于python快速实现排列组合算法
- -Android Studio导入Project的方法
- wap网页通用模板
- Cache friendly code
- 队列 数据结构作业(二)
- 机器学习理解(四)
- Python 基础——排列组合的实现
- Android studio 导入github工程
- xml被浏览器缓存了
- am335x sd卡分区制作文档
- 人的需求2
- java lucene搜索功能初探(1)
- Android 缓存-ASimplecache
- css 最重要,最基本的知识
- eclipse中项目导入到android studio出现的Manifest merger failed问题