OT--Shuffling, was Re: invert or reverse a string... warning this is a rant
J. Clifford Dyer
jcd at sdf.lonestar.org
Thu Oct 19 14:14:33 EDT 2006
Demel, Jeff wrote:
> P.S. How about a string.shuffle() method that splits the string in half
> into two new strings str1 and str2, and then recompiles the string by
> alternating one character from each str1 and str2 as it goes? Like
> shuffling cards. ;)
Jeff,
To my mind that would be the exact opposite of shuffling a deck of
cards. In your case, each time, you know exactly which stack the card
comes from, but not which card out of the stack. When you shuffle
cards, it's more like you know exactly which card is coming next off of
each stack, you just don't know which stack it's pulling from next.
import random
def shuffle(seq):
midpoint = len(seq)/2
stack1 = seq[:midpoint]
stack2 = seq[midpoint:]
shuffled = []
while stack1 and stack2:
next = random.choice((stack1, stack2))
shuffled.append(next.pop())
if stack1:
shuffled.extend(stack1)
else:
shuffled.extend(stack2)
return shuffled
More information about the Python-list
mailing list