1至9九个数字,横竖都有3个格,思考怎么使每行、每列和对角线上的三数之和都等于15
# !/usr/bin/env python# -*- coding:utf-8 -*-# Author:Hiuhung Wanlist0 = [] # 除了中间那个数是5,周围的是别的数for i in range(1, 10): if i == 5: continue list0.append(i)'''假设第一个数是x,第二个是y,那么这9个数应该是:x y 15-x-y20-2x-y 5 2x+y-10x+y-5 10-y 10-x '''count = 0for x in list0: list_temp = list0[:] # 复制 list_temp.remove(x) # 去除x后的列表 for y in list_temp: set0 = set([x, y, 15 - x - y, 20 - 2 * x - y, 5, 2 * x + y - 10, x + y - 5, 10 - y, 10 - x]) if (15-x-y) in list0 and (20-2*x-y) in list0 and (2*x+y-10) in list0 and (x+y-5) in list0 and (10-y) in list0 and (10-x) in list0 and len(set0) == 9: count += 1 print("第%s种情况:x = %s, y = %s" % (count, x, y)) print(x, y, 15 - x - y) print(20 - 2 * x - y, 5, 2 * x + y - 10) print(x + y - 5, 10 - y, 10 - x)
运行结果如下:
第1种情况:x = 2, y = 72 7 69 5 14 3 8第2种情况:x = 2, y = 92 9 47 5 36 1 8第3种情况:x = 4, y = 34 3 89 5 12 7 6第4种情况:x = 4, y = 94 9 23 5 78 1 6第5种情况:x = 6, y = 16 1 87 5 32 9 4第6种情况:x = 6, y = 76 7 21 5 98 3 4第7种情况:x = 8, y = 18 1 63 5 74 9 2第8种情况:x = 8, y = 38 3 41 5 96 7 2Process finished with exit code 0