# Day11 data structure

day11 data structure

table of Contents:

  • data structure
    • Stack
    • queue
    • Deque
    • List
    • Binary Tree
  • algorithm:
    • Binary search
    • bubble
    • select
    • fast
    • insert
    • Hill
    • Sorting binary tree

What is the algorithm analysis?

  • Students will often new to programming procedures and others have written procedures to do than to get in the process of alignment of the two sides will find a program written in a very similar but not the same. Then there will be an interesting phenomenon: two sets of procedures are used to solve the same problem, but the two programs looked so different, so which group the program better?
  • = B + C + A 1000 A 2 + B 2 ** 2 = C (a, b, c are natural numbers), obtaining a, b, c the possible combinations of?

1

for a in range(0,1001):
    for b in range(0,1001):
        for c in range(0,1001):
            if a+b+c == 1000 and a**2 + b**2 == c**2:
                print(a,b,c)

2

for a in range(0,1001):
    for b in range(0,1001):
        c = 1000 - a - b
        if a+b+c == 1000 and a**2 + b**2 == c**2:
            print(a,b,c)

---->

0 500 500
200 375 425
375 200 425
500 0 500

Judge the merits of the program method

  • Consume computer resources and efficiency (not intuitive)
  • Consuming calculation algorithm executed
  • Time complexity (recommended)

time complexity

  • Number / quantization step algorithm executed: Rule Evaluation
  • The most important item: time complexity of expression of the most significant items
  • Use big O notation to represent the time complexity: O (algorithm execution step number one most significant expression)

def sumOfN(n):
theSum = 0
for i in range(1,n+1):
theSum = theSum + i

return theSum

print(sumOfN(10))

---->55

  • Case: calculate the time complexity of the following algorithm

  • a=5
    b=6
    c=10
    for i in range(n):
       for j in range(n):
          x = i * i
          y = j * j
          z = i * j
    for k in range(n):
       w = a*k + 45
       v = b*b
    d = 33
    
    ###########################
    3 + 3*n*n + 2*n + 1
    3n**2 +2n + 4
    O(n**2)

    Common time complexity:

    • O(1) < O(logn) < O(n) < O(nlogn) < O(n^2) < O(n^3) < O(2^n) < O(n!) < O(n^n)

data structure

  • Concept: For data (basic data types (int, float, char)) of the organization was known as a data structure. How is a set of data structures solved to save, save what form.

  • Case: Some students need to store student information (name, score), then these data should be how to organize it? What is the time complexity of the query on a specific student is it? (Three tissues mode)

[
    [name,score],
    [name1,score1],
    
]
O(n)
(
    [name,score],
    [name1,score1],

)
O(n)
{
    {'name':'bobo'},
    {'score':100},
}
{
    name:{score:100},
    name2:{score:99}
}

O(1)
  • Three forms of organization based on the time complexity of the query?

  • Use a different form of organization data, based on the complexity of the time when a query is not the same. Therefore considered algorithm is designed to solve practical problems, the data structure is a vector algorithm to deal with the problem.

list (for in range ()) the fastest

Followed by [] to push the formula

Afterwards???

Stack

  • Features: last-out data structure
  • Top of the stack, the stack tail

  • Application: Each web browser has a back button. When you browse the Web, these pages are placed in a stack (actually the URL of the page). You now see the web page at the top, the first page you see at the bottom. If you press the 'Back' button will reverse order just browse the pages.

  • Stack () Creates a new empty stack. It takes no arguments and returns an empty stack.
  • push (item) will add a new item to the top of the stack. It needs to do item parameter does not return anything.
  • pop () Remove top item from the stack. It takes no arguments and returns the item. Stack has been modified.
  • peek () returns the top item from the stack, but does not delete it. No arguments. Does not modify the stack.
  • Whether isEmpty () Tests if this stack is empty. No arguments and returns a Boolean value.
  • size () Returns the number of item in the stack. No arguments and returns an integer.

class Stack():
    def __init__(self):
        self.items = []
    def push(self,item):
        self.items.append(item)
    def drop(self):
        return self.items.pop()
    def isEmpty(self):
        return self.items == []
    def size(self):
        return len(self.items)
