I am taking a discrete math course that requires me to write some short code for it. Here is the problem that I am tasked with:
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].
(To solve this quiz, implement the method change(amount) on your machine, test it on several inputs, and then paste your code in the field below and press the submit quiz button.)
And here is the code I wrote:
def change(amount):
if amount < 24:
return 0
assert(amount >= 24)
if amount == 24:
return [5, 5, 7, 7]
if amount == 25:
return [5, 5, 5, 5, 5]
if amount == 26:
return [5, 7, 7, 7]
if amount > 1000:
return 0
coins = change(amount - 5)
coins.append(5)
return coins
When I test my code on a code visualizer program (http://www.pythontutor.com/visualize.html#mode=edit) it seems to be working fine, but when I enter it as the answer for the quiz I get an error:
RuntimeErrorElement(RuntimeError,Error on line 16: coins.append(5) AttributeError: 'int' object has no attribute 'append' )
I am not sure what is going on. Do note that the class is an online one and I am typing the code into an online platform, so I am sure there is something the algorithm is checking for, but I am unsure what.
changereturns0, then you're trying to do0.append(5), which doesn't make any sense.return 0toreturn [0]should make it work, though Patrick's comment is still valid. Specifyingreturn [], i.e. an empty list, might make more sense, depending on the context.return 0line should be indented. jshamble has removed the error you note. But if that is done, your code still returns wrong answers values ofamountthat end in the decimal digit2,3,7, or8. See my answer for working code.