Python:魔术广场暴力和错误

时间:2018-01-05 08:20:21

标签: python error-handling

我正在尝试创建一个强大的代码 magic squares

是的!我检查了文档,但我无法绕过它。

知道导致错误的原因吗?

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也吐出了这个错误报告:

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

愿所有管理员,模组,凡人程序员和脚本小子都评判我和这篇文章的内容。

1 个答案:

答案 0 :(得分:0)

执行b=a时,b是对a的引用,而不是副本:

>>> 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

要制作真实副本,请使用b=a[:]例如:

>>> 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]