local variable 'B' referenced before assignment

1.3k views Asked by At
def fun(p,q,x=x):
    p=p*x^0
    q=q*x^0
    t=diff(q)
    u=p.degree(x)+1
    s=p.degree(x)-t.degree(x)
    o=s+1
    if s<0:
        print('The integral does not undertake in elementary functions')
    else:
        if s==0:
            A=var('A0')
        else:
            A=var(['A%d' %n for n in range(o)])
            r=sum([A[i]*(x^i) for i in range(o)])
            h=diff(r,x)+r*diff(q,x)-p
            l=diff(r,x)+r*diff(q,x)
            B=([l.coefficient(x,n) for n in range(u)])
            C=([p.coefficient(x,n) for n in range(u)])
        if o==1:
            t=solve((B[u-1]-C[u-1]==0),r)
            r=r.subs(t)
            print(r)
        else:
            z=[h.subs(x=n)==0 for n in range(u)]
            t=solve(z,A)
            l=len(t[0])
        if t[0][l-1]!=0:
            r=r.subs(t)
            print(r)
        else:
            print('The integral does not undertake in elementary functions')

fun(x,x**2) doesnt work but. if i'll try fun(x**2,x) it will work. or fun(x,x**3).

File “”, line 1, in File “”, line 21, in dr UnboundLocalError: local variable ‘B’ referenced before assignment

can somebody fix please? I tried everything that I can imagine.

2

There are 2 answers

0
DeepSpace On

if s == 0 and o == 1 then B is undefined. Try to follow the logic of your code.

0
Pike D. On

The variable B has not been assigned to anything when referenced on line 21, which means B does not exist. So Python is raising an error because it's told to do a computation with a value that does not exist.