Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 932763
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T20:43:14+00:00 2026-05-15T20:43:14+00:00

I’m using python, and I want a function that takes a string containing a

  • 0

I’m using python, and I want a function that takes a string containing a mathematical expression of one variable (x) and returns a function that evaluates that expression using lambdas. Syntax should be such:

f = f_of_x("sin(pi*x)/(1+x**2)")
print f(0.5)
0.8

syntax should allow ( ) as well as [ ] and use standard operator precedence. Trig functions should have precedence lower than multiplication and higher than addition. Hence the string ‘sin 2x + 1’ would be equivalent to sin(2x)+1, though both are valid. This is for evaluating user input of algebraic and trigonometric expressions, so think math syntax not programming syntax. The list of supported functions should be easily extensible and the code should be clear and easy to understand. It’s OK not to collapse constant expressions.

The sample function here is incomplete. It takes a nested list representing the expression and generates an appropriate function. While somewhat easy to understand, even this seems ugly for python.

import math

def f_of_x(op):
    if (isinstance((op[0]), (int, long, float, complex)) ):
        return (lambda x:op[0])
    elif op[0]=="pi": return lambda x: 3.14159265358979
    elif op[0]=="e": return lambda x: 2.718281828459
    elif op[0]=="x": return lambda x: x
    elif op[0]=="sin": return lambda x: math.sin(f_of_x(op[1])(x))
    elif op[0]=="cos": return lambda x: math.cos(f_of_x(op[1])(x))
    elif op[0]=="tan": return lambda x: math.tan(f_of_x(op[1])(x))
    elif op[0]=="sqrt": return lambda x: math.sqrt(f_of_x(op[1])(x))
    elif op[0]=="+": return lambda x: (f_of_x(op[1])(x))+(f_of_x(op[2])(x))
    elif op[0]=="-": return lambda x: (f_of_x(op[1])(x))-(f_of_x(op[2])(x))
    elif op[0]=="*": return lambda x: (f_of_x(op[1])(x))*(f_of_x(op[2])(x))
    elif op[0]=="/": return lambda x: (f_of_x(op[1])(x))/(f_of_x(op[2])(x))
    elif op[0]=="**": return lambda x: (f_of_x(op[1])(x))**(f_of_x(op[2])(x))
    # should never get here with well formed input
    return

def test():
    # test function f(x) = sin(pi*x)/(1+x**2)
    s = ['/',['sin',['*',['pi'],['x']]],['+',[1],['**',['x'],[2]]]]
    f = f_of_x(s)
    for x in range(30):
        print " "*int(f(x*0.2)*30+10)+"x"

As a general guideline, think of your solution as a tutorial on lambdas and parsers – not code golf. The sample code is just that, so write what you feel is clearest.

  • 1 1 Answer
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T20:43:15+00:00Added an answer on May 15, 2026 at 8:43 pm

    How about this:

    import math
    def f_of_x(op):
        return eval("lambda x:" + op, math.__dict__)
    

    It can easily be made to support [] as well as () and uses standard operator precedence. It does not let you use trig functions without parens, though, nor does it let you imply multiplication by juxtaposition (like 2x). The list of supported functions is easily extensible, however, and the code is probably as clear and easy to understand as you can get.

    If you absolutely need the extra features, look at http://christophe.delord.free.fr/tpg/. The example given on that page can be easily modified to do everything you want.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I want to count how many characters a certain string has in PHP, but
I am reading a book about Javascript and jQuery and using one of the
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I need a function that will clean a strings' special characters. I do NOT
I want to construct a data frame in an Rcpp function, but when I
I'm making a simple page using Google Maps API 3. My first. One marker

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.