Discrete Structures Lab 1 Python Basics: 1 Python Installation 2 Python Tutorial
Discrete Structures Lab 1 Python Basics: 1 Python Installation 2 Python Tutorial
DISCRETE STRUCTURES
Lab 1
Python Basics
Trần Hồng Tài
Abstract
Welcome to Python, a popular modern programing language that
widely use in research and industry alike. In this Laboratory, we will
introduce how to start with Python, basic features of Python via repro-
gramming common calculations and algorithms.
1 Python Installation
2 Python Tutorial
We will use the Python programming language for all assignments in this course.
Python is a great general-purpose programming language; this section will serve
as a quick crash course on the Python programming language. Also, any basic
Python features can be found introduce in this documentation. The content of
this section is as follows:
Elit.tdtu.edu.vn 1
TON DUC THANG UNIVERSITY
Faculty of Information Technology
y = 2.5
print ( type ( y ) ) # Prints " < class ’ float ’ >"
print (y , y + 1 , y * 2 , y ** 2 ) # Prints " 2 . 5 3 . 5 5 . 0 6 . 25 "
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 ) ) # Prints " < class ’ bool ’ >"
print ( t and f ) # Logical AND ; prints " False "
print ( t or f ) # Logical OR ; prints " True "
print ( not t ) # Logical NOT ; prints " False "
print ( t ! = f ) # Logical XOR ; prints " True "
2.2 Containers
Python includes several built-in container types: lists, dictionaries, sets, and
tuples.
2.2.1 List
A list is the Python equivalent of an array, but is resizeable and can contain
elements of different types:
Elit.tdtu.edu.vn 2
TON DUC THANG UNIVERSITY
Faculty of Information Technology
xs = [3 , 1 , 2 ] # Create a list
print ( xs , xs [ 2 ] ) # Prints "[ 3 , 1 , 2 ] 2 "
print ( xs [ - 1 ] ) # N eg at i v e indices count from the end of the list
; prints " 2 "
xs [ 2 ] = ’ foo ’ # Lists can contain e l e m e n t s of d i f f e r e n t types
print ( xs ) # Prints "[ 3 , 1 , ’ foo ’]"
xs . append ( ’ bar ’) # Add a new element to the end of the list
print ( xs ) # Prints "[ 3 , 1 , ’ foo ’, ’ bar ’]"
x = xs . pop () # Remove and return the last element of the list
print (x , xs ) # Prints " bar [3 , 1 , ’ foo ’]"
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 ’]
for idx , animal in enumerate ( animals ) :
print ( ’# % d : % s ’ % ( idx + 1 , animal ) )
# Prints "# 1 : cat " , "# 2 : dog " , "# 3 : monkey " , each on its own line
Elit.tdtu.edu.vn 3
TON DUC THANG UNIVERSITY
Faculty of Information Technology
2.2.2 Dictionary
A dictionary stores pairs of (key, value). You can use it like this:
d = { ’ cat ’: ’ cute ’ , ’ dog ’: ’ furry ’} # Create a new d i c t i o n a r y with
some data
print ( d [ ’ cat ’] ) # Get an entry from a d i c t i o n a r y ; prints "
cute "
print ( ’ cat ’ in d ) # Check if a d i c t i o n a r y has a given key ;
prints " True "
d [ ’ fish ’] = ’ wet ’ # Set an entry in a d i c t i o n a r y
print ( d [ ’ fish ’] ) # Prints " wet "
# print ( d [ ’ monkey ’]) # K e y E r r o r : ’ monkey ’ not a key of d
print ( d . get ( ’ monkey ’ , ’N / A ’) ) # Get an element with a default ;
prints " N / A "
print ( d . get ( ’ fish ’ , ’N / A ’) ) # Get an element with a default ;
prints " wet "
del d [ ’ fish ’] # Remove an element from a d i c t i o n a r y
print ( d . get ( ’ fish ’ , ’N / A ’) ) # " fish " is no longer a key ; prints " N /
A"
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 . items () :
print ( ’A % s has % d legs ’ % ( animal , legs ) )
# Prints " A person has 2 legs " , " A cat has 4 legs " , " A spider has 8
legs "
Elit.tdtu.edu.vn 4
TON DUC THANG UNIVERSITY
Faculty of Information Technology
nums = [0 , 1 , 2 , 3 , 4 ]
e v e n _ n u m _ t o _ s q u a r e = { x : x ** 2 for x in nums if x % 2 = = 0 }
print ( e v e n _ n u m _ t o _ s q u a r e ) # Prints " { 0 : 0 , 2 : 4 , 4 : 16 } "
2.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 element is in a set ; prints
" True "
print ( ’ fish ’ in animals ) # prints " False "
animals . add ( ’ fish ’) # Add an element to a set
print ( ’ fish ’ in animals ) # Prints " True "
print ( len ( animals ) ) # Number of e l e m e n t s in a set ; prints " 3 "
animals . add ( ’ cat ’) # Adding an element that is already in
the set does nothing
print ( len ( animals ) ) # Prints " 3 "
animals . remove ( ’ cat ’) # Remove an element from a set
print ( len ( animals ) ) # Prints " 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 enumerate ( 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 ) # Prints " {0 , 1 , 2 , 3 , 4 , 5 } "
2.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 ) } # Create a d i c t i o n a r y with
tuple keys
t = (5 , 6 ) # Create a tuple
print ( type ( t ) ) # Prints " < class ’ tuple ’ >"
print ( d [ t ] ) # Prints " 5 "
print ( d [ (1 , 2 ) ] ) # Prints " 1 "
Elit.tdtu.edu.vn 5
TON DUC THANG UNIVERSITY
Faculty of Information Technology
2.3 Function
Python functions are defined using the def keyword. For example:
def sign ( x ) :
if x > 0 :
return ’ positive ’
elif x < 0 :
return ’ negative ’
else :
return ’ zero ’
for x in [ -1 , 0 , 1 ] :
print ( sign ( x ) )
# Prints " n e g a t i v e " , " zero " , " p o s i t i v e "
We will often define functions to take optional keyword arguments, like this:
def hello ( name , loud = False ) :
if loud :
print ( ’ HELLO , % s ! ’ % name . upper () )
else :
print ( ’ Hello , % s ’ % name )
2.4 Class
The syntax for defining classes in Python is straightforward:
class Greeter ( object ) :
# Constructor
def __init__ ( self , name ) :
self . name = name # Create an i n s t a n c e v a r i a b l e
# I ns t a n c e method
def greet ( self , loud = False ) :
if loud :
print ( ’ HELLO , % s ! ’ % self . name . upper () )
else :
print ( ’ Hello , % s ’ % self . name )
Elit.tdtu.edu.vn 6
TON DUC THANG UNIVERSITY
Faculty of Information Technology
3 Exercises
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
4 2
+
(d) 6 6
5 1
+
2 2
14
(e) +7
2
5∗2
(f)
5 − 20 ∗ 32 + 30
2. Print the expression from 1. with their result as a string; for example (a)
will be printed as: 15*2+7*8=86
Elit.tdtu.edu.vn 7
TON DUC THANG UNIVERSITY
Faculty of Information Technology
4 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
Elit.tdtu.edu.vn 8