Header Ad

HackerRank Validating Credit Card Numbers solution in python

In this Validating Credit Card numbers problem 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!

HackerRank Validating Credit Card Numbers solution in python


Problem solution in Python 2 programming.

import re
ccn = re.compile(r'[4-6][0-9]{3}[-]?[0-9]{4}[-]?[0-9]{4}[-]?[0-9]{4}')

def check_consecutive(s):
    n = len(s)
    ch = s[0]
    count = 1
    for i in xrange(1, n):
        if s[i] == '-':
            continue
        if s[i] == ch:
            count += 1
            if count == 4:
                return False
        else:
            ch = s[i]
            count = 1
    return True

def check_hyphen(s):
    if s.count('-') == 0 or s.count('-') == 3:
        return True
    else:
        return False

N = input()
for _ in xrange(N):
    s = raw_input().strip()
    if ccn.match(s) and check_consecutive(s) and check_hyphen(s):
        print 'Valid'
    else:
        print 'Invalid'



Problem solution in Python 3 programming.

# 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 pypy programming.

# Enter your code here. Read input from STDIN. Print output to STDOUT
import re
n = int(raw_input())
for i in range(n):
    s=raw_input().strip()
    if len(s) != 16 and len(s) != 19:
        print "Invalid"
    elif s[0] not in ['4','5','6']:
        print "Invalid"
    elif len(s) == 16:
        print re.match(r'\d{16,16}',s) and not re.search(r'(\d)\1\1\1',s) and "Valid" or "Invalid"
    else:
        print re.match(r'\d\d\d\d-\d\d\d\d-\d\d\d\d-\d\d\d\d',s) and not re.search(r'(\d)\1\1\1',s.replace('-','')) and "Valid" or "Invalid"


Problem solution in pypy3 programming.

import re

start_with_456 = lambda x: x[0]=='4' or x[0]=='5' or x[0]=='6'

contain_16_digits = lambda x: bool(re.fullmatch(r'\d{16}', ''.join(x.split('-'))))

groups_of_4 = lambda x: all([len(i)==4 for i in x.split('-') if '-' in x])
    
repeating_characters = lambda x: not(bool(re.search(r'(\d)\1{3,}', ''.join(x.split('-')))))
    
tests = [start_with_456, contain_16_digits, groups_of_4, repeating_characters]

N = int(input())
for _ in range(N):
    s = input()
    if all(map(lambda x: x(s), tests)):
        print('Valid')
    else:
        print('Invalid')


Post a Comment

0 Comments