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:
Hint: Use BubbleSort and take in the array or list from the GetData method as an argument.
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!
#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)
Comments
Leave a comment