0% found this document useful (0 votes)
0 views44 pages

Hierarchy and Modular Programming

The document discusses the concepts of top-down stepwise refinement and modularity in programming, emphasizing the importance of breaking down complex problems into smaller, manageable tasks. It illustrates these concepts through examples of pseudocode and Python code for calculating class averages and analyzing exam results. Additionally, it introduces functions, modules, and object-oriented programming (OOP) as methods to enhance code organization and clarity.

Uploaded by

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

Hierarchy and Modular Programming

The document discusses the concepts of top-down stepwise refinement and modularity in programming, emphasizing the importance of breaking down complex problems into smaller, manageable tasks. It illustrates these concepts through examples of pseudocode and Python code for calculating class averages and analyzing exam results. Additionally, it introduces functions, modules, and object-oriented programming (OOP) as methods to enhance code organization and clarity.

Uploaded by

Ginzil Haman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Hierarchy -

Modularity
(real problems are always too big for your
head)
(some material due to Zhiao Shi, ACCRE)

p.s. you won't have covered specific code;


don't worry !
Top-down Stepwise
Refinement
(the way to write code!)
Top-down
• Begin
refinement
with a top level
pseudocode representation
Determine the class average for the quiz

• Divide into smaller tasks and list


them
Initialise variables
Input, sum and count the quiz grades
Calculate and print the class average

• Repeat until it’s trivial to write


the code.
• NB: many codes have initialise,
Top-down
refinement

• At the next level


#Initialise variables

• Itself divides into


#Initialize total to zero
#Initialize counter to zero
Top-down
refinement
• At the next level
Input, sum and count the quiz grades

• Itself divides into


Input the first grade (possibly the ‘halt’)
While the user has not as yet entered ‘halt‘
Add grade to the running total
Add one to the grade counter
Input the next grade (possibly the ‘halt’)
Top-down
refinement
• At the next level
Calculate and print the class average

• Itself divides into


If the counter is not equal to zero
Average = total / counter
Print Average
else
Print “No grades were entered”
Top-down
refinement
• So the present pseudocode
becomes:
Initialize total to zero
Initialize counter to zero

Input the first grade (possibly the ‘halt’)


While the user has not as yet entered ‘halt‘
Add grade to the running total
Add one to the grade counter
Input the next grade (possibly the ‘halt’)

If the counter is not equal to zero


Average = total / counter
Print Average
else
Print “No grades were entered”
Enough to write
code
# initialise variables initialise total to zero
total = counter = 0 # initialise counter to zero

# input, sum and count the quiz grades


grade = input(“Enter grade:“) # input first grade

while grade != -1 : # while not yet ‘halt’


total += grade # add to running total
counter+=1 # increment grade counter
grade = input(“Enter grade:“) #next grade
# calculate and print the class average
if counter !=0: # if counter not zero
average = total/counter # average=total/counter

print(“Average {:.2f}”, average) # print average


else:
print(“No grades”) # print no grades entered
Enough to write
code
Top-down
refinement
• Usually don’t refine from first to
last pseudocode statement.
• Refine the easiest ones first; doing
the outputs can sometimes clarify
in your mind exactly what you
need to calculate.
• Use indentation to structure the
algorithm
• Actually, you must use
indentation !
A second example
• We have a list of test results (1 =
pass, 2 = fail) for 10 students. If
more than 8 students pass, tell
the class coordinator to make the
class harder!
• Top level pseudocode
representation
Analyze exam results and decide if class should
be harder
A second example

• First refinement
Initialise variables

Input the ten quiz grades and count passes and


failures

Print a summary of the exam results including


whether class should be tougher

• Repeat refining…
A second example

• At the next level


Initialise variables

• divides into
Initialize passes to zero
Initialize failures to zero
Initialize student counter to one
A second example

• At the next level


Input the ten quiz grades and count passes and
failures

• divides into
While student counter is <= ten
Input the next exam result
If the student passed
Add one to passes
else
Add one to failures
Add one to student counter
A second example

• At the next level


Print a summary of the exam results including
whether class should be tougher

• divides into
Print the number of passes
Print the number of failures
If more than eight students passed
Print “Make class harder”
A second example
• So the present pseudocode
No

becomes:
te

Initialize passes to zero


Initialize failures to zero
in

Initialize student counter to one


de
nt

While student counter is <= ten


Input the next exam result
at

If the student passed


io n

Add one to passes


else
Add one to failures
Add one to student counter

Print the number of passes


Print the number of failures
If more than eight students passed
Print “Make class harder”
Enough to write
code
# initialise variables
passes = 0 # Init passes to zero
failures = 0 # Init failures to zero
student = 1 # Init student counter to one

# Input ten quiz grades and count passes failures

while student<=10 : # when student counter <=10


result = input(“Enter(1=pass,2=fail):”)
result=int(result) # input next exam result
if result==1 : # if student passes
passes+=1 # add one to passes
else: # else
failures+=1 # add one to failures
student+=1 # add one to counter

Indentation - default 4 spaces


