我想定义一个函数isPalindrome
并编写doctests
我的输出:
真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()
您的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.