luhn.py: Favor list comprehensions over maps (#4663)

* luhn.py: Favor list comprehensions over maps

As discussed in CONTRIBUTING.md.

* updating DIRECTORY.md

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
This commit is contained in:
Christian Clauss 2021-08-27 11:45:14 +02:00 committed by GitHub
parent 5e7eed610c
commit 46e56fa6f2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -4,39 +4,34 @@ from typing import List
def is_luhn(string: str) -> bool: def is_luhn(string: str) -> bool:
""" """
Perform Luhn validation on input string Perform Luhn validation on an input string
Algorithm: Algorithm:
* Double every other digit starting from 2nd last digit. * Double every other digit starting from 2nd last digit.
* Subtract 9 if number is greater than 9. * Subtract 9 if number is greater than 9.
* Sum the numbers * Sum the numbers
* *
>>> test_cases = [79927398710, 79927398711, 79927398712, 79927398713, >>> test_cases = (79927398710, 79927398711, 79927398712, 79927398713,
... 79927398714, 79927398715, 79927398716, 79927398717, 79927398718, ... 79927398714, 79927398715, 79927398716, 79927398717, 79927398718,
... 79927398719] ... 79927398719)
>>> test_cases = list(map(str, test_cases)) >>> [is_luhn(str(test_case)) for test_case in test_cases]
>>> list(map(is_luhn, test_cases))
[False, False, False, True, False, False, False, False, False, False] [False, False, False, True, False, False, False, False, False, False]
""" """
check_digit: int check_digit: int
_vector: List[str] = list(string) _vector: List[str] = list(string)
__vector, check_digit = _vector[:-1], int(_vector[-1]) __vector, check_digit = _vector[:-1], int(_vector[-1])
vector: List[int] = [*map(int, __vector)] vector: List[int] = [int(digit) for digit in __vector]
vector.reverse() vector.reverse()
for idx, i in enumerate(vector): for i, digit in enumerate(vector):
if i & 1 == 0:
if idx & 1 == 0: doubled: int = digit * 2
doubled: int = vector[idx] * 2
if doubled > 9: if doubled > 9:
doubled -= 9 doubled -= 9
check_digit += doubled check_digit += doubled
else: else:
check_digit += i check_digit += digit
if (check_digit) % 10 == 0: return check_digit % 10 == 0
return True
return False
if __name__ == "__main__": if __name__ == "__main__":
@ -44,3 +39,4 @@ if __name__ == "__main__":
doctest.testmod() doctest.testmod()
assert is_luhn("79927398713") assert is_luhn("79927398713")
assert not is_luhn("79927398714")