Creating a word scrambler but it won't work, need help as a beginner

214 views Asked by At

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

2

There are 2 answers

2
ryanpattison On BEST ANSWER

Since you are a beginner, I tried to change your code as little as possible. Mostly you are expecting changes to word to change the contents or your list stringArray. The comments mark the changes and reasons.

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"))
0
Scott Hunter On

Because there had to be a cleaner (and better documented) way to do this:

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