You are on page 1of 57

1

EEA216 資料結構
Data Structure
Lecture 1
Yu-Hui Huang, Data Structure

Yu-Hui Huang
Sep. 14, 2022
Yu-Hui Huang, Data Structure
Figure from https://medium.com/python4u/hello-python-509eabe5f5b1 2
Python – Setting up
• Windows : install Python IDE or Jupyter Notebook:
- install Anaconda/Miniconda
- use Google Colab from your browser:
https://colab.research.google.com/

• Linux/MacOSX: Python already installed by default


- Start it by typing “python3” in your terminal

Yu-Hui Huang, Data Structure 3


Python – How to run it?
• Interactive sessions
$ python3
Python 3.7.4 (default, Sep 7 2019, 18:27:02) [GCC 8.2.0] on linux Type
"help", "copyright", "credits" or "license" for more information.
>>>
>>> print('Hello World!’)
Hello World!

• Using the python Command


helloworld.py

$ python3 helloworld.py
hello world 11111
Yu-Hui Huang, Data Structure 4
Figure from
https://appdividend.com/2022/06/03/python-
5

comment-block/
Python – Comments

Yu-Hui Huang, Data Structure


C vs. Python

• Needs compilation • Interpreter


(compile->execute) (directly run)
$ gcc test.cpp $ python test.py
$ ./a.out

• Needs declaration • No need to declare


float x = 135.2 x = 135.2

Ref: https://engineering.purdue.edu/~milind/datascience/2018spring/notes/lecture-2.pdf
Yu-Hui Huang, Data Structure 6
C vs. Python

• Usage of { } in control • whitespace matters


statements

if (condition) { if condition:
// block of code to be print(“…”)
executed if the condition is
true
}
Indentation : whitespaces at the
beginning of the line (print…)

Yu-Hui Huang, Data Structure 7


C vs. Python

• Needs to specify return • No need to specify


type in function def. return type in func. def.

int bar(void); def foo():


return bar()
int foo() {
return bar(); def bar():
} return 42

int bar() { foo()


return 42;
}
Yu-Hui Huang, Data Structure 8
Python - Basics
• An interpreted language
• An object-oriented language (classes form the basis
for all data types)

Yu-Hui Huang, Data Structure 9


Python - Basics
• assignment statement:
temperature = 25.0
temperature float (class)
(identifier) 25.0
• alias:
other = temperature
temperature float other
25.0

Yu-Hui Huang, Data Structure 10


Python - Basics
• assignment statement:
temperature = 25.0
temperature float (class)
(identifier) 25.0
• alias:
other = temperature
temperature float other
25.0

If we execute the following command,


temperature = temperature + 3.0 ?
Yu-Hui Huang, Data Structure 11
Python - Basics

temperature = temperature + 3.0

temperature float
28.0

float other
25.0

The temperature identifier is assigned to a new value

Yu-Hui Huang, Data Structure 12


Python – Built-in Classes
• The int Class: 0, -3, 0b1010, 0o51, 0x6f
• The float Class: 3.14, 6e-23
• The bool Class: True, False

#sequence types:
• The list Class: [‘red’, ‘blue’]
• The tuple Class: (3, 5,7)
• The str Class: “hello world”, ‘hi’
• The dict Class: {‘de’: ’German’, ‘en’: ‘English’}

Yu-Hui Huang, Data Structure 13


Python - Basic Operators
• Arithmetic Operators:
Addition (+), Subtraction (-), Multiplication (*),
Division(/), Modulus (%), Exponential (**)
• Assignment Operators:
= , ex: x = 5
+=, ex: x += 3 à x = x + 3
-=, ex: x -= 3 à x = x – 3

Yu-Hui Huang, Data Structure 14


Python - Basic Operators
• Comparison Operators:
== equal, ex: x == y
!= not equal, ex: x != y
> greater than, ex: x > y
< less than, ex: x < y
>= greater than or equal to, ex: x >= y
<= less than or equal to, ex: x <= y

Yu-Hui Huang, Data Structure 15


Python - Basic Operators
• Logical Operators:
and return True if both statements are true,
ex: x < 3 and x < 10
or return True if one of the statement is true,
ex: x != y or x <= 5
not reverse the result, returns False if the result is
true, ex: not(x > y or x < 10)

Yu-Hui Huang, Data Structure 16


Python - Basic Operators
• Bitwise Operators:
~ bitwise complement
& bitwise and
| bitwise or
^ bitwise exclusive-or Returns 1 if one of the bits is 1 and
the other is 0 else returns false.
Ex:
a = 10
b=4
a&b=?
a|b =?
a^b =? Yu-Hui Huang, Data Structure 17
Python - Basic Operators
• Bitwise Operators:
<< shift bits left, filling in with zeros
>> shift bits right, filling in with zeros

a = 10
a >> 1 = ?
a << 2 = ?

Yu-Hui Huang, Data Structure 18


Python - Basic Operators
• Sequence Operators: (for str, tuple, list)
s[j] element at index j
s[start:stop] slice including indices [start, stop)
s[start:stop:step] slice including indices start, start+step,
start+step*2, …
s+t concatenation of sequences
k*s s+s+s+…(k times)
val in s check if s contains val
val not in s check if s not contains val

Yu-Hui Huang, Data Structure 19


Python - Basic Operators
• Extended Assignment Operators:
Ex:
>>> alpha = [1, 2]
>>> beta = alpha
>>> beta += [3, 4]
>>> beta = beta + [5, 6]
>>> print(beta)

>>> print(alpha)

Yu-Hui Huang, Data Structure 20


Python - lists
• lists are used to store multiple items in a single
variable.
• Ex:
>>> theList = [‘apple’, ‘guava’,
‘apple’]
>>> print(len(theList)) #number of items
3

Yu-Hui Huang, Data Structure 21


Python - lists
• lists may contain different types of elements

• Ex:
>>> theList = [3, ‘guava’, 1]
>>> print(len(theList)) #number of items
3

Yu-Hui Huang, Data Structure 22


Python - lists
• lists are zero-indexed

https://medium.com/python4u/hello-python-509eabe5f5b1

Yu-Hui Huang, Data Structure 23


Python - lists
• 2D list
My_List2 = [[1,2,3,4], [5,6,7,8]]

My_List2[0][1] = 2
Figure from https://medium.com/python4u/hello-python-509eabe5f5b1
Yu-Hui Huang, Data Structure 24
Python – list Operations

• Ex:
>>> myList = [‘apple’, ‘guava’]
>>> myList + myList #Concatenation
[‘apple’,’guava’,’apple’,’guava’]
>>> myList * 2 #Repetition
[‘apple’,’guava’,’apple’,’guava’]
>>> 3 in myList #Membership
False

https://medium.com/python4u/hello-python-509eabe5f5b1

Yu-Hui Huang, Data Structure 25


Python – list Methods
>>> myList = [‘apple’, ‘guava’]
>>> myList.index(‘apple’) #get index of an item
0
>>> myList.count(‘guava’) #count an item ‘guava’
1
>>> myList.append(‘orange’) #append an item
[‘apple’,’guava’,orange’]
>>> myList.remove(‘apple’) #remove an item
[’guava’,orange’]
>>> myList.reverse() #reverse myList
[orange’,’guava’]
>>> myList.insert(1, ’t’) #insert an item
[orange’,’t’,’guava’]

Reference: https://medium.com/python4u/hello-python-509eabe5f5b1
Yu-Hui Huang, Data Structure 26
Python – string vs. list
Common part:
• len
len(“123”) = > 3. len([1,2,3]) => 3
• Index
“123”[1] => ”2” [123][1] =>2
• In
“123” in “12345” => True
123 in [123,234,345] =>True
• Traverse
for t in “123”: for t in [1,2,3]:
print(t) print(t)
Reference: https://rilak.gitbooks.io/2018-python/content/string/basic.html
Yu-Hui Huang, Data Structure 27
Python – string vs. list
Different part:
• Immutable
String object does not support item assignment

a = “123” a = [1, 2, 3]
a[2] = “0” a[2] = 0

è TypeError! v

Reference: https://rilak.gitbooks.io/2018-python/content/string/basic.html
Yu-Hui Huang, Data Structure 28
Python – string methods

• replace: string.replace(str1, str2)

• split: string.split(str, n)

• find: string.find(str, start)

Reference: https://rilak.gitbooks.io/2018-python/content/string/basic.html
Yu-Hui Huang, Data Structure 29
Python – string methods

• replace: string.replace(str1, str2)

a = “apple”
print(a.replace(“p”,:””)). #ale

Reference: https://rilak.gitbooks.io/2018-python/content/string/basic.html
Yu-Hui Huang, Data Structure 30
Python – string methods

• split: string.split(str)

a = “apple, pie, raspberry”


a.split(“,”) # ['apple', ' pie', ' raspberry’]

Reference: https://rilak.gitbooks.io/2018-python/content/string/basic.html
Yu-Hui Huang, Data Structure 31
Python – string methods

• find: string.find(str, start)

a = “apple pie and raspberry”


a.find(“r”) # 14
a.find(“r”, 16) # 20

Reference: https://rilak.gitbooks.io/2018-python/content/string/basic.html
Yu-Hui Huang, Data Structure 32
Python – if/else Conditions
if first_condition: • Ex:
first_body if x > 1:
y = 5
elif second_condition:
elif: x <= 1:
second_body
y = 3
elif third_condition: else:
third_body y = 10
else:
forth_body

Yu-Hui Huang, Data Structure 33


Python – while loop
while condition:
body

• Ex: • Output:
i = 1 1
while i < 5: 2
print(i) 3
4
i += 1 finish

print(‘finish’)

Yu-Hui Huang, Data Structure 34


Python – while loop
• Break: • Example with break
terminates the i = 1
most immediately sum = 0
enclosing loop while True:
if i > 10:
break
sum += i
i += 1

print(sum)

Yu-Hui Huang, Data Structure 35


Python – while loop
• continue: • Example with continue
causes the i = 1
current iteration while i <= 10:
of a loop to stop if i % 2 == 0:
i += 1
continue
elif i % 3 == 0:
i += 1
continue
print(i)
i += 1

Yu-Hui Huang, Data Structure 36


Python – for loop
for element in iterable:
body # body may refer to ‘element’ as an identifier

Yu-Hui Huang, Data Structure 37


Python – for loop
• Ex1: • Output:
for i in [1,2,3,4]: 1
2
print(i) 3
4
print(‘finish’) finish

• Ex2:
for i in range(4): 0
1
print(i) 2
print(‘finish’) 3
finish

Yu-Hui Huang, Data Structure 38


Python – for loop
enumerate(list)
for i, score in enumerate(all):
print(i, score)
>>> all=[5,20,100,90]
>>> for i, score in enumerate(all):
... print(i, score)
...
0 5
1 20
2 100
3 90 Yu-Hui Huang, Data Structure 39
Python – for loop
enumerate(list)
for i, score in enumerate(all):
print(i, score)
>>> color=[‘red’, ‘green’, ‘white’,
‘pink’, ’purple’]
>>> color=[x for (i,x) in
enumerate(color) if i not in (2,3)]
>>> print(color)

Yu-Hui Huang, Data Structure 40


Python – for loop
• Ex3: • Ex4:
count = 0 count = 0
for st in ‘content’: for st in ‘content’:
count+=1
if st == ‘t’ count+=1
break if str = ‘t’:
print(str) countinue
print(‘end for’) print(str)
print(’count=%d’ print(‘end for’)
%count) print(‘count=%d’
%count)
Yu-Hui Huang, Data Structure 41
Python – lists comprehension
• a shorter syntax
• Create a new list based on the values of current lists
fruits = [‘apple’, ’guava’, ’banana’]
newlist = []
for x in fruits: newlist=[x for x in
if “a” in x: fruits if “a” in x]
newlist.append(x)
print(newlist)

Yu-Hui Huang, Data Structure 42


Python – lists comprehension
• Syntax:
newlist = [expression for item in iterable if condition==True]
fruits = [‘apple’, ’guava’, ’banana’]
newlist = []
for x in fruits: newlist=[x for x in
if “a” in x: fruits if “a” in x]
newlist.append(x)
print(newlist)

Yu-Hui Huang, Data Structure 43


Python – lists comprehension
• Syntax:
newlist = [expression for item in iterable if condition==True]
fruits = [‘apple’, ’guava’, ’banana’]
newlist=[x for x in fruits if “a” in x]
=

newlist=[x for x in fruits]

Yu-Hui Huang, Data Structure 44


Python – lists comprehension
• Syntax:
newlist = [expression for item in iterable if condition==True]
fruits = [‘apple’, ’guava’, ’banana’]

What to do if we only need all items except


for “apple”?

Yu-Hui Huang, Data Structure 45


Python – lists comprehension
newlist = [expression for item in iterable if condition==True]
The iterable can be any iterable objects (list, tuple, set,…)

newlist = [x for x in range(5)]

newlist = [x for x in range(5) if x<3]

Yu-Hui Huang, Data Structure 46


Python – lists comprehension
newlist = [expression for item in iterable if condition==True]

Exercise:
We have a list.
a = [1,6,2,4,7,10,3]
Write a program to print out all the
elements of the list that is smaller than 6.

Yu-Hui Huang, Data Structure 47


Enough to Understand the Code
• Indentation matters to code meaning
• Block structure indicated by indentation
• First assignment to a variable creates it
• Variable types don’t need to be declared.
• Python figures out the variable types on its own.
• Assignment is = and comparison is ==
• For numbers + - * / % are as expected
• Special use of + for string concatenation and % for string
formatting (as in C’s printf)
• The basic printing command is print

From Learn Python in three hours Yu-Hui Huang, Data Structure 48


Python – functions
function:
describe a traditional, stateless function that is invoked
without the context of a particular class or an instance
of that class.
Ex: sorted(data)
method:
describe a member function that is invoked upon a
specific object using an object-oriented message
passing syntax
Ex: data.sort()

Yu-Hui Huang, Data Structure 49


Python – functions

def count(data, target): -->function signature


”count how many elements
equal to the target from the data” -->function docstring
total = 0
for item in data:
if item == target:
total += 1
return total -->return expression

print(count([0,2,4,6,3,1,1,0], 0))
Yu-Hui Huang, Data Structure 50
Python – functions

def a_list(items):
total = 0
for x in items:
total += x
return total
print(a_list[3,-5,6])

Yu-Hui Huang, Data Structure 51


Python – Anonymous Functions
• Functions not called through def keyword are called
anonymous functions.
• Use lambda keyword to create anonymous functions.

Syntax:
lambda [arg1 [,arg2, …, argn]]: expression

Ex:
sum = lambda arg1, arg2: arg1 + arg2;
print “value of total:” , sum(10, 20)
Yu-Hui Huang, Data Structure 52
Python – Variables Scope
• Global variables
• Local variables

#!/usr/bin/python
num = 0 #global variable

def sum (arg1, arg2):


num = arg1 + arg2
print “Inside the function call: num = “, num

sum(10, 20)
print “Outside the function call: num = “, num
Yu-Hui Huang, Data Structure 53
Python – Variables Scope
#!/usr/bin/python
num = 0 #global variable

def sum (arg1, arg2):


num = arg1 + arg2
print “Inside the function call: num = “, num
return num

num = sum(10, 20)


print “Outside the function call: num = “, num
Yu-Hui Huang, Data Structure 54
Python – file I/O

fp = open(‘xxx.txt’) #Mode
fo = open(‘yyy.txt’, ’w’) ‘w’ : write to the file
for lines in fp: ‘a’ : append to the end of the
line = fp.read() file
fo.write(line) ‘rb’: read binary files
fp.close() ‘wb’: write binary
fo.close()

Yu-Hui Huang, Data Structure 55


Python – References:
• 資訊之芽Python班課程講義
https://rilak.gitbooks.io/2018-python/content/
• ⿈建庭的教學網站
https://sites.google.com/view/zsgititit/
• Hello Python!|Python⼊⾨詳細介紹
https://medium.com/python4u/hello-python-
509eabe5f5b1
• W3 Schools
https://www.w3schools.com/python/default.asp

Yu-Hui Huang, Data Structure 56


Python – Exercise
• pythonds:
ch1.8 (Getting started with data),
ch1.9 (Input and output),
ch1.10 (Control structures)

https://runestone.academy/ns/books/
published/pythonds/index.html)

Yu-Hui Huang, Data Structure 57

You might also like