How to print an element from a list each time a given method is called?

Asked

Viewed 1,023 times

1

I’m trying to make a game of mathematical expressions in python, but I need my Mandaexp method to return an expression every time it’s called. In this method I have a list called explist, where several expressions are organized according to the user’s difficulty selection. Searching I found some things but the way it is it only returns a list with the indices, ie, a list that goes from 0 to 430. Follow the code part:

class MotorDoJogoSP(object):
import operator
def MandaExp(self, dif):
    Dificultador.Sort = Dicio[dif]
    expr = Dificultador().Sort()
    explist = [operator.attrgetter('expressao')(x) for x in expr]
    resplist = [operator.attrgetter('resposta')(x) for x in expr]
    for e in range(len(explist)):
        yield e

If I do print list(MotorDoJogoSP().MandaExp(dif)) he returns: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ..., 430]

The expected output was the explist elements, each time the method was called an element would come out of the list, Example: 36 + 0, 30/0, ...

  • Explain a little better. What was the expected exit?

1 answer

2

So I added the Dice to a new list, the fix was:

class MotorDoJogoSP(object):
import operator
def MandaExp(self, dif):
    Dificultador.Sort = Dicio[dif]
    expr = Dificultador().Sort()
    explist = [operator.attrgetter('expressao')(x) for x in expr]
    resplist = [operator.attrgetter('resposta')(x) for x in expr]
    for e in explist:
        yield e

And I’m using next() to print one after the other, how many times is called.

  • Yes. Note that instead of using next manually, you can put your call to the generating function MandaExp direct at a command for: for expressao in MandaExp(dif):

Browser other questions tagged

You are not signed in. Login or sign up in order to post.