i have var DICTIONARY, which is a dictionary where the keys are English letters and the values are words that start with the corresponding letter. The initial filling of DICTIONARY looks like this:
DICTIONARY = {
'a': 'apple',
'b': 'banana',
'c': 'cat',
'd': 'dog',
...
}
i'm trying to write coroutine called alphabet, which takes letters as input and returns the words associated with the given letter from the DICTIONARY.
Sample Input 1:
coro = alphabet()
next(coro)
print(coro.send('a'))
print(coro.send('b'))
print(coro.send('c'))
Sample Output 1:
text
apple
banana
cat
Sample Input 2:
python
coro = alphabet()
next(coro)
for letter in 'qwerty':
print(coro.send(letter))
Sample Output 2:
text
quail
walrus
elephant
rabbit
tiger
yak
my code uses 2 yields , 1 is assigned as variable:
def alphabet():
while True:
ch = yield
yield DICTIONARY[ch]
however 2 yield statements used in coroutine actually skip 1 value always:
Test input:
coro = alphabet()
next(coro)
print(coro.send('a'))
print(coro.send('b'))
print(coro.send('c'))
Correct output:
apple
banana
cat
Your code output:
apple
None #this is the problem
cat
i dont know how to deal with None and it skips 'b' for banana.
updated:
#still dont really get it how it works
def alphabet(letter='a'):
while True:
letter = yield DICTIONARY[letter]
next(gen)is equivalent togen.send(None)and b)yieldandyield <something>both consume object fed to.send()? Your problem asks you to 1) load the first character (ch = yield) once, and then 2) yield the word, receiving the next character, and repeat.yield. (and you need twoyieldstatements, not only one)