TypeError: 'float' object has no attribute 'getitem' What does this mean ???

Recommended Answers

All 11 Replies

It means that a function tried to call an attribute getitem on a float object, like this code

>>> x = 3.14
>>> x.getitem
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'float' object has no attribute 'getitem'

Here are similar errors

>>> x = 3.14
>>> x.date_of_birth
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'float' object has no attribute 'date_of_birth'
>>> x.email_address
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'float' object has no attribute 'email_address'

So what change should i make in my programme to avoid this error ??
My Part of prog which is giving this error is :

def calcdist(data):
for p in data:
x = p[:1]
y = p[:2]
z = p[:3]
for i in range(len(data)):
dist = sqrt((x[i]-x[i+1])^2 + (y[i]-y[i+1])^2 +(z[i]-z[i+1]^2))
return dist
def ReadPointCloud(filename):
return [tuple(map(float, l.split()[1:4])) for l in open(filename)]

This code is not indented, so it can't run. Notice that the power operator is **, not ^, python is not latex. Also when there is an error, python outputs a long message, starting with the word Traceback (most recent call last). To find the error, you must analyze this message, and if you want people to be able to help you, you should post the code and the traceback.

import cv
from math import floor, sqrt, ceil
from numpy import array, dot, subtract, add, linalg as lin

def calcdist(data):
    for p in data:
        x = p[0]
        y = p[1]
        z = p[2]
    for i in range(len(data)):
      dist = sqrt((x[i]-x[i+1])**2 + (y[i]-y[i+1])**2 +(z[i]-z[i+1]**2))
      return dist

 def ReadPointCloud(filename):
    return [tuple(map(float, l.split()[1:4])) for l in open(filename)]

 def main (data):
    for i in range(len(data)): # Finding Neighbours
       for j in range(len(data)):
          dist = calcdist(data)
          print dist

if __name__ == '__main__':
    data = ReadPointCloud(r'C:\Thesis\NEHreflectance_Scanner_1_part.txt')
    data = data[0:100]
    main(data)

This is the error in the above programme to loop within a list and calculate distance between 2 3d points with in the list..

Traceback (most recent call last):
  File "C:\Users\inshu\Desktop\cal-dist.py", line 29, in <module>
    main(data)
  File "C:\Users\inshu\Desktop\cal-dist.py", line 22, in main
    dist = calcdist(data)
  File "C:\Users\inshu\Desktop\cal-dist.py", line 11, in calcdist
    dist = sqrt((x[i]-x[i+1])**2 + (y[i]-y[i+1])**2 +(z[i]-z[i+1]**2))
TypeError: 'float' object has no attribute '__getitem__'

Python complains because x, y, z are floating point numbers and you cannot write x[i] when x is a number. Apart from that, your main function is meaningless. At line 20, you try to compute a quantity which does not depend on i and j. Then why compute it in a double loop ? Each iteration will yield the same result. Also the comment # Finding Neighbours is meaningless. Start by defining the expected output of your computation.

if I cannot write x{i] what should i do to take difference between two consequtive points in my loop which are {x, y,z} and {x+i, y+i, z+i} and yes u r write my main is useless yet.. m trying to make a nested loop for taking a point in main nd calculating distance using another point in main .. m so confused..

OK, I can see your getting flustered, so let's back away from the code for a bit and consider the overall problem you are trying to solve. Just what is the program supposed to compute, and how would you do it by hand if you had to? I don't mean you should actually go through it manually, just sketch out the process for us.

Also, I would recommend removing any import statements that aren't strictly needed. They simply clutter up both the code and the namespace.

Ok I will try to xplain my prob here step by step : 

Step 1 : Read a file containing 3 co-ordinates of a point in a point cloud data
Step 2 : Take a point and find its nearest neighbours which m trying to by the above
         Prog that is : 
         1. Read first point from the list , find its distance with other points in the 
            list. Find the points which are at shortest distance from it.
         2. Repeat first step for every point in data, and try to find neighbours of each
            point.
         3. Store these points in the list sorting them with incresaing distance. {means 
          the distance between first point and last point in the list should be maximum}
         4. Then proceed to Step 3 
