0% found this document useful (0 votes)
127 views

Comp1012 (2015)

This document provides an overview of key concepts in computer programming for scientists and engineers, including: 1. It defines common terminology used in programming like literals, variables, keywords, and data types. 2. It discusses casting between different data types in Python and formatting output for printing. 3. It covers formatting strings for printing numbers with controls for precision, padding, and justification. 4. It provides a brief introduction to complex numbers and operator precedence in Python.
Copyright
© © All Rights Reserved
0% found this document useful (0 votes)
127 views

Comp1012 (2015)

This document provides an overview of key concepts in computer programming for scientists and engineers, including: 1. It defines common terminology used in programming like literals, variables, keywords, and data types. 2. It discusses casting between different data types in Python and formatting output for printing. 3. It covers formatting strings for printing numbers with controls for precision, padding, and justification. 4. It provides a brief introduction to complex numbers and operator precedence in Python.
Copyright
© © All Rights Reserved
You are on page 1/ 16

1

COMP  1012  
Section  A02    
Computer  Programming  
for  Scientists  and  Engineers   REVIEW
2015  January  to  April  

3   4  

Terminology Terminology
n  Literal   n  Variable   n  Key  word   Full  list?  
n  “hello  world”   n  D_  =  3.4   n  Import    
n  2   n  statement  =  “hello   n  while,  for   import  keyword  
n  5.678   world”   n  if,  elif,  else   keyword.kwlist  
n  3.141592653   n  math.pi   n  print    
n  ‘y’   n  myTuple  =  (3.4,2.5,1.2)   n  def   You  can’t  use  any  of  these  
n  True   n  mixedTuple  =   n   and,  or,  in,    is,  as     as  variable  or  function  
(math.pi,math.e,state names!  
n  assert  
ment)    
n  try,  except  

1  
5   6  

Data Types Casting to type


Given a number x
numbers  (integers,  floating  point)      abs(x)
  Returns the absolute value of x
characters,  Strings     int(x) Converts x to an integer
long(x) Converts x to a long integer
boolean,  (True  or  False…  1  or  0…..  Value  or  no  value)       float(x) Converts x to a floating point number
    str(x) Puts x into a string

-­‐  In  python  you  don’t  have  to  declare  the  type  it   You  can  also  use  math…  
automatically  happens…  but  if  you  WANT  a  specific    
type  you  need  to  cast  it  to  that  type.    There  are  built  
 
in  functions  for  this…  
We  can  have  more  control  with  the  string  by  
formatting  the  number…  

7   8  

Formatting to Print Formatted Printing


Given a x
number Given a floating point Number x

“%r”%x Creates a string containing a representation of the value of x as “%0f”%x Includes a leading 0 before the
it is stored in memory… as close as possible. number

“%10r”%x The same as above, but only what fits into 10 character spaces! “%.9f”%x Shows x as a floating point number
with 9 decimal places

“%s”%x Creates a string containing the value of x. If x is a floating point “%-10f”%x Left justifies the ‘field’ tha the
this may be less precise. numberis placed in.

“%d”%x Creates a string containing an integer representation of the value “%+10f”%x Shows a plus sign for positive
of x. (python site says you can also use ‘i’) numbers a negative sign for negative
numbers within the 10 character
“%f”%x Creates a string containing a floating point representation of the spaces allotted for the field.
value of x. If x is an integer and you do not say how many
decimal spaces to print? Testing says 6! “%10.6”%x Assigns 10 character spaces for the
field and shows 6 decimal spaces for
“%e”%x Scientific notation. Use this when you have super small, or x. Is right justified. If the number is
super large numbers. Floating point exponential format. Here TOO big for 10 space, it will go over.
also you would want to say how many decimal places to show.

2  
9   49  

What about Complex numbers? Operator Precedence (BEDMAS)


Operator  Type   Operators  
n  Ok  so  to  start  off  with  you’ve  got  j,  
Brackets   (  ),  abs(6),  x[3],  (1,2,3)  
which  is  a  literal,  but  CANNOT  STAND  
ALONE…   Exponentiation   2**4  

n  Then  you’ve  got  the  built  in  function   Unary  sign     +  len,  –  2**4  
complex…   Division,  Multiplication,   7  /  3,  7  //  3,  7  %  3,  7  *  3  
remainder  
Addition,  Subtraction   12  +  2,  6  -­‐  2.1  
              this functionality when
Use
you have formulas that Relational   <  <=  >  >=  !=  ==,  in,  is  
include the imaginary
number the root of -1  
Logical/Boolean   not  
and  
or  

11   12  

Built in Functions Import packages


n  For  our  purposes  so  
far  we  are  using  the  
math  and  cmath  
packages…  we’ll  
look  at  others  in  the  
second  half  of  the  
term.      
n  Toolbox  at  our  
disposal…  functions  
and  variables  
http://docs.python.org/2/library/functions.html  
 

3  
13   74  

While Loops While loop


n  Loop  through  a  set  of  calculations  until  the  control   #  put  initialization  statements  here  
structures  boolean  expression  evaluates  to  false.   while  expression  :                #  note  the  colon  
       statement  1                      #  indent  4  spaces  
n  Might  be  looping  until  a  user  input  is  of  a  specific  
       statement  2   As  long  as  expression  
type  
       ...   evaluates  to  True,  the  
n  Might  be  looping  until  a  calculated  value  fits  a          statement  n   indented  statements  will  be  
certain  specification          #  put  updates  here   executed,  in  a  loop  
 
#  un-­‐indented  statements  put  here  are  executed    
#  after  the  loop  is  complete  (that  is,  after  
#  expression  becomes  false).    
 

15   16  
Infinite Sums
– a particular kind of loop Tuples and Lists
n  Sum   n  Store  multiple  values  of  any  type  
n  Term   n  Tuples  Are  immutable,  lists  can  change  in  size  and  
n  Count  (sometimes)   content  
n  Calculation  inside  the  loop  calculates  a  term  and  adds   n  Allow  for  passing  multiple  values  back  from  a  
it  to  a  sum   single  function    
n  Watch  for  some  thing  about  the  term  that  is  fractal  
like…  linking  it  to  the  last  term.    How  are  the  terms   n  Tuple  …(  )  and  list…  []  
related?    Can  you  calculate  the  new  term  from  the  old   n  A  list  and  a  tuple  may  contain  the  same  values  but  
term?       they  would  not  be  considered  equal  in  a  boolean  
n  When  does  the  loop  stop?    The  new  term  ==  the  old   expression  
term?    The  new  term  is  so  small  ?      

4  
119   121  

Conversion to/from Strings [2] The range function


n  Casting  from  string  to  list  or  tuple  is  easy:   n  The  range  function  gives  a  list  of  evenly  spaced  integers  
tuple("team")  à  ('t',  'e',  'a',  'm')   range(10)  →  [0,  1,  2,  3,  4,  5,  6,  7,  8,  9]  
range(2,12)  →  [2,  3,  4,  5,  6,  7,  8,  9,  10,  11]  
list("team")    à  ['t',  'e',  'a',  'm']  
range(0,173,2)  →  [0,  2,  4,  6,  8,  …,  172]  
n  Going  back  to  string  is  harder   range(-­‐1)  →  [  ]  
str(tuple("team"))  à  "('t',  'e',  'a',  'm')"   range(-­‐5,  -­‐1,  2)  →  [-­‐5,  -­‐3]  
n  We'll  see  some  ways  later   range(7,  1,  -­‐3)  →  [7,  4]  
n  [sneak  preview]:   n  You  can  use  the  range  function  only  with  integers  
join  is  used  in  the  cypher  example!  
n  "".join(tuple("team"))  à  "team"  
n  You  never  get  the  last  item  in  the  sequence  
   Recall  in  example….   n  Number  of  entries  is  (last  –  first)  //  step  
n  See  QuizMaster  part  d!  

121   121  

