Search code examples
pythonalgorithmrecursive-backtracking

cant store the value in global variable


Im trying to do permutation problem in leetcode with backtracking Algorithm, While Printing I got all the Possiblities but when i Trying to store those value in global variable I'm not allow to that

Ex:
AnswerIwant:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

when i print those value while recursion it is print 
Example:
[1, 2, 3]
[1, 3, 2]
[2, 3, 1]
[2, 1, 3]
[3, 1, 2]
[3, 2, 1]

When I store The Value In Global variable for outPut I got like This

[1, 2, 3]
[[1, 2, 3]]
[[1, 2]]
[1, 3, 2]
[[1, 3, 2], [1, 3, 2]]
[[1, 3], [1, 3]]
[[1], [1]]
[2, 3, 1]
[[2, 3, 1], [2, 3, 1], [2, 3, 1]]
[[2, 3], [2, 3], [2, 3]]
[2, 1, 3]
[[2, 1, 3], [2, 1, 3], [2, 1, 3], [2, 1, 3]]
[[2, 1], [2, 1], [2, 1], [2, 1]]
[[2], [2], [2], [2]]
[3, 1, 2]
[[3, 1, 2], [3, 1, 2], [3, 1, 2], [3, 1, 2], [3, 1, 2]]
[[3, 1], [3, 1], [3, 1], [3, 1], [3, 1]]
[3, 2, 1]
[[3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1]]
[[3, 2], [3, 2], [3, 2], [3, 2], [3, 2], [3, 2]]
[[3], [3], [3], [3], [3], [3]]

[[], [], [], [], [], []]

Here Is my code For the Above OutPut

nums = [1,2,3]
val=nums
answerIwant = []
numberOfValues=len(val)-1
answer=[]
def permutation(nums, bucket, index,sub):
    global answerIwant,numberOfValues
    for i in range(len(nums)):
        val=nums.pop(0)
        bucket.append(val)
        if len(bucket)-1==numberOfValues:
            print(bucket)
            answerIwant.append(bucket)
        permutation(nums, bucket, index,sub)
        nev=bucket.pop()
        nums.append(nev)
    print(answerIwant)
#[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
sub=[]
bucket = []

val=(permutation(nums, bucket, index,sub))
print(val)

Explain that problem i'm facing with symbol word Thank You


Solution

  • You have to append the copy of the list during appening in the answerIwant list. So you should replace answerIwant.append(bucket) to answerIwant.append(bucket.copy()).

    Refer this for more info. So your code could be this,

    nums = [1,2,3]
    val=nums
    answerIwant = []
    numberOfValues=len(val)-1
    answer=[]
    def permutation(nums, bucket, index,sub):
        global numberOfValues
        for i in range(len(nums)):
            val=nums.pop(0)
            bucket.append(val)
            if len(bucket)-1==numberOfValues:
                # print(bucket)
                answerIwant.append(bucket.copy())
            permutation(nums, bucket, index,sub)
            nev = bucket
            nev=bucket.pop()
            nums.append(nev)
    
    #[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
    sub=[]
    bucket = []
    
    permutation(nums, bucket, 0,sub)
    
    print(answerIwant)