Exemplo n.º 1
0
@time: 2019/4/9 22:41
@desc: 第32讲:连续放入
       采用向量数据结构,持续放入n个节点
       由于python中没有指针的概念,故与结构体的push back是一样的
"""
import time

from common_lib.vector import Vector

global m

class xnode(object):
    def __init__(self, d):
        data = []
        for i in range(m):
            data.append(d)
        data.append(0)

if __name__ == '__main__':
    n = 1000000
    m = 16
    V = Vector()
    start = time.process_time()
    for i in range(n):
        p = xnode(i)
        V.push_back(p)
    end = time.process_time()
    print("运行时间(s):", end - start)
    for v in V:
        del v
Exemplo n.º 2
0
    N = 5
    a = [2, 5, 3, 1, 4]

    # 从小到大排序
    a.sort()
    print(a)

    # 从大到小排序
    a.sort(reverse=True)
    print(a)

    # 对字符串排序
    b = ["www", "algorithm", "racer", "text", "wait"]
    b.sort()
    print(b)
    b.sort(reverse=True)
    print(b)

    # 对向量排序
    v = Vector(["www", "algorithm", "racer", "text", "wait"])
    # 从小到大排序
    v.sort()
    print(v)
    # 从大到小排序
    v.sort(reverse=True)
    print(v)
    # 基于范围循环打印v中的元素
    for x in v:
        print(x, end=" ")

Exemplo n.º 3
0
    print(result)


def reverse(header):
    prev = None
    curr = header.next
    while curr:
        # 存储下一个节点的位置
        next = curr.next
        # 将当前节点进行逆置
        curr.next = prev
        # 前一个节点向下移动
        prev = curr
        # 当前节点向下移动
        curr = next
    header.next = prev


if __name__ == '__main__':
    V = Vector([Node(), Node(1), Node(2), Node(3)])
    i = 0
    while i + 1 < len(V):
        V[i].next = V[i + 1]
        i += 1
    traverse(V[0])
    reverse(V[0])
    traverse(V[0])

    FL = [1, 2, 3]
    FL.reverse()
    print(FL)
Exemplo n.º 4
0
#!/usr/bin/env python
# encoding: utf-8
"""
@author: HuRuiFeng
@file: int_push_back.py
@time: 2019/4/9 22:34
@desc: 第32讲:连续放入
       采用向量数据结构,持续放入n个整数
