這是我在互聯網上找到的一些代碼,它沒有太多解釋。我只是好奇它是如何工作的。我不完全瞭解yield
和[s for s in subsets(S)]
部分。任何有識之士將非常感謝!Python 3 - [s for s in subsets(S)] and yield
def subsets(aList):
if aList ==[]: # base case
yield []
else:
first = aList[0]
rest = aList[1:]
for ss in subsets(rest): # include first or don't in each
yield ss # subset of rest
yield [first]+ss
print ("\n testing subsets")
S = ['A','B','C','D','E']
ss = [s for s in subsets(S)]
print ("The subsets of",S,"are:")
print (ss)