Home > Back-end >  List of the indexes of the cappital letters
List of the indexes of the cappital letters

Time:08-29

i want to return a list of the indexes of the capital letters in a word based on a "user_input" word. i tried the code with lot of words and it actually works except wih "TEsT", it returns [0, 1, 0] instead of [0, 1, 3] :\ What's wrong?

I actually just read the similar question here, the answer was using "enumerate" to get the tuple of (index, char) at the same time, and check if the character is capital case. But i still wanna know what's wrong with my code :)

def capital_indexes(string):
    my_list = list(string)
    one_list = []
    for capital in my_list:
        if capital.isupper():
           capital_index = int(my_list.index(capital))
           one_list.append(capital_index)
    print(one_list)
    #return(one_list)
    
    return (one_list)

#capital_indexes("HeLlO")          

user_input = str(input("Enter a word"))
capital_indexes(user_input)

CodePudding user response:

The reason your code returns [0, 1, 0] is because the .index method of a list returns the first instance of the element, so in your example, TEsT has T at index 0 then again at index 3, but int(my_list.index("T")) will always return 0.
Your code will actually always be incorrect for strings with repeated characters,
Ex: AAAA or EVIL EVIL
There are several ways you can solve this, here are two approaches that preserve your code structure

  1. Iterate over the array using its indices rather than elements

     def capital_indexes(string):
         my_list = list(string)
         one_list = []
         for capital_index in range(len(my_list)):
            capital = my_list[capital_index]
            if capital.isupper():
                one_list.append(capital_index)
            print(one_list)
    
         return (one_list)
    
  2. Use enumerate to get element and index at the same time

     def capital_indexes(string):
         my_list = list(string)
         one_list = []
         for capital_index, capital in enumerate(my_list):
             if capital.isupper():
                 one_list.append(capital_index)
             print(one_list)
    
         return (one_list)
    

CodePudding user response:

The problem was with .index function. Try this instead:

  def capital_indexes(string):
        strings_list = list(string)
        store_list = []
        for index in range(len(strings_list)):
            if strings_list[index].isupper():
                store_list.append(index)
        print(store_list)
    
    user_input = str(input("Enter a word: "))
    capital_indexes(user_input)

CodePudding user response:

We can also use the enumerate class to generate the indices of the iterable object.

def capital_indexes(string):
    one_list = []
    for i, char in enumerate(string):
        if char.isupper():
            one_list.append(i)
    print(one_list)
    return one_list


user_input = str(input("Enter a word"))
capital_indexes(user_input)

Here, i will act as the index of the string as the list, and the char will be the element in the string at index i.

CodePudding user response:

When you find an uppercase character in the string, you are searching for the first appearance of that character using the index built-in function. That is why you are getting the 0, 1, 0 for TEsT as you can see, the first occurrence of T is found at index 0.

From Python documentation:

list.index(x[, start[, end]])

Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.

You can keep an index variable and increase it in the loop. Then when you get an uppercase character, you insert the index in the result list.

def capital_indexes(string):
    one_list = []
    i = 0
    for c in string:
        if c.isupper():
            one_list.append(i)
        i  = 1
    return one_list


print(capital_indexes("TEsT"))

Output:

[0, 1, 3]

Alternative solution:

You can use a list comprehension to do the same task:

def capital_indexes(string):
    return [i for i, c in enumerate(string) if c.isupper()]


print(capital_indexes("TEsT"))

References:

  • Related