0% found this document useful (0 votes)
18 views80 pages

03 - Basic Python Programming II

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views80 pages

03 - Basic Python Programming II

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

巨量資料探勘與應用

Big Data Mining and Applications

Basic Python Programming II


李建樂
Chien-Yueh Lee, Ph.D.
Assistant Professor
Master Program in Artificial Intelligence
Innovation Frontier Institute of Research for Science and Technology
Department of Electrical Engineering
National Taipei University of Technology
Mar. 3, 2025
Outline

u Part 1:Function

u Part 2:Data Containers


Par t 1: Function

u Understanding Functions
u Defining and Calling Functions
u Keyword Argument
u Default Argument Value
u Arbitrary Argument
u Parameter Passing Methods
u Function Return Values
u Global and Local Variables
u Recursive Functions
Understanding
Functions
Understanding Functions

u A function is an independent program unit assigned a name for later calls that
captures a set of statements with a designated functionality or for frequent use.
u A function is like a machine, where you can design its functionality, as well as the
required input (raw materials) and output (products). E.g.,
• Vending machine → Function
• Coins and product selection buttons → Input
• Dispensed products → Output
u In some programming languages, functions are referred to as methods,
procedures, or subroutines.
Advantages of Using Functions
u Reusability
u Simplifies Code and Improves Readability
u Easier Debugging
u Modularity and Consistency
Function

Call
functions

Each time the


function is called, the
same statements are
executed.
Defining and
Calling Functions
Define a Function
u Use the def keyword to define a function name and the required parameters.
The syntax is as follows:
def functionName([parameter1, parameter2, …]):
statements
[return value]

u The rules for naming functions are the same as for variables.
u Statements form the body of the function and execute specific tasks.
u Statements must be indented to the right relative to def, indicating that they
belong to the function block.
u Return value represents the function's output, also called the return value. It can
be one or multiple values.
u The return value can be a string, number, boolean, container (list, dict, etc.), or
other objects. If a function has no return value, the return statement can be
omitted.
Call a Function

u A function must be called to execute. The syntax is as follows:


functionName([argument1, argument2, …])

u The values passed when calling a function are referred to as arguments (引數),
and they correspond to the function's parameters (參數).
u Even if a function has no required parameters, parentheses () must still be
included when calling it. E.g., myInput = input()
When to Use Functions
u A function can be used to capture two or more very similar code segments that
vary only in a few values or variables.

Design the parts of the process that


reference different values or variables as
parameters.
Keyword Argument
Keyword Argument
u Python uses positional arguments by default, but when the order of
parameters is hard to remember, keyword arguments can be used to
differentiate them.
u A keyword argument explicitly specifies the parameter name when calling a
function, ensuring clarity and flexibility.
For example:
D e f a u l t A r g u m e n t Va l u e
D e f a u l t A r g u m e n t Va l u e

u When defining a function, default argument values can be set.


u This allows the function to be called without explicitly providing those
arguments, as they will take on their default values.
For example:
Arbitrar y Argument
Arbitrar y Argument

u Python supports arbitrary arguments, allowing a function to accept an


unlimited number of parameters.
u To use arbitrary arguments, prefix a parameter with a single asterisk (*). The
arguments will be received as a tuple.
Syntax: functionName(*args)
u If a parameter is prefixed with two asterisks (**), the function accepts arbitrary
keyword arguments. The arguments will be received as a dictionary containing
key-value pairs.
Syntax: functionName(**kwargs)
Arbitrar y Argument
u Example 1:
Arbitrar y Argument
u Example 2:
Pa r a m e t e r Pa s s i n g
Methods
Parameter Passing Methods
u When the parameter is an u When the parameter is a
immutable (不可改變) object, such mutable (可改變) object, such
as a number, string, or tuple, call as a list, set, or dictionary, call
by value is used. by reference is used.
Memory

Memory
x

y
x[0]

x[1]
a

b
F u n c t i o n Re t u r n
Va l u e s
F u n c t i o n R e t u r n Va l u e s

u Functions with No Return Value


