1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] how to generate correct output using 2 yield statements in coroutine?

Discussão em 'Python' iniciado por Stack, Outubro 7, 2024 às 13:32.

  1. Stack

    Stack Membro Participativo

    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]

    Continue reading...

Compartilhe esta Página