|
| 1 | +def is_valid_renavam(renavam): # type: (str) -> bool |
| 2 | + """ |
| 3 | + Validates the Brazilian vehicle registration number (RENAVAM). |
| 4 | +
|
| 5 | + This function takes a RENAVAM string and checks if it is valid. |
| 6 | + A valid RENAVAM consists of exactly 11 digits. Theast digit a check digit |
| 7 | + calculated from the the first 10 digits using a specific weighting system. |
| 8 | +
|
| 9 | + Args: |
| 10 | + renavam (str): The RENAVAM string to be validated. |
| 11 | +
|
| 12 | + Returns: |
| 13 | + bool: True if the RENAVAM is valid, False otherwise. |
| 14 | +
|
| 15 | + Example: |
| 16 | + >>> is_valid_renavam('35298206229') |
| 17 | + True |
| 18 | + >>> is_valid_renavam('12345678900') |
| 19 | + False |
| 20 | + >>> is_valid_renavam('1234567890a') |
| 21 | + False |
| 22 | + >>> is_valid_renavam('12345678 901') |
| 23 | + False |
| 24 | + >>> is_valid_renavam('12345678') # Less than 11 digits |
| 25 | + False |
| 26 | + >>> is_valid_renavam('') # Empty string |
| 27 | + False |
| 28 | + """ |
| 29 | + |
| 30 | + if len(renavam) != 11 or not renavam.isdigit(): |
| 31 | + return False |
| 32 | + |
| 33 | + ## Calculating the check digit |
| 34 | + digits = [int(digit) for digit in renavam[:10]] # 10 digits |
| 35 | + weights = [3, 2, 9, 8, 7, 6, 5, 4, 3, 2] |
| 36 | + checksum = sum( |
| 37 | + digit * weight for digit, weight in zip(digits, weights) |
| 38 | + ) # Sum of the products of the digits and weights |
| 39 | + |
| 40 | + remainder = checksum % 11 |
| 41 | + check_digit = 0 if remainder == 0 else 11 - remainder |
| 42 | + |
| 43 | + # If the calculated check digit is 0, return False |
| 44 | + if check_digit == 0: |
| 45 | + return False |
| 46 | + |
| 47 | + # Checking if the calculated check digit is equal to the last digit of the RENAVAM |
| 48 | + return int(renavam[-1]) == check_digit |
0 commit comments