• A function that does not return a value simply executes its statements without
using the return keyword or returns None by default.
u Functions with a Return Value
• A function can return a single or multiple values using the return statement. The
returned values can be strings, numbers, booleans, containers (lists, dictionaries,
etc.), or other objects.
F u n c t i o n R e t u r n Va l u e s
u In principle, the program's control remains within the
function until all statements are executed.
u If it is necessary to exit the function early and return
to the function call, the return statement can be used.
Global & Local
Va r i a b l e s
D e f i n i t i o n o f G l o b a l & L o c a l Va r i a b l e s

u Global variable
• A variable created outside a function.
• It is accessible by all statements Global variable

within the program. Local variable

u Local variable
• A variable created inside a function.
• It can only be accessed by statements
within that function.
C o m m o n M i s t a k e W h e n M o d i f y i n g Va r i a b l e s

u If there is a global variable x and we want to modify its value through the
function changeX(), the code is as follows:

?
u What will ? be?
R e a d i n g G l o b a l & L o c a l Va r i a b l e s i n a F u n c t i o n

u In the readFunc1() function, the global variable x is read without modifying its content.
u In the readFunc2() function, a new variable with the same name as the global variable x
is assigned.
Memory
u In a function, the program will first look for an assigned local variable name.
x = 10
If it cannot find one, it will then search for the global variable in the main

program.
Global var x = 20

Local var
R e l a t i o n s h i p B e t w e e n N a m e s p a c e & Va r i a b l e s

u A namespace defines the scope in which a variable name is visible.


u Each namespace contains unique variable names.
u Variables in different namespaces can have the same name.
Main Program
For example, function X can define a variable A, and
Var A (Global variable)
function B can also define A variable a; these two A Func X()

variables are entirely different. Var A


(Local
variable)
Func Y()

Var A
(Local
variable)

Three different A variables are


completely separate from each other.
H o w t o M o d i f y t h e Va l u e o f a
G l o b a l Va r i a b l e i n a F u n c t i o n
u Use the global statement to declare a variable as a global variable within a
function.
P r i n t i n g E x i s t i n g Va r i a b l e s

u globals(): Returns a dictionary containing the names and values of all global
variables in the program.
u locals(): Returns a dictionary containing the names and values of all local
variables within the current function.
Re c u r s i v e F u n c t i o n s
Recursive Functions

u A function that continuously calls itself during execution is called a recursive function.
u Recursion is similar to a loop but can handle parameters and return values that loops
may struggle with.
u Recursive functions offer better logic, readability, and flexibility compared to loops.
u Characteristics of a Recursive Function:
1. The function must be able to call itself.
2. It must have a stopping condition.
Recursive Function Example –
Calculating Factorial
u When n = 0: F(n) = F(0) = 0! = 1
u When n > 0: F(n) = n! = n * (n-1)! = n * F(n-1)
u When n < 0: F(n) = -1 (indicating that the factorial cannot be calculated)
F(4) =24

=4* F(3) =6

=3* F(2) =2

=2* F(1) =1

= 1 * F(0) =1
Par t 2: Data Containers
u Set
u List • Creating a Set
• Creating a List • Built-in Functions of a Set
• Built-in Functions of a List • Operators, Subsets, and Supersets
• Operators • Intersection, Union, Difference, and
• Modifying Elements Symmetric Difference
• List Processing Methods • Set Processing Methods
• List Comprehension (解析) u Dictionary
• Two-Dimensional Lists • Creating a Dictionary
u Tuple • Built-in Functions and Operators of
• Creating a Tuple a Dictionary
• Tuple Operations • Reading a Dictionary
• Dictionary Processing Methods
• Shallow Copy vs. Deep Copy in
Lists and Dictionaries
• Dictionary Comprehension
List
Creating a List
u list (List): A sequence of ordered elements that can be modified
u A list is enclosed in square brackets [ ], with elements separated by
commas. The data types of the elements can be different.
u You can create a list using Python's built-in list() function or [ ], e.g.,
>>> list1 = list()
>>> list1
[]
>>> list2 = list([1, 2, 3])
>>> list2
[1, 2, 3]
u Alternatively, you can define a list using [ ] as shown below.
>>> list1 = []
>>> list2 = [1, 2, 3]
B u i l t- i n F u n c t i o n s of a L i s t
Common built-in functions for lists:
u len(L) >>> len([1, 2, 3, 4, 5])
5
u max(L) >>> max([1, 2, 3, 4, 5])
5
u min(L)
>>> min([1, 2, 3, 4, 5])
u sum(L) 1
>>> sum([1, 2, 3, 4, 5])
15
Concatenation and Repetition Operators
u Concatenation Operator (+)
• The + operator can be used to concatenate lists, e.g.,

