Python练习题答案: 功能工厂【难度:2级】--景越Python编程实例训练营,1000道上机题等你来挑战

功能工厂【难度:2级】:

答案1:

def function_factory(x,y,o):
    return lambda: eval(str(x)+o+str(y))

答案2:

from operator import add, sub, mul, truediv, mod

def function_factory(x,y,o):
    return lambda: {"+": add, "-": sub, "*": mul, "/": truediv, "%": mod}[o](x, y)
    
def naughty_function_factory(x,y,o):
    return lambda: eval("{} {} {}".format(x, o, y))

答案3:

def function_factory(x,y,o):
    def f():
        return eval('{}{}{}'.format(x,o,y))
    return f​

答案4:

def function_factory(x, y, operator):
    def my_function():
        return eval(f"{x} {operator} {y}")
        
    return my_function​

答案5:

def function_factory(x,y,o):
    return lambda: eval(f'{x}{o}{y}')

答案6:

def function_factory(x,y,o):
    a = str(x)
    b = str(y)
    return lambda: eval(a+o+b)

答案7:

def function_factory(x,y,o):
    def func():
        return eval(str(x)+o+str(y))
    return func​

答案8:

def function_factory(x,y,o):
    operations = {'+':x + y,
                  '-':x - y, 
                  '*':x * y, 
                  '/':x / y, 
                  '%':x % y}
    def evaluate():
        return operations[o]
    return evaluate​

答案9:

def function_factory(x,y,o):
    def add():
        return x + y
    def subtract():
        return x - y
    def multiply():
        return x * y
    def divide():
        return x / y
    def reminder():
        return x % y
    
    operations = {'+':add,
                  '-':subtract, 
                  '*':multiply, 
                  '/':divide, 
                  '%':reminder}
    
    return operations[o]

答案10:

def function_factory(x,y,o):
    operations = {'+':x + y,
                  '-':x - y, 
                  '*':x * y, 
                  '/':x / y, 
                  '%':x % y}
    
    def calc_function():
        return operations[o]
    return calc_function
  ​




Python基础训练营景越Python基础训练营QQ群

在这里插入图片描述
欢迎各位同学加群讨论,一起学习,共同成长!

你可能感兴趣的:(Python编程习题答案,python面试题库和答案,python编程练习,编程基础上,功能,控制流)