0

This is a homework assignment that I've been working on to compute if a credit card number is valid. It has many steps and uses 2 other helper functions.

The first helper function makes a list consisting of each digit in n:

def intToList(n):
    strr = [num for num in str(n)]
    theList = list(map(int, strr))
    return theList

The second helper function adds the sum of digits in a number. For example:

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

So the function I am working on is suppose to validate a 16 digit credit card number. It has specific orders to follow in the order given.

  1. Verifies that it contains only digits. #Done.
  2. Verifies that it is 16 digits long. #Done.
  3. if n is a string, it converts it to an integer.
  4. creates a list using the function intToList(n).
  5. Multiplies the odd indices of the list made by intToList(n) by 2 and any products that produce two-digit numbers are replaced by the sum of the digits using the function addDigits(n).
  6. Computes the sum of all the single digits in the list made my intToList(n). If the sum is equal to 0 modulo 10, the original value, n, is a valid credit card number.

As of right now I have this:

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

Here is my issue, I am unsure where to go from here. I am pretty sure the code above is correct so far, but I don't know how to make the products that produce two-digit numbers compute to single digit ones using my function and computes the sum of all the single digits in the list.

Any help would be greatly appreciated. Let me know if I can clear anything up.

added what I've worked on.

4

1 回答 1

1

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

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
于 2016-11-03T03:18:39.273 回答