Data Structures and Algorithms (3) and the recursion stack

1 stack of understanding

  1. The stack is a collection of data, the list will be appreciated that only one end of the insertion or deletion operation.

  2. Stack features: LIFO

  3. The basic operation of the stack

    1. Push: push
    2. Pop: pop
    3. Take the stack: gettop
  4. def brace_match(s):
        stack = []
        d = {"(":")", "[":"]", "{":"}"}
        for ch in s:
            if ch in {'(','[','{'}:
                stack.append(ch)
            elif len(stack) == 0:
                print('多了右括号%s' % ch)
                return False
            elif d[stack[-1]] == ch:
                stack.pop()
            else:
                print('括号%s处不匹配' % ch)
                return False
        if len(stack) == 0:
            return True
        else:
            print('剩余括号未匹配')
            return False
    

2 appreciated queue

Queue understanding:

  1. Queue (Queue) is a set of data, allowing only one end inserted in the list, delete the other end.
  2. One end of the tail is referred to as insert (rear), referred to as the insertion operation into the team or the team.
  3. One end is called the team head deletion (front), delete the action is called from the team.
  4. Nature queue: FIFO (first-in, first-out)
  5. Bidirectional Queue: Queue at both ends to allow operation of the intake and dequeue

Queue built-in module: from collections import deque

  1. Creating a queue: queue = deque (li)
  2. Into the team: append
  3. A team: popleft
  4. The first two-way queue into the team: appendleft
  5. Two-way end of the queue into the team: pop

3 recursive Fibonacci function

# 递归:
def my_num(x):
    if x == 1:
        return 1
    elif x == 2:
        return 2
    else:
        return my_num(x-2) + my_num(x-1)
for i in range(1, 10):
    print(my_num(i))

4 vehicle scheduling problem

def VehicleReecorder(Trucks, k):
    BufferRails = []
    for i in range(k):
        BufferRails.append([])
    currentCarriage = 1
    for i in Trucks:
        if i == currentCarriage:
            print(f'{i}')
            currentCarriage += 1
            continue
        else:
            for buffer in BufferRails:
                if not buffer:
                    buffer.append(i)
                    break
                else:
                    if min(buffer) > i:
                        buffer.append(i)
                        break
    for buffer_list in BufferRails:
        for i in range(len(buffer_list)):
            last = buffer_list.pop()
            if last == currentCarriage:
                print(f'{i}')
                currentCarriage +=1

Guess you like

Origin www.cnblogs.com/yangjiez/p/12181745.html