Question

In: Computer Science

PYTHON-- trying to teach myself how to create new classes. The Bird class will read a...

PYTHON-- trying to teach myself how to create new classes. The Bird class will read a file that has a list of species and will write to another file with the species and # of occurrences . use __lt__ to compare species and use #comments to explain the def methods in the class

example of input file:

blackbird

canary

hummingbird

canary

hummingbird

canary

output file:

 Blackbird,1
 Hummingbird,2
 Canary,3
class Birds:
    
    #do i need count in init?
    def __init__(self, species, count):
        self.species = species
        self.count = int(count)


    
    def __str__(self):
        return f" {self.species}, {self.count}"

    
    def __repr__(self):
       

    
    def __eq__(self, other):
        

    
    def __lt__(self, other):
        return self.species < other.species


word_freq = []
with open('bird_observations_small.txt', 'r') as input_file:
    for line in input_file:
        data = line.strip().split(',')
        x = Birds(data[0], data[1])
        if x not in word_freq:
            word_freq.append(x)
            

with open('sorted_species.csv', 'w') as output_file:
    for i in word_freq:
        output_file.write(f"{i.species},{i.count}\n")

Solutions

Expert Solution

class Birds:
    count = 0  #intial bird count is 0
    def __init__(self, species):
        self.species = species #initialize it with a string that is the bird name
    
    def __count__(self):
        self.count = self.count + 1         #increaces 1 everytime it gets called

    def __compare__(self, other):
        if self.species == other: #compares self.name with the string passed to it
            return True
        else:
            return False
    def getSpeciesName(self): #getname
        return self.species

    def getCount(self):   #getcount
        return self.count



blackbird = Birds("blackbird") #objects created
canary = Birds("canary")
hummingbird = Birds("hummingbird")

#you can use an array of bird to make things simple and robust

with open('test', 'r') as input_file: #comparision
    for line in input_file:
        line = line.strip() 
        if blackbird.__compare__(line):
            blackbird.__count__()
        if canary.__compare__(line):
            canary.__count__()
        if hummingbird.__compare__(line):
            hummingbird.__count__()
            

with open('out', 'w') as output_file:
    output_file.write(f"{blackbird.getSpeciesName()},{blackbird.getCount()}\n")
    output_file.write(f"{canary.getSpeciesName()},{canary.getCount()}\n")
    output_file.write(f"{hummingbird.getSpeciesName()},{hummingbird.getCount()}\n")

Related Solutions

In Python, create a program with 2 classes that do the following. HashCreate class, this class...
In Python, create a program with 2 classes that do the following. HashCreate class, this class will accept a directory and hash each file in the directory and store the results in a dictionary. The dictionary will contain the hash value and file name. HashVerify, the second class will accept the dictionary as input and save that in an instance attribute. This class must also contain a method for lookups that require a file path as input. The lookup method...
If the class Parrot extends the class Bird, what can't be said about the classes? Select...
If the class Parrot extends the class Bird, what can't be said about the classes? Select one answer: A. The Parrot class has access to the Parrot methods B. The Parrot class has access to the Bird methods C. The Bird class has access to the Bird methods D. The Bird class has access to the Parrot methods
Objectives: Use class inheritance to create new classes. Separate class definition and implementation in different files....
Objectives: Use class inheritance to create new classes. Separate class definition and implementation in different files. Use include guard in class header files to avoid multiple inclusion of a header. Tasks: In our lecture, we wrote a program that defines and implements a class Rectangle. The source code can be found on Blackboard > Course Content > Classes and Objects > Demo Program 2: class Rectangle in three files. In this lab, we will use class inheritance to write a...
Write two classes Class A and Class B in class A you should read from the...
Write two classes Class A and Class B in class A you should read from the keyboard a number and you should call a public method of the class B that will print on the screen whether the number that was read from the keyboard in class A is multiple of 7 and has the last digit 5.
Classes and Objects Write a program that will create two classes; Services and Supplies. Class Services...
Classes and Objects Write a program that will create two classes; Services and Supplies. Class Services should have two private attributes numberOfHours and ratePerHour of type float. Class Supplies should also have two private attributes numberOfItems and pricePerItem of type float. For each class, provide its getter and setter functions, and a constructor that will take the two of its private attributes. Create method calculateSales() for each class that will calculate the cost accrued. For example, the cost accrued for...
Create a new project in BlueJ. Create two new classes in the project, with the following...
Create a new project in BlueJ. Create two new classes in the project, with the following specifications: Class name: Part Fields: id (int) description (String) price (double) onSale (boolean) 1 Constructor: takes parameters partId, partDescrip, and partPrice to initialize fields id, description, and price; sets onSale field to false. Methods: Write get-methods (getters) for all four fields. The getters should be named getId, getDescription, getPrice, and isOnSale.
// **************************************************************** // Incrementarray.java // // Define a IncrementMatrix class with methods to create and read...
// **************************************************************** // Incrementarray.java // // Define a IncrementMatrix class with methods to create and read in // info for a matrix and to check whether the matrix (2d array) is increment, // in other words, all elements in each row are in increasing order and // all elements in each column are in increasing order. // **************************************************************** import java.util.Scanner; public class IncrementMatrix { int[][] matrix; //-------------------------------------- //create new array of given size //-------------------------------------- public IncrementMatrix(int row, int col) {...
In python- Create a class defined for Regression. Class attributes are data points for x, y,...
In python- Create a class defined for Regression. Class attributes are data points for x, y, the slope and the intercept for the regression line. Define an instance method to find the regression line parameters (slope and intercept). Plot all data points on the graph. Plot the regression line on the same plot.
C++ HW Aim of the assignment is to write classes. Create a class called Student. This...
C++ HW Aim of the assignment is to write classes. Create a class called Student. This class should contain information of a single student. last name, first name, credits, gpa, date of birth, matriculation date, ** you need accessor and mutator functions. You need a constructor that initializes a student by accepting all parameters. You need a default constructor that initializes everything to default values. write the entire program.
Create a preorder iterator for the class binarytree from the Python program below. class Binarytree: def...
Create a preorder iterator for the class binarytree from the Python program below. class Binarytree: def __init__(self, DataObject): self.data = DataObject self.parents = None self.left_child = None self.right_child = None @property def left_child(self): return self.__left_child @left_child.setter def left_child(self, node): self.__left_child = node if node is not None: node.parents = self @property def right_child(self): return self.__right_child @right_child.setter def right_child(self, node): self.__right_child = node if node is not None: node.parents = self def is_leafNode(self): if self.left_child is None and self.right_child is None:...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT