一位学生遇到了一个家庭作业的难题,该作业涉及到电梯模拟,其中用户需要输入楼层数和使用电梯的人数,每个人的起始楼层和目标楼层都是楼层数内的随机数。学生意识到自己的代码非常稀疏,并且有很多空白,但他不知道从哪里继续。他希望在 Building 类中获得帮助,包括如何使 run() 和 output() 部分工作。他还希望获得其他任何有用的建议。
- 解决方案
import random
floors = input('Please enter the number of floors for the simulation: ')
while floors.isalpha() or floors.isspace() or int(floors) <= 0:
floors = input('Please re-enter a digit for the number of floors: ')
customers = input('Please enter the number of customers in the building: ')
while customers.isalpha() or customers.isspace() or int(customers) < 0:
customers = input('Please re-enter a digit for the number of customers: ')
count = 1
class Building:
def __init__(self, floors, customers):
self.num_of_floors = floors
self.customer_list = customers
self.elevator = Elevator()
def run(self):
for customer in self.customer_list:
self.elevator.register_customer(customer)
while customer.in_elevator():
self.elevator.move()
if self.elevator.cur_floor == customer.dst_floor:
self.elevator.cancel_customer(customer)
def output(self):
print(f'Elevator current floor: {
self.elevator.cur_floor}')
class Elevator:
def __init__(self):
self.num_of_floors = self.building.num_of_floors
self.register_list = []
self.cur_floor = 1
self.direction = self.get_direction()
def get_direction(self):
if self.cur_floor == 1:
return 'up'
elif self.cur_floor == self.num_of_floors:
return 'down'
else:
return None
def move(self):
if self.direction == 'up':
self.cur_floor += 1
elif self.direction == 'down':
self.cur_floor -= 1
def register_customer(self, customer):
self.register_list.append(customer.ID)
def cancel_customer(self, customer):
self.register_list.remove(customer.ID)
class Customer:
def __init__(self):
self.cur_floor = random.randint(0, int(floors))
self.dst_floor = random.randint(0, int(floors))
while self.dst_floor == self.cur_floor:
self.dst_floor = random.randint(0, int(floors))
self.ID = count
count += 1
self.cust_dict = {
self.ID: self.dst_floor}
def in_elevator(self):
return self.ID in self.elevator.register_list
def finished(self):
return self.ID not in self.elevator.register_list
if __name__ == '__main__':
building = Building(floors, customers)
building.run()
building.output()
在这个改进后的代码中:
- 我们使用了 Building 类来模拟整个电梯系统。
- 在 Building 类中,我们使用 init() 方法来初始化楼层数、客户列表和电梯。
- 我们还定义了 run() 方法来模拟电梯的运行,并定义了 output() 方法来输出电梯的当前楼层。
- 在 Elevator 类中,我们使用 init() 方法来初始化电梯的当前楼层、楼层数和注册的客户列表。
- 我们还定义了 get_direction() 方法来获取电梯的当前方向、move() 方法来移动电梯、register_customer() 方法来将客户注册到电梯、cancel_customer() 方法来将客户从电梯中取消。
- 在 Customer 类中,我们使用 init() 方法来初始化客户的当前楼层、目标楼层和 ID。
- 我们还定义了 in_elevator() 方法来检查客户是否在电梯中、finished() 方法来检查客户是否已到达目标楼层。
- 最后,我们在 main() 函数中创建了 Building 对象并调用了 run() 和 output() 方法。