Skip to content Skip to sidebar Skip to footer

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 ti

Solution 1:

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(1for i in text.split() iflen(i) == 2)
2

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

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

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

Solution 2:

Your function works fine, you are just returning early:

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

This is equivalent to:

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

Solution 3:

How about:

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

Post a Comment for "How Do I Find The Number Of Times A Word Is Of Len N In Python?"