content stringlengths 7 1.05M |
|---|
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def has_path(root, stack, x):
if not root:
return False
stack.append(root.val)
if root.val == x:
return True
if has_path(root.left, stack, x) or has_path(root.right, s... |
# 39.阅读一下代码他们的输出结果是什么?
def multi():
return [lambda x : i*x for i in range(4)]
print([m(3) for m in multi()])
# 输出的应该是
# [0,3,6,9]
# 正确答案是[9,9,9,9],而不是[0,3,6,9]产生的原因是Python的闭包的后期绑定导致的,这意味着在闭包中的变量是在内部函数被调用的时候被查找的,因为,最后函数被调用的时候,for循环已经完成, i 的值最后是3,因此每一个返回值的i都是3,所以最后的结果是[9,9,9,9]
|
def add(x, y):
return x + y
def sub(x, y):
return x - y
# as we implemented new multiply method is started showing error
# crashing our python project
# so testing in python is important
def multiply(x, y):
"""Function to perform multiply"""
return x * (-1 * y)
# return x * y
def division(x, y... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
# O(h) time | O(h) space - where h is the height of tree
def deleteNode(self, root: Optional[TreeNode], ... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
self.nodes_sorted = []
self.index = -1
... |
class Solution:
def isValidSequence(self, root: TreeNode, arr: List[int]) -> bool:
if len(arr) == 1:
return root and root.val == arr[0] and not root.left and not root.right
if not root or root.val != arr[0]:
return False
return self.isValidSequence(root.left, arr[1:])... |
#import osgeo._gdal
#import osgeo._gdalconst
#import osgeo._ogr
#import osgeo._osr
#import osgeo
#import gdal
#import gdalconst
#import ogr
#import osr
#
#cnt = ogr.GetDriverCount()
#for i in xrange(cnt):
# print ogr.GetDriver(i).GetName()
#
#import os1_hw
pass
|
class Solution:
def numberOfSteps(self, ans: int) -> int:
steps = 0
while ans != 0:
if ans % 2 == 0:
ans = ans / 2
steps += 1
else:
ans -= 1
steps += 1
return steps
|
class MaxStack:
def __init__(self):
# do intialization if necessary
self.St = []
self.maxSt = []
"""
@param: number: An integer
@return: nothing
"""
def push(self, x):
# write your code here
self.St.append(x)
if not self.maxSt or x >= sel... |
"""
This state module is used to manage Wordpress installations
:depends: wp binary from http://wp-cli.org/
"""
def __virtual__():
if "wordpress.show_plugin" in __salt__:
return True
return (False, "wordpress module could not be loaded")
def installed(name, user, admin_user, admin_password, admin_e... |
SEQUENCE = [
'webhooktarget_extra_state',
'webhooktarget_extra_data_null',
'manytomanyfield_rm_null',
]
|
# https://www.codewars.com/kata/5868b2de442e3fb2bb000119
def closest(strng):
if not strng:
return []
arr = [i for i in strng.split()]
arr_num = []
for i in arr:
sum_num = 0
for j in i:
sum_num += int(j)
arr_num.append(sum_num)
arr = [int(i) for i in arr]
... |
#
# PySNMP MIB module PCSYSTEMSMIF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PCSYSTEMSMIF-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:37:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
# output: ok
count = 0
total = 0
last = 0
for i in (1, 2, 3):
count += 1
total += i
last = i
assert count == 3
assert total == 6
assert last == 3
count = 0
total = 0
last = 0
i = 1
while i <= 3:
count += 1
total += i
last = i
i += 1
assert count == 3
assert total == 6
assert last == 3
cou... |
"""
A module implementing package-specific exceptions
"""
class OutputValidationError(Exception):
""" This exception is raised whenever there is something wrong with the submitted output
""" |
"""
Tower of Hanoi
Problem:
Given three rods and disks
The objective of the puzzle is to move the
entire stack of disks to another rod.
The following rules needs to be followed:
*Only one disk can be moved at a time.
*Each move consists of taking the upper disk from one of the stacks and placing it on top
... |
ix.enable_command_history()
ix.api.SdkHelpers.create_shading_layer_for_items_selected(ix.application, 3)
ix.disable_command_history() |
# If we list all the natural numbers below 10 that are multiples
# of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
if __name__ == "__main__":
numbers = [ n for n in range(1,1000) if n % 3 == 0 or n % 5 == 0 ]
print(sum(numbers))
|
class Solver:
def __init__(self, cells):
self.cells = cells
def determine_cell_possibilities(self):
for cell in self.cells:
candidates = list(range(1, 10))
for association in cell.get_unique_associations():
if association.number is not None:
if association.number in candidates... |
n = int(input())
arr = []
i = list(map(int, input().split()))
arr = list(range(i[0], i[1]+1))
for each in range(n - 1):
i = list(map(int, input().split()))
for c,every in enumerate(arr):
if every < i[0]:
arr[c] = -1
elif every > i[1]:
arr[c] = -1
if sum(arr) == (-1*len(ar... |
# __author__ = 'tusharmakkar08'
class Wallet:
def __init__(self):
self.amount = 0 # TODO: get init amount on the basis of user name from db
def load_money(self, amount):
self.amount += amount
def deduct_money(self, amount):
self.amount -= amount
def get_money(self):
... |
r_TPC = 0.664
r_FSWires = 0.668
r_FSGuards = 0.680
path_main = '/dali/lgrandi/peres/efieldsim/'
path_cache = path_main + 'cache/'
path_root_files = path_main + '/solved_outputs/EField_SR0/' |
# The following is used as a global constant to represent
# the contribution rate.
CONTRIBUTION_RATE = 0.05
def main():
gross_pay = float(input('Enter the gross pay: '))
bonus = float(input('Enter the amount of bonuses: '))
show_pay_contrib(gross_pay)
show_bonus_contrib(bonus)
# The show_pay_contrib f... |
class Water:
i = 1
def __add__(self, other):
if Water.i + other.i == 3:
return 'Шторм'
elif Water.i + other.i == 4:
return "Пар"
elif Water.i + other.i == 5:
return 'Грязь'
class Wind:
i = 2
def __add__(self, other):
if Wind.i + other... |
'''
Created on 1.12.2016
@author: Darren
''''''
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,... |
def test_create_stat_table():
pass
def test_get_latest_successful_ts():
pass
def test_update_latest_successful_ts():
pass
|
books = int(input("How many books do you want to buy? "))
amount = int(input("How much do you have? "))
amount_required = 100
if books == amount_required > amount:
print("you can purchase the books")
else:
print("You donot have sufficient funds to buy the books")
print(f"You will need {amount} to buy the book... |
class i18n(object):
def __init__(self):
# Default domain
self._domain = 'idn'
def domain(self, country):
self._domain = country
def translate(self, domain):
dic = {}
dic['idn'] = {
# Month
'Januari': 'January',
'Februari': 'Febru... |
#
# @lc app=leetcode.cn id=1700 lang=python3
#
# [1700] minimum-deletion-cost-to-avoid-repeating-letters
#
None
# @lc code=end |
"""Rules to load archives for Bazel plugins."""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def rules_docker_archives(version, sha256):
http_archive(
name = "io_bazel_rules_docker",
sha256 = sha256,
strip_prefix = "rules_docker-%s" % version,
urls = ["https... |
""" Implementaçao do algoritmo de busca sequencial com recursão """
def busca_sequencial(valor, lista, index):
"""Busca sequencial recursiva.
Returns:
Retorna o indice do valor na lista.
Se nao encontrar retorna -1.
"""
if len(lista) == 0 or index == len(lista):
return -1
if lista... |
'''
Created on 2009-09-16
@author: beaudoin
A Python version of the C++ Observable class found in Utils
'''
class Observable(object):
def __init__(self):
self._observers = []
self._hasChanged = False
self._batchChangeDepth = 0
def setChanged(self):
"""Protected.... |
#
# Code property of Jared Scarito
#
testCases = int(input())
outCases = []
for i in range(testCases):
weights = []
dataSet = str(input())
case = dataSet.split(" ")[0]
maxWeight = int(dataSet.split(" ")[1])
for weightIndex in range(len(dataSet.split(" "))):
if int(weightIndex) > 1:
... |
SMS_setting = {
'secretId':'',
'secretKey':'',
'req_Appid':'',
'req_Sign':'',
'req_SessionContext':'',
'req_NumberSet':[],
'req_TemplateID':'',
'req_TemplateParmSet':[],
}
|
LEFT = 0
UP = 1
RIGHT = 2
DOWN = 3
vectors = [(-1, 0), (0, 1), (1, 0), (0, -1)]
class Laser:
def __init__(self, board, x, y):
self.board = board
class Board:
def __init__(self, size):
self.size = size
self.real = [[False for _ in range(size)] for _ in range(size)]
def set_mirro... |
#!/usr/bin/env python3
# Based on the code in
# https://www.cs.princeton.edu/courses/archive/spr09/cos333/beautiful.html
# by Rob Pike.
def match(regexp, text):
if regexp and regexp[0] == '^':
return match_here(regexp[1:], text)
while text:
print('\nmatch({!r}, {!r})'.format(regexp, text))
... |
expected_output = {
'socket_connections': {
'total_socket_connections': 4,
'sockets_in_listen_state': ['Tunnel1-head-0', 'Tunnel2-head-0', 'Tunnel3-head-0', 'Tunnel20-head-0'],
'Tu1': {
'peers': {
'remote_ip': '10.0.0.2',
'local_ip': '85... |
x = input('Digite algo: ')
print('tipo de dado: {}'.format(type(x)))
print('Possui apenas espaços:: {}'.format(x.isspace()))
print('É numérico: {}'.format(x.isnumeric()))
print('É alfabético: {}'.format(x.isalpha()))
print('É alfanumérico: {}'.format(x.isalnum()))
print('Tem apenas letras maiúsculas: {}'.format(x.isup... |
# A simple way to resolve the palindrome problem
# Note: this example does not deal with punctuation
def is_palindrome(content):
processed_content = ''.join(content.lower().split())
return processed_content == processed_content[::-1]
if __name__ == '__main__':
assert is_palindrome('ovo')
assert is_p... |
def list_function(x):
return x
n = [3, 5, 7]
print(list_function(n))
|
t = int(input())
for i in range(t):
n = int(input())
m = n-1
arr = []
# print(arr)
uparr = list(range(1,n)) + list(range(n-1,0,-1))
down = 2
up = 0
# print(uparr)
start = 1
for j in range(n):
if j>0:
start += down
down += 1
temp = []
... |
def sum(a , b):
return a + b
def getAllData():
listOfCategory = [
{
'id': 1,
'cat_name': 'Cell phone',
'products': [
{
'product_id': 1,
'product_name': 'iPhone 12 Pro Max'
},
{
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 23 14:42:54 2016
@author: ktritz
"""
def currentshot(self):
return self._connections[0].get('current_shot("nstx")').value
|
# Marcelo Campos de Medeiros
# ADS UNIFIP
# REVISÃO DE PYTHON
# AULA 18 Variáveis Composta Listas 2° parte---> GUSTAVO GUANABARA
'''
Faça um programa que o usuário possa digitar sete valores númericos e cadastre-os em uma lista única
que matenha separados os valores pares e ímpares.
No final moste os valores pares e ... |
"""
Interface Segregation Principle
Make fine grained interfaces that are client specific Clients should not be
forced to depend upon interfaces that they do not use. This principle deals
with the disadvantages of implementing big interfaces.
Let’s look at the below IShape interface:
"""
class IShape:
def draw_... |
if __name__ == "__main__":
"""
('f', 'f', 'f')
('l', 'l', 'l')
('o', 'o', 'i')
('w', 'w', 'g')
"""
nums = ['flower','flow','flight'] # each string is regarded as a tuple
for i in zip(*nums):
print(i)
"""
The list elements are connected in sequence
"""
l = ['a', '... |
# Book03.py
# Book : title, author, price
class Book :
def __init__(self,*args):
self.title = '무제' if len(args)<1 else args[0]
self.author = '작자미상' if len(args)<2 else args[1]
self.price = 0 if len(args)<3 else args[2]
def pBook(self):
print(self.title,self.author,self.price)
b1... |
class MULT18X18():
def __init__(self, clk=True, site=None, **kwargs):
self.inst = inst("MULT18X18SIO", site, **kwargs)
self.setcfgs({
"AREG": "0",
"BREG": "0",
"B_INPUT": "DIRECT",
"CEAINV": "CEA",
"CEBINV": "CEB",
"CEPINV": "... |
# NBA Game Predictor
# File: baseline.py
# Authors: Tarmily Wen & Andrew Petrosky
#
# A baseline predictor based purely of winning percentage
def model(train_x, train_y, test_x, test_y):
# Train test
print("Testing on training data...")
correct = 0.0
total = 0.0
for i in range(len(train_x)):
... |
def name_file(fmt, nbr, start):
if not isinstance(nbr, int) or not isinstance(start, int) or nbr <= 0:
return []
filename = fmt.replace('<index_no>', '{0}').format
return [filename(a) for a in xrange(start, start + nbr)]
|
# import numpy as np
def add(x, y):
"""
This function sums up two numbers.
Parameters
----------
x : float
The first number to be added.
y : float
The second number to be added.
Returns
-------
sum : float
The sum of x and y.
"""
sum = x + y
ret... |
SHARD_COUNT = 2**10 # 1024
EPOCH_LENGTH = 2**6 # 64 slots, 6.4 minutes
TARGET_COMMITTEE_SIZE = 2**8 # 256 validators
|
class Stack:
'''Visual FX Stack'''
def __init__(self, layers=[]):
self.layers = layers
def apply(self, frame):
'''Return the frame with the fx layers applied.'''
output = frame.copy()
for layer in self.layers:
if layer.active:
output = layer.app... |
class Solution:
def searchRange(self, nums: list[int], target: int) -> list[int]:
first,last = -1,-1
def search(lo,hi):
nonlocal first,last
if nums[lo]<=target<=nums[hi]:
mid = (lo+hi)//2
if nums[mid]==target:
if fi... |
regions = {'jp': 'amazon.co.jp',
'uk': 'amazon.co.uk',
'de': 'amazon.de',
'eu': 'amazon.co.uk',
'us': 'amazon.com',
'na': 'amazon.com'}
|
""" Exception classes for panzer """
class PanzerError(Exception):
""" base class for all panzer exceptions """
pass
class SetupError(PanzerError):
""" error in the setup phase """
pass
class BadASTError(PanzerError):
""" malformatted AST encountered (e.g. C or T fields missing) """
pass
cla... |
# coding: utf-8
n, m = [int(i) for i in input().split()]
d = {}
for i in range(m):
tmp = input().split()
d[tmp[0]] = tmp[1]
s = input().split()
for i in range(n):
if len(s[i])>len(d[s[i]]):
s[i] = d[s[i]]
print(' '.join(s))
|
#MergeSort.py
# 20 Oct 2017
#written by Amin dehghan
#DS & Algorithms With Python
def merge(seq,start,mid,stop):
lst=[]
i=start
j=mid
while i<mid and j<stop:
if seq[i]<seq[j]:
lst.append(seq[i])
i+=1
else:
lst.append(seq[j])
j+=1
... |
class ReactionZone:
"""
Store a block of 9 reactions.
"""
def __init__(self, indexes, reactions_array):
self.reactions_array = reactions_array
self.contained_indexes = indexes
def getFields(self):
list_of_fields = []
for index in self.contained_indexes:... |
"""[ 11 - Classe carro: Implemente uma classe chamada Carro com as seguintes propriedades:
a - Um veículo tem um certo consumo de combustível (medidos em km / litro) e uma certa quantidade de combustível no tanque.
b - O consumo é especificado no construtor e o nível de combustível inicial é 0.
c - Forneça um método a... |
"""Student data in a dictionary"""
student = {}
for i in range(3):
name = input("Enter name: ")
age = input("Enter age: ")
reg = input("Enter registration number: ")
student[name] = f"{age}, {reg}"
dict(student)
print(student) |
# A Dynamic Programming based Python Program for the Egg Dropping Puzzle
INT_MAX = 32767
# Function to get minimum number of trials needed in worst
# case with n eggs and k floors
def eggDrop(n, k):
# A 2D table where entery eggFloor[i][j] will represent minimum
# number of trials needed for i eggs and j flo... |
def my_map(transformation_function, sequence):
for elt in sequence:
yield transformation_function(elt)
powers_of_two = my_map(lambda x: x**2, range(1,11))
print(powers_of_two)
print(next(powers_of_two))
print(list(powers_of_two)) |
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return f'{self.value}'
class Stack:
def __init__(self):
self.top = None
self.bottom = None
self.length = 0
def isEmpty(self):
return self.top == Non... |
print("""
065) Crie um programa que leia vários números inteiros pelo teclado.
No final da execução mostre a média entre todos os valores e qual foi
o maior e o menor valores lidos. O programa deve perguntar ao usuário
se ele quer ou não continuar a digitar valores.
""")
maior = menor = soma = contador = 0
condicaoDeP... |
#
# PySNMP MIB module HPN-ICF-LswQos-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-LswQos-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:27:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
# 选择排序
def swap(arr, l, r):
temp = arr[l]
arr[l] = arr[r]
arr[r] = temp
def selectSort(arr):
"""选择排序"""
end = len(arr)-1
minindex = 0
while end >0:
for i in range(minindex, len(arr)):
if arr[minindex] > arr[i]:
swap(arr, i , minindex)
minind... |
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
self.bt(nums, [], res)
return res
def bt(self, nums, tempList, res):
if len(tempList) == len(nums):
res.append(tempList)
return
for i in range(len(nums)):
... |
"""Learners"""
NAME = "Model"
DESCRIPTION = "Prediction."
BACKGROUND = "#FAC1D9"
ICON = "icons/Category-Model.svg"
PRIORITY = 4
|
"""
Specification of canopies
"""
class Canopy(object):
def __init__(self, **kwargs):
self.d = kwargs.get('d', None)
self._check()
def _check(self):
assert self.d is not None, 'Vegetation height needs to be given'
class OneLayer(Canopy):
"""
define a homogeneous one layer ca... |
def bubble_sort(alist):
for _ in range(len(alist)-1,0,-1):
for i in range(_):
if alist[i] > alist[i+1]:
alist[i+1],alist[i] = alist[i],alist[i+1]
return alist
print(bubble_sort([1,4,2,3,9,0]))
|
(n, k) = map(int, input().split())
cnt = 0
arr = [0 for _ in range(0, n + 1)]
for i in range(2, n + 1):
for j in range(i, n + 1, i):
if arr[j] != 0:
continue
arr[j] = 1
cnt += 1
if cnt == k:
print(j)
exit(0) |
a = int(input(">> "))
if a%3 == 0:
if a%7 == 0:
print("3と7の両方で割り切れる")
else:
print("3のみで割り切れる")
else:
if a%7 == 0:
print("7のみで割り切れる")
else:
print("3でも7でも割り切れない") |
def strangeCounter(t):
initial = 3
j = 3 + 1
time = 0
while True:
time += 1
j -= 1
if t > time -1 + initial:
time += initial -1
initial = initial * 2
j = initial + 1
continue
return j - (t - time)
if __name__ =... |
'''
Description: exercise: day old bread
Version: 1.0.1.20210114
Author: Arvin Zhao
Date: 2021-01-13 06:12:15
Last Editors: Arvin Zhao
LastEditTime: 2021-01-14 03:49:47
'''
def print_receipt(loaf_num: int, regular_per_price: float, discount_rate: float) -> None:
'''
Calculate and print the regular price for lo... |
{
"includes": [
"../../common.gypi"
],
'target_defaults': {
'default_configuration': 'Release',
'cflags':[
'-std=c99'
],
'configurations': {
'Debug': {
'defines': [ 'DEBUG', '_DEBUG' ],
},
'Release': {
'defines': [ 'NDEBUG' ],
}
},
'conditions'... |
#!/usr/bin/python3
""" This challenge is as follows:
Given an int n, return the absolute difference
between n and 21, except return double the
absolute difference if n is over 21.
Expected Results:
19 -> 2
10 -> 11
21 -> 0 """
def diff21(n):
# This part is where the challen... |
# HeadModel
# 得到<head>中需要用到的CSS样式表和JavaScript脚本文件的路径
# CSS
css_path = '/static/css/'
css_files = [
'frameworks.css',
'github.css',
'basic.css',
'editor.css',
]
def getCSS():
return [css_path + css_file for css_file in css_files]
# JS
js_path= '/static/javascript/'
js_files = [
'basic.js',
]
... |
data = [
["Total Bill","Tip","Payer Gender","Payer Smoker","Day of Week","Meal","Party Size"],
[16.99,1.01,"Female","Non-Smoker","Sunday","Dinner",2],
[10.34,1.66,"Male","Non-Smoker","Sunday","Dinner",3],
[21.01,3.5,"Male","Non-Smoker","Sunday","Dinner",3],
[23.68,3.31,"Male","Non-Smoker","Sunday","Dinner",2],
[24.59,3... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:... |
# !/usr/bin/env python3
# -*- encoding: utf-8 -*-
if __name__ == "__main__":
month = int(input("Enter a month: "))
year = int(input("Enter a year: "))
if month < 1 or month > 12:
print("Недопустимое значение month")
else:
if month == 2:
if (year % 4 == 0 and year... |
discord_token = 'NDQyNTQ3OTY0MDI0NzE3MzEy.DdAacQ._iDLpBSxzKb8T5rZDh4De9A1sXc'
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0'
goat_url = 'https://2fwotdvm2o-dsn.algolia.net/1/indexes/ProductTemplateSearch/query'
stockx_url = 'https://xw7sbct9v6-dsn.algolia.net/1/inde... |
lista=[]
for i in range(1,101):
if(i%7!=0):
lista.append(i)
print(lista)
|
class Solution:
"""
@param nums: A list of integer which is 0, 1 or 2
@return: nothing
给定一个包含红,白,蓝且长度为 n 的数组,将数组元素进行分类使相同颜色的元素相邻,并按照红、白、蓝的顺序进行排序。
我们可以使用整数 0,1 和 2 分别代表红,白,蓝。
Example
样例 1
输入 : [1, 0, 1, 2]
输出 : [0, 1, 1, 2]
解释 : 原地排序。
"""
def sortColors(self, nums):
# write your code... |
def fizz_buzz(fizz, buzz, highest):
result = []
for i in range(1, highest + 1):
letter = ''
# If divisible by fizz or buzz, add F or B appropriately.
if i % fizz == 0:
letter += 'F'
if i % buzz == 0:
letter += 'B'
# If neither F or B has been la... |
# -*- encoding: utf-8 -*-
'''
@project : LeetCode
@File : MaxQueue.py
@Contact : 9824373@qq.com
@Desc :
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
示例 1:
输入:
["MaxQueue... |
""" Implements some convenience logic for specifying item embedding dependencies.
In the context of invalidation scope, it is imperative that we embed all fields used in
default embeds (display_title). The hope is DependencyEmbedder will make it easy to do so, allowing
one to specify the dependencies in onl... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
maxProfit = 0
minValue = 10**5
for price in prices:
minValue = min(price, minValue)
maxProfit = max(price - minValue, maxProfit)
return maxProfit |
steps = []
def do_action(name):
steps.append(name)
WAREHOUSE_PHONE = '<phone number here e.g. +44712345678>'
SECRET_CODE = '<paste here>'
def handle_purchase():
"""
Here are the actions you can trigger:
calculate_price - Calculates total cost of the order
check_inventory - Checks that th... |
class Node:
def __init__(self, element):
self.item = element
self.next_link = None
self.prev_link = None
class DoubleLinkedList:
def __init__(self):
self.first_node = None
def is_empty(self):
if self.first_node is None:
print("Error! The list is empty!"... |
#Ejercicio 9-5 -----------------------------------------------------------------
class user:
def __init__(self, first_name, last_name, semester, collage):
self.first_name = first_name
self.last_name = last_name
self.semester = semester
self.collage = collage
self.access = 0
... |
"""
Pops the gear onto the peg. Uses solenoids.
"""
class GearSol(object):
def __init__(self, sol):
self.sol = sol
def run(self, trigger):
if (trigger == True):
self.sol.set(self.sol.Value.kForward)
else:
self.sol.set(self.sol.Value.kReverse)
|
# Import the library that makes it easier to write context managers
# Implement a context manager that writes to a text file
# using a class:
class MyContextManager:
pass
# Implement a context manager using a method with a decorator
def my_context_manager():
raise Exception("Method not implemented")
def c... |
# Дано предложение. Определить порядковые номера первой пары одинаковых
# соседних символов. Если таких символов нет, то должно быть напечатано
# соответствующее сообщение.
s = input("Введите предложение: ")
# Порядковые номера
rep1 = 0
rep2 = 0
# Проходит по всем символам в предложении
for i in range(1, len(s)):
... |
# items implementation
class Item:
def __init__(self, item_name, item_description):
self.item_name = item_name
self.item_description = item_description
def __str__(self):
return '%s, %s' % (self.item_name, self.item_description)
|
# tiles
ONE_MAN = 0
TWO_MAN = 1
THREE_MAN = 2
FOUR_MAN = 3
FIVE_MAN = 4
SIX_MAN = 5
SEVEN_MAN = 6
EIGHT_MAN = 7
NINE_MAN = 8
ONE_PIN = 9
TWO_PIN = 10
THREE_PIN = 11
FOUR_PIN = 12
FIVE_PIN = 13
SIX_PIN = 14
SEVEN_PIN = 15
EIGHT_PIN = 16
NINE_PIN = 17
ONE_SOU = 18
TWO_SOU = 19
THREE_SOU = 20
FOUR_SOU = 21
FIVE_SOU = 22
S... |
garden_waitlist = ["Jiho", "Adam", "Sonny", "Alisha"]
garden_waitlist[1] = "Calla"
garden_waitlist[-1] = "Alex"
print(garden_waitlist)
|
string = input()
# string = 'Привет'
i = 0
while i < len(string):
print(string[i])
i += 1
|
#!/usr/bin/env python
# coding: utf-8
# p676
class MagicDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self._words = dict() # type: dict[int, list[str]]
def buildDict(self, dict):
"""
Build a dictionary through a list of words
... |
def one2two(digit):
if len(digit) == 1:
return "0" + digit
else:
return digit
def result(pt, st):
rt = ""
second, minute, hour = 0, 0, 0
sc, mc = 0, 0
if st[2] - pt[2] >= 0:
second = st[2] - pt[2]
else:
second = st[2] - pt[2] + 60
sc = 1
if st[... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.