Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions assignment3/decorator.log
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@

function: hello
positional parameters: none
keyword parameters: none
return: None
74 changes: 74 additions & 0 deletions assignment3/extend-point-to-vector.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Task 5: Extending a Class
import math

# Task 5: step 2
# Create class Point to represent a point in 2d space
class Point:
# with x and y values passed to the __init__() method.
def __init__(self, x, y):
self.x = x
self.y = y

# include method for equality
def __eq__(self, other):
# Checks if two points have the same coordinates
if not isinstance(other, Point):
return False
return self.x == other.x and self.y == other.y

# include methods for string
def __str__(self):
return f"Point({self.x}, {self.y})"

# include methods for Euclidian distance to another point
def distance(self, other):
return math.sqrt((other.x - self.x)**2 + (other.y - self.y)**2)

# Task 5: step 3
# Create a class called Vector
class Vector(Point):

# method to override the string representation so Vectors print differently than Points
def __str__(self):
return f"Vector<{self.x}, {self.y}>"

# Override the + operator so that it implements vector addition,
def __add__(self, other):
if isinstance(other, Vector):
# summing the x and y values and returning a new Vector
return Vector(self.x + other.x, self.y + other.y)
return NotImplemented

# Task 5: step 4
# Print results which demonstrate all of the classes and methods which have been implemented
if __name__ == "__main__":
p1 = Point(0, 0)
p2 = Point(3, 4)
p3 = Point(0, 0)

print(f"Point 1: {p1}")
print(f"Point 2: {p2}")
print(f"P1 equals P3 : {p1 == p3}")
print(f"Distance between P1 and P2: {p1.distance(p2)}")

print("_" * 10)

#Vector
v1 = Vector(1, 2)
v2 = Vector(3, 4)

print(f"Vector 1: {v1}")
print(f"Vector 2: {v2}")

# Vector addition
v3 = v1 + v2
print(f"Sum of V1 and V2: {v3}")

# Vector inheriting distance from Point
print(f"Distance from origin for V1: {p1.distance(v1)}")






53 changes: 53 additions & 0 deletions assignment3/hangman-closure.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# # Task 4: Closure Practice

# # Task 4: step 2
# Declare a function called make_hangman() that has one argument called secret_word
def make_hangman(secret_word):
# declare an empty array called guesses
guesses = []

# declare a function called hangman_closure() that takes a letter
def hangman_closure(letter):
# appended the new letter to the guesses array
guesses.append(letter.lower())

display_word = ""
all_guessed = True

# build display string with the current guesses
for char in secret_word.lower():
if char in guesses:
display_word += char
else:
display_word += "_"
all_guessed = False

print(display_word)
return all_guessed

return hangman_closure

# Task 4: step 3
# Implement a hangman game that uses make_hangman()
if __name__ == "__main__":

# Use the input() function to prompt for the secret word
secret = input("Enter the secret word: ").strip()

play_round = make_hangman(secret)

is_finished = False
print("\nGame started!")


# use the input() function to prompt guesses until the full word is guessed
while not is_finished:
guess = input("Guess a letter: ").strip().lower()

if len(guess) == 1 and guess.isalpha():
is_finished = play_round(guess)
else:
print("Invalid input. Please enter exactly one letter.")

# Task 4: step 4
print("Great! You have guessed the full word")
31 changes: 31 additions & 0 deletions assignment3/list-comprehensions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Task 3: List Comprehensions Practice
import csv

# Task 3: step 1

# file path related to the assignment3 folder
csv_file_path = '../csv/employees.csv'

# read the contents of the filepath into a list of lists using the csv module
with open(csv_file_path, mode='r' , newline='') as file:
reader = csv.reader(file)
employee_data = list(reader)

# Task 3: step 2

# create a list of the employee names, first_name + space + last_name.
# The list comprehension should iterate through the items in the list read from the csv file.
# Print the resulting list. Skip the item created for the heading of the csv file.

full_name = [f"{row[1]} {row[2]}" for row in employee_data[1:]]
print("Full Name: ")
print(full_name)

# Task 3: step 3
# filter list to include only those names that contain the letter "e"
names_with_e = [name for name in full_name if 'e' in name.lower()]

# Print this list
print("\n Names with letter 'e': ")
print(names_with_e)

62 changes: 62 additions & 0 deletions assignment3/log-decorator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@


import logging
from functools import wraps

# Task 1: Writing and Testing a Decorator

# one time setup
logger = logging.getLogger(__name__ + "_parameter_log")
logger.setLevel(logging.INFO)
logger.addHandler(logging.FileHandler("./decorator.log","a"))

#Task1 -step 2

# Declare decorator(logger_decorator) to log function name (func.__name__)
def logger_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
# formatt positional parameters
pos_parameters = list(args) if args else "none"

