Python动态建模(2)

上一篇参见:

Python 动态建模(1)_Unconquerable&Llxy的博客-优快云博客例,x=y=z=t就可以改为x=y=z=(具体数值),所以实际上formula就变成了一(N)个方程。把一个数丢进去不断推演,最后得知n个答案,把所有答案的坐标点连起来,实现一个模型。主要改动将单方程“a-b”改为列表性双方程“a-b”,“b-a”,思路大体一致,讲解略。......https://blog.youkuaiyun.com/html_finder/article/details/126020597

今天要写的是项目中的第一个主体:write函数。

上次的write函数经过了试验后发现,由于write函数的方法有很多(遍历t算法,遍历t嵌套x算法,遍历t嵌套y算法,以及 遍历t嵌套z算法),所以决定把write方法改写成一个类。

class write:
    def _write_t_x(self,formula,tmin_=-10, tmax_=10, tnums=100,
                 min_=-10, max_=10, nums=100,printout=True):

其实就不打算去做一个__init__(初始化)函数了:就把它当成一个集合包吧。

直接键入第一个函数:_write_t_x,遍历t的可能,里面再嵌套对x的遍历。


(!)参数出现改动:

self,自带变量;                        

formula,公式;-----------------------------------------str字符串类型-------无默认值,需输入

tmin_,t值的最小取值点;----------------------------int整型----------------默认为-10

tmax_,t值的最大取值点;---------------------------int整型----------------默认为10

tnums,t值的取值数;---------------------------------int整型----------------默认为100

min_,x值的最小取值点;----------------------------int整型----------------默认为-10

max_,x值的最大取值点;---------------------------int整型----------------默认为10

nums,x值的取值数;---------------------------------int整型----------------默认为100

printout,是否输出【包括:打印进度条、打印进程(例如:正在计算、计算成功,等等)】。

-----------------------------------------------------------bool布尔值(True、False)------------默认为True,真


再把上次的一串变量放进来:

(!)注:有改动

        global x, y, z, t
        I = 1j
        oo = inf

        self.step = (tmax_ - tmin_) / tnums
        self.aa = tmin_ - self.step
        self.xstep = (max_ - min_) / nums
        r"""

        print(un)
        print(lf,toLeg(formula),sep="\n\n",end="\n\n")
        """
        solves = []

(为什么step,aa,xstep要设成self.step,self.aa,self.xstep?

原因:否则for循环里好像会出一些问题)

再次解释一下新加的xstep变量:

表示x值每步的变化。

接下来是t值的遍历循环,即第一层循环:

        for iVal in range(tnums + 2):

            self.aa = self.aa + self.step
            self.aa = float("%.10f" % self.aa)
            xValue = min_ - self.xstep

注:第四行的代码“ self.aa = float("%.10f" % self.aa)”表示对self.aa进行精度保留小数点后10位。

(让x值,即变量xValue初始化。)

接下来是第二层循环,即对x的遍历:

for XVAL in range(nums + 2):

接下来就可以开始对方程的处理了。

代码:

                lf, un = legalSet(toLeg(formula))
                xValue += self.xstep
                xValue = float("%.10f" % xValue)

第一行获取对方程和未知数的处理列表。每循环一次取值一次,因为循环会对方程进行处理,继而会发生改变,所以需要重新取值。

第二、三行的作用就是对x值进行递加(具体意思基本同上)

-------------------------------------------------------------------------------------------------------------------------------

代码写了那么多,估计可能会有些紊乱;

让我们梳理一下,

先过一下目前的完整代码:

# coding=utf-8

import sympy
from tkinter.messagebox import *
from tkinter import *
from math import *

def no_ans():
    Tk().geometry("9x9+990000+999999")
    showerror("警告", "方程无解析解")


x = []
y = []
z = []
t = []

def toLeg(fx):
    v=str(fx).split("\n")
    val=[]
    for i in v:
        tv=i.split("=")
        length=len(tv)
        last=None
        while length!=0:
            if length==2:
                val.append('='.join(tv))
                break
            if length==1:
                val.append('='.join([tv[0],str(last)]))
                break
            val.append('='.join([tv[-2],tv[-1]]))
            length=length-1
            last=tv[-1]
            tv.pop()
    return '\n'.join(val)
