5
I’m trying to make a magic square:
- A magic square is one divided into rows and columns, with a number in each position and in which the sum of the rows, columns and diagonals is the same.
Example (3x3 - 1 to 9):
8 3 4 1 5 9 6 7 2
I tried using a 3x3 matrix and a vector with 9 indices.
import random
#j(coluna)
matriz = [[1, 2, 3],#i(linha)
[4, 5, 6],
[7, 8, 9]]
res = False
#DEFINIR UMA FUNÇÃO PARA CALCULAR AS SOMAS DE TODOS OS LADOS
def magicsquare():
if matriz[0][0] + matriz[1][0] + matriz[2][0] == matriz[0][1] + matriz[1][1] + matriz[2][1] == matriz[0][2] + matriz[1][2] + matriz[2][2] == matriz[0][0] + matriz[0][1] + matriz[0][2] == matriz[1][0] + matriz[1][1] + matriz[1][2] == matriz[2][0] + matriz[2][1] + matriz[2][2] == matriz[0][0] + matriz[1][1] + matriz[2][2] == matriz[0][2] + matriz[1][1] + matriz[2][0]:
return res == True
else:
return res == False
#DEFINIR UM LOOP PARA GERAR Nº ALEAT. ATÉ ENCONTRAR OS QUE SATIZFAZEM
#AS CONDIÇÕES DE UM QUADRADO MÁGICO
seq = [1, 2, 3, 4, 5, 6, 7, 8, 9]
while res == False:
for i in range(2):
for j in range(2):
z = random.choice(seq)
matriz[i][j] = z
x = seq.index(z)
seq[x] = []
magicsquare()
print (matriz)
#---------------------------------------------------------------------------------------------------------------------------------------------------------------
res = False
def magicsquare():
if vetor[0] + vetor[1] + vetor[2] == vetor[3] + vetor[4] + vetor[5] == vetor[6] + vetor[7] + vetor[8] == vetor[0] + vetor[3] + vetor[6] == vetor[1] + vetor[4] + vetor[7] == vetor[2] + vetor[5] + vetor[8] == vetor[0] + vetor[4] + vetor[8] == vetor[2] + vetor[4] + vetor[6]:
return res == True
else:
return res == False
# 0 1 2 3 4 5 6 7 8
vetor = [1, 2, 3, 4, 5, 6, 7, 8, 9]
seq = [1, 2, 3, 4, 5, 6, 7, 8, 9]
if res == False:
for i in range(8):
w = random.choice(seq)
#Repor o valor w(1 a 9) no index i(0 a 8). Sem usar valores e indexes repetidos
vetor.insert(i, w)
#Eliminar os valores já utilizados
x = seq.index(w)
seq[x] =[]
magicsquare()
print (vetor)
The result is always: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Can someone help me build a magic square?
Using Python 3.5.0
Having this code, how does it work? How would I simulate the creation of a magic square? Also, this code has some problem?
– Leonel Sanches da Silva
Are you sure the code you are using is the same code you posted here? I tested the first part of the code above and got
TypeError: unsupported operand type(s) for +: 'int' and 'list'
. Besides, I see you’re never assigning theres
, only by comparing it with other variables, so thatwhile res == False:
will enter an infinite loop.– mgibsonbr