

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python program to check credit card number is valid or not
Suppose we have a credit card number. We have to check whether the card number is valid or not. The card numbers have certain properties −
It will start with 4, 5 and 6
It will be 16 digits’ long
Numbers must contain only digits
It may have digits in four groups separated by '-'
It must not use any other separator like space or underscore
It must not have 4 or more consecutive same digits
So, if the input is like s = "5423-2578-8632-6589", then the output will be True
To solve this, we will follow these steps −
- if number of '-' in s is greater than 0, then
- a := a list of parts separated by "-"
- p:= 1
- if size of a is not same as 4, then
- p:= null
- a:= blank list
- for each b in a, do
- if size of b is not same as 4, then
- p:= null
- come out from loop
- if size of b is not same as 4, then
- otherwise,
- p := search a substring which is starting with 4 or 5 or 6 and remaining are numbers of 15 digits long
- s := remove "-" from s
- q := search substring where 4 or more consecutive characters are same
- if p is not null and q is null, then
- return True
- otherwise,
- return False
Example
Let us see the following implementation to get better understanding
import re def solve(s): if s.count("-")>0: a = s.split("-") p=1 if len(a)!=4: p=None a=[] for b in a: if len(b)!=4: p=None break else: p = re.search("[456][0-9]{15}",s) s = s.replace("-","") q = re.search(".*([0-9])\\1{3}.*",s) if p!=None and q==None: return True else: return False s = "5423-2578-8632-6589" print(solve(s))
Input
"5423-2578-8632-6589"
Output
False
- Related Questions & Answers
- Java Program for credit card number validation
- C Program to check if a date is valid or not
- Program to check whether given list is in valid state or not in Python
- Program to check a number is ugly number or not in Python
- Python program to check if a number is Prime or not
- Python program to check a number n is weird or not
- Check whether a string is valid JSON or not in Python
- Program to check whether a board is valid N queens solution or not in python
- Program to check whether given number is Narcissistic number or not in Python
- Program to check all listed delivery operations are valid or not in Python
- Program to check a number is power of two or not in Python
- Check whether triangle is valid or not if sides are given in Python
- How to check if an URL is valid or not using Java?
- C# Program to check if a number is prime or not
- C++ Program to Check Whether a Number is Prime or Not
Advertisements