This commit is contained in:
louiscklaw
2025-01-31 21:15:04 +08:00
parent 3337cc3d1e
commit acf9d862ff
324 changed files with 43162 additions and 0 deletions

View File

@@ -0,0 +1,5 @@
chakmanchung@ln.hk
Password:@Mc1234567
hurry
HKD 200

View File

@@ -0,0 +1,6 @@
'''
Draft a python script to
Count down a nonnegative number to zero
n,n— 1, n — 2, ...,0
'''

View File

@@ -0,0 +1,19 @@
## Mandatory
- P01: Please use recursion to define and test a function to calculate the sum of a list of numbers.
`def list_sum_Recur(num_list):`
- P02: Please use recursion to define and test a function to find the greatest common division of two positive integers.
`def gcd_Recur(a,b):`
- P03: Please use recursion to define and test a function to calculate the harmonic series upto `n` terms.
`def harmonic_sum_Recur(n):`
- P04: Please use recursion to define and test a function to calculate the value of 𝑥 to the power of `n`.
`def power_Recur(x,n):`
## Optional
- P05: Please use recursion to define and test a function to accept a decimal integer and display its binary equivalent.
`def Dec2Binary_Recur(num):`
- P06: Please use recursion to define and test a function to take in a string and returns a reversed copy of the string.
`def reverse_Recur(a,b):`
- P07: Please use recursion to define and test a function to check whether a number is Prime or not.
`def isPrime_Recur(a,b):`

View File

@@ -0,0 +1,9 @@
#!/usr/bin/env bash
set -ex
git add .
git commit -m"update max015,"
git push

View File

@@ -0,0 +1,7 @@
chakmanchung@ln.hk
Password:@Mc1234567
hurry
HKD 200
https://www.leetcode.com

View File

@@ -0,0 +1,33 @@
'''
Draft a python script to solve the following questions. thanks
# Requirement
Please use recursion to define and test a function to calculate the sum of a list of numbers.
# procedure
- let's think it step by step
- leave me comment with your code
- solve with recursion
- write your code in `def list_sum_Recur(num_list):` , with comment `# implementation here`
- write a sample function to use it, with comment `# test here`
'''
import sys
sys.setrecursionlimit(999999)
def list_sum_Recur(num_list):
# implementation here
if len(num_list) == 1:
return num_list[0]
else:
return num_list[0] + list_sum_Recur(num_list[1:])
# test here
def test_list_sum_Recur():
print(list_sum_Recur([1, 2, 3, 4, 5]))
print( (1+5)*5 / 2)
print(list_sum_Recur(list(range(1,9999+1))))
print( (1+9999)*9999 / 2)
test_list_sum_Recur()

BIN
max015/CDS2003_assignment02/src/P01_result.png (Stored with Git LFS) Normal file

Binary file not shown.

View File

@@ -0,0 +1,73 @@
'''
Draft a python script to solve the following questions. thanks
# Background
The greatest common divisor (GCD) of integers a and b, at least one of which is nonzero, is the greatest positive integer d such that d is a divisor of both a and b; that is, there are integers e and f such that a = de and b = df, and d is the largest such integer. The GCD of a and b is generally denoted gcd(a, b).[8]
When one of a and b is zero, the GCD is the absolute value of the nonzero integer: gcd(a, 0) = gcd(0, a) = |a|.
This case is important as the terminating step of the Euclidean algorithm.
The above definition is unsuitable for defining gcd(0, 0), since there is no greatest integer n such that 0 × n = 0.
However, zero is its own greatest divisor if greatest is understood in the context of the divisibility relation,
so gcd(0, 0) is commonly defined as 0.
This preserves the usual identities for GCD, and in particular Bézout's identity,
namely that gcd(a, b) generates the same ideal as {a, b}.[9][10][11]
This convention is followed by many computer algebra systems.[12]
Nonetheless, some authors leave gcd(0, 0) undefined.[13]
# Requirement
Please use recursion to define and test a function to find the greatest common division of two positive integers.
# procedure
- let's think it step by step
- leave me comment with your code
- solve with recursion
- write your code in `def gcd_Recur(a,b):` , with comment `# implementation here`
- write a sample function to use it, with comment `# test here`
'''
lteration = 0
def gcd_Recur(a,b):
# implementation here
global lteration
# https://proofwiki.org/wiki/GCD_for_Negative_Integers
if a < 0 or b < 0:
print("Conservative result: tested number more reasonable if greater than 1")
if a == 0 and b == 0:
return 0
if b == 0:
return a
else:
lteration+=1
return gcd_Recur(abs(b), abs(a % b))
# test here
def test_gcd_Recur():
global lteration
input_list = [
# from wiki: gcd(54,24) = 6
(54,24),
# from wiki: gcd(8, 12) = 4
(8,12),
# for no gcd
(5,7),
(-12,3), (-12,0),(12,-1),
# https://en.wikipedia.org/wiki/Greatest_common_divisor
# from wiki: gcd(0, 0) is commonly defined as 0
(0,0),
# https://en.wikipedia.org/wiki/Greatest_common_divisor
# from wiki: When one of a and b is zero, the GCD is the absolute value of the nonzero integer: gcd(a, 0) = gcd(0, a) = |a|.
(0,6), (1,0),
(0,88),(99,0)]
for a,b in input_list:
lteration = 0
print("gcd of ", a, " and ", b, " is: ", gcd_Recur(a,b))
test_gcd_Recur()

BIN
max015/CDS2003_assignment02/src/P02_result.png (Stored with Git LFS) Normal file

Binary file not shown.

View File

@@ -0,0 +1,47 @@
'''
Draft a python script to solve the following questions. thanks
# Background
In mathematics, the harmonic series is the infinite series formed by summing all positive unit fractions.
# Requirement
Please use recursion to define and test a function to calculate the harmonic series upto `n` terms.
# procedure
- let's think it step by step
- leave me comment with your code
- solve with recursion
- write your code in `def gcd_Recur(a,b):` , with comment `# implementation here`
- write a sample function to use it, with comment `# test here`
'''
import sys
sys.setrecursionlimit(999999)
lteration = 0
def harmonic_series_Recur(n):
# implementation here
global lteration
# https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)
if lteration == 0 and n < 1:
return "Error: n should equal or lager than 1"
if lteration == 0 and n == 0:
return 1
if n == 1:
return 1
else:
lteration +=1
return 1/n + harmonic_series_Recur(n-1)
# test here
def test_harmonic_series_Recur():
global lteration
n_list = [-10,-1,0,1,5, 99, 9999]
for n in n_list:
print("result of ", n, ' is : ', harmonic_series_Recur(n))
lteration = 0
if __name__ == '__main__':
test_harmonic_series_Recur()

BIN
max015/CDS2003_assignment02/src/P03_result.png (Stored with Git LFS) Normal file

Binary file not shown.

View File

@@ -0,0 +1,42 @@
'''
Draft a python script to solve the following questions. thanks
# Requirement
Please use recursion to define and test a function to calculate the value of 𝑥 to the power of `n`.
# procedure
- let's think it step by step
- leave me comment with your code
- solve with recursion
- write your code in `def power_Recur(x,n):` , with comment `# implementation here`
- write a sample function to use it, with comment `# test here`
'''
import sys
sys.setrecursionlimit(10000)
def power_Recur(x,n):
# implementation here
if n == 0:
return 1
else:
return x * power_Recur(x, n-1)
# test here
def test_power_Recur():
input_list = [
(0, 0),
(0, 3),
(3, 0),
(2, 3),
(-2, 3),
(-2, 4),
(10, 10),
(10, 99),
]
for x, n in input_list:
result = power_Recur(x, n)
print("x:",x,"n:",n, " result : ", result, ",len of answer", len(str(result)))
test_power_Recur()

BIN
max015/CDS2003_assignment02/src/P04_result.png (Stored with Git LFS) Normal file

Binary file not shown.

View File

@@ -0,0 +1,30 @@
'''
Draft a python script to solve the following questions. thanks
# Requirement
Please use recursion to define and test a function to accept a decimal integer and display its binary equivalent.
# procedure
- let's think it step by step
- leave me comment with your code
- solve with recursion
- write your code in `def Dec2Binary_Recur(num):` , with comment `# implementation here`
- write a sample function to use it, with comment `# test here`
'''
def Dec2Binary_Recur(num):
# implementation here
if num > 1:
return Dec2Binary_Recur(num // 2) + str(num % 2)
else:
return str(num % 2)
# test here
def test_Dec2Binary_Recur():
num_list = [ 1,32,64,128,255]
for num in num_list:
temp = Dec2Binary_Recur(num)
print('result of DEC', str(num).zfill(4), ' is :',(8 - len(temp))*'0'+temp)
if __name__ == '__main__':
test_Dec2Binary_Recur()

BIN
max015/CDS2003_assignment02/src/P05_result.png (Stored with Git LFS) Normal file

Binary file not shown.

View File

@@ -0,0 +1,43 @@
'''
Draft a python script to solve the following questions. thanks
# Requirement
Please use recursion to define and test a function to take in a string and returns a reversed copy of the string.
# procedure
- let's think it step by step
- leave me comment with your code
- solve with recursion
- write your code in `def reverse_Recur(a,b):` , with comment `# implementation here`
- write a sample function to use it, with comment `# test here`
'''
def reverse_Recur(a, b):
# implementation here
if len(a) == 0:
return b
else:
return reverse_Recur(a[1:], a[0] + b)
# test here
test = ''''''
print("test string:")
print(test)
print("reversed:")
print(reverse_Recur(test, ""))
print()
print()
test = '''helloworld'''
print("test string:")
print(test)
print("reversed:")
print(reverse_Recur(test, ""))
print()
print()
test = '''The exponent is usually shown as a superscript to the right of the base. In that case, bn is called "b raised to the nth power", "b (raised) to the power of n", "the nth power of b", "b to the nth power",[2] or most briefly as "b to the n(th)".'''
print("test string:")
print(test)
print("reversed:")
print(reverse_Recur(test, ""))

BIN
max015/CDS2003_assignment02/src/P06_result.png (Stored with Git LFS) Normal file

Binary file not shown.

View File

@@ -0,0 +1,43 @@
'''
Draft a python script to solve the following questions. thanks
# Requirement
Please use recursion to define and test a function to check whether a number is Prime or not.
# procedure
- let's think it step by step
- leave me comment with your code
- solve with recursion
- write your code in `def isPrime_Recur(a,b):` , with comment `# implementation here`
- write a sample function to use it, with comment `# test here`
'''
import sys
sys.setrecursionlimit(999999)
def isPrime_Recur(a,b):
# implementation here
# https://t5k.org/notes/faq/negative_primes.html
if a < 0:
return "tested number should be greater than 1"
# https://corp.tutorocean.com/is-1-a-prime-number/
if a == 0 or a == 1:
return "Conservative result: tested number is neither prime nor composite"
if b == 1:
return True
if a % b == 0:
return False
else:
return isPrime_Recur(a,b-1)
# test here
if __name__ == '__main__':
num_list = [-99, -3, -1, 0, 1, 3, 7, 9, 9999, 10007]
for num in num_list:
print('is ', num, ' Prime?', isPrime_Recur(num, num-1))

BIN
max015/CDS2003_assignment02/src/P07_result.png (Stored with Git LFS) Normal file

Binary file not shown.

View File

@@ -0,0 +1,20 @@
P01
https://leetcode.com/playground/gZTt9LMe
P02
https://leetcode.com/playground/CsnfvkZe
P03
https://leetcode.com/playground/Ga3kggri
P04
https://leetcode.com/playground/R6Xh2hnB
P05
https://leetcode.com/playground/8DPfAMSb
P06
https://leetcode.com/playground/CsnfvkZe
P07
https://leetcode.com/playground/H9BecSM9

Binary file not shown.

View File

@@ -0,0 +1,49 @@
assignment02_Q01_4086741
Q01:
Please use recursion to define and test a function to calculate the sum of a list of numbers.
A01:
---
assignment02_Q02_4086741
Q02:
A02:
---
assignment02_Q03_4086741
Q03:
A03:
---
assignment02_Q04_4086741
Q04:
A04:
---
assignment02_Q05_4086741
Q05:
A05:
---
assignment02_Q06_4086741
Q06:
A06:
---
assignment02_Q07_4086741
Q07:
A07:
---

View File

@@ -0,0 +1,26 @@
'''
Draft a python script to solve the following questions. thanks
# Requirement
Count down a nonnegative number to zero
n,n— 1, n — 2, ...,0
# procedure
- let's think it step by step
- leave me comment with your code
- solve with recursion
'''
def countdown(n):
"""
Count down a nonnegative number to zero
"""
if n == 0:
print(n)
else:
print(n)
countdown(n-1)
if __name__ == '__main__':
countdown(5)

View File

@@ -0,0 +1,22 @@
'''
Draft a python script to solve the following questions. thanks
# Requirement
Calculate the factorial Of a nonnegative integer where
n! = n * (n - 1) * (n - 2) * ... * 2 * 1 and 0 != 1
# procedure
- let's think it step by step
- leave me comment with your code
- solve with recursion
'''
def factorial(n):
"""
Calculate the factorial Of a nonnegative integer where
n! = n * (n - 1) * (n - 2) * ... * 2 * 1 and 0 != 1
"""
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 KiB

View File

@@ -0,0 +1,4 @@
# NOTES
### quote
HKD450

BIN
max015/T04/CDS1001.pdf Normal file

Binary file not shown.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

1
max015/T04/quotation.md Normal file
View File

@@ -0,0 +1 @@
HKD200

11
max015/T04/test.py Normal file
View File

@@ -0,0 +1,11 @@
def genGreetingLetter(customer_name, title, your_name):
greeting_letter_template = '''
Dear {Title} {Customer_Name},
Merry Christmas and Happy New Year!
Best,
{Your_Name}
'''.strip().replace('{Customer_Name}', customer_name).replace('{Title}', title).replace('{Your_Name}', your_name)
return greeting_letter_template

27
max015/T04/test_2_5.py Normal file
View File

@@ -0,0 +1,27 @@
rate1 = 10.0
threshold1 = 100
discount1 = 0.1
rate2 = 11.0
threshold2 = 200
discount2 = 0.3
def compute_cost_discount(quantity, rate, threshold, discount):
cost = rate * quantity
if quantity>=threshold:
cost = cost*(1.0-discount)
return cost
customer = input('Enter customer name: ')
quantity = int(input('Enter order quantity: '))
cost1 = compute_cost_discount(quantity, rate1, threshold1, discount1)
cost2 = compute_cost_discount(quantity, rate2, threshold2, discount2)
lowest_cost = cost1
if cost2<lowest_cost:
lowest_cost = cost2
print('Lowest Cost for', customer, ':', lowest_cost)

19
max015/T04/test_2_6.py Normal file
View File

@@ -0,0 +1,19 @@
def computepay(hours, rate):
output = 0
hours = int(hours)
rate = float(rate)
if (hours > 40):
output = 40*rate + (hours-40)*rate*1.5
else:
output = hours*rate
return output
print('Input:')
hours = input('Enter Hours: ')
rate = input('Enter Rate: ')
pay = computepay(hours, rate)
print('Output:')
print(f"Pay: {pay}")

7
max015/T04/test_3_1.py Normal file
View File

@@ -0,0 +1,7 @@
import math
math.pi = 123321
pi = math.pi
d = math.sqrt(2)
print(pi * d)

45
max015/T05/2a.drawio Normal file
View File

@@ -0,0 +1,45 @@
<mxfile host="65bd71144e">
<diagram id="x3mvl7MIxiUfgaiuTItL" name="Page-1">
<mxGraphModel dx="533" dy="574" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="0" pageScale="1" pageWidth="827" pageHeight="1169" background="#ffffff" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="4" style="edgeStyle=none;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;strokeColor=#1A1A1A;" parent="1" source="2" target="3" edge="1">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="2" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;&lt;font color=&quot;#1a1a1a&quot; style=&quot;font-size: 12px;&quot;&gt;initialize&lt;/font&gt;&lt;/div&gt;&lt;div style=&quot;&quot;&gt;&lt;font color=&quot;#1a1a1a&quot; style=&quot;&quot; size=&quot;3&quot;&gt;sales = [100, 200, 100, 200, 300, 400]&lt;/font&gt;&lt;/div&gt;&lt;div style=&quot;background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#E6E6E6;fontColor=#050505;strokeColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="281" y="120" width="288" height="60" as="geometry"/>
</mxCell>
<mxCell id="6" value="True" style="edgeStyle=none;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;fontFamily=Helvetica;fontSize=12;strokeColor=#1A1A1A;labelBackgroundColor=none;fontColor=#1A1A1A;" parent="1" source="3" target="5" edge="1">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="9" value="&lt;font&gt;False&lt;/font&gt;" style="edgeStyle=none;html=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;fontFamily=Helvetica;fontSize=12;strokeColor=#1A1A1A;fontColor=#1A1A1A;labelBackgroundColor=none;" parent="1" source="3" target="8" edge="1">
<mxGeometry x="-0.1748" y="-10" relative="1" as="geometry">
<Array as="points">
<mxPoint x="209" y="300"/>
</Array>
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="3" value="sales[i] &amp;gt;= 0 ?" style="rhombus;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="363" y="260" width="125" height="80" as="geometry"/>
</mxCell>
<mxCell id="7" style="edgeStyle=none;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;fontFamily=Helvetica;fontSize=12;entryX=1;entryY=0.5;entryDx=0;entryDy=0;strokeColor=#1A1A1A;" parent="1" source="5" target="3" edge="1">
<mxGeometry relative="1" as="geometry">
<mxPoint x="710" y="450.28571428571445" as="targetPoint"/>
<Array as="points">
<mxPoint x="670" y="450"/>
<mxPoint x="670" y="300"/>
</Array>
</mxGeometry>
</mxCell>
<mxCell id="5" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;inventory = inventory - sales[i]&lt;/div&gt;&lt;div style=&quot;&quot;&gt;i = i + 1&lt;/div&gt;&lt;div style=&quot;background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="326" y="420" width="198" height="60" as="geometry"/>
</mxCell>
<mxCell id="8" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;&lt;font style=&quot;&quot; color=&quot;#1a1a1a&quot;&gt;print inventory left&lt;/font&gt;&lt;/div&gt;&lt;div style=&quot;color: rgb(212, 212, 212); background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;" parent="1" vertex="1">
<mxGeometry x="110" y="420" width="198" height="60" as="geometry"/>
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>

108
max015/T05/2b.drawio Normal file
View File

@@ -0,0 +1,108 @@
<mxfile host="65bd71144e">
<diagram id="x3mvl7MIxiUfgaiuTItL" name="Page-1">
<mxGraphModel dx="950" dy="1232" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="0" pageScale="1" pageWidth="827" pageHeight="1169" background="#ffffff" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="10" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;&lt;font color=&quot;#1a1a1a&quot; style=&quot;font-size: 12px;&quot;&gt;initialize&lt;/font&gt;&lt;/div&gt;&lt;div style=&quot;&quot;&gt;&lt;div&gt;sales = [100, 200, 100, 200, 300, 400, -1]&lt;/div&gt;&lt;div&gt;i = 0&lt;/div&gt;&lt;div&gt;inventory = 1000&lt;/div&gt;&lt;/div&gt;&lt;div style=&quot;background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#E6E6E6;fontColor=#050505;strokeColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="281.5" y="-370" width="288" height="130" as="geometry"/>
</mxCell>
<mxCell id="11" value="sales[i] &amp;gt;= 0 ?" style="rhombus;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="363" y="-160" width="125" height="80" as="geometry"/>
</mxCell>
<mxCell id="13" style="edgeStyle=none;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;strokeColor=#1A1A1A;" parent="1" edge="1">
<mxGeometry relative="1" as="geometry">
<mxPoint x="424.64" y="-240" as="sourcePoint"/>
<mxPoint x="425.14" y="-160" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="14" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;inventory = inventory - sales[i]&lt;/div&gt;&lt;div style=&quot;background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="326" y="-30" width="198" height="60" as="geometry"/>
</mxCell>
<mxCell id="17" value="inventory &amp;lt; 0" style="rhombus;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="362.5" y="100" width="125" height="80" as="geometry"/>
</mxCell>
<mxCell id="18" style="edgeStyle=none;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;strokeColor=#1A1A1A;" parent="1" source="14" target="17" edge="1">
<mxGeometry relative="1" as="geometry">
<mxPoint x="435.5" y="-70" as="sourcePoint"/>
<mxPoint x="435.0000000000001" y="-20" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="19" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;i = i + 1&lt;/div&gt;&lt;div style=&quot;background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="580" y="110" width="86" height="60" as="geometry"/>
</mxCell>
<mxCell id="20" value="True" style="edgeStyle=none;html=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;strokeColor=#1A1A1A;labelBackgroundColor=none;fontColor=#1A1A1A;" parent="1" source="17" edge="1">
<mxGeometry x="-0.856" y="-10" relative="1" as="geometry">
<mxPoint x="424.81" y="180" as="sourcePoint"/>
<mxPoint x="310" y="-120" as="targetPoint"/>
<Array as="points">
<mxPoint x="310" y="140"/>
</Array>
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="23" value="False" style="edgeStyle=none;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;strokeColor=#1A1A1A;labelBackgroundColor=none;fontColor=#1A1A1A;" parent="1" target="19" edge="1">
<mxGeometry x="-0.1111" y="10" relative="1" as="geometry">
<mxPoint x="490" y="140" as="sourcePoint"/>
<mxPoint x="434.81000000000006" y="260" as="targetPoint"/>
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="24" value="" style="edgeStyle=none;html=1;entryX=1;entryY=0.5;entryDx=0;entryDy=0;strokeColor=#1A1A1A;labelBackgroundColor=none;fontColor=#1A1A1A;exitX=1;exitY=0.5;exitDx=0;exitDy=0;" parent="1" source="19" target="11" edge="1">
<mxGeometry x="0.1429" y="15" relative="1" as="geometry">
<mxPoint x="500" y="150" as="sourcePoint"/>
<mxPoint x="590" y="150" as="targetPoint"/>
<mxPoint as="offset"/>
<Array as="points">
<mxPoint x="740" y="140"/>
<mxPoint x="740" y="-120"/>
</Array>
</mxGeometry>
</mxCell>
<mxCell id="25" value="inventory &amp;gt;= 0" style="rhombus;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="185" y="-50" width="100" height="80" as="geometry"/>
</mxCell>
<mxCell id="26" value="False" style="edgeStyle=none;html=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;strokeColor=#1A1A1A;labelBackgroundColor=none;fontColor=#1A1A1A;" parent="1" source="11" target="25" edge="1">
<mxGeometry x="0.1429" y="15" relative="1" as="geometry">
<mxPoint x="434.80999999999995" y="190" as="sourcePoint"/>
<mxPoint x="434.80999999999995" y="260" as="targetPoint"/>
<mxPoint as="offset"/>
<Array as="points">
<mxPoint x="235" y="-120"/>
</Array>
</mxGeometry>
</mxCell>
<mxCell id="27" value="True" style="edgeStyle=none;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;strokeColor=#1A1A1A;labelBackgroundColor=none;fontColor=#1A1A1A;" parent="1" source="11" target="14" edge="1">
<mxGeometry x="0.1429" y="15" relative="1" as="geometry">
<mxPoint x="434.80999999999995" y="190" as="sourcePoint"/>
<mxPoint x="434.80999999999995" y="260" as="targetPoint"/>
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="28" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;print inventory left&lt;/div&gt;&lt;div style=&quot;background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="50" y="110" width="110" height="60" as="geometry"/>
</mxCell>
<mxCell id="29" value="True" style="edgeStyle=none;html=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;strokeColor=#1A1A1A;labelBackgroundColor=none;fontColor=#1A1A1A;" parent="1" source="25" edge="1">
<mxGeometry x="0.1429" y="15" relative="1" as="geometry">
<mxPoint x="104.57999999999993" y="40" as="sourcePoint"/>
<mxPoint x="104.57999999999993" y="110" as="targetPoint"/>
<mxPoint as="offset"/>
<Array as="points">
<mxPoint x="105" y="-10"/>
</Array>
</mxGeometry>
</mxCell>
<mxCell id="30" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;print&lt;/div&gt;&lt;div style=&quot;&quot;&gt;out of stock&lt;/div&gt;&lt;div style=&quot;background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="180" y="110" width="110" height="60" as="geometry"/>
</mxCell>
<mxCell id="31" value="False" style="edgeStyle=none;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;strokeColor=#1A1A1A;labelBackgroundColor=none;fontColor=#1A1A1A;" parent="1" target="30" edge="1">
<mxGeometry x="0.1429" y="15" relative="1" as="geometry">
<mxPoint x="234.6599999999999" y="30" as="sourcePoint"/>
<mxPoint x="234.6599999999999" y="100" as="targetPoint"/>
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>

73
max015/T05/3a.drawio Normal file
View File

@@ -0,0 +1,73 @@
<mxfile host="65bd71144e">
<diagram id="x3mvl7MIxiUfgaiuTItL" name="Page-1">
<mxGraphModel dx="1900" dy="2464" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="0" pageScale="1" pageWidth="827" pageHeight="1169" background="#ffffff" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="42" value="" style="edgeStyle=none;html=1;strokeColor=#1A1A1A;" parent="1" source="10" target="33" edge="1">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="10" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;&lt;font color=&quot;#1a1a1a&quot;&gt;loop through every sale in sales list,&lt;/font&gt;&lt;/div&gt;&lt;div style=&quot;&quot;&gt;&lt;font color=&quot;#1a1a1a&quot;&gt;get item &quot;sale&quot;&lt;/font&gt;&lt;/div&gt;&lt;div style=&quot;background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#E6E6E6;fontColor=#050505;strokeColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="281" y="-450" width="288" height="90" as="geometry"/>
</mxCell>
<mxCell id="43" value="" style="edgeStyle=none;html=1;strokeColor=#1A1A1A;" parent="1" source="32" target="10" edge="1">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="32" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;&lt;font color=&quot;#1a1a1a&quot; style=&quot;font-size: 12px;&quot;&gt;initialize&lt;/font&gt;&lt;/div&gt;&lt;div style=&quot;&quot;&gt;&lt;div&gt;sales = [100, 200, 100, 200, 300, 400, -1]&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;background-color: initial;&quot;&gt;inventory = 1000&lt;/span&gt;&lt;br&gt;&lt;/div&gt;&lt;/div&gt;&lt;div style=&quot;background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#E6E6E6;fontColor=#050505;strokeColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="281" y="-620" width="288" height="90" as="geometry"/>
</mxCell>
<mxCell id="41" value="False" style="edgeStyle=none;html=1;strokeColor=#1A1A1A;labelBackgroundColor=none;fontColor=#1A1A1A;" parent="1" source="33" target="34" edge="1">
<mxGeometry x="-0.3343" y="25" relative="1" as="geometry">
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="45" value="True" style="edgeStyle=none;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0.75;entryY=0;entryDx=0;entryDy=0;strokeColor=#1A1A1A;labelBackgroundColor=none;fontColor=#1A1A1A;" parent="1" source="33" target="36" edge="1">
<mxGeometry x="-0.003" y="20" relative="1" as="geometry">
<Array as="points">
<mxPoint x="580" y="-260"/>
<mxPoint x="580" y="50"/>
<mxPoint x="520" y="50"/>
<mxPoint x="456" y="50"/>
</Array>
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="33" value="end of list" style="rhombus;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="363" y="-300" width="125" height="80" as="geometry"/>
</mxCell>
<mxCell id="40" value="" style="edgeStyle=none;html=1;strokeColor=#1A1A1A;" parent="1" source="34" target="35" edge="1">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="34" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;inventory = inventory - sales[i]&lt;/div&gt;&lt;div style=&quot;background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="326" y="-160" width="198" height="60" as="geometry"/>
</mxCell>
<mxCell id="38" value="True" style="edgeStyle=none;html=1;strokeColor=#1A1A1A;fontColor=#1A1A1A;labelBackgroundColor=none;" parent="1" source="35" target="36" edge="1">
<mxGeometry x="0.2" y="14" relative="1" as="geometry">
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="44" value="False" style="edgeStyle=none;html=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=0.5;entryDx=0;entryDy=0;strokeColor=#1A1A1A;labelBackgroundColor=none;fontColor=#1A1A1A;" parent="1" source="35" target="10" edge="1">
<mxGeometry x="-0.0049" y="-20" relative="1" as="geometry">
<Array as="points">
<mxPoint x="220"/>
<mxPoint x="220" y="-405"/>
</Array>
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="35" value="inventory &amp;lt; 0" style="rhombus;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="363" y="-40" width="125" height="80" as="geometry"/>
</mxCell>
<mxCell id="39" value="" style="edgeStyle=none;html=1;strokeColor=#1A1A1A;" parent="1" source="36" target="37" edge="1">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="36" value="print inventory left" style="rounded=0;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="363.75" y="90" width="123.5" height="50" as="geometry"/>
</mxCell>
<mxCell id="37" value="end" style="rounded=0;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="363.75" y="190" width="123.5" height="50" as="geometry"/>
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>

72
max015/T05/3b.drawio Normal file
View File

@@ -0,0 +1,72 @@
<mxfile host="65bd71144e">
<diagram id="x3mvl7MIxiUfgaiuTItL" name="Page-1">
<mxGraphModel dx="1900" dy="2464" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="0" pageScale="1" pageWidth="827" pageHeight="1169" background="#ffffff" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="42" value="" style="edgeStyle=none;html=1;strokeColor=#1A1A1A;" edge="1" parent="1" source="10" target="33">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="10" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;&lt;font color=&quot;#1a1a1a&quot;&gt;loop through every sale in sales list,&lt;/font&gt;&lt;/div&gt;&lt;div style=&quot;&quot;&gt;&lt;font color=&quot;#1a1a1a&quot;&gt;get item &quot;sale&quot;&lt;/font&gt;&lt;/div&gt;&lt;div style=&quot;background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#E6E6E6;fontColor=#050505;strokeColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="281" y="-450" width="288" height="90" as="geometry"/>
</mxCell>
<mxCell id="43" value="" style="edgeStyle=none;html=1;strokeColor=#1A1A1A;" edge="1" parent="1" source="32" target="10">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="32" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;&lt;font color=&quot;#1a1a1a&quot; style=&quot;font-size: 12px;&quot;&gt;initialize&lt;/font&gt;&lt;/div&gt;&lt;div style=&quot;&quot;&gt;&lt;div&gt;sales = [100, 200, 100, 200, 300, 400, -1]&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;background-color: initial;&quot;&gt;inventory = 1000&lt;/span&gt;&lt;br&gt;&lt;/div&gt;&lt;/div&gt;&lt;div style=&quot;background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#E6E6E6;fontColor=#050505;strokeColor=#1A1A1A;" vertex="1" parent="1">
<mxGeometry x="281" y="-620" width="288" height="90" as="geometry"/>
</mxCell>
<mxCell id="41" value="False" style="edgeStyle=none;html=1;strokeColor=#1A1A1A;labelBackgroundColor=none;fontColor=#1A1A1A;" edge="1" parent="1" source="33" target="34">
<mxGeometry x="-0.3343" y="25" relative="1" as="geometry">
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="45" value="True" style="edgeStyle=none;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0.75;entryY=0;entryDx=0;entryDy=0;strokeColor=#1A1A1A;labelBackgroundColor=none;fontColor=#1A1A1A;" edge="1" parent="1" source="33" target="37">
<mxGeometry x="-0.003" y="20" relative="1" as="geometry">
<Array as="points">
<mxPoint x="580" y="-260"/>
<mxPoint x="580" y="170"/>
<mxPoint x="456" y="170"/>
</Array>
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="33" value="end of list" style="rhombus;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" vertex="1" parent="1">
<mxGeometry x="363" y="-300" width="125" height="80" as="geometry"/>
</mxCell>
<mxCell id="40" value="" style="edgeStyle=none;html=1;strokeColor=#1A1A1A;" edge="1" parent="1" source="34" target="35">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="34" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;inventory = inventory - sales[i]&lt;/div&gt;&lt;div style=&quot;background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" vertex="1" parent="1">
<mxGeometry x="326" y="-160" width="198" height="60" as="geometry"/>
</mxCell>
<mxCell id="38" value="True" style="edgeStyle=none;html=1;strokeColor=#1A1A1A;fontColor=#1A1A1A;labelBackgroundColor=none;" edge="1" parent="1" source="35" target="36">
<mxGeometry x="0.2" y="14" relative="1" as="geometry">
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="44" value="False" style="edgeStyle=none;html=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=0.5;entryDx=0;entryDy=0;strokeColor=#1A1A1A;labelBackgroundColor=none;fontColor=#1A1A1A;" edge="1" parent="1" source="35" target="10">
<mxGeometry x="-0.0049" y="-20" relative="1" as="geometry">
<Array as="points">
<mxPoint x="220"/>
<mxPoint x="220" y="-405"/>
</Array>
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="35" value="inventory &amp;lt; 0" style="rhombus;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" vertex="1" parent="1">
<mxGeometry x="363" y="-40" width="125" height="80" as="geometry"/>
</mxCell>
<mxCell id="39" value="" style="edgeStyle=none;html=1;strokeColor=#1A1A1A;" edge="1" parent="1" source="36" target="37">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="36" value="print out of stock" style="rounded=0;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" vertex="1" parent="1">
<mxGeometry x="363.75" y="90" width="123.5" height="50" as="geometry"/>
</mxCell>
<mxCell id="37" value="end" style="rounded=0;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" vertex="1" parent="1">
<mxGeometry x="363.75" y="190" width="123.5" height="50" as="geometry"/>
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>

67
max015/T05/3c.drawio Normal file
View File

@@ -0,0 +1,67 @@
<mxfile host="65bd71144e">
<diagram id="x3mvl7MIxiUfgaiuTItL" name="Page-1">
<mxGraphModel dx="1346" dy="1840" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="0" pageScale="1" pageWidth="827" pageHeight="1169" background="#ffffff" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="49" style="edgeStyle=none;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;labelBackgroundColor=none;strokeColor=#1A1A1A;fontColor=#1A1A1A;" edge="1" parent="1" source="10" target="46">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="10" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;&lt;font color=&quot;#1a1a1a&quot;&gt;loop through every sale in sales list,&lt;/font&gt;&lt;/div&gt;&lt;div style=&quot;&quot;&gt;&lt;font color=&quot;#1a1a1a&quot;&gt;get item &quot;sale&quot; (denoted 's')&lt;/font&gt;&lt;/div&gt;&lt;div style=&quot;background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#E6E6E6;fontColor=#050505;strokeColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="281" y="-450" width="288" height="90" as="geometry"/>
</mxCell>
<mxCell id="43" value="" style="edgeStyle=none;html=1;strokeColor=#1A1A1A;" parent="1" source="32" target="10" edge="1">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="32" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;&lt;font color=&quot;#1a1a1a&quot; style=&quot;font-size: 12px;&quot;&gt;initialize&lt;/font&gt;&lt;/div&gt;&lt;div style=&quot;&quot;&gt;&lt;div&gt;sales = [100, 200, None, 100, 200, 300, 400, None]&lt;/div&gt;&lt;div&gt;&lt;span style=&quot;background-color: initial;&quot;&gt;inventory = 1000&lt;/span&gt;&lt;br&gt;&lt;/div&gt;&lt;/div&gt;&lt;div style=&quot;background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#E6E6E6;fontColor=#050505;strokeColor=#1A1A1A;" parent="1" vertex="1">
<mxGeometry x="281" y="-600" width="288" height="90" as="geometry"/>
</mxCell>
<mxCell id="48" value="True" style="edgeStyle=none;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=1;entryY=0.5;entryDx=0;entryDy=0;strokeColor=#1A1A1A;labelBackgroundColor=none;fontColor=#1A1A1A;" edge="1" parent="1" source="46" target="10">
<mxGeometry x="0.0172" y="20" relative="1" as="geometry">
<Array as="points">
<mxPoint x="640" y="-250"/>
<mxPoint x="640" y="-405"/>
</Array>
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="51" value="False" style="edgeStyle=none;html=1;labelBackgroundColor=none;strokeColor=#1A1A1A;fontColor=#1A1A1A;" edge="1" parent="1" source="46" target="50">
<mxGeometry y="15" relative="1" as="geometry">
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="46" value="s == None ?" style="rhombus;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" vertex="1" parent="1">
<mxGeometry x="362.5" y="-290" width="125" height="80" as="geometry"/>
</mxCell>
<mxCell id="53" value="" style="edgeStyle=none;html=1;labelBackgroundColor=none;strokeColor=#1A1A1A;fontColor=#1A1A1A;" edge="1" parent="1" source="50" target="52">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="50" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;&lt;font color=&quot;#1a1a1a&quot;&gt;inventory = inventory - s&lt;/font&gt;&lt;/div&gt;&lt;div style=&quot;background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#E6E6E6;fontColor=#050505;strokeColor=#1A1A1A;" vertex="1" parent="1">
<mxGeometry x="281" y="-170" width="288" height="90" as="geometry"/>
</mxCell>
<mxCell id="55" value="False" style="edgeStyle=none;html=1;labelBackgroundColor=none;strokeColor=#1A1A1A;fontColor=#1A1A1A;" edge="1" parent="1" source="52" target="54">
<mxGeometry y="15" relative="1" as="geometry">
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="58" value="True" style="edgeStyle=none;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;labelBackgroundColor=none;strokeColor=#1A1A1A;fontColor=#1A1A1A;" edge="1" parent="1" source="52" target="56">
<mxGeometry x="-0.2537" y="10" relative="1" as="geometry">
<Array as="points">
<mxPoint x="575"/>
</Array>
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="52" value="inventory &amp;lt; 0 ?" style="rhombus;whiteSpace=wrap;html=1;strokeColor=#1A1A1A;fillColor=#E6E6E6;fontColor=#1A1A1A;" vertex="1" parent="1">
<mxGeometry x="362.5" y="-40" width="125" height="80" as="geometry"/>
</mxCell>
<mxCell id="54" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;&lt;font color=&quot;#1a1a1a&quot;&gt;print &quot;out of stock&quot;&lt;/font&gt;&lt;/div&gt;&lt;div style=&quot;background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#E6E6E6;fontColor=#050505;strokeColor=#1A1A1A;" vertex="1" parent="1">
<mxGeometry x="370" y="80" width="110" height="90" as="geometry"/>
</mxCell>
<mxCell id="56" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;div style=&quot;&quot;&gt;&lt;font color=&quot;#1a1a1a&quot;&gt;end&lt;/font&gt;&lt;/div&gt;&lt;div style=&quot;background-color: rgb(30, 30, 30); font-size: 18px; font-family: &amp;quot;Monaco for Powerline&amp;quot;, &amp;quot;Droid Sans Mono&amp;quot;, &amp;quot;monospace&amp;quot;, monospace, Consolas, &amp;quot;Courier New&amp;quot;, monospace;&quot;&gt;&lt;/div&gt;&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#E6E6E6;fontColor=#050505;strokeColor=#1A1A1A;" vertex="1" parent="1">
<mxGeometry x="520" y="80" width="110" height="90" as="geometry"/>
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>

View File

@@ -0,0 +1,914 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# CDS1001 Tutorial 5 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 loops are used in coding\n",
"- Be able to understand and use while loop and for loop\n",
"- Be able to understand and apply the basic pattens of loops\n",
"- Be able to understand and draw flow charts for loops\n",
"- Be able to use print() in debugging"
]
},
{
"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 5 report\n",
"* Complete Parts 1-5 led by the lecturer\n",
"* Complete Part 6 independently\n",
"* Follow Section 3 of the tutorial instruction to save the report and zip the report folder. The zip file is named as CDS1001T5Report{your student_id}.zip (e.g., if student_id is 1234567, then the zip file's name is CDS1001T5Report1234567.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'>24 Oct 2023 11:55 PM</font>**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 1 Loop"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.1. Read and execute the following code, and answer the questions below:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter the city you are from: Hong Kong\n",
"Enter the city you are from: Shanghai\n",
"Enter the city you are from: Tokyo\n",
"Enter the city you are from: Hong Kong\n",
"Enter the city you are from: end\n",
"Number of guests from Hong Kong: 2\n"
]
}
],
"source": [
"number_hk = 0\n",
"flag_end = False\n",
"while not flag_end:\n",
" city = input('Enter the city that the guest comes from: ')\n",
" if city == 'Hong Kong':\n",
" number_hk = number_hk +1\n",
" elif city == 'End' or city == 'end':\n",
" flag_end = True\n",
"print('Number of guests from Hong Kong:', number_hk)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 1.1.1: What is the body of the loop used in the code above? (2 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Answer:\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 1.1.2: What's the condition for the loop to stop? (2 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to answer the question above</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 1.1.3: What does the loop of the above code do? (2 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to answer the question above</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 1.1.4: Is it possible to rewrite the code above without using loops but using repeated codes? Explain your reasons. (2 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to answer the question above</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 2 while Loop"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.1. Execute the codes below, explain how the codes are executed, and draw the flowcharts. (4 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (a)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Inventory left: -300\n"
]
}
],
"source": [
"sales = [100, 200, 100, 200, 300, 400, -1]\n",
"i = 0\n",
"inventory = 1000\n",
"while sales[i]>=0: #sales[i] indicates the (i+1)-th item of the sequence sales\n",
" inventory = inventory - sales[i]\n",
" i = i + 1\n",
"print('Inventory left:', inventory)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to explain how the above code is executed </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to insert a figure of the flowchart of the code above</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (b)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Out of stock!\n"
]
}
],
"source": [
"sales = [100, 200, 100, 200, 300, 400, -1]\n",
"i = 0\n",
"inventory = 1000\n",
"while sales[i]>=0: #sales[i] indicates the (i+1)-th item of the sequence sales\n",
" inventory = inventory - sales[i]\n",
" if inventory < 0:\n",
" break\n",
" i = i + 1\n",
"if inventory >= 0:\n",
" print('Inventory left:', inventory)\n",
"else:\n",
" print('Out of stock!')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to explain how the above code is executed </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to insert a figure of the flowchart of the code above</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.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": 12,
"metadata": {},
"outputs": [
{
"ename": "IndentationError",
"evalue": "expected an indented block (<ipython-input-12-a14b33f59865>, line 4)",
"output_type": "error",
"traceback": [
"\u001b[0;36m File \u001b[0;32m\"<ipython-input-12-a14b33f59865>\"\u001b[0;36m, line \u001b[0;32m4\u001b[0m\n\u001b[0;31m total = total + i\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mIndentationError\u001b[0m\u001b[0;31m:\u001b[0m expected an indented block\n"
]
}
],
"source": [
"total = 0\n",
"i = 1\n",
"while i<=100:\n",
"total = total + i\n",
"i = i + 1\n",
"print(total)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to explain what are the errors and how to fix them </font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell to write the correct code:\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (b)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"ename": "SyntaxError",
"evalue": "invalid syntax (<ipython-input-6-4110f0b7133b>, line 4)",
"output_type": "error",
"traceback": [
"\u001b[1;36m File \u001b[1;32m\"<ipython-input-6-4110f0b7133b>\"\u001b[1;36m, line \u001b[1;32m4\u001b[0m\n\u001b[1;33m while flag=0:\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
]
}
],
"source": [
"total = 0\n",
"flag = 0\n",
"i = 1\n",
"while flag=0:\n",
" total = total + i\n",
" i = i + 1\n",
" if i > 100:\n",
" flag = 1\n",
"print(total)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to explain what are the errors and how to fix them </font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell to write the correct code:\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.3. Write a code for the flow chart below using a while loop, and explain the code: (4 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src = \"flow0.png\" width=\"400\">"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"#edit this cell to write the code for the flowchart above"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to explain what the above code does:</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 3 for Loop"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 3.1. Execute the codes below, explain how the codes are executed, and draw the flowcharts: (6 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (a)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Inventory left: -300\n"
]
}
],
"source": [
"sales = [100, 200, 100, 200, 300, 400]\n",
"inventory = 1000\n",
"for s in sales:\n",
" inventory = inventory - s \n",
"print('Inventory left:', inventory)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to explain how the above code is executed </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to insert a figure of the flowchart of the code above</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (b)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Out of stock!\n"
]
}
],
"source": [
"sales = [100, 200, 100, 200, 300, 400]\n",
"inventory = 1000\n",
"for s in sales:\n",
" inventory = inventory - s\n",
" if inventory<0:\n",
" print('Out of stock!')\n",
" break"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to explain how the above code is executed </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to insert a figure of the flowchart of the code above</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### (c)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Out of stock!\n"
]
}
],
"source": [
"sales = [100, 200, None, 100, 200, 300, 400, None] \n",
"inventory = 1000\n",
"for s in sales:\n",
" if s == None:\n",
" continue\n",
" inventory = inventory - s\n",
" if inventory<0:\n",
" print('Out of stock!')\n",
" break"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to explain how the above code is executed </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to insert a figure of the flowchart of the code above</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 3.2. Write a code for the flow chart below, using for loop, and explain the code. (4 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src = \"flow1.png\" width=\"400\">"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"#edit this cell to write the code for the flowchart above"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to explain what the above code does:</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 4 Loop Patterns"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 4.1. Vote\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\". Please write a program to enter each colleague's choice, and output the poll result.\n",
"\n",
"Sample Input/Output\n",
"\n",
" Enter Your Choice (0-Exit Poll, 1-Disney, 2-Hotel ICON, 3-Ocean Park): 1\n",
" Enter Your Choice (0-Exit Poll, 1-Disney, 2-Hotel ICON, 3-Ocean Park): 2\n",
" Enter Your Choice (0-Exit Poll, 1-Disney, 2-Hotel ICON, 3-Ocean Park): 2\n",
" Enter Your Choice (0-Exit Poll, 1-Disney, 2-Hotel ICON, 3-Ocean Park): 3\n",
" Enter Your Choice (0-Exit Poll, 1-Disney, 2-Hotel ICON, 3-Ocean Park): 0\n",
" \n",
" Disney: 1\n",
" Hotel ICON: 2\n",
" Ocean Park: 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 4.1.1: How are you going to define variables to store votes for three different candidate locations? What are their names and types? (2 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to answer the question above:</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 4.1.2: Are you going to use a while loop or a for loop to write the code? Why and how?(2 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to answer the question above:</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 4.1.3: Write codes. (6 points)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"#edit this cell to write the program"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 4.1.4: Are there any other ways to write the code? For example, is it possible to use an infinite loop with break, or use a flag variable, etc? (2 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to answer the question above:</font>"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"#edit this cell to show other possible ways to write the code"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 5 Debugging"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 5.1. Execute the code below, and use the information printed to identify the error and fix it"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"max of data is: 5\n",
"sum of data is: 21\n",
"min of data is: 1\n"
]
}
],
"source": [
"data = [1,4,2,5,4]\n",
"result = 0\n",
"for entry in data:\n",
" if entry>result:\n",
" result = entry\n",
"print('max of data is:', result)\n",
"for entry in data:\n",
" result = result + entry\n",
"print('sum of data is:', result)\n",
"for entry in data:\n",
" if entry<result:\n",
" result = entry\n",
"print('min of data is:', result)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 5.1.1. Execute the code above, and describe which output information is not correct. (2 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to answer the question above:</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 5.1.2. From the wrong output information identified, can you tell which part of the code may have problems? (2 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to answer the question above:</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Question 5.1.3. Describe the problem of the code, and explain how to correct it. (4 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to answer the question above:</font>"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell to write the corrected code"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>*Create a python file of the code above in Python IDLE, execute the code for a test, and paste the screenshot of the test result below in this cell:*</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 6 Other Exercises"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 6.1. Cheapest Carrier (25 points)\n",
"Use a while loop to write a program that prompts a logistics manager to enter shipping rates submitted by carriers until the manager enters 'quit'. The program then outputs the lowest shipping rate, and the carrier who submits the lowest shipping rate.\n",
"\n",
"Sample Input/Output\n",
"\n",
" Enter Carrier Name: OOCL\n",
" Enter Shipping Rate: 130\n",
" Enter Carrier Name: MMM\n",
" Enter Shipping Rate: 100\n",
" Enter Carrier Name: NNN\n",
" Enter Shipping Rate: 110\n",
" Enter Carrier Name: quit\n",
" \n",
" The lowest shipping rate is 100, submitted by MMM."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"#edit this cell to write your code\n",
"#Hint: (1) define variables to store the lowest shipping rate, and the carrier who submits the lowest shipping rate. \n",
"# (2) update these variables in each iteration"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Execute and test your revised code above for various inputs. Edit this cell to copy your test results below:</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to explain how you use iterations to write the code:</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 6.2. Sales Forecast (25 points)\n",
"\n",
"Given the actual sales in the past year as follows, a sales manager predicts sales for the new year in the following way:\n",
"\n",
"For the i-th month of the new year, its forecasted sales = the actual sales of the i-th month of the past year * 1.2 if i is not 6 or 7; otherwise, its forecasted sales = the actual sales of the i-th month of the past year * 1.3\n",
"\n",
"Use a for loop to revise the code below, so as to output the sales forecast for the 12 months of the new year"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Actual Sales of month 1 in the past year: 100\n",
"Actual Sales of month 2 in the past year: 120\n",
"Actual Sales of month 3 in the past year: 100\n",
"Actual Sales of month 4 in the past year: 120\n",
"Actual Sales of month 5 in the past year: 140\n",
"Actual Sales of month 6 in the past year: 130\n",
"Actual Sales of month 7 in the past year: 120\n",
"Actual Sales of month 8 in the past year: 150\n",
"Actual Sales of month 9 in the past year: 150\n",
"Actual Sales of month 10 in the past year: 110\n",
"Actual Sales of month 11 in the past year: 120\n",
"Actual Sales of month 12 in the past year: 100\n"
]
}
],
"source": [
"#the actual sales of the 12 months of the past year are stored in the list actual_sales_past:\n",
"actual_sales_past = [100,120,100,120,140,130,120,150,150,110,120,100]\n",
"#the actual sales of the i-th month of the past year is stored in actual_sales_past[i-1] for i =1,2,...,12\n",
"#the for loop below is to print the actual sales for the 12 months of the past years:\n",
"for i in [1,2,3,4,5,6,7,8,9,10,11,12]:\n",
" print('Actual Sales of month', i, 'in the past year:', actual_sales_past[i-1])\n",
"\n",
"#Based on the code above and the rule mentioned in the problem description, \n",
"#write a new code below to compute and output the sales forcast for the 12 months of the new year: \n",
"\n",
"#Hints:(1) use a for loop to iteratate data entry in actual_sales_past; \n",
"# (2) use a variable i to indicate the month id to be processed in the iteartion;\n",
"# (3) compute the forecasted sales for month i based on the actual sales of the i-th month of the past year, \n",
"# which is stored in actual_sales_past[i-1] for i = 1,2,...,12\n",
"# (4) print the forecasted sales for month i\n",
"# (5) update variable i"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Execute and test your revised code above for various inputs. Edit this cell to copy your test results below:</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to explain how you use iterations to write the code:</font>"
]
}
],
"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
}

