pythonunsupportedoperation

Unsupported Opreand Type in Python


Hello this is error message that i recieved, please help me to find where could be the problem.

<ipython-input-52-2e0822fefabf> in main()
     11         k = 3
     12         for x in range(len(testSet)):
---> 13                 neighbors = getNeighbors(trainingSet, testSet[x], k)
     14                 result = getResponse(neighbors)
     15                 predictions.append(result)

<ipython-input-48-401931b7da2b> in getNeighbors(trainingSet, testInstance, k)
      4         length = len(testInstance)-1
      5         for x in range(len(trainingSet)):
----> 6                 dist = euclideanDistance(testInstance, trainingSet[x], length)
      7                 distances.append((trainingSet[x], dist))
      8         distances.sort(key=operator.itemgetter(1))

<ipython-input-45-f927a4da7f1b> in euclideanDistance(instance1, instance2, length)
      3         distance = 0
      4         for x in range(length):
----> 5                 distance += pow((instance1[x] - instance2[x]), 2)
      6         return math.sqrt(distance)

TypeError: unsupported operand type(s) for -: 'str' and 'str'

Solution

  • These values: testInstance, trainingSet[x]

    Are not int or float. They should be, as you cannot subtract strings from strings.

    You can do:

    neighbors = getNeighbors(int(trainingSet), int(testSet[x]), k)
    

    Or this if they are floats:

    neighbors = getNeighbors(float(trainingSet), float(testSet[x]), k)