Python:从循环创建两个列表并将它们相加

时间:2017-06-24 10:45:42

标签: python cs50

我正在处理CS50的信用项目,我在验证信用卡方面遇到了一些问题。

这里是我创建的函数:

def main():

while True :
    cardnumber = input("Please enter a credit card number: ")
    if cardnumber.isdecimal() and int(cardnumber) > 0 :
        break

count = len(cardnumber)

if count != 13 and count != 15 and count != 16:
    print("INVALID")
else:
    check(count, cardnumber)


def check(length, number):

lenght_max = 15

if length == 15 and int(number[0]) == 3 and (int(number[1]) == 4 or int(number[1]) == 7):
    if validator(number):
        print("AMEX")
elif length == 16 and int(number[0]) == 5 and int(number[1]) <= 5:
    if validator(number):
        print("MASTERCARD")
elif length == 16 or length == 13 and int(number[0]) == 4:
    if validator(number):
        print("VISA")
else:
    print("INVALID")
return number


def validator(num):

sum = 0
while num > 0:
    sum += num % 10
    num = num // 10

return sum
odd = [int(num[i]) * 2 for i in range(1, len(num), 2)]
even = [int(num[i]) for i in range(0, len(num), 2)]

new_sum = sum(validator(x) for x in odd) + sum(even)
if(new_sum % 10 == 0):
    return True
else:
    print("INVALID")

main()

我找到了打印平均值和赔率的方法(也乘以时间2),但现在我必须对摊位求和并检查剩余部分是否为0

Image

这里有完整的说明: http://docs.cs50.net/problems/credit/credit.html

2 个答案:

答案 0 :(得分:1)

编写辅助函数来对数字求和。您需要广泛使用它。

def dig_sum(num):
   sum = 0
   while num > 0:
      sum += num % 10
      num = num // 10

   return sum

num = '378282246310005' # your credit card number
odd = [int(num[i]) * 2 for i in range(1, len(num), 2)] # these two remain the same
even = [int(num[i]) for i in range(0, len(num), 2)]

new_sum = sum(dig_sum(x) for x in odd) + sum(even)
if(new_sum % 10 == 0):
    print('Valid') #valid!

sum(dig_sum(x) for x in odd)将获取odd列表中每个号码的数字总和以及找到结果总和的sum(...)

输入:

'378282246310005'

输出:

Valid

答案 1 :(得分:1)

你的功能的第一个问题是你没有存储偶数/奇数位:你每次构造一个包含一个元素的列表,并打印该元素。

现在由于两位数,只能产生两位数,我们可以使用:

def sum2(x):
    return (2*x)//10 + (2*x)%10

您可以使用以下内容构建所有奇数索引位的列表

odd = [int(number[i]) for i in range(1,length,2)]

偶数索引处的数字相同:

even = [int(number[i]) for i in range(0,length,2)]

现在我们只需使用 sum(..)内置功能来总结数字:

total = sum(sum2(oddi) for oddi in odd) + sum(even)

并检查它是否是10的倍数:

return total%10 == 0

或者把它们放在一起:

def validator(number, length):
    odd = [int(number[i]) for i in range(1,length,2)]
    even = [int(number[i]) for i in range(0,length,2)]
    total = sum(sum2(oddi) for oddi in odd) + sum(even)
    return total%10 == 0

或者我们可以为专家使用以下一个班轮:

from itertools import zip_longest

def validator(number,length):
    numbi = iter(numbi)
    return sum(x+sum2(y) for x,y in zip_longest(numbi,numbi,fillvalue=0))%10 == 0