How to multiply every other list item by 2 in python -
i'm making program validates credit card, multiplying every other number in card number 2; after i'll add digits multiplied 2 ones not multiplied 2. of double digit numbers added sum of digits, 14 becomes 1+4. have photo below explains all. i'm making python program of steps. i've done code below it, have no idea next? please help, , appreciated. code have returns error anyway.
class validator(): def __init__(self): count = 1 self.card_li = [] while count <= 16: try: self.card = int(input("enter number "+str(count)+" of card number: ")) self.card_li.append(self.card) #print(self.card_li) if len(str(self.card)) > 1: print("only enter 1 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()
to perform sum:
>>> s = '4417123456789113' >>> sum(int(c) c in ''.join(str(int(x)*(2-i%2)) i, x in enumerate(s))) 70
how works
the code consists of 2 parts. first part creates string every other number doubled:
>>> ''.join(str(int(x)*(2-i%2)) i, x in enumerate(s)) '8427226410614818123'
for each character x
in string s
, converts character integer, int(x)
, multiplies either 1 or 2 depending on whether index, i
, or odd: (2-i%2)
. resulting product converted string: str(int(x)*(2-i%2))
. strings joined together.
the second part sums each digit in string:
>>> sum(int(c) c in '8427226410614818123') 70
Comments
Post a Comment