题目描述:
题目:将1-8几个数字填写下边表格,要求每一列数字比右边大,每一行数字比下边大,有几种填法?
代码
count=0 for a in range(1,9): for b in range(1, 9): for c in range(1, 9): for d in range(1, 9): for e in range(1, 9): for f in range(1, 9): for g in range(1, 9): for h in range(1, 9): if (a!=b and a!=c and a!=d and a!=e and a!=f and a!=g and a!=h and b!=c and b!=d and b!=e and b!=f and b!=g and b!=h and c != d and c != e and c != f and c != g and c != h and d != e and d != f and d != g and d != h and e != f and e != g and e != h and f != g and f != h and g!=f ): if ((a>b) and (b>c) and (c>d)and(e>f)and(f>g)and(g>h) and (a>e)and(b>f) and (c>g)and(d>h)): print(a,b,c,d) print(e,f,g,h) count=count+1 print(count)
运行结果
编程思想:
a | b | c | d |
---|---|---|---|
e | f | g | h |
每一个字母表示都有8种可能所以所以8层循环,遍历出所有结果:
for a in range(1,9): for b in range(1, 9): for c in range(1, 9): for d in range(1, 9): for e in range(1, 9): for f in range(1, 9): for g in range(1, 9): for h in range(1, 9):
但是每一个字母表示的值并不相同,换句话说,如果a取1的话,那么b,c,d,e,f,g,h都不能取1。后面的取值一样。
if (a!=b and a!=c and a!=d and a!=e and a!=f and a!=g and a!=h and b!=c and b!=d and b!=e and b!=f and b!=g and b!=h and c != d and c != e and c != f and c != g and c != h and d != e and d != f and d != g and d != h and e != f and e != g and e != h and f != g and f != h and g!=f ):
筛选出左边数值大于右边,上边大于下边
(a>b) and (b>c) and (c>d)and(e>f)and(f>g)and(g>h) #左边大于右边 and (a>e)and(b>f) and (c>g)and(d>h)#上边大于下边