Advertisement
makispaiktis

Project Euler 112 - Bouncy numbers

Jul 29th, 2020 (edited)
323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. '''
  2. Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468.
  3. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420.
  4. We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349.
  5. Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy.
  6. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538.
  7. Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%.
  8. Find the least number for which the proportion of bouncy numbers is exactly 99%.
  9. '''
  10.  
  11. # FUNCTION 1
  12. def isIncreasing(n):
  13.     s = str(n)
  14.     counter = 0
  15.     length = len(s)
  16.     for i in range(length-1):
  17.         if int(s[i]) <= int(s[i+1]):
  18.             counter += 1
  19.     if counter == length-1:
  20.         return True
  21.     else:
  22.         return False
  23.  
  24.  
  25. # FUNCTION 2
  26. def isDecreasing(n):
  27.     s = str(n)
  28.     counter = 0
  29.     length = len(s)
  30.     for i in range(length - 1):
  31.         if int(s[i]) >= int(s[i + 1]):
  32.             counter += 1
  33.     if counter == length - 1:
  34.         return True
  35.     else:
  36.         return False
  37.  
  38.  
  39. # FUNCTION 3
  40. def isBouncy(n):
  41.     if isDecreasing(n) == False and isIncreasing(n) == False:
  42.         return True
  43.     return False
  44.  
  45.  
  46. # FUNCTION 4
  47. def bouncyProportion(proportion):
  48.     n = 1
  49.     counter = 0
  50.     counter += isBouncy(1)
  51.     prop = counter / n
  52.     while prop != proportion:
  53.         n += 1
  54.         counter += isBouncy(n)
  55.         prop = counter / n
  56.     return n
  57.  
  58.  
  59. # MAIN FUNCTION
  60. print(bouncyProportion(0.5))
  61. print(bouncyProportion(0.9))
  62. print(bouncyProportion(0.99))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement