Skip to content

fixed solutions in 02_lists/03_erase_canvas file and other directories #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
20 changes: 17 additions & 3 deletions PROJECTS/homework_projects/00_intro_python/02_agreement_bot.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
## Problem Statement

Write a program which asks the user what their favorite animal is, and then always responds with "My favorite animal is also ___!" (the blank should be filled in with the user-inputted animal, of course).
Write a program which asks the user what their favorite animal is, and then always responds with "My favorite animal is also \_\_\_!" (the blank should be filled in with the user-inputted animal, of course).

Here's a sample run of the program (user input is in bold italics - note the space between the prompt and the user input!):

What's your favorite animal? cow
What's your favorite animal? cow

My favorite animal is also cow!

Expand All @@ -21,4 +21,18 @@ if __name__ == '__main__':
main()
```

## Solution
## Solution

```bash
def main():
# Ask the user for their favorite animal
favorite_animal = input("What's your favorite animal? ")

# Print the response including the user's input
print(f"My favorite animal is also {favorite_animal}!")


# Ensure the script runs only when executed directly
if __name__ == '__main__':
main()
```
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ The Celsius scale is widely used to measure temperature, but places still use Fa

The equation you should use for converting from Fahrenheit to Celsius is the following:

degrees_celsius = (degrees_fahrenheit - 32) * 5.0/9.0
degrees_celsius = (degrees_fahrenheit - 32) \* 5.0/9.0

(Note. The .0 after the 5 and 9 matters in the line above!!!)

Here's a sample run of the program (user input is in bold italics):

Enter temperature in Fahrenheit: 76
Enter temperature in Fahrenheit: 76

Temperature: 76.0F = 24.444444444444443C

Expand All @@ -29,4 +29,21 @@ if __name__ == '__main__':
main()
```

## Solution
## Solution

