1 of 54

Advanced Python Programming

Hoang-Giang Cao (高黃江)

Sep 2023

2 of 54

Optimization Methods (Spring 2024)

  • Brute Force Search - Random search
  • Hill Climbing/Genetic Algorithm/Simulated Annealing
  • Gradient Descent - Newton Method
  • Simple Neural Network

3 of 54

Leetcode

  • Create account
  • Try some first easy questions
  • Select Python3

Maximum Subarray

https://leetcode.com/problems/maximum-subarray/

Two sum

https://leetcode.com/problems/two-sum/

Fizz Buzz

https://leetcode.com/problems/fizz-buzz/

Single Number

https://leetcode.com/problems/single-number/

Defanging an IP Address

https://leetcode.com/problems/defanging-an-ip-address/

Number of Good Pairs

https://leetcode.com/problems/number-of-good-pairs/

Select Python3

Nested loop

4 of 54

Basic Python

Extra homework 10/28

  • Only 10/28 submission
  • Deadline: 12/21 23:59 (tonight)

  • Practice for the FINAL EXAM -> Do it yourself
  • If you can not finish this HW -> You will get trouble in the FINAL EXAM

30mins delay 8:30 AM

5 of 54

Basic Python

HW 1-2-3

  • Who has not submitted HW 1, 2, 3 can re-submit
  • Deadline: 23:59PM 12/28
  • To: chgiang24@mail.mcu.edu.tw
  • 50% score

6 of 54

Basic Python

FINAL EXAM

  • 12 Jan 2024.
  • 10 programming questions (no OOP)
    • 4 easy, 4 medium (HW+Midterm), 2 hard
  • Be prepared.
    • Practice on HW, extra-HW, exercises.
    • You MUST know how to code Python to solve a problem
    • Min, max, average value, if-else, for-while, divisible by, count condition

7 of 54

Basic Python

On-site practice for Final Exam -> Extra homework.

  • Friday Dec 29th 2023.
  • 90 mins. From 8:20 to 9:50
  • 5 programming questions (medium level)
  • +3% to final score.
  • Prepare for the Final Exam.

8 of 54

Advanced Python Programming

FINAL EXAM

  • 23 Dec 2024
  • 90 mins 13:15 - 14:45
  • 6-8 programming questions. On-site programming
  • Be prepared.
    • You must know how to code Python for solving the problems. Similar to the Midterm
    • Min, max, average value, if-else, for-while, divisible by, count, conditioned number
    • Basic Object Oriented Programming (Class, Inheritance)

9 of 54

Schedule Advanced Python Programming

ID

Date

Content

1

9 Dec 2024

11 Dec 2024

Python library (Numpy + Matplotlib)

Python library (Matplotlib)

2

16 Dec 2024

18 Dec 2024

Pre-Final Advanced Python Programming

Review Pre-Final Advanced Python Programming

3

23 Dec 2024

25 Dec 2024

Final Advanced Python Programming (13:00 - 15:00)

Final Exam Data Structure in the afternoon (14:00 - 16:00)

4

30 Dec 2024

01 Jan 2025

(Online class) Review Final Exam Advanced Python Programming

No Class

5

6 Jan 2025

8 Jan 2025

(Online class) Python Library (Matplotlib + Numpy)

No Class

10 of 54

Python Libraries

  • What is library in python
  • How to use library in Python
  • Popular library in Python
  • How to make your own library

11 of 54

Python Libraries

  • 37,000 python libraries
  • There are over 137,000 python libraries present today
    • Machine learning, data science, data visualization, image and data manipulation applications, and more

  • Cannot cover them all in this course

12 of 54

Python Libraries

  • There is lots of python libraries: 37,000 python libraries
  • Objective:
    • Briefly introduce some popular libraries and their functions
    • Know how to install and use the library
  • To deeply understand a specific library, you need to work through practical projects.

13 of 54

Library in python

  • A library in Python is a collection of pre-written code or modules.
  • Libraries are designed for reuse a set of functions and methods.

from random import randint

number = randint(5,100)

print(number)

Python library (random.py)

Your file

14 of 54

Library in python

  • Someone already wrote a set of functions/modules
  • We can just use them.

from random import randint

number = randint(5,100)

print(number)

Python library (random.py)

Your file

15 of 54

Python Libraries

  • There are some built-in library in Python
  • Can use directly, don't need to install

