Reputation: 943
I have the following function in Python, and I want to convert it into a more vanilla function that does not use yield
so I can translate it to other languages.
Could someone please explain how I could go about this?
The function simply prints out the permutations of n
choose m
.
i.e. for n==4
, m==2
, it will create arrays of the form:
1001
, 1100
, 1010
and so on.
def bitmasks(n, m):
if n == m:
yield (1 << n) - 1
elif m > 0:
for x in bitmasks(n-1, m-1):
yield (1 << (n-1)) + x
for x in bitmasks(n-1, m):
yield x
else:
yield 0
Upvotes: 0
Views: 66
Reputation: 2048
Add your results to a list.
def bitmasks(n, m):
if n == m:
return [(1 << n) - 1]
elif m > 0:
res = []
for x in bitmasks(n-1, m-1):
res.append((1 << (n-1)) + x)
for x in bitmasks(n-1, m):
res.append(x)
return res
else:
return [0]
Upvotes: 2
Reputation: 553
The function does not print anything, it just yields each result piece by piece. You can create an empty list in the beginning and then replace each yield
by an append
to your list. In the end, you just return the full list of results.
Upvotes: 2