Reputation: 33
I have an list and through a for loop I must calculate the number of words in that list that have more than five letters and print the number.
but I have an error that is the following:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5444/3081067402.py in <module>
7 for i in words:
8 if len(words)>5:
----> 9 more_than_five.append(words.sum(i))
10
11 print(more_than_five)
C:\ProgramData\Anaconda3\lib\site-packages\numpy\core\_methods.py in _sum(a, axis, dtype, out, keepdims, initial, where)
45 def _sum(a, axis=None, dtype=None, out=None, keepdims=False,
46 initial=_NoValue, where=True):
---> 47 return umr_sum(a, axis, dtype, out, keepdims, initial, where)
48
49 def _prod(a, axis=None, dtype=None, out=None, keepdims=False,
TypeError: cannot perform reduce with flexible type
this is my code:
list_countries = 'Japan, Singapore, Maldives, Europe, Italy, Korea'
words = np.array(list_countries.split())
more_than_five = []
for i in words:
if len(words)>5:
more_than_five.append(words.sum(i))
print(more_than_five)
What is causing this error? Can someone help me to correct it?
For example:
list_countries = 'Japan, Singapore, Maldives, Europe, Italy, Korea
the expected output is: 3
Because there are only three words that have more than 5 letters, Singapore, Maldives and Europe.
but instead I get the error that I named them.
Upvotes: 1
Views: 1412
Reputation: 96
Although you've already gotten great solutions to this problem, I thought I'd chime in on what the error means if you run across it in the future. Basically, anytime Python throws a 'TypeError' it means it has ran across a type that confuses it in the given context. In your problem, python is expecting an 'int' or 'float' for the function words.sum(i). However, you have given it a 'str' type, which can't be used for mathematical operations.
Hope this helps in the future!
Upvotes: 0
Reputation: 119
First, what you called a list is in fact a string, so you have to change this string into a list
Then,if you just want the number of words that have more than five letters, "more_than_five" should be an "int"
Here is my proposition:
import numpy as np
list_countries = 'Japan, Singapore, Maldives, Europe, Italy, Korea'
list_countries = list_countries.replace(' ', '').split(',')
more_than_five = 0
for words in list_countries:
if len(words) > 5:
more_than_five += 1
print(more_than_five)
The output:
3
Upvotes: 2
Reputation: 452
You’re using numpy.Array.sum, when you could just find the length of a normal python list, without numpy.
The easiest fix to preserve what you have would be to only do more_than_5.append(i)
, then calculate the sum at the end.
However, you could also do:
list_countries = 'Japan, Singapore, Maldives, Europe, Italy, Korea'
print(len(list(filter(lambda i: len(i)>5, list_countries.split(", ")))))
This is essentially the same thing, just shortened down
Upvotes: 0