Click here to Skip to main content
15,667,355 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to write the Hosoya's Triangle program in Python that print out the following result if we need 5 levels. The function should be recursive and follow the mentioned structure:
def computeTriangle(levels):
def printTriangle(triangle, levels):
def main():

The expected output should be exactly like this:

1  1

2  1  2

3  2   2  3

5  3  4  3  5

What I have tried:

I have tried this code but the output is wrong:
def computeTriangle(levels):
    if levels == 0:
        return []
    elif levels == 1:
        return [[1]]
        triangle = computeTriangle(levels-1)
        row = [1]
        for i in range(1, levels-1):
            row.append(triangle[-1][i-1] + triangle[-1][i])
        return triangle

# Function to print the Hosoya Triangle
def printTriangle(triangle, levels):
    for i in range(levels):
        row = [str(triangle[i][j]) for j in range(i+1)]
        print("  ".join(row))

# Main function
def main():
    # Compute and print the Hosoya Triangle
    levels = int(input("Enter the number of levels of the Hosoya Triangle to compute: "))
    triangle = computeTriangle(levels)
    printTriangle(triangle, levels)

if __name__ == '__main__':
Updated 22-Mar-23 20:00pm

1 solution

Have a look here: Hosoya's Triangle - GeeksforGeeks[^] - it explains what you have to do pretty well, and provides code samples - I'd suggest you largely ignore them as you won't learn much unless you do it yourself.
Share this answer
Richard MacCutchan 23-Mar-23 5:59am    
Should there be a link at "here"?
OriginalGriff 24-Mar-23 4:09am    
Yep. Dunno what happened there, Total Brain Failure, I assume.

Thank Chrome for Searchable Page History!
Maria61 23-Mar-23 8:18am    
Is there any like or somethings to access the solution?
OriginalGriff 24-Mar-23 4:09am    
Sorry about that - I have covid ATM so my brain appears to have failed. The links in there now.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900