ActiveState Code

Recipe 388110: Scramble Word


Scramble word re-arrange characters of word by using simple string manipulation and Random.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Scramble word re-arrange characters of word by using simple string manipulation and Random.
import random
s= raw_input("Give Word:")
n=0
st=[]
while n<>len(s):
    st.append(s[n])
    n=n+1
print st
n=0
rst=[]
while n<>len(s):
    rno=random.randint(0,len(s)-1)
    if rst.count(rno)==0:
        rst.append(rno)
        n=n+1
print rst
n=0
ost=''
while n<>len(s):
    ost=ost+ st[rst[n]]
    n=n+1
print ost

Discussion

Basic string maniplution and use of random. Basic algorithm useful in advance programming.Kids can play as a game.

Comments

  1. 1. At 9:43 a.m. on 21 feb 2005, Anonymous said:

    Another way. This could also be done with:

    import random
    word = raw_input('Word: ')
    print ''.join(random.sample(word, len(word)))
    
  2. 2. At 2:07 a.m. on 15 may 2006, Michael Howells said:

    Heres another way. Heres something I whipped up just then

    def randomize(string):

    string = list(string)
     temp = string[:]
    
    
    for i in range(len(string)):
    
        randomnum = int(random.random()*len(temp))
    
        string[i] = temp[randomnum]
    
        temp.remove(string[i])
    
    
    return ''.join(string)
    

    Basically, what it does is just take in a string, convert it to a list, and make a temporary copy.

    Once it has done this, it then iterates in a loop equal to the length of the original string, and in each loop, takes a random value from the temporary array, and replaces the next position in the original string with this value.

    At the end, the value is removed from the temporary array.

Sign in to comment