题目
有序排列
'''
输入,m,n, 输出0~m,中任选N的有序排列结果
例子:
10,3
->720
4,2
->12
'''
$$
A_m^n=\frac{m!}{(m-n)!}\qquad(m>=n)
$$
$$
A_4^2=\frac{4!}{2!}=\frac{4\times3\times2\times1}{2\times1}=12
$$
def main(m,n):
result=[]
def handler(ldata,n,sel=[],cnt=0):
if(cnt==n):
result.append(sel)
else:
for item in ldata:
handler([i for i in ldata if i!=item],n,sel=sel+[item],cnt=cnt+1)
pass
ldata=list(range(m))
handler(ldata,n)
return result
pass
r=main(4,2)
for i in range(len(r)):
print(f'{i+1:2d} {r[i]}')
1 [0, 1]
2 [0, 2]
3 [0, 3]
4 [1, 0]
5 [1, 2]
6 [1, 3]
7 [2, 0]
8 [2, 1]
9 [2, 3]
10 [3, 0]
11 [3, 1]
12 [3, 2]
无序组合
'''
输入,m,n, 输出0~m,中任选N的有序排列结果
例子:
10,3
->120
4,2
->6
'''
$$
C_mn=\frac{A_mn}{n!}
=\frac{m!}{n!(m-n)!}\qquad(m>=n)
$$
$$
C_42=\frac{A_42}{2!}
=\frac{4!}{2!(4-2)!}=\frac{4\times3\times2\times1}{(2\times1)\times(2\times1)}=6
$$
def main(m,n):
result={}
def handler(ldata,n,sel=[],cnt=0):
if(cnt==n):
v=set(sel)
result[tuple(v)]=None
else:
for item in ldata:
handler([i for i in ldata if i!=item],n,sel=sel+[item],cnt=cnt+1)
pass
ldata=list(range(m))
handler(ldata,n)
return list(result.keys())
r=main(4,2)
for i in range(len(r)):
print(f'{i+1:2d} {r[i]}')
1 (0, 1)
2 (0, 2)
3 (0, 3)
4 (1, 2)
5 (1, 3)
6 (2, 3)