Archive for the ‘Python’ Category

Collective Intelligence (Segaran) – Chapter 5 – NoneType error

July 25, 2010

Been working through this excellent book when I stumbled upon the following error:

File "", line 163, in geneticoptimize
    scores=[(costf(v),v) for v in pop]
  File "", line 42, in dormcost
    for i in range(len(vec)):
TypeError: object of type 'NoneType' has no len()

After running the code on and before page 109. It took me a while to get to the bottom of it, so I thought I would share my findings. I did numerous searches on Google and eventually came across this posting, belonging to wentrue.

I had to translate it and found that the function mutate(vec) in genticoptimize has a “bug” in it. This “bug” (using the term very lightly) is because the condition to decide what to return appears to have a hole in it and sometimes nothing will be returned because the value being compared falls outside the criteria. To make live easy I simply added an else clause to the function and chose to return the first criteria result.

	def mutate(vec):
		if random.random()<0.5 and vec[i]>domain[i][0]:
			return vec[0:i]+[vec[i]-step]+vec[i+1:]
		elif vec[i]<domain[i][1]:
			return vec[0:i]+[vec[i]+step]+vec[i+1:]
			return vec[0:i]+[vec[i]-step]+vec[i+1:]

Further to this I found on the errdata (search for page 109), for the book, a better way of running the code which is:


Thats it, back to having fun with the book. Hope this helps others.

Python PIL error IOError: decode jpeg not available and encode jpeg not available

June 1, 2010

Just working through Toby Segaran‘s book Collective Intelligence.

Stumbled across this error (OS X 10.5.8) , I fixed it by:

Remove the current PIL installation:

cd /Library/Python/2.5/site-packages/
sudo rm -rf PIL
sudo rm PIL.pth

Remove the Images directory which you extracted to perform the installation (e.g. $HOME/Downloads/Imaging-1.1.7)

Now you need to ensure JPEG library is installed, I use mac ports:

sudo port install jpeg

Now extract your Imaging file and change directory into the new directory (Imaging-1.1.7):

sudo python install

then run it again!

python build_ext -i

now run the test:


My thanks go to a post by Simon Wilder’s blog which eased my frustration!