Validating credit card
Sequence must not: -Use any other separator; -Have 4 or more consecutive repeated digits.
NET to process online credit card orders, it is a good idea if you can perform some sort of validation on the credit card number before submitting it to your processor.
A valid credit card number - must contain exactly 16 digits, - must start with a 4, 5 or 6 - must only consist of digits (0-9) or hyphens '-', - may have digits in groups of 4, separated by one hyphen "-".
- must NOT use any other separator like ' ' , '_', - must NOT have 4 or more consecutive repeated digits.
If they are only invalid four 4 character groups, we can simply check whether the current character import re PATTERN='^([0-9])-? A valid credit card number - must contain exactly 16 digits, - must start with a 4, 5 or 6 - must only consist of digits (0-9) or hyphens '-', - may have digits in groups of 4, separated by one hyphen "-".
""" match = re.match(PATTERN,sequence) if match == None: return False for group in match.groups: if group * 4 == group: return False return True If the repeated digits may also not span hyphens/groups it gets a little bit more complicated, but not too much. That being said: make sure to handle multiple numbers, not a single one.
Rules for sequences to qualify as credit card numbers: Sequences must: -Contain exactly 16 digits; -Start with a 4,5 or 6; -Only consist of digits (0-9).
(s0,s1,s2,s3), (s1,s2,s3,s4), (s2,s3,s4,s5), ..." a, b, c, d = itertools.tee(iterable, 4) next(b, None) next(c, None) next(c, None) next(d, None) next(d, None) next(d, None) return zip(a, b, c, d) def val_rep(num): return not any( all(head == item for item in (a, b, c)) for head, a, b, c in quadwise(num) ) def valid_creditcard(card): groups = re.match(REGEX, card) if not groups: return False if card.count('-') not in (0, 3): return False return val_rep(''.join(groups.groups())) if __name__ == '__main__': total_count = int(raw_input()) cards = [ raw_input() for count in range(total_count) ] for card in cards: if valid_creditcard(card): print('Valid') else: print('Invalid') import re PATTERN = "([4-6])([0-9]-? )([0-9])" def is_valid_creditcard(sequence): """Check if a sequence is a valid credit card number.
This verification does not tell you if funds are available in the account and it certainly doesn't tell whether or not the person submitting the order is committing credit card fraud.
In fact, it's possible that the card number is mistyped in such a way that it just happens to pass verification.
But it does catch most typing errors and reduces bandwidth by catching those errors before trying to actually process the credit card.
The algorithm to validate a credit card number starts by adding the value of every other digit, starting from the right-most digit and working left.