【问题标题】:How can I pass user input in the form of a variable to a lambda function in python?如何以变量的形式将用户输入传递给 python 中的 lambda 函数?
【发布时间】:2017-11-27 19:38:32
【问题描述】:

所以我对编程有点陌生,我正在寻求一些帮助。我正在制作一个图形计算器,并希望用户使用 x 输入一个等式,例如 (x + 3) 或 (x^2 + 3x + 4)。我最近发现了 lambda 函数,想知道是否有办法将变量传递给它,以便使用用户方程获取绘图点。我计划使用 for 循环将新值传递给方程。如果您对如何完成我的图形计算器有任何其他建议,请随时通知我。到目前为止,我的代码只是用户浏览我的程序的一种方式。这是我的代码:

def main():
    while True:
        response = menu()
        if response == "1":
            print("enter an equation in the form of mx + b")
            equation = (input())
            print(coordinates(equation))
        elif response == "2":
            print("enter a value for x")
            x = input()
            print("enter a value for y")
            y = input()
        elif response == "0":
            print("Goodbye")
            break
        else:
            print("please enter '1' '2' or '0'")

def menu():
    print("Graphing Calculator")
    print("0) Quit")
    print("1) Enter an equation")
    print("2) Plot points")
    print("Please select an option")
    response = input()
    return response

"""def coordinates(equation):
    f = lambda x: equation
"""

if __name__ == "__main__":
    main()

【问题讨论】:

  • 还可以考虑将 Sympy 用于您的后端。

标签: python variables lambda calculator graphing


【解决方案1】:

我知道我要回答你的问题两次。但这一次,我将向您展示一些非常酷的东西,而不是仅仅修复您的代码。

输入:Sympy。 Sympy 是 Numpy 包的一个模块,它进行符号操作。你可以找到一些文档here

太好了,又一个模块。但是它做什么

Sympy 将方程和表达式保留为符号而不是变量。继续 import sympy 或 pip 安装它,如果你没有它。现在,让我们为该单变量方程坐标查找器构建一个评估单元。首先,让我们确保 python 知道 x 是一个 sympy 符号。这很重要,因为否则,python 会将其视为普通变量,并且不会将控制权交给 sympy。 Sympy 可以很容易地做到这一点,甚至支持一次制作多个符号。所以继续做x, y, z = sympy.symbols("x y z")。现在,让我们请求函数。

def make_an_equation(raw_equation = ""):
  if raw_equation == "": #This allows for make_an_equation to be used from the console AND as an interface. Spiffy, no?
    raw_equation = raw_input("Y=")
  #filter and rewrite the equation for python compatibility. Ex. if your raw_equation uses ^ for exponentiation and XOR for exclusive or, you'd turn them into ** and ^, respectively. 
  expr = eval(filtered_equation)
  return expr

好的,你有一个可以做方程式的东西。但是......你还不能完全使用它。这完全是象征性的。您必须使用 expr.subs 来替换 x 的数字。

>>> my_expression = make_an_equation("x**2") #I'm assuming that the filter thing was never written. 
>>> my_expression
x**2
>>> my_expression.subs(x,5)
25

看看这有多容易?你也可以变得更加复杂。让我们用另一个符号代替数字。

>>> my_expression.subs(x,z)
z**2

Sympy 包含许多非常酷的工具,例如三角函数和微积分。无论如何,你去吧,介绍 Sympy!玩得开心!

【讨论】:

  • :D 我会对此进行更多研究,谢谢您的建议
【解决方案2】:

所以...我继续查看了您的整个代码。我将向您介绍我在 cmets 中所做的事情。

def main():
    while True:
        response = raw_input("Graphing Calculator\n0) Quit\n1) Enter an equation\n2) Plot points\nPlease select an option\n>>>")

        #I removed menu() and condensed the menu into a single string. 
        #Remember to use raw_input if you just want a string of what was input; using input() is a major security risk because it immediately evaluates what was done. 

        if response == "1":
            print("Enter an equation")
            equation = raw_input("Y=")  #Same deal with raw_input. See how you can put a prompt in there? Cool, right?
            finished_equation = translate_the_equation(equation)
            #This is to fix abnormalities between Python and math. Writing this will be left as an exercise for the reader.
            f = coordinates(finished_equation)
            for i in xrange(min_value,max_value): 
              print((i,f(i))) #Prints it in (x,y) coordinate pairs.
        elif response == "2":
            x = raw_input("X=? ")
            y = raw_input("Y=? ")
            do_something(x,y)
        elif response == "0":
            print("Goodbye")
            break
        else:
            print("please enter '0', '1', or '2'") #I ordered those because it's good UX design. 
coordinates = lambda equation: eval("lambda x:"+ equation)
#So here's what you really want. I made a lambda function that makes a lambda function. eval() takes a string and evaluates it as python code. I'm concatenating the lambda header (lambda x:) with the equation and eval'ing it into a true lambda function.

【讨论】:

  • 这是一个很好的答案,但应该注意的是,通常的数学语法和 Python 表达式之间存在差异。例如,Python 中的mx+bmx 对象和b 对象之和;而在数学中它可能被理解为m*x + b。如果 OP 真的想像数学一样获得mx+b,则需要某种形式的解析/翻译。
  • @FrancisColas 是的,但这是题外话,坦率地说,我讨厌与解析器打交道。我将添加一个手波解析部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多