0

I am trying to make a code that bruteforces magic squares

Yes! I have checked the docs, but I can't wrap my head around it.

Any idea what causes the bugs?

a   =   [0,0,0,
         0,0,0,
         0,0,0]

def test(a=a):
    for i in range(len(a)-1):
        b = a
        b.pop(i)
        if a[i] in b:
            return 0
    return 1

def win():
    global a
    if sum(a[0:3]) == sum(a[3:6]) == sum(a[6:]) == (a[0]+a[4]+a[8]) == (a[2]+a[4]+a[6]) == (a[0]+a[3]+a[6]) == (a[1]+a[4]+a[7]) == (a[2]+a[5]+a[8]):
        print(a[:3], "\n", a[3:6], "\n", a[6:])
        return True
    return False


def m(x):
    global a
    while a[x] < 100:
        if test() == 1:
            if x == 8:
                if win():
                    print(a)
                    return True
            else:
                m(x+1)
        a[x] += 1
    return False

print(m(0))

pycharm also spits out this bug report:

C:\Users\2404sebj\AppData\Local\Programs\Python\Python36-32\python.exe "C:/Uisers/2404sebj/PycharmProjects/gjør matte her/Matte.py"
Traceback (most recent call last):
  File "C:/Users/2404sebj/PycharmProjects/gjør matte her/Matte.py", line 33, in <module>
    print(m(0))
  File "C:/Users/2404sebj/PycharmProjects/gjør matte her/Matte.py", line 29, in m
    m(x+1)
  File "C:/Users/2404sebj/PycharmProjects/gjør matte her/Matte.py", line 22, in m
    while a[x] < 100:
IndexError: list index out of range

Process finished with exit code 1

May all admins, mods, mortal programers and script kiddies judge me and the contents of this post.

Bjamse
  • 333
  • 5
  • 17

1 Answers1

0

When doing b=a, b is a reference to a, not a copy:

>>> a=range(4)
>>> for i in range(len(a)-1):
...   b = a
...   b.pop(i)
...   print a,b
...
0
[1, 2, 3] [1, 2, 3]
2
[1, 3] [1, 3]
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
IndexError: pop index out of range

In order to make a real copy, use b=a[:] for example:

>>> a=range(4)
>>> for i in range(len(a)-1):
...   b = a[:]
...   b.pop(i)
...   print a,b
...
0
[0, 1, 2, 3] [1, 2, 3]
1
[0, 1, 2, 3] [0, 2, 3]
2
[0, 1, 2, 3] [0, 1, 3]
fredtantini
  • 15,966
  • 8
  • 49
  • 55