Shuffle a word in Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Shuffle a word in Python

Going through exercises for my Programming final, and for some reason IDLE is registering an error with this code, haven't been able to figure out why. The exercise is to write a function "Shuffle(A)" which shuffles a strings characters and returns the results, and reiterates for as long as need be. This is the code I have: from random import randint A = input("Enter a word: ") def shuffle(A): wordlen = len(A) A = list(A) for i in range(0,wordlen-1): pos = randint(i+1,wordlen-1) A[i], A[pos] = A[pos], A[i] A = "".join(A) return A print shuffle(A)

9th Dec 2017, 11:57 PM
Ceolan McMullin
Ceolan McMullin - avatar
6 Answers
+ 3
A=input("Enter a word:") def Shuffle(A): ans="" B=list(A) for i in range(len(A)): a=random.randrage(0,len(A) ans+=B[a] B.pop(a) return ans print(Shuffle(A))
10th Dec 2017, 12:03 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 3
There are possible repeats here. So I will make a new code
10th Dec 2017, 12:00 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 1
Thats perfect! silly of me to forget the brackets. How do you make it endable by the user. as in "Would you like to enter another word? y/n" and if it is y, make it go back to the original function.
10th Dec 2017, 12:29 AM
Ceolan McMullin
Ceolan McMullin - avatar
+ 1
cont="y" while cont=="y": #code cont=input("Continue? y/n").lower() print("Ended")
10th Dec 2017, 12:31 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
10th Dec 2017, 12:46 AM
Ceolan McMullin
Ceolan McMullin - avatar
0
Yes. Except it returns an infinite loop
10th Dec 2017, 12:48 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar