Detect Floating Point Number HackerRank Solution In Python

Problem

Check Tutorial tab to know how to to solve.

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.

Read Also: XML 1 – Find the score solution in python

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 0

4
4.0O0
-1.00
+4.54
SomeRandomStuff

Sample Output 0

FalseTrueTrueFalse

Explanation 0

4.0O0: is not a digit.

-1.00: is valid.

+4.54: is valid.

SomeRandomStuff: is not a number.

Solution to HackerRank Detect Floating Point Number In Python.

In this problem, we are to check with the aid of Python’s Regular Expression (Regex) whether an in input is a float point number or not.

import refor _ in range(int(input())):    s = input()    pattern = re.compile('^[+-]?[0-9]*[.][0-9]+$')    print(bool(pattern.match(s)))

Alternatively

import refor _ in range(int(input())):    s = input()    pattern = re.compile('^[+-]?d*[.]d+$')    print(bool(pattern.match(s)))

Learn more about regular expression here

Comments