开发者

why do I get unsupported operand type(s) type error?

ok, so I got a little exercise for python and I want to find the values of speed and location at every second from 0 to 30th within a list. also it must notify me when they intersect. while finding the location of the first car I am to use the method of Trapezoid code only.

the speed equation of the first car is V1=t^3-3*t^2+2*t and the second is V2=10*t

开发者_开发问答

my code:

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"

when I use this code it gives me such an error:

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'

what do I do now?


I don't know Python, but your function LocationV2() doesn't seem to be returning anything.


b=LocationV2(t)

The problem is, this returns None and hence a-b gives the error you are getting.

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

should really be:

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

And this should fix your problem.


As far as I can see you are doing

b = LocationV2(t)

and LocationV2 does not return anything, so it implicitly returns NoneType. Then you call

if (a-b)<=0.1:

and it is trying to subtract NoneType from an int. In fact, I have no idea what LocationV2 actually does. It seems to multiply x by 1. Return the value from LocationV2 and you should be fine.


The LocationV2 function does not return explicitly return a value, thus Python runtime make it return None.


LocationV2 does not return anything, therefore b is None.


A grossly over-engineered version:

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()

which results in:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