ZE16 ZE16 - 2 months ago 6
Python Question

How can I continuously replace an element of an array?

At each time step, I am trying to replace one element of my

list
with the sum of the other 2 plus 1. This is my code:

def replace(x, y, z):

for i in range(3):

rep_x = [y+z+1, y, z]
rep_y = [x, x+z+1, z]
rep_z = [x, y, x+y+1]

ini_x = rep_x
ini_y = rep_y
ini_z = rep_z

return ini_x, ini_y, ini_z


print replace(2, 4, 6)


This gives me a single line - a one-time replacement. I would like the code to keep doing the replacements on the newly-obtained arrays every time, for example:

([11, 4, 6], [2, 9, 6], [2, 4, 7])
((11, 4, 6], [11, 18, 6], [11, 4, 16]), ([19, 9, 6], [2, 9, 6], [2, 9, 12]), ([12, 4, 7], [2, 10, 7], [2, 4, 7]))

How can I do this?

Answer

Is this helpful:

def replace(x, y, z):
  ini_x = [y+z+1, y, z]
  ini_y = [x, x+z+1, z]
  ini_z = [x, y, x+y+1]
  return ini_x, ini_y, ini_z


s = replace(2, 4, 6)
print s
for i in s:
    print replace(i[0], i[1], i[2])

output:

([11, 4, 6], [2, 9, 6], [2, 4, 7])
([11, 4, 6], [11, 18, 6], [11, 4, 16])
([16, 9, 6], [2, 9, 6], [2, 9, 12])
([12, 4, 7], [2, 10, 7], [2, 4, 7])