Hackerrank Solution: Validating credit card numbers in Python

Question: Validating Credit Card Numbers - Hacker Rank (Python Regex and Parsing)

You and Fredrick are good friends. Yesterday, Fredrick received N credit cards from ABCD Bank. He wants to verify whether his credit card numbers are valid or not. You happen to be great at regex so he is asking for your help!

A valid credit card from ABCD Bank has the following characteristics:

Advertisement
  • It must start with a 4, 5 or 6.
  • 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.

Valid credit card numbers:

4253625879615786
4424424424442444
5122-2368-7954-3214

Invalid credit card numbers:

42536258796157867       #17 digits in card number → Invalid 
4424444424442444        #Consecutive digits are repeating 4 or more times → Invalid
5122-2368-7954 - 3214   #Separators other than '-' are used → Invalid
44244x4424442444        #Contains non digit characters → Invalid
0525362587961578        #Doesn't start with 4, 5 or 6 → Invalid

Input format:

The first line of input contains an integer N.
The next N lines contain credit card numbers.

Constraints:

  • 0 < N < 100

Output format:

Advertisement

Print ‘Valid’ if the credit card number is valid. Otherwise, print ‘Invalid’. Do not print the quotes.

Sample input:

6
4123456789123456
5123-4567-8912-3456
61234-567-8912-3456
4123356789123456
5133-3367-8912-3456
5123 - 3567 - 8912 - 3456

Sample output:

Valid
Valid
Invalid
Valid
Invalid
Invalid

Explanation:

4123456789123456 : Valid
5123-4567-8912-3456 : Valid
61234-567-8912-3456 : Invalid, because the card number is not divided into equal groups of 4.
4123356789123456 : Valid
51-33-33-67-8912-3456 : Invalid, consecutive digits 3333 is repeating 4 times.
5123456789123456 : Invalid, because space ‘  ‘ and - are used as separators.

 

Possible solutions:

Now we will use various methods to find the possible solutions to the question given above to validate the credit card number based on some conditions. Before going to the solutions, make sure that you have a solid understanding of regular expressions as we will be using regular expressions for the validation of the credit card numbers. We will use the following ways to solve the question.

  • Using regular expressions
  • Using if-else statements
  • Using try-except blocks

 

Solution-1: Using regular expression

In this solution, we will use regular expressions to find valid credit card numbers. The re module in Python provides a set of powerful regular expression facilities, which allows you to quickly check whether a given string matches a given pattern (using the match function), or contains such a pattern (using the search function).

In the solution, we will use the re.compile which is used to compile a regular expression pattern provided as a string into a regex pattern object ( re. Pattern ). Later we can use this pattern object to search for a match inside different target strings using regex methods such as a re. match() or re.search().

let's start with the solution:

# importing the regular expression module
import re

# compile the patterns
pattern = re.compile(
    r'^'
    r'(?!.*(\d)(-?\1){3})'
    r'[456]\d{3}'
    r'(?:-?\d{4}){3}'
    r'$')

# using for loop to the input from user 
for _ in range(int(input().strip())):
    
    #using pattern to search if the number is valid
    print('Valid' if pattern.search(input().strip()) else 'Invalid')

Input:

6
4123456789123456
5123-4567-8912-3456
61234-567-8912-3456
4123356789123456
5133-3367-8912-3456
5123 - 3567 - 8912 - 3456

Output:

Valid
Valid
Invalid
Valid
Invalid
Invalid

As you can see, we get the desired output.

Advertisement

 

Solution-2: Using if-else statements

This time, along with the regular expressions, we will also use the if-else statements as well. Let us start the coding part.

# importing module
import re

# taking input from user
n = int(input())

# iterating through the credit cards
for t in range(n):
    
    #taking the credit card number from user
    credit = input().strip()
    credit_removed_hiphen = credit.replace('-','')
    
    # valid is true in the beggining
    valid = True
    
    # using regual expressions
    length_16 = bool(re.match(r'^[4-6]\d{15}$',credit))
    length_19 = bool(re.match(r'^[4-6]\d{3}-\d{4}-\d{4}-\d{4}$',credit))    
    consecutive = bool(re.findall(r'(?=(\d)\1\1\1)',credit_removed_hiphen))
    
    # checking if the above regural expressions are true
    if length_16 == True or length_19 == True:
        if consecutive == True:
            valid=False
    else:
        valid = False       
    if valid == True:
        print('Valid')
    else:
        print('Invalid')

Input:

6
4123456789123456
5123-4567-8912-3456
61234-567-8912-3456
4123356789123456
5133-3367-8912-3456
5123 - 3567 - 8912 - 3456

Output:

Valid
Valid
Invalid
Valid
Invalid
Invalid

As you can see, we got the required output.

 

Solution-3: Using try-except block

This time we will use the try-except-else block with regular expressions. The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error. Lets us start the coding part.

# importing the module
import re


# using for loop
for i in range(int(input())):
    
    # taking the input credit card number
    card = input()
    
    # using try block
    try:
        assert re.search(r'^[456]', card)
        assert re.search(r'^(-?\d{4}){4}$', card)
        assert not re.search(r'(\d)(-?\1){3}', card)
    
    # exept block
    except:
        print('Invalid')
    else:
        print('Valid')

Input:

Advertisement
6
4123456789123456
5123-4567-8912-3456
61234-567-8912-3456
4123356789123456
5133-3367-8912-3456
5123 - 3567 - 8912 - 3456

Output:

Valid
Valid
Invalid
Valid
Invalid
Invalid

As you can see, we get the desired output.

 

Summary

In this short article, we solved the validating credit card question on Hacker Rank using Python. We were able to come up with three different solutions.

 

Further Reading

Python re
Question on Hacker rank: Validating Credit Card Numbers in Python

 

Related Keywords: validating credit card numbers hackerrank solution, validating credit card numbers hackerrank solution python, validating credit card numbers hackerrank solution python3

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X