Using python regular expressions , write python script.

QUESTION

Return True if a given inequality expression is correct and False otherwise. Put comments in the program.

 

SUMMARY

The inequality expression is passed to a function in the form of a string. Then this expression is evaluated to check if it is true or false.

 

EXPLANATION

An argument is passed as a string to a function. The expression in the string is evaluated to check if it is true or not using the ‘eval’ function of python.

1)  When the first string/expression is passed, 2<7<15 is correct and therefore True will be returned.

2)  In the second expression, 30< 45> 21 > 9 is incorrect and hence False will be returned.

3)  In the third expression, 4 < 7 < 8 < 12 > 2 is true so True will be returned.

 

CODE

# definition  

# inequality function 

def check(s):

    regex=eval(s)

    if regex:

        return True

    else:

return False 

# printing result 

print(check("2 < 7 < 15"))

print(check("30 > 45 > 21 > 9"))

print(check("4 < 7 < 8< 12 > 2"))

 

OUTPUT

True

False

True

 

 

Also, read Design a class that performs arithmetic and relational operations on fractions.

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *