2009-11-16 100 views
1

我使用python腳本帕斯卡三角

我已經做了,直到這裏,而且不知道如何在

numstr= raw_input("please enter the height:") 
height = int() 

tri = [] 

row1 = [1] 
row2 = [1, 1] 
tri.append(row1) 
tri.append(row2) 

while len(tri) < height: 
+2

雖然不希望採取任何從你的努力了,到目前爲止,有*是*一個楊輝三角的代碼高爾夫球:http://stackoverflow.com/questions/1242073/code - 高爾夫球-生成帕斯卡三角 – pavium 2009-11-16 07:12:46

回答

3

添加你將不得不採取的最後一排有在尋找楊輝三角形三角形,創造下一個這樣的:

  1. 將一個1在新行
  2. 開始對於每一個號碼的最後一排,除了最後一個,計算數量和其右鄰的總和,並把它放入新行
  3. 換個1在新行

你也可以計算出使用binomial coefficients新號碼的結束,儘管這可能是更多的工作得到正確的。

2

其實,下一行越過最後一排的軸總和。例如,如果最後一行是[1,1],下一行是:

 [1, 1] 
+ [1, 1] 
----------- 
= [1, 2, 1] 

    [1, 2, 1] 
+ [1, 2, 1] 
-------------- 
= [1, 3, 3, 1] 

因此,循環體可以是這樣的:

tri.append(map(lambda x, y: x + y, [0] + tri[-1], tri[-1] + [0])) 
0

這裏是我的解決方案產生一個帕斯卡三角

def factorial(x): 

    return 1 if x == 0 else x * factorial(x - 1) 

def triangle(n): 

    return [[factorial(i)/(factorial(j) * factorial(i - j)) for j in range(i + 1)] for i in range(n)] 
1

嘗試scipy pascal模塊:

from scipy.linalg import pascal 
pascal(6, kind='lower') 

輸出:

array([[ 1, 0, 0, 0, 0, 0], 
    [ 1, 1, 0, 0, 0, 0], 
    [ 1, 2, 1, 0, 0, 0], 
    [ 1, 3, 3, 1, 0, 0], 
    [ 1, 4, 6, 4, 1, 0], 
    [ 1, 5, 10, 10, 5, 1]], dtype=uint64) 
0
// C++ code for pascal triangle 
#include<stdio.h> 
#include<ctype.h> 
#include<conio.h> 
#include<time.h> 
#include<stdlib.h> 

long unsigned int Factorial(long unsigned int Number) 
{ 
long unsigned int Fact=0; 
if (Number==0) 
    return (long unsigned int) 1; 
    else 

     { Fact=Number*Factorial(Number-1); 
     return Fact; 
     } 

    } 


    long unsigned int Combination(long unsigned int num1,long unsigned int num2) 
    { 
    long unsigned int Comb,num3; 
    long unsigned int Factor1, Factor2,Factor3; 
    Factor1=Factorial(num1); 
    Factor2=Factorial(num2); 
    num3=num1-num2; 
    Factor3=Factorial(num3); 
    Comb=Factor1/(Factor2*Factor3); 

    return(Comb); 

    } 

    int main() 
    { 

    long unsigned int i,j,Num=0; 
    long unsigned int **Matrix; 
    clrscr(); 
    printf(" %d\n " ,sizeof(long unsigned int)); 
    printf("Enter Index of Square Matrix Num =: "); 
    scanf ("%lu",&Num); 



    Matrix=(long unsigned int **) malloc(Num*Num*sizeof(long unsigned int *)); 

    for(i=0;i<Num;i++) 
    { for (j=0;j<Num;j++) 
    { *(*(Matrix+i)+j)=0; 
     } 
    } 

    for(i=0;i<Num;i++) 
{ for(j=0;j<=i;j++) 
    { printf(" %lu " , *(*(Matrix+i)+j)); } 

    printf("\n"); 

    } 


    for(i=0;i<Num;i=i+1) 
    { 
    for(j=0;j<=i;j=j+1) 
    { 


    *(*(Matrix+i)+j)=Combination(i,j); 

     } 
     printf("\n"); 
    } 

     for(i=0;i<Num;i++) 
     { 
      for(j=0;j<=i;j++) 
     { 

    // printf(" \n %lu %lu \n",i,j); 
    printf(" %lu ",*(*(Matrix+i)+j)); 

    } 
    printf("\n"); 
    } 





     getch(); 
     return(0); 

      }