九宫格,每行每列及对角之和是15
1至9九个数字,横竖都有3个格,思考怎么使每行、每列和对角线上的三数之和都等于15
# !/usr/bin/env python # -*- coding:utf-8 -*- # Author:Hiuhung Wan list0 = [] # 除了中间那个数是5,周围的是别的数 for i in range(1, 10): if i == 5: continue list0.append(i) ''' 假设第一个数是x,第二个是y,那么这9个数应该是: x y 15-x-y 20-2x-y 5 2x+y-10 x+y-5 10-y 10-x ''' count = 0 for 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 = 7 2 7 6 9 5 1 4 3 8 第2种情况:x = 2, y = 9 2 9 4 7 5 3 6 1 8 第3种情况:x = 4, y = 3 4 3 8 9 5 1 2 7 6 第4种情况:x = 4, y = 9 4 9 2 3 5 7 8 1 6 第5种情况:x = 6, y = 1 6 1 8 7 5 3 2 9 4 第6种情况:x = 6, y = 7 6 7 2 1 5 9 8 3 4 第7种情况:x = 8, y = 1 8 1 6 3 5 7 4 9 2 第8种情况:x = 8, y = 3 8 3 4 1 5 9 6 7 2 Process finished with exit code 0