我试着按字母顺序数一数最长的字符串
s = 'abcv'
longest = 1
current = 1
for i in range (len(s) - 1):
if s[i] <= s[i+1]:
current += 1
else:
if current > longest:
longest = current
current = 0
i += 1
print longest
对于这个特定的字符串,“Current”以正确的长度4结束,但从不修改最长长度。你知道吗
编辑:下面的代码现在遇到错误
s = 'abcv'
current = 1
biggest = 0
for i in range(len(s) - 1):
while s[i] <= s[i+1]:
current += 1
i += 1
if current > biggest:
biggest = current
current = 0
print biggest
似乎我的逻辑是正确的,但我遇到了某些字符串的错误。:(
虽然网上有打印最长字符串的代码源,但我似乎找不到如何打印最长的字符串。你知道吗
使用while条件循环,然后您可以很容易地定义在什么条件下完成循环。 如果您想长期使用QualityCode: While循环比中断更好,因为您可以在一个地方看到循环条件。在loopbody之间识别简单的中断通常更糟糕。你知道吗
break
将跳转到循环后面(作为for
语句跳转到sam缩进)。continue
将跳转到循环的开头并执行下一次迭代你在
else:
语句中的逻辑不起作用-你需要减少一个缩进。你知道吗检查“实际字符是否小于或等于下一个字符”-如果是这种情况,则需要增加内部计数器,如果较长,则设置longest
你可能会因为
if s[i] <= s[i+1]:
而惹上麻烦-你要一直干到len(s)-1
。"jfjfjf"
是len("jfjfjf") = 6
—您可以从0到5进行迭代—但是if访问s[5]
和s[6]
,这两个值比有个项还多。你知道吗一种不同的方法,不需要遍历显式索引并将其分为两个职责(获取按字母顺序排列的子字符串的列表,首先对它们进行最长排序):
输出:
这个函数返回拆分数组+按长度降序排列。在一个关键的环境中,这比你的内存消耗更多,因为你只缓存一些数字,而另一种方法填充列表并将其复制到一个排序的列表中。你知道吗
要解决代码索引问题,请稍微更改逻辑: 从第二个字符开始,测试前一个字符是否小于这个字符。这样你就可以把这个字符和以前的字符核对一下了
你必须删掉else语句。因为考虑电流刚好超过最长值的情况,即从
current = 3 and longest =3
,电流通过自身递增变成4。现在在这里,您仍然希望它进入if current > longest
语句相关问题 更多 >
编程相关推荐