返回顶部

手写怪

1.数据结构

1.1栈

class Stack(object):
    def __init__(self):
        self.items = []
    def push(self,item):
        self.items.append(item)  # 将一个新项添加到栈的顶部
    def pop(self):
       return self.items.pop()  # 取出(删除)栈顶元素,栈被修改
	def peek(self):
       return self.items[len(self.items)-1] # 从栈返回顶部项,但不会删除它,不修改栈
    def isEmpty(self):
        return self.items == None  # 测试栈是否为空
    def size(self):
        return len(self.items) # 返回栈中的 item 数量

1.2队列

class Queue(object):
    def __init__(self):
        self.items = []
    def enqueue(self,item):
        """添加至队尾"""
        self.items.insert(0,item)
    def dequeue(self):
        """移除(查看)队首项,队列被修改"""
        return self.items.pop()
    def isEmpty(self):
        return self.items == []
    def size(self):
        return len(self.items)

1.3双端队列

class Dequeue():
    def __init__(self):
        self.items = []
    def isEmpty(self):
        return self.items == []
    def size(self):
        return len(self.items)
    def addFront(self,item):
        self.items.append(item)
    def addRear(self,item):
        self.items.insert(0,item)
    def removeFront(self):
        return self.items.pop()
    def removeRear(self):
        return self.items.pop(0)

1.4单链表

class Node(object):
    """单链表节点构建"""

    def __init__(self, item):
        self.item = item
        self.next = None


class Link(object):
    """单链表链子构建"""

    # 构建一个空的链表_head
    def __init__(self):
        self._head = None  # _head要永远指向链表中的头节点,指向None就是空链表

    def add(self, item):
        """向链表的头部插节点"""
        # 创建一个节点
        node = Node(item)
        # print(node)
        # 更改头部节点指向
        node.next = self._head
        # 更改_head指向新建节点内存地址
        self._head = node

    def travel(self):
        """遍历链表"""
        # _head的内存指向不能被改变,重新定义一个
        cur = self._head
        count = 0
        while cur:  # 当cur的执行为空时,布尔类型为None
            print(cur.item)
            cur = cur.next
            count += 1
        print("长度", count)

    # def is_empty(self):
    #     return self._head == None
    def search(self, item):
        """查找item"""
        cur = self._head
        ret = False
        while cur:
            if cur.item == item:
                ret = True
                break
            cur = cur.next
        return ret

    def append(self, item):
        """尾部添加节点"""
        # 创建一个节点
        node = Node(item)
        # 判断如果链表为空,直接将_head指向新节点
        if not self._head:
            self._head = node

        cur = self._head
        pre = None
        while cur:
            pre = cur  # 让pre记录cur前一个节点
            cur = cur.next  # 最后一次循环cur为None
        pre.next = node

    def insert(self, pos, item):
        """向指定位置插入节点
        pos:插入位置"""
        node = Node(item)
        # 需要判断 插入位置是不是正确
        try:
            cur = self._head
            pre = None
            # 插在哪就循环多少次
            for i in range(pos):
                pre = cur
                cur = cur.next
            pre.next = node
            node.next = cur
        except Exception as e:
            print(e, "插入位置异常")

    def remove(self, item):
        """删除节点"""
        cur = self._head
        pre = None
        if not self._head.next:
            print("无节点")
            return
        # 删除第一个节点的情况
        if self._head.item == item:
            self._head = self._head.next
            return
        while cur:
            pre = cur
            cur = cur.next
            if cur.item == item:
                pre.next = cur.next
                break


link = Link()
link.add(3)
link.add(4)
link.add(5)
link.append(6)
link.remove(6)
print("search_result", link.search(6))
link.insert(0, 7)
link.travel()

1.5二叉树

#封装一个节点对象
class Node(object):
    def __init__(self,item):
        self.item = item
        self.left = None
        self.right = None
class Tree(object):
    def __init__(self):#构造出一颗空的二叉树
        self.root = None #root指向第一个节点的地址,如果root指向了None,则该二叉树为空
    #向二叉树中插入节点
    def addNode(self,item):
        node = Node(item)
        if self.root == None:
            #addNode如果第一次被调用则意味着:向空树中插入第一个节点,该节点一定是该树的根节点
            self.root = node
            return
        cur = self.root
        queue = [cur]
        while queue:
            n = queue.pop(0)
            if n.left != None:
                queue.append(n.left)
            else:
                n.left = node
                break
            if n.right != None:
                queue.append(n.right)
            else:
                n.right = node
                break
    def travel(self):
        """广度遍历"""
        #如果是为空则
        if self.root == None:
            print('空!')
            return
        #树为非空
        cur = self.root
        queue = [cur]
        while queue:
            n = queue.pop(0)
            print(n.item)
            if n.left != None:
                queue.append(n.left)
            if n.right != None:
                queue.append(n.right)
                
    def forward(self,root):
        """前序(根左右)"""
        if root == None: # 递归结束条件
            return
        print(root.item)
        self.forward(root.left) # 递归,本行代码结束才会执行下一行代码
        self.forward(root.right)
        
    def middle(self, root):
        """中序(左根右)"""
        if not root:
            return
        self.middle(root.left) # 递归,将root变为左叶子节点的根
        print(root.item, end='')
        self.middle(root.right)
        
    def back(self, root):
        """后序(左右后)"""
        if not root:
            return
        self.back(root.left)
        self.back(root.right)
        print(root.item)

