Use return of a function in another function

0

I have a function in Python that receives a text and returns 2 lists, one with all the words that appear and the other returns 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 average value of the frequency:

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

How can I do this ??

    
asked by anonymous 13.06.2017 / 13:36

3 answers

1

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

Applying in your code would look 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.

    
13.06.2017 / 14:07
0
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)

You just assign the return values of your frequency function to the two variables, which can have any name, just put xList and xFreq to make it easier to understand.

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

    
13.06.2017 / 14:19
0

As you compact in return, you have to unpack in the main code of your script. Because the variants only stored in the function they have to be uncompressed in the main code.

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

xList, xFreq = frequencia(lista)
    
14.06.2017 / 03:52