CS入门学习笔记4-MIT 6.00.1x

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当成一个整体,用它的开头去从前往后寻找,但用它的结尾去给寻找加上结束的限制。

代码修订后如下:


                
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值