Answer to Question #332912 in Python for junior

Question #332912

Create a class in Python called Sorting which takes in a file name as an argument. An object of class Sorting will have methods called:

  •  Create a method called GetData which reads in the numbers found in the file and stores them in a list or array.
  •  Create a method called SortData which sorts the data collected by the GetData method in ascending order.

Hint: Use BubbleSort and take in the array or list from the GetData method as an argument.

  • Create a method called ReverseData which sorts the data contained in the file in descending order.

 Hint: You can use any method of reversing a list or array for this requirement. This can be done using slicing, by using the build in reversed() method, or by importing/using modules like array and NumPy. Keep in mind the last two methods require pip installs!

  •  Create a function called main which creates an object of class Sorting and calls the GetData, SortData, and ReverseData methods. Use __main__ to automatically call this main method at runtime.
1
Expert's answer
2022-04-24T07:03:29-0400



#define class Sorting
class Sorting:
  """class sorting wich sort numbers data"""
  def __init__(self,filename="input.txt"):
    self.__filename=filename#private member
    self.ls=list()
  def GetData(self):
    """Read data """
    fl=open(self.__filename,mode="r+")
    for line in fl:
      nm=list(map(int,line.split()))
      for _ in nm:
        self.ls.append(_)
  def SortData(self):
     n = len(self.ls)
     # Traverse through all array elements
     for i in range(n-1):
     # range(n) also work but outer loop will
     # repeat one time more than needed.
       for j in range(0, n-i-1):
            if self.ls[j] > self.ls[j + 1] :
                self.ls[j], self.ls[j + 1] = self.ls[j + 1], self.ls[j]
  def  ReverseData(self):
    self.ls=self.ls[::-1]
filename="data.txt"
sr=Sorting(filename)
sr.GetData()
print(sr.ls)
sr.SortData()
print(sr.ls)
sr.ReverseData()
print(sr.ls)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS