创建一个单词扰码器,但它不会起作用,需要初学者的帮助

时间:2014-11-16 02:39:49

标签: python word scramble

这里有初学python编码器,请保持简单。

所以,我需要下面的代码来加扰两个字母而不会扰乱第一个或最后一个字母。在scrambler()函数之前,一切似乎都有效。

from random import randint
def wordScramble(string):
    stringArray = string.split()
    for word in stringArray:
        if len(word) >= 4:
            letter = randint(1,len(word)-2)
            point = letter
            while point == letter:
                point = randint(1, len(word)-2)
            word = switcher(word,letter,point)
    ' '.join(stringArray)
    return stringArray
def switcher(word,letter,point):
    word = list(word)
    word[letter],word[point]=word[point],word[letter]
    return word
print(wordScramble("I can't wait to see how this turns itself out"))

结果总是:

I can't wait to see how this turns itself out

2 个答案:

答案 0 :(得分:0)

由于您是初学者,我尝试尽可能少地更改您的代码。大多数情况下,您希望更改word以更改内容或列表stringArray。评论标志着变化和原因。

from random import randint

def wordScramble(myString): # avoid name clashes with python modules
    stringArray = myString.split() 
    for i, word in enumerate(stringArray):   # keep the index so we can update the list
        if len(word) >= 4:
            letter = randint(1,len(word)-2)
            point = letter
            while point == letter:
                point = randint(1, len(word)-2)
            stringArray[i] = switcher(word,letter,point)  # update the array
    return ' '.join(stringArray)   # return the result of the join

def switcher(word,letter,point):
    word = list(word)
    word[letter],word[point]=word[point],word[letter]
    return ''.join(word)  # return word back as a string

print(wordScramble("I can't wait to see how this turns itself out"))

答案 1 :(得分:0)

因为 是更清洁(并且记录更好)的方法:

from random import sample

def wordScramble(sentence):
    # Split sentence into words; apply switcher to each; rejoin into a sentence
    return ' '.join([switcher(x) for x in sentence.split()])

def switcher(word):
    if len(word) <= 3: # Don't bother if not enough letters to scramble
        return word

    # Pick 2 positions from interior of word
    a,b = sorted(sample( xrange(1,len(word)-1), 2 ))

    # Re-assemble word with out 2 positions swapped using bits before, between & after them
    return word[:a] + word[b] + word[a+1:b] + word[a] + word[b+1:]

print wordScramble("I can't wait to see how this turns itself out")