Use return of a function in another function

Asked

Viewed 3,098 times

1

I have a function in Python that takes a text and returns 2 lists, one with all the words that appear and the other returns is the number of times each word appears.

def frequencia(lista):
    conv = str(lista)
    plSeparadas = separa_palavras(conv)        

    listUnic = []
    listFreq = []

    for p in plSeparadas:
        if p in listUnic:
            i = listUnic.index(p)
            listFreq[i] = listFreq[i] + 1
        else:
            listUnic.append(p)
            listFreq.append(1)

            xList = listUnic
            xFreq = listFreq

    return xList, xFreq

I need to use this number of times (xFreq) in another function to calculate the mean value of the frequency :

def mediaFreq(listaFrequencia):
    ordenar = sorted(listaFrequencia)
    tamanho = len(ordenar)
    media = tamanho/2
    return(media)

How can I do that ??

3 answers

1

If the method returns a tuple of values it is necessary to use a tuple to receive the return of it.

Applying it to your code would be something like:

xList, xFreq = frequencia(lista)
media = mediaFreq(xFreq)

Example:

def teste():
    return 'A', 'B'

x, y = teste()

print(x)  # A
print(y)  # B

See working on repl.it.

1

def frequencia(lista):
    conv = str(lista)
    plSeparadas = separa_palavras(conv)        

    listUnic = []
    listFreq = []

    for p in plSeparadas:
        if p in listUnic:
            i = listUnic.index(p)
            listFreq[i] = listFreq[i] + 1
        else:
            listUnic.append(p)
            listFreq.append(1)

            xList = listUnic
            xFreq = listFreq

    return xList, xFreq
def mediaFreq(listaFrequencia, xFreq):
    ordenar = sorted(listaFrequencia)
    tamanho = len(ordenar)
    media = tamanho/2
    return(media)
xList, xFreq = frequencia(lista)
media = mediaFreq(listaFrequencia, xFreq)

Just you assign the return values of your function frequency to two variables, which can have any name, just put xList and xFreq to facilitate understanding.

How they were RETORNADAS of function frequencia, now they are in global scope and can then be passed by parameter to their function mediaFreq as follows: media = mediaFreq(listaFrequencia, xFreq). We must not forget to change the input parameters of mediaFreq.

0

As you compact in Return, you have to unzip in the main code of your script. Why variants only stored in the function they have to be unzipped in the main code.

This way the function return will be stored in the global variants of the main code.

xList, xFreq = frequencia(lista)

Browser other questions tagged

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