1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonで言語処理100本ノック2015 問題03

Last updated at Posted at 2017-11-21

すっかり2017年も冬でございますね〜

早速ですが問題です

出典はこちら → 言語処理100本ノック

問題03
"Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
という文を単語に分解し,各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ.

実装してみた

python3
s = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."

s = s.replace(',', '').replace('.','')


s_list = s.split()

answer = []

#文字数をカウントし出現順に配列に格納してるとこ
for n in s_list:
    answer.append(len(n))
    
print(answer)

実行結果は以下

結果
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]

#正規表現で実装してみた

py3
import re

s = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."

"""
re.sub(pattern, repl, string, count=0, flags=0)
"""
s = re.sub(r'[,.]', '', s)

s_list = s.split()

answer = []

#文字数をカウントし出現順に配列に格納してるとこ
for n in s_list:
    answer.append(len(n))
    
print(answer)

結果
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]

#備考
・この問題はstr.maketransで実装する場面ではありませんでした
 がしかし、このメソッドは適当な場面では非常に使える代物です。
 こちらのページにmaketransなど文字列置換の処理がわかりやすい実装を掲載されてます

・python3の正規表現の文字列クラスについて →リファレンスはこちら
・去年から10Kg大きい男になりました

1
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?