由於我在CareerCup上看到一個有趣的問題,我正在嘗試進行電梯模擬。我的問題是,我想讓電梯「花費時間」從一層移動到另一層。現在它立即移動到「訪問」列表中的下一個樓層。我不確定如何編程,以便在電梯移動時可以接入「取件請求」。我認爲這可能需要線程和time.sleep()函數。我如何使一個線程向電梯發出隨機請求,另一個線程使電梯試圖滿足所有請求?這是我到目前爲止:用於電梯模擬的蟒蛇線程
import time
from random import *
import math
class Elevator:
def __init__(self, num_floors):
self.going_up = False
self.going_down = False
self.docked = True
self.curr_floor = 0
self.num_floors = num_floors
self.floors_to_visit = []
self.people_waiting = []
def print_curr_status(self):
for i in range(self.num_floors):
if i == self.curr_floor:
print('. []')
else:
print('.')
print ("to_visit: ", self.floors_to_visit)
def handle_call_request(self, person):
if not self.going_up and not self.going_down:
self.floors_to_visit = [person.curr_floor] + self.floors_to_visit
self.going_up = True
self.docked = False
self.people_waiting.append(person)
else:
self.floors_to_visit.append(person.curr_floor)
self.people_waiting.append(person)
def handle_input_request(self, floor_num):
self.floors_to_visit.append(floor_num)
def go_to_next(self):
if not self.floors_to_visit:
self.print_curr_status()
return
self.curr_floor = self.floors_to_visit.pop(0)
for i,person in enumerate(self.people_waiting):
if person.curr_floor == self.curr_floor:
person.riding = True
person.press_floor_num()
self.people_waiting.pop(i)
return
class Person:
def __init__(self, assigned_elevator, curr_floor):
self.curr_floor = curr_floor
self.desired_floor = math.floor(random() * 10)
self.assigned_elevator = assigned_elevator
self.riding = False
def print_floor(self):
print(self.desired_floor)
def call_elevator(self):
self.assigned_elevator.handle_call_request(self)
def press_floor_num(self):
self.assigned_elevator.handle_input_request(self.desired_floor)
my_elevator = Elevator(20)
while True:
for i in range(3):
some_person = Person(my_elevator, math.floor(random() * 10))
some_person.call_elevator()
my_elevator.go_to_next()
my_elevator.print_curr_status()
time.sleep(1)
這是不難在所有做,你可以使用python線程,因爲他們將完美工作。他們在翻譯中使用搶先式線程這一事實根本就不重要。 – spectras
這取決於你如何做到這一點。 –
當然,總是有可能讓事情變得比他們應該更努力。 – spectras