+ 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)
7 Réponses
+ 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))
+ 3
There are possible repeats here. So I will make a new code
+ 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.
+ 1
cont="y"
while cont=="y":
#code
cont=input("Continue? y/n").lower()
print("Ended")
+ 1
Like this? https://code.sololearn.com/c2YgqplKDODr/#py
0
Yes. Except it returns an infinite loop