-6

For a homework assignment, I am suppose to implement a function numLen() that takes a string s and an integer n as parameters, and returns the number of words in the string s that have length n. Words in the string are non-space characters separated by at least one space.

an example would be to input:

>>> numLen("This is a test", 4)

and get 2 because there are 2 words in the string that have 4 characters.

I have no clue how to do this.

Aleksei Zyrianov
  • 2,294
  • 1
  • 24
  • 32
jr.
  • 7
  • 1
  • This is easily done in python. Look into the split() method and the len() method. – ecline6 Apr 21 '13 at 19:35
  • 4
    [Fellow student of yours?](http://stackoverflow.com/questions/16127550/how-do-i-find-the-number-of-times-a-word-is-of-len-n-in-python) – Cairnarvon Apr 21 '13 at 19:36
  • 2
    And one more! http://stackoverflow.com/questions/16051777/counting-unique-words-of-a-minimum-length-in-a-string My god, I wonder if this teacher knows that nobody in their class wants to learn anything. – ecline6 Apr 21 '13 at 19:53
  • I didn't necessarily mean to ask for the answer, but rather how to begin. – jr. Apr 21 '13 at 20:27
  • @JasonRay You begin by trying something, anything, yourself. A google search for what you're looking for would have pointed you in the right direction. The Python documentation has everything you need to do your homework. Your assignment is trivial and you didn't even try. The same can be said for at least 3 of your classmates. – ecline6 Apr 21 '13 at 20:30

1 Answers1

4

Split the string into words with str.split(), iterate over the words, compare their length to the given number, return the count.

Here's a compact implementation using some builtins:

In [1]: def numLen(s, n):
   ...:     return sum(1 for w in s.split() if len(w) == n)
   ...: 

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

You can exercise by building a version on your own along the lines of

def numLen(s, n):
    words = ... # build a list of separate words
    i = 0 # a counter for words of length n
    for word in words:
        # check the length of 'word'
        # increment the counter if needed
    # return the counter
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175