How to find/calculate the shaded area of this shape in python? - python

I'm trying to write a python program to calculate the shaded area of the circle in this picture:
[![enter image description here][1]][1]
Here is the input and output:
Enter the radius of a circle: 10
Enter the side of square :3
Enter the width of a rectangle :4
Enter the length of a rectangle :2
The shaded area is : 12.0
Here is my code:
PI = 3.14
radius = float(input("Enter the radius of a circle:"))
area = PI * radius ** 2
side = int(input("Enter the side of square:"))
area = side*side
width = float(input("Enter the width of a rectangle:"))
length = float(input("Enter the length of a rectangle:"))
area = width * length
perimeter = (width + length) * 2
print("The shaded area is :", perimeter)

Problem
You are overwriting the value of area and the previous assigned values are lost.
Example
area = input('enter first value')
10
# the value of area is 10
area = input('enter second value')
3
# the value of area is now 3 and 10 is lost
However you can use area -= number or area += number to substract or add a number to the current value of the variable like so:
area = input('enter first value')
10
# the value of area is 10
area -= input('enter second value')
3
# the value of area is now 10 - 3 = 7
As correctly pointed out in the comments you should also import math and use math.pi instead of using the value 3.14
The correct output for the shaded area is:
Enter the radius of a circle:10
Enter the side of square:3
Enter the width of a rectangle:4
Enter the length of a rectangle:2
The shaded area is : 297.1592653589793
>
I would recommend solution 1 as variables should have meaningful names (unlike solution 2):
Meaningful Variable Names
and solution 3 is a bit harder to read and understand:
Make your code easy to read/understand
Solution 1 (Using different variable names)
import math
def findDimensions():
radius = float(input("Enter the radius of a circle:"))
# radius = 10
circle_area = math.pi * radius ** 2
side = int(input("Enter the side of square:"))
# side = 3
square_area = side * side
# but you could use square_area = side ** 2 as well
width = float(input("Enter the width of a rectangle:"))
# width = 4
length = float(input("Enter the length of a rectangle:"))
# length = 2
rectangle_area = width * length
shaded_area = circle_area - square_area - rectangle_area
print("The shaded area is :", shaded_area)
findDimensions()
Solution 2 (Updating the area variable instead of overwriting it)
import math
def findDimensions():
radius = float(input("Enter the radius of a circle:"))
# radius = 10
area = math.pi * radius ** 2
side = int(input("Enter the side of square:"))
# side = 3
area -= side * side
# but you could use area -= side ** 2 as well
width = float(input("Enter the width of a rectangle:"))
# width = 4
length = float(input("Enter the length of a rectangle:"))
# length = 2
area -= width * length
print("The shaded area is :", area)
findDimensions()
Solution 3 (Moving calculations to the end)
import math
def findDimensions():
radius = float(input("Enter the radius of a circle:"))
# radius = 10
side = int(input("Enter the side of square:"))
# side = 3
width = float(input("Enter the width of a rectangle:"))
# width = 4
length = float(input("Enter the length of a rectangle:"))
# length = 2
shaded_area = (math.pi * radius ** 2) - (side * side) - (width * length)
print("The shaded area is :", shaded_area)
findDimensions()

Related

Making an Euclidean Distance Matrix with Random Points in Python

