九宫格程序
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @date: 2018/4/10 19:36
# @Author: netlogger
# @File: squared.py
"""
九宫格
1-9
-------------
| A | B | C |
| D | E | F |
| G | H | I |
-------------
所有的横竖斜线加起来都等于15
"""
number = list()
for i in range(1, 10):
number.append(i)
# 使用for循环,拷贝列表移除循环中获得的元素,最后把横竖斜线加起来都等于15的可能的数字计算出来
count = 1
for A in number:
a = number.copy()
a.remove(A)
for B in a:
b = a.copy()
b.remove(B)
for C in b:
c = b.copy()
c.remove(C)
for D in c:
d = c.copy()
d.remove(D)
for E in d:
e = d.copy()
e.remove(E)
for F in e:
f = e.copy()
f.remove(F)
for G in f:
g = f.copy()
g.remove(G)
for H in g:
h = g.copy()
h.remove(H)
for I in h:
if (A+B+C == D+E+F == G+H+I == A+D+G == B+E+H == C+F+I == A+E+I == G+E+C == 15):
print('''
第{9}种例子
-------------
| {0} | {1} | {2} |
| {3} | {4} | {5} |
| {6} | {7} | {8} |
-------------'''.format(A,B,C,D,E,F,G,H,I,count))
count += 1
程序运行结果如下:
第1种例子
-------------
| 2 | 7 | 6 |
| 9 | 5 | 1 |
| 4 | 3 | 8 |
-------------
第2种例子
-------------
| 2 | 9 | 4 |
| 7 | 5 | 3 |
| 6 | 1 | 8 |
-------------
第3种例子
-------------
| 4 | 3 | 8 |
| 9 | 5 | 1 |
| 2 | 7 | 6 |
-------------
第4种例子
-------------
| 4 | 9 | 2 |
| 3 | 5 | 7 |
| 8 | 1 | 6 |
-------------
第5种例子
-------------
| 6 | 1 | 8 |
| 7 | 5 | 3 |
| 2 | 9 | 4 |
-------------
第6种例子
-------------
| 6 | 7 | 2 |
| 1 | 5 | 9 |
| 8 | 3 | 4 |
-------------
第7种例子
-------------
| 8 | 1 | 6 |
| 3 | 5 | 7 |
| 4 | 9 | 2 |
-------------
第8种例子
-------------
| 8 | 3 | 4 |
| 1 | 5 | 9 |
| 6 | 7 | 2 |
-------------