def levelOrder(self, root: TreeNode) -> List[List[int]]:
     if not root: return []
     res, deque = [], collections.deque()
     deque.append(root)
     while deque:
         tmp = []
         # 打印奇数层
         for _ in range(len(deque)):
             # 从左向右打印
             node = deque.popleft()
             tmp.append(node.val)
             # 先左后右加入下层节点
             if node.left: deque.append(node.left)
             if node.right: deque.append(node.right)
         res.append(tmp)
         if not deque: break
         # 打印偶数层
         tmp = []
         for _ in range(len(deque)):
             # 从右向左打印
             node = deque.pop()
             tmp.append(node.val)
             # 先右后左加入下层节点
             if node.right: deque.appendleft(node.right)
             if node.left: deque.appendleft(node.left)
         res.append(tmp)
     return res
Beispiel #2
0
def top_sort(v):
    colors[v] = 'gray'

    for w in graph[v]:
        if colors[w] == 'white':
            top_sort(w)

    colors[v] = 'black'
    deque.appendleft(str(v))
Beispiel #3
0
 def rotate(self, nums, k):
     """
     :type nums: List[int]
     :type k: int
     :rtype: None Do not return anything, modify nums in-place instead.
     """
     deque = deque(nums)
     k %= len(nums)
     for _ in range(k):
         deque.appendleft(deque.pop())
     nums[:] = list(deque)
Beispiel #4
0
def rapid_led_update(deque, arr):
    """
    Address all 80 LEDs with 40 consecutive instructions.

    The array `arr` should be an (10, 8) array of colors as integers.

    """
    for v1, v2 in arr.reshape(-1, 2):
        deque.appendleft((0, (RAPID_LED_UPDATE, v1, v2)))

    # exit rapid LED update mode by resending a value with regular status
    deque.appendleft((0, (SET_GRID_LED, 0x0, arr[0, 0])))
 def is_similar_to(self, *, text=None, clean_text=None, ngrams=None):
     if not ngrams:
         if not clean_text:
             clean_text = self.clean_text(text)
         ngrams = self.ngramify(clean_text)
     else:
         ngrams = tuple(ngrams)
     for ngrams_in_deque in self:
         if any(ngram in ngrams_in_deque for ngram in ngrams):
             self.remove(ngrams_in_deque)
             deque.appendleft(self, ngrams_in_deque)
             return True
     else:
         self.appendleft(ngrams)
         return False
 def append(self, timeStampedValue):
     cutoffDateTime = datetime.now() - self.MaximumAge
     #print 'cutoffDateTime: ' + str(cutoffDateTime)
     #print(timeStampedValue)
     done = False
     while not done:
         if len(self) == 0:
             done = True
         else:
             oldestTimeStampedValue = deque.popleft(self)
             if oldestTimeStampedValue.TimeStamp >= cutoffDateTime:
                 # not old enough; we need to keep it
                 deque.appendleft(self, oldestTimeStampedValue)
                 done = True
     
     deque.append(self, timeStampedValue)
Beispiel #7
0
def do_command(deque, command):
    parts = command.split()
    action = parts[0]

    if action == "append":
        item = parts[1]
        deque.append(item)

    elif action == "appendleft":
        item = parts[1]
        deque.appendleft(item)
    
    elif action == "pop":
        deque.pop()

    elif action == "popleft":
        deque.popleft()
Beispiel #8
0
def dfs(s, t, edges):
    stack = deque([s.name])
    visited = set()
    path_map = {}
    while stack:
        current = deque.popleft(stack)
        if current not in visited:
            visited.add(current)
            if current == t:
                return True
            if current in edges and edges[current]:
                for next in edges[current]:
                    if next in visited: 
                        continue
                    path_map[next.name] = current
                    deque.appendleft(stack, next.name)
    return False
Beispiel #9
0
def invoke(command, arg=0):
    if command == "push_front":
        deque.appendleft(arg)
    elif command == "push_back":
        deque.append(arg)
    elif command == "pop_front":
        print(deque.popleft() if deque else -1)
    elif command == "pop_back":
        print(deque.pop() if deque else -1)
    elif command == "size":
        print(len(deque))
    elif command == "empty":
        print(0 if deque else 1)
    elif command == "front":
        print(deque[0] if deque else -1)
    elif command == "back":
        print(deque[-1] if deque else -1)
Beispiel #10
0
def dfs(s, t, edges):
    stack = deque([(s.name, s.color)])
    visited = set()
    path_map = {}
    while stack:
        current, current_color = deque.popleft(stack)
        if current not in visited:
            visited.add(current)
            if current == t:
                return True
            if current in edges and edges[current]:
                for next in edges[current]:
                    if next in visited:
                        continue
                    if current_color == "Red" and next.color == "Black" or \
                       current_color == "Black" and next.color == "Red":
                        path_map[next.name] = current
                        deque.appendleft(stack, (next.name, next.color))
    return False
 def deckRevealedIncreasing1(self, deck):
     from collections import deque
     deque = deque()
     deck.sort(reverse=True)
     for num in deck:
         if deque:
             deque.appendleft(deque.pop())
             deque.appendleft(num)
         else:
             deque.appendleft(num)
     return list(deque)
Beispiel #12
0
def _merge_prefix(deque, size):
    if len(deque) == 1 and len(deque[0]) <= size:
        return
    prefix = []
    remaining = size
    while deque and remaining > 0:
        chunk = deque.popleft()
        if len(chunk) > remaining:
            deque.appendleft(chunk[remaining:])
            chunk = chunk[:remaining]
        prefix.append(chunk)
        remaining -= len(chunk)
    if prefix:
        deque.appendleft(type(prefix[0])().join(prefix))
    if not deque:
        deque.appendleft(b"")
def f(p):
    from collections import deque

    if not p:
        return p

    deque.appendleft(p)

    while deque:
        q = deque.pop()
        q.left, q.right = q.right, q.left

        if q.right:
            deque.appendleft(q.right)
        if q.left:
            deque.appendleft(q.left)

    return p
Beispiel #14
0
 def appendleft(self, item):
     if item in self:
         self.remove(item)
     deque.appendleft(self, item)
     if len(self) == self.size:
         self.appendleft = self.full_appendleft
Beispiel #15
0
def push_front(deque, x):
    deque.appendleft(x)
Beispiel #16
0
import sys

input = sys.stdin.readline

n = int(input())
lst = list(map(int, input().split()))
dp = [[1, 1] for i in range(n)]

for i in range(1, n):

    for j in range(i):
        if lst[i] > lst[j]:
            dp[i][0] = max(dp[i][0], dp[j][0] + 1)

max_size = max(dp)[0]
print(max_size)

for i in range(n):
    if max_size == dp[i][0]:
        x = i

from collections import deque

deque = deque()
for i in range(max_size):
    deque.appendleft(lst[x])
    x = dp[x][1]

for k in range(max_size):
    print(deque[k], end=' ')
Beispiel #17
0
# ecoding=utf-8
from collections import deque
import math

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
fruits.append('bestraway')
fruits.count('apple')
fruits.extend('abc')
# fruits.pop()
fruits.sort()
print(fruits)
# 队列
que = deque(["Eric", "John", "Michael"])
deque.popleft(que)
deque.appendleft(que, 'Bob')
que.append('Alan')
print(que)
# 列表创建
seq = []
for x in range(10):
    seq.append(x)

# 列表创建
seq1 = [x for x in range(10)]
seq2 = list(map(lambda x: x * 3, range(10)))
# 列表推导式
var = [(x, y) for x in [1, 2, 3] for y in [4, 5, 6] if x != y]
lst = []
for x in [1, 2, 3]:
    for y in [4, 5, 6]:
        if x != y:
Beispiel #18
0
    def update_one_pass(self, output, target, *args):
        """
        record the confusion matrix statistics for each label.
        average is done on the final metrics of all labels, not before
        :param output: PyTorch 0.3.1 Variables, [0-1]
        :param target: ditto
        :return:
        """
        if not self.test:
            assert (output <= 1).all()
            assert (output >= 0).all()
            for dequename, loss in zip(self.dequenames, args):
                assert (not isinstance(loss, Variable))
                deque = self.__getattribute__("running_" + dequename + "_loss")
                deque.appendleft(loss)

            positive = output.data.cpu().numpy()
            conditional_positive = target.data.cpu().numpy()
            true_positive = positive * conditional_positive
            true_negative = (1 - positive) * (1 - conditional_positive)
            conditional_negative = 1 - conditional_positive

            conditional_positive = conditional_positive.sum(0)
            true_positive = true_positive.sum(0)
            true_negative = true_negative.sum(0)
            conditional_negative = conditional_negative.sum(0)

            # self.positive[:,self.idx]=positive
            # self.negative[:,self.idx]=negative
            self.conditional_positives[:, self.idx] = conditional_positive
            self.conditional_negatives[:, self.idx] = conditional_negative
            self.true_positive[:, self.idx] = true_positive
            self.true_negative[:, self.idx] = true_negative

            batch_sensitivity = np.mean(true_positive /
                                        conditional_positive.clip(1e-8, None),
                                        axis=0)
            batch_specificity = np.mean(true_negative /
                                        conditional_negative.clip(1e-8, None),
                                        axis=0)
            batch_ROC = batch_sensitivity + batch_specificity

            assert ((batch_sensitivity >= 0).all())
            assert ((batch_sensitivity <= 1).all())
            assert ((batch_specificity >= 0).all())
            assert ((batch_specificity <= 1).all())
            assert ((batch_ROC >= 0).all())
            assert ((batch_ROC <= 2).all())
            self.idx += 1
            if self.idx == self.memory_len:
                self.idx = 0
                self.all = True

            return batch_sensitivity, batch_specificity, batch_ROC
        else:

            for dequename, loss in zip(self.dequenames, args):
                assert (not isinstance(loss, Variable))
                deque = self.__getattribute__("running_" + dequename + "_loss")
                deque.appendleft(loss)

            # during test time, no running stats is kept.
            assert (output <= 1).all()
            assert (output >= 0).all()
            assert (target <= 1).all()
            assert (target >= 0).all()
            output = output.detach().cpu().numpy()
            target = target.detach().cpu().numpy().astype(np.bool)
            output = np.expand_dims(output, axis=1)
            output = np.repeat(output, self.steps, axis=1)
            positive = output > self.ruler

            target_repeat = np.expand_dims(target, axis=1)
            target_repeat = np.repeat(target_repeat, self.steps, axis=1)

            true_positive = positive * target_repeat
            true_negative = np.invert(positive) * np.invert(target_repeat)
            false_positive = positive * np.invert(target_repeat)
            false_negative = np.invert(positive) * target_repeat

            true_positive = true_positive.sum(axis=0)
            true_negative = true_negative.sum(axis=0)
            false_positive = false_positive.sum(axis=0)
            false_negative = false_negative.sum(axis=0)

            conditional_positive = target.sum(axis=0)
            conditional_negative = np.invert(target).sum(axis=0)

            self.true_positive += true_positive
            self.conditional_positives += conditional_positive
            self.true_negative += true_negative
            self.conditional_negatives += conditional_negative

            self.false_positive += false_positive
            self.false_negative += false_negative

            self.idx += 1
 def appendleft(self, elem):
     if len(self) >= self._limit:
         self.pop()
     deque.appendleft(self, elem)
Beispiel #20
0
import sys
from collections import deque
input = sys.stdin.readline
N = int(input())
deque = deque()
for i in range(N):
    cmd = list(input().split())
    if cmd[0] == 'push_front':
        deque.appendleft(cmd[1])
    elif cmd[0] == 'push_back':
        deque.append(cmd[1])
    elif cmd[0] == 'pop_front':
        if deque:
            print(deque.popleft())
        else:
            print(-1)
    elif cmd[0] == 'pop_back':
        if deque:
            print(deque.pop())
        else:
            print(-1)
    elif cmd[0] == 'size':
        print(len(deque))
    elif cmd[0] == 'empty':
        if deque:
            print(0)
        else:
            print(1)
    elif cmd[0] == 'front':
        if deque:
            print(deque[0])
Beispiel #21
0
from collections import deque
import sys

deque = deque()
for i in range(int(input())):
    command = sys.stdin.readline().rstrip().split(" ")
    if command[0] == "push_front":
        deque.appendleft(command[1])

    elif command[0] == "push_back":
        deque.append(command[1])
    elif command[0] == "pop_front":
        if len(deque) == 0:
            print(-1)
        else:
            print(deque.popleft())
    elif command[0] == "pop_back":
        if len(deque) == 0:
            print(-1)
        else:
            print(deque.pop())
    elif command[0] == "size":
        print(len(deque))
    elif command[0] == "empty":
        if len(deque) == 0:
            print(1)
        else:
            print(0)
    elif command[0] == "front":
        print(deque[0] if len(deque) != 0 else -1)
    elif command[0] == "back":
    def appendleft(self,x):
    	deque.appendleft(self,x)
	if len(self[0])>0:
	    self[0].handle_head_of_queue()
Beispiel #23
0
# https://www.acmicpc.net/problem/1463

from sys import stdin
input = stdin.readline

from collections import deque
n = int(input())
deque = deque([1])
cnt_list = [n]*(n+1)
cnt_list[1]=0

while len(deque) > 0 :
	nextIndex = deque.pop()
	if nextIndex == n :
		break
	if cnt_list[nextIndex+1] > cnt_list[nextIndex]+1 :
		cnt_list[nextIndex+1] = cnt_list[nextIndex]+1
		deque.appendleft(nextIndex+1)
	try :
		if cnt_list[nextIndex*2] > cnt_list[nextIndex]+1 :
			cnt_list[nextIndex*2] = cnt_list[nextIndex]+1
			deque.appendleft(nextIndex*2)
		if cnt_list[nextIndex*3] > cnt_list[nextIndex]+1 :
			cnt_list[nextIndex*3] = cnt_list[nextIndex]+1
			deque.appendleft(nextIndex*3)
	except :
		pass
print(cnt_list[n])
Beispiel #24
0
def enqueue_first(deque, x):
    deque.appendleft(x)
Beispiel #25
0
"""
É uma lista de alta performance
"""

from collections import deque

deque = deque("Alex Pereira Maranhão")
print(deque)

# manipula tanto a ponto quanto o final da lista
deque.appendleft("J")
print(deque)

letra = deque.popleft()
print(deque)
print(letra)
Beispiel #26
0
 def appendleft(self, x):
     deque.appendleft(self, x)
     self.__size_sema.release()
Beispiel #27
0
# -*- coding: utf-8 -*-
__author__ = 'qylk'

from collections import deque

deque = deque((1, 2, 3, 4, 5), 5)
deque.append(6)
deque.appendleft(0)
deque.pop()  # 移出
deque.popleft()

print deque
#stack.append(1)     # 1 추가
#print("현재 스택 :",stack)
#stack.append(2)     # 2 추가
#print("현재 스택 :",stack)
#stack.pop()         #끝 원소 하나 제거
#print("현재 스택 :",stack)
#stack.pop()         #끝 원소 하나 제거
#print("현재 스택 :",stack, end="\n\n")

#queue=[]    #큐 선언
#print("현재 큐 :",queue)
#queue.append(1)     # 1 추가
#print("현재 큐 :",queue)
#queue.append(2)     # 2 추가
#print("현재 큐 :",queue)
#queue.pop(0)         #첫 원소 하나 제거
#print("현재 큐 :",queue)
#queue.pop(0)         #첫 원소 하나 제거
#print("현재 큐 :",queue)

from collections import deque  #데크 모듈 선언
deque = deque()
print("현재 데크 :", deque)
deque.append(1)  #오른쪽에 1 추가
print("현재 데크 :", deque)
deque.appendleft(2)  #왼쪽에 2 추가
print("현재 데크 :", deque)
deque.popleft()  #첫 번째 원소 제거
print("현재 데크 :", deque)
deque.pop()  #끝 원소 제거
print("현재 데크 :", deque)
Beispiel #29
0
 def appendleft(self, item):
     while len(self)>self._maxlen:
         self.pop()
     deque.appendleft(self, item)
 def insert_nth(deque, n, x):
     deque.rotate(-n)
     deque.appendleft(x)
     deque.rotate(n)
Beispiel #31
0
 def full_appendleft(self, item):
     if item in self:
         self.remove(item)
     else:
         self.pop()
     deque.appendleft(self, item)
 def appendleft(self, value):
     deque.appendleft(self, value)
     if len(self) > 100:
         self.pop()
stack.append(2)
stack.pop()

# 利用列表模拟一个队列
queue = []
queue.append(1)
queue.append(2)
queue.pop(0)

print('list = {}, set = {}, dict = {}, stack = {}, queue = {}'.format(list, set, dict, stack, queue))

# 使用双端队列操作队列或者栈
from collections import deque
deque = deque()
deque.append(1)
deque.appendleft(2)
deque.appendleft(3)
print(deque)
deque.pop()
print(deque)
deque.popleft()
print(deque)
print('-----------------------------------------------')


'''
字符串方法
center 使字符串处于一定区间内的居中位置,默认两边填充空格,也可以自定义填充
join 主要用于使用特定符号串联起一些值,是split的逆方法,常用于 linux 和 windows 的路径问题
split 以一个标志字符拆分
lower()/upper()/string.capwords(s) 转换成小写、大写、首字母大写
Beispiel #34
0
        if length == 0:
            print(-1)
        else:
            print(deque.pop())
            length -= 1
    elif command == 'size\n':
        print(length)
    elif command == 'empty\n':
        if length == 0:
            print(1)
        else:
            print(0)
    elif command == 'front\n':
        if length == 0:
            print(-1)
        else:
            print(deque[0])
    elif command == 'back\n':
        if length == 0:
            print(-1)
        else:
            print(deque[length - 1])
    elif command[5] == 'f':
        idx = command.index(' ')
        deque.appendleft(int(command[idx + 1:]))
        length += 1
    else:
        idx = command.index(' ')
        deque.append(int(command[idx + 1:]))
        length += 1
def append_all(x, deques):
    for deque in deques:
        deque.appendleft(x)
Beispiel #36
0
from sys import stdin
from collections import deque

tc = int(stdin.readline().rstrip())

deque = deque()
for _ in range(tc):
    order = stdin.readline().split()

    if order[0] == "push_back":
        deque.append(order[1])
    elif order[0] == "push_front":
        deque.appendleft(order[1])
    elif order[0] == "pop_front":
        if not deque:
            print(-1)
        else:
            print(deque.popleft())
    elif order[0] == "pop_back":
        if not deque:
            print(-1)
        else:
            print(deque.pop())
    elif order[0] == "size":
        print(len(deque))
    elif order[0] == "empty":
        if not deque:
            print(1)
        else:
            print(0)
    elif order[0] == "front":
Beispiel #37
0
 def appendleft(self, x):
     deque.appendleft(self, x)
     self.__size_sema.release()
#判断回文

from collections import deque

words=['RADAR','WARTER START','MILK KLIM','RESERVERED','IWI','ABBA']
i=0
for word in words:
    deque = deque([])
    for c in word:
        deque.appendleft(c)
        i+=1
    print(deque)
    for c in word:
        if c==deque.popleft() and i==len(deque):

            print(word+"is huiwen")
        else:
            print(word+"not huiwen")



    deque.clear()