Define a function definition of 'isPalindrome' which checks if given number positive number is palindrome or not and return True and False correspondingly.
- write a doctest which checks the function call 'isPalindrome(121)' returns True.
- write a doctest which checks the function call 'isPalindrome(344)' returns False.
- write a doctest which checks the function call 'isPalindrome(-121)' raises ValueError with an error message as 'x must be positive integer'.
- write a doctest which checks the function call 'isPalindrome('hello')' raises TypeError with an error message as 'x must be an integer'.
I tried below but its giving answer as -
True 4 1 1 4 0
but the expected answer is
True 4 1 1 4 2
#!/bin/python3
import math
import os
import random
import re
import sys
import inspect
# Complete the isPalindrome function below.
def isPalindrome(x):
# Write your doctests below.
"""
>>> isPalindrome(121)
True
>>> isPalindrome(344)
False
>>> isPalindrome(-121)
ValueError: x must be positive integer.
>>> isPalindrome("hello")
TypeError: x must be integer.
"""
# Write the functionality below
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()
Please suggest