1

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

3
  • Please format your code accordingly
    – ForceBru
    Commented Feb 10, 2019 at 14:57
  • Sorry about formatting, doctest """ was causing the issue I have updated it now.
    – R D
    Commented Feb 10, 2019 at 15:07
  • Could anyone suggest what I am doing wrong?
    – R D
    Commented Feb 14, 2019 at 17:49

7 Answers 7

2

In doctest inorder to detect an exception it needs two keywords : Traceback and the ExceptionName.

for example: If your block raises a ValueError, The test case you provide in doctest file should have a Traceback line and the second line next to it should have the Exception name with its custom message(if any).

The following is the correct way to write the test code:

def isPalindrome(x):
    # Write the doctests:
    """
    >>>isPalindrome(121)
    True
    >>>isPalindrome(344)
    False
    >>>isPalindrome(-121)
    Traceback (most recent call last):
    ValueError : x must be a positive integer
    >>>isPalindrome("hello")
    Traceback (most recent call last):
    TypeError : x must be an integer
    """
    # Write the functionality:
    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
        
    
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()
1

Small Modification ---- Use below code

import math
import os
import random
import re
import sys
import inspect


def isPalindrome(x):
    """
    >>> 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 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")
1
  • please describe what modifications and why? provide links if any to get context behind modifications
    – Dev
    Commented May 26, 2019 at 7:48
0

Use Value Error for x which is less then Zero. In your code, for Negative value of x, you called Type Error. You have to call Value Error.

    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 ValueError
        else:
            raise TypeError
    except ValueError:
        raise ValueError("x must be positive integer")
    except TypeError:
        raise TypeError("x must be an integer")
0

This is the function 'isPalindrome' to check if given number positive number is palindrome or not and return True and False correspondingly.

def isPalindrome(x):
    # Write the doctests:
    """
    >>>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 integer
    """
    # Write the functionality:
    s = str(x)
    li = list(s)
    li.reverse()
    s1 = ''.join(li)
    if x == int(s1):
        return True
    else:
        return False
0
**

# Using the below code. You wont face any issues
def isPalindrome(x):
    # Write the doctests:
    """
    >>>isPalindrome(121)
    True
    >>>isPalindrome(344)
    False
    >>>isPalindrome(-121)
    Traceback (most recent call last):
    ValueError:X must be a positive integer
    >>>isPalindrome("hello")
    Traceback (most recent call last):
    ValueError:X must be an integer
    """
    # Write the functionality:

    return str(x)==str(x)[::-1]

**

1
  • use the above mentioned code. you wont face any issues.
    – narayana
    Commented Apr 20, 2020 at 11:08
0

Complete the isPalindrome function below.

def isPalindrome(x):
    # Write your doctests below.
    """
    >>> isPalindrome(121)
    True
    >>> isPalindrome(344)
    False
    >>> isPalindrome(-121)
    Traceback (most recent call last):
    ...
    ValueError: x must be a positive integer
    >>> isPalindrome("Hello")
    Traceback (most recent call last):
    ...
    ValueError: x must be an 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 ValueError
        else:
            raise TypeError
    except ValueError:
        raise ValueError("x must be positive integer")
    except TypeError:
        raise TypeError("x must be an integer")
-1

Use this:

def isPalindrome(x):
    # Write your doctests below.
    """
    >>> 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 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")
1
  • Ah, I see. That's why it's important to format your code properly and explain your changes instead of writing "use this"
    – barbsan
    Commented May 9, 2019 at 13:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.