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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T14:14:26+00:00 2026-05-13T14:14:26+00:00

I know tree is a well studied structure. I’m writing a program that randomly

  • 0

I know tree is a well studied structure.

I’m writing a program that randomly generates many expression trees and then sorts and selects by a fitness attribute.

I have a class MakeTreeInOrder() that turns the tree into a string that ‘eval’ can evaluate.

but it gets called many many times, and should be optimized for time.

below is a function that builds a tree that adds successive numbers to use as a test.

I was wondering if there is an optimized way to evaluate an expression that is in a tree structure. I figured that

that it’s used quite a bit and somebodys already done this.

import itertools
from collections import namedtuple 

#Further developing Torsten Marek's second suggestion

KS = itertools.count()
Node = namedtuple("Node", ["cargo", "args"]) 

def build_nodes (depth = 5):     
    if (depth <= 0): 
        this_node = Node((str(KS.next())), [None, None])
        return this_node 
    else:
        this_node = Node('+', []) 
        this_node.args.extend( 
          build_nodes(depth = depth - (i + 1))                             
          for i in range(2)) 

        return this_node

The following is the code that I think can be made a lot faster. And I was hoping for some ideas.

class MakeTreeInOrder(object):
    def __init__(self, node):
        object.__init__(self)
        self.node = node
        self.str = ''
    def makeit(self, nnode = ''):
        if nnode == '':
            nnode = self.node
        if nnode == None: return
        self.str +='('
        self.makeit(nnode.args[0])
        self.str += nnode.cargo
        self.makeit(nnode.args[1])
        self.str+=')'
        return self.str

def Main():
    this_tree = build_nodes()
    expression_generator = MakeTreeInOrder(this_tree)
    this_expression = expression_generator.makeit()
    print this_expression
    print eval(this_expression)

if __name__ == '__main__':
    rresult = Main()
  • 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-05-13T14:14:27+00:00Added an answer on May 13, 2026 at 2:14 pm

    Adding a touch of object orientation here makes things simpler. Have subclasses of Node for each thing in your tree, and use an ‘eval’ method to evaluate them.

    import random
    
    class ArithmeticOperatorNode(object):
        def __init__(self, operator, *args):
            self.operator = operator
            self.children = args
        def eval(self):
            if self.operator == '+':
                return sum(x.eval() for x in self.children)
            assert False, 'Unknown arithmetic operator ' + self.operator
        def __str__(self):
            return '(%s)' % (' ' + self.operator + ' ').join(str(x) for x in self.children)
    
    class ConstantNode(object):
        def __init__(self, constant):
            self.constant = constant
        def eval(self):
            return self.constant
        def __str__(self):
            return str(self.constant)
    
    def build_tree(n):
        if n == 0:
            return ConstantNode(random.randrange(100))
        else:
            left = build_tree(n - 1)
            right = build_tree(n - 1)
            return ArithmeticOperatorNode('+', left, right)
    
    node = build_tree(5)
    print node
    print node.eval()
    

    To evaluate the tree, just call .eval() on the top level node.

    node = build_tree(5)
    print node.eval()
    

    I also added a __str__ method to convert the tree to a string so you can see how this generalizes to other tree functions. It just does ‘+’ at the moment, but hopefully it’s clear how to extend this to the full range of arithmetic operations.

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

Sidebar

Ask A Question

Stats

  • Questions 377k
  • Answers 377k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I got the reason why there was an error. It… May 14, 2026 at 8:48 pm
  • Editorial Team
    Editorial Team added an answer You can do this by adding a simple loop after… May 14, 2026 at 8:48 pm
  • Editorial Team
    Editorial Team added an answer There's only one way -- to use less continuations. This… May 14, 2026 at 8:48 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.