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.
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")
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Validating Credit Card Numbers
You are viewing a single comment's thread. Return to all 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")