Search code examples
pythonscramble

How can I scramble a word with a factor?


I would like to scramble a word with a factor. The bigger the factor is, the more scrambled the word will become.

For example, the word "paragraphs" with factor of 1.00 would become "paaprahrgs", and it will become "paargarphs" with a factor of 0.50.

The distance from the original letter position and the number of scrambled letters should be taken into consideration.

This is my code so far, which only scrambles without a factor:

def Scramble(s): 
    return ''.join(random.sample(s, len(s)))

Any ideas?

P.S. This isn't an homework job - I'm trying to make something like this: http://d24w6bsrhbeh9d.cloudfront.net/photo/190546_700b.jpg


Solution

  • You could use the factor as a number of shuffling chars in the string around. As the factor seem's to be between 0 and 1, you can multiply the factor with the string's length.

    from random import random
    
    def shuffle(string, factor):
        string    = list(string)
        length      = len(string)
        if length < 2:
            return string
        shuffles    = int(length * factor)
        for i in xrange(shuffles):
            i, j    = tuple(int(random() * length) for i in xrange(2))
            string[i], string[j]    = string[j], string[i]
    
        return "".join(string)
    
    x = "computer"
    print shuffle(x, .2)
    print shuffle(x, .5)
    print shuffle(x, .9)
    

    coupmter
    eocpumtr
    rpmeutoc

    If you want the first and the last characters to stay in place, simply split them and add them later on.

    def CoolWordScramble(string, factor = .5):
        if len(string) < 2:
            return string
        first, string, last = string[0], string[1:-1], string[-1]
    
        return first + shuffle(string, factor) + last