Advertisement
makispaiktis

Luhn Algorithm

May 12th, 2022 (edited)
1,335
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. from copy import deepcopy
  2.  
  3. # Function 1 - Break intergers into his digits
  4. def break_digits(n):
  5.     temp = [str(element) for element in str(n)]
  6.     card = [int(element) for element in temp]
  7.     return card
  8.  
  9.  
  10. # Function 2 - Reversing and doubling
  11. def double(card):
  12.     LEN = len(card)
  13.     card.reverse()
  14.     # 1. Doubling the elements from the second-to-last-digit and moving to the left
  15.     # 2. Checking if it is 2-digit number: If yes, add the digits (or % 9)
  16.     for i in range(1, LEN, 2):
  17.         card[i] = 2*card[i] % 9
  18.     card.reverse()
  19.     return card
  20.  
  21.  
  22. # Function 3 - Checking if it is valid
  23. def check_valid(card):
  24.     S = sum(card) % 10
  25.     if S == 0:
  26.         return True, S
  27.     else:
  28.         return False, S
  29.  
  30.  
  31. # Function 4 - Propose solution
  32. def propose_correct(card, S):
  33.     last = card[len(card) - 1]
  34.     extra = 10 - S
  35.     correct_last = (last + extra) % 10
  36.     print("If the last digit is changed from " + str(last) + " to " + str(correct_last) + ", we will have a valid card number.")
  37.     return correct_last
  38.  
  39.  
  40. # Function 5 - Simulate
  41. def Luhn(CARD):
  42.     card = break_digits(CARD)
  43.     initial_card = deepcopy(card)
  44.     # print("Initial card = " + str(initial_card))
  45.     new_card = double(card)
  46.     # print("New card = " + str(new_card))
  47.     flag, S = check_valid(new_card)
  48.     if flag:
  49.         print(str(initial_card) + " = VALID")
  50.     else:
  51.         print(str(initial_card) + " = INVALID")
  52.         correct_last = propose_correct(new_card, S)
  53.         correct = deepcopy(initial_card)
  54.         correct[len(card) - 1] = correct_last
  55.         print(str(correct) + " =  VALID")
  56.  
  57.  
  58. # MAIN FUNCTION
  59. CARD1 = 5146713835430
  60. Luhn(CARD1)
  61. print()
  62. CARD2 = 5146713835435
  63. Luhn(CARD2)
  64.  
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement