Validating Credit Card Numbers

  • + 0 comments
    import sys
    import re
    
    def is_valid_format(card_number):
        """Check if the card number has the correct format."""
        format_pattern = r"^[456]\d{3}([-]?\d{4}){3}$"
        return bool(re.match(format_pattern, card_number))
    
    def has_repeated_digits(card_number):
        """Check if the card number contains four consecutive repeated digits."""
        cleaned_number = ''.join(card_number.split('-')) 
        return bool(re.search(r"(.)\1{3}", cleaned_number))
    
    def validate_card_numbers(card_numbers):
        """Validate a list of card numbers and return the results."""
        results = []
        for card in card_numbers:
            if is_valid_format(card) and not has_repeated_digits(card):
                results.append("Valid")
            else:
                results.append("Invalid")
        return results
    
    if __name__ == "__main__":
        text = sys.stdin.read().splitlines()[1:] 
        results = validate_card_numbers(text)
        print("\n".join(results))