Skip to content

Luhn algorithm #4487

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jun 13, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions hashes/luhn.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
""" Luhn Algorithm """
from typing import List


def is_luhn(string: str) -> bool:
"""
Perform Luhn validation on input string
Algorithm:
* Double every other digit starting from 2nd last digit.
* Subtract 9 if number is greater than 9.
* Sum the numbers
*
>>> test_cases = [79927398710, 79927398711, 79927398712, 79927398713,
... 79927398714, 79927398715, 79927398716, 79927398717, 79927398718,
... 79927398719]
>>> test_cases = list(map(str, test_cases))
>>> list(map(is_luhn, test_cases))
[False, False, False, True, False, False, False, False, False, False]
"""
check_digit: int
_vector: List[str] = list(string)
__vector, check_digit = _vector[:-1], int(_vector[-1])
vector: List[int] = [*map(int, __vector)]
Comment on lines +20 to +23
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can remove the noise of extra variables with similar names here

tokens, check_digit = list(string), int(list(string)[-1])
vector: List[int] = list(map(int, tokens[:-1]))

A variable declaration costs memory, so use it judicially

Copy link
Contributor Author

@QuantumNovice QuantumNovice Jun 13, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mypy static checks doesn't pass when "the noise" isn't there
:)


vector.reverse()
for idx, i in enumerate(vector):

if idx & 1 == 0:
doubled: int = vector[idx] * 2
if doubled > 9:
doubled -= 9

check_digit += doubled
else:
check_digit += i

if (check_digit) % 10 == 0:
return True
return False


if __name__ == "__main__":
import doctest

doctest.testmod()
assert is_luhn("79927398713")