The list comprehension at the heart of this function is building up an implicit list that ultimately gets returned. We can unwind the function, remove the comprehension, and use an explicit list:
def combine(n, k):
"""
Given two integers n and k, return all possible
combinations of k numbers out of 1 ... n.
"""
result = []
if k == 0:
result.append([])
else:
for i in range(1, n + 1):
for pre in combine(i - 1, k - 1):
result.append(pre + [i])
return result
print(combine(7, 4))
what does pre store in an internal loop?
The pre
variable store individual elements of the recursion. For example, to get all four digit combinations of seven digits, the code uses recursion to calculate all the three digit combinations and then augments them. That elements of that recursive result, each three digit combination, is stored, in turn, in pre
.
solved One line recursive loop in python