Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมตรวจสอบว่าลิสต์เพิ่มหรือลดอย่างเคร่งครัดใน Python

ตรวจสอบลิสต์ตัวเลขว่า strictly increasing (เพิ่มทุกขั้น) หรือ strictly decreasing (ลดทุกขั้น)

ตัวอย่าง: [10,12,23,34,55] → True (strictly increasing)

อัลกอริธึม

  • ถ้าความยาว ≤ 2 → True เสมอ
  • ถ้ามีค่าซ้ำ → False
  • เรียงลิสต์ → เปรียบเทียบกับต้นฉบับและ reversed

การนำไปใช้

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]))  # True