Valid Credit Card Checker – Detailed Version #Python #Regex #HackerRank #Validation

preview_player
Показать описание
In this problem, you and your friend Fredrick need to validate a series of credit card numbers from ABCD Bank using regular expressions. A valid credit card number must satisfy the following criteria:

Starts with 4, 5, or 6:

The card number must begin with one of these digits. This is checked using the regex pattern ^[4-6].

Contains exactly 16 digits:

The credit card number should have exactly 16 digits, though it may be represented with hyphen separators (e.g., groups of 4 digits). The regex allows for both formats:

A continuous 16-digit number, e.g., 4253625879615786.

A hyphenated format with 4 groups of 4 digits, e.g., 5122-2368-7954-3214.

Only digits (and optionally hyphens):

The card number must not contain any characters other than digits or hyphens. Other separators (like spaces or underscores) are not allowed.

No 4 or more consecutive repeated digits:

Even if the digits are separated by hyphens, there must not be any sequence where the same digit repeats 4 or more times consecutively. For instance, 4444 anywhere in the number makes it invalid.

The solution uses Python's re module to define a regular expression that validates the overall format of the card number and then applies a second check to ensure there are no four or more consecutive identical digits (after removing hyphens).

Step-by-Step Process:

Regex Pattern:

The pattern used is ^[4-6]\d{3}(-?\d{4}){3}$:

^[4-6] ensures the number starts with 4, 5, or 6.

\d{3} ensures the next three characters are digits.

(-?\d{4}){3} ensures that there are exactly three groups of four digits, optionally separated by a hyphen.

Hyphen Removal:

After the initial format check, hyphens are removed to check for any sequence of 4 or more repeating digits.

Consecutive Digits Check:

The regex (\d)\1{3,} is used to search for any digit that repeats four or more times consecutively.

Final Decision:

If both checks pass, the card is deemed "Valid"; otherwise, it is "Invalid".

This detailed solution is ideal for those interested in learning how to combine regular expressions for complex validation tasks and demonstrates effective use of Python’s regex functionalities for real-world problems.

Code (Detailed Version):

import re

def is_valid_credit_card(card_number):
# Check basic format using regex:
pattern = r'^[4-6]\d{3}(-?\d{4}){3}$'
return "Invalid"

# Remove hyphens for consecutive digit checking

# Check for 4 or more consecutive repeating digits
return "Invalid"

return "Valid"

def solve():
n = int(input().strip())
for _ in range(n):
card = input().strip()
print(is_valid_credit_card(card))

if __name__ == '__main__':
solve()
Рекомендации по теме
visit shbcf.ru