0

I'm working on a homework assignment that asks me to create a Pascal Triangle using a recursive function. Below is what I've managed so far along with what I was given to work with. I'm quite new to Python and programming so I've got no idea where to head from here, any help would be appreciated!

def combination(n, k):
    print((n - 1) / (k - 1)) + ((n - 1) / k)

def pascals_triangle(rows):
    for row in range(rows):
        answer = ""
        for column in range(row + 1):
            answer = answer + combination(row, column) + "\t"
        print(answer)

pascals_triangle(5)
4
  • What exactly is your problem that you cannot resolve, at this point? Commented May 4, 2015 at 17:25
  • it looks like you expect combination(row, column) to return a string, but it just prints to the terminal and then returns None Commented May 4, 2015 at 17:28
  • @Donkey Kong I'm getting a ZeroDivisionError and I'm not sure why. Commented May 4, 2015 at 17:28
  • @RialJohnson you're getting divide by zero because range(n) iterates from 0 to n-1. Commented May 4, 2015 at 17:30

1 Answer 1

3

You are not, in fact, using recursion at all in your answer. I think you are trying to code the formula nCk = (n-1)C(k-1) + (n-1)Ck. You need, therefore, to call combination from within itself (with a guard for the "end" conditions: nC0 = nCn = 1):

def combination(n, k):
    if k == 0 or k == n:
        return 1
    return combination(n - 1, k - 1) + combination(n - 1, k)

def pascals_triangle(rows):
    for row in range( rows):
        answer = ""
        for column in range( row + 1):
            answer = answer + str(combination(row, column)) + "\t"
        print(answer)

pascals_triangle(5)

Output:

1   
1   1   
1   2   1   
1   3   3   1   
1   4   6   4   1

Note that this is a spectacularly inefficient way of doing this: you are calling combination many, many times with the same arguments each time you get a binomial coefficient. You might consider caching the coefficients you find as you go along.

The other problem with your code is that your combination function wasn't actually returning anything, it was simply printing a value and exiting (returning None).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this worked perfectly for what I needed! After doing a lot more reading about recursion (I'm a student and very new to Python) I was able to come close to the solution you gave, but your explanation definitely helped a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.