content stringlengths 7 1.05M |
|---|
class Solution:
def canCompleteCircuit(self, gas, cost):
sum = 0
total = 0
start = 0
for i in range(len(gas)):
total += (gas[i] - cost[i])
if sum < 0:
sum = gas[i] - cost[i]
start = i
else:
sum += (ga... |
"""
Author: Xavid Ramirez
Email: xavid.ramirez01@utrgv.edu
Date: November 2, 2016
Desc: Hamming word encoding and decoding program. The python program
Will take either a set of bits to encode or decode. Encode will
encode the bits into Hamming Encoding. Decoding will check the
given bits, check the par... |
def encrypt(text,s):
result = ""
# transverse the plain text
for i in range(len(text)):
char = text[i]
# Encrypt uppercase characters in plain text
if (char.isupper()):
result += chr((ord(char) + s-65) % 26 + 65)
# Encrypt lowercase characters in plain text
... |
def amount_of_elements_smaller(matrix, i, j):
'''Count the amount of elements smaller than m[i][j] in the (square) matrix.
Each column and row is sorted in ascending order.
>>> amount_of_elements_smaller([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 1, 1)
4
'''
size = len(matrix)
assert size == len(ma... |
class FieldTypeError(Exception):
"""Value has wrong datatype"""
pass
class ToManyMatchesError(Exception):
"""Found multiple Nodes instead of one."""
pass
class DoesNotExist(Exception):
"""Object Does not exist."""
pass
class RelationshipMatchError(Exception):
"""Err with Relationships.... |
# print('~~~~~~~~~~~~~我爱鱼C工作室~~~~~~~~~~~~~~~~')
# temp=input("不妨猜一下小甲鱼想的数字:")
# guess=int(temp)
# if guess == 8:
# print("卧槽,你是蛔虫吗")
# print("哼,猜中也没有奖励")
# else:
# print("猜错了,现在想的是8")
# print("游戏结束,不玩了")
# teacher='小甲鱼'
# print(teacher)
# teacher='老甲鱼'
# print(teacher)
# first=3
# second=8
# third=first+se... |
# coding: utf-8
# __The Data Set__
# In[1]:
r = open('la_weather.csv', 'r')
# In[2]:
w = r.read()
# In[3]:
w_list = w.split('\n')
# In[4]:
weather = []
for w in w_list:
wt = w.split(',')
weather.append(wt)
weather[:5]
# In[5]:
del weather[0]
# In[6]:
col_weather = []
for w in weather:
... |
URL_CONFIG ="www.python.org"
DEFAULT_VALUE = 1
DEFAULT_CONSTANT = 0
|
class Solution:
def reverse(self, x: int) -> int:
negative = x<0
x = abs(x)
reversed = 0
while x!= 0:
reversed = reversed*10 + x%10
x //= 10
if reversed > 2**31-1:
return 0
return reversed if not negative else... |
""" modules for income tax """
# import datetime
class TaxReturn:
""" Tax return class """
def hello(self, x):
print("hello ", x)
print("Hi")
taxreturn = TaxReturn()
taxreturn.hello("monkey")
|
# type: ignore
__all__ = [
"meshc",
"barh",
"trisurf",
"compass",
"isonormals",
"plotutils",
"ezcontour",
"streamslice",
"scatter",
"rgb2ind",
"usev6plotapi",
"quiver",
"streamline",
"triplot",
"tetramesh",
"rose",
"patch",
"comet",
"voronoi",... |
#!/usr/bin/python
print('Hello Git!')
print("Nakano Masaki")
|
a = [int(x) for x in input().split()]
a.sort() #this command sorts the list in ascending order
if a[-2]==a[-1]:
print(a[-3]+a[1])
else:
print(a[-2] + a[1])
|
N, A, B = map(int, input().split())
def f(a, b):
return [
p
for p in [
N - i * a + j
for i in range(
1,
N // a + 1 if N % a > b - N // a else
N // a
)
for j in range(1, a + 1)
] +
[
... |
# The MessageQueue class provides an interface to be implemented by classes that store messages.
class MessageQueue(object):
# add a single message to the queue
def add(self, folder_id, folder_path, message_type, parameters=None, sender_controller_id=None, sender_user_id=None, timestamp=None):
pass
... |
info = open("phonebook.txt", "r+").readlines()
ph = {}
for i in range(len(info)):
word = info[i].split()
ph[word[0]]=word[1]
for i in sorted(ph.keys()):
print(i,ph[i]) |
print("Welcome to the roller coaster!")
height = int(input("What is your height in cm? "))
canRide = False
if height > 120:
age = int(input("What is your age in years? "))
if age > 18:
canRide = True
else:
canRide = False
else:
canRide = False
if canRide:
print('You can r... |
class Pilot:
current_job = 'Pilot'
def __init__(self, name):
self.name = name
def say_hallo(self):
print(f'My name... {self.name}')
class CosmonautPilot(Pilot):
current_job = 'Cosmonaut'
previous_job = 'Pilot'
class GieroyCosmonautPilot(CosmonautPilot):
status = 'Gieroy'
... |
#
# PySNMP MIB module MYLEXDAC960SCSIRAIDCONTROLLER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MYLEXDAC960SCSIRAIDCONTROLLER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:06:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using P... |
n = int(input('Informe um número entre 0 e 9999: ').strip())
u = n // 1 % 10
d = n // 10 % 10
c = n // 100 % 10
m = n // 1000 % 10
print(f'Analisando o número {n}...')
print('Unidade: {}'.format(u))
print('Dezena: {}'.format(d))
print('Centena: {}'.format(c))
print('Milhar: {}'.format(m))
|
class GCodeSegment():
def __init__(self, code, number, x, y, z, raw):
self.code = code
self.number = number
self.raw = raw
self.x = x
self.y = y
self.z = z
self.has_cords = (self.x is not None or self.y is not None or self.z is not None)
if self.has... |
print('Welcom to the Temperature Conventer.')
fahrenheit = float(input('\nWhat is the given temperature in Fahrenheit degrees? '))
celsius = (fahrenheit - 32) * 5 / 9
celsius = round(celsius, 4)
kelvin = (fahrenheit + 569.67) * 5 / 9
kelvin = round(kelvin, 4)
print('\nThe given temperature is equal to:')
print('\nFahr... |
StageDict = {
"welcome":"welcome",
"hasImg":"hasImg",
"registed":"registed"
} |
n = int(input('digite um numero: '))
dobro = int(n*2)
triplo = int(n*3)
raiz = float(n**(1/2))
print('O dobro de {} é {}, o triplo é {} e a raiz é {:.2f}'.format(n, dobro, triplo, raiz))
'''n = int(input('digite um numero: '))
mul = n*2
tri = n*3
rai = n**(1/2)
print('o dobro de {} é {}, o triplo é {} e a raiz quad... |
'''
В школе решили набрать три новых математических класса.
Так как занятия по математике у них проходят в одно и то же время,
было решено выделить кабинет для каждого класса и купить в них
новые парты. За каждой партой может сидеть не больше двух учеников.
Известно количество учащихся в каждом из трёх классов. Сколько... |
# -*- coding: utf-8 -*-
class CookieHandler(object):
"""This class intends to Handle the cookie field described by the
OpenFlow Specification and present in OpenVSwitch.
Cookie field has 64 bits. The first 32-bits are assigned to the id
of ACL input. The next 4 bits are assigned to the op... |
#-*- coding: utf-8 -*-
def getAdjacentes(qtde_v, MATRIZ):
"""Método getAdjacentes p/ pegar os adjacentes do Grafo"""
aMATRIZ = []
for i in range(qtde_v):
linha = []
for j in range(qtde_v):
if MATRIZ[i][j] == 1:
linha.append("v" + str(j))
aMATRIZ.append(l... |
# Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project au... |
n1 = int(input('Digite um número: '));
antecessor = n1 - 1;
sucessor = n1 + 1;
print('O antecessor do número {}, é: {}, e seu sucessor é: {}.'.format(n1, antecessor, sucessor));
|
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
i = 0
while i < len(nums):
if nums[i] == val: nums.pop(i)
else: i += 1
return len(nums) |
class Base():
"""
This class represents the base variation of the game upon which other variations can be
built, utilizing the functionalities of this class.
If the superclass does not override all of these functions in this class, an error is
thrown.
"""
def __init__(self, players):
... |
class Animal:
def __init__(self, nombre):
self.nombre = nombre
def dormir(self):
print("zZzZ")
def mover(self):
print("caminar")
class Sponge(Animal):
def mover(self):
pass
class Cat(Animal):
def hacer_ruido(self):
print("Meow")
class Fish(Animal):
d... |
{
'targets': [
{
'target_name': 'ftdi_labtic',
'sources':
[
'src/ftdi_device.cc',
'src/ftdi_driver.cc'
],
'include_dirs+':
[
'src/',
],
'conditions':
[
['OS == "win"',
{
'include_dirs+':
[
... |
def print_head(msg: str):
start = "| "
end = " |"
line = "-" * (len(msg) + len(start) + len(end))
print(line)
print(start + msg + end)
print(line)
|
load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies")
load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies", "go_repository")
def rpmpack_dependencies():
go_rules_dependencies()
go_register_toolchains()
gazelle_dependencies()
go_repository(
name = "com_g... |
#Faça um programa para a leitura de duas notas parciais de um aluno.
#O programa deve calcular a média alcançada por aluno e apresentar:
#A mensagem "Aprovado", se a média alcançada for maior ou igual a sete;
#A mensagem "Reprovado", se a média for menor do que sete;
#A mensagem "Aprovado com Distinção", se a média for... |
class FiltroRecurso():
""" Representa um filtro de recurso que pode conter:
Nome, Tipo, Localização e Intervalos
"""
def __init__(self, nome, tipo, local, intervalos):
self.nome = nome
self.tipo = tipo
self.local = local
self.intervalos = intervalos
def atende(self,... |
class Dict(dict):
"""
内置dict方法的扩展
增加gets方法
传入以 逗号 “,” 为分隔符的多个key组成的字符串,或者多个key组成的列表或元组或集合,返回第一个有值的key对应的value
若需查找的key中本身有含有逗号 "," 则建议直接使用 get 方法
意义是寻找动态json中可能存在的值
例如:
新建字典:
d = Dict()
d["a"] = 1
d["c"] = 5
print(d.gets("a")) --> 1
print(d.gets("c,b,a")) --> 5
... |
#rekursif adalah fungsi yg memanggil dirinya sendiri ok sip
def cetak(x):
print(x)
if x>1:
cetak(x-1)
elif x<1:
cetak(x+1)
cetak(5)
|
def more_zeros(s):
s = "".join(dict.fromkeys(s)) # Getting rid of the duplicates in order
s2 = [bin(ord(i))[2:] for i in s]
s2 = [len(i)>2*i.count('1') for i in s2]
return [i for j, i in enumerate(s) if s2[j]]
print(more_zeros("DIGEST"))
|
tc = int(input())
while tc:
tc -= 1
n, k = map(int, input().split())
if k > 0:
print(n%k)
else:
print(n) |
arr = list(map(int,input().split()))
i = 1
while True:
if i not in arr:
print(i)
break
i+=1
|
"""
Define citations for ESPEI
"""
ESPEI_CITATION = "B. Bocklund, R. Otis, A. Egorov, A. Obaied, I. Roslyakova, Z.-K. Liu, ESPEI for efficient thermodynamic database development, modification, and uncertainty quantification: application to Cu-Mg, MRS Commun. (2019) 1-10. doi:10.1557/mrc.2019.59."
ESPEI_BIBTEX = """@ar... |
class Token:
def __init__(self, t_type, lexeme, literal, line):
self.type = t_type
self.lexeme = lexeme
self.literal = literal
self.line = line
def __repr__(self):
return f"Token(type: {self.type}, lexeme: {self.lexeme}, literal: {self.literal}, line: {self.line})"
c... |
class Pessoa:
olhos = 2 # atributo de classe
def __init__(self, idade=None, nome='', *filhos): # Método construtor
self.idade = idade # atributo de objeto ou atributo de Instância
self.nome = nome
self.filhos = list(filhos) # atributo complexo
def cumprimentar(self):
re... |
CONNECTION = {
'server': 'example@mail.com',
'user': 'user',
'password': 'password',
'port': 993
}
CONTENT_TYPES = ['text/plain', 'text/html']
ATTACHMENT_DIR = ''
ALLOWED_EXTENSIONS = ['csv']
|
class LNode:
def __init__(self, elem, next_=None):
self.elem = elem
self.next = next_
class LCList:
def __init__(self):
self._rear = None
def is_empty(self):
return self._rear is None
def prepend(self, elem):
p = LNode(elem)
if self._rear is None:
p.next = p
self._rear = p
else:
p.next = s... |
counter = 0
while counter <= 5:
print("counter", counter)
counter = counter + 1
else:
print("counter has become false ") |
LIMIT_STATEMENT = "LIMIT {last} OFFSET {offset}"
SUBTREES = """
SELECT keyword_tree.fingerprint, keyword, library, status, arguments, call_index
FROM keyword_tree
JOIN tree_hierarchy ON tree_hierarchy.subtree=keyword_tree.fingerprint
WHERE tree_hierarchy.fingerprint=%(fingerprint)s
ORDER BY call_index::int;
"""
TEAM... |
n = int(input())
space = n-1
for i in range(n):
for k in range(space):
print(" ",end="")
for j in range(i+1):
print("* ",end="")
print()
space -= 1
|
type = 'MMDetector'
config = '/home/linkinpark213/Source/mmdetection/configs/faster_rcnn/faster_rcnn_x101_64x4d_fpn_1x_coco.py'
checkpoint = 'https://open-mmlab.s3.ap-northeast-2.amazonaws.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_x101_64x4d_fpn_1x_coco/faster_rcnn_x101_64x4d_fpn_1x_coco_20200204-833ee192.pth'
conf_... |
def add_voxelizer_parameters(parser):
parser.add_argument(
"--voxelizer_factory",
choices=[
"occupancy_grid",
"tsdf_grid",
"image"
],
default="occupancy_grid",
help="The voxelizer factory to be used (default=occupancy_grid)"
)
par... |
def describe_pet(animal_type, pet_name='virgil'):
"""Display info about Virgil"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}")
describe_pet('dog', 'virgil')
describe_pet('hamster', 'harry')
describe_pet(pet_name='garfield', animal_type='cat')
describe_pet('dog... |
j = 1
while j <= 9:
i = 1
while i <= j:
print(f'{i}*{j}={i*j}' , end='\t')
i += 1
j += 1
print() |
# This Document class simulates the HTML DOM document object.
class Document:
def __init__(self, window):
self.window = window
self.created_elements_index = 0 # This property is required to ensure that every created HTML element can be accessed using a unique reference.
def getE... |
LOAD_HUB_FROM_EXT_TEMP = """
insert into {{ params.hub_name }}
select
ext.*
from {{ params.hub_name }}_ext ext
left join {{ params.hub_name }} h
on h.{{ params.pk_name }} = ext.{{ params.pk_name }}
where
h.{{ params.pk_name }} is null
and ext.load_dtm::time > '{{ params.from_dtm }}';
"""
LOAD_LINK_FR... |
# Resample and tidy china: china_annual
china_annual = china.resample('A').last().pct_change(10).dropna()
# Resample and tidy us: us_annual
us_annual = us.resample('A').last().pct_change(10).dropna()
# Concatenate china_annual and us_annual: gdp
gdp = pd.concat([china_annual,us_annual],join='inner',axis=1)
... |
#уверен, что есть способ короче, но в голову не пришел
input_array_str = input("введите список разделенный пробелами: ").split(" ")
if len(input_array_str) > 0:
for i in range(1, len(input_array_str), 2):
a = input_array_str[i]
input_array_str[i] = input_array_str[i-1]
input_array_str[i-1] ... |
train = dict(
batch_size=10,
num_workers=4,
use_amp=True,
num_epochs=100,
num_iters=30000,
epoch_based=True,
lr=0.0001,
optimizer=dict(
mode="adamw",
set_to_none=True,
group_mode="r3", # ['trick', 'r3', 'all', 'finetune'],
cfg=dict(),
),
grad_acc_... |
def simple_game(builder):
return builder. \
room(
name='the testing room',
description=
"""
It's a room with a Pythonista writing test cases.
There is a locked drawer with a key on top.
You need to get to the production server room
at t... |
examples = [
{
"file": "FILENAME",
"info": [
{
"turn_num": 1,
"user": "USER QUERY",
"system": "HUMAN RESPONSE",
"HDSA": "HDSA RESPONSE",
"MarCo": "MarCo RESPONSE",
"MarCo vs. system":
... |
# ____ _____
# | _ \ __ _ _ |_ _| __ __ _ ___ ___ _ __
# | |_) / _` | | | || || '__/ _` |/ __/ _ \ '__|
# | _ < (_| | |_| || || | | (_| | (_| __/ |
# |_| \_\__,_|\__, ||_||_| \__,_|\___\___|_|
# |___/
#
VERSION = (0... |
A, B = map(int, input().split())
result = 0
for i in range(A, B + 1):
if (A + B + i) % 3 == 0:
result += 1
print(result)
|
# -*- coding: utf-8 -*-
class Graph(object):
r"""Graph.
This class described the graph data structure.
"""
pass
class DirectedGraph(Graph):
r"""Directed Graph.
This class described the directed graph data structure.
The graph is described using a dictionary.
graph = {node: [[paren... |
# Search in Rotated Sorted Array: https://leetcode.com/problems/search-in-rotated-sorted-array/
# There is an integer array nums sorted in ascending order (with distinct values).
# Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array ... |
def init_logger(logger_type, data):
logger_profile = []
log_header = 'run_time,read_time,'
# what sesnors are we logging?
for k, v in data.items():
if(data[k]['device'] != ''): # check to see if our device is setup
for kk, vv in data[k]['sensors'].items():
if(data[k][... |
class Solution(object):
def XXX(self, root):
def dfs(node, num, ret):
if node is None:
return num
num += 1
return max(dfs(node.left, num, ret), dfs(node.right, num, ret))
num -= 1
return dfs(root, 0, 0)
|
# Copyright 2012 Kevin Gillette. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
_ord = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"
_table = dict((c, i) for i, c in enumerate(_ord))
def encode(n, len=0):
out = ""
while... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Send SMS to Visitor with leads',
'category': 'Website/Website',
'sequence': 54,
'summary': 'Allows to send sms to website visitor that have lead',
'version': '1.0',
'description': """All... |
class User:
def __init__(self,name):
self.name=name
def show(self):
print(self.name)
user =User("ada66")
user.show() |
def merge(left, right):
results = []
while(len(left) and len(right)):
if left[0] < right[0]:
results.append(left.pop(0))
print(left)
else:
results.append(right.pop(0))
print(right)
return [*results, *left, *right]
print(merge([3, 8, 12], [5, ... |
SIZE = 400
END_SCORE = 4000
GRID_LEN = 3
WINAT = 2048
GRID_PADDING = 10
CHROMOSOME_LEN = pow(GRID_LEN, 4) + 4*GRID_LEN*GRID_LEN + 1*(pow(GRID_LEN, 4))
TOURNAMENT_SELECTION_SIZE = 4
MUTATION_RATE = 0.4
NUMBER_OF_ELITE_CHROMOSOMES = 4
POPULATION_SIZE = 10
GEN_MAX = 10000
DONOTHINGINPUT_MAX = 5
BACKGROUND_COLOR_GAME = "... |
#!/usr/bin/env python
'''
ch8q2a1.py
Function1 = obtain_os_version -- process the show version output and return the OS version (Version 15.0(1)M4) else return None.
Looking for line such as:
Cisco IOS Software, C880 Software (C880DATA-UNIVERSALK9-M), Version 15.0(1)M4, RELEASE SOFTWARE (fc1)
'''
def obtain_os_ver... |
# 5
# / \
# 3 7
# / \ / \
# 2 4 6 8
tree = Node(5)
insert(tree, Node(3))
insert(tree, Node(2))
insert(tree, Node(4))
insert(tree, Node(7))
insert(tree, Node(6))
insert(tree, Node(8))
# 5 3 2 4 7 6 8
preorder(tree)
|
numero = int(input('Digite um número inteiro: '))
dezena = numero // 10
dezena = dezena % 10
print(f'O dígito das dezenas é {dezena}')
|
"Primera parte del ejercicio"
def mcd_euclides (a,b):
#Vamos a resolver el algoritmo de euclides utilizando iteracion
while b != 0:
# Hacemos uso de la siguiente propiedad: mcd(a,b) = mcd(a−b,b)
aux = b
b = a%b
a = aux
#De esta manera vamos reduciendo a hasta que este sea el mcd
return a
"Seg... |
# Copyright (C) 2021 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
def sanitize(time_string):
if '-' in time_string:
spliter = '-'
elif ':' in time_string:
spliter = ':'
else:
return time_string
(mins, secs) = time_string.split(spliter)
return mins + '.' + secs
def get_coach_data(filepath):
try:
with open(filepath) as f:
... |
class SemanticException(Exception):
def __init__(self, message, token=None):
if token is None:
super(SemanticException, self).__init__(message)
else:
super(SemanticException, self).__init__(message + ': ' + token.__str__()) |
keys = {
"x" :"x",
"y" :"y",
"l" :"left",
"left" :"left",
"r" :"right",
"right" :"right",
"t" :"top",
"top" :"top",
"b" :"bottom",
"bottom":"bottom",
"w" :"width",
"width" :"width",
"h" :"height",
"height":"height",
"a" :"align",
"align" :"align",
"d" :"dock",
"dock" :"dock"
}
align_values_rev... |
# this contains some predefined pair outputs .
def fixedpair(inp):
if inp == "who?":
pair = "I am TS3000."
elif inp == "who ?" :
pair = "I m bitch"
return pair
|
class PlanCircuit(APIObject, IDisposable):
""" An object that represents an enclosed area in a plan view within the Autodesk Revit project. """
def Dispose(self):
""" Dispose(self: APIObject,A_0: bool) """
pass
def GetPointInside(self):
"""
GetPointInside(self: PlanCircu... |
'''
05 - Putting a list of dates in order
Much like numbers and strings, date objects in Python can be put
in order. Earlier dates come before later ones, and so we can sort
a list of date objects from earliest to latest.
What if our Florida hurricane dates had been scrambled? We've gone
ahead and shuffl... |
_base_ = ['./rretinanet_obb_r50_fpn_1x_dota_v3.py']
# switch data path in '../_base_/datasets/dota1_0.py'
angle_version = 'v3'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_... |
# O(n) time | O(n) space
# Iterative solution 2
def spiralTraverse(array):
result = []
startRow, endRow = 0, len(array) - 1
startCol, endCol = 0, len(array[0]) - 1
while startRow <= endRow and startCol <= endCol:
for col in range(startCol, endCol + 1):
result.append(array[startRow][... |
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.helper = []
def push(self, x: int) -> None:
self.stack.append(x)
if not self.helper or x <= self.helper[-1]:
self.helper.append(x)
def p... |
"""Return empty resources block."""
def GenerateConfig(_):
return """resources:"""
|
for i in range(5):
ans = 0
coins = []
for i in range(int(input())):
coins.append(int(input()))
avg = sum(coins) // len(coins)
for i in coins:
ans += abs(avg - i)
print(ans // 2)
|
"""
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two's complement method is used.
Note:
All letters in hexadecimal (a-f) must be in lowercase.
The hexadecimal string must not contain extra leading 0s.
If the number is zero, it is represented by a single zero character '0';... |
app_name = 'app004'
urlpatterns = [
] |
#
# PySNMP MIB module ZHONE-DISMAN-TRACEROUTE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-DISMAN-TRACEROUTE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:41:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... |
# Given a list of intervals,
# merge all the overlapping intervals to produce a list that has only mutually exclusive intervals.
# Example:
# Intervals: [[1,4], [2,5], [7,9]]
# Output: [[1,5], [7,9]]
# Explanation: Since the first two intervals [1,4] and [2,5] overlap, we merged them into one [1,5].
# O(N) for merg... |
class AlignmentType:
@property
def _alignment_type(self):
return self.record_type
|
"""
Write a function called sed that takes as arguments a pattern string, a replacement string,
and two filenames; it should read the first file and write the contents into the second file
(creating it if necessary). If the pattern string appears anywhere in the file, it should be
replaced with the replacement strin... |
def reverse_number(n):
r = 0
while n > 0:
r *= 10
r += n % 10
n //= 10
return r
def isPrime(n):
flag = False
if(n > 1):
for i in range(2, n):
if(n % i == 0):
flag = True
break
return flag
n = int(input())
flag = Fals... |
#
# PySNMP MIB module HPN-ICF-L4RDT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-L4RDT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:39:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
"""
file access support
"""
def backup_one_line(fd):
"""
Moves the file pointer to right after the previous newline in an ASCII file
@param fd :
@type fd : file descriptor
Notes
=====
It ignores the current character in case it is a newline.
"""
index = -2
c = ""
while c != "\n":
fd.seek... |
"""
Error types
"""
class AlreadyBoundError(Exception):
"""
Raised if a factory is already bound to a name.
"""
pass
class CyclicGraphError(Exception):
"""
Raised if a graph has a cycle.
"""
pass
class LockedGraphError(Exception):
"""
Raised when attempting to create a c... |
"""
Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size.
Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the previous one exactly by 1.
He may need some addi... |
# -*- coding: utf-8 -*-
# @Time : 2021/1/3
# @Author : handsomezhou
DB_SUFFIX = "db"
DB_SUFFIX_WITH_FULL_STOP = ".db"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.