def rivers_by_station_number(stations, N): """Returns a list of tuples (river, number of stations on that river)""" river_counts = [] river_dict = stations_by_river(stations) for (river, river_stations) in river_dict.items(): river_counts.append((river, len(river_stations))) # sort the list of rivers by number of stations, then by alphabetical # removes any ambiguity for tied rivers sorted_rivers = sorted_by_key(river_counts, 0) sorted_rivers = sorted_by_key(sorted_rivers, 1, reverse=True) return list(first_N_with_ties(sorted_rivers, N, i=1))
def rivers_by_station_number(stations, N): """1E. Determine the N rivers with the greatest number of monitoring stations. It should return a list of (river name, number of stations) tuples, sorted by the number of stations. In the case that there are more rivers with the same number of stations as the N th entry, include these rivers in the list""" stationsbyriver = stations_by_river(stations) convertedlist = [] for river, stations in stationsbyriver.items(): #loop and find number of stations for each river convertedlist.append((river, len(stations))) #sort according to number of stations convertedlist = sorted_by_key(convertedlist, 1) #reverse the list so that can start with river with greatest umber of stations convertedlist.reverse() copy = convertedlist #create final list without repeats first final = copy[:N] for x in range(N, len(copy)): #loop over and use copy for comprison if copy[x][1] == final[-1][1]: #after comparing, if there are rivers with same no of stations not in final, append to final final.append(copy[x]) """ for x in range (N): max=copy[:1][0][1] counter=0 for y in copy: if y[1]==max: final.append(y) counter+=1 for z in range (counter): del copy[0]""" return final
def stations_level_over_threshold(stations, tol): """Return the stations whose relative water level exceed a threshold. The stations are listed in order of decreasing relative water level. Parameters ---------- stations : list[MonitoringStation] tol : float threshold for relative water level Returns ------- list[(MonitoringStation, float)] A list of tuples containing the MonitoringStation object and its relative water level. """ output = [] for station in stations: relative_level = station.relative_water_level() if relative_level is not None: if relative_level > tol: output.append((station, relative_level)) return sorted_by_key(output, 1, reverse=True)
def stations_highest_rel_level(stations, N): '''This function creates a sorted list of all stations in order of relative water level it then returns the highest N values from that list''' if N >= len(stations): l = [("list is shorter than range", "soz")] return l else: update_water_levels(stations) l = [] for i in stations: x = i.relative_water_level() name = str(i.name) if x != 0: if i.typical_range_consistent() == True: if i.latest_level is not None: y = (name, x) l.append(y) l = sorted_by_key(l, 1, reverse=True) highest_rel_range = [] for i in range(N): highest_rel_range.append(l[i]) return highest_rel_range
def run(): """Requirement for task 2G""" #build a list of stations stations = build_station_list() update_water_levels(stations) stations_at_risk = stations_highest_rel_level(stations, 10) # Fetch data over past 2 days dt = 0.5 danger_stations = [] for station in stations_at_risk: dates, levels = fetch_measure_levels(station.measure_id, dt=datetime.timedelta(days=dt)) try: prediction = predicted_value(dates, levels) danger_level = danger_assigning(station, prediction) if danger_level is not None: if danger_level[1] == "severe" or danger_level[1] == "high": danger_stations.append(danger_level) except: pass sorted_stations = sorted_by_key(danger_stations, 1, reverse=True) for i in sorted_stations: print(i[0] + ":" + i[1])
def run(): """Requirement for Task 2E""" #Initialise variables data = build_station_list() update_water_levels(data) ls = [] ID = [] #Number of days in past taken data from dt = 7 #How many graphs per window limit = 4 #How many stations number = 6 #Create list of measuring_id's sorted by water level for station in data: if station.typical_range_consistent( ) == True and station.relative_water_level() != None: ls.append((station, station.relative_water_level())) ls = sorted_by_key(ls, 1) for station in ls: ID.append(station[0]) s = count_inconsistent_sets(ID[:number], dt) ID = ID[:number + s] plot_water_levels(ID, dt, limit, s)
def rivers_by_station_number(stations, N): output_list = [] rivers = [] number_of_rivers = [] for i in stations: """Iterates through stations that are given to the function""" if i.river not in rivers: """Adds a new entry to rivers when new river is seen and initializes that rivers number to 1""" rivers.append(i.river) number_of_rivers.append(1) else: """Keeps adding 1 to every river that is already in the list""" for j in range(0, len(rivers)): if rivers[j] == i.river: number_of_rivers[j] = number_of_rivers[j] + 1 for w in range(0, len(rivers)): """combines the rivers and number of rivers list into one as tuples""" output_list.append((rivers[w], number_of_rivers[w])) """sorts them based on the number of rivers""" output_list = sorted_by_key(output_list, 1) """orders it from highest to lowest""" output_list = output_list[::-1] while output_list[N - 1][1] == output_list[N][1]: """Checks if the next few rivers also have the same number and outputs them if they do""" N = N + 1 return (output_list[:N])
def run(): """Requirements for Task 1B""" cam_coord = (52.2053, 0.1218) #coordinates of Cambridge city centre #build station list stations = build_station_list() #calculate the distances to coordinates distances_to_cam = stations_by_distance(stations, cam_coord) #10 closest will be the first 10 items in the list close10 = distances_to_cam[:10] #reverse the order and take the first 10 items of the re-orderd list distances_to_cam = sorted_by_key(distances_to_cam, 1, reverse=True) far10 = distances_to_cam[:10] #format outputs close10formatted = [] far10formatted = [] for i in close10: close10formatted.append((i[0].name, i[0].town, i[1])) for i in far10: far10formatted.append((i[0].name, i[0].town, i[1])) print("Closest 10 stations to Cambride:") for i in close10formatted: print(i) print("") print("Furthest 10 stations from Cambridge:") for i in far10formatted: print(i)
def stations_by_distance(stations, p): a = [] for i in stations: x = float(haversine(p, i.coord, miles=False)) y = (i, x) a.append(y) a = sorted_by_key(a, 1) return a
def low_and_moderate_staions(stations): output_list = [] output_list_low = [] output_list_moderate = [] stations_that_are_flooding = [] relative_water_level = [] for i in stations: if i.relative_water_level() != None: """adding all things that are low""" if i.relative_water_level() > 0 and i.relative_water_level() < 1: stations_that_are_flooding.append(i.name) relative_water_level.append(i.relative_water_level()) for j in range(1, len(stations_that_are_flooding)): """putting them in one tuple""" output_list.append( (stations_that_are_flooding[j], relative_water_level[j])) """sorting stuff out""" output_list = sorted_by_key(output_list, 1) output_list = output_list[::-1] output_list_low = output_list output_list = [] moderate_list = [] stations_that_are_flooding = [] relative_water_level = [] for i in stations: if i.relative_water_level() != None: """adding all things that are moderate""" if i.relative_water_level() > 1: stations_that_are_flooding.append(i.name) relative_water_level.append(i.relative_water_level()) """FOR YOU TO USE""" moderate_list.append(i) for j in range(1, len(stations_that_are_flooding)): """putting them in one tuple""" output_list.append( (stations_that_are_flooding[j], relative_water_level[j])) """sorting stuff out""" output_list = sorted_by_key(output_list, 1) output_list = output_list[::-1] output_list_moderate = output_list return ( "The list of stations that have a low risk are: " + str(output_list_low) + "....................................................... The list of stations that have a moderate risk are: " + str(output_list_moderate))
def stations_by_distance(stations, p): """Function to sort stations distance from a coordinate""" sdlist = [] # List store all the station and distance with p distance = 0 for station in stations: # Loop for all the stations cord = station.coord # Coordinate of the station distance = haversine(p, cord) # Use function to get the distance sdlist.append((station.name, distance)) # Add Tuple to the List return sorted_by_key(sdlist, 1) # Return the sorted list
def stations_by_distance(stations, p): "function returns a list of tuples in format (station name, distance from p)" stations_and_distances = [] for station in stations: distance = haversine(station.coord, p) stations_and_distances.append((station, distance)) final = sorted_by_key(stations_and_distances, 1, reverse=False) return final
def stations_by_distance(stations, p): output_list = [] for i in stations: """Iterates through the list named "stations" given to the function""" dist = haversine(p, i.coord) output_list.append((i, dist)) output_list = sorted_by_key(output_list, 1) """This uses the function from the utils file and outputs the same list, but sorted based on the 2nd element which has i=1""" return (output_list)
def stations_level_over_threshold(stations, tol): "Function returns a list of tuples of stations at which the current relative water level is greater than tol in the form (station name, relative water level)" relatives = [] for station in stations: if station.relative_water_level( ) != None and station.relative_water_level() >= tol: relatives.append((station.name, station.relative_water_level())) descending_relatives = sorted_by_key(relatives, 1, reverse=True) return descending_relatives
def stations_highest_rel_level(stations, N): station_rel_level = [] for station in stations: if station.relative_water_level() == None: pass else: #Same as previous but this time does not check if above tolerance, do for all stations name_level = (station.name, station.relative_water_level()) station_rel_level.append(name_level) sorted_station = sorted_by_key(station_rel_level, 1, True) return sorted_station[:N]
def stations_by_distance_with_town(stations, p): """function for doing 1B demonstration program""" sdlist = [] # List store all the station and distance with p distance = 0 for station in stations: # Loop for all the stations cord = station.coord # Coordinate of the station distance = haversine(p, cord) # Use function to get the distance town = station.town sdlist.append( ((station.name, town), distance)) # Add Tuple to the List return sorted_by_key(sdlist, 1) # Return the sorted list
def stations_by_distance(stations, p): """Given a list of station objects and a coordinate, the function returns a list of tuples (station, distance)""" distances = [] for station in stations: coordinate = station.coord distance = haversine(coordinate, p) distances.append((station, distance)) sorted_distances = sorted_by_key(distances, 1) return sorted_distances
def stations_level_over_threshold(stations, tol): update_water_levels(stations) stationsleveloverthreshold=[] for station in stations: if station.relative_water_level() == None: continue if station.relative_water_level()>tol: stationsleveloverthreshold.append((station,station.relative_water_level())) stationsleveloverthreshold=sorted_by_key(stationsleveloverthreshold,1) stationsleveloverthreshold.reverse() return stationsleveloverthreshold
def stations_level_over_threshold(stations, tol): """Returns a list of tuples, each holding a station at which the latest relative water level is over tol and the relative water level at that station""" water_level_stations = [] for station in stations: relative_level = station.relative_water_level() if relative_level is not None and relative_level > tol: details = (station, relative_level) water_level_stations.append(details) sorted_stations = sorted_by_key(water_level_stations, 1, True) return sorted_stations
def stations_highest_rel_level(stations, N): """Returns a list of the N stations at which the water level, relative to the typical range, is highest""" water_level_stations = [] for station in stations: relative_level = station.relative_water_level() if relative_level is not None: details = (station, relative_level) water_level_stations.append(details) sorted_by_water_level = sorted_by_key(water_level_stations, 1, True) sorted_stations = [i[0] for i in sorted_by_water_level] return sorted_stations[:N]
def stations_highest_rel_level(stations, N): stationsratio=[] for station in stations: if station.relative_water_level()==None: continue else: stationsratio.append((station,station.relative_water_level())) #sort with highest at level at the start stationsratio=sorted_by_key(stationsratio,1) stationsratio.reverse() #take the top 10 stationshighestratio=stationsratio[:N] return stationshighestratio
def stations_by_distance(p): distance = [] stationname = [] name_distance = [] stations = build_station_list() for station in stations: stationname.append(station.name) distance.append(haversine(station.coord, p)) i = 0 while i < len(stationname): name_distance.append((stationname[i], distance[i])) i += 1 return sorted_by_key((name_distance), 1)
def stations_level_over_threshold(stations, tol): #Create empty list that will hold station that is above the tolerance flood_stations = [] for station in stations: #Ignore stations where there is no relative water level if station.relative_water_level() == None: pass else: #Add station and the water level to list if the relative water level is above tolerance if station.relative_water_level() > tol: high_station_level = (station.name, station.relative_water_level()) flood_stations.append(high_station_level) #Return list sorted by relative water level return sorted_by_key(flood_stations, 1, True)
def stations_highest_rel_level(stations, N): """ Sorts list of stations by highest to lowest relative water level and returns highest N stations :param stations: Stations to be sorted :param N: Number of stations to be returned :return: List of N stations with highest relative water level """ stations_level = [] for station in stations: if station.relative_water_level() is not None: stations_level.append((station, station.relative_water_level())) sorted_levels = sorted_by_key(stations_level, 1, True) return [x[0] for x in sorted_levels[:N]]
def station_by_distance(stations, p): """ This function returns a list of (station, distance) tuples, where distance(float) is the distance of the station(MonitoringStation) from the coordinate p given a list of stations """ #Initialising variables ls = [] #Add stations and distance of station from p to list for station in stations: distance = haversine(station.coord, p) ls.append((station, distance)) #Returns list sorted by distance return sorted_by_key(ls, 1)
def age_in_years(stations): """ Function that takes in MonitoringStation object and calculates how many years there are between its opening date and the current date, returns a list of tuples with name of staion and age""" #Initialise variables d2 = date.today() d = [] for station in stations: #Convert to datetime object d1 = parser.parse(station.dateOpened).date() #Calculates age in days and rounds to nearest year d.append((station, round(abs((d2 - d1).days) / 365.25))) return sorted_by_key(d, 1)
def stations_by_distance(station, p): distance_list = [] for i in station: name = i.name town = i.town coordinate = i.coord #Taking the desired values from the list of monitoring stations distance = haversine(coordinate, p) d = (name, town, distance) distance_list.append(d) #Putting the desired value into a new list, along with the distance return sorted_by_key(distance_list, 2)
def stations_highest_rel_level(stations, N): output_list = [] station_name = [] relative_water_level = [] for i in stations: """Making up a randomish list of all sttaions and relative levels""" if i.relative_water_level() != None: station_name.append(i.name) relative_water_level.append(i.relative_water_level()) for j in range(1, len(station_name)): """putting them in one tuple""" output_list.append((station_name[j], relative_water_level[j])) """sorting the stuff out well and good""" output_list = sorted_by_key(output_list, 1) output_list = output_list[::-1] output_list = output_list[0:N] return (output_list)
def run(): # Build list of stations stations = build_station_list() # Update latest level data for all stations update_water_levels(stations) #Initiate empty list levellist = [] #initiate temperory storage for water level data for error processing templevel = 0 # iterate for all stations for station in stations: templevel = station.latest_level # Change NonType to zero for data analysis if templevel == None: templevel = 0 # Change negative error data to zero if templevel < 0: templevel = 0 # append to a list levellist.append((station.name, templevel)) # Sorted after iteration levellist = sorted_by_key(levellist, 1) # get the greatest five station levellist = levellist[-5:] # Get the name of the 5 stations (first entry of the tumple) stationname = [] for llist in levellist: stationname.append(llist[0]) print(stationname) for station_name in stationname: station_temp = None for station in stations: if station.name == station_name: station_temp = station break dt = 12 dates, levels = fetch_measure_levels(station_temp.measure_id, dt=datetime.timedelta(days=dt)) plot_water_level_with_fit(station_name, dates, levels, 4)
def stations_by_distance(stations, p): """1.B In the submodule geo implement a function that, given a list of station objects and a coordinate p, returns a list of (station, distance) tuples, where distance (float) is the distance of the station (MonitoringStation) from the coordinate p. The returned list should be sorted by distance. """ #create empty list stationsorteddistance = [] #looop over all stations for station in stations: #compute distance for each station distance = float(haversine(p, station.coord)) #for each station create tuple containing station name and distance) s = (station.name, station.town, distance) #append each new entry to the list stationsorteddistance.append(s) #sort the list according to station distance stationsorteddistance = sorted_by_key(stationsorteddistance, 2) return stationsorteddistance