数据结构英汉翻译小词典
时间: 2023-11-26 22:46:47 浏览: 178
这里提供两种实现数据结构英汉翻译小词典的方法:
方法一:哈希表和顺序查找
```python
# 定义一个字典,key为英文单词,value为中文翻译
dictionary = {'apple': '苹果', 'banana': '香蕉', 'cherry': '樱桃', 'orange': '橙子', 'pear': '梨子'}
# 定义一个函数,用于查找单词
def search_word(word):
count = 0 # 记录比较次数
if word in dictionary:
count += 1
return dictionary[word], count
else:
count += 1
return '未找到该单词', count
# 测试查找单词
result, count = search_word('apple')
print(result, count) # 输出:苹果 1
# 定义一个函数,用于插入单词
def insert_word(word, translation):
if word not in dictionary:
dictionary[word] = translation
return '插入成功'
else:
return '该单词已存在'
# 测试插入单词
result = insert_word('grape', '葡萄')
print(result) # 输出:插入成功
# 定义一个函数,用于删除单词
def delete_word(word):
if word in dictionary:
del dictionary[word]
return '删除成功'
else:
return '该单词不存在'
# 测试删除单词
result = delete_word('banana')
print(result) # 输出:删除成功
```
方法二:PAT树
```python
# 定义一个节点类
class Node:
def __init__(self, char):
self.char = char # 节点存储的字符
self.value = None # 节点存储的值
self.children = {} # 子节点
# 定义一个PAT树类
class PATTree:
def __init__(self):
self.root = Node('') # 根节点
# 定义一个函数,用于查找单词
def search_word(self, word):
count = 0 # 记录比较次数
node = self.root
for char in word:
count += 1
if char in node.children:
node = node.children[char]
else:
return '未找到该单词', count
if node.value:
return node.value, count
else:
return '未找到该单词', count
# 定义一个函数,用于插入单词
def insert_word(self, word, translation):
node = self.root
for char in word:
if char in node.children:
node = node.children[char]
else:
new_node = Node(char)
node.children[char] = new_node
node = new_node
node.value = translation
# 定义一个函数,用于删除单词
def delete_word(self, word):
node = self.root
for char in word:
if char in node.children:
node = node.children[char]
else:
return '该单词不存在'
if node.value:
node.value = None
return '删除成功'
else:
return '该单词不存在'
# 测试PAT树
tree = PATTree()
tree.insert_word('apple', '苹果')
tree.insert_word('banana', '香蕉')
tree.insert_word('cherry', '樱桃')
result, count = tree.search_word('apple')
print(result, count) # 输出:苹果 5
result = tree.delete_word('banana')
print(result) # 输出:删除成功
```
阅读全文