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

1713 lines
51 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# CDS1001 Tutorial 6 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 strings and files are used in coding\n",
"- Be able to understand and use strings and their basic operations and functions\n",
"- Be able to understand and use files to read and write data\n",
"- Be able to use dir() and help() to learn how to use functions of objects\n",
"- Be able to understand and apply the parsing-extracting pattern in coding for text processing"
]
},
{
"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 6 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 CDS1001T6Report{your student_id}.zip (e.g., if student_id is 1234567, then the zip file's name is CDS1001T6Report1234567.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'>7 Nov 2023 11:55 PM</font>**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 1 String Operations"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.1. Execute the codes below, and explain the meaning of the codes (10 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (a) Add comment to each line of the code below to explain the meanings of the code:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"scrolled": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"n\n",
"k\n",
"31\n",
"n email from kenfong@ln.edu.hk\n",
"An email from kenfong@ln.edu.h\n",
"email\n"
]
}
],
"source": [
"s = 'An email from kenfong@ln.edu.hk' #define a string s\n",
"print(s[1]) # print out the second character\n",
"print(s[-1]) # print out the last character \n",
"len_s = len(s) # get the length of string, store it in len_s\n",
"print(len_s) # print the length len_s\n",
"print(s[1:]) # print the string ignore the first one\n",
"print(s[:-1]) # print the string ignore the last one\n",
"print(s[3:8]) # print the string starting from 4th letter to 8th letter"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (b) Add comment to each line of the code below to explain the meaning of the code:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"----------------------------------------------------------\n",
"Notification: An email from kenfong@ln.edu.hk is received!\n",
"----------------------------------------------------------\n"
]
}
],
"source": [
"email = 'kenfong@ln.edu.hk' # define a string email\n",
"s = 'Notification: An email from '+email+ ' is received!' # concat string the the email defined above\n",
"s_len = len(s) # get the length of string \n",
"print('-'*(s_len)) # print \"-\" with total length equals to s at line 2\n",
"print(s) # print string defined at 2nd line\n",
"print('-'*(s_len)) # print \"-\" with total length equals to s at line 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (c) Add comment to each line of the code below to explain the meaning of the code:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The email address belongs to LingU!\n"
]
}
],
"source": [
"email = 'kenfong@ln.edu.hk' # define string to variable named email\n",
"if 'ln.edu.hk' in email: # check if ln.edu.hk found in variable email\n",
" print('The email address belongs to LingU!') # print this string if found \n",
"else:\n",
" print('The email address does not belong to LingU!') # print this string if not found"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (d) Add comment to each line of the code below to explain the meaning of the code:"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"scrolled": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"False\n",
"True\n",
"False\n"
]
}
],
"source": [
"print('AAA'=='aaa') #A refer to 65 in ascii code, and a refers to 97 in ascii code, so 'AAA' should be less than 'aaa'\n",
"print('AAA'<'aaa') # A refer to 65 in ascii code, and a refers to 97 in ascii code, so print true here\n",
"print('Ken Fong'>'Fong Ken') # compare two string character by character, left to right. As \"e\" is smaller than \"o\", so False"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (e) Add comment to each line of the code below to explain the meaning of the code:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"text = 'Subject: Greeting\\nSender: Ken Fong\\nRecipient: All\\nBody: Merry Christmas and Happy New Year!\\n' # define a string text\n",
"print('-'*50) # print \"-\" with 50 character long\n",
"for c in text: # for every character in text\n",
" print(c,end='') # print character \"c\", without default new line ending\n",
" if c =='\\n': # if the character is a new line\n",
" print('-'*50) # print \"-\" with 50 character long"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.2. Execute the code below, explain the errors received, and discuss how to fix the errors (8 points):"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (a) "
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"scrolled": true
},
"outputs": [
{
"ename": "IndexError",
"evalue": "string index out of range",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb Cell 20\u001b[0m line \u001b[0;36m2\n\u001b[1;32m <a href='vscode-notebook-cell:/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb#X25sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m choice \u001b[39m=\u001b[39m \u001b[39m'\u001b[39m\u001b[39mA\u001b[39m\u001b[39m'\u001b[39m\n\u001b[0;32m----> <a href='vscode-notebook-cell:/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb#X25sZmlsZQ%3D%3D?line=1'>2</a>\u001b[0m \u001b[39mif\u001b[39;00m choice[\u001b[39m1\u001b[39;49m]\u001b[39m==\u001b[39m\u001b[39m'\u001b[39m\u001b[39mA\u001b[39m\u001b[39m'\u001b[39m: \u001b[39m# Index out of range, we do not index 1, we only have index 0 in this code.\u001b[39;00m\n\u001b[1;32m <a href='vscode-notebook-cell:/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb#X25sZmlsZQ%3D%3D?line=2'>3</a>\u001b[0m \u001b[39mprint\u001b[39m(\u001b[39m'\u001b[39m\u001b[39mTrue\u001b[39m\u001b[39m'\u001b[39m) \u001b[39m# \u001b[39;00m\n",
"\u001b[0;31mIndexError\u001b[0m: string index out of range"
]
}
],
"source": [
"choice = 'A'\n",
"if choice[1]=='A': # Index out of range, we do not index 1, we only have index 0 in this code.\n",
" print('True')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'> Edit this cell to explain the errors and illustrate how to fix the errors: </font>\n"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n"
]
}
],
"source": [
"choice = 'A'\n",
"if choice[0]=='A': \n",
" print('True') "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (b)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"scrolled": false
},
"outputs": [
{
"ename": "TypeError",
"evalue": "can only concatenate str (not \"int\") to str",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb Cell 24\u001b[0m line \u001b[0;36m2\n\u001b[1;32m <a href='vscode-notebook-cell:/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb#X32sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m rate \u001b[39m=\u001b[39m \u001b[39m10\u001b[39m\n\u001b[0;32m----> <a href='vscode-notebook-cell:/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb#X32sZmlsZQ%3D%3D?line=1'>2</a>\u001b[0m message \u001b[39m=\u001b[39m \u001b[39m'\u001b[39;49m\u001b[39mshipping rate = \u001b[39;49m\u001b[39m'\u001b[39;49m \u001b[39m+\u001b[39;49m rate\n\u001b[1;32m <a href='vscode-notebook-cell:/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb#X32sZmlsZQ%3D%3D?line=2'>3</a>\u001b[0m \u001b[39mprint\u001b[39m(message)\n",
"\u001b[0;31mTypeError\u001b[0m: can only concatenate str (not \"int\") to str"
]
}
],
"source": [
"rate = 10\n",
"message = 'shipping rate = ' + rate # rate is a integer, cannot concatenate a string with a integer\n",
"print(message)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'> Edit this cell to explain the errors and illustrate how to fix the errors: </font>\n"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"shipping rate = 10\n"
]
}
],
"source": [
"rate = 10\n",
"message = 'shipping rate = ' + str(rate)\n",
"print(message)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (c) "
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"scrolled": false
},
"outputs": [
{
"ename": "ValueError",
"evalue": "could not convert string to float: '$100'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb Cell 28\u001b[0m line \u001b[0;36m2\n\u001b[1;32m <a href='vscode-notebook-cell:/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb#X36sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m input_rate \u001b[39m=\u001b[39m \u001b[39m'\u001b[39m\u001b[39m$100\u001b[39m\u001b[39m'\u001b[39m\n\u001b[0;32m----> <a href='vscode-notebook-cell:/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb#X36sZmlsZQ%3D%3D?line=1'>2</a>\u001b[0m rate \u001b[39m=\u001b[39m \u001b[39mfloat\u001b[39;49m(input_rate)\n\u001b[1;32m <a href='vscode-notebook-cell:/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb#X36sZmlsZQ%3D%3D?line=2'>3</a>\u001b[0m \u001b[39mprint\u001b[39m(rate)\n",
"\u001b[0;31mValueError\u001b[0m: could not convert string to float: '$100'"
]
}
],
"source": [
"input_rate = '$100'\n",
"rate = float(input_rate) # cannot parse \"$\" into a number\n",
"print(rate)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'> Edit this cell to explain the errors and illustrate how to fix the errors: </font>\n"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"100.0\n"
]
}
],
"source": [
"input_rate = '$100'\n",
"rate = float(input_rate[1:]) \n",
"print(rate)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (d) "
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"--------------------------------------------------\n",
"92\n",
"Subject: Greeting\n",
"--------------------------------------------------\n",
"Sender: Ken Fong\n",
"--------------------------------------------------\n",
"Recipient: All\n",
"--------------------------------------------------\n",
"Body: Merry Christmas and Happy New Year!\n",
"--------------------------------------------------\n"
]
},
{
"ename": "IndexError",
"evalue": "string index out of range",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb Cell 32\u001b[0m line \u001b[0;36m7\n\u001b[1;32m <a href='vscode-notebook-cell:/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb#X43sZmlsZQ%3D%3D?line=4'>5</a>\u001b[0m i\u001b[39m=\u001b[39m\u001b[39m0\u001b[39m\n\u001b[1;32m <a href='vscode-notebook-cell:/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb#X43sZmlsZQ%3D%3D?line=5'>6</a>\u001b[0m \u001b[39mwhile\u001b[39;00m i\u001b[39m<\u001b[39m\u001b[39m=\u001b[39mtext_len: \u001b[39m# cannot get the letter as text_len will return length of text\u001b[39;00m\n\u001b[0;32m----> <a href='vscode-notebook-cell:/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb#X43sZmlsZQ%3D%3D?line=6'>7</a>\u001b[0m \u001b[39mprint\u001b[39m(text[i],end\u001b[39m=\u001b[39m\u001b[39m'\u001b[39m\u001b[39m'\u001b[39m)\n\u001b[1;32m <a href='vscode-notebook-cell:/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb#X43sZmlsZQ%3D%3D?line=7'>8</a>\u001b[0m \u001b[39mif\u001b[39;00m text[i] \u001b[39m==\u001b[39m\u001b[39m'\u001b[39m\u001b[39m\\n\u001b[39;00m\u001b[39m'\u001b[39m: \n\u001b[1;32m <a href='vscode-notebook-cell:/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb#X43sZmlsZQ%3D%3D?line=8'>9</a>\u001b[0m \u001b[39mprint\u001b[39m(\u001b[39m'\u001b[39m\u001b[39m-\u001b[39m\u001b[39m'\u001b[39m\u001b[39m*\u001b[39m\u001b[39m50\u001b[39m)\n",
"\u001b[0;31mIndexError\u001b[0m: string index out of range"
]
}
],
"source": [
"text = 'Subject: Greeting\\nSender: Ken Fong\\nRecipient: All\\nBody: Merry Christmas and Happy New Year!\\n'\n",
"print('-'*50)\n",
"text_len = len(text)\n",
"print(text_len) # \"i\" havn't initialized\n",
"while i<=text_len: # cannot get the letter as text_len will return length of text is 92, cannot refer it to i\n",
" print(text[i],end='')\n",
" if text[i] =='\\n': \n",
" print('-'*50)\n",
" i=i+1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'> Edit this cell to explain the errors and illustrate how to fix the errors: </font>\n"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"--------------------------------------------------\n",
"Subject: Greeting\n",
"--------------------------------------------------\n",
"Sender: Ken Fong\n",
"--------------------------------------------------\n",
"Recipient: All\n",
"--------------------------------------------------\n",
"Body: Merry Christmas and Happy New Year!\n",
"--------------------------------------------------\n"
]
}
],
"source": [
"text = 'Subject: Greeting\\nSender: Ken Fong\\nRecipient: All\\nBody: Merry Christmas and Happy New Year!\\n'\n",
"print('-'*50)\n",
"text_len = len(text)\n",
"i = 0\n",
"while i< text_len: # cannot get the letter as text_len will return length of text is 92, cannot refer it to i\n",
" print(text[i],end='')\n",
" if text[i] =='\\n': \n",
" print('-'*50)\n",
" i=i+1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.3. Consider a string variable email = 'kenfong@ln.edu.hk'. Write and execute codes for the following tasks (6 points):"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (a)"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"kenfong\n",
"ln.edu.hk\n",
"ln\n"
]
}
],
"source": [
"email = 'kenfong@ln.edu.hk'\n",
"\n",
"#(1) In the line below, print a slice of the variable email from the beginning to the character before '@':\n",
"print(email[0:7])\n",
"\n",
"#(2) In the line below, print a slice of the variable email from the end to the character after '@':\n",
"print(email[8:])\n",
"\n",
"#(3) In the line below, print a slide of the variable email from the character after '@' to the character before '.edu.hk':\n",
"print(email[8:10])\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (b)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"kenfonglneduhk"
]
}
],
"source": [
"email = 'kenfong@ln.edu.hk'\n",
"#In the lines below, use a for loop to print each alphabetic character of the variable email in separated lines, \n",
"#which uses the ``in`` operation and the following string of alphabetic characters to check \n",
"#whether a character of the email is an alphabetic character.\n",
"letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n",
"\n",
"for c in email:\n",
" if c in letters:\n",
" print(c, end=\"\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### (c)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"kenfonglneduhk"
]
}
],
"source": [
"email = 'kenfong@ln.edu.hk'\n",
"#In the lines below, use a while loop to print each non-alphabetic character of the variable email in separated lines,\n",
"#which uses the ``in`` operation and the following string of alphabetic characters to check \n",
"#whether a character of the email is an alphabetic character.\n",
"letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n",
"\n",
"len_email = len(email)\n",
"i = 0\n",
"while i < len_email:\n",
" if (email[i] in letters):\n",
" print(email[i], end=\"\")\n",
" i = i + 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 2 String Functions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.1. Use dir() to list all the available functions for a string object, and use help() to show the usage of function ``isalpha`` of a string object (2 points)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['__add__',\n",
" '__class__',\n",
" '__contains__',\n",
" '__delattr__',\n",
" '__dir__',\n",
" '__doc__',\n",
" '__eq__',\n",
" '__format__',\n",
" '__ge__',\n",
" '__getattribute__',\n",
" '__getitem__',\n",
" '__getnewargs__',\n",
" '__getstate__',\n",
" '__gt__',\n",
" '__hash__',\n",
" '__init__',\n",
" '__init_subclass__',\n",
" '__iter__',\n",
" '__le__',\n",
" '__len__',\n",
" '__lt__',\n",
" '__mod__',\n",
" '__mul__',\n",
" '__ne__',\n",
" '__new__',\n",
" '__reduce__',\n",
" '__reduce_ex__',\n",
" '__repr__',\n",
" '__rmod__',\n",
" '__rmul__',\n",
" '__setattr__',\n",
" '__sizeof__',\n",
" '__str__',\n",
" '__subclasshook__',\n",
" 'capitalize',\n",
" 'casefold',\n",
" 'center',\n",
" 'count',\n",
" 'encode',\n",
" 'endswith',\n",
" 'expandtabs',\n",
" 'find',\n",
" 'format',\n",
" 'format_map',\n",
" 'index',\n",
" 'isalnum',\n",
" 'isalpha',\n",
" 'isascii',\n",
" 'isdecimal',\n",
" 'isdigit',\n",
" 'isidentifier',\n",
" 'islower',\n",
" 'isnumeric',\n",
" 'isprintable',\n",
" 'isspace',\n",
" 'istitle',\n",
" 'isupper',\n",
" 'join',\n",
" 'ljust',\n",
" 'lower',\n",
" 'lstrip',\n",
" 'maketrans',\n",
" 'partition',\n",
" 'removeprefix',\n",
" 'removesuffix',\n",
" 'replace',\n",
" 'rfind',\n",
" 'rindex',\n",
" 'rjust',\n",
" 'rpartition',\n",
" 'rsplit',\n",
" 'rstrip',\n",
" 'split',\n",
" 'splitlines',\n",
" 'startswith',\n",
" 'strip',\n",
" 'swapcase',\n",
" 'title',\n",
" 'translate',\n",
" 'upper',\n",
" 'zfill']"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#edit this cell to list all the available functions for a string object\n",
"\n",
"dir(str)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on method_descriptor:\n",
"\n",
"isalpha(self, /)\n",
" Return True if the string is an alphabetic string, False otherwise.\n",
" \n",
" A string is alphabetic if all characters in the string are alphabetic and there\n",
" is at least one character in the string.\n",
"\n"
]
}
],
"source": [
"#edit this cell to show the usage of function ``isalpha`` of a string object\n",
"help(str.isalpha)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.2. Use function ``isalpha`` of a string object to rewrite Code for (b) of Question 1.3: (2 points)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"kenfonglneduhk"
]
}
],
"source": [
"email = 'kenfong@ln.edu.hk'\n",
"\n",
"for c in email:\n",
" if c.isalpha and not (c==\"@\" or c==\".\"):\n",
" print(c, end=\"\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.3. Execute the codes below, explain the meanings of the codes (12 points)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (a) Add comment to each line of the code below to explain the meaning of the code:"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Email ID: kenfong\n",
"Email Domain: ln.edu.hk\n"
]
}
],
"source": [
"email = 'kenfong@ln.edu.hk' # define an email string\n",
"at_pos = email.find('@') # find the first occurrence of the '@' in email\n",
"email_id = email[:at_pos] # grab the string before letter '@'\n",
"email_domain = email[at_pos+1:] # grab the domain after letter '@'\n",
"print('Email ID:', email_id) # print email_id\n",
"print('Email Domain:', email_domain) # print domain"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (b) Add comment to each line of the code below to explain the meaning of the code:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"email_id = 'Kenfong' # define an email string\n",
"if email_id.upper()=='KENFONG': # convert email_id to upper case and compare it to 'KENFONG'\n",
" print(\"The email is from Ken Fong.\") # print 'The email is from Ken Fong' if true\n",
"else: #otherwise:\n",
" print(\"The email is not from Ken Fong.\") # print 'The email is not from Ken Fong' if false"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (c) Add comment to each line of the code below to explain the meaning of the code:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"subject_template = 'Thank you, {user_name}!' # define template string\n",
"user_name = 'Ken' # define 'Ken' to user_name\n",
"subject = subject_template.replace('{user_name}', user_name) # apply 'Ken' to template string\n",
"print(subject) # print it out"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (d) Add comment to each line of the code below to explain the meaning of the code:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"user_name = ' Ken Fong\\n' # define user_name\n",
"print(user_name) # print user_name\n",
"luser_name = user_name.lstrip() # remove non-character from the left and assign it to luser_name\n",
"print(luser_name) # print luser_name out\n",
"ruser_name = user_name.rstrip() # remove non-character from the right and assign it to ruser_name\n",
"print(ruser_name) # print it out\n",
"suser_name = user_name.strip() # remove non-character from both side\n",
"print(suser_name) # print it out"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (e) Add comment to each line of the code below to explain the meaning of the code:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"email = 'kenfong@ln.edu.hk' # define email with string\n",
"if email.endswith('.hk'): # check if the string end with '.hk', equivalently from the right side.\n",
" print('You are from Hong Kong!') # print 'You are from Hong Kong!' if true"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (f) Add comment to each line of the code below to explain the meaning of the code:"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Thank you, %s!\n",
"Thank you, Alice!\n"
]
}
],
"source": [
"subject_template = 'Thank you, %s!' # define template string\n",
"print(subject_template) # print template string\n",
"user_name = 'Alice' # define user_name\n",
"subject = subject_template % user_name # apply user_name to template(subject_template) and assign it to subject\n",
"print(subject) # print it out"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.3. Write codes for the following tasks (12 points):"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (a)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ln\n"
]
}
],
"source": [
"email = 'kenfong@ln.edu.hk'\n",
"#(1) In the space below, use function find() to find th position of '@' in email, \n",
"# and store the position in variable start:\n",
"start = email.find('@')\n",
"\n",
"#(2) In the space below, use function find() to find the position of the first '.' after '@' in the email, \n",
"# and store the position in the variable end:\n",
"end = email.find('.')\n",
"\n",
"\n",
"#(3) In the space below, print the slice from start to end (excluding start and end):\n",
"print(email[start+1:end])\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (b)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"kenfong@ ln.edu.hk\n"
]
}
],
"source": [
"email = ' kenfong@ ln.edu.hk\\n'\n",
"#(1) In the space below, remove white spaces at the beginning of email and print the result:\n",
"lstrip_email = email.lstrip()\n",
"\n",
"#(2) In the space below, remove white spaces at the ending of email and print the result:\n",
"rstrip_email = email.rstrip()\n",
"\n",
"#(3) In the space below, remove white spaces both at the beginning and the ending of email and print the result:\n",
"print(email.strip())\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (c)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"kenfong@ln.edu.hk\n"
]
}
],
"source": [
"email = ' kenfong@ ln.edu.hk '\n",
"#In the space below, remove all the spaces in the email, and print the result:\n",
"#Hint: use replace function of a string object\n",
"print(email.replace(' ',''))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (d)"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" kenfong@ ln.edu.hk\n",
"\n"
]
}
],
"source": [
"email = ' ckkfong@ ln.edu.hk\\n'\n",
"#In the space below, replace 'ckkfong' with 'kenfong' of email, and print the result:\n",
"print(email.replace('ckkfong','kenfong'))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (e)"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n",
"False\n",
"True\n"
]
}
],
"source": [
"email = 'kenfong@ln.edu.hk'\n",
"#(1) In the space below, test whether email contains 'ln', and print the test result:\n",
"print(email.find('ln')>0)\n",
"\n",
"#(2) In the space below, test whether email ends with 'ln', and print the test result:\n",
"print(email.endswith('ln'))\n",
"\n",
"#(3) In the space below, test whether email starts with 'kenfong', and print the test result:\n",
"print(email.startswith('kenfong'))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (f)"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Email from kenfong@ln.edu.hk is confirmed.\n"
]
}
],
"source": [
"email = 'kenfong@ln.edu.hk'\n",
"#In the space below, use format operator % to print a message 'Email from kenfong@ln.edu.hk is confirmed.', \n",
"#where 'kenfong@ln.edu.hk' is the second operand of the format string:\n",
"\n",
"template = 'Email from %s is confirmed.'\n",
"out = template % email\n",
"print(out)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 3 File"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 3.1. Read codes below and answer the questions (12 points):"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 3.1.1: For the code below, list the file name, file handler, mode of opening below."
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<_io.TextIOWrapper name='requests.txt' mode='r' encoding='UTF-8'>\n"
]
}
],
"source": [
"input_file = open ('requests.txt', 'r')\n",
"print(input_file)\n",
"input_file.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```\n",
"file name is `requests.txt`\n",
"file handler is `input_file`\n",
"mode of opening is read-only\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 3.1.2: Execute the code below, and explain how and why print(s) and print(repr(s)) are different"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"APPLE 100\n",
"\n",
"'APPLE 100\\n'\n",
"ORANGE 90\n",
"\n",
"'ORANGE 90\\n'\n",
"BANANA 95\n",
"\n",
"'BANANA 95\\n'\n",
"APPLE 120\n",
"\n",
"'APPLE 120\\n'\n",
"APPLE 130\n",
"\n",
"'APPLE 130\\n'\n",
"BANANA 2\t5\n",
"'BANANA 2\\t5'\n"
]
}
],
"source": [
"input_file = open ('requests.txt', 'r')\n",
"for s in input_file:\n",
" print(s)\n",
" print(repr(s)) \n",
"input_file.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `repr()` function returns a printable representation of the given object.\n",
"While `print` only render the character to the console. \n",
"For example \"\\n\" will render a new-line(using `print`) and \"\\n\" (using `repr`) instead.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 3.1.3: Execute the code below, explain how the code is executed, and draw a flowchart"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"APPLE 100\n",
"APPLE 120\n",
"APPLE 130\n"
]
}
],
"source": [
"input_file = open ('requests.txt', 'r')\n",
"output_file = open ('new_requests.txt', 'w')\n",
"for s in input_file: \n",
" if s.startswith('APPLE'):\n",
" print(s, end='')\n",
" output_file.write(s)\n",
"output_file.close()\n",
"input_file.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- open file `request.txt`, assign it to file_handler `input_file`\n",
"- open file `new_request.txt`, assign it to file_handler `output_file`\n",
"- in each line of input_file, if the line started with `APPLE`, print it out without new line ending and write it to the `output_file` \n",
"- close the `output_file` handler\n",
"- close the `input_file` handler\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![](./3.1.3.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 3.1.4: Execute the code below, explain how the error occurs, and use try-exception to avoid the error"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [
{
"ename": "FileNotFoundError",
"evalue": "[Errno 2] No such file or directory: 'requests-new.txt'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb Cell 87\u001b[0m line \u001b[0;36m1\n\u001b[0;32m----> <a href='vscode-notebook-cell:/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb#Y152sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m input_file \u001b[39m=\u001b[39m \u001b[39mopen\u001b[39;49m (\u001b[39m'\u001b[39;49m\u001b[39mrequests-new.txt\u001b[39;49m\u001b[39m'\u001b[39;49m, \u001b[39m'\u001b[39;49m\u001b[39mr\u001b[39;49m\u001b[39m'\u001b[39;49m)\n\u001b[1;32m <a href='vscode-notebook-cell:/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb#Y152sZmlsZQ%3D%3D?line=1'>2</a>\u001b[0m s \u001b[39m=\u001b[39m input_file\u001b[39m.\u001b[39mread()\n\u001b[1;32m <a href='vscode-notebook-cell:/workspace/carousell-comission-playlist/max015/T06/T06/CDS1001T6Report.ipynb#Y152sZmlsZQ%3D%3D?line=2'>3</a>\u001b[0m \u001b[39mprint\u001b[39m(s)\n",
"File \u001b[0;32m~/.local/lib/python3.11/site-packages/IPython/core/interactiveshell.py:284\u001b[0m, in \u001b[0;36m_modified_open\u001b[0;34m(file, *args, **kwargs)\u001b[0m\n\u001b[1;32m 277\u001b[0m \u001b[39mif\u001b[39;00m file \u001b[39min\u001b[39;00m {\u001b[39m0\u001b[39m, \u001b[39m1\u001b[39m, \u001b[39m2\u001b[39m}:\n\u001b[1;32m 278\u001b[0m \u001b[39mraise\u001b[39;00m \u001b[39mValueError\u001b[39;00m(\n\u001b[1;32m 279\u001b[0m \u001b[39mf\u001b[39m\u001b[39m\"\u001b[39m\u001b[39mIPython won\u001b[39m\u001b[39m'\u001b[39m\u001b[39mt let you open fd=\u001b[39m\u001b[39m{\u001b[39;00mfile\u001b[39m}\u001b[39;00m\u001b[39m by default \u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 280\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mas it is likely to crash IPython. If you know what you are doing, \u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 281\u001b[0m \u001b[39m\"\u001b[39m\u001b[39myou can use builtins\u001b[39m\u001b[39m'\u001b[39m\u001b[39m open.\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 282\u001b[0m )\n\u001b[0;32m--> 284\u001b[0m \u001b[39mreturn\u001b[39;00m io_open(file, \u001b[39m*\u001b[39;49margs, \u001b[39m*\u001b[39;49m\u001b[39m*\u001b[39;49mkwargs)\n",
"\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'requests-new.txt'"
]
}
],
"source": [
"input_file = open ('requests-new.txt', 'r')\n",
"s = input_file.read()\n",
"print(s)\n",
"input_file.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`requests-new.txt` file does not exist"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[Errno 2] No such file or directory: 'requests-new.txt'\n"
]
}
],
"source": [
"try:\n",
" input_file = open ('requests-new.txt', 'r')\n",
" s = input_file.read()\n",
" print(s)\n",
" input_file.close()\n",
"\n",
"except Exception as e:\n",
" print(e)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 4 Parsing-Extracting"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 4.1. Vote from a File (18 points)\n",
"You 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\". 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 is a string equal to 'Disney', 'Hotel ICON', or 'Ocean Park', and the file ends with -1.\n",
"\n",
"A sample file of votes.txt available contains the following four lines:\n",
"\n",
" Disney\n",
" Hotel ICON\n",
" Hotel ICON\n",
" Ocean Park\n",
" -1\n",
" \n",
"Your program write 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: 1\n",
" \n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 4.1.1: Use a text editor to to create votes.txt in the report folder of the tutorial (i.e., /CDS1001/T6/report) to include some votes for a test, which shall be different from the sample described above. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```\n",
"Disney\n",
"Hotel ICON\n",
"Hotel ICON\n",
"Ocean Park\n",
"Disney\n",
"Hotel ICON\n",
"Ocean Park\n",
"Disney\n",
"Ocean Park\n",
"Hotel ICON\n",
"-1\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 4.1.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:4\n",
"Ocean Park:3\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 4.1.3: For this problem, how are you going to define file handlers? "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"i will define a `votes_file` as file handler with mode read-only, and `results_file` file-handler with write."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 4.1.4: Let ``line`` be the variable to store each line of the input file. How are you going to define the condition to identify votes for Disney? "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```python\n",
"line.strip() == \"Disney\"\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 4.1.5: Write the code for this problem"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [],
"source": [
"#edit this cell to write the program\n",
"\n",
"votes_file = open ('./report/votes.txt', 'r')\n",
"results_file = open ('./report/results.txt', 'w')\n",
"disney_vote = 0\n",
"hotel_icon_vote = 0\n",
"ocean_park_vote = 0\n",
"\n",
"for s in votes_file: \n",
" if s.strip() == 'Disney':\n",
" disney_vote = disney_vote + 1\n",
" if s.strip() == 'Hotel ICON' :\n",
" hotel_icon_vote = hotel_icon_vote + 1\n",
" if s.strip() == 'Ocean Park':\n",
" ocean_park_vote = ocean_park_vote + 1\n",
"\n",
"disney_output = 'Disney:%s\\n' % disney_vote\n",
"hotel_icon_output = 'Hotel ICON:%s\\n' % hotel_icon_vote\n",
"ocean_park_output = 'Ocean Park:%s\\n' % ocean_park_vote\n",
"output = disney_output + hotel_icon_output + ocean_park_output\n",
"\n",
"results_file.write(output.strip())\n",
"\n",
"results_file.close()\n",
"votes_file.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 4.1.6: Execute the code and show the output"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```bash\n",
"bash-5.2$ python 4_1_6.py \n",
"bash-5.2$ cat report/results.txt \n",
"Disney:3\n",
"Hotel ICON:4\n",
"Ocean Park:3bash-5.2$ \n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 5 Other Exercises"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 5.1. Cheapest Carrier from a File (18 points)\n",
"Write a program that prompts a logistics manager to analyze a file of shipping rates, so as to output the lowest shipping rate, and the carrier who submits the lowest shipping rate.\n",
"\n",
"The input file name is input by the logistics manager. Each line of the input file (except the last line) contains a carrier name and a shipping rate, separated by a space, where the carrier name is a string of capitalized letters, and the shipping rate is a float number.\n",
"\n",
"Sample input file\n",
"\n",
" OOCL 130\n",
" MMM 100\n",
" NNN 110\n",
" -1\n",
" \n",
"Sample output on screen:\n",
"\n",
" The lowest shipping rate is 100, submitted by MMM."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 5.1.1: Use a text editor to create an input file in the report folder of the tutorial (i.e., /CDS1001/T6/report) to include some shipping rates."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```bash\n",
"bash-5.2$ cat carrier.txt \n",
"OOCL 130\n",
"MMM 100\n",
"NNN 110\n",
"OOO 99\n",
"PPP 80\n",
"RRR 111\n",
"-1bash-5.2$ \n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 5.1.2: For the input file created, what's the expected output?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`The lowest shipping rate is 80, submitted by PPP.`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 5.1.3: Let ``line`` be the variable to store each line of the file. What's the condition for reaching the end of the file?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"line receive -1 as its content."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 5.1.4: Let ``line`` be the variable to store each line of the file. How to extract the carrier id and shipping rate from ``line``?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"line = 'OOCL 130'\n",
"#(1) in the space below, write a statement to find the index of space in line, and assign it to a variable p\n",
"p = line.find(' ')\n",
"\n",
"#(2) to get the carrier id, in the space below, \n",
"#write a statement to print the slice of line from the beginning to the character before the space\n",
"print(line[0:p])\n",
"\n",
"#(3) to get the shipping rate, in the space below, \n",
"#write a statement to print the slice of line after the space of line\n",
"print(line[p+1:])\n",
"\n",
"#(4) then, in the space below, convert the slice of line after the space of line to a float number, and print the float number:\n",
"rate = float(line[p+1:])\n",
"print(rate)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 5.1.5: Based on your answers to Questions 5.1.3 and 5.1.4, write the code for the problem 5.1:"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The lowest shipping rate is 80.0, submitted by PPP.\n"
]
}
],
"source": [
"#edit this cell to write your code\n",
"#Hint: (1) input the name of the input file\n",
"# (2) define a file handle for the input file\n",
"# (3) for each line of the file, extract the carrier id and shipping rate by using string's find function \n",
"# and slice operation, and then update the variables that store the lowest shipping rate and its carrier id\n",
"\n",
"lowest_rate = -1\n",
"lowest_rate_carrier = \"\"\n",
"\n",
"file_name = input(\"please enter a file name: \")\n",
"\n",
"with open(file_name, 'r') as carrier_file:\n",
" for s in carrier_file: \n",
" if s != \"-1\":\n",
" p = s.find(' ')\n",
" rate = float(s[p+1:])\n",
" carrier = s[0:p]\n",
" if ( rate < lowest_rate or lowest_rate == -1):\n",
" lowest_rate_carrier = carrier\n",
" lowest_rate = rate\n",
"\n",
"output = 'The lowest shipping rate is %s, ' % lowest_rate\n",
"output1 = 'submitted by %s.' % lowest_rate_carrier\n",
"print(output+ output1)\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 5.1.6: Execute and test the code:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```bash\n",
"please enter a file name: ./report/carrier.txt\n",
"The lowest shipping rate is 80.0, submitted by PPP.\n",
"```"
]
}
],
"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
}