Using double if statements in the same line as required - python

Hello dear SO members and staffs. I have been working on a project where I took the coordinates of the already drawn rectangle with the center of (0,0) coordinates. What I want to do is ask the user to put his x and y coordinates, after which it will tell you that whether if your coordinates is within the area of that or not. I have reached some of my goals, except the one that I need to ask the if statement for both of the x and y at the same time as if I will write only X statement it will display for only checking the X and not Y.
So, I need your help in how to check both of them before displaying?
(The center of the rectangle is at the (0,0) with the total length of 5 and the width of 10.)
y1 = -2.5
y2 = 2.5
x1 = -5
x2 = 5
inputX = eval(input("Please put in the X coordinate: "))
inputY = eval(input("Please put in the Y coordinate: "))
if x1<inputX<x2, y1<inputY<y2:
print("Your coordinates are in the range of the rectangle!")
else:
print("Sorry, your coordinates are not in the range of the rectangle!")

Use and to combine them:
if (x1 < inputX < x2) and (y1 < inputY < y2):

i think that will work
if (x1<inputX and inputX<x2 and y1<inputY and inpputY<y2):
print("Your coordinates are in the range of the rectangle!")
else:
print("Sorry, your coordinates are not in the range of the rectangle!")

The following code will work for only integer inputs - as it uses range function - range()
`
x1 = -5
x2 = 5
y1 = -2
y2 = 2
inputX = eval(input("Please put in the X coordinate: "))
inputY = eval(input("Please put in the Y coordinate: "))
if (inputX in range(x1,x2+1)) and (inputY in range(y1,y2+1)):
print("Your coordinates are in the range of the rectangle!")
else:
print("Sorry, your coordinates are not in the range of the rectangle!")
`
The answer before given using if condition has no problem, I am writing this to give an idea for an approach of using it using a function

Related

Lab4 - trying to understand what I'm supposed to do

This is what I have to do; "Assume that you have the coordinates (x,y) of four points p1, p2, p3, and p4. Write a function name
check_is_square() that asks the user for the coordinates of those four points (total of eight integer inputs) and prints the message Yes – it is a Square if those four points can form a square on the coordinate plane and the message No – it is not a square otherwise. Call check_is_square()from the main() function."
This is the code I have currently;
import math
def check_square(x1,x2,y1,y2):
if (math.sqrt((x1 - x2)**2+(y1-y2)**2) % 2 == 0):
print("Yes - it is a square")
else:
print("No - it is not a square")
def main():
x1 = int(input("Enter coordinate 1: "))
x2 = int(input("Enter coordinate 2: "))
y1 = int(input("Enter coordinate 3: "))
y2 = int(input("Enter coordinate 4: "))
check_square(x1,x2,y1,y2)
main()

Python algorithm to scan a rectangular area by a drone and calculate the flying time

I have a course project where I need to write a python algorithm to do the following steps:
1- Take the camera angle, flyings height and sped for the user.
2- Take x and y (represents longitude and altitude) from the user.
3- Calculate the area of the rectangle the drone needs to scan.
4- Divide the area into columns based on the camera angle.
5- Make the drone start from the middle of the first column from top then goes to bottom, then moves half of the next column's width and goes from bottom to top. the repeat till the whole area covered.
6- calculate distance then flying time.
The first 4 steps are straight forward and i added them to clarify the task details.
The algorithm required in the 5th step and then how to calculate the flying time is what I need help at.
I'm new to algorithm writing and coding in python in general, can anyone help on how I can write the algorithm required in step 5
I added the code I wrote to getting the total distance. I keep getting the distance = 0. plus I don't think the distance of the path is correctly calculated (please see the attached screenshot to shows the path)
def distance(height, angle, speed, x1, y1, x2, y2):
xc = (x1 + x2)/2
yc = (y1 + y2)/2
xd = (x1 - x2)/2
yd = (y1 - y2)/2
#Third corner
x3 = xc - yd
y3 = yc + xd
#Fourth corner
x4 = xc + yd
y4 = yc - xd
#width and heigth of the rectangle
width = x2 - x1
length= y2 - y1
#calculating a single column width
column_w = (math.sin(angle/2) * height) * 2
total_columns = int(width / column_w)
total_distance= 0
for i in range(total_columns):
total_distance = total_distance + length
if(i % 2 == 0):
print("drone movement: down, right, up")
else:
print("drone movement: up, right, down")
print(total_distance)
print(legnth)
#To get the inputs from the user
height = int(input("Enter height:"))
angle = int(input("Enter angle:"))
speed = int(input("Enter speed:"))
x1 = int(input("Enter x1:"))
y1 = int(input("Enter y1:"))
x2 = int(input("Enter x2:"))
y2 = int(input("Enter y2:"))
distance(height, angle, speed, x1, y1, x2, y2)
I think this is more to do as a formula rather than an "algorithm".
Your resulting flight path is a series of "S"s starting top left, down, U-turn, back up, U-turn, down and so on and so forth.
From what you've written in step #5, when the drone does a U-turn it goes sideways half the width of a column.
The total "hight" is given by the y input, so h1 is similar to that (minus some for camera angle etc).
The total width of the field is given by the x input (I think).
Assuming we have n columns in it with width w1, we get the number of U-turns:
Each one moves w1/2 sideways and so coverage is (for m sideways moves):
1 + m * (w1/2) = n * w1.
This results in m = 2n - 1 (after rounding up) U-turns.
Works out you'll need 2n * h1 (up/down flights - maybe 2n-1 for odd/even cases) + (2n-1) * w1 sideway fligths.
For a complete path:
direction = 'down'
nextUTurn = 'left'
columnsNeeded = n
for (columnIndex of columnsNeeded) {
print(direction)
print('U-Turn ' + nextUTurn)
direction = getOther(direction)
nextUTurn = getOther(nextUTurn)
}

Check if a list of points is part of a rectangle

I have a list of points and I need to find if the points exist in a rectangle defined by the top-left and bottom-right corners. If all the points belong in the rectangle then the result is True, otherwise the result is False.
Here is my code but I am getting it wrong somewhere.
def Functn1(topLeft=(0,0), bottomRight=(0,0), pointList=[]):
x1 = topLeft[0]
y1 = topLeft[1]
x2 = bottomRight[0]
y2 = bottomRight[1]
xa = pointList[i][0]
ya = pointList[i][0]
xb = pointList[i][1]
yb = pointList[i][1]
lengthofList = len(pointList)
for i in range(lengthofList):
if ((xa > x1 and xb < x2) and (ya > y1 and yb < y2)):
#if ((x[i][0] > x1 and x[i][1] < x2) and (y[i][0] > y1 and y[i][1] < y2)):
#Also tried using this code but keep getting the same error
return True
else:
return False
Functn1((0,0), (5,5), [(1,1), (0,0), (5,6)]) #should get False
I am getting this error:
<ipython-input-153-669eeffdb011> in allIn(topLeft, bottomRight, pointList)
20
21 for i in range(lengthofList):
---> 22 if ((x[i][0] > x1 and x[i][1] < x2) and (y[i][0] > y1 and y[i][1] < y2)):
23 return True
24 else:
TypeError: 'int' object is not subscriptable
Based on my understanding of your question, these are some of the mistakes you made in your code:
You used the i variable before setting or initializing it like:-.
xa = pointList[i][0]
ya = pointList[i][0]
xb = pointList[i][1]
yb = pointList[i][1]
I think you wanted to use it as an iterating variable in the for loop but you used it outside the loop.
You created four variables for each point in the pointList variable which I think are for the point's x, y, width, height although a point has no any width or height.
Your loop is invalid because it returns True or False after looping through the first item in the list, and it won't search for the other points to know if they are inside or outside the rectangle.
So I created a copy of your code with some changes based on what you want to and to also understand it easily:
def Functn1(topLeft=(0,0), bottomRight=(0,0), pointList=[]):
x = topLeft[0] #Rectangle x
y = topLeft[1] #Rectangle y
w = bottomRight[0] #Rectangle width(which you created with name of x2)
h = bottomRight[1] #Rectangle height(which you created with name of y2)
for i in range(len(pointList)):
p_x = pointList[i][0] #Current point x
p_y = pointList[i][1] #Current point y
if not ((p_x >= x and p_x < w) and (p_y >= y and p_y < h)): #Return False if the point wasn't in the rectangle (because you said theyre all must be inside the rectangle)
return False
return True #If non of them was outside the rectangle (Or it wasn't returned False) so return True
But if you worked or read about graphics you should know the (0, 0) in your example is inside the rectangle and (5, 5) is outside the rectangle, because if the size of something was 5 pixels so the last pixel's value is 4 not 5, and I wrote the code like that and if you want to change it so you can easily change the < operator to <= and also the > to >= to include the last point of the rectangle.

Request user input of X/Y positions for turtle circle program

