Alon
Alon

Reputation: 1

How do I remove the extra zero in the end of each line of the output?

This code generates a pascal triangle:

import pprint

def nextRow(cRow):
    cRow.append(0)
    return [cRow[m - 1] + cRow[m + 1] for m in range(len(cRow) - 1)]

def Pascal(n):
    row = [0, 0, 0, 0, 1, 0, 0, 0, 0]
    l = []

    for h in range(n):
        l.append(row)
        row = nextRow(row)

    return l

pprint.pprint(Pascal(5))

I am trying to remove the extra zeros without just removing them in the end of the code:

Output:

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

Desired Output:

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

Upvotes: 0

Views: 69

Answers (1)

lauriane.g
lauriane.g

Reputation: 337

You can save in l the row calculated without the last element with l.append(row[:-1]) instead of l.append(row) in the Pascal function.

import pprint


def nextRow(cRow):
    cRow.append(0)
    return [cRow[m - 1] + cRow[m + 1] for m in range(len(cRow) - 1)]


def Pascal(n):
    row = [0, 0, 0, 0, 1, 0, 0, 0, 0]
    l = []

    for h in range(n):
        l.append(row[:-1])
        row = nextRow(row)

    return l


pprint.pprint(Pascal(5))

Upvotes: 1

Related Questions