为什么我得到不支持的操作数类型错误?

时间:2011-01-09 19:11:18

标签: python

好的,所以我为python做了一些练习,我希望在列表中的0到30之间每秒找到速度和位置的值。它们相交时也必须通知我。在找到第一辆车的位置时,我只使用梯形码的方法。

第一辆车的速度方程是V1 = t ^ 3-3 * t ^ 2 + 2 * t,第二辆是V2 = 10 * t

我的代码:

def cars():

    def LocationV1(x):
        x=x*1.0
        h=x/1000.0
        m=0
        n=m+h
        L=0.0
        for i in range (0,1000):
            def f(u):
                return u**3+3*u**2+2*u
            L=L+(f(m)+f(n))*h/2
            m=m+h
            n=n+h
        return L
    def LocationV2(x):
        x=x*1.0
        def g(x):
            return 5*x**2/2
    def SpeedV1 (x):
        x=x*1.0
        return x**3-3*x**2+2*x
    def SpeedV2 (x):
        x=x*1.0
        return 10*x
    V1=[]
    V2=[]
    t=0
    a=LocationV1(t)
    b=LocationV2(t)
    while t<=30:
        t=t+1
        V1=V1+[[LocationV1(t), SpeedV1(t), t]]
        V2=V2+[[LocationV2(t), SpeedV2(t), t]]
        print V1
        print V2
        if (a-b)<=0.1:
            print "cars meet"

当我使用这段代码时,它给了我一个错误:

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    cars()
  File "C:/Users/ÖZGÜR/Desktop/ödev", line 35, in cars
    if (a-b)<=1:
TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'

我现在该怎么办?

6 个答案:

答案 0 :(得分:2)

b=LocationV2(t)

问题是,这会返回None,因此a-b会给出错误。

def LocationV2(x):
    x=x*1.0
    def g(x):
        return 5*x**2/2

应该是:

def LocationV2(x):
    x=x*1.0
    return 5*x**2/2

这应该可以解决你的问题。

答案 1 :(得分:1)

我不懂Python,但你的函数LocationV2()似乎没有返回任何内容。

答案 2 :(得分:0)

据我所知,你正在做什么

b = LocationV2(t)

和LocationV2不返回任何内容,因此它隐式返回NoneType。然后你打电话

if (a-b)<=0.1:

并且它试图从int中减去NoneType。事实上,我不知道LocationV2实际上做了什么。它似乎将x乘以1.从LocationV2返回值,你应该没问题。

答案 3 :(得分:0)

LocationV2函数未返回显式返回值,因此Python运行时使其返回None

答案 4 :(得分:0)

LocationV2不返回任何内容,因此bNone

答案 5 :(得分:0)

严重过度设计的版本:

rng = xrange if xrange else range

class Polynomial(object):
    def __init__(self, *args):
        """
        Args are coefficients of x**0, x**1, x**2, ...
        ie, Polynomial(3,0,2) is 2*(x**2) + 3
        """
        self.coeffs = [float(a) for a in args]

    def __call__(self, x):
        "Evaluate poly at x"
        return sum(a*(x**n) for n,a in enumerate(self.coeffs))

    def integrate(self, yAtZero=0.0):
        "Do symbolic integration of poly, return result as new poly"
        newCoeffs = [yAtZero] + [a/(n+1.0) for n,a in enumerate(self.coeffs)]
        return Polynomial(*newCoeffs)

class TrapezoidIntegrator(object):
    def __init__(self, fn, steps=1000):
        self.fn = fn
        self.steps = int(steps)

    def __call__(self, x):
        "Integrate fn from 0 to x in steps pieces"
        myfn = self.fn
        w = float(x)/self.steps
        return -0.5*w*myfn(0.0) + w*sum(myfn(w*step) for step in rng(self.steps)) + 0.5*w*myfn(x)

class Car(object):
    def __init__(self, posFn, speedFn):
        self.pos = posFn
        self.speed = speedFn

    def at(self, t):
        return self.pos(t), self.speed(t)

class Ahead(object):
    def __init__(self, fmt, *args):
        """
        @param fmt,  string:  format-string with one parameter, to report a change in leader
        @param args, strings: contestant names
        """        
        self.was_ahead = None
        self.fmt = fmt
        self.names = list(args)

    def __call__(self, *args):
        "Compare an arbitrary number of racers and report whenever the leader changes"
        state = zip(args, self.names)    # we assume that len(args)==len(self.names)
        state.sort(reverse=True, key=lambda x: x[0])
        leader = state[0][1]

        if leader==self.was_ahead:
            return ''
        else:
            self.was_ahead = leader
            return self.fmt.format(leader)

def niceFloat(val, width, decimals):
    """
    Really wretchedly annoying - I have not yet found a nice way to do
    decimal-aligned floats with the new-style string formatting.
    """
    fmt = "%{0}.{1}f".format(width, decimals)
    return fmt % val

def main():
    v1 = Polynomial(0,2,-3,1)    # speed of first car = t^3 - 3t^2 + 2t
    d1 = TrapezoidIntegrator(v1) # must use trapezoidal numeric integration
    car1 = Car(d1, v1)

    v2 = Polynomial(0,10)        # speed of second car is 10t
    d2 = v2.integrate()          # use symbolic integration
    car2 = Car(d2, v2)

    fmt = "{0:>4}: {1:>10} {2:>10}{3}"
    print(fmt.format('Time','Car1','Car2',''))
    ahead = Ahead('  Car {0} is in the lead!', 1, 2)
    log = []

    for t in rng(31):
        a, da = car1.at(t)
        b, db = car2.at(t)

        print(fmt.format(t, niceFloat(a,10,2), niceFloat(b,10,2), ahead(a,b)))
        log.append((t,a,da,b,db))

if __name__=="__main__":
    main()

导致:

Time:       Car1       Car2
   0:       0.00       0.00  Car 1 is in the lead!
   1:       0.25       5.00  Car 2 is in the lead!
   2:       0.00      20.00
   3:       2.25      45.00
   4:      16.00      80.00
   5:      56.25     125.00
   6:     144.00     180.00
   7:     306.25     245.00  Car 1 is in the lead!
   8:     576.00     320.00
   9:     992.25     405.00
  10:    1600.00     500.00
  11:    2450.25     605.00
  12:    3600.00     720.00
  13:    5112.26     845.00
  14:    7056.01     980.00
  15:    9506.26    1125.00
  16:   12544.01    1280.00
  17:   16256.27    1445.00
  18:   20736.02    1620.00
  19:   26082.28    1805.00
  20:   32400.04    2000.00
  21:   39800.29    2205.00
  22:   48400.05    2420.00
  23:   58322.31    2645.00
  24:   69696.08    2880.00
  25:   82656.34    3125.00
  26:   97344.11    3380.00
  27:  113906.37    3645.00
  28:  132496.14    3920.00
  29:  153272.41    4205.00
  30:  176400.19    4500.00