enumerate()
列挙してみましょう! 与えられた文字列に対して、関数 retrieve_character_indices() を定義し、辞書 character_indices を作成します。各キーはその文字列に含まれる一意の文字を表し、対応する値はその文字が文字列内で現れるインデックス(位置)のリストになります。
たとえば、文字列 'ukulele' を retrieve_character_indices() 関数に渡すと、次の出力になります: {'e': [4, 6], 'k': [1], 'l': [3, 5], 'u': [0, 2]}。
この課題では、文字列メソッドは使用しないでください!
この演習はコースの一部です
Pythonでコーディング面接問題を練習する
演習の手順
- 文字列中の文字とそのインデックスを反復する
forループを定義します。 - キーがすでに存在する場合は辞書を更新します。
- キーが存在しない場合は辞書を更新します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
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'))