+ 2

[SOLVED]How to make this function return/yield each permutation?

https://code.sololearn.com/cBDSqIIcI3DI/?ref=app

4th Oct 2020, 8:43 AM
abhinav
abhinav - avatar
5 Answers
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'
5th Oct 2020, 1:42 AM
abhinav
abhinav - avatar
+ 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
4th Oct 2020, 2:41 PM
Lothar
Lothar - avatar
+ 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))
4th Oct 2020, 3:01 PM
Josh Greig
Josh Greig - avatar
+ 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.
4th Oct 2020, 2:51 PM
abhinav
abhinav - avatar
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.
4th Oct 2020, 3:08 PM
abhinav
abhinav - avatar