Search code examples
pythonlistfunctiondictionaryreturn

Python doesn't return correct values with a dictionary using a function


I have a function that returns an array of values and another array with dictionaries, All dictionaries are different but it returns the same value

When I print it form the function I get correct values for example

{0: 0}
{0: 1, 1: 0}
{0: 2, 1: 1, 2: 0}      
{0: 3, 1: 5, 2: 0}      
{0: 4, 1: 1, 2: 0}      
{0: 5, 1: 0, 2: 0}      
{0: 6, 1: 5, 2: 0}      
{0: 7, 1: 2, 2: 1, 3: 0}

But when I return the array y get this (the wrong answer)

([0, 2, 4, 4, 6, 1, 6, 5], # This array is correct
 [{0: 7, 1: 2, 2: 1, 3: 0}, # From here is incorrect
  {0: 7, 1: 2, 2: 1, 3: 0},
  {0: 7, 1: 2, 2: 1, 3: 0},
  {0: 7, 1: 2, 2: 1, 3: 0},
  {0: 7, 1: 2, 2: 1, 3: 0},
  {0: 7, 1: 2, 2: 1, 3: 0},
  {0: 7, 1: 2, 2: 1, 3: 0},
  {0: 7, 1: 2, 2: 1, 3: 0}])

This is the fragment of code with this problem

    .
    .
    .
    for i in range(n):
        j = i
        count = 0
        while parent[j] != -1:
            s[i][count] = j
            count = count + 1
            j = parent[j]
        s[i][count] = start
        ###########
        print(s[i])
        ###########
        
    return dist, s

Solution

  • I think this is what u 're looking for:

    for i in range(n):
            j = i
            s = []
            while parent[j] != -1:
                s.append(j)
                j = parent[j]
            s.append(start)
            path[i] = s[::-1]