"""
import time

from common_lib.vector import Vector

if __name__ == '__main__':
    n = 1000000
    start = time.process_time()
    V = Vector()
    for i in range(n):
        V.push_back(0)
    end = time.process_time()
    print("运行时间(s):", end - start)
Exemplo n.º 5
0
#!/usr/bin/env python
# encoding: utf-8
"""
@author: HuRuiFeng
@file: doubling.py
@time: 2019/2/13 21:55
@desc: 第25讲:容量之妙-向量容量是高效的来源
"""

from common_lib.vector import Vector

if __name__ == '__main__':
    n = 40
    #size()返回当前元素个数, capacity()返回当前容量
    A = Vector()
    for i in range(n):
        print(A.size(), A.capacity())
        A.push_back(0)
    print(A.size(), A.capacity())

    B = Vector()
    # 提前预留容量n.
    B.resize(n)
    for i in range(n):
        print(B.size(), B.capacity())
        B.push_back(0)
    print(B.size(), B.capacity())
# encoding: utf-8
"""
@author: HuRuiFeng
@file: binary_search_vector.py
@time: 2019/2/9 16:14
@desc:第8讲:向量二分查找
"""

from common_lib.vector import Vector


def binary_search_vector(key, data, N):
    low = 0
    high = N
    while low < high:
        mid = int(low + (high - low) / 2)
        if key < data[mid]:
            high = mid
        elif data[mid] < key:
            low = mid + 1
        else:
            return True
    return False


if __name__ == '__main__':
    v = Vector([1, 2, 3, 4, 5])
    print(binary_search_vector(2, v, 5))
    print(binary_search_vector(0, v, 5))
    print(binary_search_vector(2, v[2:], 3))
    print(binary_search_vector(0, v, 0))
# encoding: utf-8
"""
@author: HuRuiFeng
@file: common_running_times.py
@time: 2019/2/9 23:30
@desc: 第20讲:常见运行时间-给出代码并分析常见运行时间
"""

from common_lib.vector import Vector
import time
import bisect

if __name__ == '__main__':
    N = 10000000

    v = Vector(N)

    # 线性时间
    start = time.process_time()
    length = v.size()
    for i, item in enumerate(v):
        v[i] = length - i
    end = time.process_time()
    print("运行时间(s):", end - start)

    # 线对时间
    start = time.process_time()
    v.sort()
    end = time.process_time()
    print("运行时间(s):", end - start)
Exemplo n.º 8
0
#!/usr/bin/env python
# encoding: utf-8
"""
@author: HuRuiFeng
@file: vector_example.py
@time: 2019/2/13 21:09
@desc: 第24讲-向量用法
"""

from common_lib.vector import Vector

if __name__ == '__main__':
    # 定义一个初始长度为10的向量A, 可用位置数为10.
    A = Vector(10)
    # 下标i从0到A.size()-1对A中每个元素赋值i.
    # 由于python的list可以放置任何类型元素
    # 向量的下标用法与数组相同, 但要注意应保证向量中实有元素个数就是size().
    for i in range(A.size()):
        A[i] = i
    for i in range(A.size()):
        A[i] = 1

    # 定义一个长度为5的向量B, 初始元素全为3.
    B = Vector(5, 3)
    # 在向量B末尾加入100个2.
    B.resize(B.size() + 100, 2)
    # 在向量V的尾部加入4
    B.push_back(4)
    # 迭代器的另一种用法,使用列表推导
    B = Vector([value * 2 for i, value in enumerate(B)])
    # 若向量B不为空,则持续输出其尾部元素并删除之
Exemplo n.º 9
0
#!/usr/bin/env python
# encoding: utf-8
"""
@author: HuRuiFeng
@file: buffer.py
@time: 2019/4/20 18:05
@desc: 第35讲: 循环队列-讲清来龙去脉
       需要考虑push(x), pop(), full(), empty()
"""

from queue import Queue
from common_lib.vector import Vector

if __name__ == '__main__':
    buffer = Vector()
    # 容量取10
    C = 10
    # 真实buffer长度为N
    N = C + 1
    buffer.resize(N)
    # 初值任选buffer中的一个有效位置
    front = int(N / 2)
    # 这里都取N / 2
    rear = int(N / 2)
    x = 0
    # 当buffer不满, 持续放入0, 1, ... , C - 1
    # 代替取模运算front = (rear+1) % N
    while (rear + 1 != front if rear + 1 < N else 0 != front):
        buffer[rear] = x
        x += 1
        # 下面的操作比rear = (rear + 1) % N更快
Exemplo n.º 10
0
#!/usr/bin/env python
# encoding: utf-8
"""
@author: HuRuiFeng
@file: order_statistics_set.py
@time: 2019/2/9 19:03
@desc: 第13讲:集合中的次序统计量-寻找集合中第k小的元素
"""

from common_lib.set import Set
from common_lib.vector import Vector

if __name__ == '__main__':
    S = Set([3, 2, 1, 4, 5])
    k = int(input("请输入k: "))
    if k<=0 or k > S.size():
        print("超出范围!")
    else:
        # 第一种方法
        print(sorted(S.copy())[k-1])
        # 第二种方法
        V = Vector(k-1)
        for i in range(0, k-1):
            V[i] = S.begin()
            S.discard(S.begin())
        print(S.begin())
        for i in range(V.size()):
            S.insert(V[i])

        print(S)
Exemplo n.º 11
0
@time: 2019/4/9 22:52
@desc: 第32讲:连续放入
       采用向量数据结构,持续放入n个节点
"""

import time

from common_lib.vector import Vector

global m


