In short. How do I write something else than this: for another in combinationOfK(K-1, L[i+1:]):
My function combinationOfK(...) is not iterable.
I am trying to understand the code from here, solution to. Problem 26: Generate the combinations of K distinct objects chosen from the N elements of a list
I know what yield does. But I am trying to write the code without a yield
statement. Code with yield statement is this.
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
gave me the idea that I could replace yield. The recepie they give, which is not working for me, is:
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.
Using this to get code without yield give me this. The code is not working (the function is not iterable). What do I have to write to get this code working without 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
I am using this code to test the function,
the_list = ['a','b','c','d','e']
print list(combinationOfK(2, the_list))
raising error TypeError: 'NoneType' object is not iterable
.