Question

Complete the function load_trees_from_file() specified in A1.py It should take as a parameter the name of...

Complete the function load_trees_from_file() specified in A1.py

It should take as a parameter the name of a file containing a set of trees and return a list containing instances of the Tree class representing all of the trees listed in the file. If the file does not exist, it should print that the file is not found and return None.

You will need to include your Tree class definition from Question 1 in your answer.

Consider the following code fragment:

trees = load_trees_from_file('Trees.txt')
[print(t) for t in trees]

If the file Trees.txt contains the following lines:

Ash,10,150,75,0,0,255,0,30
Oak,12,130,70,0,0,200,0,45

The output will be:

Ash
Oak

class Tree:

class Tree:
def __init__(self,name,length,color_b,color_l,angle): # defining init method
self.name = name
self.length = length
self.color_b = color_b
self.color_l = color_l
self.angle = angle
  
def __str__(self): # defining str method
return self.name
  
def __repr__(self): # defining repr method
return 'Tree("{}", {}, {}, {}, {})'.format(self.name,self.length,self.color_b,self.color_l,self.angle)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

Note: Please maintain proper code spacing (indentation), just copy the code part and paste it in your compiler/IDE directly, no modifications required.

#code

class Tree:
    def __init__(self, name, length, color_b, color_l, angle):  # defining init method
        self.name = name
        self.length = length
        self.color_b = color_b
        self.color_l = color_l
        self.angle = angle

    def __str__(self):  # defining str method
        return self.name

    def __repr__(self):  # defining repr method
        return 'Tree("{}", {}, {}, {}, {})'.format(self.name, self.length, self.color_b, self.color_l, self.angle)



#required method
def load_trees_from_file(filename):
    #opening file inside a try-except block
    try:
        file=open(filename,'r') #opening file in read mode
        #creating an empty list
        trees=[]
        #looping through each line
        for line in file:
            #stripping blanks/newlines from either ends and splitting line by ','
            fields=line.strip().split(',')
            #checking if resultant list's length is 9
            if len(fields)==9:
                #taking first value as name
                name=fields[0]
                #parsing second value as integer for length
                length=int(fields[1])
                #creating a 2 element tuple using the next three values as integers for
                #representing r,g,b values for color_b (assuming that is how you store color in Tree class)
                color_b=(int(fields[2]),int(fields[3]),int(fields[4]))
                #doing the same with next three values for color_l
                color_l = (int(fields[5]), int(fields[6]), int(fields[7]))
                #fetching next value as integer angle
                angle=int(fields[8])
                #creating a Tree with these values, adding to the list
                t=Tree(name,length,color_b,color_l,angle)
                trees.append(t)
        #closing file
        file.close()
        #returning list
        return trees
    except:
        #file not found, displaying error and returning None
        print('file is not found')
        return None


