基本运算符
Coddy Python 计算器项目 课程的第 12 课,共 29 课。
下一步是把列表 struct 成我们的基本结构。
考虑计算 1 + 2 + 3,首先我们把它转换成列表 [1, '+', 2, '+', 3],然后将它 struct 成我们的 eval 函数接收的形式:['+', ['+', 1, 2], 3]。
在这一步中,我们只关心把列表组织成 eval 函数接收的格式。
示例:
[4.5, '-', 3]->['-', 4.5, 3][4.5, '-', 3, '+', 2]->['+', ['-', 4.5, 3], 2][1, 'sub', 2, 'add', 3, '+', 4]->['+', ['add', ['sub', 1, 2], 3], 4]
挑战
中等创建函数 struct,它接收上述格式的列表,并返回适用于 eval 函数的格式。
目前只处理基本运算符 '+' 和 '-'。
亲手试试
def calc(op, n1, n2=None):
if not isinstance(n1, int) and not isinstance(n1, float):
raise Exception('Invalid number "' + str(n1) + '"')
if n2 is None:
if op == '+' or op == 'add':
return n1
if op == '-' or op == 'sub':
return -n1
raise Exception('Invalid operator "' + op + '"')
if not isinstance(n2, int) and not isinstance(n2, float):
raise Exception('Invalid number "' + str(n2) + '"')
if op == '+' or op == 'add':
return n1 + n2
if op == '-' or op == 'sub':
return n1 - n2
if op == '*' or op == 'mul':
return n1 * n2
if op == '/' or op == 'div':
if n2 == 0:
raise Exception("Division by zero")
return n1 / n2
if op == '%' or op == 'mod':
if n2 == 0:
raise Exception("Division by zero")
return n1 % n2
if op == '^' or op == 'pow':
return n1 ** n2
raise Exception('Invalid operator "' + op + '"')
def eval(lst):
if not isinstance(lst, list):
raise Exception('Failed to evaluate "' + str(lst) + '"')
if len(lst) == 2:
op = lst[0]
n = lst[1]
if not isinstance(n, list):
return calc(op, n)
if isinstance(n, list):
n = eval(n)
return calc(op, n)
elif len(lst) == 3:
op = lst[0]
n1 = lst[1]
n2 = lst[2]
if not isinstance(n1, list) and not isinstance(n2, list):
return calc(op, n1, n2)
if isinstance(n1, list):
n1 = eval(n1)
if isinstance(n2, list):
n2 = eval(n2)
return calc(op, n1, n2)
else:
raise Exception('Failed to evaluate "' + str(lst) + '"')Python 计算器项目中的所有课
自己练习: Python 在线编译器