2016-07-15 23 views
-1

此代碼翻轉除第一個和最後一個字符之外的單詞中的所有字符。我該怎麼做才能讓它只是隨機翻轉除了第一個和最後一個字符之外的兩個字符?Python - 隨機翻轉除第一個和最後一個字以外的字中的2個字符

例如:

computers 
cmoputers 
comupters 
compuetrs 

代碼:

def scramble(word): 
    result = word[0] 

    if len(word) > 1: 
     for i in range(len(word) - 2, 0, -1): 
      result += word[i] 

     result += word[len(word) - 1] 

    return result 


def main(): 
    print ("scrambled interesting python computers") 
    print scramble("scrambled"),scramble("interesting"),scramble("python"), scramble("computers") 

main() 
+0

添加'if'聲明 –

回答

1

這應該在翻轉兩個字母。如果單詞的長度小於或等於3,則不能翻轉。在這種情況下,它只是返回單詞。

from random import randint 

def scramble(word): 
    if len(word) <= 3: 
     return word 
    word = list(word) 
    i = randint(1, len(word) - 2) 
    word[i], word[i+1] = word[i+1], word[i] 
    return "".join(word) 

如果你想切換兩個隨機字母,你可以這樣做:

from random import sample 

def scramble(word): 
    if len(word) <= 3: 
     return word 
    word = list(word) 
    a, b = sample(range(1, len(word)-1), 2) 
    word[a], word[b] = word[b], word[a] 
    return "".join(word) 
+0

我相信OP想要*翻轉*字符,而不是*開關*。 –

+0

謝謝,改變了!很容易修復^^ –

1

嘗試看看,如果這個代碼對你的作品:

import numpy as np 

def switchtwo(word): 
    ind1 = np.random.randint(1, len(word)-1) 
    ind2 = np.random.randint(1, len(word)-1) 
    l = list(word) 
    l[ind1], l[ind2] = l[ind2], l[ind1] 
    return "".join(l) 

注意,這裏可能會有沒有開關,如果ind1碰巧等於ind2。如果不是這樣,你應該檢查這種情況。

+0

請將您導入 –

+0

另外,如果你不想要的模塊* ind1 *能夠等於* ind2 *你總是可以做'while ind2 == ind1:ind2 = np.random.randint(1,len(word)-1)' –

+1

我相信OP想要*翻轉*字符,不*切換*。 –

0

以下作品僅使用標準庫。另外,它總是從字符串中選擇2個不同的字符。

import random 
def scramble2(word): 
    indx = random.sample(range(1,len(word)-1), 2) 
    string_list = list(word) 
    for i in indx: 
     string_list[i], string_list[-i+len(word)-1] = string_list[-i+len(word)-1], string_list[i] 
    return "".join(string_list) 

此外,您將需要處理的案件LEN(字)< = 3:在這種情況下,random.sample方法將拋出一個ValueError,因爲不會有足夠的項目從樣品(其樣品無需更換)。一種方法是在這些情況下返回單詞。

def scramble2(word): 
    try: 
     indx = random.sample(range(1,len(word)-1), 2) 
    except ValueError: 
     return word 
    string_list = list(word) 
    for i in indx: 
     string_list[i], string_list[-i+len(word)-1] = string_list[-i+len(word)-1], string_list[i] 
    return "".join(string_list) 
相關問題