1.6排序二叉树

class Node(object):
    def __init__(self,item):
        self.item = item
        self.left = None
        self.right = None
class sort(object):
    class SortTree():
    def __init__(self):
        self.root = None
        
    def insertNode(self,item):
        node = Node(item)
        #向空树中插入第一个节点的情况
        if self.root == None:
            self.root = node
            return
        #树为非空的情况
        cur = self.root
        while True:
            if node.item > cur.item:#往右插
                if cur.right == None:
                    cur.right = node
                    break

                else:
                    cur = cur.right
            else:#往左插
                if cur.left == None:
                    cur.left = node
                    break
                else:
                    cur = cur.left
        
    def middleTravel(self,root): # 只有中序才能将排序二叉树中的节点数据按顺序读出
        if root == None:
            return
        self.middle(root.left)
        print(root.item)
        self.middle(root.right)

1.7二分查找

def sort(alist,item): #item就是我们要找的元素
    low = 0 #进行二分查找操作的列表中第一个元素的下标
    high = len(alist)-1#进行二分查找操作的列表中最后一个元素的下标
    find = False
    
    while low <= high:
        mid = (low+high) // 2 #中间元素的下标
        if item > alist[mid]:#我们要找的数比中间元素值大,则意味着我们要找的数在中间元素的右侧
            low = mid + 1
        elif item < alist[mid]:#找的数比中间元素小,则意味着我们要找的数是在中间元素左侧
            high = mid - 1
        else:#找到啦
            find = True
            break
    return find

2.网编与并发

2.1进程

# 函数进程
from multiprocessing import Process
def func(args):
    pass
if __name__ = "__main__":
    pro = Process(target = func,args = (1,))
    pro.daemon = True
    pro.start()
# 面向对象起进程
from multiprocessing import Process
class MyProcess(Process):
    def __init__ (self,x,y):
        self.x=x
        self.y=y
        super().__init__() #传参数时加上super()的init
    def run(self): #gai方法的名字一定要写成run,不能变
        for i in range(5):
            print('in son1')

if __name__=='__main__':
	mp = MyProcess(1,2) #传入参数(1,2)
	mp.daemon = True
	mp.start()

2.2线程

# 线程的创建
from threading import Thread
def func(args):
    pass
if __name__ = "__main__":
    thd = Thread(target = func,args = (1,))
    thd.daemon = True
    thd.start()

# 线程单例模式
import time
from threading import Lock
class A:
	__instance = None
	lock = Lock()
	def __new__(cls, *args, **kwargs):
		with cls.lock:
			if not cls.__instance:
				cls.__instance = object.__new__(cls)
		return cls.__instance
	def __init__(self,name,age):
		self.name = name
		self.age = age
def func():
	a = A('alex', 84)
	print(a)
from threading import Thread
for i in range(10):
    t = Thread(target=func)
    t.start()

2.3协程

# 协程
# gevent模块
import gevent
from gevent import monkey
monkey.patch_all()  #用mokey模块使协程识别多次使用的外部方法,比如time.time()

def func():
    time.sleep()
    
g_l = []
for i in range(10):
    g= genvent.spawn(func)
    g_l.append(g)
gevent.joinall(g_l)

# asyncio模块
import asynico

asyncio def func():
    await asyncio.sleep(1) #阻塞,阻塞必须写入await之后 且使用asyncio模块自己的方
法
loop = asyncio.get_envent_loop()
obj = asyncio.wait([func(),func()])
loop.run_until_complete(obj)



2.4池

# 进程池#基本格式
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
def func(i,name):
	print('start',os.getpid())
	time.sleep(random.randint(1,3))
	print('end', os.getpid())
	return '%s * %s'%(i,os.getpid()) #返回值
if __name__ == '__main__':
	p = ProcessPoolExecutor(5) #池中进程数
	ret_l = []
	for i in range(10):
		ret = p.submit(func,i,'alex')
		ret_l.append(ret) #提交任务
	for ret in ret_l:
		print('ret-->',ret.result()) # ret.result() 取返回值, 同步阻塞
    p.shutdown() ## 关闭池之后就不能继续提交任务,并且会阻塞,直到已经提交的任务完成
    
# 线程池基本格式
#类不同,其余格式相同
from concurrent.futures import ThreadPoolExecutor
def func(i):
    print('start', os.getpid())
    time.sleep(random.randint(1,3))
    print('end', os.getpid())
    return '%s * %s'%(i,os.getpid())
tp = ThreadPoolExecutor(20)
for i in range(10):
    ret = tp.submit(func,i)
