I wanted to make a magic square, where I put 9 numbers, and the sum of them has to result 15 (horizontal and vertical)

Asked

Viewed 534 times

-1

Good evening guys, I have this matrix:

inserir a descrição da imagem aqui

I need the matrix numbers summed all 15.
Both vertical and horizontal..

Code:

import numpy as np
import random

from tabulate import tabulate 

a = [1,2,3,4,5,6,7,8,9]

random.shuffle(a)

data = np.reshape(a, (3, 3))

soma_horizontal = []
for lista in data:
    soma_horizontal.append(sum(lista))
soma_vertical = []
for x in range(len(data)):
    soma = 0
    for lista in data:
        soma += lista[x]
    soma_vertical.append(soma)
indice = 0
for lista in data:
    lista.extend(['\u2192', soma_horizontal[indice]])
    indice += 1
setas_cima = ['\u2191'] * 3
data = [soma_vertical] + [setas_cima] + data
print(tabulate(data, tablefmt="grid", stralign='center', numalign='center'))

The program running on repl:

https://repl.it/@William33/UnwillingPopularAndeancondor-3

  • 2

    Start by correcting the indentation of the question, which is not correct nor equal to the code you have in repl. Then you’re basically looking for a magic square. You can find a solution using combinations

  • Good evening @Isac I changed the name of the question.. I wonder if you could help me??

  • I copied the code that’s in the rpli-it, but don’t do this anymore: Python identation is not optional, what you had pasted there was a command soup, not a Python script. Use the button { } to format your code instead of trying to manually ident in editing here.

1 answer

0

Face your doubt is not very clear if you want a solution to this magic square (which is unlikely), or an algorithm that would solve such a case.

The algorithm shown is as follows

Tips for solving the 3x3 magic square:

  1. The total you want to get in all directions should be divided by 3. Which will result in the number to be placed in the center of the square.
  2. The numbers to be placed in the corners should be even if the center is odd, or vice versa.
  3. The last number to be placed should be the center plus 4.

These rules apply only if the numbers are multiples of 3. Ex: 15, 18, 21, 24, 27, 30 etc.

From this just implement it.

References

Browser other questions tagged

You are not signed in. Login or sign up in order to post.