CSCI Final Cheat Sheet
CSCI Final Cheat Sheet
CSCI Final Cheat Sheet
Notes:
They are all case-sensitive
Cannot start with a number
Cannot contain special characters (like, $)
Cannot be keywords used in Python (like def , class , break , many more)
Order of Operations:
The acronym PEMDAS is a useful way to remember the rules:
Parentheses ( ) have the highest precedence and can be used to force an expression to
evaluate in the order you want.
Exponents ** has the next highest precedence
Multiplication * and Division / have higher precedence than...
Addition + and Subtraction -
Operators with the same precedence are evaluated from left to right
list.sort() : Sorts (i.e., modies the orders of elements in) the list based on the regular
number/string comparisons, revser=True (descending order)
list.copy() : Creates and returns a (shallow) copy of the list
zip() takes 2 or more lists (and other iterables ) and returns paired elements (of tuples)
with those lists.
nums = [1, 2, 3, 4, 5]
words = ["hi", "bye", "hello", "sayonara", "what?"]
for z in zip(nums, words):
print(z)
Slicing Lists:
Drawing Rectangle:
width = int(input("Enter the width: "))
height = int(input("Enter the height: "))
print()
# for each line:
for line in range(0, height):
# draw * NUM_STARS_IN_LINE times
for star in range(0, width):
if line == 0 or line == height -1 or star == 0 or star == width
-1:
print("*", end="") # don't let it go to the next line just yet!
else :
print(" ", end="") # don't let it go to the next line just yet!
print() #insert newline at the end of each line
Code:
width = int(input("Enter the width: "))
height = int(input("Enter the height: "))
print()
# for each line:
for line in range(0, height):
# draw * NUM_STARS_IN_LINE times
for star in range(0, width):
if line == 0 or line == height -1 or star == 0 or star == width -1:
print("*", end="") # don't let it go to the next line just yet!
else :
print(" ", end="") # don't let it go to the next line just yet!
print() #insert newline at the end of each line
Isoceles triangle:
num_lines = int(input("What size do you want to have? "))
ch = input("What character do you want to use? ")
# for each line:
for line in range(1, num_lines+1):
# print a space, (num_lines - line) times
for sp in range(1, (num_lines - line) + 1): # +1 because upper-end exclusive
print(" ", end="") # don't let it go to the next line just yet!
# draw ch (line*2 -1) times
for star in range(1, (line * 2 -1) + 1): # +1 because upper-end exclusive
print(ch, end="") # don't let it go to the next line just yet!
print() #insert newline at the end of each line
Strings:
String methods:
replace(old, new) : Returns a copy of the string with ALL occurrences of the substring
old replaced by the string new.
replace(old, new, count) : Same as above, except it only replaces the rst count
occurrences of old.
find(x, start= 0,end=len(string)) : Returns the index of the rst occurrence of item x in the
string, the search index beginning at index start and stops the search at index==end - 1
. It returns -1 x is no found in the string.
rfind(x, start= 0,end=len(string)) : Same as nd(x) but searches the string in reverse,
returning the last occurrence in the string
between indices [start, end).
count(x, start= 0,end=len(string)) : Returns the number of times x occurs in the string
between [start (default 0):end (len)).
Methods that return a True or False (i.e., Boolean value):
isalnum() -- Returns True if all characters in the string are lowercase or uppercase
letters, or numbers 0-9.
isdigit() -- Returns True if all characters are numbers 0-9.
islower() -- Returns True if all (cased) characters are lowercase letters.
isupper() -- Returns True if all (cased) characters are uppercase letters.
isspace() -- Returns True if all characters are whitespace.
startswith(x) -- Returns True if the string starts with x.
endswith(x) -- Returns True if the string ends with x.
In addition to catching exceptions that may or may not occur, you can also raise
exceptions when you think it's appropriate.
e.g.)
valid_value = False
while not valid_value:
try:
value = input("Type YES or NO: ")
valid_value = value == "YES" or value == "NO"
if not valid_value:
raise ValueError("It wasn't a valid answer! Try again!")
except ValueError as e:
print(e)
Write code to read a string and print each character backward.
This can be done in many different ways!
def get_first_words(paragraphs):
first_words = []
for paragraph in paragraphs:
if paragraph.strip(): # Check if the paragraph is not empty
first_word = paragraph.split()[0]
first_words.append(first_word)
return first_words
Read the lines back from the output above (which contains two numbers each line
separated by a comma). Create a list of tuples, i.e.,
a list of tuples ( num , num_sq ).
f = open(PATH + OUT_FILE_NAME, "r") #read only
lines = f.readlines() #read them into a list of lines
combos = list()
for line in lines:
values = line.split(sep=",") #split into a list
combo = int(values[0].strip()), int(values[1].strip())
combos.append(combo)
Write 2 functions:
1. one is to ask for non-negative oating number values until a negative number is
entered and returns these non-negative numbers as
a list
2. the other method is to receive a list of numbers, asks for the name of an output le,
and writes those numbers and their cubed
values, each pair (the original number and the cubed) on each line in the output le.
def write_numbers(nums):
file_name = input("Enter the output file name: ")
with open(PATH + file_name, "w") as f:
for num in nums:
f.write(f"{num}, {num**3}\n")
# to run the program
nums = get_numbers()
write_numbers(nums)
def __str__(self):
"""
Overloaded function that returns the string representation of
the instance
of Student class
"""
return f"{self.name} ({self.a_num}):" + \
f"grade = {self.grade} (Letter: {self.get_letter_grade()})"
(Sample code)
PATH = "drive/MyDrive/Colab
Notebooks/CSCI1227/lecture_notes/wk09_File_IO_and_exception_hand
ling/"
FILE_NAME = "random_integers.txt"
nums = list()
f = open(PATH + FILE_NAME)
texts = f.readlines()
for text in texts:
try: #just in case there's some garbage vaues
num = int(text) #try to conver
nums.append(num)
except:
pass #just ignore junk
f.close()
Dictionary:
names = ["Yumi", "Joe", "Satoru", "Yasushi"]
letters = ["A+", "B-", "C+", "F"]
grades ={key:value for key, value in zip(names,letters)}
grades["Yumi"] # will return "A+"
grades["Joe"] # will return "B-"
grades["Yasushi"] # will return "F”
searches key:
def get_airport_code(city):
code = "not found"
for key in canadian_airports:
if city in canadian_airports[key]:
code = key
return code
city = input("Type a name of your city: ")
print(f"Airport code for {city} is {get_airport_code(city)}.")
def print_menu(target_dict):
print(f"{'keys':^20s}:{'values':^30s}")
print("-" * 51)
for key in target_dict:
print(f"{key:20s}:{str(person[key]):30s}")
def modify_value(target_dict, key):
print(f"\n\nCurrent value for {key} is {target_dict[key]}\n")
new_value = input(f"Enter a new value for {key}: ")
target_dict[key] = new_value
print_menu(person)
key_found = True
while key_found:
key = input("\nSelect a key to modify: ")
if key in person:
modify_value(person, key)
print("\n\nUpdated dictionary:")
print_menu(person)
else:
key_found = False
Dictionary Methods:
Random module:
A bunch of functions that are used to generate (pseudo-)random numbers and select
thing(s) (pseudo-)randomly
random() : Returns a random oat number between 0 and 1
randrange(start, stop, step) : Returns a random number between the given range
randint() : Returns a random number between the given range
randint(start,stop) is the same as randrange(start,stop+1)
choice() : Returns a random element from the given sequence
choices() : Returns a list with a random selection from the given sequence
random.sample(sequence, k) : Creates a list of random numbers of the size k
Numpy Module:
Import numpy as np
Np.array([1,2,3,4,5])
# 1D to 2D
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(4, 3)
print(newarr)
Matplotlib
mport random
import numpy as np
import matplotlib.pyplot as plt
################
# Plot (lines)
################
# Define coefficients for the quadratic function
a = random.choice(range(-8,9,2))
b = random.choice(range(-8,9,2))
c = random.choice(range(-8,9,2))
d = random.choice(range(-8,9,2))
# Generate sample data points
xpoints = np.array(range(-10, 11))
ypoints = np.array([a*x**3 + b*x**2 + c*x + d for x in xpoints])
plt.plot(xpoints, ypoints) # "smoothed" lines
plt.title(f"y = ({a})x**3 + ({b})x**2 + ({c})x + ({d})")
plt.show()
plt.plot(xpoints, ypoints, 'x') #plots with x
plt.show()
# just to show the sample coords
points = [(x,y) for x, y in zip(xpoints, ypoints)]
print(points)
################
# Scatter plot
################
xpoints = np.array(random.sample(range(100),k=20)) #create 20
random samples
ypoints = np.array(random.sample(range(100),k=20))
plt.scatter(xpoints, ypoints) #scatter plot
plt.show()
# just to show the sample coords
points = [(x,y) for x, y in zip(xpoints, ypoints)]
print(points)
################
# Bar chart
################
# np.arange([start, ] stop, [step, ]) creates an array of
numbers that are evenly spaced
xpoints = np.arange(0,8,0.2)
ypoints = np.array(random.sample(range(100),k=len(xpoints)))
# plot
plt.bar(xpoints, ypoints, edgecolor="white", width=0.2)
plt.show()
CSV:
# you need to mount it first, need to run only once
from google.colab import drive
drive.mount('/content/drive')
import csv
PATH = "drive/MyDrive/Colab
Notebooks/CSCI1227/lecture_notes/wk12_popular_python_modules/"
FILE_NAME = "world_population.csv"
with open(PATH+FILE_NAME) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=",") #returns an
iterator object of lists
countries = list()
population = list()
first_row = True
for row in csv_reader:
countries.append(row[2])
if first_row: #header, don't convert to int
population.append(row[5])
first_row = False
else:
population.append(int(row[5]))
# You can of course convert the data to numpy ndarrays etc. if
you want!
# now plot the data!
import matplotlib.pyplot as plt
# showing only the 1st 35 countries, and dropping the header row
plt.bar(countries[1:35], population[1:35])
plt.title("World Population")
plt.xlabel(countries[0])
plt.ylabel(population[0])
plt.xticks(rotation=90)
plt.show()