tp.shutdown()

2.5 socket

  • tcp协议

    # server端
    import socket
    sk = socket.socket()
    sk.bind(('127.0.0.1',8000))
    sk.listen(10)
    while True:
    	conn,addr = sk.accept()
    	conn.recv(1024)
    	conn.send(b'abc')
    	conn.close()
    sk.close()
    
    # client端
    import socket
    sk = socket.socket()
    sk.connect(('127.0.0.1',9000))
    while True:
    	inp = input('>>>')
    	sk.send(inp.encode('utf-8'))
    	msg = sk.recv(1024).decode('utf-8')
    	print(msg)
    sk.close()
    
    
    
  • udp协议

    #server端
    import socket
    sk = socket.socket(type = socket.SOCK_DGRAM)
    sk.bind(('127.0.0.1',9000))
    while True:
    	msg,client_addr = sk.recvfrom(1024)
    	print(msg.decode('utf-8'))
    	msg = input('>>>').encode('utf-8')
    	sk.sendto(msg,client_addr)
    sk.close()
    
    #client端
    import socket
    sk = socket.socket(type=socket.SOCK_DGRAM)
    while True:
    	inp = input('>>>').encode('utf-8')
    	sk.sendto(inp,('127.0.0.1',9000))
    	ret = sk.recv(1024)
    	print(ret.decode('utf-8'))
    sk.close()
    
    
    

3.基础知识

3.1迭代器/生成器

def func():
	count = 1
	while True:
		yield count
		count += 1
val = func()
for item in val:
	print(item)

3.2面向对象的上下文管理

class Foo(object):
	def do_something(self):
		print('内部执行')
class Context:
	def __enter__(self):
		print('进入')
		return Foo()
	def __exit__(self, exc_type, exc_val, exc_tb):
		print('推出')
with Context() as ctx:
	print('内部执行')
	ctx.do_something()

3.3 安全的单例模式

import time
from threading import Lock
class A:
	__instance = None
	lock = Lock()
	def __new__(cls, *args, **kwargs):
		with cls.lock:
			if not cls.__instance:
				time.sleep(0.1)
				cls.__instance = object.__new__(cls)
		return cls.__instance

3.4发送ajax请求

$.ajax({
	url:'https://api.apeland.cn/api/banner/',
	methods:'get',
	success:function(res){
		console.log(res);
		},
	error:function(err){
	console.log(err);
}

4.数据库

5.排序算法

5.1冒泡排序

def sort(alist):
    for j in range(len(alist) - 1):  # 控制遍历的次数
        for i in range(len(alist) - 1 - j):  # 控制比较的次数
            if alist[i] > alist[i + 1]:
                alist[i], alist[i + 1] = alist[i + 1], alist[i]
    return alist

alist = [2, 1, 4, 6, 3]
print(sort(alist))

5.2选择排序

def sort(alist):
    for j in range(len(alist) - 1, 0, -1): # 控制遍历次数
        max = 0  # 假定索引为0的值最大
        for i in range(j):   # 控制比较次数
            if alist[max] < alist[i + 1]:
                max = i + 1
        # 将最大值放置到列表末尾的位置        
        alist[max], alist[j] = alist[j], alist[max]
    return alist

alist = [2, 1, 4, 6, 3]
print(sort(alist))

5.3插入排序

def sort(alist):
    for i in range(1, len(alist)):
        while i > 0: # 与有序段全部数据比较
            if alist[i] < alist[i - 1]:
                alist[i], alist[i - 1] = alist[i - 1], alist[i]
            i -= 1
    return alist

alist = [2, 1, 4, 6, 3]
print(sort(alist))

5.4希尔排序

#继续缩小增量
def sort(alist):
    gap = len(alist) // 2
    while gap >= 1:
        #将增量设置成gap
        for i in range(gap,len(alist)):
            while i > 0 :
                if alist[i] < alist[i-gap]:
                    alist[i],alist[i-gap] = alist[i-gap],alist[i]
                    i -= gap
                else:
                    break
        gap //= 2
    return alist

5.5快速排序

![1567929391683](C:\Users\big cattle\AppData\Roaming\Typora\typora-user-images\1567929391683.png)

def sort(alist,start,end):
    low = start
    high = end
    if low > high: # 递归结束条件
        return
   mid = alist[low]
    while low < high:
        while low < high:
            if alist[high] > mid:#将high向左偏移
                high -= 1
            else:
                alist[low] = alist[high]
                break

        while low < high:
            if alist[low] < mid:#向右移动low
                low += 1
            else:
                alist[high] = alist[low]
                break
            
    if low == high:
        alist[low] = mid#alist[high] = mid
        
    #将sort的操作作用到基数左侧部分
    sort(alist,start,low-1)
    #将sort的操作作用的基数右侧部分
    sort(alist,high+1,end)
   
    return alist    

posted @ 2019-10-05 23:00  高薪程序员  阅读(10)  评论(0编辑  收藏  举报