Slices Slices
n  nums  =  range(10)   n  nums  =  [14,  32,  2,  6,  2,  18,  9,  5,  73,  28]  
n  nums  à  [0,  1,  2,  3,  4,  5,  6,  7,  8,  9]   n  nums  à  [14,  32,  2,  6,  2,  18,  9,  5,  73,  28]  
n  nums[0]  à  0   n  nums[0]  à  14  
n  nums[-­‐1]  à  9  #  same  as  length  -­‐  1   n  nums[-­‐1]  à  28  #  same  as  length  -­‐  1  
n  nums[2:5]  à  [2,  3,  4]   n  nums[2:5]  à  [2,  6,  2]  
n  nums[7:-­‐1]  à  [7,  8]   n  nums[7:-­‐1]  à  [5,  73]  
n  nums[7:  ]  à  [7,  8,  9]   n  nums[7:  ]  à  [5,  73,  28]  
n  nums[  :  4]  à  [0,  1,  2,  3]   n  nums[  :  4]  à  [14,  32,  2,  6]  
n  nums[  :  ]  à  [0,  1,  2,  3,  4,  5,  6,  7,  8,  9]   n  nums[  :  ]  à  [14,  32,  2,  6,  2,  18,  9,  5,  73,  28]  
n  nums[2:1]  à  [  ]   n  nums[2:1]  à  [  ]  

5  
21   22  

For Loop For Loop


n  Loop  through  something  
For i in range(1,23): i will be an integer that increases by
n  A  range   #statements one for every time through the loop
until it is larger than 23
n  A  list  
Dates = (“2013”,”2012”,”2011”) For each element of Dates set the
n  A  tuple   For date in Dates: variable date to point to it and do the
#statements following operations.
n  A  string  
text = “hello world” For each character in the string text
For nextChar in text: set the variable nextChar to point to it
#statements and do the following operations
n  Interates  a  specific  number  of  times  updating  a  variable  
to  a  new  value  every  time.    

23   24  

Nested Loops User Defined Functions


n  We  can  put  a  loop  inside  another  loop.   Options:    
n  Remember  that  the  inner  loop  is  executed  every   1.  write  code  then  transfer  it  into  a    function  or    
time  the  outer  loop  iterates…  be  sure  that  this  is   2.  define  input  and  output  of  code  with  default  test  
what  you  want…       output,  then  fill  in  code  after  test  framework  is  in  
n  Draw  a  rectangle   place    
n  Certain  search  algorithms  
In  either  case  you  want  to  build  from  simple  to  more  
n  Calculating  anything  based  on  a  matrix   complex.    Start  with  functions  do  not  call  any  other  
functions…  once  they  are  in  place  you  can  write  
other  functions  that  take  advantage  of  the  earlier  
ones  you  created.  

6  
25   26  

User Defined Functions User Defined Functions


Questions  to  ask  yourself:   More  questions  and  steps  
1.  What  are  the  input  types?   1.  Are  there  any  intermediary  calculations?  

2.  What  are  the  output  types?   2.  Any  constant  values  required?  
  3.  Calculate  the  output  using  formula  or  algorithm  
4.  Test  the  result  and  fix  errors  
n  If  you  are  hand  coding,  mentally  run  through  your  
code  as  if  you  were  the  computer.  
Make  sure  you’ve  identiGied  what  you  are  returning  and  include   n  Try  various  input  values.  
that  as  soon  as  you  deGine  your  function.    If  the  function  is   5.  Make  changes  as  necessary  and  repeat  
printing  out  and  not  returning  identify  that  in  comments.      

27   28  

Why User Defined Functions? List Comprehension


  Combine  defining  a  list  with  a  loop  that  does  
n  Readability   operations  on  a  list  contents.  
n  Reusability     Takes  advantage  of  For  loops  &    ranges,  consists  of:      
n  Break  down  big  problems  into  smaller    more   1.  The  list  variable  name  =    
manageable  ones   2.  The  operation  that  calculates  the  value  to  add  to  
the  new  list  
n  Split  up  work  among  multiple  people  
3.  For  loop  that  iterates  over  an  existing  list  (or  tuple  
n  Maintenance  –  when  an  operation  needs  to  be   or  string  or  range)  
updated  you  only  have  to  update  it  in  one  place  
The  loop  is  embedded  in  the  declaration  of  the  new  
list.  

