Frank
Frank

Reputation: 349

Return a specific line of pascals triangle recursivly with python

The code that I'm writing should have outputs as follows:

>>> pascalLine(0)
[1]
>>> pascalLine(1)
[1, 1]
>>> pascalLine(2)
[1, 2, 1]
>>> pascalLine(3)
[1, 3, 3, 1]

I have the code doing this through iteration, but I need it done recursively, and I'm lost in trying to do so. Here's the code that I have:

def pascalLine(n):
    value = 1
    new_row = [value]
    if n == 0:
        return new_row
    else:
        for i in range(n):
            value = int((value * (n-i)) / (i+1))
            new_row.append(value)
        return new_row

Any help welcomed! Thanks!

Upvotes: 0

Views: 173

Answers (1)

Simon Fromme
Simon Fromme

Reputation: 3174

How about the following?

from operator import add

def pascal_line(n):
    if n < 2:
        return [1]*(n+1)
    l = pascal_line(n-1)
    return [1] + map(add, l[1:], l[:-1]) + [1]

Upvotes: 2

Related Questions