Skip to content

Commit 0202859

Browse files
cclaussgithub-actions
authored andcommitted
luhn.py: Favor list comprehensions over maps (TheAlgorithms#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>
1 parent e36abda commit 0202859

File tree

1 file changed

+11
-15
lines changed

1 file changed

+11
-15
lines changed

Diff for: hashes/luhn.py

+11-15
Original file line numberDiff line numberDiff line change
@@ -4,43 +4,39 @@
44

55
def is_luhn(string: str) -> bool:
66
"""
7-
Perform Luhn validation on input string
7+
Perform Luhn validation on an input string
88
Algorithm:
99
* Double every other digit starting from 2nd last digit.
1010
* Subtract 9 if number is greater than 9.
1111
* Sum the numbers
1212
*
13-
>>> test_cases = [79927398710, 79927398711, 79927398712, 79927398713,
13+
>>> test_cases = (79927398710, 79927398711, 79927398712, 79927398713,
1414
... 79927398714, 79927398715, 79927398716, 79927398717, 79927398718,
15-
... 79927398719]
16-
>>> test_cases = list(map(str, test_cases))
17-
>>> list(map(is_luhn, test_cases))
15+
... 79927398719)
16+
>>> [is_luhn(str(test_case)) for test_case in test_cases]
1817
[False, False, False, True, False, False, False, False, False, False]
1918
"""
2019
check_digit: int
2120
_vector: List[str] = list(string)
2221
__vector, check_digit = _vector[:-1], int(_vector[-1])
23-
vector: List[int] = [*map(int, __vector)]
22+
vector: List[int] = [int(digit) for digit in __vector]
2423

2524
vector.reverse()
26-
for idx, i in enumerate(vector):
27-
28-
if idx & 1 == 0:
29-
doubled: int = vector[idx] * 2
25+
for i, digit in enumerate(vector):
26+
if i & 1 == 0:
27+
doubled: int = digit * 2
3028
if doubled > 9:
3129
doubled -= 9
32-
3330
check_digit += doubled
3431
else:
35-
check_digit += i
32+
check_digit += digit
3633

37-
if (check_digit) % 10 == 0:
38-
return True
39-
return False
34+
return check_digit % 10 == 0
4035

4136

4237
if __name__ == "__main__":
4338
import doctest
4439

4540
doctest.testmod()
4641
assert is_luhn("79927398713")
42+
assert not is_luhn("79927398714")

0 commit comments

Comments
 (0)