九宮格
阿新 • • 發佈:2018-01-28
list() 必須 amd __main__ utf uil end .py file 一、九宮格
1、第一種方式
1、第一種方式
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2018/1/28 17:25 # @Author : zhouyuyao # @File : nine.py # PyCharm 2017.3.2 (Community Edition) # Build #PC-173.4127.16, built on December 19, 2017 # JRE: 1.8.0_152-release-1024-b8 amd64 # JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o # Windows 10 10.0 # Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) # [MSC v.1900 64 bit (AMD64)] on win32 ‘‘‘ 九宮格 ___________ |_A_|_B_|_C_| |_D_|_E_|_F_| |_G_|_H_|_I _| 如果A取1到9,B則只能在1到9中取出A的值,C的值則從1到9中取出A和B, 每個數的取值都從1到9中取值,然後加入條件,這九個數之間存在的聯系, 其一:9個數都不能相等, 其二:行和列每三個的數相加等於15 該算法比較慢,大概需要計算10的10次冪 ‘‘‘ number = list() for i in range(1,10): number.append(i) for A in number: for B in number: for C in number: for D in number: for E in number: for F in number: for G in number: for H in number: for I in number: s = set() s.add(A) s.add(B) s.add(C) s.add(D) s.add(E) s.add(F) s.add(G) s.add(H) s.add(I) if (A+B+C) == (D+E+F) == (G+H+I) == (A+D+G) == (B+E+H) == (C+F+I) == (A+E+I) == (C+E+G) ==15 and len(s)==9: print(""" ______________ |_{0}_|_{1}_|_{2}_| |_{3}_|_{4}_|_{5}_| |_{6}_|_{7}_|_{8}_|""".format(A,B,C,D,E,F,G,H,I))
這樣的算法運行結果需要很長時間:
___________ |_2_|_7_|_6_| |_9_|_5_|_1_| |_4_|_3_|_8_| ___________ |_2_|_9_|_4_| |_7_|_5_|_3_| |_6_|_1_|_8_| ___________ |_4_|_3_|_8_| |_9_|_5_|_1_| |_2_|_7_|_6_| ___________ |_4_|_9_|_2_| |_3_|_5_|_7_| |_8_|_1_|_6_| ___________ |_6_|_1_|_8_| |_7_|_5_|_3_| |_2_|_9_|_4_| ___________ |_6_|_7_|_2_| |_1_|_5_|_9_| |_8_|_3_|_4_| ___________ |_8_|_1_|_6_| |_3_|_5_|_7_| |_4_|_9_|_2_| ___________ |_8_|_3_|_4_| |_1_|_5_|_9_| |_6_|_7_|_2_|
2、第二種方式
class NinePaper(object): def __init__(self): print(‘‘‘ ______________ |____|____|____| |____|____|____| |____|____|____| A,B,C,E,F,G,H,I,J必須是1-9,所有行和列的三個數相加都等於15 ‘‘‘) self.numbers=list() for i in range(1,10): self.numbers.append(i) print("number = {0}".format(self.numbers)) def run(self): for A in range(1,10): l1=list() l1+=self.numbers l1.remove(A) for B in l1: l2=list() l2+=l1 l2.remove(B) for C in l2: l3=list() l3+=l2 l3.remove(C) for D in l3: l4=list() l4+=l3 l4.remove(D) for E in l4: l5=list() l5+=l4 l5.remove(E) for F in l5: l6=list() l6+=l5 l6.remove(F) for G in l6: l7=list() l7+=l6 l7.remove(G) for H in l7: l8=list() l8+=l7 l8.remove(H) for I in l8: if A+B+C==E+F+D==H+I+G==A+E+I==B+E+H==C+G+E==A+E+I==C+F+I==15: print(‘‘‘ ___________ |_{0}_|_{1}_|_{2}_| |_{3}_|_{4}_|_{5}_| |_{6}_|_{7}_|_{8}_| ‘‘‘.format(A,B,C,D,E,F,G,H,I)) # ABC # DEF # GHI def main(): ninePaper=NinePaper() ninePaper.run() if __name__ == ‘__main__‘: main()
九宮格