Question 2 of Homework 11 from Berkeley's CS6 1A says:
Implement
permutations
, a generator function that takes in alst
and outputs all permutations oflst
, each as a list (see doctest for an example). The order in which you generate permutations is irrelevant.
This is my solution:
def permutations(lst):
if not lst:
yield []
return
"*** YOUR CODE HERE ***"
if type(lst)==tuple:
t=lst
lst=[]
for elem in t:
lst+=[elem]
if type(lst)==str:
lst=list(lst)
for elem in lst:
if elem:
l_temp=[lst[0]]
lst=lst[1:]
lst.extend(l_temp)
temp=list(lst[1:])
r_list=[]
lst_of_lst=[]
r_list+=[lst[0]]
while len(lst_of_lst)!=len(lst)-1:
holder=temp[1:]
t_holder=[temp[0]]
temp=[]
temp.extend(holder)
temp.extend(t_holder)
if len(r_list)==1:
r_list.extend([e for e in temp])
lst_of_lst+=[r_list,]
r_list=[]
r_list+=[lst[0]]
yield lst_of_lst
Test cases:
>>> sorted(permutations([1, 2, 3]))
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
>>> type(permutations([1, 2, 3]))
<class 'generator'>
>>> sorted(permutations((10, 20, 30)))
[[10, 20, 30], [10, 30, 20], [20, 10, 30], [20, 30, 10], [30, 10, 20], [30, 20, 10]]
>>> sorted(permutations("ab"))
[['a', 'b'], ['b', 'a']]
I need some suggestions in order to improve my code.
itertools.permutations
? Is this an exercise for a programming class? \$\endgroup\$