Thursday, May 17, 2012

How to Implement Pascal Triangle in Python

My implementation of Pascal Triangle.
#!/usr/bin/env python
def pascal(n):
    if n == 0: 
        return [1]
    else:
        l1 = pascal(n-1)
        print l1
        l2 = [1]
        for i in xrange(1, len(l1)):
            l2.append(l1[i-1] + l1[i])
        l2 += [1]
        return l2

if __name__ == "__main__":
    import sys
    if len(sys.argv) != 2:
        print "Usage:", sys.argv[0], "n"
        sys.exit(1)
    pascal(int(sys.argv[1]))

No comments:

Post a Comment