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

Discrete Structures Lab 1 Python Basics: 1 Python Installation 2 Python Tutorial

This document introduces Python basics including data types, containers, and common operations. It discusses numeric, string, boolean, list, and dictionary data types. It provides examples of basic operations on each type such as arithmetic operations, string methods, list indexing/slicing, and dictionary lookup. The document also introduces loops and comprehensions for iterating over and transforming container elements.

Uploaded by

huy phan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
126 views

Discrete Structures Lab 1 Python Basics: 1 Python Installation 2 Python Tutorial

This document introduces Python basics including data types, containers, and common operations. It discusses numeric, string, boolean, list, and dictionary data types. It provides examples of basic operations on each type such as arithmetic operations, string methods, list indexing/slicing, and dictionary lookup. The document also introduces loops and comprehensions for iterating over and transforming container elements.

Uploaded by

huy phan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

TON DUC THANG UNIVERSITY

Faculty of Information Technology

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:

2.1 Basic data types


Like most languages, Python has a number of basic types including integers,
floats, booleans, and strings. These data types behave in ways that are familiar
from other programming languages.
Numbers: Integers and floats work as you would expect from other languages:
x = 3
print ( type ( x ) ) # Prints " < class ’ int ’ >"
print ( x ) # Prints " 3 "
print ( x + 1 ) # Ad d i t i o n ; prints " 4 "
print ( x - 1 ) # S u b t r a c t i o n ; prints " 2 "
print ( x * 2 ) # M u l t i p l i c a t i o n ; prints " 6 "
print ( x ** 2 ) # E x p o n e n t i a t i o n ; prints " 9 "
x += 1
print ( x ) # Prints " 4 "
x *= 2
print ( x ) # Prints " 8 "

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 "

Strings: Python has great support for strings:

hello = ’ hello ’ # String l i te r a l s can use single quotes


world = " world " # or double quotes ; it does not matter .
print ( hello ) # Prints " hello "
print ( len ( hello ) ) # String length ; prints " 5 "
hw = hello + ’ ’ + world # String c o n c a t e n a t i o n
print ( hw ) # prints " hello world "
hw12 = ’% s % s % d ’ % ( hello , world , 12 ) # sprintf style string
formatting
print ( hw12 ) # prints " hello world 12 "

String objects have a bunch of useful methods; for example:


s = " hello "
print ( s . capitalize () ) # C a p i t a l i z e a string ; prints " Hello "
print ( s . upper () ) # Convert a string to u p p e r c a s e ; prints "
HELLO "
print ( s . rjust ( 7 ) ) # Right - justify a string , padding with
spaces ; prints " hello "
print ( s . center ( 7 ) ) # Center a string , padding with spaces ;
prints " hello "
print ( s . replace ( ’l ’ , ’( ell ) ’) ) # Replace all i n s t a n c e s of one
s u b s t r i n g with another ;
print ( ’ world ’. strip () ) # Strip leading and t r a i l i n g w h i t e s p a c e ;
prints " world "

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 ’]"

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 ( range ( 5 ) ) # range is a built - in f u n c t i o n that
creates a list of i n t e g e r s
print ( nums ) # Prints "[ 0 , 1 , 2 , 3 , 4 ]"
print ( nums [ 2 : 4 ] ) # Get a slice from index 2 to 4 (
e x c l u s i v e ) ; 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 (
e x c l u s i v e ) ; 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 n e ga t i v e ; prints
"[ 0 , 1 , 2 , 3 ]"
nums [ 2 : 4 ] = [8 , 9 ] # Assign a new sublist to a slice
print ( nums ) # Prints "[ 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 ’]
for idx , animal in enumerate ( animals ) :
print ( ’# % d : % s ’ % ( idx + 1 , animal ) )
# Prints "# 1 : cat " , "# 2 : dog " , "# 3 : monkey " , each on its own line

List comprehensions: When programming, frequently we want to transform


one type of data into another. As a simple example, consider the following code
that computes square numbers:
nums = [0 , 1 , 2 , 3 , 4 ]
squares = [ ]
for x in nums :
squares . append ( x ** 2 )
print ( squares ) # Prints [0 , 1 , 4 , 9 , 16 ]

Elit.tdtu.edu.vn 3
TON DUC THANG UNIVERSITY
Faculty of Information Technology

You can make this code simpler using a list comprehension:


nums = [0 , 1 , 2 , 3 , 4 ]
squares = [ x ** 2 for x in nums ]
print ( squares ) # Prints [0 , 1 , 4 , 9 , 16 ]

List comprehensions can also contain conditions:


nums = [0 , 1 , 2 , 3 , 4 ]
even_squares = [ x ** 2 for x in nums if x % 2 = = 0 ]
print ( even_squares ) # Prints "[ 0 , 4 , 16 ]"

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"

Loops: It is easy to iterate over the keys in a dictionary:


d = { ’ person ’: 2 , ’ cat ’: 4 , ’ spider ’: 8 }
for animal in d :
legs = d [ animal ]
print ( ’A % s has % d legs ’ % ( animal , legs ) )
# Prints " A person has 2 legs " , " A cat has 4 legs " , " A spider has 8
legs "

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 "

Dictionary comprehensions: These are similar to list comprehensions, but


allow you to easily construct dictionaries. For example:

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 )

hello ( ’ Bob ’) # Prints " Hello , Bob "


hello ( ’ Fred ’ , loud = True ) # Prints " HELLO , FRED !"

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 )

g = Greeter ( ’ Fred ’) # C o n s t r u c t an i n s t a n c e of the Greeter class


g . greet () # Call an i n s t a n c e method ; prints " Hello , Fred
"
g . greet ( loud = True ) # Call an i n s t a n c e method ; prints " HELLO , FRED
!"

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

3. Write a function S=sumN(n) to calculate the sum from 0 to n; for exam-


ple sumN(2) should return 0+1+2=3; sumN(-5) should return 0+(-1)+(-
2)+(-3)+(-4)+(-5)=-15
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.
5. Write a function to calculate an operation between 2 positive integers us-
ing 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.
Hint2: to convert a string such as str1=”23” to number we use num-
ber1=int(str1) to get number1=23
6. Write a function to do the same job as previous exercise but using Dictio-
nary instead of If

Elit.tdtu.edu.vn 7
TON DUC THANG UNIVERSITY
Faculty of Information Technology

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
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
Xn
size m × q where: Ci,j = Ai,k × Bk,j
k=1

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

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

You might also like