'my function keeps checking the same index instead of checking the other index
def capital_indexes(word):
letters = []
capital_letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
index_letters = []
# append letters in the word to a list
for letter in word:
letters.append(letter)
# go through the letters in the list letters
for i in letters:
# checks if the indexes in the list match with the indexes in the list 'capital_leters'
if i in capital_letters:
index_letters.append(word.index(i))
return index_letters
word_capital = capital_indexes('TEsT')
# this should return (0, 1, 3) but it keeps returning (0, 1, 0)
print(word_capital)
Solution 1:[1]
.index returns the first occurrence of a letter, use enumerate and .isupper:
def capital_indexes(word):
return [i for i,l in enumerate(word) if l.isupper()]
Solution 2:[2]
Your code is highly inefficient, for instance the conversion to list is useless (you can iterate over a string), then looping through all capital letters is also inefficient (rather use a set). Finally, your main error resides in the fact that word.index(i) will always return the position of the first match (thus the 0 in place of 3).
Here is an alternative solution:
def capital_indexes(word):
# general case for any given set of characters
from string import ascii_uppercase
letters = set(ascii_uppercase)
return [i for i,c in enumerate(word) if c in letters]
# case for uppercase only
# return [i for i,c in enumerate(word) if c.isupper()]
capital_indexes('TEsT')
# [0, 1, 3]
Solution 3:[3]
This is because T is at index 0 and index 3, so index 0 is returned twice.
Try:
import string
result = [i for i, char in enumerate(word) if char in string.ascii_uppercase]
In your example:
>>> word = "TEsT"
>>> [i for i, char in enumerate(word) if char in string.ascii_uppercase]
[0, 1, 3]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pedro Maia |
| Solution 2 | mozway |
| Solution 3 | ChrisOram |
