Search code examples
pythonpascals-triangle

Programming a basic Pascal Triangle in Python


I'm 4th week into programming(python) and it's getting serious. Our professor asked us to programme a field in python, existing of fields of increasing length for the representation of the triangle of Pascal:

b = [[1],[1,1],[1,2,1],[1,3,3,1],...]

We are just beginning with basics of coding, meaning we are not allowed to use any add-ons like functions or the like. For the most, we worked with while- and for-loops, and with the if statements.

I would really need help to get started here. I began like this:

n = int(input("Number of layers="))
b = [[1]]

for layer in range(0,n):
     for row in range(0,n):

and here is the point where I am stuck.

I see the structure in the way the triangle of pascale is presented: As far as I can see, the length of the fields inside of b grows by 1 with each additional layer. I had an idea, that I could check for outside elements, because they always keep the value "1". I just don't find a solution, how to do that..

1
11
121
1331
14641
..
..

However, I just cannot find a starting point from here on to keep going.. Maybe someone can help me out.. Please keep in mind, that I have to keep it to while- , and for- loops. That is it. No extra functions or something.


Solution

  • Im sure there are really nice solution out there but if you are looking for something that is on beginer level check out this

    n = 5 #depth of the pascal tree
    
    pascal = []
    
    for x in range(n):
    
        if x == 0:
            help_list = [1]        
            pascal.append(help_list)
            continue
        if x==1:
            help_list = [1,1]       
            pascal.append(help_list)
            continue
    
        help_list = [l for l in range(x+1)] #this will just initialize list so you can add to it
        for y in range(1,x):
            help_list[0] = 1
            help_list[x] = 1 
            help_list[y] = pascal[x-1][y] + pascal[x-1][y-1]        
    
        pascal.append(help_list)
    
    print(pascal)