2017-01-09 6 views
0

指定されたストリングをスウェーデンの強盗の言葉に変えるために割り当てられています。つまり、フレーズのすべての子音が、その間に置かれた 'o'で2倍になります。例えば、「これは楽しい」という言い方は、「tothohisos isos fofunon」に変わるでしょう。 また、 'translate'関数内にある必要があります。私が間違っていることを教えてください。かなり簡単に説明しようとしてください、私は非常に進んでいないよ:)スウェーデンの強盗の翻訳

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 なし

答えて

-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

EDIT

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

おかげさまで、私はマップとラムダが何であるか分かりません。多分それを少し簡略化できますか?それはカップルより多くの行がかかる場合、その大丈夫。ありがとう! – Addison

+1

これはまったく別の解決策であることを理解していますか?そして、あなたはより高度な概念を導入しましたか?これは質問に対する答えではありません。これは最初に述べた問題に対する「あなたの」答えです。 –

+0

@Addison 'map'は関数をコレクションにマッピングし、' lambda'は匿名関数(例えば名前に束縛されていない関数)を作成することを可能にします。 'lambda'関数[here](http://www.secnetix.de/olli/Python/lambda_functions.hawk)の詳細を読むことができます。 –

0

コードには1つのループが多数ありました。あなたのコードはもう少し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") 
関連する問題