总之。我怎么写别的东西比这个:for another in combinationOfK(K-1, L[i+1:]):
我的函数combinationOfK(...)是不可迭代的。用迭代的东西代替函数
我想了解从here解决方案的代码。 Problem 26: Generate the combinations of K distinct objects chosen from the N elements of a list
我知道什么产量。但我正在尝试编写代码而没有 a 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
给了我一个想法,我可以代替产量。他们给recepie,这不是为我工作,就是:
当你看到
yield
语句的功能,应用此容易 招明白会发生什么:
- 插入线
result = []
在函数的开始处。- 用
result.append(expr)
替换每个yield expr
。- 在函数的底部插入一行
return result
。- Yay - 没有更多
yield
声明!阅读并找出代码。- 将功能还原为原始定义。
以此来获得不屈服的代码给我这个。代码不工作(该函数不可迭代)。 我必须写些什么才能让代码在没有收益的情况下工作?
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' object is not iterable
。
你忘了缩进你的最后一个函数5日线。 – 2012-07-23 15:57:46
固定。现在它缩进了。 – 2012-07-23 16:35:48