I was trying a leetcode, where we have to calculate the number of words in a sentence. The code I wrote calculates the number of words but for some reason it just appends 1 to the max_words list each time, regardless of the number of words.
JavaScript
x
20
20
1
def mostWordsFound(sentences):
2
max_words=[]
3
for i in range(0,len(sentences)):
4
num_of_words=1
5
for j in range(0,len(sentences[i])):
6
if sentences[i][j]==" ":
7
num_of_words+=1
8
print(num_of_words)
9
if j==len(sentences[i][j])-1:
10
print("reached here")
11
max_words.append(num_of_words)
12
j+=1
13
i+=1
14
print(max_words)
15
16
17
18
sentences = ["please wait.", "continue to fight.", "continue to win."]
19
mostWordsFound(sentences)
20
Advertisement
Answer
You were using len(sentences[i][j])
which will always be 1 because it represents a letter/char
. You need to use len(sentences[i])
to get the length of the sentence. Also there’s no need to use i += 1
or j += 1
as its value will automatically increment in for
loop.
Code after modifications:
JavaScript
1
19
19
1
def mostWordsFound(sentences):
2
max_words=[]
3
for i in range(0,len(sentences)):
4
num_of_words=1
5
for j in range(0,len(sentences[i])):
6
if sentences[i][j]==" ":
7
num_of_words+=1
8
print(num_of_words)
9
if j==len(sentences[i])-1:
10
print("reached here")
11
max_words.append(num_of_words)
12
print(max_words)
13
14
15
16
sentences = ["please wait.", "continue to fight.", "continue to win."]
17
mostWordsFound(sentences)
18
19
However, if you are interested here’s a simple implementation:
JavaScript
1
8
1
def mostWordsFound(sentences):
2
max_words= [sentence.split() for sentence in sentences] # This line splits the word on the basis of a space and creates a list.
3
n_of_words = [len(word) for word in max_words] # This line counts the number of all words in split sentence list.
4
print(n_of_words)
5
6
sentences = ["please wait.", "continue to fight.", "continue to win."]
7
mostWordsFound(sentences)
8