我想定义一个函数isPalindrome并编写一个doctest
我的产出:
真实4 1 1 4 0
预期产出:
真实4 1 1 4 2
使用的代码:
import math
import random
import re
import inspect
def isPalindrome(x):
"""
>>> isPalindrome(121)
True
>>> isPalindrome(344)
False
>>> isPalindrome(-121)
ValueError: x must be positive integer.
>>> isPalindrome("hello")
TypeError: x must be integer.
"""
try:
x = int(x)
temp=x
rev=0
if(x>0):
while(x>0):
dig=x%10
rev=rev*10+dig
x=x//10
if(temp==rev):
return True
else:
return False
elif(x<0):
raise TypeError
else:
raise ValueError
except ValueError:
raise ValueError("x must be positive integer")
except TypeError:
raise TypeError("x must be an integer")
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
x = input()
if x.isdigit():
x = int(x)
res = isPalindrome(x)
doc = inspect.getdoc(isPalindrome)
func_count = len(re.findall(r'isPalindrome', doc))
true_count = len(re.findall(r'True', doc))
false_count = len(re.findall(r'False', doc))
pp_count = len(re.findall(r'>>>', doc))
trace_count = len(re.findall(r'Traceback', doc))
fptr.write(str(res)+'\n')
fptr.write(str(func_count)+'\n')
fptr.write(str(true_count)+'\n')
fptr.write(str(false_count)+'\n')
fptr.write(str(pp_count) + '\n')
fptr.write(str(trace_count) + '\n')
fptr.close()发布于 2019-04-01 08:42:47
您的doc测试没有正确处理异常,下面是更正的测试:
"""
>>> isPalindrome(121)
True
>>> isPalindrome(344)
False
>>> isPalindrome(-121)
Traceback (most recent call last):
...
ValueError: x must be positive integer.
>>> isPalindrome("hello")
Traceback (most recent call last):
...
TypeError: x must be an integer.
""" 请注意,我将Traceback (most recent call last): ...添加到例外情况中,并将an添加到TypeError: x must be an integer.中。
https://stackoverflow.com/questions/55439879
复制相似问题