[Python] A more efficient solution for solving this matrix puzzle?

Discussão em 'Python' iniciado por Stack, Abril 29, 2025.

  1. Stack

    Stack Membro Participativo

    Find the 3x3 matrix, M, whose rows, columns and diagonals add up to 15. Condition: you must use every number from 1-9.

    I'm not very clever, so I just tried this brute force method:

    def solve_999():
    for a in range(1, 10):
    for b in range(1, 10):
    for c in range(1, 10):
    for d in range(1, 10):
    for e in range(1, 10):
    for f in range(1, 10):
    for g in range(1, 10):
    for h in range(1, 10):
    for i in range(1, 10):
    if (a+b+c == d+e+f == g+h+i == a+d+g == b+e+h == c+f+i == a+e+i == c+e+g == 15):
    if check_unique([a, b, c, d, e, f, g, h, i]):
    print(a, b, c)
    print(d, e, f)
    print(g, h, i)
    return


    def check_unique(L):
    d = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0}
    for letter in L:
    d[letter] += 1
    if d[letter] > 1:
    return False
    return True


    It works, but it isn't very efficient. Can anyone help me find a more efficient solution?

    Continue reading...

Compartilhe esta Página