简体   繁体   中英

Recursion error, maximum recursion reached

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!

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM