iKyriaki
iKyriaki

Reputation: 609

Attempting to print the number of words that have a certain length

The format for this function is numLen(s,n): where s is a string and n is an integer. What the code is supposed to do is return the number of words in the string that have length n, so:

numLen("This is a test", 4)

Would return 2, since two words have 4 characters.

def numLen(s, n):
'''
takes string s and integer n as parameters and returns the number of words
in the string s that have length n
'''
return s.split()
if len(s) == n:
    return 'hello'

I attempted to split the string into a list and check the length of each word in that list, but that didn't seem to work out. The farthest I managed to get was returning "hello" when I replaced 4 with 14, just to see if the length code would work.

Upvotes: 2

Views: 4772

Answers (5)

iratxe
iratxe

Reputation: 77

With this code , you can to obtain the length from each word from you sentence . With python 2.7

a = raw_input("Please give a sentence: ").split() 
for i in range(len(a)):
   print "The Word, ", str(a[i]), " have,", str(len(a[i])), " lengths"

With Python 3.x

 a = input("Please give a sentence: ").split() 
 for i in range(len(a)):
    print ("The Word, ", str(a[i]), " have,", str(len(a[i])), " lengths")   

Upvotes: 0

user1130661
user1130661

Reputation:

This works for me:

def numLen(s, n):
    num = 0
    for i in s.split():
        if len(i) == n:
            num += 1
    return num

Is this what you are going for? This doesn't take into account punctuation (periods, commas, etc.) however.

Upvotes: 0

newtover
newtover

Reputation: 32094

reduce(lambda a, w: a+(len(w)>=4), s.split(), 0)

Upvotes: 2

RocketDonkey
RocketDonkey

Reputation: 37279

Since I'm assuming this is for a class, the below example is a basic way of accomplishing it (although +1 to Oscar Lopez's solution for Pythonicity :) ).

In [1]: def numLen(s, n):
   ...:     # Split your string on whitespace, giving you a list
   ...:     words = s.split()
   ...:     # Create a counter to store how many occurrences we find
   ...:     counter = 0
   ...:     # Now go through each word, and if the len == the target, bump the counter
   ...:     for word in words:
   ...:         if len(word) == n:
   ...:             counter += 1
   ...:     return counter
   ...: 

In [2]: numLen("This is a test", 4)
Out[2]: 2

In [3]: numLen("This is another test", 7)
Out[3]: 1

In [4]: numLen("And another", 12)
Out[4]: 0

Upvotes: 3

Óscar López
Óscar López

Reputation: 236160

Try this:

def numLen(s, n):
    return sum(1 for x in s.split() if len(x) == n)

I'm using a generator expression, it works like this:

  • First, we split the string s in words using split()
  • Then, we filter those words that have exactly length n
  • We add 1 for each of those that meet the condition
  • And finally we add all the 1s

Upvotes: 5

Related Questions