Reputation: 63
I am trying to figure out how to use a for loop to identify a quadrant that a point (defined by a tuple) is in.
The program prompts until a non-numerical answer is given. Then, using the points input by the user, I need to identify which quadrant each point would be in.
For example: points (0, 1),(1,2),(2,3), and (3,4) are stored in a list and need their quadrants identified by a for loop.
I am unsure where to start with this. My input code is as follows:
locationlist = []
count = 0
while True :
try :
tup = input("Enter X and Y separated by a space, or enter a non-number to stop: ")
x, y = tup.split()
x = float(x)
y = float(y)
count = count + 1
locationlist.append(tup)
except ValueError:
break
print("Points: ",locationlist)
Upvotes: 0
Views: 114
Reputation: 2147
You don't need to create extra variables for that, just nest your test.
for x, y in locationList:
if y >= 0:
if x >= 0: print( x, y, 'Quadrant 1' )
else: print( x, y, 'Quadrant 2' )
else: ## y < 0
if x < 0: print( x, y, 'Quadrant 3' )
else: print( x, y, 'Quadrant 4' )
Edit: If axis is required:
for x, y in locationList:
if y > 0:
if x > 0: print( x, y, 'Quadrant 1' )
elif x < 0: print( x, y, 'Quadrant 2' )
else: print( x, y, 'pos Y-axis' )
elif y < 0
if x < 0: print( x, y, 'Quadrant 3' )
elif x > 0: print( x, y, 'Quadrant 4' )
else: print( x, y, 'neg Y-axis' )
else:
if x > 0: print( x, y, 'pos X-axis' )
elif x < 0: print( x, y, 'neg X-axis' )
else: print( x, y, 'Origin' )
Upvotes: 1
Reputation: 1025
I think I would use a divide-and-conquer strategy to reduce the number of comparisons. Perhaps something like this:
for x, y in locationList:
# 2nd or 4th
if x * y < 0:
if x < 0:
# Second quadrant.
else:
# Fourth quadrant.
# 1st or 3rd
elif x * y > 0:
if x < 0:
# Third quadrant.
else:
# First quadrant.
# On an axis: quadrant not well-defined.
else:
# No quadrant.
Upvotes: 1
Reputation: 312
I believe this is what you are asking for:
for x, y in locationList:
a = x > 0
b = y > 0
c = x == 0 or y == 0
if not c:
if a and b:
# 1st quadrant
elif a:
# 4th quadrant
elif b:
# 2nd quadrant
else:
# 3rd quadrant
else:
# no quadrant
Basically what I'm doing is storing the conditions of whether x and y are positive or not, so that I can do logic on those without repeatedly calculating those conditions.
Upvotes: 2