携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第11天,点击查看活动详情
大家好 我是短袖撸码蒂尔尼。今天带来的是一道python的题目,来自之前我的一个朋友的课程作业,在他提交完作业之后,我搞到了原题,题目难度不大。但我好久没做过这种题目了,就在此为大家分享一下解答思路。
题目阐述
你的手里有一幅地铁线路图:
读取的文件是一个txt格式的文件。 格式如下:
大体思路
前三点比较简单,第四点的实现思路如下:
- 查找是否在同一条线上
- 如果在同一条线路上 返回列表(包含起始站点和终止站点)
- 如果只有一站点:返回列表(包含站点)
- 然后查找下一条线路 :
- 如果找不到 就 print 未找到连接
- 如果找到了 判断是否和刚才找到的是同一个站点
- 如果不是 就查找中转站
- 然后查找下一条线路 :
代码实现
这道题目的思路使用自定义类的思想,首先去建立一个地铁类Line name代表线路名称,stations代表站点列表。
class Line:
def __init__(self, name, stations):
self.name = name
self.stations = stations
然后编写两个函数
find_connection函数,目的是找到两条线路的中转站:
def find_connection(l1: Line, l2: Line):
interchange_stations = []
for l1_station in l1.stations:
i = 0
while i < len(l2.stations):
l2_station = l2.stations[i]
if l1_station == l2_station:
interchange_stations.append(l2_station)
break
i += 1
interchange_stations.sort(key=sort_by_first_letter, reverse=False)
return interchange_stations
find_station_in_same_line:检查输入的两个站点是否下同一条线路上 返回符合条件:在线路l1上的站点o和d的列表**search_list **
def find_station_in_same_line(l: Line, o, d):
station_list = []
for station in l.stations:
if station == o:
station_list.insert(0, o)
if station == d:
station_list.append(d)
return station_list
通过返回的L1和L2的 search_list的长度进行条件判断:
小于2 说明线路上根本没这两站点 洗洗睡吧
l1_searchlist = find_station_in_same_line(line1, origin, destination)
l2_searchlist = find_station_in_same_line(line2, origin, destination)
if len(l1_searchlist) + len(l2_searchlist) < 2:
print("Station not found")
2,说明有路线,注意一下输出顺序即可。
# The two stations are on the same line and no change is needed.
elif 4 > len(l1_searchlist) + len(l2_searchlist) and (
len(l1_searchlist) == 2 or len(l2_searchlist) == 2
):
if len(l1_searchlist) == 2:
print(
"To get from %s to %s take the %s line" % (origin, destination, line1.name)
)
else:
print(
"To get from %s to %s take the %s line" % (origin, destination, line2.name)
)
#
长度为4,说明不止一条线路:
elif len(l1_searchlist) + len(l2_searchlist) == 4:
namelist = sorted([line1.name, line2.name])
print(
"To get from %s to %s take the %s line or the %s line"
% (origin, destination, namelist[0], namelist[1])
)
好了,当 search_list长度为2-4而且是一个站点在l1 第二个l2那怎么办呢
只需要找一下中转站:
interchange_stations = find_connection(line1, line2)
if len(interchange_stations) == 0:
print("No connection found!")
如果存在中转站按情况打印即可。
我是短袖撸码蒂尔尼
一名热爱阿森纳的前端工程师
如果本文对您有帮助,可以给一个免费的赞吗?谢谢!