Write a boolean function, is Inside Rect(t W,H), which returns True if turtle t
ID: 3866057 • Letter: W
Question
Write a boolean function, is Inside Rect(t W,H), which returns True if turtle t is inside a rectangle of width, W and height, H, centered at the origin. You might want to use the position function, which returns a tuple x, y of the turtle's current postion look it up in python does in the turtle module. The setposition(x, y) & the sleep function from the time moduke might be useful for testing & debugging. setposition(x, y) moves the turtle to the coordinates (x, y). sleep(s) puts the code execution on hold for s seconds. Sample run: import turtle, random, time wn = turtle.screen () wn.bgcolor ("light green) Set the window background color wn. title("Tess wanders around inside a rectangle") Set the window title tess = turtle.Turtle() tess.color("blue") Tell tess to change her color tess.pensize (3) Tell tess to set her pen width tess.speed (5) test it - takeW = 600, H = 300 W, H = 600, 300 rectangle (tess, W,H) for (x, y) in [(W/4,H/4), (-W/4, -H/4), (W/4,H/2), (W/2,H/4), (W/4,1.2*H/2)]: tess.setpos (x,y) print (x, y, isInsideRect (tess, W, H) time.sleep (4) > > > 150.0 75.0 True -150.0-75.0 True 150.0 150.0 False 300.0 75.0 False 150.0 180.0 FalseExplanation / Answer
def isInsideRect(t, W, H): x, y = t.position() # determining turtle position # using ternary operator widthRange = range(-W/2 + 1, W/2) if W % 2 == 0 else range(-W/2, W/2 + 1) # using range() to get a list of points in x-axis heightRange = range(-H/2 + 1, H/2) if H % 2 == 0 else range(-H/2, H/2 + 1) # using range() to get a list of points in y-axis if x in widthRange and y in heightRange: # if turtle is in the range return True else: return False
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.