diff --git a/Python-Projects(Beginner)/Arithmetic-Formatter/ArthemeticFormatter.py b/Python-Projects(Beginner)/Arithmetic-Formatter/ArthemeticFormatter.py new file mode 100644 index 0000000..8b05015 --- /dev/null +++ b/Python-Projects(Beginner)/Arithmetic-Formatter/ArthemeticFormatter.py @@ -0,0 +1,71 @@ +def arithmetic_arranger(problems: str, answers: bool=False) -> str: + """ Returns the problems arranged vertically and side-by-side. """ + + # Error handling + if len(problems) > 5: + return "Error: Too many problems." + + for problem in problems: + problem = problem.split() + + if problem[1] not in ["+", "-"]: + return "Error: Operator must be '+' or '-'." + elif not problem[0].isnumeric() or not problem[2].isnumeric(): + return "Error: Numbers must only contain digits." + elif len(problem[0]) > 4 or len(problem[2]) > 4: + return "Error: Numbers cannot be more than four digits." + + # Rearrange functionality + arranged_problems = "" + line_one = [] + line_two = [] + line_three = [] + problem_answers = [] + between = " " * 4 + + for problem in problems: + problem = problem.split() + + # Determine what's the largest digit + largest = "" + if len(problem[0]) > len(problem[2]): + largest = problem[0] + elif len(problem[0]) < len(problem[2]): + largest = problem[2] + else: + largest = problem[0] + + dashes = "-" * (len(largest) + 2) + + # "Space" refers to blank spaces + spaces_one = "" + spaces_two = "" + if largest == problem[0]: + spaces_one = " " * 2 + spaces_two = " " * (len(largest) - len(problem[2])) + elif largest != problem[0]: + spaces_one = " " * ((len(largest) + 2) - len(problem[0])) + + # Line formatting + line_one.append(f"{spaces_one}{problem[0]}") + line_two.append(f"{problem[1]} {spaces_two}{problem[2]}") + line_three.append(f"{dashes}") + + result = eval(f"{problem[0]}{problem[1]}{problem[2]}") + spaces_three = " " * (len(dashes) - len(str(result))) + + problem_answers.append(f"{spaces_three}{result}") + + arranged_problems = ( + f"{between.join(line_one)}\n" + f"{between.join(line_two)}\n" + f"{between.join(line_three)}" + ) + + # If `answers` is True, print the answers; otherwise delete the variable + if answers: + arranged_problems += f"\n{between.join(problem_answers)}" + else: + del problem_answers + + return arranged_problems \ No newline at end of file diff --git a/Python-Projects(Beginner)/Arithmetic-Formatter/README.md b/Python-Projects(Beginner)/Arithmetic-Formatter/README.md new file mode 100644 index 0000000..8665e7b --- /dev/null +++ b/Python-Projects(Beginner)/Arithmetic-Formatter/README.md @@ -0,0 +1,69 @@ +### Assignment + +Students in primary school often arrange arithmetic problems vertically to make them easier to solve. For example, "235 + 52" becomes: +``` + 235 ++ 52 +----- +``` + +Create a function that receives a list of strings that are arithmetic problems and returns the problems arranged vertically and side-by-side. The function should optionally take a second argument. When the second argument is set to `True`, the answers should be displayed. + +### For example + +Function Call: +```py +arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"]) +``` + +Output: +``` + 32 3801 45 123 ++ 698 - 2 + 43 + 49 +----- ------ ---- ----- +``` + +Function Call: +```py +arithmetic_arranger(["32 + 8", "1 - 3801", "9999 + 9999", "523 - 49"], True) +``` + +Output: +``` + 32 1 9999 523 ++ 8 - 3801 + 9999 - 49 +---- ------ ------ ----- + 40 -3800 19998 474 +``` + +### Rules + +The function will return the correct conversion if the supplied problems are properly formatted, otherwise, it will **return** a **string** that describes an error that is meaningful to the user. + + +* Situations that will return an error: + * If there are **too many problems** supplied to the function. The limit is **five**, anything more will return: + `Error: Too many problems.` + * The appropriate operators the function will accept are **addition** and **subtraction**. Multiplication and division will return an error. Other operators not mentioned in this bullet point will not need to be tested. The error returned will be: + `Error: Operator must be '+' or '-'.` + * Each number (operand) should only contain digits. Otherwise, the function will return: + `Error: Numbers must only contain digits.` + * Each operand (aka number on each side of the operator) has a max of four digits in width. Otherwise, the error string returned will be: + `Error: Numbers cannot be more than four digits.` +* If the user supplied the correct format of problems, the conversion you return will follow these rules: + * There should be a single space between the operator and the longest of the two operands, the operator will be on the same line as the second operand, both operands will be in the same order as provided (the first will be the top one and the second will be the bottom. + * Numbers should be right-aligned. + * There should be four spaces between each problem. + * There should be dashes at the bottom of each problem. The dashes should run along the entire length of each problem individually. (The example above shows what this should look like.) + +### Development + +Write your code in `arithmetic_arranger.py`. For development, you can use `main.py` to test your `arithmetic_arranger()` function. Click the "run" button and `main.py` will run. + +### Testing + +The unit tests for this project are in `test_module.py`. We imported the tests from `test_module.py` to `main.py` for your convenience. The tests will run automatically whenever you hit the "run" button. + +### Submitting + +Copy your project's URL and submit it to freeCodeCamp. diff --git a/Python-Projects(Beginner)/Arithmetic-Formatter/main.py b/Python-Projects(Beginner)/Arithmetic-Formatter/main.py new file mode 100644 index 0000000..dca9316 --- /dev/null +++ b/Python-Projects(Beginner)/Arithmetic-Formatter/main.py @@ -0,0 +1,9 @@ +# This entrypoint file to be used in development. Start by reading README.md +from pytest import main + +from arithmetic_arranger import arithmetic_arranger + +print(arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"])) + +# Run unit tests automatically +main(['-vv']) diff --git a/Python-Projects(Beginner)/Arithmetic-Formatter/test_module.py b/Python-Projects(Beginner)/Arithmetic-Formatter/test_module.py new file mode 100644 index 0000000..b048221 --- /dev/null +++ b/Python-Projects(Beginner)/Arithmetic-Formatter/test_module.py @@ -0,0 +1,77 @@ +import pytest + +from arithmetic_arranger import arithmetic_arranger + +test_cases = [ + pytest.param( + [['3801 - 2', '123 + 49']], + ' 3801 123\n' + '- 2 + 49\n' + '------ -----', + 'Expected different output when calling "arithmetic_arranger()" with ["3801 - 2", "123 + 49"]', + id='test_two_problems_arrangement1'), + pytest.param( + [['1 + 2', '1 - 9380']], + ' 1 1\n' + '+ 2 - 9380\n' + '--- ------', + 'Expected different output when calling "arithmetic_arranger()" with ["1 + 2", "1 - 9380"]', + id='test_two_problems_arrangement2'), + pytest.param( + [['3 + 855', '3801 - 2', '45 + 43', '123 + 49']], + ' 3 3801 45 123\n' + '+ 855 - 2 + 43 + 49\n' + '----- ------ ---- -----', + 'Expected different output when calling "arithmetic_arranger()" with ["3 + 855", "3801 - 2", "45 + 43", "123 + 49"]', + id='test_four_problems_arrangement'), + pytest.param( + [['11 + 4', '3801 - 2999', '1 + 2', '123 + 49', '1 - 9380']], + ' 11 3801 1 123 1\n' + '+ 4 - 2999 + 2 + 49 - 9380\n' + '---- ------ --- ----- ------', + 'Expected different output when calling "arithmetic_arranger()" with ["11 + 4", "3801 - 2999", "1 + 2", "123 + 49", "1 - 9380"]', + id='test_five_problems_arrangement'), + pytest.param( + [['44 + 815', '909 - 2', '45 + 43', '123 + 49', + '888 + 40', '653 + 87']], + 'Error: Too many problems.', + 'Expected calling "arithmetic_arranger()" with more than five problems to return "Error: Too many problems."', + id='test_too_many_problems'), + pytest.param( + [['3 / 855', '3801 - 2', '45 + 43', '123 + 49']], + "Error: Operator must be '+' or '-'.", + '''Expected calling "arithmetic_arranger()" with a problem that uses the "/" operator to return "Error: Operator must be '+' or '-'."''', + id='test_incorrect_operator'), + pytest.param( + [['24 + 85215', '3801 - 2', '45 + 43', '123 + 49']], + 'Error: Numbers cannot be more than four digits.', + 'Expected calling "arithmetic_arranger()" with a problem that has a number over 4 digits long to return "Error: Numbers cannot be more than four digits."', + id='test_too_many_digits'), + pytest.param( + [['98 + 3g5', '3801 - 2', '45 + 43', '123 + 49']], + 'Error: Numbers must only contain digits.', + 'Expected calling "arithmetic_arranger()" with a problem that contains a letter character in the number to return "Error: Numbers must only contain digits."', + id='test_only_digits'), + pytest.param( + [['3 + 855', '988 + 40'], True], + ' 3 988\n' + '+ 855 + 40\n' + '----- -----\n' + ' 858 1028', + 'Expected solutions to be correctly displayed in output when calling "arithmetic_arranger()" with ["3 + 855", "988 + 40"] and a second argument of `True`.', + id='test_two_problems_with_solutions'), + pytest.param( + [['32 - 698', '1 - 3801', '45 + 43', '123 + 49', '988 + 40'], True], + ' 32 1 45 123 988\n' + '- 698 - 3801 + 43 + 49 + 40\n' + '----- ------ ---- ----- -----\n' + ' -666 -3800 88 172 1028', + 'Expected solutions to be correctly displayed in output when calling "arithmetic_arranger()" with five arithmetic problems and a second argument of `True`.', + id='test_five_problems_with_solutions'), +] + + +@pytest.mark.parametrize('arguments,expected_output,fail_message', test_cases) +def test_template(arguments, expected_output, fail_message): + actual = arithmetic_arranger(*arguments) + assert actual == expected_output, fail_message diff --git a/Python-Projects(Beginner)/Budget-app/__pycache__/budgetapp.cpython-311.pyc b/Python-Projects(Beginner)/Budget-app/__pycache__/budgetapp.cpython-311.pyc new file mode 100644 index 0000000..7eb2f76 Binary files /dev/null and b/Python-Projects(Beginner)/Budget-app/__pycache__/budgetapp.cpython-311.pyc differ diff --git a/Python-Projects(Beginner)/Budget-app/budgetapp.py b/Python-Projects(Beginner)/Budget-app/budgetapp.py new file mode 100644 index 0000000..cb17f50 --- /dev/null +++ b/Python-Projects(Beginner)/Budget-app/budgetapp.py @@ -0,0 +1,86 @@ +class Category: + def __init__(self, label): + self.label = label + self.ledger = [] + + def get_balance(self): + c = 0 + for item in self.ledger: + c += item['amount'] + return c + + def check_funds(self, amount): + return amount <= self.get_balance() + + def deposit(self, amount, description=""): + self.ledger.append({"amount": amount, "description": description}) + + def withdraw(self, amount, description=""): + if self.check_funds(amount): + self.ledger.append({"amount": -amount, "description": description}) + return True + + return False + + def transfer(self, amount, obj): + if self.withdraw(amount, "Transfer to " + obj.label): + obj.deposit(amount, "Transfer from " + self.label) + return True + + return False + + def __str__(self): + output = "" + output += self.label.center(30,"*") + "\n" + + total = 0 + for item in self.ledger: + total += item['amount'] + + output += item['description'].ljust(23, " ")[:23] + output += "{0:>7.2f}".format(item['amount']) + output += "\n" + + output += "Total: " + "{0:.2f}".format(total) + return output + +def create_spend_chart(categories): + output = "Percentage spent by category\n" + + # Retrieve total expense of each category + total = 0 + expenses = [] + labels = [] + len_labels = 0 + + for item in categories: + expense = sum([-x['amount'] for x in item.ledger if x['amount'] < 0]) + total += expense + + if len(item.label) > len_labels: + len_labels = len(item.label) + + expenses.append(expense) + labels.append(item.label) + + # Convert to percent + pad labels + expenses = [(x/total)*100 for x in expenses] + labels = [label.ljust(len_labels, " ") for label in labels] + + # Format output + for c in range(100,-1,-10): + output += str(c).rjust(3, " ") + '|' + for x in expenses: + output += " o " if x >= c else " " + output += " \n" + + # Add each category name + output += " " + "---"*len(labels) + "-\n" + + for i in range(len_labels): + output += " " + for label in labels: + output += " " + label[i] + " " + output += " \n" + + return output.strip("\n") \ No newline at end of file diff --git a/Python-Projects(Beginner)/Budget-app/main.py b/Python-Projects(Beginner)/Budget-app/main.py new file mode 100644 index 0000000..334a570 --- /dev/null +++ b/Python-Projects(Beginner)/Budget-app/main.py @@ -0,0 +1,21 @@ +import budgetapp +from budgetapp import create_spend_chart + +food = budgetapp.Category("Food") +food.deposit(1000, "initial deposit") +food.withdraw(10.15, "groceries") +food.withdraw(15.89, "restaurant and more food for dessert") +print(food.get_balance()) +clothing = budgetapp.Category("Clothing") +food.transfer(50, clothing) +clothing.withdraw(25.55) +clothing.withdraw(100) +auto = budgetapp.Category("Auto") +auto.deposit(1000, "initial deposit") +auto.withdraw(15) + +print(food) +print(clothing) + +print(create_spend_chart([food, clothing, auto])) + diff --git a/Python-Projects(Beginner)/Polygon-Area-Calculator/__pycache__/shape_calculator.cpython-311.pyc b/Python-Projects(Beginner)/Polygon-Area-Calculator/__pycache__/shape_calculator.cpython-311.pyc new file mode 100644 index 0000000..232cfad Binary files /dev/null and b/Python-Projects(Beginner)/Polygon-Area-Calculator/__pycache__/shape_calculator.cpython-311.pyc differ diff --git a/Python-Projects(Beginner)/Polygon-Area-Calculator/main.py b/Python-Projects(Beginner)/Polygon-Area-Calculator/main.py new file mode 100644 index 0000000..2fd036e --- /dev/null +++ b/Python-Projects(Beginner)/Polygon-Area-Calculator/main.py @@ -0,0 +1,24 @@ +# This entrypoint file to be used in development. Start by reading README.md +import shape_calculator +# from unittest import main +rect = shape_calculator.Rectangle(10, 5) +print(rect.get_area()) +rect.set_height(3) +print(rect.get_perimeter()) +print(rect) +print(rect.get_picture()) + +sq = shape_calculator.Square(9) +print(sq.get_area()) +sq.set_side(4) +print(sq.get_diagonal()) +print(sq) +print(sq.get_picture()) + +rect.set_height(8) +rect.set_width(16) +print(rect.get_amount_inside(sq)) + + +# Run unit tests automatically +# main(module='test_module', exit=False) \ No newline at end of file diff --git a/Python-Projects(Beginner)/Polygon-Area-Calculator/shape_calculator.py b/Python-Projects(Beginner)/Polygon-Area-Calculator/shape_calculator.py new file mode 100644 index 0000000..160672c --- /dev/null +++ b/Python-Projects(Beginner)/Polygon-Area-Calculator/shape_calculator.py @@ -0,0 +1,52 @@ +class Rectangle: + def __init__(self,width=None,height=None) -> None: + self.width = width + self.height=height + def __str__(self): + return f"Rectangle(width={self.width}, height={self.height})" + def set_width(self,width:int): + self.width=width + def set_height(self,height:int): + self.height=height + def get_area(self): + return self.width*self.height + def get_perimeter(self)->float: + perimter=(2 * self.width + 2 * self.height) + return perimter + def get_diagonal(self): + dia=((self.width ** 2 + self.height ** 2) ** .5) + return dia + + def get_picture(self): + h = self.height + w = self.width + if h > 50 or w > 50: + return "Too big for picture.\n" + + picture = "" + for i in range(h): + picture += "*" * w + "\n" + + return picture + def get_amount_inside(self, shape): + if not isinstance(shape, (Rectangle, Square)): + raise ValueError("The 'shape' argument must be an instance of Rectangle or Square.") + + # Calculate how many times 'shape' can fit horizontally and vertically + horizontal_fit = self.width // shape.width + vertical_fit = self.height // shape.height + + return horizontal_fit * vertical_fit + +class Square(Rectangle): + def __init__(self, side=None) -> None: + super().__init__(width=side, height=side) + + def set_side(self,side): + super().__init__(width=side,height=side) + + def __str__(self): + return f"Square(side={self.width})" + + + diff --git a/Python-Projects(Beginner)/Probability-Calculator/main.py b/Python-Projects(Beginner)/Probability-Calculator/main.py new file mode 100644 index 0000000..a6eaa97 --- /dev/null +++ b/Python-Projects(Beginner)/Probability-Calculator/main.py @@ -0,0 +1,16 @@ +# This entrypoint file to be used in development. Start by reading README.md +import prob_calculator +# from unittest import main + +prob_calculator.random.seed(95) +hat = prob_calculator.Hat(blue=4, red=2, green=6) +probability = prob_calculator.experiment( + hat=hat, + expected_balls={"blue": 2, + "red": 1}, + num_balls_drawn=4, + num_experiments=3000) +print("Probability:", probability) + +# Run unit tests automatically +# main(module='test_module', exit=False) \ No newline at end of file diff --git a/Python-Projects(Beginner)/Probability-Calculator/prob_calculator.py b/Python-Projects(Beginner)/Probability-Calculator/prob_calculator.py new file mode 100644 index 0000000..ca86814 --- /dev/null +++ b/Python-Projects(Beginner)/Probability-Calculator/prob_calculator.py @@ -0,0 +1,53 @@ +import copy +import random +# Consider using the modules imported above. + +class Hat: + def __init__(self,**kwargs) -> None: + self.contents=[] + for color , count in kwargs.items(): + self.contents.extend([color]*count) + def draw(self,arg): + if(arg > len(self.contents)): + drawn_ball=[] + drawn_ball=self.contents + self.contents=[] + return drawn_ball + else: + drawn_balls =random.sample(self.contents,arg) + for i in drawn_balls: + self.contents.remove(i) + return drawn_balls +def experiment( + hat: object, expected_balls: dict, + num_balls_drawn: int, num_experiments: int +) -> float: + """ + Returns the probability of how many times the balls indicated + were drawn from the hat (number of successes / number of + times run). Creates a deep copy to avoid reading the same + data (list of balls). + """ + + success = 0 + for _ in range(num_experiments): + hat_copy = copy.deepcopy(hat) + + drawn_balls = hat_copy.draw(num_balls_drawn) + keep = True # False if there are not enough values + for key, value in expected_balls.items(): + if drawn_balls.count(key) < value: + keep = False + + if keep: + success += 1 + + return success / num_experiments + +hat = Hat(red=4, green=3, blue=5) +expected_balls = {"red": 2, "green": 1} +num_balls_drawn = 5 +num_experiments = 2000 + +probability = experiment(hat, expected_balls, num_balls_drawn, num_experiments) +print("Estimated probability:", probability) \ No newline at end of file diff --git a/Python-Projects(Beginner)/Time-Calculator/README.md b/Python-Projects(Beginner)/Time-Calculator/README.md new file mode 100644 index 0000000..141e22b --- /dev/null +++ b/Python-Projects(Beginner)/Time-Calculator/README.md @@ -0,0 +1,47 @@ +### Assignment + +Write a function named `add_time` that takes in two required parameters and one optional parameter: +* a start time in the 12-hour clock format (ending in AM or PM) +* a duration time that indicates the number of hours and minutes +* (optional) a starting day of the week, case insensitive + +The function should add the duration time to the start time and return the result. + +If the result will be the next day, it should show `(next day)` after the time. If the result will be more than one day later, it should show `(n days later)` after the time, where "n" is the number of days later. + +If the function is given the optional starting day of the week parameter, then the output should display the day of the week of the result. The day of the week in the output should appear after the time and before the number of days later. + +Below are some examples of different cases the function should handle. Pay close attention to the spacing and punctuation of the results. +```py +add_time("3:00 PM", "3:10") +# Returns: 6:10 PM + +add_time("11:30 AM", "2:32", "Monday") +# Returns: 2:02 PM, Monday + +add_time("11:43 AM", "00:20") +# Returns: 12:03 PM + +add_time("10:10 PM", "3:30") +# Returns: 1:40 AM (next day) + +add_time("11:43 PM", "24:20", "tueSday") +# Returns: 12:03 AM, Thursday (2 days later) + +add_time("6:30 PM", "205:12") +# Returns: 7:42 AM (9 days later) +``` + +Do not import any Python libraries. Assume that the start times are valid times. The minutes in the duration time will be a whole number less than 60, but the hour can be any whole number. + +### Development + +Write your code in `time_calculator.py`. For development, you can use `main.py` to test your `time_calculator()` function. Click the "run" button and `main.py` will run. + +### Testing + +The unit tests for this project are in `test_module.py`. We imported the tests from `test_module.py` to `main.py` for your convenience. The tests will run automatically whenever you hit the "run" button. + +### Submitting + +Copy your project's URL and submit it to freeCodeCamp. \ No newline at end of file diff --git a/Python-Projects(Beginner)/Time-Calculator/main.py b/Python-Projects(Beginner)/Time-Calculator/main.py new file mode 100644 index 0000000..ecaf44c --- /dev/null +++ b/Python-Projects(Beginner)/Time-Calculator/main.py @@ -0,0 +1,10 @@ +# This entrypoint file to be used in development. Start by reading README.md +from time_calculator import add_time +from unittest import main + + +print(add_time("3:00 PM", "3:10")) + + +# Run unit tests automatically +main(module='test_module', exit=False) \ No newline at end of file diff --git a/Python-Projects(Beginner)/Time-Calculator/time_cal.py b/Python-Projects(Beginner)/Time-Calculator/time_cal.py new file mode 100644 index 0000000..1a6dc6c --- /dev/null +++ b/Python-Projects(Beginner)/Time-Calculator/time_cal.py @@ -0,0 +1,50 @@ +def add_time(start: str, duration: str, day: str="") -> str: + """ Returns the hour of the day after the sum. """ + + start_h, start_m = start[:-3].split(":") + clock = start.split()[1] # hour format + duration_h, duration_m = duration.split(":") + + carry_h = 0 # carrying hours + days_n = 0 # number of X days later + days = "" # X days later (string-formatted) + week_days = ["Monday", "Tuesday", "Wednesday", "Thursday", + "Friday", "Saturday", "Sunday"] + + # Calculate result minutes + minutes = int(start_m) + int(duration_m) + if minutes > 60: + carry_h = minutes // 60 + minutes = minutes % 60 + + # Calculate result hours + hours = int(start_h) + int(duration_h) + carry_h + if hours >= 12: + if clock == "AM" and (hours // 12) % 2 == 1: + clock = "PM" + else: + clock = "AM" + + # Adds days later if sum resulted in 1 or more days + if clock == "AM": + if (hours // 12) == 2: + days_n = (hours // 24) + elif (hours // 12) == 1 or (hours // 12) > 2: + days_n = (hours // 24) + 1 + + if days_n == 1: + days = " (next day)" + elif days_n > 1: + days = f" ({days_n} days later)" + + hours = hours % 12 + if hours == 0: # converts 00 to 12 + hours = 12 + + if len(day) > 0: + day_n = week_days[(week_days.index(day.title()) + days_n) % 7] + day = f", {day_n}" + + new_time = f"{hours}:{str(minutes).rjust(2, '0')} {clock}{day}{days}" + + return new_time \ No newline at end of file