I first converted the string to a list, added the lengths of all the words, and divided by the total number of words to get the arithmetic mean.
st = "Yo estoy estudiando programacion"
lt = st.split()
x = 0
for i in lt:
x += len(i)
m_a = x/len(lt)
if len(i) < m_a:
print("las palabras menores a la media: ", i)
elif len(i) > m_a:
print("las palabras mayores a la media:", i)
But the program returns me:
las palabras mayores a la media: programacion
I should go out "studying" too.
Please could you help me.
What happens is that at the end of the cycle
for
the variablei
ends with the valueprogramacion
That is why when making the comparison you are only doing it with the word
programación
and you are not comparing the rest of the words.What you should do is go through the list of words again and compare them against the average, and group those that meet the defined conditions into a separate list.
Another more compact way to solve this problem using the statistics and list comprehension module:
I think here it is about "partitioning" the words once they have been sorted ("lower bound" and "upper bound") around the middle length.
We can generate a list of "tuples" of words and lengths (after the
split
), order them and separate them into a list of words and a list of lengths.Since the elements are corresponding, we partition the list of lengths with bisect and use the partition point in the list of words.
Result
Note:
bisect_right
these words they would remain as "minor" (which makes sense if the mean is not directly an integer). If the mean had to be an integer and they had to be considered as "greater" then it would be necessary to applybisect_left