/+junk/pygooglechart-py3k

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/%2Bjunk/pygooglechart-py3k

« back to all changes in this revision

Viewing changes to examples/helpers/country_code_helper.py

  • Committer: gak
  • Date: 2009-03-15 07:34:55 UTC
  • Revision ID: git-v1:2ce2bd2a423b1305ad2ad81c72b69c004fecec05
Added some example helpers for MapChart

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
class CountryCodes:
 
2
    '''
 
3
    This is just a helper to generate useful data files. It isn't directly used
 
4
    in these examples.
 
5
    '''
 
6
    
 
7
    def __init__(self):
 
8
        self.parse_codes_data()   
 
9
        
 
10
    def parse_codes_data(self):
 
11
        lines = open('iso3166-1-a2.txt', 'rb').read().split('\n')
 
12
        self.codes = dict([ a.split(' ', 1) for a in lines[:-1] ])
 
13
 
 
14
    def get_country_code_from_name(self, guess_name):
 
15
        best_score = 100
 
16
        best_code = None
 
17
        for code, name in self.codes.items():
 
18
            score = self.levenshtein(guess_name, name)
 
19
            if score < best_score:
 
20
                best_score = score
 
21
                best_code = code
 
22
        return best_code
 
23
 
 
24
    def levenshtein(self, a, b):
 
25
        "Calculates the Levenshtein distance between a and b."
 
26
        n, m = len(a), len(b)
 
27
        if n > m:
 
28
            # Make sure n <= m, to use O(min(n,m)) space
 
29
            a,b = b,a
 
30
            n,m = m,n
 
31
            
 
32
        current = range(n+1)
 
33
        for i in range(1,m+1):
 
34
            previous, current = current, [i]+[0]*n
 
35
            for j in range(1,n+1):
 
36
                add, delete = previous[j]+1, current[j-1]+1
 
37
                change = previous[j-1]
 
38
                if a[j-1] != b[i-1]:
 
39
                    change = change + 1
 
40
                current[j] = min(add, delete, change)
 
41
                
 
42
        return current[n]
 
43