Search code examples
pythonrecursionmathinteger

How to make sure all combinations for each number are given in an integer composition recursion in Python?


I'm watching the MIT OCW 2008 Introduction to Computer Science and Programming, and trying to do the assignments. This is informal so there's no grading involved. There's this problem where you have to have to buy specific numbers of nuggets with packs containing 6, 9, and 20 nuggets. The aim is to learn to how to use recursions in Python. I'm solving for up to 65 nuggets.

I've written the code below. It kind of works, but the problem is, I get exactly one solution for each number I input. How do I make sure that I get all the possible combinations for each number of total nuggets?

def testtheorem(x):
    for a in range(0,15):
        for b in range(0,15):
            for c in range(0,15):
                y = 6*a + 9*b + 20*c
                if y == x and x < 66:
                    print ("For", int(x), "total;")
                    print ("6 piece can be", int(a))
                    print ("9 piece can be", int(b))
                    print ("20 piece can be", int(c))
                    testtheorem(x+1)
                    return

Solution

  • I took a quick go at this question, following the comment from gog.

    The reason that you are only getting one answer for each answer you input is that you are returning prematurely.

    Each time you find the first answer, you create a new child function and look for an answer in this number. Eventually, you reach 66 which can never have an answer. Then you start heading back, all the way to the top - to your input number.

    I drew a small example with starting at 64:

    enter image description here

    To solve your problem, you need to change at which point in the function you are calling the recursive function and when you are returning.

    Other than that, your code is on the right track.