打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
python实现排列和组合

python实现排列和组合

一、模块

python模块实现排列和组合

  1. 组合

from itertools import combinationss = "123456"print(list(combinations(s, 4)))# [('1', '2', '3', '4'), ('1', '2', '3', '5'), ('1', '2', '3', '6'), # ('1', '2', '4', '5'), ('1', '2', '4', '6'), ('1', '2', '5', '6'), # ('1', '3', '4', '5'), ('1', '3', '4', '6'), ('1', '3', '5', '6'), # ('1', '4', '5', '6'), ('2', '3', '4', '5'), ('2', '3', '4', '6'), # ('2', '3', '5', '6'), ('2', '4', '5', '6'), ('3', '4', '5', '6')]

combinations(iterable,r)
iterable:可迭代对象,需要组合的对象
r:需要组合的位数
2. 排列

from itertools import permutationss = "123456"print(list(permutations(s, 2)))# [('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('1', '6'), ('2', '1'), # ('2', '3'), ('2', '4'), ('2', '5'), ('2', '6'), ('3', '1'), ('3', '2'), # ('3', '4'), ('3', '5'), ('3', '6'), ('4', '1'), ('4', '2'), ('4', '3'), # ('4', '5'), ('4', '6'), ('5', '1'), ('5', '2'), ('5', '3'), ('5', '4'), # ('5', '6'), ('6', '1'), ('6', '2'), ('6', '3'), ('6', '4'), ('6', '5')]

permutations(iterable,r)
iterable:可迭代对象,需要排列的对象
r:需要排列的位数

二、python实现

来源于官网,效率不如模块

  1. 组合

def combinations(iterable, r):    pool = tuple(iterable)    n = len(iterable)    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)


if __name__=='__main__':
cl="123456789"
r=5
clist=list(combinations(cl, r))
print(f'组合数的个数为{len(clist)}。')
print('它们是:\n',clist)


  1. 排列

def permutations(iterable, r=None):    pool = tuple(iterable)    n = len(iterable)    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


if __name__=='__main__':
pl=[1,2,3,4,5,6,7,8,9]
r=3
plist=list(permutations(pl, r))
print(f'排列数的个数为{len(plist)}。')
print('它们是:\n',plist)
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
Python all() 函数 | 菜鸟教程
python中的itertools.Permutations()
python itertools模块详解
Python秒算24点,行还是不行?
python itertools功能详解
16个鲜为人知的 Python 小众技巧,让你的代码更加简洁高效
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服