Search code examples
pythonpython-3.xpascals-triangle

How to find a particular row of a pascals triangle in python?


Here is a snapshot of my code to write a pascal's triangle up to n rows into a file named "pascalrow.txt" after which it takes a row number as an input, and if that row is found, it reopens the file, finds the row number and displays the whole row.

It is kind of working but..as soon as I move above 9 rows then I am returned with None.

For example : I tried this and it worked perfectly, as expected. But then I tried doing this and I got freaked out. In the second picture, it can be seen that anything above row number 9, I gave as an input, It returns me none. Btw, I used files cause I didn't want to think about much how to return the row cause I was feeling real lazy. Anyway can anyone help me understand as to why its happening and the possible fix? :3

def pascal(n):
    if n==0:
        return [1]
    else:
        N = pascal(n-1)
        return [1] + [N[i] + N[i+1] for i in range(n-1)] + [1]


def pascal_triangle(n,fw):
    for i in range(n):
        fw.write(str(pascal(i))+"\n")
    fw.close()

def findRow(fr,row):
    for x in fr:
        for y in x:
            if y==str(row):
                return (x)



n=int(input("Enter the number of rows to print : "))
fw = open('pascalrow.txt', 'w')
fr = open('pascalrow.txt', 'r')
row = int(input("Enter the row to search : "))
pascal_triangle(n, fw)
a = findRow(fr,row)
print("The",row," th row is : ",a)

Solution

  • The fact that your code works at all is amazing.

    You write a stringed list to a line in a file, then read the file and look at the line character by character. So, by a miracle, you find line 8 because the first 8 you find is a character in '[1, 8, 28...]' Of course, it fails for row, e.g. 6, and anything above 9 (because '10' won't match any character.)

    So, dump all the file nonsense, and write:

    a = pascal(n)