2017-01-09 101 views
0

指定將給定的字符串轉換爲瑞典強盜語言,這意味着短語中的每個輔音都加上了一個「o」。比如'這很有趣'會變成'tothohisos isos fofunon'。 它還需要在一個函數'翻譯'。讓我知道我做錯了什麼。請儘量相當簡單解釋一下,我不是很先進的:)瑞典強盜翻譯

old_string="this is fun" 

vowels=("a", "A", "e", "E", "i", "I", "o", "O", "u", "U") 

def translate(old_string): 

l=len(old_string) 

for let in old_string[0:l]: 
    for vow in vowels: 
     if let!=vow: 
      print str(let)+'o'+str(let) 

print translate(old_string) 

輸出我得到的是「TOT TOT TOT TOT TOT TOT TOT TOT TOT TOT 無

回答

-1

試試這個:

def translate(old_string): 
    consonants = set("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ") 
    return ''.join(map(lambda x: x+"o"+x if x in consonants else x, old_string)) 

工作小提琴here

編輯:這裏是您的解決方案的一個修正版本:

old_string="this is fun" 

vowels=("a", "A", "e", "E", "i", "I", "o", "O", "u", "U") 

def translate(old_string): 

    l=len(old_string) 
    translated = "" 
    for let in old_string[0:l]: 
     if let not in vowels and let != " ": 
     translated += let + "o" + let 
     else: 
     translated += let 
    return translated 

print translate(old_string) 

工作小提琴here

+0

嘿謝謝,但我不知道什麼地圖和lambda是。你能簡化一下嗎?它可以,如果它需要更多的線路。謝謝! – Addison

+1

你確實意識到這是一個完全不同的解決方案,對吧?而且你引入了更先進的概念?這不是對這個問題的回答。這是「你的」對初始問題的回答。 –

+0

@Addison'map'將一個函數映射到一個集合上,'lambda'允許您創建匿名函數(例如,不綁定到名稱的函數)。你可以閱讀更多關於'lambda'函數[這裏](http://www.secnetix.de/olli/Python/lambda_functions.hawk)。 –

0

你的代碼有許多循環。這是你的代碼變得更加pythonic。

# define vowels as a single string, python allows char lookup in string 
vowels = 'aAeEiIoOuU' 

# do not expand vowels or spaces 
do_not_expand = vowels + ' '  

def translate(old_string): 
    # start with an empty string to build up 
    new_string = '' 

    # loop through each letter of the original string 
    for letter in old_string: 

     # check if the letter is in the 'do not expand' list 
     if letter in do_not_expand: 

      # add this letter to the new string 
      new_string += letter 

     else: 
      # translate this constant and add to the new string 
      new_string += letter + 'o' + letter 

    # return the newly constructed string 
    return new_string 

print translate("this is fun")