1

I would like to copy one list to another:

list1= 
[[0,0,1,0,0],
 [0,1,0,0,0],
 [0,1,0,0,0],
 [0,1,0,0,0],
 [0,1,0,0,0]]
list2=
 [[2,2],
  [2,0],
  [2,0]]

If you look at it, list two looks like a tetris "L". My objective is to copy this "L" part to list one in way that the part would change list one by writing 2's in the part place. So the list1 after copying would look like:

list1= 
[[2,2,1,0,0],
 [2,1,0,0,0],
 [2,1,0,0,0],
 [0,1,0,0,0],
 [0,1,0,0,0]]

OR

list1= 
[[0,0,1,0,0],
 [0,1,0,0,0],
 [0,1,2,2,0],
 [0,1,2,0,0],
 [0,1,2,0,0]]

ETC.

As I need to place more parts (only one solution, as puzzle), I was thinking about using recursive function.

list1= [[0,0,0,0],
        [0,0,0,0],
        [0,0,1,0]],
list2= [[2,2],
        [2,0]],
list3= [[3,3],
        [3,0],
        [3,0]]
list4= [[4,4],
        [0,4],
        [0,4]]

List 1 should look like:

list1= [[3,3,4,4],
        [3,2,2,4],
        [3,2,1,4]]

IT NEEDS TO WORK AUTOMATICALLY. Any ideas?

IHav
  • 117
  • 7

1 Answers1

3

Try this way (destructive for list1):

dx, dy = 0, 0
for x, sub2 in enumerate(list2):
  for y, e in enumerate(sub2):
    if e != 0: list1[x+dx][y+dy] = e

dx and dy gives you the shift, take care of the index limit.

To see the output, dx, dy = 2, 2:

for line in list1:
  print (line)

# [0, 0, 1, 0, 0]
# [0, 1, 0, 0, 0]
# [0, 1, 2, 2, 0]
# [0, 1, 2, 0, 0]
# [0, 1, 2, 0, 0]


To reuse the code, define a method:
def move(matrix, piece, dx=0, dy=0):
  for x, line in enumerate(piece):
    for y, e in enumerate(line):
      if e != 0: matrix[x+dx][y+dy] = e
  return matrix

Then call depending on the moves you make:

list1= [[0,0,0,0], [0,0,0,0], [0,0,1,0]]
list2= [[2,2], [2,0]]
list3= [[3,3], [3,0], [3,0]]
list4= [[4,4],[0,4],[0,4]]

move(list1, list2, 1, 1)
move(list1, list3)
move(list1, list4, 0, 2)

The final result after the calls is:

for line in list1:
  print (line)

# [3, 3, 4, 4]
# [3, 2, 2, 4]
# [3, 2, 1, 4]
iGian
  • 11,023
  • 3
  • 21
  • 36
  • not sure whether it will work in "puzzle type - list1= [[0,0,0,0], [0,0,0,0], [0,0,1,0]], list2= [[2,2], [2,0]], list3= [[3,3], [3,0], [3,0]] list4= [[4,4],[0,4],[0,4]]` List 1 should look like: `list1= [[3,3,4,4], [3,2,2,4], [3,2,1,4]]` – IHav Dec 08 '18 at 18:24
  • You added new information, so I changed the code adding `if e != 0:`. Also I added an example of method and moves. – iGian Dec 08 '18 at 20:12
  • Need it to work automatically... Sadly I can't decide in which order and where the lists 2-4 will be located - the computer has to find the best solution itself – IHav Dec 08 '18 at 20:56
  • Updated it. Your code works perfectly, but sadly I can't put in the dx, dy, move order - it has to work automatically. – IHav Dec 09 '18 at 15:50