提问
简而言之.除此以外,我该如何写别的东西:对于CombineOfK(K-1,L [i 1:])中的另一个:我的函数combinationOfK(…)是不可迭代的.我试图理解从here到解决方案的代码.问题26:生成从列表的N个元素中选择的K个不同对象的组合我知道产量是多少.但是我试图在没有yield语句的情况下编写代码.带有yield语句的代码是这个.
def combination(K, L):
if K<=0:
yield []
return
for i in range(len(L)):
thisone = L[i:i+1]
for another in combination(K-1, L[i+1:]):
yield thisone + another
The question, yield-keyword-explained
给我的想法是我可以代替产量.他们给的收据对我不起作用,是:
When you see a function with
yield
statements, apply this easy
trick to understand what will happen:
- Insert a line
result = []
at the start of the function.- Replace each
yield expr
withresult.append(expr)
.- Insert a line
return result
at the bottom of the function.- Yay – no more
yield
statements! Read and figure out code.- Revert function to original definition.
用它来获取代码而不屈服于我.代码不起作用(该函数不可迭代).我要写什么才能使该代码正常工作而不屈服?
def combinationOfK(K,L):
result = []
if K <= 0:
result.append([])
return
for i in range(len(L)):
thisone = L[i:i+1]
for another in combinationOfK(K-1, L[i+1:]): # the error
result.append(thisone + another)
return result
我正在使用此代码测试功能,
the_list = ['a','b','c','d','e']
print list(combinationOfK(2, the_list))
引发错误TypeError:“ NoneType”对象不可迭代.
最佳答案
问题在于您的原始代码以异常的方式使用return.def combination(K, L):
if K<=0:
yield []
return # <--- hmmm
大多数时候,您不会在生成器中看到返回值,因为您并不经常需要它.通常,生成器最后只会“掉线”.解释器到达生成器的末尾而没有遇到return语句,然后知道抛出StopIteration.
在这种情况下,代码的编写者插入了return语句以“加快”该过程.当K< = 0时,没有更多的工作要做,因此生成器可以抛出StopIteration,但是如果没有return语句,它将进入for循环,从而产生错误的结果.我认为,更清晰的方法是这样的:
def combination(K, L):
if K<=0:
yield []
else:
for i in range(len(L)):
thisone = L[i:i+1]
for another in combination(K-1, L[i+1:]):
yield thisone + another
现在,转换可以按预期进行:
def combination2(K, L):
result = []
if K <= 0:
result.append([])
else:
for i in range(len(L)):
thisone = L[i:i + 1]
for another in combination2(K - 1, L[i + 1:]):
result.append(thisone + another)
return result