16 of 54

Python Libraries

  • There are some built-in library in Python
  • Can use directly, don't need to install

For math functions

  • math.sqrt ->
  • Math.pow -> xy
  • Math.sin -> sin(x)
  • math.cos -> cos(x)

17 of 54

Python Libraries

  • There are some built-in library in Python
  • Can use directly, don't need to install

For random generator

  • random.random()
  • random.randint(a,b)
  • random.choice(arr)
  • random.shuffle(x)

18 of 54

Third-party Python Libraries

  • Some other library need to install if you want to use it
  • Some popular Python libraries
    • Numpy, Pandas, Matplotlib, SciPy, Keras for Data Processing
    • OpenCV, Pillow for Image Processing
    • Pytorch, Tensorflow for Deep Learning
    • Tkinter for GUI Application

19 of 54

Third-party Python Libraries

  • Some other library need to install if you want to use it
  • Some popular Python libraries
    • Numpy, Pandas, Matplotlib, SciPy, Keras for Data Processing
    • OpenCV, Pillow for Image Processing
    • Pytorch, Tensorflow for Deep Learning
    • Tkinter for GUI Application

GCI_Auto_Judge made by Tkinter

20 of 54

Third-party Python Libraries

  • To install library, use pip install name_of_library
  • From the terminal, type:

pip install numpy

pip install matplotlib

pip install

21 of 54

Python Libraries

22 of 54

Third-party Python Libraries

Numpy

23 of 54

Third-party Python Libraries

Matplotlib

24 of 54

Built-in Python Libraries

Random

25 of 54

Random library

  • To use a built-in library, we need to import the library in to your code

import random

number = random.randint(5,100)

print(number)

Need to call the library_name.function()

26 of 54

Random library

  • To use a built-in library, we need to import the library in to your code

import random as rd

number = rd.randint(5,100)

print(number)

Need to call the shorter_name.function()

as shorter_name

import numpy as np

import matplotlib as plt

import tensorflow as tf

27 of 54

Random library

  • To use a built-in library, we need to import the library in to your code

from random import randint,randchoice

number = randint(5,100)

print(number)

Only import the needed function

Don’t need to call with the library name

28 of 54

Random library

  • To use a built-in library, we need to import the library in to your code

from random import *

number = randint(5,100)

print(number)

Import all functions in the library

Don’t need to call with the library name

29 of 54

Random library

  • To use a built-in library, we need to import the library in to your code

from random import *

number = randint(5,100)

print(number)

import random

number = random.randint(5,100)

print(number)

from random import randint,randchoice

number = randint(5,100)

print(number)

import random as rd

number = rd.randint(5,100)

print(number)

Import the library

Import the library as shorter name

Import specific functions

Import all functions

30 of 54

Random library

  • The random library equips us with powerful tools to generate pseudo-random numbers
  • Let’s see some functions from random library
      • random()
      • randint(a, b)
      • choice(seq)
      • shuffle(seq)
      • uniform(a, b)

31 of 54

Random library

  • random() -> return a random float number in range 0-1

Adding noise for generalization purpose in training data

import random

number = random.random()

print("random number",number )

32 of 54

Random library

  • randint(min,max) -> Random a number in range [a,b]

import random

lucky_number = random.randint(0,100)

print("The winner is",lucky_number )

import random

lucky_number = random.randint(1,40)

print("The winner is U116270"+str(lucky_number).zfill(2))

33 of 54

Random library

  • choice(x) -> random choice an item in a list

import random

arr = ["McDonald","Burger King", "Mos Burger","KFC"]

result = random.choice(arr)

print("Today, you should eat",result)

34 of 54

Random library

  • choice(x) -> random choice an item in a list

import random

arr = ["A","B", "C","D"]

result = random.choice(arr)

print("Random answer, you should choice",result)

35 of 54

Random library

  • shuffle() -> shuffle a list

Shuffle data for training

import random

arr = [1,2,3,4,5,6,7,8,9]

print("before shuffle:")

print(arr)

random.shuffle(arr)

print("After shuffle:")

print(arr)

36 of 54

Random library

  • Create rock paper scissors game

import random

def get_computer_choice():

return random.choice(['rock', 'paper', 'scissors'])

computer_choice = get_computer_choice()

print("computer_choice:", computer_choice)

37 of 54

Random library

  • Create rock paper scissors game

import random

def get_computer_choice():

