Setting distance Dimension in Or tools for vehicle routing problem - python
I am trying to solve a vehicle routing problem with 5 drivers for deliveries. I am using haversine and lat-long to calculate the distance matrix. I am new to OR tools, so following the vrp example.
The issues is that the out 0f 5 drivers, only routes are generated for 2 drivers and these routes are very long. I want to generate multiple shorter routes so that all the drivers are utilized. Can please check if I am setting some constraint wrong.
Can someone please explain, how to set "Distance" dimension and SetGlobalSpanCostCoefficient in google OR-tools. Here is the code and output.
from __future__ import print_function
import pandas as pd
import numpy as np
import googlemaps
import math
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
gmaps = googlemaps.Client(key='API Key')
def calculate_geocodes():
df = pd.read_csv("banglore_zone.csv")
df['lat'] = pd.Series(np.repeat(0, df.size), dtype=float)
df['long'] = pd.Series(np.repeat(0, df.size), dtype=float)
result = np.zeros([df.size, 2])
for index, row in df.iterrows():
# print(row['Address'])
geocode_result = gmaps.geocode(row['Address'])[0]
lat = (geocode_result['geometry']['location']['lat'])
lng = (geocode_result['geometry']['location']['lng'])
result[index] = lat, lng
df.lat[index] = lat
df.long[index] = lng
print("First step", df)
coords = df.as_matrix(columns=['lat', 'long'])
return coords, df
def calculate_distance_matrix(coordinates, gmaps):
distance_matrix = np.zeros(
(np.size(coordinates, 0), np.size(coordinates, 0))) # create an empty matrix for distance between all locations
for index in range(0, np.size(coordinates, 0)):
src = coordinates[index]
for ind in range(0, np.size(coordinates, 0)):
dst = coordinates[ind]
distance_matrix[index, ind] = distance(src[0], src[1], dst[0], dst[1])
return distance_matrix
def distance(lat1, long1, lat2, long2):
# Note: The formula used in this function is not exact, as it assumes
# the Earth is a perfect sphere.
# Mean radius of Earth in miles
radius_earth = 3959
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi / 180.0
phi1 = lat1 * degrees_to_radians
phi2 = lat2 * degrees_to_radians
lambda1 = long1 * degrees_to_radians
lambda2 = long2 * degrees_to_radians
dphi = phi2 - phi1
dlambda = lambda2 - lambda1
a = haversine(dphi) + math.cos(phi1) * math.cos(phi2) * haversine(dlambda)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
d = radius_earth * c
return d
def haversine(angle):
h = math.sin(angle / 2) ** 2
return h
def create_data_model(distance_matrix, number_of_vehicles, depot):
"""Stores the data for the problem."""
data = {}
data['distance_matrix'] = distance_matrix
print(distance_matrix)
data['num_vehicles'] = number_of_vehicles
data['depot'] = depot
return data
def print_solution(data, manager, routing, solution, address_dataframe):
"""Prints solution on console."""
max_route_distance = 0
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
route_distance = 0
while not routing.IsEnd(index):
plan_output += ' {} ---> '.format(address_dataframe.iloc[manager.IndexToNode(index), 0])
previous_index = index
index = solution.Value(routing.NextVar(index))
route_distance += routing.GetArcCostForVehicle(
previous_index, index, vehicle_id)
plan_output += '{}\n'.format(manager.IndexToNode(index))
plan_output += 'Distance of the route: {}m\n'.format(route_distance)
print(plan_output)
max_route_distance = max(route_distance, max_route_distance)
print('Maximum of the route distances: {}m'.format(max_route_distance))
def main():
coordinates, address_dataframe = calculate_geocodes()
distance_matrix = calculate_distance_matrix(coordinates, gmaps)
data = create_data_model(distance_matrix, 5, 0)
# Create the routing index manager.
manager = pywrapcp.RoutingIndexManager(
len(data['distance_matrix']), data['num_vehicles'], data['depot'])
# Create Routing Model.
routing = pywrapcp.RoutingModel(manager)
# Create and register a transit callback.
def distance_callback(from_index, to_index):
"""Returns the distance between the two nodes."""
# Convert from routing variable Index to distance matrix NodeIndex.
from_node = manager.IndexToNode(from_index)
to_node = manager.IndexToNode(to_index)
return data['distance_matrix'][from_node][to_node]
transit_callback_index = routing.RegisterTransitCallback(distance_callback)
# Define cost of each arc.
routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
# Add Distance constraint.
dimension_name = 'Distance'
routing.AddDimension(
transit_callback_index,
0, # no slack
80, # vehicle maximum travel distance
True, # start cumul to zero
dimension_name)
distance_dimension = routing.GetDimensionOrDie(dimension_name)
distance_dimension.SetGlobalSpanCostCoefficient(100)
# Setting first solution heuristic.
search_parameters = pywrapcp.DefaultRoutingSearchParameters()
search_parameters.local_search_metaheuristic = (
routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
search_parameters.time_limit.seconds = 120
search_parameters.log_search = False
# Solve the problem.
solution = routing.SolveWithParameters(search_parameters)
# Print solution on console.
if solution:
print_solution(data, manager, routing, solution, address_dataframe)
if __name__ == '__main__':
main()
And the distance matrix and output is -
> [[ 0. 0.31543319 3.36774402 ... 8.79765925 8.94261055
> 8.83759758] [ 0.31543319 0. 3.09418962 ... 8.81074289 8.95034082
> 8.84901702] [ 3.36774402 3.09418962 0. ... 10.87348059 10.97329493
> 10.89962072] ... [ 8.79765925 8.81074289 10.87348059 ... 0. 0.20726879
> 0.06082994] [ 8.94261055 8.95034082 10.97329493 ... 0.20726879 0.
> 0.1465572 ] [ 8.83759758 8.84901702 10.89962072 ... 0.06082994 0.1465572
> 0. ]] Route for vehicle 0: 3Embed software 10th Cross St, RBI Colony, Ganganagar, Bengaluru, Karnataka 560024 ---> 0 Distance of
> the route: 0m
>
> Route for vehicle 1: 3Embed software 10th Cross St, RBI Colony,
> Ganganagar, Bengaluru, Karnataka 560024 ---> 0 Distance of the route:
> 0m
>
> Route for vehicle 2: 3Embed software 10th Cross St, RBI Colony,
> Ganganagar, Bengaluru, Karnataka 560024 ---> Sindhi High School,
> Kempapura ---> Hoppers stop Building No.12, Krishnaja Avenue, Near
> Kogilu Cross, International Airport Road, Yelahanka, Bengaluru --->
> Kempegowda International Airport Bengaluru ---> mvit International
> Airport Road, Hunasamaranahalli, Yelahanka, Krishnadeveraya Nagar,
> Bengaluru ---> Canadian International School 4 & 20, Manchenahalli,
> Yelahanka, Bengaluru ---> brick factory RMZ Galleria, Office Block,
> Ground Floor, B.B. Road, Yelahanka ---> Jakkur Aerodrome Bellary
> Road, Post, Yelahanka, Bengaluru, Karnataka ---> Godrej Platinum
> International Airport Road, Hebbal, Bengaluru, Karnataka ---> Vidya
> Niketan School 30, Kempapura Main Road, Kempapura, Hebbal, Bengaluru,
> Karnataka ---> Atria Institute of Technology, 1st Main Rd, Ags
> Colony, Anandnagar, Hebbal, Bengaluru, Karnataka ---> 0 Distance of
> the route: 26m
>
> Route for vehicle 3: 3Embed software 10th Cross St, RBI Colony,
> Ganganagar, Bengaluru, Karnataka 560024 ---> Caffe cofee day CBI road
> banglore ---> 0 Distance of the route: 0m
>
> Route for vehicle 4: 3Embed software 10th Cross St, RBI Colony,
> Ganganagar, Bengaluru, Karnataka 560024 ---> RT Nagar Police station
> ---> bus stop mekhri circle banglore ---> Truffles 80 Feet Road, Jaladarsini Layout, Sanjaynagar Banglore ---> BEL circle banglore
> ---> Paragon Outlet Shivapura, Peenya, Bengaluru ---> Taj vivanta Yeshwantpur, Bengaluru ---> Orion Mall A Block, Brigade Gateway, Dr
> Rajkumar Rd, Malleshwaram, Bengaluru ---> brand factory Malleshwaram
> Banglore ---> Mantri Square Mall, Sampige Road, Malleshwaram,
> Bengaluru, Karnataka ---> Krantivira Sangolli Rayanna Bengaluru, M.G.
> Railway Colony, Majestic, Bengaluru ---> UB city banglore --->
> Brigade road banglore ---> MG Road metro station Banglore --->
> commercial street bangalore ---> Infantry Road, Beside Prestige
> Building, Tasker Town, Shivaji Nagar, Bengaluru, Karnataka --->
> Garuda Mall Magrath Rd, Ashok Nagar, Bengaluru ---> Brand Factory -
> Home Town Above HomeTown, Vanshee Towers, Survey No.92/4 3rd and 4th
> Floors, Outer Ring Rd, Marathahalli, Bengaluru ---> KLM Shopping
> Mall, Marathahalli Bridge Marathahalli ---> Favourite Shop HAL Old
> Airport Rd, Subbaiah Reddy Colony, Marathahalli Village, Marathahalli,
> Bengaluru ---> Max RPR Plaza, Varthur Rd, Marathahalli, Bengaluru
> ---> Pick 'n' Move Shop No. 102, Ground Floor, Varthur Rd, Marathahalli Village, Marathahalli, Bengaluru ---> Lotto Shoes 45/2,
> Varthur Rd, Marathahalli Village, Marathahalli, Bengaluru, Karnataka
> ---> The Raymond Shop Opp. Mga Hospital, Marathalli Main Road Near Ring Road Junction, Bengaluru, Karnataka ---> chinnaswamy stadium
> banglore ---> fun cinemas cunningham road Banglore ---> Cant station
> banglore ---> Radhakrishna Theatre 25, 1st Main Rd, Mattdahally, RT
> Nagar, Bengaluru ---> Presidency School Near R T Nagar, HMT Layout,
> Bengaluru, Karnataka ---> 0 Distance of the route: 20m
>
> Maximum of the route distances: 26m
You should reduce vehicle maximum travel distance. currently you set it to 80.
and your routes distances are 20 and 26.
routing.AddDimension(
transit_callback_index,
0, # no slack
80, # vehicle maximum travel distance
True, # start cumul to zero
dimension_name)
You can use global span cost which would reduce the longest route traveled by any vehicle.
Eg. use it on the distance dimension like distance_dimension.SetGlobalSpanCostCoefficient().
Pass a high integer value as an argument, which is greater than the sum of all costs. Try setting it to 1000 or so.
Related
Problems in trying to decode through statistics
My goal is to decode a message with the statistics of letters occurrence in the French language. For that, I created a first function which creates a string in decreasing order of occurrence in the text. Then, I match the index of the characters and I change each character with the one corresponding to the French language. The problem is that the text comes out unchanged in the console. I am a beginner in programming and any help on my mistakes or inaccuracies are appreciated. Thanks !!! import string texte = f"""iwnspa rynjjdj arg sj hjuajhask awaigkhihaj ag sj ongyaonghihaj ps vvha rhaiwa, rdsqajg idjrhpaka idooa wa xaka pa wn gyadkha pa w’hjbdkonghdj. hw arg ja wa 30 nqkhw 1916 n xagdrlaf, pnjr wa ohiyhunj. rdj xaka arg sj csua, ag rn oaka arg wa xkdqhrask ps wfiaa pa unfwdkp, sja nsgka qhwwa ps ohiyhunj. hw agspha n w’sjhqakrhga ps ohiyhunj ds hw rshg sj pdszwa iskrsr aj awaigkhihga ag aj ongyaonghmsar. hw dzghajg sja whiajia pnjr iar pasv phrihxwhjar aj 1936, nqnjg pa xdskrshqka rar agspar ns kaxsga ohg (onrrniysraggr hjrghgsga db gaiyjdwduf ). hw rdsghajg aj 1940 sja gyara pa pdigdkng aj ongyaonghmsar (awwa xdkgnhg rsk par nxxwhinghdjr par ongyaonghmsar n wn uajaghmsa) ag sj oaodhka pa onrgak aj awaigkhihga. rh wn xkaohaka bsg wnkuaoajg hujdkaa, wn raidjpa,msh avxwhmsa idooajg sghwhrak war nwuazkar pa zddwa xdsk w’njnwfra par rhujnsv awaigkhmsar, arg kargaa iawazka. aj 1941, hw arg aoznsiya pnjr war wnzdkngdhkar pa wn idoxnujha pa gawaxydja ngg zaww. hooaphngaoajg, hw gknqnhwwa rsk par xkdcagr aj whnhrdj nqai war rakqhiar raikagr, msh wsh bdjg jdgnooajg nzdkpak par msarghdjr pa ikfxgduknxyha. aj 1949, hw ra onkha; xnk wn rshga, hw nskn gkdhr ajbnjgr. rynjjdj gknqnhwwa nsv wnzdkngdhkar pa zaww csrms’aj 1971. xnknwwawaoajg n iawn, hw arg nsrrh xkdbarrask ns ohg pa 1958 n 1978. rynjjdj idoxkajpmsa gdsga pdjjaa, oaoa wn qdhv ds par honuar, xasg ra gknjroaggka n w’nhpa p’sja rshga pa 0 ag pa 1 (war zhgr), dsqknjg wn qdha nsv idoosjhinghdjr jsoakhmsar ag jdj xwsr njnwduhmsar. hw odjgka nsrrh idooajg wa bnhg p’ncdsgak iakgnhjr zhgr n sj oarrnua xasg xakoaggka pa qakhbhak msa war nsgkar djg aga idkkaigaoajg gknjrohr (dj xnkwa pa idpa idkkaigask p’akkaskr). hw n kais pa jdozkasv ydjjaskr, pdjg wn oapnhwwa jnghdjnwa par rihajiar par onhjr ps xkarhpajg cdyjrdj aj 1966, ag wa xkhv lfdgd aj 1985. n wn bhj pa rn qha, hw rdsbbka pa wn onwnpha p’nwtyahoak, ia msh wa idjpshg pnjr sja onhrdj pa kaxdr ps onrrniysraggr. hw f paiapa wa 24 baqkhak 2001, n w’nua pa 84 njr.""" def count(texte): ordre_txt = {} order = "" texte.lower() alfb = list(string.ascii_lowercase) for i in range(len(alfb)): ordre_txt[alfb[i]] = texte.count(alfb[i]) ordre_txt = sorted(ordre_txt.items(), key = lambda x: x[1], reverse = True) for elt in ordre_txt: order += elt[0] return order def trad2(texte): ordre_fr = 'esaitnruolhdcgmpvfqbjxzykw' ordre_txt = count(texte) for i in range(26): texte.replace(ordre_txt[i], ordre_fr[i]) return texte print(trad2(texte))
str.lower() Return a copy of the string with all the cased characters converted to lowercase. So use texte = texte.lower() instead of texte.lower() at the 3rd line in def count(texte):. Apply str.translate(table) in def trad2(texte): e.g. as follows: def trad2(texte): ordre_fr = 'esaitnruolhdcgmpvfqbjxzykw' ordre_txt = count(texte) tr_table = str.maketrans(ordre_txt, ordre_fr) return texte.translate(tr_table) Note the str.maketrans() static method (returns a translation table usable for str.translate())…If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y.
how to create groups from string? [duplicate]
This question already has answers here: How do I split a list into equally-sized chunks? (66 answers) Closed 2 years ago. I have string and I will do split for this string and then I will get 320 elements. I need to create 4 groups. Every group will be with 100 elements and the last group must be with 20 last elements. And the last step is that all groups must be string and not list. how can I do that? I can do that if I know how many elements I have: s_l = 'AA AAL AAOI ACLS ADT ADTX ADVM AEL AIG ALEC ALLY ALT AMCX ANGI APA APDN APLS APPS APRN AQUA ARMK ARNC ARVN ATNM ATOM ATRA ATSG AVCT AVT AX AXDX BCLI BE BEAM BJRI BKE BKU BLDR BLNK BMRA BOOT BXS BYD CAKE CALX CAPR CARG CARR CARV CATM CC CCL CELH CEQP CFG CHEF CHRS CIT CLDX CLR CLSK CNK CNST CODX COLB COOP CPE CRS CTVA CUK CVET CVI CVM CYTK DAL DBX DCP DDS DEI DISCA DISCK DK DNB DRNA DVAX DXC ECOM EIGR ELAN ELF ELY ENVA EQ EQT EXEL FE FHI FIXX FL FLWS FMCI FORM FOX FOXA FRTA FUN GBX GIII GM GNMK GOCO GPRE GRAF GRPN GRWG GTHX GWB HALO HCC HCSG HEAR HFC HGV HIBB HMSY HOG HOME HP HSC HTH HWC IMUX IMVT INO INOV INSG INSM INT IOVA IRDM ITCI JELD JWN KMT KODK KPTI KSS KTB KTOS KURA LAKE LB LCA LL LPI LPRO LSCC LYFT MAXR MBOT MCRB MCS MD MDP MGM MGNX MIC MLHR MOS MRSN MTOR MXL MYGN NCLH NCR NK NKTR NLS NMIH NOVA NTLA NTNX NUAN NVST NXTC ODP OFC OKE OMER OMF OMI ONEM OSPN OSUR OXY OZK PACW PD PDCE PDCO PEAK PGNY PLAY PLCE PLT PLUG PPBI PRPL PRTS PRVB PS PSNL PSTX PSXP PTGX PVAC RCUS REAL REZI RKT RMBL RPAY RRGB RRR RVLV RVP RXN SANM SAVE SBGI SC SCPL SEAS SEM SFIX SFM SGMS SGRY SHLL SHOO SHYF SIX SKX SLQT SMCI SNAP SNDX SNV SONO SPAQ SPCE SPR SPWH SPWR SRG SRNE SSNT SSSS STOR SUM SUN SUPN SVMK SWBI SYF SYRS TBIO TCDA TCF TCRR TDC TEX TFFP TGTX THC TMHC TRGP TRIP TSE TUP TVTY UBX UCBI UCTT UFS UNFI UONE UPWK URBN USFD VCRA VERI VIAC VIRT VIVO VREX VSLR VSTO VXRT WAFD WBS WFC WHD WIFI WKHS WORK WORX WRK WRTC WW WWW WYND XEC XENT XPER XRX YELP ZGNX ZUMZ ZYXI' split_s_l = s_l.split(" ") part_1 = ' '.join(split_s_l[:100]) part_2 = ' '.join(split_s_l[100:200]) part_3 = ' '.join(split_s_l[200:300]) part_4 = ' '.join(split_s_l[300:]) for part in (part_1, part_2, part_3, part_4): print(part) but I don't know how to do that If I have many elements in list.
For a variable number of items, you can loop using: sep = ' ' num = 100 split_s_l = s_l.split(sep) for i in range(0, len(split_s_l), num): part = sep.join(split_s_l[i : i+num]) print(part) Bear in mind that for the last slice in the example case ([300:400]) it does not matter that there are only 320 elements -- just the last 20 items will be included (no error).
Something like this? def break_up(s, nwords, separator): words = s.split() return [separator.join(words[n:n+nwords]) for n in range(0, len(words), nwords)] print(break_up('a b c d e f g h', 3, ' ')) Result: ['a b c', 'd e f', 'g h'] Of course, you might call as print(break_up(s_l, 100, ' '))
Below s_l = 'AA AAL AAOI ACLS ADT ADTX ADVM AEL AIG ALEC ALLY ALT AMCX ANGI APA APDN APLS APPS APRN AQUA ARMK ARNC ARVN ATNM ATOM ATRA ATSG AVCT AVT AX AXDX BCLI BE BEAM BJRI BKE BKU BLDR BLNK BMRA BOOT BXS BYD CAKE CALX CAPR CARG CARR CARV CATM CC CCL CELH CEQP CFG CHEF CHRS CIT CLDX CLR CLSK CNK CNST CODX COLB COOP CPE CRS CTVA CUK CVET CVI CVM CYTK DAL DBX DCP DDS DEI DISCA DISCK DK DNB DRNA DVAX DXC ECOM EIGR ELAN ELF ELY ENVA EQ EQT EXEL FE FHI FIXX FL FLWS FMCI FORM FOX FOXA FRTA FUN GBX GIII GM GNMK GOCO GPRE GRAF GRPN GRWG GTHX GWB HALO HCC HCSG HEAR HFC HGV HIBB HMSY HOG HOME HP HSC HTH HWC IMUX IMVT INO INOV INSG INSM INT IOVA IRDM ITCI JELD JWN KMT KODK KPTI KSS KTB KTOS KURA LAKE LB LCA LL LPI LPRO LSCC LYFT MAXR MBOT MCRB MCS MD MDP MGM MGNX MIC MLHR MOS MRSN MTOR MXL MYGN NCLH NCR NK NKTR NLS NMIH NOVA NTLA NTNX NUAN NVST NXTC ODP OFC OKE OMER OMF OMI ONEM OSPN OSUR OXY OZK PACW PD PDCE PDCO PEAK PGNY PLAY PLCE PLT PLUG PPBI PRPL PRTS PRVB PS PSNL PSTX PSXP PTGX PVAC RCUS REAL REZI RKT RMBL RPAY RRGB RRR RVLV RVP RXN SANM SAVE SBGI SC SCPL SEAS SEM SFIX SFM SGMS SGRY SHLL SHOO SHYF SIX SKX SLQT SMCI SNAP SNDX SNV SONO SPAQ SPCE SPR SPWH SPWR SRG SRNE SSNT SSSS STOR SUM SUN SUPN SVMK SWBI SYF SYRS TBIO TCDA TCF TCRR TDC TEX TFFP TGTX THC TMHC TRGP TRIP TSE TUP TVTY UBX UCBI UCTT UFS UNFI UONE UPWK URBN USFD VCRA VERI VIAC VIRT VIVO VREX VSLR VSTO VXRT WAFD WBS WFC WHD WIFI WKHS WORK WORX WRK WRTC WW WWW WYND XEC XENT XPER XRX YELP ZGNX ZUMZ ZYXI' words= s_l.split(" ") num_of_100_groups = int(len(words) / 100) groups = [] for i in range(0,num_of_100_groups): groups.append(words[i * 100 : (i+1) * 100]) groups.append(words[num_of_100_groups * 100:]) for sub_group in groups: print(' '.join(sub_group))
Python Classes and Object assignment
I need to write a program that does the following: First, find the County that has the highest turnout, i.e. the highest percentage of the population who voted, using the objects’ population and voters attributes Then, return a tuple containing the name of the County with the highest turnout and the percentage of the population who voted, in that order; the percentage should be represented as a number between 0 and 1. I took a crack at it, but am getting the following error: Error on line 19: allegheny = County("allegheny", 1000490, 645469) TypeError: object() takes no parameters Here is what I've done so far. Thank you so much for your help. class County: def __innit__(self, innit_name, innit_population, innit_voters) : self.name = innit_name self.population = innit_population self.voters = innit_voters def highest_turnout(data) : highest_turnout = data[0] for County in data: if (county.voters / county.population) > (highest_turnout.voters / highest_turnout.population): highest_turnout = county return highest_turnout # your program will be evaluated using these objects # it is okay to change/remove these lines but your program # will be evaluated using these as inputs allegheny = County("allegheny", 1000490, 645469) philadelphia = County("philadelphia", 1134081, 539069) montgomery = County("montgomery", 568952, 399591) lancaster = County("lancaster", 345367, 230278) delaware = County("delaware", 414031, 284538) chester = County("chester", 319919, 230823) bucks = County("bucks", 444149, 319816) data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks] result = highest_turnout(data) # do not change this line! print(result) # prints the output of the function # do not remove this line!
def __innit__(self, innit_name, innit_population, innit_voters) : You mispelled __init__
How to know if a request is fulfilled on python?
I making a request to download some data on python from Copernicus website. The thing is that I want to know when the request is fulfilled and when the download is finished. Is is solid enough to work with 2 flags(request_finished and download_finished)? import cdsapi c = cdsapi.Client() latitude = 43.1 # North, South longitude = -1.5 # West , East #str(latitude)+'/'+str(longitude)+'/'+str(latitude)+'/'+str(longitude) r = c.retrieve( 'reanalysis-era5-single-levels', { 'product_type':'reanalysis', 'variable':[ '100m_u_component_of_wind','100m_v_component_of_wind','10m_u_component_of_wind','10m_v_component_of_wind','2m_temperature', 'surface_pressure' ], 'area' : str(latitude)+'/'+str(longitude)+'/'+str(latitude)+'/'+str(longitude), # North, West, South, East. Default: global 'year':'2018', 'grid':'0.1/0.1', # Latitude/longitude grid in degrees: east-west (longitude) and north-south resolution (latitude). Default: reduced Gaussian grid 'month':'01', 'day':[ '01','02','03', '04','05','06', '07','08','09', '10','11','12', '13','14','15', '16','17','18', '19','20','21', '22','23','24', '25','26','27', '28','29','30', '31' ], 'time':[ '00:00','01:00','02:00', '03:00','04:00','05:00', '06:00','07:00','08:00', '09:00','10:00','11:00', '12:00','13:00','14:00', '15:00','16:00','17:00', '18:00','19:00','20:00', '21:00','22:00','23:00' ], 'format':'netcdf' } ) request_finished = 1 r.download('download_grid_reduction_one_month_point_limit.nc') download_finished = 1
Python voter turnout assignment - class and object
I need to write a code to turn out the name of the County which: (i) has the highest voter turnout and (ii) percentage of population voted. Can you help me because I'm so confused. Here is what I have done: class County: def __init__(self, init_name, init_population, init_voters) : self.population = init_population self.voters = init_voters allegheny = County("allegheny", 1000490, 645469) philadelphia = County("philadelphia", 1134081, 539069) montgomery = County("montgomery", 568952, 399591) lancaster = County("lancaster", 345367, 230278) delaware = County("delaware", 414031, 284538) chester = County("chester", 319919, 230823) bucks = County("bucks", 444149, 319816) data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks] def highest_turnout(self): highest = self[0] highest_voters = self[0].voters for county in data: if county.voters > highest_voters: highest = county result = highest_turnout(self) print(result)
Summarizing suggestions from comments, the highest_turnout function needs to return the highest otherwise after the function finishes the highest value is lost. Then instead of passing in self to highest_turnout pass in data: class County: def __init__(self, init_name, init_population, init_voters): self.name = init_name self.population = init_population self.voters = init_voters allegheny = County("allegheny", 1000490, 645469) philadelphia = County("philadelphia", 1134081, 539069) montgomery = County("montgomery", 568952, 399591) lancaster = County("lancaster", 345367, 230278) delaware = County("delaware", 414031, 284538) chester = County("chester", 319919, 230823) bucks = County("bucks", 444149, 319816) data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks] def highest_voter_turnout(data): '''iterate over county objects comparing county.voters values; returns county object with max voters attribute''' highest_voters = data[0] for county in data: if county.voters > highest_voters.voters: highest_voters = county return highest_voters result_highest_voter_turnout = highest_voter_turnout(data) print(result_highest_voter_turnout.name) So far, this will return and display the name of the "County which: (i) has the highest voter turnout" (i.e. allegheny). A similar function can now be created to compute the county with the highest "(ii) percentage of population voted" (one method also mentioned in comments).