我正在尝试创建一个函数,对于字符串中的每一个元音,反转said-string (并且当它这样做时包含元音)。对于我的理解来说,这个函数有点复杂,所以我想要一些帮助,或者对它进行详细的分析。但是,我只想使用我目前正在学习的操作符和语句(for/while和if)。如果可能的话,我也想避免使用列表理解.。
--这是输入和输出应该是什么样子:
一个示例输入是reverse_per_vowel('aerith'),它返回'iraeth'
如果我们将该函数的过程分解为步骤,它应该如下所示:
(a)erith→(a)erith (第一个字母是元音,所以它是相反的)。但是,因为它是字符串中的第一个字母,所以没有可见的更改。)
(ae)rith→(ea)rith (第二个字母也是元音,因此字符串中的每个字母都指向并包含元音)。
(eari)th→(irae)th (第四个字母是元音),所以所有通向和包含它的东西也是相反的。请注意,它如何解释字符串中先前反转的字母。)
正如您所看到的,字符串反转的次数是累积的,我不太确定如何为此编写代码。但是,我尝试编写函数的一个组件。
我在尝试什么,
vowellist = 'aeiouAEIOU'
sampleword = 'aerith'
indexlist = []
for i in range(len(sampleword)):
if sampleword[i] in vowel_list:
indexlist.append(i)
indexlist输出:[0, 1, 3]
此摘录不反转字符串的任何部分,但是它返回应该反转字符串的索引。我计划以某种方式将这些索引插入示例单词,并使用:-1反转字符串的一部分。然而,我不知道我会怎么做,也不知道这是否是个好主意。任何帮助都将不胜感激。
发布于 2022-04-10 07:02:34
如果有许多元音,那么重复的倒转似乎是可以避免的,因为第二次逆转在某种程度上是对先前的逆转的撤销。
是的,你可以使用这个算法:
- As long as they are consonants add them to the currently active string
- When it is a vowel, switch the active string to be the other one, and add the vowel there在此过程结束时,反转第二个字符串并返回两个字符串的连接:
VOWELS = set("aeiouAEIOU")
def reverse_per_vowel(s):
endings = ["", ""]
side = 1
for c in reversed(s):
if c in VOWELS:
side = 1 - side # Toggle between 0 and 1
endings[side] += c
return endings[0] + endings[1][::-1]由于该算法不是每次遇到元音时都会倒转,但在结束时只执行一次反转,因此它以线性时间复杂度运行,这与您按字面实现所描述的过程时所得到的结果相反,后者的最坏情况是时间复杂度为O(N)。
通过这种复杂性分析,我假设用字符扩展字符串是一个恒定的时间过程。如果对此有疑问,那么使用两个字符列表来实现它,调用append并在进程结束时执行一个join以获得最终字符串:
VOWELS = set("aeiouAEIOU")
def reverse_per_vowel(s):
endings = [[], []]
side = 1
for c in reversed(s):
if c in VOWELS:
side = 1 - side # Toggle between 0 and 1
endings[side].append(c)
return "".join(endings[0] + endings[1][::-1])发布于 2022-04-10 06:49:01
实现这一目标的一种简单方法是使用递归:
vowels = set('aeiouAEIOU')
def reverse_per_vowel(s):
if not s: # empty string
return ''
beforelast, last = s[:-1], s[-1]
if last in vowels:
return last + reverse_per_vowel(beforelast)[::-1]
return reverse_per_vowel(beforelast) + last
print(reverse_per_vowel('aerith')) # iraeth发布于 2022-04-10 06:51:00
只需简单地修改for循环和一些高级切片,就可以做到这一点:
vowellist = 'aeiouAEIOU'
sampleword = 'aerith'
for i in range(len(sampleword)):
if sampleword[i] in vowellist:
sampleword = sampleword[i::-1] + sampleword[i + 1:]
print(sampleword)每次迭代,如果元音出现,你可以重新分配字符串与新的,部分颠倒。输出:
iraeth你可以帮助我的国家,检查。
https://stackoverflow.com/questions/71814322
复制相似问题