Reputation: 335
So I've defined a function called change(a,d)
that computes the change of amount a given denominations d. I've also got some parameters: a must be of type int, d must be of type list of int, and the elements of d must be in ascending order, otherwise ChangeParameterError is raised. My code is as follows:
class ChangeRemainderError(Exception):
pass
class ChangeParameterError(Exception):
pass
def change(a, d):
if type(a) != int:
raise ChangeParameterError
if type(d) != type(list):
raise ChangeParameterError
if type(d) != d.sort():
raise ChangeParameterError
i, r, c = len(d)-1, a, len(d)*[0]
while i >= 0:
c[i], r = divmod(r, d[i])
i = i-1
return c
def printChange(a, d):
try:
print(change(a, d))
except ChangeParameterError:
print('needs an integer amount and a non-empty list \
of denominations in ascending order')
except ChangeRemainderError:
print('no exact change possible')
except:
print('unexpected error')
and as it stands it's throw ChangeParameterError for tests it shouldn't be doing so. For example:
change(3, [3, 7]) == [1, 0]
returns the ChangeParameterError even though a is an int and d is a list in ascending order. And the error message isn't really helpful. The error message is as follows:
<ipython-input-39-62477b9defff> in change(a, d)
19 raise ChangeParameterError
20 if type(d) != type(list):
---> 21 raise ChangeParameterError
22 if type(d) != d.sort():
23 raise ChangeParameterError
ChangeParameterError:
Any help is appreciated, thanks!
Upvotes: 0
Views: 64
Reputation: 137418
You've got two logic errors that I can see. Try this instead:
def change(a, d):
if type(a) != int:
raise ChangeParameterError
if type(d) != list: # 1
raise ChangeParameterError
if d != sorted(d): # 2
raise ChangeParameterError
First, type(list)
is going to return the type <type>
.
Second, you included type(d)
in your third check where it doesn't make sense. Also, d.sort()
doesn't return anything; it sorts the list in place.
Also, it's better to use isinstance
rather than checking the return value of type
.
Upvotes: 1