CSCI Final Cheat Sheet

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

CSCI – 1227

a//b- integer division, the value is rounded down to nearest integer.

Variable names in Python:


Python variable names can be made up of
upper- and lower-case letters,
digits (0–9), and
underscores (_).
Identiers are unlimited in length.
Variables

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

Logical Operators in Python:


and : Returns True if both condtions are true
or : Returns True if at least one of the statements is true
not : Reverses the result (e.g., returns False if the result is True )

Exercise: Write a calculator program with a menu.


Sample output:
Enter the 1st number: 2.5
Enter the 2nd number: 3.2
Menu
match and case (Python v.3.10 and above)
a) Addition
b) Subtraction
c) Multiplication
d) Division
Select your choice (a, b, c, or d): c
The result is 8.0.
Code (with match ):
num_1 = float(input("Enter the 1st number: "))
num_2 = float(input("Enter the 2nd number: "))
print("\nMenu")
print(" a) Addition")
print(" b) Subtraction")
print(" c) Multiplication")
print(" d) Division")
print("\n")
choice = input("Select your choice (a, b, c, or d): ")
match choice:
case 'a':
result = num_1 + num_2
case 'b':
result = num_1 - num_2
case 'c':
result = num_1 * num_2
case 'd':
result = num_1 / num_2
case _:
result = "invalid"
print(f"The result is {result}.")

There are 3 types of containers in Python:


1. list
2. tuple
3. dict (dictionaries)
<list> + <list> : concatenation, * : repeats n times

Append: adds in end of list, extend: adds lists

list.insert(<index>, <item>) : Inserts an item into list before position at index

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:

print(a) # will print the entire list


print(a[:5]) # will print the 1st 5 elements (indices from 0 to 4)
print(a[::2]) # will print every 2 elements starting from 0 (default, omitted) to the last
element (default
print(a[5:]) # will print from the 6th element (ind = 5) to the last
print(a[2::2]) # will print every 2 elements from the 3rd element, going to the last or 2nd
last depending
print(a[::-1]) #printing them backward

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

Drawing X inside square;

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:

print(f"{a:,d}") #decimal with commas


print(f"{a:010d}") #with leading zeros to fill 10 digits
print(f"{a:015d}") #with leading zeros to fill 15 digits
print(f"{a:f}") #floating point
print(f"{a:015f}") #floating point with leading/trailing zeros to fill 15 digits
print(f"{a:015.2f}") #floating point with leading zeros with 2 decimal points to fill 15 digits
print(f"{a:.2f}") #floating point with no leading zeros with 2 decimal points
print(f"{a:,.2f}") #floating point with no leading zeros with 2 decimal points with commas

print(f"{name:20s}",f"{name:10s}","and more...") #allocate 20 symbols, allocate 10


symbols
print(f"{name:>20s}",f"{name:>10s}","and more...") #allocate 20 symbols, allocate 10
symbols, with RIGHT al
print(f"{name:^20s}",f"{name:^10s}","and more...") #allocate 20 symbols, allocate 10
symbols, with CENTRE a
a = 400
print(f"{a:<10.2f}") #floating point with 2 decimal points, left aligned (default)
print(f"{a:>10.2f}") #floating point with 2 decimal points, right aligned
print(f"{a:^10.2f}") #floating point with 2 decimal points, centre aligned

Create a nicely formatted table to print out the following lists:


names = ["John", "Paul", "George", "Richard"]
years_born = [1940, 1942, 1943, 1940]
net_worth = [800000000, 1200000000, 400000000, 400000000]
Expected output:
Name |Born |Net worth
----------+----------+--------------------
John | 1940|$ 800,000,000.00
Paul | 1942|$ 1,200,000,000.00
George | 1943|$ 400,000,000.00
Richard | 1940|$ 400,000,000.00
names = ["John", "Paul", "George", "Richard"]
years_born = [1940, 1942, 1943, 1940]
net_worth = [800000000, 1200000000, 400000000, 400000000]
print(f"{'Name':<10s}|{'Born':<10s}|{'Net worth':<20s}")
print( ('-' * 10) + '+' + ('-' * 10) + '+' + ('-' * 20))
for i in range(len(names)):
print(f"{names[i]:<10s}|{years_born[i]:>10d}|${net_worth[i]:>18,.2f}")

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.

Methods to create new strings:


capitalize() -- Returns a copy of the string with the rst character capitalized and the rest
lowercased.
lower() -- Returns a copy of the string with all characters lowercased.
upper() -- Returns a copy of the string with all characters uppercased.
strip() -- Returns a copy of the string with leading and trailing whitespace removed (but
not the inner whitespaces).
title() -- Returns a copy of the string as a title, with rst letters of words capitalized.

eroDivisionError : Divide by zero error


ValueError : Invalid value (Ex: Input mismatch)
TypeError : An operation or function is applied to an object of inappropriate type
IndexError : Index is out of bounds.

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!

sentence = input("Enter something: ")


print(sentence[::-1]) # method 1
for i in range(len(sentence)-1,-1,-1): # method 2
print(sentence[i],end="")
print()
for symbol in sentence[::-1]: # method 3
print(symbol,end="")
print()

def count_words(paragraphs, word):


count = 0
for paragraph in paragraphs:
# Convert both paragraph and word to lowercase for case-insensitive comparison
if word.lower() in paragraph.lower().split():
count += paragraph.lower().split().count(word.lower())
return count

def count_paras(paragraphs, word):


count = 0
for paragraph in paragraphs:
# Convert both paragraph and word to lowercase for case-insensitive comparison
if word.lower() in paragraph.lower():
count += 1
return count

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

open(file, mode='r', buffering=-1, encoding=None, errors=None,


newline=None, closefd=True, opener=None)
'r': open for reading (default): will not allow writing (thus it's the safest to protect the le
from accidental modications)
'w': open for writing, truncating the le rst
'a': open for writing, appending to the end of le if it exists

write() function only takes string.

Writelines()- writes lists of texts


file.flush() #this will force flush the buffered text into the
drive
file.close() #close() function automatically flushes it before
closing the file
If you want to retain the original content of the le but also want to add new contents, you
should use 'a' (append) option.
e.g.)
#first add a line ('w') option
file = open(PATH + FILE_NAME, 'w')
file.write("This is the 1st line.\n")
file.close()
#open it again with 'a' option
file = open(PATH + FILE_NAME, 'a')
for i in range(100):
file.write(str(i) + "\n")
file.close()
If you open a le with a 'w' or 'a' option and try to read the content, it will fail.

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()

