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]
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With