杨辉三角,是二项式系数在三角形中的一种几何排列。
使用shell 和python 打印杨辉三角,比较差异
shell:
[email protected]:~# cat triangles.sh #!/bin/bash # Author: xieshengsen # 打印数学杨辉三角 if (test -z $1) ; then read -p "Input Max Lines:" Max else Max=$1 fi i=1 while [ $i -le $Max ] do j=1 while [ $j -le $i ] do f=$[i-1] g=$[j-1] if [ $j -eq $i ] || [ $j -eq 1 ]; then declare SUM_${i}_$j=1 else declare A=$[SUM_${f}_$j] declare B=$[SUM_${f}_$g] declare SUM_${i}_$j=`expr $A + $B` fi echo -en $[SUM_${i}_$j]" " let j++ done echo let i++ done [email protected]:~# [email protected]:~# . triangles.sh 10 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 [email protected]:~#
python:
方法一:
[[email protected] ~]# cat triangle_v1.py #!/usr/bin/env python # -*- coding: utf-8 -*- # Author:xieshengsen # 使用函数打印杨辉三角 """ 第一次循环执行 yield L,输出【1】 第二次循环执行 yield L 之后的语句 L.append(0)后,L =【1,0】,再执行后面的语句 L = [L[i - 1] + L[i] for i in range(len(L))] 此时L =【1,1】(i=0时 L[- 1] + L[0]为1,i =1时 L[0] + L[1]为1)直到再次遇到yield L语句,输出【1,1】 第三次循环执行 yield L 之后的语句 L.append(0)后,L =【1,1,0】,再执行后面的语句 L = [L[i - 1] + L[i] for i in range(len(L))] 此时L =【1,2,1】(i=0时 L[- 1] + L[0]为1,i =1时 L[0] + L[1]为2,i=2时,L[1] + L[2]为1)直到再次遇到yield L语句,输出【1,2,1】 """ def triangles(n): L = [1] while True: yield L L.append(0) L = [L[ i - 1 ] + L[i] for i in range(len(L))] if len(L) > n: break m = triangles(10) for i in m: print (i) [[email protected] ~]# python triangle_v1.py [1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] [1, 5, 10, 10, 5, 1] [1, 6, 15, 20, 15, 6, 1] [1, 7, 21, 35, 35, 21, 7, 1] [1, 8, 28, 56, 70, 56, 28, 8, 1] [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] [[email protected]er01 ~]#
方法二:
[[email protected] ~]# cat triangle_v2.py #!/usr/bin/env python # -*- coding: utf-8 -*- # Author:xieshengsen """ 规律: 1、每行开始和结尾都是1 2、每行的数都是从两边都中间逐步变大(除第一、二行外) 3、从第三行开始,每个数都等于上方两个数之和 4、第n行有n个项 5、每行的数字之和为2的n-1次方(上期写的是n-2) """ def triangles(n): L = [1] while True: yield L L = [L[x]+L[x+1] for x in range(len(L)-1)] L.insert(0,1) L.append(1) if len(L) > n: break a = triangles(10) for i in a: print (i) [[email protected] ~]# python triangle_v2.py [1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] [1, 5, 10, 10, 5, 1] [1, 6, 15, 20, 15, 6, 1] [1, 7, 21, 35, 35, 21, 7, 1] [1, 8, 28, 56, 70, 56, 28, 8, 1] [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] [[email protected] ~]#
时间: 2024-10-02 00:22:44