return random.choice(['rock', 'paper', 'scissors'])

def get_user_choice():

print("1. rock")

print("2. paper")

print("3. scissors")

int_choice = input("your choice:")

int_choice = int (int_choice)

if (int_choice ==1) :

return "rock"

elif (int_choice ==2) :

return "paper"

elif (int_choice ==3) :

return "scissors"

computer_choice = get_computer_choice()

your_choice = get_user_choice()

print("")

print("computer_choice:", computer_choice)

print("your_choice:", your_choice)

38 of 54

Random library

  • Create rock paper scissors game

def who_win(your_choice,computer_choice):

if (your_choice == "rock"):

if (computer_choice=="paper"):

return "You Lose!"

elif(computer_choice=="scissors"):

return "You Win!"

elif(computer_choice=="rock"):

return "Draw"

if (your_choice == "paper"):

if (computer_choice=="paper"):

return "Draw"

elif(computer_choice=="scissors"):

return "You Lose!"

elif(computer_choice=="rock"):

return "You Win!"

if (your_choice == "scissors"):

if (computer_choice=="paper"):

return "You Win"

elif(computer_choice=="scissors"):

return "Draw!"

elif(computer_choice=="rock"):

return "You Loss!"

39 of 54

Random library

  • Create rock paper scissors game

def who_win(your_choice,computer_choice):

if your_choice == computer_choice:

return "Draw!"

elif (

(your_choice == 'rock' and computer_choice == 'scissors') or

(your_choice == 'paper' and computer_choice == 'rock') or

(your_choice == 'scissors' and computer_choice == 'paper')

):

return "You win!"

else:

return "Computer wins!"

Optimize the code

Check it by yourself!

40 of 54

Random library

  • Create rock paper scissors game

import random

def get_computer_choice():

arr = ["rock","paper","scissors"]

return random.choice(arr)

def get_user_choice():

print("1. rock")

print("2. paper")

print("3. scissors")

user_input = input("Your choice is:")

user_input = int (user_input)

if user_input == 1:

return "rock"

elif user_input == 2:

return "paper"

elif user_input == 3:

return "scissors"

def who_win (your_choice, computer_choice):

if (your_choice == computer_choice):

return "Draw"

if (your_choice == "rock"):

if (computer_choice== "paper"):

return "Computer Win!"

elif(computer_choice== "scissors"):

return "You Win!"

if (your_choice == "paper"):

if (computer_choice== "rock"):

return "You Win!"

elif(computer_choice== "scissors"):

return "Computer Win!"

if (your_choice == "scissors"):

if (computer_choice== "rock"):

return "Computer Win!"

elif(computer_choice== "paper"):

return "You Win!"

you_win = 0

computer_win = 0

while (you_win != 3 and computer_win != 3):

computer_choice = get_computer_choice()

your_choice = get_user_choice()

print("computer_choice:",computer_choice)

print("your_choice:",your_choice)

print("")

result = who_win(your_choice,computer_choice)

print(result)

if (result=="You Win!"):

you_win +=1

if (result=="Computer Win!"):

computer_win +=1

print(f"You {you_win} : {computer_win} Computer")

print("")

if (you_win == 3):

print("You are the winner")

elif(computer_win == 3):

print("Computer is the winner")

41 of 54

Built-in Python Libraries

Math

42 of 54

Math library

  • In Python, the math module is a standard library module that provides mathematical functions.

  • sqrt -> Square Root
  • sin, cos, tan - Trigonometric Functions
  • pow - Power Function
  • ceil, floor - Ceiling and Floor Functions
  • fabs - Absolute Value
  • round - Rounding

43 of 54

Math library

  • How to import math library

import math

num = -10

abs_value = math.fabs(num)

print(f"|{num}| = {abs_value}")

import math as m

num = -10

abs_value = m.fabs(num)

print(f"|{num}| = {abs_value}")

from math import *

num = -10

abs_value = fabs(num)

print(f"|{num}| = {abs_value}")

from math import fabs

num = -10

abs_value = fabs(num)

print(f"|{num}| = {abs_value}")

44 of 54

Math library

  • sqrt(x) -> Square Root of (x)->

import math

num = 25

result = math.sqrt(num)

print(result)

45 of 54

Math library

  • pow(x,y) -> power functions -> xy
  • Similar as x**y -> xy

import math

x = 2

y = 3

result_exp = math.pow(x,y)

print (f"{x}^{y}={result_exp}")

result_exp_2= x**y

print (f"{x}^{y}={result_exp_2 }")

46 of 54

Math library

  • Ceil: rounds a number UP to the nearest integer.
  • It returns the smallest integer greater than or equal to the given number

import math

num = 4.5

ceil_result = math.ceil(num)

print(f"Ceil of {num} = {ceil_result}")

num = 4.9

ceil_result = math.ceil(num)

print(f"Ceil of {num} = {ceil_result}")

num = 4.1

ceil_result = math.ceil(num)

print(f"Ceil of {num} = {ceil_result}")

Ceil of 4.5 = 5

Ceil of 4.9 = 5

Ceil of 4.1 = 5

47 of 54

Math library

  • floor: rounds a number DOWN to the nearest integer.
  • It returns the smallest integer smaller than or equal to the given number

import math

num = 4.5

ceil_result = math.floor(num)

print(f"Floor of {num} = {ceil_result}")

num = 4.9

ceil_result = math.floor(num)

print(f"Floor of {num} = {ceil_result}")

num = 4.1

ceil_result = math.floor(num)

print(f"Floor of {num} = {ceil_result}")

Floor of 4.5 = 4

Floor of 4.9 = 4

Floor of 4.1 = 4

48 of 54

  • round(x): Rounds a floating-point number to the nearest integer.
  • Built-in function, not in math library

num = 4.5

ceil_result = round(num)

print(f"Round of {num} = {ceil_result}")

num = 4.51

ceil_result = round(num)

print(f"Round of {num} = {ceil_result}")

num = 4.49

ceil_result = round(num)

print(f"Round of {num} = {ceil_result}")

num = 4.9

ceil_result = round(num)

print(f"Round of {num} = {ceil_result}")

num = 4.1

ceil_result = round(num)

print(f"Round of {num} = {ceil_result}")

round of 4.5 = 4

round of 4.51 = 5

round of 4.49 = 4

round of 4.9 = 5

round of 4.1 = 4

49 of 54

  • round(x,precise): Rounds a floating-point number to a specified number of decimal places (precision)
  • Built-in function, not in math library

num = 4.5

ceil_result = round(num)

print(f"round of {num} = {ceil_result}")

num = 4.5524123

precision = 2

ceil_result = round(num,precision)

print(f"round of {num} with {precision} decimal = {ceil_result}")

num = 4.5524123

precision = 4

ceil_result = round(num,precision)

print(f"round of {num} with {precision} decimal = {ceil_result}")

round of 4.5 = 4

round of 4.5524123 with 2 decimal = 4.55

round of 4.5524123 with 4 decimal = 4.5524

50 of 54

Math library

  • fabs(x) -> function returns the absolute value -> |x|

import math

num = -10

abs_value = math.fabs(num)

print(f"|{num}| = {abs_value}")

|-10| = 10.0

51 of 54

Math library

  • math.radians(x), math.degree(x), math.pi - Trigonometric Functions

import math

rad = math.pi

degree = math.degrees(rad)

print(rad,"rad","=", degree,"degree")

degree = 180

rad = math.radians (degree)

print(degree,"degree","=", rad,"rad")

  • math.radians(x) converts from degree to radian
  • math.degree(x) converts from radian to degree
  • math.pi: PI value

52 of 54

Math library

  • sin(x), cos(x), tan(x) - Trigonometric Functions

import math

rad = math.pi/2

sin_value = math.sin(rad)

cos_value = math.cos(rad)

print(f"sin({rad }) = {sin_value}")

print(f"cos({rad }) = {cos_value}")

degree = 60

sin_value = math.sin(math.radians(degree))

cos_value = math.cos(math.radians(degree))

print(f"sin({degree}) = {sin_value}")

print(f"cos({degree}) = {cos_value}")

  • Use radian
  • Need to convert to radian

53 of 54

Advanced Python Programming

FINAL EXAM

  • 23 Dec 2024
  • 90 mins 13:15 - 14:45
  • 6-8 programming questions. On-site programming
  • Be prepared.
    • You must know how to code Python for solving the problems
    • Min, max, average value, if-else, for-while, divisible by, count, conditioned number
    • Basic Object Oriented Programming (Class, Inheritance)

54 of 54

Advanced Python Programming

Good luck to you with this course!

Any questions?