views:

1474

answers:

4

I receive as input a list of strings and need to return a list with these same strings but in randomized order. I must allow for duplicates - same string may appear once or more in the input and must appear the same number of times in the output.

I see several "brute force" ways of doing that (using loops, god forbid), one of which I'm currently using. However, knowing Python there's probably a cool one-liner do get the job done, right?

+5  A: 

Looks like this is the simplest way, if not the most truly random: http://docs.python.org/library/random.html#random.shuffle

MatrixFrog
+1 beat me with less than a second :-)
balpha
+24  A: 
>>> import random
>>> x = [1, 2, 3, 4, 3, 4]
>>> random.shuffle(x)
>>> x
[4, 4, 3, 1, 2, 3]
>>> random.shuffle(x)
>>> x
[3, 4, 2, 1, 3, 4]
John Kugelman
+3  A: 

You'll have to read the strings into an array and then use a shuffling algorithm. I recommend Fisher-Yates shuffle

Charles Ma
Based on a glance at the Wikipedia article, it looks like that's more or less what it's doing anyway. You can read the code in C:\Python26\Lib\random.py (or equivalent for other OS's) and it looks like it's doing the same thing described here: http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modern_method
MatrixFrog
A: 

Given a string str, here is a one-liner:

''.join([str(w) for w in random.sample(str, len(str))])
Yann VR