-8

I have been stumped trying to figure how to locate and change the values of the area bordered around a single element of an list without affecting the element values needing to be bordered.

This is what I'm trying to achieve:

BEFORE:

[[0,0,0,0,0],
 [0,1,1,0,0],
 [0,1,0,1,0],
 [0,0,1,0,0],
 [0,0,0,0,0]]

AFTER:

[[9,9,9,9,0],
 [9,1,1,9,9],
 [9,1,9,1,9],
 [9,9,1,9,9],
 [0,9,9,9,0])

I just need to know if I need mainly for loops as well as if/else statements, or if I need a separate library to get this solved.

Thanks in advance for helping!

2 Answers2

1

And yes , you can just pass with if/else and for loops :

 a = [[0,0,0,0,0],
      [0,1,1,0,0],
      [0,1,0,1,0],
      [0,0,1,0,0],
      [0,0,0,0,0]]

 to_replace = 1
 replacement = 9 

 for i in range(len(a)):
     for x in range(len(a[i])):
        if a[i][x] == to_replace:
            for pos_x in range(i-1,i+2):
                for pos_y in range(x-1,x+2):
                    try:
                        if  a[pos_x][pos_y] != to_replace:
                            a[pos_x][pos_y] = replacement
                    except IndexError:
                        print "Out of  list range" #may happen when to_replace is in corners
 for line in a:
     print line 

 #this will give you 
 # [9, 9, 9, 9, 0]
 # [9, 1, 1, 9, 9]
 # [9, 1, 9, 1, 9]
 # [9, 9, 1, 9, 9]
 # [0, 9, 9, 9, 0]
Marko Mackic
  • 2,293
  • 1
  • 10
  • 19
0

for loops and if/else statements will suffice.

Noam
  • 550
  • 2
  • 11
  • Sorry, was just replying directly to his question. He didn't seem to be asking for code. – Noam Jul 26 '16 at 19:13