0
votes

So, I'm doing a Coursera course about discrete mathematics and one of the quizzes there had us implement a program with this instructions:

Develop a Python method change(amount) that for any integer amount in the range from 24 to 1000 returns a list consisting of numbers 5 and 7 only, such that their sum is equal to amount. For example, change(28) may return [7, 7, 7, 7], while change(49) may return [7, 7, 7, 7, 7, 7, 7] or [5, 5, 5, 5, 5, 5, 5, 7, 7] or [7, 5, 5, 5, 5, 5, 5, 5, 7].

And this is what the code I've done so far.

def change(amount):
    assert(24 <= amount <= 1000)
    coins = []

    if amount == 24:
        return coins + [7, 7, 5, 5]

    if amount == 25:
        return coins + [5, 5, 5, 5, 5]

    if amount == 28:
        return coins + [7, 7, 7, 7]

    if amount == 49:
        return coins + [7, 7, 7, 7, 7, 7, 7]

    coins = change(amount - 5)
    coins.append(5)
    return coins

#Only submit the change function
x = int(input())
print(change(x))

It works right until 69 (nice). From there on after, it says a recursion error. It has reached the maximum amount of calls. If there's anyone that can point me in the right direction as to how to solve my dilemma, it would be really appreciated!

1
Run it for x=26, you'll see the issue - Abhinav Mathur
I see now, thanks! >.< - user13805402
I'd recommend to drop recursion and try using math for this - Abhinav Mathur
You could also drop the case for 49 and add in the cases for 26 & 27 and that way have a proper base case covered - shapiro yaacov
The problem had a starter solution of implementing recursion :/ We just had to complete it. Thanks though! @AbhinavMathur! - user13805402

1 Answers

0
votes

first, thank you to those who replied! Second, I'm going to post my solution here in case anyone taking the same Coursera course stumbles upon that error as well.

def change(amount):
    assert(24 <= amount <= 1000)
    coins = []
    
    if amount == 24:
        return coins + [7, 7, 5, 5]

    if amount == 25:
        return coins + [5, 5, 5, 5, 5]

    if amount == 26:
        return coins + [7, 7, 7, 5]

    if amount == 27:
        return coins + [7, 5, 5, 5, 5]
  
    if amount == 28:
        return coins + [7, 7, 7, 7]

    if amount == 49:
        return coins + [7, 7, 7, 7, 7, 7, 7]

    coins = change(amount - 5)
    coins.append(5)
    return coins

#Only submit the change function
x = int(input())
print(change(x))