Skip to content

Instantly share code, notes, and snippets.

@JPaulMora
Last active March 10, 2023 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JPaulMora/8e573abc67c871d5d174f6bab71c1f56 to your computer and use it in GitHub Desktop.
Save JPaulMora/8e573abc67c871d5d174f6bab71c1f56 to your computer and use it in GitHub Desktop.
Validar NIT en Python
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
@JPaulMora
Copy link
Author

  • 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.

@JPaulMora
Copy link
Author

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