Reputation: 95
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]
Upvotes: 5
Views: 5729
Reputation: 304157
If you use a bytearray
, you can use random.shuffle
directly
import random
word = bytearray(raw_input("Enter a word: "))
random.shuffle(word)
Upvotes: 0
Reputation: 236004
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
Upvotes: 4
Reputation: 309919
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.
Upvotes: 1