Created
March 1, 2023 07:11
-
-
Save sae13/2902f0dfaec5fefdb758eef0b574ae4b to your computer and use it in GitHub Desktop.
code melli generator validator
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 random | |
class NationalCode: | |
code_melli:str = None | |
def __init__(self,code_melli:str|int=None,starts_with='',with_numbers=[0,1,2,3,4,5,6,7,8,9]): | |
self.code_melli=str(code_melli).rjust(10,'0') | |
if code_melli is not None: | |
self.validate() | |
else: | |
self.code_melli=self.generate(with_numbers=with_numbers,starts_with=starts_with) | |
def validate(self): | |
if len(self.code_melli)!= 10: | |
raise Exception('wrong length') | |
sum_ = sum([(10 - i)*(int(self.code_melli[i])) for i in range(9)]) | |
calc = sum_ % 11 | |
if calc != int(self.code_melli[9]) and 11 - calc != int(self.code_melli[9]) : | |
raise Exception(f'national code is not valid {self.code_melli}') | |
print(f'national code is valid: {self.code_melli}') | |
return True | |
@staticmethod | |
def generate(with_numbers=[0,1,2,3,4,5,6,7,8,9],starts_with=''): | |
code_melli = starts_with | |
for i in range(9 - len(starts_with)): | |
code_melli+=str(with_numbers[random.randint(0,len(with_numbers) - 1)]) | |
sum_ = sum([(10 - i)*(int(code_melli[i])) for i in range(9)]) | |
code_melli+=str(sum_%11 if sum_%11 < 2 else 11 - (sum_%11) ) | |
print(f'generated national code: {code_melli}') | |
return code_melli | |
NationalCode(69965) | |
NationalCode('0000069991') | |
NationalCode(starts_with='00000069',with_numbers=[6,9]) |
Author
sae13
commented
Mar 1, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment