Kaggle competition: Hash Code Archive - Drone Delivery
models = {'lr':lr_model,
'rf':rf_model,
'et':et_model,
'svm': svm_model,
'knn': knn_model,
'nb': nb_model,
'stack': stacked_model,
'vote':voting_model}<save_to_csv>
init_notebook_mode(connected=True)
 layout=go.Layout(paper_bgcolor='rgba(255,255,2555,0.5)', plot_bgcolor='rgba(250,250,250,0.8)', autosize=True)
 fig = go.Figure(layout=layout)
 templated_fig = pio.to_templated(fig)
 pio.templates['my_template'] = templated_fig.layout.template
pio.templates.default = 'my_template'
for i in models.keys() :
m = models[i].fit(X,y)
 y_pred = m.predict(test_X)
 prediction = pd.read_csv('.. /input/titanic/gender_submission.csv')
 prediction['Survived'] = y_pred
prediction.set_index('PassengerId')
 prediction.to_csv('submission-'+i+'.csv',index = False )<load_from_csv>
distance = lambda x1, y1, x2, y2:np.sqrt(np.abs(x1-x2)**2 + np.abs(y1-y2)**2 )
traindf = pd.read_csv('.. /input/titanic/train.csv' ).set_index('PassengerId')
 testdf = pd.read_csv('.. /input/titanic/test.csv' ).set_index('PassengerId')
 df = pd.concat([traindf, testdf], axis=0, sort=False)
 df['Title'] = df.Name.str.split(',' ).str[1].str.split('.' ).str[0].str.strip()
df['IsWomanOrBoy'] =(( df.Title == 'Master')|(df.Sex == 'female'))
df['LastName'] = df.Name.str.split(',' ).str[0]
family = df.groupby(df.LastName ).Survived
df['WomanOrBoyCount'] = family.transform(lambda s: s[df.IsWomanOrBoy].fillna(0 ).count())
 df['WomanOrBoyCount'] = df.mask(df.IsWomanOrBoy, df.WomanOrBoyCount - 1, axis=0)
 df['FamilySurvivedCount'] = family.transform(lambda s: s[df.IsWomanOrBoy].fillna(0 ).sum())
 df['FamilySurvivedCount'] = df.mask(df.IsWomanOrBoy, df.FamilySurvivedCount - df.Survived.fillna(0), axis=0)
 df['WomanOrBoySurvived'] = df.FamilySurvivedCount / df.WomanOrBoyCount.replace(0, np.nan)
 df['Alone'] =(df.WomanOrBoyCount == 0)
 train_y = df.Survived.loc[traindf.index]
df = pd.concat([df.WomanOrBoySurvived.fillna(0), df.Alone, df.Sex.replace({'male': 0, 'female': 1})], axis=1)
 test_x = df.loc[testdf.index]<feature_engineering>
files = ['.. /input/hashcode-drone-delivery/busy_day.in']
file_name = files[0]
with open(file_name)as file:
lines = file.read().splitlines()
line_list = [[int(n)for n in ll.split() ] for ll in lines]
test_x['Survived'] =(((test_x.WomanOrBoySurvived <= 0.238)&(test_x.Sex > 0.5)&(test_x.Alone > 0.5)) | \ 
(( test_x.WomanOrBoySurvived > 0.238)& \
~(( test_x.WomanOrBoySurvived > 0.55)&(test_x.WomanOrBoySurvived <= 0.633))))<save_to_csv>
order_startline = 2*(n_warehouses+1)+2
print(end_wh, order_startline)
 assert order_startline == end_wh
n_order = line_list[end_wh][0]
print("There is : ", n_order, " orders")
 order_delivery = []
order_n_items = []
order_quantity_items = []
print(3*(n_order)+(order_startline+1))
end_order = 3*(n_order)+(order_startline+1)
 for i in np.arange(order_startline+1, 3*(n_order)+(order_startline+1), 3):
order_delivery.append(line_list[i])
 order_n_items.append(line_list[i+1][0])
 order_quantity_items.append(line_list[i+2])
 end_o = i+3
print(len(order_quantity_items))
assert n_order == len(order_n_items)
 assert n_order == len(order_delivery)
 assert n_order == len(order_quantity_items)
 assert order_n_items[32] == len(order_quantity_items[32] )
pd.DataFrame({'Survived': test_x['Survived'].astype(int)}, \
index=testdf.index ).reset_index().to_csv('survived.csv', index=False )<set_options>
warnings.filterwarnings("ignore" )<load_from_csv>
d_wh = {
"warehouse" : [i for i in range(0, n_warehouses)],
"x" : [i[0] for i in warehouses],
"y" : [i[1] for i in warehouses],
}
for i in range(n_products):
p_id = 'prod_'+str(i)
 d_wh[p_id] = []
for j in range(n_warehouses):
for i in range(n_products):
p_id = 'prod_'+str(i)
 d_wh[p_id].append(wh_stocks[j][i])
 df_wh = pd.DataFrame(d_wh)
 df_wh.head()
traindf = pd.read_csv('.. /input/titanic/train.csv' ).set_index('PassengerId')
 testdf = pd.read_csv('.. /input/titanic/test.csv' ).set_index('PassengerId')
 df = pd.concat([traindf, testdf], axis=0, sort=False )<feature_engineering>
d_order = {
"order" : [i for i in range(0, n_order)],
"items" : order_n_items,
"total_weight" : [0]*n_order,
"x": [order[0] for order in order_delivery],
"y" : [order[1] for order in order_delivery],
}
for i in range(n_products):
p_id = 'prod_'+str(i)
 d_order[p_id] = [0]*n_order
for j in range(0, n_warehouses):
d_order["wh_"+str(j)] = [0]*n_order
d_order["dist_"+str(j)] = [0]*n_order
for k in range(n_order):
w = 0
for i in order_quantity_items[k]:
p_id = 'prod_'+str(i)
 d_order[p_id][k] += 1
w += product_weight[i]
for j in range(0, n_warehouses):
if df_wh[p_id][j] > 0:
d_order["wh_"+str(j)][k] += 1
else:
d_order["wh_"+str(j)][k] += 0
for j in range(0, n_warehouses):
d_order["dist_"+str(j)][k] = distance(d_order['x'][k], d_order['y'][k],
df_wh['x'][j], df_wh['y'][j])
 d_order["total_weight"][k] += w
df_order = pd.DataFrame(d_order)
 df_order['nearest_wh'] = df_order[['dist_'+str(i)for i in range(0, n_warehouses)]].T.idxmin().apply(lambda x: x.split('_')[1])
 df_order.head()
df['Title'] = df.Name.str.split(',' ).str[1].str.split('.' ).str[0].str.strip()
df['IsWomanOrBoy'] =(( df.Title == 'Master')|(df.Sex == 'female'))
df['LastName'] = df.Name.str.split(',' ).str[0]
family = df.groupby(df.LastName ).Survived
df['WomanOrBoyCount'] = family.transform(lambda s: s[df.IsWomanOrBoy].fillna(0 ).count())
 df['WomanOrBoyCount'] = df.mask(df.IsWomanOrBoy, df.WomanOrBoyCount - 1, axis=0)
 df['FamilySurvivedCount'] = family.transform(lambda s: s[df.IsWomanOrBoy].fillna(0 ).sum())
 df['FamilySurvivedCount'] = df.mask(df.IsWomanOrBoy, df.FamilySurvivedCount - df.Survived.fillna(0), axis=0)
 df['WomanOrBoySurvived'] = df.FamilySurvivedCount / df.WomanOrBoyCount.replace(0, np.nan)
 df['Alone'] =(df.WomanOrBoyCount == 0 )<prepare_x_and_y>
n = 1150
order_quantity_items[n].sort()
order_quantity_items[n]
for p in order_quantity_items[n]:
assert int(df_order[df_order.order == n]['prod_'+str(p)])> 0
train_y = df.Survived.loc[traindf.index]
data = pd.concat([df.WomanOrBoySurvived.fillna(0), df.Alone, \
df.Sex.replace({'male': 0, 'female': 1})], axis=1)
 train_x, test_x = data.loc[traindf.index], data.loc[testdf.index]
train_x.head(5 )<train_on_grid>
%%time
for i in range(0, 10):
print(df_order[['order', 'items', 'wh_'+str(i), 'dist_'+str(i), 'nearest_wh']].query("nearest_wh == "+str(i)+" and wh_"+str(i)+" == items" ).shape )
parameters = {'max_depth' : np.arange(2, 5, dtype=int),
'min_samples_leaf' : np.arange(2, 5, dtype=int)}
classifier = DecisionTreeClassifier(random_state=1000)
 model = GridSearchCV(estimator=classifier, param_grid=parameters, scoring='accuracy', cv=2, n_jobs=-1)
 model.fit(train_x, train_y)
 best_parameters = model.best_params_
print(best_parameters )<train_model>
%%time
count = 0
for i in range(0, 10):
n = df_order[['order', 'items', 'wh_'+str(i), 'dist_'+str(i), 'nearest_wh']].query("wh_"+str(i)+" == items" ).shape[0]
print('Number of order which could be supplid by warehouse '+str(i)+' only: ',n,' / '+str(n_order))
count += n
print("
By assigning orders to warehouses we could supply ", count, ' / '+str(n_order), '
' )
model=DecisionTreeClassifier(max_depth = best_parameters['max_depth'],
random_state = 1000)
 model.fit(train_x, train_y )<save_to_csv>
! pip install pulp
dot_data = export_graphviz(model, out_file=None, feature_names=train_x.columns, class_names=['0', '1'],
filled=True, rounded=False,special_characters=True, precision=3)
 graph = graphviz.Source(dot_data)
 graph<predict_on_test>
stock = [[0]*n_products]*n_warehouses
for wh in range(n_warehouses):
for prod in range(n_products):
stock[wh][prod] = wh_stocks[wh][prod]
stock = np.array(stock)
 demand = np.array([[0]*n_order]*n_products)
 for order in range(n_order):
for prod in order_quantity_items[order]:
demand[prod][order] += 1
demand = np.array(demand)
 x = [[[LpVariable("x_"+str(k)+"_"+str(i)+"_"+str(j), 0, min(1, demand[k][i]), LpInteger)
 for j in range(n_warehouses)]
for i in range(n_order)]
for k in range(n_products)]
cols0 = ['dist_'+str(j)for j in range(n_warehouses)]
dist = np.array(df_order[cols0] ).astype('float32' )
y_pred = model.predict(test_x ).astype(int)
 print('Mean =', y_pred.mean() , ' Std =', y_pred.std() )<data_type_conversions>
stock = [[0]*n_products]*n_warehouses
for wh in range(n_warehouses):
for prod in range(n_products):
stock[wh][prod] += wh_stocks[wh][prod]
stock = np.array(stock )
test_x['Survived'] =(((test_x.WomanOrBoySurvived <= 0.238)&(test_x.Sex > 0.5)&(test_x.Alone > 0.5)) | \ 
(( test_x.WomanOrBoySurvived > 0.238)& \
~(( test_x.WomanOrBoySurvived > 0.55)&(test_x.WomanOrBoySurvived <= 0.633))))
y_pred = test_x['Survived'].astype(int)
 print('Mean =', y_pred.mean() , ' Std =', y_pred.std() )<save_to_csv>
%%time
prob = LpProblem("assign_product_to_order", LpMinimize)
 prob += lpSum(dist[i][j] * x[k][i][j] for k in range(n_products)for i in range(n_order)for j in range(n_warehouses)) , "obj"
for k in range(n_products):
prob += lpSum(x[k][i][j] for i in range(n_order)for j in range(n_warehouses)) <= lpSum(stock[j][k] for j in range(n_warehouses)) , "Stock cst"+str(k)
 for i in range(n_order):
for k in range(n_products):
prob += lpSum(x[k][i][j] for j in range(n_warehouses)) == demand[k][i], "demand cst"+str(k)+"_"+str(i)
 prob.writeLP("ass_order_item_prob.lp")
 print('ok' )
pd.DataFrame({'Survived': y_pred}, index=testdf.index ).reset_index().to_csv('submission.csv', index=False )<load_from_csv>
%%time
prob.solve()
print("Status:", LpStatus[prob.status])
 print("objective=", value(prob.objective))
train_data = pd.read_csv("/kaggle/input/titanic/train.csv")
 train_data.head()<load_from_csv>
%%time
z = np.array([[0]*n_warehouses]*n_order ).astype('int32')
 df_assign = pd.DataFrame(columns = ['warehouse', 'order', 'product_id', 'quantity', 'total_weight'])
 for k in range(n_products):
for i in range(n_order):
for j in range(n_warehouses):
if x[k][i][j].varValue > 0:
z[i][j] = 1
df_assign = df_assign.append({
'warehouse': j,
'order': i,
'product_id': k,
'quantity' : int(x[k][i][j].varValue),
'total_weight': int(x[k][i][j].varValue)* product_weight[k]
}, ignore_index=True)
 print(df_assign.shape)
 order = 10
tmp = df_assign.sort_values('warehouse' ).query('order == '+str(order))
prods = tmp.product_id
for p in order_quantity_items[10]:
assert np.isin(p, prods)
test_data = pd.read_csv("/kaggle/input/titanic/test.csv")
 test_data.head()<define_variables>
%%time
for i in range(n_order):
if sum(z[i])> 1:
print("more than 1 wh ",i, ", sum = ", sum(z[i]))
if sum(z[i])== 0:
print("0 wh", i)
 for j in range(n_warehouses):
df_order['assign_'+str(j)] = z.T[j]
women = train_data.loc[train_data.Sex == 'female']["Survived"]
rate_women = sum(women)/len(women)
 print("% of women who survived:", rate_women )<define_variables>
wh = 1
n_drone_per_wh = n_drones//10
df = df_assign.query("warehouse == "+str(wh)).sort_values('order')
 order_list = list(df.order)
 print(len(order_list))
df.head()
men = train_data.loc[train_data.Sex == 'male']["Survived"]
rate_men = sum(men)/len(men)
 print("% of men who survived:", rate_men )<save_to_csv>
%%time
demands = df['total_weight'].tolist() + [0]
products = df['product_id'].tolist() +[0]
len(demands)
 X = np.array(d_order['x'])
 Y = np.array(d_order['y'])
 ref_dist = np.array([[ distance(X[i], Y[i], X[j], Y[j])for j in range(n_order)] for i in range(n_order)])
 tmp = pd.DataFrame(np.array([[ref_dist[i][j] for j in order_list] for i in order_list]))
tmp[tmp.shape[0]] = pd.Series([df_order.iloc[i]['dist_'+str(wh)] for i in order_list]+[0])
 tmp = tmp.append(pd.Series([df_order.iloc[i]['dist_'+str(wh)] for i in order_list]+[0]), ignore_index=True)
 distance_ = np.array(tmp)
 print(distance_.shape)
 distance_
y = train_data["Survived"]
features = ["Pclass", "Sex", "SibSp", "Parch", "Age", "Embarked"]
X = pd.get_dummies(train_data[features])
 X_test = pd.get_dummies(test_data[features])
 X.Age.fillna(X.Age.mean() , inplace=True)
 X_test.Age.fillna(X_test.Age.mean() , inplace=True)
 model = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=1)
 model.fit(X, y)
 predictions = model.predict(X_test)
 output = pd.DataFrame({'PassengerId': test_data.PassengerId, 'Survived': predictions})
 output.to_csv('my_submission.csv', index=False)
 print("Your submission was successfully saved!" )<feature_engineering>
turns = 30
n_drone_per_wh = 10 * turns
<prepare_x_and_y>
turns = [30, 30, 30, 100, 100, 100, 40, 40, 30]
def create_data_model(wh=0):

 n_drone_per_wh = n_drones//10
df = df_assign.query("warehouse == "+str(wh)).sort_values('order')
 order_list = list(df.order)
 demands = df['total_weight'].tolist() +[0]
products = df['product_id'].tolist() +[0]
len(demands)
 X = np.array(d_order['x'])
 Y = np.array(d_order['y'])
 ref_dist = np.array([[ distance(X[i], Y[i], X[j], Y[j])for j in range(n_order)] for i in range(n_order)])
 tmp = pd.DataFrame(np.array([[ref_dist[i][j] for j in order_list] for i in order_list]))
tmp[tmp.shape[0]] = pd.Series([df_order.iloc[i]['dist_'+str(wh)] for i in order_list]+[0])
 tmp = tmp.append(pd.Series([df_order.iloc[i]['dist_'+str(wh)] for i in order_list]+[0]), ignore_index=True)
 distance_ = np.array(tmp)
 turns = [30, 30, 30, 2000, 400, 100, 100, 100, 100,100]
turns = turns[wh]
n_drone_per_wh = 10 * turns
data = {}
data['distance_matrix'] = distance_
data['demands'] = demands
data['vehicle_capacities'] = [payload]*n_drone_per_wh
data['num_vehicles'] = n_drone_per_wh
data['depot'] = tmp.shape[0]-1
data['products'] = products
data['order_list'] = order_list+[0]
data['time_matrix'] = distance_
data['vehicle_load_time'] = 1
data['vehicle_unload_time'] = 1
data['time_windows'] = [(0, T)]*len(demands)
 data['depot_capacity'] = n_drone_per_wh
return data
<feature_engineering>
%%time
a = create_data_model(3 )
<prepare_x_and_y>
def print_solution(data, manager, routing, solution):

 dropped_nodes = 'Dropped nodes:'
for node in range(routing.Size()):
if routing.IsStart(node)or routing.IsEnd(node):
continue
if solution.Value(routing.NextVar(node)) == node:
dropped_nodes += ' {}'.format(manager.IndexToNode(node))
print(len(dropped_nodes.split(' ')))
 print(dropped_nodes)
 total_distance = 0
total_load = 0
count = 0
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
 plan_output = 'Route for vehicle {}:
'.format(vehicle_id)
 route_distance = 0
route_load = 0
while not routing.IsEnd(index):
node_index = manager.IndexToNode(index)
 route_load += data['demands'][node_index]
plan_output += ' {0} Load({1})-> '.format(node_index, route_load)
 previous_index = index
index = solution.Value(routing.NextVar(index))
route_distance += routing.GetArcCostForVehicle(
 previous_index, index, vehicle_id)
 plan_output += ' {0} Load({1})
 '.format(manager.IndexToNode(index),
route_load)
 plan_output += 'Distance of the route: {}m
'.format(route_distance)
 plan_output += 'Load of the route: {}
'.format(route_load)
 if route_load > 0:
print(plan_output)
 count += 1
