112.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import unittest
  2. def isIncreasing(n):
  3. """
  4. Returns boolean whether number is increasing
  5. Decreasing defined as whether next digit is larger or equal
  6. """
  7. s = str(n)
  8. b = True
  9. for i in range(len(s) - 1):
  10. if int(s[i]) > int(s[i + 1]):
  11. b = False
  12. return b
  13. def isDecreasing(n):
  14. """
  15. Returns boolean whether number is decreasing
  16. Decreasing defined as whether next digit is smaller or equal
  17. """
  18. s = str(n)
  19. b = True
  20. for i in range(len(s) - 1):
  21. if int(s[i]) < int(s[i + 1]):
  22. b = False
  23. return b
  24. def isBouncy(n):
  25. """
  26. Returns boolean whether number is bouncy
  27. Bouncy defined as not increasing or decreasing
  28. """
  29. return not (isIncreasing(n) or isDecreasing(n))
  30. def main(n):
  31. bouncy = 0.0 # Number of bouncy numbers so far
  32. total = 0 # Also functions as a counter
  33. prop = 0.0 # Proportion of bouncy numbers
  34. while prop < n:
  35. total += 1
  36. if isBouncy(total):
  37. bouncy += 1
  38. prop = bouncy / total
  39. return total
  40. # Testing suite
  41. # Based on Project Euler description
  42. class Bouncy(unittest.TestCase):
  43. def test_increasing(self):
  44. self.assertTrue(isIncreasing(134468))
  45. self.assertFalse(isIncreasing(66420))
  46. self.assertFalse(isIncreasing(155349))
  47. def test_decreasing(self):
  48. self.assertFalse(isDecreasing(134468))
  49. self.assertTrue(isDecreasing(66420))
  50. self.assertFalse(isDecreasing(155349))
  51. def test_bouncy(self):
  52. self.assertFalse(isBouncy(134468))
  53. self.assertFalse(isBouncy(66420))
  54. self.assertTrue(isBouncy(155349))
  55. def test_50bouncy(self):
  56. self.assertEqual(538, main(0.5))
  57. def test_90bouncy(self):
  58. self.assertEqual(21780, main(0.9))
  59. if __name__ == "__main__":
  60. print main(0.99)
  61. unittest.main()