Given a list of unique elements, a permutation of the list is a reordering of th
ID: 3716645 • Letter: G
Question
Given a list of unique elements, a permutation of the list is a reordering of the elements. For example, [2, 1, 3], [1, 3, 2], and [3, 2, 1] are all permutations of the list [1, 2, 3].
Implement permutations, a generator function that takes in a lst and outputs all permutations of lst, each as a list (see doctest for an example). The order in which you generate permutations is irrelevant.
Hint: If you had the permutations of lst minus one element, how could you use that to generate the permutations of the full lst?
Note that in the provided code, the return statement acts like a raise StopIteration. The point of this is so that the returned generator doesn't enter the rest of the body on any calls to next after the first if the input list is empty. Note that this return statement does not affect the fact that the function will still return a generator object because the body contains yield statements.
"*** YOUR CODE HERE ***"
Explanation / Answer
here is your code : -------------->>>>>>>>>>>
def permutations(lst):
"""Generates all permutations of sequence LST. Each permutation is a
list of the elements in LST in a different order.
The order of the permutations does not matter.
>>> 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']]
"""
temp1 = []
temp1.append(lst)
res = []
temp = []
tr = []
for i in range(0,len(lst)):
for j in range(0,len(lst)):
if i < j:
n = len(temp1)
for l in range(0,n):
tr = temp1[l]
for k in range(0,len(tr)):
if k == i:
temp.append(tr[j])
elif k == j:
temp.append(tr[i])
else:
temp.append(tr[k])
if temp not in res:
res.append(temp)
temp1.append(temp)
temp = []
res.append(lst)
return res;
b = [1,2,3,4]
obj = permutations(b)
print(sorted(obj))
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.