blandman1990
blandman1990

Reputation: 73

how do i find the number of times a word is of len n in python?

I am trying to find the number of times in a list a word is equal to a set length? So for the example: 'my name is ryan' and 2 the function would give me back 2 as the number of times a word has a length of 2. I have:

def LEN(a,b):
'str,int==>int'
'returns the number of words that have a len of b'
c=a.split()
res=0
for i in c:
    if len(i)==b:
        res=res+1
        return(res)

But all this gives me is a res of 1 and doesn't go past the first i with a len of c.

Upvotes: 0

Views: 179

Answers (3)

Volatility
Volatility

Reputation: 32300

You return res inside the for loop, and the program will immediately stop execution once it hits that statement. You can either move it outside the loop, or use this perhaps more pythonic approach:

>>> text = 'my name is ryan'
>>> sum(1 for i in text.split() if len(i) == 2)
2

Or shorter but a little less clear (but and recommended):

>>> sum(len(i) == 2 for i in text.split())
2

The second function is based on that fact that True == 1

Upvotes: 4

arshajii
arshajii

Reputation: 129507

How about:

>>> s = 'my name is ryan'
>>> map(len, s.split()).count(2)
2

Upvotes: 2

jamylak
jamylak

Reputation: 133554

Your function works fine, you are just returning early:

def LEN(a,b):
        'str,int==>int'
        'returns the number of words that have a len of b'
        c= a.split()
        res = 0
        for i in c:
            if len(i)==b:
                res= res + 1
        return(res) # return at the end

This is equivalent to:

>>> text = 'my name is ryan'
>>> sum(len(w) == 2 for w in text.split())
2

Upvotes: 3

Related Questions