W1 TO W7 TUTORIAL UNCOMMENTED
# w2q1a #
n = 4 + 5 * 3.2 - 2
print(n)
# w2q1b #
n = (10**2) / 4.25 + 7.5 * 2
print(n)
# w2q1c #
n = 6 / (2 * (1 + 2))
print(n)
# w2q2 #
Y = 36
F = 30
more_ex = max(Y, F)
result = (more_ex * 1.1) * 1.09
print(round(result, 2))
print(round(result / 2, 2))
# w2q3 #
budget = 3000
t_shirts = 0
first_20_price = 12.50
next_50_price = 11.75
next_100_price = 10.45
next_200_price = 9.35
thereafter_price = 8.90
first_20_max = min(20, budget // first_20_price)
t_shirts += int(first_20_max)
budget -= first_20_max * first_20_price
next_50_max = min(50, budget // next_50_price)
t_shirts += int(next_50_max)
budget -= next_50_max * next_50_price
next_100_max = min(100, budget // next_100_price)
t_shirts += int(next_100_max)
budget -= next_100_max * next_100_price
next_200_max = min(200, budget // next_200_price)
t_shirts += int(next_200_max)
budget -= next_200_max * next_200_price
thereafter_max = budget // thereafter_price
t_shirts += int(thereafter_max)
print("Total T-shirts class can print:", t_shirts)
# w2q3b #
budget = 3000
t_shirts = 0
gst = 1.09
first_20_price = 12.50 * gst
next_50_price = 11.75 * gst
next_100_price = 10.45 * gst
next_200_price = 9.35 * gst
thereafter_price = 8.90 * gst
first_20_max = min(20, budget // first_20_price)
t_shirts += int(first_20_max)
budget -= first_20_max * first_20_price
next_50_max = min(50, budget // next_50_price)
t_shirts += int(next_50_max)
budget -= next_50_max * next_50_price
next_100_max = min(100, budget // next_100_price)
t_shirts += int(next_100_max)
budget -= next_100_max * next_100_price
next_200_max = min(200, budget // next_200_price)
t_shirts += int(next_200_max)
budget -= next_200_max * next_200_price
thereafter_max = budget // thereafter_price
t_shirts += int(thereafter_max)
print("Total T-shirts class can print:", t_shirts)
# w2q4 #
area_of_normal = (3.14*6*6)/3
area_of_promo = (3.14*8*8)/4
price_of_normal = 6/area_of_normal
price_of_promo = 8/area_of_promo
print(price_of_normal)
print(price_of_promo)
# w3q1a #
testimony = "\"He's owing me $10 dollars each year for every
$100 dollars he borrowed for the past year,\" said witness
PW-1."
testimony = [Link]("$100", "hundred")
testimony = [Link]("$10", "ten")
print(testimony)
# w3q1b #
full_testimony = "THE WITNESS' TESTIMONY IN COURT ON 1 APRIL
2022:\n\n" + testimony
print(full_testimony)
# w3q2a #
case = "RecordTV Pte Ltd v MediaCorp TV Singapore Pte Ltd,
[2010] SgCA 43 (Singapore Court of Appeal)"
casename_end = [Link](",")
casename = case[:casename_end]
print(casename)
citation_end = [Link]("(")
citation = case[casename_end +2:citation_end]
print(citation)
court_end = [Link](")")
court = case[citation_end +1:court_end]
print(court)
print("Use this citation", citation, "for", casename, ",
decided by the ", court, "? Enter Y/N:")
# w3q2e #
case = "Sony Corp. of America v. Universal City Studios, Inc.,
464 U.S. 417 (1984)"
court_end = [Link](")")
court_start = [Link]("(")
court = case[court_start:court_end+1]
print(court)
casename_end = [Link](",", 0, court_start)
casename = case[:casename_end]
print(casename)
citation_end = [Link]("(")
citation = case[casename_end+1:citation_end]
print(citation)
# w4q1 #
angle_1 = 50
angle_2 = 40
if angle_1 <= 0 or angle_2 <= 0 or angle_1+angle_2 >= 180:
print("undefined")
if angle_1 == 60 and angle_2 == 60:
print("equilateral")
else:
print("not equilateral")
if angle_1 == angle_2 or (180 - angle_1 == angle_2) or (180 -
angle_2 == angle_1):
print("isoceles")
else:
print("not isoceles")
if angle_1 > 90 or angle_2 > 90 or angle_1+angle_2 < 90:
print("obtuse")
else:
print("not obtuse")
if angle_1 == 90 or angle_2 == 90 or (angle_1 == 45 and
angle_2 == 45):
print("right angle & isoceles")
else:
print("not right angle & isoceles")
if (angle_1 == 90 or angle_2 == 90 or (angle_1 + angle_2 ==
90)) and angle_1 != angle_2:
print("right angle")
else:
print("not right angle")
angle_1 = 60
angle_2 = 90
if angle_1 <= 0 or angle_2 <= 0 or angle_1+angle_2 >= 180:
print("undefined")
elif angle_1 == 60 and angle_2 == 60:
print("equilateral")
elif (angle_1 > 90 or angle_2 > 90 or angle_1+angle_2 < 90)
and (angle_1 == angle_2 or (180 - angle_1 == angle_2) or (180
- angle_2 == angle_1)):
print("obtuse & isoceles")
elif (angle_1 < 90 or angle_2 < 90 or angle_1+angle_2 > 90)
and (angle_1 == angle_2 or (180 - angle_1 == angle_2) or (180
- angle_2 == angle_1)):
print("acute & isoceles")
elif angle_1 == 90 or angle_2 == 90 or (angle_1 == 45 and
angle_2 == 45):
print("right angle & isoceles")
elif (angle_1 == 90 or angle_2 == 90 or (angle_1 + angle_2 ==
90)) and angle_1 != angle_2:
print("right angle")
elif angle_1 > 90 or angle_2 > 90 or angle_1+angle_2 < 90:
print("obtuse")
elif angle_1 < 90 or angle_2 < 90 or angle_1+angle_2 > 90:
print("acute")
else:
print("unknown")
# w4q3 #
n = 15
for i in range(1, n+1):
if i % 3 == 0 and i % 5 == 0:
print("TickTock")
elif i % 3 == 0:
print("Tick")
elif i % 5 == 0:
print("Tock")
else:
print(i)
# w5q1a #
for i in range(5, 0, -1):
print(i)
# w5q1b #
for i in range(14, -2, -3):
print(i)
# w5q1c #
for i in range(1, 6):
print(i**2)
# w5q1d #
for i in range(3, -3, -1):
print(2**i)
# w5q1e #
for i in range(2,4):
for j in range(1,5):
print(i*j)
# w5q2 #
n = 5
while n > 0:
print(n)
n -= 1
n = 14
while n > -2:
print(n)
n -= 3
n = 1
while n < 6:
print(n**2)
n += 1
n = 3
while n > -3:
print(2**n)
n -= 1
i = 2
j = 1
while i < 4:
while j < 5:
print(i*j)
j += 1
i += 1
j = 1
i = 2
j = 1
while i < 4:
while j < 5:
print(i * j)
j += 1
i += 1
j = 1
# w5q3 #
total = 0
for n in range(1,6):
print(n*111)
total += n*111
print(total)
total = 0
for n in range(1,6):
print(str(5)*n)
total += int(str(5)*n)
print(total)
total = 0
for n in range(9, 0, -1):
print(str(n)*n)
total += int(str(n)*n)
print(total)
i = 1
total = 0
for r in range(1,10):
if r <= 5:
n = int(str(i)*r)
else:
n = int(str(i)*(10-r))
print(n)
total += n
i += 1
print(total)
# w5q4 #
list_1 = ["q1021766", "q1537522", "q1563573", "q1075655"]
list_2 = ["q1100979", "q1286097"]
list_dropped = ["q1563573", "q1075655"]
for item in list_dropped:
if item in list_1:
list_1.remove(item)
print(list_1+list_2)
total_no = len(list_1+list_2)
print(total_no)
list_1 = ["q1021766", "q1537522", "q1563573", "q1075655"]
list_2 = ["q1100979", "q1286097"]
list_dropped = ["q1563573", "q1075655"]
for item in list_dropped:
if item in list_1:
list_1.remove(item)
current_list = sorted(list_1+list_2)
for i, item in enumerate(current_list, 1): #
enumerate(current_list, 1) to start the enumeration at 1
instead of 0
print(i, item)
# w6q1b #
contact_info = {}
while True:
expert_name = input("What is the expert's name").title()
if expert_name == "":
break
expert_number = input("What is the expert's number?")
contact_info[expert_name] = expert_number
print(contact_info)
# w6q1c #
print("Contact information:")
for name, phone in contact_info.items(): # .items() is only
used for dictionaries, NOT lists
print(f"{name} - {phone}")
# w6q1d #
contact_info = {
"Able": "1234567890",
"Bob": "0987654321",
"Cass": "5555555555",
"Dow": "9999999999",
"Ed": "1111111111",
"Fed": "2222222222"
}
while True:
expert_name = input("What is the expert's name?").title()
if expert_name == "":
break
if expert_name in contact_info:
print(f"[{expert_name}] -
[{contact_info[expert_name]}]")
# w6q1e #
contact_info = {
"Able": "1234567890",
"Bob": "0987654321",
"Cass": "5555555555",
"Dow": "9999999999",
"Ed": "1111111111",
"Fed": "2222222222"
}
while True:
name = input("Name of expert to delete: ").title()
if name == "":
break
if name in contact_info:
print(f"{name} – {contact_info[name]} has been deleted
from the dictionary")
del contact_info[name]
else:
print(f"{name} does not exist in the dictionary")
# w6q1f # method 1 - use list of dictionaries
contact_info = []
i = 0
while True:
name = input(f"Enter name of expert {i+1} (or press Enter
to finish): ").title()
if name == "":
break
phone = input(f"Enter phone number of expert {i+1}: ")
email = input(f"Enter email of expert {i+1}: ").lower()
contact_info.append({
'name': name,
'phone': phone,
'email': email
})
i += 1
for expert in contact_info: # dont need to use .items() if
selecting specific item like expert['phone']
print(f"{expert['name']} - {expert['phone']} -
{expert['email']}")
# w6q1f # extra method 1 - deleting list of dictionaries
contact_info = [
{"name": "Able", "phone": "1234567890", "email":
"able@gmail"},
{"name": "Bob", "phone": "0987654321", "email":
"bob@gmail"},
{"name": "Cass", "phone": "5555555555", "email":
"cass@gmail"},
{"name": "Dow", "phone": "9999999999", "email":
"dow@gmail"},
{"name": "Ed", "phone": "1111111111", "email":
"ed@gmail"},
{"name": "Fed", "phone": "2222222222", "email":
"fed@gmail"}
]
while True:
name = input("Enter name to delete (or press Enter to
finish): ").title()
if name == "":
break
for expert in contact_info:
if expert["name"] == name:
print(f"{name}'s information has been deleted.")
contact_info.remove(expert)
break
else:
print(f"{name} does not exist in the contact info.")
for expert in contact_info: # dont need to use .items() if
selecting specific item like expert['phone']
print(f"{expert['name']} - {expert['phone']} -
{expert['email']}")
# w6q1f # method 2 - use nested lists
contact_info = []
i = 0
while True:
name = input(f"Enter name of expert {i+1} (or press Enter
to finish): ").title()
if name == "":
break
phone = input(f"Enter phone number of expert {i+1}: ")
email = input(f"Enter email of expert {i+1}: ").lower()
contact_info.append([name, phone, email])
i += 1
for expert in contact_info: # dont need to use .items() as it
is a list
print(f"{expert[0]} - {expert[1]} - {expert[2]}")
# w6q1f # extra method 2 - deleting nested lists
contact_info = [
["Able", "1234567890", "able@gmail"],
["Bob", "0987654321", "bob@gmail"],
["Cass", "5555555555", "cass@gmail"],
["Dow", "9999999999", "dow@gmail"],
["Ed", "1111111111", "ed@gmail"],
["Fed", "2222222222", "fed@gmail"]
]
while True:
name = input("Enter name to delete (or press Enter to
finish): ").title()
if name == "":
break
for expert in contact_info: # dont need to use .items() as
it is a list
if expert[0] == name: # Check if the name matches
print(f"{name} - {expert[1]} - {expert[2]} has
been deleted from the list.")
contact_info.remove(expert) # Remove the nested
list
break
else:
print(f"{name} does not exist in the list.")
for expert in contact_info:
print(f"{expert[0]} – {expert[1]} – {expert[2]}")
# w6q1f # method 3 - half dictionary half lists
contact_info = {}
i = 0
while True:
expert_name = input(f"Enter name of expert {i+1} (or press
Enter to finish): ").title()
if expert_name == "":
break
expert_number = input(f"Enter phone number of expert
{i+1}: ")
expert_email = input(f"Enter email of expert {i+1}:
").lower()
contact_info[expert_name] = [expert_number, expert_email]
i += 1
for expert in contact_info:
print(f"{expert} – {contact_info[expert][0]} –
{contact_info[expert][1]}")
# w6q1f # extra method 3 - deleting half dictionary half lists
contact_info = [
{"Able": ["1234567890", "able@gmail"]},
{"Bob": ["0987654321", "bob@gmail"]},
{"Cass": ["5555555555", "cass@gmail"]},
{"Dow": ["9999999999", "dow@gmail"]},
{"Ed": ["1111111111", "ed@gmail"]},
{"Fed": ["2222222222", "fed@gmail"]}
]
while True:
name = input("Enter name to delete (or press Enter to
finish): ").title()
if name == "":
break
for expert in contact_info:
if name in expert: # Check if the name exists as a
key
contact_details = expert[name]
print(f"{name} - {contact_details[0]} -
{contact_details[1]} has been deleted from the list.")
contact_info.remove(expert) # Remove the
dictionary containing the name
break
else:
print(f"{name} does not exist in the list.")
for expert in contact_info:
print(f"{expert} – {contact_info[expert][0]} –
{contact_info[expert][1]}")
# w6q2a #
ids = ["S8822311H", "G8556864G", "T9722439Q", "S7248859D"]
anon_ids = [id[-4:]for id in ids]
anon_ids.sort()
for id in anon_ids:
print(id, end=" ")
# w6q2b #
postal_codes = [781234, 805384, 794258, 739938]
anon_code = [str(code)[:2] for code in postal_codes]
anon_code.sort()
for code in anon_code:
print(code, end=" ")
# w6q3a # - method 1
sentence = input("Enter a sentence: ").lower()
punctuation = "—~!@#$%^&*()_+`-=[]}{\|:'\"“”;/.,<>?1234567890"
translation_table = [Link](punctuation, " " *
len(punctuation))
clean_text = [Link](translation_table)
tokens = []
for token in clean_text:
[Link](token)
tokens = "".join(tokens).split()
print(tokens)
# w6q3b # - method 1
sentence = input("Enter a sentence: ").lower()
punctuation = "—~!@#$%^&*()_+`-=[]}{\\|:'\"“”;/.,<>?
1234567890"
translation_table = [Link](punctuation, " " *
len(punctuation))
clean_text = [Link](translation_table)
tokens = clean_text.split()
token_count = {}
for token in tokens:
if token:
if token not in token_count:
token_count[token] = 1
else:
token_count[token] += 1
for token, count in token_count.items():
print(f"{token}: {count}")
# w6q3b # - method 2
sentence = input("Enter a sentence: ").lower()
punctuation = "—~!@#$%^&*()_+`-=[]}{\|:'\"“”;/.,<>?1234567890"
translation_table = [Link](punctuation, " " *
len(punctuation))
clean_text = [Link](translation_table)
tokens = clean_text.split()
token_count = {token: [Link](token) for token in
set(tokens)}
for token, count in token_count.items():
print(f"{token}: {count}")
# w6q3b # - method 3 - does not use set()
sentence = input("Enter a sentence: ").lower()
punctuation = "—~!@#$%^&*()_+`-=[]}{\|:'\"“”;/.,<>?1234567890"
translation_table = [Link](punctuation, " " *
len(punctuation))
clean_text = [Link](translation_table)
tokens = clean_text.split()
token_count = {}
for token in tokens:
if token not in token_count:
token_count[token] = [Link](token)
for token, count in token_count.items():
print(f"{token}: {count}")
# w6q3b # - EXTRA - finding numbers in sentence
def is_number(s): # function to check if word is number
try:
float(s)
return True
except ValueError:
return False
sentence = input("Enter a sentence: ").lower()
punctuation = "—~!@#$%^&*()_+`-=[]}{\|:'\"“”;/.,<>?"
translation_table = [Link](punctuation, " " *
len(punctuation))
clean_text = [Link](translation_table)
words = clean_text.split()
numbers = [word for word in words if is_number(word)] # Find
all numbers in the sentence
number_count = {}
for number in numbers:
if number not in number_count:
number_count[number] = number_count.get(number, 0) + 1
# alternative: number_count[number] = [Link](number)
if number_count:
print("\nNumbers found and their counts:")
for number, count in number_count.items():
print(f"{number}: {count}")
else:
print("No numbers found in the sentence.")
# w7q1 #
def calculate_tshirts_with_gst(budget):
gst = 1.09
price_tiers = [
(20, 12.50 * gst),
(50, 11.75 * gst),
(100, 10.45 * gst),
(200, 9.35 * gst),
(float('inf'), 8.90 * gst)
]
total_shirts = 0
total_cost = 0
for i, (quantity, price) in enumerate(price_tiers):
if i == len(price_tiers) - 1:
remaining_budget = budget - total_cost
shirts_in_tier = int(remaining_budget / price)
else:
shirts_in_tier = min(quantity, int((budget -
total_cost) / price))
total_shirts += shirts_in_tier
total_cost += shirts_in_tier * price
if total_cost >= budget:
break
return total_shirts
budget = 3000
num_tshirts = calculate_tshirts_with_gst(budget)
print(f"\nThe class could print {num_tshirts} T-shirts with a
budget of ${budget} including 9% GST.")
# w7q2a #
def c2f(celsius):
farenheit = 9/5 * celsius + 32
if farenheit <= -459.67:
return None
return farenheit
def f2c(farenheit):
celsius = (farenheit - 32) * 5/9
if celsius <= -273.15:
return None
return celsius
# w7q2a #
temp = input("Enter temperature (e.g., 100C or 212F): ")
if temp[-1].upper() == "F":
try:
farenheit_value = float(temp[:-1])
print(f"{farenheit_value}F is {f2c(farenheit_value)}
C")
except ValueError:
print("Invalid input. Please enter a valid number.")
elif temp[-1].upper() == "C":
try:
celsius_value = float(temp[:-1])
print(f"{celsius_value}C is {c2f(celsius_value)}F")
except ValueError:
print("Invalid input. Please enter a valid number.")
else:
print("Error: Indicate C or F at the end of the
temperature.")
# w7q3a #
def litres_to_gallons(litre):
gallon = litre / 3.78541
return gallon
# w7q3b #
def km_to_miles(km):
mile = km / 1.60934
return mile
# w7q3c #
cars_fuel_economy = {"Car A": 8.7, "Car B": 10.5, "Car C":
11.5}
for car, liters_per_100km in cars_fuel_economy.items():
# .items() is only used for dictionaries, NOT lists
mpg = km_to_miles(100) /
litres_to_gallons(liters_per_100km)
cars_fuel_economy[car] = mpg
cars_mpg = cars_fuel_economy
print(cars_mpg)
# w7q3d #
for car, mpg in cars_mpg.items():
if mpg >= 23:
print(f"{car}: {mpg:.2f}mpg")
# W5 Graded Coding Exercise #
instruction = input("Enter instruction: clientname, UEN,
patent_application_no, next_succeeding_year")
sections = [Link](",") # alternatively,
use .replace(" ", "") to remove all whitespaces instead
of .strip() below
if len(sections) == 4:
client_name, uen, patent_application_no,
next_succeeding_year = [[Link]() for section in
sections]
if next_succeeding_year.isdigit() and
int(next_succeeding_year) > 4:
print("")
else:
print("Can't process! Next succeeding year must be a
number greater than 4.")
else:
print("Can't process! Your instruction is not in the
correct format!")
next_succeeding_year = int(next_succeeding_year)
total_renewal_fee = 0
if next_succeeding_year > 4:
if next_succeeding_year <= 7:
total_renewal_fee = (next_succeeding_year - 4) * 165
elif next_succeeding_year <= 10:
total_renewal_fee = 3 * 165 + (next_succeeding_year -
7) * 430
elif next_succeeding_year <= 13:
total_renewal_fee = 3 * 165 + 3 * 430 +
(next_succeeding_year - 10) * 600
elif next_succeeding_year <= 16:
total_renewal_fee = 3 * 165 + 3 * 430 + 3 * 600 +
(next_succeeding_year - 13) * 775
elif next_succeeding_year <= 19:
total_renewal_fee = 3 * 165 + 3 * 430 + 3 * 600 + 3 *
775 + (next_succeeding_year - 16) * 945
elif next_succeeding_year == 20:
total_renewal_fee = 3 * 165 + 3 * 430 + 3 * 600 + 3 *
775 + 3 * 945 + 1120
else:
total_renewal_fee = 3 * 165 + 3 * 430 + 3 * 600 + 3 *
775 + 3 * 945 + 1120 + (next_succeeding_year - 20) * 1380
print(f"Dear counsel for {client_name} ({uen}):\nPlease
confirm by 15 Sep 2024 that your patent
{patent_application_no} is due to be renewed to year
{next_succeeding_year}, for a total cost of S$
{total_renewal_fee:.2f}.")