排列组合
时间:2008-11-14 来源:jiangerji
求出s个元素中n个的所有排列情况P(s, n)
比如0,1,2的所有排列情况为012, 021, 102, 120, 201, 210,共6种情况
比如0,1,2的所有排列情况为012, 021, 102, 120, 201, 210,共6种情况
def permutation(s, n):
#从s中选取n进行排列
if (n > len(s)) or (n <= 0) or (len(s) == 0):
return
if n == 1:
for i in range(len(s)):
yield [s[i]]
else:
for i in s:
#print i, len(s), r
st = list(s)
st.remove(i)
for j in permutation(st, n-1):
yield [i] + j
其中yield是python的生成器。
获取组合的代码为
#从s中选取n进行排列
if (n > len(s)) or (n <= 0) or (len(s) == 0):
return
if n == 1:
for i in range(len(s)):
yield [s[i]]
else:
for i in s:
#print i, len(s), r
st = list(s)
st.remove(i)
for j in permutation(st, n-1):
yield [i] + j
其中yield是python的生成器。
获取组合的代码为
def combination(s, n):
if (n > len(s)) or (n <= 0) or (len(s) == 0):
return
if n == 1:
for i in s:
yield [i]
else:
for i in range(len(s)):
for j in combination(s[i+1:], n-1):
yield [s[i]]+j
if (n > len(s)) or (n <= 0) or (len(s) == 0):
return
if n == 1:
for i in s:
yield [i]
else:
for i in range(len(s)):
for j in combination(s[i+1:], n-1):
yield [s[i]]+j
相关阅读 更多 +