今さらPython3 (33) - 第4章課題

この本の第4章の課題をやってみます。

入門 Python 3

入門 Python 3

4.1
>>> guess_me = 7
>>> if guess_me < 7:
...     print('too low')
... elif guess_me > 7:
...     print('too high')
... elif guess_me == 7:
...     print('just right!')
...
just right!
>>>

if...elif...elseの方がきれいかなとも思ったけど、問題文に7と等しければと書いてあるので、==にしました。。

4.2
>>> guess_me = 7
>>> start = 1
>>> while True:
...     if start < guess_me:
...         print('too low, ', start)
...     elif start == guess_me:
...         print('found it, ', start)
...     elif start > guess_me:
...         print('Oops, ', start)
...         break
...     start += 1
...
too low,  1
too low,  2
too low,  3
too low,  4
too low,  5
too low,  6
found it,  7
Oops,  8
>>>

Whileに条件入れるのかと思ったら、breakさせる練習っぽかったので、このロジックに変更。startに数字以外が入った場合のことも考えて、さらにelse: breakを追加しようと考えたけど、最初の条件文で落ちると思うので敢えて入れず。

4.3
>>> thelist = [3,2,1,0]
>>> for elem in thelist:
...     print(elem)
...
3
2
1
0
>>>

さすがに慣れてます。

4.4
>>> [num for num in range(0,10) if num % 2==0]
[0, 2, 4, 6, 8]
4.5
>>> {num:num * num for num in range(0,10)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

※4.6をやった後に追記。

>>> squares = {num:num * num for num in range(0,10)}
>>> squares
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

これの方が良かったかな。

4.6
>>> {num for num in range(0,10) if num % 2 == 1}
{1, 9, 3, 5, 7}

上のDictも一緒だけど、oddという名前のセットを作れと言っているなら、こうした方が良いのかな。

>>> odd = {num for num in range(0,10) if num % 2 == 1}
>>> odd
{1, 9, 3, 5, 7}
>>>
4.7

タプルの内包表記は作れないという前振りを思い出したけど、あたまに'Got 'とかあるので、yieldを使うパターンかなと想像。

>>> def got_numbers():
...      yield 'Got '
...      for num in range(0, 10):
...          yield num
...
>>> got_numbers2 = got_numbers()
>>> for num in got_numbers2:
...     print(num)
...
Got
0
1
2
3
4
5
6
7
8
9
>>>

できたけど、なんか美しくないな。後ろのfor文でnumで回しているけど、got_numbers()のnumという訳ではないんだね。任意の名称でイケるって事に見える。

>>> for num in got_numbers2:
...     print(num)
...
>>>

いちおう、ジェネレータだよという確認。

4.7 のやり直し (後で追加)
>>> number_thing2 = ('Got' + str(num) for num in range(10))
>>> for x in number_thing2:
...     print(x)
...
Got0
Got1
Got2
Got3
Got4
Got5
Got6
Got7
Got8
Got9

Gotの後ろにスペース忘れたけど、こういうのを期待しているのかなと想像。

4.8
>>> def good():
...     return ['Harry', 'Ron', 'Hermione']
...
>>> good()
['Harry', 'Ron', 'Hermione']
>>>

なんだこれ?こんなんでいいの?

4.9

あれ?ここでジェネレータ関数だって。4.7やり直しかも。

>>> def get_odds():
...     for num in range(0,10):
...         if num % 2 == 1:
...             yield num
...
>>> odds = get_odds()
>>> counter = 0
>>> for x in odds:
...     if counter == 2:
...          print(x)
...     counter += 1
...
5
>>>

答えは正しいけど、やっぱり美しくない。

4.10
>>> def test(func):
...     def new_function(*args, **kwargs):
...         print('start')
...         result = func(*args, **kwargs)
...         return result
...         print('end')
...     return new_function
...
>>> @test
... def print_nums(a):
...     b = [num for num in range(0,a)]
...     return b
...
>>> print_nums(9)
start
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>>

あれ?endがprint()されてない。。。仕切り直し。

>>> def test(func):
...     def new_function(*args, **kwargs):
...         print('start')
...         result = func(*args, **kwargs)
...         print('end')
...     return new_function
...
>>> @test
... def print_nums2(a):
...     b = [num for num in range(0,a)]
...     return b
... 
>>> print_nums2(9)
start
end
>>> 

ファッッッ!!??でも、print('end')の位置はここでよさそう。

>>> @test
... def print_num3(a):
...     b = [num for num in range(0,a)]
...     print(b)
... 
>>> print_num3(5)
start
[0, 1, 2, 3, 4]
end
>>> 

returnじゃなくてprint()にしたら出ました。

4.11

これ、本と同じ感じに出来なかったヤツじゃん。もう1回試してみる。

>>> class OopsException(Exception):
...     pass
... 
>>> try:
...     raise OopsException('Caught an Oops')
... except OopsException as exc:
...     print(exc)
... 
Caught an Oops
>>> 

テキスト丸写しじゃなくて、classを定義しないとダメということね。しかも、Exceptionを継承していないとダメ。

4.12
>>> titles = ['Creature of Habit', 'Crewel Fate']
>>> plots = ['A nun turns into a monster', 'A haunted yarn shop']
>>> movies = zip(titles, plots)
>>> movies
<zip object at 0x10207c248>
>>> dict(zip(titles, plots))
{'Crewel Fate': 'A haunted yarn shop', 'Creature of Habit': 'A nun turns into a monster'}
>>> 

最後になって、結構前の方からの出題に戻ったね。

(つづく)