s = Stack()
s.push(1)
len(s.items)
print(s.drop())
print(s.isEmpty())
print(s.size())

s.push('第一')
s.push('第二')
s.push('第三')
s.items  # ['第一', '第二', '第三']
# print(s.drop()) # 后进先出对的  # '第三

--->

1
True
0
s = Stack()

def getRequest(url):
    s.push(url)
def showCurenrUrl():
    print('当前页面展示的url:'+s.pop())
def back():
    print('回退按钮点击后显示的url:',s.pop())

getRequest('www.1.com')
getRequest('www.2.com')
getRequest('www.3.com')

showCurenrUrl()
back()
back()

---->

当前页面展示的url:www.3.com
回退按钮点击后显示的url: www.2.com
回退按钮点击后显示的url: www.1.com

queue

  • Queue: FIFO
  • Scenario:
    • Our computer lab has 30 computers and a printer networking. When students want to print their print jobs with all other print job is waiting for the "consistent." The first task is to complete the entry. If you are the last one, you have to wait for you in front of all other tasks Print
  • Queue () to create a new empty queue. It takes no parameters and returns an empty queue.
  • enqueue (item) to add a new item to the tail. It requires item as an argument, it does not return anything.
  • dequeue () Removes an item from the head of the queue. It takes no arguments and returns the item. Queue is modified.
  • isEmpty () to see if the queue is empty. It takes no arguments and returns a Boolean value.
  • size () Returns the number of items in the queue. It takes no parameters and returns an integer.
class Queue():
    def __init__(self):
        self.items = []
    def push(self,index,item):
        self.items.insert(index,item)
    def drop(self):
        return self.items.pop()
    def isEmpty(self):
        return self.items == []
    def size(self):
        return len(self.items)
    def peek(self): #最后一个的位置 因为从零开始
        return len(self.items)-1
    
q = Queue()
q.push(0,'第一')
q.push(0,'第二')
q.push(0,'第三')

q.items # ['第三', '第二', '第一']
# q.drop() # '第一'

q.peek()

Hot potato game

  • Case: hot potato
    • Hot potato game: Siege of six children in a circle, specify the order of the children themselves. The first child of the hands of a hot potato, sweet potato will need timing 1 second timer is passed to the next child, and so on. Rule is that when the timer counting every 7 seconds, the hands of a potato kids out of the game. The rest of the game until the end of a child, the last remaining child wins. Please use the queue implementation strategy of the game, came in several locations will eventually win.
  • in conclusion:
    • Seven seconds after instant to, potato is passed six times.
    • Guarantee the hands of a potato kids always stand on the head of the queue
class Queue():
    def __init__(self):
        self.items = []
    def push(self,index,item):
        self.items.insert(index,item)
    def drop(self):
        return self.items.pop()
    def isEmpty(self):
        return self.items == []
    def size(self):
        return len(self.items)
    def peek(self): #最后一个的位置 因为从零开始
        return len(self.items)-1
# 7 秒 ,去除第一个人中手上不传出的1秒    
q1 = Queue()
kids = ['A','B','C','D','E','F']
for kid in kids : 
    q1.push(0,kid)    # 把数据添加进去
q1.items
while len(q1.items)>1:  # 当数据只有1个时,为游戏的胜者
    for i in range(6):
        a = q1.drop()   # 先删,后添加到最初位置,就是换顺序
        q1.push(0,a)    # ,一个个往后走,然后保证山芋在第一位
    q1.drop()        # 删除第一位
q1.items    

Deque

  • Compared with the same column, there are two head and tail. You can insert and delete data in the dual port, a single data structure characteristic stacks and queues

  • Deque () to create a new, empty deque. It takes no arguments and returns an empty deque.
  • addFront (item) will add a new item to the header of the deque. It takes the item parameter does not return anything.
  • addRear (item) will add a new item to the end of the deque. It takes the item parameter does not return anything.
  • removeFront () to delete the first item in the deque. It takes no arguments and returns the item. deque is modified.
  • removeRear () delete the item from the tail of the deque. It takes no arguments and returns the item. deque is modified.
  • Whether isEmpty () Test deque is empty. It takes no arguments and returns a Boolean value.
  • size () Returns the number of items in the deque. It takes no parameters and returns an integer.

