给出TypeError的二进制搜索:' int'对象不可调用

时间:2014-08-01 12:41:00

标签: python binary-search

我正在尝试执行二进制搜索。我一直遇到错误:

    outcome = overlap (base, start_pos, end_pos)
TypeError: 'int' object is not callable

错误可以在此代码的第58行找到。我已经在代码中标出了它。

def overlap (x, start_y, end_y):
    if x < start_y:
        return -2
    elif x > end_y:
        return 2
    elif x >= start_y and x <= end_y:
        return 0

import csv

file1 = open ('path_to_file','rt', newline = '')
bait = csv.reader(file1, delimiter = '\t')

file2 = open ('path_to_file','rt', newline = '')
stress_33 = csv.reader(file2, delimiter = '\t')

file3 = open ('path_to_file','wt', newline ='')
output = csv.writer(file3, delimiter = '\t')

file4 = open ('path_to_file','wt', newline ='')
output_off = csv.writer(file4, delimiter = '\t')

files = file1, file2, file3, file4

bait_dict = {}

for line in bait:
    chromosome = line[0]
    start = int(line[1])
    end = int(line[2])
    location = start, end
    if chromosome not in bait_dict:
        bait_dict[chromosome] = []
        bait_dict[chromosome].append (location)
    elif chromosome in bait_dict:
        bait_dict[chromosome].append (location)

for item in bait_dict:
    bait_dict[item].sort(key = lambda i: i[0])

no_overlap = 0
overlap = 0

for i, line in enumerate(stress_33):
    if i == 0:
        output.writerow(line)
        output_off.writerow(line)
    elif i > 0:
        chrom_stress = line[1]
        base = int(line[2])
        if chrom_stress in bait_dict:
            for key, value in bait_dict.items():
                low = 0
                high = len(value) -1
                while low <= high:
                    mid = (low + high)//2
                    start_pos, end_pos = value[mid]
                    outcome = overlap (base, start_pos, end_pos) # TypeError: 'int' object is not callable
                    if outcome == 0:
                        output.writerow(line)
                    else:
                        if outcome == -2:
                            low = mid + 1
                        elif outcome == 2:
                            high = mid - 1
                no_overlap += 1
                output_off.writerow(line)    

print ('Number of ontarget is %d an number of off target is %d' %(overlap, no_overlap))


for file in files:
    file.close()

2 个答案:

答案 0 :(得分:2)

因为您尝试将overlap作为函数调用,所以当您将其声明为整数时。我不确定你在第58行尝试做什么,所以很难建议如何修复它,但原因是overlap根本就不是一个函数。

编辑:哦,我没有看到你之前宣布过一个名为overlap的函数。您收到错误的原因是在声明该函数后,您将overlap重新声明为整数。只需为功能或价值选择一个不同的名称,你就应该是金色的。

答案 1 :(得分:2)

您不能同时拥有变量overlap和名为overlap的函数。在Python中,函数和值都是生活在同一名称空间中的对象。

您在顶部的功能称为overlap,然后您重新绑定名称以包含整数:

overlap = 0

现在你的函数对象不再可寻址(它已被清理,在此之后不再存在)。

重命名函数或变量。