我在做一个假设很简单的python挑战,一个朋友给了我一个电梯和它运动背后的逻辑。一切都进行得很顺利,直到我不得不写下如何确定电梯是否可以移动,并在到达下一个排队楼层的途中撞上一个叫的楼层。你知道吗
def floorCompare(currentFloor,destinationFloor,calledFloor):
if calledFloor > currentFloor and calledFloor < destinationFloor:
return(True)
elif calledFloor < currentFloor and calledFloor > destinationFloor:
return(True)
else:
return(False)
floor = "1"
doors = "closed"
queue = []
def elevator(): # function defines how the elevator should move
print("The Elevator is on floor: 1. The doors are "+doors+".")
for x in range(int(input("How many floors need to be visited? "))):
callFloor = int(input("Floor to call the elevator to: "))
queue.append(callFloor)
if callFloor > 10 or callFloor < 1:
raise Exception(str(callFloor)+" is not a valid floor.")
if queue[0] == 1:
del queue[0]
print("The elevator has arrived on floor 1, and the doors are open.")
print("The queue of floors to visit is...",queue)
for x in queue:
print("The elevator's doors are closed and it's moving to floor:",x)
floor = str(x)
print("...")
print()
print("The elevator has arrived on floor "+floor+", and the doors are open.")
queue.remove(x)
addFloor = int(input("Floor to call the elevator to: "))
if addFloor > 10 or addFloor < 1:
raise Exception(str(addFloor)+" is not a valid floor.")
print(queue)
if floorCompare(int(floor), int(queue[0]), int(addFloor)) == True:
print("The elevator can hit this stop en route to its next one.")
else:
print("The elevator must hit this stop separately.")
print("Continuing Queue")
elevator()
所以在For循环中,有一个嵌套的If/Else循环,我假设它将与For循环中的其余代码一起迭代。但是,当我运行代码时,在到达If/Else循环时,它会跳出For循环,继续它的快乐之路,而忽略了需要在数组中进行的任何进一步迭代。这是怎么回事?你知道吗
当我用一个基本的楼层测试集运行代码时,下面是我得到的输出。你知道吗
The Elevator is on floor: 1. The doors are closed.
How many floors need to be visited? 4
Floor to call the elevator to: 3
Floor to call the elevator to: 6
Floor to call the elevator to: 9
Floor to call the elevator to: 10
The queue of floors to visit is... [3, 6, 9, 10]
The elevator's doors are closed and it's moving to floor: 3
...
The elevator has arrived on floor 3, and the doors are open.
Floor to call the elevator to: 7
[6, 9, 10]
The elevator must hit this stop seperately.
The elevator's doors are closed and it's moving to floor: 9
...
The elevator has arrived on floor 9, and the doors are open.
Floor to call the elevator to: 3
[6, 10]
The elevator must hit this stop separately.
Process finished with exit code 0
提前退出的原因是,您在列表上循环时正在修改列表。举个简单的例子:
输出为
但是,当前代码还有许多其他问题。我能抓住的是:
for
循环中添加新调用的楼层。你知道吗queue[0]
作为目标调用floorCompare
方法,而不是final方法。如您所见,由于您比较了3
和6
,因此7
没有被认为是在途中。你应该比较3
和10
,最远的一个。你知道吗还要注意,
queue
最初没有排序,中间调用也不会按顺序排列。所以你在使用它的时候要记住这一点。你知道吗我认为您的问题在于将for循环与队列.删除()功能。似乎
for x in queue:
操作符在运行时编辑列表时遇到了问题。我建议改为使用while queue:
,并将x设置为第一个元素。你知道吗它之所以跳过第6层,是因为从正在迭代的列表中删除了数据。你知道吗
输出: 三 6 9 10 14个
输出: 三 9 14个
相关问题 更多 >
编程相关推荐