A bouncy number is any non-negative integer that is neither increasing nor decreasing.
An increasing integer is any integer in which when going from left to right, the current digit is greater than or equal to the previous digit. For example, 1234 and 14779 are both increasing integers. In contrast, a decreasing integer is any integer in which when going from left to right, the current digit is less than or equal to the previous digit. Some examples of decreasing integers are 6432 and 988743.
Unlike an increasing or decreasing integer, a bouncy number’s digits neither increase or decrease. Rather, they “bounce” between increasing and decreasing. An example is 12435 or 1441. Because the digits both increase and decrease from left to right, they are called bouncy numbers.
For clarification, there are no bouncy numbers before 100, and the first bouncy number is 101. The bouncy numbers between 100 and 120 are 101, 102, 103, 104, 105, 106, 107, 108, 109, and 120.
def is_bouncy(n): return sorted(str(n)) != list(str(n)) and sorted(str(n)) != list(str(n))[::-1] print(is_bouncy(152))
In the solution above, the function returns if the input
n is a bouncy number by checking if it is not increasing or decreasing.
str method converts the input
n from an integer to a string.
sorted method can convert a string of numbers into a list of the digits in increasing order.
list method splits a string into a list.
[::-1] reverses a list from
["t", "e", "s", "t"] into
["t", "s", "e", "t"]
The string is sorted in both increasing and decreasing order. These sorted strings are compared with the original to check if it is bouncy.
View all Courses