Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help solving a problem
#7
If lower left is not always the lower left corner, make it so.
def point_in_rectangle(lower_left, upper_right, point):
    """Return True if point is in rectangle defined by corners lowerLeft
    and upper right.
    """
    llx = min(lower_left[0], upper_right[0])
    lly = min(lower_left[1], upper_right[1])
    urx = max(lower_left[0], upper_right[0])
    ury = max(lower_left[1], upper_right[1])
    x, y = point
    return llx <= x <= urx and lly <= y <= ury
But if you do that or not, use the Python way of comparing against a range, not the C way.
Do:
x1 <= test1 <= x2
Not
test1 >= x1 and test1 <= x2
If you really want to do a bunch of comparisons, do them using any():
def point_in_rectangle(lower_left, upper_right, point):
    """Return True if point is in rectangle defined by corners lowerLeft
    and upper right.
    """
    x1, y1 = lower_left
    x2, y2 = upper_right
    x, y = point

    return any((
        x1 <= x <= x2 and y1 <= y <= y2,
        x1 <= x <= x2 and y1 >= y >= y2,
        x1 >= x >= x2 and y1 <= y <= y2,
        x1 >= x >= x2 and y1 >= y >= y2))

print(point_in_rectangle((1, 2), (3, 4), (1.5, 3.2)))
See how easy it is to verify the logic when they are all aligned vertically like this?
Reply


Messages In This Thread
Need help solving a problem - by rufenghk - Jun-02-2022, 03:02 PM
RE: Need help solving a problem - by ndc85430 - Jun-02-2022, 03:35 PM
RE: Need help solving a problem - by bowlofred - Jun-02-2022, 03:37 PM
RE: Need help solving a problem - by deanhystad - Jun-02-2022, 07:55 PM
RE: Need help solving a problem - by rufenghk - Jun-02-2022, 09:26 PM
RE: Need help solving a problem - by rufenghk - Jun-02-2022, 08:58 PM
RE: Need help solving a problem - by deanhystad - Jun-03-2022, 12:31 AM
RE: Need help solving a problem - by rufenghk - Jun-04-2022, 10:15 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  SOlving LInear Equations in Python(Symoy, NUmpy) - Coefficient Problem quest 3 1,788 Jan-30-2022, 10:53 PM
Last Post: quest
  Problem in solving optimization problem Ruchika 0 1,605 Jul-27-2020, 05:28 AM
Last Post: Ruchika

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020