言語処理100本ノックやった 09 #python
過去
#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(inp): inp = inp.split() ans = [] for item in inp: if len(item) > 4: word = [] word.append(item[0]) center = random.sample(item[1:-1], len(item[1:-1])) #Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement. word.append(''.join(center)) word.append(item[-1]) word = ''.join(word) ans.append(word) else: ans.append(item) return ' '.join(ans) print typoglycemia(raw_input()) # (input) I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind # (1st) I cln'dout beveile that I colud autlacly unadsnretd what I was rniadeg : the pnomaehnel power of the haumn mind # (2nd) I cu'nldot bvielee that I cloud acltualy uetnrandsd what I was radieng : the pneonahmel pwoer of the haumn mind # (3rd) I cnduo'lt bileeve that I culod aatlculy unnseradtd what I was riednag : the peahmeonnl peowr of the haumn mind
9.6. random — 擬似乱数を生成する — Python 2.7ja1 documentation
9.6. random — Generate pseudo-random numbers — Python 2.7.10 documentation
スペースで分割、語の長さで場合分け、長かったら最初と最後を除いた (: item[1:-1]) やつに対して random.sample して新しい word に変えて append、 最後につなげる
乱数って名前だけど対象は数じゃなくてもいいんですね
物語の最初と最後はいらない【CD+DVD(特典LIVE映像2曲収録)】
- アーティスト: 石川智晶
- 出版社/メーカー: SPACE SHOWER MUSIC
- 発売日: 2015/09/16
- メディア: CD
- この商品を含むブログ (2件) を見る