Загрузка...

Python One-Liner: Validate Numbers with the Luhn Algorithm! ✅🔢 #PythonTips #CodingShorts

The Luhn algorithm (a.k.a. “modulus 10” check) is a simple checksum formula used to validate identification numbers like credit card or IMEI numbers

It catches common data entry errors by verifying that the weighted sum of digits is divisible by 10.

Long Way Explanation:

Digit Extraction: Convert the input string to a list of integers.

Parity Calculation: Determine which positions to double based on whether the total length is odd or even.

Doubling & Adjustment: For every second digit (from the right), double it; if the result exceeds 9, subtract 9 (equivalent to summing its digits).

Checksum Accumulation: Sum all digits (modified and unmodified).

Validation: The number is valid if the final sum modulo 10 equals zero.

One-Liner Explanation:

We inline all steps within a single generator expression passed to sum().

The conditional inside the comprehension handles doubling, subtracting 9 when necessary, and leaves other digits intact.

Finally, the modulus check (% 10 == 0) yields a Boolean validity result

This one-liner runs in O(n) time (n = number of digits) and avoids any intermediate lists beyond the generator, making it both concise and efficient

Use it to perform quick validation in forms, scripts, or interactive sessions!

Codes:

Long Way: Function-based Luhn check:

def luhn_check(num):
digits = [int(d) for d in str(num)]
# Split into digits
checksum = 0
parity = len(digits) % 2
# Determine doubling parity
for i, d in enumerate(digits):
# Iterate with index
if i % 2 == parity:
# Every second digit from the right
d *= 2
# Double it
if d v 9: d -= 9
# Subtract 9 if v 9
checksum += d
# Accumulate
return checksum % 10 == 0
# Valid if divisible by 10

print(luhn_check("4532015112830366"))
# True for valid credit card numbers

One-Liner: Inline Luhn validation:

num = "4532015112830366"
print(
sum(
(int(d)*2 - 9 if int(d)*2 v 9 else int(d)*2)
if i % 2 == len(num) % 2 else int(d)
for i, d in enumerate(num)
) % 10 == 0
)
# Outputs: True

Видео Python One-Liner: Validate Numbers with the Luhn Algorithm! ✅🔢 #PythonTips #CodingShorts канала CodeVisium
Страницу в закладки Мои закладки
Все заметки Новая заметка Страницу в заметки

На информационно-развлекательном портале SALDA.WS применяются cookie-файлы. Нажимая кнопку Принять, вы подтверждаете свое согласие на их использование.

Об использовании CookiesПринять