enumerate()
Let's enumerate! Your task is, given a string, to define the function retrieve_character_indices()
that creates a dictionary character_indices
, where each key represents a unique character from the string and the corresponding value is a list containing the indices/positions of this letter in the string.
For example, passing the string 'ukulele'
to the retrieve_character_indices()
function should result in the following output: {'e': [4, 6], 'k': [1], 'l': [3, 5], 'u': [0, 2]}
.
For this task, you are not allowed to use any string methods!
Este ejercicio forma parte del curso
Practicing Coding Interview Questions in Python
Instrucciones de ejercicio
- Define the
for
loop that iterates over the characters in the string and their indices. - Update the dictionary if the key already exists.
- Update the dictionary if the key is absent.
Ejercicio interactivo práctico
Pruebe este ejercicio completando este código de muestra.
def retrieve_character_indices(string):
character_indices = dict()
# Define the 'for' loop
for index, character in ____(____):
# Update the dictionary if the key already exists
if character in character_indices:
____[____].____(____)
# Update the dictionary if the key is absent
else:
____[____] = [____]
return character_indices
print(retrieve_character_indices('enumerate an Iterable'))