【发布时间】:2017-10-20 00:09:03
【问题描述】:
我正在给一个朋友辅导 python,我自己并不擅长。任务是编写一个脚本来反转一些编造的外星语言,在这些语言中,他们在添加字母“p”后重复每个元音序列。一些例子:
tomato -> topomapatopogroovy->groopoovy和beautiful -> 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)
【问题讨论】: