我們被賦予了將Pig-Latin轉換爲英文的任務。因此對於例如我必須編寫一個程序來轉換豬拉丁語句子:iway ovealay omputeracy ienceascay - 我愛計算機科學。我們也假設我們的程序爲piglatin.py並將其導入由它們提供的不同程序中。所以你可以看到這就是我所做的。豬拉丁文到英文轉換
def toEnglish(s):
words = s.split(" ") ; # split based on space character
for word in words:
if word[-3:] == 'way':
qq = word[:-3]
return qq
elif word[-3:] != 'way':
x = word[:-2]
y = x[::-1]
z = y.index('a')
rrr = int(z)
a = y[:rrr]
d = a[::-1]
b = y[z+1:]
rr = b[::-1]
k = d+rr
return k
我不得不導入到這個程序
import piglatin
choice = input ("(E)nglish or (P)ig Latin?\n")
action = choice[:1]
if action == 'E':
s = input("Enter an English sentence:\n")
new_s = piglatin.toPigLatin(s)
print("Pig-Latin:")
print(new_s)
elif action =='P':
s = input("Enter a Pig Latin sentence:\n")
new_s = piglatin.toEnglish(s)
print("English:")
print(new_s)
#You can just ignore the middle part 'E' of the program.
問題是,當我運行的代碼到這個程序這一點,它只是將第一字我打字。所以,如果我在atabay類型anamay,我只得到'蝙蝠'而不是'蝙蝠俠'。
好的,我得到了解決我的問題。
def toEnglish(s)
words = s.split(" ") ; # split based on space character
k = []
for word in words:
if word[-3:] == 'way':
qq = word[:-3]
k.append(qq)
elif word[-3:] != 'way':
x = word[:-2]
y = x[::-1]
z = y.index('a')
rrr = int(z)
a = y[:rrr]
d = a[::-1]
b = y[z+1:]
rr = b[::-1]
l = d+rr
k.append(l)
return ' '.join(k)
你'return'太早,因此函數永遠只能儘可能的第一個字 – jonrsharpe