2 min to read
Validating Credit Card Numbers - HackerRank Solution Python
Validating Credit Card Numbers is a medium level problem of python on Hackerrank that requires knowledge of regex
in python. In this post, you will learn how to solve Hackerrank’s Validating Credit Card Numbers problem and its solution in Python.
Problem Statement and Explanation
verify the credit card number using the following rules:
- It must start with a
4
,5
or6
. - It must contain exactly
16
digits. - It must only consist of digits (
0
-9
). - It may have digits in groups of
4
, separated by one hyphen-
. - It must NOT use any other separator like
' '
,'_'
, etc. - It must NOT have
4
or more consecutive repeated digits.
Input Format
- The first line of input contains an integer
N
. - Next
N
lines contain credit card numbers.
Validating Credit Card Numbers HackerRank Solution
Explanation of Solution
This section compiles a regular expression pattern that will match valid credit card numbers. The pattern is as follows:
- The number must start with a 4, 5, or 6.
- The number must be 16 digits long.
- The number must consist of only digits, with the optional exception of hyphens separating the digits into groups of four.
- The number must not have four or more consecutive repeated digits.
The regular expression pattern is compiled into a Pattern
object, which is then stored in the variable pattern
.
This function takes a credit card number as input and returns Valid
if the number is valid, or Invalid
if the number is not valid.
The function first uses the pattern
object to match the credit card number against the regular expression pattern. If the pattern matches, the function returns Valid
. Otherwise, the function returns Invalid
.
The main function first prompts the user to enter the number of credit card numbers they want to validate. The function then iterates over the number of credit card numbers and validates each number using the validate_credit_card_number()
function. The function then prints the validation result to the console.