|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 py540105162 于 2018-8-12 17:11 编辑
习题地址:https://fishc.com.cn/thread-42532-1-1.html
题目如下:
2. 编写一个函数 findstr(),该函数统计一个长度为 2 的子字符串在另一个字符串中出现的次数。
例如:假定输入的字符串为“You cannot improve your past,
but you can improve your future. Once time is wasted, life is wasted.”,
子字符串为“im”,函数执行后打印“子字母串在目标字符串中共出现 3 次”。
我的代码如下:
- def findstr(str1, str2):
-
- str1_len = len(str1)
- count = 0
- i = 0
- while i < str1_len and i+1 < str1_len:
- if str2[0] == str1[i] and str2[1] == str1[i+1]:
- count += 1
- i += 2
- print("子字符串在目标字符串中出现%d次" % count)
- str1 = input("请输入目标字符串:")
- str2 = input("请输入子字符串(两个字符):")
- findstr(str1, str2)
复制代码
看上去我的代码没什么问题,但是在完成子字符串输入后,感觉shell就停滞了,没有反应。请问是什么原因导致的?
- def findstr(str1, str2):
- str1_len = len(str1)
- count = 0
- i = 0
- while i < str1_len and i+1 < str1_len:
- if str2[0] == str1[i] and str2[1] == str1[i+1]:
- count += 1
- i += 1
- print("子字符串在目标字符串中出现%d次" % count)
- str1 = input("请输入目标字符串:")
- str2 = input("请输入子字符串(两个字符):")
- findstr(str1, str2)
复制代码
i+=2有两个bug
改成i+=1 为什么要一个一个的移动呢,假如aabcab这里面搜ab 自己想一想
然后就是i+=1多tab了一下 不管count是否加,你都要往后面搜索
|
|