09. Typoglycemia
問題
スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.ただし,長さが4以下の単語は並び替えないこととする.適当な英語の文(例えば”I couldn’t believe that I could actually understand what I was reading : the phenomenal power of the human mind .”)を与え,その実行結果を確認せよ.
回答例
ここをクリックして回答を見る
import random
def typoglycemia(text): words = text.split(" ") result = [] for word in words: # 4文字より短かったら、そのままにする if len(word) <= 4: result.append(word)
else: s = list(word[1:-1]) # スライスで最初と最後を除いた中間の文字列を取り出し、リストにする random.shuffle(s) # リストの中身をランダムに並び替える s = word[0] + "".join(s) + word[-1] # リストを文字列に戻して、最初と最後の文字を付け足す
result.append(s)
return " ".join(result)
s = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."print(typoglycemia(s))