In: Computer Science
Python query for below:
There are different ways of representing a number. Python’s function isdigit() checks whether the input string is a positive integer and returns True if it is, and False otherwise. You are to make a more generalised version of this function called isnumeric().
Just like isdigit(), this function will take input as a string and not only return a Boolean True or False depending on whether the string can be treated like a float or not, but will also return its float representation up to four decimal places if it is True.
Remember that numbers can be represented as fractions, negative integers, and float only. Check the sample test cases to understand this better.
Input: One line of string. The string will contain alphabets, numbers and symbols: '/' '.' '^'
Output: One line with True/False and then a space and the number with 4 decimal places if it is true and ‘nan’ if it is false
Sample Input 1: .2
Sample Output 1:
True 0.2000
Sample Input 2: 1 /. 2
Sample Output 2:
True 5.0000
Sample Input 3: 3^1.3
Sample Output 3:
True 4.1712
Sample Input 4: 3/2^3
Sample Output 4:
False NaN
Explanation:
if '^' and '/' are both present then give False. Since it is
ambiguous, 2^5/5 can be seen as 2^(5/5) or (2^5)/5 likewise 3/2^3
can be seen as 3/(2^3) or (3/2)^3
Sample Input 5: 1.2.3
Sample Output 5:
False NaN
Sample Input 6: -2.
Sample Output 6:
True -2.0000
str="13"
digit1=""
digit2=""
operator=""
count=0
countForDotDigit2=0
countForDotDigit1=0
for element in str:
if element!='/' and element!='.' and element!='*' and element!='^'
and element!='-' and element!='+' and element!='0' and element!='1'
and element!='3' and element!='4' and element!='5' and element!='6'
and element!='7' and element!='8' and element!='9' and
element!='2':
print("False NaN")
break
elif element.isdigit() and count==0:
digit1+=element
elif element.isdigit() and count==1:
digit2+=element
elif element=='.' and count==1:
digit2+=element
countForDotDigit2=countForDotDigit2+1
if countForDotDigit2==2:
print("False NaN")
elif element=='.' and count==0:
digit1+=element
countForDotDigit1=countForDotDigit1+1
if countForDotDigit1==2:
print("False NaN")
elif element=='/' or element=='*' or element=='^' or element=='-'
or element=='+':
count=count+1
operator=element
one=float(digit1)
if operator=='':
print("True ",'{:.4f}'.format(one))
elif operator=='+':
two=float(digit2)
result=one+two
print("True ", '{:.4f}'.format(result))
elif operator=='-':
two=float(digit2)
result=one-two
print("True ",'{:.4f}'.format(result))
elif operator=='*':
two=float(digit2)
result=one*two
print("True ", '{:.4f}'.format(result))
elif operator=='/':
two=float(digit2)
result=one/two
print("True ", '{:.4f}'.format(result))
elif operator=='^':
two=float(digit2)
result=one**two
print("True ", '{:.4f}'.format(result))
COMMENT DOWN FOR ANY QUERIES
AND,
LEAVE A THUMBS UP IF THIS ANSWER HELPS YOU.