I am looking for a function or short program that recieves a string (up to 10 letters) and shuffles it.
thanks Ariel
views:
234answers:
3
+6
A:
There is a function shuffle in the random module. Note that it shuffles in-place so you first have to convert your string to a list of characters, shuffle it, then join the result again.
import random
l = list(s)
random.shuffle(l)
result = ''.join(l)
Mark Byers
2010-04-19 14:42:36
@Mark: no (was that wrong?)
N 1.1
2010-04-19 14:45:06
>>> s=string >>>random.shuffle(s)returnn an error
ariel
2010-04-19 14:46:30
@ariel: s="string"
N 1.1
2010-04-19 14:47:48
+4
A:
>>> import random
>>> s="abcdef123"
>>> ''.join(random.sample(s,len(s)))
'1f2bde3ac'
ghostdog74
2010-04-19 14:49:44
that don't give the good result if there is repetition in the string for example s="abcdef123a"
Xavier Combelle
2010-04-19 15:05:06
@Xavier Combelle: It works fine with repetition. Have you tried it?
Daniel Stutzbach
2010-04-19 15:42:19
A:
An alternate take for shuffling a string:
# Python < 3
import random, array
def shuffle_text(text):
if isinstance(text, unicode):
temp= array.array('u', text)
converter= temp.tounicode
else:
temp= array.array('c', text)
converter= temp.tostring
random.shuffle(temp)
return converter()
I added this answer just for completeness' sake; on my slow home server, it is faster for small input strings (but the difference is very small), while it is slower for larger strings.
ΤΖΩΤΖΙΟΥ
2010-04-20 00:06:06