This function to calculate the area of a rectangle is not veryreadable - python-3.x

This function to calculate the area of a rectangle is not very readable. Can you refactor it, and then call the function to calculate the area with base of 5 and height of 6? Tip: a function that calculates the area of a rectangle should probably be called rectangle_area, and if it's receiving base and height, that's what the parameters should be called.
def f1(x, y):
z = x*y # the area is base*height
print("The area is " + str(z))
My Error:
def rectangle_area (x, y):
area = 5*6 # the area is base*height
print("The area is " + str(area))
(Python) - Code Style

The Answer:
def rectangle_area(base, height):
area = base*height
print("The area is " + str(area))
rectangle_area(5,6)

Accurate Answer :
given by the question base =5 and height=6
Python code Style :-
def rectangle_area(base,height):
area = base*height # the area is base*height
print(f"The area is :{str(area)}")
rectangle_area(5,6)
Output :-
The area is : 30

def rectangle_area(base, height):
area = base * height
print("The area is "+ str(area))
rectangle_area(5,6)

The code will be:
def rectangle_area(base,height):
area = base*height
return area
base = float(input("Enter the base length of the rectangle : "))
height = float(input("Enter the height of the rectangle : "))
print("The area is ",rectangle_area(base,height))
Then the output will be:
Enter the base length of the rectangle : 5
Enter the height of the rectangle : 6
The area is 30.0

Related

Interference of canvas items and problem in setting coordinates

I'm working on an animation of a moving object, while drawing it's path.
I want to draw the pixels in which the center of the object went through... but guess what? python decided to set the NW anchor of the image with the coordinates I send, instead of the center. I infer it has something to do with the pixels I draw simultaneously (creating a one pixel rectangle). so the image appear on the right of the path bellow... I want the center of it to be on the top of the pixels... adding the main of the code:
from tkinter import*
import time
dt = 0.01
clock_place = (500, 10)
def round_two(t, t0):
return round((t-t0)*100)/100
def round_three(t, t0):
return round((t-t0)*1000)/1000
# showing 'real time motion' for a known path (also cyclic), with
# parametric representation
def paint_known_path(x_pos, y_pos, t_0):
window = Tk()
canvas = Canvas(window, height=700, width=1000)
canvas.pack()
canvas.config(background='black')
tennis_ball = PhotoImage(file='tennis ball.png')
t = t_0
x = x_pos(t_0)
y = y_pos(t_0)
particle = canvas.create_image(x, y, image=tennis_ball)
clock = canvas.create_text(clock_place, text=round_two(t, t_0),
fill='white')
while True:
canvas.create_rectangle(x, y, x, y, outline='red')
canvas.itemconfig(clock, text=round_two(t, t_0))
t += dt
x = x_pos(t)
y = y_pos(t)
canvas.moveto(particle, x, y)
window.update()
if x == x_pos(t_0) and y == y_pos(t_0):
if t - t_0 > 100*dt:
break
time.sleep(dt)
canvas.create_text((500, 100), text='orbit duration: ' +
str(round_three(t, t_0)), fill='white')
window.mainloop()
It turns out to be quite a bit require, but here is the main completion components.
The first additional part that you need to add:
# print('the ten ball height', tennis_ball.height(), tennis_ball.width())
# tennis ball dimensions
tb_hght = tennis_ball.height()
tb_wdth = tennis_ball.width()
mid_point_x = x + tennis_ball.height() / 2
mid_point_y = y + tennis_ball.width() / 2
Secondly, also needed to add some functions to for x_pos and y_pos like this (these are just example functions to make the code work):
def x_pos(a):
# any function of t,
return 100
def y_pos(a):
# any function of t,
return 100
Furthermore, you need to call the function at the end like this:
paint_known_path(x_pos,y_pos,0)
Finally, need to add the mid_point_x and mid_point_y to the path that is drawn (as these will be the image centre points).

Demonstrate the use of functions in python (BMI)

