Thursday, December 5, 2019

Validating phone numbers - Hacker Rank Solution

Let's dive into the interesting topic of regular expressions! You are given some input, and you are required to check whether they are valid mobile numbers.
A valid mobile number is a ten digit number starting with a  or .

Concept
A valid mobile number is a ten digit number starting with a  or .
Regular expressions are a key concept in any programming language. A quick explanation with Python examples is available here. You could also go through the link below to read more about regular expressions in Python.
Input Format
The first line contains an integer , the number of inputs.
 lines follow, each containing some string.
Constraints
Output Format
For every string listed, print "YES" if it is a valid mobile number and "NO" if it is not on separate lines. Do not print the quotes.
Sample Input
2
9587456281
1252478965
Sample Output
YES
NO

Validating phone numbers - Hacker Rank Solution

We can solve this using regex.

[789] : match a single digit  or .
\d{9} : match  digits.


import re
for i in range(int(raw_input())):
    print 'YES' if re.search(r"^[789]\d{9}$",raw_input()) else 'NO'
  

No comments:

Post a Comment

Powered by Blogger.