Cookie Consent by Privacy Policies

Re-Learning Data Structures and Algorithms Series ๐Ÿง‘๐Ÿพโ€๐Ÿ’ป: Python 3 + Classes

Re-Learning Data Structures and Algorithms Series ๐Ÿง‘๐Ÿพโ€๐Ÿ’ป: Python 3 + Classes
Photo by Hitesh Choudhary on Unsplash
If you have not read the first blog on the why, how, and hope of this series, check out the first ๐Ÿ‘‰๐Ÿพ here.

Python 2 vs Python 3 ๐Ÿ: Which one?!?!

I think the biggest reason why I have chosen Python 3 over Python 2 is that starting this year, there will be no maintaining of Python 2 and almost no more bug fixes (see more here on Pythonโ€™s official documentation). Thus, Iโ€™ve decided to go ahead and code in Python 3 for the remainder of this series. Now, with that comes an interesting question: whatโ€™s changed between versions? What Iโ€™ve seen on the internet and many of blog posts, itโ€™s a few things that come to mind:

# Python 2 verison of print
>>> print "Hello World"
Hello World

# Python 3 version of print - print is now a function
>>> print("Hello World")
Hello World
print statements in Python3
#Python 2 - range([start - optional], stop, [step - optional]) vs. xrange([start - optional], stop, [step - optional])
#range gives you a python list of values that you can iterate through immediately
>>> a = range(1,100)
>>> print "%s" % a
[0,1,2,3,....99]
#xrange gives you back an object that evaluates lazily ๐Ÿ‘‰๐Ÿพ (as you need it/on-demand) - good for memory
>>> b = xrange(1,100)
>>> print(b)
xrange(1,100)
>>> for i in b:
>>>   print "%d" % i
[0,1,2,3,....99]


#Python 3 - there is no more xrange! Just 1 range to rule them all (range in Python 3 includes xrange)
>>> c = range(1,100)
>>> print(c)
range(1,100)
# if you want to make a list out of the range object
>>> new_c = list(c)
>>> print(new_c)
[0,1,2,3,....99]
range vs xrange in Python -> see more explanation at this stack Overflow post ๐Ÿ‘‰๐Ÿพ https://bit.ly/2SPX4c5
#Python 2 - watch out for values that evaluate to float data types!
>>> num1 = 1/2
>>> print "num"
0

#Python 3 - you'll get a float value
>>> num2 = 1/2
>>> print(num2)
0.5
float handling in Python3

While this is not at all an exhaustive list, I hope this gives an idea of somethings that have changed from Python 2 to Python 3. Ultimately, if you are working on a legacy system of some sort, you might have to switch to Python 2 so the best case scenario is to be comfortable with both versions ๐Ÿ˜ƒ.


Whatโ€™s a Class?

Seeing as the blog posts will focus on the understanding and implementation of data structures and algorithms, I think itโ€™s important to explain a fundamental part of any object-oriented programming language, and thatโ€™s classes. Rather than give you a definition first, it may be easier to think about a picture. Letโ€™s think about your standard calculator.

Photo by StellrWeb on Unsplash

A calculator has many different functions that a person has access to. A person can come to the calculator with their given numbers and add, subtract, multiply, divide and (depending on if itโ€™s a fancy calculator) also plot graphs, utilize charts, and much more. A class in python is no different than a calculator. You can think of a class as an interface with defined functionality and attributes (the calculatorโ€™s job is not to tell you the weather ๐Ÿ‘‰๐Ÿพ itโ€™s to crunch numbers) to be accessed through an object (your finger would be the object, in this case, accessing the functionality of the calculator, providing the input in numbers and operations and the calculator gives you the desired output). This can take you down a rabbit hole of examples when you think it through (a car can be considered a class, the remote you use for you tv can be considered a class, the possibilities and internet are endless with examples ๐Ÿ˜‚). Weโ€™ll choose to stay above ground and see what this simple example looks like in code ๐Ÿ˜ƒ


Building a Calculator From Scratch

class Calculator:
  
  def __init__(self, num1, num2):
    self.num1 = num1
    self.num2 = num2
    
Consider this like the laying of groundwork for the Class

The def __init__ is considered to initialize the classยน. Most, if not all classes have this at the top of the class file. You might be wondering about the self in the argument list. This took me a while to figure out when first learning object-oriented programming but in a nutshell, the self is โ€œused to refer to the object being created at the momentโ€ of initializationยน. Num1 and Num2 are both considered as attributes and more so represent how you can extend your class (you donโ€™t have to use the same two numbers every single time you use your calculator).

def add(self, n1, n2):
  return (n1 + n2)

def subtract(self, n1, n2):
  return (n1 - n2)

def multiply(self, n1, n2):
  return (n1 * n2)

#remember in Python3 from above, you'll get out floats if you pass two integers
def divide(self, n1, n2):
  return (n1/n2)
Rest of the functionality of the Calculator class

The add, subtract, multiply, and divide functions above would be considered the actual โ€œbuttonsโ€ that a user of the calculator would physically press for the desired usage. These functions work in the exact same way! Once you create your object, you can then access the class functions via the object as you can see below ๐Ÿ‘‡๐Ÿพ

class Calculator:
  
  def __init__(self, num1, num2):
    self.num1 = num1
    self.num2 = num2
    
 def add(self):
    return (self.num1 + self.num2)

 def subtract(self):
    return (self.num1 - self.num2)

 def multiply(self):
    return (self.num1 * self.num2)
  
 def divide(self):
    return (self.num1/self.num2)
Final Calculator.py file you would save
# assuming you have saved the above code to a .py file in the same directory of launching python interpreter or ipython 
  
>>> cal_object1 = Calculator(4,5)
#cal_object1 is now the object that you will use to access the functions/methods in the Calculator class
>>> cal_object1.add()
9
>>> cal_object1.multiply()
20
>>> cal_object1.subtract()
-1
>>> cal_object1.divide()
0.8
>>> cal_object1.num1
4
>>> cal_object1.num2
5

# The flexible part about creating a class is assigning different attributes (or in our case numbers)
# all you have to do is create a new object! 
>>> cal_object2 = Calculator(10,20)
>>> cal_object2.add()
30
Object creation using Calculator.py

You Did It!

via GIPHY

If this example makes sense and you are solid on the information, you did it! Pat yourself on the back ๐Ÿ˜ƒ. Being comfortable with classes moving through the series is very important as the data structures and algorithms that we will be invoking are not native to Python (or really any other language), therefore they will need to be built before implemented.

Seeing as the only way to get better is through practice, I will be posting some programming problems sometime next week via online flashcards that I will share publicly so you can practice your programming anywhere.

Until next time! ๐Ÿ‘‹๐Ÿพ Tweet me your thoughts! ๐Ÿ˜ƒ


References:
[1] Shovic, John C, and Alan Simpson. โ€œDoing Python with Class.โ€ Python All-In-One For Dummies, John Wiley & Sons, Inc., 2019, pp. 213โ€“220.
Show Comments