Posted on:

04 Apr 2023

0

This is my solution (not very similar to the proposed solution)

def check_credit_card(credit_card):
    #transform to string in order to get length and be able to iterate, could as well be a list.
    card_str= str(card)
    # counter to iterate through numbers that are multiplied
    i = len(card_str) - 2
    # counter to iterate through numbers that are not multiplied
    j = len(card_str) - 1
    # variable to maintain the total sum
    sum = 0
    # iteration of multiplied numbers
    while i >= 0:
        # sum of the product's two digits
        sum += (int(card_str[i])*2 // 10) + (int(card_str[i])*2 % 10 )
        i = i - 2
    # iteration of non-multiplied numbers
    while j >= 0:
        sum += int(card_str[j])
        j = j - 2
    # if clause to return results
    if sum % 10 == 0:
        return print('Credit Card valid')
    return print('Credit Card not valid')

Would be curious to know where it fits in terms of performance and big O. 

I didn't go for the loop with i%2 != 0 cause I wasn't sure if the credit card number's length varied. I guess the proposed solution assumes that credit card lengths are always an even number?

0 answers ( 0 marked as helpful)

Submit an answer