Show Menu
Cheatography

Cosc121 Cheat Sheet (DRAFT) by

Cosc121 cosc 121 cosc 121

This is a draft cheat sheet. It is a work in progress and is not finished yet.

plot_s­qua­red() - NumPy + Matplotlib Plotting

 
import numpy as np
import matplo­tli­b.p­yplot as plt

def plot_s­qua­red(n, x0, x1):
xs = np.lin­spa­ce(x0, x1, n)
ys = xs * xs
plt.pl­ot(xs, ys)
plt.ti­tle­("y = x * x")
plt.xl­abe­l("x­")
plt.yl­abe­l("y­")
plt.gr­id(­True)
plt.show()

afunct­ion() - Nested While Loops

 
def afunct­ion­(va­lue1, value2):
op1 = 0
while op1 < value1:
op2 = value1
while op2 > value2:
result = op1 * op2
print(­f"{o­p1:3} × {op2:3} = {resul­t:3­}")
op2 -= 1
op1 += 1
 

File Max Finder

 
'ye'
def main():
'ye'
filename = input(­"­Fil­ename? ")
with open(f­ile­name, "­r") as file:
max_int = None
for line in file:
line = int(line)
if max_int == None or line > max_int:
max_int = line
print(­f"La­rgest number found: {max_i­nt}­")
main()

Files

 
def case_f­ixe­r(i­npu­t_name, output­_name):
"­ye"
with open(i­npu­t_name, 'r') as infile, open(o­utp­ut_­name, 'w') as outfile:
for line in infile:
cleane­d_line = line.s­tri­p().lo­wer()
outfil­e.w­rit­e(c­lea­ned­_line + '\n')

line.s­trip() # Remove leadin­g/t­railing whitespace
line.s­plit() # Split into list of words
line.s­pli­t(',') # Split by comma
d.lower(), .upper(), .title() # Case transforms

outputs

 
def trongo(x):
print(­len(x))
s = set(x)
y = {'fo', 'to', 'fun'}
if len(s.i­nt­ers­ect­ion(y)) == 1:
s = s.union(y)
print(­", ".jo­in(­sor­ted­(li­st(­s))))

# Example usage:
trongo­(['fo', 'fi', 'hasan', 'fi', 'hasan'])
# Output:
# 5
# fi, fo, fun, hasan, to
 

Student Class 1

 
class Student:
def __init­__(­self, studen­t_id, usercode, first_­name, family­_name):
self.s­tud­ent_id = int(st­ude­nt_id)
self.u­sercode = str(us­ercode)
self.f­irs­t_name = str(fi­rst­_name)
self.f­ami­ly_name = str(fa­mil­y_name)
self.c­ourses = set()

def __str_­_(s­elf):
return f"{s­elf.st­ude­nt_id} {self.f­am­ily­_na­me.u­pp­er()}, {self.f­ir­st_­nam­e.c­api­tal­ize­()}­"

def get_em­ail­_ad­dre­ss(­self):
return f"{s­elf.us­erc­ode­}@u­cli­ve.a­c.n­z"

Dicts

def invert­ed_­wor­d_c­oun­ts(­wor­d_c­oun­t_d­ict):
"­ye"
inverted = {}
for word, word_count in word_c­oun­t_d­ict.it­ems():
if word_count in inverted:
invert­ed[­wor­d_c­oun­t].a­pp­end­(word)
else:
invert­ed[­wor­d_c­ount] = [word]
for words in invert­ed.v­al­ues():
words.s­ort()
return inverted


def find_k­ey(­inp­ut_­dict, value):
"­ye"
for key, val in input_­dic­t.i­tems():
if val == value:
return key
return None

Bar Graph

 
import numpy as np
import matplo­tli­b.p­yplot as plt

def main():
rainfalls = np.loa­dtx­t('­lak­eta­ylo­rst­ati­on2­005.txt', delimi­ter­=',', skipro­ws=9, usecols=3)
days = np.ara­nge(1, len(ra­inf­alls) + 1)
axes = plt.axes()
axes.b­ar(­days, rainfalls)
axes.s­et_­tit­le(­"Lake Taylor Station Rainfalls, 2005")
axes.s­et_­xla­bel­("Day number­")
axes.s­et_­yla­bel­("Ra­infall (mm)")
axes.g­rid­(True)
plt.show()

main()
 

Student Class 2

 
def enrol_­cou­rse­(self, course):
self.c­our­ses.ad­d(c­ourse)

def is_enr­oll­ed_­in(­self, course):
return course in self.c­ourses

def main():
astudent = Studen­t(1­234567, "­ffn­127­", "­first NAMES", "­Family name")
print(­typ­e(a­stu­dent))
print(­ast­udent)
astude­nt.e­nr­ol_­cou­rse­("CO­SC1­21")
print(­ast­ude­nt.i­s_­enr­oll­ed_­in(­"­COS­C12­1"))
print(­ast­ude­nt.i­s_­enr­oll­ed_­in(­"­COS­C12­2"))
print(­ast­ude­nt.g­et­_em­ail­_ad­dre­ss())

main()

dict

 
def freque­nci­es(­inp­ut_­str):
"­ye"
count_dict = {}
for char in input_str:
if char in count_­dict:
count_­dic­t[char] += 1
else:
count_­dic­t[char] = 1
return count_dict

Classes

 
class Whatsit:
def __init­__(­self, grade, name, health):
allowed = {'Soog­let', 'Throve', 'Plagu­elet'}
if grade not in allowed:
raise ValueE­rro­r('­Invalid Whatsit grade')
self.grade = grade
self.name = name
self.h­ealth = max(fl­oat­(he­alth), 0)

def __str_­_(s­elf):
return f"{s­elf.name} ({self.gr­ade}), health = {self.h­ea­lth­:.1­f}"

def damage­(self, amount):
self.h­ealth = max(se­lf.h­ealth - amount, 0)