I’m trying to make a list of matrices using numpy to represent the minimum number of moves to solve the towers of Hanoi problem. My solution works when I print m after each move but when I try and append m to a list, the resulting list just contains the final matrix repeated over and over. Here’s my code:
def set_up(total,start):
global moves
moves = 0
m = np.empty((3,total+1))
for i in range(3):
for j in range(total+1):
m[i,j] = -1
for i in range(total):
m[start,i] = int(total-i-1)
m_list = [m]
return m,m_list
def move_disk(total,num,m,move_from,move_to,m_list):
global moves
temp =m[move_from,np.where(m[move_from]==-1)[0][0]-1]
m[move_from,np.where(m[move_from]==-1)[0][0]-1]= -1
m[move_to,np.where(m[move_to]==-1)[0][0]] = temp
moves = moves + 1
m_list.append(m)
def towers_algorithm(total,num,m,start,middle,final,m_list):
if num == 0:
return
else:
towers_algorithm(total,num-1,m,start,final,middle,m_list)
move_disk(total,num,m,start,final,m_list)
towers_algorithm(total,num-1,m,middle,start,final,m_list)
I’ve tried passing the list as a parameter and making m_list a global variable. Both gave the same result.
Syd Stafferton is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.