4

I was solving this leetcode permutation problem and came across an error that am getting n empty lists inside my returned list which suppose to print different permutations of the given list

getting output => [[], [], [], [], [], []]

Expected output=> [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

def permute(nums):
    l=[]
    s=list()
    ans=[]

        return helper(nums,s,l)
def helper(nums,s,l):
    if not nums:
        print(l)
        s.append(l)
    else:
        for i in range(len(nums)):
            c=nums[i]
            l.append(c)
            nums.pop(i)
            helper(nums,s,l)
            nums.insert(i,c)
            l.pop()
    return s
print(permute([1,2,3]))

2 Answers 2

7

You should do s.append(l.copy()) because otherwise you pop all values from the same list l, that's why the result consists of empty lists.

Sign up to request clarification or add additional context in comments.

4 Comments

can you edit the code so that i could get the desired answer as am getting this [<function list.copy()>, <function list.copy()>, <function list.copy()>, <function list.copy()>, <function list.copy()>, <function list.copy()>]
@yolonbsn please check if you write exactly s.append(l.copy()), not s.append(l.copy) - note the parentheses.
can you please tell me how the l is getting empty why did we used copy()
@yolonbsn it is getting empty because of two factors: 1) the list l is always the same in every call to helper function - it is passed by reference. 2) there is a line l.pop() to every line l.append(...) so in the end the number of calls to pop and append equals. To avoid this problem we use copy at the moment we need the value of l to be unchanged.
0

You can also use s.append(l[:]) this slicing also does the same

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.