Welcome, guest | Sign In | My Account | Store | Cart

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

Python, 23 lines
 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

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

2 comments

mhuffnagle 16 years, 9 months ago  # | flag

Another way. This could also be done with:

import random
word = raw_input('Word: ')
print ''.join(random.sample(word, len(word)))
Michael Howells 15 years, 6 months ago  # | flag

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.