5

I'm learning a bit of python coding and I'm following this youtube video too to make some practice. Now here is what I'm running.

import urllib
import operator
from xml.etree.ElementTree import parse
import webbrowser
from showmap import showmap

def getbuses():
    u = urllib.urlopen('http://ctabustracker.com/bustime/map/getBusesForRoute.jsp?route=22')
    data = u.read()
    f = open('rt22.xml', 'wb')
    f.write(data)
    f.close()
    doc = parse('rt22.xml')
    running_buses = {}
    for bus in doc.findall('bus'):
        idbus = int(bus.findtext('id'))
        lat = float(bus.findtext('lat'))
        lon = float(bus.findtext('lon'))
        direction = str(bus.findtext('d'))
        running_buses[idbus] = {lat, lon, direction}
    return running_buses

def print_routes(running_buses):    
    print 'Running buses on route 22:\n'
    for b, (lat, lon, direction) in running_buses.items():
        print '  Bus number: {} \n     - Latitude: {} \n     - Longitude: {}\n     - Direction: {}'.format(b, lat, lon, direction)
    return

def breakline():
    print '____________________________________\n'
    return

def closest_bus():
    running_buses = getbuses()
    officelat, officelon = 41.980262, -87.668452
    diffs = []
    found = False
    print 'Office coordinates: lat {0} lon {1}'.format(officelat, officelon)
    for b, (lat, lon, direction) in running_buses.items():
        if lat > officelat:
            if direction.startswith('North'):
                diff = (officelat - lat) + (officelon - lon)
                diffs.append(tuple((abs(diff), b)))
                found = True
    if found == False:
        print 'No bus going north right now'
    else:
        closbus = min(diffs, key = operator.itemgetter(0))
    return closbus

def main():
    breakline()
    running_buses = getbuses()
    print_routes(running_buses)
    breakline()
    print 'Closest bus going north: {}'.format(closest_bus()[1])
    return

if __name__ == '__main__':
    main()

The strange thing is that for a few buses, the program somehow mixes longitude, latitude and direction for no apparent reason.

For example, this is what I've got right now:

root@kali:~/python_training/newtraining# python bussearch.py 
____________________________________

Running buses on route 22:

  Bus number: 1920 
     - Latitude: North West Bound 
     - Longitude: 41.9186187744
     - Direction: -87.6363869407
  Bus number: 1856 
     - Latitude: 41.8836083476 
     - Longitude: South Bound
     - Direction: -87.6310359701
  Bus number: 1764 
     - Latitude: South Bound 
     - Longitude: -87.6317800846
     - Direction: 41.9113892609
  Bus number: 1893 
     - Latitude: South Bound 
     - Longitude: 41.8746980631
     - Direction: -87.6310698311
  Bus number: 1882 
     - Latitude: 41.9857769012 
     - Longitude: -87.669216156
     - Direction: North Bound
  Bus number: 1911 
     - Latitude: 41.978255328 
     - Longitude: -87.6683738559
     - Direction: North Bound
  Bus number: 1400 
     - Latitude: -87.6738596316 
     - Longitude: 42.0089025851
     - Direction: North Bound
  Bus number: 1892 
     - Latitude: North West Bound 
     - Longitude: -87.6453846035
     - Direction: 41.933323362
  Bus number: 1914 
     - Latitude: -87.6671066284 
     - Longitude: South Bound
     - Direction: 41.9671321698
  Bus number: 1723 
     - Latitude: -87.6315689087 
     - Longitude: South Bound
     - Direction: 41.9017485594
  Bus number: 1885 
     - Latitude: South Bound 
     - Longitude: 41.9857135407
     - Direction: -87.6692754667    
____________________________________

Office coordinates: lat 41.980262 lon -87.668452
Traceback (most recent call last):
  File "bussearch.py", line 69, in <module>
    main()
  File "bussearch.py", line 65, in main
    print 'Closest bus going north: {}'.format(closest_bus()[1])
  File "bussearch.py", line 50, in closest_bus
    if direction.startswith('North'):
AttributeError: 'float' object has no attribute 'startswith'

I know the code is not so clean but I started coding in python since 3 days now and I'm learning. I'm not totally new to coding, and this doesn't make any sense to me... What am I doing wrong? Everything seemed to work fine before introducing direction. Any help?

4
  • 3
    Your problem is here "running_buses[idbus] = {lat, lon, direction}". You created a set, which has no guarantee of order Commented Jun 21, 2017 at 15:45
  • 3
    Here's how you debug python programs: You step through one line at a time in the interpretor using pdb after each line you check to make sure all the variables hold what you expect. As soon as something unexpected happens, you've found the bug. docs.python.org/2/library/pdb.html Commented Jun 21, 2017 at 15:45
  • @RPGillespie If he doesn't know the difference between a set and tuple, that won't help him fix the bug. Commented Jun 21, 2017 at 15:47
  • 1
    @Barmar Fixing the bug for him won't help him either (in the long run); otherwise he'll run back to SO anytime he encounters a bug. pdb will at least let him know which line is behaving unexpectedly rather than doing a code dump to SO which helps literally nobody but him. Commented Jun 21, 2017 at 15:49

1 Answer 1

6

In this line running_buses[idbus] = {lat, lon, direction} you are defining a set, which is an unordered collection. Thus, when you say for b, (lat, lon, direction) in running_buses.items(), you are assigning a lat or lon to the direction variable in some cases.

Change the first line to running_buses[idbus] = (lat, lon, direction) to use an (ordered) tuple instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh yeah, this is so obvious now! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.