1 # 问题描述 计算字符串中的单词数,其中一个单词定义为不含空格的连续字符串
2 # 问题示例: 输入 :"Hello, my name is john" 输出 5
3 class Solution:
4 def count_word(self, string):
5 count = 0
6 for i in range(len(string) - 1):
7 if string[i] != ' ' and (string[i + 1] == ' ' or string[i + 1] == string[-1]):
8 count += 1
9
10 return count
11
12
13 c1 = Solution()
14 print(c1.count_word('i am yu xin'))
15 print(c1.count_word(' i am yu xin'))
16 print(c1.count_word(' i am yu xin'))
17 print(c1.count_word('i am yu xin '))
18 print(c1.count_word('i am yu xin '))
19 print(c1.count_word(' i am yu xin '))
20 print(c1.count_word(' i am yu xin '))
21 print(c1.count_word(' i am yu xin '))
22 print(c1.count_word(' i am yu xin '))
23
24
25
26 # 计算1到2021里面有多少个0
27 sum = 0
28 for i in range(1, 20):
29 sum += (str(i).count('2'))
30 print(sum)