ich habe mehrere PLZ-Bereiche und möchte Überscheidungen finden und beseitigen
aus folgenden Bereichen: 0-10000,14900-15100, 11000-12000,15101, 14000-15000,11500-14500,28001
möchte ich folgendes Ergebnis: 0-10000,11000-15101,28001
Mein Ansatz ist bis jetzt folgender:
Code: Alles auswählen
import re
import string
zipcodeStr = "0-10000,14900-15100, 11000-12000,15101, 14000-15000,11500-14500,28001"
zipcodeStr = zipcodeStr.replace(" ", "")
zipcodeFields = [zipcode for zipcode in zipcodeStr.split(",") if zipcode]
zipcodesList = [0] * 100000
matchStr = re.compile("(\d+)\-(\d+)")
for zipcodeArea in zipcodeFields:
if zipcodeArea.find("-") > 0:
match = matchStr.match(zipcodeArea)
if match:
zipcodeFrom = int(match.group(1))
zipcodeTo = int(match.group(2))
if zipcodeFrom > zipcodeTo:
zipcodeFrom, zipcodeTo = zipcodeTo, zipcodeFrom
for i in range(zipcodeFrom, zipcodeTo + 1):
zipcodesList[i] = 1
else:
print "Wrong Zipcode Area %s" % zipcodeArea
else:
zipcodesList[int(zipcodeArea)] = 1
try:
zipcodesList[int(zipcodeArea)] = 1
except:
print "Wrong Zipcode %s" % zipcodeArea
zipcodeFields = []
zipcodeStart = None
zipcodeEnd = None
for i in range(len(zipcodesList)):
if zipcodesList[i] == 1:
if zipcodeStart is None:
zipcodeStart = i
else:
zipcodeEnd = i
else:
if zipcodeStart is not None:
if zipcodeEnd is not None:
zipcodeFields.append("%d-%d" % (zipcodeStart, zipcodeEnd))
else:
zipcodeFields.append("%d" % (zipcodeStart))
zipcodeStart = None
zipcodeEnd = None
zipcodeStr = string.join(zipcodeFields, ",")
print zipcodeStr
Mein Algorithmus ist etwas ineffizient, wenn Bereiche z.B. doppelt angegeben werden oder in ein Bereich zig andere Bereiche fallen. Ich muss auch den höchsten Index kennen, da es sonst zum IndexError kommt.
mfg
Twilo