Enough to write
code
# Print a summary of the exam results
# print number of passes and number of failures
print(“Passed {}".format(passes))
print(“Failed {}".format(failures))

if passes >8 : # if more than 8 students pass


print(“Make course harder”);
# make the course harder
Modularity -
Functions
functions, subroutines, subprograms,…

traditional way to split up a program into


bits !
easy to make a machine do this !

an introduction
functions =
outsourcing
• Break large computing tasks into
smaller ones - a bit like top-down
refinement.
• But, importantly, the details of how
each section works is shuffled off to
another part of the file, so that you
can see the flow of the overall
program more clearly.
• The main program then becomes a
series of calls to
functions - why?
• promotes modular and ‘top-down’
coding
• promotes ‘standard libraries’ from
colleagues, or experts from rest of
world
• hides implementation - makes the
important points of the code more
clear
• makes code change/debugging
easier
functions - why?
• you have already seen this done !
• print(“hello world”)

• printing / formatting is complex,


and has been sorted by someone
else.
• The print function takes one or
more inputs, does something
useful, hides complexity.
functions,
modules,
packages, libraries
• later, you will write your own
functions and classes.
• first - need to know enough to find
and use other people's functions.
• some (like print) are intrinsic
• groups of useful functions are
gathered into modules.
functions,
modules,
packages, libraries

math, cmath, date, time, strin


functions,
modules,
packages, libraries
• groups of useful modules, each
containing useful functions, are
packaged together into packages,
which we sometimes call libraries
• optimised maths operations:
numpy, SciPy, matplotlib - we will
use these.
• web services: Django
• games: Pygame
functions,
modules,
packages, libraries
simple function
layout
• in general functions are defined :
def func_name(arguement, arguement,…):
"""Text Description."""
declarations_of_local_variables
statements
return expression #optional

• for example :
def cat_age(human_age):
"""Translate human to cat ages."""
multiplier = 4
if (human_age==1): return 15
if (human_age==2): return 24
return human_age*multiplier + 16
functions - calling
• functions are defined before use,
and then called by :
...
my_age = 46
cat_age(12) # pointless, ignores answer
felix_age = cat_age(4) # felix_age now 32
print(cat_age(12) # output ancient!
...

• and that's all you need on what a


function is for now. More subtlety
later.
• How do I get and use 'em?
using modules
• modules are just python files with
functions in them.
• import them into the top of your
code in a few simple ways (to
avoid duplicates).
• you've seen this already :
importing and
using
• simplest :
import math
...
root = math.sqrt(discriminant)

• one at a time (what we did before):


from math import sqrt
...
root = sqrt(discriminant)
importing and
using
• aliasing to reduce typing :
import math as m
...
root = m.sqrt(discriminant)

• aliasing one particular function :


from math import sqrt as r
...
root = r(discriminant)
# obviously don't alias something already small!
# aliasing to a variable name in use is grim!
Packages
• work the same way as modules,
but usually package functions are
more serious beasts!
import numpy as np
...
two_d = np.array([(1,2,3),(4,5,6),(7,8,9)])
# create a 2D array
one_d = np.linspace(0,100,6)
# array of six evenly spaced values from 0-100
new_one_d = np.append(one_d,110)
# appends the number 110 to the end of the array
two_d = two_d + np.eye(3)
# add the 3x3 identity matrix to two_d
Packages
• How do I know what I've
got ?
• https://docs.python.org/3/l
ibrary/

or,
import numpy as np
dir(np)
# list of 'names'
# (functions, variables, classes)
help(np)
# help pages - but too long!
Object Oriented
Programming
the more modern way to partition a program

easier for humans - i.e. faster developed


code.

less like what the machine is doing - i.e.


tougher to get compilers to make quick code
.
OOP
• everything is an object (i.e.
variables on steroids; rich and
talkable to)
• a program is a bunch of objects
talking (a message is pretty much
a function call)
• each object has its own hidden
guts (containing variables, which
are objects!)
OOP
• each object has a type (ok,
actually a type on steroids, called
a class, with hierarchy)
• all objects of a given type can
receive messages aimed for that
type (i.e. if a circle is a shape it
can accept circle messages and
shape messages).
• that last one gives OOP much
power !
C++ one you've
seen
• led1 is not a variable, it's an object,
hiding a whole pile of complication
under the hood :
#include "mbed.h"

DigitalOut led1(LED1); in
te
int main() { rf
while (true) { ac
led1 = !led1; e
// or led1.write( !led1.read() );
wait(0.5);
}
}
cl ob
as je
s c
Example you've
seen
interface
creation stuff

function like
interface

operator like
interface
OOP
• Using objects is usually a doddle,
especially if some other expert
coder made them.
• A useful object is a pleasure to use
again...
• Making objects is harder. Good
design is never easy.
• Firstly we'll use objects 🙂,only later
will we try writing them.
OOP structure...
• definition :
class Car():
"""Model a Car."""
def __init__(self, make, model):
"""Initialise"""
self.make = make
self.model = model
self.tank_cap = 60 #60 litre tank
self.tank = 0 #initial fuel fill

def fillup(self):
"""fill tank to brim"""
self.tank = self.tank_cap
print("Full!")

def ... #other functions and private vars


OOP structure...
• use - much, much easier than
definition! :
myCar = Car('nissan', 'micra')

print(myCar.make)
print(myCar.model)

myCar.fillup()

• of course, it is still possible to muck


up:
myOtherCar = Car('nissan', 'leaf')

print(myOtherCar.make)
print(myOtherCar.model)
OOP: back to
numpy
• carefully only mentioned functions
last time
import numpy as np
two_d = np.array([(1,2,3),(4,5,6),(7,8,9)])
# create a 2D array

• but numpy arrays are, of course,


objects
two_d = two_d.resize(4,4)
# array is extended, filling with zeros
smallest = two_d.min()
# smallest set to zero, minimum integer in array
two_d = two_d.T
# transpose the array
OOP: and strings
• strings are also objects
"frog".centre(8,'$')
# $$frog$$
"texas".capitalize()
# Texas
"acatbcatccatdcatecatfcatgcatdog".count("cat")
# returns integer 7
"john27".isalpha()
#returns False

• and about 44 other methods that


can be applied to strings !
docs.python.org/3/library/stdtypes.html

You might also like