(python)求排列

运用itertools库求排列

import itertools
#a=[1,2,3]
#a=['a','b','c']
a=['(',')','(',')']
#a=[6,'(','a']
b=itertools.permutations(a) #返回元组类型
#去除相同的排列
ans=set() #运用集合的特性
for i in b:
   ans.add(i)
for i in  ans:
    print(i)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中有多种方式可以排列组合,下面介绍两种常见的方法。 1. 使用itertools模块 Python的itertools模块提供了多种排列组合的函数,包括permutations(排列)和combinations(组合)。这些函数可以快速方便地生成排列组合结果。 例如,要长度为3的列表[1,2,3]的所有排列,可以使用itertools.permutations函数: ```python import itertools lst = [1,2,3] perms = itertools.permutations(lst, 3) for perm in perms: print(perm) ``` 输出结果为: ``` (1, 2, 3) (1, 3, 2) (2, 1, 3) (2, 3, 1) (3, 1, 2) (3, 2, 1) ``` 要长度为2的列表[1,2,3]的所有组合,可以使用itertools.combinations函数: ```python import itertools lst = [1,2,3] combs = itertools.combinations(lst, 2) for comb in combs: print(comb) ``` 输出结果为: ``` (1, 2) (1, 3) (2, 3) ``` 2. 自己实现排列组合函数 如果不想使用itertools模块,也可以自己实现排列组合函数。下面是一个简单的实现: ```python def permutations(lst, n): if n == 0: yield [] else: for i in range(len(lst)): for perm in permutations(lst[:i] + lst[i+1:], n-1): yield [lst[i]] + perm def combinations(lst, n): if n == 0: yield [] else: for i in range(len(lst)-n+1): for comb in combinations(lst[i+1:], n-1): yield [lst[i]] + comb ``` 这里的permutations函数和combinations函数分别实现了排列和组合。它们都使用了递归算法,对于每个元素,可以选择使用或者不使用。当选择了n个元素后,即得到一个排列或组合。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值