0

请考虑到我这样做是为了做作业,我不想使用任何内置方法,我只使用我学到的东西,即 find 方法

我正在尝试计算字符串中单词的数量,但它似乎永远运行?我什sentence.find(" ", last_position) != -1:至在将它作为while True:

def count_words(sentence):
    count = 0
    last_position = 0

    while sentence.find(" ", last_position) != -1:
        count += 1
        last_position = sentence.find(" ", last_position) + 1

    return count + 1 # +1 because essentially we're only count spaces, not words..
4

3 回答 3

2

find中,start参数被解释为切片参数。如果您不熟悉切片,start则包括在内。因此,find搜索包含刚刚找到的字符的索引的字符串。结果,find重复返回相同的索引,从而创建了一个无限循环。

要解决这个问题,正如 jasonharper 提到的,只需添加 1:

last_position = sentence.find(" ", last_position) + 1
于 2019-03-28T02:43:38.360 回答
0

使用现有代码的老派方式。查看更多关于find()

def count_words(sentence):
    count = 0
    last_position = sentence.find(" ", 0)  
    while last_position != -1:
        count += 1
        last_position+=1
        last_position = sentence.find(" ", last_position)

    return count+1

result = count_words('my name is always sunny')
print(result)
于 2019-03-28T02:48:19.807 回答
0

调试(使用 ipython):

In [2]: s = 'asdfasdf asdf asdf asd sdfa'
In [4]: def count_words(sentence):
   ...:     count = 0
   ...:     last_position = 0
   ...:
   ...:     while sentence.find(" ", last_position) != -1:
   ...:         count += 1
   ...:         print(f'count: {count}, position: {last_position}')
   ...:         last_position = sentence.find(" ", last_position)
   ...:         print(f'new position: {last_position}')
   ...:         if count > 4:
   ...:             break
   ...:     return count
   ...:

In [5]: count_words(s)
count: 1, position: 0
new position: 8
count: 2, position: 8
new position: 8
count: 3, position: 8
new position: 8
count: 4, position: 8
new position: 8
count: 5, position: 8
new position: 8
Out[5]: 5

看看为什么:

In [6]: s.find?
Docstring:
S.find(sub[, start[, end]]) -> int

Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end].  Optional
arguments start and end are interpreted as in slice notation.

Return -1 on failure.
Type:      builtin_function_or_method

定影:

In [7]: def count_words(sentence):
   ...:     count = 0
   ...:     last_position = 0
   ...:
   ...:     while sentence.find(" ", last_position) != -1:
   ...:         count += 1
   ...:         last_position = sentence.find(" ", last_position+1)
   ...:     return count
   ...:

In [8]: count_words(s)
Out[8]: 5
于 2019-03-28T02:52:03.763 回答