-1

Beginner python coder here, keep things simple, please.

So, I need this code below to scramble two letters without scrambling the first or last letters. Everything seems to work right up until the scrambler() function.

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"))

The outcome is always:

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

4

2 回答 2

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")
于 2014-11-16T03:15:17.613 回答
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"))
于 2014-11-16T02:50:40.910 回答