关于子串替换优化初学者python脚本

时间:2017-10-20 00:09:03

标签: python string char

我在python里辅导一个朋友,我自己并不擅长。作业是编写一个脚本,用于反转某些组成的外星语言,在这些语言中,在添加字母“p”后,它们重复每个元音序列。一些例子:

tomato -> topomapatopo groovy->groopoovybeautiful -> beaupeautipifupul

目标是扭转这一局面。来自groopoovy -> groovy

由于这是荷兰的作业,有一个例外:“ij”被视为元音。所以blijpij -> blij(这会使事情复杂化,我发现)

我的解决方案对我来说似乎很笨重,我对更好,更优雅的解决方案感兴趣。由于这是编程的入门课程,不幸的是,基础知识是关键。

    word = input()
    vowels = ('a', 'e', 'i', 'o', 'u')
    position = 0
    solution = ""
    while position < len(word):
        if word[position] == 'p':       # obviously, search for the letter 'p'
            add = 1                     # keep track of the sub string size
            group = ""
            while True:                 # loop to get consecutive vowels
                if word[position + add] in vowels:
                    group += word[position + add]
                    if word[position + add] == 'i' and word[position + add + 1] == 'j':   # recognize the "ij"
                        group += 'j'
                        add += 1
                    add += 1
                else:
                    break
                if position+add == len(word):       # stay within the bounds of the string
                    break
            add -= 1
            if word[position - add:position].lower() == group.lower() and group != "":
                position += add
            else:

                solution += 'p'
        else:
            solution += word[position]
        position += 1
    print(solution)

2 个答案:

答案 0 :(得分:0)

import re
input_text = "tomato"
encoded = re.sub('([aeiou]+)','\\1p\\1',input_text)
print(encoded)
decoded = re.sub('([aeiou]+)p\\1','\\1',encoded)
print(decoded)

应该只做那个

答案 1 :(得分:0)

对于一个介绍性的Python类,这个怎么样。 顶部有几个例子;只需更改注释#。

而不是检查&#34; p&#34;在每一步,我都会检查元音序列的开头。该序列将始终由&#34; p&#34;终止。这是您不希望将角色附加到解决方案的唯一情况;相反,你想跳到元音序列的末尾。

&#34; ij&#34;是元音不会创造一个特殊情况,因为&#34; i&#34;开始元音序列。

word = "poopoo-poopoo"
# word = "poopooh"
# word = "hijipijinks"
# word = "apapepe"
# word = "copovfepefepe"
vowels = ('a', 'e', 'i', 'o', 'u')
position = 0
solution = ""
vowel_count = 0   # consecutive vowels
while position < len(word):
    c = word[position]
    if vowel_count > 0:
        if c == 'p':
            position += vowel_count + 1
            vowel_count = 0
            continue
        vowel_count += 1
    else:
        if c in vowels:
            vowel_count = 1
    solution += c
    position += len(c)

print(solution)