如何在python中将每个其他列表项乘以2

时间:2016-07-15 18:48:58

标签: python

我制作一个验证信用卡的程序,将卡号中的每个其他数字乘以2;在我将数字乘以2后加到不加2的数字之后。所有的两位数字都加上它们的数字之和,因此14变为1 + 4。我在下面有一张照片可以解释这一切。我正在制作一个执行所有步骤的python程序。我已经为它做了一些代码,但我不知道下一步该做什么?请帮助,非常感谢。我的代码无论如何都会返回错误。

enter image description here

class Validator():
    def __init__(self):
        count = 1
        self.card_li = []
        while count <= 16:
            try:
                self.card = int(input("Enter number "+str(count)+" of your card number: "))
                self.card_li.append(self.card)
                #print(self.card_li)
                if len(str(self.card)) > 1:
                    print("Only enter one number!")
                    count -= 1
            except ValueError:
               count -= 1   
        count += 1
        self.validate()

    def validate(self):
        self.card_li.reverse()
        #print(self.card_li)
        count = 16
        while count >= 16:
            self.card_li[count] = self.card_li[count] * 2
            count += 2






Validator()

2 个答案:

答案 0 :(得分:3)

执行该总和:

>>> s = '4417123456789113'
>>> sum(int(c) for c in ''.join(str(int(x)*(2-i%2)) for i, x in enumerate(s)))
70

如何运作

代码由两部分组成。第一部分创建一个字符串,其他每个数字加倍:

>>> ''.join(str(int(x)*(2-i%2)) for i, x in enumerate(s))
'8427226410614818123'

对于字符串x中的每个字符s,这会将字符转换为整数int(x)并将其乘以1或2,具体取决于索引i ,是偶数还是奇数:(2-i%2)。生成的产品将转换回字符串:str(int(x)*(2-i%2))。然后将所有字符串连接在一起。

第二部分对字符串中的每个数字求和:

>>> sum(int(c) for c in '8427226410614818123')
70

答案 1 :(得分:0)

您需要增加count循环内的while()。此外,在进行card_li检查后,将用户输入附加到if..列表。您的 init 方法应如下所示:

def __init__(self):
    count = 1
    self.card_li = []
    while count <= 16:
        try:
            self.card = int(input("Enter number "+str(count)+" of your card number: "))
            if len(str(self.card)) > 1:
                print("Only enter one number!")
            self.card_li.append(self.card)
            count += 1
        except ValueError:
           pass  
    self.validate()

至于你的验证方法,即使根据你所写的逻辑,它似乎也不完整。

相关问题