如何实现二叉树和其一系列操作的代码

建二叉树和怎么运算结果的代码链接已经表明,本文的重点不是这个

首先就是将二叉树序列化,这个文件命名为package.py

import pickle

def package(*args):
    """serialisation"""
    ''' A package named pickle was used. '''
    t1 = open("exercises.py", 'wb')

    '''open the file'''

    '''Pay attention, the file will be create if it was not existed'''

    pickle.dump(args, t1)

    '''dump() will save the args into file'''

    t1.close()
def read():
    '''do not forget to close the file'''

    t2 = open('exercises.py', 'rb')

    b = pickle.load(t2)

    '''Read it'''

    t2.close()

    print(b)

'''Thus, we create a file to save a binary in to a binary file. '''

def delete_content():
    """ After save the binary tree, we cannot run the code correctly """

    with open("exercises.py", 'r+') as file:

        file.truncate(0)

        file.close()
''' the file was empty'''

然后就是检查括号和运算符是否有误!这个文件命名为check.py

def check(expre):

    lst1 = list(expre)
    l = len(lst1)

    a = 0

    b = 0

    lst = list(expre)
    ''' use a list to save the data of expression. '''

    for j in lst:

        if j == "+" or j == "-" or j == "*" or j == "/":

                a += 1

        elif j == "(" or j == ")":

                b += 1
        else:

            pass

    if lst[0] != "(" or lst[-1] != ")":

        return 1

    if b > 2*a:
        return 1


    elif b < 2 * a:

        return 0

    for i in range(1,l):

        if lst1[i] in "0123456789" and lst1[i-1] == "(" and lst1[i+1] == ")":
            return 0

'''it will find some brackets mismatched like (1+2)) or 1+2'''


def operator_missing(expre):

    expre1 = list(expre)

    lst = []

    for j in expre1:

        if j == "+":
            lst.append("+")

        if j == "-":
            lst.append("-")

        if j == "*":
            lst.append("*")

        if j == "/":
            lst.append("/")

        if j == "1":
            lst.append("1")

        if j == "2":
            lst.append("2")

        if j == "3":
            lst.append("3")

        if j == "4":
            lst.append("4")

        if j == "5":
            lst.append("5")

        if j == "6":
            lst.append("6")

        if j == "7":
            lst.append("7")

        if j == "8":
            lst.append("8")

        if j == "9":
            lst.append("9")

        if j == "0":
            lst.append("0")

    l = len(lst)

    if l == 1:

        pass

    if l > 1:

        for i in range(1, l):

            if lst[i] in "0123456789" and lst[i-1] in "0123456789":

                return 1

            else:

                pass

最后一个就是创建一个文件test.py作为主程序,其余的文件均作为包来调用

import os

import unittest

import check

import package

import binary_tree

class TestException(unittest.TestCase):

    """ Moreover, some unit tests are necessary """
    ''' unittest was used in this case '''

    def test(self):

        formulas = input("Enter your equations: ")

        ''' input an equation, and go on. '''

        if check.check(formulas) == 0:

            """ using check() to check the Exception """

            raise Exception("Not a valid expression, operator missing.")


        elif check.operator_missing(formulas) == 1:

            ''' using operator_missing() to check another Exception'''

            raise Exception("Not a valid expression, operator missing.")


        elif check.check(formulas) == 1:

            ''' using check() to check brackets mismatched.'''

            raise Exception("Not a valid expression, brackets mismatched.")



        else:


            fTree = binary_tree.BuildTree(formulas)


            eTree = fTree.createTree()

            ''' build a tree '''

            value = fTree.evaluate(eTree)
            ''' get the result value '''

            if os.path.getsize("exercises.py") == 0:
                package.package(eTree)
                package.read()
                '''if the file has no content, binary tree will be save'''

            else:
                package.read()
                package.delete_content()
                '''if the file has content, it will be delete and become empty.'''






            '''package.delete_content()'''
            '''it will delete the content of binary file'''

            print(value)


if __name__ == "__main__":
    unittest.main()
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值