爲什麼不會從道路對象列表中刪除項目?爲什麼我不能從道路清單中刪除道路?
相關信息
道對象需要(自我,city1,城2,長度),以及市採取的對象(自我,名稱,人口);
我將這些對象保存到列表_cities和_roads中,以便我可以修改它們。
這個定義應該刪除所有連接到城市的道路,然後刪除城市。然而,我的代碼並不想刪除我的道路(而且我沒有錯誤),所以我的邏輯必須是有缺陷的。
你能幫忙嗎?
class Network:
def __init__(self):
self._cities = [] # list of City objects in this network
self._roads = [] # list of Road objects in this network
def hasCity(self, name):
for x in self._cities:
if x.name == name:
return True
return False
def hasRoad(self, road):
for x in self._roads:
if x.city1 == road[0] and x.city2 == road[1]:
return True
elif x.city1 == road[1] and x.city2 == road[0]:
return True
else:
return False
def addCity(self, name, pop):
if self.hasCity(name) == True:
return False
else:
self._cities.append(City(name, pop))
return True
def addRoad(self, road, length):
if self.hasRoad(road) == True:
return False
else:
self._roads.append(Road(road[0], road[1], length))
return True
def delRoad(self, road):
if self.hasRoad(road) == False:
return False
else:
for x in self._roads:
if x.city1 == road[0] and x.city2 == road[1]:
self._roads.remove(x)
return True
elif x.city1 == road[1] and x.city2 == road[0]:
self._roads.remove(x)
return True
else:
return False
def delCity(self, city):
if self.hasCity(city) == False:
return False
else:
for x in self._cities:
if x.name == city:
for j in self._roads:
if j.city1 == x.name:
self.delRoad((j.city1, j.city2))
self.delRoad((j.city2, j.city1))
elif j.city2 == x.name:
self.delRoad((j.city1, j.city2))
self.delRoad((j.city2, j.city1))
self._cities.remove(x)
return True
你可以放在全班上課嗎? –
您可以將該問題改爲「如何刪除無向圖的邊緣」。 – asheeshr
深嵌「if」塊看起來多餘;他們可以在一個'if j.city1 == x.name或j.city2 == x.name:'子句 –