Week 2 Problem Set
1. Assume s is a string of lower case characters.
Write a program that counts up the number of vowels contained in the string s. Valid vowels are: ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’. For example, if s = ‘azcbobobegghakl’, your program should print:
“Number of vowels: 5”**
使用for循环:
n = 0
s = 'aabbcceeoo'
for i in range(len(s)):
if s[i] in 'aeiou':
n = n + 1
i = i + 1
print('Number of vowels:' + str(n))
使用while循环:
n = 0
s = 'aabbeeoo'
i = 0
while i <= len(s)-1:
if s[i] in 'aeiou':
n = n + 1
i = i + 1
print('Number of vowels:' + str(n))
小结:
len(s)会得出的是整个字符串的位数n,而range(len(s))返回的会是0–n-1, s[i]中的i的取值应是0–n-1。由此会出现while与for循环在i的取值上的不同写法。
2. Assume s is a string of lower case characters.
Write a program that prints the number of times the string ‘bob’ occurs in s. For example, if s = ‘azcbobobegghakl’, then your program should print
“Number of times bob occurs is: 2”
一开始写的:
n = 0
s = 'azcbobobobegghakl'
i = 0
while i <= len(s)-1:
if s[i] == 'b' and s[i+1] == 'o' and s[i+2] == 'b':
n = n + 1
i = i + 1
print('Number of times bob occurs is:' + str(n))
提交后发现当s='obobobontsbboobiobobd’或 s='eobobgbobqoboboboobboobbobobbbobb’时会报错,意识到问题:当在倒数第三位及之后出现b时,if语句中s[i+2]这个判断便会“string index out of range”,所以应当把i限定在len(s)-3之内,把bob当成一个整体,用它的开头去从前往后寻找,但用它的结尾去给寻找加上结束的限制。
代码修订后如下: