Input Format
The first line of input contains an integer .
The next  lines contain credit card numbers.
Constraints
Output Format
Print 'Valid' if the credit card number is valid. Otherwise, print 'Invalid'. Do not print the quotes.

hackerrank validating credit card numbers problem solution in python

Problem solution in Python 3 programming language.

import re
for i in range(int(input())):
    S = input().strip()
    pre_match = re.search(r'^[456]\d{3}(-?)\d{4}\1\d{4}\1\d{4}$',S)
    if pre_match:
        processed_string = "".join(pre_match.group(0).split('-'))
        final_match = re.search(r'(\d)\1{3,}',processed_string)
        print('Invalid' if final_match else 'Valid')
    else:
        print('Invalid')

Second solution

# Enter your code here. Read input from STDIN. Print output to STDOUT
import re
TESTER = re.compile(
    r"^"
    r"(?!.*(\d)(-?\1){3})"
    r"[456]"
    r"\d{3}"
    r"(?:-?\d{4}){3}"
    r"$")
for _ in range(int(input().strip())):
    print("Valid" if TESTER.search(input().strip()) else "Invalid")

Problem solution in Python 2 programming language.

import re
for i in range(int(raw_input())):
    S = raw_input().strip()
    pre_match = re.search(r'^[456]\d{3}(-?)\d{4}\1\d{4}\1\d{4}$',S)
    if pre_match:
        processed_string = "".join(pre_match.group(0).split('-'))
        final_match = re.search(r'(\d)\1{3,}',processed_string)
        print 'Invalid' if final_match else 'Valid'
    else:
        print 'Invalid'