0% found this document useful (0 votes)
2 views22 pages

Lecture08 Modular Design

The document discusses the concept of modular design in programming, emphasizing the importance of breaking down large programs into manageable modules for individual development and testing. It covers the use of Python's standard library functions, built-in modules like math, random, statistics, and csv, and provides examples of how to import and utilize these modules. Additionally, it includes exercises for creating custom modules to calculate arithmetic mean and mode.

Uploaded by

seongjaego50
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views22 pages

Lecture08 Modular Design

The document discusses the concept of modular design in programming, emphasizing the importance of breaking down large programs into manageable modules for individual development and testing. It covers the use of Python's standard library functions, built-in modules like math, random, statistics, and csv, and provides examples of how to import and utilize these modules. Additionally, it includes exercises for creating custom modules to calculate arithmetic mean and mode.

Uploaded by

seongjaego50
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

컴퓨터 개념 및 실습

Lecture 8. Modular Design

Taewhan Kim
What is a Module?
■ Well-designed software is that programs are designed as a
collection of modules
■ Module: the design and/or implementation of specific
functionality to be incorporated into a program
■ Module design
❑ Allow large programs to be broken down into manageable size parts
❑ Allow modules to be individually developed and tested and eventually
integrated as a part of a complete system
❑ Facilitate program modification

2
Modules and Namespaces

def double(lst): def double(lst):


"""Returns a new list """Returns a new list with
with each number doubled, each number duplicated,
for example, [1,2,3] for example, [1,2,3]
returned as [(1,1), (2,2),
returned [2,4,6] (3,3)]
""" """
[Link] [Link]

# main
import module1
import module2

.
num_list = [3,8,14]
ambiguous
result = double(num_list)
reference for
.
identifier double
(name clash)

3
Modules and Namespaces

def double(lst): def double(lst):


"""Returns a new list """Returns a new list with
with each number doubled, each number duplicated,
for example, [1,2,3] for example, [1,2,3]
returned as [(1,1), (2,2),
returned [2,4,6] (3,3)]
""" """
[Link] [Link]

# main
import module1
import module2

. references function double


ans1 = [Link](…) from module1's namespace
ans2 = [Link](…) references function double
. from module2's namespace

4
Standard Library Functions and the import Statement

• Standard library: library of pre-written functions that comes with


Python
• Library functions perform tasks that programmers commonly need
• Example: print, input, range
• Viewed by programmers as a “black box”
• Some library functions built into Python interpreter
• To use, just call the function
• Modules: files that stores functions of the standard library
• Help organize library functions not built into the interpreter
• Copied to computer when you install Python
• To call a function stored in a module, need to write an import
statement
• Written at the top of the program
• Format: import module_name
"Import" from other Python file
def exp(base, ex):
return base ** ex

[Link] Each Python file can become a module

import tools
print([Link](3, 3))

from tools import exp Screen


print(exp(3, 3)) 27

import tools as t
print([Link](3, 3))

6
Python Built-in Modules
■ Python Standard Library
❑ math
❑ random
❑ statistics
❑ csv

❑ [Link]

7
Python Built-in Module #1: math
■ 'import' Math library
❑ place at the beginning of your code
❑ type them before in interactive mode

■ Essential functions
❑ Exponential(pow), square root(sqrt)
❑ Round functions: floor, ceil
❑ Factorial
❑ Trigonometric functions
■ sin, cos, tan, ...
❑ And more...

Interpreter
8
Python Build-in Module #2: random
■ import random
■ Useful methods in 'random'
❑ [Link]()
■ Return a random float number in a range [0.0, 1.0]
❑ [Link](a, b)
■ Return a random integer number in a range [a, b]
❑ [Link](start, stop, step)
■ Return a random integer number, among numbers can be generated by
range() function with same arguments

❑ [Link]([a])
■ Initialize random number generator with seed value
❑ Same seed should generate same sequence of random numbers
❑ By default, Python use current system time as the seed value

9
Example: Random Guess Game

from random import randint

hidden = randint(1, 100)

print("Guess a number in [1, 100]")


num = int(input("Guess? "))

while num != hidden:


if num < hidden:
print("Up")
else:
print("Down")

num = int(input("Guess? "))


print("Got it!")

10
Python Build-in Module #3: statistics
■ import statistics
■ Useful methods in 'statistics'
❑ [Link](data) >>> import statistics
■ Return arithmetic mean (average) of data
>>> a = [0, 1, 1, 3, 4, 9,
❑ [Link](data)
15]
■ Return median (middle value) of data >>> [Link](a)
❑ [Link](data) 4.71428…
■ Return most common value of data >>> [Link](a)
3
❑ [Link](data)
>>> [Link](a)
■ Return standard deviation of data 1
❑ [Link](data) >>> [Link](a)
■ Return variance of data 5.43796…
>>> [Link](a)
29.5714…

Interpreter
11
Python Build-in Module #4: csv
■ import csv

2020-02-21;1001;banana
2020-02-22;1002;orange
2020-02-23;1003;apple

[Link]

import csv

with open('[Link]') as csvfile:


my_csv_file = [Link](csvfile, delimiter=';')
for row in my_csv_file:
print(row) Screen
['2020-02-21', '1001', 'banana']
['2020-02-22', '1002', 'orange']
['2020-02-23', '1003', 'apple']
12
A Programmer-Defined Stack Module
■ Stacks are used to temporarily store and retrieve data
■ The last item placed on the stack is the first to be retrieved
❑ LIFO – "last in, first out"