>>> [1, 2, 3] + ["One", "Two", "Three"]


[1, 2, 3, 'One', 'Two', 'Three']

u Repetition Operator (*)


• The * operator can be used to repeat a list, e.g.,

>>> 3 * [1, 2, 3]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Comparison & Membership Operators
u Comparison Operators
• The comparison operators (>, <, >=, <=, ==, !=) can be used to
compare the size or equality of two lists, e.g.,
>>> [1, 'two', '三'] == ['三', 'two', 1]
False
>>> [1, 2, 3] != [1, 2, 3, 4]
True
u in and not in Membership Operators
• The in operator checks if an element exists in a list, e.g.,
>>> "Three" in [1, 2, "Three", "Four"]
True
• The not in operator checks if an element does not exist in a list, e.g.,
>>> 2 not in [1, 2, "Three", "Four"]
False
Indexing and Slicing Operators
u Use the indexing operator [i] to access elements in a list.
Given a list variable: L = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
• L[0], L[1], ..., L[9] represent 5, 10, ..., 50.
• L[-1], L[-2], ..., L[-10] represent 50, 45, ..., 5.
Index

Content

Index

u Use the slicing operator [start:end:step] to specify a range of indices, e.g.,


>>> L = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50] >>> print(L[5:])
>>> print(L[2:5]) [30, 35, 40, 45, 50]
[15, 20, 25] >>> print(L[5::2])
>>> print(L[:5]) [30, 40, 50]
[5, 10, 15, 20, 25]
Modifying Elements Using
Indexing & Slicing Operators

u The contents of a list can be modified using indexing and slicing operators.
u Use the indexing operator [i] to modify a specific element in the list, e.g.,
>>> fruits = ['apple', 'banana', 'orange']
>>> fruits[0] = 'grape'
>>> print(fruits)
['grape', 'banana', 'orange']

u Use the slicing operator [start : end] to modify all elements within the
specified index range, e.g.,
>>> a = ['a', 'b', 'c', 'd', 'e']
>>> a[1:4] = [100, 200, 300]
>>> print(a)
['a', 100, 200, 300, 'e']
List Processing Methods

u Adding elements into a list: >>> list1 = [10, 20, 30]


>>> list2 = [100, 200, 300]
• list.append(x) >>> list1.append(40)
>>> print(list1)
• list.extend(L) [10, 20, 30, 40]
• list.insert(i, x) >>> list1.extend(list2)
>>> print(list1)
[10, 20, 30, 40, 100, 200, 300]

>>> list1.insert(1, 1000)


>>> print(list1)
[10, 1000, 20, 30, 40, 100, 200, 300]
List Processing Methods
>>> print(list1)
[10, 1000, 20, 30, 40, 100, 200, 300]
u Removing elements from a list: >>> del list1[1]
>>> print(list1)
• del list[i] [10, 20, 30, 40, 100, 200, 300]

• list.remove(x) >>> list1.remove(100)


>>> print(list1)
[10, 20, 30, 40, 200, 300]
• list.pop([i])
>>> pop_element = list1.pop()
• list.clear() >>> print(pop_element)
300
>>> print(list1)
[10, 20, 30, 40, 200]
>>> pop_element = list1.pop(3)
>>> print(list1)
[10, 20, 30, 200]

>>> list1.clear()
>>> print(list1)
[]
List Processing Methods
u Copy a list: >>> print(list2)
[100, 200, 300]
• list.copy()
>>> list3 = list2.copy()
• list2 = list1[:] >>> print(list3)
[100, 200, 300]

