Home > database >  function should return a list of all the indexes in the string that have capital letters
function should return a list of all the indexes in the string that have capital letters

Time:01-12

Tried a different approach to what I have seen. Im going through each line of code however I'm not seeing where the issue is with this code

def capital_indexes(s):
    cap_list = []            
    for idx, letter in enumerate(s):
        if letter.isupper() == True:
            cap_list.append(idx)
            return cap_list

CodePudding user response:

the Indentation of return is not right, the return statement is inside the if statement , so after finding first capital it would exit: the right place is outside the for loop:

def capital_indexes(s):
    cap_list = []
    for idx, letter in enumerate(s):
        if letter.isupper():
            cap_list.append(idx)
    return cap_list

CodePudding user response:

You return after first iteration! It should be:

def capital_indexes(s):
    cap_list = []            
    for idx, letter in enumerate(s):
        if letter.isupper():
            cap_list.append(idx)
    
    return cap_list

And as a oddity, you can (and should!) use list comprehesion to make code more concise.

def capital_indexes(s):
    return [idx for idx, letter in enumerate(s) if letter.isupper()]

CodePudding user response:

Ok thank you guys, I have added the corrections but I still don't seem to be getting the index of the capital letters, is it working for you guys?

  •  Tags:  
  • Related