Reputation: 609
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
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
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
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
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:
s
in words using split()
n
1
for each of those that meet the condition1
sUpvotes: 5