Skip to content

Commit 1da2a1c

Browse files
authored
♻️ Make checksum calculation more descriptive (#293)
1 parent a31555e commit 1da2a1c

File tree

2 files changed

+6
-8
lines changed

2 files changed

+6
-8
lines changed

pydantic_extra_types/isbn.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
from __future__ import annotations
77

8+
import itertools as it
89
from typing import Any
910

1011
from pydantic import GetCoreSchemaHandler
@@ -35,9 +36,9 @@ def isbn13_digit_calc(isbn: str) -> str:
3536
Returns:
3637
The calculated last digit of the ISBN-13 value.
3738
"""
38-
total = sum(int(digit) * (1 if idx % 2 == 0 else 3) for idx, digit in enumerate(isbn[:12]))
39+
total = sum(int(digit) * factor for digit, factor in zip(isbn[:12], it.cycle((1, 3))))
3940

40-
check_digit = (10 - (total % 10)) % 10
41+
check_digit = (10 - total) % 10
4142

4243
return str(check_digit)
4344

pydantic_extra_types/routing_number.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from __future__ import annotations
66

7+
import itertools as it
78
from typing import Any, ClassVar
89

910
from pydantic import GetCoreSchemaHandler
@@ -83,11 +84,7 @@ def _validate_routing_number(cls, routing_number: str) -> str:
8384
Raises:
8485
PydanticCustomError: If the routing number is incorrect.
8586
"""
86-
checksum = (
87-
3 * (sum(map(int, [routing_number[0], routing_number[3], routing_number[6]])))
88-
+ 7 * (sum(map(int, [routing_number[1], routing_number[4], routing_number[7]])))
89-
+ sum(map(int, [routing_number[2], routing_number[5], routing_number[8]]))
90-
)
91-
if checksum % 10 != 0:
87+
checksum = sum(int(digit) * factor for digit, factor in zip(routing_number, it.cycle((3, 7, 1))))
88+
if checksum % 10:
9289
raise PydanticCustomError('aba_routing_number', 'Incorrect ABA routing transit number')
9390
return routing_number

0 commit comments

Comments
 (0)