1.排列
1.1 使用itertools
from itertools import permutations
list(permutations(["a","b","c"]))
1.2 自定义函数
def perm(ls,begin,end):
global res,count
if begin==end-1:
res.append(ls.copy())
count+=1
return
else:
for ind in range(begin,end):
ls[begin],ls[ind]=ls[ind],ls[begin]
perm(ls,begin+1,end)
ls[begin],ls[ind]=ls[ind],ls[begin]
arr = ["a","b",'c']
res=[]
count=0
perm(arr, 0, len(arr))
print(res)
2.组合
2.1 使用itertools
from itertools import combinations
list(combinations(["a","b","c","d"],2))
2.2 自定义函数
def combine(ls,sub,ind):
global res,k
if len(sub)==k:
res.append(sub[:])
return
for i in range(ind,len(ls)):
sub.append(ls[i])
combine(ls[ind:],sub,i+1)
sub.pop()
arr=['a','b','c','d']
res=[]
k=2
combine(arr,[],0)
print(res)