tonyabracadabra
tonyabracadabra

Reputation: 319

How can I improve this code in python?

def generate(self, numRows):
        if numRows == 0:
            return []
        if numRows == 1:
            return [[1],]
        a = [[0]*num for num in xrange(1, numRows+1)]
        a[0] = [1]
        for i in xrange(1, numRows):
            a[i][0], a[i][i] = 1, 1
            for j in xrange(1, len(a[i])-1):
                a[i][j] = a[i-1][j] + a[i-1][j-1]
        return a

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5, Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

I am a programming newbie and try practicing my coding ability. I hope you could first improve my code on the basis of my code other than simply rewrite it. Also, it is also welcomed that you to provide your own code in a neater way.

Thank you so much!

Upvotes: 0

Views: 74

Answers (1)

Alex Pertsev
Alex Pertsev

Reputation: 948

You can avoid using multidimensional array and a lot of indexes by separating main function:

def _generate_row (row_number, prev_row):
    if row_number == 1:
        return [1]

    row_data = [0] + prev_row + [0]
    return [sum(row_data[a:a+2]) for a in xrange(0, len(row_data)-1)]

def generate(num_rows):
    prev_row = None
    for i in xrange(1, num_rows+1):
        prev_row = _generate_row(i, prev_row)
        yield prev_row

print list(generate(5))

Next step you can optimize row generation - it is symmetrical so you don't need to go through xrange(len(a[i])-1), only half of it.

And use snake_case - it is a python! =)

Upvotes: 1

Related Questions