So I've been working on a generator for Pascal's triangle in Python. Now, I wouldn't call myself a Python god, so my program is a lot longer than the very confusing ones on the internet. It's more of a logical approach to creating the triangle.
Here's the program:
def double_chunker(lst): leng = len(lst) for i in range(leng): if i == 0: yield [lst] elif i == 1: yield [lst, lst] elif i == leng: yield [lst[-1]] else: yield [lst[i-1], lst[i]] yield [lst[-1]] def chunk_adder(lst): for i in lst: if len(i) == 1: yield i else: yield sum(i) def pascal_next(lst): return list(chunk_adder(double_chunker(lst))) def pascal_triangle(rows): end = [] for i in range(rows): end.append(pascal_next(end[-1])) return end
A simple go-through of how it works:
double_chunker()splits up a row of Pascal's triangle into the pairs of numbers you would use when adding up to determine the numbers in the next row. This algorithm is little jerry-rigged - I had to add some special exceptions for some numbers on the end of the row to make it work properly.
chunk_adder()adds together a list of chunks generated by
double_chunkerto determine the next row in the Pascal sequence.
chunk_adder()to, when given one row in Pascal's triangle, determine the next row in the triangle.
pascal_triangle()iteratively creates rows of Pascal's triangle using
So, here are some of my questions:
Is there anything in my program that seems redundant, repetitive, or can be shortened?
Is there any better code practices I should be employing and am not?
And obviously, as always, feel free to provide any other feedback you may have. Thanks in advance!