class xnode(object):
    def __init__(self, d):
        data = []
        for i in range(m):
            data.append(d)
        data.append(0)


if __name__ == '__main__':
    n = 1000000
    m = 16
    V = Vector()
    start = time.process_time()
    for i in range(n):
        V.push_back(xnode(i))
    end = time.process_time()
    print("运行时间(s):", end - start)
    for v in V:
        del v
Exemplo n.º 12
0
# encoding: utf-8
"""
@author: HuRuiFeng
@file: description.py
@time: 2019/2/9 20:57
@desc: 第15讲:以集合描述算法-学会用集合的语言实现算法
"""

from common_lib.set import Set
from common_lib.vector import Vector

if __name__ == '__main__':
    # 差集
    A = Set([3, 2, 1, 4, 7, 9, 11])
    B = Set([6, 2, 9])
    C = Vector()
    for i, a in enumerate(A):
        if a not in B:
            C.push_back(a)
    print(C)

    # 转存
    D = Set([3, 5, 1, 7, 2, 8, 0])
    E = Set()
    while not D.empty():
        if D.begin() % 2 == 0:
            E.insert(D.begin())
        D.erase(D.begin())

    print(E)
Exemplo n.º 13
0
# D为计算次数
def memoized_Collatz(v, n):
    D = 0
    # 如果n不在向量v的下标范围之内, 先转换到合理范围之内并计算偏移D
    while n >= len(v):
        n = int(n / 2 if n % 2 == 0 else 3 * n + 1)
        D = D + 1

    # 对v[n]进行赋值, 注意此处n在向量v的下标范围之内, 直接递归加1赋值即可
    if v[n] == 0 and n > 0:
        v[n] = memoized_Collatz(v, int(n / 2 if n % 2 == 0 else 3 * n + 1)) + 1

    # 返回值是原有的n对应的序列长度, 应加上偏移量D
    return v[n] + D


if __name__ == '__main__':
    # 利用备忘录保存已算出的值, 适合多次求解
    m = 10000
    v = Vector(m, 0)
    v[1] = 1

    # 测试迭代和备忘录计算结果是否一致, 测试范围为[1, max]
    max = 100000
    equal = True
    for n in range(1, max + 1):
        if iterative_Collatz(n) != memoized_Collatz(v, n):
            equal = False
    print("相符" if equal else "不相符")
Exemplo n.º 14
0
@file: phone.py
@time: 2019/4/21 17:58
@desc: 第37讲: 电话号码排序
"""
from queue import Queue

from common_lib.vector import Vector

if __name__ == '__main__':
    # 字符串长度
    L = 9
    # 基数
    B = 10
    # 如果是特别长的字符串,可以考虑用链表存储原始数据,后续队列也用链表实现
    # 不要用字符串向量再配上字符串指针向量来变动操作,那样效果不好
    phone_numbers = Vector(10, "123456789")
    Q = Vector(B)
    # d从L - 1到0,注意用法
    d = L
    while d > 0:
        d -= 1
        for x in phone_numbers:
            if not Q[ord(x[d]) - ord('0')]:
                Q[ord(x[d]) - ord('0')] = Queue()
            Q[ord(x[d]) - ord('0')].put(x)
        i = 0
        for k in range(B):
            while Q[k] and not Q[k].empty():
                phone_numbers[i] = Q[k].get()
                i += 1
Exemplo n.º 15
0
"""
@author: HuRuiFeng
@file: array_and_vector.py
@time: 2019/2/9 13:33
@desc: 第3讲:数组和向量
"""

from common_lib.vector import Vector

if __name__ == '__main__':

    n = 42
    c = 1

    # 定义
    V1 = Vector(n)

    # 初始化
    A1 = [c for i in range(n)]
    V2 = Vector(n, c)

    # 列表初始化
    V3 = Vector([1, 2, 3, 4, 5])
    print(V3)

    # 动态变化
    V3.push_back(6)
    print(len(V3))
    print(V3.front(), V3.back())
    V3.pop_back()
    print(len(V3))