Validating Credit Card Numbers Hackerrank

Viewed 40

This ts My code of Validating Number Cards In Hackerrank I tried many times To Know where is the error but i didn't find Also it work well for single input But if i entered many inputs ex:5, it give me "Index out of range" here is the code

def cal_Redundant(string):                
    """To calculate Redundant String in list """  
   for i in range(len(string)) :        

     if string[i] == string[i+1] and i<=len(string):
        return False 
    else :
        return True
def Validate(string):

 

divide_str_if_slash=string.split('-')  
df=cal_Redundant(divide_str_if_slash)   
divide_str2=[string[x:x+4] for x in range(0,len(string),4)]  
df2=cal_Redundant(divide_str2)   
if len(string) == 19 :  
    for i in range(len(string)) :  
        if string[0] in ['4','5','6'] \  
            and  string[4] == '-' and string[9] == '-' and string[14] == '-' \  
                and 48 <= ord(string[i])  <= 57  \  
                    and df :  
            print('Valid')  
            break   
        else :  
            print('Invalid')  
            break  
elif len(string) == 16 :  
    for i in range(len(string)) :  
        if string[0] in ['4','5','6'] \  
                and 48 <= ord(string[i])  <= 57 \  
                    and df2 :  
            print('Valid')  
            break   
        else :  
            print('Invalid')  
            break  
else :  
    print("InValid")  

if __name__=="__main__":  
    cards = list()  
    for i in range(int(input())):  
        cards.append(input())  
    
    for c in cards:  
        Validate(c)
1 Answers

The way you're checking for use of hyphens is flawed. Consider this invalid credit card number:

4567-4567-4567- 4567

Note the embedded space. So, whilst there are three hyphens, the total length is greater than 19.

You may find this more robust:

def Validate(cc):
    if '-' in cc:
        tokens = cc.split('-')
        if len(tokens) != 4 or any(len(t) != 4 for t in tokens):
            return False
        cc = ''.join(tokens)
    for c in set(cc):
        if c*4 in cc:
            return False
    return len(cc) == 16 and cc.isdigit() and cc[0] in {'4','5','6'}
Related