2016-07-15 39 views
0

我的函數會隨機翻轉除第一個和最後一個字符之外的一個單詞的2個字符。我想用這個函數來編寫另一個函數build_sentence(string),它使用我的函數來翻譯句子中每個單詞的2個字符。函數build_sentence(string)應該返回一個字符串,其中包含整個句子,其中每個單詞的字母已被scrambled(word)加擾。Python - 翻轉一個句子中每個單詞的2個字符

例如:

I dn'ot gvie a dman for a man taht can olny sepll a wrod one way. (Mrak Taiwn) 

import random 
 

 
def scramble(word): 
 
    i = random.randint(1, len(word) - 2) 
 
    j = random.randint(1, len(word) - 3) 
 
    if j >= i: 
 
     j += 1 
 

 
    if j < i: 
 
     i, j = j, i 
 

 
    return word[:i] + word[j] + word[i + 1:j] + word[i] + word[j + 1:] 
 

 
def main(): 
 
    word = scramble(raw_input("Please enter a word: ")) 
 
    print (word) 
 
    
 
main()

+0

你的邏輯目前看起來不完整,如果用戶輸入一個3個字母的單詞,爲什麼如果'i'大於1就加1到'j'? – depperm

回答

0

假設所以也沒有對錯誤的話用3或你很高興與您現有的字加擾功能(帶有一個小的變化更少的字母):

import random 

def Scramble(word): 
    if len(word) > 3: 
     i = random.randint(1, len(word) - 2) 
     j = random.randint(1, len(word) - 3) 
     if j >= i: 
      j += 1 

     if j < i: 
      i, j = j, i 

     return word[:i] + word[j] + word[i + 1:j] + word[i] + word[j + 1:] 
    else: 
     return word 

def ScrambleSentence(sentence): 
    scrambledSentence = "" 
    for word in str.split(sentence): 
     print(scrambledSentence + "\n") 
     scrambledSentence += Scramble(word) + " " 
    return scrambledSentence.strip() 

def main(): 
    sentence = ScrambleSentence(input("Please enter a sentence: ")) 
    print (sentence) 

main() 
1

您是否嘗試過:

' '.join(scramble(word) for word in phrase.split(' ')) 
相關問題