everfortuneai_interview/Q2/code.py

64 lines
1.4 KiB
Python

# code.py
# Please use env.yaml to build corresponding conda env if you want to run this script
#
# author : deng
# date : 20230919
# platform: MacBook Pro 14 2021
VALID_CHARS = ['T', 'F', 'O', 'A', '(', ')']
CAL_DICT = {
'T': 'T',
'F': 'F',
'TAT': 'T',
'TAF': 'F',
'FAT': 'F',
'FAF': 'F',
'TOT': 'T',
'TOF': 'T',
'FOT': 'T',
'FOF': 'F'
}
def log_cal(exp: str) -> str:
while True:
if exp in CAL_DICT:
return CAL_DICT[exp]
else:
try:
exp = CAL_DICT[exp[:3]] + exp[3:]
except KeyError:
return 'E'
def bool_exp(exp: str) -> str:
stack = []
for char in exp:
if char not in VALID_CHARS:
return 'E'
if char == ')':
sub_exp = ''
while True:
try:
val = stack.pop()
if val == '(':
break
sub_exp = val + sub_exp
except IndexError:
return 'E'
cal_exp = log_cal(sub_exp)
if cal_exp == 'E':
return 'E'
stack.append(cal_exp)
else:
stack.append(char)
return log_cal(''.join(stack))
if __name__ == '__main__':
exp = input('Please input expression:').upper()
print(bool_exp(exp))