```bash
def main():
# Prompt the user to enter temperature in Fahrenheit
degrees_fahrenheit = float(input("Enter temperature in Fahrenheit: "))

# Convert Fahrenheit to Celsius using the given formula
degrees_celsius = (degrees_fahrenheit - 32) * 5.0 / 9.0

# Print the result with both Fahrenheit and Celsius values
print(f"Temperature: {degrees_fahrenheit}F = {degrees_celsius}C")


# Ensure the script runs only when executed directly
if __name__ == '__main__':
main()
```
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Ask the user for a number and print its square (the product of the number times

Here's a sample run of the program (user input is in bold italics):

Type a number to see its square: 4
Type a number to see its square: 4

4.0 squared is 16.0

Expand All @@ -24,7 +24,6 @@ if __name__ == '__main__':
## Solution

```bash

def main():
num: float = float(input("Type a number to see its square: ")) # Make sure to cast the input to a float so we can do math with it!
print(str(num) + " squared is " + str(num ** 2)) # num * num is equivalent to num ** 2. The ** operator raises something to a power!
Expand All @@ -34,5 +33,4 @@ def main():

if __name__ == '__main__':
main()

```
```
173 changes: 99 additions & 74 deletions PROJECTS/homework_projects/02_lists/03_erase_canvas.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
## Problem Statement

Implement an 'eraser' on a canvas.
Implement an 'eraser' on a canvas.

The canvas consists of a grid of blue 'cells' which are drawn as rectangles on the screen. We then create an eraser rectangle which, when dragged around the canvas, sets all of the rectangles it is in contact with to white.

## Installation

To run this program, you need to install the `graphics.py` library. You can install it using:

```bash
pip install graphics.py
```

## Starter Code

```bash
Expand All @@ -20,92 +28,109 @@ if __name__ == '__main__':
## Solution

"""
This program implements an 'eraser' on a canvas.
This program implements an 'eraser' on a canvas.

The canvas consists of a grid of blue 'cells' which are drawn
The canvas consists of a grid of blue 'cells' which are drawn
as rectangles on the screen. We then create an eraser rectangle
which, when dragged around the canvas, sets all of the rectangles
which, when dragged around the canvas, sets all of the rectangles
it is in contact with to white.
"""

```bash
from graphics import Canvas
from graphics import GraphWin, Rectangle, Point, Text
import time
CANVAS_WIDTH : int = 400
CANVAS_HEIGHT : int = 400

CELL_SIZE : int = 40
ERASER_SIZE : int = 20

def erase_objects(canvas, eraser):
"""Erase objects in contact with the eraser"""
# Get mouse info to help us know which cells to delete
mouse_x = canvas.get_mouse_x()
mouse_y = canvas.get_mouse_y()

# Calculate where our eraser is
left_x = mouse_x
top_y = mouse_y
right_x = left_x + ERASER_SIZE
bottom_y = top_y + ERASER_SIZE

# Find things that overlap with our eraser
overlapping_objects = canvas.find_overlapping(left_x, top_y, right_x, bottom_y)

# For everything that overlaps with our eraser (that isn't our eraser), change
# its color to white
for overlapping_object in overlapping_objects:
if overlapping_object != eraser:
canvas.set_color(overlapping_object, 'white')

# There is no need to edit code beyond this point

CANVAS_WIDTH: int = 400
CANVAS_HEIGHT: int = 400

CELL_SIZE: int = 40
ERASER_SIZE: int = 20


def erase_objects(cells, eraser):
"""Erase cells that overlap with the eraser by setting their fill to white."""
eraser_p1 = eraser.getP1()
eraser_p2 = eraser.getP2()
left_x = eraser_p1.getX()
top_y = eraser_p1.getY()
right_x = eraser_p2.getX()
bottom_y = eraser_p2.getY()

# For every cell in the grid, check for overlap with the eraser
for cell in cells:
cell_p1 = cell.getP1()
cell_p2 = cell.getP2()
if (
left_x < cell_p2.getX()
and right_x > cell_p1.getX()
and top_y < cell_p2.getY()
and bottom_y > cell_p1.getY()
):
cell.setFill("white")


def main():
canvas = Canvas(CANVAS_WIDTH, CANVAS_HEIGHT)

num_rows = CANVAS_HEIGHT // CELL_SIZE # Figure out how many rows of cells we need
num_cols = CANVAS_WIDTH // CELL_SIZE # Figure out how many columns of cells we need

# Make a grid of squares based on the number of rows and columns.
# The rows and columns along with our cell size help determine where
# each individual cell belongs in our grid!
win = GraphWin("Eraser by Abdul Samad", CANVAS_WIDTH, CANVAS_HEIGHT)
win.setBackground("white")

num_rows = CANVAS_HEIGHT // CELL_SIZE
num_cols = CANVAS_WIDTH // CELL_SIZE

# Create a grid of blue squares
cells = []
for row in range(num_rows):
for col in range(num_cols):
left_x = col * CELL_SIZE
top_y = row * CELL_SIZE
right_x = left_x + CELL_SIZE # The right coordinate of the cell is CELL_SIZE pixels away from the left
bottom_y = top_y + CELL_SIZE # The bottom coordinate of the cell is CELL_SIZE pixels away from the top

# Create a single cell in the grid
cell = canvas.create_rectangle(left_x, top_y, right_x, bottom_y, 'blue')


canvas.wait_for_click() # Wait for the user to click before creating the eraser

last_click_x, last_click_y = canvas.get_last_click() # Get the starting location for the eraser

# Create our eraser
eraser = canvas.create_rectangle(
last_click_x,
last_click_y,
last_click_x + ERASER_SIZE,
last_click_y + ERASER_SIZE,
'pink'
right_x = left_x + CELL_SIZE
bottom_y = top_y + CELL_SIZE

cell = Rectangle(Point(left_x, top_y), Point(right_x, bottom_y))
cell.setFill("blue")
cell.setOutline("blue")
cell.draw(win)
cells.append(cell)

# Display instructions
instructions = Text(
Point(CANVAS_WIDTH / 2, CANVAS_HEIGHT - 10),
"Click anywhere to erase. Press any key to quit.",
)

# Move the eraser, and erase what it's touching
while True:
# Get where our mouse is and move the eraser to there
mouse_x = canvas.get_mouse_x()
mouse_y = canvas.get_mouse_y()
canvas.moveto(eraser, mouse_x, mouse_y)

# Erase anything touching the eraser
erase_objects(canvas, eraser)

time.sleep(0.05)
instructions.setSize(10)
instructions.draw(win)

# Main loop - respond to clicks until user presses a key
while win.checkKey() == "":
# Wait for a click
click = win.checkMouse()
if click:
# Create eraser at clicked position
mouse_x = click.getX()
mouse_y = click.getY()

if __name__ == '__main__':
# Remove previous eraser if it exists
try:
eraser.undraw()
except:
pass

# Create new eraser
eraser = Rectangle(
Point(mouse_x - ERASER_SIZE / 2, mouse_y - ERASER_SIZE / 2),
Point(mouse_x + ERASER_SIZE / 2, mouse_y + ERASER_SIZE / 2),
)
eraser.setFill("pink")
eraser.setOutline("red")
eraser.draw(win)

# Erase overlapping cells
erase_objects(cells, eraser)

time.sleep(0.01) # Short delay

win.close()


if __name__ == "__main__":
main()
```
```
6 changes: 4 additions & 2 deletions PROJECTS/homework_projects/02_lists/06_get_last_element.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ if __name__ == '__main__':

## Solution

```bash
def get_last_element(lst):
"""
Prints the last element of the provided list.
Expand All @@ -26,7 +27,7 @@ def get_last_element(lst):
print(lst[len(lst) - 1])

# The line below works too!!
# print(lst[-1])
# print(lst[-1])

# There is no need to edit code beyond this point

Expand All @@ -47,4 +48,5 @@ def main():


if __name__ == '__main__':
main()
main()
```
15 changes: 14 additions & 1 deletion PROJECTS/homework_projects/05_loops_control_flow/04_liftoff.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Liftoff!
There are many ways to solve this problem. One approach is to use a for loop, and to use the for loop variable i. Recall that i will keep track of how many times the for loop has completed executing its body. As an example this code:

for i in range(10):
print(i)
print(i)

Will print out the values 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. The values printed in liftoff are 10 minus the number of times the for loop has completed.

Expand All @@ -38,3 +38,16 @@ if __name__ == '__main__':

## Solution

```bash
def main():
# Loop from 10 down to 1
for i in range(10, 0, -1):
print(i)

# Print liftoff message after countdown
print("Liftoff!")


if __name__ == '__main__':
main()
```
18 changes: 16 additions & 2 deletions PROJECTS/homework_projects/05_loops_control_flow/05_double_it.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ For example if the user enters the number 2 you would then print:
64
128

Note that:
Note that:

2 doubled is 4

Expand All @@ -25,7 +25,7 @@ We stop at 128 because that value is greater than 100.

Maintain the current number in a variable named curr_value. When you double the number, you should be updating curr_value. Recall that you can double the value of curr_value using a line like:

curr_value = curr_value * 2
curr_value = curr_value \* 2

This program should have a while loop and the while loop condition should test if curr_value is less than 100. Thus, your program will have the line:

Expand All @@ -46,3 +46,17 @@ if __name__ == '__main__':

## Solution

```bash
def main():
# Ask user to enter a number
curr_value = int(input("Enter a number: "))

# Keep doubling the number until it reaches or exceeds 100
while curr_value < 100:
curr_value *= 2 # Double the value
print(curr_value) # Print the updated value


if __name__ == '__main__':
main()
```
Loading