class Queue():
    def __init__(self):
        self.items = []
        # 队列方式加到栈首
    def addfront(self,index,item):
        self.items.insert(index,item)
        # 栈模式,从前面取,就是双端队列
    def addback(self,item):
        self.items.append(item)
        
    def dropfront(self):
        return self.items.pop()
    def dropback(self):
        return self.items.pop(0)  # 123  先进先出   
    
    def isEmpty(self):
        return self.items == []
    def size(self):
        return len(self.items)
    def peek(self): #最后一个的位置 因为从零开始
        return len(self.items)-1
    
q = Queue()

q.addfront(0,1)
q.addfront(0,2)
q.addfront(0,3)
q.items
q.dropfront()
q.dropfront()
q.dropfront()
# 首先进先出

q.addback(1)
q.addback(2)
q.addback(3)
q.dropfront()
q.dropfront()
q.dropfront()
q.items
# 栈  删除方式就是栈了   [1]  


q.addback(1)
q.addback(2)
q.addback(3)

q.items
q.dropback()
q.dropback()
q.dropback()
# 后进后厨
尾先进新出: 两边都是  

Deque Applications: palindrome inspection

Palindrome is a string, reading the same first and last characters, e.g., radar toot madam.

Copy of the teacher:

ab = 'abcdaddcba'
    
def huiwen(st):
    q = Queue()
    ex = 'True'
    for s in st:
        q.addback(s)
    while len(q.items)>1:
        if q.dropback()!= q.dropfront():
            ex = 'False'
            break 
    return ex
    
print(huiwen(ab))      
False

RAM

  • The role of the computer
    • For storing binary data and computing
  • A measure of computer memory size unit:
    • bit (bit):
    • Byte: 8bit
    • kb: 1024 bytes
    • mb:1024kb
  • Question: How computer to calculate 1 + 2?
    • It must open up memory space in the computer's memory
    • Only the corresponding value stored in the memory
  • The concept of variables
    • a = 10 meaning representation in a computer (memory map)
    • After a good memory space opened up, every piece of memory space will have two default properties
      • The size of the memory space: computer memory size unit
      • Memory address space: hexadecimal value
        • Address effect: for positioning (tracking) the specified memory, can obtain the data stored in the memory
    • Variable represents the essence of memory address space, usually a variable is intended to represent the memory address corresponding to the memory space
  • A = appreciated that the memory 10 (reference point)
    • Quote: Variable
    • Point: If a certain variable / address of a reference stored in a memory, it means that the variable pointing to the memory address of the memory space corresponding to.
  • The size of the memory space occupied by different data

Order table

  • Elements of the container / data structure is stored in sequential, the structure of sequence table can be divided into two forms: a single data type (numpy) and multiple data types (list).
  • python lists and tuples belong to multiple data types order table

  • Single data type sequence table memory map (memory continuously open)

  • Multiple Data Types FIG sequence table memory (RAM discontinuous open)

  • Malpractice order of the table: the order table structure needs to know in advance the size of the data to apply continuous storage space, time and needs to be expanded during the relocation of data.

List:

No data with respect to the order of the relocation table, list structure may take advantage of computer memory, dynamic memory management for flexible and be expanded.

  • List (Linked list) is a common basic data structures, a linear table, as sequence table but not continuously stored data, but each node information (data storing means) stored in the next node ( That address)

Claim

. is_empty():链表是否为空

. length():链表长度

. travel():遍历整个链表

. add(item):链表头部添加元素

. append(item):链表尾部添加元素

. insert(pos, item):指定位置添加元素

. remove(item):删除节点

. search(item):查找节点是否存在

Establish node

class Node():
    def __init__(self,item): #建立一个节点,新节点,后续的还不知道,所以没有next

​        self.item = item   # 添加的值
​        self.next = None   # 链子指向,因为是新值,还没来得及建链,故None
node  = Node(3)       # 实例化一个

