comparing two lists

Ladislav Andel ladaan at iptel.org
Thu Aug 23 17:50:51 EDT 2007


Well, I know it's quite ugly what I did to the code, but any 
improvements are welcome.
Actually, it doesn't work as it should yet.
The items should stay the same as at the beginning.
I say in one sentence what I want to achieve:
Synchronized items with dblist.
It should remove hosts from items which are not dblist
or it should add a new host from dblist which is not in items.
I'm sorry I'm not very skilled programmer.

What O notations(algorithm complexity) I introduced to it?
I know made it much slower this way.


dblist = [{'id':1, 'host':'google.com','ip_address':'1.2.3.4'},
      {'id':3, 'host':'msn.com','ip_address':'11.3.2.3'},
      {'id':9, 'host':'yahoo.com','ip_address':'5.6.7.8'}]


class Item(object):
    def __init__(self, id, host, **discarded):
        self._tuple = (id, host)
    def __hash__(self):
        return hash(self._tuple)
    def __eq__(self, other):
        return self._tuple == other._tuple
    def __repr__(self):
        return "Item(id=%r, host=%r)" % self._tuple
   
def syncMemAndDBlist_1():
    for d in dblist:
        item = Item(**d)
        if item not in items:
            print "adding", item
            items.add(item)
        else:       
            print item, "already there"

def syncMemAndDBlist_2(a):
    while a > 0:
        for i in items:
            if i not in dblistitems:
                items.remove(i)
                break
        a -= 1
    if len(items) == 0:
        syncMemAndDBlist_1()
   
items = set([Item(1, "google.com"), Item(3, "yahoo.com"), Item(9, 
"msn.com")])

dblistitems = set()  
for d in dblist:
    dblistitems.add(Item(**d))

a = len(items)
b = len(dblistitems)

if a < b:
    syncMemAndDBlist_1()
else:
    syncMemAndDBlist_2(a)
   
print 'final items are' ,items




More information about the Python-list mailing list