Professional Documents
Culture Documents
EEA216 資料結構
Data Structure
Lecture 5
Yu-Hui Huang, Data Structure
Yu-Hui Huang
Sep. 28, 2022
Python – OOP Class Car:
def __init__(self, fuel, maxspd):
self.fuel = fuel
self.maxspeed = maxsp
def refuel():
pass
class Vehicle:
def __init__(self, name, max_speed, mileage):
self.name = name
self.max_speed = max_speed
self.mileage = mileage
class Bus(Vehicle):
pass
Reference: https://www.brilliantcode.net/761/python-3-6-class/
Yu-Hui Huang, Data Structure 6
L4: Exercise 3
Write a program with the following class definition
and test it with the following expressions.
>>>cir = Circle(6)
Polygon
>>>print(cir.area())
(num_sides)
113.097335529
area
>>>print(cir.perimeter())
perimeter
37.6991118430
inherit inherit
>>>rec = rectangle(6,6)
>>>print(rec.area())
Circle Rectangle
36
(num_sides, radius) (num_sides, length,
>>>print(rec.perimeter())
area breadth)
24
perimeter area
perimeter
Reference: https://en.wikipedia.org/wiki/Algorithm#Algorithmic_analysis
Yu-Hui Huang, Data Structure 9
Flow chart
print(fact1(10)) print(fact2(10))
print(fact1(100)) print(fact2(100))
Example:
3n+2 = O(n) as 3n+2 ≤4n for all n ≥2
3n+3 = O(n) as 3n+3 ≤4n for all n ≥3
100n+6 = O(n) as 100n+6 ≤ 101n for n ≥10
• 1000𝑛! + 100𝑛 − 6 = Ο 𝑛! ?
• Yes, since 1000𝑛! + 100𝑛 − 6 ≤ 1001𝑛! for all 𝑛 ≥
100.
• 6 ∗ 2" + 𝑛! = Ο(2" ) ?
• Yes, since 6 ∗ 2" + 𝑛! ≤ 7 ∗ 2# for all 𝑛 ≥ 4.
• 3𝑛 + 3 = Ο(𝑛! ) ?
• Yes, since 3𝑛 + 3 ≤ 3𝑛! for all 𝑛 ≥ 2.
• 10𝑛! + 4𝑛 + 2 = Ο(𝑛$ ) ?
• Yes, since 10𝑛! + 4𝑛 + 2 ≤ 10𝑛$ for all 𝑛 ≥ 2.
• 3𝑛 + 2 = Ο 1 ?
• No. Cannot find c and n% . 3n < c − 2 is never true.
16
Big-O
• Theorem 1.
If 𝑓 𝑛 = 𝑎& 𝑛& + ⋯ + 𝑎' 𝑛+ 𝑎% , 𝑡ℎ𝑒𝑛 𝑓 𝑛 = 𝑂 𝑛& .
Example:
5n4+3n3+n2+5 is O(n4)
2n+2 is O(2n)
Example:
3n+2 = Ω(n) as 3n+2 ≥ 3n for n ≥ 1
3n+3 = Ω(n) as 3n+3 ≥ 3n for n ≥ 1
Example:
3nlogn-2n is Ω(nlogn)
Example:
3n+2 = Θ(n) as 3n+2≥3n for all n ≥2 and
3n+2 ≤ 4n for all n ≥2
--> 𝑐"=3, 𝑐#=4 and 𝑛!=2
Example:
3nlogn+4n+5logn is Θ(n)
Good!
Superb!
• Typical Operations:
- Arithmetic calculation
- Comparison
- Assignment statement
- Invoking a method or function.
def add_2D_list(inList):
sum=0
for row in inList:
for element in row:
sum += element
add_2D_list([[1,2],[3,4]])
Reference: https://www.linkedin.com/pulse/time-complexity-algorithms-python-examples-hiral/
https://runestone.academy/ns/books/
published/pythonds/index.html)