SlideShare a Scribd company logo
1 of 3
Download to read offline
__author__ = 'Davisr'
import csv
import math
import cx_Oracle
v_Schema = 'xxxxxxx'
v_Password = 'xxxxxxxx'
v_ODBCConnection = '@xxxxxx'
v_AgtZipCodeArray = []
v_AgentDetailArray = []
v_ZipArray = []
v_ZipLatitude = []
v_ZipLongitude = []
v_ZipCity = []
v_ZipState = []
v_ZipSets = []
v_ZipSetsLess31 = []
#variable that determines the max distance between zip codes
v_MaxDistance = 30
counter = 1
v_OracleSignIn = v_Schema+'/'+v_Password+v_ODBCConnection
v_Connection = cx_Oracle.connect(v_OracleSignIn)
v_Cursor = v_Connection.cursor()
v_InputPath = "C:UsersdavisrDownloadsZipCodes"
v_InputFile = v_InputPath+"free-zipcode-database-
Primary.csv"
#file from the following URL: http://federalgovernmentzipcodes.us/
v_OutputPath = "P:AllshareTravis"
# v_OutputPath = "C:UsersdavisrDesktop"
v_OutputFile = v_OutputPath+"agent_zip_code_file.csv"
v_SQLStatementCreateTbl8 = ("CREATE TABLE
"+v_Schema+".tbl_08_SalesAgents_ZipCodes AS "
"SELECT t041.empl_svc_num , "
"t041.agt_stat_cd , "
"t041.agt_ctrct_cd , "
"t041.home_city , "
"t041.home_st , "
"t041.home_zip_cd "
"FROM mim.omimt041_agt t041 "
"WHERE t041.agt_ctrct_cd IN
('10','14') "
"AND t041.agt_stat_cd = 'A' ")
v_SQLStatementDropTbl8 = ("DROP TABLE
"+v_Schema+".tbl_08_SalesAgents_ZipCodes " )
v_SQLStatementSelectTbl8_1 = ("SELECT DISTINCT(tbl_8.home_zip_cd) AS
agt_zip_cd "
"FROM
"+v_Schema+".tbl_08_SalesAgents_ZipCodes tbl_8 ")
v_SQLStatementSelectTbl8_2 =("SELECT tbl_8. empl_svc_num , "
"tbl_8.home_zip_cd "
"FROM
"+v_Schema+".tbl_08_SalesAgents_ZipCodes tbl_8 " )
def calculate_distance(lat1, lon1, lat2, lon2):
if (lat1 == lat2) and (lon1 == lon2):
return 0
else:
if (not lat1) or (not lon1) or (not lat2) or (not lon2):
return -1
lat1 = float(lat1) * math.pi/180
lon1 = float(lon1) * math.pi/180
lat2 = float(lat2) * math.pi/180
lon2 = float(lon2) * math.pi/180
return 3959.0 * math.acos(math.sin(lat1)*math.sin(lat2) +
math.cos(lat1)*math.cos(lat2)*math.cos(lon2-lon1))
#Above function changed from the following URL:
http://iamtgc.com/geocoding-with-python/ with the exception of the
#first if statement to check for the same zip code
try:
v_Cursor.execute(v_SQLStatementCreateTbl8)
v_Connection.commit()
except:
v_Cursor.execute(v_SQLStatementDropTbl8)
v_Cursor.execute(v_SQLStatementCreateTbl8)
v_Connection.commit()
v_Cursor.execute(v_SQLStatementSelectTbl8_1)
v_Connection.commit()
#get the Agt Data into an array
for results in v_Cursor.fetchall():
v_AgtZipCodeArray.append(results[0])
print v_AgtZipCodeArray
v_AllZipsFile = csv.DictReader(open(v_InputFile))
#read Zip code file into an array
for row in v_AllZipsFile:
v_ZipArray.append(row["Zipcode"])
v_ZipLatitude.append(row["Lat"])
v_ZipLongitude.append(row["Long"])
v_ZipCity.append(row["City"])
v_ZipState.append(row["State"])
#get the longitude and latitude of a zip code by looping through zip code
file
for i in range(len(v_AgtZipCodeArray)):
for j in range(len(v_ZipArray)):
if v_AgtZipCodeArray[i] == v_ZipArray[j]:
#Agent zip code [0], Agent Zip City [1], Agent Zip State [2],
Agent Latitude [3] , Agent Longitude [4]
v_ZipSets.append([v_AgtZipCodeArray[i] , v_ZipCity[j],
v_ZipState[j], v_ZipLatitude[j], v_ZipLongitude[j] ])
#get a list of zip codes from MIMs that are not in the zip code file.
for i in range(len(v_AgtZipCodeArray)):
InArray = v_AgtZipCodeArray[i] not in v_ZipArray
if InArray == True :
print v_AgtZipCodeArray[i]
#get the agent zipcodes and get the distances and if the distance is 30
miles or less then append to an array
# with detail
for i in range(len(v_ZipSets)):
for j in range(len(v_ZipArray)):
v_ZipDistance =
calculate_distance(v_ZipSets[i][3],v_ZipSets[i][4], v_ZipLatitude[j],
v_ZipLongitude[j])
#write zip code data for those zip codes that are equal to or
less than MaxDistance
#write zip code data for those zip codes are greater than -1
which is returned if one of the values is
#invalid in the function
if v_ZipDistance > -1 and v_ZipDistance <= v_MaxDistance :
#Agt zip code [0], Agt Zip City [1] , Agt Zip State [2], Agt
Latitude [3], Agt Longitude [4]
#Destination City, Destination State, Destination Zip Code,
Air Miles Distance
v_ZipSetsLess31.append([v_ZipSets[i][0], v_ZipSets[i][1],
v_ZipSets[i][2], v_ZipSets[i][3],
v_ZipSets[i][4], v_ZipCity[j],
v_ZipState[j], v_ZipArray[j],
v_ZipLatitude[j],
v_ZipLongitude[j],float(v_ZipDistance)] )
print v_ZipSetsLess31
v_Cursor.execute(v_SQLStatementSelectTbl8_2)
v_Connection.commit()
#get the employee service number for each origin zip to add
for results in v_Cursor.fetchall():
#employee service number [0], home zip code [1]
v_AgentDetailArray.append([results[0], results[1]])
#put the employee service number and add if the agent zip code matches
the origin zip code
for i in range(len(v_ZipSetsLess31)):
for j in range(len(v_AgentDetailArray)):
if v_ZipSetsLess31[i][0] == v_AgentDetailArray[j][1]:
v_ZipSetsLess31[i].append(v_AgentDetailArray[j][0])
v_OPF = open(v_OutputFile,'w')
for i in range(len(v_ZipSetsLess31)):
if counter == 1:
header = (["employee_service_number", "origin_zip_code",
"destination_zip_code", "distance"+"n" ])
v_OPF.write(','.join(header))
record = (v_ZipSetsLess31[i][11], v_ZipSetsLess31[i][0],
v_ZipSetsLess31[i][7],str(v_ZipSetsLess31[i][10])+'n')
counter = counter+1
v_OPF.write(','.join(record))
else:
record = (v_ZipSetsLess31[i][11], v_ZipSetsLess31[i][0],
v_ZipSetsLess31[i][7],str(v_ZipSetsLess31[i][10])+'n')
v_OPF.write(','.join(record))
v_OPF.close()

More Related Content

What's hot

cocos2d 事例編 HungryMasterの実装から
cocos2d 事例編 HungryMasterの実装からcocos2d 事例編 HungryMasterの実装から
cocos2d 事例編 HungryMasterの実装からYuichi Higuchi
 
Nonlinear analysis of frame with hinge by hinge method in c programming
Nonlinear analysis of frame with hinge by hinge method in c programmingNonlinear analysis of frame with hinge by hinge method in c programming
Nonlinear analysis of frame with hinge by hinge method in c programmingSalar Delavar Qashqai
 
Nonlinear 2nd order analysis of 2 d fixed support beam with plastic hinge con...
Nonlinear 2nd order analysis of 2 d fixed support beam with plastic hinge con...Nonlinear 2nd order analysis of 2 d fixed support beam with plastic hinge con...
Nonlinear 2nd order analysis of 2 d fixed support beam with plastic hinge con...Salar Delavar Qashqai
 
Multi dimensional array
Multi dimensional arrayMulti dimensional array
Multi dimensional arrayRajendran
 
IGraph a tool to analyze your network
IGraph a tool to analyze your networkIGraph a tool to analyze your network
IGraph a tool to analyze your networkPushpendra Tiwari
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...ssuserd6b1fd
 

What's hot (20)

cocos2d 事例編 HungryMasterの実装から
cocos2d 事例編 HungryMasterの実装からcocos2d 事例編 HungryMasterの実装から
cocos2d 事例編 HungryMasterの実装から
 
Nonlinear analysis of frame with hinge by hinge method in c programming
Nonlinear analysis of frame with hinge by hinge method in c programmingNonlinear analysis of frame with hinge by hinge method in c programming
Nonlinear analysis of frame with hinge by hinge method in c programming
 
Ch 4
Ch 4Ch 4
Ch 4
 
Array notes
Array notesArray notes
Array notes
 
constructors
constructorsconstructors
constructors
 
Nonlinear 2nd order analysis of 2 d fixed support beam with plastic hinge con...
Nonlinear 2nd order analysis of 2 d fixed support beam with plastic hinge con...Nonlinear 2nd order analysis of 2 d fixed support beam with plastic hinge con...
Nonlinear 2nd order analysis of 2 d fixed support beam with plastic hinge con...
 
Multi dimensional array
Multi dimensional arrayMulti dimensional array
Multi dimensional array
 
IGraph a tool to analyze your network
IGraph a tool to analyze your networkIGraph a tool to analyze your network
IGraph a tool to analyze your network
 
Statistics.cpp
Statistics.cppStatistics.cpp
Statistics.cpp
 
C++ L06-Pointers
C++ L06-PointersC++ L06-Pointers
C++ L06-Pointers
 
C++ examples &revisions
C++ examples &revisionsC++ examples &revisions
C++ examples &revisions
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
C++ L09-Classes Part2
C++ L09-Classes Part2C++ L09-Classes Part2
C++ L09-Classes Part2
 
Arrays
ArraysArrays
Arrays
 
Array
ArrayArray
Array
 
C++ L11-Polymorphism
C++ L11-PolymorphismC++ L11-Polymorphism
C++ L11-Polymorphism
 
C++ TUTORIAL 4
C++ TUTORIAL 4C++ TUTORIAL 4
C++ TUTORIAL 4
 
C++ L04-Array+String
C++ L04-Array+StringC++ L04-Array+String
C++ L04-Array+String
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
 
Arrays
ArraysArrays
Arrays
 

Viewers also liked

Pubblicità Elettronautica Cosentino
Pubblicità Elettronautica CosentinoPubblicità Elettronautica Cosentino
Pubblicità Elettronautica Cosentinodariloja
 
Presentation 2 1
Presentation 2 1Presentation 2 1
Presentation 2 1Franbri45
 
sandip Resume (1) (1).docx 1
sandip Resume (1) (1).docx 1sandip Resume (1) (1).docx 1
sandip Resume (1) (1).docx 1Sandip Atugade
 
Test powerpoint
Test powerpointTest powerpoint
Test powerpointskunz55
 
8c21da14 1c9c-44ee-8e24-9a1ddd64ca82-150211062639-conversion-gate02
8c21da14 1c9c-44ee-8e24-9a1ddd64ca82-150211062639-conversion-gate028c21da14 1c9c-44ee-8e24-9a1ddd64ca82-150211062639-conversion-gate02
8c21da14 1c9c-44ee-8e24-9a1ddd64ca82-150211062639-conversion-gate02Anand Nandani
 
Seattle Interactive Conference 2014 Brochure
Seattle Interactive Conference 2014 BrochureSeattle Interactive Conference 2014 Brochure
Seattle Interactive Conference 2014 Brochureweaveuser
 
Voyage of Independence II ARC August 2011 bremerhaven to baltimore
Voyage of Independence II ARC August 2011 bremerhaven to baltimoreVoyage of Independence II ARC August 2011 bremerhaven to baltimore
Voyage of Independence II ARC August 2011 bremerhaven to baltimoreThe Diesel Driver
 
Stephanie Cairns, Member, Alberta Climate Leadership Panel
Stephanie Cairns, Member, Alberta Climate Leadership PanelStephanie Cairns, Member, Alberta Climate Leadership Panel
Stephanie Cairns, Member, Alberta Climate Leadership PanelSustainable Prosperity
 
Silverman powerpoint assignment
Silverman powerpoint assignmentSilverman powerpoint assignment
Silverman powerpoint assignmentSarah Silverman
 

Viewers also liked (11)

Pubblicità Elettronautica Cosentino
Pubblicità Elettronautica CosentinoPubblicità Elettronautica Cosentino
Pubblicità Elettronautica Cosentino
 
Presentation 2 1
Presentation 2 1Presentation 2 1
Presentation 2 1
 
sandip Resume (1) (1).docx 1
sandip Resume (1) (1).docx 1sandip Resume (1) (1).docx 1
sandip Resume (1) (1).docx 1
 
Test powerpoint
Test powerpointTest powerpoint
Test powerpoint
 
8c21da14 1c9c-44ee-8e24-9a1ddd64ca82-150211062639-conversion-gate02
8c21da14 1c9c-44ee-8e24-9a1ddd64ca82-150211062639-conversion-gate028c21da14 1c9c-44ee-8e24-9a1ddd64ca82-150211062639-conversion-gate02
8c21da14 1c9c-44ee-8e24-9a1ddd64ca82-150211062639-conversion-gate02
 
Seattle Interactive Conference 2014 Brochure
Seattle Interactive Conference 2014 BrochureSeattle Interactive Conference 2014 Brochure
Seattle Interactive Conference 2014 Brochure
 
Fs moskau zimmer
Fs moskau zimmerFs moskau zimmer
Fs moskau zimmer
 
Dave Sawyer, Enviro Economics
Dave Sawyer, Enviro EconomicsDave Sawyer, Enviro Economics
Dave Sawyer, Enviro Economics
 
Voyage of Independence II ARC August 2011 bremerhaven to baltimore
Voyage of Independence II ARC August 2011 bremerhaven to baltimoreVoyage of Independence II ARC August 2011 bremerhaven to baltimore
Voyage of Independence II ARC August 2011 bremerhaven to baltimore
 
Stephanie Cairns, Member, Alberta Climate Leadership Panel
Stephanie Cairns, Member, Alberta Climate Leadership PanelStephanie Cairns, Member, Alberta Climate Leadership Panel
Stephanie Cairns, Member, Alberta Climate Leadership Panel
 
Silverman powerpoint assignment
Silverman powerpoint assignmentSilverman powerpoint assignment
Silverman powerpoint assignment
 

Similar to Zip Code Distance

i need help fixing my program so that the user can input both uper and.pdf
i need help fixing my program so that the user can input both uper and.pdfi need help fixing my program so that the user can input both uper and.pdf
i need help fixing my program so that the user can input both uper and.pdfshreeaadithyaacellso
 
Need to make a flowchart for the following codepublic static voi.pdf
Need to make a flowchart for the following codepublic static voi.pdfNeed to make a flowchart for the following codepublic static voi.pdf
Need to make a flowchart for the following codepublic static voi.pdffaktdeal
 
C++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerC++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerAndrey Karpov
 
Keygenning using the Z3 SMT Solver
Keygenning using the Z3 SMT SolverKeygenning using the Z3 SMT Solver
Keygenning using the Z3 SMT Solverextremecoders
 
Cs pritical file
Cs pritical fileCs pritical file
Cs pritical fileMitul Patel
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2Mouna Guru
 
#include bitsstdc++.h#include unistd.h#include GLglew.h.pdf
#include bitsstdc++.h#include unistd.h#include GLglew.h.pdf#include bitsstdc++.h#include unistd.h#include GLglew.h.pdf
#include bitsstdc++.h#include unistd.h#include GLglew.h.pdfcomputersmartdwarka
 
Please finish the codes in Graph.h class.#################### Vert.pdf
Please finish the codes in Graph.h class.#################### Vert.pdfPlease finish the codes in Graph.h class.#################### Vert.pdf
Please finish the codes in Graph.h class.#################### Vert.pdfpetercoiffeur18
 
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)Make Mannan
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings imtiazalijoono
 
A scrupulous code review - 15 bugs in C++ code
A scrupulous code review - 15 bugs in C++ codeA scrupulous code review - 15 bugs in C++ code
A scrupulous code review - 15 bugs in C++ codePVS-Studio LLC
 
Computer Networks Lab File
Computer Networks Lab FileComputer Networks Lab File
Computer Networks Lab FileKandarp Tiwari
 
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...AntareepMajumder
 
Chapter 8 c solution
Chapter 8 c solutionChapter 8 c solution
Chapter 8 c solutionAzhar Javed
 
ParallelProgrammingBasics_v2.pdf
ParallelProgrammingBasics_v2.pdfParallelProgrammingBasics_v2.pdf
ParallelProgrammingBasics_v2.pdfChen-Hung Hu
 

Similar to Zip Code Distance (20)

i need help fixing my program so that the user can input both uper and.pdf
i need help fixing my program so that the user can input both uper and.pdfi need help fixing my program so that the user can input both uper and.pdf
i need help fixing my program so that the user can input both uper and.pdf
 
Need to make a flowchart for the following codepublic static voi.pdf
Need to make a flowchart for the following codepublic static voi.pdfNeed to make a flowchart for the following codepublic static voi.pdf
Need to make a flowchart for the following codepublic static voi.pdf
 
R Language
R LanguageR Language
R Language
 
C++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerC++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical Reviewer
 
Keygenning using the Z3 SMT Solver
Keygenning using the Z3 SMT SolverKeygenning using the Z3 SMT Solver
Keygenning using the Z3 SMT Solver
 
Cs pritical file
Cs pritical fileCs pritical file
Cs pritical file
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2
 
#include bitsstdc++.h#include unistd.h#include GLglew.h.pdf
#include bitsstdc++.h#include unistd.h#include GLglew.h.pdf#include bitsstdc++.h#include unistd.h#include GLglew.h.pdf
#include bitsstdc++.h#include unistd.h#include GLglew.h.pdf
 
Please finish the codes in Graph.h class.#################### Vert.pdf
Please finish the codes in Graph.h class.#################### Vert.pdfPlease finish the codes in Graph.h class.#################### Vert.pdf
Please finish the codes in Graph.h class.#################### Vert.pdf
 
R Programming Intro
R Programming IntroR Programming Intro
R Programming Intro
 
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
 
2D array
2D array2D array
2D array
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
 
A scrupulous code review - 15 bugs in C++ code
A scrupulous code review - 15 bugs in C++ codeA scrupulous code review - 15 bugs in C++ code
A scrupulous code review - 15 bugs in C++ code
 
Dvst
DvstDvst
Dvst
 
Java arrays
Java    arraysJava    arrays
Java arrays
 
Computer Networks Lab File
Computer Networks Lab FileComputer Networks Lab File
Computer Networks Lab File
 
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
 
Chapter 8 c solution
Chapter 8 c solutionChapter 8 c solution
Chapter 8 c solution
 
ParallelProgrammingBasics_v2.pdf
ParallelProgrammingBasics_v2.pdfParallelProgrammingBasics_v2.pdf
ParallelProgrammingBasics_v2.pdf
 

Zip Code Distance

  • 1. __author__ = 'Davisr' import csv import math import cx_Oracle v_Schema = 'xxxxxxx' v_Password = 'xxxxxxxx' v_ODBCConnection = '@xxxxxx' v_AgtZipCodeArray = [] v_AgentDetailArray = [] v_ZipArray = [] v_ZipLatitude = [] v_ZipLongitude = [] v_ZipCity = [] v_ZipState = [] v_ZipSets = [] v_ZipSetsLess31 = [] #variable that determines the max distance between zip codes v_MaxDistance = 30 counter = 1 v_OracleSignIn = v_Schema+'/'+v_Password+v_ODBCConnection v_Connection = cx_Oracle.connect(v_OracleSignIn) v_Cursor = v_Connection.cursor() v_InputPath = "C:UsersdavisrDownloadsZipCodes" v_InputFile = v_InputPath+"free-zipcode-database- Primary.csv" #file from the following URL: http://federalgovernmentzipcodes.us/ v_OutputPath = "P:AllshareTravis" # v_OutputPath = "C:UsersdavisrDesktop" v_OutputFile = v_OutputPath+"agent_zip_code_file.csv" v_SQLStatementCreateTbl8 = ("CREATE TABLE "+v_Schema+".tbl_08_SalesAgents_ZipCodes AS " "SELECT t041.empl_svc_num , " "t041.agt_stat_cd , " "t041.agt_ctrct_cd , " "t041.home_city , " "t041.home_st , " "t041.home_zip_cd " "FROM mim.omimt041_agt t041 " "WHERE t041.agt_ctrct_cd IN ('10','14') " "AND t041.agt_stat_cd = 'A' ") v_SQLStatementDropTbl8 = ("DROP TABLE "+v_Schema+".tbl_08_SalesAgents_ZipCodes " ) v_SQLStatementSelectTbl8_1 = ("SELECT DISTINCT(tbl_8.home_zip_cd) AS agt_zip_cd " "FROM "+v_Schema+".tbl_08_SalesAgents_ZipCodes tbl_8 ") v_SQLStatementSelectTbl8_2 =("SELECT tbl_8. empl_svc_num , " "tbl_8.home_zip_cd " "FROM "+v_Schema+".tbl_08_SalesAgents_ZipCodes tbl_8 " ) def calculate_distance(lat1, lon1, lat2, lon2): if (lat1 == lat2) and (lon1 == lon2): return 0
  • 2. else: if (not lat1) or (not lon1) or (not lat2) or (not lon2): return -1 lat1 = float(lat1) * math.pi/180 lon1 = float(lon1) * math.pi/180 lat2 = float(lat2) * math.pi/180 lon2 = float(lon2) * math.pi/180 return 3959.0 * math.acos(math.sin(lat1)*math.sin(lat2) + math.cos(lat1)*math.cos(lat2)*math.cos(lon2-lon1)) #Above function changed from the following URL: http://iamtgc.com/geocoding-with-python/ with the exception of the #first if statement to check for the same zip code try: v_Cursor.execute(v_SQLStatementCreateTbl8) v_Connection.commit() except: v_Cursor.execute(v_SQLStatementDropTbl8) v_Cursor.execute(v_SQLStatementCreateTbl8) v_Connection.commit() v_Cursor.execute(v_SQLStatementSelectTbl8_1) v_Connection.commit() #get the Agt Data into an array for results in v_Cursor.fetchall(): v_AgtZipCodeArray.append(results[0]) print v_AgtZipCodeArray v_AllZipsFile = csv.DictReader(open(v_InputFile)) #read Zip code file into an array for row in v_AllZipsFile: v_ZipArray.append(row["Zipcode"]) v_ZipLatitude.append(row["Lat"]) v_ZipLongitude.append(row["Long"]) v_ZipCity.append(row["City"]) v_ZipState.append(row["State"]) #get the longitude and latitude of a zip code by looping through zip code file for i in range(len(v_AgtZipCodeArray)): for j in range(len(v_ZipArray)): if v_AgtZipCodeArray[i] == v_ZipArray[j]: #Agent zip code [0], Agent Zip City [1], Agent Zip State [2], Agent Latitude [3] , Agent Longitude [4] v_ZipSets.append([v_AgtZipCodeArray[i] , v_ZipCity[j], v_ZipState[j], v_ZipLatitude[j], v_ZipLongitude[j] ]) #get a list of zip codes from MIMs that are not in the zip code file. for i in range(len(v_AgtZipCodeArray)): InArray = v_AgtZipCodeArray[i] not in v_ZipArray if InArray == True : print v_AgtZipCodeArray[i] #get the agent zipcodes and get the distances and if the distance is 30 miles or less then append to an array # with detail for i in range(len(v_ZipSets)):
  • 3. for j in range(len(v_ZipArray)): v_ZipDistance = calculate_distance(v_ZipSets[i][3],v_ZipSets[i][4], v_ZipLatitude[j], v_ZipLongitude[j]) #write zip code data for those zip codes that are equal to or less than MaxDistance #write zip code data for those zip codes are greater than -1 which is returned if one of the values is #invalid in the function if v_ZipDistance > -1 and v_ZipDistance <= v_MaxDistance : #Agt zip code [0], Agt Zip City [1] , Agt Zip State [2], Agt Latitude [3], Agt Longitude [4] #Destination City, Destination State, Destination Zip Code, Air Miles Distance v_ZipSetsLess31.append([v_ZipSets[i][0], v_ZipSets[i][1], v_ZipSets[i][2], v_ZipSets[i][3], v_ZipSets[i][4], v_ZipCity[j], v_ZipState[j], v_ZipArray[j], v_ZipLatitude[j], v_ZipLongitude[j],float(v_ZipDistance)] ) print v_ZipSetsLess31 v_Cursor.execute(v_SQLStatementSelectTbl8_2) v_Connection.commit() #get the employee service number for each origin zip to add for results in v_Cursor.fetchall(): #employee service number [0], home zip code [1] v_AgentDetailArray.append([results[0], results[1]]) #put the employee service number and add if the agent zip code matches the origin zip code for i in range(len(v_ZipSetsLess31)): for j in range(len(v_AgentDetailArray)): if v_ZipSetsLess31[i][0] == v_AgentDetailArray[j][1]: v_ZipSetsLess31[i].append(v_AgentDetailArray[j][0]) v_OPF = open(v_OutputFile,'w') for i in range(len(v_ZipSetsLess31)): if counter == 1: header = (["employee_service_number", "origin_zip_code", "destination_zip_code", "distance"+"n" ]) v_OPF.write(','.join(header)) record = (v_ZipSetsLess31[i][11], v_ZipSetsLess31[i][0], v_ZipSetsLess31[i][7],str(v_ZipSetsLess31[i][10])+'n') counter = counter+1 v_OPF.write(','.join(record)) else: record = (v_ZipSetsLess31[i][11], v_ZipSetsLess31[i][0], v_ZipSetsLess31[i][7],str(v_ZipSetsLess31[i][10])+'n') v_OPF.write(','.join(record)) v_OPF.close()