Lab 1 - Python Review
Lab 1 - Python Review
Note: Unlike many languages, Python does not have unary increment (x++) or
decrement (x–) operators.Python also has built-in types for complex numbers;
Booleans: Python implements all of the usual operators for Boolean logic, but uses
English words (and, or, etc.) rather than symbols (&&, ||, etc.):
t = True
f = False
print ( type ( t ) ) # P r in ts " < class ’ bool ’ >"
print ( t and f ) # Log ic al AND ; p r in ts " Fal se "
print ( t or f ) # Log ic al OR ; p r in ts " T r ue "
print ( not t ) # Log ic al NOT ; p r ints " F alse "
print ( t ! = f ) # Log ic al XOR ; p r in ts " T rue "
1
TON DUC THANG UNIVERSITY
Faculty of Information Technology
print ( s . capit al ize () ) # C a p ita l iz e a s tr ing ; p r in ts " Hello "
print ( s . upper () ) # Co n ver t a s tr ing to u p p e r c a s e ; p r in ts "
HELLO "
print ( s . rjust ( 7 ) ) # Right - j u s tif y a string , p a dd ing w ith
spa ce s; prints " hello "
print ( s . center ( 7 ) ) # Ce n ter a string , p a dd ing with s pace s ;
prints " hello "
print ( s . replace ( ’l ’, ’( ell ) ’) ) # Rep lace all i n s t a n c e s of one
s u b s tr i n g with a no the r ;
print ( ’ world ’. strip () ) # Str ip le a d ing and tr a iling w h i te s p a c e ;
p r in ts " world "
2. Containers
Python includes several built-in container types: lists, dictionaries, sets, and tuples.
2.1. List
A list is the Python equivalent of an array, but is resizeable and can contain elements
of different types:
xs = [3 , 1 , 2 ] # Create a list
print ( xs , xs [ 2 ] ) # P r in ts "[ 3 , 1 , 2 ] 2 "
print ( xs [ - 1 ] ) # Neg a tive in d ice s count from the end of the lis t; prints " 2 "
xs [ 2 ] = ’ foo ’ # L is ts can co nta in ele m en ts of d if f e r e n t ty pes
print ( xs ) # P r in ts "[ 3 , 1 , ’ foo ’]"
xs . append ( ’ bar ’) # Add a new ele men t to the end of the l is t
print ( xs ) # P r in ts "[ 3 , 1 , ’ foo ’, ’ bar ’]"
x = xs . pop () # Re mo ve and re tur n the last eleme n t of the lis t
print (x , xs ) # P r in ts " bar [3 , 1 , ’ foo ’]"
Slicing: In addition to accessing list elements one at a time, Python provides concise
syntax to access sublists; this is known as slicing:
nums = list ( rang e ( 5 ) ) # r an ge is a built - in f un ction tha t
creates a list of integers
print ( nums ) # Prin ts "[0 , 1 , 2 , 3 , 4 ]"
print ( nums [ 2 : 4 ] ) #Get a slice from index 2 to 4 (exclusive ); prints "[2 , 3 ]"
print ( nums [ 2 : ] ) #Get a slice from index 2 to the end ; prints "[2 , 3 , 4 ]"
print ( nums [ : 2 ] ) #Get a slice from the start to index 2 (exclusive ); prints "[0 , 1 ]"
print ( nums [ : ] ) #Get a slice of the whole list ; prints"[0 , 1 , 2 , 3 , 4 ]"
print ( nums [ : - 1 ] ) #Slice indices can be negative ; prints"[0 , 1 , 2 , 3 ]"
nums [ 2 : 4 ] = [ 8 , 9 ] # As sign a new s u bli s t to a slice
print ( nums ) # Prin ts "[0 , 1 , 8 , 9 , 4 ]"
We will see slicing again in the context of numpy arrays. Loops: You can loop over the
elements of a list like this:
animals = [ ’ cat ’, ’ dog ’, ’ monkey ’] for animal in
animals :
print ( animal )
# Prints " cat", " dog", " monkey ", each on its own line .
If you want access to the index of each element within the body of a loop, use the built-
in enumerate function:
animals = [ ’ cat ’, ’ dog ’, ’ monkey ’]
2
TON DUC THANG UNIVERSITY
Faculty of Information Technology
for idx , animal in en ume rate ( animals ) :
print ( ’# % d : % s ’ % ( idx + 1 , animal ) )
# P r in ts "# 1 : cat " , "# 2 : dog " , "# 3 : mon ke y " , eac h on its own line
2.2. Dictionary
A dictionary stores pairs of (key, value). You can use it like this:
d = { ’ cat ’: ’ cute ’, ’ dog ’: ’ furry ’} # C re a te a new d ic tio n a r y w ith
some da ta
print ( d [ ’ cat ’] ) # Get an entr y fro m a d i c tio n a r y ; p r in ts "
cute "
print ( ’ cat ’ in d ) # Check if a d ic tio n a r y has a given key ;
prints " True "
d [ ’ fish ’] = ’ wet ’ # Set an entr y in a d ic t io n a r y
print ( d [ ’ fish ’] ) # P r in ts " wet "
# print( d[’ monkey ’]) # Key Error: ’ monkey ’ not a key of d
print ( d . get ( ’ monkey ’, ’N / A ’) ) # Get an ele me n t w ith a def aul t ;
prints " N/ A"
print ( d . get ( ’ fish ’, ’N / A ’) ) # Get an ele me n t w ith a def aul t ;
p r in ts " wet "
del d [ ’ fish ’] # Re mo ve an ele me n t fro m a d ic tio n a r y
print ( d . get ( ’ fish ’, ’N / A ’) ) # " fis h " is no lo nge r a key ; p r in ts " N/
A"
3
TON DUC THANG UNIVERSITY
Faculty of Information Technology
If you want access to keys and their corresponding values, use the items method:
d = { ’ person ’: 2 , ’ cat ’: 4 , ’ spider ’: 8 }
for animal , legs in d . it ems () :
print ( ’A % s has % d legs ’ % ( animal , legs ) )
# Prints " A person has 2 legs", " A cat has 4 legs", " A spider has 8
legs"
Dictionary comprehensions: These are similar to list comprehensions, but allow you
to easily construct dictionaries. For example:
nums = [0 , 1 , 2 , 3 , 4 ]
e ve n _n u m_ t o_ s qu a re = { x : x ** 2 for x in nums if x % 2 = = 0 }
print ( ev e n_ n um _ to_s q ua r e ) # P r in ts " { 0 : 0 , 2 : 4 , 4 : 16 } "
2.3. Set
A set is an unordered collection of distinct elements. As a simple example, consider the
following:
animals = { ’ cat ’, ’ dog ’}
print ( ’ cat ’ in animals ) # Check if an ele me nt is in a set ; p r ints
" True "
print ( ’ fish ’ in animals ) # p r in ts " Fal se "
animals . add ( ’ fish ’) # Add an ele me nt to a set
print ( ’ fish ’ in animals ) # P r in ts " T rue "
print ( len ( animals ) ) # Nu m be r of eleme n ts in a set ; p r in ts " 3 "
animals . add ( ’ cat ’) # Add ing an ele me n t tha t is al re ad y in
the set does nothing
print ( len ( animals ) ) # P r in ts " 3 "
animals . remove ( ’ cat ’) # Re mo ve an ele me n t fro m a set
print ( len ( animals ) ) # P r in ts " 2 "
Loops: Iterating over a set has the same syntax as iterating over a list; however since sets
are unordered, you cannot make assumptions about the order in which you visit the
elements of the set:
animals = { ’ cat ’, ’ dog ’, ’ fish ’}
for idx , animal in en ume rate ( animals ) :
print ( ’# % d : % s ’ % ( idx + 1 , animal ) )
# Prints "# 1 : fish ", "# 2 : dog", "# 3 : cat"
Set comprehensions: Like lists and dictionaries, we can easily construct sets using
set comprehensions:
from math import sqrt
nums = { int ( sqrt ( x ) ) for x in range ( 30 ) }
print ( nums )# P r in ts " {0 , 1 , 2 , 3 , 4 , 5 } "
4
TON DUC THANG UNIVERSITY
Faculty of Information Technology
2.4. Tuples
A tuple is an (immutable) ordered list of values. A tuple is in many ways similar to a list;
one of the most important differences is that tuples can be used as keys in dictionaries
and as elements of sets, while lists cannot. Here is a trivial example:
d = { (x , x + 1 ) : x for x in range ( 10 ) } # C re a te a d ic tio n a r y w ith
tuple keys
t = (5 , 6 ) # Create a tuple
print ( type ( t ) ) # P r in ts " < clas s ’ tu ple ’ >"
print ( d [ t ] ) # P r in ts " 5 "
print ( d [ (1 , 2 ) ] ) # P r in ts " 1 "
3. Function
Python functions are defined using the def keyword. For example:
def sign ( x):
if x > 0 :
return ’ p osi ti ve ’
elif x < 0 :
return ’ n ega ti ve ’
else :
return ’ zero ’
for x in [ -1 , 0 , 1 ] :
print ( sign ( x ) )
# Prints " negative ", " zero ", " positive "
We will often define functions to take optional keyword arguments, like this:
def hello ( name , loud = Fal se ) :
if loud :
print ( ’ HELLO , % s ! ’ % name . upper () )
else :
print ( ’ Hello , % s ’ % name )
4. Class
The syntax for defining classes in Python is straightforward:
class Greeter ( object ) :
# Constr uct or
def _ _i nit __ ( self , name ) :
self . name = name # C re a te an in s ta nce v a r ia ble
# Instance method
def greet ( self , loud = Fal se ) :
if loud :
print ( ’ HELLO , % s ! ’ % self . name . upper () )
else :
print ( ’ Hello , % s ’ % self . name )
5
TON DUC THANG UNIVERSITY
Faculty of Information Technology
5. Exercises
Exercise 1:
Calculate and print the following expressions using python:
(a) 15 ∗ 2 + 7 ∗ 8
(b) 20 − 15 + 15 ∗ 2
(c) 20 + 30 − 3 ∗ 15 + 5 ∗ 52
(d)
(e) 14/2 + 7
(f)
Exercise 2:
Print the expression from 1. with their result as a string; for example (a) will be printed
as: 15*2+7*8=86
Exercise 3:
Write a function S=sumN(n) to calculate the sum from 0 to n; for example sumN(2)
should return 0+1+2=3; sumN(-5) should return 0+(-1)+(- 2)+(-3)+(-4)+(-5)=-15
Exercise 4:
Write a function to print an input string then:
(a) Remove all space (" ") then print the result string
(b) Replace all space (" ") with “_” then print the result string
Hint: Use A=Input(“Input your string:”) to input a string to A from key- board.
Use B=A.split() to make a list of words from a string for processing.
Use C=" ".join(B) to merge the list back into a string with a blank space " " between
words.
Exercise 5:
Write a function to calculate an operation between 2 positive integers using If for
different operators cases. For example, input: 1+2 -> output: 3; input: 2*3 -> output: 6;.
. . the possible input operators are: +, -, *, /,%,^.
Hint: you will need to separate the input string into 3 sub-strings: first number;
operator; second number.
6
TON DUC THANG UNIVERSITY
Faculty of Information Technology
Hint2: to convert a string such as str1=”23” to number we use num-ber1=int(str1) to get
number1=23
Exercise 6:
Write a function to do the same job as previous exercise but using Dictio- nary instead of
If.
Exercise 7:
Write a function to calculate summation of 2 matrices C=mSum(A,B) where A,B,C
are lists used to representation 3 matrices; if the product can’t be calculate due to
matrix size print:"Matrix dimension error". Hint: the summation of matrix A size m
× n and B size m × n is matrix C size m × n where: Ci,j = Ai,j + Bi,j
Exercise 8:
Write a function to calculate product of 2 matrices C=mProd(A,B); if the product
can’t be calculate due to matrix size print:"Matrix dimension error". Hint: the product of
matrix A size m × n and B size n × q is matrix C size m × q where:
Exercise 9:
Write functions to combine 2 strings p,q represent 2 statements whose first words are the
subjects using:
(a) "if p, then q"result=ithCombine(p,q).
(b) "p, and not q"result=panqCombine(p,q).
(c) "not p, or q"result=npoqCombine(p,q)
for example: p="it sunny", q="I go camping" will give the output
(a) if it sunny, then I go camping
(b) it sunny and I not go camping
(c) it not sunny, or I go camping
6. Reference
[1] Johan Nordlander. Discrete Mathematics through the eyes of a Python pro- grammer
staff. www.ltu.se/ tomas/MAM200-Python1.pdf
[2] Ralph P. Grimaldi. Discrete and Combinatorial Mathematics: An Applied
Introduction, Fifth Edition. Pearson, 2003.
[3] Justin Johnson. Python Tutorial. http://cs231n.github.io/python-numpy-
tutorial/python-basic