~saurabhanandiit/gtg/exportFixed

« back to all changes in this revision

Viewing changes to GTG/tools/sorted_dict.py

Merge of my work on liblarch newbase and all the backends ported to liblarch
(which mainly means porting the datastore).
One failing test, will check it.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# -*- coding: utf-8 -*-
 
2
# pylint: disable-msg=W0201
 
3
# -----------------------------------------------------------------------------
 
4
# Getting Things Gnome! - a personal organizer for the GNOME desktop
 
5
# Copyright (c) 2010 - Luca Invernizzi
 
6
#
 
7
# This program is free software: you can redistribute it and/or modify it under
 
8
# the terms of the GNU General Public License as published by the Free Software
 
9
# Foundation, either version 3 of the License, or (at your option) any later
 
10
# version.
 
11
#
 
12
# This program is distributed in the hope that it will be useful, but WITHOUT
 
13
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 
14
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 
15
# details.
 
16
#
 
17
# You should have received a copy of the GNU General Public License along with
 
18
# this program.  If not, see <http://www.gnu.org/licenses/>.
 
19
# -----------------------------------------------------------------------------
 
20
 
 
21
import  bisect
 
22
 
 
23
 
 
24
 
 
25
class SortedDict(dict):
 
26
    '''
 
27
    Keeps a list of tuples sorted in the first tuple element.
 
28
    It's possible to delete a tuple just by giving an element and its position.
 
29
    The sorted element must be a Unicode string (lexicographical sorting)
 
30
    '''
 
31
 
 
32
 
 
33
    def __init__(self, key_position, sort_position, *initial_values):
 
34
        super(SortedDict, self).__init__()
 
35
        self.__key_position = key_position
 
36
        self.__sort_position = sort_position
 
37
        self.__sorted_list = []
 
38
        for value in  initial_values:
 
39
            self.sorted_insert(value)
 
40
 
 
41
    def sorted_insert(self, a_tuple):
 
42
        sort_elem = a_tuple[self.__sort_position].lower()
 
43
        position = bisect.bisect(self.__sorted_list, sort_elem)
 
44
        self.__sorted_list.insert(position, sort_elem)
 
45
        self[a_tuple[self.__key_position]]= a_tuple
 
46
        return position
 
47
 
 
48
    def pop_by_key(self, key):
 
49
        a_tuple = self[key]
 
50
        sort_elem = a_tuple[self.__sort_position].lower()
 
51
        self.__sorted_list.remove(sort_elem)
 
52
        return a_tuple
 
53
 
 
54
    def get_index(self, a_tuple):
 
55
        sort_elem = a_tuple[self.__sort_position]
 
56
        position = bisect.bisect(self.__sorted_list, sort_elem)
 
57
        if self.__sorted_list[position] == sort_elem:
 
58
            return position
 
59
        else:
 
60
            return None
 
61
 
 
62
 
 
63