How to find a particular row of a pascals triangle in python?
<p>Here is a snapshot of my code to write a pascal's triangle up to n rows into a file named "<strong>pascalrow.txt</strong>" 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.</p>

<p>It is kind of working but..as soon as I <strong>move above 9 rows then I am returned with None</strong>.</p>

<p>For example : I <a href="http://i.stack.imgur.com/wfMHk.jpg" rel="nofollow">tried this</a> and it worked perfectly, as expected.
But then <a href="http://i.stack.imgur.com/aFjkw.jpg" rel="nofollow">I tried doing this</a> 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</p>

<pre><code>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)
</code></pre>

<p>The fact that your code works at all is amazing. </p>

<p>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.)</p>

<p>So, dump all the file nonsense, and write:</p>

<pre><code>a = pascal(n)
</code></pre>

python python-3.x pascals-triangle