Add a comment
Know the answer?
Add Answer to:
Complete the function load_trees_from_file() specified in A1.py It should take as a parameter the name of...
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
  • PYTHON: Conan is writing a module to contain different implementations of trees. After his first tree,...

    PYTHON: Conan is writing a module to contain different implementations of trees. After his first tree, the BinaryTreeclass, he wrote test code and is having problems understanding the error. Locate his problem and explain how you would fix it. class Node(object): def __init__(self, data=None): self.data = data def __str__(self): return "NODE: " + str(self.data)    class Tree(object): def __init__(self): self.root_node = None self.size = 0    def __len__(self): return self.size    def add(self, data): raise NotImplementedError("Add method not implemented.")    def inorder_traversal(self): raise NotImplementedError("inorder_traversal...

  • Page 3 of 7 (Python) For each substring in the input string t that matches the...

    Page 3 of 7 (Python) For each substring in the input string t that matches the regular expression r, the method call re. aub (r, o, t) substitutes the matching substring with the string a. Wwhat is the output? import re print (re.aub (r"l+\d+ " , "$, "be+345jk3726-45+9xyz")) a. "be$jk3726-455xyz" c. "bejkxyz" 9. b. "be$jks-$$xyz" d. $$$" A object a- A (2) 10. (Python) What is the output? # Source code file: A.py class A init (self, the x): self.x-...

  • I am stuck on how to increase and decrease the population of il in the below...

    I am stuck on how to increase and decrease the population of il in the below question using Python 3: import logging class State: """A class representing a US state.""" def __init__(self, name, postalCode, population): self.name = name self.postalCode = postalCode self.population = population def __str__(self): """Readable version of the State object""" return 'Name: ' + self.name + ", Population (in MM): " + str(self.population) + ", PostalCode: " + self.postalCode def increase_population(self, numPeople): """Increases the population of the state."""...

  • QUESTION 31 The tkinter command _____ kicks off the GUI event loop. goloop() doloop() mainloop() loopDloop()...

    QUESTION 31 The tkinter command _____ kicks off the GUI event loop. goloop() doloop() mainloop() loopDloop() 2.5 points    QUESTION 32 Which of the following statements about superclasses and subclasses is true? A subclass is not connected to a super class in any way A superclass inherits from a subclass. A superclass extends a subclass. A subclass extends a superclass. 2.5 points    QUESTION 33 Pickled objects can be loaded into a program from a file using the function ____....

  • 9p This is for Python I need help. Pet #pet.py mName mAge class Pet: + __init__(name,...

    9p This is for Python I need help. Pet #pet.py mName mAge class Pet: + __init__(name, age) + getName + getAge0 def init (self, name, age): self.mName = name self.mAge = age Dog Cat def getName(self): return self.mName mSize mColor + __init__(name, age,size) + getSize() + momCommento + getDog Years() +_init__(name, age,color) + getColor + pretty Factor + getCatYears def getAge(self): return self.mAge #dog.py import pet #cat.py import pet class Dog (pet. Pet): class Cat (pet. Pet): def init (self,...

  • Use your Food class, utilities code, and sample data from Lab 1 to complete the following...

    Use your Food class, utilities code, and sample data from Lab 1 to complete the following Tasks. def average_calories(foods):     """     -------------------------------------------------------     Determines the average calories in a list of foods.     foods is unchanged.     Use: avg = average_calories(foods)     -------------------------------------------------------     Parameters:         foods - a list of Food objects (list of Food)     Returns:         avg - average calories in all Food objects of foods (int)     -------------------------------------------------------     """ your code here is the...

  • Type up the GeometricObject class (code given on the back of the paper). Name this file Geometric...

    Python only please, thanks in advance. Type up the GeometricObject class (code given on the back of the paper). Name this file GeometricObjectClass and store it in the folder you made (xxlab14) 1. Design a class named Rectangle as a subclass of the GeometricObject class. Name the file RectangleClass and place it in the folder. 2. The Rectangle class contains Two float data fields named length and width A constructor that creates a rectangle with the specified fields with default...

  • Using the following code: store.py from abc import ABC,abstractmethod class Store(ABC): #creating a abstract class name=''...

    Using the following code: store.py from abc import ABC,abstractmethod class Store(ABC): #creating a abstract class name='' #declaring attributes in class address='' status='' sales_tax_percentage=0.0 def __init__(self,name,address,status,sales_tax_percentage): #init method to initialize the class attributes self.name=name self.address=address self.status=status self.sales_tax_percentage=sales_tax_percentage def get_name(self): #Getter and setter methods for variables return self.name def set_name(self,name): self.name=name def get_address(self): return self.address def set_address(self,address): self.address=address def set_status(self,status): self.status=status def get_status(self): return self.status def set_sales_tax_percentage(self,sales_tax_percentage): self.sales_tax_percentage=sales_tax_percentage def get_sales_tax_percentage(self): return self.sales_tax_percentage def is_store_open(self): #check store status or availability if self.status=="open": #Return...

  • PYTHON The provided code in the ATM program is incomplete. Complete the run method of the...

    PYTHON The provided code in the ATM program is incomplete. Complete the run method of the ATM class. The program should display a message that the police will be called after a user has had three successive failures. The program should also shut down the bank when this happens. [comment]: <> (The ATM program allows a user an indefinite number of attempts to log in. Fix the program so that it displays a message that the police will be called...

  • 1. Code a breadth First traversal. 2. Code a depth First traversal. Note, your traversals should return a string listing...

    1. Code a breadth First traversal. 2. Code a depth First traversal. Note, your traversals should return a string listing the nodes added to the min spanning tree and the order they are added. Using Python. Starter code: from collections import deque class Edge: def __init__(self, endIndex, next = None): self.endIndex = endIndex self.next = next class Node: def __init__(self, name): self.name = name self.visited = False self.connects = None class Graph: def __init__(self): self.nodeList = [] self.size = 20...

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