When I was tasting Python recently, I had a good task called Zundokokiyoshi, so I made it. Is it only Python-like using a generator?
zundoko.py
import random
def zundoko_gen():
while True:
yield random.choice(('Dung', 'Doco', 'Huh'))
class ZunDokoChecker:
def __init__(self):
self.zun_count = 0
def check(self, word):
if word == 'Doco':
result = self.zun_count >= 4
self.zun_count = 0
else:
self.zun_count = self.zun_count + 1 if word == 'Dung' else 0
result = False
return result
checker = ZunDokoChecker()
for word in zundoko_gen():
print(word)
if checker.check(word):
print('Ki yo shi!')
break
I got a theme from shiracamus, so I made it immediately.
zundoko2.py
import random
def zundoko_gen():
zun_count = 0
word_list = ('Dung', 'Doco', 'Huh')
while True:
word = random.choice(word_list)
yield word
if word == 'Dung':
zun_count += 1
else:
if word == 'Doco' and zun_count >= 4:
return
zun_count = 0
for word in zundoko_gen():
print(word);
print('Ki yo shi!')
I tried to devise it, but when I detected the completion of Zundoko, I had to notify the end of generation with the next value return, but at first I did it with a flag.
Since yield is used, the value is returned for the time being, and then it is judged as the end, so it was refreshing without a flag.
It's a hobby to get word_list out of the innermost loop. Since it is a built-in shop, I was worried about creating a list instance every time with the BUILD_LIST command.
Recommended Posts