Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def and_function(expression1, expression2):
- if expression1=="true" and expression2=="true":
- return "true"
- else:
- return "false"
- def or_function(expression1, expression2):
- if expression1== "true" or expression2=="true":
- return "true"
- else:
- return "false"
- def not_function(expression):
- if expression == "true":
- return "false"
- elif expression == "false":
- return "true"
- binary_bool_dict = {'AND':and_function, 'OR':or_function}
- unary_bool_dict = {'NOT':not_function}
- def interpret( exprsn, dct):
- if isinstance( exprsn, list):
- lst = exprsn
- temp_result = None
- for idx, item in enumerate( lst):
- if item == 'true' or item == 'false':
- # item is already in its interpreted state
- continue
- elif isinstance( item, list):
- # recursive call cond 2)
- lst[idx] = interpret( item,dct)
- elif item in dct:
- # get the meaning of this item from dictionary
- lst[idx] = dct[item]
- else:
- # recursive call cond 1)
- lst[idx+1] = interpret( lst[ idx+1],dct)
- '''
- interpret(["NOT", ["lights_on", "AND" , "candleNeeded"]],{"lights_on":"true", "candleNeeded" :"false"})
- temp_result = None
- item --> "NOT" ie item is in unary_bool_dict
- NOT requires operand on right side to be interpreted completely first ( we can do short-circuit-eval for OR, AND see the improved version of answer)
- next item( right operand) is a list so we will make a recursive call( cond 2)
- { lst[idx+1] }{1} = interpret( { lst[ idx+1] }{2}, {dct}{3} ) after finding interpretation of list we will replace with its interpretation
- ["lights_on", "AND" , "candleNeeded"]{1} = interpret( ["lights_on", "AND" , "candleNeeded"]{2},{lights_on:"true", candleNeeded: "false"}{3} )
- lst[idx+1] = "false"
- now our orignal list arguement has become = ["NOT","false"]
- temp_result = unary_bool_dict[item]("false")
- temp_result = "true"
- '''
- if item in binary_bool_dict:
- if temp_result == None:
- temp_result = binary_bool_dict[item]( lst[ idx-1], lst[idx+1])
- else:
- temp_result = binary_bool_dict[item]( temp_result, lst[idx+1])
- else:
- # item in unary_bool_dict:
- temp_result = unary_bool_dict[item](lst[idx+1])
- return temp_result # eventually temp_result will become our final answer
- else:
- return dct.get( exprsn,exprsn) # if exprsn( as key) is present in dct get its value else just return exprsn ( it must be already a 'true' or 'false')
- print(interpret(["NOT", ["lights_on", "AND" , "candleNeeded"]],{"lights_on":"true", "candleNeeded" :"false"}))
Add Comment
Please, Sign In to add comment