一个合法的身份证号码由17位地区、日期编号和顺序编号加1位校验码组成。校验码的计算规则如下:
首先对前17位数字加权求和,权重分配为:{7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};然后将计算的和对11取模得
到值Z;最后按照以下关系对应Z值与校验码M的值:
Z:0 1 2 3 4 5 6 7 8 9 10
M:1 0 X 9 8 7 6 5 4 3 2
现在给定一些身份证号码,请你验证校验码的有效性,并输出有问题的号码。
输入第一行给出正整数N(<= 100)是输入的身份证号码的个数。随后N行,每行给出1个18位身份证号码。
按照输入的顺序每行输出1个有问题的身份证号码。这里并不检验前17位是否合理,只检查前17位是否全为数字且最后1位校验码计算准确。如果所有号码都正常,
则输出“All passed”。
4 320124198808240056 12010X198901011234 110108196711301866 37070419881216001X
12010X198901011234 110108196711301866 37070419881216001X
import sys
WEIGHT = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
M = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]
def is_valid(id_number: str) -> bool:
if len(id_number)!=18:
return False
weighted_sum = 0
for i in range(17):
if not id_number[i].isnumeric():
return False
weighted_sum += WEIGHT[i]*int(id_number[i])
z = weighted_sum % 11
expected_m = str(M[z])
if id_number[17] == expected_m:
return True
return False
if __name__ == '__main__':
n = int(sys.stdin.readline().strip('\n'))
all_pass = True
for _ in range(n):
id_number = sys.stdin.readline().strip('\n')
if not is_valid(id_number):
print(id_number)
all_pass = False
if all_pass:
print('All passed')
import re
T = (7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2)
D = dict(zip(list(range(11)), list('10X98765432')))
def func(s):
L = [eval(i) for i in s[:-1]]
L = [T[i] * j for i,j in enumerate(L)]
Z = sum(L) % 11
M = D[Z]
return M
N = eval(input())
L = [input() for i in range(N)]
L6 = [i for i in L if re.search(r'[^\d]', i[:-1])]
for i in L6: print(i)
L = [i for i in L if not re.search(r'[^\d]', i[:-1])]
L = [i for i in L if func(i) != i[-1]]
for i in L: print(i)
if len(L6) == 0 and len(L) == 0: print('All passed') a=int(input())
ls1=[]
ls=[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
dic={0:'1',1:'0',2:'X',3:'9',4:'8',5:'7',6:'6',7:'5',8:'4',9:'3',10:'2'}
for i in range(a):
b=input()
num=0
Sum=0
if b[:-1].isdigit():
for j in b[:-1]:
Sum=Sum+(int(j)*ls[num])
num+=1
true_18=Sum%11
if dic[true_18]!=b[-1:]:
ls1.append(b)
print(b)
else:
ls1.append(b)
print(b)
if len(ls1)==0:
print('All passed')
flag,Sum = 0,0
weights = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
dictory = "10X98765432"
N = int(input())
for i in range(N):
Sum = 0
Input = input()
IsNumber = Input[:17].isdigit()
if Input[:17].isdigit():
for j in range(17):
Sum += (int(Input[j])*weights[j])
if dictory[Sum%11] != Input[17]:
print(Input)
flag = 1
else:
print(Input)
flag = 1
if flag == 0:
print('All passed')
又来分享Python版了
while True:
try:
num = int(input())
idLists = []
checkCode = "10X98765432"
weights = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
for i in range(num):
idLists.append(input())
wrongResult = []
for i in range(num):
codeSum = 0
if idLists[i][:17].isdigit(): #检查前十七位是否为数字
for j in range(17): #循环加权重
codeSum += weights[j]*int(idLists[i][j])
if checkCode[codeSum%11] != idLists[i][17]:
wrongResult.append(idLists[i])
else:
wrongResult.append(idLists[i])
if len(wrongResult) == 0:
print("All passed")
else:
for i in wrongResult:
print(i)
except Exception:
break