LoginSignup
2
3

More than 5 years have passed since last update.

Pythonのサブジェネレータへの委譲構文を使ったズンドコキヨシ

Last updated at Posted at 2016-03-21

ふと、あまり使い道の分からなかったサブジェネレータへの委譲構文が使えるのではないか、と思った。
サブジェネレータへの委譲構文ってなに?って方は、公式ドキュメントか、手前味噌ですがこの記事をご覧ください。

(2016/3/22 ちょっと間違ってたので修正)

import random

def zundoko(n=0):
    if n == 5:
        yield 'キ・ヨ・シ!'
        raise StopIteration

    x = random.random() < 0.5
    if x:
        if n < 4:
            yield 'ズン'
        else:
            yield 'ドコ' 
        yield from zundoko(n+1)
    else:
        if n < 4:
            yield 'ドコ'
            yield from zundoko()
        else:
            yield 'ズン'
            yield from zundoko(4)

print(''.join(zundoko()))
2
3
0

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
2
3