+ 2
[SOLVED]How to make this function return/yield each permutation?
5 Réponses
0
Thanks a lot to all helpers.
Now I've come up with a solution.
The problem in appending all permutations(a) to a list L was that whenever "a" changed the values in L would also change because it contained just a reference to a. L+=[list(a)] or L.append(list(a)) solved this issue.
Also, more accurate solution will be to use 'yield from'
+ 7
Here is a sample that shows how a generator is working. to keep the code in good readability, i have used itertools.permutations().
res_perm is a generator object. i have included 2 print statements that demonstrates the "interaction" of the main program and the function permut()
from itertools import permutations as pm
def permut(nums):
for i in pm(nums):
print('next step is yield ',end ='') # for demonstration only
yield i
res_perm = permut([1,2,3])
for i in res_perm:
print(i,end='')
print(' <-- from main...') # for demonstration only
+ 2
Here is a simple solution:
import itertools
def per(a):
return itertools.permutations(a)
for l in per([1, 2, 3, 4]):
print('list = ' + str(l))
+ 1
Bro I know about generators and how yield and return works. I want my function to yield each permutation.
As it is recursion I'm not able to return/yield the (permutated) values.
I even tried taking another list and appending each permutation(a) to it but in vain.
0
Modules are always there but we should prefer using our brain if you don't mind.
I've made my own code for it and in that I want some help.