Public synchronized int incContador (int val)
1
# Hw *8
addition = float(input(“Enter the annual addition of public residential land (in sq land):”))
years = 0
current_total = initial_total
while current_total < target_total:
years += 1
private_residential = private_residential*1.03
public_residential = public_residential + addition
current_total = private_residential + public_residential + rurual_settlement
print(f”It will take at least {years} year(s) for the residential land in Hong Kong to double in size.”)
#cw 9
def pv_annuity(c,r,n):
s = 0
for i in range (1, n+1):
s += c/(1+r)**i
return round (s,2)
###** for i in range (1, n+1) = repeat sth a certain number of times
## i goes up by 1 each time and stop before hitting the end number
## why + 1? Cux python read from 0
## Hw 9
def caesar(message, shift) :
encrypted = “”
message = message.Upper()
for char in message:
if char.Isalpha():
encrypted += chr((ord(char)-ord(‘A’)+shift)%26 + ord(‘A’))
else:
encrypted += char
## Outout is Upper case, so no need to differeniate upper or lower at the beginning
## ord: change the alphabic to number
## chr: chnage the number to alphabic , cuz computer dont know how to skip alphabic, only know how to skip number
## /26 cuz what if the alphabic comes to an end, the computer dk, so this function helps us to skip to the front to encrypt
##cw 10
def fib(n):
if n in [1,2]:
return 1
else:
return fib(n-1) + fib(n-2)
## This part = the 3rd term plus the second term
## aka the sum of the two numbers in the font
##[fib(i) for i range(1,16)] ## It will stop a the 15th term
## hw 10
def scalar_mult(c,tp):
return c*tp[0],c*tp[1]
## cw11
class Employee: ##WHAT CLASS MEANS
def __init__(self,first,last): ## WHAT INIT MEANS
self.First = first
self.Last = last
def initial (self):
return self.First[0]+self.Last[0]
def number_letter (self):
return len(self.First)+len(self.Last)
##HW 11 ** supper(). – Avoids explicity naming, ensure order of parent class
class CEO:
def __init__(self,first,last,salary,term):
Employee. __init__ (slef,first,last)
self.Salary = salary
self.Term = term
def pv_salary(self):
r= 0.005
n = self.Term
PMT = self.Salary
pv = PMT*(1-(1+r)**(-n))/r
pv_rounded = round(pv)
return f”The present value of {self.First}{self.Last}’s {self.Term}months of salaries is ${pv_rounded}.”
## ** list comprehension vs set comprehension
## list comprehension : {x**2 for x in range(-3,3)} # It is a for loop and it counts untill 2
## set comprehension : list2 = [f(x) for x in list1]
## Difference: List Have repeat numbers + acoording to order but Set wont
# set comprehension have few ways of combining
# 1. Union = combine two sets tgt , no repeat
# 2. Intersection = Take numbers that both sets have
# 3. Difference = LOok at and consider only set 1, remove things that are repetitive
# 4. Symmetric Difference = combine two sets tgt, Remove their common points
# Here is an example
with open (“school.Txt”,’r’) as infile: #= open txt file and turn the lines into sets and but in set 1 # Then make set2
set1 = set(infile)
#Option A/B/C
set1.Union(set2)
set1.Intersection(set2)
set1 – set2
with open (“school.Txt”,’r’) as outfile:
outfile.Writelines(set1.Union(set2))
##What does this code mean ?
##It means that it made txt to read to data and use set to combine to two sets and save as new txt
## CSV file
## What if the file has serval data in column ?
## we first split the column
“CityU was found in 1984.”.Split() #split in space
“Hey, how is it going?”.Split(‘,’) #split in comma
ratio = round(int(x[1])/int(x[2]))
#WHat is x[1] x[2] ?
# x = [ HKU, 2874, 2877 ]
# x[1] = 2874 , x[2] = 2877
# int makes it turn from string to integer , cux the numbers read in the file are string
# AFter split, We need to join back the two , It is just the opposite of split
” “.Join([‘CityU’,’was’,’founded’,’in’,’1984.’])
#HW12
with open (“people.Txt”,”r”) as infile:
initials = set () #We use set to remove duplicated initials
for line in infile: # = Look ath the file line by line
first,last = line.
strip().Split()
initials.Add(first[0]+last[0])
with open (“initial.Txt”,’w’) as outfile:
for initial in sorted (initials): #Give them alphabatic order
outfile.Write(initial+”\n”) #\n = skip a line , wo \n the file becomes AHAW but not line by line
rate = float(input(“Enter a target MONTHLY rate of return (without the % sign):”))
number = float(input (“Enter the number of months:”))
futureValue = round(1000*((1+rate)**number -1)/rate)
print(“With a monthly contribution of $1000, your MPF will worth $” + str(futureValue) + “after 5 months.”) #Need to add str to combine numbers (data with strings for printin orlogging )
#** Add it when need to print number and words
r= float(input(“Enter a target MONTHLY rate of return (without the % sign):”))
m = float(input(“Enter the number of months:”))
presentValue = round(1000*(1-(1+r)**-m)/r)
print(“The total MPF of $5000 in 5 months is worth $” + str(presentValue) + “today.”)
ref=”ABCDEFGHIJKLMNOPQRSTUVWXYZ”
word=input(“Enter a 3-letter airport code:”).Strip().Upper()
shift=int(input(“Shifts?”)) # int : Make the number we enter as a number not a text , cuz we need to use that number
Letter0 = ref[(ref.Find(word[0])+ shift)%26] #Find the remainder
Letter1 = ref[(ref.Find(word[1])+ shift)%26]
Letter2 = ref[(ref.Find(word[2])+ shift)%26]
print(f”{word} is encrypted to {Letter0}{Letter1}{Letter2}.”) # if have f , we dont need to use + , + to connect everything
ref=”ABCDEFGHIJKLMNOPQRSTUVWXYZ”
word=input(“Enter a 3-letter airport code:”).Strip().Upper()
shift=(input(“Enter a 3-letter key:”)).Strip().Upper()
ref=”ABCDEFGHIJKLMNOPQRSTUVWXYZ”
word=input(“Enter a 3-letter airport code:”).Strip().Upper()
shift=(input(“Enter a 3-letter key:”)).Strip().Upper()
ref=”ABCDEFGHIJKLMNOPQRSTUVWXYZ”
order0= ref[(ref.Find(shift[0])
order1= ref[(ref.Find(shift[1])
order2= ref[(ref.Find(shift[2])
letter0= ref[(ref.Find(word[0]) + order0)%26]
letter1= ref[(ref.Find(word[1]) + order1)%26]
letter2= ref[(ref.Find(word[2]) + order2)%26]
print(f”{word} is encrypted to {letter0}{letter1}{letter2}.”)
paragraph = input(“Enter a random paragraph:”).Strip() #strip() removes extra spaces from the begining and end of your input , to avoid miscount
num1 = paragraph.Count(“.”)+paragraph.Count(“?”)+paragraph.Count(“!”)
num2 = len(paragraph.Split()) #num2 = paragraph.Count(” “)+1 #split=cut the paragraph into pieces #len=count how many items are in the loist
print(f”This paragraph has {num1} sentence(s).{num2} words in total.”)
userInput=input(“Enter 4 numbers separated by comma(a,b,c,d):”)
matrix=userInput.Split(“,”) #split(“,”) cuts at every comma #separate each alphba
a=float(matrix[0].Strip())#float=2>2.0 #strip()=remove extra spaces #matrix[0]=gets first item”2″
b=float(matrix[1].Strip()) #ie a=2
c=float(matrix[2].Strip())
d=float(matrix[3].Strip())
jcal=a*d-b*c
ans=[[d/cal,-b/cal],[-c/cal,a/cal]] #follow the equation
year=int(input(“Enter a year:”))
if year % 4 == 0 :
if year %100 == 0 and year %400! = 0: #divisiable by 100 but not 400 #!= not equal to
print(f”Year{year} is not a leap year.”)
else:
print(f”Year{year} is a leap year.”)
else:
print(f”Year{year} is not a leap year.”) #ones that are not dvisiable by 4
input(“\nPress ENTER to exit.”) #\n = new line # This line is for user the end the program
num1 = int(input(“Enter the first number:”))
num2 = int(input(“Enter the second number:”))
num3 = int(input(“Enter the third number:”))
if num1 >= num2 and num1 >= num3:
if num2 >= num3: #1 largest
#FOR LOOP
#wrong #only handles one future payment
year=int(input(“Enter the number of years:”))
presentValue=(1000/(1.05)**year)
print(f”The present value is $”presentValue”.”)
#Correct #handles multiple future payments (an annuity)
year=int(input(“Enter the number of years:”))
pV = 0 #Think of pV as an empty bank where we will add the value of each year’s payment
for i in range (n): #This starts a loop #starts from 0
pV += 1000/1.05**(i+1) #(i+1) is becuz the loop starts at 0 but the first payment is in 1 year
print(f”the present value is ${round(pV)}.”)
#What is a loop?
#A loop is telling the computer “Do this same task over and over again untill i tell u to stop
year=int(input(“Enter the number of years:”))
pV=0
for i in range(n):
B = 1000 + (i//5)*10 #Figure ot how much you get paid this year (ie start at $1000, everyyear you get a tiny raise, after 5 years uour raise totals $10
pV += B/1.05**(i+1)
print(f”The present value is ${round(pV)}.”)
#WHILE LOOP
target=float(input(“Enter the target balance:”))
fV=0 #RN = 0
n=0
while fV < target : #Means keep doing it as long as my bank is less than my goal
fV += 1000*1.05**n
n += 1 #count the year
print(f”It will take {n} year(s) to reach $[round(target)}.”)
# For LOOP vs While LOOP
# For LOOP : Use when you know how many times to repeat (ie how many years )
# While LOOP : Use when you know when to stop repeating (ie when the fV reaches a certain level )
# eg I’ll eat five cookies vs I’ll eat until I’m full
# int vs float
# int : whole numbers (no decimal point )
# float : numbers with decimals
