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 8101123
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T22:54:33+00:00 2026-06-05T22:54:33+00:00

Given a string such as 2*(i+j) <= 100 I want to generate the corresponding

  • 0

Given a string such as

"2*(i+j) <= 100"

I want to generate the corresponding lambda function,

fn = lambda i,j: 2*(i+j) <= 100
  • I can do this with eval, but I am seeking a less evil method.

  • I have found

    import ast
    f = ast.Lambda('i,j', '2*(i+j) <= 100')
    

    but I haven’t figure out how to execute the result!

  • Ideally, I would like to automatically pull out the parameter list (‘i’,’j’) as well – right now, I am just using re.findall(‘\w+’), but I would love to be able to properly use existing functions like cos instead of shadowing them as ‘keywords’.


I was looking at Is there a Python library for handling complicated mathematical sets (constructed using mathematical set-builder notation)? and trying to figure out how best to parse the set-builder notation into the lambdas to feed to the constraint-solver.

I’m basically wishing for ast.literal_eval which would also recognize variables.

Ideally, given i >= 20 I would like to get back ((lambda x: x >= 20), ['i']) which I could then feed directly to constraint.

  • 1 1 Answer
  • 0 Views
  • 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-06-05T22:54:34+00:00Added an answer on June 5, 2026 at 10:54 pm

    If your input is from a trusted source, the eval() is the easiest, clearest, and most reliable way to go.

    If your input is untrusted, then it needs to be sanitized.

    One reasonable approach is the use of a regex. Make sure there are no function calls, attribute lookups, or double underscores in the string.

    Alternatively, a more sophisticated approach is to walk the AST parse tree to determine whether there are any objectionable calls.

    A third approach is to walk the AST parse tree and execute it directly. That puts you in complete control over what gets calls. The ast.literal_eval function takes this approach. Perhaps you start with its source and do some buildouts for any operations you want to support:

    def literal_eval(node_or_string):
        """
        Safely evaluate an expression node or a string containing a Python
        expression.  The string or node provided may only consist of the following
        Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
        and None.
        """
        _safe_names = {'None': None, 'True': True, 'False': False}
        if isinstance(node_or_string, basestring):
            node_or_string = parse(node_or_string, mode='eval')
        if isinstance(node_or_string, Expression):
            node_or_string = node_or_string.body
        def _convert(node):
            if isinstance(node, Str):
                return node.s
            elif isinstance(node, Num):
                return node.n
            elif isinstance(node, Tuple):
                return tuple(map(_convert, node.elts))
            elif isinstance(node, List):
                return list(map(_convert, node.elts))
            elif isinstance(node, Dict):
                return dict((_convert(k), _convert(v)) for k, v
                            in zip(node.keys, node.values))
            elif isinstance(node, Name):
                if node.id in _safe_names:
                    return _safe_names[node.id]
            elif isinstance(node, BinOp) and \
                 isinstance(node.op, (Add, Sub)) and \
                 isinstance(node.right, Num) and \
                 isinstance(node.right.n, complex) and \
                 isinstance(node.left, Num) and \
                 isinstance(node.left.n, (int, long, float)):
                left = node.left.n
                right = node.right.n
                if isinstance(node.op, Add):
                    return left + right
                else:
                    return left - right
            raise ValueError('malformed string')
        return _convert(node_or_string)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Given a string such as: a:2:{i:0;s:1:1;i:1;s:1:2;} I want to find every integer within quotes
Given a string such as: new/path - path/path/03 - filename.ext, how can I use
Given a string such as abc-def-ghi-jkl . Can the sed command extract the substring
Using PHP, given a string such as: this is a <strong>string</strong> ; I need
Given a string such as this: Bob Smith <bobsmith@gmail.com>, Jones, Rich A. <richjones@gmail.com> I
Given a string, how do I generate a .txt file containing such string?
Given a font CSS string such as this: font:italic bold 12px/30px Georgia, serif; or
Given an input string (such as D4C3B2A1) I want to sort the alphabet characters,
Possible Duplicate: In PHP given a month string such as “November” how can I
Given a string such as 8584320342564023450211233923239923239110001012346596 , how can get all consecutive 4 digit

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.