字典和集合:源代码

本文深入探讨了Python中字典和集合的实现,特别是通过二叉排序树的角度。从关联类的基础概念开始,详细讲解了二分检索的原理,然后介绍了如何构建二叉排序树字典类。进一步讨论了最佳二叉排序树和平衡二叉排序树,以优化查找效率,为理解字典和集合底层工作原理提供了深入见解。
摘要由CSDN通过智能技术生成

目录

1. 关联类

2. 二分检索

3. 二叉排序树字典类

4. 最佳二叉排序树

5. 平衡二叉排序树


1. 关联类

""" class Assoc 
"""

class Assoc:
    def __init__(self, key, value):
        self.key = key
        self.value = value

    def __lt__(self, other):
        return self.key < other.key

    def __le__(self, other):
        return self.key < other.key or self.key == other.key

    def __str__(self):
        return "Assoc({0},{1})".format(self.key, self.value)
    
if __name__ == '__main__':
    a1 = Assoc(1,2)
    print(str(a1))
    pass

2. 二分检索

""" Dictionary and searching 
"""

from Assoc import Assoc
from random import randint

# Suppose lst is a list of Assoc object,
# where e.key and e.value give their key and value respectively
def bisearch(lst, key):
    low, high = 0, len(lst)-1
    while low <= high: # There are elements in the interval
        mid = (low + high)//2
        if key == lst[mid].key:
            return lst[mid].value
        if key < lst[mid].key:
            high = mid - 1 # continue in the lower half part
        else:
            low = mid + 1  # continue in the higher half part

# A simple digit-str/general-str hash function
def int_str_hash(sn): 
    c = 0
    for c in sn:
        h = (h*10 + int(c)*31) % 65521
    return h

class LSet: # A part of a simple set class
    def __init__(self, elems = []):
        self.elems = []
        for x in elems:
            if x not in self.elems:
                self.elems.append(x)

    def includes(self, e):
        return e in self.elems
        
if __name__ == '__main__':

    lst1 = [Assoc(randint(1, 30), i) for i in range(16)]
    lst1.sort()
    print(list(map(str, lst1)))
    for i in range(1, 30, 3):
        ind = bisearch(lst1, i)
        print("Search", i, "in the list and get:", ind)

    pass
        
    

3. 二叉排序树字典类

""" Dictionary and searching 
"""

from BiTree1 import BiTNode, print_BiTNodes
from SStack import *
from Assoc import Assoc

def bt_search(btree, key):
    bt = btree
    while bt is not None:
        entry = bt.data
        if key < entry.key:
            bt = bt.left
        elif key > entry.key:
            bt = bt.right
        else: return entry.value
    return None

class DictBTree:
    def __init__(self):
        self._root = None

    def is_empty(self):
        return self._root == None

    def preorder(self):
        t, s = self._root, SStack()
        while t is not None or not s.is_empty():
            while t is not None: 
                s.push
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值