首页 > 解决方案 > Python:信用卡数字验证

问题描述

我需要实现一个名为“verify”的函数,它接受一个名为“number”的参数,然后检查以下规则:

  1. 第一个数字必须是 4。
  2. 第四位必须比第五位大一;请记住,这些由破折号分隔,因为格式是####-####-####。
  3. 所有数字之和必须能被 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!

标签: python

解决方案


您似乎忘记了您已经转换cardnumber为整数列表。它不再是一个字符串,所以你不需要int每次都使用。要计算总和,您只需要cardnumber[0]*10+cardnumber[1]cardnumber[7]*10+cardnumber[8]


推荐阅读