Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomize letters in a word

Tags:

python

the question asks to have to user enter a one word string, then randomize the place of the letters in the word, for example, "hello" can turn into "elhlo"

import random

def word_jumble():
    word = raw_input("Enter a word: ")
    new_word = ""
    for ch in range(len(word)):
        r = random.randint(0,len(word)-1)
        new_word += word[r]
        word = word.replace(word[r],"",1)
    print new_word

def main():
    word_jumble()

main()

I got the program from someone else, but have no idea how it works. can someone explain to me please? I understand everything before

new_word += word[r]
like image 422
Mandy Quan Avatar asked Dec 15 '13 23:12

Mandy Quan


2 Answers

The code is unnecessarily complex, maybe this will be easier to understand:

import random
word = raw_input("Enter a word: ")

charlst = list(word)        # convert the string into a list of characters
random.shuffle(charlst)     # shuffle the list of characters randomly
new_word = ''.join(charlst) # convert the list of characters back into a string
like image 160
Óscar López Avatar answered Sep 22 '22 12:09

Óscar López


r is a randomly selected index in the word, so word[r] is a randomly selected character in the word. What the code does is it selects a random character from word and appends it to new_word (new_word += word[r]). The next line removes the character from the original word.

like image 24
mgilson Avatar answered Sep 19 '22 12:09

mgilson