class Link():
    def __init__(self):
        # 建立一个空链表
        self._head = None   # 第一个指向None ,还没有添加进来
        
    def add(self,item): # 链表头部添加元素
        node = Node(item)   # 实例化一个, 没有后续,next=None  item=item 
        node.next = self._head  
        # 之前的head 1 空, 2次添加是上一个node,因为head被重新赋值了
        # 变成了上一个的node(实例化的) 下面一行代码 ,然后一直迭代
        self._head = node  # 给head指向,实例化的那个Node 第一次             

1565874673548

  • As these two logic functions are used:
    • We are not aware of the number of cycles, so use a while loop, then, has been next, until it is empty, then exit
   def travel(self): # 遍历整个链表
        cur = self._head # 地址
        while cur: # 最后为空 
            print(cur.item) # 值
            cur = cur.next # 下一个
    def length(self):   # 链表长度
        cur = self._head # 地址
        count = 0  
        while cur: # 最后为空
            print(cur.item) # 值
            count += 1 
            cur = cur.next # 下一个          
#             print('长度为',count)
        return count
  • Do not forget node is represented _head
 def isEmpty(self):
        return self._head == None
  • The for loop then returned to find the True Instructions to find, can not find, and thought the same as above, next to go down
    def search(self,item):     #查找节点是否存在 
        cur = self._head 
        find = 'False' 
        for i in range(self.length()):
            if cur.item == item :
                find = 'True'
            else:
                cur = cur.next 
        return find
  • I was guilty of two errors, because the copy of the results of the colon is Chinese, not found
  • The following cur, pre circulation, chain stitching
  • 1565875155955
#加到最后
#最后一个指向为none ,主要是对前一个操作
#因为最后一个next = None,而前一个,指向的是最后一个,所以要链一下最后一个,一条链
    def append(self,item):
        node = Node(item)
        cur = self._head # 地址
        
        # 注意的项:
        # 第一次添加,没有前一项 # 的时候直接,没有最后一个,next 
        if self.isEmpty():
            self._head = node 
            return  # 不要忘了,return 退出
        pre = None 
        while cur: # 最后为空
             
            pre = cur # 前一个    
            cur = cur.next # 下一个          
             
        pre.next = node 
    # 插入  
    # 没想到不难,会了append之后,改一下链子,别的不大动,
    # 值的注意的点,范围插入时,
    def insert(self, pos, item):
        node = Node(item)
        cur = self._head # 地址
        if 0 > pos or pos > self.length()+1:
            print(pos,'超范围,没法插入,请重新插入')
            return 
        
        pre = None 
         # 最后为空
        for i in range(1,pos): # 第几个位置 前面添加后天添加建立两个连接
            pre = cur  # 前一个
            cur = cur.next  # 下一个   
            
        node.next = pre.next # node.next ✔  
                             # 顺序不能错了,先把后面的链子给了中间的
        pre.next = node      # 然后给前面的链子,中间的
 #删除节点
    def remove(self,item):
        node = Node(item)
        cur = self._head # 地址
        if self.search(item)=='False': #用搜索,查,在里面然后删
            return '不在里面,不用删除'
        if self.length()==1 or self.length():  #1个或者多个的时候不走下面循环
            self._head == None
            return 
        pre = None 
         # 最后为空  
        for i in range(1,self.length()): # 第几个位置 前面添加后天添加建立两个连接
            pre = cur   # 前一个    
            cur = cur.next   # 下一个   
            
        pre.next = cur.next   #上一个的链连接下一个的下一个的链,所以下一个断开连接 
        
        print('长度',self.length())  

Print

link = Link()
link.add(1)
link.add(2)
link.add(3)
# link.append(1)
# link.append(2)
# link.append(3)
# link.insert(2,4)
# link.insert(2,4)
# link.insert(4,4)
# link.insert(44,4)# 超范围的不行
# link.travel()
# link.length()  
# link.isEmpty()
# link.search(-1)
link.remove(1)
print(link.remove(4))
# link.search(1)
3
2
1
3
2
1
3
2
1
3
2
1
不在里面,不用删除

Guess you like

Origin www.cnblogs.com/Doner/p/11361048.html