def legalSet(fx):


    v=str(fx).split("\n")
    nw=[]
    for l in v:

        tmpstr=""
        tmpstr2=""
        if l=='':continue
        k=l.split("=")
        tmpstr+="(("+k[0]+")-("+k[1]+"))"
        tmpstr2 += "((" + k[1] + ")-(" + k[0] + "))"
        tmpstrs=[tmpstr,tmpstr2]
        nw.append(tmpstrs)
    v=nw
    del nw

    index=-1
    for i in v:
        index+=1
        for j in range(2):
            if ":" in i: v[index][j] = i[j].replace(":", "/")
            if "^" in i: v[index][j] = i[j].replace("^", "**")
            if "÷" in i: v[index][j] = i[j].replace("÷", "/")
            if "×" in i: v[index][j] = i[j].replace("×", "*")
            if "[" in i: v[index][j] = i[j].replace("[", "(")
            if "]" in i: v[index][j] = i[j].replace("]", ")")
            if "【" in i: v[index][j] = i[j].replace("【", "(")
            if "】" in i: v[index][j] = i[j].replace("】", ")")
            if "{" in i: v[index][j] = i[j].replace("{", "(")
            if "}" in i: v[index][j] = i[j].replace("}", ")")
            if "(" in i: v[index][j] = i[j].replace("(", "(")
            if ")" in i: v[index][j] = i[j].replace(")", ")")
    newlt=[]
    lt=[]
    for j in v:


        lt__=[]
        funcs=[]
        news = []
        for i_ in j:
            new = ""
            pos = -1


            for i in i_:

                pos+=1
                tmpos=pos+0
                string=""
                while (i_[tmpos].isalpha()):
                    string+=i_[tmpos]
                    tmpos=tmpos+1
                if string in sympy.__all__ :
                    funcs+=[i for i in range(pos,tmpos+1)]


                if ((i.isalpha() or i == "(") and (i_[pos-1].isnumeric() or i_[pos-1].isalpha())
                        and pos!=0 and pos not in funcs):
                    new+="*"+i

                else:
                    new+=i
                if i.isalpha() and pos not in funcs:lt__.append(i)
            news.append(new)

        lt__=list(set(lt__))
        lt.append(lt__)
        newlt.append(news)
    return newlt,lt

class write:
    def _write_t_x(self,formula,tmin_=-10, tmax_=10, tnums=100,
                 min_=-10, max_=10, nums=100,printout=True):

        global x, y, z, t
        I = 1j
        oo = inf

        self.step = (tmax_ - tmin_) / tnums
        self.aa = tmin_ - self.step
        self.xstep = (max_ - min_) / nums
        r"""

        print(un)
        print(lf,toLeg(formula),sep="\n\n",end="\n\n")
        """
        solves = []
        for iVal in range(tnums + 2):

            self.aa = self.aa + self.step
            self.aa = float("%.10f" % self.aa)
            xValue = min_ - self.xstep
            for XVAL in range(nums + 2):
                lf, un = legalSet(toLeg(formula))
                xValue += self.xstep
                xValue = float("%.10f" % xValue)

接下来需要对列表进行一个排序,需确保一下含有x和t的方程前置;

(原因:x和t值因为for的遍历有了实际值,继而可以推导出整个方程)

首先,因为排序需要使用sorted函数,我们应当先指定一个“标准”:

                 def key(item):
                    if "t" in item[0] or "x" in item[0]:
                        return 1
                    else:
                        return 999

依靠这个标准“key”进行排序。

可是,方程的顺序变了,相应的,未知数的顺序也要变。

                bf = dict(enumerate(lf))
                lf = sorted(lf, key=key)
                nun = []
                for i in range(len(lf)):
                    nun.insert(lf.index(bf[i]), un[i])
                un = nun
                del nun

bf记录了lf中值的顺序,接下来用sorted函数对lf进行排序,再按照相应顺序把未知数放入到un中指定的相应位置上。

接下来,需要进行一个处理。x和t的值要被替换到方程式里面去才行。这就应该有两个步骤:

1)删除未知数x,t(因为已经被替换成了具体的值)

2)方程里的x值和t值换成对应的具体值。

第一步

这是删除元素x和t的代码:

                idx = -1
                for imp in un:
                    idx += 1
                    for __imp in imp:
                        if __imp == 't':
                            un[idx].remove("t")
                        if __imp == 'x':
                            un[idx].remove("x")
                del idx

第二步

存储对应的值到列表

(替换将会在下面进行)

                repl = {"t": [str(self.aa)], "x": [str(xValue)]}

然后就是while循环了。在此之前,让我们先定义一个变量is_exit……

                is_exit = False

它的用途想必大家都知道:

(作为终止循环条件)


接下来是while循环:

                while not is_exit:

(在循环内,要多次进行上述操作,即:

1)删除未知数x,t(因为已经被替换成了具体的值)

2)方程里的x值和t值换成对应的具体值。

那么再把上述功能实现一下。对了,还要先遍历一下方程列表。(while循环的作用是由于部分方程有依赖性,依靠循环进行多次解析)。

接下来是替换的代码:

                    indx = -1
                    for lf_ in lf:
                        indx += 1
                        for i in repl.keys():
                            for j in range(2):
                                if str(i) in str(lf_[j]):
                                    lf_[j] = lf_[j].replace(i, str(repl[i][0]))

                        idx = -1
                        for imp in un:
                            idx += 1
                            for __imp in imp:
                                if __imp in repl.keys():
                                    un[idx].remove(__imp)
                        del idx

然后的话就是剔除空值(比如,方程"x=y",x和y均被替换(可能是因为出现了y的解)),显示的是lf_=["(10)-(10)","(10)-(10)"],un=[],需要剔除这类值)。

                        if un[indx] == []:
                            del un[indx]
                            del lf[indx]
                            if indx == 0 or (indx - 1) >= len(lf): break
                            indx -= 1
                            continue

终于到了解方程时:

                        try:
                            ams = sympy.solve(tuple(lf_), tuple(un[indx]))
                        except NotImplementedError as err:
                            print(err)
                            no_ans()
                            is_exit = True
                            break

注:

(try...except相当于C++和Java的try...catch,意为捕获异常)

try内的语句:用sympy的solve函数计算结果。

except内语句:(solve函数会抛出一个异常:(即NotImplementedError)表示在所有的答案内,方程无解析解。抓住这个异常,输出具体的问题(err),运行no_ans函数(见上一篇,意为没有解析解),设置允许退出,退出for循环)。

