gpt4 book ai didi

python - 如果满足 'if' 条件,有没有办法增加迭代器

转载 作者:太空宇宙 更新时间:2023-11-04 02:07:07 28 4
gpt4 key购买 nike

我正在解决 this HackerRank challenge :

Alice has a binary string. She thinks a binary string is beautiful if and only if it doesn't contain the substring '010'.

In one step, Alice can change a 0 to a 1 or vice versa. Count and print the minimum number of steps needed to make Alice see the string as beautiful.

所以基本上计算传递给函数的字符串 'b' 中 '010' 的出现次数。

一旦 if 语句为真,我想将 i 递增 2,这样我就不会在中包含重叠的 '010' 字符串我的计数

我确实意识到我可以只使用计数方法,但我想知道为什么我的代码没有按照我想要的方式工作。

def beautifulBinaryString(b):
count = 0
for i in range(len(b)-2):
if b[i:i+3]=='010':
count+=1
i+=2
return count

输入:0101010

预期输出:2

我用这段代码得到的输出:3

最佳答案

您计算的是重叠 序列。对于您输入的 0101010,您会找到 010 三次,但中间的 010 与外面的两个 010 序列重叠:

0101010
--- ---
---

您不能在 for 循环中递增 i,因为 for 循环构造 sets i 在顶部。在循环体内给 i 一个不同的值不会改变这一点。

不要使用for 循环;您可以使用 while 循环:

def beautifulBinaryString(b):
count = 0
i = 0
while i < len(b) - 2:
if b[i:i+3]=='010':
count += 1
i += 2
i += 1
return count

如您所述,一个更简单的解决方案是只使用 b.count("010")

关于python - 如果满足 'if' 条件,有没有办法增加迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54427561/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com