Guest User

Untitled

a guest
Jul 16th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. import math
  2. import copy
  3.  
  4. class dimension:
  5. def __init__(self, a, b):
  6. self.a = a
  7. self.b = b
  8.  
  9. def get_ratio(self):
  10. return self.a/self.b
  11.  
  12. #scales this object so it fits into to_fit, maximizing size while keeping its ratio
  13. def scale_to_fit(self, to_fit):
  14. r = self.get_ratio()
  15. if r > to_fit.get_ratio(): # wider than to_fit -> fit width, scale height
  16. self.a, self.b = to_fit.a, to_fit.a/r
  17. else: # higher than to_fit -> fit height, scale width
  18. self.a, self.b = to_fit.b*r, to_fit.b
  19.  
  20. #for test runs of dim.scale_to_fit
  21. def test(to_scale, to_fit):
  22. after_to_scale, after_to_fit = copy.copy(to_scale), copy.copy(to_fit)
  23. after_to_scale.scale_to_fit(after_to_fit)
  24.  
  25. print("--- test run ---")
  26. print("to_fit dim: ", to_fit.a, to_fit.b)
  27. print("to_fit ratio:", to_fit.get_ratio())
  28. print("to_scale dim: ", to_scale.a, to_scale.b)
  29. print("to_scale ratio:", to_scale.get_ratio())
  30.  
  31. print("new to_scale dim:", after_to_scale.a, after_to_scale.b)
  32. print("new to_scale ratio:", after_to_scale.get_ratio())
  33.  
  34. assert to_fit.get_ratio() == to_fit.a / to_fit.b, "ratio calculation failed"
  35. assert after_to_fit.a == to_fit.a, "to_fit changed"
  36. assert after_to_fit.b == to_fit.b, "to_fit changed"
  37. assert math.isclose(after_to_scale.get_ratio(), to_scale.get_ratio(), rel_tol=1e-07), "to_scale ratio changed"
  38.  
  39. if after_to_scale.get_ratio() > after_to_fit.get_ratio():
  40. assert after_to_scale.a == after_to_fit.a, "scaling failed"
  41. assert after_to_scale.b == after_to_fit.a / to_scale.get_ratio(), "scaling failed"
  42. else:
  43. assert after_to_scale.a == after_to_fit.b * to_scale.get_ratio(), "scaling failed"
  44. assert after_to_scale.b == after_to_fit.b, "scaling failed"
  45.  
  46.  
  47. if __name__ == "__main__":
  48. test(dimension(1600, 900), dimension(10, 30))
  49. test(dimension(1600, 900), dimension(30, 30))
  50. test(dimension(30, 10), dimension(1600, 900))
  51. test(dimension(10, 30), dimension(1600, 900))
Add Comment
Please, Sign In to add comment