我的任务是编写一个函数解释,它接受两个参数,一个有效的表达式和一个解释,如果在这个特定的解释中整个表达式为真,则给出真值。逻辑常量和表达式应该作为字符串进行管理,因此您需要为布尔操作实现自己的函数。
请注意,该函数应返回“true”或“false”而不是True或False。
以下是一些可能的输入和输出:
def and_operator(statement, values):
if isinstance(statement[0], str) and isinstance(statement[2], str):
statement[0] = (statement[0], values)
statement[2] = (statement[2], values)
return "true" if statement[0] == "true" and statement[2] == "true" else "false"
if isinstance(statement[0], str):
return and_operator()
return interpret(statement[0], values), interpret(statement[2], values)
def or_operator(statement, values):
if isinstance(statement[0], str) and isinstance(statement[2], str):
statement[0] = (statement[0], values)
statement[2] = (statement[2], values)
return "true" if statement[0] == "true" or statement[2] == "true" else "false"
def not_operator(expr, value):
if isinstance(expr[1], str):
return "false" if expr[1] == "true" else "true"
return interpret(expr[1:], value)
def real_values(element, interp):
if element in interp:
element = interp[element]
return element
def item_is_list(e, i):
return True if isinstance(e[i], list) else False
def interpret(statement, interpretation):
length = len(statement)
if item_is_list(statement, 0):
return statement
if length == 3:
if statement[1] == "AND":
return and_operator(statement, interpretation)
elif statement[1] == "OR":
return or_operator(statement, interpretation)
elif len(statement) == 2:
return not_operator(statement, interpretation)
所以这是我的代码,它适用于上面显示的第一个和最后一个案例,但在其他所有案例中,我得到错误的输出或根本没有。这是什么问题,如何解决?
student_number=raw_input("What is your 5-digit student number?")
added_digits=sum(int(x) for x in student_number)
div_7=added_digits%7
if div_7==0 and len(str(student_number))==5:
print "Your student number is valid."
grades=raw_input("To find out your average GPA, please list your letter grades for each class.\n")
grade_list = [grades] #use a list to store your grades
while grades!="":
grades=raw_input()
grade_list.append(grades) #store every input in grade_list
grade_value=0
for x in grade_list: #use grade_list, not grades
if x=="A":
grade_value+=4.0
print grade_value
if x=="B":
grade_value+=3.0
print grade_value
else:
print "That is not a valid student number."