1264 lines
34 KiB
Plaintext
1264 lines
34 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"# CDS1001 Tutorial 8 Report"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"#### Input your name and student ID in the cell below (<font color='red'>if a cell is not in edit mode, double click it</font>):"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Your name: \n",
|
|
"\n",
|
|
"Your student ID:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"#### Objectives:\n",
|
|
"\n",
|
|
"- Understand why dictionaries and tuples are used in coding \n",
|
|
"- Understand dictionaries as well as their basic operations and functions\n",
|
|
"- Be able to use a dictionary as a set of counters\n",
|
|
"- Be able to traverse keys, values, and key-value pairs of a dictionary\n",
|
|
"- Be able to use translate and maketrans functions to parsing texts\n",
|
|
"- Understand tuples as well their basic operations and functions\n",
|
|
"- Understand how to compare tuples\n",
|
|
"- Be able to use tuples as keys in a dictionary\n",
|
|
"- Be able to sort keys of a dictionary, and to use tuples and lists to sort values of a dictionary (following the Decorate-Sort-Undecroate Pattern)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## **Instructions for the report**:\n",
|
|
"* Follow Section 1 and Section 2 of the tutorial instruction to launch Python IDLE through Anaconda Navigation.\n",
|
|
"* Refer to Section 2.2 of the tutorial instruction to open tutorial 8 report\n",
|
|
"* Complete Parts 1-6 led by the lecturer\n",
|
|
"* Complete Part 7 independently\n",
|
|
"* Follow Section 3 of the tutorial instruction to save the report and zip the report folder. The zip file is named as CDS1001T8Report{your student_id}.zip (e.g., if student_id is 1234567, then the zip file's name is CDS1001T8Report1234567.zip). <font color='red'>The zip file needs to include the following files:\n",
|
|
" - an .ipynb file of this tutorial report \n",
|
|
" - image files of flowcharts or screenshots used in this tutorial report </font> \n",
|
|
"* Submit the zip file of the report folder to the Moodle. The submission due date is **<font color='red'>21 Nov 2023, 11:55PM</font>**"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### Part 1 Dictionary: Basics "
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"#### 1.1. Execute the codes below, and add comments to explain each line of the codes (4 points):"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (a)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"scores = {'CDS1001': 'A-', 'CDS1002':'A+', 'CDS2003':'B', 'CDS3001':'A'} # declare variable scores and assign dictionary\n",
|
|
"print(scores['CDS1001']) # get by key \"CDS1001\"\n",
|
|
"scores['CDS1001'] = 'A' # store to the dictionary \"CDS1001\" with \"A\"\n",
|
|
"print(scores) # print dictionary\n",
|
|
"scores['CDS2003'] = 'B+' # store to the dictionary \"CDS2003\" with \"B+\"\n",
|
|
"print(scores) # print dictionary"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (b)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"scores = {'CDS1001': 'A-', 'CDS1002':'A+', 'CDS2003':'B', 'CDS3001':'A'} # declare variable scores with dictionary\n",
|
|
"print(scores.pop('CDS2003')) # pop the value of dictionary with key \"CDS2003\"\n",
|
|
"print(scores) # show the value of dictionary, should be 3 as \"CDS2003\" were popped\n",
|
|
"print(scores.pop('CDS3003', -1)) # pop the value of dictionary with key \"CDS3003\", nothing matched\n",
|
|
"print(scores) # show the value of dictionary, should be nothing changed as nothing popped.\n",
|
|
"del scores['CDS1001'] # delete dictionary with key \"CDS1001\"\n",
|
|
"print(scores) # show the value of dictionary, should be 2 as element delete in previous step"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"#### 1.2. Execute the code below, explain the errors received, and discuss how to fix the errors (6 points):"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (a)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"scrolled": true
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"scores = ['CDS1001': 'A-', 'CDS1002':'A+', 'CDS2003':'B', 'CDS3001':'A']"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"It should use `{}` instead when initialize a dictionary."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"scrolled": true
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"# write the corrected code below:\n",
|
|
"scores = {'CDS1001': 'A-', 'CDS1002':'A+', 'CDS2003':'B', 'CDS3001':'A'}"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (b)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"scrolled": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"scores = {'CDS1001': 'A-', 'CDS1002':'A+', 'CDS2003':'B', 'CDS3001':'A'}\n",
|
|
"scores.append('CDS4001', 'B-')"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"dictionary have no definition of `append` method.\n",
|
|
"Essentially we cannot add dictionary element with `append`"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# write the corrected code below:\n",
|
|
"scores = {'CDS1001': 'A-', 'CDS1002':'A+', 'CDS2003':'B', 'CDS3001':'A'}\n",
|
|
"scores['CDS4001']='B-'\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (c)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"scrolled": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"scores = {'CDS1001': 'A-', 'CDS1002':'A+', 'CDS2003':'B', 'CDS3001':'A'}\n",
|
|
"scores.pop('CDS1002')\n",
|
|
"del scores['CDS1002']"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"Key \"CDS1002\" not exist after popped."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"scrolled": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"# write the corrected code below:\n",
|
|
"scores = {'CDS1001': 'A-', 'CDS1002':'A+', 'CDS2003':'B', 'CDS3001':'A'}\n",
|
|
"scores.pop('CDS1002')\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"#### 1.3.Write codes for the following tasks (6 points):"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"#(1) In the line below, define a dictionary variable named student_names with keys representing student id, and \n",
|
|
"# values representing student names, by using values for the following two students: \n",
|
|
"# Student 1: name - 'Adam', id - 'lu123'\n",
|
|
"# Student 2: name - 'Alice', id - 'lu321'\n",
|
|
"student_names = {'lu123': 'Adam', 'lu321': 'Alice'}\n",
|
|
"\n",
|
|
"\n",
|
|
"#(2) In the line below, add an item to the dictionary variable student_names for the student named 'Bob' \n",
|
|
"# and student id 'lu231'\n",
|
|
"student_names['lu231'] = 'Bob'\n",
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"#(3) In the line below, remove the item for the student with an id 'lu321'\n",
|
|
"del student_names['lu321']\n",
|
|
"\n",
|
|
"\n",
|
|
"print(student_names)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### Part 2 Using Dictionary as a Set of Counters"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"#### 2.1. Password Checker\n",
|
|
"\n",
|
|
"Write a program to prompt for a user to input a line of password, and to print 'pass' if the password contains no character more than twice, and print 'fail' otherwise\n",
|
|
"\n",
|
|
"Sample input/output:\n",
|
|
"\n",
|
|
" Enter a password: AabBcCAabBcC\n",
|
|
" pass\n",
|
|
" \n",
|
|
" Enter a password: AabBcCAabBcCa\n",
|
|
" fail"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### Question 1: Explain how you are going to define a dictionary variable ``char_count`` that represents the number of times that each character appears in the input password? What are its keys and value? (2 points)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"```python\n",
|
|
"char_count[c] = char_count[c]+1\n",
|
|
"```\n",
|
|
"\n",
|
|
"using dictionary with character as a key, we can count the occurence."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### Question 2: Explain how you are going to define a boolean variable ``flag_fail`` that indicates whether or not there exists a character that appears in the password for more than twice. What's its initial value? (2 points)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"```python\n",
|
|
"for v in char_count.values():\n",
|
|
" if (v > 2) :\n",
|
|
" flag_fail = True\n",
|
|
"```\n",
|
|
"\n",
|
|
"iterate each values of `char_count`. if any value more than 2 means fail."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### Question 3: Explain how you are going to use a for loop to traverse each character ``c`` appearing in the input password. For each character ``c`` traversed, how are you going to update the dictionary variable ``char_count`` and how are you going to update the boolean variable ``flg_fail``? (2 points)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"```python\n",
|
|
" for c in test_password:\n",
|
|
" if (c in char_count.keys()):\n",
|
|
" char_count[c] = char_count[c]+1\n",
|
|
" else:\n",
|
|
" char_count[c]=1\n",
|
|
"```\n",
|
|
"\n",
|
|
"for each character `c`, if `c` found in dictionary `char_count`, add the value by 1. or else initialze it.\n",
|
|
"\n",
|
|
"finally we can get the character occurence after iterate the whole string"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### Question 4: Draw a flow chart to explain how the code will work. (2 points)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
""
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": []
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### Question 5: Write the code: (6 points)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"#edit this cell to write your code\n",
|
|
"def check_fail(test_password):\n",
|
|
" char_count = {}\n",
|
|
" flag_fail = False\n",
|
|
" for c in test_password:\n",
|
|
" if (c in char_count.keys()):\n",
|
|
" char_count[c] = char_count[c]+1\n",
|
|
" else:\n",
|
|
" char_count[c]=1\n",
|
|
"\n",
|
|
" for v in char_count.values():\n",
|
|
" if (v > 2) :\n",
|
|
" flag_fail = True\n",
|
|
"\n",
|
|
" return \"fail\" if flag_fail else \"pass\"\n",
|
|
"\n",
|
|
"for i in range(0,2):\n",
|
|
" test= input(\"Enter a password: \")\n",
|
|
" print(check_fail(test))\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### Question 6: Execute and test the code by at least two different inputs: (2 points)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"```\n",
|
|
"Enter a password: AabBcCAabBcC\n",
|
|
"pass\n",
|
|
"Enter a password: AabBcCAabBcCa\n",
|
|
"fail\n",
|
|
"```"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### Part 3 Loops and Dictionaries"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"#### 3.1. Write codes for the following tasks (4 points):"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (a)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"scores = {'CDS1001': 'A-', 'CDS1002':'A+', 'CDS2003':'B', 'CDS3001':'A'}\n",
|
|
"\n",
|
|
"#In the line below, print the keys, values, and items of the list scores:\n",
|
|
"\n",
|
|
"print(scores.keys())\n",
|
|
"print(scores.values())\n",
|
|
"print(scores.items())\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (b)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"scores = {'CDS1001': 'A-', 'CDS1002':'A+', 'CDS2003':'B', 'CDS3001':'A'}\n",
|
|
"\n",
|
|
"#In the line below, write a loop to print each pair of key and value of the list above in separated lines, \n",
|
|
"#where key and value are separated by ',':\n",
|
|
"\n",
|
|
"for (k,v) in scores.items():\n",
|
|
" print(k + ', ' + v)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### Part 4 Advanced Text Parsing"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"#### 4.1. Execute the codes below, explain how the codes are executed (2 points)."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"scrolled": true
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"my_string = \"1234, 1234, 3221\"\n",
|
|
"print(my_string.translate(str.maketrans('1234', 'abcd', ',')))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The code first creates a string variable `my_string` with the value \"1234, 1234, 3221\". \n",
|
|
"\n",
|
|
"After that it uses the `translate()` method with the `str.maketrans()` function to replace the characters '1', '2', '3', and '4' in the string with 'a', 'b', 'c', and 'd' accordingly. \n",
|
|
"\n",
|
|
"The `','` character is then replaced with an empty string. \n",
|
|
"\n",
|
|
"Finally, it prints the modified string.\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"#### 4.2. Write codes for the following tasks (2 points):"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"password = 'HongKongLingnan4455889'\n",
|
|
"# In the space below, use translate and maketrans methods to transform the password by replacing all digits with '*'\n",
|
|
"\n",
|
|
"transformed_password = password.translate(str.maketrans('0123456789', '**********'))\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### Part 5 Tuples: Concepts"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"#### 5.1. Execute the codes below, and add comments to explain each line of the codes (10 points)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (a)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"scores = ('A+','B','A-','B+','B','B') # declare variable score and initialize it\n",
|
|
"print(scores.count('B')) # print number of \"B\" in scores\n",
|
|
"print(scores.index('B')) # print the position of first occurence of \"B\" in scores\n",
|
|
"print(scores.index('B',4)) # print the position of first occurence of \"B\" in scores, start finding it in 4th\n",
|
|
"print(scores[-1]) # print the last element of scores\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (b)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"scores = ('A+','B','A-','B+','B','B') # declare variable score and initialize it\n",
|
|
"scores = ('C',) + scores[1:] # add element 'C' at the beginning of the list\n",
|
|
"print(scores) # print scores\n",
|
|
"scores = ('C',) * 10 # set the value of scores list to 10 of \"C\"\n",
|
|
"print(scores) # print scores"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (c)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"(user, phone) = 'adam:34113624'.split(':') #split string by \":\" and assign to user and phone\n",
|
|
"print(user,phone) # print it out\n",
|
|
"\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (d)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"dicts = {'adam':'34113624', 'alice':'3413622', 'bob':'35223221'} # declare variable dict and initialize it \n",
|
|
"for user in dicts: # iterate every key in the list and assign it to a variable user \n",
|
|
" print(user) # print it out\n",
|
|
"for phone in dicts.values(): # iterate the values in dicts ad assign it to a variable phone\n",
|
|
" print(phone) # print it out"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (e)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"dicts = {'adam':'34113624', 'alice':'3413622', 'bob':'35223221'} # declare variable dicts\n",
|
|
"dicts['andy'] = '37332322' # assign value '37332322' to key 'andy' into dicts\n",
|
|
"for (user, phone) in dicts.items(): # iterate every items in the dicts and assign it to a variable user and phone\n",
|
|
" print(user,phone) # print it out"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"#### 5.2. Execute the code below, explain the errors received, and discuss how to fix the errors (4 points):"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (a)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"scrolled": true
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"scores = ('C') + ('B','B')\n",
|
|
"print(scores)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"duple did not support `concatenate` method"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"scrolled": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"# write the corrected code below:\n",
|
|
"\n",
|
|
"scores = ('C',) + ('B','B')\n",
|
|
"print(scores)\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (b)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"scrolled": true
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"scores = ('A+','B','A-','B+','B','B')\n",
|
|
"scores[-1] = 'C'\n",
|
|
"print(scores)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"cannot index tuple like what we did in list.\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"scrolled": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"# write the corrected code below:\n",
|
|
"\n",
|
|
"scores = ('A+','B','A-','B+','B','B')\n",
|
|
"print(scores[:-1]+('C',) )\n",
|
|
"print(scores)\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"#### 5.3.Write codes for the following tasks (16 points):"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (a)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"visitors = ('adam', 'alice', 'alice', 'adam', 'bob')\n",
|
|
"#(1) In the line below, print the visitors of the first 3 visits:\n",
|
|
"print(visitors[:3])\n",
|
|
"\n",
|
|
"#(2) In the line below, print how many times alice has visited:\n",
|
|
"print(visitors.count(\"alice\"))\n",
|
|
"\n",
|
|
"#(3) In the line below, print the first position of alice: (the position should count from 1)\n",
|
|
"print(visitors.index('alice'))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (b)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"visitors = ('adam', 'alice', 'alice', 'adam', 'bob')\n",
|
|
"new_visitors = ('bob', 'alan')\n",
|
|
"#(1) In the line below, print the concatenation of the above two tuples:\n",
|
|
"print(visitors+new_visitors)\n",
|
|
"\n",
|
|
"#(2) In the line below, print a tuple that repeat new_visitors for three times:\n",
|
|
"print(new_visitors*3)\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (c)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"emails = {'adam':'adam@ln.edu.hk', 'bob':'bob2@ln.edu.hk', 'alice':'alice0@ln.edu.hk'}\n",
|
|
"# In the line below, write a for loop to traverse all the key-value pairs using variable user_id representing key,\n",
|
|
"\n",
|
|
"# and variable email representing value, print each key-value pair in a line, and key and value are separated by ': '\n",
|
|
"\n",
|
|
"for (user_id, email) in emails.items():\n",
|
|
" print(user_id + ': '+ email)\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (d)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# (1) In the line below, swap the values of x and y without using the tuple assignment:\n",
|
|
"x = 'Alice'\n",
|
|
"y = 'Bob'\n",
|
|
"\n",
|
|
"temp = x\n",
|
|
"x =y \n",
|
|
"y = temp\n",
|
|
"\n",
|
|
"print(x,y)\n",
|
|
"\n",
|
|
"# (2) In the line below, use tuple assignment to swap the values of x and y:\n",
|
|
"x = 'Alice'\n",
|
|
"y = 'Bob'\n",
|
|
"(x,y) = (y, x)\n",
|
|
"\n",
|
|
"\n",
|
|
"print(x,y)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### Part 6 Tuples: Comparing"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"#### 6.1. Execute the codes below, explain how the codes are executed (6 points)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (a)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"t = [(3,4),(3,5),(2,4),(2,3)]\n",
|
|
"t.sort(reverse=True)\n",
|
|
"print(t)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The code creates a list of tuples `t` with four elements. It then sorts the list in reverse order based on the tuples' values. Finally, it prints the sorted list `t`.\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (b)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"scrolled": false
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"scores = {'CDS3108':100, 'CDS3100':96, 'CDS3105': 95, 'CDS3103': 98}\n",
|
|
"print(sorted(list(scores.items())))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The code creates a dictionary scores with:\n",
|
|
"keys representing course codes \n",
|
|
"values representing scores. \n",
|
|
"\n",
|
|
"It converts the dictionary into a list of tuples using the items() method, then sorts the list based on the keys. \n",
|
|
"Finally, it prints the sorted list of tuples.\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### (c)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"scrolled": true
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"scores = {'CDS3108':100, 'CDS3100':96, 'CDS3105': 95, 'CDS3103': 98}\n",
|
|
"lst = []\n",
|
|
"for subject,score in scores.items():\n",
|
|
" lst.append((score,subject))\n",
|
|
"print(lst)\n",
|
|
"print(sorted(lst))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The code creates an empty list `lst`. \n",
|
|
"\n",
|
|
"It iterates over the items in the `scores` dictionary, appending each item as a tuple with the `score` as the first element and the `subject` as the second element to the list. \n",
|
|
"\n",
|
|
"It then sorts the list of tuples based on the scores in ascending order and prints the sorted list.\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"#### 6.2. Read the code below and answer the question (6 points):"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"scrolled": true
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"sales = {'Hong Kong':100, 'Guangzhou':98, 'Tokyo': 95, 'San Francisco': 95}\n",
|
|
"d = {}\n",
|
|
"for (city,sale) in sales.items():\n",
|
|
" d[city] = sale\n",
|
|
"s = sorted(d, reverse=True)\n",
|
|
"for city in s:\n",
|
|
" print(city)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Question:** The above code is developed to sort the cities according to their sales volumes from highest to lowest. However, the output is not correct. \n",
|
|
"\n",
|
|
"Please illustrate \n",
|
|
"\n",
|
|
"(1) what the correct output should be, \n",
|
|
"\n",
|
|
"(2) what the error is in the code, \n",
|
|
"\n",
|
|
"(3) how to correct the error by following a Decorate-Sort-Undecorate pattern."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"(1)\n",
|
|
"Hong Kong\n",
|
|
"Guangzhou\n",
|
|
"Tokyo\n",
|
|
"San Francisco\n",
|
|
"\n",
|
|
"(2)\n",
|
|
"It sort the cities in reverse alphabetical order instead.\n",
|
|
"\n",
|
|
"(3)\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# write the corrected code below:\n",
|
|
"\n",
|
|
"sales = {'Hong Kong':100, 'Guangzhou':98, 'Tokyo': 95, 'San Francisco': 95}\n",
|
|
"d = {}\n",
|
|
"test = []\n",
|
|
"\n",
|
|
"for (city,sale) in sales.items():\n",
|
|
" test.append([sale, {city, sale}])\n",
|
|
"s = sorted(test, reverse=True)\n",
|
|
"for a in s:\n",
|
|
" (city, sale) = a[1]\n",
|
|
" print(city)\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### Part 7 Other Exercises"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"#### 7.1. Lowest Shipping Rates for Origin-Destination Pairs\n",
|
|
"Write a program that prompts a logistics manager to analyze a file of shipping rates, so as to output the lowest shipping rate for each origin-destination pair that appears in the file.\n",
|
|
"\n",
|
|
"The input file name is input by the logistics manager. The input file is ended by a line -1. Except the last line, each line of the file contains a letter string for the origin port, a letter string for the destination port, a shipping rate, and a letter string for the carrier submitted the rate, which are all separated by a space.\n",
|
|
"\n",
|
|
"Sample input file\n",
|
|
"\n",
|
|
" HK RD 1030.0 MMMM\n",
|
|
" HK SF 1000.0 OOCL\n",
|
|
" HK SF 1020.0 MMMM\n",
|
|
" HK RD 1025.0 OOCL\n",
|
|
" -1\n",
|
|
" \n",
|
|
"Sample output on screen:\n",
|
|
" \n",
|
|
" The lowest shipping rate from HK to SF is 1000.0.\n",
|
|
" The lowest shipping rate from HK to RD is 1025.0."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Question 1:** Create two different input files named **input-7-1.txt** and **input-7-2.txt** to include some shipping rates. (1 points)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"input-7-1.txt\n",
|
|
"```\n",
|
|
"HK RD 2030.0 MMMM\n",
|
|
"HK SF 2000.0 OOCL\n",
|
|
"HK SF 2020.0 MMMM\n",
|
|
"HK RD 2025.0 OOCL\n",
|
|
"-1\n",
|
|
"```\n",
|
|
"\n",
|
|
"\n",
|
|
"input-7-2.txt \n",
|
|
"```\n",
|
|
"HK RD 5030.0 MMMM\n",
|
|
"HK SF 5000.0 OOCL\n",
|
|
"HK SF 6020.0 MMMM\n",
|
|
"HK RD 6025.0 OOCL\n",
|
|
"-1\n",
|
|
"```\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Question 2:** For the input file created, what's the expected output? (2 points)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"For input-7-1.txt\n",
|
|
"```\n",
|
|
"The lowest shipping rate from HK to SF is 1000.0.\n",
|
|
"The lowest shipping rate from HK to RD is 1025.0.\n",
|
|
"```\n",
|
|
"\n",
|
|
"For input-7-2.txt\n",
|
|
"```\n",
|
|
"The lowest shipping rate from HK to SF is 5000.0.\n",
|
|
"The lowest shipping rate from HK to RD is 5030.0.\n",
|
|
"```\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Question 3:** For each line of the input file, how to transform it to values for origin port, destination port, shipping rate, and carrier name? How to store these values to different variables? (2 points)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"first of all, strip the ending '\\n'.\n",
|
|
"then split the ' '\n",
|
|
"then we can assign the corrosponding value\n",
|
|
"\n",
|
|
"```\n",
|
|
"[origin_port, destination_port, shipping_rate, carrier_name] = l.strip().split(' ')\n",
|
|
"```"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Question 4:** How to define a variable to store the lowest shipping for each origin-destination pair that appears in the input file? What's its initial value? How to update the variable when reading the file? (3 points)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"define variable with a dictionary\n",
|
|
"```python\n",
|
|
" for l in lines:\n",
|
|
" if (l != '-1'):\n",
|
|
" [origin_port, destination_port, shipping_rate, carrier_name] = l.strip().split(' ')\n",
|
|
" shipping_rate = float(shipping_rate)\n",
|
|
"\n",
|
|
" if (destination_port in lowest_rate.keys()):\n",
|
|
" if shipping_rate < lowest_rate[destination_port]['shipping_rate'] :\n",
|
|
" lowest_rate[destination_port] = {'origin_port': origin_port, 'destination_port': destination_port, 'shipping_rate': shipping_rate, 'carrier_name': carrier_name}\n",
|
|
" else:\n",
|
|
" lowest_rate[destination_port] = {'origin_port': origin_port, 'destination_port': destination_port, 'shipping_rate': shipping_rate, 'carrier_name': carrier_name}\n",
|
|
"\n",
|
|
"```\n",
|
|
"\n",
|
|
"initialize it to read value if not found in dictionary.\n",
|
|
"if destination found in dictionary. compare it to the one existing in it and update if the rate is lower.\n",
|
|
"\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Question 5:** How are you going to use a for loop to output the result? (2 points)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"```python\n",
|
|
" for v in lowest_rate.values():\n",
|
|
" print(f\"The lowest shipping rate from {v['origin_port']}' to {v['destination_port']} is {v['shipping_rate']}.\")\n",
|
|
" print()\n",
|
|
"```\n",
|
|
"\n",
|
|
"\n",
|
|
"iterate the values inside the dictionary and print it out."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Question 6:** Write the code: (6 points)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"#edit this cell to write your code\n",
|
|
"\n",
|
|
"files = ['./input-7-1.txt', './input-7-2.txt']\n",
|
|
"\n",
|
|
"for f in files:\n",
|
|
" with open(f,'r') as fi:\n",
|
|
" lowest_rate = {}\n",
|
|
"\n",
|
|
" lines = fi.readlines()\n",
|
|
" for l in lines:\n",
|
|
" if (l != '-1'):\n",
|
|
" [origin_port, destination_port, shipping_rate, carrier_name] = l.strip().split(' ')\n",
|
|
" shipping_rate = float(shipping_rate)\n",
|
|
"\n",
|
|
" if (destination_port in lowest_rate.keys()):\n",
|
|
" if shipping_rate < lowest_rate[destination_port]['shipping_rate'] :\n",
|
|
" lowest_rate[destination_port] = {'origin_port': origin_port, 'destination_port': destination_port, 'shipping_rate': shipping_rate, 'carrier_name': carrier_name}\n",
|
|
" else:\n",
|
|
" lowest_rate[destination_port] = {'origin_port': origin_port, 'destination_port': destination_port, 'shipping_rate': shipping_rate, 'carrier_name': carrier_name}\n",
|
|
"\n",
|
|
" print(f)\n",
|
|
" for v in lowest_rate.values():\n",
|
|
" print(f\"The lowest shipping rate from {v['origin_port']}' to {v['destination_port']} is {v['shipping_rate']}.\")\n",
|
|
" print()\n",
|
|
"\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"**Question 7:** Execute and test the code by at least two different input files: (2 points)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
""
|
|
]
|
|
}
|
|
],
|
|
"metadata": {
|
|
"kernelspec": {
|
|
"display_name": "Python 3 (ipykernel)",
|
|
"language": "python",
|
|
"name": "python3"
|
|
},
|
|
"language_info": {
|
|
"codemirror_mode": {
|
|
"name": "ipython",
|
|
"version": 3
|
|
},
|
|
"file_extension": ".py",
|
|
"mimetype": "text/x-python",
|
|
"name": "python",
|
|
"nbconvert_exporter": "python",
|
|
"pygments_lexer": "ipython3",
|
|
"version": "3.9.7"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 4
|
|
}
|