Skip to main content
 首页 » 编程设计

python之Lambda 函数要求输入两次,

2025年02月15日7EasonJim

我正在使用 python 进行一个相当复杂的数学项目,但一直遇到一个问题:

a = lambda x: input('Function in terms of x') 

这一直有效,直到我必须运行如下命令:

z = a(n) 

每次完成后,它都会再次要求输入,所以我得到一个如下所示的控制台:

Function in terms of x: 
Function in terms of x: 

我知道理论上我应该能够解决以下问题:

func = input('Function: ') 
a = lambda x: func 

这会产生另一个问题:x 没有在外部作用域中定义,所以我添加了 sympy 符号,如下所示:

x = sym.Symbol('x') 
func = input('Function: ') 
a = lambda x: func 

但是然后运行这样的命令会导致一些奇怪的事情:

Function: 5*x +1 
>>>a(10) 
5*x + 1 

我认为这是因为 lambda 不适用于 sympy,但我想不出另一种方法来解决这个问题...谢谢您的帮助。

完整代码如下;该函数在第 18 行请求第一个输入,然后在第 50 行不应该的地方请求输入。我相信这与我两次使用 lambda 函数有关。

import matplotlib.pyplot as plt 
import os 
import time 
from mpl_toolkits.mplot3d import axes3d 
from sympy import * 
import numpy as np 
import tkinter as tk 
from colorama import init, Fore, Back, Style 
import mpmath 
 
 
def main(): 
    """ 
    Handling for Range and function 
    """ 
    rng = raw_input('Minimum, Maximum: ').split(',') 
    rng = [float(rng[i]) for i in range(2)] 
    a = lambda x: input('Function of x: ')  # function a is the main polynomial# 
    """ 
        2 Dimensional Graph 
    """ 
    two_d_x = np.arange(rng[0], rng[1], abs(rng[1] - rng[0]) / 100) 
    two_d_y = a(two_d_x) 
    fig1 = plt.figure() 
    ax1 = fig1.add_subplot(221) 
    print [np.amin(two_d_x), np.amax(two_d_x), np.amin(two_d_y), np.amax(two_d_y)] 
    ax1.axis([np.amin(two_d_x), np.amax(two_d_x), np.amin(two_d_y), np.amax(two_d_y)]) 
    ax1.plot(two_d_x, two_d_y, 'r-') 
    ax1.set_title(r'$\mathit{f(x)}\in \mathbb{R}^2$') 
    ax1.set_xlabel(r'$\mathit{x}$') 
    ax1.set_ylabel(r'$\mathit{y}$') 
    ax1.grid() 
    ax1.spines['left'].set_position('zero') 
    ax1.spines['right'].set_color('none') 
    ax1.spines['bottom'].set_position('zero') 
    ax1.spines['top'].set_color('none') 
    ax1.spines['left'].set_smart_bounds(True) 
    ax1.spines['bottom'].set_smart_bounds(True) 
    plt.gca().set_aspect('equal', adjustable='box') 
    ax1.xaxis.set_ticks_position('bottom') 
    ax1.yaxis.set_ticks_position('left') 
    """ 
        Quiver Plot of Function 
    """ 
    ax2 = fig1.add_subplot(222) 
    u, v = np.meshgrid(np.arange(rng[0], rng[1], 1), 
                       np.arange(rng[0], rng[1], 1)) 
    ### u+vj -> w+rjf 
    print False 
    output = a(u + (v * 1j)) 
    print False 
    w = output.real 
    r = output.imag 
    ax2.axis([np.amin(w) * 1.1, np.amax(w) * 1.1, np.amin(r) * 1.1, np.amax(r) * 1.1]) 
    distance = np.sqrt(((w - u) ** 2) + ((r - v) ** 2)) 
    quiver_plot = ax2.quiver(u, v, w, r, distance, angles='xy', scale_units='xy', scale=1, cmap=plt.cm.jet) 
    plt.colorbar(quiver_plot, cmap=plt.cm.jet) 
    ax2.set_title(r'$\mathit{f(x)}\in \mathbb{C}^2$') 
    ax2.set_xlabel(r'$\mathit{rl}$') 
    ax2.set_ylabel(r'$\mathit{im}$') 
    ax2.grid() 
    ax2.spines['left'].set_position('zero') 
    ax2.spines['right'].set_color('none') 
    ax2.spines['bottom'].set_position('zero') 
    ax2.spines['top'].set_color('none') 
    ax2.spines['left'].set_smart_bounds(True) 
    ax2.spines['bottom'].set_smart_bounds(True) 
    plt.gca().set_aspect('equal', adjustable='box') 
    ax2.xaxis.set_ticks_position('bottom') 
    ax2.yaxis.set_ticks_position('left') 
    plt.show() 
 
 
main_program_loop = True 
while main_program_loop == True: 
    print '| Quandri 1.0 | by: Boolean Designs\n' 
    main() 
    stay_loop_tp = True 
    while stay_loop_tp != False: 
        stay_loop_tp = raw_input("Would you like to continue using this program <yes/no>? ") 
        if stay_loop_tp == 'yes' or stay_loop_tp == 'y': 
            os.system('cls') 
            stay_loop_tp = False 
        elif stay_loop_tp == 'no' or stay_loop_tp == 'n': 
            print 'Exiting Quandri...' 
            time.sleep(1) 
            exit() 
            stay_loop_tp = False 
        else: 
            print "Improper Input." 
            time.sleep(2) 
            os.system('cls') 

请您参考如下方法:

sympy 库支持解析和评估表达式:

import sympy 
from sympy.parsing.sympy_parser import parse_expr 
 
x = sympy.Symbol('x') 
expression_string = input("Function: ") 
expr = parse_expr(expression_string) 
expr.evalf(subs={x:10}) 

看这个http://docs.sympy.org/dev/modules/parsing.html 还有这个How to calculate expression using sympy in python


编辑:Thomas Kühn 的回答很好,但在 python2.7 中必须使用 raw_input

f = raw_input("Function: ") 
a = lambda x:eval(f)  
print(a(10))