>>> list4 = list2[:] >>> list1 = [50, 20, 40, 20, 30, 20, 10]
u Additional functions: >>> print(list4) >>> list1.index(20)
[100, 200, 300] 1
• list.index(x) >>> list1.count(20)
3
• list.count(x) >>> list1.sort()
>>> print(list1)
• list.sort() [10, 20, 20, 20, 30, 40, 50]
>>> list1.reverse()
• list.reverse() >>> print(list1)
[50, 40, 30, 20, 20, 20, 10]
List Assignment vs. List Copying
u Assignment u Copy
• list2 = list1 • list.copy()
• list2 = list1[:]
>>> list1 = [10, 20, 30] >>> list1 = [10, 20, 30]
>>> list2 = list1 >>> list3 = list1.copy() #i.e., list3 = list1[:]
>>> del list1[1] >>> del list1[1]
>>> print(list1) >>> print(list1)
[10, 30] [10, 30]
>>> print(list2) >>> print(list3)
[10, 30] [10, 20, 30]
u Summary:
• Using assignment (=) appears to copy a list, but in reality, list1
and list2 both reference the same list.
• When the elements of list1 are modified, list2 is also affected.
Conversion Between Lists and Strings
u str.split(s)
• Convert a string to a list: Use str.split(s) to split a string str into a list
based on the specified delimiter s.
u str.join(L)
• Convert a list to a string: Use str.join(L) to join the elements of list L
into a single string, using str as the
separator.
List Comprehension
u List comprehension provides a more concise way to create a list.
u The square brackets [ ] contain a for statement, which can be
followed by multiple for or if statements.
u The elements of the list are generated based on the specified
expressions, e.g.,
List Comprehension with
Conditional Statements
uWith a single if condition:
• [expression for item in iterable if condition]
uWith an if…else condition:
• [expression1 if condition else expression2 for item in iterable]
uWith nested if conditions:
• [expression for item in iterable if condition1 if condition2]
Tw o - D i m e n s i o n a l L i s t s
uA two-dimensional list is an extension of a regular list that can store tabular data
or matrices.
uFor example, a 5-row × 3-column grade sheet can be stored in a 5×3 two-
dimensional list named grades:
grades = [[95, 100, 100], [86, 90, 75], [98, 98, 96], [78, 90, 80], [70, 68, 72]]
uTo access elements in this two-dimensional list, two indices are required:
• The first index represents the row index.
• The second index represents the column index.
Chinese English Math Chinese English Math
Student 1 Student 1

Student 2 Student 2
Student 3 Student 3
Student 4 Student 4
Student 5 Student 5
E x a m p l e o f a Tw o - D i m e n s i o n a l L i s t
uThe following example prints the total score for each student based on the grade sheet.
Tu p l e
C r e a t i n g a Tu p l e
utuple (Tuple): A sequence of ordered elements that cannot be modified.
uA tuple is enclosed in parentheses ( ), with elements separated by
commas. The data types of the elements can be different
uYou can create a tuple using Python's built-in tuple() function or ( ), e.g.,
>>> tuple1 = tuple()
>>> tuple1
()
>>> tuple2 = tuple((1, 2, 3))
>>> tuple2
(1, 2, 3)

uAlternatively, a tuple can be written as shown below.


>>> tuple1 = ()
>>> tuple2 = (1, 2, 3)
Tu p l e O p e r a t i o n s
uA tuple supports all common list operations. The built-in functions len(), max(), min(), and
sum() also work with tuples.
uSince random.shuffle() modifies the order of elements, it cannot be used with tuples.
uIn general, any list-compatible operation that does not modify elements can be used with
tuples, including:
• Concatenation (+)
• Repetition (*)
• Comparison operators (>, <, >=, <=, ==, !=)
• Membership operators (in, not in)
• Indexing ([ ])
• Slicing ([start:end:step])
uAdditional tuple methods:
• tuple.index(x): Returns the index of the first occurrence of x.
• tuple.count(x): Returns the number of times x appears in the tuple.
Set
Creating a Set
u set (Set): An unordered collection of unique elements that can be
modified, is similar to a mathematical set.
u A set is enclosed in curly brackets { }, with elements separated by
commas. The data types of the elements can be different.
u A set can be created using Python's built-in set() function or { }, e.g.,
>>> set1 = set()
>>> print(set1)
set()
>>> set2 = set({1, 2, 3, 3, 2, 1})
>>> print(set2)
{1, 2, 3}
>>> set3 = {"Taipei", "New York", "Tokyo", "Tokyo"}
>>> print(set3)
{'Taipei', 'New York', 'Tokyo'}
B u i l t- i n F u n c t i o n s of a S e t
u The built-in functions len(), max(), min(), and sum() can be used with sets.
u However, since sets do not maintain a specific order, the random.shuffle()
method cannot be used with sets, as it relies on modifying element order.

>>> S = {1, 2, 3, 4, 5}
>>> print(len(S))
5
>>> print(max(S))
5
>>> print(min(S))
1
>>> print(sum(S))
15
Operators, Subsets, and Supersets
u A set does not support:
• Concatenation (+)
• Repetition (*)
>>> S = {'a', 'b', 'c', 'd', 1, 2, 3}
• Indexing ([ ])
>>> print('b' in S)
• Slicing ([start:end]) True
• Any other order-related operations
>>> print(10 not in S)
u Supported Operators: True
• Membership operators (in, not in): Check whether a specific element exists in a set.
• Comparison operators (<, <=, >, >=): Determine subset or superset relationships
between two sets.
Operators, Subsets, and Supersets
u If A and B are both sets, the following syntax can be used for checks:
Condition Syntax Operator Description
A and B contain exactly the same elements A == B == A and B are identical sets
A and B have different elements A != B != A and B are not identical
B is a subset of A B <= A <= B is entirely contained within A, or A and B are identical
B is a proper subset of A B<A < B is fully contained within A, and A has additional elements
A is a superset of B A >= B >= A fully contains B, or A and B are identical
A is a proper superset of B A>B > A fully contains B and has extra elements not in B
Operators, Subsets, and Supersets
u Example: >>> A = {4, 1, 3, 2}; B = {1, 2, 3}; C = {3, 1, 2} >>> B <= A
>>> B == C True
>>> B < A
True True
>>> A != B >>> A >= B
True True
>>> A > B
True
u Additionally, to check for subset or superset relationships, the following
methods can be used:
• set.issubset(S) → Returns True if the set is a subset of S. >>> B.issubset(A)
True
• set.issuperset(S) → Returns True if the set is a superset of S. >>> A.issuperset(B)
True
Intersection, Union, Difference, and
Symmetric Difference
Condition Operator Set method
Intersection & set.intersection(S)
Union | set.union(S)
Difference - set.difference(S)
Symmetric difference ^ set.symmetric_difference(S)
Intersection, Union, Difference, and
Symmetric Difference
>>> S1 = {10, 20, 30}
>>> S2 = {20, 30, 40}

>>> print(S1. intersection(S2))


u set.intersection(S) {20, 30}

u set.union(S) >>> print(S1.union(S2))


{20, 40, 10, 30}
u set.difference(S) >>> print(S1. difference(S2))
{10}
u set.symmetric_difference(S)
>>> print(S1.symmetric_difference(S2))
u set.isdisjoint(S) {40, 10}

>>> #To check whether two sets are disjoint


>>> print(S1.isdisjoint(S2))
False
>>> S3 = {40, 50}
>>> print(S1.isdisjoint(S3))
True
Set Processing Methods

>>> S1 = {10, 20, 30, 40}


u Adding elements and copying a set: >>> S1.add(50)
>>> print(S1)
• set.add(x) {40, 10, 50, 20, 30}

• set.update(S) >>> S2 = {60, 70}


>>> S1.update(S2)
• set.copy() >>> print(S1)
{70, 40, 10, 50, 20, 60, 30}