BIN
max015/T05/flow0.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
max015/T05/flow1.png (Stored with Git LFS) Normal file

Binary file not shown.

13
max015/T05/package.json Normal file
View File

@@ -0,0 +1,13 @@
{
"name": "t05",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"gitUpdate":"git add . && git commit -m\"update max015\""
},
"keywords": [],
"author": "",
"license": "ISC"
}

View File

@@ -0,0 +1,73 @@
<mxfile host="65bd71144e">
<diagram id="IsahtfXpGEnurlJZm06P" name="Page-1">
<mxGraphModel dx="1085" dy="1014" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="15" value="" style="edgeStyle=none;html=1;fontColor=#000000;" edge="1" parent="1" source="2" target="5">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="2" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;font&gt;&lt;span style=&quot;font-size: 18px;&quot;&gt;open file request.txt, assign it to file_handler input_file&lt;/span&gt;&lt;/font&gt;&lt;br&gt;&lt;/div&gt;" style="whiteSpace=wrap;html=1;labelBackgroundColor=default;fontColor=#000000;" parent="1" vertex="1">
<mxGeometry x="110" y="60" width="380" height="60" as="geometry"/>
</mxCell>
<mxCell id="16" value="" style="edgeStyle=none;html=1;fontColor=#000000;" edge="1" parent="1" source="5" target="7">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="5" value="&lt;div style=&quot;line-height: 24px;&quot;&gt;&lt;font&gt;&lt;span style=&quot;font-size: 18px;&quot;&gt;open file new_request.txt, assign it to file_handler output_file&lt;/span&gt;&lt;/font&gt;&lt;br&gt;&lt;/div&gt;" style="whiteSpace=wrap;html=1;fontFamily=Helvetica;strokeColor=default;fillColor=none;align=center;labelBackgroundColor=default;fontColor=#3b3535;" parent="1" vertex="1">
<mxGeometry x="110" y="190" width="380" height="60" as="geometry"/>
</mxCell>
<mxCell id="17" value="" style="edgeStyle=none;html=1;fontColor=#000000;" edge="1" parent="1" source="7" target="9">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="23" style="edgeStyle=none;html=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;fontColor=#000000;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="7" target="10">
<mxGeometry relative="1" as="geometry">
<mxPoint x="50" y="370.1111111111111" as="targetPoint"/>
<Array as="points">
<mxPoint x="100" y="370"/>
<mxPoint x="100" y="620"/>
</Array>
</mxGeometry>
</mxCell>
<mxCell id="7" value="if the line started with APPLE" style="rhombus;whiteSpace=wrap;html=1;fontSize=18;" parent="1" vertex="1">
<mxGeometry x="153.75" y="310" width="292.5" height="120" as="geometry"/>
</mxCell>
<mxCell id="18" value="" style="edgeStyle=none;html=1;fontColor=#000000;" edge="1" parent="1" source="9" target="10">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="9" value="&lt;font style=&quot;font-size: 18px;&quot;&gt;print it out without new line ending&amp;nbsp;&lt;br&gt;write it to the output_file&lt;br&gt;&lt;/font&gt;" style="whiteSpace=wrap;html=1;fontFamily=Helvetica;" parent="1" vertex="1">
<mxGeometry x="135" y="480" width="330" height="60" as="geometry"/>
</mxCell>
<mxCell id="19" value="" style="edgeStyle=none;html=1;fontColor=#000000;" edge="1" parent="1" source="10" target="14">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="10" value="&lt;font style=&quot;font-size: 18px;&quot;&gt;next line&lt;/font&gt;" style="whiteSpace=wrap;html=1;" parent="1" vertex="1">
<mxGeometry x="160" y="590" width="280" height="60" as="geometry"/>
</mxCell>
<mxCell id="21" value="" style="edgeStyle=none;html=1;fontColor=#000000;" edge="1" parent="1" source="11" target="13">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="11" value="close the output_file handler" style="whiteSpace=wrap;html=1;fontSize=18;" parent="1" vertex="1">
<mxGeometry x="160" y="820" width="280" height="60" as="geometry"/>
</mxCell>
<mxCell id="13" value="close the input_file handler" style="whiteSpace=wrap;html=1;fontSize=18;" parent="1" vertex="1">
<mxGeometry x="160" y="930" width="280" height="60" as="geometry"/>
</mxCell>
<mxCell id="20" value="" style="edgeStyle=none;html=1;fontColor=#000000;" edge="1" parent="1" source="14" target="11">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="22" style="edgeStyle=none;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;fontColor=#000000;" edge="1" parent="1" source="14">
<mxGeometry relative="1" as="geometry">
<mxPoint x="300" y="280" as="targetPoint"/>
<Array as="points">
<mxPoint x="560" y="740"/>
<mxPoint x="560" y="280"/>
</Array>
</mxGeometry>
</mxCell>
<mxCell id="14" value="reach the &lt;br&gt;end of file ?" style="rhombus;whiteSpace=wrap;html=1;fontSize=18;" parent="1" vertex="1">
<mxGeometry x="192.5" y="700" width="215" height="80" as="geometry"/>
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>