7  
29   30  

List Comprehension if,elif,else


n  Test  boolean  expressions    
n  If  (expression)  :  
 
Following  elif  and  else  statements  are  only  tested  if  
the  earlier  expression  is  false.  
 
Be  CAREFUL  about  spacing  and  what  statements  
might  separate  if/elif  ‘ladder’  

31   173  

if,elif,else What if there are several possibilities?


n  You  can  have  one  if,  multiple  elif  parts,  and  one  
 
else  in  a  conditional  statement  
n  Simple  if  statement  can  filter  and  update  a  sentinal  
n  put  short  error  conditions  first  for  readability  
value.    
if    age  <  1  :  
         print  "%d  is  too  small;  using  1"  %  age  
n  Use  a  series  of  if,  multiple  elif,    to  test  for  multiple          age  =  1  
possible  values  with  multiple  outcomes…  the  else   elif  age  >  100  :  
provides  a  default  case.          print  "%d  is  too  big;  using  100"  %  age  
       age  =  100  
else  :  
       print  "%d  is  a  wonderful  age!"  %  age  

8  
33   34  

User Input Managing Possible Errors


n  Sys  input  will  not  be  covered  on  term  test.   n  Keyword  assert  
n  Followed  by  conditional  statement  –  this  statement  
must  be  true,  if  it  is  false  then  the  code  will  stop  
 input  =  raw_input(“prompt  the  user  for  input”)  
n  Followed  by  optional  output  string  –  the  output  
 
string  allows  the  coder  to  provide  meaningful  
n  raw_input  will  always  return  a  string  value.    You   information  about  why  the  program  stopped  
need  to  validate  this  input  so  that  you  can  prevent   working  
errors  in  your  code.  
n  Tell  the  user  what  sort  of  input  you  want.    Loop  
your  prompt  until  you  get  the  right  kind  of  input.    

35   36  

Managing Possible Errors Managing Possible Errors


n  Try  Catch  Block  –  Keywords  try  and  except   n  Try  Catch  Block  
n  Allows  for  the  coder  to  surround  a  set  of  code  in  a   n  Example  
block  and  provide  some  context  if  any  function  calls  
within  the  block  should  fail  
n  Used  when  the  calls  within  the  block  attempt  
actions  where  things  are  outside  the  main  codes  
control:      
n  accessing  files  which  may  or  may  not  exist    
n  processing  user  in  put  which  may  or  may  not  be  the  
correct  format    

Here  for  your  own  reference.  

9  
37   38  

Infinite Sum Infinite Sums

cos( ) = + + ... n  Review  the  various  incarnations  of  infinite  sums  
! ! ! ! n  Understand  how  these  can  be  efficiently  coded  
n  Consider  how  each  term  builds  of  the  last  term  
n  the  sum  is  simply  sum  +  term  for  however  many  
terms  –  same  for  each  
n  But  the  term  calculation  is  different  for  each  
series…  practice  on  a  few  series…  you  can  even  
look  up  some  series  online  to  get  practice  –  
compare  your  answer  to  math.cos,  math.sin,  
math.arcsin  etc      …        

Topics 3   40  

Week
Topic
Event

Numpy Arrays
0   Introduction   A1  posted  
1   Basics:  Expressions  and  Scripts   Weekly  labs  start   n  Arrays  allow  for  vectorization…  doing  operations  
2   while  Loops  and  Infinite  Sums  
on  large  sets  of  data  all  at  once  (or  at  least  
3   Lists  and  Tuples   A2  posted  
4   for  Loops   A1  due   seeming  to  us)  
5   Functions  and  if  …  else   n  What  is  different  when  you  are  calculating  for  a  
6   User  interactions   A2  due,  A3  posted   scalar  vs  calculating  for  an  array?    
7   Review  
8   Mid  Term    &  Start  Arrays   Mid  Term  Wed  Oct  30   n  Calculating  a  list  vs  calculating  for  an  array?  
9   Arrays    A3  due,  A4  posted    
10   Curve  plotting   VW  deadline  
n  If  you  want  to  do  vector  arithmetic  you  cannot  use  
11   Pseudorandom  numbers  
math  library  you  must  use  numpy  library  
12   String  processing   A4  due  
Final Exam
Dec  12  9AM  

