Files
004_comission/max015/T07/deliver/CDS1001T7Report.ipynb
louiscklaw acf9d862ff update,
2025-01-31 21:15:04 +08:00

1512 lines
43 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# CDS1001 Tutorial 7 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": [
"<div class=\"alert alert-info\">\n",
" \n",
"Your name: \n",
"\n",
"Your student ID:\n",
" \n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Objectives:\n",
"- Understand why lists are used in coding \n",
"- Be able to understand and apply the two ways to traverse a list using in, len(), and range()\n",
"- Be able to understand and use lists as well their basic operations and functions\n",
"- Understand the similarities and differences of lists and strings\n",
"- Understand the concept of reference and its applications in lists\n",
"- Be able to apply lists and strings together in text and file processing\n",
"- Be able to debug for lists"
]
},
{
"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 7 report\n",
"* Complete Parts 1-4 led by the lecturer\n",
"* Complete Part 5 independently\n",
"* Follow Section 3 of the tutorial instruction to save the report and zip the report folder. The zip file is named as CDS1001T7Report{your student_id}.zip (e.g., if student_id is 1234567, then the zip file's name is CDS1001T7Report1234567.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'>14 Nov 2023 11:55PM</font>**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 1 List Operations and Traverse"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.1. Execute the codes below, and add comments to explain each line of the codes (6 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (a)"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CDS1001\n",
"CDS2003\n",
"CDS4001\n",
"4\n",
"CDS4001\n",
"['CDS3001', 'CDS4001']\n",
"['CDS1001', 'CDS2003']\n",
"['CDS2003', 'CDS3001']\n"
]
}
],
"source": [
"subjects = ['CDS1001', 'CDS2003', 'CDS3001', 'CDS4001'] # declare subjects variable as a list\n",
"print(subjects[0]) # print first element of subjects\n",
"print(subjects[1]) # print second element of subject\n",
"print(subjects[-1]) # print last element of subject\n",
"n = len(subjects) # get number of subjects\n",
"print(n) # print number of subjects\n",
"print(subjects[n-1]) # print last element of subject\n",
"print(subjects[2:]) # print elements starting from the 3rd element\n",
"print(subjects[:2]) # print first 2 element\n",
"print(subjects[1:3]) # print 2 and 3 element"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (b)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['CDS1001', 'CDS2003', 'CDS3001', 'CDS4001', 'CDS2001', 'CDS4013']\n",
"['CDS2001', 'CDS4013', 'CDS2001', 'CDS4013', 'CDS2001', 'CDS4013']\n"
]
}
],
"source": [
"subjects2022 = ['CDS1001', 'CDS2003', 'CDS3001', 'CDS4001'] # declare subjects2022 variable as a list\n",
"new_subjects = ['CDS2001', 'CDS4013'] # declare subjects2022 variable as a list\n",
"subjects2023 = subjects2022 + new_subjects # concentrate two lists\n",
"print(subjects2023) # print the concentrate list\n",
"print(new_subjects*3) # print list 3 times"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (c)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n",
"False\n",
"CDS5154 was not offered in 2022.\n"
]
}
],
"source": [
"subjects2022 = ['CDS1001', 'CDS2003', 'CDS3001', 'CDS4001'] # declare list as subjects2002\n",
"print('CDS1001' in subjects2022) # find \"CDS1001\" in subjects2002 and print the result\n",
"print('CDS3107' in subjects2022) # find \"CDS3107\" in subjects2002 and print the result\n",
"subject = 'CDS5154' # declare string \"CDS5154\" as subject\n",
"if subject not in subjects2022: # try to find \"CDS5154\" in subjects2002\n",
" print('%s was not offered in 2022.' % subject) # print string if not found"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.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": 24,
"metadata": {
"scrolled": true
},
"outputs": [
{
"ename": "TypeError",
"evalue": "'str' object does not support item assignment",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"Input \u001b[0;32mIn [24]\u001b[0m, in \u001b[0;36m<cell line: 2>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m subjects2022 \u001b[38;5;241m=\u001b[39m [\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mCDS1001\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mCDS2003\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mCDS3001\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mCDS4001\u001b[39m\u001b[38;5;124m'\u001b[39m] \n\u001b[0;32m----> 2\u001b[0m subjects2022[\u001b[38;5;241m0\u001b[39m][\u001b[38;5;241m0\u001b[39m] \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mcDS1001\u001b[39m\u001b[38;5;124m'\u001b[39m\n",
"\u001b[0;31mTypeError\u001b[0m: 'str' object does not support item assignment"
]
}
],
"source": [
"subjects2022 = ['CDS1001', 'CDS2003', 'CDS3001', 'CDS4001'] \n",
"subjects2022[0][0] = 'cDS1001' #change the first element of the list to be 'cDS1001'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to explain what are the errors and how to fix them </font> \n",
"\n",
"Problem: \n",
"Actually the first element of subjects2022 `subjects2022[0]` is not a list\n",
"\n",
"Fix: \n",
"subjects2022 = ['CDS1001', 'CDS2003', 'CDS3001', 'CDS4001'] \n",
"subjects2022[0] = 'cDS1001' #change the first element of the list to be 'cDS1001'\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (b)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"ename": "IndexError",
"evalue": "list assignment index out of range",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)",
"Input \u001b[0;32mIn [14]\u001b[0m, in \u001b[0;36m<cell line: 3>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m subjects2022 \u001b[38;5;241m=\u001b[39m [\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mCDS1001\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mCDS2003\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mCDS3001\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mCDS4001\u001b[39m\u001b[38;5;124m'\u001b[39m]\n\u001b[1;32m 2\u001b[0m n \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mlen\u001b[39m(subjects2022)\n\u001b[0;32m----> 3\u001b[0m subjects2022[n] \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mCDS3000\u001b[39m\u001b[38;5;124m'\u001b[39m\n",
"\u001b[0;31mIndexError\u001b[0m: list assignment index out of range"
]
}
],
"source": [
"subjects2022 = ['CDS1001', 'CDS2003', 'CDS3001', 'CDS4001']\n",
"n = len(subjects2022)\n",
"subjects2022[n] = 'CDS3000' #change the last element of the list to be 'CDS3000'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to explain what are the errors and how to fix them </font>\n",
"\n",
"explain:\n",
"element at 4 exceed while 0 - 3 is available\n",
"\n",
"fix:\n",
"```python\n",
"subjects2022 = ['CDS1001', 'CDS2003', 'CDS3001', 'CDS4001']\n",
"n = len(subjects2022)\n",
"subjects2022[-1] = 'CDS3000' #change the last element of the list to be 'CDS3000'\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.3.Write codes for the following tasks (8 points):"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (a)"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"months=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n",
"\n",
"#(1) In the line below, print a slice of the variable months for the first three months:\n",
"print(months[0:3])\n",
"\n",
"#(2) In the line below, print a slice of the variable months for the second three months:\n",
"print(months[0+3:3+3])\n",
"\n",
"#(3) In the line below, print a slice of the variable months for the last three months:\n",
"print(months[0+3*3:3+3*3])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (b)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Jan', 'Feb', 'Mar', 'Apr', 'May']\n"
]
}
],
"source": [
"months = ['Jan', 'Feb', 'Mar']\n",
"#(1) In the line below, use + operator to add 'Apr' and 'May' to months, and print the updated value of months:\n",
"print(months+['Apr','May'])\n",
"\n",
"#(2) In the line below, use * operator to repeat elements in months for 3 times, and print the updated value of months:\n",
"update_months = months*3\n",
"print(update_months)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (c)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['jan', 'Feb', 'Mar']\n"
]
}
],
"source": [
"months = ['Jan', 'Feb', 'Mar']\n",
"\n",
"#(1) In the line below, change the first element of months to be lower cased, and print the updated value of months:\n",
"months[0] = months[0].lower()\n",
"print(months)\n",
"\n",
"#(2) In the line below, change the last element of months to 'March', and print the updated value of months:\n",
"months[2] = \"March\"\n",
"print(months)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (d)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Apr\n",
"Aug\n"
]
}
],
"source": [
"#(1) \n",
"months=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n",
"#In the line below, use for loop without using range to print elements in months starting with 'A':\n",
"months_len = len(months)\n",
"for m in months :\n",
" if (m[0] == \"A\"):\n",
" print(m)\n",
"\n",
"\n",
"#(2) \n",
"sales = [100,200,100,200,150,150,200,160,200,200,130,155]\n",
"#In the line below, use for loop, len() and range() to print the sales data for each month:\n",
"# e.g., Sales of Jan is 100\n",
"# Sales of Feb is 100\n",
"# ......\n",
"for i in range(0, len(sales)):\n",
" print(sales[i])\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.4. For the given list ``subjects2022 = ['CDS1001', 'CDS2003', 'CDS3001', 'CDS4001']``, use three different ways to traverse the elements of the list, and print only subjects with the last digit of 1. i.e. CDS1001, CDS2001, etc(6 points):"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (a) Use for loop without range():"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell to write the code:\n",
"subjects2022 = ['CDS1001', 'CDS2003', 'CDS3001', 'CDS4001'] \n",
"\n",
"for i in subjects2022:\n",
" if (i[-1] == \"1\"):\n",
" print(i)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (b) Use for loop and range():"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell to write the code:\n",
"subjects2022 = ['CDS1001', 'CDS2003', 'CDS3001', 'CDS4001'] \n",
"\n",
"for i in range(0,len(subjects2022)):\n",
" if (subjects2022[i][-1] == \"1\"):\n",
" print(subjects2022[i])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (c) Use while loop:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell to write the code:\n",
"subjects2022 = ['CDS1001', 'CDS2003', 'CDS3001', 'CDS4001'] \n",
"\n",
"i = 0\n",
"while i < len(subjects2022):\n",
" if (subjects2022[i][-1] == \"1\"):\n",
" print(subjects2022[i])\n",
" i +=1 \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 2 List Methods and Functions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.1. (a) Use dir() to show all the available methods for a list object, and (b) use help() to show the usage of function 'reverse' for a list object (3 points)"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']\n"
]
}
],
"source": [
"#edit this cell to write a code for the task (a) of 2.1\n",
"print(dir([]))"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"#edit this cell to write a code for the task (b) of 2.1\n",
"print(help(reversed))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```python\n",
"a = [1,2,3,4,5]\n",
"\n",
"# will print out [5, 4, 3, 2, 1]\n",
"print(list(reversed(a)))\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.2. Execute the codes below, and answer the questions (12 points)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (a)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Jan', 'Feb', 'Mar', 'May']\n"
]
}
],
"source": [
"months=[] \n",
"months.append('Jan') \n",
"months.append('Feb') \n",
"months.extend(['Mar','May']) \n",
"print(months) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Ans:\n",
"\n",
"The code initializes an empty list called months.\n",
"Appends 'Jan' and 'Feb' to it, and then extends it with 'Mar' and 'May'. Finally, it prints the updated months list.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (b)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"months=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] \n",
"months.sort() \n",
"print(months) \n",
"months.sort(reverse=True) \n",
"print(months) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Ans:\n",
"\n",
"The `sort()` function sorts the elements of the months list in ascending order, changing its original order. The `sort(reverse=True)` function sorts the list in descending order, again modifying the original list.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (c)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Jan', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov']\n",
"['Jan', 'Mar', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov']\n",
"['Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov']\n"
]
}
],
"source": [
"months=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] \n",
"months.pop(1) \n",
"months.pop(-1)\n",
"print(months)\n",
"months.remove('Apr')\n",
"print(months)\n",
"del months[:3]\n",
"print(months)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `pop(1)` function removes the element at index 1 from the `months` list, and `pop(-1)` removes the last element. `remove('Apr')` removes the element 'Apr'. `del months[:3]` deletes the first three elements.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (d)"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3\n",
"['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n",
"['Jan', 'Feb', 'Mar', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n"
]
}
],
"source": [
"months=['Jan', 'Feb', 'Mar', 'Apr', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n",
"pos = months.index('Apr')\n",
"print(pos)\n",
"months.insert(pos+1, 'May')\n",
"print(months)\n",
"del months[pos]\n",
"print(months)\n",
"#hint: using help() function to find the use of method index and method insert for a list object"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The code finds the index of 'Apr' in the `months` list using the `index()` method. \n",
"Then, it inserts 'May' after 'Apr' using `insert()`. \n",
"After that, `del` statement removes 'Apr' from the list based on its index and finally print it out."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (e)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"sales = [100,200,100,200,150,150,200,160,200,200,130,155]\n",
"del sales[-3:]\n",
"print(sales)\n",
"del sales[1:3]\n",
"print(sales)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `del sales[-3:]` statement deletes the last three elements from the `sales` list. \n",
"After that, the `del sales[1:3]` statement removes elements at index 1 and 2 from the updated `sales` list. The modified `sales` list is printed twice to show the changes made.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (f)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"sales = [100,200,100,200,150,150,200,160,200,200,130,155]\n",
"print(max(sales), min(sales), sum(sales))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `max(sales)` function returns the maximum value in the sales list.\n",
"The `min(sales)` returns the minimum value.\n",
"The `sum(sales)` returns the sum of all values. \n",
"Finally print the maximum sales, minimum sales and total sales."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.3. Write codes for the following tasks (9 points):"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (a)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"#(1) In the space below, create a list variable basket with an empty value, \n",
"#and print the variable basket\n",
"basket = []\n",
"print(basket)\n",
"\n",
"#(2) In the space below, append an element 'apple' to the list variable basket, \n",
"#and print the variable basket\n",
"basket.append('apple')\n",
"print(basket)\n",
"\n",
"\n",
"#(3) In the space below, append elements in ['banana', 'orange'] to the variable basket, \n",
"#and print the variable basket\n",
"basket.extend(['banana','orange'])\n",
"print(basket)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (b)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
]
}
],
"source": [
"ids = list(range(10))*2\n",
"print(ids)\n",
"\n",
"#(1) In the space below, use del operator to remove the last 3 elements of ids, and print ids\n",
"ids_del = list(ids)\n",
"del ids_del[-3:]\n",
"print(ids_del)\n",
"\n",
"#(2) In the space below, use pop method to remove the third element of ids, and print ids\n",
"ids_pop = list(ids)\n",
"ids_pop.pop(2)\n",
"print(ids_pop)\n",
"\n",
"#(3) In the space below, use while loop, in operator, and remove method to remove all the elements of ids equal to 1, and print ids\n",
"ids_while = list(ids)\n",
"i = 0\n",
"while 1 in ids_while:\n",
" ids_while.remove(1)\n",
"\n",
"print(ids_while)\n",
"\n",
"#(4) Sort the elements in ids in a descending order, and print ids\n",
"ids_sort = list(ids)\n",
"ids_sort = sorted(ids)\n",
"print(ids_sort)\n",
"\n",
"print(ids)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (c)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"#(1) In the space below, use for loop to create a list that contains all the even numbers between 1 to 99, \n",
"# and store the list in the variable even_number1:\n",
"even_number1 = []\n",
"for i in range(0,99+1):\n",
" if ( i % 2 == 0):\n",
" even_number1.append(i)\n",
"print(even_number1)\n",
"\n",
"#(2) In the space below, use range function to create a list that contains all the even numbers between 1 to 99, \n",
"# and store the list in the variable even_number2:\n",
"# Hint: use help(range) to understand the usage of range function\n",
"even_number1 = list(range(0,99,2))\n",
"print(even_number1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 3 References"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 3.1. Execute the codes below, and answer the questions (12 points)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (a)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Jan', 'Feb', 'Mar']\n",
"['Jan', 'Feb', 'Mar']\n",
"['JAN', 'Feb', 'Mar']\n",
"['JAN', 'Feb', 'Mar']\n",
"['JAN', 'Feb', 'Mar']\n",
"['jan', 'Feb', 'Mar']\n"
]
}
],
"source": [
"months=['Jan', 'Feb', 'Mar']\n",
"months2 = months\n",
"months2[0].upper()\n",
"print(months)\n",
"print(months2)\n",
"\n",
"months2 = months\n",
"months2[0] = months2[0].upper()\n",
"print(months)\n",
"print(months2)\n",
"\n",
"months2 = months.copy() #Hint: use help() function to understand the usage of method copy() of a list object\n",
"months2[0] = months2[0].lower()\n",
"print(months)\n",
"print(months2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"- (1) For Line 1 and Line 2 of the output: why are both ``months[0]`` and ``months2[0]`` not changed to 'JAN'?\n",
"\n",
"Answer: \n",
"\n",
"It is because the result(uppercase of text) were not assigned to the months2 list.\n",
"\n",
"\n",
"- (2) For Line 3 and Line 4 of the output: why are both ``months[0]`` and ``months2[0]`` changed to 'JAN'?\n",
"\n",
"Answer: \n",
"\n",
"It is because the result(uppercase of text) were assigned to the months2 list.\n",
"\n",
"- (3) For Line 5 and Line 6 of the output: Why is ``months[0]`` still equal to 'JAN', but why is ``months2[0]`` changed to 'jan'?\n",
"\n",
"Answer: \n",
"\n",
"it is because the `months2` is a copy of the `months`. compare to the former codes example. They are `months2` is an references of `months`."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (b)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"def insert_head1(lst, element):\n",
" lst = [element] + lst\n",
" \n",
"def insert_head2(lst, element):\n",
" lst.insert(0,element) #Hint: use help() to understand the usage of method insert of a list object\n",
" \n",
"def insert_head3(lst, element):\n",
" lst = [element] + lst\n",
" return lst\n",
" \n",
"months=['Mar', 'Apr']\n",
"\n",
"insert_head1(months, 'Feb')\n",
"print(months)\n",
"\n",
"insert_head2(months, 'Feb')\n",
"print(months)\n",
"\n",
"months = insert_head3(months, 'Jan')\n",
"print(months)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- (1) For Line 1 of the output: why is ``months`` not changed?\n",
"\n",
"Answer: \n",
"\n",
"The insert_head1 function creates a new list by concatenating [element] with lst, but it does not modify the original months list. Therefore, when print(months) is called, it displays the original unchanged months list.\n",
"\n",
"- (2) For Line 2 of the output: How is ``months`` changed? Why?\n",
"\n",
"Answer: \n",
"\n",
"The `insert_head2` function uses the `insert()` method of a list object to add the `element` at index 0, effectively inserting it at the beginning of the `lst` list. This modifies the original `months` list in-place, so when `print(months)` is called, it displays the updated `months` list.\n",
"\n",
"- (3) For Line 3 of the output: How is ``months`` changed? Why?\n",
"\n",
"Answer: \n",
"\n",
"First of all, the months values is ['Feb', 'Mar', 'Apr'] when program runs.\n",
"\n",
"In the `insert_head3` function, a new list is created by concatenating `[element]` with the `lst` list, resulting in ['Jan', 'Feb', 'Mar', 'Apr']. This new list is then returned and assigned to `months`, effectively replacing the original list with the new one."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 3.2. Write codes for the following tasks (4 points):"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (a)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 4]\n"
]
}
],
"source": [
"#Revise the code in the space below, to define a function add_two(t) where parameter t is a list of integers,\n",
"#so that the function adds each number in list t by two.\n",
"#For example, if nums=[1,2,3,4], then after calling add_two(nums), nums becomes [3,4,5,6]\n",
"#Hint: use for loop and len()\n",
"\n",
"\n",
"def add_two(t):\n",
" for i in range(len(t)):\n",
" t[i] += 2\n",
" return t\n",
"\n",
"nums=[1,2,3,4]\n",
"print(nums)\n",
"print(add_two(nums))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (b)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"cities = ['Hong Kong', 'Shanghai', 'New York']\n",
"\n",
"#(1) In the space below, create a new list that has the same elements as cities, and stores the new list in variable cc\n",
"cc = list(cities)\n",
"\n",
"#(2) Remove the first element of cc, but keep all the three elements in cities\n",
"del cc[0]\n",
"\n",
"print(cities)\n",
"print(cc)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 4 List and Strings"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 4.1. Execute the codes below, and answer the questions (4 points)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"months=['Jan', 'Feb', 'Mar'] \n",
"str_months = ', '.join(months) \n",
"print(str_months) \n",
"str_months = str_months + ', Apr' \n",
"months = str_months.split(',') \n",
"print(months) \n",
"months = str_months.split(', ')\n",
"print(months) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- (1) What is ``', '.join(months)`` doing?\n",
"\n",
"Answer: \n",
"The `', '.join(months)` statement joins the elements of the `months` list into a single string, while it is separated by `', '`. \n",
"\n",
"- (2) The 2nd line and 3rd line of the output are different. Why?\n",
"\n",
"Answer: \n",
"it is because the split matches nothing in 2nd line and found match in 3rd line.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 4.2. Write codes for the following tasks (2 points):"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"current_time = '09:14:16'\n",
"# In the space below, use split method of a string to obtain a list of three strings that represent \n",
"# hour, minute, second of the current_time, respectively, and then print the list of the three strings obtained\n",
"\n",
"time_list = current_time.split(':')\n",
"print(time_list[0])\n",
"print(time_list[1])\n",
"print(time_list[2])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 4.3. Multiple Votes (15 points)\n",
"Your department has a poll on the location to celebrate the new year, among three candidates, including 'Hong Kong Disney Land Hotel', \"Hotel ICON', and \"Hong Kong Ocean Park Marriott Hotel\". Each vote can contain one or two candidates. Write a program to count votes from a text file named 'votes.txt'. Each line of the text file (except the last line) contains a vote, which includes one or two hotel names (separated by a comma and a space), with each string equal to 'Disney', 'Hotel ICON', or 'Ocean Park'. The last line of the file contains -1.\n",
"\n",
"A sample file of votes.txt contains the following four lines:\n",
"\n",
" Disney, Ocean Park\n",
" Hotel ICON, Ocean Park\n",
" Hotel ICON\n",
" Ocean Park\n",
" -1\n",
" \n",
"Your program writes the result to a file named 'result.txt':\n",
"\n",
"For the sample file of votes.txt, the file 'result.txt' contains the following three lines:\n",
" \n",
" Disney: 1\n",
" Hotel ICON: 2\n",
" Ocean Park: 3\n",
" \n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 4.3.1: Create an input file votes.txt in the report folder, to include some votes for a test, which shall have more lines than the sample described above, but shall also include votes that contain one or two hotel names."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Copy the votes.txt in this cell:</font>\n",
"\n",
"```\n",
"Disney, Ocean Park\n",
"Hotel ICON, Ocean Park\n",
"Hotel ICON\n",
"Ocean Park\n",
"Disney, Ocean Park\n",
"Hotel ICON, Ocean Park\n",
"Hotel ICON\n",
"Ocean Park\n",
"Disney, Ocean Park\n",
"Hotel ICON, Ocean Park\n",
"Hotel ICON\n",
"Ocean Park\n",
"-1\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 4.3.2: For the votes.txt created, what's the expected output to file result.txt?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```\n",
"Disney: 3\n",
"Hotel ICON: 6\n",
"Ocean Park: 9\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 4.3.3: For each line of the file, how are you going to transform it to a list of hotel names? How are you going to remove leading and trailing white spaces of each hotel's name? How are you going to traverse each hotel name in the list and update the hotel's vote, accordingly?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"I will transform list of hotel names using split, split(', ') can split the lines with multiple hotel names into a line.\n",
"\n",
"Using count can count the hotel wanted in the list and that the vote.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 4.3.4: Write the code for this task."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#edit this cell to write the program\n",
"\n",
"hotel = []\n",
"\n",
"with open(\"./votes.txt\",'r') as fi:\n",
" lines = fi.readlines()\n",
" for l in lines:\n",
" l2 = l.strip()\n",
" hotel.extend(l2.split(', '))\n",
"\n",
"print(hotel)\n",
"\n",
"print(\"Disney: \" + str(hotel.count(\"Disney\")))\n",
"print(\"Hotel ICON: \" + str(hotel.count(\"Hotel ICON\")))\n",
"print(\"Ocean Park: \" + str(hotel.count(\"Ocean Park\")))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 4.3.5: Execute the code and show the output"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```\n",
"Disney: 3\n",
"Hotel ICON: 6\n",
"Ocean Park: 9\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 5 Other Exercises"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 5.1. Letters to Customers (15 points)\n",
"\n",
"Consider the following letter template, in which {customer_name} and {product_name} need to be specified.\n",
"\n",
" Dear {customer_name},\n",
" Thank you for purchasing {product_name}. \n",
" Wish you Merry Christmas and Happy New year!\n",
"\n",
" Regards,\n",
" Company LU\n",
"\n",
"Your company needs to prepare letters for multiple customers and products that they have purchased. \n",
"\n",
"Write a program to generate a letter from the template for each customer, where data about the customers and the products purchased are read from an input file. \n",
"\n",
"Each line of the input file (except the last line) contains a customer's ID, the customer's name, and the purchased product's name, separated by a comma and a space. The last line of the input file is -1.\n",
"\n",
"For each line of the input file (except the last line), the program needs to generate a letter as a text file with the file name being 'letter-{customer_id}.txt', where {customer_id} represents the customer's ID.\n",
"\n",
"Sample Input File (sales.txt)\n",
"\n",
" 000001, Alice, Laster Printer X50\n",
" 000002, Bob, Laster Printer X51\n",
" 000003, Carl, LED Monitor M310\n",
" -1\n",
" \n",
"\n",
"Sample Output (including three text files):\n",
" \n",
"*letter-000001.txt*:\n",
" \n",
" Dear Alice,\n",
" Thank you for purchasing Laser Printer X50. \n",
" Wish you Merry Christmas and Happy New year!\n",
"\n",
" Regards,\n",
" Company LU\n",
"\n",
"\n",
"*letter-000002.txt*:\n",
" \n",
" Dear Bob,\n",
" Thank you for purchasing Laser Printer X51. \n",
" Wish you Merry Christmas and Happy New year!\n",
"\n",
" Regards,\n",
" Company LU\n",
"\n",
"\n",
"*letter-000003.txt*:\n",
" \n",
" Dear Carl,\n",
" Thank you for purchasing LED Monitor M310. \n",
" Wish you Merry Christmas and Happy New year!\n",
"\n",
" Regards,\n",
" Company LU\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 5.1.1: Create an input file named sales.txt (stored in the report folder), which shall have more lines than the sample input file above."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```\n",
"000001, John Lee, Laster Printer X50\n",
"000002, Eric Chan, Laster Printer X51\n",
"000003, Paul Chan, LED Monitor M310\n",
"-1\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 5.1.2: For the input file created, what's the expected content of each output file?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`letter-000001.txt`\n",
"Dear John Lee,\n",
"Thank you for purchasing Laster Printer X50. \n",
"Wish you Merry Christmas and Happy New year!\n",
"\n",
"Regards,\n",
"Company LU\n",
"\n",
"`letter-000002.txt`\n",
"Dear Eric Chan,\n",
"Thank you for purchasing Laster Printer X51. \n",
"Wish you Merry Christmas and Happy New year!\n",
"\n",
"Regards,\n",
"Company LU\n",
"\n",
"`letter-000003.txt`\n",
"Dear Paul Chan,\n",
"Thank you for purchasing LED Monitor M310. \n",
"Wish you Merry Christmas and Happy New year!\n",
"\n",
"Regards,\n",
"Company LU\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 5.1.3: Explain how are you going to transform each line of the input file to a list of strings with no leading or trailing white spaces, and how to assign strings from the list to variables that store data of customer_id, customer_name, product_name?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Answer:\n",
"\n",
"I can use `strip` to trim the leading and trailing space of lines.\n",
"\n",
"`[customer_id, customer_name, product_name] = l.strip().split(', ')` can split the values and assign it accordingly.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 5.1.4: Write the code:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"hotel = []\n",
"\n",
"template = '''\n",
"Dear {customer_name},\n",
"Thank you for purchasing {product_name}. \n",
"Wish you Merry Christmas and Happy New year!\n",
"\n",
"Regards,\n",
"Company LU\n",
"'''.strip()\n",
"\n",
"with open('./sales.txt','r') as fi:\n",
" lines = fi.readlines()\n",
" for l in lines:\n",
" if (l != '-1'):\n",
" [customer_id, customer_name, product_name] = l.strip().split(', ')\n",
" letter = template.replace('{customer_name}', customer_name).replace('{product_name}',product_name)\n",
" filename = 'letter-'+customer_id+'.txt'\n",
" with open(filename, 'w+') as fw:\n",
" fw.writelines(letter)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 5.2.5: Execute and test the code:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![](./txt_content.png)"
]
}
],
"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.11.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}