Question

Hi can anyone help me with this question? Please use python when you do it. THANKS

1. Arithmetic trees 50 marks You are given an input file with multiple pairs of input lines. The first line of each pair is a

0 0
Add a comment Improve this question Transcribed image text
Answer #1
  • I have pasted the code and screenshot of successful run below.
  • The program accepts input file name as first command line argument:
    python a.py <filename>
  • In case of any doubts just comment down.
  • If you found it helpful please do upvote.

-------------------------Screenshot-----------------------

ksmukta:26.python - python a.py input.txt 5 6 ksmukta į 26-python->
-------------------------input.txt-----------------------

-1,0,0,0,1,1
+,*,2,3,0,7
2,0,-1,0
+,3,*,3

-------------------------Code-----------------------

import sys

file = open(sys.argv[1])
lines = file.readlines()

class Node():
   def __init__(self, data):
       self.data = data
       self.children = []

   def isLeaf(self):
       return len(self.children)==0

   def addChild(self, n):
       self.children.append(n)

   def getVal(self):
       if(self.isLeaf()):
           return self.data
       elif(self.data=='+'):
           sm = 0
           for child in self.children:
               sm += child.getVal()
           return sm
       elif(self.data=='*'):
           pd = 1
           for child in self.children:
               pd *= child.getVal()
           return pd

      

def tryInt(c):
   try:
       i = int(c)
       return i
   except:
       return c

for i in range(len(lines)/2):
   predecessor = [int(x) for x in lines[2*i].split(',')]
   nodevalue = [tryInt(x) for x in lines[2*i+1].split(',')]
   node = [Node(nodevalue[i]) for i in range(len(nodevalue))]
   root = None
   for i in range(len(predecessor)):
       if(predecessor[i]==-1): root=node[i]; continue
       pred = node[predecessor[i]]
       pred.addChild(node[i])
   print(root.getVal())
  

Add a comment
Know the answer?
Add Answer to:
Hi can anyone help me with this question? Please use python when you do it. THANKS...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please submit only Python source code. 1. Arithmetic trees 50 marks You are given an input file with multiple pairs of...

    Please submit only Python source code. 1. Arithmetic trees 50 marks You are given an input file with multiple pairs of input lines. The first line of each pair is a tree given as a predecessor array. The second line is the value at the corresponding node. Values at leaf nodes (nodes with no children) are integers. At non-leaf nodes, the two possible values are + or *. The tree represents an arithmetic expression where the value at a non-leaf...

  • plz use python to answer it, thanks in advance 3. Tree and back arcs in a DFS 40 Marks For a given set of digraphs, write a program that performs DFS on each digraph starting at node 0 and prints...

    plz use python to answer it, thanks in advance 3. Tree and back arcs in a DFS 40 Marks For a given set of digraphs, write a program that performs DFS on each digraph starting at node 0 and prints out the total number of tree arcs and back arcs resulting from the traversal. Use our standard convention that when there is a choice of white or grey nodes, the one with the lowest index should be chosen. Input format:...

  • Hierarchical structures: Write a java class to implement a Multi-way tree, with an appropriate constructor and...

    Hierarchical structures: Write a java class to implement a Multi-way tree, with an appropriate constructor and methods for the following:             Methods to find and insert on the tree.             Method to return the height of the tree. Methods to output the values from this tree in any one of the following ways:             Pre-order:        Left to right order of siblings             Post-order:      Right to left order of siblings             Level order:    Left to right order of siblings             Method to store the tree to a file per the...

  • This is programming assignment of discrete structure. Anyone know how to do it. Pls help! Thanks....

    This is programming assignment of discrete structure. Anyone know how to do it. Pls help! Thanks. Problem 1[50 pts]: Your program must take as input a filename. This input file has the following format. The first line contains five positive integers separated by white space characters. Call them a, b,c, m, n. The next m lines describe the pairs in a relation Ri on the set {1, 2, , a x(1, 2, b), and the n lines following it describe...

  • Sc Python 1 Task 2 3 Consider a binary tree of N vertices 4 such that children of node K are 2* K + 1. Vertex 1...

    Sc Python 1 Task 2 3 Consider a binary tree of N vertices 4 such that children of node K are 2* K + 1. Vertex 1 is the root Kand 2 of the tree and each node has an integer value associated with it. Such a tree may be represented as an array of N integers by writing down values from consecutive nodes For example, the tree below 8 Test might be represented as an array o A node...

  • Would appreciate the answer in the Java coding language please and thank you! 10d 10h left...

    Would appreciate the answer in the Java coding language please and thank you! 10d 10h left Java 7 1. Check the Structure Autocomplete Ready 1 > import java.io.*;... 10 ALL A binary tree uses a multi-node data structure where each node may have 0 to 2 child nodes, and has one stored value, its node number in this case. A tree may either be: 11 class Result { * Complete the 'isValid' function below. • An empty tree, the root...

  • C language huffman This exercise will familiarize you with linked lists, which you will need for...

    C language huffman This exercise will familiarize you with linked lists, which you will need for a subsequent programming Getting Started assignment Overview Requirements Getting Started Submit Start by getting the files. Type 264get hw13 and then cd hw13 from bash. Pre-tester You will get the following files: Q&A Updates 1. huffman.h: An empty header file, you have to define your own functions in this homework. 2. huffman.c: An empty c file, you have to define your own functions in...

  • Code to be written in C++: Initially, you will be given symbols printed in a preorder...

    Code to be written in C++: Initially, you will be given symbols printed in a preorder traversal of a boolean expression tree. The internal nodes of the tree will contain one of the following operators: & (and), | (or), ^ (exclusive-or), or ! (not). The nodes containing the first three operators will have two children, while the nodes containing the ! operator will contain only a left child. The leaves of the tree will contain an operand - either f...

  • Summary You will write an application to build a tree structure called Trie for a dictionary...

    Summary You will write an application to build a tree structure called Trie for a dictionary of English words, and use the Trie to generate completion lists for string searches. Trie Structure A Trie is a general tree, in that each node can have any number of children. It is used to store a dictionary (list) of words that can be searched on, in a manner that allows for efficient generation of completion lists. The word list is originally stored...

  • Homework 2 Description This homework will test the use of arrays and control structures. In summary,...

    Homework 2 Description This homework will test the use of arrays and control structures. In summary, you will read 10 integers from standard input, store them into an array and then produce some statistics. Details You need to compute Array Statistics. Create a class called Hwk2 that implements a main to solve your homework. At the beginning display a line with the following text: Type 10 integer values: Then, read 10 integers from standard input, one by one and store...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT