Add function PrintMap() in Go

This commit is contained in:
machangxin 2022-12-16 10:55:28 +08:00
parent e432f0b987
commit 26ad485dd2
3 changed files with 13 additions and 8 deletions

View File

@ -7,6 +7,8 @@ package chapter_hashing
import ( import (
"fmt" "fmt"
"testing" "testing"
. "github.com/krahets/hello-algo/pkg"
) )
func TestHashmap(t *testing.T) { func TestHashmap(t *testing.T) {
@ -21,9 +23,7 @@ func TestHashmap(t *testing.T) {
mapp[13276] = "小法" mapp[13276] = "小法"
mapp[10583] = "小鸭" mapp[10583] = "小鸭"
fmt.Println("\n添加完成后哈希表为\nKey -> Value") fmt.Println("\n添加完成后哈希表为\nKey -> Value")
for key, value := range mapp { PrintMap(mapp)
fmt.Printf("%d -> %s\n", key, value)
}
/* 查询操作 */ /* 查询操作 */
// 向哈希表输入键 key ,得到值 value // 向哈希表输入键 key ,得到值 value
@ -34,9 +34,7 @@ func TestHashmap(t *testing.T) {
// 在哈希表中删除键值对 (key, value) // 在哈希表中删除键值对 (key, value)
delete(mapp, 10583) delete(mapp, 10583)
fmt.Println("\n删除 10583 后,哈希表为\nKey -> Value") fmt.Println("\n删除 10583 后,哈希表为\nKey -> Value")
for key, value := range mapp { PrintMap(mapp)
fmt.Printf("%d -> %s\n", key, value)
}
/* 遍历哈希表 */ /* 遍历哈希表 */
// 遍历键值对 key->value // 遍历键值对 key->value

View File

@ -1,6 +1,6 @@
// File: print_utils.go // File: print_utils.go
// Created Time: 2022-12-03 // Created Time: 2022-12-03
// Author: Reanon (793584285@qq.com), Krahets (krahets@163.com) // Author: Reanon (793584285@qq.com), Krahets (krahets@163.com), msk397 (machangxinq@gmail.com)
package pkg package pkg
@ -96,3 +96,10 @@ func showTrunk(t *trunk) {
showTrunk(t.prev) showTrunk(t.prev)
fmt.Print(t.str) fmt.Print(t.str)
} }
// PrintHashMap Print a hash map
func PrintMap(m map[int]string) {
for key, value := range m {
fmt.Printf("%d -> %s\n", key, value)
}
}

View File

@ -39,7 +39,7 @@ class ArrayHashMap:
""" 删除操作 """ """ 删除操作 """
def remove(self, key): def remove(self, key):
index = self.hashFunc(key) index = self.hashFunc(key)
# 置为空字符,代表删除 # 置为None,代表删除
self.bucket[index] = None self.bucket[index] = None
""" 获取所有键值对 """ """ 获取所有键值对 """