Here is my program:
from turtle import *
xpos=0
ypos=0
radius = 35
while radius > .1:
pu()
goto (xpos, ypos)
pd()
circle(radius)
ypos = ypos + (radius*2)
radius = radius - 5
I would like to somehow ASK the user to input x and y positions, and also request radius and shrink value. The program should then carry out the process that was keyed in by the user (depending on the integers they used) Is this possible?
I'm guessing it's something along the lines of int(input
You can use raw_input:
# use input if using python3
x_pos = int(raw_input("Insert x pos: "))
y_pos = int(raw_input("Insert y pos: "))
radius = int(raw_input("Insert radius: "))
shrink = int(raw_input("Insert shrink value: "))
print "x: {} y: {} radius: {} shrink: {}".format(x_pos, y_pos, radius, shrink)
Example on the command line:
% python request_input.py
Insert x pos: 4
Insert y pos: 5
Insert radius: 1
Insert shrink value: 2
x: 4 y: 5 radius: 1 shrink: 2
You can use input to do this. I didn't handle converting to ints and / or checking that they are indeed integer inputs. I leave this to you. Hint: isdigit() if you want to check for integer input.
input is python3 raw_input for python2
from turtle import *
....
xpos = input("Enter the x position:")
ypos = input("Enter the y position:")
radius = input("Enter the radius:")
shrink = input("Enter the shrink value")
#convert above to int's, or turn into a function.
....

Python Test If Point is in Rectangle

I am new to python and still learning the ropes but I am hoping someone with more experience can help me out.
I am trying to write a python script that:
creates four points
creates four rectangles
check if each of the point is in any of the rectangles then write out the results to a output file.
The problem involves two data structures Point and Rectangle class. I have already started to create the Point class and Rectangle classes. Rectangle class should hold relevant data sets created from random module’s random method. As you can tell from my attempts that I am kind of all over the place but I have used #comments to try to get what I am trying to do.
Specific questions I have are:
1) how can I get this script working?
2) What variables or functions am I missing to generate random rectangles and see if specific points are in those rectangles?
## 1. Declare the Point class
class Point:
def __init__(self,x = 0.0, y = 0.0):
self.x = x
self.y = y
pass
## 2. Declare the Rectangle class
class Rectangle:
def __int__(self): ## A rectangle can be determined aby (minX, maxX) (minY, maxY)
self.minX = self.minY = 0.0
self.maxX = self.maxY = 1.0
def contains(self, point): ## add code to check if a point is within a rectangle
"""Return true if a point is inside the rectangle."""
# Determine if a point is inside a given polygon or not
# Polygon is a list of (x,y) pairs. This function
# returns True or False.
def point_in_poly(x,y,poly):
n = len(poly)
inside = False
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
## 3. Generate four points
##define a Point list to keep four points
points = []
##add codes to generate four points and append to the points list
polygon = [(0,10),(10,10),(10,0),(0,0)]
point_x = 5
point_y = 5
## 4. Generate four rectangles
##define a Rectangle list
rects = []
for i in range(4):
rectangle = Rectangle()
## Generate x
x1 = random.random()
x2 = random.random()
## make sure minX != maxX
while(x1 == x2):
x1 = random.random()
if x1<x2:
rectangle.minX=x1
rectangle.maxX=x2
elif x1>x2:
rectangle.minX=x2
rectangle.maxX=x1
rects.append(rectangle)
## Develop codes to generate y values below
## make sure minY != maxY
while(y1 == y2):
y1 = random.random()
if y1<y2:
rectangle.minY=y1
rectangle.maxY=y2
elif y1>y2:
recetangle.minY=y2
racetangle.maxY=y1
## add to the list
rects.append(rectangle)
## 5. Add code to check which point is in which rectangle
resultList = [] ## And use a list to keep the results
for i in range(4):
for j in range(4):
if points[i] in rectangle[j]:
print i
# write the results to file
f=open('Code5_4_1_Results.txt','w')
for result in resultList:
f.write(result+'\n')
f.close()
This is pretty simple math. Given a rectangle with points (x1,y1) and (x2,y2) and assuming x1 < x2 and y1 < y2 (if not, you can just swap them), a point (x,y) is within that rectangle if x1 < x < x2 and y1 < y < y2. Since Python comparison operators can be chained, this is even valid Python code which should produce the correct result (in other languages you'd have to write something like x1 < x and x < x2, etc).
If you want, you can use <= instead of <. Using <= means points on the boundary of the rectangle (eg, the point (x1,y1)) count as being inside it, while using < so means such points are outside it.
It is better to write a separate function to do the job. Here's my function. You can just copy it if you want
def pointInRect(point,rect):
x1, y1, w, h = rect
x2, y2 = x1+w, y1+h
x, y = point
if (x1 < x and x < x2):
if (y1 < y and y < y2):
return True
return False

Categories