From 57c6f1439a9fd7aa643c151be3fb36ed99a4631e Mon Sep 17 00:00:00 2001 From: acidvegas Date: Sun, 12 May 2024 04:01:54 -0400 Subject: [PATCH] Fixed modulo 10 algorithm --- luhn_algo.py | 51 ++++++++++++++++++++++++--------------------------- 1 file changed, 24 insertions(+), 27 deletions(-) diff --git a/luhn_algo.py b/luhn_algo.py index 6b5a86e..259ac13 100644 --- a/luhn_algo.py +++ b/luhn_algo.py @@ -1,41 +1,38 @@ #!/usr/bin/env python # Luhn Algorithm Example - Developed by acidvegas in Python (https://git.acid.vegas/msr90) -def modulus10(card_number: str) -> str: - ''' - Validate a card number using the Luhn Algorithm +def modulo10(card_number: str) -> str: + ''' + Validate a card number using the Luhn Algorithm - :param card_number: The card number to validate - ''' - - digits = [int(d) for d in card_number] - total_sum = 0 - reversed_digits = digits[::-1] + :param card_number: The card number to validate + ''' - for i in range(len(reversed_digits)): - digit = reversed_digits[i] + digits = [int(d) for d in card_number] + total_sum = 0 - if i % 2 != 0: - digit = digit * 2 + for i, digit in enumerate(reversed(digits)): + if i % 2 == 0: + digit = digit * 2 - if digit > 9: - digit -= 9 + if digit > 9: + digit -= 9 - total_sum += digit + total_sum += digit - check_digit = (10 - (total_sum % 10)) % 10 - full_card_number = card_number + str(check_digit) - - if (total_sum + check_digit) % 10 != 0: - raise ValueError('failed luhn check (non-divisible by 10)') + check_digit = (10 - total_sum % 10) % 10 + full_card_number = card_number + str(check_digit) - return full_card_number + if (total_sum + check_digit) % 10 != 0: + raise ValueError('failed luhn check (non-divisible by 10)') + + return full_card_number if __name__ == '__main__': - card_number = input('Enter your card number without the last digit:') + card_number = input('Enter your card number without the last digit: ') - if not card_number.isdigit(): - raise ValueError('invalid card number') - - print(f'Full card number: {modulus10(card_number)}') + if not card_number.isdigit(): + raise ValueError('invalid card number') + + print(f'Full card number: {modulo10(card_number)}')