Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -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
69 changes: 69 additions & 0 deletions Python-Projects(Beginner)/Arithmetic-Formatter/README.md
Original file line number Diff line number Diff line change
@@ -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.
9 changes: 9 additions & 0 deletions Python-Projects(Beginner)/Arithmetic-Formatter/main.py
Original file line number Diff line number Diff line change
@@ -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'])
77 changes: 77 additions & 0 deletions Python-Projects(Beginner)/Arithmetic-Formatter/test_module.py
Original file line number Diff line number Diff line change
@@ -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
Binary file not shown.
86 changes: 86 additions & 0 deletions Python-Projects(Beginner)/Budget-app/budgetapp.py
Original file line number Diff line number Diff line change
@@ -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")
21 changes: 21 additions & 0 deletions Python-Projects(Beginner)/Budget-app/main.py
Original file line number Diff line number Diff line change
@@ -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]))

Binary file not shown.
24 changes: 24 additions & 0 deletions Python-Projects(Beginner)/Polygon-Area-Calculator/main.py
Original file line number Diff line number Diff line change
@@ -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)
Loading