2017-03-17 134 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