Pregunta

I've been getting weird results and I finally noticed that my habit of putting spaces in a tuple is causing the problem. If you can reproduce this problem and tell me why it works this way, you would be saving what's left of my hair. Thanks!

jcomeau@intrepid:/tmp$ cat haversine.py
#!/usr/bin/python
def dms_to_float(degrees):
 d, m, s, compass = degrees
 d, m, s = int(d), float(m), float(s)
 float_degrees = d + (m / 60) + (s / 3600)
 float_degrees *= [1, -1][compass in ['S', 'W', 'Sw']]
 return float_degrees

jcomeau@intrepid:/tmp$ python
Python 2.6.7 (r267:88850, Jun 13 2011, 22:03:32) 
[GCC 4.6.1 20110608 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from haversine import *
>>> dms_to_float((111, 41, 0, 'SW'))
111.68333333333334
>>> dms_to_float((111,41,0,'Sw'))
-111.68333333333334

With spaces in the tuple, the answer is wrong. Without, the answer is correct.

¿Fue útil?

Solución

The spaces should make no difference. The difference is due to the case: SW vs Sw.

You don't check for SW here:

compass in ['S', 'W', 'Sw']] 

Perhaps change it to this:

compass.upper() in ['S', 'W', 'SW']] 

Otros consejos

Presuming that the "degrees" relate to degrees of latitude or longitude, I can't imagine why "SW" is treated as a viable option. Latitude is either N or S. Longitude is either E or W. Please explain.

Based on your sample of size 1, user input is not to be trusted. Consider checking the input, or at least ensuring that bogus input will cause an exception to be raised. You appear to like one-liners; try this:

float_degrees *= {'n': 1, 's': -1, 'e': 1, 'w': -1}[compass.strip().lower()]
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top