sharpie_pen
sharpie_pen

Reputation: 51

Do rectangles overlap, not overlap, or are the same?

If one or more coordinates from r1 & r2 are the same, then ("The rectangles do overlap.")

If no coordinates are the same, then ("The rectangles do not overlap.")

If all coordinates are the same, then ("The rectangles are the same.")

So, when all coordinates are the same, my code prints out "The rectangles do overlap." along with "The rectangles are the same." -- but I just want it to print "The rectangles are the same.". How can it be done?

shape = input("Select (rectangle / circle): ")


if shape == "rectangle":

x1 = float(input("Enter rectangle A's left coordinate: "))
x2 = float(input("Enter rectangle A's right coordinate: "))
y1 = float(input("Enter rectangle A's top coordinate: "))
y2 = float(input("Enter rectangle A's bottom coordinate: "))

x01 = float(input("Enter rectangle B's left coordinate: "))
x02 = float(input("Enter rectangle B's right coordinate: "))
y01 = float(input("Enter rectangle B's top coordinate: "))
y02 = float(input("Enter rectangle B's bottom coordinate: "))

r1 = (int(x1), int(x2), int(y1), int(y2))
r2 = (int(x01), int(x02), int(y01), int(y02))

if any(item in r1 for item in r2):
    print("The rectangles do overlap.")
    
if all(item in r1 for item in r2):
    print("The rectangles are the same.")
            
else:
    print("The rectangles do not overlap.")

Upvotes: 2

Views: 77

Answers (1)

Selcuk
Selcuk

Reputation: 59184

Your problem is in the fact that if all(...) is true, any(...) will also be true. Just change the order of if statements and use elif:

if all(item in r1 for item in r2):
    print("The rectangles are the same.")
elif any(item in r1 for item in r2):
    print("The rectangles do overlap.")
else:
    print("The rectangles do not overlap.")

Upvotes: 1

Related Questions