fork download
  1. # ball_collide.py
  2. # MIT OCW 6.189 Homework 3
  3. # http://o...content-available-to-author-only...t.edu/courses/electrical-engineering-and-computer-science/6-189-a-gentle-introduction-to-programming-using-python-january-iap-2011/assignments/MIT6_189IAP11_hw3.pdf
  4. # Written for Python 3.x
  5. # Mechanical MOOC
  6. # Glenn Richard
  7. # July 20, 2013
  8. # ********** Exercise 3.2 **********
  9. import math
  10. class Ball():
  11. def __init__(self, x, y, r):
  12. self.x = x
  13. self.y = y
  14. self.r = r
  15. def __str__(self):
  16. return "Ball(x: " + str(self.x) + ", y: " + str(self.y) + ", r: " + str(self.r) + ")"
  17. # Define your function here
  18. def ball_collide(b1, b2):
  19. ##### YOUR CODE HERE #####
  20. sum_radii = b1.r + b2.r
  21. dist = math.sqrt((b1.x - b2.x) ** 2 + (b1.y - b2.y) ** 2)
  22. return dist <= sum_radii
  23.  
  24. # Test Cases for Exercise 3.2
  25. b1 = Ball(0, 0, 1)
  26. b2 = Ball(3, 3, 1)
  27. b3 = Ball(5, 5, 2)
  28. b4 = Ball(2, 8, 3)
  29. b5 = Ball(7, 8, 2)
  30. b6 = Ball(4, 4, 3)
  31. print(str(b1) + " and " + str(b2) + " " + str(ball_collide(b1, b2))) # Should be False
  32. print(str(b3) + " and " + str(b4) + " " + str(ball_collide(b3, b4))) # Should be True
  33. print(str(b5) + " and " + str(b6) + " " + str(ball_collide(b5, b6))) # Should be True
  34.  
Success #stdin #stdout 0.16s 10224KB
stdin
Standard input is empty
stdout
Ball(x: 0, y: 0, r: 1) and Ball(x: 3, y: 3, r: 1) False
Ball(x: 5, y: 5, r: 2) and Ball(x: 2, y: 8, r: 3) True
Ball(x: 7, y: 8, r: 2) and Ball(x: 4, y: 4, r: 3) True