本人纯小白,记录一下离散数学作业,合式公式的层次,大佬多多指正 #非 1 not 1==0 #或 or #与 and #蕴涵 y #等价 d import re import numpy as np class Level(): def __init__(self): input=self._input() init=self.init(input) def _input(self): print("每个字符需有空格,每个运算需有括号!") a=input("输入公式:") a = (str(a)).split(' ') countl = 0 countr = 0 for i in a: if i == '(': countl += 1 elif i == ')': countr += 1 if countl != countr: print('输入格式错误!(左右括号不相等或空格输入不符合标准)') exit(0) for i in range(len(a)): if a[i] not in ['not' , 'or' , 'and' , 'y' , 'd' , '1' , '0' , '(' , ')',' ',1,0]: print("输入格式错误!") exit(0) i=0 while i<int(len(a)): if a[i] == '1' or a[i]==1: a[i] ='0' if i<len(a)-1: if a[i+1]=='not': a.insert(i+1,'0') i+=1 i+=1 return a def sreach_next(self,a):#找()部分,从(找到) b = np.array(a) indexl = np.array(np.where(b == '(')[0]) c=0 re_indexl=reversed(indexl) for i in re_indexl: while 1: i += 1 if b[i]==')': c=i break return c def chengci_part(self,arr):#判断小部分层次!!! count=0 regester=[] arr=list(arr) for i in range(len(arr)): try: arr[i]=int(arr[i]) except: continue for i in range(len(arr)): if arr[i] in [1, 0, '1', '0',2,3,4,5,6,7,8,9,10,11]: if arr[i + 1] not in ['not', 'or', 'and', 'y', 'd','(',')' ] or arr[i - 1] not in ['not', 'or', 'and', 'y', 'd','(',')']: print('不是合式公式!1') print(arr) exit(0) if arr[i] in ['not', 'or', 'and', 'y', 'd']: if arr[i + 1] not in [1, 0, '1', '0',2,3,4,5,6,7,8,9,10,11] or arr[i-1] not in [1, 0, '1', '0',2,3,4,5,6,7,8,9,10,11]: print('不是合式公式!2') print(arr) exit(0) for i in range(len(arr)): if arr[i] in [0,1,2,3,4,5,6,7,8,9,10,11]: regester.append(arr[i]) try : count=max(regester)+len(regester)-1 except: pass return count def chengci_all(self,arr):#切片传参 b = np.array(arr) indexl = np.array(np.where(b == '(')[0]) re_indexl = indexl[::-1] re_indexr=self.sreach_next(arr) return_part=self.chengci_part(arr[re_indexl[0]:re_indexr+1]) arr=list(arr) arr[re_indexl[0]:re_indexr+1]=[] arr[re_indexl[0]:re_indexl[0]] = (return_part,) return arr def init(self,input):#假迭代器 input=np.array(input) for i in range(len(np.array(np.where(input == '('))[0])): input=self.chengci_all(input) try: input=input[0] except: pass print(input) if __name__=='__main__': Level() #( ( ( 1 and 1 ) and 1 ) or 1 ) #( 1 and 1 ) #( not ( ( 1 y 0 ) or ( 0 or 1 ) ) )
离散数学作业:返回合式公式的层次
最新推荐文章于 2024-11-02 16:28:26 发布