Programing Language: latitude-longitude-decimalize
Ian Kelly
ian.g.kelly at gmail.com
Tue Nov 29 18:49:18 EST 2011
On Tue, Nov 29, 2011 at 3:53 PM, Xah Lee <xahlee at gmail.com> wrote:
> fun programing exercise. Write a function “latitude-longitude-
> decimalize”.
>
> It should take a string like this: 「"37°26′36.42″N 06°15′14.28″W"」.
> The return value should be a pair of numbers, like this: 「[37.44345
> -6.25396]」.
>
> Feel free to use perl, python, ruby, lisp, etc. I'll post a emacs lisp
> solution in a couple of days.
For Python 3:
import re
def latitude_longitude_decimalize(string):
regex = r"""(\d+)\xb0(\d+)'([\d+.]+)"([NS])\s*(\d+)\xb0(\d+)'([\d+.]+)"([EW])"""
match = re.match(regex, string)
if not match:
raise ValueError("Invalid input string: {0:r}".format(string))
def decimalize(degrees, minutes, seconds, direction):
decimal = int(degrees) + int(minutes) / 60 + float(seconds) / 3600
if direction in 'SW':
decimal = -decimal
return decimal
latitude = decimalize(*match.groups()[:4])
longitude = decimalize(*match.groups()[4:8])
return latitude, longitude
More information about the Python-list
mailing list