lundi 23 novembre 2015

python 3.5.0 :::: MAGIC SQUARE

I'm trying to built a magic square:

A magic square is one divided in rows and columns, with a number in each position and which the sum of rows, columns and diagonals is the same. Example (3x3 - numbers from 1 to 9):

8 3 4

1 5 9

6 7 2

I tried to use a matrix 3x3 and a vector with 9 indexes.

import random
                #j(column)
matriz = [[1, 2, 3],#i(row)
          [4, 5, 6],
          [7, 8, 9]]
res = False
#DEFINE A FUNCTION TO CALCULATE ALL SUMS OF ALL SIDES
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

#DEFINE A LOOP TO GENERATE RANDOM NUMBER UNTIL FIND THE ONES THAT
#SATISFY THE CONDITIONS OF A MAGIC SQUARE
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)
        #Replace the value w in index i
        vetor.insert(i, w)
        #Eliminate the valyes already used
        x = seq.index(w)
        seq[x] =[]
    magicsquare()
print (vetor)

The result is always: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Can anyone help me built a magic square and tell what's wrong with my code?

Using Python 3.5.0




Aucun commentaire:

Enregistrer un commentaire