├── Week_9 ├── CKCS_Examples │ ├── topics.txt │ ├── Halloween.txt │ ├── coordinates.txt │ ├── A_File.txt │ ├── Working_Dir.py │ ├── Write_File.py │ ├── Coords.py │ ├── Try_Except.py │ ├── Mat_Plot.py │ └── Reading_File.py ├── Iter_Tools.py ├── Fib.py ├── Multi_Array.py ├── Generator.py ├── Rand_Int.py ├── Factorial.py ├── Random_Strings.py ├── Balanced_Brackets.py ├── Random_Array.py ├── Lambda_Example.py ├── Brackets_Tests.py ├── Fruity_Recursion.py ├── List_Frequency.py ├── Mem_Fib.py ├── Generators.py └── List_Freq_Tests.py ├── Review ├── Review Session.pdf ├── __pycache__ │ ├── Brackets.cpython-37.pyc │ └── ReviewQuestion1.cpython-37.pyc ├── Answers │ ├── __pycache__ │ │ ├── Brackets.cpython-37.pyc │ │ └── RecursiveBrackets.cpython-37.pyc │ ├── Brackets.py │ ├── EpsilonGreater.py │ ├── EvenAddition.py │ ├── RecursivePalindrome.py │ ├── FactorialRecursion.py │ ├── StringConcat.py │ ├── MatrixCheck.py │ ├── HeronPractice.py │ ├── RemoveLetter.py │ ├── Inheritance.py │ ├── RecursiveBrackets.py │ ├── OOPRectangle.py │ ├── SentenceSplitter.py │ ├── SentenceTokens.py │ ├── CreateTest.py │ └── ClassExamPrepSolution.py ├── True_And_False.py ├── List_Ex.py ├── FactorialRecursion.py ├── HeronPractice.py ├── RecursiveBrackets.py ├── StringConcat.py ├── String_Examples.py ├── Brackets.py ├── SentenceTokens.py ├── EvenAddition.py ├── AlexMidtermQuestionBank │ ├── q8-2.py │ ├── q8-1.py │ ├── q8-5.py │ ├── q8-3.py │ ├── q4-1.py │ ├── q8-4.py │ ├── q8-6.py │ └── q8-7.py ├── MatrixCheck.py ├── SentenceSplitter.py ├── EpsilonGreater.py ├── RecursivePalindrome.py ├── CreateTest.py ├── Inheritance.py ├── RemoveLetter.py ├── OOPRectangle.py └── ClassExamPrepQuestion.py ├── Week_5 ├── File_B.py ├── Spooky.txt ├── File_A.py ├── Zip_Func.py ├── another_file.txt ├── Continue.py ├── File_Reading.py ├── CKCS_Examples │ ├── Basic_Numpy.py │ ├── Multi_List.py │ ├── Matricies.py │ └── Other_Arrays.py ├── Recursion_1.py ├── Reads_File.py ├── More_Files.py ├── Zip_Ex.py ├── Spooky.json ├── With_Reading.py ├── For_With_Break.py ├── More_Dicts.py ├── Read_JSON.py ├── List_Comprehension.py ├── While_With_Else.py ├── Recursion_0.py ├── Spooky_File_Read.py ├── Binary_Search.py ├── Break_Statements.py ├── Mutable_vs_Immutable.py ├── Even_More_Dicts.py └── Season_Of_The_Witch.txt ├── Week_8 └── CKCS_Examples │ ├── Func_Objects.py │ ├── Misc_Funcs.py │ ├── Scopes.py │ ├── Grouping.py │ ├── Funcs_As_Values.py │ ├── Fucs_As_Args.py │ ├── Funcs_As_Return.py │ └── Data_Frame.py ├── Week_4 ├── CKCS_Examples │ ├── Imports_A_File.py │ ├── Functions_We_Know.py │ ├── Var_Args.py │ ├── Default_Args.py │ ├── Funcs_As_Values.py │ ├── kwargs.py │ ├── Extra_Func.py │ ├── Lambdas.py │ ├── Functions_As_Arguments.py │ └── Custom_Functions.py ├── a_file.txt ├── For_Over_Range.py ├── Math_Functions.py ├── Non_Recurs_Fact.py ├── Enumerate.py ├── For_List.py ├── Other_Ranges.py ├── Grade_Dict.py ├── Loop_In_Function.py ├── Nested_Loop.py ├── Function_In_Loop.py ├── Set.py ├── Read_Files.py ├── Dictionary.py └── Function_And_For.py ├── Week_3 ├── Funky_Range.py ├── List_Experiments.py ├── String_Comparisons.py ├── Int_Triangle.py ├── Nested_While.py ├── Lecture_Example.py ├── CKCS_Examples │ ├── Sets.py │ ├── Sequences.py │ ├── Dict.py │ └── Loop_Experiments.py ├── Dict.py ├── Sets.py ├── Basic_While.py ├── Right_Triangle.py ├── Main_And_While.py ├── String_Experiments.py ├── User_While.py ├── Tuple_Examples.py ├── Function_And_While.py ├── Binary_Strings.py ├── Backward_String.py ├── List_Examples.py ├── Default_Arguments.py ├── String_Operations.py ├── Arb_Root_Any_Number.py └── Exhaustive_Enumeration.py ├── Week_10 ├── Scope_Ex.py ├── Higher_Order.py ├── Funcs_As_Values.py ├── Funcs_In_Structures.py ├── Fucs_As_Args.py ├── Funcs_As_Return.py ├── More_Lambdas.py ├── Funcs_Ex.py ├── Scope.py └── Book_Class.py ├── README.md ├── Week_11 ├── Multi_Inheritance.py ├── Classes │ ├── ExampleFourTests.py │ ├── ExampleTwoCorrect.py │ ├── ExampleOne.py │ ├── ExampleThreeCorrect.py │ ├── ExampleThree.py │ ├── ExampleOneCorrect.py │ ├── ExampleFour.py │ └── ExampleTwo.py ├── Rand_With_Classes.py ├── ExampleOne.py ├── Car_Tests.py ├── Bank_Account.py ├── Manga_Exercise.py ├── Last_Class_Example.py ├── Book_Tests.py ├── Card_Class.py ├── CKCS_Examples │ └── Car.py ├── Board_Class.py ├── Book_Exercise.py ├── In_Class_Example.py ├── Car_Class.py └── Lang_Dict.py ├── Week_2 ├── Complex_Condition.py ├── CKSC_Examples │ ├── CKCS_Lists.py │ ├── CKCS149_Lecture_2.py │ ├── CKCS_If.py │ └── CKCS_Loops.py ├── Stop_Light.py ├── Lecture_Two.py ├── Function_And_If.py └── Function_Example.py ├── Week_1 ├── Boolean_Examples.py ├── Basic_Example.py ├── Hello_World.py ├── Lecture_One.py ├── String_Examples.py ├── CKCS_Lecture_1.py └── DataTypeCheatSheet.py ├── Week_6 └── CKCS_Examples │ ├── Basic_Series.py │ └── Data_Frame.py └── .gitignore /Week_9/CKCS_Examples/topics.txt: -------------------------------------------------------------------------------- 1 | Computer Science is rewarding! -------------------------------------------------------------------------------- /Review/Review Session.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cassLaffan/CPS109/HEAD/Review/Review Session.pdf -------------------------------------------------------------------------------- /Week_5/File_B.py: -------------------------------------------------------------------------------- 1 | import File_A 2 | 3 | if __name__ == "__main__": 4 | print(File_A.add_numbers(1000, 20000)) 5 | -------------------------------------------------------------------------------- /Week_5/Spooky.txt: -------------------------------------------------------------------------------- 1 | Happy Halloween! 2 | 🎃 Trick or Treat! 3 | 🕷️ Spooky spiders everywhere! 4 | 👻 Ghosts are out tonight! -------------------------------------------------------------------------------- /Review/__pycache__/Brackets.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cassLaffan/CPS109/HEAD/Review/__pycache__/Brackets.cpython-37.pyc -------------------------------------------------------------------------------- /Week_8/CKCS_Examples/Func_Objects.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == "__main__": 3 | # A reminder about lambdas 4 | al = lambda x: x * 2 5 | print(al(2)) -------------------------------------------------------------------------------- /Week_9/CKCS_Examples/Halloween.txt: -------------------------------------------------------------------------------- 1 | Happy Halloween! 2 | 🎃 Trick or Treat! 3 | 🕷️ Spooky spiders everywhere! 4 | 👻 Ghosts are out tonight! -------------------------------------------------------------------------------- /Review/Answers/__pycache__/Brackets.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cassLaffan/CPS109/HEAD/Review/Answers/__pycache__/Brackets.cpython-37.pyc -------------------------------------------------------------------------------- /Review/__pycache__/ReviewQuestion1.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cassLaffan/CPS109/HEAD/Review/__pycache__/ReviewQuestion1.cpython-37.pyc -------------------------------------------------------------------------------- /Week_4/CKCS_Examples/Imports_A_File.py: -------------------------------------------------------------------------------- 1 | from Custom_Functions import * 2 | 3 | if __name__ == "__main__": 4 | print(muliply_string("Grape"), end=" ") 5 | print("Hi!") -------------------------------------------------------------------------------- /Review/Answers/__pycache__/RecursiveBrackets.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cassLaffan/CPS109/HEAD/Review/Answers/__pycache__/RecursiveBrackets.cpython-37.pyc -------------------------------------------------------------------------------- /Week_4/a_file.txt: -------------------------------------------------------------------------------- 1 | Cat mice 2 | Dog bones 3 | Fish flakes 4 | Moose leaves 5 | Deer grass 6 | Human doritos 7 | Teletubby humans 8 | Monkey bananas 9 | Bird seeds 10 | -------------------------------------------------------------------------------- /Week_4/CKCS_Examples/Functions_We_Know.py: -------------------------------------------------------------------------------- 1 | my_list = ["Banana", "Kiwi", "Mango", "Lemon", "Pear"] 2 | print(len(my_list)) 3 | new_banana = my_list[0].upper() 4 | my_list.append("Apple") -------------------------------------------------------------------------------- /Week_9/CKCS_Examples/coordinates.txt: -------------------------------------------------------------------------------- 1 | 1.0 2.5 2 | 2.0 3.7 3 | 3.0 5.2 4 | 4.0 6.8 5 | 5.0 8.1 6 | 6.0 9.4 7 | 7.0 10.9 8 | 8.0 12.3 9 | 9.0 13.6 10 | 10.0 15.0 -------------------------------------------------------------------------------- /Week_8/CKCS_Examples/Misc_Funcs.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | if __name__ == "__main__": 4 | s1 = pd.Series(['a', 'b']) 5 | s2 = pd.Series(['c', 'd']) 6 | print(pd.concat([s1, s2])) 7 | -------------------------------------------------------------------------------- /Week_3/Funky_Range.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | new_list = ['one', 'two', 'three', 'four'] 3 | # 0 -> length(list) - 1 4 | for i in range(len(new_list)): 5 | print(i) 6 | print(new_list[i]) -------------------------------------------------------------------------------- /Week_5/File_A.py: -------------------------------------------------------------------------------- 1 | def add_numbers(a, b): 2 | return a + b 3 | 4 | if __name__ == "__main__": 5 | print(add_numbers(0, 0)) 6 | print(add_numbers(-1, -10)) 7 | print(add_numbers(3, 2)) 8 | -------------------------------------------------------------------------------- /Week_5/Zip_Func.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == "__main__": 3 | list1 = [1, 2, 3] 4 | list2 = ['a', 'b', 'c'] 5 | 6 | result = zip(list1, list2) 7 | print(list(result)) # Convert iterator to list 8 | -------------------------------------------------------------------------------- /Week_5/another_file.txt: -------------------------------------------------------------------------------- 1 | Somebody once told me 2 | The world was gonna roll me 3 | I ain't the sharpest tool in the shed 4 | She was lookin kinda dumb 5 | With her finger and her thumb 6 | In the shape of an L on her forehead 7 | -------------------------------------------------------------------------------- /Week_9/CKCS_Examples/A_File.txt: -------------------------------------------------------------------------------- 1 | Somebody once told me 2 | The world was gonna roll me 3 | I ain't the sharpest tool in the shed 4 | She was lookin kinda dumb 5 | With her finger and her thumb 6 | In the shape of an L on her forehead -------------------------------------------------------------------------------- /Week_5/Continue.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == "__main__": 3 | lst = ['Banana', 'Orange', 'Kiwi', 'Jackfruit', 'Pineapple', 'Strawberry'] 4 | 5 | for fruit in lst: 6 | if len(fruit) % 3 == 0: 7 | print("Skipping this fruit!") 8 | continue 9 | print(fruit) -------------------------------------------------------------------------------- /Week_8/CKCS_Examples/Scopes.py: -------------------------------------------------------------------------------- 1 | # A demonstration of scopes 2 | 3 | y = 20 4 | 5 | def func(): 6 | x = 10 7 | # Will cause the changes to y to persist after the function exits 8 | global y 9 | y = x + 5 10 | print(y) 11 | 12 | func() 13 | print(y) -------------------------------------------------------------------------------- /Week_4/For_Over_Range.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | user_string = input("Please enter a string: ") 3 | 4 | # This program simply iterates through any given string. 5 | for i in range(len(user_string)): 6 | print(user_string[i] + "\t", end = "") -------------------------------------------------------------------------------- /Week_9/CKCS_Examples/Working_Dir.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | if __name__ == "__main__": 4 | # Get the current working directory 5 | curr = os.getcwd() 6 | print(curr) 7 | 8 | # Change working directory 9 | os.chdir('/Users/courier/Documents') 10 | print(os.getcwd()) 11 | -------------------------------------------------------------------------------- /Week_4/CKCS_Examples/Var_Args.py: -------------------------------------------------------------------------------- 1 | 2 | def unpacks_fruit(*fruits): 3 | for fruit in fruits: 4 | print(f"Unpacking {fruit} from grocery bag.") 5 | 6 | if __name__ == "__main__": 7 | fruit_list = new_list = ["Banana", "Kiwi", "Mango", "Lemon", "Pear"] 8 | unpacks_fruit(*fruit_list) -------------------------------------------------------------------------------- /Week_9/Iter_Tools.py: -------------------------------------------------------------------------------- 1 | from itertools import islice 2 | 3 | if __name__ == "__main__": 4 | numbers = (x * x for x in range(10)) # Lazy generator 5 | squared_numbers = list(islice(numbers, 3)) # Get first 3 squares 6 | print(squared_numbers) # Outputs: [0, 1, 4] 7 | 8 | -------------------------------------------------------------------------------- /Week_4/CKCS_Examples/Default_Args.py: -------------------------------------------------------------------------------- 1 | 2 | def say_hello(a_name="Cassandra"): 3 | return f"Hello, {a_name}" 4 | 5 | if __name__ == "__main__": 6 | print(say_hello("Tavis")) 7 | print(say_hello()) 8 | 9 | new_list = ["Banana", "Kiwi", "Mango", "Lemon", "Pear"] 10 | 11 | print(*new_list) -------------------------------------------------------------------------------- /Week_9/Fib.py: -------------------------------------------------------------------------------- 1 | def fibonacci(n): 2 | # Base cases 3 | if n == 0: 4 | return 0 5 | elif n == 1: 6 | return 1 7 | # Recursive case 8 | else: 9 | print(f"Recursive call, n = {n}!") 10 | return fibonacci(n - 1) + fibonacci(n - 2) 11 | 12 | if __name__ == "__main__": 13 | print(fibonacci(8)) -------------------------------------------------------------------------------- /Week_3/List_Experiments.py: -------------------------------------------------------------------------------- 1 | new_list = [] 2 | 3 | print(new_list) 4 | 5 | # Produces index error! 6 | # print(new_list[1]) 7 | 8 | new_list.append("This is an element\n") 9 | new_list.extend(["apple", "banana", "grape\n"]) 10 | new_list.append(10) 11 | 12 | print(new_list) 13 | print(new_list[0], new_list[3]) -------------------------------------------------------------------------------- /Week_3/String_Comparisons.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | # String Comparison Examples 3 | str1 = "tina" 4 | str2 = "jack" 5 | 6 | print(str1 == str2) # False 7 | print(str1 != str2) # True 8 | print(str1 < str2) # True (because 'a' < 'b') 9 | print(str1 > str2) # False 10 | -------------------------------------------------------------------------------- /Week_5/File_Reading.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | 3 | # Opens the file (in r mode) 4 | our_file = open("another_file.txt", "r") 5 | 6 | # Reads the file into the variable 7 | st = our_file.read() 8 | print("The file reads: ", st) 9 | 10 | # Closes the file 11 | our_file.close() -------------------------------------------------------------------------------- /Review/True_And_False.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | var = 8 < 10 and 9 == 9 3 | print(var) 4 | 5 | var_b = 7 != 7 or 7 != 6 6 | print(var_b) 7 | print(not var_b) 8 | var_int = 7 9 | str_int = "Hello" 10 | print(f"{str_int} is {var_int}") 11 | print(str(var_int) + str_int) 12 | -------------------------------------------------------------------------------- /Week_10/Scope_Ex.py: -------------------------------------------------------------------------------- 1 | # A global variable (bad) 2 | x = 20 3 | 4 | def sum(): 5 | # Doesn't work due to x becoming local 6 | # x = x + 30 7 | # Global tells Python to persist changes 8 | global x 9 | x = x + 30 10 | print(f"The value of local x is: {x}") 11 | 12 | sum() 13 | print(f"The value of global x is: {x}") -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CPS109 2 | This is where examples from the lecture will be posted on a weekly basis! 3 | 4 | To see the examples, click the folder for the week you want (lab 1 examples are in the folder Lab1 for instance). 5 | There, you will see things like "Example_One.py". Just click that and it will show you the code in your browser. 6 | -------------------------------------------------------------------------------- /Week_3/Int_Triangle.py: -------------------------------------------------------------------------------- 1 | def int_triangle(num): 2 | count = 1 3 | while count <= num: 4 | inner = 1 # Counter for inner loop 5 | while inner <= count: 6 | print(inner, end=" ") 7 | inner+=1 8 | print() 9 | count+=1 10 | 11 | if __name__ == "__main__": 12 | inp = int(input("Please enter a number. ")) 13 | int_triangle(inp) -------------------------------------------------------------------------------- /Week_3/Nested_While.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Here, we're exploring how we can nest logic, 3 | even, loops, inside a while loop. 4 | ''' 5 | 6 | if __name__ == '__main__': 7 | i = 1 8 | while i <= 5: 9 | j = 1 10 | while j <= 5: 11 | print("Our new product is: ", i * j) 12 | j += 1 13 | i += 1 -------------------------------------------------------------------------------- /Review/List_Ex.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | a_list = [1, 2, "three"] 3 | a_list.append([4, 5]) 4 | print(a_list) 5 | a_list.pop() 6 | print(a_list) 7 | a_list.extend([4, 5]) 8 | print(a_list) 9 | 10 | for i in range(len(a_list)): 11 | if i == 2: 12 | continue 13 | print(a_list[i]) 14 | -------------------------------------------------------------------------------- /Week_3/Lecture_Example.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | movies = [] 3 | user_input = str(input("Enter some of your favourite movies! ")) 4 | while user_input.lower() != "exit": 5 | movies.append(user_input) 6 | user_input = str(input("Enter another movie. ")) 7 | 8 | for i, movie in enumerate(movies): 9 | print(f"Your number {i + 1} movie is {movie}") -------------------------------------------------------------------------------- /Review/FactorialRecursion.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | ''' 3 | Write a recursive factorial function. Then, write FIVE 4 | test cases for the output. Two test cases should be edge 5 | cases. 6 | ''' 7 | 8 | def factorial(num): 9 | pass 10 | 11 | class FacTest(unittest.TestCase): 12 | pass 13 | 14 | if __name__ == "__main__": 15 | unittest.main(exit=True) -------------------------------------------------------------------------------- /Week_4/CKCS_Examples/Funcs_As_Values.py: -------------------------------------------------------------------------------- 1 | 2 | def prints_a_list(ls): 3 | print(*ls) 4 | 5 | def does_stuff(function, a_list): 6 | function(a_list) 7 | 8 | if __name__ == "__main__": 9 | variable = prints_a_list 10 | new_list = ["Banana", "Kiwi", "Mango", "Lemon", "Pear", "Strawberry"] 11 | variable(new_list) 12 | 13 | does_stuff(prints_a_list, new_list) -------------------------------------------------------------------------------- /Week_5/CKCS_Examples/Basic_Numpy.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | 3 | if __name__ == "__main__": 4 | an_array = numpy.array([33, 44, 10, 40]) 5 | second_array = numpy.array([5, 1, 7, 10]) 6 | 7 | print(an_array) 8 | vec = an_array + second_array 9 | print(vec) 10 | print(type(an_array)) 11 | print(type(vec)) 12 | 13 | print(vec.shape) 14 | print(vec.dtype) 15 | -------------------------------------------------------------------------------- /Week_5/CKCS_Examples/Multi_List.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | list_of_lists = [["banana", "apple", "pear"], 3 | ["strawberry", "pumpkin", "grape"], 4 | ["raspberry", "blueberry", "Mango"]] 5 | 6 | print(list_of_lists) 7 | 8 | ls_one = [2, 1, 8, 4] 9 | ls_two = [5, 3, 8, 1] 10 | ls_three = ls_one + ls_two 11 | 12 | print(ls_three) 13 | -------------------------------------------------------------------------------- /Week_10/Higher_Order.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In this file, I'll be demonstrating the usage of higher order functions. 3 | ''' 4 | 5 | # Here again we see a function where the first argument is a function 6 | def apply(func, value): 7 | return func(value) 8 | 9 | if __name__ == "__main__": 10 | # Now, we call our function, where the function argument is a lambda! 11 | apply(lambda x: x ** 2, 4) -------------------------------------------------------------------------------- /Week_11/Multi_Inheritance.py: -------------------------------------------------------------------------------- 1 | class Animal: 2 | def speak(self): 3 | print("Animal speaks") 4 | 5 | class Bird: 6 | def fly(self): 7 | print("Bird is flying") 8 | 9 | class FlyingAnimal(Animal, Bird): 10 | pass 11 | 12 | if __name__ == "__main__": 13 | fa = FlyingAnimal() 14 | fa.speak() # Inherited from Animal 15 | fa.fly() # Inherited from Bird 16 | -------------------------------------------------------------------------------- /Week_11/Classes/ExampleFourTests.py: -------------------------------------------------------------------------------- 1 | import ExampleFour 2 | import unittest 3 | 4 | class MyTests(unittest.TestCase): 5 | def test1(self): 6 | pass 7 | def test2(self): 8 | pass 9 | def test3(self): 10 | pass 11 | def test4(self): 12 | pass 13 | def test5(self): 14 | pass 15 | 16 | if __name__ == "__main__": 17 | unittest.main(exit=True) -------------------------------------------------------------------------------- /Week_4/CKCS_Examples/kwargs.py: -------------------------------------------------------------------------------- 1 | 2 | # Convention just says we name it kwargs 3 | def print_a_family(**kwargs): 4 | for key, value in kwargs.items(): 5 | print(key) 6 | print(*value) 7 | 8 | if __name__ == "__main__": 9 | family_names = ["Cassandra", "Tavis", "Craig", "Susan"] 10 | fam_roles = ["Daughter", "Son", "Dad", "Mom"] 11 | 12 | print_a_family(roles = fam_roles, names = family_names) -------------------------------------------------------------------------------- /Week_5/Recursion_1.py: -------------------------------------------------------------------------------- 1 | def print_recursively(num): 2 | if num == 0: 3 | print("Starting to print at 0") 4 | return 0 5 | else: 6 | a = print_recursively(num - 1) 7 | print("Now we are at ", a) 8 | return num 9 | 10 | if __name__ == "__main__": 11 | inp = int(input("What number of recursions would you like to see?")) 12 | print_recursively(inp) -------------------------------------------------------------------------------- /Week_3/CKCS_Examples/Sets.py: -------------------------------------------------------------------------------- 1 | # Make an empty set 2 | my_set = set() 3 | 4 | user_input = str(input("Please enter a fruit: ")) 5 | 6 | while user_input.lower() != "exit": 7 | my_set.add(user_input) 8 | user_input = str(input("Please enter a fruit: ")) 9 | 10 | print(my_set) 11 | 12 | user_input = str(input("Select an item to remove: ")) 13 | 14 | my_set.discard(user_input) 15 | 16 | print(my_set) -------------------------------------------------------------------------------- /Week_2/Complex_Condition.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | # Here, I have a condition which strings together several 3 | # questions. You can chain these as much as you like in 4 | # Python! 5 | 6 | a_number = 10 7 | 8 | if (0 <= a_number <= 20) or (a_number != 9): 9 | print("The number is less than 20 but greater than 0!") 10 | else: 11 | print("Number is out of range!") -------------------------------------------------------------------------------- /Week_5/Reads_File.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == "__main__": 3 | our_file = open("./Season_Of_The_Witch.txt", "r") 4 | 5 | line_string = our_file.readline() 6 | counter = 1 7 | 8 | while line_string: 9 | if counter == 5: 10 | print("\t", line_string, end="") 11 | counter = 1 12 | else: 13 | print(line_string, end="") 14 | counter+=1 15 | line_string = our_file.readline() 16 | 17 | our_file.close() -------------------------------------------------------------------------------- /Week_9/Multi_Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This is a matrix! 2x3 to be exact. 3 | ''' 4 | def print_matrix(our_matrix): 5 | for i in our_matrix: 6 | for j in i: 7 | print(" | " + str(j), end="") 8 | print("| ") 9 | 10 | if __name__ == "__main__": 11 | our_matrix = [[3, 1, 4], [2, 5, 1], [0, 0, 0]] 12 | 13 | print_matrix(our_matrix) 14 | 15 | for i in our_matrix: 16 | print(i) -------------------------------------------------------------------------------- /Week_9/Generator.py: -------------------------------------------------------------------------------- 1 | 2 | def backwards_gen(lower, upper): 3 | num = upper 4 | while num != lower: 5 | yield num 6 | num = num - 1 7 | 8 | if __name__ == "__main__": 9 | lower_input = int(input("Enter the lower limit of the range: ")) 10 | upper_input = int(input("Enter the upper limit of the range: ")) 11 | 12 | generated = backwards_gen(lower_input, upper_input) 13 | for num in generated: 14 | print(num) -------------------------------------------------------------------------------- /Week_3/Dict.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | new_dict = dict() 3 | user_input = input("Enter a key: ") 4 | while user_input.lower() != "exit": 5 | second_input = input("Enter a value: ") 6 | # Adds a key:value pair in the form of user_input : second_input 7 | new_dict[user_input] = second_input 8 | user_input = input("Enter a key: ") 9 | 10 | print(new_dict) 11 | 12 | for entry in new_dict: 13 | print(new_dict[entry]) -------------------------------------------------------------------------------- /Week_8/CKCS_Examples/Grouping.py: -------------------------------------------------------------------------------- 1 | import pandas 2 | 3 | if __name__ == "__main__": 4 | df = pandas.DataFrame({'X' : ['B', 'B', 'A', 'A'], 'Y' : [1, 2, 3, 4]}) 5 | print(df) 6 | # Group by operations 7 | print(df.groupby(['X']).sum()) 8 | # Outdated, someone should tell the head prof! 9 | print(df.groupby(['X']).get_group('A')) 10 | 11 | # Pivot tables 12 | pv = pandas.pivot_table(df, index=["X"], aggfunc='sum') 13 | print(pv) -------------------------------------------------------------------------------- /Week_3/CKCS_Examples/Sequences.py: -------------------------------------------------------------------------------- 1 | fruit_list = ["Strawberry", "Blueberry", "Grape", "Banana"] 2 | x = 10 3 | 4 | for number in range(x, 0, -1): 5 | print(number) 6 | 7 | for index, fruit in enumerate(fruit_list): 8 | print(f"Index: {index}", f" Fruit: {fruit}") 9 | 10 | new_list = [fruit.upper() for fruit in fruit_list] 11 | print(new_list) 12 | 13 | second_new_list = [num * 10 for num in range(10, -1, -1)] 14 | print(second_new_list) -------------------------------------------------------------------------------- /Week_5/More_Files.py: -------------------------------------------------------------------------------- 1 | # This file will loop and write a line to a file so long as the user wants it to. 2 | if __name__ == "__main__": 3 | 4 | our_file = open("another_file.txt", "a") # w means you "write to it" 5 | 6 | inp = "" 7 | 8 | while inp != "Stop": 9 | inp = input("What would you like to write to the file?\n") 10 | if inp != "Stop": 11 | our_file.write(inp + "\n") 12 | 13 | our_file.close() -------------------------------------------------------------------------------- /Week_3/Sets.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | new_set = set() 3 | new_list = [] 4 | user_input = input("Enter something! ") 5 | 6 | while user_input.lower() != "exit": 7 | new_list.append(user_input) 8 | new_set.add(user_input) 9 | user_input = input("Enter something! ") 10 | 11 | print(new_set) 12 | print(new_list) 13 | 14 | user_input = input("Enter something to remove: ") 15 | new_set.discard(user_input) 16 | print(new_set) 17 | -------------------------------------------------------------------------------- /Week_10/Funcs_As_Values.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This is a demonstration of functions as class-first objects! 3 | Note the syntax here. We don't use the () syntax for a function 4 | in the main until we want to call the functionality! 5 | ''' 6 | 7 | def greet(): 8 | return "Hello, world!" 9 | 10 | if __name__ == "__main__": 11 | # Assigning a function to a variable 12 | greet_func = greet 13 | # Calling the function through the variable 14 | print(greet_func()) -------------------------------------------------------------------------------- /Week_8/CKCS_Examples/Funcs_As_Values.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This is a demonstration of functions as class-first objects! 3 | Note the syntax here. We don't use the () syntax for a function 4 | in the main until we want to call the functionality! 5 | ''' 6 | 7 | def greet(): 8 | return "Hello, world!" 9 | 10 | if __name__ == "__main__": 11 | # Assigning a function to a variable 12 | greet_func = greet 13 | # Calling the function through the variable 14 | print(greet_func()) -------------------------------------------------------------------------------- /Week_9/Rand_Int.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | if __name__ == "__main__": 4 | # Seed, using the default 5 | random.seed() 6 | 7 | # Random integers 8 | print(random.randint(1, 6)) # Simulates rolling a die 9 | print(random.randrange(0, 100, 10)) # Random number in steps of 10 10 | 11 | # Shuffling a list 12 | my_list = [1, 2, 3, 4, 5] 13 | random.shuffle(my_list) 14 | print(my_list) # Outputs a shuffled list, e.g., [3, 1, 4, 2, 5] 15 | -------------------------------------------------------------------------------- /Week_5/Zip_Ex.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | list_one = ['Banana', 'Orange', 'Kiwi', 'Jackfruit'] 3 | list_two = ['Yellow', 'Orange', 'Brown', 'Brown?'] 4 | # Last element gets chopped off 5 | list_three = [1.30, 2.50, 3.33, 10.10, 9.11] 6 | 7 | # Needs to be cast as a list in order to be printed in a meaningful fashion 8 | print(list(zip(list_one, list_two, list_three))) 9 | 10 | new_list = [a + b for a, b in list(zip(list_one, list_two))] 11 | print(new_list) 12 | -------------------------------------------------------------------------------- /Week_9/Factorial.py: -------------------------------------------------------------------------------- 1 | # Let's do a recursive function that calculates a factorial! 2 | 3 | def factorial(num): 4 | new_num = 0 5 | # Base case is num == 0 6 | if(num < 1): 7 | new_num = 1 8 | print("This is our base case!") 9 | else: 10 | print(f"This is a recursive case. The value is {num}.") 11 | new_num = num * factorial(num - 1) 12 | return new_num 13 | 14 | if __name__ == "__main__": 15 | print(f"{5}! = {factorial(5)}") -------------------------------------------------------------------------------- /Week_2/CKSC_Examples/CKCS_Lists.py: -------------------------------------------------------------------------------- 1 | new_list = ["Cassandra", "Frances", "Laffan", "Tavis", "Brian", "Laffan"] 2 | another_list = [1, 10, "A string", True] 3 | var_three = "Hello, world!" 4 | str_lst = var_three.split() 5 | 6 | print(new_list[0]) 7 | print(new_list[1:5]) 8 | print(another_list) 9 | print(str_lst) 10 | 11 | new_list.append("Susan") 12 | print(new_list) 13 | 14 | new_list.remove("Frances") 15 | print(new_list) 16 | 17 | tup = ("This", "Is", "A", "Tuple") 18 | print(tup) 19 | print(tup[2]) -------------------------------------------------------------------------------- /Week_9/Random_Strings.py: -------------------------------------------------------------------------------- 1 | import random 2 | ''' 3 | Here, we will practice more with the random library. We're taking 4 | a random choice out of an iterable! 5 | ''' 6 | 7 | def print_funny(choice): 8 | our_weird_strings = ["----------", "+++++++++", "+_+_+_+_+_+_+_+_+_+_"] 9 | 10 | for i in choice: 11 | print(random.choice(our_weird_strings) + i) 12 | 13 | if __name__ == "__main__": 14 | random.seed() 15 | ls = random.randint(0, 10) 16 | print_funny(random.choice("hello")) -------------------------------------------------------------------------------- /Week_3/CKCS_Examples/Dict.py: -------------------------------------------------------------------------------- 1 | my_dict = dict() 2 | 3 | my_dict["Banana"] = "Yellow" 4 | my_dict["Apple"] = ["Red"] 5 | my_dict["Strawberry"] = "Red" 6 | my_dict["Grape"] = "Purple" 7 | my_dict["Guava"] = "Green" 8 | 9 | my_dict["Apple"].append("Green") 10 | 11 | print(my_dict) 12 | 13 | del my_dict["Guava"] 14 | 15 | print(my_dict) 16 | 17 | bana_colour = my_dict.pop("Banana") 18 | 19 | print(bana_colour) 20 | 21 | print(my_dict) 22 | 23 | for key in my_dict: 24 | print(key) 25 | print(my_dict[key]) -------------------------------------------------------------------------------- /Week_10/Funcs_In_Structures.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In this file, we explore how functions can be stored in iterable 3 | data structures, such as lists. 4 | ''' 5 | # Some basic functions 6 | def add(a, b): 7 | return a + b 8 | 9 | def multiply(a, b): 10 | return a * b 11 | 12 | if __name__ == "__main__": 13 | # Storing the functions in a list 14 | operations = [add, multiply] 15 | # Calling the first function by index, giving it arguments 16 | print(operations[0](2, 3)) 17 | var = operations[1](2, 6) 18 | print(var) -------------------------------------------------------------------------------- /Week_3/Basic_While.py: -------------------------------------------------------------------------------- 1 | # Now let's look at while loops 2 | 3 | # This is a very simple example of a while loop 4 | # How a while loop works is that it will loop for every time its condition isn't 5 | # found to be true. In this case, it will loop once more every time it finds that x 6 | # is strictly less than 10. Once x == 10, then it will no longer execute any of the 7 | # code within the loop. 8 | if __name__ == "__main__": 9 | x = 0 10 | 11 | while x <= 10: 12 | print(x) 13 | x+=1 -------------------------------------------------------------------------------- /Week_4/Math_Functions.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | # This file will just show a some of the neat things you can call 4 | # in the math module. 5 | 6 | if __name__ == "__main__": 7 | # Some constants! 8 | circumference = 2 * math.pi * 5 9 | print(circumference) 10 | 11 | circumference = math.tau * 5 12 | print(circumference) 13 | 14 | # You can call Euler's Number 15 | print(math.e) 16 | 17 | # And infinity (but it's only useful when doing algorithms) 18 | print(math.inf) 19 | 20 | -------------------------------------------------------------------------------- /Week_4/Non_Recurs_Fact.py: -------------------------------------------------------------------------------- 1 | # Let's program a factorial. 2 | # Remember: a factorial is just that number multiplied 3 | # by every single number in the range of it and 1. 4 | # Like, 4! = 4 * 3 * 2 * 1 = 24 5 | 6 | def factorial(num): 7 | fact_num = 1 8 | 9 | for i in range(1, num + 1): 10 | fact_num = fact_num * i 11 | 12 | return fact_num 13 | 14 | if __name__ == "__main__": 15 | inp = input("What number should we calculate the factorial for?\n") 16 | x = factorial(int(inp)) 17 | print(x) -------------------------------------------------------------------------------- /Review/HeronPractice.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import math 3 | ''' 4 | Write a function which returns a guess, the approximate square root of x, 5 | such that abs(guess**2 - x) < epsilon using Heron's algorithm. Start with 6 | guess = x / 2 and improve guess to be (guess + x / guess) / 2 7 | 8 | Then, write FIVE unit tests for this function. 9 | ''' 10 | 11 | def heron(x, epsilon) : 12 | pass 13 | 14 | class HeronTests(unittest.TestCase): 15 | pass 16 | 17 | if __name__=='__main__': 18 | unittest.main(exit=True) 19 | -------------------------------------------------------------------------------- /Week_4/Enumerate.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In this file, we will be using enumeration to navigate 3 | lists! 4 | ''' 5 | 6 | if __name__ == "__main__": 7 | # I like fruit ok 8 | fruits = ['strawberry', 'blueberry', 'cherry'] 9 | 10 | for index, fruit in enumerate(fruits): 11 | print(f"Index {index}: {fruit}") 12 | 13 | # You can also decide what index you wish to start at 14 | # using the start argument 15 | for index, fruit in enumerate(fruits, start=1): 16 | print(f"Fruit number {index}: {fruit}") 17 | -------------------------------------------------------------------------------- /Week_4/For_List.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Here, we will be using a for loop to iterate 3 | over some basic iterable types in Python. 4 | ''' 5 | 6 | if __name__ == "__main__": 7 | # List example 8 | fruits = ['apple', 'banana', 'cherry'] 9 | for fruit in fruits: 10 | print(f"I like {fruit}") # Hey, another fstring! 11 | 12 | # String example 13 | for char in "hello": 14 | print(char) 15 | 16 | # Tuple example 17 | coords = (1, 2, 3) 18 | for coord in coords: 19 | print(coord) 20 | 21 | -------------------------------------------------------------------------------- /Week_10/Fucs_As_Args.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file shows how you can pass functions as arguments! Notice 3 | that unlike in C++ where the functions pass in as arguments 4 | will just be replaced with the values they return, functions 5 | passed as arguments in Python can literally act as functions! 6 | ''' 7 | 8 | def execute(func, value): 9 | # See? We're calling a function passed as an argument! 10 | x = func(value) 11 | return x 12 | 13 | def square(x): 14 | return x * x 15 | 16 | if __name__ == "__main__": 17 | print(execute(square, 5)) -------------------------------------------------------------------------------- /Week_3/Right_Triangle.py: -------------------------------------------------------------------------------- 1 | # Assume the user_input is an integer 2 | def right_triangle(user_input): 3 | iterator = 1 4 | while iterator <= user_input: 5 | second_itr = 1 6 | while second_itr <= iterator: 7 | print(second_itr, end=" ") # Overrides the end of a line with a space 8 | second_itr += 1 9 | print() # Prints a new line, nothing else 10 | iterator += 1 11 | 12 | if __name__ == "__main__": 13 | inp = int(input("Please enter a number: ")) 14 | right_triangle(inp) -------------------------------------------------------------------------------- /Week_9/Balanced_Brackets.py: -------------------------------------------------------------------------------- 1 | def count_brackets(brackets): 2 | ''' 3 | Takes a string of brackets like so: {{}} or }{{}} 4 | and tells us if it's balanced. 5 | ''' 6 | count = 0 7 | 8 | for b in brackets: 9 | if b == "{": 10 | count = count + 1 11 | else: 12 | count = count - 1 13 | if count < 0: 14 | break 15 | 16 | return count == 0 17 | 18 | if __name__ == "__main__": 19 | our_brackets = "{}}}" 20 | print(count_brackets(our_brackets)) 21 | -------------------------------------------------------------------------------- /Week_4/CKCS_Examples/Extra_Func.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | 3 | def squares_a_number(num): 4 | return num**2 5 | 6 | if __name__ == "__main__": 7 | lst = [10, 2, 3, 6, 100, -2] 8 | new_list = map(squares_a_number, lst) 9 | print(list(new_list)) 10 | 11 | second_list = map(lambda x: x**3, lst) 12 | print(list(second_list)) 13 | 14 | third_list = filter(lambda x: x % 2 == 0, lst) 15 | print(*list(third_list)) 16 | 17 | # Ternery operation 18 | fourth_item = reduce(lambda a, b: a if (a > b) else b, lst) 19 | print(fourth_item) -------------------------------------------------------------------------------- /Week_4/CKCS_Examples/Lambdas.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == "__main__": 3 | # This variable will store this functionality for later 4 | adds_four = lambda a, b, c, d: a + b + c + d 5 | print("Hi!") 6 | print(adds_four(2, 4, 2, 7)) 7 | print(adds_four(10, 20, 30, 10)) 8 | # We killed the function and can't access it anymore on line 9 onwards 9 | adds_four = 20 10 | print(adds_four) 11 | 12 | new_list = ["Banana", "Kiwi", "Mango", "Lemon", "Pear"] 13 | # Try sorting this list without using the lambda 14 | new_list.sort(key=lambda x: x[1]) 15 | -------------------------------------------------------------------------------- /Week_4/CKCS_Examples/Functions_As_Arguments.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file shows how you can pass functions as arguments! Notice 3 | that unlike in C++ where the functions pass in as arguments 4 | will just be replaced with the values they return, functions 5 | passed as arguments in Python can literally act as functions! 6 | ''' 7 | 8 | def execute(func, value): 9 | # See? We're calling a function passed as an argument! 10 | return func(value) 11 | 12 | def square(x): 13 | return x * x 14 | 15 | if __name__ == "__main__": 16 | print(execute(square, 5)) -------------------------------------------------------------------------------- /Week_8/CKCS_Examples/Fucs_As_Args.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file shows how you can pass functions as arguments! Notice 3 | that unlike in C++ where the functions pass in as arguments 4 | will just be replaced with the values they return, functions 5 | passed as arguments in Python can literally act as functions! 6 | ''' 7 | 8 | def execute(func, value): 9 | # See? We're calling a function passed as an argument! 10 | x = func(value) 11 | return x 12 | 13 | def square(x): 14 | return x * x 15 | 16 | if __name__ == "__main__": 17 | print(execute(square, 5)) -------------------------------------------------------------------------------- /Review/Answers/Brackets.py: -------------------------------------------------------------------------------- 1 | def find_balance(s): 2 | ''' 3 | Takes a string of brackets as an argument. Will return 4 | True or False, depending on whether or not the string 5 | is balanced. An empty string is balanced. 6 | 7 | find_balance("}}}{") -> False 8 | find_balance("{}{}") -> True 9 | ''' 10 | counter = 0 11 | for ch in s: 12 | if ch == "{": 13 | counter += 1 14 | else: 15 | counter -=1 16 | if counter < 0: 17 | break 18 | 19 | return counter == 0 -------------------------------------------------------------------------------- /Week_10/Funcs_As_Return.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Here, we can see that you can return a function instead of 3 | a value in Python! 4 | ''' 5 | 6 | def outer(): 7 | def inner(a_value): 8 | return f"Hello from the inner function, {a_value}!" 9 | # Note that we can return the function by name? 10 | return inner 11 | 12 | if __name__ == "__main__": 13 | # return_func stores the inner() function 14 | return_func = outer() 15 | # And we can call the returned function! 16 | print(return_func) 17 | print(return_func("wow!")) 18 | var = return_func("Cass") 19 | print(var) -------------------------------------------------------------------------------- /Week_5/Spooky.json: -------------------------------------------------------------------------------- 1 | { 2 | "haunted_locations": [ 3 | { 4 | "name": "The Old Oak Tree", 5 | "location": "Creepy Hollow", 6 | "ghosts": 3, 7 | "haunting": true 8 | }, 9 | { 10 | "name": "Abandoned Asylum", 11 | "location": "Darkness Falls", 12 | "ghosts": 7, 13 | "haunting": true 14 | }, 15 | { 16 | "name": "Phantom Lake", 17 | "location": "Whispering Woods", 18 | "ghosts": 0, 19 | "haunting": false 20 | } 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /Week_3/Main_And_While.py: -------------------------------------------------------------------------------- 1 | # Let's do an example of a loop that relies on the user entering a specific 2 | # input for it to terminate. In this case, so long as the user doesn't 3 | # enter 1, it will loop forever. 4 | 5 | if __name__ == "__main__": 6 | x = -1 7 | 8 | while x != 1: 9 | # You'll notice that we don't take into account the user 10 | # being a jerk and entering something that isn't a number. 11 | # Don't worry, we'll get to that later. 12 | x = int(input("Please enter a number:\n")) 13 | print("Thank you!") 14 | -------------------------------------------------------------------------------- /Week_3/String_Experiments.py: -------------------------------------------------------------------------------- 1 | a_string = "This is a string!" 2 | 3 | split_string = a_string.split() 4 | print(split_string) 5 | 6 | print(a_string.lower()) 7 | 8 | # Get something at index -1 9 | print(a_string[-1]) 10 | 11 | print(a_string[0]) 12 | 13 | print(a_string[4]) 14 | 15 | print("This is another string"[6]) 16 | 17 | # Important note: lower bound is inclusive, 18 | # upper bound is exclusive 19 | new_variable = a_string[0:4] 20 | print(a_string[0:7]) 21 | 22 | variable_orange = " " 23 | variable_apple = "" 24 | 25 | print(variable_orange > variable_apple) -------------------------------------------------------------------------------- /Week_11/Rand_With_Classes.py: -------------------------------------------------------------------------------- 1 | import Card_Class as Card 2 | import random 3 | 4 | def draw_card(deck): 5 | return random.choice(deck) 6 | 7 | if __name__ == "__main__": 8 | random.seed() 9 | our_deck = Card.createDeck() 10 | 11 | print("Before we draw a random card, our deck contains: " +str(len(our_deck)) + " cards!") 12 | 13 | our_card = draw_card(our_deck) 14 | if our_card.colour == 'heart': 15 | our_deck.remove(our_card) 16 | 17 | print("How many cards does our deck have now? " + str(len(our_deck))) 18 | 19 | print("Done!") -------------------------------------------------------------------------------- /Week_8/CKCS_Examples/Funcs_As_Return.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Here, we can see that you can return a function instead of 3 | a value in Python! 4 | ''' 5 | 6 | def outer(): 7 | def inner(a_value): 8 | return f"Hello from the inner function, {a_value}!" 9 | # Note that we can return the function by name? 10 | return inner 11 | 12 | if __name__ == "__main__": 13 | # return_func stores the inner() function 14 | return_func = outer() 15 | # And we can call the returned function! 16 | print(return_func) 17 | print(return_func("wow!")) 18 | var = return_func("Cass") 19 | print(var) -------------------------------------------------------------------------------- /Week_11/Classes/ExampleTwoCorrect.py: -------------------------------------------------------------------------------- 1 | '''Here is how you would write the functionality in ExampleTwo.py 2 | correctly.''' 3 | 4 | # You will notice how, again, I have a doc string after the 5 | # declaration. 6 | def print_these_strings(str_one, str_two): 7 | '''Takes two strings and prints them sequentially.''' 8 | print(str_one) 9 | print(str_two) 10 | 11 | # Notice how I keep variables local. 12 | if __name__ == "__main__": 13 | a = input("Please input your first string:\n") 14 | b = input("Please input your second string:\n") 15 | print_these_strings(a, b) -------------------------------------------------------------------------------- /Week_5/With_Reading.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Here, we will examine using the "with" keyword 3 | again while reading a file! 4 | ''' 5 | 6 | if __name__ == "__main__": 7 | with open('Spooky.txt', 'r') as file: 8 | # Reads everything 9 | content = file.read() 10 | print(content) 11 | 12 | with open('halloween.txt', 'r') as file: 13 | # Reads the first line 14 | first_line = file.readline() 15 | # Reads all the lines 16 | all_lines = file.readlines() 17 | print("First line:", first_line) 18 | print("All lines:", all_lines) 19 | -------------------------------------------------------------------------------- /Week_2/Stop_Light.py: -------------------------------------------------------------------------------- 1 | def light_switcher(user_input): 2 | print("Running the function!") 3 | if user_input.lower() == "red": 4 | print("Stop!") 5 | elif user_input.lower() == "yellow": 6 | print("Speed up!") 7 | elif user_input.lower() == "green": 8 | print("Go!") 9 | else: 10 | print("Your light is broken.") 11 | 12 | if __name__ == "__main__": 13 | uinp = str(input("What colour is the light? Type 'exit' to get out of the car. ")) 14 | while uinp.lower() != "exit": 15 | light_switcher(uinp) 16 | uinp = str(input("What colour is the light now? Type 'exit' to get out of the car. ")) -------------------------------------------------------------------------------- /Week_3/User_While.py: -------------------------------------------------------------------------------- 1 | def string_list(): 2 | str_lst = [] 3 | user_input = "" 4 | while user_input.lower() != "end": 5 | user_input = str(input("Please enter a movie to add to the list: ")) 6 | if user_input.lower() != "end": 7 | str_lst.append(user_input) 8 | return str_lst 9 | 10 | if __name__ == '__main__': 11 | local_list = string_list() 12 | # Enumerate allows us to get an index-value pair from a list or tuple 13 | for iterator, movie in enumerate(local_list): 14 | print(f"Movie number {iterator + 1} is {movie}") # Another f string! -------------------------------------------------------------------------------- /Week_4/Other_Ranges.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Here, we will examine the range function and its 3 | various arguments! 4 | ''' 5 | 6 | if __name__ == "__main__": 7 | # range can have two arguments: start, stop 8 | for i in range(2, 6): 9 | print(i) 10 | 11 | # range can also have three arguments: start, stop, step 12 | # step is how you're counting up from start to stop 13 | for i in range(0, 10, 2): 14 | print(i) 15 | 16 | # You can also use step and a bigger start, smaller stop 17 | # to step backwards! 18 | for i in range(5, 0, -1): 19 | print(i) 20 | 21 | -------------------------------------------------------------------------------- /Review/RecursiveBrackets.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a RECURSIVE function that performs the same 3 | functionality as the function in Brackets.py. 4 | ''' 5 | 6 | def find_balance(s): 7 | ''' 8 | Takes a string of brackets as an argument. Will return 9 | True or False, depending on whether or not the string 10 | is balanced. An empty string is balanced. 11 | 12 | find_balance("}}}{") -> False 13 | find_balance("{}{}") -> True 14 | ''' 15 | pass 16 | 17 | ''' 18 | Note: There are no tests included in this file. Use the 19 | tests you've written in CreateTest.py to test your code. 20 | ''' -------------------------------------------------------------------------------- /Week_3/Tuple_Examples.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Here, we'll play around with Tuples! 3 | ''' 4 | 5 | # Tuple Functions Demo 6 | 7 | if __name__ == "__main__": 8 | # Create a tuple 9 | my_tuple = (1, 2, 3, 2, 4, 2) 10 | 11 | # How man times does 2 occur? 12 | count_of_twos = my_tuple.count(2) 13 | print("Count of 2 in the tuple:", count_of_twos) 14 | 15 | # Find the index of 3 16 | index_of_two = my_tuple.index(3) 17 | print("First index of 3 in the tuple:", index_of_two) 18 | 19 | # Tuple unpacking 20 | a, b = (1, 2) 21 | print("Unpacked values: a =", a, ", b =", b) 22 | 23 | -------------------------------------------------------------------------------- /Week_9/CKCS_Examples/Write_File.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Here, we're going to open a file in write mode and write content to it. 3 | ''' 4 | if __name__ == "__main__": 5 | # The w stands for write 6 | # It will create a file if it doesn't exist! 7 | with open('topics.txt', 'w') as output_file: 8 | output_file.write("Computer Science") 9 | 10 | # a is for append, which will tack stuff onto the end of a file! 11 | with open('topics.txt', 'a') as output_file: 12 | output_file.write(" is rewarding!") 13 | 14 | with open('topics.txt', 'r') as output_file: 15 | contents = output_file.read() 16 | print(contents) 17 | -------------------------------------------------------------------------------- /Week_10/More_Lambdas.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Here we look at lambdas! Don't be intimidated by their name 3 | or syntax. They're just basic functions we define in-line. 4 | ''' 5 | if __name__ == "__main__": 6 | # We can assign it to a variable! 7 | add = lambda x, y: x + y 8 | print(add(2, 3)) 9 | 10 | # Or we can use them in place like with the sorted function 11 | a_tuple_list = [(2, 3), (1, 5), (9, 0)] 12 | # Let's sort it by the second element 13 | # x is the argument, which is our inner element, and the index 14 | # is what we're sorting it by 15 | new_list = sorted(a_tuple_list, key=lambda x: x[1]) 16 | print(new_list) -------------------------------------------------------------------------------- /Week_5/For_With_Break.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Break statements will stop a loop in its tracks. Furthermore, 3 | if you have an inner and an outer loop, a break in the inner 4 | loop will only stop the inner loop! 5 | ''' 6 | 7 | if __name__ == "__main__": 8 | new_list = ["Banana", "Strawberry", "Kiwi", "Guava", "Mango", "Pineapple", "Watermelon"] 9 | 10 | for fruit in new_list: 11 | for letter in fruit: 12 | # This will only break us out of this inner loop 13 | if letter == "i": 14 | break 15 | print(letter, end=" ") 16 | else: 17 | print("\nThis fruit doesn't have an i in it!") 18 | print() # prints a new line -------------------------------------------------------------------------------- /Week_11/ExampleOne.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def recurse_dict(name_list, re_dict): 4 | 5 | if len(name_list) == 1: 6 | re_dict[name_list[0]] = random.randint(1, 100) 7 | return recurse_dict 8 | else: 9 | re_dict[name_list[0]] = random.randint(1, 100) 10 | recurse_dict(name_list[1:], re_dict) 11 | 12 | return re_dict 13 | 14 | if __name__ == "__main__": 15 | user_list = [] 16 | 17 | for i in range(1, 10): 18 | user_list.append(input("Please enter a name: ")) 19 | 20 | new_dict = {} 21 | 22 | new_dict = recurse_dict(user_list, new_dict) 23 | 24 | print(new_dict) -------------------------------------------------------------------------------- /Week_9/Random_Array.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | ''' 4 | Let's use random to create a miltidimensional array (list) 5 | ''' 6 | if __name__ == "__main__": 7 | # This is necessary. You can't get random numbers 8 | # without seeding it first 9 | random.seed() 10 | 11 | our_dimension = random.randint(0, 10) 12 | our_matrix = [] 13 | 14 | # It's really just nested lists, I promise 15 | for d in range(our_dimension): 16 | our_matrix.append([]) 17 | for i in range(our_dimension): 18 | our_matrix[-1].append(random.randint(-10, 10)) 19 | print(our_matrix[-1]) 20 | 21 | print(our_matrix) -------------------------------------------------------------------------------- /Review/StringConcat.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | ''' 3 | Assume s is a string. Write a function that returns 4 | a new string formed by concatenating i copies of each 5 | letter at position i. Recall, i is any given index in 6 | a string or list. 7 | 8 | Here is an example: 9 | 10 | string_concat('dog') returns 'ogg' since 0 of 'd' and 1 11 | of 'o' and 2 of 'g'. 12 | 13 | Then, write four tests for this function. At least ONE 14 | should be an edge case. 15 | ''' 16 | 17 | 18 | def string_concat(s) : 19 | pass 20 | 21 | class StringTests(unittest.TestCase): 22 | pass 23 | 24 | if __name__=='__main__': 25 | unittest.main(exit=True) 26 | -------------------------------------------------------------------------------- /Week_2/Lecture_Two.py: -------------------------------------------------------------------------------- 1 | age = 25 2 | print("I am " + str(age) + " years old") 3 | 4 | a = 13 5 | b = 15 6 | c = 13 7 | 8 | print(a < b) 9 | print(a < c) 10 | 11 | print(a != b and b != c) 12 | 13 | print(not (a == c)) 14 | 15 | print((a != c or b != c) and a == b) 16 | 17 | if a > b or not (c == b) and (a > c or b > c): 18 | print("First condition!") 19 | elif a == b: 20 | print("Second condition!") 21 | elif c == b: 22 | print("Third condition!") 23 | elif a != c: 24 | print("Fourth condition!") 25 | else: 26 | print("Else condition!") 27 | 28 | 29 | d = "HELLO" 30 | e = "World" 31 | f = "hello" 32 | 33 | print(d == f) 34 | print(d < f) -------------------------------------------------------------------------------- /Week_11/Car_Tests.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import Car_Class 3 | 4 | class CarTests(unittest.TestCase): 5 | def setUp(self): 6 | self.car_one = Car_Class.car("Honda Civic", "Red", 14000) 7 | def test1(self): 8 | car_two = Car_Class.car("Toyota RAV4", "Green", 14000) 9 | self.assertEqual(Car_Class.compare_price(self.car_one, car_two), True) 10 | def test2(self): 11 | car_three = Car_Class.car("Chrysler Malibu", "Blue", 9000) 12 | self.assertNotEqual(Car_Class.compare_price(self.car_one, car_three), True) 13 | 14 | if __name__ == '__main__': 15 | unittest.main(exit=True) # invokes the unit tests and exits -------------------------------------------------------------------------------- /Review/String_Examples.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | string_a = "Hello!" 3 | string_b = "World!" 4 | 5 | string_a = string_a + string_b 6 | string_b = string_b.upper() 7 | 8 | print(string_a) 9 | print(string_b) 10 | 11 | new_string = " My mom told me to get \"apples\" please?" 12 | stripped_string = new_string.strip() 13 | print(stripped_string) 14 | split_string = new_string.split() 15 | print(split_string) 16 | joined_string = "_".join(split_string) 17 | print(joined_string) 18 | 19 | print(new_string[::-1]) 20 | 21 | print(joined_string + str(10)) 22 | 23 | int_a = int("10") 24 | -------------------------------------------------------------------------------- /Week_4/Grade_Dict.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | # Creating a dictionary 3 | grade_dict = {"John" : [99, 86, 90, 80], 4 | "David" : [100, 75, 80, 82], 5 | "Harsimran" : [60, 99, 79, 100], 6 | "Jatin" : [98, 99, 100, 80] 7 | } 8 | 9 | # Adding new key-value pairs to the dictionary 10 | grade_dict["Yanis"] = [80, 81, 79, 90] 11 | grade_dict["Moaed"] = [85, 85, 85, 85] 12 | 13 | # Changing a value in an existing key-value pair 14 | grade_dict["David"].append(90) 15 | 16 | for key in grade_dict: 17 | print(key, "'s grades are: ", grade_dict[key]) 18 | -------------------------------------------------------------------------------- /Week_5/More_Dicts.py: -------------------------------------------------------------------------------- 1 | 2 | ''' 3 | Prompts the user for keys, then values. 4 | ''' 5 | def make_dict(): 6 | inp = "" 7 | # Syntax for creating a dictionary! 8 | # Notice the squiggly brackets. 9 | 10 | our_dict = {} 11 | while inp != "Stop!": 12 | inp = input("Please enter a store: ") 13 | inp_prod = input("Now please enter what product they sell: ") 14 | # Creates a key and associated value 15 | our_dict[inp] = inp_prod 16 | inp = input("Would you like to continue? Type 'Stop!' to stop. ") 17 | 18 | return our_dict 19 | 20 | if __name__ == "__main__": 21 | print(make_dict()) 22 | print("Goodbye!") -------------------------------------------------------------------------------- /Week_3/Function_And_While.py: -------------------------------------------------------------------------------- 1 | def make_new_string(string): 2 | print("??" + string + "!!") 3 | 4 | if __name__ == "__main__": 5 | # Notice how inp stays the same so the while loop can check it, 6 | # despite the fact that the function manipulates it? 7 | # Part of the reason is because the changes to inp are local only to the function. 8 | # The other part of the reason is strings are immutable, so these changes 9 | # just create a new string, instead of editing the old one. 10 | inp = "" 11 | while (inp != "end"): 12 | inp = str(input("Please enter a word:\n")) 13 | if not (inp == "end"): 14 | make_new_string(inp) -------------------------------------------------------------------------------- /Review/Brackets.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file is just for the CreateTest.py file. You do not need 3 | to implement anything in this file. 4 | ''' 5 | 6 | def find_balance(s): 7 | ''' 8 | Takes a string of brackets as an argument. Will return 9 | True or False, depending on whether or not the string 10 | is balanced. An empty string is balanced. 11 | 12 | find_balance("}}}{") -> False 13 | find_balance("{}{}") -> True 14 | ''' 15 | counter = 0 16 | for ch in s: 17 | if ch == "{": 18 | counter += 1 19 | else: 20 | counter -=1 21 | if counter < 0: 22 | break 23 | 24 | return counter == 0 -------------------------------------------------------------------------------- /Week_3/Binary_Strings.py: -------------------------------------------------------------------------------- 1 | # A short example converting to binary strings 2 | # Why? 3 | 4 | # ¯\_(ツ)_/¯ 5 | 6 | if __name__ == "__main__": 7 | 8 | my_input = 0 9 | 10 | while my_input != -1: 11 | my_input = int(input("Enter a number you want to see in binary!\n")) 12 | if my_input >= 0: 13 | # The bin function gives us the binary representation of positive 14 | # integers in Python. 15 | print(bin(my_input)) 16 | else: 17 | print("This should be done in C.") # Ask me why lol 18 | # Hint: Python doesn't have much of a notion of signed vs. unsigned ints. 19 | 20 | print("Goodbye!") -------------------------------------------------------------------------------- /Week_9/Lambda_Example.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Here is an example of a lambda, which is an in-line, short, anonymous 3 | function. 4 | ''' 5 | if __name__ == "__main__": 6 | sum_of_squares = lambda x, y: x*x + y*y 7 | print(sum_of_squares(3, 8)) 8 | print(sum_of_squares(2, 2)) 9 | 10 | sum_of_squares = 10 11 | print(sum_of_squares) 12 | 13 | reversed_str = lambda a_str: a_str[::-1] 14 | print(reversed_str("hello")) 15 | print(reversed_str("Cassandra")) 16 | 17 | reversed_str = "eip" 18 | print(reversed_str) 19 | 20 | another_math_example = lambda x, y, z: x * y * z 21 | another_var = another_math_example(1, 2, 3) 22 | print(another_var) -------------------------------------------------------------------------------- /Week_9/CKCS_Examples/Coords.py: -------------------------------------------------------------------------------- 1 | # Final exercise, let's open up the coordinates .txt file and plot it! 2 | import matplotlib.pyplot as plt 3 | 4 | if __name__ == "__main__": 5 | x_coords = [] 6 | y_coords = [] 7 | 8 | # Opening our file in read mode 9 | coord_file = open("./coordinates.txt", "r") 10 | 11 | for line in coord_file: 12 | c_lst = line.split() 13 | x_coords.append(c_lst[0]) 14 | y_coords.append(c_lst[1]) 15 | 16 | coord_file.close() 17 | 18 | plt.plot(x_coords, y_coords, 'g^') 19 | plt.title("Trend Graph") 20 | plt.xlabel("Value") 21 | plt.ylabel("Frequency") 22 | # Saves the figure to your active directory 23 | plt.savefig('linechart') 24 | plt.show() -------------------------------------------------------------------------------- /Week_2/CKSC_Examples/CKCS149_Lecture_2.py: -------------------------------------------------------------------------------- 1 | var_one = 11 2 | var_two = 12 3 | 4 | print(f"The value of these variables are {var_one} and {var_two}") 5 | 6 | var_three = "Hello, world!" 7 | var_four = var_three.lower() # Makes all the letters lower 8 | var_five = var_three.upper() # Makes all the letter upper case! 9 | 10 | print(f"Our strings are {var_four} and {var_five}") 11 | print(var_three) 12 | 13 | print(var_three[0]) 14 | print(var_three[-1]) 15 | print(var_three[3]) 16 | 17 | sliced_variable = var_five[2:10] 18 | print(sliced_variable) 19 | 20 | str_one = "apple" 21 | str_two = "anana" 22 | 23 | print(str_one > str_two) 24 | 25 | new_str = str_two.split("a") 26 | print(new_str) -------------------------------------------------------------------------------- /Week_5/Read_JSON.py: -------------------------------------------------------------------------------- 1 | import json 2 | ''' 3 | In order to use json functionality, we need to import 4 | the json library. 5 | ''' 6 | 7 | if __name__ == "__main__": 8 | # Load the spooky data from the JSON file 9 | with open('Spooky.json', 'r') as file: 10 | spooky_locations = json.load(file) 11 | 12 | # Display the haunted locations 13 | for location in spooky_locations['haunted_locations']: 14 | if location['haunting']: 15 | print(f"Beware! {location['name']} in {location['location']} has {location['ghosts']} ghosts haunting it!") 16 | else: 17 | print(f"{location['name']} in {location['location']} seems safe... for now.") 18 | -------------------------------------------------------------------------------- /Week_4/Loop_In_Function.py: -------------------------------------------------------------------------------- 1 | # Let's look at a for loop in a function! 2 | 3 | # For loops can work anywhere in a program so long as they're correctly written 4 | def for_loop_here(num): 5 | x = 1 6 | for i in range(num): 7 | # x = x + i 8 | x+=i 9 | print("x is now: ", x) 10 | return x 11 | 12 | if __name__ == "__main__": 13 | item = 5 14 | # Remember, you can skip extra lines by using the function and its argument(s) 15 | # as arguments for other functions, like print! 16 | # Also remember that you have to cast it to a string if you want to concatonate a string this way 17 | a = for_loop_here(item) 18 | print("Our number is: " + str(a)) -------------------------------------------------------------------------------- /Week_5/List_Comprehension.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file just explores some of the functionalities we covered 3 | last week combined with list comprehensions! 4 | 5 | List comprehension allows you to create a list based off another 6 | iterable (such as a range, another list, etc.) 7 | ''' 8 | 9 | if __name__ == "__main__": 10 | # We cannot escape the fruit list 11 | fruit_list = ["Strawberry", "Blueberry", "Grape", "Banana"] 12 | 13 | # List Comprehensions require an expression that evaluates 14 | # then populates each element of your name list. 15 | new_list = [fruit.upper() for fruit in fruit_list] 16 | print(new_list) 17 | 18 | second_new_list = [num * 10 for num in range(10)] 19 | print(second_new_list) -------------------------------------------------------------------------------- /Week_9/Brackets_Tests.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import Balanced_Brackets 3 | 4 | class my_tests(unittest.TestCase): 5 | def test1(self): 6 | self.assertEqual(Balanced_Brackets.count_brackets("{{}}"), True) 7 | def test2(self): 8 | self.assertEqual(Balanced_Brackets.count_brackets("}}{{"), False) 9 | def test3(self): 10 | self.assertEqual(Balanced_Brackets.count_brackets("}}}}"), False) 11 | def test4(self): 12 | self.assertEqual(Balanced_Brackets.count_brackets("{}{}{}{}"), True) 13 | def test5(self): 14 | self.assertEqual(Balanced_Brackets.count_brackets("{{}}{}{{}}"), True) 15 | 16 | 17 | if __name__ == '__main__': 18 | unittest.main(exit=True) -------------------------------------------------------------------------------- /Week_2/CKSC_Examples/CKCS_If.py: -------------------------------------------------------------------------------- 1 | a = 10 2 | b = 5 3 | c = 2 4 | # Conditional logic! Built off our boolean understanding 5 | if a < b: 6 | print("Success!") 7 | elif a % b == 0: 8 | print("Special success!") 9 | elif a / b == 3: 10 | print("Another special statement!") 11 | else: 12 | print("Not successful!") 13 | 14 | # More complex conditions 15 | # Or requires at least one of the conditions to be true 16 | if (a == b) or (c != b): 17 | print("Complex condition one!") 18 | # and requires both conditions on either side of it to be true 19 | elif (c == b) and (c % 2 == 0): 20 | print("Complex condition two!") 21 | # not flips true -> false and false -> true 22 | elif not c == b: 23 | print("Not condition!") -------------------------------------------------------------------------------- /Week_5/While_With_Else.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In this file, we're looking at a while loop with an else and a 3 | continue statement. 4 | 5 | An else after a loop will only execute of the loop does not exit 6 | prematurely. 7 | 8 | A continue statement will force a loop to its next iteration! 9 | ''' 10 | 11 | if __name__ == "__main__": 12 | new_list = ["Banana", "Strawberry", "Kiwi", "Guava", "Mango", "Pineapple", "Watermelon"] 13 | count = -1 14 | while count < len(new_list) - 1: 15 | count+=1 16 | if count % 3 == 0: 17 | # This will force us to the next iteration of our while loop! 18 | continue 19 | print(f"The fruit at index {count} is {new_list[count]}") 20 | else: 21 | print("Finished the fruit loop!") -------------------------------------------------------------------------------- /Week_1/Boolean_Examples.py: -------------------------------------------------------------------------------- 1 | # One more example. Let's deal with OR and AND 2 | 3 | # These just check the true status of whatever is on either side of the operator. 4 | 5 | print(True and False) # Will return False because the second condition is false! 6 | 7 | print(not(True) and True) # Will return False because of the negation. 8 | 9 | # You can assign these to variables like any other datatype. 10 | x = False 11 | y = True 12 | 13 | # Do you know what this will print off? 14 | print((x and y) or (y and y)) 15 | 16 | # You can, in principle, string as many of these together as your heart desires. 17 | 18 | print(x or y and y or x) # Hehe you just have to keep your logic in check. I would reccomend using brackets. -------------------------------------------------------------------------------- /Week_11/Bank_Account.py: -------------------------------------------------------------------------------- 1 | ''' 2 | More Class Examples! 3 | ''' 4 | class BankAccount: 5 | # This is a class attribute! 6 | total_accounts = 0 7 | 8 | def __init__(self, balance): 9 | self.balance = balance 10 | BankAccount.total_accounts += 1 11 | 12 | @property 13 | def USD(self): 14 | return self.balance * 0.72 15 | 16 | @USD.setter 17 | def USD(self, value): 18 | self.balance = value * 0.72 19 | 20 | def __add__(self, other): 21 | return BankAccount(self.balance + other.balance) 22 | 23 | 24 | if __name__ == "__main__": 25 | ba = BankAccount(1000) 26 | print(ba.USD) 27 | 28 | ba.USD = 8000 29 | 30 | print(ba.balance) -------------------------------------------------------------------------------- /Week_5/Recursion_0.py: -------------------------------------------------------------------------------- 1 | # Let's write a very basic recursive function. 2 | # Remember, a recursive function is just a function that calls itself 3 | # somewhere in its code. 4 | 5 | # This function will do one of two things 6 | # If num is odd, it will recursively call itself on the next lowest number. 7 | # If the number is even, it will return a new number which is num * 2 8 | def our_recursion(num): 9 | new_num = 0 10 | if(num % 2 != 0): 11 | new_num = our_recursion(num - 1) 12 | else: 13 | # Base case is an even num 14 | new_num = num * 2 15 | 16 | return new_num 17 | 18 | 19 | if __name__ == "__main__": 20 | 21 | rec_call = our_recursion(3) 22 | print(rec_call) 23 | -------------------------------------------------------------------------------- /Week_11/Classes/ExampleOne.py: -------------------------------------------------------------------------------- 1 | '''Here is our first example of what a BAD program looks like''' 2 | 3 | # First problem: we have a variable named after its data type 4 | # Stop doing this. This is not only bad practice but will often 5 | # times lead to unpredictable behaviour. Not only that, other 6 | # languages simply don't allow it. 7 | 8 | # Second problem: list and the succeeding for-loop are sitting in 9 | # the ether. 10 | list = input("Enter a bunch of words seperated by spaces.").split() 11 | 12 | for i in list: 13 | print(i) 14 | 15 | # Not only are the list and for-loop sitting in the ether, the main is 16 | # sitting here and doing nothing. We use the main for a reason! 17 | if __name__ == "__main__": 18 | pass -------------------------------------------------------------------------------- /Week_9/Fruity_Recursion.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def recurse_fruit(fruits, fruity_dict): 4 | 5 | if len(fruits) == 0: 6 | return 7 | elif len(fruits) == 1: 8 | fruity_dict[fruits[0]] = random.randint(0, 20) 9 | else: 10 | temp = int(len(fruits)/2) - 1 11 | recurse_fruit(fruits[:temp], fruity_dict) 12 | recurse_fruit(fruits[temp:], fruity_dict) 13 | 14 | return fruity_dict 15 | 16 | if __name__ == "__main__": 17 | 18 | fruit_list = [] 19 | for i in range(0, 5): 20 | fruit_list.append(input("Please enter a fruit: ")) 21 | 22 | fruit_dict = {} 23 | 24 | fruit_dict = recurse_fruit(fruit_list, fruit_dict) 25 | 26 | print(fruit_dict) -------------------------------------------------------------------------------- /Week_4/Nested_Loop.py: -------------------------------------------------------------------------------- 1 | # I would label these files with more meaningful names but then 2 | # you wouldn't read through all of them :P 3 | 4 | # This example shows us two things 5 | # First, how a for loop would iterate over not one, but two strings. 6 | # It also shows us a nested for loop, as in, theres a for loop inside a for loop. 7 | # Notice how in the second for loop, it still knows what value i is? 8 | # i is local to the top most for loop. Once that outer loop is terminated, 9 | # then it will no longer know what i is. 10 | if __name__ == "__main__": 11 | str_one = "Gibberish?" 12 | str_two = "Perish the thought!" 13 | 14 | for i in str_one: 15 | for j in str_two: 16 | print(i + j, end = '\t') 17 | -------------------------------------------------------------------------------- /Week_9/CKCS_Examples/Try_Except.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Try/except blocks allow you to create exception handling. You can deal 3 | with errors, exceptions and generally funky behaviour! 4 | ''' 5 | 6 | if __name__ == "__main__": 7 | # Basic try/except example 8 | try: 9 | # Attempt to convert user input to an integer 10 | number = int(input("Enter a number: ")) 11 | print(f"You entered the number: {number}") 12 | except ValueError: 13 | # Handle the case where input is not a valid integer 14 | print("That's not a valid number! Please try again.") 15 | except TypeError: 16 | print("How did you even get this??") 17 | # Finally will run regardless of whether an exception happens 18 | finally: 19 | print("This is the finally block!") -------------------------------------------------------------------------------- /Week_3/Backward_String.py: -------------------------------------------------------------------------------- 1 | # This example is just to remind you guys how functions are called in Python. 2 | def backward_string(my_string): 3 | new_string = my_string[::-1] 4 | return new_string 5 | 6 | # This shows a function that takes two arguments 7 | def multiply_string(string_1, mulitplier): 8 | newer_string = string_1 * mulitplier 9 | return newer_string 10 | 11 | if __name__ == "__main__": 12 | inp = "temp" 13 | 14 | while inp != "": 15 | inp = input("Enter a string to reverse:\n") 16 | if inp != "": 17 | i = int(input("How many times should it be repeated?\n")) 18 | print(backward_string(inp)) 19 | print(multiply_string(inp, i)) 20 | 21 | print("Good bye") -------------------------------------------------------------------------------- /Review/SentenceTokens.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | ''' 3 | Assume that sentence is a valid string. Write a function 4 | which returns a list of all the words in sentence, where a 5 | word is a tokenseparated by white space. Then for each word, 6 | make it lowercase and remove any character that is not 7 | alpha-numeric (a-z or 0-9). 8 | 9 | For example, 10 | sentence_splitter('Red@Dragon....ca is great!') 11 | should return ['reddragonca', 'is', 'great'] 12 | 13 | Then, write five tests for this function. At least ONE should 14 | be an edge case. 15 | ''' 16 | 17 | def sentence_splitter(sentence) : 18 | pass 19 | 20 | 21 | class SentenceTests(unittest.TestCase): 22 | pass 23 | 24 | if __name__=='__main__': 25 | unittest.main(exit=True) 26 | -------------------------------------------------------------------------------- /Week_10/Funcs_Ex.py: -------------------------------------------------------------------------------- 1 | # Basic function 2 | def greeting(): 3 | return "Hello!" 4 | 5 | def call_twice(func): 6 | print(func()) 7 | print(func()) 8 | 9 | def create_greeting(): 10 | def a_greeting(arg): 11 | return f"This is a greeting, {arg}" 12 | return a_greeting 13 | 14 | if __name__ == "__main__": 15 | # Assigning a function to a variable, thus 16 | # creating a function object. 17 | var = greeting 18 | # Print the variable's location in memory 19 | print(var) 20 | # Invoking the function 21 | print(var()) 22 | # Function as an argument for another function 23 | call_twice(var) 24 | call_twice(greeting) 25 | # Storing a returned function in a function object 26 | func_object = create_greeting() 27 | print(func_object("Cass")) -------------------------------------------------------------------------------- /Week_10/Scope.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This file will demonstrate various kinds of scopes! Play around with 3 | this file, and check where and when variables die. 4 | ''' 5 | 6 | # y is global to this file and anything that imports it 7 | y = 20 8 | 9 | def foo(): 10 | # x is local to foo 11 | x = 10 12 | print(x, y) 13 | 14 | # If you have a global variable and need to modify it, 15 | # you can use the global keyword 16 | def modify_global(): 17 | global y 18 | y = 30 19 | 20 | 21 | # Enclosing or nonlocal scope. Notice that the inner function 22 | # can access the outer variable? 23 | def outer(): 24 | z = 10 25 | def inner(): 26 | nonlocal z 27 | z = 20 28 | inner() 29 | print(z) # 20 30 | 31 | 32 | 33 | if __name__ == "__main__": 34 | outer() -------------------------------------------------------------------------------- /Week_5/Spooky_File_Read.py: -------------------------------------------------------------------------------- 1 | '''Write a program that reads the lyrics from the .txt 2 | into a list. Then, print off the elements of the list 3 | one at a time, with every fifth line intended with the 4 | tab character.''' 5 | 6 | def read_lyrics(file): 7 | lyric_list = [] 8 | with open(file, 'r') as f: 9 | for line in f: 10 | lyric_list.append(line) 11 | 12 | #counter = 1 13 | for lyric in range(len(lyric_list)): 14 | if (lyric + 1) % 5 == 0: 15 | print("\t", lyric_list[lyric], end="") 16 | #counter = 1 17 | else: 18 | print(lyric_list[lyric], end="") 19 | #counter = counter + 1 20 | 21 | if __name__ == "__main__": 22 | read_lyrics("Season_Of_The_Witch.txt") -------------------------------------------------------------------------------- /Week_9/List_Frequency.py: -------------------------------------------------------------------------------- 1 | def mostfrequent(L) : 2 | ''' 3 | Assume that L is a non-empty list. 4 | Return the number which is most frequent in the list. 5 | For example, 6 | mostfrequent([5, 2, 9, 2, 9, 1, 18, 9, 3]) would return 9, since 7 | there are three 9's, and two 2's, and one of other values. 8 | ''' 9 | maximum = 0 10 | maximum_count = 1 11 | 12 | for i in L: 13 | temp_count = 0 14 | for j in L: 15 | if i == j: 16 | temp_count = temp_count + 1 17 | if temp_count >= maximum_count: 18 | maximum = i 19 | maximum_count = temp_count 20 | 21 | return maximum 22 | 23 | if __name__ == "__main__": 24 | print(mostfrequent([5, 2, 9, 2, 9, 1, 18, 9, 3])) -------------------------------------------------------------------------------- /Week_9/Mem_Fib.py: -------------------------------------------------------------------------------- 1 | # This works because dictionaries are mutable. 2 | # Mutable data types are changed in function calls 3 | # and those changes persist because everything in python 4 | # is "Pass by reference". 5 | def memoized_fib(n, memo={}): 6 | # the memo={} syntax is a default argument 7 | if n in memo: 8 | return memo[n] 9 | elif n <= 1: 10 | return n 11 | else: 12 | # Creating a key-value pair for our dictionary and 13 | # also passing it along to our two recursive calls. 14 | # That way, we can persist results across function calls. 15 | memo[n] = memoized_fib(n - 1, memo) + memoized_fib(n - 2, memo) 16 | return memo[n] 17 | 18 | 19 | if __name__ == "__main__": 20 | print(memoized_fib(80)) 21 | -------------------------------------------------------------------------------- /Week_1/Basic_Example.py: -------------------------------------------------------------------------------- 1 | # Our very first python example! 2 | # Adding the pound sign (hashtag) in front of a line comments it out 3 | # That means that when the machine reads your code, it will ignore everything 4 | # on the line after the hashtag. 5 | 6 | # To "run" this program (in a text editor such as VSCode or in your terminal/command line) 7 | # type in "Example_One.py" and hit Enter. It won't read out any of the text printed out. 8 | 9 | print("This is how you print a line") 10 | 11 | # Notice how after the word print the line we actually want to print is in brackets? 12 | # What is in those brackets is called an "Argument". 13 | # An argument is what you put in a function to make it do what you like. 14 | # In Python 3 (the version we're working in), print is a function. -------------------------------------------------------------------------------- /Week_4/Function_In_Loop.py: -------------------------------------------------------------------------------- 1 | # This example shows us two things: 2 | # First, that you can call a function within a for loop (very important!) 3 | # and second, the syntax for iterating over a range of numbers in python. 4 | 5 | # Notice how this function has no return statement, but a print statement? 6 | # Python functions treat print statements as return statements if no other return 7 | # statements exist in the function. 8 | def count(num): 9 | print(num + 1) 10 | 11 | if __name__ == "__main__": 12 | # This is pretty intuitive! All it does is iterate over the numbers 13 | # 1 to 10 and feeds them into our count function. You'll notice that 14 | # the computer knows to increment n by 1 for every pass of the loop. 15 | for n in range(10): 16 | count(n) -------------------------------------------------------------------------------- /Week_5/Binary_Search.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This program will help us understand binary search! 3 | Remember, binary search only really works on sorted data. 4 | ''' 5 | 6 | # I like to think of binary search as finding the drain, 7 | # then circling it. 8 | def binary_search(arr, target): 9 | left, right = 0, len(arr) - 1 10 | result = -1 11 | while left <= right and result == -1: 12 | mid = (left + right) // 2 # Floor division 13 | if arr[mid] == target: 14 | result = mid 15 | elif arr[mid] < target: 16 | left = mid + 1 17 | else: 18 | right = mid - 1 19 | return result 20 | 21 | if __name__ == '__main__': 22 | arr = [10, 20, 30, 40, 50] 23 | target = 30 24 | print(binary_search(arr, target)) # Output: 2 -------------------------------------------------------------------------------- /Week_1/Hello_World.py: -------------------------------------------------------------------------------- 1 | # Now let's do the classic opening program whenever we learn a new language. 2 | # Let's tell the computer to print "Hello, world!" to our terminal. 3 | # Remember: the terminal is that funky looking window/blinking cursor where your text 4 | # is fed out. 5 | 6 | print("Hello, world!\n") 7 | 8 | # Notice the '\n' at the end of the line? That's how the computer knows to go to the 9 | # next line of text. That way, you don't have everything printing off on one line! 10 | # It is known as the "newline character". 11 | 12 | # However, when you run this program, you'll notice that it will skip a line, 13 | # leaving a blank line after our "Hello, world!" output. 14 | # That's because the print function in Python 3 automatically puts a newline character at the end of strings. -------------------------------------------------------------------------------- /Week_11/Manga_Exercise.py: -------------------------------------------------------------------------------- 1 | import Book_Exercise as BE 2 | ''' 3 | Can represent manhua/manwha. 4 | ''' 5 | class Manga(BE.Book): 6 | def __init__(self, t = None, a = None, 7 | g = None, p = None, pl = None, c = None, o = None): 8 | super().__init__(t, a, g, p, pl) 9 | self.is_colour = c 10 | self.origin_country = o 11 | 12 | def __str__(self): 13 | return f"Title: {self.title}\nAuthor: {self.author}\nOrigin: {self.origin_country}" 14 | 15 | def has_anime(self, number_sold): 16 | return number_sold >= 1000000 17 | 18 | if __name__ == "__main__": 19 | a_manga = Manga("Uzumaki", "Junji Ito", "Horror", "Dark Horse", 20 | 300, False, "Japan") 21 | 22 | print(a_manga) 23 | print(a_manga.has_anime(10000)) 24 | -------------------------------------------------------------------------------- /Week_1/Lecture_One.py: -------------------------------------------------------------------------------- 1 | # Creating our first variable and storing the result of 2 | # this mathematical operator! 3 | variable_one = 7 + (2 * 3) ** 2 / 4 4 | variable_two = variable_one + 10 5 | int_divison = 9//4 6 | big_operation = (8 + 2) * (5 - 3) ** 2 7 | string_add = "String one and " + "string two!" 8 | 9 | # Invoking the print statement! This shows output 10 | # to our user! 11 | print("Hello!") 12 | # We can print off variable values 13 | print(variable_one) 14 | print(variable_two) 15 | print(int_divison) 16 | print(big_operation) 17 | # We can print off the result of operations directly! 18 | print(9/4) 19 | 20 | # This is us overwriting variable_two! There is still one 21 | # instance of this variable. It just now has a new value. 22 | variable_two = "Overwritten!" 23 | print(variable_two) 24 | print(string_add) -------------------------------------------------------------------------------- /Review/EvenAddition.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | ''' 3 | Returns the sum of the even numbers from n to 4*n, inclusive 4 | even_addition(2) returns 20 since 2, 3, 4, 5, 6, 7, 8 -> 2 + 4 + 6 + 8 = 20 5 | Do NOT assume that this function recieves a positive number, but do assume 6 | that it recieves an integer. 7 | ''' 8 | 9 | def even_addition(n) : 10 | pass 11 | 12 | class myTests(unittest.TestCase): 13 | def test1(self): 14 | self.assertEqual(even_addition(2), 20) 15 | def test2(self): 16 | self.assertEqual(even_addition(1), 6) 17 | def test3(self): 18 | self.assertEqual(even_addition(0), 0) 19 | def test4(self): 20 | self.assertEqual(even_addition(100), 37750) 21 | 22 | if __name__=='__main__': 23 | print(even_addition(2), 'Expect 20') 24 | unittest.main(exit=True) 25 | -------------------------------------------------------------------------------- /Review/AlexMidtermQuestionBank/q8-2.py: -------------------------------------------------------------------------------- 1 | def equalPairs(a,b,c,d): 2 | ''' 3 | Assume a, b, c and, d are all integers. 4 | Return True if the integers can be split into two pairs 5 | that equal each other when added together. 6 | 7 | For example (12,2,6,8) would return true, as 8 | 12+2 = 14 and 6+8 = 14 9 | ''' 10 | pass 11 | 12 | 13 | class equalPairsTests(unittest.TestCase): 14 | def test1(self): 15 | self.assertEqual(equalPairs(12,8,6,2), True) 16 | def test2(self): 17 | self.assertEqual(equalPairs(12,3,6,8), False) 18 | def test3(self): 19 | self.assertEqual(equalPairs(12,12,12,12), True) 20 | def test3(self): 21 | self.assertEqual(equalPairs(6,10,14,10), True) 22 | def test3(self): 23 | self.assertEqual(equalPairs(1,2,8,12), False) -------------------------------------------------------------------------------- /Review/MatrixCheck.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | ''' 3 | Assume that matrix is a 2D array of integers. 4 | Write a function that returns True if the second 5 | last number of the second row occurs in any other rows. 6 | 7 | For example, 8 | matrix_check([[5, 6, 7, 2], [9, 8, 4, 22]]) -> False 9 | matrix_check([[7, 6, 9, 2], [9, 4, 7, 22], [7, 1, 6, 99]]) -> True 10 | 11 | Hint: use negative indicies for this one. 12 | ''' 13 | 14 | def matrix_check(matrix) : 15 | pass 16 | 17 | class MatrixTests(unittest.TestCase): 18 | def test1(self): 19 | m = [[5, 6, 7, 2], [9, 8, 4, 22]] 20 | self.assertFalse(matrix_check(m)) 21 | def test2(self): 22 | m = [[7, 6, 9, 2], [9, 4, 7, 22], [7, 1, 6, 99]] 23 | self.assertTrue(matrix_check(m)) 24 | 25 | if __name__=='__main__': 26 | unittest.main(exit=True) -------------------------------------------------------------------------------- /Week_11/Classes/ExampleThreeCorrect.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | # Notice how the FIRST THING I do in my program is import the necessary 3 | # library and I only import it once. 4 | 5 | '''This is how you correctly design a program. You write the tests FIRST.''' 6 | 7 | def our_function(a, b): 8 | '''A function that multiples a and b.''' 9 | pass 10 | 11 | class MyTests(unittest.TestCase): 12 | def test1(self): 13 | self.assertEqual(our_function(0, 0), 0) 14 | def test2(self): 15 | self.assertEqual(our_function(2, 3), 6) 16 | def test3(self): 17 | self.assertEqual(our_function(3, 3), 9) 18 | def test4(self): 19 | self.assertEqual(our_function(-1, 9), -9) 20 | def test5(self): 21 | self.assertEqual(our_function(-1, -1), 1) 22 | 23 | if __name__ == "__main__": 24 | unittest.main(exit=True) -------------------------------------------------------------------------------- /Week_5/Break_Statements.py: -------------------------------------------------------------------------------- 1 | def find_element_in_list(required, ls): 2 | for item in ls: 3 | # the item we're looking for 4 | if item == required: 5 | print("Item found!") 6 | break 7 | else: 8 | print("Item isn't yet found!") 9 | else: 10 | # Logic that will only execute if the loop does not terminate early 11 | print("Item not found in list.") 12 | 13 | def weather_report(weather): 14 | while weather.lower() == "snow": 15 | print("Stay inside and stay warm!") 16 | weather = str(input("What is the weather like now? ")) 17 | if weather.lower() == "thunder": 18 | print("Take cover!") 19 | break 20 | else: 21 | print("Well at least it's not thundering!") 22 | 23 | if __name__ == "__main__": 24 | lst = ['Banana', 'Orange', 'Kiwi', 'Jackfruit', 'Pineapple'] 25 | find_element_in_list('Kiwi', lst) 26 | #weather_report("snow") 27 | -------------------------------------------------------------------------------- /Review/SentenceSplitter.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | ''' 3 | Assume that sentence is a valid string. Write a function 4 | which returns a list of the most frequent words in the sentence, 5 | where words are obtained by sentence.split(). Each word is trimmed 6 | by removing trailing punctuation marks. 7 | 8 | For example, 9 | split_sentence('Hey diddle diddle the cat and the fiddle, the cow jumped over the moon') 10 | should return ['the'] since 'the' is the most frequent word. 11 | split_sentence('red; blue!! blue red'] 12 | should return ['red', 'blue'], where the items are in any order. 13 | 14 | Then, you should write five tests. At least ONE should be an edge 15 | case. 16 | ''' 17 | 18 | 19 | def split_sentence(sentence) : 20 | pass 21 | 22 | class myTests(unittest.TestCase): 23 | pass 24 | 25 | if __name__=='__main__': 26 | unittest.main(exit=True) 27 | -------------------------------------------------------------------------------- /Week_11/Classes/ExampleThree.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | # Notice how the FIRST THING I do in my program is import the necessary 3 | # library and I (should) only import it once. 4 | 5 | '''This example of bad programming practice involves us writing our 6 | tests AFTER designing our program. This is bad practice and is to be 7 | avoided. Always write your code to be black box tested.''' 8 | 9 | def our_function(a, b): 10 | '''fnction mustlplies a and b then return c''' 11 | c = a * b 12 | return c 13 | 14 | class MyTests(unittest.TestCase): 15 | pass 16 | 17 | # There is a problem with the first line in the main. You should only 18 | # import once, and your imports should be at the top of the code. 19 | # Importing again could make things run extremely slow. 20 | if __name__ == "__main__": 21 | import unittest 22 | unittest.main(exit=True) 23 | -------------------------------------------------------------------------------- /Week_4/Set.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In this file, we're going to explore one of python's other 3 | iterable types: sets! Sets contain only unique data entries. 4 | ''' 5 | 6 | if __name__ == "__main__": 7 | # Using curly braces 8 | fruits = {'blueberry', 'banana', 'cherry', 'strawberry'} 9 | 10 | # Using the set constructor 11 | more_fruits = set(['orange', 'kiwi', 'banana']) 12 | 13 | # Add a mango to the set 14 | fruits.add('mango') 15 | 16 | # Remove banana 17 | # fruits.remove('banana') 18 | 19 | # Remove will raise an error, however, discard won't! 20 | fruits.discard('banana') 21 | 22 | combined_froot = fruits | more_fruits 23 | print(combined_froot) 24 | 25 | # Get the intersection of sets 26 | common_fruit = fruits & more_fruits 27 | 28 | # Get the difference between two sets 29 | diff = fruits - more_fruits 30 | -------------------------------------------------------------------------------- /Week_4/CKCS_Examples/Custom_Functions.py: -------------------------------------------------------------------------------- 1 | 2 | # A function which returns a reversed string 3 | 4 | def backward_string(a_string): 5 | # How to reverse a string quickly 6 | return a_string[::-1] 7 | 8 | def muliply_string(new_string): 9 | return "The string " + new_string + " repeated 6 times is: " + (backward_string(new_string) * 6) 10 | 11 | def inefficient_backwards_string(a_string): 12 | empty_string = "" 13 | 14 | for letter in range(len(a_string) - 1, -1, -1): 15 | empty_string = empty_string + a_string[letter] 16 | 17 | print(empty_string) 18 | 19 | def this_function_doesnt_return_anything(): 20 | pass 21 | 22 | # This checks if this is the main module being run 23 | if __name__ == "__main__": 24 | new_str = backward_string("Banana") 25 | print(new_str) 26 | print(muliply_string("Apple")) 27 | 28 | print(inefficient_backwards_string("Pear")) 29 | 30 | print(this_function_doesnt_return_anything()) -------------------------------------------------------------------------------- /Week_9/CKCS_Examples/Mat_Plot.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | 4 | ''' 5 | Let's plot some graphs! Here we'll use the matplotlib library. To install, type: 6 | python -m pip install -U matplotlib 7 | ''' 8 | 9 | if __name__ == "__main__": 10 | # Line graph! 11 | # Making x,y coords 12 | xs = [1, 2, 3, 4, 5] 13 | ys = [x**2 for x in xs] 14 | 15 | # Plotting 16 | plt.plot(xs, ys) 17 | 18 | # Saving and showing the graph 19 | # This my take a moment 20 | plt.savefig('linechart') 21 | plt.xlabel("Value") 22 | plt.ylabel("Frequency") 23 | plt.show() 24 | 25 | # Messing with formatting! 26 | t = np.arange(0., 5., 0.2) 27 | plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') 28 | plt.show() 29 | 30 | # Box graph! 31 | data = [np.random.normal(0, std, 100) for std in range(1, 4)] 32 | # rectangular box plot 33 | plt.boxplot(data,vert=True,patch_artist=True) 34 | plt.show() 35 | -------------------------------------------------------------------------------- /Review/EpsilonGreater.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | ''' 3 | Write a function that returns True if a and b are 4 | a distance greater than epsilon away from one another. For example: 5 | 6 | outside_of(5, 6, 2) -> False 7 | outside_of(5, 7, 1.5) -> True 8 | ''' 9 | 10 | def outside_of(a, b, epsilon) : 11 | pass 12 | 13 | class myTests(unittest.TestCase): 14 | def test0(self): 15 | self.assertEqual(outside_of(5, 6, 2), False) 16 | def test1(self): 17 | self.assertEqual(outside_of(5, 7, 1.5), True) 18 | def test2(self): 19 | self.assertEqual(outside_of(1, 2, 1), False) 20 | def test3(self): 21 | self.assertEqual(outside_of(9, 9, 0), False) 22 | def test4(self): 23 | self.assertEqual(outside_of(9, 9, 100), False) 24 | def test5(self): 25 | self.assertEqual(outside_of(-90, 100, 0), True) 26 | 27 | if __name__=='__main__': 28 | unittest.main(exit=True) 29 | -------------------------------------------------------------------------------- /Review/AlexMidtermQuestionBank/q8-1.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def anagramTester(string1, string2): 4 | ''' 5 | Assume that the two parameters are strings. 6 | Return True if string1 and string2 are anagrams of each other, 7 | and False if not. 8 | Reminder, a word a is an anagram of another word b if a's letters 9 | can be rearanged to write b. 10 | ''' 11 | pass 12 | 13 | class anagramTests(unittest.TestCase): 14 | def test1(self): 15 | self.assertEqual(anagramTester('listen','silent'), True) 16 | def test2(self): 17 | self.assertEqual(anagramTester('listen','silence'), False) 18 | def test3(self): 19 | self.assertEqual(anagramTester('evil','vile'), True) 20 | def test4(self): 21 | self.assertEqual(anagramTester('a gentleman','elegant man'), True) 22 | def test5(self): 23 | self.assertEqual(anagramTester('this really','shouldn\'t work'), False) -------------------------------------------------------------------------------- /Review/RecursivePalindrome.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | ''' 3 | Assume that s is a string. Check to see if s is a palindrome. 4 | If it is, return True. Else, return False. Recall that a 5 | palinedrome is a string that is the same string if reversed. 6 | 7 | You must use RECURSION to solve the problem. 8 | 9 | For example, 10 | recursive_palindrome('racecar') is True 11 | recursive_palindrome('blue') is False 12 | 13 | Three test caases have been included. Add two more, 14 | both of which should be edge cases. 15 | ''' 16 | def recursive_palindrome(s) : 17 | pass 18 | 19 | class PalinTests(unittest.TestCase): 20 | def test1(self): 21 | self.assertTrue(recursive_palindrome('racecar')) 22 | def test2(self): 23 | self.assertFalse(recursive_palindrome('blue')) 24 | def test3(self): 25 | self.assertTrue(recursive_palindrome('madam')) 26 | 27 | if __name__=='__main__': 28 | unittest.main(exit=True) 29 | -------------------------------------------------------------------------------- /Week_11/Last_Class_Example.py: -------------------------------------------------------------------------------- 1 | # Function to prompt the user for key-value pairs 2 | def get_entries(entries): 3 | flag = True 4 | while flag: 5 | key = input("Enter the key (or 'done' to stop): ") 6 | if key.lower() == 'done': 7 | flag = False 8 | continue 9 | value = input(f"Enter the value for key '{key}': ") 10 | entries.append((key, value)) 11 | 12 | # Function to sort the list by the second element of each tuple 13 | def sort_entries(user_entries): 14 | sorted_entries = sorted(user_entries, key=lambda x: x[1]) # Sort by the second element (value) 15 | return sorted_entries 16 | 17 | if __name__ == "__main__": 18 | entries = [] 19 | # Main program flow 20 | get_entries(entries) 21 | sort_entries(entries) 22 | 23 | # Display the sorted list 24 | print("\nSorted entries (by value):") 25 | for entry in sort_entries: 26 | print(entry) -------------------------------------------------------------------------------- /Week_3/List_Examples.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Here, we're messing with list functions built into Python! 3 | ''' 4 | 5 | if __name__ == "__main__": 6 | # Create an initial list 7 | my_list = [1, 2, 3] 8 | print("Initial list:", my_list) 9 | 10 | # Append a value to the end 11 | my_list.append(4) 12 | print("After appending 4:", my_list) 13 | 14 | # Extend a list by the following elements 15 | my_list.extend([5, 6, 7]) 16 | print("After extending with [5, 6, 7]:", my_list) 17 | 18 | # Insert 14 at the beginning 19 | my_list.insert(0, 14) 20 | print("After inserting 14 at index 0:", my_list) 21 | 22 | # Remove the first occurrence of 3 23 | my_list.remove(3) 24 | print("After removing 3:", my_list) 25 | 26 | # Remove and return the last item 27 | popped_item = my_list.pop() 28 | print("Popped item:", popped_item) 29 | print("After popping the last item:", my_list) 30 | 31 | -------------------------------------------------------------------------------- /Week_11/Classes/ExampleOneCorrect.py: -------------------------------------------------------------------------------- 1 | '''This is how you'd write the basic functionality shown in ExampleOne.py 2 | correctly.''' 3 | 4 | # Notice how I've abstracted some functionality out to a function 5 | # Also, you'll notice how I've added a doc string inside the function 6 | # definition before any functionality. This is the proper format 7 | # for documenting your function. If you type help(print_list) into the 8 | # console, it will print off the doc string description. 9 | def print_list(ls): 10 | '''Takes a list and iterates through it, printing each element on a new line.''' 11 | for i in ls: 12 | print(i) 13 | 14 | # Notice how the functionality not in the function is contained in the main! 15 | # Notice how I have things named more meaningfully and not just their datatypes. 16 | if __name__ == "__main__": 17 | my_list = input("Please enter a series of words seperated by spaces:\n").split() 18 | print_list(my_list) -------------------------------------------------------------------------------- /Week_2/CKSC_Examples/CKCS_Loops.py: -------------------------------------------------------------------------------- 1 | # While loop section 2 | 3 | user_input = str(input("Please enter a word: ")) 4 | user_list = [] 5 | 6 | # This may not run because our user might enter exit the first time he's prompted 7 | while user_input.lower() != "exit": 8 | if user_input.lower() == "dog": 9 | print("Woof!") 10 | elif user_input.lower() == "cat": 11 | print("Meow!") 12 | user_list.append(user_input) 13 | user_input = str(input("Please enter another word (exit to stop): ")) 14 | 15 | # For Loop section 16 | # We will use the user list 17 | 18 | for item in user_list: 19 | # You can iterate over iterable items, even inside a for loop! 20 | #for letter in item: 21 | # print(letter) 22 | print(f"Your string {item} is of length {len(item)}") 23 | 24 | # If you want to use the indicies instead of the actual items inside an iterable object 25 | for i in range(len(user_list)): 26 | print(f"Your string at index {i} is {user_list[i]}!") -------------------------------------------------------------------------------- /Review/Answers/EpsilonGreater.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def outside_of(a, b, epsilon) : 4 | ''' 5 | Returns True if a and b are a distance greater than epsilon 6 | away from one another. For example: 7 | outside_of(5, 6, 2) -> False 8 | outside_of(5, 7, 1.5) -> True 9 | ''' 10 | return abs(a - b) > epsilon 11 | 12 | class myTests(unittest.TestCase): 13 | def test0(self): 14 | self.assertEqual(outside_of(5, 6, 2), False) 15 | def test1(self): 16 | self.assertEqual(outside_of(5, 7, 1.5), True) 17 | def test2(self): 18 | self.assertEqual(outside_of(1, 2, 1), False) 19 | def test3(self): 20 | self.assertEqual(outside_of(9, 9, 0), False) 21 | def test4(self): 22 | self.assertEqual(outside_of(9, 9, 100), False) 23 | def test5(self): 24 | self.assertEqual(outside_of(-90, 100, 0), True) 25 | 26 | if __name__=='__main__': 27 | unittest.main(exit=True) 28 | -------------------------------------------------------------------------------- /Week_11/Book_Tests.py: -------------------------------------------------------------------------------- 1 | import Book_Exercise 2 | import Manga_Exercise 3 | import unittest 4 | 5 | # Pascal case 6 | class BookTests(unittest.TestCase): 7 | def setUp(self): 8 | self.book_one = Book_Exercise.Book() 9 | self.book_two = Book_Exercise.Book("Xyz", "ABC", 10 | "Any", "None", 100) 11 | self.manga_one = Manga_Exercise.Manga("Uzumaki", "Junji Ito", "Horror", "Dark Horse", 12 | 300, False, "Japan") 13 | self.manga_two = Manga_Exercise.Manga() 14 | 15 | def test1(self): 16 | self.book_two.double_page_length() 17 | self.assertEqual(self.book_two.page_length, 200) 18 | 19 | def test2(self): 20 | self.assertTrue(self.manga_one.has_anime(2000000)) 21 | 22 | def test3(self): 23 | self.assertIsNone(self.book_one.author) 24 | 25 | if __name__ == "__main__": 26 | unittest.main(exit=True) 27 | 28 | -------------------------------------------------------------------------------- /Week_2/Function_And_If.py: -------------------------------------------------------------------------------- 1 | # This file shows us if statements and the steps you might need for them. 2 | # There are three potential steps in an if statment (you don't always need all three) 3 | 4 | # This function will just compare its two arguments, x and y. 5 | def if_bigger(x, y): 6 | if (x > y): 7 | print("X is bigger than Y.") 8 | # Elif is short for "else if". This indicates to the computer that if the previous condition 9 | # isn't met, that this one should be checked next. This one isn't really necessary, but good practice. 10 | elif (y > x): 11 | print("Y is bigger than X.") 12 | # Else tells the computer that if none of the preceeding conditions are met, that it has 13 | # to execute this one. 14 | else: 15 | print("X and Y are equal.") 16 | 17 | return x 18 | 19 | if __name__ == "__main__": 20 | if_bigger(5, 7) 21 | i = if_bigger(5, 3) 22 | if_bigger(4, 4) 23 | print(i) -------------------------------------------------------------------------------- /Week_9/Generators.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This is an example of a generator; generators don’t 3 | execute right away. Instead, they return iterator objects. 4 | ''' 5 | 6 | def count_up_to(n): 7 | count = 1 8 | while count <= n: 9 | print("Hello") 10 | yield count 11 | count += 1 12 | 13 | def lazy_range(n): 14 | for i in range(n): 15 | yield i 16 | 17 | def backwards_lazy_range(lower, upper): 18 | for i in range(upper, lower - 1, -1): 19 | yield i 20 | 21 | if __name__ == "__main__": 22 | counter = count_up_to(5) 23 | for num in counter: 24 | print(num) 25 | ''' 26 | for num in lazy_range(5): # Generates numbers 0 to 4 on-demand 27 | print(num) 28 | ''' 29 | 30 | upper = int(input("What is the upper limit? ")) 31 | lower = int(input("What is the lower limit? ")) 32 | 33 | lr = backwards_lazy_range(lower, upper) 34 | 35 | for item in lr: 36 | print(item) -------------------------------------------------------------------------------- /Week_9/List_Freq_Tests.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import List_Frequency 3 | 4 | ''' 5 | What the heck is going on here? 6 | This, in short: a built in class definition that lets 7 | you automatically test your code. You writ things this way, 8 | Python does the leg work for you. 9 | ''' 10 | class MyTests(unittest.TestCase): 11 | def test1(self): 12 | self.assertEqual(List_Frequency.mostfrequent([5, 2, 9, 2, 9, 1, 18, 9, 3]), 9) 13 | def test2(self): 14 | self.assertEqual(List_Frequency.mostfrequent(['cat', 'dog', 'dog', 'cat', 'cat']), 'cat') 15 | def test3(self): 16 | self.assertEqual(List_Frequency.mostfrequent([5]), 5) 17 | def test4(self): 18 | self.assertEqual(List_Frequency.mostfrequent([1, 2, 3, 3, 2, 1]), 1) 19 | def test5(self): 20 | self.assertEqual(List_Frequency.mostfrequent([(5, 5, 5), (3, 2, 1), (5, 5, 5)]), (5, 5, 5)) 21 | 22 | 23 | if __name__ == '__main__': 24 | unittest.main(exit=True) -------------------------------------------------------------------------------- /Week_8/CKCS_Examples/Data_Frame.py: -------------------------------------------------------------------------------- 1 | import pandas 2 | 3 | def times_two(x): 4 | return x * 2 5 | 6 | if __name__ == "__main__": 7 | # A dictionary containing some data! 8 | data = {'Company':['Cmp 1', 'Cmp 1', 'Cmp 2', 'Cmp 2', 'Cmp 3','Cmp 3'], 9 | 'Person':['Sam', 'Charlie', 'Amy', 'Vanessa', 'Carl', 'Sarah'], 10 | 'Sales':[200,0,340,124,0,350]} 11 | 12 | # Creating a data frame based off the data 13 | df = pandas.DataFrame(data) 14 | 15 | print(df) 16 | 17 | # Comparator with the numerical value! 18 | print((df.Sales > 200)) # Gives you a new table of each comparison 19 | print(df[df.Sales > 0]) # Will give you a table of the rows that match the condition 20 | 21 | # This works because times_two is a function object 22 | print(df.Sales.apply(times_two)) 23 | 24 | df.loc[df.Sales == 0, 'Sales_times_2'] = 200 25 | 26 | print(df) 27 | 28 | # Checks if a Person contains a certian substring 29 | print(df[df.Person.str.contains('am', case=True)]) -------------------------------------------------------------------------------- /Week_4/Read_Files.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In this file, we will be using a function to read a file 3 | and go through it line by line utilizing a for loop. 4 | 5 | Notice that the file is treated as an iterable? 6 | ''' 7 | 8 | def file_peak(): # Peaking at the file, getting content and lines 9 | num_lines = 0 10 | # Setting an empty string to add the contents from the file to 11 | file_contents = "" 12 | 13 | # You need to open the file temporarily with a while loop 14 | # There are other ways to open a file but this one ensures 15 | # your file closes after 16 | with open("a_file.txt") as f: 17 | # Iterable file object 18 | for line in f: 19 | file_contents = file_contents + line 20 | num_lines = num_lines + 1 21 | 22 | # Return a tuple containing the number of lines and file 23 | # contents as a pair. 24 | return (num_lines, file_contents) 25 | 26 | if __name__ == "__main__": 27 | t = file_peak() 28 | print(t[1]) -------------------------------------------------------------------------------- /Review/Answers/EvenAddition.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def even_addition(n) : 4 | ''' 5 | Returns the sum of the even numbers from n to 4*n, inclusive 6 | even_addition(2) returns 20 since 2, 3, 4, 5, 6, 7, 8 -> 2 + 4 + 6 + 8 = 20 7 | Do NOT assume that this function recieves a positive number, but do assume 8 | that it recieves an integer. 9 | ''' 10 | our_number = 0 11 | 12 | for i in range(n, (4*n) + 1): 13 | if i%2 == 0: 14 | our_number += i 15 | 16 | return our_number 17 | 18 | class myTests(unittest.TestCase): 19 | def test1(self): 20 | self.assertEqual(even_addition(2), 20) 21 | def test2(self): 22 | self.assertEqual(even_addition(1), 6) 23 | def test3(self): 24 | self.assertEqual(even_addition(0), 0) 25 | def test4(self): 26 | self.assertEqual(even_addition(100), 37750) 27 | 28 | if __name__=='__main__': 29 | print(even_addition(2), 'Expect 20') 30 | unittest.main(exit=True) 31 | -------------------------------------------------------------------------------- /Week_5/Mutable_vs_Immutable.py: -------------------------------------------------------------------------------- 1 | # This file simply shows what immutable vs. immutable means 2 | 3 | if __name__ == "__main__": 4 | # You'll notice that you can do things like: 5 | my_list = [1, 2, 3, 4, 5, 6, 7, 8] 6 | my_list.append(10) 7 | print(my_list) 8 | 9 | # But if you try it with a string, it will throw an error: 10 | my_string = "This is a string" 11 | # my_string.append("!") 12 | # Or a tuple... 13 | my_tuple = (1, 4, 7, 2, -11) 14 | #my_tuple.append(9) 15 | 16 | # This is all despite the fact that you can iterate through 17 | # both a string, a list and a tuple! 18 | for i in my_list: 19 | print(i) 20 | 21 | for j in my_string: 22 | print(j) 23 | 24 | for k in my_tuple: 25 | print(k) 26 | 27 | # Weird, right? That's because strings and tuples are immutable! You can't mess with them. 28 | # The only thing you can do is create new instances of tuples and strings with the 29 | # assignment operator (=). 30 | -------------------------------------------------------------------------------- /Week_1/String_Examples.py: -------------------------------------------------------------------------------- 1 | # Let's look at strings. 2 | # Python likes to treat them like lists sometimes and their own datatype other times. 3 | # For now, let's just say you want to cut up a string. Let's say you want to 4 | # return a string without its first letter and several of its laster letters. 5 | # It has, much like a list, indecies at each letter starting at 0. 6 | 7 | # Let's assign our string to a variable first so we can manipulate it. 8 | myString = "This is a string!" 9 | 10 | # Let's print it off to be sure. 11 | print(myString) 12 | 13 | # Next, let's chop it up... 14 | newStr = myString[1:5] 15 | # Let's note now that the first side of the [a:b] slide of a string is inclusive, so the h will be kept. 16 | # However, the b part of the slice is not included. It is everything before index 5 in this case. 17 | 18 | # Finally, let's print off our new string. 19 | print(newStr) 20 | 21 | # See what we did? We took a slice of the string at its indexes 1 to 5. 22 | # To access a string or a list at a specific index, use square brackets. -------------------------------------------------------------------------------- /Review/Answers/RecursivePalindrome.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | def recursive_palindrome(s) : 3 | ''' 4 | Assumes that s is a string. Checks to see if s is a palindrome. 5 | If it is, returns True. Else, returns False. 6 | ''' 7 | if len(s) == 1 or len(s) == 0: 8 | return True 9 | elif len(s) == 2: 10 | return s[0] == s[1] 11 | else: 12 | truth = s[0] == s[-1] 13 | return truth and recursive_palindrome(s[1:-1]) 14 | 15 | class PalinTests(unittest.TestCase): 16 | def test1(self): 17 | self.assertTrue(recursive_palindrome('racecar')) 18 | def test2(self): 19 | self.assertFalse(recursive_palindrome('blue')) 20 | def test3(self): 21 | self.assertTrue(recursive_palindrome('madam')) 22 | 23 | ''' 24 | Edge cases. 25 | ''' 26 | def test4(self): 27 | self.assertTrue(recursive_palindrome('')) 28 | def test5(self): 29 | self.assertTrue(recursive_palindrome('eeeeeee')) 30 | 31 | if __name__=='__main__': 32 | unittest.main(exit=True) 33 | -------------------------------------------------------------------------------- /Week_11/Card_Class.py: -------------------------------------------------------------------------------- 1 | class Card: 2 | def __init__(self, value, colour): 3 | self.value = value 4 | self.colour = colour 5 | 6 | ''' 7 | This syntax below is called list comprehension! 8 | What this does puts a loop inside a list. 9 | 10 | nums = [Card(value, colour) for value in range(1, 11) for colour in colours] 11 | can be written as: 12 | 13 | for value in range(1, 11): 14 | for colour in colours: 15 | nums.append(Card(value, colour)) 16 | 17 | See? It makes an object then appends it to the list! 18 | 19 | face = [Card(10, colour) for value in range(0, 3) for colour in colours] 20 | can be written as: 21 | 22 | for value in range(0, 3): 23 | for colour in colours: 24 | face.append(Card(10, colour)) 25 | ''' 26 | def createDeck(): 27 | colours = ['heart', 'diamonds', 'spades', 'clubs'] 28 | nums = [Card(value, colour) for value in range(1, 11) for colour in colours] 29 | face = [Card(10, colour) for value in range(0, 3) for colour in colours] 30 | nums.extend(face) 31 | 32 | return nums 33 | -------------------------------------------------------------------------------- /Week_5/CKCS_Examples/Matricies.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | import scipy 3 | 4 | if __name__ == "__main__": 5 | my_matrix = [[5, 10, 15], 6 | [40, 20, 30], 7 | [2, 4, 6], 8 | [-1, -2, -3]] 9 | 10 | new_matrix = numpy.array(my_matrix) 11 | print(new_matrix) 12 | print(type(new_matrix)) 13 | print(new_matrix.shape) 14 | print(new_matrix.dtype) 15 | print(new_matrix[0]) 16 | 17 | # We're accessing new_matrix[0][1] 18 | new_matrix[3, 1] = 70 19 | #print(new_matrix.transpose()) 20 | print(new_matrix) 21 | print(new_matrix.argmax()) 22 | print(new_matrix.argmin()) 23 | # Will overwrite your original array 24 | new_matrix.sort() 25 | print(new_matrix) 26 | 27 | #print(new_matrix[0:2]) 28 | # Prints off everything at index 1 29 | #print(new_matrix[:,1]) 30 | # Reassigns everything at index 1 31 | # new_matrix[:,1] = [0, 0, 0, 0] 32 | # print(new_matrix) 33 | 34 | bool_matrix = new_matrix < 10 35 | #print(bool_matrix) 36 | print(new_matrix.sum()) 37 | print(new_matrix.max()) 38 | print(new_matrix.mean()) 39 | print(scipy.stats.mode(new_matrix)) -------------------------------------------------------------------------------- /Week_11/CKCS_Examples/Car.py: -------------------------------------------------------------------------------- 1 | # Defining a car class 2 | class Car: 3 | # Class variable, shared between all cars 4 | total_cars = 0 5 | # Initialization function (otherwise known as a constructor) 6 | def __init__(self, col, pr): 7 | self.colour = col 8 | self.price = pr 9 | Car.total_cars += 1 10 | 11 | def __str__(self): 12 | return f"Car colour: {self.colour}\nCar price: {self.price}" 13 | 14 | # Some logic for the + operator. 15 | # And a type signature, meaning other programmers know that other should be an int 16 | def __add__(self, other: int): 17 | self.price += other 18 | 19 | def start_engine(self): 20 | print("Starting engine...") 21 | 22 | def drive(self, km): 23 | self.start_engine() 24 | print(f"Driving for {km} kilometers.") 25 | 26 | def how_many_cars(self): 27 | print(Car.total_cars) 28 | 29 | if __name__ == "__main__": 30 | # Calling the constructor 31 | our_car = Car("Blue", 15000) 32 | second_car = Car("Red", 100000) 33 | 34 | print(our_car) 35 | 36 | our_car + 300 37 | 38 | print(our_car) 39 | 40 | our_car.drive(100) 41 | our_car.how_many_cars() -------------------------------------------------------------------------------- /Week_3/Default_Arguments.py: -------------------------------------------------------------------------------- 1 | # This example is just to remind you guys how functions are called in Python. 2 | # Except there's a twist! Notice those crazy equals and their values? 3 | def backward_string(my_string="Heck"): 4 | new_string = my_string[::-1] 5 | return new_string 6 | 7 | # This shows a function that takes two arguments 8 | def multiply_string(my_string, mulitplier=1): 9 | newer_string = my_string * mulitplier 10 | return newer_string 11 | 12 | if __name__ == "__main__": 13 | 14 | inp = "temp" 15 | 16 | while(inp != "Stop"): 17 | inp = input("Enter a string to reverse:\n") 18 | if(inp != ""): 19 | i = int(input("How many times should it be repeated?\n")) 20 | print(backward_string(inp)) 21 | print(multiply_string(inp, i)) 22 | else: 23 | print("How many times should the default be repeated?\n") 24 | print("Wait I don't care!\n") 25 | new_string = backward_string() 26 | print(new_string) 27 | print(multiply_string(new_string)) 28 | 29 | print("Good bye") -------------------------------------------------------------------------------- /Week_6/CKCS_Examples/Basic_Series.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | from IPython.display import display 4 | 5 | if __name__ == "__main__": 6 | # Creating a basic series from a list 7 | data = [200, 300, 230, 500, 900] 8 | idx = [x for x in range(1, 6)] 9 | new_series = pd.Series(data, dtype=float, index=idx) 10 | print(new_series) 11 | print(new_series.index) 12 | print(new_series.values) 13 | 14 | # Creating a basic series from an ndarray 15 | months = ['Jan','Feb','March','April','May','June','July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'] 16 | monthly_data = [x * 10 for x in range(1, 13)] 17 | data_arr = np.array(monthly_data) 18 | month_dict = dict() 19 | print(monthly_data) 20 | for num in range(0, 12): 21 | month_dict[months[num]] = monthly_data[num] 22 | 23 | month_series = pd.Series(data=data_arr, index=month_dict) 24 | print(month_series) 25 | 26 | # Accessing things inside various series 27 | print(month_series['April']) 28 | print(new_series[2]) 29 | print(month_series.April) 30 | print(month_series[5::2]) 31 | print(new_series + month_series) 32 | 33 | display(new_series) -------------------------------------------------------------------------------- /Week_10/Book_Class.py: -------------------------------------------------------------------------------- 1 | class Book: 2 | # Total books in the library 3 | total_books = 0 4 | 5 | def __init__(self, t, a, g, p, pl): 6 | self.title = t 7 | self.author = a 8 | self.genre = g 9 | self.publisher = p 10 | self.page_length = pl 11 | Book.total_books = Book.total_books + 1 12 | 13 | def __str__(self): 14 | return f"Title: {self.title} \nAuthor: {self.author}" 15 | 16 | def change_author(self, new_author): 17 | self.author = new_author 18 | 19 | def double_page_length(self): 20 | self.page_length = self.page_length * 2 21 | 22 | def reset_count(self): 23 | Book.total_books = 0 24 | 25 | @property 26 | def maybe_double(self): 27 | return self.page_length * 2 28 | 29 | if __name__ == "__main__": 30 | a_book = Book("War and Peace", "Tolstoy", 31 | "Drama", "Tsar", 1000) 32 | second_book = Book("Metamorphosis", "Kafka", 33 | "Drama", "Penguin House", 100) 34 | print(a_book) 35 | 36 | print(a_book.page_length) 37 | a_book.change_author("Cassandra Laffan") 38 | print(a_book) 39 | print(a_book.maybe_double) 40 | print(Book.total_books) 41 | a_book.reset_count() 42 | print(Book.total_books) 43 | -------------------------------------------------------------------------------- /Review/Answers/FactorialRecursion.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | ''' 3 | Here is the simplest implementation of a recursive factorial function. 4 | There are five test cases, two of which are edge cases. Your answers 5 | may vary slightly. The commonality should be that all of your tests 6 | pass. 7 | ''' 8 | def factorial(num): 9 | # factorial of n = n * (n-1)! 10 | if num <= 1: 11 | return 1 12 | return num * factorial(num-1) 13 | 14 | class FacTest(unittest.TestCase): 15 | ''' 16 | The following two tests are considered edge cases. 17 | ''' 18 | def test1(self): 19 | self.assertEqual(factorial(0), 1) 20 | def test2(self): 21 | self.assertEqual(factorial(-1), 1) 22 | ''' 23 | The next three are just regular test cases. 24 | ''' 25 | def test3(self): 26 | self.assertEqual(factorial(2), 2) 27 | def test4(self): 28 | #notice how I take advantage of a different function in this library 29 | self.assertNotEqual(factorial(10), 1) 30 | def test5(self): 31 | self.assertEqual(factorial(11), 39916800) 32 | 33 | if __name__ == "__main__": 34 | unittest.main(exit=True) -------------------------------------------------------------------------------- /Week_11/Classes/ExampleFour.py: -------------------------------------------------------------------------------- 1 | '''This is the program that accompanies the problem outlined at the 2 | end of this week's slides.''' 3 | 4 | '''What do we need? Well, since employees contain a lot of information, 5 | we will probably need an Employee class of some sort, with some helper 6 | functions.''' 7 | 8 | class Employee: 9 | '''Employee class that contains relevant information for an employee.''' 10 | def __init__(self, name, emp_number, position, department, salary): 11 | pass 12 | 13 | def promotion(self, new_position): 14 | pass 15 | 16 | def name_change(self, new_name): 17 | pass 18 | 19 | '''Helper functions''' 20 | 21 | def employee_lookup(employee_list, employee_search): 22 | '''Will look up an employee and return their information''' 23 | pass 24 | 25 | def add_employee(employee_list): 26 | '''Will prompt the user for information, create an employee and then add 27 | said employee to the employee list.''' 28 | pass 29 | 30 | def delete_employee(employee_list, employee_name): 31 | '''Deletes the specified employee from the list.''' 32 | pass 33 | 34 | if __name__ == "__main__": 35 | pass -------------------------------------------------------------------------------- /Review/Answers/StringConcat.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def string_concat(s) : 4 | ''' 5 | Assumes s is a string. Returns a new string formed 6 | by concatenating i copies of the letter at position i, 7 | for each index position in string s. For example, 8 | string_concat('dog') returns 'ogg' since 0 of 'd' and 1 9 | of 'o' and 2 of 'g' 10 | ''' 11 | new_string = "" 12 | 13 | for i in range(len(s)): 14 | # new_string = new_string + s[i] * i 15 | new_string += s[i] * i 16 | 17 | return new_string 18 | 19 | class StringTests(unittest.TestCase): 20 | def test1(self): 21 | self.assertEqual(string_concat('dog'), 'ogg') 22 | def test2(self): 23 | self.assertEqual(string_concat('horse'), 'orrssseeee') 24 | def test3(self): 25 | self.assertEqual(string_concat('b'), '') 26 | def test4(self): 27 | self.assertEqual(string_concat('hippotamus'), 'ipppppooootttttaaaaaammmmmmmuuuuuuuusssssssss') 28 | ''' 29 | Edge case here. 30 | ''' 31 | def test5(self): 32 | self.assertEqual(string_concat(''), '') 33 | 34 | if __name__=='__main__': 35 | unittest.main(exit=True) 36 | -------------------------------------------------------------------------------- /Week_3/String_Operations.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Here's a file where we take some of the functions used 3 | to manipulate strings and actually use them! 4 | ''' 5 | 6 | if __name__ == "__main__": 7 | # Take user input 8 | user_input = input("Please enter a sentence: ") 9 | 10 | # Makes a new string, all lowercase 11 | upper_case = user_input.upper() 12 | print("Uppercase:", upper_case) 13 | 14 | # Makes a new string, all lowercase 15 | lower_case = user_input.lower() 16 | print("Lowercase:", lower_case) 17 | 18 | # Creates a new string, whitespace removed 19 | stripped_input = user_input.strip() 20 | print("Stripped input (whitespace removed):", stripped_input) 21 | 22 | # Splits the string based on a specifier (blank is default) 23 | split_words = user_input.split() 24 | print("Split words:", split_words) 25 | 26 | # Joins strings 27 | joined_string = " - ".join(split_words) 28 | print("Joined string with ' - ':", joined_string) 29 | 30 | # Replaces one character with another in a string 31 | replaced_string = user_input.replace(" ", "_") 32 | print("String with spaces replaced by underscores:", replaced_string) 33 | -------------------------------------------------------------------------------- /Week_11/Board_Class.py: -------------------------------------------------------------------------------- 1 | class Board(object): 2 | 3 | def __init__(self,width: int,height: int): 4 | self.width = width 5 | self.height = height 6 | self.board_space = [[ ' ' for x in range(0,width)] for y in range(0,height)] 7 | 8 | def __str__(self): 9 | out_string = "" 10 | out_string += ('-'*(self.width+2)) + '\n' 11 | for y in range(self.height): 12 | out_string +='|' 13 | for x in range(self.width): 14 | out_string += self.board_space[y][x] 15 | out_string +='|\n' 16 | out_string += ('-'*(self.width+2)) + '\n' 17 | 18 | return out_string 19 | 20 | def addWord(self,x: int,y: int,word: str): 21 | spaces = self.width 22 | if len(word) <= spaces-x: 23 | index_counter = x 24 | for char in word: 25 | self.board_space[y][index_counter] = char 26 | index_counter += 1 27 | else: 28 | print('The word cannot fit') 29 | 30 | 31 | 32 | if __name__ == '__main__': 33 | my_board = Board(10,10) 34 | my_board.addWord(0,0,'apple') 35 | print(my_board) 36 | 37 | -------------------------------------------------------------------------------- /Week_3/Arb_Root_Any_Number.py: -------------------------------------------------------------------------------- 1 | import math 2 | # Let's find an arbitrary root for any number! 3 | 4 | if __name__ == "__main__": 5 | # Type safety? Never heard of her. 6 | # Let's say I left this in as an example of nested type conversion 7 | num = float(abs(int(input("What number do you want the root for?\n")))) 8 | root = float(abs(int(input("And what root do you want to find for it?\n")))) 9 | 10 | lo = 0 11 | hi = max(num, 1.0) 12 | 13 | guess = (lo + hi) / 2 14 | e = 0.0001 15 | error = guess ** root - num 16 | 17 | # So for those who are confused by this (I ripped it out of the p. 33 in the textbook) 18 | # Think of this while loop like a pendulum, with the root specified above 19 | # as the centre. The program will swing back and forth past the real root, 20 | # adjusting its swing, until eventually it lands approximately in the centre. 21 | # (On the root). 22 | while abs(error) > e : 23 | if error < 0 : 24 | lo = guess 25 | else : 26 | hi = guess 27 | 28 | guess = (lo + hi) / 2 29 | error = guess ** root - num 30 | 31 | print('The approximate cube root of ', num, 'is', guess) 32 | -------------------------------------------------------------------------------- /Review/Answers/MatrixCheck.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def matrix_check(matrix) : 4 | ''' 5 | Assumes that matrix is a 2D array of integers. 6 | Returns True if the second last number of the 7 | second row occurs in any other rows. 8 | 9 | For example, 10 | matrix_check([[5, 6, 7, 2], [9, 8, 4, 22]]) -> False 11 | matrix_check([[7, 6, 9, 2], [9, 4, 7, 22], [7, 1, 6, 99]]) -> True 12 | 13 | Hint: use negative indicies for this one. 14 | ''' 15 | our_check = matrix[1][-2] 16 | conclusion = False 17 | 18 | for i in range(len(matrix)): 19 | for j in range(len(matrix[i])): 20 | if i != 1 and j != len(matrix[i]) - 1 and matrix[i][j] == our_check: 21 | conclusion = True 22 | break # We do not need to go any further. 23 | 24 | return conclusion 25 | 26 | 27 | class MatrixTests(unittest.TestCase): 28 | def test1(self): 29 | m = [[5, 6, 7, 2], [9, 8, 4, 22]] 30 | self.assertFalse(matrix_check(m)) 31 | def test2(self): 32 | m = [[7, 6, 9, 2], [9, 4, 7, 22], [7, 1, 6, 99]] 33 | self.assertTrue(matrix_check(m)) 34 | 35 | if __name__=='__main__': 36 | unittest.main(exit=True) -------------------------------------------------------------------------------- /Week_3/CKCS_Examples/Loop_Experiments.py: -------------------------------------------------------------------------------- 1 | new_list = ["Banana", "Strawberry", "Kiwi", "Guava", "Mango", "Pineapple", "Watermelon"] 2 | 3 | for fruit in new_list: 4 | print(fruit) 5 | if fruit == "Mango": 6 | pass 7 | else: 8 | print("This fruit is not a mango.") 9 | print("But it is a fruit!") 10 | else: 11 | # Loop else statements are mutually exclusive to break statements 12 | # if a break statement is met, the else statement won't evaluate! 13 | print("Found the mango!") 14 | 15 | 16 | for fruit in new_list: 17 | for letter in fruit: 18 | if letter == "i": 19 | break 20 | print(letter, end=" ") 21 | else: 22 | print("\nThis fruit doesn't have an i in it!") 23 | print() # prints a new line 24 | 25 | count = -1 26 | # Since I am incrementing count first, we needed to start at -1, and then increment from there 27 | # However, since the check on line 26 is prior to incrementation, we risk an index out of 28 | # range error. Thus, we change the bound such that it doesn't happen! 29 | while count < len(new_list) - 1: 30 | count+=1 31 | if count % 3 == 0: 32 | continue 33 | print(f"The fruit at index {count} is {new_list[count]}") 34 | else: 35 | print("Finished the fruit while loop!") 36 | -------------------------------------------------------------------------------- /Review/CreateTest.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import Brackets 3 | 4 | ''' 5 | For this question, assume you have a function called find_balance 6 | from a seperate module called Brackets. This function takes one 7 | argument, a string of 0 or more brackets, such as "}}{{}{}" or 8 | "}}}{{{" or "{}{}{}{}". It will access whether or not a string of 9 | these brackets is balanced or not. If a string IS balanced, it will 10 | return True. If it IS NOT balanced, it will return False. 11 | 12 | A string is considered balanced if it is empty, if it is of the form 13 | {}, or it is of the form {x}, where x is also a balanced string. It is 14 | also balanced if it is of the form {x}{x}, where x is either empty, or 15 | contains other balanced strings. So, for example, 16 | 17 | Brackets.find_balance("{{}}") -> True 18 | Brackets.find_balance("}{") -> False 19 | 20 | Write FIVE test cases for this function, including two that account for 21 | abnormal (edge) cases. Do not include the two examples above. 22 | 23 | To call this function, you will use the syntax Brackets.find_balance(argument). 24 | ''' 25 | 26 | class BracketTest(unittest.TestCase): 27 | pass 28 | 29 | if __name__ == "__main__": 30 | unittest.main(exit=True) -------------------------------------------------------------------------------- /Review/Answers/HeronPractice.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import math 3 | 4 | def heron(x, epsilon) : 5 | ''' 6 | Returns guess, the approximate square root of x, such that 7 | abs(guess**2 - x) < epsilon using Heron's algorithm, where 8 | start with guess = x / 2 and improve guess to be (guess + x / guess) / 2 9 | ''' 10 | guess = x / 2 11 | 12 | while(not(abs(guess**2 - x) < epsilon)): 13 | guess = (guess + x / guess) / 2 14 | 15 | return guess 16 | 17 | class HeronTests(unittest.TestCase): 18 | ''' 19 | Remember, your test cases may vary. It is important to remember 20 | that there are many functions at your disposal in this library. 21 | ''' 22 | def test0(self): 23 | self.assertTrue(abs(heron(4, 0.1) - 2) <= 0.1) 24 | def test1(self): 25 | self.assertTrue(abs(heron(99, 0.1) - math.sqrt(99)) <= 0.1) 26 | def test2(self): 27 | self.assertTrue(abs(heron(999, 0.1) - math.sqrt(999)) <= 0.1) 28 | def test3(self): 29 | self.assertTrue(abs(heron(1, 0.1) - 1) <= 0.1) 30 | def test4(self): 31 | self.assertTrue(abs(heron(0.25, 0.01) - 0.5) <= 0.01) 32 | 33 | if __name__=='__main__': 34 | unittest.main(exit=True) 35 | -------------------------------------------------------------------------------- /Week_11/Book_Exercise.py: -------------------------------------------------------------------------------- 1 | class Book: 2 | # Total books in the library 3 | total_books = 0 4 | # Added default arguments, meaning we can have an empty object 5 | def __init__(self, t = None, a = None, g = None, p = None, pl = None): 6 | self.title = t 7 | self.author = a 8 | self.genre = g 9 | self.publisher = p 10 | self.page_length = pl 11 | Book.total_books = Book.total_books + 1 12 | 13 | def __str__(self): 14 | return f"Title: {self.title} \nAuthor: {self.author}" 15 | 16 | def change_author(self, new_author): 17 | self.author = new_author 18 | 19 | def double_page_length(self): 20 | self.page_length = self.page_length * 2 21 | 22 | def reset_count(self): 23 | Book.total_books = 0 24 | 25 | @property 26 | def maybe_double(self): 27 | return self.page_length * 2 28 | 29 | if __name__ == "__main__": 30 | a_book = Book("War and Peace", "Tolstoy", 31 | "Drama", "Tsar", 1000) 32 | second_book = Book("Metamorphosis", "Kafka", 33 | "Drama", "Penguin House", 100) 34 | print(a_book) 35 | 36 | print(a_book.page_length) 37 | a_book.change_author("Cassandra Laffan") 38 | print(a_book) 39 | print(a_book.maybe_double) 40 | print(Book.total_books) 41 | a_book.reset_count() 42 | print(Book.total_books) 43 | -------------------------------------------------------------------------------- /Week_4/Dictionary.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Here, we'll create a simple dictionary and use 3 | some of the built in methods to manipulate it. 4 | ''' 5 | 6 | if __name__ == "__main__": 7 | # Using curly braces 8 | person = {'name': 'Alice', 'age': 30, 'city': 'New York'} 9 | 10 | # Using the dict constructor 11 | car = dict(make='Toyota', model='Camry', year=2022) 12 | 13 | # Attempting to use | on two dictionaries 14 | new_dict = person | car 15 | 16 | print(new_dict) 17 | 18 | # Accessing values 19 | print(person['name']) 20 | print(person['age']) 21 | 22 | # Let's update the person by giving her a new job. 23 | person['job'] = 'Engineer' 24 | 25 | # Now let's age her up 26 | person['age'] = 31 # Updates age to 31 27 | 28 | # Let's make her homeless and delete her city 29 | del person['city'] # Removes the city key-value pair 30 | 31 | # Or use pop to remove and return the value 32 | job = person.pop('job') # Removes 'job' and returns its value 33 | 34 | 35 | # Let's check for a key... 36 | if 'name' in person: 37 | print("Name exists in the dictionary!") 38 | 39 | # Loop through the dictionary! 40 | for key in person: 41 | print(f"{key}: {person[key]}") 42 | 43 | -------------------------------------------------------------------------------- /Week_5/Even_More_Dicts.py: -------------------------------------------------------------------------------- 1 | # This file shows you how to make a dictionary 2 | # and then look things up in it given a key value. 3 | 4 | if __name__ == "__main__": 5 | # This is how you declare an empty dictionary 6 | # Dictionaries are mutable, much like lists, so you can 7 | # add stuff to it as need be. 8 | name_dict = {} 9 | 10 | inp = "-1" 11 | emp_num = "" 12 | 13 | while inp != "": 14 | inp = str(input("Please enter an employee name. To exit, press 'enter' with no name.\n")) 15 | if inp == "": 16 | break 17 | else: 18 | emp_num = str(input("Now please enter their employee number.\n")) 19 | while emp_num == "": 20 | emp_num = str(input("Bad input! Please input an employee number.\n")) 21 | 22 | # This is the syntax for adding a new key-value pair to an existing dictionary 23 | # dictionary[key] = value 24 | if inp in name_dict: 25 | temp = name_dict[inp] 26 | name_dict[inp] = [] 27 | name_dict[inp].append(temp) 28 | name_dict[inp].append(emp_num) 29 | else: 30 | name_dict[inp] = emp_num 31 | 32 | print(name_dict) 33 | 34 | print("Goodbye") -------------------------------------------------------------------------------- /Review/AlexMidtermQuestionBank/q8-5.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def listMerge(listOfLists): 4 | ''' 5 | Assume that listOfLists is a 2D list of lists. 6 | 7 | EX: [[12,22,44][12,9][2,4]] 8 | 9 | Create and return a new list that merges the lists with the following rules 10 | 11 | 1. Create an empty output list 12 | 13 | 2. Then, For each list in listOfLists: 14 | 2.1. If list's sum is even, append the list's sum to the output list 15 | 2.2. If list's sum is odd, append all of list's values to the output list 16 | 17 | For example, the above listOfLists would return 18 | 19 | [78,12,9,6] 20 | ''' 21 | pass 22 | 23 | class listMergeTests(unittest.TestCase): 24 | def test1(self): 25 | self.assertEqual(listMerge([[12,22,44],[12,9],[2,4]]),[78,12,9,6]) 26 | def test2(self): 27 | self.assertEqual(listMerge([[12],[44,11],[4,7,13]]),[12,44,11,24]) 28 | def test3(self): 29 | self.assertEqual(listMerge([[88,19],[2,4,8,8,12],[8,7,14,12,12],[18,99]]),[88,19,34,8,7,14,12,12,18,99]) 30 | def test4(self): 31 | self.assertEqual(listMerge([[],[2,4,8,9,12],[18,99]]),[2,4,8,9,12,18,99]) 32 | def test5(self): 33 | self.assertEqual(listMerge([[],[],[]]),[]) 34 | 35 | if __name__ == '__main__': 36 | unittest.main(exit=True) -------------------------------------------------------------------------------- /Review/AlexMidtermQuestionBank/q8-3.py: -------------------------------------------------------------------------------- 1 | def leastCoins(toonies, loonies, quarters, dimes, nickels): 2 | ''' 3 | Assume that toonies, loonies, quarters, dimes and, 4 | nickles are all integer values representing the number 5 | of coins that a user has. 6 | 7 | Given this input, return an array of format 8 | [toonies, loonies, quarters, dimes, nickels] 9 | which has the same total value as the original input, but with 10 | the least amount of coins 11 | 12 | for example leastCoins(2,1,5,0,2) would return 13 | [3,0,1,1,0] 14 | As our original input was equal to $6.35, and the way to represent 15 | that value with the least coins is with 3 toonies, one quarter and 16 | one dime. 17 | 18 | Hints: 19 | 20 | 1. you may need to use the round(number, numberOfDigits) function 21 | to deal with floating point precision issues. 22 | EX: round(10.4999,2) -> 10.50 23 | 24 | 2. Remember your modulus (%) and floor division (//) operators 25 | ''' 26 | pass 27 | 28 | class leastCoinsTests(unittest.TestCase): 29 | def test1(self): 30 | self.assertEqual(leastCoins(2,1,5,0,2), [3,0,1,1,0]) 31 | def test2(self): 32 | self.assertEqual(leastCoins(0,1,4,0,10), [1,0,2,0,0]) 33 | def test2(self): 34 | self.assertEqual(leastCoins(0,1,4,0,10), [1,0,2,0,0]) -------------------------------------------------------------------------------- /Week_2/Function_Example.py: -------------------------------------------------------------------------------- 1 | # Now here is a slightly more complex program that makes use of the boolean datatype 2 | # and our ability to create our own functions 3 | 4 | # Here we create a simple function in which we feed in a bool (True or False) 5 | # and then return the opposite (the negated value of the True or False) 6 | # Note that any variables assigned during a function call will be released/removed when the function exits 7 | # This is due to the concept of SCOPE. Code written WITHIN a function (like in our example here) belongs to that 8 | # function's SCOPE, meaning we cannot access the variable from outside the function 9 | # note if we wanted to use a variable defined within a function, outisde of a function we can use the keyword 'global' 10 | def get_value(value): 11 | return not value 12 | 13 | # Finally, we call the function and print its value 14 | if __name__ == '__main__': 15 | x = get_value(False) 16 | print(x) 17 | u = get_value(True) 18 | print(u) 19 | w = get_value(False) 20 | print(w) 21 | 22 | #print(value) #this does not work because we cannot access the 'value' paramater variable in the get_value function from this scope. 23 | 24 | # Notice that we can pass the value of a function within the print function? 25 | # We can pass functions in as arguments as python, so long as their datatypes match! -------------------------------------------------------------------------------- /Review/AlexMidtermQuestionBank/q4-1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import unittest 3 | # -------------------------------------------------------------- 4 | # Sum = 1/1 + 1/2 + 1/3 + ... + 1/n 5 | # -------------------------------------------------------------- 6 | def series0(epsilon) : 7 | ''' 8 | Return the value of n such that the above sum is 9 | within epsilon of 4.23. 10 | For example, 11 | if epsilon is 4, then return 1, since 1 the first term is within 4 of 4.23 12 | if epsilon is 3, then return 2, since 1 + 1/2 = 1.5 is within 3 of 4.23 13 | ''' 14 | pass 15 | 16 | 17 | 18 | # -------------------------------------------------------------- 19 | # The Testing 20 | # -------------------------------------------------------------- 21 | class myTests(unittest.TestCase): 22 | def test1(self): 23 | self.assertEqual(series0(4), 1) 24 | def test2(self): 25 | self.assertEqual(series0(3), 2) 26 | def test3(self): 27 | self.assertEqual(series0(1), 14) 28 | def test4(self): 29 | self.assertEqual(series0(0.5), 23) 30 | def test5(self): 31 | self.assertEqual(series0(0.01), 38) 32 | 33 | 34 | if __name__ == '__main__': 35 | unittest.main(exit=True) 36 | 37 | 38 | 39 | 40 | # -------------------------------------------------------------- 41 | # The End 42 | # -------------------------------------------------------------- 43 | -------------------------------------------------------------------------------- /Review/Answers/RemoveLetter.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def remove_letter(s, removable_letter) : 4 | ''' 5 | Assumes s is a string, and removable_letter is a letter. 6 | Returns a string obtained by removing any intances of 7 | removable_letter in the string. If the string doesn't 8 | have any instances of removable_letter, it simply returns 9 | the original string. Returns a ValueError if the values 10 | aren't typed correctly. 11 | ''' 12 | try: 13 | if len(removable_letter) > 1: 14 | raise ValueError 15 | return s.replace(removable_letter, '') 16 | except Exception as error: 17 | raise ValueError 18 | 19 | class RemoveTests(unittest.TestCase): 20 | def test1(self): 21 | self.assertEqual(remove_letter('blue', 'x'), 'blue') 22 | def test2(self): 23 | with self.assertRaises(ValueError): 24 | remove_letter(529, 'a') 25 | def test3(self): 26 | with self.assertRaises(ValueError): 27 | remove_letter('red', 'xy') 28 | def test4(self): 29 | self.assertEqual(remove_letter('y', 'x'), 'y') 30 | def test5(self): 31 | self.assertEqual(remove_letter('', 'x'), '') 32 | def test6(self): 33 | self.assertEqual(remove_letter('z', 'z'), '') 34 | 35 | if __name__=='__main__': 36 | unittest.main(exit=True) 37 | 38 | -------------------------------------------------------------------------------- /Week_3/Exhaustive_Enumeration.py: -------------------------------------------------------------------------------- 1 | # Let's do a basic example of exhaustive enumeration 2 | # (also known as brute force!) through a very basic list. 3 | 4 | # What this function will do is take two arguments: 5 | # First, a list, then the integer you want to find in the list 6 | # it will return a list of the indicies where new_num occurs. 7 | def check_every_item(my_list, new_num): 8 | 9 | # Let's define an empty list that we can append our indicies to. 10 | ind_list = [] 11 | 12 | i = 0 13 | 14 | while i < len(my_list): 15 | if my_list[i] == new_num: 16 | # Lists, unlike strings, can be modified! 17 | # So we just add new items to 18 | ind_list.append(i) 19 | # i = i + 1 20 | i+=1 21 | 22 | return ind_list 23 | 24 | if __name__ == "__main__": 25 | # Here we will define a list in our program. 26 | # We will have some examples later on that will have more 27 | # dynamic lists made from user input. 28 | 29 | # The numbers are intentional 30 | # Indicies are 0 - 7, where 7 is the length of the list minus 31 | new_list = [2, 5, 1, 6, 2, 82, -10, 2] 32 | 33 | index_list = check_every_item(new_list, 2) 34 | # The output for this program will be [0, 4, 7] 35 | # Meaning we had to iterate through every single element to find every 2. 36 | print(index_list) -------------------------------------------------------------------------------- /Week_5/CKCS_Examples/Other_Arrays.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | 3 | if __name__ == "__main__": 4 | # Linspace will create an array with the number of indicies equally spaced 5 | # between the first and second numbers 6 | print(numpy.linspace(0, 25, 10)) 7 | 8 | # Similar to the range function, but makes an array 9 | print(numpy.arange(1, 11, 1)) 10 | 11 | # Will create a matrix with mostly 0s, with whatever number you enter 12 | # interrupting in a diagnal fashion 13 | diagn = numpy.diag([3, 3, 3, 3]) 14 | 15 | # Will create a matrix of only zeros (in float format) 16 | print(numpy.zeros(10)) 17 | 18 | # Will create a matrix of ones (also in float format) 19 | ones = numpy.ones((4, 4)) 20 | 21 | print(ones * 4) 22 | print(diagn * 5) 23 | 24 | numpy.random.seed() 25 | 26 | print(numpy.random.rand(3, 3)) 27 | 28 | #ones.shape = (-1, 1) 29 | 30 | print(diagn) 31 | print(diagn.transpose()) 32 | 33 | print(numpy.linalg.inv(diagn)) 34 | 35 | print(ones) 36 | print(numpy.dot(ones, diagn)) 37 | print(numpy.eye(3)) 38 | 39 | # Are actually looking at the same block of memory for the same matrix 40 | new_ones = ones 41 | print(ones is new_ones) 42 | # Allocates a new block of memory and copies all of the values over 43 | second_new_ones = new_ones.copy() 44 | print(new_ones is second_new_ones) 45 | 46 | print(ones.var()) 47 | print(ones.std()) 48 | -------------------------------------------------------------------------------- /Review/Inheritance.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Here is the implementation of a parent class called 3 | Animal. As you can see, it has the constructor (that __init__) 4 | already implemented, as well as a member method. Implement 5 | the __eq__ method for animal such that Python returns True if 6 | the name and age of both of the animals being compared are identical. 7 | 8 | You are to write a child class of Animal called Cat. 9 | Add another member variable to the Cat class called 10 | fur_colour, eye_colour and is_brushed. is_brushed should 11 | be automatically set to False. Add another class function 12 | called brushies. This function will set the is_brushed 13 | member variable to true and print a cat face to the 14 | screen (^._.^) 15 | 16 | Finally, finish the __eq__ function for cat, such that it 17 | also compared the other member variables of self to other. 18 | Make two Cat objects in the main and call your member 19 | method for Brushies on one. Then, compare them and print the 20 | result. 21 | ''' 22 | 23 | class Animal(): 24 | def __init__(self, name, age): 25 | self.name = name 26 | self.age = age 27 | 28 | def __eq__(self, other): 29 | return (self.name == other.name) and (self.age == other.age) 30 | 31 | def take_for_walk(self): 32 | print(f"Your {self.name} has gone for a walk!") 33 | 34 | ''' 35 | Put your cat class here. 36 | ''' 37 | 38 | if __name__ == "__main__": 39 | pass -------------------------------------------------------------------------------- /Review/RemoveLetter.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | ''' 3 | Assume s is a string, and removable_letter is a letter. 4 | Write a function that returns a string obtained by 5 | removing any intances of removable_letter in the string. 6 | If the string doesn't have any instances of removable_letter, 7 | it simply returns the original string. 8 | 9 | Should return a ValueError if the values aren't typed correctly. 10 | 11 | remove_letter('blue', 'x') should return 'blue' 12 | remove_letter(529, 'a') should raise ValueError 13 | remove_letter('red', 'yz') should raise ValueError 14 | remove_letter('', 'z') should return '' 15 | remove_letter('x', 'z') should return 'x' 16 | remove_letter('zz', 'z') should return '' 17 | ''' 18 | 19 | def remove_letter(s, removable_letter) : 20 | pass 21 | 22 | class RemoveTests(unittest.TestCase): 23 | def test1(self): 24 | self.assertEqual(remove_letter('blue', 'x'), 'blue') 25 | def test2(self): 26 | with self.assertRaises(ValueError): 27 | remove_letter(529, 'a') 28 | def test3(self): 29 | with self.assertRaises(ValueError): 30 | remove_letter('red', 'xy') 31 | def test4(self): 32 | self.assertEqual(remove_letter('y', 'x'), 'y') 33 | def test5(self): 34 | self.assertEqual(remove_letter('', 'x'), '') 35 | def test6(self): 36 | self.assertEqual(remove_letter('z', 'z'), '') 37 | 38 | if __name__=='__main__': 39 | unittest.main(exit=True) 40 | 41 | -------------------------------------------------------------------------------- /Week_11/Classes/ExampleTwo.py: -------------------------------------------------------------------------------- 1 | '''Second bad coding example.''' 2 | 3 | # This program will work but there are many things wrong with it. 4 | 5 | # Two problems arise here: first, a and b are sitting in the ether. 6 | # Second, there are typos in the strings. Proof read your code! 7 | # Just because Python doesn't complain about your spelling inside of 8 | # strings doesn't mean you should write garbage. 9 | a = input("iunput string:") 10 | b = input("inpoot strung:") 11 | 12 | # Several problems arise from this func definition. First, it is named 13 | # ambigiously so the reader has no idea what they're looking at. 14 | # Second, there are function definitions within the function. 15 | # Having functions declared in functions won't necessarily throw an error 16 | # but it indicates that you have no idea why functions are used. 17 | # Third, I am calling a and b inside of these functions which are declared 18 | # outside of any code blocks, at the beginning of the code. These are essentially 19 | # globals without the 'global' keyword. 20 | def func(): 21 | def func_two(a): 22 | print(a) 23 | def func_three(b): 24 | print(b) 25 | func_two() 26 | func_three() 27 | 28 | # If you open this inside of your code editor (which you should), you'll 29 | # see that these function calls are underlined in red. That's because these 30 | # functions are declared locally inside of func() and when you try to run this 31 | # code, you'll get an error. 32 | func_two(a) 33 | func_three(b) -------------------------------------------------------------------------------- /Week_5/Season_Of_The_Witch.txt: -------------------------------------------------------------------------------- 1 | When I look out my window 2 | Many sights to see 3 | And when I look in my window 4 | So many different people to be 5 | That it's strange 6 | So strange 7 | 8 | You got to pick up every stitch 9 | You got to pick up every stitch 10 | You got to pick up every stitch 11 | Mmmm, must be the season of the witch 12 | Must be the season of the witch, yeah 13 | Must be the season of the witch 14 | 15 | When I look over my shoulder 16 | What do you think I see? 17 | Some other cat lookin' over 18 | His shoulder at me 19 | And he's strange 20 | Sure is strange 21 | 22 | You got to pick up every stitch 23 | You got to pick up every stitch, yeah 24 | Beatniks are out to make it rich 25 | Oh no, must be the season of the witch 26 | Must be the season of the witch, yeah 27 | Must be the season of the witch 28 | 29 | You got to pick up every stitch 30 | Two rabbits runnin' in the ditch 31 | Beatniks out to make it rich 32 | Oh no, must be the season of the witch 33 | Must be the season of the witch 34 | Must be the season of the witch 35 | When I go 36 | 37 | When I look out my window 38 | What do you think I see? 39 | And when I look in my window 40 | So many different people to be 41 | It's strange 42 | Sure is strange 43 | 44 | You got to pick up every stitch 45 | You got to pick up every stitch 46 | Two rabbits runnin' in the ditch 47 | Oh no, must be the season of the witch 48 | Must be the season of the witch, yeah 49 | Must be the season of the witch 50 | When I go 51 | When I go -------------------------------------------------------------------------------- /Week_9/CKCS_Examples/Reading_File.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In this file, we're opening a file and reading it. We're not making 3 | any changes to the file! 4 | ''' 5 | if __name__ == "__main__": 6 | # r is short for read 7 | # You can also take user input and open a file from the string they enter 8 | my_file = open("./A_File.txt", "r") 9 | 10 | # Reads everything from the file into string 11 | contents = my_file.read() 12 | content_list = contents.split("\n") 13 | print(content_list) 14 | for line in content_list: 15 | print(line) 16 | 17 | # We need to close the file! 18 | my_file.close() 19 | 20 | print("_____________________________") 21 | 22 | # We can also read the file line by line: 23 | filename = "./Halloween.txt" 24 | file = open(filename, "r") 25 | for line in file: 26 | print(line, end="") 27 | file.close() 28 | 29 | print("\n_____________________________") 30 | 31 | # We can also use the with block, which negates the requirement for the close func 32 | with open('./A_File.txt', 'r') as file: 33 | first_ten_chars = file.read(10) 34 | the_rest = file.read() 35 | print("The first 10 characters:", first_ten_chars) 36 | print("The rest of the file:", the_rest) 37 | 38 | print("_____________________________") 39 | 40 | # This block of code will do something similar to the split function above 41 | with open('./A_File.txt', 'r') as example_file: 42 | lines = example_file.readlines() 43 | print(lines) 44 | 45 | print("_____________________________") 46 | 47 | # Let's sort that list 48 | new_list = sorted(lines) 49 | print(new_list) -------------------------------------------------------------------------------- /Week_4/Function_And_For.py: -------------------------------------------------------------------------------- 1 | # This example goes over how to use lists and 2 | # strings for loops. 3 | 4 | # So here we have a definition of a function that takes 5 | # a string as an argument. Then, it iterates over the 6 | # contents of the string and prints out the characters one 7 | # at a time. 8 | def loop_over_string(my_string): 9 | 10 | # Notice that I have range(len(my_string)) 11 | # Why? Well, this is how you iterate over a collection of numbers 12 | # in a specific range. It begins at the first number inclusive 13 | # and then ends at the last number NOT inclusive. 14 | for c in range(len(my_string)): 15 | print(my_string[c]) 16 | 17 | # Here I have defined a function that takes a list as an argument 18 | # Then it iterates over each item in the list, just like in the string above 19 | def loop_over_list(my_list): 20 | for i in range(len(my_list)): 21 | # The square brackets are the syntax for finding an item in a list (or string) 22 | # given the index number. 23 | print(my_list[i]) 24 | 25 | if __name__ == "__main__": 26 | # Recall: a string is just something contained in quotations 27 | this_string = "This is our string" 28 | 29 | # This is a list of strings. A list is denoted by square brackets on either side 30 | # and its contents are seperated with commas 31 | this_list = ["this", "is", "our", "list"] 32 | 33 | for i in range(len(this_list)): 34 | print(i) 35 | 36 | # Now we call the functions 37 | loop_over_string(this_string) 38 | loop_over_list(this_list) -------------------------------------------------------------------------------- /Review/AlexMidtermQuestionBank/q8-4.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def shopSort(productDict): 4 | ''' 5 | Assume that productDict is a dictionary of product price pairs 6 | 7 | EX: 8 | { 9 | 'rice':10.99 10 | 'cheese':3.99 11 | 'eggs':5.99 12 | } 13 | 14 | Return a list of tuples of all the products in the dict 15 | sorted by price from greatest to least. 16 | 17 | For example, the above dictionary would return: 18 | 19 | [('rice',10.99), ('eggs',5.99), ('cheese',3.99)] 20 | ''' 21 | pass 22 | 23 | class shopSortTests(unittest.TestCase): 24 | def test1(self): 25 | self.assertEqual(shopSort({'rice':10.99,'cheese':3.99,'eggs':5.99}), 26 | [('rice',10.99), ('eggs',5.99), ('cheese',3.99)]) 27 | def test2(self): 28 | self.assertEqual(shopSort({'water':2.99,'gum':1.50,'burger':5.99,'crackers':3.00}), 29 | [('burger',5.99), ('crackers',3.00),('water',2.99), ('gum',1.50)]) 30 | def test3(self): 31 | self.assertEqual(shopSort({'cola':2.00,'redbull':3.49}), 32 | [('redbull',3.49),('cola',2.00)]) 33 | def test4(self): 34 | self.assertEqual(shopSort({'kool aid':15.00,'grape juice':100.22,'Q-tip':1000.39}), 35 | [('Q-tip',1000.39),('grape juice',100.22),('kool aid',15.00)]) 36 | def test5(self): 37 | self.assertEqual(shopSort({'these':100,'all':100,'have':100,'the':100,'same':100,'price':100}), 38 | [('these',100),('all',100),('have',100),('the',100),('same',100),('price',100)]) 39 | 40 | if __name__ == '__main__': 41 | unittest.main(exit=True) -------------------------------------------------------------------------------- /Week_11/In_Class_Example.py: -------------------------------------------------------------------------------- 1 | ''' 2 | def first_preceded_by_smaller(items, k=1): 3 | 4 | Find and return the first element of the given list of items 5 | that is preceded by at least k smaller elements in the list. 6 | These required k smaller elements can be positioned anywhere 7 | before the current element, not necessarily consecutively 8 | immediately before that element. 9 | 10 | If no element satisfying this requirement exists anywhere in 11 | the list, this function should return None. 12 | 13 | Since the only operation performed for the individual 14 | items is their order comparison, and especially no arithmetic 15 | occurs at any point during the execution, this function should 16 | work for lists of any types of elements, as long as those 17 | elements are pairwise order comparable with each other. 18 | ''' 19 | 20 | def first_preceded_by_smaller(items, k=1): 21 | count_value = 0 22 | return_value = None 23 | 24 | for i in range(k, len(items)): 25 | count_value = 0 26 | for j in range(i): 27 | if(items[j] < items[i]): 28 | count_value += 1 29 | if(count_value >= k): 30 | return_value = items[i] 31 | break 32 | 33 | return return_value 34 | 35 | if __name__ == "__main__": 36 | lst = [4, 4, 5, 6] 37 | print(first_preceded_by_smaller(lst, 2)) 38 | 39 | lst_new = [42, 99, 16, 55, 7, 32, 17, 18, 73] 40 | print(first_preceded_by_smaller(lst_new, 3)) 41 | 42 | lst_string = ['bob', 'carol', 'tina', 'alex', 'jack', 'emmy', 'tammy', 'sam', 'ted'] 43 | print(first_preceded_by_smaller(lst_string, 4)) 44 | 45 | long_lst = [9, 8, 7, 6, 5, 4, 3, 2, 1, 10] 46 | print(first_preceded_by_smaller(long_lst)) 47 | -------------------------------------------------------------------------------- /Review/OOPRectangle.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | '''This class represents a rectangle in the x-y coordincate system 3 | where the edges of the rectangle are aligned with the x- and y- axes. 4 | A Rectangle object has data attributes lowerleft and upperright, 5 | which are tuples representing the (x, y) coordinates of the lower 6 | left corner and the upper right corner. 7 | 8 | Fill in functions for the class. 9 | ''' 10 | 11 | class Rectangle(object): 12 | def __init__(self, x1, y1, x2, y2) : 13 | '''Assumes the (x1, y1) are the coordinates of the lower left corner 14 | and (x2, y2) are the coordinates of the upper right corner. 15 | ''' 16 | pass 17 | 18 | def width(self) : 19 | '''Returns the width of the rectangle 20 | ''' 21 | pass 22 | 23 | def height(self) : 24 | '''Returns the height of the rectangle 25 | ''' 26 | pass 27 | 28 | def area(self) : 29 | '''Returns the area of the rectangle''' 30 | pass 31 | 32 | def __eq__(self, other) : 33 | '''Returns true if the two rectangles have equal area''' 34 | pass 35 | 36 | class RecTests(unittest.TestCase): 37 | def test1(self): 38 | box1 = Rectangle(0, 0, 2, 2) 39 | self.assertEqual(box1.width(), 2) 40 | def test2(self): 41 | box1 = Rectangle(0, 0, 2, 2) 42 | self.assertEqual(box1.height(), 2) 43 | def test3(self): 44 | box1 = Rectangle(0, 0, 2, 2) 45 | self.assertEqual(box1.area(), 4) 46 | def test4(self): 47 | box1 = Rectangle(0, 0, 2, 2) 48 | box2 = Rectangle(2, 2, 6, 3) 49 | self.assertTrue(box1 == box2) 50 | 51 | if __name__=='__main__': 52 | unittest.main(exit=True) 53 | -------------------------------------------------------------------------------- /Week_11/Car_Class.py: -------------------------------------------------------------------------------- 1 | class Vehicle: 2 | def start_engine(self): 3 | print("Starting the engine...") 4 | 5 | class car(Vehicle): 6 | ''' 7 | This is a very basic class. All it has is three properties: 8 | make, colour, price. Why does it have a "self"? 9 | Well, let's, instead, look at our method. 10 | ''' 11 | def __init__(self, m, c, p): 12 | self.make = m 13 | self.colour = c 14 | self.price = p 15 | 16 | ''' 17 | Notice how we have to call self again? And how there is only 18 | one argument, and it's self? 19 | 20 | Let's go look at its implementation 21 | ''' 22 | 23 | def age_price(self): 24 | self.price = self.price - 500 25 | 26 | # Overriding the parent function 27 | def start_engine(self): 28 | print("We're starting this engine instead!") 29 | 30 | def __str__(self): 31 | return f"Car(make='{self.make}', colour='{self.colour}', price={self.price})" 32 | 33 | def compare_price(car_one, car_two): 34 | return car_one.price == car_two.price 35 | 36 | if __name__ == "__main__": 37 | our_car = car("Honda Civic", "Blue", 12000) 38 | our_car_2 = car("Honda Civic", "Red", 14000) 39 | 40 | # Calling the parent class' function 41 | our_car.start_engine() 42 | ''' 43 | print(compare_price(our_car, our_car_2)) 44 | 45 | 46 | Notice how when we call this method, that it has no arguments? 47 | Well, python actuall reads it as: age_price(our_car) (sorta). 48 | The "self" is the current object we're dealing with! 49 | 50 | our_car.age_price() 51 | print("It now costs: " + str(our_car.price)) 52 | 53 | our_car.age_price() 54 | print("It now costs: " + str(our_car.price)) 55 | ''' -------------------------------------------------------------------------------- /Review/AlexMidtermQuestionBank/q8-6.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def marketResearch(carts): 4 | ''' 5 | Assume carts is a list of of lists that represent items that users have purchased 6 | 7 | For example: 8 | [['peas','potatoes','gravy','chicken'],['potatoes','gravy','beans','steak'],['potatoes','grapes'],['grapes','steak','beans']] 9 | 10 | Return a tuple of the most commonly purchased item, and the item that most commonly appears in lists that contain the most common tiem. 11 | 12 | For example, potatoes is the most common item across the lists. 13 | Among the lists containing potatoes, gravy is the most common item (excluding potatoes). 14 | 15 | Therefore we return (potatoes, gravy) 16 | ''' 17 | pass 18 | 19 | 20 | class marketResearchTests(unittest.TestCase): 21 | def test1(self): 22 | self.assertEqual(marketResearch([['peas','potatoes','gravy','chicken'],['potatoes','gravy','beans','steak'],['potatoes','grapes'],['grapes','steak','beans']]), ('potatoes', 'gravy')) 23 | def test2(self): 24 | self.assertEqual(marketResearch([['rgb fans','cpu','graphics card'],['graphics card','rgb fans'],['cpu','monitor'],['graphics card']]), ('graphics card', 'rgb fans')) 25 | def test3(self): 26 | self.assertEqual(marketResearch([['rice','black beans'],['rice','water','fanta'],['rice','black beans','sprite'],[]]), ('rice','black beans')) 27 | def test4(self): 28 | self.assertEqual(marketResearch([['rice','black beans'],['rice','splenda'],['rice'],['splenda']]), ('rice','black beans')) 29 | def test5(self): 30 | self.assertEqual(marketResearch([['grapes','squash'],['squash']]), ('squash','grapes')) 31 | 32 | if __name__ == '__main__': 33 | unittest.main(exit=True) -------------------------------------------------------------------------------- /Week_6/CKCS_Examples/Data_Frame.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | from IPython.display import display 4 | from numpy.random import randn 5 | 6 | if __name__ == "__main__": 7 | np.random.seed(101) 8 | new_data_frame = pd.DataFrame(randn(5,4),index=['A', 'B', 'C', 'D', 'E'],columns=['W', 'X', 'Y', 'Z']) 9 | print(new_data_frame) 10 | 11 | print(new_data_frame['W']) 12 | # Will access columns 13 | print(new_data_frame[['W', 'Z']]) 14 | # Will access rows 15 | print(new_data_frame[0:2]) 16 | # Short for index location 17 | print(new_data_frame.iloc[3]) 18 | # Short for location 19 | print(new_data_frame.loc['A']) 20 | 21 | # Adding a column 22 | new_data_frame['R'] = new_data_frame['W'] + new_data_frame['Y'] 23 | print(new_data_frame) 24 | # Removing a column, inplace is necessary 25 | new_data_frame.drop('R', axis=1, inplace=True) 26 | print(new_data_frame) 27 | # Remove row, inplace tells Python we are certian! 28 | new_data_frame.drop('C', axis=0, inplace=True) 29 | print(new_data_frame) 30 | 31 | # Needs square brackets 32 | # NaN means Not a Number! 33 | print(new_data_frame[new_data_frame < 0]) 34 | 35 | # Will fetch the first n rows (the head of the spreadsheet) 36 | print(new_data_frame.head(2)) 37 | # Will give you the unique entries in a column 38 | print(new_data_frame['W'].unique()) 39 | # Will give you a randomly ordered sample from your data frame 40 | print(new_data_frame.sample(3)) 41 | 42 | # Regex is short for regular expression and it is a pattern matching 43 | # syntax. 44 | print(new_data_frame.filter(regex='1|2',axis=1)) 45 | print(new_data_frame.filter(regex='1|2',axis=0)) 46 | # Will give you information 47 | print(new_data_frame.info()) 48 | # Will give you the mathematical information 49 | print(new_data_frame.describe()) 50 | 51 | print(new_data_frame.sort_values(by='W')) 52 | 53 | display(new_data_frame) -------------------------------------------------------------------------------- /Review/Answers/Inheritance.py: -------------------------------------------------------------------------------- 1 | class Animal: 2 | ''' 3 | An implementation of the Animal parent class. 4 | ''' 5 | def __init__(self, name, age): 6 | self.name = name 7 | self.age = age 8 | 9 | def __eq__(self, other): 10 | return (self.name == other.name) and (self.age == other.age) 11 | 12 | def take_for_walk(self): 13 | print(f"Your {self.name} has gone for a walk!") 14 | 15 | class Cat(Animal): 16 | ''' 17 | Child class of Animal called Cat. Since cats aren't 18 | brushed by default, the member variable for is_brushed is 19 | set to False. 20 | ''' 21 | def __init__(self, name, age, fur_colour, eye_colour): 22 | # This is the idiomatic way to call the parent class' constructor 23 | super().__init__(name, age) 24 | # Since is_brushed is automatically False, I have opted to not have it as an argument 25 | # in the constructor. 26 | self.fur_colour = fur_colour 27 | self.eye_colour = eye_colour 28 | self.is_brushed = False 29 | 30 | def __eq__(self, other): 31 | return (super().__eq__(other)) and (self.eye_colour == other.eye_colour) and (self.fur_colour == other.fur_colour) and (self.is_brushed == other.is_brushed) 32 | 33 | def brushie(self): 34 | self.is_brushed = True 35 | print(f"{self.name} has been brushed! (^._.^)") 36 | 37 | def is_good(one): 38 | return one.brushie() 39 | 40 | if __name__ == "__main__": 41 | ''' 42 | Make two Cat objects in the main and call your member 43 | method for Brushies on one. Then, compare them and print the 44 | result. 45 | ''' 46 | mischief = Cat("Mischief", 13, "Brown", "Green") 47 | chaos = Cat("Chaos", 11, "Grey and white", "Yellow/Green") 48 | 49 | mischief.brushie() 50 | is_good(mischief) 51 | 52 | print(mischief == chaos) -------------------------------------------------------------------------------- /Review/Answers/RecursiveBrackets.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a RECURSIVE function that performs the same 3 | functionality as the function in Brackets.py. 4 | 5 | Something of this difficulty will not appear on your 6 | exam. This is just here for fun! 7 | ''' 8 | 9 | ''' 10 | Cassandra's solution logic: 11 | 12 | So there are lots of base cases. Instead of working our way 13 | from one side to the other in an iterative fashion, we 14 | work our way into the middle, while keeping a count of the brackets 15 | closed and open on either side of the centre slice. 16 | 17 | l (for left) and r (for right) are by default 0. They are what 18 | keep track of the counts on either side. 19 | ''' 20 | 21 | def find_balance(s, l = 0, r = 0): 22 | ''' 23 | Takes a string of brackets as an argument. Will return 24 | True or False, depending on whether or not the string 25 | is balanced. An empty string is balanced. 26 | 27 | find_balance("}}}{") -> False 28 | find_balance("{}{}") -> True 29 | ''' 30 | check = False 31 | 32 | # Lots of base cases in this instance. 33 | if len(s) == 0: 34 | if l == abs(r) and l >= 0 and r <= 0: 35 | check = True 36 | else: 37 | check = False 38 | elif len(s) == 1: 39 | if s[0] == "}" and l == 1: 40 | check = True 41 | elif s[0] == "{" and r == -1: 42 | check = True 43 | else: 44 | check = False 45 | else: 46 | if s[0] == "{": 47 | l += 1 48 | elif s[0] == "}": 49 | l -=1 50 | if s[-1] == "}": 51 | r -= 1 52 | elif s[-1] == "{": 53 | r += 1 54 | 55 | check = True and find_balance(s[1:-1], l, r) 56 | 57 | return check 58 | ''' 59 | Note: There are no tests included in this file. Use the 60 | tests you've written in CreateTest.py to test your code. 61 | ''' -------------------------------------------------------------------------------- /Review/Answers/OOPRectangle.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | '''This class represents a rectangle in the x-y coordincate system 3 | where the edges of the rectangle are aligned with the x- and y- axes. 4 | A Rectangle object has data attributes lowerleft and upperright, 5 | which are tuples representing the (x, y) coordinates of the lower 6 | left corner and the upper right corner. 7 | 8 | Fill in functions for the class. 9 | ''' 10 | 11 | class Rectangle(object): 12 | def __init__(self, x1, y1, x2, y2) : 13 | '''Assumes the (x1, y1) are the coordinates of the lower left corner 14 | and (x2, y2) are the coordinates of the upper right corner. 15 | ''' 16 | self.lowerleft = (x1, y1) 17 | self.upperright = (x2, y2) 18 | 19 | def width(self) : 20 | '''Returns the width of the rectangle 21 | ''' 22 | return self.upperright[0] - self.lowerleft[0] 23 | 24 | def height(self) : 25 | '''Returns the height of the rectangle 26 | ''' 27 | return self.upperright[1] - self.lowerleft[1] 28 | 29 | def area(self) : 30 | '''Returns the area of the rectangle''' 31 | return self.height() * self.width() 32 | 33 | def __eq__(self, other) : 34 | '''Returns true if the two rectangles have equal area''' 35 | return self.area() == other.area() 36 | 37 | class RecTests(unittest.TestCase): 38 | def test1(self): 39 | box1 = Rectangle(0, 0, 2, 2) 40 | self.assertEqual(box1.width(), 2) 41 | def test2(self): 42 | box1 = Rectangle(0, 0, 2, 2) 43 | self.assertEqual(box1.height(), 2) 44 | def test3(self): 45 | box1 = Rectangle(0, 0, 2, 2) 46 | self.assertEqual(box1.area(), 4) 47 | def test4(self): 48 | box1 = Rectangle(0, 0, 2, 2) 49 | box2 = Rectangle(2, 2, 6, 3) 50 | self.assertTrue(box1 == box2) 51 | 52 | if __name__=='__main__': 53 | unittest.main(exit=True) 54 | -------------------------------------------------------------------------------- /Week_1/CKCS_Lecture_1.py: -------------------------------------------------------------------------------- 1 | variable_one = 1 # this is a variable that contains an int 2 | print(variable_one) 3 | print(4) 4 | 5 | variable_two = 4.57 # this is a variable containing a float 6 | print(variable_two) 7 | 8 | variable_three = 'Hello!' 9 | variable_four = "World!" 10 | print(variable_three, variable_four) 11 | print("This is a string!") 12 | 13 | print(type(variable_four)) 14 | print(type(variable_one)) 15 | 16 | a, b, c = 2, 2.5, "two" 17 | print(a, b, c) 18 | 19 | cat_age, cat_name = 17, "Mischief" 20 | print(cat_age, cat_name) 21 | 22 | #---------- Math Operations Below ----------- 23 | 24 | print(2 + 4) 25 | print(2 * 3) 26 | # Power logic is base number times itself however many times the exponent is 27 | # For example, 2 ** 3 == 2 * 2 * 2 -> 4 * 2 -> 8 28 | print(2 ** 3) 29 | print(3 ** 2) # 3 * 3 -> 9 30 | # Modulo operator calculates the remainder! 31 | print(8 % 3) 32 | print(8 % 4) 33 | # Note the difference in behaviour between the two divisions! 34 | print(8/4) 35 | print(8//4) 36 | 37 | print(variable_one % variable_two) 38 | 39 | # 8 + 10 / 5 -> 8 + 2 -> 10 40 | var_a = int(8 + (12 - 2) / 5) 41 | print(var_a) 42 | 43 | var_a += 10 44 | print(var_a) 45 | 46 | # --------- User Input Examples ------------- 47 | 48 | ''' 49 | # This takes input from the user 50 | user_input = str(input("Please input a string: ")) 51 | # F string, which allows you to format a string with other variable 52 | print(f"Your string is {user_input}") 53 | 54 | user_input += " likes cats!" 55 | print(user_input) 56 | 57 | user_input += str(variable_two) 58 | print(user_input) 59 | ''' 60 | # ------- Boolean logic ------- 61 | 62 | new_var = True 63 | other_variable = 7 >= 2 64 | print(other_variable) 65 | print(other_variable == new_var) 66 | print(variable_one != variable_two) 67 | print(not (variable_one != variable_two)) 68 | 69 | 70 | print(new_var == other_variable and variable_one == variable_two) 71 | print(new_var == other_variable or variable_one == variable_two) -------------------------------------------------------------------------------- /Review/Answers/SentenceSplitter.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import string 3 | 4 | def split_sentence(sentence) : 5 | ''' 6 | Assumes that sentence is a valid string. Returns a 7 | list of the most frequent words in the sentence, where 8 | words are obtained by sentence.split(). Each word is trimmed 9 | by removing trailing punctuation marks. 10 | ''' 11 | word_dict = {} 12 | sentence_list = sentence.split() 13 | 14 | # Very short hand syntax, your results may vary 15 | # I personally hate list comprehension but you guys used it a lot 16 | sentence_list = [''.join(c for c in s if c not in string.punctuation) for s in sentence_list] 17 | 18 | for word in sentence_list: 19 | if word not in word_dict: 20 | word_dict[word] = 1 21 | else: 22 | word_dict[word] += 1 23 | 24 | frequency_list = [] 25 | 26 | # try/except here because you cannot take a max of an empty list 27 | try: 28 | maximum = max(word_dict.values()) 29 | except: 30 | maximum = 0 31 | 32 | for search in sentence_list: 33 | if word_dict[search] == maximum and search not in frequency_list: 34 | frequency_list.append(search) 35 | 36 | return frequency_list 37 | 38 | class myTests(unittest.TestCase): 39 | def test1(self): 40 | s = 'Hey diddle diddle the cat and the fiddle, the cow jumped over the moon' 41 | r = ['the'] 42 | self.assertEqual(sorted(split_sentence(s)), r) 43 | def test2(self): 44 | s = 'red, blue;, red! blue!!' 45 | r = ['blue', 'red'] 46 | self.assertEqual(sorted(split_sentence(s)), r) 47 | ''' 48 | Edge cases are here. 49 | ''' 50 | def test3(self): 51 | s = 'Red, blUe;, red! blue!!' 52 | r = ['Red', 'blUe', 'blue', 'red'] 53 | self.assertEqual(sorted(split_sentence(s)), r) 54 | def test4(self): 55 | s = '!!' 56 | r = [''] 57 | self.assertEqual(split_sentence(s), r) 58 | def test5(self): 59 | self.assertEqual(split_sentence(''), []) 60 | 61 | if __name__=='__main__': 62 | unittest.main(exit=True) -------------------------------------------------------------------------------- /Review/Answers/SentenceTokens.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def sentence_splitter(sentence) : 4 | ''' 5 | Assumes sentence is a string. 6 | Returns a list of all the words in sentence, where a word is a token 7 | separated by white space, (you can use sentence.split()), and then 8 | for each word, make it lowercase and remove any character that is not 9 | alpha-numeric (a-z or 0-9). 10 | 11 | For example, 12 | sentence_splitter('"The Plague" (French: "La Peste"), 1947, by Albert Camus.') 13 | should return ['the', 'plague', 'french', 'la', 'peste', '1947', 'by', 'albert', 'camus'] 14 | sentence_splitter('Red@Dragon....ca is great!') 15 | should return ['reddragonca', 'is', 'great'] 16 | ''' 17 | word_list = sentence.split() 18 | new_list = [] 19 | alpha_numeric = "0123456789abcdefghijklmnopqrstuvwxyz" 20 | 21 | for word in word_list: 22 | word = word.lower() 23 | new_string = "" 24 | for letter in word: 25 | if letter in alpha_numeric: 26 | new_string += letter 27 | new_list.append(new_string) 28 | 29 | return new_list 30 | 31 | 32 | class SentenceTests(unittest.TestCase): 33 | def test1(self): 34 | s = '"The Plague" (French: "La Peste"), 1947, by Albert Camus.' 35 | r = ['the', 'plague', 'french', 'la', 'peste', '1947', 'by', 'albert', 'camus'] 36 | self.assertEqual(sentence_splitter(s), r) 37 | def test2(self): 38 | s = 'Hey diddle diddle the cat and the fiddle, the cow jumped over the moon.' 39 | r = ['hey', 'diddle', 'diddle', 'the', 'cat', 'and', 'the', 'fiddle', 'the', 'cow', 'jumped', 'over', 'the', 'moon'] 40 | self.assertEqual(sentence_splitter(s), r) 41 | def test3(self): 42 | s = 'The end of the free lunch??!!' 43 | r = ['the', 'end', 'of', 'the', 'free', 'lunch'] 44 | self.assertEqual(sentence_splitter(s), r) 45 | ''' 46 | Edge cases are here. 47 | ''' 48 | def test4(self): 49 | s = '?@?@#' 50 | r = [''] 51 | self.assertEqual(sentence_splitter(s), r) 52 | def test5(self): 53 | self.assertEqual(sentence_splitter(''), []) 54 | 55 | if __name__=='__main__': 56 | unittest.main(exit=True) 57 | -------------------------------------------------------------------------------- /Week_11/Lang_Dict.py: -------------------------------------------------------------------------------- 1 | class LangDict: 2 | ''' 3 | This class is a demonstration of more class syntax, 4 | as well as containing a dictionary in a class. 5 | ''' 6 | 7 | # Notice that we only have name as an argument for the init function 8 | # This is to demonstrate that you don't need to initialize with arguments 9 | # necessarily. You can easily have member variables that weren't fed in as 10 | # arguments 11 | def __init__(self, name): 12 | self.name = name 13 | self.lang_dict = {} 14 | 15 | def add_dict(self, k, v): 16 | self.lang_dict[k] = v 17 | 18 | def look_up(self, search): 19 | # You can check if a key exists in a dictionary with the key word "in" 20 | if search in self.lang_dict: 21 | # This is also the syntax for getting a value from a dictionary 22 | # dictionary[key] -> value 23 | return self.lang_dict[search] 24 | else: 25 | return None 26 | 27 | # A menu helper function to make this program run a bit easier. 28 | def menu(): 29 | choice = 0 30 | 31 | while choice != 1 and choice != 2: 32 | choice = int(input("If you would like to add a key/value pair to the dictionary, press 1. If you would like to search for a key, press 2.\n")) 33 | 34 | return choice 35 | 36 | # Main block for this program. We create a dictionary and then enter words and their definitions 37 | # to it. 38 | if __name__ == "__main__": 39 | new_dict_class = LangDict(input("Please enter the name of the dictionary.\n")) 40 | 41 | inp = "-1" 42 | 43 | while inp != "": 44 | option = menu() 45 | if option == 1: 46 | k = str(input("Please input a word.\n")) 47 | v = str(input("Please input its definition.\n")) 48 | new_dict_class.add_dict(k, v) 49 | elif option == 2: 50 | result = new_dict_class.look_up(str(input("What word would you like to look up?\n"))) 51 | if result == None: 52 | print("Word does not exist in the dictionary! Please add it.") 53 | else: 54 | print(str(result)) 55 | inp = str(input("Press 'enter' to exit. Otherwise, enter whatever you want lol.\n")) 56 | -------------------------------------------------------------------------------- /Review/Answers/CreateTest.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import Brackets 3 | import RecursiveBrackets 4 | 5 | ''' 6 | For this question, assume you have a function called find_balance 7 | from a seperate module called Brackets. This function takes one 8 | argument, a string of 0 or more brackets, such as "}}{{}{}" or 9 | "}}}{{{" or "{}{}{}{}". It will access whether or not a string of 10 | these brackets is balanced or not. If a string IS balanced, it will 11 | return True. If it IS NOT balanced, it will return False. 12 | 13 | A string is considered balanced if it is empty, if it is of the form 14 | {}, or it is of the form {x}, where x is also a balanced string. It is 15 | also balanced if it is of the form {x}{x}, where x is either empty, or 16 | contains other balanced strings. So, for example, 17 | 18 | Brackets.find_balance("{{}}") -> True 19 | Brackets.find_balance("}{") -> False 20 | 21 | Write FIVE test cases for this function, including two that account for 22 | abnormal (edge) cases. Do not include the two examples above. 23 | 24 | To call this function, you will use the syntax Brackets.find_balance(argument). 25 | ''' 26 | ''' 27 | class BracketTest(unittest.TestCase): 28 | def test1(self): 29 | self.assertEqual(Brackets.find_balance("{{}}"), True) 30 | def test2(self): 31 | self.assertEqual(Brackets.find_balance("}}{{"), False) 32 | def test3(self): 33 | self.assertEqual(Brackets.find_balance("}}}}"), False) 34 | def test4(self): 35 | self.assertEqual(Brackets.find_balance("{}{}{}{}"), True) 36 | def test5(self): 37 | self.assertEqual(Brackets.find_balance("{{}}{}{{}}"), True) 38 | ''' 39 | 40 | class BracketTest(unittest.TestCase): 41 | def test1(self): 42 | self.assertEqual(RecursiveBrackets.find_balance("{{}}"), True) 43 | def test2(self): 44 | self.assertEqual(RecursiveBrackets.find_balance("}}{{"), False) 45 | def test3(self): 46 | self.assertEqual(RecursiveBrackets.find_balance("}}}}"), False) 47 | def test4(self): 48 | self.assertEqual(RecursiveBrackets.find_balance("{}{}{}{}"), True) 49 | def test5(self): 50 | self.assertEqual(RecursiveBrackets.find_balance("{{}}{}{{}}"), True) 51 | 52 | if __name__ == "__main__": 53 | unittest.main(exit=True) -------------------------------------------------------------------------------- /Review/AlexMidtermQuestionBank/q8-7.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | def primeTime(showDict, viewerList): 4 | ''' 5 | Assume that showDict is a dictionary containing the names of TV shows and their air times in military time. 6 | Also, assume that each show airs for an hour 7 | 8 | For example: 9 | { 10 | 'Nighly News':1800, 11 | 'Really Ancient Aliens':2200, 12 | 'Morning Report':600, 13 | 'Mourning Report':1130 14 | } 15 | 16 | and that viewerList contains a list of tuples representing the start and stop times of when a user watches their TV 17 | 18 | For example: 19 | [(600,1230),(1200,1900),(1130,1230)] 20 | 21 | Return the name of the most watched show, assuming that a user 'watches' the show if its air time 22 | falls between their start and stop times, and that they watch the show for its full duration of an hour. 23 | 24 | For example: 25 | User 1 (600,1230) watched 'Morning Report' and, 'Mourning Report' in their entirety 26 | User 2 (1200,1900) watched 'Nightly News' in its entirety 27 | User 3 (1130,1230) watched 'Mourning Report' in their entirety 28 | 29 | Because 2 users watched 'Mourning Report' in its entirety, return the function would return 'Mourning Report' 30 | ''' 31 | pass 32 | 33 | class primeTimeTests(unittest.TestCase): 34 | def test1(self): 35 | self.assertEqual(primeTime({'Nighly News':1800, 'Really Ancient Aliens':2200, 'Morning Report':600, 'Mourning Report':1130}, [(600,1230),(1200,1900),(1130,1230)]),'Mourning Report') 36 | def test2(self): 37 | self.assertEqual(primeTime({'Jazz Nightly':1900, 'Speedy Cars':1200, 'McGruff, Crime Dog':1600, 'Worm Eating Contest':100}, [(100,200),(10,1900),(120,1300),(1200,1700)]),'Speedy Cars') 38 | def test3(self): 39 | self.assertEqual(primeTime({'Jazz Nightly':1900, 'Speedy Cars':1200, 'McGruff, Crime Dog':1600, 'Worm Eating Contest':100}, [(100,200),(10,1900),(1230,2000),(1200,2000)]),'McGruff, Crime Dog') 40 | def test4(self): 41 | self.assertEqual(primeTime({'3 Billion Devices drinking coffee':1000,'See Sharp, an intro to coding at Microsoft':900, 'Steve Irwin teaches Python':1900}, [(10,200),(10,1800),(900,1000),(900,1999)]),'See Sharp, an intro to coding at Microsoft') 42 | def test5(self): 43 | self.assertEqual(primeTime({'Fortnite Pro Series':1800,'How to floss, a tutorial':1200, 'TikTok and you':700, 'How to connect with the youth':500}, [(10,600),(500,800),(1800,1900),(1200,1900)]),'Fortnite Pro Series') 44 | 45 | 46 | if __name__ == '__main__': 47 | unittest.main(exit=True) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 110 | .pdm.toml 111 | .pdm-python 112 | .pdm-build/ 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | -------------------------------------------------------------------------------- /Week_1/DataTypeCheatSheet.py: -------------------------------------------------------------------------------- 1 | #Python primitive data type cheatsheet 2 | 3 | #Note on Python and variable assignment: Python is a DYNAMICALLY TYPED language, 4 | # if you come from a Java background you will wonder why we aren't declaring any types during variable assignment. 5 | #This is because in Python, variable types are evaluated at run time, meaning the program doesn't know the data type for 6 | # it's variables until it executes the line where the variable gets assigned 7 | # Also note: everything in Python is an 'objet' more on that later 8 | 9 | #Integers can be declared as numbers with no decimal point 10 | #note when declaring a variable DO NOT USE RESERVED KEYWORDS this leads to confusion when reading your code 11 | myInteger = 1 12 | 13 | #floats (floating point numbers) can be declared as 14 | myFloating = 4.56789 15 | 16 | #booleans (bools) can be declared similarly, but we won't do this often in code 17 | myBool = True #note in python, True/False is always capitalized 18 | 19 | #Strings can be declared with single quotes: 20 | myString = 'This is a string' 21 | #or with double quotes 22 | myString2 = "This is a string" 23 | #or with triple quotes spanning multiple lines 24 | myString3 = '''This 25 | is 26 | a 27 | string 28 | ''' 29 | #or with triple double quotes spanning multiple lines 30 | myString4 = """ 31 | This 32 | is 33 | a 34 | string 35 | """ 36 | 37 | #note that we can get the type of a variable by using the 'type' function 38 | #only used for debugging purposes 39 | print(type(myInteger)) # 40 | print(type(myFloating)) # 41 | print(type(myBool)) # 42 | print(type(myString)) # 43 | 44 | #Why does it say the word 'class' here? Because since everything in Python is an object, everything in the backend has what is called a 'Class definition' 45 | #A class is used to define the properties,methods etc of an object 46 | #An object is an 'instance' of a class 47 | #more on that later in the course don't worry about this now... 48 | 49 | 50 | #We can also cast objects and turn them into other objects ex: 51 | 52 | intcast = int(myFloating) #transform float to integer, 'truncating' (removing) the fractional component (lose data) 53 | floatcast = float(myInteger) #transforms integer to float 54 | stringcast = str(myInteger) #transforms integer to string (note the 'print' function does this automatically) 55 | 56 | 57 | #Integer Operations 58 | # Python supports: 59 | # the addition operator(+), 60 | # subtraction operator (-), 61 | # multiplication operator (*) 62 | # and division operator (/) 63 | # Order of operations follows BEDMAS (Brackets, Exponents, Division, Multiplication, Addition, Subtraction) 64 | ##Bonus 65 | # Integer division (removes fractions) (//) 66 | # Modulus operator (%) returns only the remainder component from a division 67 | # Exponent operator (**) e.g 2**4 = 16, 4**0.5 = 2 68 | new_integer = (myInteger + 5) * 6 / 2 - 1 #What will the new_integer value be? 69 | int_division = 7//2 #outputs 3 70 | modulo = 3 % 2 #What will the modulo value be? 71 | exp_example = 5**2 72 | exp_example2 = 48**0.5 #Effectively taking the square root 73 | 74 | #All these operations also work on floats, but note that if you perform a division on an integer 75 | # that does not divide evenly the output will be a float to account for the decimal 76 | 77 | #Boolean operations 78 | #These can be useful for control statements 79 | _integer = 10 80 | mybool = True and False #False, both values need to be true in order to return true 81 | mybool2 = True or False #True , one value needs to be true in order to return true 82 | #the 'not' operator flips the boolean value from 'True' to 'False' and vice versa 83 | mybool3 = not True #False 84 | mybool4 = _integer == 10 #'==' is the equality operator, it checks if the values on either side are the same and evaluates to either true or false 85 | mybool5 = _integer > 5 #True, Greater than sign checks if the value on the left is greater than the value on the right, can be used for floats, has many weird interactions with certain datatypes 86 | mybool6 = _integer >= 10 #True This operator checks for both greater than, and equality 87 | mybool7 = _integer < 5 #false 88 | mybool8 = _integer <= 5 #false 89 | 90 | #You can also group many operators together 91 | # order of operations goes by Brackets > Everything else from left to right 92 | question = False and True or False #what does this evaluate to? 93 | question2 = (True or False) and True #what about this? 94 | mega_bool = not(mybool3 and mybool4 or (not mybool5 and mybool6)) 95 | -------------------------------------------------------------------------------- /Review/ClassExamPrepQuestion.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | ''' 4 | Completing this class rundown should mean that you are pretty well-prepared for the 5 | upcoming exam questions (or at least most of them) on classes. 6 | 7 | Generally, concepts you should be familiar with are: 8 | 1. Creating an "__init__" method for your class 9 | (Including how to make default variables within your class) 10 | 2. Accessing, modifying, and defining variables in the class 11 | 3. Creating instance methods within your class 12 | 4. How to use helper methods alongside classes 13 | 14 | This question will get you to do all of the above, and I'll identify the relevant 15 | sections so you can practice what you need specifically. I'll also be going over 16 | the solution to this during the Review Session on Sunday December 5th at 10 am, 17 | and I'll post the solutions on the Discord too! 18 | ''' 19 | 20 | ''' 21 | Story: The Teletubbies are vanquished, but in the realm of dreams they still haunt 22 | you! Your task is to implement the following classes and helper methods according 23 | to the requirements described in each class/method, so as to conquer your nightmares, 24 | and obliterate all traces of the Teletubbies! 25 | ''' 26 | 27 | class Dream: 28 | ''' 29 | Dreams are pretty good. Usually with apple pies and candies and all that good stuff. 30 | 31 | Your task is as follows: 32 | Construct the "__init__" method for a Dream class, that takes in 2 arguments (plus self), 33 | self (which you ALWAYS require in your constructors, even if there is nothing else in them!) 34 | a string "title", and 35 | an int "length" 36 | And sets a list dream_elements to start as the empty list: [] 37 | [1] 38 | 39 | Then, once you have completed your constructor, create an instance method called 40 | change_title(a), which changes the title of your dream instance to the string a. 41 | [2, 3] 42 | 43 | Then, create another instance method called add_to_dream(topic), which adds the string 44 | topic to the dream_elements list. 45 | [2, 3] 46 | 47 | Finally, create an instance method dreams_to_dust(), which replaces each element of the 48 | dream_elements list with the string "dust". 49 | [2, 3] 50 | ''' 51 | pass 52 | 53 | class Nightmare: 54 | ''' 55 | Nightmares are pretty bad. Usually with Teletubbies and chainsaws and all that bad stuff. 56 | 57 | Your task is as follows: 58 | Construct the "__init__" method for a Nightmare class, that takes in 0 arguments (except self of course)! 59 | However, you should create an instance variable "topic" that defaults to the string 60 | "Teletubbies", and an instance variable for an attached Dream that the nightmare is 61 | in, called "attached_dream" (which defaults to None). 62 | [1] 63 | 64 | Then, create a method attach_to_dream(d), which attached your nightmare instance 65 | to a dream via setting attached_dream to the argument Dream d. 66 | [2, 3] 67 | 68 | Then, create a method has_attached_dream() which returns True if your attached_dream 69 | is not None, and False otherwise. 70 | [2, 3] 71 | 72 | Finally, create a method WAKE_ME_UP(), which will set the attached_dream's length to 0, 73 | and call it's dreams_to_dust() method. 74 | [2, 3] 75 | ''' 76 | pass 77 | 78 | def return_titles(list_of_dreams): 79 | ''' 80 | Create a method that takes in a list of Dreams "list_of_dreams" as input, and returns 81 | a list containing the titles of all Dreams in that list. 82 | [2, 4] 83 | ''' 84 | pass 85 | 86 | def WAKE_ME_UP_INSIDE(cant_wake_up): 87 | ''' 88 | Create a method that takes in a list of Nightmares "cant_wake_up", as input, which 89 | then calls the WAKE_ME_UP() method for each Nightmare in the list. 90 | [3, 4] 91 | ''' 92 | pass 93 | 94 | def how_long_are_my_dreams(list_of_dreams): 95 | ''' 96 | Create a method that takes in a list of Dreams "list of dreams" as input, and returns 97 | the sum of all Dream lengths in that list. 98 | [2, 4] 99 | ''' 100 | pass 101 | 102 | # -------------------------------------------------------------- 103 | # The Testing 104 | # -------------------------------------------------------------- 105 | class myTests(unittest.TestCase): 106 | def test1(self): # Testing Dream constructor 107 | d = Dream("my awesome dream", 5) 108 | self.assertEqual(d.title, "my awesome dream") 109 | self.assertEqual(d.length, 5) 110 | self.assertEqual(d.dream_elements, []) 111 | def test2(self): # Testing nightmare constructor 112 | n = Nightmare() 113 | self.assertEqual(n.topic, "Teletubbies") 114 | self.assertEqual(n.attached_dream, None) 115 | def test3(self): # Testing Dream.change_title() 116 | d = Dream("my awesome dream", 5) 117 | d.change_title("my great dream") 118 | self.assertEqual(d.title, "my great dream") 119 | def test4(self): # Testing Dream.add_to_dream() 120 | d = Dream("my awesome dream", 5) 121 | d.change_title("my great dream") 122 | d.add_to_dream("rainbows") 123 | d.add_to_dream("butterflies") 124 | self.assertEqual(d.dream_elements, ["rainbows", "butterflies"]) 125 | def test5(self): # Testing Dream.dreams_to_dust() 126 | d = Dream("my ruined dream", 5) 127 | d.add_to_dream("rainbows") 128 | d.add_to_dream("butterflies") 129 | d.add_to_dream("horsies") 130 | d.dreams_to_dust() 131 | self.assertEqual(d.dream_elements, ["dust", "dust", "dust"]) 132 | def test6(self): # Testing Nightmare.attach_to_dream() 133 | n = Nightmare() 134 | d = Dream("my awesome dream", 5) 135 | n.attach_to_dream(d) 136 | self.assertEqual(n.attached_dream, d) 137 | def test7(self): 138 | n = Nightmare() 139 | d = Dream("my awesome dream", 5) 140 | self.assertEqual(n.has_attached_dream(), False) 141 | n.attach_to_dream(d) 142 | self.assertEqual(n.has_attached_dream(), True) 143 | def test8(self): # Testing Nightmare.WAKE_ME_UP() 144 | n = Nightmare() 145 | d = Dream("my awesome dream", 5) 146 | d.add_to_dream("pumpkins") 147 | n.attach_to_dream(d) 148 | n.WAKE_ME_UP() 149 | self.assertEqual(d.length, 0) 150 | self.assertEqual(d.dream_elements, ["dust"]) 151 | def test9(self): # Testing return_titles() 152 | d1 = Dream("my awesome dream!", 5) 153 | d2 = Dream("my fantastic dream!!", 4) 154 | d3 = Dream("my superb dream!!!", 3) 155 | self.assertEqual(return_titles([d1, d2, d3]), ["my awesome dream!", "my fantastic dream!!", "my superb dream!!!"]) 156 | def test10(self): # Testing WAKE_ME_UP_INSIDE() 157 | d1 = Dream("my awesome dream!", 5) 158 | d1.add_to_dream("sprinkles") 159 | d2 = Dream("my fantastic dream!!", 4) 160 | d2.add_to_dream("cake") 161 | d2.add_to_dream("chocolates") 162 | n1 = Nightmare() 163 | n2 = Nightmare() 164 | n1.attach_to_dream(d1) 165 | n2.attach_to_dream(d2) 166 | WAKE_ME_UP_INSIDE([n1, n2]) 167 | self.assertEqual(d1.length, 0) 168 | self.assertEqual(d2.length, 0) 169 | self.assertEqual(d1.dream_elements, ["dust"]) 170 | self.assertEqual(d2.dream_elements, ["dust", "dust"]) 171 | def test11(self): # Testing how_long_are_my_dreams() 172 | d1 = Dream("my awesome dream!", 5) 173 | d2 = Dream("my fantastic dream!!", 4) 174 | d3 = Dream("my superb dream!!!", 3) 175 | self.assertEqual(how_long_are_my_dreams([d1, d2, d3]), 12) 176 | if __name__ == '__main__': 177 | unittest.main(exit=True) 178 | # -------------------------------------------------------------- 179 | # The End 180 | # -------------------------------------------------------------- 181 | -------------------------------------------------------------------------------- /Review/Answers/ClassExamPrepSolution.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | ''' 4 | Completing this class rundown should mean that you are pretty well-prepared for the 5 | upcoming exam questions (or at least most of them) on classes. 6 | 7 | Generally, concepts you should be familiar with are: 8 | 1. Creating an "__init__" method for your class 9 | (Including how to make default variables within your class) 10 | 2. Accessing, modifying, and defining variables in the class 11 | 3. Creating instance methods within your class 12 | 4. How to use helper methods alongside classes 13 | 14 | This question will get you to do all of the above, and I'll identify the relevant 15 | sections so you can practice what you need specifically. I'll also be going over 16 | the solution to this during the Review Session on Sunday December 5th at 10 am, 17 | and I'll post the solutions on the Discord too! 18 | ''' 19 | 20 | ''' 21 | Story: The Teletubbies are vanquished, but in the realm of dreams they still haunt 22 | you! Your task is to implement the following classes and helper methods according 23 | to the requirements described in each class/method, so as to conquer your nightmares, 24 | and obliterate all traces of the Teletubbies! 25 | ''' 26 | 27 | class Dream: 28 | ''' 29 | Dreams are pretty good. Usually with apple pies and candies and all that good stuff. 30 | 31 | Your task is as follows: 32 | Construct the "__init__" method for a Dream class, that takes in 2 arguments (plus self), 33 | self (which you ALWAYS require in your constructors, even if there is nothing else in them!) 34 | a string "title", and 35 | an int "length" 36 | And sets a list dream_elements to start as the empty list: [] 37 | [1] 38 | 39 | Then, once you have completed your constructor, create an instance method called 40 | change_title(a), which changes the title of your dream instance to the string a. 41 | [2, 3] 42 | 43 | Then, create another instance method called add_to_dream(topic), which adds the string 44 | topic to the dream_elements list. 45 | [2, 3] 46 | 47 | Finally, create an instance method dreams_to_dust(), which replaces each element of the 48 | dream_elements list with the string "dust". 49 | [2, 3] 50 | ''' 51 | def __init__(self, title, length): 52 | self.title = title 53 | self.length = length 54 | self.dream_elements = [] 55 | 56 | def change_title(self, a): 57 | self.title = a 58 | 59 | def add_to_dream(self, topic): 60 | self.dream_elements.append(topic) 61 | 62 | def dreams_to_dust(self): 63 | for element in range(len(self.dream_elements)): 64 | self.dream_elements[element] = "dust" 65 | 66 | class Nightmare: 67 | ''' 68 | Nightmares are pretty bad. Usually with Teletubbies and chainsaws and all that bad stuff. 69 | 70 | Your task is as follows: 71 | Construct the "__init__" method for a Nightmare class, that takes in 0 arguments (except self of course)! 72 | However, you should create an instance variable "topic" that defaults to the string 73 | "Teletubbies", and an instance variable for an attached Dream that the nightmare is 74 | in, called "attached_dream" (which defaults to None). 75 | [1] 76 | 77 | Then, create a method attach_to_dream(d), which attached your nightmare instance 78 | to a dream via setting attached_dream to the argument Dream d. 79 | [2, 3] 80 | 81 | Then, create a method has_attached_dream() which returns True if your attached_dream 82 | is not None, and False otherwise. 83 | [2, 3] 84 | 85 | Finally, create a method WAKE_ME_UP(), which will set the attached_dream's length to 0, 86 | and call it's dreams_to_dust() method. 87 | [2, 3] 88 | ''' 89 | def __init__(self): 90 | self.topic = "Teletubbies" 91 | self.attached_dream = None 92 | 93 | def attach_to_dream(self, d): 94 | self.attached_dream = d 95 | 96 | def has_attached_dream(self): 97 | if (self.attached_dream is not None): 98 | return True 99 | else: 100 | return False 101 | 102 | def WAKE_ME_UP(self): 103 | if (self.has_attached_dream()): 104 | self.attached_dream.length = 0 105 | self.attached_dream.dreams_to_dust() 106 | 107 | def return_titles(list_of_dreams): 108 | ''' 109 | Create a method that takes in a list of Dreams "list_of_dreams" as input, and returns 110 | a list containing the titles of all Dreams in that list. 111 | [2, 4] 112 | ''' 113 | to_return_list = [] 114 | for dream in list_of_dreams: 115 | to_return_list.append(dream.title) 116 | return to_return_list 117 | 118 | def WAKE_ME_UP_INSIDE(cant_wake_up): 119 | ''' 120 | Create a method that takes in a list of Nightmares "cant_wake_up", as input, which 121 | then calls the WAKE_ME_UP() method for each Nightmare in the list. 122 | [3, 4] 123 | ''' 124 | for nightmare in cant_wake_up: 125 | nightmare.WAKE_ME_UP() 126 | 127 | def how_long_are_my_dreams(list_of_dreams): 128 | ''' 129 | Create a method that takes in a list of Dreams "list of dreams" as input, and returns 130 | the sum of all Dream lengths in that list. 131 | [2, 4] 132 | ''' 133 | total_sum = 0 134 | for dream in list_of_dreams: 135 | total_sum += dream.length 136 | return total_sum 137 | 138 | # -------------------------------------------------------------- 139 | # The Testing 140 | # -------------------------------------------------------------- 141 | class myTests(unittest.TestCase): 142 | def test1(self): # Testing Dream constructor 143 | d = Dream("my awesome dream", 5) 144 | self.assertEqual(d.title, "my awesome dream") 145 | self.assertEqual(d.length, 5) 146 | self.assertEqual(d.dream_elements, []) 147 | def test2(self): # Testing nightmare constructor 148 | n = Nightmare() 149 | self.assertEqual(n.topic, "Teletubbies") 150 | self.assertEqual(n.attached_dream, None) 151 | def test3(self): # Testing Dream.change_title() 152 | d = Dream("my awesome dream", 5) 153 | d.change_title("my great dream") 154 | self.assertEqual(d.title, "my great dream") 155 | def test4(self): # Testing Dream.add_to_dream() 156 | d = Dream("my awesome dream", 5) 157 | d.change_title("my great dream") 158 | d.add_to_dream("rainbows") 159 | d.add_to_dream("butterflies") 160 | self.assertEqual(d.dream_elements, ["rainbows", "butterflies"]) 161 | def test5(self): # Testing Dream.dreams_to_dust() 162 | d = Dream("my ruined dream", 5) 163 | d.add_to_dream("rainbows") 164 | d.add_to_dream("butterflies") 165 | d.add_to_dream("horsies") 166 | d.dreams_to_dust() 167 | self.assertEqual(d.dream_elements, ["dust", "dust", "dust"]) 168 | def test6(self): # Testing Nightmare.attach_to_dream() 169 | n = Nightmare() 170 | d = Dream("my awesome dream", 5) 171 | n.attach_to_dream(d) 172 | self.assertEqual(n.attached_dream, d) 173 | def test7(self): 174 | n = Nightmare() 175 | d = Dream("my awesome dream", 5) 176 | self.assertEqual(n.has_attached_dream(), False) 177 | n.attach_to_dream(d) 178 | self.assertEqual(n.has_attached_dream(), True) 179 | def test8(self): # Testing Nightmare.WAKE_ME_UP() 180 | n = Nightmare() 181 | d = Dream("my awesome dream", 5) 182 | d.add_to_dream("pumpkins") 183 | n.attach_to_dream(d) 184 | n.WAKE_ME_UP() 185 | self.assertEqual(d.length, 0) 186 | self.assertEqual(d.dream_elements, ["dust"]) 187 | def test9(self): # Testing return_titles() 188 | d1 = Dream("my awesome dream!", 5) 189 | d2 = Dream("my fantastic dream!!", 4) 190 | d3 = Dream("my superb dream!!!", 3) 191 | self.assertEqual(return_titles([d1, d2, d3]), ["my awesome dream!", "my fantastic dream!!", "my superb dream!!!"]) 192 | def test10(self): # Testing WAKE_ME_UP_INSIDE() 193 | d1 = Dream("my awesome dream!", 5) 194 | d1.add_to_dream("sprinkles") 195 | d2 = Dream("my fantastic dream!!", 4) 196 | d2.add_to_dream("cake") 197 | d2.add_to_dream("chocolates") 198 | n1 = Nightmare() 199 | n2 = Nightmare() 200 | n1.attach_to_dream(d1) 201 | n2.attach_to_dream(d2) 202 | WAKE_ME_UP_INSIDE([n1, n2]) 203 | self.assertEqual(d1.length, 0) 204 | self.assertEqual(d2.length, 0) 205 | self.assertEqual(d1.dream_elements, ["dust"]) 206 | self.assertEqual(d2.dream_elements, ["dust", "dust"]) 207 | def test11(self): # Testing how_long_are_my_dreams() 208 | d1 = Dream("my awesome dream!", 5) 209 | d2 = Dream("my fantastic dream!!", 4) 210 | d3 = Dream("my superb dream!!!", 3) 211 | self.assertEqual(how_long_are_my_dreams([d1, d2, d3]), 12) 212 | if __name__ == '__main__': 213 | unittest.main(exit=True) 214 | # -------------------------------------------------------------- 215 | # The End 216 | # -------------------------------------------------------------- 217 | --------------------------------------------------------------------------------