目录
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