10  
41   42  
We can switch between lists and
Lists vs numpy arrays arrays
List Array
Similarities
Uses slice notation [a : b : c] uses slice notation [a : b : c]
Apply functions len, .sort Apply functions len, .sort
Apply operators is, in Apply operators is, in
Mutible, can change contents Mutable, can change contents
a, b, c, d, e = range 5 a, b, c, d, e = np. arange(5)
Differences
Any collection of types All entries must be the same type
+ concatenates; * repeates +, *, / … operate term by term
Functions append, insert, remove Size is fixed (see np, repeat, np.resize())

Generate with range, list comprehension, Generate with zeros, arrange, linspace, + numerical
append, + * operations

y = x[a:b] # a copy of the list data y = x[a:b] is the same array data
Use math library functions Use numpy library functions

43   44  

Array Creation Arithmetic


n  Use  *  /  +  -­‐    -­‐  operate  on  a  array  and  give  back  an  
array  
n  Also  use  np.ceil,  np.sqrt,  np.max,  np.cos,  np.sin  to  
operate  on  an  array  
n  np.cos(arrayVariable)  gives  a  new  array  full  of  the  
cos  of  each  item  in  the  original.  
n  But!  
n  np.max(arrayVariable)  –  returns  a  scalar,  the  max  
value  from  the  array  
know  what  the  numpy  math  functions  do  

11  
45   46  

Examples Passing a function as a Parameter

Acceptable Functions Unacceptable

47   48  

Plotting Examples Plotting Examples – Two figures

12  
49   50  

Plotting Example - Historgram Probability Theory Concepts


n  Probabilistic  or  stochastic  experiments  have  
unpredictable  results  (opposite  of  deterministic)  
n  Sample  space  –  set  of  all  possible  outcomes  
n  Elementary  outcome  –  each  one  of  the    specific  
possible    outcomes  
n  Event  –  a  specific  outcome  in  a  specific  time  and  
place  (could  be  an  experiment)  

n  These  feed  into  probability  formula  to  provide  a  


likelyhood  specific  event  occurring  given  the  
possible  outcomes  in  a  sample  space  

51   52  

Simulating Stochastic Events Generate Pseudo Random Numbers


Random – single random values Numpy.random – Array of random
the number of outcomes in E E values
P( E ) = Pr{ x ∈ E} = = import  random   import  numpy  as  np  
the total number of outcomes in S S
random.random()  #float  between  0  and  1   np.random.random(99)    #99  floats  
between  0  and  1  
random.randrange(aa,bb)    #float  
bettween  aa  and  bb  
Depending  on  the  sample  space  we  can  generate  pseudo  
Random.randint(aa,bb)  #int  between  aa   np.random.randint(aa,bb,99)  #99  
random  events,  then  plot  these  events  and  normalize  the   and  bb   integers  between  aa  and  bb  

plot  to  see  the  probability  of  each.    Thus  we  take   random.seed(12345)      np.random.seed(12345)  
   
advantage  of  computers  to  simulate  stochastic,   #the  code  will  always  produce  the  same   #note  that  you  could  pass  in  something  

unpredictable  occurrences.   series  of  numbers  if    put  a  literal  


here  –  good  for  debugging  purposes  
variable  like  the  date/time  here  and  
simply  take  control  of  how  the  random  
numbers  are  generated  

13  
53   54  

Graphing Monty Hall Problem Graph of Monty Hall Problem

55   56  

Reading a File Reading a File

n  Put  file  to  be  read  in  the  same  folder  as  the  python   n  Now  we  just  need  the  file  name  and  we  can  open  
script  file   and  read  the  file  quite  simply…  
n  Import  items  to  help  find  the  file  