total_distance += route_distance
total_load += route_load
print('Total needed rounds : {} '.format(count//10))
print('Total distance of all routes: {}m'.format(total_distance))
print('Total load of all routes: {}'.format(total_load))
<import_modules>
def main(wh=0, print_solution=False):

 data = create_data_model(wh)
 manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']), data['num_vehicles'], data['depot'])
 routing = pywrapcp.RoutingModel(manager)
 def distance_callback(from_index, to_index):

 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)
 routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
 def demand_callback(from_index):

 from_node = manager.IndexToNode(from_index)
 return data['demands'][from_node]
demand_callback_index = routing.RegisterUnaryTransitCallback(
 demand_callback)
 routing.AddDimensionWithVehicleCapacity(
 demand_callback_index,
0,
data['vehicle_capacities'],
True,
'Capacity')
 penalty = 15000
for node in range(1, len(data['distance_matrix'])) :
routing.AddDisjunction([manager.NodeToIndex(node)], penalty)
 search_parameters = pywrapcp.DefaultRoutingSearchParameters()
search_parameters.first_solution_strategy =(routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
 search_parameters.local_search_metaheuristic =(routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
 search_parameters.log_search = True
search_parameters.time_limit.FromSeconds(1200)
 solution = routing.SolveWithParameters(search_parameters)
 print("Solver status: ", routing.status())
 if print_solution:
if solution:
print_solution(data, manager, routing, solution)
 return(data, manager, routing, solution )
<import_modules>
def main_df(wh=0): 
(data, manager, routing, solution)= main(wh, False)
 dropped_nodes = 'Dropped nodes:'
for node in range(routing.Size()):
if routing.IsStart(node)or routing.IsEnd(node):
continue
if solution.Value(routing.NextVar(node)) == node:
dropped_nodes += ' {}'.format(manager.IndexToNode(node))
print(len(dropped_nodes.split(' ')))
 print(dropped_nodes)
 dropped_nodes = 'Dropped nodes:'
for node in range(routing.Size()):
if routing.IsStart(node)or routing.IsEnd(node):
continue
if solution.Value(routing.NextVar(node)) == node:
dropped_nodes += ' {}'.format(manager.IndexToNode(node))
print(len(dropped_nodes.split(' ')))
 print(dropped_nodes)
 total_distance = 0
total_load = 0
count = 0
df_route = pd.DataFrame(columns=['warehouse', 'route', 'order', 'product', 'load'])
 for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
 plan_output = 'Route for vehicle {}:
'.format(vehicle_id)
 route_distance = 0
route_load = 0
while not routing.IsEnd(index):
node_index = manager.IndexToNode(index)
 route_load += data['demands'][node_index]
prod = data['products'][node_index]
plan_output += ' {0} Load({1} - product: {2})-> '.format(data['order_list'][node_index], route_load, prod)
 tmp_data = {'warehouse': wh,
'route': vehicle_id,
'product': prod,
'order': data['order_list'][node_index],
'load': route_load }
df_route = df_route.append(tmp_data,
ignore_index=True)
 previous_index = index
index = solution.Value(routing.NextVar(index))
route_distance += routing.GetArcCostForVehicle(previous_index, index, vehicle_id)
 '.format(node_index, route_load, prod)
 plan_output += 'Distance of the route: {}m
'.format(route_distance)
 plan_output += 'Load of the route: {}
'.format(route_load)
 if route_load > 0:
print(plan_output)
 count += 1
total_distance += route_distance
total_load += route_load
print('Total needed rounds : {} '.format(count//10))
print('Total distance of all routes: {}m'.format(total_distance))
print('Total load of all routes: {}'.format(total_load))
return df_route
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler, StandardScaler, LabelBinarizer, LabelEncoder
from sklearn.feature_selection import RFECV
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, roc_curve, auc<load_from_csv>
%%time
warehouses = [0, 1, 2, 5, 6, 7, 8, 9 ]
tmp_list = []
df_route = pd.DataFrame()
for wh in warehouses:
print("
Warehouse : ", wh)
 tmp = main_df(wh)
 tmp_list.append(tmp )
train = pd.read_csv('.. /input/train.csv')
 train.head()<load_from_csv>
df_route = pd.concat(tmp_list)
 order = 121
tmp = df_route.query('order == '+str(order))
for prod in order_quantity_items[order]:
assert np.isin(prod, tmp['product'])
 df_route.shape
test = pd.read_csv('.. /input/test.csv')
 test.head()<count_values>
df_route = df_route.query('load != 0')
 print("instruction for warehouse 1 : ", df_route.query("warehouse == "+str(1)).shape[0] )
print(train['Embarked'].value_counts())
 most_freq = train['Embarked'].value_counts().index[0]
train['Embarked'].fillna(most_freq, inplace=True )<feature_engineering>
df_route['qty'] = [1]*df_route.shape[0]
df_route.groupby(['warehouse', 'route', 'product'])['qty'].sum().reset_index().query('qty > 1 and product != 0' )
train["Title"] = train["Name"].str.extract('([A-Za-z]+)\.',expand=False)
 test["Title"] = test["Name"].str.extract('([A-Za-z]+)\.',expand=False)
 for i in [train, test]:
i['Title'] = i['Title'].replace('Mr', 'Mr')
 i['Title'] = i['Title'].replace(( 'Mme', 'Ms'), 'Mrs')
 i['Title'] = i['Title'].replace('Mlle', 'Miss')
 i['Title'] = i['Title'].replace(( 'Capt', 'Col', 'Major', 'Dr','Rev'), 'Officer')
 i['Title'] = i['Title'].replace(( 'Jonkheer', 'Don', 'Sir', 'Countess','Dona', 'Lady'), 'Royalty' )<feature_engineering>
%%time
def submit(df_route):
instruction = ""
time = [T]*n_drones
fleet_per_wh = n_drones//n_warehouses
instruction = []
for wh in warehouses :
print("warehouse : ", wh)
 routes = set(df_route.query('warehouse == '+str(wh)).route)
 for turn in range(len(routes)) :
instruction_d = []
instruction_l = []
drone = fleet_per_wh*wh + turn%fleet_per_wh
r = turn
route = df_route.query("route == "+str(r)+" and warehouse == "+str(wh))
prec =(int(df_wh['x'][wh]), int(df_wh['y'][wh]))
for line in range(route.shape[0]):
if line > 0:
product = route.iloc[line]['product']
qty = 1
order = route.iloc[line]['order']
instruction_l.append("{0} L {1} {2} {3}
".format(drone, wh, product, qty))
time[drone] -= 1
instruction_d.append("{0} D {1} {2} {3}
".format(drone, order, product, qty))
time[drone] -= distance(prec[0], prec[1], df_order['x'][order], df_order['y'][order])
 prec =(df_order['x'][order], df_order['y'][order])
 time[drone] -= distance(prec[0], prec[1], df_wh['x'][wh], df_wh['y'][wh])
 instruction += instruction_l + instruction_d
print(time)
 return instruction
<data_type_conversions><EOS> 
file1 = open("submission.csv","w")
 file1.write(str(len(instruction)) +'
')
 for line in instruction:
file1.write(line)
 file1.close()