Python 参数误差
所以我定义了一个名为changea,d的函数,它计算给定面额d的金额变化。我还得到了一些参数:a的类型必须是int,d的类型必须是list of int,d的元素必须按升序排列,否则会引发ChangeParameterError。我的代码如下:Python 参数误差,python,python-3.x,parameters,Python,Python 3.x,Parameters,所以我定义了一个名为changea,d的函数,它计算给定面额d的金额变化。我还得到了一些参数:a的类型必须是int,d的类型必须是list of int,d的元素必须按升序排列,否则会引发ChangeParameterError。我的代码如下: class ChangeRemainderError(Exception): pass class ChangeParameterError(Exception): pass def change(a, d): if type(a
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')
<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:
就目前而言,它是抛出ChangeParameterError用于测试,它不应该这样做。例如:
更改3[3,7]=[1,0]
返回ChangeParameterError,即使a是int,d是升序列表。而错误消息并没有真正的帮助。错误消息如下所示:
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')
<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:
感谢您的帮助,谢谢 我可以看到您有两个逻辑错误。请尝试以下方法:
def change(a, d):
if type(a) != int:
raise ChangeParameterError
if type(d) != list: # 1
raise ChangeParameterError
if d != sorted(d): # 2
raise ChangeParameterError
首先,typelist将返回类型
第二,你在第三次检查中输入了没有意义的内容。而且,d.sort不返回任何内容;它对列表进行适当的排序
此外,最好使用isinstance,而不是检查类型的返回值。请显示错误消息的其余部分。事实上,它的底部是最重要的。非常感谢,乔纳森!这确实解决了变化3、[3,7]=[1,0]。但是现在change3,[2,7]应该会产生上述错误,现在只是返回[1,0]哈哈哈。我不明白为什么会产生错误。第一个参数是int,第二个参数是list,list是排序的。哎呀,对不起,我还有一个“ChangeRemainderError”,我在回复你的时候感到困惑!谢谢