BIN
max015/T06/T06/3.1.3.png (Stored with Git LFS) Normal file

Binary file not shown.

25
max015/T06/T06/4_1_6.py Normal file
View File

@@ -0,0 +1,25 @@
#edit this cell to write the program
votes_file = open ('./report/votes.txt', 'r')
results_file = open ('./report/results.txt', 'w')
disney_vote = 0
hotel_icon_vote = 0
ocean_park_vote = 0
for s in votes_file:
if s.strip() == 'Disney':
disney_vote = disney_vote + 1
if s.strip() == 'Hotel ICON' :
hotel_icon_vote = hotel_icon_vote + 1
if s.strip() == 'Ocean Park':
ocean_park_vote = ocean_park_vote + 1
disney_output = 'Disney:%s\n' % disney_vote
hotel_icon_output = 'Hotel ICON:%s\n' % hotel_icon_vote
ocean_park_output = 'Ocean Park:%s\n' % ocean_park_vote
output = disney_output + hotel_icon_output + ocean_park_output
results_file.write(output.strip())
results_file.close()
votes_file.close()

24
max015/T06/T06/5_1_5.py Normal file
View File

@@ -0,0 +1,24 @@
#edit this cell to write your code
#Hint: (1) input the name of the input file
# (2) define a file handle for the input file
# (3) for each line of the file, extract the carrier id and shipping rate by using string's find function
# and slice operation, and then update the variables that store the lowest shipping rate and its carrier id
lowest_rate = -1
lowest_rate_carrier = ""
file_name = input("please enter a file name: ")
with open(file_name, 'r') as carrier_file:
for s in carrier_file:
if s != "-1":
p = s.find(' ')
rate = float(s[p+1:])
carrier = s[0:p]
if ( rate < lowest_rate or lowest_rate == -1):
lowest_rate_carrier = carrier
lowest_rate = rate
output = 'The lowest shipping rate is %s, ' % lowest_rate
output1 = 'submitted by %s.' % lowest_rate_carrier
print(output+ output1)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,3 @@
APPLE 100
APPLE 120
APPLE 130

