帕斯卡的三角形

时间:2009-11-16 06:51:24

标签: python

我正在寻找使用python脚本的Pascals三角形

直到这里我已经完成了,并且不知道如何添加

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:

8 个答案:

答案 0 :(得分:3)

您必须取三角形中的最后一行并创建下一行:

  1. 在新行的开头添加1
  2. 对于除最后一行之外的最后一行中的每个数字,计算数字及其右邻居的总和并将其放入新行
  3. 在新行的末尾添加另一个
  4. 您还可以使用binomial coefficients计算新数字,但这可能需要更多工作才能做到正确。

答案 1 :(得分:3)

答案 2 :(得分: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]))

答案 3 :(得分: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)

答案 4 :(得分:1)

这是帕斯卡三角形的python代码:

# python code for Pascal's Triangle
# printPascal() function for printing pascal's triangle.
def printPascal(N):
    # declaring 2 array
    arr = [1]
    temp = []

    print("pascal's triangle of", N, "Rows...")
    # calculating next rows.
    for i in range(N):
        # printing current row.
        print("rows", i+1, end=" : ")
        for j in range(len(arr)):
            print(arr[j], end=' ')
        print()

        # calculating next rows.
        temp.append(1)
        for j in range(len(arr)-1):
            temp.append(arr[j] + arr[j + 1])
        temp.append(1)

        # copy next row to current row.
        arr = temp
        # initialize temp to empty array.
        temp = []


# Driver code
N = 9
printPascal(N)

欲知更多详情:https://algorithmdotcpp.blogspot.com/2021/07/print-n-rows-of-pascals-triangle-in-cpp-and-python.html

答案 5 :(得分:0)

这是我生成pascal三角形的解决方案

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)]

答案 6 :(得分: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);

          }

答案 7 :(得分:-1)

C# 解决方案:

public IList<IList<int>> Generate(int numRows) {
        var result = new List<IList<int>>();
            var item1 = new List<int>();
            item1.Add(1);
            result.Add(item1);

            if (numRows == 1)
                return result;

            var item2 = new List<int>();
            item2.Add(1);
            item2.Add(1);
            result.Add(item2);

            if (numRows == 2)
                return result;

            var i = 2;
            while (i != numRows)
            {
                var data = result.Last().ToArray();                
                var n = data.Length;
                var item = new int[n + 1];
                item[0] = 1;
                item[n] = 1;
                for (var x = 1; x < n; x++)
                    item[x] = data[x - 1] + data[x];
                result.Add(item);i++;
            }
            
            return result;
    }