Code speedup tips
Raymond Hettinger
vze4rx4y at verizon.net
Sun Mar 2 00:01:03 EST 2003
"Carl Banks"
> Here is how I rewrote CA_Function. There are some details in it I've
> left unexplained; feel free to ask for a clarification:
>
>
> def CA_Function(Length,Steps):
> # Create the two lattices
> current = zeros((Length,Length),Int)
> workspace = zeros((Length-2,Length-2),Int)
>
> # Create slices of the current lattice
> # We don't have to do this every step because slicing shares
memory
> left = current[0:-2,1:-1]
> up = current[1:-1,0:-2]
> right = current[2:,1:-1]
> down = current[1:-1,2:]
>
> # Set the start cell to black
> current[Length/2,Length/2] = 1
>
> # Apply the rule
> for step in xrange(Steps):
> # In the workspace, add the shifted lattices
> # This uses a bunch of += because it's faster
> workspace[:] = left
> workspace[:] += up
> workspace[:] += right
> workspace[:] += down
> # Set the current lattice
> current[1:-1,1:-1] = where(workspace,1,0)
Nice job.
More information about the Python-list
mailing list