1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
from cs50 import get_int, get_string
americanExpressLength = 15
masterCardLength = 16
visaLength = 13
americanExpressStarts = [34, 37]
masterCardStarts = [51, 52, 53, 54, 55]
visaStart = 4
def main():
number = get_string("Number: ")
# 把号码依次变成数字存到数组
numbers = [int(c) for c in number]
count = len(numbers)
# 开头两位数
starts = int(str(numbers[0]) + str(numbers[1]))
valid = validate(numbers)
if not valid:
print("INVALID\n")
exit(1)
if isAmericanExpress(count, starts):
print("AMEX\n")
exit(0)
elif isMasterCard(count, starts):
print("MASTERCARD\n")
exit(0)
elif isVisa(count, starts, numbers):
print("VISA\n")
exit(0)
else:
print("INVALID\n")
exit(1)
# 验证号码是否正确
def validate(numbers):
nums = [];
for num in range(len(numbers) - 2, -1, -2):
i = numbers[num] * 2
if i < 10:
nums.append(i)
else:
tmp = str(i)
nums.append(int(tmp[0]))
nums.append(int(tmp[1]))
total = sum(nums)
for num in range(len(numbers) - 1, -1, -2):
total += numbers[num]
if int(str(total)[-1]) == 0:
return True
else:
return False
def isAmericanExpress(count, starts):
return count == americanExpressLength and starts in americanExpressStarts
def isMasterCard(count, starts):
return count == masterCardLength and starts in masterCardStarts
def isVisa(count, starts, numbers):
if count == masterCardLength or count == visaLength:
if numbers[0] == visaStart:
return True
return False
if __name__ == "__main__":
main()
|