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