python 排列 组合_python实现排列和组合

一、模块

python模块实现排列和组合组合from itertools import combinations

s = "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 permutations

s = "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实现

来源于官网,效率不如模块组合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)排列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)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值