>>> S3 = S1.copy()
>>> print(S3)
{50, 20, 70, 40, 10, 60, 30}
Set Processing Methods
u Removing elements from a set: >>> S1.discard(70)
>>> print(S1)
• set.remove(x) {40, 10, 20, 60, 30}
>>> S1.discard(70)
• set.discard(x) >>> print(S1)
{40, 10, 20, 60, 30}
• set.pop()
>>> pop_element = S1.pop()
• set.clear() >>> print(pop_element)
40
>>> S1.remove(50)
>>> print(S1)
>>> print(S1)
{70, 40, 10, 20, 60, 30} {10, 20, 60, 30}
>>> S1.remove(50)
Traceback (most recent call last): >>> S1.clear()
File "<stdin>", line 1, in <module> >>> print(S1)
KeyError: 50 set()
Dictionar y
Creating a Dictionar y
u dict (Dictionary): A collection of key-value pairs, where keys are
unique, unordered (not exactly true), and the content can be modified.
u It belongs to the mapping type, meaning values in the dictionary are
accessed using keys as indexes.
u A dictionary is enclosed in curly braces {}, with key-value pairs
separated by commas.
u A dictionary can be created using Python's built-in dict() function or
{ }.The following four examples create the same dictionary, and any
one of them can be used: >>> A = {"one": 1, "two": 2, "three": 3}
>>> B = dict({"three": 3, "one": 1, "two": 2})
>>> C = dict(one=1, two=2, three=3)
>>> D = dict([("two", 2), ("one", 1), ("three", 3)])
>>> print(A)
{'three': 3, 'two': 2, 'one': 1}
Does a Python Dictionar y Have Order?
u Yes!!!
u In Python 3.7 and later, dictionaries maintain insertion order as an
implementation detail, and in Python 3.8+, it's officially guaranteed
by the language specification.
u This means that when you iterate over a dictionary, the keys will
appear in the order they were added.
# Python 3.7+
>>> my_dict = {"a": 1, "b": 2, "c": 3}
>>> print(my_dict)
{'a': 1, 'b': 2, 'c': 3}

u Before Python 3.7, dictionaries were unordered, meaning the order


of elements could be arbitrary.
B u i l t- i n F u n c t i o n s & O p e r a t o r s
of a Dictionar y
u The only built-in function applicable to dictionaries is len(), which
returns the number of key-value pairs in the dictionary.
>>> D = {"ID": "N123456", "name": "Tom"}
>>> len(D)
2

u Since key-value pairs in a dictionary have no order, dictionaries do


not support the concatenation operator (+), repetition operator (*),
indexing operator ([ ]), slicing operator ([start:end]), or other order-
related operations.
u Dictionaries support the in and not in operators to check whether a
specified key exists in the dictionary.
u Dictionaries only support the == and != comparison operators,
while >, >=, <, and <= are not applicable to dictionaries.
Reading a Dictionar y
u After creating a dictionary, values can be accessed using their
corresponding keys in the following ways:
>>> A_keys = A.keys()
• dict[key] >>> A_values = A.values()
• dict.get(key) >>> print(A_keys)
>>> A = {"one": 1, "two": 2, "three": 3} dict_keys(['one', 'two', 'three'])
>>> x = A['one'] >>> print(A_values)
>>> print(x) dict_values([1, 2, 3])
1
>>> y = A.get('two') >>> print(list(A_keys))
>>> print(y) ['one', 'two', 'three']
2 >>> print(tuple(A_values))
(1, 2, 3)
u To retrieve all keys and values:
• dict.keys() – returns all keys >>> for k, v in A.items():
... print(k, v)
• dict.values() – returns all values one 1
• dict.items() – returns all key-value pairs two 2
three 3
Dictionar y Processing Methods
u Adding and modifying a dictionary:
• Using dict[key] = value, you can add a new key-value pair to the
dictionary.
• If the specified key already exists, its value will be updated with the
new value.
>>> A['four'] = 4
>>> print(A)
{'one': 1, 'two': 2, 'three': 3, 'four': 4}

>>> A['four'] = 'IV'


>>> print(A)
{'one': 1, 'two': 2, 'three': 3, 'four': 'IV'}
Dictionar y Processing Methods
>>> del A['four']
u Copying a dictionary: >>> print(A)
• dict.copy() – creates a shallow copy of the dictionary. {'one': 1, 'two': 2, 'three': 3}

>>> B = A.copy() >>> pop_element = A.pop('three')


>>> print(B) >>> print(pop_element)
{'one': 1, 'two': 2, 'three': 3, 'four': 'IV'} 3
>>> print(B == A) >>> print(A)
True {'one': 1, 'two': 2}

u Removing from a dictionary: >>> pop_key_val = A.popitem()


• del dict[key] – removes the specified key and its value. >>> print(pop_key_val)
• dict.pop(key) – removes the specified key and returns ('two', 2)
its value. >>> print(A)
• dict.popitem() – removes and returns the last key-value {'one': 1}
pair (in Python 3.7+ it follows insertion order).
• dict.clear() – removes all key-value pairs, making the >>> A.clear()
dictionary empty. >>> print(A)
{}
Dictionar y Processing Methods
u Merging dictionaries:
• dict.update(D) – updates the dictionary with key-value pairs from D. If keys already
exist, their values will be updated.
>>> C = {"five": 5, "six": 6}
>>> B.update(C)
>>> print(B)
{'one': 1, 'two': 2, 'three': 3, 'four': 'IV', 'five': 5, 'six': 6}

• new_dict = {**D1, **D2, …} – merges multiple dictionaries into a new dictionary.


Principle: The double asterisks ** unpack dictionaries into keyword arguments, and
{} recombines them into a new dictionary.
>>> D = {"seven": 7, "eight": 8}
>>> newDict = {**B, **D}
>>> print(newDict)
{'one': 1, 'two': 2, 'three': 3, 'four': 'IV', 'five': 5, 'six': 6 , 'seven': 7, 'eight': 8}
Shallow Copy vs. Deep Copy
in Lists and Dictionaries
u If a list or dict contains mutable objects, a shallow copy only copies the memory
addresses of the elements.
u To create a completely independent copy, use the deep copy function copy.deepcopy().
Dictionar y Comprehension
u Similar to list comprehension, Python provides a concise dictionary
comprehension syntax for creating dictionaries.
HW2-1

u The formula for converting Celsius temperature C to Fahrenheit


temperature F is given as:
F=C×1.8+32
u Design functions based on the following conditions:
• Write a function CtoF1 with no return value that converts Celsius
to Fahrenheit and prints the result.
• Write a function CtoF2 with a return value that converts Celsius to
Fahrenheit, returns the result, and then prints it.
HW2-2

1. Discuss why the following code results in an UnboundLocalError


error message.
2. How can it be modified?
HW2-3
u Write a function fibo(n) to compute the Fibonacci sequence
according to the following rules and allow the user to input the
number of Fibonacci numbers to display:
• When n=1, fibo(n)=fibo(1)=1
• When n=2, fibo(n)=fibo(2)=1
• When n>2, fibo(n)=fibo(n−1)+fibo(n−2)
u Example:
• [Input] 10
• [Output] 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
HW2-4
u Write a Python function to check parentheses validity. For example:
1. ( )( ) : Valid (True)
2. ( ( ) : Invalid (False)
3. ( ) ) : Invalid (False)
4. ( )( )( ) : Valid (True)
5. ( ( ( ( ( ) ) ) ) ) : Valid (True)
6. ) ( : Invalid (False)
Simple stack illustration.

Hint: Use a stack (Last In, First Out) to track opening parentheses. When
encountering a closing parenthesis, check if it matches the top of the stack. If
the stack is empty (indicating no corresponding opening parenthesis) or is not
empty after checking all characters (indicating unmatched opening
parentheses), the parentheses in the string are considered invalid.
HW2-5

u Allow the user to enter an English sentence and count the


occurrences of each word.
u Example:
[Input]
Please enter an English sentence: This is a pen that is a pencil
[Output]
{'This': 1, 'is': 2, 'a': 2, 'pen': 1, 'that': 1, 'pencil': 1}
HW2-6

uThe mathematical constant e is calculated using the following formula:

uDesign a function e(n) that takes an input n from the user and returns
the computed value of e. Then, calculate the values of e for n=5, 10, 100.

Hint:
• Use list comprehension
• Use math.factorial(i) to compute factorials
• Use sum(L) to sum the list elements
HW2-7
u Randomly generate four unique digits (0–9) for the user to guess. Provide hints using "A" and "B":
• "A" means the digit and position are correct.
• "B" means the digit is correct but in the wrong position.
u For example, if the correct answer is 1234 and the user guesses 1245, the program should display
2A1B. The game continues until the user guesses correctly (4A0B).
u Additional requirements:
• After each input, check if the four-digit number contains duplicate digits.
If not, display the hint and the number of attempts.
• The program should include at least the following two functions:
— generate_number(): Generates a unique four-digit number from 0–9.
— check_number(guess, answer): Compares the user's guess with the
correct answer and returns the number of "A" and "B".

You might also like