【问题标题】:Why are repeated letters skipped in some strings? [closed]为什么在某些字符串中会跳过重复的字母? [关闭]
【发布时间】:2018-06-06 23:15:20
【问题描述】:

此代码旨在“分解”给定的字符串 s

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。)

【问题讨论】:

标签: python for-loop indexing


【解决方案1】:

你应该抄录代码而不是张贴图片:

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)))

【讨论】:

  • 递归:return string_splosion(s[:-1]) + s if len(s) > 1 else s :)
猜你喜欢
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多