Question

I'm taking my first programming class and I'm a little lost as to how to finish off this code. I'm trying to construct a Pascal's triangle with n rows. I got the lines to print, each on their own row, but I'm having trouble formatting them into a triangle. Below is what I've got so far. Thanks in advance!

def print_pascal_triangle(n):
    # problem0_pascal.pascal_triangle(n) provides the rows in a list of lists         
    rows = problem0_pascal.pascal_triangle(n)


    # Now print the rows, one by one, CALLING  digits_in_biggest_number
    # and  print_row  as appropriate.
    for k in range(len(rows)):
        spaces = digits_in_biggest_number(rows[k])
        print_row(rows[k], spaces)

def digits_in_biggest_number(row):
    """
    Returns the number of digits in the biggest number in the
    given list of numbers.
    """

    largest = 0
    for k in range(len(row)):
        if row[k] > largest:
            largest = row[k]

    digits = int(math.log10(largest)) + 1
    return digits



def print_row(numbers, spaces_per_number):
    """
    Prints the numbers in the given list of numbers.
    Each number is printed using the given number of spaces, except
    for the first number (1) which is printed with a single space.
    """
    line = ''
    for k in range(len(numbers)):
        line += str(numbers[k]) + (spaces_per_number * ' ')

    print(line)
Was it helpful?

Solution

Since you're trying to learn, I won't give you a solution, but will make some suggestions...

In print_row, consider what your objective is. You have a docstring saying you're printing the number "using the given number of spaces". Is that what you want?

Think about it. You want this:

        1
       1 1
      1 2 1
     1 3 3 1
      ...

In all the rows, you want them centered, based on the longest row (the last one, right?). For the last row you don't need any indentation, in other rows, you want them indented. So maybe you have a function that figures out the longest line and then figure out the length of other lines and how much to indent, based on the difference in length.

If you're not using python in interactive mode (or using IDLE), consider doing that, so you can explore with the functions you have. With that, you can then run the functions individually, to see what they are doing.

For example, you can type in your functions, and then enter:

print_row([1, 2, 1], 10)

And see if the output matches what you expect. You can do this on each function to help verify what you expect for different inputs.

A more advanced technique, BTW, is to do Test Driven Development, where you write tests that call functions and verify they do what is expected. If you want to learn about that more Google on TDD and Python for some cool info on coding.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top