为什么在某些字符串中跳过重复的字母?



这段代码旨在"分解"给定的字符串

def string_splosions(s):
"""erp9yoiruyfoduifgyoweruyfgouiweryg"""
new = ''
for i in s:
new += s[0:int(s.index(i))+1]
return new

由于某种原因,此代码可以为大多数单词返回正确的"爆炸",但是具有重复字母的单词无法正确打印。 例子。

正确的输出是:

Code --> CCoCodCode
abc  --> aababc
pie  --> ppipie
incorrect outputs when s is
Hello --> HHeHelHelHello (should be HHeHelHellHello)

(注意:在不正确的输出中,倒数第二个重复中应该再有 1 个 l。

您应该转录代码而不是发布图片:

def string_splosion(s):
new = ''
for i in s:
new += s[0:int(s.index(i))+1]
return new

问题是 index(i( 返回该字符的第一个实例的索引,对于 "Hello" 中的两个 l,索引均为 2。 解决方法是直接使用索引,这也更简单:

def string_splosion(s):
new = ''
for i in range(len(s)):
new += s[:i+1]
return new

甚至:

def string_splosion(s):
return ''.join(s[:i+1] for i in range(len(s)))

最新更新