python - Python:信用卡数字验证
问题描述
我需要实现一个名为“verify”的函数,它接受一个名为“number”的参数,然后检查以下规则:
- 第一个数字必须是 4。
- 第四位必须比第五位大一;请记住,这些由破折号分隔,因为格式是####-####-####。
- 所有数字之和必须能被 4 整除。 4 如果将前两位数视为两位数,第七位和第八位视为两位数,它们的和必须是 100 这就是我的到目前为止提出:
def verify(number) : # do not change this line!
# write your code here so that it verifies the card number
number_string = number.replace("-","")
cardnumber = [int(n) for n in number_string]
if cardnumber[0] != 4:
return 1
elif cardnumber[3] != cardnumber[4] + 1:
return 2
elif sum(map(int, cardnumber)) % 4 != 0:
return 3
elif cardnumber[0:2] + cardnumber[6:8] != 100:
return 4
return True
# be sure to indent your code!
input = "4002-1001-0000" # change this as you test your function
output = verify(input) # invoke the method using a test input
print(output) # prints the output of the function
# do not remove this line!
解决方案
您似乎忘记了您已经转换cardnumber
为整数列表。它不再是一个字符串,所以你不需要int
每次都使用。要计算总和,您只需要cardnumber[0]*10+cardnumber[1]
和cardnumber[7]*10+cardnumber[8]
。
推荐阅读
- python - 尝试在 geopandas 中使用 to_crs 投影 shapefile 会出错
- android - ROOM 单库多实体,不同表插入查询
- c - Gdb 挂起断点无法解析
- join - 如何使用 InfluxDB 通量查询在 Grafana 中以特定方式合并(连接)两个表?
- django - 重写序列化程序的 update() 函数失败
- google-api - 如何从 Youtube Analytics API 获取观看率?
- security - OpenID Connect 如何处理服务链?
- haskell - 使用过滤器的初学者类型错误
- r - div类抓取
- sql - 如何处理动态查询