Validating Credit Card Numbers

  • + 0 comments

    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")