Posts Tagged ‘NoneType’

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.