TypeError: unsupported operand type(s) for /: 'tuple' and 'int'

8.7k Views Asked by At

I'm having trouble with dealing with this error unsupported operand type error and I'm not sure what I'm doing wrong in this case. Any help would be appreciated!!

def closest_pair(list):
if (len(list) <= 3):
    return min_distance(list)
else:
    left, right = split_into_two(list)
    left_min = closest_pair(left)
    right_min = closest_pair(right)
    if(left_min[2]>right_min[2]):
        return right_min
    else:
        return left_min

def split_into_two(list):
    med_val = statistics.median(list)
    med_x = med_val[0]
    left = []
    right = []
    for i in list:
        if (i[0]<med_x):
            left.append(i)
        else:
            right.append(i)
    return left, right

and printing closest_pair gives out:

Traceback (most recent call last):
  File, line 109, in <module>
    print(closest_pair(text_file))
  File, line 61, in closest_pair
    left_min = closest_pair(left)
  File, line 62, in closest_pair
    right_min = closest_pair(right)
  File, line 60, in closest_pair
    left, right = split_into_two(list)
  File, line 44, in split_into_two
    med_val = statistics.median(list)
  File, line 358, in median
    return (data[i - 1] + data[i])/2
TypeError: unsupported operand type(s) for /: 'tuple' and 'int'
1

There are 1 best solutions below

0
On

The error message is very explicit:

    return (data[i - 1] + data[i])/2
TypeError: unsupported operand type(s) for /: 'tuple' and 'int'

It says that the program is trying to divide a tuple by an int. So, data[i - 1] + data[i] is a tuple, and that means that each of data[i - 1] and data[i] are tuples and not numbers as you may be expecting.

Note that the error occurs inside the statistics.median function. Check that you are passing arguments with the right type to this function.