Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackCoaching1:1 coaching with people at your target companiesSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Build my plan
Luhn Credit Card Validation
00:00
5 left

Luhn Credit Card Validation

MediumPython

Problem

American Express payment flows need to reject card numbers with invalid check digits before further processing. Write a function that validates a card number using the Luhn algorithm.

Spaces and hyphens may appear as formatting characters and must be ignored. Any other non-digit character makes the input invalid. The function should return True when the resulting digit sequence passes the Luhn checksum and False otherwise.

Formal Specification

Implement is_valid_card_number(card_number), where card_number is a string containing a card number with optional spaces or hyphens. Return a boolean. The input is valid only if it contains between 2 and 19 digits after formatting characters are removed and its Luhn checksum is valid.

To compute the checksum, scan digits from right to left. Double every second digit, beginning with the digit immediately left of the rightmost digit. If doubling produces a value greater than 9, subtract 9. The sum of all transformed digits must be divisible by 10.

Constraints

  • card_number contains at most 50 characters
  • After removing spaces and hyphens, the number contains 2 to 19 digits
  • Only digits, spaces, and hyphens are allowed
  • The input is provided as a string

Function Signature

def is_valid_card_number(card_number):
Interviewer

Your question is Luhn Credit Card Validation. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
Sign up free to run your codeLog inLn 2
Run your code to see test output here.