akse232
akse232

Reputation: 45

Python - Randomly flipping 2 characters in a word other than the first and last one

This code flips all characters in the word besides the first and last character. How do I make it so that it only randomly flips two characters besides the first and last character?

For example:

computers
cmoputers
comupters
compuetrs

Code:

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

Upvotes: 0

Views: 1086

Answers (3)

Ted Klein Bergman
Ted Klein Bergman

Reputation: 9746

This should work at flipping two letters. If the length of the word is less than or equal to 3, then it cannot be flipped. In that case it just returns the word back.

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)

If you want two random letters to be switched, you can do this:

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)

Upvotes: 1

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95927

The following works using only the standard library. Also, it always chooses 2 distinct characters from inside the string.

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)

Also, you will need to deal with cases were len(word) <= 3: in such cases the random.sample method will throw a ValueError because there won't be enough items to sample from (it samples without replacement). One way is just to return the word in these cases.

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)

Upvotes: 0

Aguy
Aguy

Reputation: 8059

Try to see if this code works for you:

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)

Note that here is is possible that there will be no switch, if ind1 happened to be equal to ind2. If this is not goof you should check for such case.

Upvotes: 1

Related Questions