I'm trying to make my own bubble-sort algorithm for learning purposes. I'm doing it by:
- Making a random array
- Checking if the first two indexes of the array need to be swapped
- it does this throughout the whole list
- and does it over and over until when looping through until the end it doesn't need to swap anything anymore then the loop breaks
but when I print any variable in the class it says that the class has no attribute of the variable. this is my code right now
from random import randint
class bubbleSort:
def __init__(self, size):
self.size = size # Array size
self.array = [] # Random array
self.sorted = self.array # Sorted array
self.random = 0 # Random number
self.count = 0
self.done = False
self.equal = 0
while self.count != self.size:
random = randint(1, self.size)
if random in self.array:
pass
else:
self.array.append(random)
self.count = 1
def sort(self):
while self.done != True:
self.equal = False
for i in range(self.size):
if i == self.size:
pass
else:
if self.sorted[i] > [self.tmp]:
self.equal = 1
if self.equal == self.size:
self.done = True
else:
self.sorted[i], self.sorted[i 1] = self.sorted[i 1], self.sorted[i]
new = bubbleSort(10)
print(bubbleSort.array)
This is what outputs
Traceback (most recent call last):
File "/home/musab/Documents/Sorting Algorithms/Bubble sort.py", line 38, in <module>
print(bubbleSort.array)
AttributeError: type object 'bubbleSort' has no attribute 'array'
CodePudding user response:
In your case, you have a class called bubbleSort
and an instance of this class called new
, which you create using new = bubbleSort(10)
.
Since bubbleSort
only refers to the class itself, it has no knowledge of member fields of any particular instance (the fields you create using self.xyz = abc
inside of the class functions. And this is good, imagine having two instances
b1 = bubbleSort(10)
b2 = bubbleSort(20)
and you want to access the array of b1
, you need to specify this somehow. The way to do it is to call b1.array
.
Therefore, in your case you need to print(new.array)
.
CodePudding user response:
bubbleSort
is a class type, each object of this class type has its own array
. To access array
, one must do it through a class object. __init__
is called when creating a class object.
give the following a try:
bubbleSortObj = bubbleSort(10) # create a bubbleSort object
print(bubbleSortObj.array) # print the array before sort
bubbleSortObj.sort() # sort the array
print(bubbleSortObj.array) # print the array after sort
Notes
- In
__init__
you've got:
self.array = [] # Random array
self.sorted = self.array # Sorted array
In this case, array
and sorted
point to the same list and changing one would change the other. To make a copy of a list, one approach (among many) is to call sorted = list(array)
- If there are any local function variables you can remove the
self
, eg,self.count = 0
can just becount = 0
, as it's not needed again once it's used, and doesn't need to be a class member