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.

JavaScript

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

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

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement