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

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.
This is using Python, it is utilizing code from a Fraction class to create a Binary...
This is using Python, it is utilizing code from a Fraction class to create a Binary Class Please leave comments so I may be able to learn from this. Instruction for Binary Class: Exercise 6.18: Design an immutable class BinaryNumber, in the style of our Fraction class. Internally, your only instance variable should be a text string that represents the binary value, of the form '1110100'. Implement a constructor that takes a string parameter that specifies the original binary value....
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.
Using Python to play Checkers: 1) Create classes to represent the necessary objects for game play....
Using Python to play Checkers: 1) Create classes to represent the necessary objects for game play. This will include, at least, the game board, the two types of pieces and the two sides. You will need to determine the best way to represent the relationship between them. 2) Set up one side of the board. Print the status of the board.
Please create a python module named homework.py and implement the classes and methods outlined below. Below...
Please create a python module named homework.py and implement the classes and methods outlined below. Below you will find an explanation for each class and method you need to implement. When you are done please upload the file homework.py to Grader Than. Please get started as soon as possible on this assignment. This assignment has many problems, it may take you longer than normal to complete this assignment. This assignment is supposed to represent a group of students in a...
In python using tkinter, I want to create a program. The program can have various classes...
In python using tkinter, I want to create a program. The program can have various classes and methods but I want it to have circles, triangles, and squares. Each shape movies in a certain way, like circles can move linearly, triangles can be affected by gravity, and squares can only go up and down. If the shapes get too close to one another then they disappear and a new shape appears somewhere else. I want this program to run continuously.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT