python-3.x - Getting errors in a python code
问题描述
Started learning python a couple weeks back. Wrote a python program to count the number of times the sequence 'bob' appears in a string s:
s=input('Enter String')
a=0
b=1
c=2
count=0
for var in s:
if(s[a]=='b' and s[b]=='o' and s[c]=='b'):
count+=1
if (c<(len(s)-1)):
a+=1
b+=1
c+=1
print(count)
The output shows up properly for strings like 'bobbooboboooblobobbobbc'. But, for strings like 'nqsbobobdbtobob', I'm getting output count two more than the actual count of number of occurrences of 'bob'. Can someone please tell me what the cause might be?
解决方案
The quick answer is to use a custom built function for this as is shown in this post:
But my guess is that you aren't all that interested in finding "bob" in a longer string, but more so figuring out how python works and your logic.
I think that the numbers are off because you are iterating over all of s and then catching the 2 extra characters with your second if statement. It might be cleaner to just do that in the for loop itself:
for a in range(0,len(s)-3):
b = a + 1
c = b + 1
...
and follow that logic.
推荐阅读
- sql - 在sql中连接两个表,一列到多列
- php - 工作工人的数量少于最大池大小
- linux - NASM GNU/Linux 精灵:无法通过 scanf 读取浮点数
- kubernetes - Prometheus 操作员 AlertmanagerConfig 未知字段“webhook_configs”
- c# - 如何在文本框中添加asp:动态控件值
- r - R验证,获取违反规则的行
- c# - EntityFramework Core 过滤父记录以包含基于子用户权限的所有子记录
- reactjs - 从子组件调用时回调函数不起作用
- html - 具有不同高度分量的柱子
- kotlin - 为什么我的微调器不显示所选项目