Hi all very new hear I have just started to learn python, unfortunately, my knowledge is very very basic so I was asked to create a BMI inside a function this is what I have so far the error I receive when trying to run the code is weight is not defined here is my code thanks in advance
def bmi(height, weight):
height = int(input("Input your height in meters: "))
weight = int(input("Input your weight in kilogram: "))
result = (weight + height)
return result
print("Your body mass index is: ", round(weight / (height * height), 2))
In your original code the height and weight variables exist only within the scope of the bmi function while your last print statement is outside the scope of said function.
A simple fix would be to put the last print before the return like so:
def bmi():
height = int(input("Input your height in meters: "))
weight = int(input("Input your weight in kilogram: "))
result = (weight + height)
print("Your body mass index is: ", round(weight / (height * height), 2))
return result
Since you had two parameters in your bmi function you could restructure your code to retain the origin function definition:
def bmi(height, weight):
result = (weight + height)
print("Your body mass index is: ", round(weight / (height * height), 2))
return result
def main():
height = int(input("Input your height in meters: "))
weight = int(input("Input your weight in kilogram: "))
result = bmi(height, weight)
...

Rectangle/Rectangle Collision Detection

I am trying to solve an issue when two rectangles intersect/overlap each other. when this happens, i want to know if intersection is True or False. I found a solution, however it is written in C or C++. I want to write these code in Python.
Here is the source: http://www.jeffreythompson.org/collision-detection/rect-rect.php
This is literally the first line of python code I've ever written (I do know C++ however)
def rectRect(r1x, r1y, r1w, r1h, r2x, r2y, r2w, r2h):
# are the sides of one rectangle touching the other?
return r1x + r1w >= r2x and \ # r1 right edge past r2 left
r1x <= r2x + r2w and \ # r1 left edge past r2 right
r1y + r1h >= r2y and \ # r1 top edge past r2 bottom
r1y <= r2y + r2h # r1 bottom edge past r2 top
IMHO rectRect is a really bad name for the function, I kept it from the linked code however.
Following is simple class that can perform both rectangle-rectangle intersection as well as point to rectangle intersection. The difference between earlier solution is that following snippet allows even detection of rotated rectangles.
import numpy as np
import matplotlib.pyplot as plt
class Rectangle:
def __init__(self, center: np.ndarray, dims: np.ndarray, angle: float):
self.corners = self.get_rect_points(center, dims, angle)
self.area = dims[0] * dims[1]
#staticmethod
def get_rect_points(center: np.ndarray, dims: np.ndarray, angle: float):
"""
returns four corners of the rectangle.
bottom left is the first conrner, from there it goes
counter clockwise.
"""
center = np.asarray(center)
length, breadth = dims
angle = np.deg2rad(angle)
corners = np.array([[-length/2, -breadth/2],
[length/2, -breadth/2],
[length/2, breadth/2],
[-length/2, breadth/2]])
rot = np.array([[np.cos(angle), np.sin(angle)], [-np.sin(angle), np.cos(angle)]])
corners = rot.dot(corners.T) + center[:, None]
return corners.T
def is_point_in_collision(self, p: np.ndarray):
"""
check if a point is in collision with the rectangle.
"""
def area_triangle(a, b, c):
return abs((b[0] * a[1] - a[0] * b[1]) + (c[0] * b[1] - b[0] * c[1]) + (a[0] * c[1] - c[0] * a[1])) / 2
area = 0
area += area_triangle(self.corners[0], p, self.corners[3])
area += area_triangle(self.corners[3], p, self.corners[2])
area += area_triangle(self.corners[2], p, self.corners[1])
area += area_triangle(self.corners[1], p, self.corners[0])
return area > self.area
def is_intersect(self, rect_2: Rectangle):
"""
check if any of the four corners of the
rectangle is in collision
"""
if not np.all([self.is_point_in_collision(c) for c in rect_2.corners]):
return True
return False
def plot_rect(p1, p2, p3, p4, color='r'):
ax.plot([p1[0], p2[0]], [p1[1], p2[1]], color)
ax.plot([p2[0], p3[0]], [p2[1], p3[1]], color)
ax.plot([p3[0], p4[0]], [p3[1], p4[1]], color)
ax.plot([p4[0], p1[0]], [p4[1], p1[1]], color)
mid_point = 0.5 * (p1 + p3)
plt.scatter(mid_point[0], mid_point[1], marker='*')
plt.xlim([-1, 1])
plt.ylim([-1, 1])
Following are two samples:
Sample 1:
ax = plt.subplot(111)
st = Rectangle((0.067, 0.476),(0.61, 0.41), 90)
gripper = Rectangle((-0.367, 0.476),(0.21,0.16), 45)
plot_rect(*st.corners)
plot_rect(*gripper.corners)
plt.show()
print(f"gripper and rectangle intersect: {st.is_intersect(gripper)}")
Sample 2:
ax = plt.subplot(111)
st = Rectangle((0.067, 0.476),(0.61, 0.41), 90)
gripper = Rectangle((-0.167, 0.476),(0.21,0.16), 45)
plot_rect(*st.corners)
plot_rect(*gripper.corners)
plt.show()
print(f"gripper and rectangle intersect: {st.is_intersect(gripper)}")

