📜  门| GATE-CS-2002 |第 38 题(1)

📅  最后修改于: 2023-12-03 15:28:41.371000             🧑  作者: Mango

门| GATE-CS-2002 |第 38 题

该题目是GATE-CS-2002的第38道题目,要求实现一个门类(Gate)的结构体与相关的操作(函数)。以下是该题目的详细介绍:

题目描述

定义一个结构体 Gate 表示门对象,每个门都有三种基本状态,如下:

  • OPEN: 表示门是打开的
  • CLOSED: 表示门是关闭的
  • BROKEN: 表示门是损坏的

Gate 结构体应该有下面的元素:

  • state: 表示门的状态,取值应该是 OPEN,CLOSED 或 BROKEN
  • number_of_doors: 表示门的数目,取值可以是任何正整数(0,1和2也是有效的值)
  • is_locked: 表示门是否被锁,如果门是被锁,则只有当状态为 CLOSED 时才可以打开
  • Door_names: 元组类型,包含门的名称,类型是(str,str),如('Front','Back')

结构体应该支持下面的操作:

  1. Display: 该函数用于打印门的当前状态(例如,Front door is OPEN)
  2. Open: 该函数用于打开一个门,前提是门不是 BROKEN 的并且不是锁定的
  3. Close: 该函数用于关闭一个门,前提是门不是 BROKEN 的并且不是锁定的
  4. Lock: 该函数用于锁定一个门,前提是门不是 BROKEN 的并且没有锁定
  5. Unlock: 该函数用于解锁门,前提是门没有 BROKEN 标记,并且锁定
  6. SetState: 该函数用于更改门的状态,前提是门没有 BROKEN 标记
  7. SetDoors: 该函数用于更改门的数目和名称,前提是门没有 BROKEN 标记
代码实现

以下是结构体 Gate 的定义以及相应操作的实现代码:

class Gate:
    def __init__(self, state, num_of_doors, is_locked, door_names):
        self.state = state
        self.num_of_doors = num_of_doors
        self.is_locked = is_locked
        self.door_names = door_names
  
    def Display(self):
        print(self.door_names[0] + " door is " + self.state)

    def Open(self):
        if self.state == "BROKEN":
            print("Can't open the door. It's BROKEN!")
        elif self.is_locked:
            print("Can't open the door. It's locked!")
        else:
            self.state = "OPEN"
            self.Display()

    def Close(self):
        if self.state == "BROKEN":
            print("Can't close the door. It's BROKEN!")
        else:
            self.state = "CLOSED"
            self.Display()

    def Lock(self):
        if self.state == "BROKEN":
            print("Can't lock the door. It's BROKEN!")
        elif self.is_locked:
            print("The door is already locked!")
        else:
            self.is_locked = True
            self.Display()

    def Unlock(self):
        if self.state == "BROKEN":
            print("Can't unlock the door. It's BROKEN!")
        elif not self.is_locked:
            print("The door is already unlocked!")
        else:
            self.is_locked = False
            self.Display()

    def SetState(self, new_state):
        if self.state == "BROKEN":
            print("Can't set the state. The door is BROKEN!")
        else:
            self.state = new_state
            self.Display()

    def SetDoors(self, num_of_doors, door_names):
        if self.state == "BROKEN":
            print("Can't set door details. The door is BROKEN!")
        else:
            self.num_of_doors = num_of_doors
            self.door_names = door_names
            self.Display()

以上代码实现了题目中要求定义的Gate类,并实现了各个操作。可以通过初始化一个Gate对象并直接调用类的函数来测试这些操作。