开发者

why would spaces in a Python tuple matter?

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.


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']] 


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()]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