使用python

时间:2016-11-03 02:32:43

标签: algorithm validation python-3.x sum luhn

这是我正在努力计算信用卡号是否有效的家庭作业。它有许多步骤,并使用其他2个辅助函数。

第一个辅助函数生成一个由n:

中的每个数字组成的列表
def intToList(n):
    strr = [num for num in str(n)]
    theList = list(map(int, strr))
    return theList

第二个辅助函数添加数字中的数字之和。例如:

def addDigits(n):
    sums = 0
    while n:
        if n > 0:        
            sums += n % 10
            n //= 10
        else:
            return
    return sums

>>>(332) #(3+3+2) = 7
>>> 7

因此,我正在处理的功能是假设验证一个16位数的信用卡号码。它按照给定的顺序具有特定的命令。

  1. 验证它仅包含数字。 #Done。
  2. 验证它是16位数。 #Done。
  3. 如果n是字符串,则将其转换为整数。
  4. 使用函数intToList(n)创建一个列表。
  5. 将intToList(n)生成的列表的奇数索引乘以2,使用函数addDigits(n)将产生两位数字的任何产品替换为数字的总和。
  6. 计算我的intToList(n)列表中所有单个数字的总和。如果总和等于0模10,则原始值n是有效的信用卡号。
  7. 截至目前,我有这个:

    def checkCreditCard(n):
        #Suppose to convert n to int.
        n = int(n)
        #Helper function 1 to make a list.
        myList = intToList(n)
        #For loop to apply the math to each odd indices.*
        for ele in myList:
            if ele % 2 == 1:
                ele *= 2
            if ele >= 10:
                single = addDigits(?) #not sure what to put I've tried everything
            if sum(myList) % 10 == 0:
                return True
            return False
    

    这是我的问题,我不确定从哪里开始。我很确定上面的代码到目前为止是正确的,但我不知道如何使用我的函数将产生两位数字的产品计算为单位数字,并计算所有单个数字的总和。列表。

    非常感谢任何帮助。如果我能搞清楚,请告诉我。

    添加了我所做的工作。

1 个答案:

答案 0 :(得分:1)

简单技巧:可以通过减去9来计算10到18之间所有数字的数字之和(用于加倍或添加单个数字值的可能的两位数值)。因此,如果您有可能的单个,可能是两位数的值,则可以将其用作单个数字:

singledigit = maybetwodigit - 9 * (maybetwodigit >= 10)

对于记录,您编写的代码正确:

def checkCreditCard(n):
    #My checks for length and digits.
    if len(str(n)) == 16 and str(n).isdigit():
        return True
    else:
        return False
    # nothing at this line or below will ever execute, because both your if
    # and else conditions return

此外,您的(当前未使用的)循环将永远不会起作用,因为您没有分配您计算的内容。你可能想要这样的东西:

for i, ele in enumerate(myList):
    if i % 2 == 1:
        ele *= 2
        myList[i] = ele - 9 * (ele >= 10)  # Seamlessly sum digits of two digit nums