View File

@@ -0,0 +1,7 @@
OOCL 130
MMM 100
NNN 110
OOO 99
PPP 80
RRR 111
-1

View File

@@ -0,0 +1,3 @@
Disney:3
Hotel ICON:4
Ocean Park:3

View File

@@ -0,0 +1,11 @@
Disney
Hotel ICON
Hotel ICON
Ocean Park
Disney
Hotel ICON
Ocean Park
Disney
Ocean Park
Hotel ICON
-1

View File

@@ -0,0 +1,6 @@
APPLE 100
ORANGE 90
BANANA 95
APPLE 120
APPLE 130
BANANA 2 5

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,6 @@
Dear John Lee,
Thank you for purchasing Laster Printer X50.
Wish you Merry Christmas and Happy New year!
Regards,
Company LU

View File

@@ -0,0 +1,6 @@
Dear Eric Chan,
Thank you for purchasing Laster Printer X51.
Wish you Merry Christmas and Happy New year!
Regards,
Company LU

View File

@@ -0,0 +1,6 @@
Dear Paul Chan,
Thank you for purchasing LED Monitor M310.
Wish you Merry Christmas and Happy New year!
Regards,
Company LU

View File

@@ -0,0 +1,4 @@
000001, John Lee, Laster Printer X50
000002, Eric Chan, Laster Printer X51
000003, Paul Chan, LED Monitor M310
-1

View File

@@ -0,0 +1,18 @@
#edit this cell to write the program
hotel = []
with open("./votes.txt",'r') as fi:
lines = fi.readlines()
for l in lines:
l2 = l.strip()
hotel.extend(l2.split(', '))
print("Disney: " + str(hotel.count("Disney")))
print("Hotel ICON: " + str(hotel.count("Hotel ICON")))
print("Ocean Park: " + str(hotel.count("Ocean Park")))
print("helloworld")

BIN
max015/T07/deliver/txt_content.png (Stored with Git LFS) Normal file

Binary file not shown.

View File

@@ -0,0 +1,13 @@
Disney, Ocean Park
Hotel ICON, Ocean Park
Hotel ICON
Ocean Park
Disney, Ocean Park
Hotel ICON, Ocean Park
Hotel ICON
Ocean Park
Disney, Ocean Park
Hotel ICON, Ocean Park
Hotel ICON
Ocean Park
-1

View File

@@ -0,0 +1,6 @@
Dear John Lee,
Thank you for purchasing Laster Printer X50.
Wish you Merry Christmas and Happy New year!
Regards,
Company LU

View File

@@ -0,0 +1,6 @@
Dear Eric Chan,
Thank you for purchasing Laster Printer X51.
Wish you Merry Christmas and Happy New year!
Regards,
Company LU

View File

@@ -0,0 +1,6 @@
Dear Paul Chan,
Thank you for purchasing LED Monitor M310.
Wish you Merry Christmas and Happy New year!
Regards,
Company LU

4
max015/T07/sales.txt Normal file
View File

@@ -0,0 +1,4 @@
000001, John Lee, Laster Printer X50
000002, Eric Chan, Laster Printer X51
000003, Paul Chan, LED Monitor M310
-1

18
max015/T07/test.py Normal file
View File

@@ -0,0 +1,18 @@
#edit this cell to write the program
hotel = []
with open("./votes.txt",'r') as fi:
lines = fi.readlines()
for l in lines:
l2 = l.strip()
hotel.extend(l2.split(', '))
print("Disney: " + str(hotel.count("Disney")))
print("Hotel ICON: " + str(hotel.count("Hotel ICON")))
print("Ocean Park: " + str(hotel.count("Ocean Park")))
print("helloworld")

BIN
max015/T07/txt_content.png (Stored with Git LFS) Normal file

Binary file not shown.

13
max015/T07/votes.txt Normal file
View File

@@ -0,0 +1,13 @@
Disney, Ocean Park
Hotel ICON, Ocean Park
Hotel ICON
Ocean Park
Disney, Ocean Park
Hotel ICON, Ocean Park
Hotel ICON
Ocean Park
Disney, Ocean Park
Hotel ICON, Ocean Park
Hotel ICON
Ocean Park
-1

BIN
max015/T08/2023-11-09_14-47.png (Stored with Git LFS) Normal file

Binary file not shown.

File diff suppressed because it is too large Load Diff

76
max015/T08/Q2_4.drawio Normal file
View File

@@ -0,0 +1,76 @@
<mxfile host="65bd71144e">
<diagram id="gbafj2K8NTiN-hHC4odU" name="Page-1">
<mxGraphModel dx="812" dy="945" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="11" value="" style="edgeStyle=none;html=1;" edge="1" parent="1" source="2" target="3">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="2" value="Iterate every character" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="200" y="200" width="160" height="60" as="geometry"/>
</mxCell>
<mxCell id="9" value="No" style="edgeStyle=none;html=1;" edge="1" parent="1" source="3" target="8">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="10" value="Yes" style="edgeStyle=none;html=1;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="3" target="7">
<mxGeometry relative="1" as="geometry">
<Array as="points">
<mxPoint x="520" y="400"/>
</Array>
</mxGeometry>
</mxCell>
<mxCell id="3" value="Found match&lt;br&gt;in the dictionary ?" style="rhombus;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="200" y="320" width="160" height="160" as="geometry"/>
</mxCell>
<mxCell id="15" style="edgeStyle=none;html=1;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="7" target="12">
<mxGeometry relative="1" as="geometry">
<Array as="points">
<mxPoint x="520" y="610"/>
<mxPoint x="280" y="610"/>
</Array>
</mxGeometry>
</mxCell>
<mxCell id="7" value="increase character count" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="440" y="520" width="160" height="60" as="geometry"/>
</mxCell>
<mxCell id="14" value="" style="edgeStyle=none;html=1;" edge="1" parent="1" source="8" target="12">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="8" value="initialize character count = 1" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="200" y="520" width="160" height="60" as="geometry"/>
</mxCell>
<mxCell id="13" value="No" style="edgeStyle=none;html=1;" edge="1" parent="1" source="12">
<mxGeometry relative="1" as="geometry">
<mxPoint x="280" y="300" as="targetPoint"/>
<Array as="points">
<mxPoint x="120" y="720"/>
<mxPoint x="120" y="300"/>
</Array>
</mxGeometry>
</mxCell>
<mxCell id="17" value="" style="edgeStyle=none;html=1;" edge="1" parent="1" source="12" target="16">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="12" value="end of string ?" style="rhombus;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="200" y="640" width="160" height="160" as="geometry"/>
</mxCell>
<mxCell id="22" value="" style="edgeStyle=none;html=1;" edge="1" parent="1" source="16" target="19">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="16" value="Print output" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="200" y="850" width="160" height="60" as="geometry"/>
</mxCell>
<mxCell id="20" value="" style="edgeStyle=none;html=1;" edge="1" parent="1" source="18" target="2">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="18" value="Start" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="220" y="100" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="19" value="End" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="220" y="960" width="120" height="60" as="geometry"/>
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>

BIN
max015/T08/deliver/2023-11-09_14-47.png (Stored with Git LFS) Normal file

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,76 @@
<mxfile host="65bd71144e">
<diagram id="gbafj2K8NTiN-hHC4odU" name="Page-1">
<mxGraphModel dx="812" dy="945" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="11" value="" style="edgeStyle=none;html=1;" edge="1" parent="1" source="2" target="3">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="2" value="Iterate every character" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="200" y="200" width="160" height="60" as="geometry"/>
</mxCell>
<mxCell id="9" value="No" style="edgeStyle=none;html=1;" edge="1" parent="1" source="3" target="8">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="10" value="Yes" style="edgeStyle=none;html=1;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="3" target="7">
<mxGeometry relative="1" as="geometry">
<Array as="points">
<mxPoint x="520" y="400"/>
</Array>
</mxGeometry>
</mxCell>
<mxCell id="3" value="Found match&lt;br&gt;in the dictionary ?" style="rhombus;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="200" y="320" width="160" height="160" as="geometry"/>
</mxCell>
<mxCell id="15" style="edgeStyle=none;html=1;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="7" target="12">
<mxGeometry relative="1" as="geometry">
<Array as="points">
<mxPoint x="520" y="610"/>
<mxPoint x="280" y="610"/>
</Array>
</mxGeometry>
</mxCell>
<mxCell id="7" value="increase character count" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="440" y="520" width="160" height="60" as="geometry"/>
</mxCell>
<mxCell id="14" value="" style="edgeStyle=none;html=1;" edge="1" parent="1" source="8" target="12">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="8" value="initialize character count = 1" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="200" y="520" width="160" height="60" as="geometry"/>
</mxCell>
<mxCell id="13" value="No" style="edgeStyle=none;html=1;" edge="1" parent="1" source="12">
<mxGeometry relative="1" as="geometry">
<mxPoint x="280" y="300" as="targetPoint"/>
<Array as="points">
<mxPoint x="120" y="720"/>
<mxPoint x="120" y="300"/>
</Array>
</mxGeometry>
</mxCell>
<mxCell id="17" value="" style="edgeStyle=none;html=1;" edge="1" parent="1" source="12" target="16">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="12" value="end of string ?" style="rhombus;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="200" y="640" width="160" height="160" as="geometry"/>
</mxCell>
<mxCell id="22" value="" style="edgeStyle=none;html=1;" edge="1" parent="1" source="16" target="19">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="16" value="Print output" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="200" y="850" width="160" height="60" as="geometry"/>
</mxCell>
<mxCell id="20" value="" style="edgeStyle=none;html=1;" edge="1" parent="1" source="18" target="2">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="18" value="Start" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="220" y="100" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="19" value="End" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="220" y="960" width="120" height="60" as="geometry"/>
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>

BIN
max015/T08/deliver/Q2_4.png (Stored with Git LFS) Normal file

Binary file not shown.

View File

@@ -0,0 +1,5 @@
HK RD 2030.0 MMMM
HK SF 2000.0 OOCL
HK SF 2020.0 MMMM
HK RD 2025.0 OOCL
-1

View File

@@ -0,0 +1,5 @@
HK RD 5030.0 MMMM
HK SF 5000.0 OOCL
HK SF 6020.0 MMMM
HK RD 6025.0 OOCL
-1

View File

@@ -0,0 +1,22 @@
files = ['./input-7-1.txt', './input-7-2.txt']
for f in files:
with open(f,'r') as fi:
lowest_rate = {}
lines = fi.readlines()
for l in lines:
if (l != '-1'):
[origin_port, destination_port, shipping_rate, carrier_name] = l.strip().split(' ')
shipping_rate = float(shipping_rate)
if (destination_port in lowest_rate.keys()):
if shipping_rate < lowest_rate[destination_port]['shipping_rate'] :
lowest_rate[destination_port] = {'origin_port': origin_port, 'destination_port': destination_port, 'shipping_rate': shipping_rate, 'carrier_name': carrier_name}
else:
lowest_rate[destination_port] = {'origin_port': origin_port, 'destination_port': destination_port, 'shipping_rate': shipping_rate, 'carrier_name': carrier_name}
print(f)
for v in lowest_rate.values():
print(f"The lowest shipping rate from {v['origin_port']}' to {v['destination_port']} is {v['shipping_rate']}.")
print()

5
max015/T08/input-7-1.txt Normal file
View File

@@ -0,0 +1,5 @@
HK RD 2030.0 MMMM
HK SF 2000.0 OOCL
HK SF 2020.0 MMMM
HK RD 2025.0 OOCL
-1

5
max015/T08/input-7-2.txt Normal file
View File

@@ -0,0 +1,5 @@
HK RD 5030.0 MMMM
HK SF 5000.0 OOCL
HK SF 6020.0 MMMM
HK RD 6025.0 OOCL
-1

22
max015/T08/lowest.py Normal file
View File

@@ -0,0 +1,22 @@
files = ['./input-7-1.txt', './input-7-2.txt']
for f in files:
with open(f,'r') as fi:
lowest_rate = {}
lines = fi.readlines()
for l in lines:
if (l != '-1'):
[origin_port, destination_port, shipping_rate, carrier_name] = l.strip().split(' ')
shipping_rate = float(shipping_rate)
if (destination_port in lowest_rate.keys()):
if shipping_rate < lowest_rate[destination_port]['shipping_rate'] :
lowest_rate[destination_port] = {'origin_port': origin_port, 'destination_port': destination_port, 'shipping_rate': shipping_rate, 'carrier_name': carrier_name}
else:
lowest_rate[destination_port] = {'origin_port': origin_port, 'destination_port': destination_port, 'shipping_rate': shipping_rate, 'carrier_name': carrier_name}
print(f)
for v in lowest_rate.values():
print(f"The lowest shipping rate from {v['origin_port']}' to {v['destination_port']} is {v['shipping_rate']}.")
print()

View File

