Table of Contents- Procedural Programming - Function-level comments can be extracted
- Procedural Programming: Facing (towards) --> Process (flow/steps) --> Programming (writing code)
- IPO
- Programming
- Object-Oriented Programming
- Classes and Objects
- Customizing Object Properties
- LeetCode Testing Mechanism
- Classes and Data Types
Procedural Programming
Function-level comments can be extracted
def f1():
"""Comment for f1"""
pass
print(f1.__doc__) # Extract the comment inside the function
Procedural Programming: Facing (towards) --> Process (flow/processing) --> Programming (writing code)
IPO
Input (input) --> Process (process/processing) --> Output (output) # Main flow
Plastic (define variables) --> Melt --> Pour in to a mold --> Bottle (output a result)
Similar to a production line in a workshop --> Object-oriented programming
The goal of writing code in the future: input some variables, then process them through a series of steps to get the desired result.
def compare2(x,y):
if x > y:
return x
else:
return y
x = input()
y = input()
res = compare2(x,y)
print(res)
Procedural programming: step by step (one function at a time), where the output of one function is the input of the next.
Programming: controlling variable changes
How to find bugs
x = 10
y = 20
# Flow 1
# Print after each variable change
# Multiple ways to implement a flow --> no single solution exists
# Flow 2
res = 50 # Actual result should be 40
Debugging sources
x = 10
# Flow
print('Step 1', x)
x *= 10
x *= 0
print(1/x)
print('Step 2', x)
# Flow
print('Step 3', x)
x += 2
print('Step 4', x)
- Locate the bug, it may not be on the exact line, trace back from that line.
- Print variable states to check if the flow has issues.
Object-Oriented Programming
# Object-oriented programming (writing code) --> A monkey king is an object, a pig boy is another object
# Journey to the West: Four monks --> Monkey King (72 transformations, golden staff)/Sha Wujing (36 transformations, iron rake)/Pig Boy/Tang Sanzang
# One horse --> White Dragon
# Create a game: Journey to the West()
# 1. Monkey King
# 2. Sha Wujing
# 3. Pig Boy
# 4. Tang Sanzang
# This method builds a game --> interaction between objects
# Advantages: Changes in one object do not affect others
# Disadvantages: Complex
# Object-oriented programming: interaction between objects
Classes and Objects
# Object: a combination of properties (features) and methods (skills)
'''
Nick object:
Name: Nick
Height: 180
Weight: 140
Age: 18
Skills:
Attending class
Student class:
Name
Height
Weight
Age
Skills:
Selecting courses
Teacher class:
Name
Height
Weight
Age
Skills:
Teaching
'''
# Class: a template/category that defines objects with similar properties and skills
# 1000 objects, less than 1000 classes
# In real life, objects come before classes, but in Python, classes are defined first
# Define class
class Student():
def __init__(self,name,height,weight,age):
self.name = name
self.height = height
self.weight = weight
self.age = age
def choose_course(self):
print(f'{self.name} is selecting courses')
# Define object
yutong = Student('Yutong',150,170,16)
print(yutong.name)
print(yutong.height)
print(yutong.weight)
print(yutong.age)
yutong.choose_course()
# If the object belongs to this class, it will have all the attributes and methods of the class
Customizing Object Properties
# class Student():
# school = 'q34y'
# name = 'd12'
# height = 1
# weight = 1000
# def choose_course(self): #self instance of the object
# print('Selecting courses')
# stu1 = Student()
# print(stu1.name)
# stu2 = Student()
# print(stu2.name)
#
# def init(obj,name,height,weight):
# obj.name = name
# obj.height = height
# obj.weight = weight
# stu3 = Student()
# init(stu3,'cql',172,120)
# print(stu3.name)
# print(stu3.height)
# print(stu3.weight)
class Student():
school = 'oldboy'
def __init__(self,name,weight,height): # Initialize unique properties of the class
self.name = name
self.weight = weight
self.height = height
print(self)
stu4 = Student('lyz',6,20) # Number of properties defined in the class must match the number of parameters passed during object creation
print('stu4:',stu4)
print(stu4.__dict__) # Get all properties of the object as a dictionary
print(stu4.name)
print(stu4.weight)
print(stu4.height)
stu5 = Student('lcy',54,130)
print('stu5:',stu5)
print(stu5.__dict__)
print(stu5.name)
print(stu5.weight)
print(stu5.height)
# The class function is called when the object is instantiated
LeetCode Testing Mechanism
class Solution:
def twoSum(self, nums: list, target: int) -> list:
for i in range(len(nums), -1, -1): # for i in range(4) == for i in [0,1,2,3]:
for j in range(i + 1, len(nums)): # [1,2,3]
if nums[i] + nums[j] == target:
return [i, j]
nums = [2, 7, 11, 15]
target = 9
result = [0,1]
def main(nums,target,result):
s = Solution()
res = s.twoSum(nums,target)
if res == result:
print('Pass')
else:
print('Fail')
main(nums,target,result)
Classes and Data Types
# lt = list([2,3,1])
# lt.sort()
# print(lt)
# class List:
# def __init__(self,lis):
# print(self)
# self = lis
# print(self)
# pass
# lt = List([2,3,1])
# print(lt)
class List:
def __init__(self,lis):
self.lis = lis
def sort_list(self): #self == lt
self.lis.sort()
lt =List([2,3,1,456,231,789])
print(lt.lis)
lt.sort_list()
print(lt.lis)
# In Python, everything (data types) is an object, and everything is a data type
# dic1 = dict()
# dic2 = dict()
x = int(10)
y = float(10.1)
def func():
pass
print(func)
#1. As an object
#1. Reference x = 10; y = x
#2. As an element in a container list = [x,func,Student]
#3. As a function parameter def func(x, func, Student)
#4. As a function return value, return x, func, Student
def func():
print('from func')
lis = [1,2,func]
lis[2]()
def f2(f):
f()
f2(func)
def f3():
return func
f3()() # Call f3, return the func object, then call func()
list_ = [23,41,58,9,5,27,15]
# Bubble Sort Algorithm
def bubble_sort():
for j in range(len(list_)-1):
for i in range(0,len(list_)-1-j):
if list_[i] > list_[i+1]:
list_[i], list_[i+1] = list_[i+1],list_[i]
bubble_sort()
print(list_)
# Selection Sort Algorithm
def selection_sort():
min_val = 0
for j in range(len(list_)):
for i in range(j+1, len(list_)):
if list_[i] < min_val:
min_val = list_[i]
list_[j] = min_val
selection_sort()
print(list_)