n  Include  line  of  code  pointing  path  to  the  


appropriate  folder  
 
   

14  
256   58  

String Features As Scripts and Programs Get Large


n  File  reading:  open  and  read  a  text  file   n  Break  Up  the  Problem…  make  yourself  an  outline  
n  split:  separate  a  text  string  into  words   n  Consider  Top  Down  Programming…  
n  join:  combine  multiple  text  strings  together  into  a   n  Make  sure  you  have  the  structure  in  place  then  you  
long  string  with  a  common  separator   can  fill  in  details  
n  strip:  remove  extra  characters  from  the  ends  of  a   n  Review  CompareBooks.py    
string  
n  upper:  change  every  letter  in  a  string  to  upper  case  

258   raw_input 259  


open
getBookText
CompareBooks.py close
list
readBook simplifyChar
simplifyText
n  Now  examine  CompareBooks.py   split
upper
join
n  check  main,  the  overall  organizer   strip
countWords
n  check  the  individual  functions   zip
sort

n  What  to  look  for?   printWords sort


reversed
n  each  function  should  have  a  simple,  clear  purpose   main countWords As  you  go  further  right  in  
merge
the  structure  chart,  you  
n  no  function  should  be  too  short  (making  it   sort
Gind  more  and  more  
printMerged reversed
unnecessary)  or  too  long  (break  it  up)   reversed
standard  functions;  good  
n  the  argument  lists  and  return  values  should  be  clear   plt.hist
engineering  design  often  
means  Ginding  ways  of  
and  simple       plt.title
assembling  existing  
plotMerged plt.show
n  And  check  out  how  to  process  strings   components  to  solve  new  
theEnd plt.loglog
problems    
plt.xlabel
COMP1012  plt.ylabel
Fall  2013  

15  
61   62  

Final exam: 50 marks, 3 hours Studying


n  Approx  10  marks:  Predict  the  output   n  Studies  have  shown…  
n  more  than  half  from  QuizMaster   n  recall  is  better  in  the  same  environment  under  the  
n  Approx  10  marks:  Multiple  Choice   same  conditions  that  you  learned  the  material  
n  Approx  5  marks:  Debugging   n  so  reduce  the  differences  between  study  conditions  
(posture,  music,  etc.)  and  exam  conditions  
n  find  inserted  defects  in  code  similar  to  that  in  the  
notes  or  sample  solutions   n  better:  study  in  a  variety  of  conditions  and  locations  
n  Approx  25  marks:  Programming   n  rehearsal:  practise  the  activity  you  will  be  tested  on  
n  on  paper   n  write  out  programs  by  hand,  not  just  on  the  computer  
n  similar  to  code  in  programs  on  the  website  (e.g.,  in   n  if  you  did  not  get  great  assignment  marks,  review  the  
sample  solutions,  notes,  sample  code)   posted  solutions,  not  your  own  
n  You  will  get  a  copy  of  the  latest  Python  Guide   n  http://www.nytimes.com/2010/09/07/health/views/
07mind.html?_r=1&pagewanted=all    

63   64  

EXAM TIPS What to take


n  Circle  or  underline  information  in  the  question  that   n  Final  exam:  
relates  to  variables  –  input,  output,  constants,   n  Take  ID  (student  card  preferred)  or  a  winning  smile  
steps  in  the  formula  or  algorithm   n  Take  at  least  2  pencils  and  2  good  erasers  
n  Use  your  python  guide!   n  Take  water  
n  Watch  for  instructions  about  what  math  package   n  Take  fruit/candy  for  quick  energy  
or  built  in  functions  you  may  or  may  not  use  in   n  No  aids:  do  NOT  take  a  calculator,  translator,  iPod,  
programming  questions.   cellphone,  or  any  other  electronic  device  
n  Your  pack/books  will  be  left  all  alone  at  the  front  of  
the  room  
n   Answer  the  questions  and  then  go  back  to  double  
check….  Something  is  always  better  than  nothing.  

16  

You might also like