def sw_count(subword, words): ''' 課題5. 単語の部分文字列 subword と,単語のリスト words を与えられて, subword が words 中の各単語に何回現れるかを数え,辞書として返す関数を作成せよ. 関数を作成したら,以下の通り動作することを確認せよ. In [1]: sw_count('co', ['coffee', 'cocoa']) Out[1]: {'coffee': 1, 'cocoa': 2} In [2]: sw_count('AA', ['A', 'AA', 'AAA', 'AAAA']) Out[2]: {'A': 0, 'AA': 1, 'AAA': 1, 'AAAA': 2} ヒント. リストから辞書を生成する方法は,テキスト 3-1. 辞書 (dictionary) の[29]を参照のこと. 文字列中で,特定の部分文字列が出現する回数を調べる方法は,テキスト 2-1. 文字列 (string) の [51] を参照のこと.
def sw_count(subword, words): res = {} for word in words: res[word] = word.count(subword) return res