为什么我会收到类型错误?

时间:2014-01-21 23:12:44

标签: python types

import time

def average(numbers):
    "Return the average (arithmetic mean) of a sequence of numbers."
    return sum(numbers) / float(len(numbers)) 

#example function

def domath(a,b,c):
    a+b+c
    a*b*c
    a/b/c
    a-b-c
    a^b
    b^c


def timedcalls(n, fn, *args):
    times=[]
    if type(n)==int:
        t0 = time.clock()
        for rep in range(n):
            t0 = time.clock()
            fn(*args)
            t1 = time.clock()
            times.append(t1-t0)
    else:
        start=time.clock()
        while time.clock-start<int(n):
            t0 = time.clock()
            fn(*args)
            t1 = time.clock()
            times.append(t1-t0)    
    return min(times), average(times), max(times)

print timedcalls(5.0, domath, 1,2,3)

这个代码适用于int类型,但出于某种原因,如果我使用float它会给我这个错误。

Traceback (most recent call last):
  File "<stdin>", line 29, in <module>
  File "<stdin>", line 22, in timedcalls
TypeError: unsupported operand type(s) for -: 'builtin_function_or_method' and 'float'

这一行:

return min(times), average(times), max(times)

1 个答案:

答案 0 :(得分:7)

while time.clock-start<int(n):

应该是

while time.clock()-start<int(n):

您没有调用time.clock函数

请注意在追溯中它表示无法在'builtin_function_or_method' and 'float'

之间进行减法