You have a file that describes historic data of the London Underground showing dates when stations have been unavailable. The file contains these fields, separated by a pipe character:
- Date: Format of this is mm-dd-yyyy.
- Line: Each line has a unique name. For example, “Northern”.
- Station: Each station has a unique name. For example, “Angel”.
- Notes: Describes the outage
Here is an example of one entry in the file, which shows that the Northern Line was not operating at Bank on 23 August 2019 due to a function at London Bridge.
08-23-2019|Northern|Bank |No service on Bank branch due to birthday booking at London Bridge station.
Write a script that solves the following problems:
Display each station that was affected by an outage on 10 July 2019.
Between 10 July 2017 and 14 November 2017, which lines had outages and what was the number of stations affected?
I was able to complete both problems but the review of the work said it was done poorly.
# I created a test input file in the same folder as a proxy input.
import datetime # import built in datetime module for problem 2
with open('input.txt') as file: # read the input file into a list of lines
file_input = file.read().splitlines()
# split the file input on the pipe
LonUndOutages = []
for var in file_input:
LonUndOutages.append(var.split("|"))
# creating empty lists for the answers for Problem 2
Prob1Output = ""
LonUndStations = []
LonUndLines = []
# solving problem 1 and prep for the answers for Problem 2
print("Problem 1:")
for line in LonUndOutages:
if line[0] == "07-10-2019":
Prob1Output = Prob1Output + line[2] + "was affected by an outage on July 10, 2019\n"
line[0] = datetime.datetime.strptime(line[0], '%m-%d-%Y') # convert the date in line[0] to a datetime object
if datetime.datetime(2017,7,10) < line[0] < datetime.datetime(2017,11,14):
# the above line checks if line[0] is in the time range july 10 2017 to nov 14, 2017
if line[1] not in LonUndLines: # ensures LonUndLines doesnt have duplicates
LonUndLines.append(line[1]) # adds each line that had an outage to a list
if line[2] not in LonUndStations: # ensures LonUndStations doesnt have duplicates
LonUndStations.append(line[2]) # adds each station that had an outage to a list
if not Prob1Output:
print("There were no stations affected by an outage on July 10, 2019")
else:
print(Prob1Output)
print()
print("Problem 2:")
print("The following lines had outages:")
print(*LonUndLines, sep=', ')
print("During the period between July 10, 2017 and November 15, 2017 there were " + str(len(LonUndStations))
+ " station(s) affected")