用 Python 检查列表是严格递增还是严格递减的程序
pythonserver side programmingprogramming更新于 2026/1/7 1:16:17
假设我们有一个数字列表;我们必须检查列表是严格递增还是严格递减。
因此,如果输入为 nums = [10, 12, 23, 34, 55],则输出将为 True,因为所有元素都是不同的,并且每个元素都大于前一个元素,因此这是严格递增的。
为了解决这个问题,我们将遵循以下步骤 −
- 如果 nums 的大小 <= 2,则
- 返回 True
- 如果 num 中的所有元素都不不同,则
- 返回 False
- ordered := 对列表 nums 进行排序
- 当 nums 与 ordered 相同或 nums 与以相反方式排序的 ordered 相同时返回 true,否则返回 false。
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, nums): if len(nums) <= 2: return True if len(set(nums)) != len(nums): return False ordered = sorted(nums) return nums == ordered or nums == ordered[::-1] ob = Solution() print(ob.solve([10, 12, 23, 34, 55]))
输入
[10, 12, 23, 34, 55]
输出
True
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

