We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Validating Credit Card Numbers
Validating Credit Card Numbers
Sort by
recency
|
482 Discussions
|
Please Login in order to post a comment
Here is HackerRank Validating Credit Card Numbers in Python solution - https://programmingoneonone.com/hackerrank-validating-credit-card-numbers-solution-in-python.html
import re regex_format = r'^(?:\d{16}|\d{4}(?:-\d{4}){3})$'
regex_no_consecutive = r'(\d)(?:-?\1){3}'
card = input().strip()
if not re.match(regex_format, card): print("Invalid") else: # Remove hyphens so we can sum digits digits_only = card.replace('-', '') # 2) Check for any digit repeated 4+ times consecutively if re.search(regex_no_consecutive, card): print("Invalid") else: # 3) Sum of digits > 16? total = sum(int(d) for d in digits_only) print("Valid" if total > 16 else "Invalid")
Here is my solution, wasted too much time to understand that i was not tracking "--", but fixed and it worked. ` import re
n_cards = int(input()) if n_cards == 0: print()
cards=[] for i in range(n_cards): cards.append(input().strip())
pattern1 = r"^[456][0-9-]*$" # card format only digits or - pattern2 = r"(\d)\1{3,}" # 4 or more consecutive digits for card in cards: if len(card.replace("-","")) != 16: print("Invalid")
else: # length is 16 without hyphens if bool(re.search(pattern1,card)) and not bool(re.search(pattern2,card.replace("-",""))): # if conditions match if "--" in card: print("Invalid") elif "-" in card: card_splits = any(a>4 for a in list(map(len,card.split("-")))) if card_splits:# if hyphen then groups of 4 numbers print("Invalid") # no invalid else:# yes valid print("Valid") else: print("Valid") else: print("Invalid")