jeudi 10 décembre 2020

Preventing a change back once made in if statement python

I'm trying to change all the column values in 3 x 3 matrices to follow the following rules:

  • If 0 -> 0
  • If 1 -> 5
  • If 2 -> 6
  • If 3 -> 4
  • If 4 -> 3
  • If 5 -> 1
  • If 6 -> 2
  • If 7 -> 7
  • If 8 -> 9
  • If 9 -> 8

This is what I have been able to do so far

def solve(x):
    if x[x == 1].all() == True:
        x[x == 1] = 5
    if x[x == 5].all() == True:
        x[x == 5] = 1
    if x[x == 2].all() == True:
        x[x == 2] = 6
    if x[x == 6].all() == True:
        x[x == 6] = 2
    if x[x == 3].all() == True:
        x[x == 3] = 4
    if x[x == 4].all() == True:
        x[x == 4] = 3
    if x[x == 8].all() == True:
        x[x == 8] = 9
    if x[x == 9].all() == True:
        x[x == 9] = 8
    return x

The problem I'm having is that say a 1 goes to 5, how do I prevent it from going back to a 1 again? I've tried incorporating elif but it doesnt always yield the right results. For example say I ran this array into my function:

 array([[3, 1, 2],
        [3, 1, 2],
        [3, 1, 2]])

I'd expect to see

array([[4, 5, 6], 
       [4, 5, 6], 
       [4, 5, 6]])

But I end up getting the input again

array([[3, 1, 2],
       [3, 1, 2],
       [3, 1, 2]])

How can I work around this in the if statements?

Aucun commentaire:

Enregistrer un commentaire