@@ -0,0 +1,923 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# CDS1001 Tutorial 9"
]
},
{
"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",
"- Understand why openpyxl is used in coding \n",
"- Be able to understand and apply the use of openpyxl to create, read, change, and write excel files automatically"
]
},
{
"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 9 report\n",
"* Complete Parts 1-3 led by the lecturer\n",
"* Complete Part 4 independently\n",
"* Follow Section 3 of the tutorial instruction to save the report and zip the report folder. The zip file is named as CDS1001T9Report{your student_id}.zip (e.g., if student_id is 1234567, then the zip file's name is CDS1001T9Report1234567.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 About openpyxl module"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.1. What is the openpyxl module for? (5 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`openpyxl` is a Python library used to read, write, and modify Excel files (.xlsx). \n",
"It allows manipulation of worksheets, cells, formatting, formulas, charts, and more."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 2 Reading Excel Documents"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.1. Write and execute codes for the following questions 1-8. (24 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 1. How would you obtain a workbook object for an Excel file example.xlsx and store it in a variable ``wb``?"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here:\n",
"\n",
"wb = load_workbook('example.xlsx')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 2. How would you print the number of sheets of ``wb``?"
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here:\n",
"\n",
"print(len(wb.sheetnames))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 3. How would you retrieve the Worksheet object ``sheet2`` for a sheet named 'Sheet2' and print its number of rows?"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here:\n",
"\n",
"sheet2 = wb[\"Sheet2\"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 4. How would you retrieve the Worksheet object ``active_sheet`` for the workbooks active sheet and print its title?"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here:\n",
"\n",
"active_sheet = wb.active\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 5. How would you print the value in the cell C5 of the active_sheet?"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here:\n",
"\n",
"print(ws_active['C5'].value)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 6. How would you print the value of the cell at 2nd row and 3rd column?"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here:\n",
"\n",
"print(ws_results.cell(row=2, column=3).value)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 7. How would you print values of the active_sheet by rows?"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here:\n",
"\n",
"for row in ws_active.iter_rows(min_row=1, max_col=3, max_row=7):\n",
" for cell in row:\n",
" print(cell.value)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 8. How can you retrieve a tuple of all the Cell objects from A1 to C1, and print their values using a for loop?"
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here:\n",
"\n",
"for col in ws_active.iter_cols(min_row=1, max_col=3, max_row=7):\n",
" for cell in col:\n",
" print(cell.value)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.2. Reading Data from a Spreadsheet"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Say you have a spreadsheet of data from the 2010 US Census and you have the boring task of going through its thousands of rows to count ```both the total population and the number of census tracts for each county```. (A census tract is simply a geographic area defined for the purposes of the census.) \n",
"\n",
"Each row represents a single census tract. Well name the spreadsheet file censuspopdata.xlsx, which is available in the folder of the tutorial 9 report. Its contents look like the following figure:\n",
"<img src='fig1.jpg'>\n",
"\n",
"Even though Excel can calculate the sum of multiple selected cells, you'd still have to select the cells for each of the 3,000-plus counties. Even if it takes just a few seconds to calculate a county's population by hand, this would take hours to do for the whole spreadsheet.\n",
"\n",
"You are asked to write a python code that can read from the census spreadsheet file and calculate statistics for each county in a matter of seconds."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Task 1: What is the algorithm to tackle this automation task? What are the data structures needed? How are you going to write the code? (3 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to answer the question above. </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Task 2: Make a small sized excel file for the testing purpose, by copying a few lines from the censuspopdata.xlsx. (2 points)\n",
"\n",
"Rename the small sized excel file as test-2-2.xlsx. Make a screenshot of test-2-2.xlsx, insert the screenshot in the cell below."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to insert the screenshot: </font>\n",
"\n",
"![](./results/2023-11-20_13-03.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Task 3: Follow the steps below to write the code:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Step 1: Read the Spreadsheet Data (5 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There is just one sheet in the censuspopdata.xlsx spreadsheet, named 'Population by Census Tract', and each row holds the data for a single census tract. \n",
"\n",
"The columns are the tract number (A), the state abbreviation (B), the county name (C), and the population of the tract (D).\n",
"\n",
"In the code block below, do the followings:\n",
"- (1) Import openpyxl module;\n",
"- (2) Read file name of the excel file (e.g., censuspopdata.xlsx, test-2-2.xlsx)\n",
"- (3) Create a workbook object for the workbook of the excel file, and store it in variable ``wb_census``\n",
"- (4) Create a sheet object for the sheet 'Population by Census Tract' of the workbook loaded, and it in variable ``sheet_census``\n",
"- (5) print the number of rows in the sheet\n"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for Step 1\n",
"#(1) Import openpyxl module \n",
"import os,sys\n",
"from openpyxl import Workbook, load_workbook\n",
"\n",
"#(2) Read the file name of the excel file from the input (e.g., censuspopdata.xlsx, test-2-2.xlsx),\n",
"#and store it in a string variable filename\n",
"filename = 'censuspopdata.xlsx'\n",
"\n",
"#(3) Create a workbook object wb_census for the workbook of the excel file with the name in filename\n",
"wb_census = load_workbook(filename)\n",
"\n",
"#(4) Create a worksheet object sheet for the active sheet of the workbook\n",
"ws_active = wb_census.active\n",
"\n",
"#(5) print the number of rows in the sheet\n",
"num_rows = ws_active.max_row\n",
"print(f\"Number of rows: {num_rows}\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Step 2: Populate the Data Structure (5 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We now need to create and use a variable named countyData to calculate the statistics of the data. The data structure stored in countyData will be a dictionary with state abbreviations as its keys. Each state abbreviation will map to another dictionary, whose keys are strings of the county names in that state. Each county name will in turn map to a dictionary with just two keys, 'tracts' and 'pop'. These keys map to the number of census tracts and population for the county. For example, the dictionary will look similar to this:\n",
"\n",
" {'AK': {'Aleutians East': {'pop': 3141, 'tracts': 1},\n",
" 'Aleutians West': {'pop': 5561, 'tracts': 2},\n",
" 'Anchorage': {'pop': 291826, 'tracts': 55},\n",
" 'Bethel': {'pop': 17013, 'tracts': 3},\n",
" 'Bristol Bay': {'pop': 997, 'tracts': 1}, \n",
" ... \n",
" \n",
"The countyData dictionarys keys will look like this:\n",
" \n",
" countyData[state abbrev][county]['tracts']\n",
" countyData[state abbrev][county]['pop']\n",
" \n",
"In the code below, do the followings: \n",
"- (1) define the dictionary variable countyData with an empty initial value. \n",
"- (2) write a for loop to traverse the row id from 2, 3, 4, ..., to the last row number (included).\n",
"- (3) during the iteration of the loop: extract data of state, county, and pop for each row.\n",
"- (4) update countyData to compute the total number of census tracts, and the total value of populations.\n",
"- (5) print the list of counties in state AL"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for Step 2\n",
"\n",
"#(1) define the dictionary variable countyData with an empty initial value. \n",
"countyData = { }\n",
"\n",
"#(2) write a for loop to traverse the row id from 2, 3, 4, ..., to the last row number (included) of the sheet.\n",
"last_row = ws_active.max_row\n",
"for row in ws_active.iter_rows(min_row=2, max_col=4, max_row=last_row):\n",
" #(3) during the iteration of the loop: extract data of state, county, and pop for each row.\n",
"\n",
" state = row[1].value\n",
" country = row[2].value\n",
" pop_2010 = row[3].value\n",
" census_tract = row[0].value\n",
"\n",
" #(4) update countyData to compute the total number of census tracts, and the total value of populations.\n",
" if not(state in list(countyData.keys())):\n",
" countyData[state] = {}\n",
" \n",
" if not(country in list(countyData[state].keys())):\n",
" countyData[state][country] = {'pop':0, \"tracts\":0}\n",
"\n",
" countyData[state][country]['pop'] = countyData[state][country]['pop'] + pop_2010\n",
" countyData[state][country]['tracts'] = countyData[state][country]['tracts'] + 1\n",
"\n",
"#(5) print the list of counties in state AL\n",
"print(countyData)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Step 3: Print Results (2 points)\n",
"\n",
"In the code below, write codes to (1) print the total populations of county Autauga of state AL, and (2) print the total number of census tracts of county Union of state AR"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for Step 3\n",
"\n",
"#(1) print the total populations of county Anchorage of state AK:\n",
"print(countyData['AL']['Autauga']['pop'])\n",
"\n",
"#(2) print the total number of census tracts of county Union of state AR\n",
"print(countyData['AL']['Autauga']['tracts'])\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Task 4: Test the above codes by using the small sized excel file first, and then the large sized excel file. (2 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to illustrate the testing results of Step 3 for the large sized excel file, and paste the screenshot of the results. </font>\n",
"\n",
"![](./results/2023-11-20_11-29.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 3 Writing Excel Documents"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 3.1. Write and execute codes for the following questions 1-8, with varibles ``wb`` and ``sheet`` as defined in Task 2.2 for the Excel file example.xlsx . (12 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 1. How would you change the title of the sheet to 'Results'?"
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here?\n",
"\n",
"ws_active.title = \"Results\"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 2. How would you create a new sheet with a title 'New Results' for the workbook?"
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here?\n",
"\n",
"ws1 = wb.create_sheet(\"New Results\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 3. How would you set the value of cell 'A2' in the sheet 'New Results' to 'Forecasting'"
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here?\n",
"\n",
"ws1['A2'] = \"Forecasting\"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 4. How would you save the workbook to the filename new_results.xlsx?"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here?\n",
"\n",
"wb.save('new_results.xlsx')\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to paste the screenshot of the sheet 'New Results' of new_results.xlsx. </font>\n",
"\n",
"\n",
"![](./results/2023-11-20_11-36.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 3.2. Updating a Spreadsheet \n",
"\n",
"In this problem, youll write a program to update cells in a spreadsheet of produce sales. Your program will look through the spreadsheet, find specific kinds of produce, and update their prices. The spreadsheet is produceSales.xlsx located in the folder of tutorial 9 report.\n",
"\n",
"The figure below shows what the spreadsheet looks like.\n",
"<img src='fig2.jpg'></img>\n",
"\n",
"Each row represents an individual sale. The columns are the type of produce sold (A), the cost per pound of that produce (B), the number of pounds sold (C), and the total revenue from the sale (D). The TOTAL column is set to the Excel formula =ROUND(B3\\*C3, 2), which multiplies the cost per pound by the number of pounds sold and rounds the result to the nearest cent. With this formula, the cells in the TOTAL column will automatically update themselves if there is a change in column B or C.\n",
"\n",
"Now imagine that the prices of garlic, celery, and lemons were entered incorrectly, leaving you with the task to write a code to go through thousands of rows in this spreadsheet to update the cost per pound for any garlic, celery, and lemon rows.\n",
"\n",
"The prices that you need to update are as follows:\n",
"\n",
" Celery 1.19\n",
" Garlic 3.07\n",
" Lemon 1.27\n",
" \n",
"You cannot do a simple find-and-replace for the price, because there might be other items with the same price that you do not want to mistakenly \"correct\". For thousands of rows, this would take hours to do by hand. But you can write a program that can accomplish this in seconds."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Task 1: What is the algorithm to tackle this automation task? What are the data structures needed? How are you going to write the code? (3 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to answer the question above. </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Task 2: Make a small sized excel file for the testing purpose, by copying a few lines from the updateProduceSales.xlsx. (2 points)\n",
"\n",
"Rename the small sized excel file as test-3-2.xlsx. Make a screenshot of test-3-2.xlsx, insert the screenshot in the cell below.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to insert the screenshot: </font>\n",
"\n",
"![](./results/2023-11-20_11-48.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Task 3: Follow the steps below to write the code:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Step 1: Read a Workbook and Set Up a Data Structure with the Update Information (6 points)\n",
"\n",
"In the code block below, do the followings:\n",
"- (1) Import openpyxl module;\n",
"- (2) Read file name of the excel file (e.g., produceSales.xlsx, test-3-2.xlsx)\n",
"- (3) Create a workbook object stored in a variable ``wb_update`` by loading the workbook from the excel file;\n",
"- (4) Create a sheet object stored in a variable ``sheet_update`` by assigning it to the active sheet of the workbook loaded;\n",
"- (5) Create a dictionary object stored in a variable PRICE_UPDATES, which maps product type to updated prices\n",
"- (6) print the number of rows and the number of columns in the sheet"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for Step 1:\n",
"# (1) Import openpyxl module;\n",
"from openpyxl import Workbook, load_workbook\n",
"\n",
"# (2) Read file name of the excel file (e.g., produceSales.xlsx, test-3-2.xlsx)\n",
"filename = './test-3-2.xlsx'\n",
"\n",
"# (3) Create a workbook object stored in a variable ``wb_update`` by loading the workbook from the excel file;\n",
"wb_update = load_workbook(filename)\n",
"\n",
"# (4) Create a sheet object stored in a variable ``sheet_update`` by assigning it to the active sheet of the workbook loaded;\n",
"sheet_update = wb_update.active\n",
"\n",
"# (5) Create a dictionary object stored in a variable PRICE_UPDATES, which maps product type to updated prices\n",
"PRICE_UPDATES = {\n",
" \"Celery\": 1.19,\n",
" \"Garlic\": 3.07,\n",
" \"Lemon\": 1.27,\n",
"}\n",
"\n",
"# (6) print the number of rows and the number of columns in the sheet\n",
"last_row = sheet_update.max_row\n",
"num_cols = sheet_update.max_column\n",
"print(last_row)\n",
"print(num_cols)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Step 2: Check All Rows and Update Incorrect Prices (2 points)\n",
"\n",
"The next part of the program will loop through all the rows in the spreadsheet:\n",
"\n",
"(1) write a for loop to traverse the row id from 2, 3, 4, ..., to the last row number (included).\n",
"(2) during each iteration of the loop, update the cost per unit if needed, according to PRICE_UPDATES.\n"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for Step 2:\n",
"#(1) write a for loop to traverse the row id from 2, 3, 4, ..., \n",
"# to the last row number (included).\n",
"for row in sheet_update.iter_rows(min_row=2, max_col=num_cols, max_row=last_row):\n",
" \n",
" #(2) during each iteration of the loop, \n",
" # update the cost per unit if needed, \n",
" # according to PRICE_UPDATES.\n",
" p_type = row[0].value\n",
" if(p_type in PRICE_UPDATES.keys()):\n",
" row[3].value = PRICE_UPDATES[p_type]['price']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Step 3: Write the updated Workbook to a new Excel File (1 point)\n",
"Write the updated workbook to a new excel file named \"updatedProduceSales.xlsx\""
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for Step 3:\n",
"#Write the updated workbook to a new excel file named \"updatedProduceSales.xlsx\"\n",
"wb_update.save('updatedProduceSales.xlsx')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Task 4: Test the above codes by using the small sized excel file first, and then the large sized excel file. (2 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to illustrate the testing results of Step 3 for the large sized excel file, and paste the screenshot of the results. </font>\n",
"\n",
"![](./results/2023-11-20_12-25.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 4 Manipulating Excel Documents"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 4.1. Write and execute codes for the following questions 1-8: (24 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 1. Write a code below to obtain a workbook object for \"sales.xlsx\" and store it in a variable ``wb_sales``, obtain a worksheet object for Sheet 'Sheet1' of the workbook and store it in a variable ``sheet_sales``, print the number of rows and columns of the sheet."
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for question above:\n",
"\n",
"import os,sys\n",
"from openpyxl import Workbook, load_workbook\n",
"from pprint import pprint\n",
"\n",
"wb_sales = load_workbook('sales.xlsx')\n",
"sheet_sales = wb_sales[\"Sheet1\"]\n",
"last_row = sheet_sales.max_row\n",
"num_cols = sheet_sales.max_column\n",
"print(last_row)\n",
"print(num_cols)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 2. How do you set a formula in cell B14 to sum up the values of cells from B2 to B13?"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for question above:\n",
"sheet_sales['B14'].value = \"=SUM(B2:B13)\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 3. How would you set the height of the first row to 50, and the width of the first column to 20?"
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for question above:\n",
"\n",
"sheet_sales.row_dimensions[1].height = 50\n",
"sheet_sales.column_dimensions[\"A\"].width = 20"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 4. How would you change the font size and the text color of cell 'A1' to 20 and to red, respectively?"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for question above:\n",
"#sheet_sales.row_dimensions[1].font = openpyxl.styles.Font(size = 20, color='FF0000')\n",
"\n",
"sheet_sales['A1'].font = openpyxl.styles.Font(size = 20, color='FF0000')\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 5. How would you freeze the first row"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for question above:\n",
"\n",
"sheet_sales.freeze_panes = 'A2'\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 6. How to create a bar chart for the 12-month sales?"
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for question above:\n",
"\n",
"chart = BarChart()\n",
"chart.title = \"12-Month Sales\"\n",
"chart.x_axis.title = \"Month\"\n",
"chart.y_axis.title = \"Sales\"\n",
"\n",
"data = Reference(sheet_sales, min_col=1, min_row=2, max_row=13, max_col=1)\n",
"categories = Reference(sheet_sales, min_col=2, min_row=1, max_row=1)\n",
"\n",
"chart.add_data(data, titles_from_data=True)\n",
"chart.set_categories(categories)\n",
"\n",
"sheet_sales.add_chart(chart, \"D2\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 7. How to save the updated workbook to a new excel file named 'new_sales.xlsx':"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for question above:\n",
"\n",
"wb_sales.save('new_sales.xlsx')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 8. Open new_sales.xlsx, take a screenshot of the sheet, and insert it in the excel below:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to insert a screenshot of 'new_sales.xlsx' </font>\n",
"\n",
"![](./results/2023-11-20_12-45.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.9.7"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

View File

@@ -0,0 +1,798 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# CDS1001 Tutorial 9"
]
},
{
"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",
"- Understand why openpyxl is used in coding \n",
"- Be able to understand and apply the use of openpyxl to create, read, change, and write excel files automatically"
]
},
{
"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 9 report\n",
"* Complete Parts 1-3 led by the lecturer\n",
"* Complete Part 4 independently\n",
"* Follow Section 3 of the tutorial instruction to save the report and zip the report folder. The zip file is named as CDS1001T9Report{your student_id}.zip (e.g., if student_id is 1234567, then the zip file's name is CDS1001T9Report1234567.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 About openpyxl module"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 1.1. What is the openpyxl module for? (5 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to answer the question above: </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 2 Reading Excel Documents"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.1. Write and execute codes for the following questions 1-8. (24 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 1. How would you obtain a workbook object for an Excel file example.xlsx and store it in a variable ``wb``?"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 2. How would you print the number of sheets of ``wb``?"
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 3. How would you retrieve the Worksheet object ``sheet2`` for a sheet named 'Sheet2' and print its number of rows?"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 4. How would you retrieve the Worksheet object ``active_sheet`` for the workbooks active sheet and print its title?"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 5. How would you print the value in the cell C5 of the active_sheet?"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 6. How would you print the value of the cell at 2nd row and 3rd column?"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 7. How would you print values of the active_sheet by rows?"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 8. How can you retrieve a tuple of all the Cell objects from A1 to C1, and print their values using a for loop?"
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2.2. Reading Data from a Spreadsheet"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Say you have a spreadsheet of data from the 2010 US Census and you have the boring task of going through its thousands of rows to count ```both the total population and the number of census tracts for each county```. (A census tract is simply a geographic area defined for the purposes of the census.) \n",
"\n",
"Each row represents a single census tract. Well name the spreadsheet file censuspopdata.xlsx, which is available in the folder of the tutorial 9 report. Its contents look like the following figure:\n",
"<img src='fig1.jpg'>\n",
"\n",
"Even though Excel can calculate the sum of multiple selected cells, you'd still have to select the cells for each of the 3,000-plus counties. Even if it takes just a few seconds to calculate a county's population by hand, this would take hours to do for the whole spreadsheet.\n",
"\n",
"You are asked to write a python code that can read from the census spreadsheet file and calculate statistics for each county in a matter of seconds."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Task 1: What is the algorithm to tackle this automation task? What are the data structures needed? How are you going to write the code? (3 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to answer the question above. </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Task 2: Make a small sized excel file for the testing purpose, by copying a few lines from the censuspopdata.xlsx. (2 points)\n",
"\n",
"Rename the small sized excel file as test-2-2.xlsx. Make a screenshot of test-2-2.xlsx, insert the screenshot in the cell below."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to insert the screenshot: </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Task 3: Follow the steps below to write the code:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Step 1: Read the Spreadsheet Data (5 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There is just one sheet in the censuspopdata.xlsx spreadsheet, named 'Population by Census Tract', and each row holds the data for a single census tract. \n",
"\n",
"The columns are the tract number (A), the state abbreviation (B), the county name (C), and the population of the tract (D).\n",
"\n",
"In the code block below, do the followings:\n",
"- (1) Import openpyxl module;\n",
"- (2) Read file name of the excel file (e.g., censuspopdata.xlsx, test-2-2.xlsx)\n",
"- (3) Create a workbook object for the workbook of the excel file, and store it in variable ``wb_census``\n",
"- (4) Create a sheet object for the sheet 'Population by Census Tract' of the workbook loaded, and it in variable ``sheet_census``\n",
"- (5) print the number of rows in the sheet\n"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for Step 1\n",
"#(1) Import openpyxl module \n",
"\n",
"#(2) Read the file name of the excel file from the input (e.g., censuspopdata.xlsx, test-2-2.xlsx),\n",
"#and store it in a string variable filename\n",
"\n",
"#(3) Create a workbook object wb_census for the workbook of the excel file with the name in filename\n",
"\n",
"#(4) Create a worksheet object sheet for the active sheet of the workbook\n",
"\n",
"#(5) print the number of rows in the sheet\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Step 2: Populate the Data Structure (5 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We now need to create and use a variable named countyData to calculate the statistics of the data. The data structure stored in countyData will be a dictionary with state abbreviations as its keys. Each state abbreviation will map to another dictionary, whose keys are strings of the county names in that state. Each county name will in turn map to a dictionary with just two keys, 'tracts' and 'pop'. These keys map to the number of census tracts and population for the county. For example, the dictionary will look similar to this:\n",
"\n",
" {'AK': {'Aleutians East': {'pop': 3141, 'tracts': 1},\n",
" 'Aleutians West': {'pop': 5561, 'tracts': 2},\n",
" 'Anchorage': {'pop': 291826, 'tracts': 55},\n",
" 'Bethel': {'pop': 17013, 'tracts': 3},\n",
" 'Bristol Bay': {'pop': 997, 'tracts': 1}, \n",
" ... \n",
" \n",
"The countyData dictionarys keys will look like this:\n",
" \n",
" countyData[state abbrev][county]['tracts']\n",
" countyData[state abbrev][county]['pop']\n",
" \n",
"In the code below, do the followings: \n",
"- (1) define the dictionary variable countyData with an empty initial value. \n",
"- (2) write a for loop to traverse the row id from 2, 3, 4, ..., to the last row number (included).\n",
"- (3) during the iteration of the loop: extract data of state, county, and pop for each row.\n",
"- (4) update countyData to compute the total number of census tracts, and the total value of populations.\n",
"- (5) print the list of counties in state AL"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for Step 2\n",
"\n",
"#(1) define the dictionary variable countyData with an empty initial value. \n",
"\n",
"#(2) write a for loop to traverse the row id from 2, 3, 4, ..., to the last row number (included) of the sheet.\n",
"#(3) during the iteration of the loop: extract data of state, county, and pop for each row.\n",
"#(4) update countyData to compute the total number of census tracts, and the total value of populations.\n",
"\n",
"#(5) print the list of counties in state AL\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Step 3: Print Results (2 points)\n",
"\n",
"In the code below, write codes to (1) print the total populations of county Autauga of state AL, and (2) print the total number of census tracts of county Union of state AR"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for Step 3\n",
"\n",
"#(1) print the total populations of county Anchorage of state AK:\n",
"\n",
"#(2) print the total number of census tracts of county Union of state AR\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Task 4: Test the above codes by using the small sized excel file first, and then the large sized excel file. (2 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to illustrate the testing results of Step 3 for the large sized excel file, and paste the screenshot of the results. </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 3 Writing Excel Documents"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 3.1. Write and execute codes for the following questions 1-8, with varibles ``wb`` and ``sheet`` as defined in Task 2.2 for the Excel file example.xlsx . (12 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 1. How would you change the title of the sheet to 'Results'?"
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 2. How would you create a new sheet with a title 'New Results' for the workbook?"
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 3. How would you set the value of cell 'A2' in the sheet 'New Results' to 'Forecasting'"
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 4. How would you save the workbook to the filename new_results.xlsx?"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {},
"outputs": [],
"source": [
"#Write your code here?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to paste the screenshot of the sheet 'New Results' of new_results.xlsx. </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 3.2. Updating a Spreadsheet \n",
"\n",
"In this problem, youll write a program to update cells in a spreadsheet of produce sales. Your program will look through the spreadsheet, find specific kinds of produce, and update their prices. The spreadsheet is produceSales.xlsx located in the folder of tutorial 9 report.\n",
"\n",
"The figure below shows what the spreadsheet looks like.\n",
"<img src='fig2.jpg'></img>\n",
"\n",
"Each row represents an individual sale. The columns are the type of produce sold (A), the cost per pound of that produce (B), the number of pounds sold (C), and the total revenue from the sale (D). The TOTAL column is set to the Excel formula =ROUND(B3\\*C3, 2), which multiplies the cost per pound by the number of pounds sold and rounds the result to the nearest cent. With this formula, the cells in the TOTAL column will automatically update themselves if there is a change in column B or C.\n",
"\n",
"Now imagine that the prices of garlic, celery, and lemons were entered incorrectly, leaving you with the task to write a code to go through thousands of rows in this spreadsheet to update the cost per pound for any garlic, celery, and lemon rows.\n",
"\n",
"The prices that you need to update are as follows:\n",
"\n",
" Celery 1.19\n",
" Garlic 3.07\n",
" Lemon 1.27\n",
" \n",
"You cannot do a simple find-and-replace for the price, because there might be other items with the same price that you do not want to mistakenly \"correct\". For thousands of rows, this would take hours to do by hand. But you can write a program that can accomplish this in seconds."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Task 1: What is the algorithm to tackle this automation task? What are the data structures needed? How are you going to write the code? (3 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to answer the question above. </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Task 2: Make a small sized excel file for the testing purpose, by copying a few lines from the updateProduceSales.xlsx. (2 points)\n",
"\n",
"Rename the small sized excel file as test-3-2.xlsx. Make a screenshot of test-3-2.xlsx, insert the screenshot in the cell below."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to insert the screenshot: </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Task 3: Follow the steps below to write the code:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Step 1: Read a Workbook and Set Up a Data Structure with the Update Information (6 points)\n",
"\n",
"In the code block below, do the followings:\n",
"- (1) Import openpyxl module;\n",
"- (2) Read file name of the excel file (e.g., produceSales.xlsx, test-3-2.xlsx)\n",
"- (3) Create a workbook object stored in a variable ``wb_update`` by loading the workbook from the excel file;\n",
"- (4) Create a sheet object stored in a variable ``sheet_update`` by assigning it to the active sheet of the workbook loaded;\n",
"- (5) Create a dictionary object stored in a variable PRICE_UPDATES, which maps product type to updated prices\n",
"- (6) print the number of rows and the number of columns in the sheet"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for Step 1:\n",
"# (1) Import openpyxl module;\n",
"\n",
"# (2) Read file name of the excel file (e.g., produceSales.xlsx, test-3-2.xlsx)\n",
"\n",
"# (3) Create a workbook object stored in a variable ``wb_update`` by loading the workbook from the excel file;\n",
"\n",
"# (4) Create a sheet object stored in a variable ``sheet_update`` by assigning it to the active sheet of the workbook loaded;\n",
"\n",
"# (5) Create a dictionary object stored in a variable PRICE_UPDATES, which maps product type to updated prices\n",
"\n",
"# (6) print the number of rows and the number of columns in the sheet\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Step 2: Check All Rows and Update Incorrect Prices (2 points)\n",
"\n",
"The next part of the program will loop through all the rows in the spreadsheet:\n",
"\n",
"(1) write a for loop to traverse the row id from 2, 3, 4, ..., to the last row number (included).\n",
"(2) during each iteration of the loop, update the cost per unit if needed, according to PRICE_UPDATES.\n"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for Step 2:\n",
"#(1) write a for loop to traverse the row id from 2, 3, 4, ..., to the last row number (included).\n",
"#(2) during each iteration of the loop, update the cost per unit if needed, according to PRICE_UPDATES."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Step 3: Write the updated Workbook to a new Excel File (1 point)\n",
"Write the updated workbook to a new excel file named \"updatedProduceSales.xlsx\""
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for Step 3:\n",
"#Write the updated workbook to a new excel file named \"updatedProduceSales.xlsx\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Task 4: Test the above codes by using the small sized excel file first, and then the large sized excel file. (2 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to illustrate the testing results of Step 3 for the large sized excel file, and paste the screenshot of the results. </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Part 4 Manipulating Excel Documents"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 4.1. Write and execute codes for the following questions 1-8: (24 points)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 1. Write a code below to obtain a workbook object for \"sales.xlsx\" and store it in a variable ``wb_sales``, obtain a worksheet object for Sheet 'Sheet1' of the workbook and store it in a variable ``sheet_sales``, print the number of rows and columns of the sheet."
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for question above:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 2. How do you set a formula in cell B14 to sum up the values of cells from B2 to B13?"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for question above:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 3. How would you set the height of the first row to 50, and the width of the first column to 20?"
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for question above:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 4. How would you change the font size and the text color of cell 'A1' to 20 and to red, respectively?"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for question above:\n",
"#sheet_sales.row_dimensions[1].font = openpyxl.styles.Font(size = 20, color='FF0000')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 5. How would you freeze the first row"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for question above:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 6. How to create a bar chart for the 12-month sales?"
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for question above:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 7. How to save the updated workbook to a new excel file named 'new_sales.xlsx':"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [],
"source": [
"#Edit this cell for question above:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 8. Open new_sales.xlsx, take a screenshot of the sheet, and insert it in the excel below:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Edit this cell to insert a screenshot of 'new_sales.xlsx' </font>"
]
}
],
"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
}

12
max015/T09/Pipfile Normal file
View File

@@ -0,0 +1,12 @@
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"
[packages]
openpyxl = "*"
[dev-packages]
[requires]
python_version = "3.11"

37
max015/T09/Pipfile.lock generated Normal file
View File

@@ -0,0 +1,37 @@
{
"_meta": {
"hash": {
"sha256": "fee46db20e17976fbc5868b14bf7011ae33f211b27363a110baf97e84018750f"
},
"pipfile-spec": 6,
"requires": {
"python_version": "3.11"
},
"sources": [
{
"name": "pypi",
"url": "https://pypi.org/simple",
"verify_ssl": true
}
]
},
"default": {
"et-xmlfile": {
"hashes": [
"sha256:8eb9e2bc2f8c97e37a2dc85a09ecdcdec9d8a396530a6d5a33b30b9a92da0c5c",
"sha256:a2ba85d1d6a74ef63837eed693bcb89c3f752169b0e3e7ae5b16ca5e1b3deada"
],
"markers": "python_version >= '3.6'",
"version": "==1.1.0"
},
"openpyxl": {
"hashes": [
"sha256:a6f5977418eff3b2d5500d54d9db50c8277a368436f4e4f8ddb1be3422870184",
"sha256:f91456ead12ab3c6c2e9491cf33ba6d08357d802192379bb482f1033ade496f5"
],
"index": "pypi",
"version": "==3.1.2"
}
},
"develop": {}
}

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More