Is there a better way to calculate Chilean RUT verification digit?

208 Views Asked by At

For those who doesn't know, Chilean RUT is an ID for residents, similar to USCIS#, and is composed by 7-8 numbers followed by a verification digit (calculated by a type of MOD11 check).

I made the next python code to get that number using python lists, but I need to ask if there is a better, newest, smarter or shorter way to obtain it.

MOD11 algorithm used:

  1. ID number of 8 digits
  2. Reverse it
  3. Multiply each digit by 2,3,4,5,6,7,2,3 (i used a 10 length number to try in case of larger number)
  4. Sum the multiplied values and calculate the modulus(%) by 11
  5. The verification digit is 11 - modulus
  6. If digit is 10 show 'K', if it's 11 show '0'.

CODE:

# Function to calculate digit using python lists
def DIG(RUT):
    RUTrev=list(reversed(RUT))
    CAD10=list(str(2345672345))
    calc = list(int(RUTrev[i]) * int(CAD10[i]) for i in range(len(RUT)))
    digit = 11-sum(calc)%11
    if digit==10:
        digit="K"
    elif digit==11:
        digit=0
    else:
        digit=digit
    return digit

# Using the function to show the entire ID
RUT=input("Insert RUT number:/n")
print(f"RUT with digit is: {RUT}-{DIG(RUT)}")

OUTPUT:

Insert RUT number:
12345678
RUT with digit is: 12345678-5
1

There are 1 best solutions below

0
SIGHUP On

Firstly, you should make the return type of your function consistent.

You can enumerate the input value (RUT) easily with map()

Something like this:

def checkDigit(rut):
    m = 2
    _sum = 0
    for d in map(int, reversed(rut)):
        _sum += m * d
        m = 2 if m == 7 else m + 1
    if (r := 11 - (_sum % 11)) == 10:
        return 'K'
    return '0' if r == 11 else str(r)

RUT = '12345678'

print(f'{RUT}-{checkDigit(RUT)}')

Output:

12345678-5