Skip to content

Instantly share code, notes, and snippets.

@ms8r
Created January 22, 2017 20:49
Show Gist options
  • Save ms8r/63efe2f41128f05e300efc3f73a7693b to your computer and use it in GitHub Desktop.
Save ms8r/63efe2f41128f05e300efc3f73a7693b to your computer and use it in GitHub Desktop.
Build continuous PuD code ranges based on ZIP:distance mapping. Writes to stdout.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from bisect import bisect_left
import begin
@begin.start(auto_convert=True, short_args=False)
def main(airport: """3 letter airport code""",
infile: """input file with whitespace separted (code, dist) pairs""",
breaks: """whitespace separated string containing sorted list with
"more than" distance breaks""",
cutoff: """value up to which distances will be included in zone
def (will be ignored if 0)""" = 0):
"""
Build continuous PuD code ranges based on ZIP: distance mapping. Writes to
stdout.
"""
with open(infile, 'r') as fp:
code_dist = (line.strip().split() for line in fp)
code_dist = [(code, int(dist)) for code, dist in code_dist if
dist.isdecimal() and (cutoff == 0 or int(dist) <= cutoff)]
breaks = [int(b) for b in breaks.split()]
# first sort by distance to assign zones:
code_dist.sort(key=lambda k: k[1])
zones = (breaks[bisect_left(breaks, d) - 1] for _, d in code_dist)
code_zone = [(code, zone) for (code, _), zone in zip(code_dist, zones)]
# now sort by code to assemble continuous ranges with same zone:
code_zone.sort(key=lambda k: k[0])
code_from = code_zone[0][0]
for (current_code, current_zone), (prev_code, prev_zone) in zip(
code_zone[1:], code_zone[:-1]):
if current_zone == prev_zone:
continue
else:
print('{0}\t{1}\t{2}\t{3}'.format(airport, code_from, prev_code,
prev_zone))
code_from = current_code
print('{0}\t{1}\t{2}\t{3}'.format(airport, code_from, current_code,
current_zone))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment