0

I am trying to save the result of a nested for loop in a list in python. can someone tell me how to do it? V is an array containing [1, 2, 3] while n is the length = 3 and sq is the matrix containing swaps.

i have tried many approaches but whenever i return the result it only gives me one element of the list. any help would be appreciated. Thankyou

def Permute1(sq,v,n):
        for i in range(n):
            for j in range(n):
                if (sq[i,j]==1):
                    temp=v[i]
                    v[i]=v[j]
                    v[j]=temp
                    print(v)



results: 
[1, 2, 3]
[2, 1, 3]
[3, 1, 2]
[3, 1, 2]
[3, 2, 1]
[3, 2, 1]
AAT
  • 47
  • 1
  • 6

3 Answers3

0

I'm not sure what is the utility of d = vhere.

To swap two elements in Python, I recommend:

v[i], v[j] = v[j], v[i]

Declaring an empty list before for loops and append the values (like AkshayNevrekar said) can also be useful, depending on what you need as a result.

DeusDev
  • 538
  • 6
  • 15
0

Check yield. You can use this to generate all the permutations and process each one of them & store them in a list.

Georgy
  • 12,464
  • 7
  • 65
  • 73
taurus05
  • 2,491
  • 15
  • 28
0
def Permute1(sq,v,n):
    result=[]
    for i in range(n):
        for j in range(n):
            if (sq[i,j]==1):
                temp=v[i]
                v[i]=v[j]
                v[j]=temp
                result += [v]
    print(result)
    return result

No tested but may be it can help.

Mohit
  • 93
  • 10