Home Hash (Python)
Post
Cancel

Hash (Python)

Original Problem

Create a dataset. Achieve three functions:

  1. Insert: put one element into the dataset.
  2. Delete: delete all the corresponding elements from the dataset.
  3. Search: check the dataset to search for certain element. If it exists, return 1; if not, return 0.

The real purpose of this problem is asking you to create a hash table. If not, the time complexibility will become $O(n^2)$. You will receive “Time limitation exceeded”. If you use hash table, the time complexity will become $O(n)$.

My Solution

Source code is listed below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python3

'''
Hash table
Written by Polly Zhou

College:
	Tsinghua University, Tsien Excellence in Education Program (TEEP)
E-mail:
	pollyjoe2003@gmail.com
Solution:
	Create a hash table to reduce time complexibility

Special acknowledgement for Qiyang Sun:
	At first I didn't want to spend much time to learn hash, but she encouraged me to use hash.
	Without her insistance, I would have given up solving this problem.

Reminder:
	This is a simplified version of hash table.
	Hash function is quite simple, and I didn't put collision resolution here.
'''

# Hash table
class HashTable:
    def __init__(self) -> None:
        self.size = 50000
        self.slots = []
        for w in range(0, self.size):
            self.slots.append([])

    def put(self, data):
        hash_value = hashfunction(data, self.size)
        self.slots[hash_value].append(data)

    def search(self, element):
        search_key = hashfunction(element, self.size)
        if_have = False
        for k in self.slots[search_key]:
            if k == element:
                if_have = True
        if if_have:
            print(1)
        else:
            print(0)

    def delete(self, element):
        del_key = hashfunction(element, self.size)
        temp = self.slots[del_key][:]
        for u in self.slots[del_key]:
            if u == element:
                temp.remove(u)
        self.slots[del_key] = temp


# Hash function, here we use modulo arithmetic
def hashfunction(data, size):
    return data % size


if __name__ == '__main__':
    table = HashTable()
    try:
        times = int(input())
        for i in range(0, times):
            op, el = input().split()
            op = int(op)
            el = int(el)
            if op == 1:
                table.put(el)
            elif op == 2:
                table.delete(el)
            elif op == 3:
                table.search(el)
            else:
                continue
    except:
        exit(0)

My idea:
In a hash table, there is a list of slots for putting in new data, and a list of keys. For example, in Python, dictionary is a special hash table (1$\to$1 type). It seems like classifying your inputs into different drawers, and if you need to pick them up, you need to search the corresponding drawer only according to the keys you’ve got. Therefore, the time cost is reduced by one dimension.

This post is licensed under CC BY 4.0 by the author.

Draw A UML Class Diagram

Tutorial for GPOPS-II