def combination(n, c, com=1, limit=0, per=[]):
for pos in range(limit, n):
t = per + [pos]
if len(set(t)) == len(t):
if len(t) == c:
yield [pos, ]
else:
for result in combination(n, c, com, com * pos, per + [pos, ]):
yield [pos, ] + result
print("排列:") # A8/1
for res in combination(8, 1, 0):
print(res)
print("组合:") # C8/3
for res in combination(8, 3):
print(res)
排列就是每次都从0开始选,组合的话,后一个必须大于前一个,combination第三个参数com表示是排列还是组合,因为函数名是combination,所以缺省是组合。
检查的话:无论排列还是组合,都不能重复,就是把列表变成词典,看看长度是否一样,不一样了就是有重复元素,不应该放到结果中
借鉴文章:戳这里