我必须使用标准集合表示法打印集合。我应该使用递归并且必须在某处有一个基本案例。最后的答案应该是成套的,我必须打印出来,不加一行。
这个函数应该打印出随机整数的幂集。第一个函数构建随机整数,第二个函数构建幂集,而最后一个函数打印集合。我有前两个函数和最后一个函数,但是当我运行代码时,它有时会打印一个集合,而其他时候则为空。我不知道我做错了什么?
整个事情是这样开始的:
from random import *
def randomSet (n, up):
return sample(range(up), n)
def powerset (A):
if A == []:
return [[]]
aoba = A[0]
imax = powerset(A[1:])
doggo = []
for set in imax:
doggo.append([aoba] + set)
return doggo + imax
def printSet (A):
for i in range(len(A)):
if i in A:
print ((set(A)),end="")
有一个我没有放在这里的测试器函数,但关键是我的代码不会一直正常工作。有时它会这样运行:
The powerset of
{0, 38, 58, 30, 24}
is
#supposed to show the powerset of the set above but it is always blank
其他时候它是这样运行的:
The powerset of
#nothing....just nothing!!!
is
#never anything here
请您参考如下方法:
您的打印功能不起作用。将其更改为 print(set(A)) ,您将获得金奖。以下是它不起作用的原因:
def printSet (A):
# range(len(A)) produces a list of the range of values [0,1,2,3,... len(A)]
# and then iterates over it, so I starts at 0 in the loop, then goes
# to 1, then 2, etc.
for i in range(len(A)):
# so here, you are checking if 0 is in your set on the first iteration
# then 1, then 2 etc and you print out the values of it is.
if i in A:
print ((set(A)),end="")
所以当集合中没有从零到集合长度范围内的数字时,您的函数将失败
例如 {32, 24, 10} 永远不会打印,因为在这个例子中没有值等于 0、1 或 2(它们是 range(set(A)) 创建的列表中的值) )
