HackerRank Python Solution - Regex and Parsing - Detect Floating Point Number

  • You are given a string N.
  • Your task is to verify that N is a floating-point number. 
  • In this task, a valid float number must satisfy all of the following requirements:
    • Number can start with +, - or . symbol.
    • For example: 
      • ✔+4.50
      • ✔-1.0
      • ✔.5
      • ✔-.7
      • ✔+.4
      • ✖-+4.5
    • Number must contain at least 1 decimal value.
    • For example:
      • ✖ 12.
      • ✔ 12.0
    • Number must have exactly one . symbol.
    • Number must not give any exceptions when converted using float(N).
Input Format:
  • The first line contains an integer T, the number of test cases.
  • The next T line(s) contains a string N.
Constraints:
  • 0 < T < 10
Output Format:
  • Output True or False for each test case.
Sample Input:

4
4.0O0
-1.00
+4.54
SomeRandomStuff
Sample Output:

False
True
True
False
Explanation:
  • 4.0O0: O is not a digit.
  • -1.00: is valid.
  • +4.54: is valid.
  • SomeRandomStuff: is not a number.
Solution:

import re

for _ in range(int(input())):
    N = input()
    pattern = '^[-+]?[0-9]*\.[0-9]+$'
    result = re.match(pattern,N)

    if result:
        print(True)
    else:
        print(False)
Note: The problem statement is given by hackerrank.com but the solution is generated by the Geek4Tutorial admin. We highly recommend you solve this on your own, however, you can refer to this in case of help. If there is any concern regarding this post or website, please contact us using the contact form. Thank you!

No comments:

Post a Comment

You might also like

Deploy your Django web app to Azure Web App using App Service - F1 free plan

In this post, we will look at how we can deploy our Django app using the Microsoft Azure app service - a free plan. You need an Azure accoun...