(也可改成

                        try:
                            ams = sympy.solve(tuple(lf_), tuple(un[indx]))
                        except NotImplementedError as err:
                            print(err)
                            no_ans()
                            return


接下来是保存值的部分:

答案(ams)可能的类型:

1)字典类。(dict)

值的样子:{量名:量值,……}

2)列表类。(list,set,tuple)

值的样子:(第0个未知数的值,第一个未知数的值,...)

2-1)内置值类。  (sympy.core.numbers.Float,sympy.core.numbers.Integer,int,float,complex,...)

(可能有非法返回类型,例如无限大(sympy.core.numbers.Infinity),等等。)

例:[10.000000]

2-2)关系类。

例:【y*2+sin(y),y】表示了两个未知数的关系。

3)乱起八糟的其他类型,一般是表示无解。

所以我们要做的,就是匹配类型,再“因类型施程序”。



在Python里,我们通常使用isinstance()来匹配类型。

因为字典类型较为特殊,不用遍历找答案,所以同样要先判断;

                        if isinstance(ams, (dict,)):
                            for km, jj in ams.items():
                                if not ('x' in str(jj) or
                                        'y' in str(jj) or
                                        'z' in str(jj) or
                                        't' in str(jj)):
                                    if km.name in repl.keys():
                                        repl[km.name].append(str(jj))
                                    else:
                                        repl[km.name] = [str(jj)]

(repl存储了结果)

然后是其他类型的遍历。

                        else:
                            ix = -1
                            undo = 0
                            for i in ams:
                                ix += 1
                                try:
                                    if isinstance(i, (sympy.core.numbers.Float,
                                                      sympy.core.numbers.Integer,
                                                      int, float, complex)):

                                        try:
                                            repl[tuple(un[indx])[ix]] = [str(eval(str(i)))]
                                        except IndexError:

                                            repl[tuple(un[indx])[undo]].append(str(eval(str(i))))
                                        for i in repl.keys():
                                            if i in lf_:
                                                lf_ = lf_.replace(i, str(repl[i][0]))
                                    elif isinstance(i, (tuple, list, set)):
                                        inxx = -1
                                        for jj in i:
                                            inxx += 1
                                            if not ('x' in str(jj) or
                                                    'y' in str(jj) or
                                                    'z' in str(jj) or
                                                    't' in str(jj)):
                                                try:
                                                    repl[tuple(un[indx][inxx])[ix]] = [str(jj)]
                                                except IndexError:
                                                    repl[tuple(un[indx][inxx])[undo]].append(str(jj))
                                    else:
                                        continue
                                except TypeError as err:
                                    print("get:err", err)
                                    continue
                                else:
                                    undo = ix

代码比较复杂,具体原理将不细讲,如有需求可以私信查询。

然后是判断字典repl(结果)长度是否为4(即全部填满),是则退出。

if len(repl.values()) >= 4: is_exit = True;break

(循环之内)将结果添加到列表;

                solves.append(repl)

(同样在while循环之内)打印进度条;

                if printout:
                    print(f"\r{(iVal * (nums + 2) + XVAL) / ((nums + 2) * (tnums + 2)) * 100}%", end="",
                          flush=True)

(动态打印进度(%百分数);(如果printout参数被设为True);)

【Note注】

如果提示报错,可以试一下改为以下代码:

                if printout:
                    print(f"\r{(iVal * (nums + 2) + XVAL) / ((nums + 2) * (tnums + 2)) * 100}%%", end="",
                          flush=True)

(while和for循环之外)

该删的变量都删一删;

            del key, undo, indx, ix, repl, bf, lf, un, ams, iVal, i, __imp, lf_

特别注意 

Python对不用的变量有自动删除功能,所以del语句在这里的意思其实是防止变量被多次调用。

如果报错了,请自行修改代码。例:

报错内容:
...
Error:local varible "xxx" ...

就把对应的变量从del语句中移除即可。

实在不行就全删掉吧。(删掉整个del语句),免得麻烦。 




