2017-03-17 132 views
0

所以我定义了一个名为change(a,d)的函数来计算给定名称d的金额变化。我也得到了一些参数:必须是int类型,d必须是int类型的列表,并且d的元素必须是升序,​​否则会引发ChangeParameterError。我的代码如下:参数错误

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

并且因为它的原因,抛出的ChangeParameterError对于测试它不应该这样做。例如: change(3, [3, 7]) == [1, 0]

返回ChangeParameterError,即使a是int并且d是列表中的升序。而错误信息并不是真的有用。错误消息如下:

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

任何帮助表示赞赏,谢谢!

+0

请显示其余的错误信息。事实上,它的底部是最重要的。 – DyZ

回答

1

你有两个我可以看到的逻辑错误。试试这个:

def change(a, d): 
    if type(a) != int: 
     raise ChangeParameterError 
    if type(d) != list: # 1 
     raise ChangeParameterError 
    if d != sorted(d): # 2 
     raise ChangeParameterError 

首先,type(list)打算返回类型<type>

其次,您在第三张支票中包含了type(d),这是没有意义的。另外,d.sort()不返回任何内容;它会对列表进行排序。

此外,最好使用isinstance而不是检查返回值type

+0

非常感谢Jonathon!这实际上解决了'变化(3,[3,7])== [1,0]'。但是现在'改变(3,[2,7])'这应该会引起上述错误,现在只是返回'[1,0]'哈哈哈。 – dejz

+0

我不明白为什么会引发错误。第一个参数是int,第二个是list,list是排序的。 –

+0

哎呀,对不起,我也有'ChangeRemainderError',我很困惑,同时回复你!谢谢! – dejz