Stumbling Toward 'Awesomeness'

A Technical Art Blog

Tuesday, October 25, 2011

Quick Note About Range(), Modulus, and Step

Maybe it’s me, but I often find myself parsing weird ascii text files from others. Sometimes the authors knew what the data was and there’s no real markup. Take this joint list for example:

143 # bones
root ground
0 0 0
root hips
0 0.9512207 6E-08
spine 1
4E-08 0.9522207 1.4E-07
spine 2
3E-07 1.0324 8.3E-07
spine 3
5.6E-07 1.11357 1.53E-06
spine 4
8.2E-07 1.194749 2.22E-06
head neck lower

So the first line is the number of joints then it begins in three line intervals stating from the root outwards: joint name, parent integer, position. I used to make a pretty obtuse loop using a modulus operator. Basically, modulus is the remainder left over after division. So X%Y gives you the remainder of X divided by Y; here’s an example:

for i in range(0,20+1):
	if i%2 == 0: print i
#>> 0
#>> 2
#>> 4
#>> 6
#>> 8
#>> 10

The smart guys out there see where this is goin.. so I never knew range had a ‘step’ argument. (Or I believe I did, I think I actually had this epiphany maybe two years ago, but my memory is that bad.) So parsing the above is as simple as this:

jnts = []
for i in range(1,numJnts*3+1,3):
	jnt = lines[i].strip()
	parent = int(lines[i+1].strip())
	posSplit = lines[i+2].strip().split(' ')
	pos = (float(posSplit[0])*jointScale, \
	float(posSplit[1])*jointScale, float(posSplit[2])*jointScale)
	jnts.append([jnt, parent, pos])

Thanks to phuuchai on #python (efnet) for nudging me to RTFM!

posted by admin at 1:42 AM  


  1. Hi,
    I don’t won’t to turn this into a contest who can right the shortest python.. but 🙂
    for times when you need to iterate over “groups” of lines i like to use:
    i = iter(lines)
    for jnt, parent, pos in zip(i,i,i):

    it takes away dealing with indexing into lines with offsets.

    Another thing would be to use a library for 3d vectors and matrices, where you can simply multiply posVector * jointScale. People seem to like pyeuclid.

    Or if you’re doing that as a script inside some modelling package, check if it exposes some types for dealing with vectors and 3d math.

    Comment by g — 2011/10/25 @ 11:14 AM

  2. Yeah, I need to learn how to use zip, itertools, and also list comprehensions. That stuff is not very intuitive to me. I will add your example to the post when I have 5 mins; thanks!

    Comment by admin — 2011/10/25 @ 3:40 PM

RSS feed for comments on this post. TrackBack URI

Leave a comment

Powered by WordPress