【发布时间】:2019-03-25 19:50:34
【问题描述】:
我正在 Python 3 中编写一个名为 word_count 的函数(它接受一个参数,我称之为 my_string),它应该计算字符串中的单词数。该字符串可能包含带有多个空格的单词(例如 hello there),并且该函数需要能够计算出它是两个单词。我不应该使用任何内置的 Python 函数,如果遇到任何错误(例如,如果感兴趣的值不是字符串,我也会使用 try-except,除非将执行返回“不是字符串"
我已经能够编写一个函数,并创建了一个名为 numspaces 的计数器变量,我已将其初始化为 0。然后我编写 try,然后编写一个 for 循环,其中包含一个名为 current_character 的索引变量,它将贯穿所有当前my_string 中的字符。我写了一个条件语句,如果 current_character 等于一个空格,numspaces 需要增加 1,并且 numwords(我用来保持字符串中单词总数的变量)等于 numspaces + 1。然后我写了一个 else if 语句,如果 numspaces 等于 0,numwords = 1 并返回 numwords。如果遇到错误,我写了一个 except ,返回“不是字符串”
def word_count(my_string):
numspaces = 0
try:
for current_character in my_string:
if current_character == " ":
numspaces += 1
numwords = numspaces + 1
elif numspaces == 0:
numwords = 1
return numwords
except:
return "Not a string"
以下是一些测试用例,以及使用测试用例时的预期结果:
Word Count: 4
Word Count: 2
Word Count: Not a string
Word Count: Not a string
Word Count: Not a string
print("Word Count:", word_count("Four words are here!"))
print("Word Count:", word_count("Hi David"))
print("Word Count:", word_count(5))
print("Word Count:", word_count(5.1))
print("Word Count:", word_count(True))
当我运行我编写的代码时,我得到以下输出:
Word Count: 4
Word Count: 4
Word Count: Not a string
Word Count: Not a string
Word Count: Not a string
我不知道如何调整我的代码以解决测试用例 2(“Hi David”)之类的问题
【问题讨论】:
标签: python string function for-loop try-catch