Last active
March 10, 2023 16:17
-
-
Save JPaulMora/8e573abc67c871d5d174f6bab71c1f56 to your computer and use it in GitHub Desktop.
Validar NIT en Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
def nit_is_valid(nit): | |
if not nit: | |
return True | |
nit_regex = re.compile(r'^\d+(-?\d|k|K)?$') | |
if not nit_regex.match(nit): | |
return False | |
nit = nit.replace('-', '') | |
number = nit[:-1] | |
expected_checker = nit[-1].lower() | |
total = sum((int(digit) * factor) for factor, digit in enumerate(number[::-1], start=2)) | |
modulus = (11 - (total % 11)) % 11 | |
computed_checker = 'k' if modulus == 10 else str(modulus) | |
return expected_checker == computed_checker |
Author
JPaulMora
commented
Mar 10, 2023
- Function and variable names are in snake_case.
- Use of raw string literals (e.g., r'^\d+(-?\d|k|K)?$') for regular expressions.
- Use of string slicing to extract substrings (e.g., nit[:-1] to get all characters except the last one).
- Use of a list comprehension to calculate the sum of the products of the digits and their corresponding factors.
- Use of the sum function instead of a for loop to add up the products.
- Use of the enumerate function to generate the factors in reverse order.
- Use of the [::-1] slicing syntax to reverse the order of the digits.
For readability, you may change total
with this version:
factors = list(range(len(digits) + 1, 1, -1))
products = [int(digit) * factor for digit, factor in zip(digits, factors)]
total = sum(products)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment