2

I am looking for a Pascals triangle using python script

I have done till here and have no idea how to add on

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:
mjv
  • 73,152
  • 14
  • 113
  • 156
geeta
  • 31
  • 2
  • 3
  • 5
  • 2
    While not wanting to take anything away from your efforts, so far, there *was* a Pascal's Triangle Code Golf: http://stackoverflow.com/questions/1242073/code-golf-generate-pascals-triangle – pavium Nov 16 '09 at 07:12

8 Answers8

3

You would have to take the last row there is in the triangle and create the next one like this:

  1. Put a 1 at the start of the new row
  2. For every number in the last row except the last, calculate the sum of the number and its right neighbor and put it into the new row
  3. Put another 1 at the end of the new row

You could also calculate the new numbers using binomial coefficients, though that's likely a little more work to get right.

Joey
  • 344,408
  • 85
  • 689
  • 683
3

Here's the correct way to make pascal's triangle.

http://ptri1.tripod.com/

http://en.wikipedia.org/wiki/Pascal%27s_triangle

alt text

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
this. __curious_geek
  • 42,787
  • 22
  • 113
  • 137
2

Actually, the next row is crossed axis sum of last row. For example, if the last row is [1, 1], the next row would be:

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

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

So, the loop body can be like this:

tri.append(map(lambda x, y: x + y, [0] + tri[-1], tri[-1] + [0]))
redraiment
  • 111
  • 2
  • 7
1

try the scipy pascal module:

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

output:

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)
ti-
  • 1
  • 1
0

here is my solution to generate a pascal triangle

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

This is python code for Pascal's triangle:

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

For more details:https://algorithmdotcpp.blogspot.com/2021/07/print-n-rows-of-pascals-triangle-in-cpp-and-python.html

-1
 // 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);

          }
-1

C# solution:

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;
    }
Mansur Kurtov
  • 726
  • 1
  • 4
  • 12