I wrote a code that produces the desired number of points in a certain width and length range in the coordinate system. How can I calculate and tabulate the distance matrix of these points I produced using the Euclidean method?
import random
npoints = int(input("Type the npoints:"))
width = float(input("Enter the Width you want:"))
height = float(input("Enter the Height you want:"))
sample = []
for _ in range(npoints):
sample.append((width * random.random(), height * random.random()))
print(*[f"({w:.2f}, {h:.2f})" for w, h in sample], sep=', ')
Output is:
Type the npoints:4
Enter the Width you want:10
Enter the Height you want:10
(8.52, 3.73), (9.69, 6.87), (8.20, 6.14), (4.18, 0.76)
Process finished with exit code 0
How can I create a distance matrix with rondom points like this example:
Thanks a lot for the help.
If you want to use external modules, scipy is very efficient for matrix calculations.
import random
import pandas as pd
from scipy.spatial import distance
npoints = int(input("Type the npoints:"))
width = float(input("Enter the Width you want:"))
height = float(input("Enter the Height you want:"))
sample = []
for _ in range(npoints):
sample.append((width * random.random(), height * random.random()))
print(*[f"({w:.2f}, {h:.2f})" for w, h in sample], sep=', ')
#Create a matrix from these points
mat_dist = distance.cdist(sample, sample, 'euclidean')
df_mat_dist = pd.DataFrame(mat_dist)
print(df_mat_dist)
Output
Type the npoints:4
Enter the Width you want:10
Enter the Height you want:10
(8.89, 8.85), (9.00, 9.43), (9.67, 9.45), (3.96, 5.68)
0 1 2 3
0 0.000000 0.584322 0.985072 5.856736
1 0.584322 0.000000 0.669935 6.277323
2 0.985072 0.669935 0.000000 6.839240
3 5.856736 6.277323 6.839240 0.000000

I tried creating an area calculator, it keeps stating invalid syntax for a correct code

I started a project in Codeacademy to create an area calculator. However the code elif option == "T": keeps producing syntax error. I looked at the solution but it looks exactly the same. Can anyone please help?
Thanks in advance.
I've tried changing indentation and spacing and changing it from double quotes to single quotes. I even copied and pasted the solution but it still doesn't work.
# it calculates area of circle and triangle
print"Calculator, Ready!"
option = raw_input("What shape. Enter C for Circle or T for triangle: ")
if option == "C":
radius = float(raw_input(" What is the radius: "))
area = 3.14159 * radius ** 2
print area
elif option == 'T':
base = float(raw_input("Base: "))
height = float(raw_input("Height: "))
area = .5 * base * height
print area
You need to indent the area calculations since they're part of the if and elif blocks. You're getting a syntax error because an elif statement must follow an if block.
Also since you're doing print area in both cases, you only need to write it once.
The important bits fixed:
if option == "C":
radius = float(raw_input(" What is the radius: "))
area = 3.14159 * radius ** 2
elif option == 'T':
base = float(raw_input("Base: "))
height = float(raw_input("Height: "))
area = .5 * base * height
print area
In Pythhon, a elif statement can only follow a elif or if statement, but in your code, it follows a print.
You may indent or remove the two following lines:
area = 3.14159 * radius ** 2
print area
My understanding of your code makes me propose you this solution:
# ==========================================
# It calculates area of circle and triangle
# A good practice is to initialise all your variable at the begining
option = None
radius = None
area = None
base = None
height = None
print("Calculator, Ready!")
option = raw_input("What shape. Enter C for Circle or T for triangle: ")
if option == "C":
radius = float(raw_input(" What is the radius: "))
area = 3.14159 * radius ** 2
elif option == 'T':
base = float(raw_input("Base: "))
height = float(raw_input("Height: "))
area = .5 * base * height
print ("The calculated area is: {}".format(area))

using while loop in python to find volume and surface area of a cone but getting incorrect answers except the first radius entered

I am trying to find the volume and surface area of a cone using the radius from 10-20 with a step of .5 and print the results. I get the correct response when using 10 but all the following responses are wrong. What am I missing?
Here's what I've got:
pi = 3.14159265359
radius = 10
height = radius * 2
import math
print ('{0: <10}'.format('radius'),\
'{0: <10}'.format('area'),\
'{0: <10}'.format('volume'))
while radius >= 9.5 and radius <= 20:
area = pi * radius * (radius + math.sqrt(height**2 + radius**2))
volume = pi * radius**2 * height / 3
print(format(radius, '<10,.2f'), \
format(area, '<10,.2f'), \
format(volume, '<12,.2f'))
radius = radius + .5
You should add height = radius * 2 after the last line. Remember about the indentation.

python 3: import module

I'm working on a small program that evaluates the area of two rectangles. The user enters the length and the width of the rectangle (my first module), then the program calculates the area of the rectangles (second module), and finally after calculating the difference between both of the areas, display the result, telling which one is the bigger.
But after entering the lengths and widths, the program displays an error message, telling that my module is not defined as:
ImportError: No module named 'inputRect'
My Code:
#Project M04: Rectangle with the bigger area
#Python 3.4.3
#Module that asks width and lenght of the two rectangles
def inputRect():
width1 = int(input("Enter the width of the first rectangle: "))
length1 = int(input("Enter the length of the first rectangle: "))
width2 = int(input("Enter the width of the second rectangle: "))
lenght2 = int(input("Enter the length of the second rectangle: "))
inputRect()
#import the fonction "inputRect"
import inputRect
#calcule the area of the two rectangles
def calcArea():
rect1 = int(width1) * int(length1)
rect2 = int(width2) * int(length2)
calcArea()
#import the fonction "calcArea"
import calcArea
#Calcul the difference between the two rectangles (rectangle 1 - rectangle 2 = difference)
#if > 0
def difference():
difference = int(rect1) - int(rect2)
# if ifference > 0 : rectangle 1 has a bigger area
if (difference) > 0 :
print ("Rectangle numer 1 is bigger than rectangle 2")
# if ifference < 0 : rectangle 2 has a bigger area
if (difference) < 0 :
print ("Rectangle numer 2 is bigger than rectangle 1")
# else : both rectangles have the same area
else:
print ("Both rectangles have the same area")
difference()
Notes:
understand difference between module and function. You can't import a function, in this case inputRect and calcArea
since you want to create function for each process, try to utilize return in your function to get data that you need
still in the spirit using function, you can separate some calculations. For example, instead of compute two rectangles in one function, create a function that only calculate an area, given width and length
Something like this could be an example:
def get_rect_input():
width1 = int(input("Enter the width of the first rectangle: "))
length1 = int(input("Enter the length of the first rectangle: "))
width2 = int(input("Enter the width of the second rectangle: "))
lenght2 = int(input("Enter the length of the second rectangle: "))
return width1, length1, width2, lenght2
def calculate_area(width, length):
return width * length
def show_comparation(width1, length1, width2, lenght2):
area1 = calculate_area(width1, lenght2)
area2 = calculate_area(width2, lenght2)
if area1 > area2:
print ("Rectangle number 1 is bigger than rectangle 2")
elif area1 < area2:
print ("Rectangle number 2 is bigger than rectangle 1")
else:
print ("Both rectangles have the same area")
if __name__ == "__main__":
width1, lenght1, width2, lenght2 = get_rect_input()
show_comparation(width1, lenght1, width2, lenght2)
Importing
You don't have to import a function that is in the module you are using (i.e.: the code of the file that you launch).
def inputRect():
"Returns width and lenght in 2 tuples"
w1 = int(input("Width 1st rectangle: "))
l1 = int(input("Lenght 1st rectangle: "))
w2 = int(input("Width 2nd rectangle: "))
l2 = int(input("Lenght 2nd rectangle: "))
# tuple 1 (w & l of rect 1) - tuple 2 (w & l of r2)
return (w1, l1), (w2, l2)
# get the 2 tuple into r1 and r2 to calculate the area
r1, r2 = inputRect()
def calcArea():
"Uses the tuples to calculate area and returns results"
area1, area2 = r1[0] * r1[1], r2[0] * r2[1]
return area1, area2
# This variable memorizes the two areas
rect = calcArea()
def difference():
"Calculates which one area is bigger"
difference = rect[0] - rect[1]
# if ifference > 0 : rectangle 1 has a bigger area
if (difference) > 0:
print("Rectangle numer 1 is bigger than rectangle 2 by", rect[0] - rect[1])
# if ifference < 0 : rectangle 2 has a bigger area
elif (difference) < 0:
print("Rectangle numer 2 is bigger than rectangle 1 by", rect[1] - rect[0])
# else : both rectangles have the same area
else:
print("Both rectangles have the same area")
difference()
OUTPUT:
Width 1st rectangle: 10
Lenght 1st rectangle: 10
Width 2nd rectangle: 20
Lenght 2nd rectangle: 20
Rectangle numer 2 is bigger than rectangle 1 by 300

