akse232
akse232

Reputation: 45

Python - Flipping 2 characters of each word in a sentence

My function randomly flips 2 characters of a word besides the first and last character. I want to use this function to write another function build_sentence(string) that uses my function to flip 2 characters of each word in the sentence. The function build_sentence(string) should return a string containing the full sentence where the letters of each word have been scrambled by scrambled(word).

for example:

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

Upvotes: 0

Views: 318

Answers (2)

Tristan Dickson
Tristan Dickson

Reputation: 159

Assuming you're happy with your current word scrambling function (with a small change so it doesn't error on words with 3 or fewer letters):

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

Upvotes: 0

Wayne Werner
Wayne Werner

Reputation: 51807

Have you tried:

' '.join(scramble(word) for word in phrase.split(' '))

Upvotes: 1

Related Questions