Step 3 : Calculate centre for every 5 points in the list. which i am doin by the code (nd thankfully it is working)  

    def CalcCentre(data):
        centre = array([0,0,0])
        count = 0
        for p in data:
            centre = add(centre, array(p[:3]))
            count += 1
        centre = dot(1./count, centre)
        return centre
Step 4 : Compute Covariance matrix for the 5 points doing by : 

    def CalcCovarianceMatrix(data, centre)
        covariance = array([(0,0,0),
                           (0,0,0),
                           (0,0,0)])

        for point in data:
            diff = subtract(array(point[:3]), centre
            matrix = array([(diff[0]*diff[0], diff[0]*diff[1], diff[0]*diff[2]),
                           (diff[0]*diff[1], diff[1]*diff[1], diff[1]*diff[2]),
                           (diff[0]*diff[2], diff[1]*diff[2], diff[2]*diff[2])])
            covariance = add(covariance, matrix)
        covariance = dot(1./(len(data)-1), covariance)
        return covariance

Step 5 : Compute Eigen values and EIgen vector for the points. 
Step 6 : Classify the points in sphere or plane using some threshold value.

Ah, this does clarify things somewhat. OK, then.

I think you'll want to fix calcdist() first; divorce it from the data stream as it is and have it take two three-tuples as it's argument:

def (a, b):
    return sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2 + (a[2]-z[2])**2)

Better still might be to write a Point3D class to represent your data, though that may be a bit heavyweight. On second thought, it would porbably save you a lot of trouble:

from math import sqrt

from sys import maxsize

class Point3D(object):
    """ Representation of a point in three dimensions."""

    def __init__(self,  *args):
        """ C'tor for the Point3D class. Can accept either a tuple, a list, or a set of three separate arguments as it's initialization. """
        if len(args) == 1 and (isinstance(args, tuple) or isinstance(args,  list)):
            self.x,  self.y,  self.z = args[0]
        elif len(args) == 3:
            self.x,  self.y,  self.z = args
        else:
            raise TypeError 

    def __str__(self):
        """ String representation of a Point3D. """
        return "<{0}, {1}, {2}>".format(self.x,  self.y,  self.z)

    def __repr__(self):
        """ Extended representation of the Point3D objects - the same as the string representation."""
        return str(self)

    def __eq__(self,  other):
        """ Test for equality between two Point3D objects."""
        return ((self.x == other.x) and (self.y == other.y) and (self.z == other.z))

    def __ne__(self,  other):
        """ Test for inequality between two Point3D objects."""
        return not self == other    

    def distance(self,  other):
        """ Computes the distance between two Point3D points."""
        return sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2 + (self.z - other.z) ** 2)


def findShortestDistance(data):
    shortestDistance = maxsize
    for a in data:
        v = Point3D(a)
        for b in data:
            w = Point3D(b)
            if v != w:
                d = v.distance(w)
                if d < shortestDistance:
                    shortestDistance = d
    return shortestDistance


if __name__ == "__main__":
    print(findShortestDistance(((1.0, 2.0, 3.0),  (4.0, 5.0, 6.0), (11.0,  3.0,  21.0) )))

This gives you a more abstract way of looking at the points. Re-writing the barycentre() function as a method of the class is left as an exercise.

I wouldn't normally do so much for you, but the way you were floundernig made it clear you needed a new approach to the problem.

oh thanx , infact I was not expecting so much from you.. I want to learn python and working with it .. I need someone who just tell my prog is write or wrong... and help me in identifying the blunders in it... Thanx ..i try to write the prog for centre nd send u here..

A good example from Schol-R-LEA is worth a thousand words.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.