2 回答
TA贡献1799条经验 获得超9个赞
此类问题应首先正确解释,然后使用笔和纸,尝试设计一种算法来解决您的问题。然后,您可以对其进行编码,从而生成无错误且功能齐全的代码。这是您解决问题的代码。
def fun(s):
words = s.split()
new_string = ""
vowels = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U")
for word in words:
new_word = ""
flag = False
for i in range(len(word)):
if word[i] in vowels and i>0:
new_word = word[i:] + word[:i] + "ay"
flag = True
break
if word[i] in vowels and i == 0:
new_word = word + "way"
break
if new_word:
new_string += " " + new_word
else:
new_string += " " + word
return new_string
测试用例:
>>> fun("this is a test")
' isthay isway away esttay'
>>> fun("bcd")
' bcd'
>>> fun("how are you today")
' owhay areway ouyay odaytay'
TA贡献1772条经验 获得超8个赞
这就是你的函数应该是什么样子
def pig_latin(s):
VOWELS = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U")
words = s.split()
result = []
for w in words:
if w[0] in VOWELS:
result.append(w + 'way')
else:
for idx, char in enumerate(w):
if char in VOWELS:
result.append(w[idx:] + w[:idx] + 'ay')
break
else:
continue
else:
result.append(w)
return ' '.join(result)
由于您想取出第一个元音之前的所有辅音,您需要遍历每个单词以检查第一个元音的位置。
此外,在执行 时s1.join(s2),您会忘记在单词之间添加额外的空格。
添加回答
举报