目前的完整函数:

    def _write_t_x(self,formula,tmin_=-10, tmax_=10, tnums=100,
                 min_=-10, max_=10, nums=100,printout=True):

        global x, y, z, t
        I = 1j
        oo = inf

        self.step = (tmax_ - tmin_) / tnums
        self.aa = tmin_ - self.step
        self.xstep = (max_ - min_) / nums
        r"""

        print(un)
        print(lf,toLeg(formula),sep="\n\n",end="\n\n")
        """
        solves = []
        for iVal in range(tnums + 2):

            self.aa = self.aa + self.step
            self.aa = float("%.10f" % self.aa)
            xValue = min_ - self.xstep
            for XVAL in range(nums + 2):
                lf, un = legalSet(toLeg(formula))
                xValue += self.xstep
                xValue = float("%.10f" % xValue)

                def key(item):
                    if "t" in item[0] or "x" in item[0]:
                        return 1
                    else:
                        return 999

                bf = dict(enumerate(lf))
                lf = sorted(lf, key=key)
                nun = []
                for i in range(len(lf)):
                    nun.insert(lf.index(bf[i]), un[i])
                un = nun
                del nun
                idx = -1
                for imp in un:
                    idx += 1
                    for __imp in imp:
                        if __imp == 't':
                            un[idx].remove("t")
                        if __imp == 'x':
                            un[idx].remove("x")
                del idx

                repl = {"t": [str(self.aa)], "x": [str(xValue)]}
                is_exit = False
                while not is_exit:

                    indx = -1
                    for lf_ in lf:
                        indx += 1
                        for i in repl.keys():
                            for j in range(2):
                                if str(i) in str(lf_[j]):
                                    lf_[j] = lf_[j].replace(i, str(repl[i][0]))

                        idx = -1
                        for imp in un:
                            idx += 1
                            for __imp in imp:
                                if __imp in repl.keys():
                                    un[idx].remove(__imp)
                        del idx

                        if un[indx] == []:
                            del un[indx]
                            del lf[indx]
                            if indx == 0 or (indx - 1) >= len(lf): break
                            indx -= 1
                            continue

                        try:
                            ams = sympy.solve(tuple(lf_), tuple(un[indx]))
                        except NotImplementedError as err:
                            print(err)
                            no_ans()
                            return


                        if isinstance(ams, (dict,)):
                            for km, jj in ams.items():
                                if not ('x' in str(jj) or
                                        'y' in str(jj) or
                                        'z' in str(jj) or
                                        't' in str(jj)):
                                    if km.name in repl.keys():
                                        repl[km.name].append(str(jj))
                                    else:
                                        repl[km.name] = [str(jj)]
                        else:
                            ix = -1
                            undo = 0
                            for i in ams:
                                ix += 1
                                try:
                                    if isinstance(i, (sympy.core.numbers.Float,
                                                      sympy.core.numbers.Integer,
                                                      int, float, complex)):

                                        try:
                                            repl[tuple(un[indx])[ix]] = [str(eval(str(i)))]
                                        except IndexError:

                                            repl[tuple(un[indx])[undo]].append(str(eval(str(i))))
                                        for i in repl.keys():
                                            if i in lf_:
                                                lf_ = lf_.replace(i, str(repl[i][0]))
                                    elif isinstance(i, (tuple, list, set)):
                                        inxx = -1
                                        for jj in i:
                                            inxx += 1
                                            if not ('x' in str(jj) or
                                                    'y' in str(jj) or
                                                    'z' in str(jj) or
                                                    't' in str(jj)):
                                                try:
                                                    repl[tuple(un[indx][inxx])[ix]] = [str(jj)]
                                                except IndexError:
                                                    repl[tuple(un[indx][inxx])[undo]].append(str(jj))
                                    else:
                                        continue
                                except TypeError as err:
                                    print("get:err", err)
                                    continue
                                else:
                                    undo = ix
                        if len(repl.values()) >= 4: is_exit = True;break

                solves.append(repl)
                if printout:
                    print(f"\r{(iVal * (nums + 2) + XVAL + 1) / ((nums + 2) * (tnums + 2)) * 100}%", end="",
                          flush=True)
            # del key, undo, indx, ix, repl, bf, lf, un, ams, iVal, i, __imp, lf_ #(删掉也行)

然后再添加一行成功提示:

        if printout:
            print("\nsucceed in Calculating Values...")

接下来是写入值的部分。

        num = 0
        for i in solves:
            if printout:
                print(f"\r{(num+1) / len(solves) * 100}%", end="", flush=True)
            num += 1
            x_ = []
            for j in i["x"]:
                x_.append(eval(j))
            x.append(x_)
            y_ = []
            for j in i["y"]:
                y_.append(eval(j))
            y.append(y_)
            z_ = []
            for j in i["z"]:
                z_.append(eval(j))
            z.append(z_)
            t_ = []
            for j in i["t"]:
                t_.append(eval(j))
            t.append(t_)

        del x_, y_, z_, t_, solves

代码原理也没有什么好讲的。

        if printout:
            print("\nsucceed in Saving Values...")

最后输出成功提示。↑

(其他的遍历t、y值,遍历t、z值和遍历t值基本相同,暂不赘述)



接下来上一下完整的代码:

# coding=utf-8

import sympy
from tkinter.messagebox import *
from tkinter import *
from math import *

def no_ans():
    Tk().geometry("9x9+990000+999999")
    showerror("警告", "方程无解析解")


x = []
y = []
z = []
t = []

def toLeg(fx):
    v=str(fx).split("\n")
    val=[]
    for i in v:
        tv=i.split("=")
        length=len(tv)
        last=None
        while length!=0:
            if length==2:
                val.append('='.join(tv))
                break
            if length==1:
                val.append('='.join([tv[0],str(last)]))
                break
            val.append('='.join([tv[-2],tv[-1]]))
            length=length-1
            last=tv[-1]
            tv.pop()
    return '\n'.join(val)