print(contents[0]) #print the first string in the list


print(contents[0][0:100]) #print the first 100 characters of the
first string in the list
print(contents[2][0:100:2]) #print every 2 characters of the
first 100 characters of the second string in the list
print("the" in contents[0]) #print if the string "the" appears
in the first string in the list
print(contents[0].count("the"))#print how many times the string
"the" appears in the first string in the list
print(len(contents[0])) # print how many characters in the first
string in the list
new_para = contents[0].replace("the","THE").replace("The",
"THE") #returns a new string with both the and The replaced with
THE
print(new_para)

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)}.")

deleting in dictionary: using keys


del grades["Yasushi"] #deleting the pair with the key "Yasushi"
del grades["Satoru"] #deleting the pair with the key "Satoru"
del grades["whoever"] #KeyError, the specified key doesn't exist
in the dictionary

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:

1. In and not in operation


Grades={“yumi”:…}
Print(“yumi” in grades) #true
2. Clear() : empties dictionary
3. get(key, default) : Returns the value for the key if it exists, but returns default if it
doesn't exist
4. update(another_dict) : Merges it with another dictionary. If another dictionary has
keys that already exist in the calling dictionary, the values in the 1st dictionary will
be overwritten
5. pop(key, default) : Removes and returns the value for the key. If the key does not
exist in the dictionary, it returns default

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])

array.shape : shows the number of elements in each dimension (as a tuple)

# 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)

indices = np.where((a==3) | (a==5)) # or


print(indices)
print(a[indices])
indices = np.where((a>1) & (a<6)) # and
print(indices)
print(a[indices])
z = np.zeros((2,3,4)) # we need () to enclose the shape as the
1st arg
print(z)
ones = np.ones((2,3,4)) # we need () to enclose the shape as the
1st arg
print(ones)
fruits = np.array(["apple", "banana", "orange", "grape",
"strawberry",
"watermelon", "kiwi", "pineapple", "blueberry", "peach",
"pear", "mango", "cherry", "plum", "raspberry"])
print(fruits)
print(np.sort(fruits)) #sort in ascending order
print(np.flip(np.sort(fruits))) #np.flip() reverses the order

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()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy