Quick actions

cmd+k|ctrl+k

Navigation

Languages

20250913 By Felix

Snippet info

Language

Python

Visibility

public

Author

antonie.job

Created

2025-09-13T13:32:39.269635Z

Updated

2025-09-14T03:32:18.816887Z

def calc(ex):
    
    try:
        if type(float(ex)) == float:
            return float(ex)
    except:
        pass

    exp = ex
    
    z = [a.strip() for a in exp.split("(")]
    if len(z) > 1:
        for i in range(len(z)-1,0,-1):
            zz = [a.strip() for a in z[i].split(")",1)]
            if len(zz) > 1:
                print(f'bf(): {tmp}')
                tmp = calc(zz[0])
                z[i-1]=(z[i-1]+str(tmp)+zz[1])
                exp = z[i-1]
                print(f'bf(): {exp}')
            else:
                print("input not correct")
                return -1
    print('1:',z)
    z = [a.strip() for a in exp.split("+")]
    print('2:',z)
    if "" in z:
        print("input not correct")
        return -1
    if len(z) > 1:
        tmp = calc(z[0])
        for i in range(len(z)-1):
            print('3:',i)
            tmp += calc(z[i+1])
            print('+tmp',tmp)
        return tmp
    #print(z)
    z = [a.strip() for a in exp.split("-")]
    if "" in z:
        print("input not correct")
        return -1
    if len(z) > 1:
        tmp = calc(z[0])
        #print('tmp',tmp,z[0])
        for i in range(len(z)-1):
            tmp -= calc(z[i+1])
            print('-tmp',tmp)
        return tmp

    z = [a.strip() for a in exp.split("*")]
    if "" in z:
        print("input not correct")
        return -1
    if len(z) > 1:
        print(f'bf: {z}')
        tmp = calc(z[0])
        print(f'aft z[0]: {tmp}')
        for i in range(len(z)-1):
            tmp *= calc(z[i+1])
            print('*tmp',tmp)
        return tmp

    z = [a.strip() for a in exp.split("/")]
    if "" in z:
        print("input not correct")
        return -1
    if len(z) > 1:
        tmp = calc(z[0])
        for i in range(len(z)-1):
            tmp /= calc(z[i+1])
            print('/tmp',tmp)    
        return tmp

    print("input not correct")
    return -1

#print(calc("1-2+6-4/3/3-8*8+3-6/3"))
#print(calc("(4/5)+1/(1+3)"))
#print(calc("4/((5+1))/(1+3)"))
print(calc('1+2*2+3+4-5-6+7+8'))
INFO