Skip to content

Latest commit

 

History

History
123 lines (82 loc) · 2.77 KB

W5.md

File metadata and controls

123 lines (82 loc) · 2.77 KB

1. Hash表

import numpy as np

class HashTable:
    # init function for our hash table
    # h is a function that maps a universe U to range(n)
    def __init__(self, h, n):
        self.h = h
        # store n buckets, each of which has a linked list. 
        # I'm just going to implement as python arrays.
        self.buckets = [ [] for i in range(n) ]
        
    def insert(self, x):
        self.buckets[self.h(x)].append(x)
        
    # delete an item in the hash table, if it's in there
    # returns the deleted item, or None if it wasn't found.
    def delete(self,x):
        bucket = self.buckets[self.h(x)]
        # take time O(n) to look for x in the bucket.
        for i in range(len(bucket)):
            if bucket[i] == x:
                return bucket.pop(i)
        return None
    
    # same as delete, but don't remove it when you find it.
    def find(self,x):
        bucket = self.buckets[self.h(x)]
        # take time O(n) to look for x in the bucket.
        for i in range(len(bucket)):
            if bucket[i] == x:
                return bucket[i]  
        return None
    
    
def xModn(x,n):
    return (7*x)%n
0
HT = HashTable(xModn, 5)

HT.insert(7)
HT.insert(5)
HT.insert(3)
HT.insert(4)
HT.insert(1)
HT.insert(2)

HT.insert(9)

HT.delete(4)

2. SQL

import sqlite3

db = sqlite3.connect("university.db")
cursor = db.cursor()

cursor .execute("""CREATE TABLE students IF NOT EXISTS class
(id INTEGER PRIMARY KEY, name TEXT NOT NULL, gender TEXT NOT NULL, age INTEGER NOT NULL);""")
---------------------------------------------------------------------------

OperationalError                          Traceback (most recent call last)

<ipython-input-10-93c3042397ec> in <module>
      4 cursor = db.cursor()
      5 
----> 6 cursor .execute("""CREATE TABLE students IF NOT EXISTS class
      7 (id INTEGER PRIMARY KEY, name TEXT NOT NULL, gender TEXT NOT NULL, age INTEGER NOT NULL);""")


OperationalError: near "IF": syntax error
db = sqlite3.connect("university.db")
cursor=db.cursor()
cursor.execute("""INSERT INTO students(id, name, gender, age)
VALUES(1, 'hsr', 'female', 20)""")

do.commit()
cursor.execute("SELECT * FROM class")
print(cursor.fetchall())
db.close()
---------------------------------------------------------------------------

OperationalError                          Traceback (most recent call last)

<ipython-input-6-ad4ca8c78b57> in <module>
      1 db = sqlite3.connect("university.db")
      2 cursor=db.cursor()
----> 3 cursor.execute("""INSERT INTO students(id, name, gender, age)
      4 VALUES(1, 'hsr', 'female', 20)""")
      5 


OperationalError: database is locked