身份证有效性校验
请写代码校验第二代身份证号码有效性。程序接收一个18位的身份证号码和性别,根据以下规则输出号码是有效还是无效。
第二代身份证号组成规则:
a) 身份证号码(18位)= 地址码(6)+ 出生日期码(8)+ 顺序码(3)+校验码(1);
b) 地址码:保证位数合法即可,无需校验合法性;
c) 出生日期码:格式为YYYYMMDD,需校验日期有效性;
d) 顺序码:男性为奇数,女性为偶数;
e) 校验码:
S = ∑(i = 1, 17) { A[i] * W[i] }
Y = S % 11
校验码 N = (12 - Y) % 11
所以N取值范围是0-10,10在身份证号码中用大写字母'X'表示
i:表示号码字符从左至右不包括校验码字符在内的位置序号
A[i]:表示第i位置上的身份证号码字符值
W[i]:表示第i位置上的加权系数,其数列为7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
输入
110101199003071938 Male
输出
Pass
def isTrueDate(a):
"""查询输入日期是否有效"""
# 把年月日剥离出来
year = int(a[0:4])
month = int(a[4:6])
day = int(a[6:])
# 判断月份是否不在0-12的范围内
if month == 0 | month > 12:
return False
# 如果 一三五七八十腊 那么 三十一天永不差
else:
if month == 1 | month == 3 | month == 5 | month == 7 | month == 8 | month == 10 | month == 12:
if day > 31:
return False
# 四六九冬三十天
else:
if month == 4 | month == 6 | month == 9 | month == 11 :
if day > 30:
return False
# 平年二月二十八,但如果年份是400的倍数,二月还是二十九天
else:
if year % 400 != 0 & year % 4 == 0:
if day > 28:
return False
else:
if day > 29:
return False
return True
def check(a):
if not a.isdigit():
return False
else:
# 调用isTRUEDate方法
if isTrueDate(a):
return True
else:
return False
def jiaoyan(num):
result = None
b = num[:-1]
c = num[-1]
lst = ('0','1','2','3','4','5','6','7','8','9','X')
xishu = (7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2)
S = sum([int(b[i])*xishu[i] for i in range(17)])
Y = S % 11
N = (12 - Y) % 11
if N == 10:
result = 'X'
else:
result = str(N)
if result in lst and result == c:
return True
else:
return False
line = input().strip().split()
while True:
num = line[0]
sex = line[1]
if len(num) != 18 or not num[0:6].isdigit():
break
else:
if check(num[6:14]) and int(num[14:17]) % 2 == 0 and jiaoyan(num) and sex == 'Female':
print("Pass")
elif check(num[6:14]) and int(num[14:17]) % 2 == 1 and jiaoyan(num) and sex == 'Male':
print("Pass")
else:
print("Fail")
line = input().strip().split()
低调做人,高调做事

浙公网安备 33010602011771号