Determining final velocity at a target distance

In this program I've been working on with Python the goal is to take user inputs on a given initial velocity, angle, and how far away a structure is/how tall it is we're aiming for. I have been able to calculate how long it takes for something to reach a target, but I'm not sure why the final velocity (how fast it is going when it reaches the target) is coming up wrong.
# User inputs
velocity = float(input('Give me a velocity to fire at (in m/s): '))
angle = float(input('Give me an angle to fire at: '))
distance = float(input('Give me how far away you are from the
structure: '))
height = float(input('Give me the height of the structure (in meters):
'))
slingshot = 5 #Height of slingshot in meters
gravity = 9.8 #Earth gravity
# Converting angles to radians
angleRad = math.radians(angle)
# Computing our x and y coordinate
x = math.cos(angleRad)
y = math.sin(angleRad)
# Calculations
time = distance/(velocity * x)
vx = x
vy = y + (-9.8 * time)
finalVelocity = math.sqrt((vx ** 2) + (vy ** 2))
# Output of program
print('It takes your bird' , time , 'seconds to reach the structure')
print('Your velocity at the target distance is' , finalVelocity ,
'meters per second.')
Here is a sample input and what the expected output should be:
Input Velocity: 20
Input Angle: 40
Input Distance: 25
Input Height of Structure: 15
Expected Output:
Time to reach structure: 1.63176 s
Final velocity: 15.6384 s
My Program's Output:
Time to reach structure: 1.63176
Final velocity: 15.36755
At first glance it would appear my program is very close, so I suspected a rounding error, but it is mere coincidence with the chosen numbers that they're close.
You miscalculated the horizontal and vertical components of the final velocity. You only used the cosine and sine of the angle, rather than the (magnitude of the) initial velocity times the cosine and sine, respectively. If you modify the following two lines of code, you will obtain the result you were looking for given the sample input you provided:
vx = velocity * x
vy = velocity * y - 9.8 * time
I rewrote your original code a bit and also computed the final height to check whether the structure was hit or not, so feel free to use it if needed:
import math
# User inputs
# v0 = float(input('Give me a velocity to fire at (in m/s): '))
# angle = float(input('Give me an angle to fire at: '))
# distance = float(input('Give me how far away you are from the structure: '))
# height_structure = float(input('Give me the height of the structure (in meters):'))
# Test inputs
v0 = 20
angle = 40
distance = 25
height_structure = 15
# Constants
height_slingshot = 5 # Height of slingshot in meters
g = 9.8 # Earth gravity
# Converting angle to radians
angleRad = math.radians(angle)
# Computing initial velocity components
vx0 = v0 * math.cos(angleRad)
vy0 = v0 * math.sin(angleRad)
# Computing time to travel horizontal distance
t_x = distance / vx0
# Computing final vertical velocity component
vy_final = vy0 - g * t_x
# Computing magnitude of final velocity
v_final = math.sqrt((vx0 ** 2) + (vy_final ** 2))
# Note: Horizontal component is constant
# Computing final height
y_final = height_slingshot + vy0 * t_x - g / 2 * t_x ** 2
# Verify if t_x was computed correctly
# t_y1 = (vy0 + math.sqrt(vy0 ** 2 - 2 * g * y_final)) / g
# t_y2 = (vy0 - math.sqrt(vy0 ** 2 - 2 * g * y_final)) / g
# Output of program
print('It takes your bird', t_x, 'seconds to reach the structure.')
print('Your velocity at the target distance is', v_final,
'meters per second.')
print('\nFinal height: ', y_final)
print('Structure height:', height_structure)
if 0. <= y_final <= height_structure:
print('\nYou hit the structure!')
elif y_final < 0:
print('\nYou missed. Not far enough!')
else:
print('\nYou missed. Too far!')

Categories

Resources