-
-
Notifications
You must be signed in to change notification settings - Fork 47k
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
Luhn algorithm #4487
Changes from 6 commits
2567562
430fa3a
0158e71
48cbd14
895ff80
840e8dd
470e3ee
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
QuantumNovice marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if doubled > 9: | ||
doubled -= 9 | ||
|
||
check_digit += doubled | ||
else: | ||
check_digit += i | ||
|
||
if (check_digit) % 10 == 0: | ||
QuantumNovice marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return True | ||
return False | ||
|
||
|
||
if __name__ == "__main__": | ||
import doctest | ||
|
||
doctest.testmod() | ||
assert is_luhn("79927398713") |
Uh oh!
There was an error while loading. Please reload this page.