跑不动啊(
本帖最后由 半灵桑 于 2023-11-19 17:36 编辑我最近闲着没事,整了个十阶幻方生成器:
#made with python3.10
import random
print('生成中……\n')
while True:
x = []
for count in range(10):
x.append([])
for count in range(10):
x.append(random.randint(-9999999999, 1000000000))
x.append(random.randint(-9999999999, 1000000000))
x.append(random.randint(-9999999999, 1000000000))
x.append(random.randint(-9999999999, 1000000000))
x.append(random.randint(-9999999999, 1000000000))
x.append(random.randint(-9999999999, 1000000000))
x.append(random.randint(-9999999999, 1000000000))
x.append(random.randint(-9999999999, 1000000000))
x.append(random.randint(-9999999999, 1000000000))
x.append(random.randint(-9999999999, 1000000000))
a = bool(sum(x) == sum(x) == sum(x)== sum(x) == sum(x) \
== sum(x) == sum(x) == sum(x)== sum(x) == sum(x))
b = bool(x + x + x + x + x + x + x + x + x + x == \
x + x + x + x + x + x + x + x + x + x == \
x + x + x + x + x + x + x + x + x + x == \
x + x + x + x + x + x + x + x + x + x == \
x + x + x + x + x + x + x + x + x + x == \
x + x + x + x + x + x + x + x + x + x == \
x + x + x + x + x + x + x + x + x + x == \
x + x + x + x + x + x + x + x + x + x == \
x + x + x + x + x + x + x + x + x + x == \
x + x + x + x + x + x + x + x + x + x )
c = bool(x + x + x + x + x + x + x + x + x + x == \
x + x + x + x + x + x + x + x + x + x)
d = bool(x != x != x != x != x != x != x != x != x != \
x != x != x != x != x != x != x != x != x != \
x != x != x != x != x != x != x != x != x != \
x != x != x != x != x != x != x != x != x != \
x != x != x != x != x != x != x != x != x != \
x != x != x != x != x != x != x != x != x != \
x != x != x != x != x != x != x != x != x != \
x != x != x != x != x != x != x != x != x != \
x != x != x != x != x != x != x != x != x != \
x != x != x != x != x != x != x != x != x != \
x != x != x != x != x != x != x != x != x != x)
if a == b == c == d == True :
break
print('生成完毕!\n')
print(*x)
print(*x)
print(*x)
print(*x)
print(*x)
print(*x)
print(*x)
print(*x)
print(*x)
print(*x)
跑不动,根本跑不动啊(
明明没有错误嘛( 这个问题的原因在于生成器中的循环条件不满足退出条件。在while循环中,虽然有a、b、c三个条件来判断是否生成了十阶幻方,但是循环体内并没有对x进行重新生成。由于循环条件一直为True,所以程序会一直在while循环中运行,导致看起来“跑不动”。解决方法是在while循环内重新生成x。以下是修改后的代码:
import random
while True:
x = []
for count in range(10):
x.append()
a = bool(all(sum(row) == sum(x) for row in x))
b = bool(all(sum(row) == sum(x) for row in zip(*x)))
c = bool(sum(x[ i][ i] for i in range(10)) == sum(x[ i] for i in range(10)))
if a and b and c:
break
print('生成完毕!\n')
for row in x:
print(*row)
这样修改后的代码会在满足条件时退出循环,并正确地生成十阶幻方。 看起来你的代码陷入了一个无限循环的情况。我注意到在你的代码中,你使用了一个无限循环 while True,并且在循环内部使用了 if a == b == c == True 来判断是否退出循环。问题可能出在这里,导致条件无法满足从而无法跳出循环。
另外,你可以考虑对生成幻方的部分进行封装,尽量避免重复的代码。
如果你想要我帮你修改代码,请告诉我你期望的行为是什么样的。你是希望生成一个满足幻方条件的十阶幻方吗? 啥玩意啊(
页:
[1]