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