# formatt keyword parameters
key_parameters = kwargs if kwargs else "none"

# call the function for return value
result = func(*args, **kwargs)

# To write a log record:
logger.log(logging.INFO, f"function: {func.__name__}")
logger.log(logging.INFO, f"positional parameters: {pos_parameters}")
logger.log(logging.INFO, f"keyword parameters: {key_parameters}")
logger.log(logging.INFO, f"return: {result}")
return result
return wrapper

#Task1 -step 3
# Declare a function that takes no parameters and returns nothing
@logger_decorator
def hello():
print("Hello, World")

#Task1 -step 4
# Declare a function that takes a variable number of positional arguments and returns True
@logger_decorator
def check_position(*args):
return True


#Task1 -step 5
# Declare a function that takes no positional arguments and a variable number of keyword arguments, and that returns logger_decorator
@logger_decorator
def return_decorator(**kwargs):
return logger_decorator

#Task1 -step 6
# mainline code
if __name__ == "__main__":
hello()
check_position(1, "Apple", 3)
return_decorator(user="admin", level='high')

print("Please check ./decorator.log for the results.")
131 changes: 131 additions & 0 deletions assignment3/tictactoe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
# Task 6: More on Classes

# Task 6: step 2
# declare class TictactoeException that inherit from the Exception class.
class TictactoeException(Exception):

# Add an __init__ method
def __init__(self, message):

#stores an instance variable called message
self.message = message

#calls the __init__ method of the superclass
super().__init__(message)

# Task 6: step 3
# Declare also a class called Board.
class Board:

# The Board class that has variable called valid_moves
valid_moves=["upper left", "upper center", "upper right",
"middle left", "center", "middle right",
"lower left", "lower center", "lower right"]

# __init__ function that only has the self argument
def __init__(self):

# Create a 3x3 list of lists, all containing a space " "
self.board_array = [[" " for _ in range(3)] for _ in range(3)]

# Create instance variables self.turn, which is initialized to "X"
self.turn = "X"

# Task 6: step 1(part 2)

# Add a __str__() method- converts the board into a displayable string
def __str__(self):

# show the current state of the game
lines = []

# The rows to be displayed are separated by newlines ("\n")
lines.append(f" {self.board_array[0][0]} | {self.board_array[0][1]} | {self.board_array[0][2]} \n")
lines.append("-----------\n")
lines.append(f" {self.board_array[1][0]} | {self.board_array[1][1]} | {self.board_array[1][2]} \n")
lines.append("-----------\n")
lines.append(f" {self.board_array[2][0]} | {self.board_array[2][1]} | {self.board_array[2][2]} \n")
return "".join(lines)


def move(self, move_string):
if not move_string in Board.valid_moves:
raise TictactoeException("That's not a valid move.")
move_index = Board.valid_moves.index(move_string)
row = move_index // 3 # row
column = move_index % 3 #column
if self.board_array[row][column] != " ":
raise TictactoeException("That spot is taken.")
self.last_move = move_string

self.board_array[row][column] = self.turn
if self.turn == "X":
self.turn = "O"
else:
self.turn = "X"

def whats_next(self):
# check for cat's Game
cat = True
for i in range(3):
for j in range(3):
if self.board_array[i][j] == " ":
cat = False
else:
continue
break
else:
continue
break
if (cat):
return (True, "Cat's Game.")

# Check for win
win = False
for i in range(3): # check rows
if self.board_array[i][0] != " ":
if self.board_array[i][0] == self.board_array[i][1] and self.board_array[i][1] == self.board_array[i][2]:
win = True
break
if not win:
for i in range(3): # check columns
if self.board_array[0][i] != " ":
if self.board_array[0][i] == self.board_array[1][i] and self.board_array[1][i] == self.board_array[2][i]:
win = True
break
if not win:
if self.board_array[1][1] != " ": # check diagonals
if self.board_array[0][0] == self.board_array[1][1] and self.board_array[2][2] == self.board_array[1][1]:
win = True
if self.board_array[0][2] == self.board_array[1][1] and self.board_array[2][0] == self.board_array[1][1]:
win = True

# Determine return state
if win:
# if win is true then winner is the player who just moved
winner = "X" if self.turn == "O" else "O"
return (True, f"{winner} has won")
if cat:
return(True, "Cat's Game.")
return(False, f"{self.turn}'s turn.")

# Mainline Game loop
if __name__ == "__main__":
game_board = Board()
over = False

print("TicTacToe Started")
print(game_board)

while not over:
prompt = f"{game_board.turn}'s turn. Enyter move: "
user_input = input(prompt).strip().lower()

try:
game_board.move(user_input)
print(game_board)
over, message = game_board.whats_next()
print(message)
except TictactoeException as e:
print(f"------Error: {e.message} ----")

Loading