push pop
push C C pop
push B B pop
A A

C C
B B B B
A A A A A A

top of top of top of top of top of top of


stack stack stack stack stack stack

13
A Programmer-Defined Stack Module
■ Stacks are used to temporarily store and retrieve data
■ The last item placed on the stack is the first to be retrieved
❑ LIFO – "last in, first out"

push
push C
>>> import stack
push B
>>> stack = [3, 4, 5]
A >>> [Link](6)
>>> stack
[3, 4, 5, 6]
C
>>> [Link](7)
B B >>> stack
A A A [3, 4, 5, 6]
Interpreter
top of top of top of
stack stack stack

14
A Programmer-Defined Stack Module
■ Stacks are used to temporarily store and retrieve data
■ The last item placed on the stack is the first to be retrieved
❑ LIFO – "last in, first out"

>>> import stack pop


>>> stack = [3, 4, 5, 6, 7] C pop
>>> stack
B pop
[3, 4, 5, 6, 7]
>>> [Link]() A
7
>>> stack
C
[3, 4, 5, 6]
>>> [Link]() B B
6 A A A
>>> stack
[3, 4, 5] top of top of top of
Interpreter stack stack stack

15
Exercise 1: Parentheses Matching Program
■ Approach #1: Elimination based
❑ In every iteration, the innermost brackets get eliminated (replaced with empty string). If
we end up with an empty string, our initial one was balanced; otherwise, not.

def check(my_string): Example


# TODO Input : {[]{()}}
Output : Balanced

Input : [{}{}(]
Output : Unbalanced

string = "{[]{()}}"
print(string, "-", "Balanced"
if check(string) else "Unbalanced") Screen
{[]{()}} - Balanced

16
Exercise 1: Parentheses Matching Program
■ Approach #1: Elimination based
❑ In every iteration, the innermost brackets get eliminated (replaced with empty string). If
we end up with an empty string, our initial one was balanced; otherwise, not.

def check(my_string): Example


brackets = ['()', '{}', '[]'] Input : {[]{()}}
while any(x in my_string for x in brackets): Output : Balanced
for br in brackets:
my_string [Link](br, '')
return not my_string Input : [{}{}(]
Output : Unbalanced

string = "{[]{()}}"
print(string, "-", "Balanced"
if check(string) else "Unbalanced") Screen
{[]{()}} - Balanced

17
Exercise 1: Parentheses Matching Program
■ Approach #2: Using stack
❑ Each time, when an open parentheses is encountered push it in the stack, and when
closed parenthesis is encountered, match it with the top of stack and pop it. If stack is
empty at the end, return Balanced otherwise, Unbalanced.
open_list = ["[", "{", "("] Example
close_list = ["]", "}", ")"] Input : {[]{()}}
def check(myStr): Output : Balanced
# TODO
Input : [{}{}(]
Output : Unbalanced

string = "{[]{()}}"
print(string, "-", check(string))
Screen
string = "[{}{})(]"
{[]{()}} – Balanced
print(string, "-", check(string))
[{}{})(] – Unbalanced
18
Exercise 2: Make your own modules!
■ Calculate arithmetic mean (one type of average)
❑ Don't use a built-in or standard library method to calculate the arithmetic mean of a list
of numbers! Make your own module!

def mean(numbers): Example


# TODO Input : []
Output : 0

Input : [1, 2, 3, 4]
Output : 2.5
my_statistics.py

import my_statistics

data1 = [1, 3, 4, 5, 7, 9, 2]
result = my_statistics.mean(data1) Screen
Mean is : 4.428571
print("Mean is :", result)
19
Exercise 2: Make your own modules!
■ Calculate arithmetic mean (one type of average)
❑ Don't use a built-in or standard library method to calculate the arithmetic mean of a list
of numbers! Make your own module!

def mean(numbers): Example


return float(sum(numbers) / Input : []
max(len(numbers), 1) Output : 0

Input : [1, 2, 3, 4]
Output : 2.5
my_statistics.py

import my_statistics

data1 = [1, 3, 4, 5, 7, 9, 2]
result = my_statistics.mean(data1) Screen
Mean is : 4.428571
print("Mean is :", result)
20
Exercise 3: Make your own modules!
■ Calculate mode (most common value of data)
❑ Don't use a built-in or standard library method to calculate the mode of a set of data!
You can add mode function in my_statistics.py.

def mode(data):
Example
# TODO
Input : [1, 1, 2, 3, 3, 3, 3, 4]
Output : 3

Input : ['red','red','green','red']
my_statistics.py Output : 'red'

import my_statistics

data2 = [3, 5, 9, 5, 5, 4, 3]
result2 = my_statistics.mode(data2) Screen
Most common value
print("Most common value is :", result2) is: 3
21
Exercise 3: Make your own modules!
■ Calculate mode (most common value of data)
❑ Don't use a built-in or standard library method to calculate the mode of a set of data!
You can add mode function in my_statistics.py.

def mode(data): my_statistics.py


d = {}
for a in data:
if not a in d:
d[a]=1
else:
d[a]+=1
return [k for k,v in [Link]() if v==max([Link]())]

import my_statistics

data2 = [3, 5, 9, 5, 5, 4, 3]
result2 = my_statistics.mode(data2) Screen
Most common value
print("Most common value is :", result2) is: 3
22

You might also like