LoginSignup
5
6

More than 5 years have passed since last update.

「自作Python100本ノック」8日目(半年ぶりの運動:41本〜52本目)

Last updated at Posted at 2018-05-14

「自作Python100本ノック」8日目です。

知り合いに誘われ、突然ですが今週の木曜に1.6km全力で走ることになったので、約半年ぶりに今日はランニングをしてきました。
ずっとパソコンしかやってこなかった身は既にボロボロです。
というかエンジニアのイメージ像って運動できない感じですよね。
「プログラミング = ギークなやつ」 っていう昔のイメージがこれだけプログラミングが一般的になった後も抜けてないんでしょうかね。まあ、どうでもいいや。

さて、
「自作Python100本ノック」とはそもそも何ぞや?
どの程度のレベル感なのか?
どのように進めて行くのか?
など気になる方は詳しくはこちらに整理してありますのでまずはそちらを確認するようお願いします。
それでは始めていきます!(ちなみに今日は、問題上の都合から12問です。)

今回の問題の多くは『入門 Python3』の内容を参考に作られていますので、気になった方は本書を確認して見てください。

Q41: Laser、Claw、SmartPhoneクラスを定義せよ。

条件:
3つのクラスは唯一のメソッドとしてdoes()を持っている。
does()は、"disintegrate" (Laser)、 "crush"(Claw) "shoot" (gun)を返す。
次に、これらのインスタンス(オブジェクト)をひとつずつ持つRobotクラスを定義する。
   

q41.py
#Laserクラス
class Laser:
    def does(self):
        return "disintegrate"

#Clawクラス
class Claw:
    def does(self):
        return "crush"

#Gunクラス
class Gun:
    def does(self):
        return "shoot"

#Robotクラス
class Robot:
    def __init__(self):
        self.laser = Laser()
        self.claw = Claw()
        self.gun = Gun()
    def does(self):
        return '''I have many attachments: My laser is to:  %s, My claw is to: %s , My gun is to: %s ''' % (
        self.laser.does(),
        self.claw.does(),
        self.gun.does() )

robbie = Robot()
print(robbie.does())

Q42: secretというUnicode文字列を作り、"\U0001f4a9"という値を代入して、表示せよ

また、secretのUnicode名を調べよう。
   

q42.py
secret = "\U0001f4a4"
secret

#Unicode名の表示
import unicodedata
print(unicodedata.name(secret))

Q43: UTF-8を使い()、secretをpop_bytesというbytes変数にエンコードせよ。

  

q43.py
pop_bytes = secret.encode("utf-8")
pop_bytes

Q44: UTF-8を使って、pop_bytesをデコードし、pop_stringを表示せよ。

   

q44.py
pop_string = pop_bytes.decode("utf-8")
pop_string

正規表現の基本

次の文について各問に答えよ
sentence = "Chicken Little"

Q45: ソースの先頭が、指定したパターンと一致しているか

   

q45.py
import re
sentence = "Chicken Little"

#ソースの先頭が、指定したパターンと一致しているか
m = re.match("Chi", sentence)
if m:
    print(m.group())

Q46: ソース内に、指定したパターンと一致しているか

   

q46.py
#ソース内に、指定したパターンと一致しているか
m1 = re.match(".*ttle", sentence)# .*(ワイルドカード)を加えることによって先頭じゃない場合もヒットさせることができる、
if m1:
    print(m1.group())

ms = re.search("ttle", sentence) # search()を使うとワイルドカード不要
if ms:
    print(ms.group())

Q47: 文字列の中に"n"を含むの文字列が何個あるか

   

q47.py
#”n”という文字だけヒット
m3 = re.findall("n", sentence)
m3
print(len(m3))

#"n"の後ろに任意の文字1字
#sentenceの最後の"n"がマッチしていないことに注目
m4 = re.findall("n.", sentence)
m4

# 最後の"n"もマッチさせたい場合
m5 = re.findall("n.?", sentence) # 0か1文字の直線の文字にマッチする(オプション)
m5

Q48: "n"を”s”に置きかえよ

   

q48.py
m = re.sub("n", "s", sentence)
m

Q49: 正規表現の活用

以下の詩を元に各問に答えよ

poetry = "We have seen thee, queen of cheese,
    Lying quietly at your ease,
    Gently fanned by evening breeze,
    Thy fair form no flies dare seize.

    All gaily dressed soon you'll go
    To the great Provincial show,
    To be admired by many a beau
    In the city of Toronto.

    Cows numerous as a swarm of bees,
    Or as the leaves upon the trees,
    It did require to make thee please,
    And stand unrivalled, queen of cheese.

    May you not receive a scar as
    We have heard that Mr. Harris
    Intends to send you off as far as
    The great world's show at Paris.

    Of the youth beware of these,
    For some of them might rudely squeeze
    And bite your cheek, then songs or glees
    We could not sing, oh! queen of cheese.

    We'rt thou suspended from balloon,
    You'd cast a shade even at noon,
    Folks would think it was the moon
    About to fall and crush them soon."

Q49:cから始まる全ての単語を表示

    

q49.py
pat = r'\bc\w*'
re.findall(pat, poetry)

#\bで単語同と日非単語の境界を先頭にするという意味である。単語の先頭か末尾を指定するために使う。
#リテラルのcは探している単語の先頭文字.
#\wは任意の単語文字
#*は、前の単語の文字が0個以上という意味
#rは未処理の文字列。(これがないと\bをバックスペースだと認識してしまうので、サーチは失敗する)

Q50: cで始まる全ての4文字単語を表示

    

q50.py
par = r'\bc\w{3}\b'
re.findall(par, poetry)

#\bをつけると「単語」のみ取り出せる。つけないとcで始まる全ての単語の4文字が返されてしまう。

Q51: rで終わる全ての単語を見つけよう。

q51.py
pat_3 = r'\b\w*r\b'
re.findall(pat_3, poetry)

Q52: 3個の連続した母音を含む全ての単語を見つけよう

   

q52.py
pat_4 = r'\b\w*[aiueo]{3}[^aiueo\s]\w*\b'
re.findall(pat_4, poetry)

感想

正規表現はいまだによくわからないです。
インターンで自然言語処理の業務をやっていた時から扱ってはいたんですが、今だに求めているワードを上手く正規表現で表現するのに手間取ります。。

ユニコードのやつはとても面白かったです。
ちょっと1文字だけ変えたりして、どんなものが表示されるか確認すると面白いです。

現在問題のストックが69問あるので、今週中には「自作Python100本ノック」は完成するかと思われます。
明日もまた走らなくは。。。

それでは!

9日目

5
6
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
5
6