class Solution: def __init__(self): self.memo = dict() self.memo[1] = 0 def getKth(self, lo, hi, k): for i in range(lo, hi + 1): self.power(i) sort_out = sorted(list(range(lo, hi + 1)), key=lambda x: self.power(x), reverse=False) return sort_out[k - 1] # Why is this one-indexed?? SMH def power(self, n): # first check the memo to ensure we don't do extra work # then the array should fill up quickly as we go if n in self.memo: return self.memo[n] elif n % 2 == 0: total = 1 + self.power(n//2) else: total = 1 + self.power(3*n+1) self.memo[n] = total return total s = Solution() print("Expected: 13") print("Got:", s.getKth(12, 15, 2))