【发布时间】:2021-07-13 13:27:58
【问题描述】:
不好意思问这个问题,但我正在学习一门名为“使用 Python 进行数据科学中的概率和统计”的 edx 课程,其中一个功能是创建组合。如下:
def combinations(A,k):
if k==1:
return [{x} for x in A]
sets = []
for x in A:
for y in combinations(A-{x},k=k-1):
if {x}|y not in sets:
sets.append({x}|y)
return sets
在哪里A=set(range(1,5))
因此调用combinations(A,2) 将返回以下内容:[{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}]。调用combinations(A,3) 将返回以下内容: [{1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}]
问题:
由于我们没有在任何地方定义 k,函数如何知道在给定集合中返回的排列长度?
我希望一旦在 for 循环中调用 combinations 函数,它会看到 k 是 !=1(因此 y 是 NoneType 因为 combinations 在 k 时什么都不做! =1),而 x 遍历 A 并被追加,产生一个长度为 A 的长集。
我们如何设置长度等于k?
谢谢!
编辑 1
递归函数...明确。但是,稍微简化一下函数仍然不太了解其行为(添加一些打印语句以查看从集合中减去的内容):
def permute(A):
if len(A)==1:
return [tuple(A)]
permutations = []
for x in A:
print(x)
for y in permute(A-{x}):
print(x,y)
print(f'x = {x},y = {y},length = {len(A-{x})}, output = {(x,)+y}, tuple = {[tuple(A)]}')
permutations.append((x,)+y)
return permutations
A = {1, 2, 3}
set(permute(A))
1
2
2 (3,)
x = 2,y = (3,),length = 1, output = (2, 3), tuple = [(2, 3)]
3
3 (2,)
x = 3,y = (2,),length = 1, output = (3, 2), tuple = [(2, 3)]
1 (2, 3)
x = 1,y = (2, 3),length = 2, output = (1, 2, 3), tuple = [(1, 2, 3)]
1 (3, 2)
x = 1,y = (3, 2),length = 2, output = (1, 3, 2), tuple = [(1, 2, 3)]
2
1
1 (3,)
x = 1,y = (3,),length = 1, output = (1, 3), tuple = [(1, 3)]
3
3 (1,)
x = 3,y = (1,),length = 1, output = (3, 1), tuple = [(1, 3)]
2 (1, 3)
x = 2,y = (1, 3),length = 2, output = (2, 1, 3), tuple = [(1, 2, 3)]
2 (3, 1)
x = 2,y = (3, 1),length = 2, output = (2, 3, 1), tuple = [(1, 2, 3)]
3
1
1 (2,)
x = 1,y = (2,),length = 1, output = (1, 2), tuple = [(1, 2)]
2
2 (1,)
x = 2,y = (1,),length = 1, output = (2, 1), tuple = [(1, 2)]
3 (1, 2)
x = 3,y = (1, 2),length = 2, output = (3, 1, 2), tuple = [(1, 2, 3)]
3 (2, 1)
x = 3,y = (2, 1),length = 2, output = (3, 2, 1), tuple = [(1, 2, 3)]
在第一次迭代时,函数取 1 并应将 y 与 (2,3) 分开,但它所做的是返回 x 的第二次迭代并取 2,因此仅将 y 留下 3,并且打印一个元组作为满足len(A)==1 的条件。为什么?
最后,如果y 是for loop,y 如何在此示例中返回 2 个元素(因此应该一个接一个地返回一个元素)?
【问题讨论】:
-
所以:
As we are not defining the k anywhere。你指的k是combinations的第二个参数吗? -
当您调用
combinations时,您正在明确设置k。combinations(A, n)返回大小集合n。 -
递归调用返回大小为
k - 1的集合y,显式排除某个值x,因此{x} | y是大小为k的集合。 -
感谢 @quamrana 和 @chepner 的 cmets。如果您有时间了解未开明的事物,请添加 EDIT 1。不熟悉递归函数,因此
k参数混淆不再相关。
标签: python combinations permutation probability