How to pick 1 of my 3 formulas in my program?

I just wrote up a program to ask the user to calculate the area, circumference, and the diameter of a circle based on a radius input. However, I'm stumped on how to ask which calculation they want to make between the 3 choices. which is step 1. I have completed 2-4 steps. Any help on this one? (I.e. Only allow them to make one calculation per run of the program) The bolded area is obviously what I tried and failed miserably at....
**Radius = float(input("What type of calculation would you like to
make? "))
if 1 = "area"
elif: 2 = "circumference"
else: 3 = "diameter"
return("num")**
PI = 3.14
radius = float(input(' Please Enter the radius of a circle: '))
area = PI * radius * radius
circumference = 2 * PI * radius
print(" Area Of a Circle = %.2f" %area)
print(" Circumference Of a Circle = %.2f" %circumference)
import math
circumference = float(input(' Please Enter the Circumference of a
circle: '))
area = (circumference * circumference)/(4 * math.pi)
print(" Area Of a Circle = %.2f" %area)
import math
diameter = float(input(' Please Enter the Diameter of a circle: '))
area1 = (math.pi/4) * (diameter * diameter)
# diameter = 2 * radius
# radius = diameter/2
radius = diameter / 2
area2 = math.pi * radius * radius
print(" Area of Circle using direct formula = %.2f" %area1);
print(" Area of Circle Using Method 2 = %.2f" %area2)
As per your requirement that to get calculate area, circumference and diameter of circle based on radius input and to make one calculation per one run with choice selected.
I have made a sample/example code for you!
import math
def CalculateArea(radius):
# r = float(input('Enter the radius of the circle :'))
area = math.pi * radius * radius
return area
def CalculateCircumference(radius):
circ = 2 * math.pi * radius
return circ
def DiameterOfCircle(radius):
return radius * 2
radius = input('Enter Radius: ')
radius = float(radius)
choice = input(" Enter 1 to get Area \n Enter 2 for Circumference \n Enter 3 for Diameter! \n")
if choice is '1':
print("Area of the circle is : %.2f" % CalculateArea(radius))
elif choice is '2':
print("Circumference of circle is: ", CalculateCircumference(radius))
elif choice is '3':
print("Diameter of circle is: ", DiameterOfCircle(radius))
else:
print("Wrong Input!")
I hope this helps you! :)

I believe I am not properly calling / returning functions in my program

I can't get this to run correctly, and I have to use 3 functions with their purposes being those of which I have them set to.
def lw():
l = input("Enter the length of your rectangle: ")
w = input("Now enter the width of your rectangle:")
return l, w
def ap():
l,w = lw()
area = l * w
perimeter = 2*1 + 2*w
return area, perimeter
def main():
area,perimeter = ap()
print("With a length of", l ."and a width of", w)
print("the area of your rectangle is", area)
print("the perimeter of your rectangle is", perimeter)
if __name__ == "__main__":
main()
This should work
def lw():
l = input("Enter the length of your rectangle: ")
w = input("Now enter the width of your rectangle:")
return l, w
def ap():
l,w = lw()
area = l * w
perimeter = 2*1 + 2*w
return l, w, area, perimeter
def main():
l,w,area,perimeter = ap()
print("With a length of", l ,"and a width of", w)
print("the area of your rectangle is", area)
print("the perimeter of your rectangle is", perimeter)
if __name__ == "__main__":
main()
I've made two changes: passing l and w in ap() function and accessing them in main() function.
Heyo,
I can see a number of issues with your code:
The first print statement in your main function seems to be calling variables that don't exist within that function's scope. You'll need to return the values of l and w from ap() in addition to area and perimeter. There's also a slight typo in the parameters of this statement (a . where a , should be).
Your perimeter calculation is a bit off. It's multiplying 2 by 1 instead of 2 by l, rendering l useless.
The inputs your code is requesting only returns string values rather than numerical ones. You'll need to pass those into either an int() or float() and return the results of those functions if you want to be able to calculate anything.

Resources