Skip to content
Advertisement

calculated value not appended in for loop, instead initialized value is appended

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.

def mostWordsFound(sentences):
    max_words=[]
    for i in range(0,len(sentences)):
        num_of_words=1
        for j in range(0,len(sentences[i])):
            if sentences[i][j]==" ":
                num_of_words+=1
                print(num_of_words)
            if j==len(sentences[i][j])-1:
                print("reached here")
                max_words.append(num_of_words)
            j+=1
        i+=1
    print(max_words)
                    
            
            
sentences = ["please wait.", "continue to fight.", "continue to win."]
mostWordsFound(sentences)

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:

def mostWordsFound(sentences):
    max_words=[]
    for i in range(0,len(sentences)):
        num_of_words=1
        for j in range(0,len(sentences[i])):
            if sentences[i][j]==" ":
                num_of_words+=1
                print(num_of_words)
            if j==len(sentences[i])-1: 
                print("reached here")
                max_words.append(num_of_words)
    print(max_words)
                    
            
            
sentences = ["please wait.", "continue to fight.", "continue to win."]
mostWordsFound(sentences)
 

However, if you are interested here’s a simple implementation:

def mostWordsFound(sentences):
    max_words= [sentence.split() for sentence in sentences] # This line splits the word on the basis of a space and creates a list.
    n_of_words = [len(word) for word in max_words] # This line counts the number of all words in split sentence list.
    print(n_of_words)     
            
sentences = ["please wait.", "continue to fight.", "continue to win."]
mostWordsFound(sentences)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement