Voder-Vocoder

The Log of Hal Canary

Navigation: Home | THE LOG | Log Archives | Resume | Contact Info | Public Key | SSL | Math Applets | Site Map | WP Backend | RSS2 | Atom

« | »

ransdomize

#!/usr/bin/env python
# randomize_list.py
# Written 2008 Hal Canary
# Dedicated to the public domain.
import sys, random
l=[]
for line in sys.stdin:
	l.append(line)
while l:
	e = random.choice(l)
	l.remove(e)
	sys.stdout.write(e)

UPDATE 2009-01-04: Just as I suspected, that code is highly inefficient. Here's a different algorithm which is much faster for large N.

#!/usr/bin/env python
# randomize_list.py
# Written 2008-2009 Hal Canary
# Dedicated to the public domain.
import sys, random
l=[]
for line in sys.stdin:
	l.append(line)
while l:
	i = random.randint(0,len(l)-1)
	sys.stdout.write(l.pop(i))

Testing with the time command showed a 74% reduction in CPU use with the better algorithm.

Hal Canary | Computers & Code | 2008-12-21 18:50:35 UTC
Permanent Link Comments Off | No Comments

Comments are closed.

Copyright 1997-2007 by Hal Canary.
mailto: h3 at halcanary dot org
xmpp:halcanary@jabber.org
aim:halwcanary
http://halcanary.org