HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Generating random HTML color grid

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
randomgridcolorgeneratinghtml

Problem

This is a Python script that generates a grid of random HTML colors. It works by reading random data from /dev/urandom and then encoding it as a hexadecimal string. This string is spit into individual values that will be represented as a color.

I am wanting to know if this is the best way to generate random values for this task. Would it be better to use the random module? Or is my method more beneficial for this task?

WIDTH = 64
HIGHT = 5

def chunks(l, n): 
   return [l[i:i+n] for i in range(0, len(l), n)]
data = file("/dev/urandom").read(HIGHT*WIDTH*3).encode("hex")
colors = ""
count = 0
for byte in chunks(data, 6): 
   if count == WIDTH: 
       colors+=""
       count=0
   count+=1
   colors+="""■""" % (byte)
file("colors.html", "w").write(colors)


This is the output:

Solution

An implementation that uses the random module has the benefit of being platform independent. This code isn't going to run so well if you try it on Windows.

There is also another alternative. os.urandom() will use the underlying os to provide the random values.


On a UNIX-like system this will query /dev/urandom, and on Windows it
will use CryptGenRandom().

You can also use random.SystemRandom() if you still want the OS source, but want to use the interface provided by random.

This answer provides an implementation of chunks() that iterates instead of constructing a list of all the chunks.

I would also lean towards an implementation that opens the output file first, then writes to it as it iterates over the chunks. This way, you won't need to build a huge string in memory before writing it to disk. Similarly, I would generate the random values as needed.

Context

StackExchange Code Review Q#37440, answer score: 6

Revisions (0)

No revisions yet.