Check if a list is monotonic. >>> is_monotonic([1, 2, 2, 3]) True >>> is_monotonic([6, 5, 4, 4]) True >>> is_monotonic([1, 3, 2]) False >>> is_monotonic([1,2,3,4,5,6,5]) False >>> is_monotonic([-3,-2,-1]) True >>> is_monotonic([-5,-6,-7]) True
(nums: list[int])
| 1 | # https://leetcode.com/problems/monotonic-array/ |
| 2 | def is_monotonic(nums: list[int]) -> bool: |
| 3 | """ |
| 4 | Check if a list is monotonic. |
| 5 | |
| 6 | >>> is_monotonic([1, 2, 2, 3]) |
| 7 | True |
| 8 | >>> is_monotonic([6, 5, 4, 4]) |
| 9 | True |
| 10 | >>> is_monotonic([1, 3, 2]) |
| 11 | False |
| 12 | >>> is_monotonic([1,2,3,4,5,6,5]) |
| 13 | False |
| 14 | >>> is_monotonic([-3,-2,-1]) |
| 15 | True |
| 16 | >>> is_monotonic([-5,-6,-7]) |
| 17 | True |
| 18 | >>> is_monotonic([0,0,0]) |
| 19 | True |
| 20 | >>> is_monotonic([-100,0,100]) |
| 21 | True |
| 22 | """ |
| 23 | return all(nums[i] <= nums[i + 1] for i in range(len(nums) - 1)) or all( |
| 24 | nums[i] >= nums[i + 1] for i in range(len(nums) - 1) |
| 25 | ) |
| 26 | |
| 27 | |
| 28 | # Test the function with your examples |