Lambda函数要求输入两次,

时间:2017-05-14 17:35:20

标签: python python-2.7 lambda

我正在使用python开展一个相当复杂的数学项目,但仍然遇到一个问题:

z = a(n)

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

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

每次这样做都会再次要求输入,所以我得到一个看起来像的控制台:

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

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

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

这会产生另一个问题:x未在外部作用域中定义,因此我添加了像这样的符号符号:

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

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

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')

我认为这是因为lambda不能与sympy合作,但我想不出另一种解决问题的方法......谢谢你的帮助。

完整代码如下;该函数要求第18行的第一个输入,然后是第50行,在第50行也不应该这样做。我相信这与我使用lambda函数两次这一事实有关。

{{1}}

2 个答案:

答案 0 :(得分:1)

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

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

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

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

答案 1 :(得分:0)

我不知道,如果建议做这样的事情,但这里有一些适用于python 3.5的代码:

func = input('Function: ')
a = lambda x: eval(func)
print(a(10))

用python调用这个脚本,我得到:

Function: x+1
11