Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't spot a bug in my python code

Tags:

python

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?

like image 974
AndTuf Avatar asked Jun 21 '17 15:06

AndTuf


People also ask

How do you identify the bugs within a code?

Using the git bisect command, you can perform a binary search through your code base until you find the commit where the bug was introduced. Looking at that diff should give you a fairly small amount of code to dig through. This is a fantastic technique when you are working in a new or unfamiliar code base.

Is there any bug in Python?

There are mainly 5 types of bugs in Python: Syntax errors: When you receive a syntax error message, it indicates that you typed something wrong. Indentation errors: Python uses indentation to understand where blocks of code start and end.

What tool is used to find bugs Python?

PyChecker is a static analysis tool that finds bugs in Python source code and warns about code complexity and style. You can get PyChecker from http://pychecker.sourceforge.net/.


1 Answers

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.

like image 85
jakevdp Avatar answered Oct 16 '22 17:10

jakevdp