Returns the nth ugly number. >>> ugly_numbers(100) 1536 >>> ugly_numbers(0) 1 >>> ugly_numbers(20) 36 >>> ugly_numbers(-5) 1 >>> ugly_numbers(-5.5) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an in
(n: int)
| 10 | |
| 11 | |
| 12 | def ugly_numbers(n: int) -> int: |
| 13 | """ |
| 14 | Returns the nth ugly number. |
| 15 | >>> ugly_numbers(100) |
| 16 | 1536 |
| 17 | >>> ugly_numbers(0) |
| 18 | 1 |
| 19 | >>> ugly_numbers(20) |
| 20 | 36 |
| 21 | >>> ugly_numbers(-5) |
| 22 | 1 |
| 23 | >>> ugly_numbers(-5.5) |
| 24 | Traceback (most recent call last): |
| 25 | ... |
| 26 | TypeError: 'float' object cannot be interpreted as an integer |
| 27 | """ |
| 28 | ugly_nums = [1] |
| 29 | |
| 30 | i2, i3, i5 = 0, 0, 0 |
| 31 | next_2 = ugly_nums[i2] * 2 |
| 32 | next_3 = ugly_nums[i3] * 3 |
| 33 | next_5 = ugly_nums[i5] * 5 |
| 34 | |
| 35 | for _ in range(1, n): |
| 36 | next_num = min(next_2, next_3, next_5) |
| 37 | ugly_nums.append(next_num) |
| 38 | if next_num == next_2: |
| 39 | i2 += 1 |
| 40 | next_2 = ugly_nums[i2] * 2 |
| 41 | if next_num == next_3: |
| 42 | i3 += 1 |
| 43 | next_3 = ugly_nums[i3] * 3 |
| 44 | if next_num == next_5: |
| 45 | i5 += 1 |
| 46 | next_5 = ugly_nums[i5] * 5 |
| 47 | return ugly_nums[-1] |
| 48 | |
| 49 | |
| 50 | if __name__ == "__main__": |