def legalSet(fx):


    v=str(fx).split("\n")
    nw=[]
    for l in v:

        tmpstr=""
        tmpstr2=""
        if l=='':continue
        k=l.split("=")
        tmpstr+="(("+k[0]+")-("+k[1]+"))"
        tmpstr2 += "((" + k[1] + ")-(" + k[0] + "))"
        tmpstrs=[tmpstr,tmpstr2]
        nw.append(tmpstrs)
    v=nw
    del nw

    index=-1
    for i in v:
        index+=1
        for j in range(2):
            if ":" in i: v[index][j] = i[j].replace(":", "/")
            if "^" in i: v[index][j] = i[j].replace("^", "**")
            if "÷" in i: v[index][j] = i[j].replace("÷", "/")
            if "×" in i: v[index][j] = i[j].replace("×", "*")
            if "[" in i: v[index][j] = i[j].replace("[", "(")
            if "]" in i: v[index][j] = i[j].replace("]", ")")
            if "【" in i: v[index][j] = i[j].replace("【", "(")
            if "】" in i: v[index][j] = i[j].replace("】", ")")
            if "{" in i: v[index][j] = i[j].replace("{", "(")
            if "}" in i: v[index][j] = i[j].replace("}", ")")
            if "(" in i: v[index][j] = i[j].replace("(", "(")
            if ")" in i: v[index][j] = i[j].replace(")", ")")
    newlt=[]
    lt=[]
    for j in v:


        lt__=[]
        funcs=[]
        news = []
        for i_ in j:
            new = ""
            pos = -1


            for i in i_:

                pos+=1
                tmpos=pos+0
                string=""
                while (i_[tmpos].isalpha()):
                    string+=i_[tmpos]
                    tmpos=tmpos+1
                if string in sympy.__all__ :
                    funcs+=[i for i in range(pos,tmpos+1)]


                if ((i.isalpha() or i == "(") and (i_[pos-1].isnumeric() or i_[pos-1].isalpha())
                        and pos!=0 and pos not in funcs):
                    new+="*"+i

                else:
                    new+=i
                if i.isalpha() and pos not in funcs:lt__.append(i)
            news.append(new)

        lt__=list(set(lt__))
        lt.append(lt__)
        newlt.append(news)
    return newlt,lt
def sqrt(base,times=2):
    if base < 0:
        ans=(-base)**(1/times)
        return eval(f"{ans}j")
    return base**(1/times)
class write:
    def _write_t_x(self,formula,tmin_=-10, tmax_=10, tnums=100,
                 min_=-10, max_=10, nums=100,printout=True):

        global x, y, z, t
        I = 1j
        oo = inf

        self.step = (tmax_ - tmin_) / tnums
        self.aa = tmin_ - self.step
        self.xstep = (max_ - min_) / nums
        r"""

        print(un)
        print(lf,toLeg(formula),sep="\n\n",end="\n\n")
        """
        solves = []
        for iVal in range(tnums + 2):

            self.aa = self.aa + self.step
            self.aa = float("%.10f" % self.aa)
            xValue = min_ - self.xstep
            for XVAL in range(nums + 2):
                lf, un = legalSet(toLeg(formula))
                xValue += self.xstep
                xValue = float("%.10f" % xValue)

                def key(item):
                    if "t" in item[0] or "x" in item[0]:
                        return 1
                    else:
                        return 999

                bf = dict(enumerate(lf))
                lf = sorted(lf, key=key)
                nun = []
                for i in range(len(lf)):
                    nun.insert(lf.index(bf[i]), un[i])
                un = nun
                del nun
                idx = -1
                for imp in un:
                    idx += 1
                    for __imp in imp:
                        if __imp == 't':
                            un[idx].remove("t")
                        if __imp == 'x':
                            un[idx].remove("x")
                del idx

                repl = {"t": [str(self.aa)], "x": [str(xValue)]}
                is_exit = False
                while not is_exit:

                    indx = -1
                    for lf_ in lf:
                        indx += 1
                        for i in repl.keys():
                            for j in range(2):
                                if str(i) in str(lf_[j]):
                                    lf_[j] = lf_[j].replace(i, str(repl[i][0]))

                        idx = -1
                        for imp in un:
                            idx += 1
                            for __imp in imp:
                                if __imp in repl.keys():
                                    un[idx].remove(__imp)
                        del idx

                        if un[indx] == []:
                            del un[indx]
                            del lf[indx]
                            if indx == 0 or (indx - 1) >= len(lf): break
                            indx -= 1
                            continue

                        try:
                            ams = sympy.solve(tuple(lf_), tuple(un[indx]))
                        except NotImplementedError as err:
                            print(err)
                            no_ans()
                            return


                        if isinstance(ams, (dict,)):
                            for km, jj in ams.items():
                                if not ('x' in str(jj) or
                                        'y' in str(jj) or
                                        'z' in str(jj) or
                                        't' in str(jj)):
                                    if km.name in repl.keys():
                                        repl[km.name].append(str(jj))
                                    else:
                                        repl[km.name] = [str(jj)]
                        else:
                            ix = -1
                            undo = 0
                            for i in ams:
                                ix += 1
                                try:
                                    if isinstance(i, (sympy.core.numbers.Float,
                                                      sympy.core.numbers.Integer,
                                                      int, float, complex)):

                                        try:
                                            repl[tuple(un[indx])[ix]] = [str(eval(str(i)))]
                                        except IndexError:

                                            repl[tuple(un[indx])[undo]].append(str(eval(str(i))))
                                        for i in repl.keys():
                                            if i in lf_:
                                                lf_ = lf_.replace(i, str(repl[i][0]))
                                    elif isinstance(i, (tuple, list, set)):
                                        inxx = -1
                                        for jj in i:
                                            inxx += 1
                                            if not ('x' in str(jj) or
                                                    'y' in str(jj) or
                                                    'z' in str(jj) or
                                                    't' in str(jj)):
                                                try:
                                                    repl[tuple(un[indx][inxx])[ix]] = [str(jj)]
                                                except IndexError:
                                                    repl[tuple(un[indx][inxx])[undo]].append(str(jj))
                                    else:
                                        continue
                                except TypeError as err:
                                    print("get:err", err)
                                    continue
                                else:
                                    undo = ix
                        if len(repl.values()) >= 4: is_exit = True;break

                solves.append(repl)
                if printout:
                    print(f"\r{(iVal * (nums + 2) + XVAL + 1) / ((nums + 2) * (tnums + 2)) * 100}%", end="",
                          flush=True)

        if printout:
            print("\nsucceed in Calculating Values...")
        num = 0
        for i in solves:
            if printout:
                print(f"\r{(num+1) / len(solves) * 100}%", end="", flush=True)
            num += 1
            x_ = []
            for j in i["x"]:
                x_.append(eval(j))
            x.append(x_)
            y_ = []
            for j in i["y"]:
                y_.append(eval(j))
            y.append(y_)
            z_ = []
            for j in i["z"]:
                z_.append(eval(j))
            z.append(z_)
            t_ = []
            for j in i["t"]:
                t_.append(eval(j))
            t.append(t_)

        del x_, y_, z_, t_, solves

        if printout:
            print("\nsucceed in Saving Values...")


    def _write_t_y(self,formula,tmin_=-10, tmax_=10, tnums=100,
                 min_=-10, max_=10, nums=100,printout=True):

        global x, y, z, t
        I = 1j
        oo = inf

        self.step = (tmax_ - tmin_) / tnums
        self.aa = tmin_ - self.step
        self.xstep = (max_ - min_) / nums
        r"""

        print(un)
        print(lf,toLeg(formula),sep="\n\n",end="\n\n")
        """
        solves = []
        for iVal in range(tnums + 2):

            self.aa = self.aa + self.step
            self.aa = float("%.10f" % self.aa)
            xValue = min_ - self.xstep
            for XVAL in range(nums + 2):
                lf, un = legalSet(toLeg(formula))
                xValue += self.xstep
                xValue = float("%.10f" % xValue)

                def key(item):
                    if "t" in item[0] or "y" in item[0]:
                        return 1
                    else:
                        return 999

                bf = dict(enumerate(lf))
                lf = sorted(lf, key=key)
                nun = []
                for i in range(len(lf)):
                    nun.insert(lf.index(bf[i]), un[i])
                un = nun
                del nun
                idx = -1
                for imp in un:
                    idx += 1
                    for __imp in imp:
                        if __imp == 't':
                            un[idx].remove("t")
                        if __imp == 'y':
                            un[idx].remove("y")
                del idx

                repl = {"t": [str(self.aa)], "y": [str(xValue)]}
                is_exit = False
                while not is_exit:

                    indx = -1
                    for lf_ in lf:
                        indx += 1
                        for i in repl.keys():
                            for j in range(2):
                                if str(i) in str(lf_[j]):
                                    lf_[j] = lf_[j].replace(i, str(repl[i][0]))

                        idx = -1
                        for imp in un:
                            idx += 1
                            for __imp in imp:
                                if __imp in repl.keys():
                                    un[idx].remove(__imp)
                        del idx

                        if un[indx] == []:
                            del un[indx]
                            del lf[indx]
                            if indx == 0 or (indx - 1) >= len(lf): break
                            indx -= 1
                            continue

                        try:
                            ams = sympy.solve(tuple(lf_), tuple(un[indx]))
                        except NotImplementedError as err:
                            print(err)
                            no_ans()
                            return


                        if isinstance(ams, (dict,)):
                            for km, jj in ams.items():
                                if not ('x' in str(jj) or
                                        'y' in str(jj) or
                                        'z' in str(jj) or
                                        't' in str(jj)):
                                    if km.name in repl.keys():
                                        repl[km.name].append(str(jj))
                                    else:
                                        repl[km.name] = [str(jj)]
                        else:
                            ix = -1
                            undo = 0
                            for i in ams:
                                ix += 1
                                try:
                                    if isinstance(i, (sympy.core.numbers.Float,
                                                      sympy.core.numbers.Integer,
                                                      int, float, complex)):

                                        try:
                                            repl[tuple(un[indx])[ix]] = [str(eval(str(i)))]
                                        except IndexError:

                                            repl[tuple(un[indx])[undo]].append(str(eval(str(i))))
                                        for i in repl.keys():
                                            if i in lf_:
                                                lf_ = lf_.replace(i, str(repl[i][0]))
                                    elif isinstance(i, (tuple, list, set)):
                                        inxx = -1
                                        for jj in i:
                                            inxx += 1
                                            if not ('x' in str(jj) or
                                                    'y' in str(jj) or
                                                    'z' in str(jj) or
                                                    't' in str(jj)):
                                                try:
                                                    repl[tuple(un[indx][inxx])[ix]] = [str(jj)]
                                                except IndexError:
                                                    repl[tuple(un[indx][inxx])[undo]].append(str(jj))
                                    else:
                                        continue
                                except TypeError as err:
                                    print("get:err", err)
                                    continue
                                else:
                                    undo = ix
                        if len(repl.values()) >= 4: is_exit = True;break

                solves.append(repl)
                if printout:
                    print(f"\r{(iVal * (nums + 2) + XVAL + 1) / ((nums + 2) * (tnums + 2)) * 100}%", end="",
                          flush=True)

        if printout:
            print("\nsucceed in Calculating Values...")
        num = 0
        for i in solves:
            if printout:
                print(f"\r{(num+1) / len(solves) * 100}%", end="", flush=True)
            num += 1
            x_ = []
            for j in i["x"]:
                x_.append(eval(j))
            x.append(x_)
            y_ = []
            for j in i["y"]:
                y_.append(eval(j))
            y.append(y_)
            z_ = []
            for j in i["z"]:
                z_.append(eval(j))
            z.append(z_)
            t_ = []
            for j in i["t"]:
                t_.append(eval(j))
            t.append(t_)

        del x_, y_, z_, t_, solves

        if printout:
            print("\nsucceed in Saving Values...")


    def _write_t_z(self,formula,tmin_=-10, tmax_=10, tnums=100,
                 min_=-10, max_=10, nums=100,printout=True):

        global x, y, z, t
        I = 1j
        oo = inf

        self.step = (tmax_ - tmin_) / tnums
        self.aa = tmin_ - self.step
        self.xstep = (max_ - min_) / nums
        r"""

        print(un)
        print(lf,toLeg(formula),sep="\n\n",end="\n\n")
        """
        solves = []
        for iVal in range(tnums + 2):

            self.aa = self.aa + self.step
            self.aa = float("%.10f" % self.aa)
            xValue = min_ - self.xstep
            for XVAL in range(nums + 2):
                lf, un = legalSet(toLeg(formula))
                xValue += self.xstep
                xValue = float("%.10f" % xValue)

                def key(item):
                    if "t" in item[0] or "z" in item[0]:
                        return 1
                    else:
                        return 999

                bf = dict(enumerate(lf))
                lf = sorted(lf, key=key)
                nun = []
                for i in range(len(lf)):
                    nun.insert(lf.index(bf[i]), un[i])
                un = nun
                del nun
                idx = -1
                for imp in un:
                    idx += 1
                    for __imp in imp:
                        if __imp == 't':
                            un[idx].remove("t")
                        if __imp == 'z':
                            un[idx].remove("z")
                del idx

                repl = {"t": [str(self.aa)], "z": [str(xValue)]}
                is_exit = False
                while not is_exit:

                    indx = -1
                    for lf_ in lf:
                        indx += 1
                        for i in repl.keys():
                            for j in range(2):
                                if str(i) in str(lf_[j]):
                                    lf_[j] = lf_[j].replace(i, str(repl[i][0]))

                        idx = -1
                        for imp in un:
                            idx += 1
                            for __imp in imp:
                                if __imp in repl.keys():
                                    un[idx].remove(__imp)
                        del idx

                        if un[indx] == []:
                            del un[indx]
                            del lf[indx]
                            if indx == 0 or (indx - 1) >= len(lf): break
                            indx -= 1
                            continue

                        try:
                            ams = sympy.solve(tuple(lf_), tuple(un[indx]))
                        except NotImplementedError as err:
                            print(err)
                            no_ans()
                            return


                        if isinstance(ams, (dict,)):
                            for km, jj in ams.items():
                                if not ('x' in str(jj) or
                                        'y' in str(jj) or
                                        'z' in str(jj) or
                                        't' in str(jj)):
                                    if km.name in repl.keys():
                                        repl[km.name].append(str(jj))
                                    else:
                                        repl[km.name] = [str(jj)]
                        else:
                            ix = -1
                            undo = 0
                            for i in ams:
                                ix += 1
                                try:
                                    if isinstance(i, (sympy.core.numbers.Float,
                                                      sympy.core.numbers.Integer,
                                                      int, float, complex)):

                                        try:
                                            repl[tuple(un[indx])[ix]] = [str(eval(str(i)))]
                                        except IndexError:

                                            repl[tuple(un[indx])[undo]].append(str(eval(str(i))))
                                        for i in repl.keys():
                                            if i in lf_:
                                                lf_ = lf_.replace(i, str(repl[i][0]))
                                    elif isinstance(i, (tuple, list, set)):
                                        inxx = -1
                                        for jj in i:
                                            inxx += 1
                                            if not ('x' in str(jj) or
                                                    'y' in str(jj) or
                                                    'z' in str(jj) or
                                                    't' in str(jj)):
                                                try:
                                                    repl[tuple(un[indx][inxx])[ix]] = [str(jj)]
                                                except IndexError:
                                                    repl[tuple(un[indx][inxx])[undo]].append(str(jj))
                                    else:
                                        continue
                                except TypeError as err:
                                    print("get:err", err)
                                    continue
                                else:
                                    undo = ix
                        if len(repl.values()) >= 4: is_exit = True;break

                solves.append(repl)
                if printout:
                    print(f"\r{(iVal * (nums + 2) + XVAL + 1) / ((nums + 2) * (tnums + 2)) * 100}%", end="",
                          flush=True)

        if printout:
            print("\nsucceed in Calculating Values...")
        num = 0
        for i in solves:
            if printout:
                print(f"\r{(num+1) / len(solves) * 100}%", end="", flush=True)
            num += 1
            x_ = []
            for j in i["x"]:
                x_.append(eval(j))
            x.append(x_)
            y_ = []
            for j in i["y"]:
                y_.append(eval(j))
            y.append(y_)
            z_ = []
            for j in i["z"]:
                z_.append(eval(j))
            z.append(z_)
            t_ = []
            for j in i["t"]:
                t_.append(eval(j))
            t.append(t_)

        del x_, y_, z_, t_, solves

        if printout:
            print("\nsucceed in Saving Values...")


    def _write_t(self,formula,tmin_=-10, tmax_=10, tnums=100,printout=True):

        global x, y, z, t
        I = 1j
        oo = inf

        self.step = (tmax_ - tmin_) / tnums
        self.aa = tmin_ - self.step
        r"""

        print(un)
        print(lf,toLeg(formula),sep="\n\n",end="\n\n")
        """
        solves = []
        for iVal in range(tnums + 2):

            self.aa = self.aa + self.step
            self.aa = float("%.10f" % self.aa)
            lf, un = legalSet(toLeg(formula))

            def key(item):
                if "t" in item[0]:
                    return 1
                else:
                    return 999

            bf = dict(enumerate(lf))
            lf = sorted(lf, key=key)
            nun = []
            for i in range(len(lf)):
                nun.insert(lf.index(bf[i]), un[i])
            un = nun
            del nun
            idx = -1
            for imp in un:
                idx += 1
                for __imp in imp:
                    if __imp == 't':
                        un[idx].remove("t")
            del idx

            repl = {"t": [str(self.aa)]}
            is_exit = False
            while not is_exit:

                indx = -1
                for lf_ in lf:
                    indx += 1
                    for i in repl.keys():
                        for j in range(2):
                            if str(i) in str(lf_[j]):
                                lf_[j] = lf_[j].replace(i, str(repl[i][0]))

                    idx = -1
                    for imp in un:
                        idx += 1
                        for __imp in imp:
                            if __imp in repl.keys():
                                un[idx].remove(__imp)
                    del idx

                    if un[indx] == []:
                        del un[indx]
                        del lf[indx]
                        if indx == 0 or (indx - 1) >= len(lf): break
                        indx -= 1
                        continue

                    try:
                        ams = sympy.solve(tuple(lf_), tuple(un[indx]))
                    except NotImplementedError as err:
                        print(err)
                        no_ans()
                        return


                    if isinstance(ams, (dict,)):
                        for km, jj in ams.items():
                            if not ('x' in str(jj) or
                                    'y' in str(jj) or
                                    'z' in str(jj) or
                                    't' in str(jj)):
                                if km.name in repl.keys():
                                    repl[km.name].append(str(jj))
                                else:
                                    repl[km.name] = [str(jj)]
                    else:
                        ix = -1
                        undo = 0
                        for i in ams:
                            ix += 1
                            try:
                                if isinstance(i, (sympy.core.numbers.Float,
                                                  sympy.core.numbers.Integer,
                                                  int, float, complex)):

                                    try:
                                        repl[tuple(un[indx])[ix]] = [str(eval(str(i)))]
                                    except IndexError:

                                        repl[tuple(un[indx])[undo]].append(str(eval(str(i))))
                                    for i in repl.keys():
                                        if i in lf_:
                                            lf_ = lf_.replace(i, str(repl[i][0]))
                                elif isinstance(i, (tuple, list, set)):
                                    inxx = -1
                                    for jj in i:
                                        inxx += 1
                                        if not ('x' in str(jj) or
                                                'y' in str(jj) or
                                                'z' in str(jj) or
                                                't' in str(jj)):
                                            try:
                                                repl[tuple(un[indx][inxx])[ix]] = [str(jj)]
                                            except IndexError:
                                                repl[tuple(un[indx][inxx])[undo]].append(str(jj))
                                else:
                                    continue
                            except TypeError as err:
                                print("get:err", err)
                                continue
                            else:
                                undo = ix
                    if len(repl.values()) >= 4: is_exit = True;break

            solves.append(repl)
            if printout:
                print(f"\r{(iVal + 1) / (tnums+2)  * 100}%", end="",
                      flush=True)

        if printout:
            print("\nsucceed in Calculating Values...")
        num = 0
        for i in solves:
            if printout:
                print(f"\r{(num+1) / len(solves) * 100}%", end="", flush=True)
            num += 1
            x_ = []
            for j in i["x"]:
                x_.append(eval(j))
            x.append(x_)
            y_ = []
            for j in i["y"]:
                y_.append(eval(j))
            y.append(y_)
            z_ = []
            for j in i["z"]:
                z_.append(eval(j))
            z.append(z_)
            t_ = []
            for j in i["t"]:
                t_.append(eval(j))
            t.append(t_)

        del x_, y_, z_, t_, solves

        if printout:
            print("\nsucceed in Saving Values...")

【只有单遍历t的部分变化较大,有兴趣的可以自行研究】

下一篇:

https://blog.youkuaiyun.com/html_finder/article/details/126117593icon-default.png?t=M666https://blog.youkuaiyun.com/html_finder/article/details/126117593

-------------------------------------完------------------------------------------------------------------------------

这里是Unconquerable&Llxy,原名html_finder

Unconquerable&Llxy的博客_优快云博客-Python从负无穷到~,Vpython-3D,办公领域博主Unconquerable&Llxy擅长Python从负无穷到~,Vpython-3D,办公,等方面的知识,Unconquerable&Llxy关注算法,python,c++领域.https://blog.youkuaiyun.com/html_finder?type=blog

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Unconquerable p

给点吧~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值