content stringlengths 7 1.05M |
|---|
"""
There are some spherical balloons spread in two-dimensional space. For each
balloon, provided input is the start and end coordinates of the horizontal
diameter. Since it's horizontal, y-coordinates don't matter, and hence the
x-coordinates of start and end of the diameter suffice. The start is al... |
"""
https://leetcode.com/problems/diameter-of-binary-tree/
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
... |
# Som del av et spørrespill skal du lage en klasse for flervalgspørsmål.
# Et flervalgspørsmål skal ha en spørsmålstekst, ei liste med svaralternativer
# (hvert svaralternativ er en tekststreng), og et tall som sier hvilket av
# svaralternativene som er korrekt.Klassen skal ha en __str__ metode som returnerer
# en stre... |
#
# PySNMP MIB module TRANGO-APEX-TRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRANGO-APEX-TRAP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:19:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
"""
District Mapping
================
Defines the algorithms that perform the mapping from precincts to districts.
"""
|
print('Digite um número inteiro positivo de três dígitos (100 a 999), para gerar o número invertido')
num = int(input('Número: '))
num = str(num)
reverso = num[::-1]
print(f'O número ao contrário de: {num} é: {reverso}') |
# -*- coding: utf-8 -*-
i = 1
for x in range(60, -1, -5):
print('I={} J={}'.format(i, x))
i += 3
|
def process(N):
temp = str(N)
temp = temp.replace('4','2')
res1 = int(temp)
res2 = N-res1
return res1,res2
T = int(input())
for t in range(T):
N = int(input())
res1,res2 = process(N)
print('Case #{}: {} {}'.format(t+1,res1,res2)) |
class T:
WORK_REQUEST = 1
WORK_REPLY = 2
REDUCE = 3
BARRIER = 4
TOKEN = 7
class Tally:
total_dirs = 0
total_files = 0
total_filesize = 0
total_stat_filesize = 0
total_symlinks = 0
total_skipped = 0
total_sparse = 0
max_files = 0
total_nlinks = 0
total_nlinke... |
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# 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 la... |
class ProgramError(Exception):
"""Generic exception class for errors in this program."""
pass
class PluginError(ProgramError):
pass
class NoOptionError(ProgramError):
pass
class ExtCommandError(ProgramError):
pass
|
''' 23. Faça um programa que receba o valor do salário mínimo, o turno de trabalho (M
— matutino; V — vespertino; ou N — noturno), a categoria (O — operário; G —
gerente) e o número de horas trabalhadas no mês de um funcionário. Suponha a
digitação apenas de dados válidos e, quando houver digitação de letras, utilize
m... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/12/15 11:26
# @Author : glacier
# @Site : 二进制计算
# @File : binary_array_to_number.py
# @Software: PyCharm Edu
# def binary_array_to_number(arr):
# sum = 0
# index = len(arr)-1
# i = 0
# while(index >= 0):
# sum += mul(a... |
# Types
Symbol = str # A Lisp Symbol is implemented as a Python str
List = list # A Lisp List is implemented as a Python list
Number = (int, float) # A Lisp Number is implemented as a Python int or float
# Exp = Union[Symbol, Exp]
def atom(token):
"Numbers become numbers; every other token i... |
def GetInfoMsg():
infoMsg = "This python snippet is triggered by the 'cmd' property.\r\n"
infoMsg += "Any command line may be triggered with the 'cmd' property.\r\n"
return infoMsg
if __name__ == "__main__":
print(GetInfoMsg()) |
def shift_rect(rect, direction, distance=48):
if direction == 'left':
rect.left -= distance
elif direction == 'right':
rect.left += distance
elif direction == 'up':
rect.top -= distance
elif direction == 'down':
rect.top += distance
return rect
|
"""
Desafio 016
Problema: Crie um programa que leia um número Real qualquer
pelo teclado e mostre na tela a sua porção Inteira."""
n = float(input('Digite um valor:'))
print(f'O número {n} tem a parte inteira {int(n)}')
|
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 6 17:11:11 2018
@author: Haider Raheem
"""
a= float(input("Type a : "))
b= float(input("Type b : "))
c= float(input("Type c : "))
x= (a*b)+(b*c)+(c*a)
y= (a+b+c)
r= x/y
print( )
print("The result of the calculation is {0:.2f}".format(r)) |
'''Crie um programa que leia varios numeros inteiros
o programa so vai parar qunado o usuario digitar 999
no final mostre a soma entre eles e quanto foram digitados'''
soma = total = 0
while True:
valor = int(input('## 999 para parar ###\n'
'Digite um valor: '))
if valor == 999:
... |
# Programa Principal
def teste():
x = 8
print(f'Na função teste, n vale {n}')
print(f'Na função teste x vale {x}')
n = 2
print(f'No programa principal, n vale {n}')
teste()
print(f'No programa principal, x vale {x}')
|
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class ObjectStatusEnum(object):
"""Implementation of the 'ObjectStatus' enum.
Specifies the status of an object during a Restore Task.
'kFilesCloned' indicates that the cloning has completed.
'kFetchedEntityInfo' indicates that information about ... |
# 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:
def getLonelyNodes(self, root: TreeNode) -> List[int]:
lonely_nodes = []
def dfs(no... |
# -*- coding: utf-8 -*-
__title__ = "flloat"
__description__ = "A Python implementation of the FLLOAT library."
__url__ = "https://github.com/marcofavorito/flloat.git"
__version__ = "1.0.0a0"
__author__ = "Marco Favorito"
__author_email__ = "marco.favorito@gmail.com"
__license__ = "MIT license"
__copyright__ = "2019 M... |
class Solution:
def rotatedDigits(self, N: 'int') -> 'int':
result = 0
for nr in range(1, N + 1):
ok = False
for digit in str(nr):
if digit in '347':
break
if digit in '6952':
ok = True
els... |
#--------------------------------------------------------------------------------
# SoCaTel - Backend data storage API endpoints docker container
# These tokens are needed for database access.
#--------------------------------------------------------------------------------
#===========================================... |
x1 = 1
y1 = 0
x2 = 0
y2 = -2
m1 = (y2 / x1)
x1 = 2
y1 = 2
x2 = 6
y2 = 10
m2 = (y2 - y1 / x2 - x1)
diff = m1 - m2
print(f'Diff of 8 and 9: {diff:.2f}') # 10 |
# https://www.codechef.com/problems/COPS
for T in range(int(input())):
M,x,y=map(int,input().split())
m,a = list(map(int,input().split())),list(range(1,101))
for i in m:
for j in range(i-x*y,i+1+x*y):
if(j in a): a.remove(j)
print(len(a)) |
# -*- coding: utf-8 -*-
"""
wordpress
~~~~
tamper for wordpress
:author: LoRexxar <LoRexxar@gmail.com>
:homepage: https://github.com/LoRexxar/Kunlun-M
:license: MIT, see LICENSE for more details.
:copyright: Copyright (c) 2017 LoRexxar. All rights reserved
"""
wordpress = {
"es... |
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: a ListNode
@param k: An integer
@return: a ListNode
@ O(n) time | O(1) space
"""
def reverseKGroup(self, head, k)... |
# -*- coding: utf-8 -*-
"""
Wrapper class for Bluetooth LE servers returned from calling
:py:meth:`bleak.discover`.
Created on 2018-04-23 by hbldh <henrik.blidh@nedomkull.com>
"""
class BLEDevice(object):
"""A simple wrapper class representing a BLE server detected during
a `discover` call.
- When usin... |
#
# Hubblemon - Yet another general purpose system monitor
#
# Copyright 2015 NAVER Corp.
#
# 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
#
# U... |
class DataGridViewCellStateChangedEventArgs(EventArgs):
"""
Provides data for the System.Windows.Forms.DataGridView.CellStateChanged event.
DataGridViewCellStateChangedEventArgs(dataGridViewCell: DataGridViewCell,stateChanged: DataGridViewElementStates)
"""
@staticmethod
def __new__(self, ... |
description = 'Verify the user cannot log in if password value is missing'
pages = ['login']
def test(data):
navigate(data.env.url)
send_keys(login.username_input, 'admin')
click(login.login_button)
capture('Verify the correct error message is shown')
verify_text_in_element(login.error_list, 'Pas... |
#######################################################################
# Copyright (C) 2017 Shangtong Zhang(zhangshangtong.cpp@gmail.com) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
################################... |
"""Version details for python-marketman
This file shamelessly taken from the requests library"""
__title__ = 'python-marketman'
__description__ = 'A basic Marketman.com REST API client.'
__url__ = 'https://github.com/LukasKlement/python-marketman'
__version__ = '0.1'
__author__ = 'Lukas Klement'
__author_email__ = 'lu... |
# Разработать класс IterInt, который наследует функциональность стандартного типа int, но добавляет
# возможность итерировать по цифрам числа
class IterInt(int):
pass
n = IterInt(12346)
for digit in n:
print("digit = ", digit)
# Выведет:
# digit = 1
# digit = 2
# digit = 3
# digit = 4
# digit = 6 |
def forward(w,s,b,y):
Yhat= w * s + b
output = (Yhat-y)**2
return output, Yhat
def derivative_W(x, output, Yhat, y):
return ((2 * output) * (Yhat - y)) * x # w
def derivative_B(b, output, Yhat, y):
return ((2 * output) * (Yhat - y)) * b #bias
def main():
w = 1.0 #weight
x = 2.0 #samp... |
# -*- coding: utf-8 -*-
"""Top-level package for Test."""
__author__ = """Lana Maidenbaum"""
__email__ = 'lana.maidenbaum@zeel.com'
__version__ = '0.1.1'
|
"""
SpEC
~~~~~~~~~~~~~~~~~~~
Sparsity, Explainability, and Communication
:copyright: (c) 2019 by Marcos Treviso
:licence: MIT, see LICENSE for more details
"""
# Generate your own AsciiArt at:
# patorjk.com/software/taag/#f=Calvin%20S&t=SpEC
__banner__ = """
_____ _____ _____
| __|___| __| |
|__ | . | ... |
# 第一行一个*,第二行两个*........ 共十行
# 打印乘法口诀
n = 1
while n <= 10:
n1 = n
while n1:
print("*", end = "")
n1 -= 1
print()
n += 1
n2 = 1
n3 = 1
while n2 < 10:
while n3 <= n2:
print(f"{n3}*{n2}={n3*n2}",end="\t")
n3 += 1
print()
n2 += 1
n3 = 1
... |
def banner(message, length, header='=', footer='*'):
print()
print(header * length)
print((' ' * (length//2 - len(message)//2)), message)
print(footer * length)
def banner_v2(length, footer='-'):
print(footer * length)
print()
|
# Soft-serve Damage Skin
success = sm.addDamageSkin(2434951)
if success:
sm.chat("The Soft-serve Damage Skin has been added to your account's damage skin collection.")
|
num1 = 100
num2 = 200
num3 = 300
num4 = 400
num5 = 500
mum6 = 600
num7 = 700
num8 = 800
|
# Link - https://leetcode.com/problems/implement-strstr/
"""
28. Implement strStr()
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Clarification:
What should we return when needle is an empty string? This is a great question to ask during... |
# 短信签名
SMS_SIGN = 'demo'
# 短信验证码模板ID
SMS_VERIFICATION_CODE_TEMPLATE_ID = 'SMS_151231777'
|
def required_model(name: object, kwargs: object) -> object:
required_fields = kwargs['required_fields'] if 'required_fields' in kwargs else []
task_f = kwargs['required_task_fields'] if 'required_task_fields' in kwargs else []
proc_f = kwargs['required_proc_fields'] if 'required_proc_fields' in kwargs else []
disp... |
# -*- coding: utf-8 -*-
"""
Created on 2018/9/20
@author: gaoan
"""
ORDER_NO = "order_no"
PREVIEW_ORDER = "preview_order"
PLACE_ORDER = "place_order"
CANCEL_ORDER = "cancel_order"
MODIFY_ORDER = "modify_order"
"""
账户/资产
"""
ACCOUNTS = "accounts"
ASSETS = "assets"
POSITIONS = "positions"
ORDERS = "orders"
ACTIVE_ORDE... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Unit:
def __init__(self, x, y, color, name):
self.x = x
self.y = y
self.color = color
self.name = name
self.taken = False
class OpUnit(Unit):
def __init__(self, x, y, color, name):
super().__init__(x, y, color... |
#!/usr/bin/env python
#coding: utf-8
class Node:
def __init__(self, elem=None, next=None):
self.elem = elem
self.next = next
if __name__ == "__main__":
n1 = Node(1, None)
n2 = Node(2, None)
n1.next = n2
|
def test_check_sanity(client):
resp = client.get('/sanity')
assert resp.status_code == 200
assert 'Sanity check passed.' == resp.data.decode()
# 'list collections' tests
def test_get_api_root(client):
resp = client.get('/', content_type='application/json')
assert resp.status_code == 200
resp_d... |
dias = int(input("quantos dias voce deseja alugar o carro? "))
km = float(input("Quantos kilometros você andou? "))
pago = dias * 60 + (km * 0.15)
print("o valor do aluguel do carro foi de R$ {:.2f}" .format(pago))
|
def factorial(num):
# 재귀함수를 세울 때는 탈출 조건부터 찾는다.
if num <= 1:
return 1
return factorial(num - 1) * num
def main():
print(factorial(5))
# return 120
if __name__ == "__main__":
main() |
'''
Single perceptron can replicate a NAND gate
https://en.wikipedia.org/wiki/NAND_logic
inputs | output
0 0 1
0 1 1
1 0 1
1 1 0
'''
def dot_product(vec1,vec2):
if (len(vec1) != len(vec2)):
print("input vector lengths are not equal")
print(len(vec1))
print(len(vec2))
reslt=0
for... |
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 3.6
dictionary = {}
for number in A:
if dictionary.get(number) == None:
dictionary[number] = 1
else:
dictionary[number] += 1
for ke... |
print(4+3);
print("Hello");
print('Who are you');
print('This is Pradeep\'s python program');
print(r'C:\Users\N51254\Documents\NetBeansProjects');
print("Pradeep "*5); |
# -*- coding: utf-8 -*-
def setup_argparser(parser):
"""コマンドパーサーのセットアップ。
パーサーは共有されるので、被らないように上手く調整すること。
:param parser: ``argparse.ArgumentParser`` のインスタンス。
"""
pass
def setup_app(args):
"""コマンドパース後のセットアップ。
:param args: ``parser.arg_parse()`` の戻り値。
"""
pass
def on_open(... |
class Bank():
def __init__(self):
pass
def reduce(self, source, to):
return source.reduce(to)
|
first_angle = int(input("Lütfen ilk açıyı giriniz: "))
second_angle = int(input("Lütfen ilk açıyı giriniz: "))
gelenAcilar = {first_angle, second_angle}
eskenar = {60, 60, 60}
dik = {25, 65, 90}
ikizKenar = {45, 45, 90}
cesitKenar = {120, 41, 19}
if gelenAcilar.intersection(ikizKenar):
print("ikizkenar")
elif ge... |
"""
Solution to Word in Reverse
"""
if __name__ == '__main__':
while True:
word = input('Enter a word: ')
word = str(word)
i = len(word)
reversed_word = ''
while i > 0:
reversed_word += word[i - 1]
i -= 1
print('{reversed_wo... |
def convert_fizzbuzz(n: int) -> str:
s = str(n)
if n % 3 == 0 and n % 5 == 0:
s = "FizzBuzz"
if n % 3 == 0:
s = "Fizz"
if n % 5 == 0:
s = "Buzz"
return s
def fizzbuzz() -> None:
"""
1から100までの整数nに対して
* nが3の倍数かつ5の倍数の時はFizzBuzz
* nが3の倍数の時はFizz
* nが5の倍数の時はBu... |
# -*- coding: utf-8 -*-
"""
Ceci est un module avec les tests unitaires et les tests d'intégrations.
"""
|
MAX_MEMORY = 5 * 1024 * 2 ** 10 # 5 MB
BUFFER_SIZE = 1 * 512 * 2 ** 10 # 512 KB
class DataSourceInterface(object):
"""Provides a uniform API regardless of how the data should be fetched."""
def __init__(self, target, preload=False, **kwargs):
raise NotImplementedError()
@property
def is_loa... |
SQLALCHEMY_DATABASE_URI = 'sqlite:///database.sqlite'
SECRET_KEY = 'F12Zr47j\3yX R~X@H!jmM]Lwf/,?KT'
SAVE_FOLDER = '../../../projects'
SQLALCHEMY_TRACK_MODIFICATIONS = 'False'
PORT = '3000'
STATIC_FOLDER = '../../client/dist/static'
|
class BinaryTree:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def insert_left(self, data):
if self.left is None:
self.left = BinaryTree(data)
else:
self.left = BinaryTree(data, left=self.l... |
discovery_node_rpc_url='https://ctz.solidwallet.io/api/v3'
request_data = {
"jsonrpc": "2.0",
"id": 1234,
"method": "icx_call",
"params": {
"to": "cx0000000000000000000000000000000000000000",
"dataType": "call",
"data": {
... |
# jaylin
hours = float(input("Enter hours worked: "))
rate = float(input("Enter hourly rate: "))
if (rate >= 15):
pay=(hours* rate)
print("Pay: $", pay)
else:
print("I'm sorry " + str(rate) + " is lower than the minimum wage!")
|
## 删除排序数组中的重复项
# 方法: 快慢指针 时间:O(n) 空间:O(1)
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
s = 0
for f in range(0, len(nums)):
if nums[f] != nums[s]:
s += 1
nums[s] = nums[f]
return s + 1 |
# This is a namespace package. See also:
# http://pythonhosted.org/distribute/setuptools.html#namespace-packages
# http://osdir.com/ml/python.distutils.devel/2006-08/msg00029.html
__import__('pkg_resources').declare_namespace(__name__)
|
# put your python code here
def event_time(hours, minutes, seconds):
return (hours * 3600) + (minutes * 60) + seconds
def time_difference(a, b):
return abs(a - b)
hours_1 = int(input())
minutes_1 = int(input())
seconds_1 = int(input())
hours_2 = int(input())
minutes_2 = int(input())
seconds_2 = int(input()... |
# buildifier: disable=module-docstring
# buildifier: disable=function-docstring-header
def detect_root(source):
"""Detects the path to the topmost directory of the 'source' outputs.
To be used with external build systems to point to the source code/tools directories.
Args:
source (Target): A filegr... |
def get_config_cs2en():
config = {}
# Settings which should be given at start time, but are not, for convenience
config['the_task'] = 0
# Settings ----------------------------------------------------------------
config['allTagsSplit'] = 'allTagsSplit/' # can be 'allTagsSplit/', 'POSextra/' or ... |
ALLOWED_HOSTS = ['testserver']
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOC... |
#!/usr/bin/env python
"""
_Scripts_
"""
|
my_dictionary = {
'type': 'Fruits',
'name': 'Apple',
'color': 'Green',
'available': True,
'number': 25
}
print(my_dictionary)
print(my_dictionary['name'])
# searching with wrong key
print(my_dictionary['weight'])
###############################################################
# printing keys and ... |
vTotal = 0
i = 0
vMenorValor = 0
cont = 1
vMenorValorItem = ''
while True:
vItem = str(input('Insira o nome do produto: '))
vValor = float(input('Valor do produto: R$'))
vTotal = vTotal + vValor
if vValor >= 1000:
i = i + 1
if cont == 1:
vMenorValor = vValor
vM... |
# Tai Sakuma <tai.sakuma@gmail.com>
##__________________________________________________________________||
class Parallel(object):
def __init__(self, progressMonitor, communicationChannel, workingarea=None):
self.progressMonitor = progressMonitor
self.communicationChannel = communicationChannel
... |
"""Solution to Project Euler Problem 1
https://projecteuler.net/problem=1
"""
NUMBERS = 3, 5
MAXIMUM = 1000
def compute(*numbers, maximum=MAXIMUM):
"""Compute the sum of the multiples of `numbers` below `maximum`."""
if not numbers:
numbers = NUMBERS
multiples = tuple(set(range(0, maximum, numb... |
# Algorithms > Warmup > Compare the Triplets
# Compare the elements in two triplets.
#
# https://www.hackerrank.com/challenges/compare-the-triplets/problem
#
a = map(int, input().split())
b = map(int, input().split())
alice, bob = 0, 0
for i, j in zip(a, b):
if i > j:
alice += 1
elif i < ... |
# Gerard Hanlon, 30.01.2018
# A program that displays Fibonacci numbers.
def fib(n):
"""This function returns the nth Fibonacci numbers."""
i = 0 # variable i = the first fibonacci number
j = 1 # variable j = the second fibonacci number
n = n - 1 # variable n = n - 1
while n >= 0: # while n is greater than ... |
'''
Normal Counting sort without any associated array to keep track of
Time Complexity = O(n)
Space Complexity = O(n + k)
Auxilary Space = O(k)
'''
def countingSort(a):
b = [0]*(max(a) + 1)
c = []
for i in range(len(a)):
b[a[i]] += 1
for i in range(len(b)):
if(b[i] != 0)... |
# 创建变量,外星人为绿色
alien_color = 'green'
# 条件判断
if alien_color == 'green':
print("You get 5 points.")
elif alien_color == 'yellow':
print("\nYou get 10 points.")
else:
print("\nYou get 15 points.")
# 创建变量,外星人为黄色
alien_color = 'yellow'
# 条件判断
if alien_color == 'green':
print("You get 5 points.")
elif alien... |
n,m=map(int,input().split())
L = [list(map(int,input().split())) for i in range(m)]
ans = 0
L.sort(key = lambda t:t[0],reverse = True)
for i in L[:-1]:
ans += max(0,n-i[0])
print(ans) |
"""
A-Z: 65-90
a-z: 97-122
"""
dic = {}
n = 0
for i in range(10):
dic[n] = str(i)
n += 1
for i in range(65, 91):
dic[n] = chr(i)
n += 1
for i in range(97, 123):
dic[n] = chr(i)
n += 1
print(dic)
|
lst = ['инженер-конструктор Игорь', 'главный бухгалтер МАРИНА', 'токарь высшего разряда нИКОЛАй', 'директор аэлита']
some_str = ''
i = 0
for elem in lst:
some_str = elem
lst[i] = some_str.split()
some_str = ''
i += 1
for i in lst:
for j in range(len(i)):
if j == len(i)-1:
som... |
N = int(input())
def factorial(N):
if N == 0:
return 1
return N * factorial(N-1)
print(factorial(N))
|
# -*- coding:utf-8 -*-
# ---------------------------------------------
# @file Function.py
# @description Function
# @author WcJun
# @date 2020/06/20
# ---------------------------------------------
# 求两个数 n 加到 m 的和
def add(n, m):
s = 0
while n <= m:
s += n
n += 1
return s
# 求和
add = add... |
class AreWeUnitTesting(object):
# no doc
Value = False
__all__ = []
|
# coding=utf-8
#
# @lc app=leetcode id=1108 lang=python
#
# [1108] Defanging an IP Address
#
# https://leetcode.com/problems/defanging-an-ip-address/description/
#
# algorithms
# Easy (85.21%)
# Likes: 66
# Dislikes: 256
# Total Accepted: 36.7K
# Total Submissions: 43.1K
# Testcase Example: '"1.1.1.1"'
#
# Given... |
CJ_PATH = r''
COOKIES_PATH = r''
CHAN_ID = ''
VID_ID = ''
|
class Rectangle:
def __init__(self, length, breadth, unit_cost=0):
self.length = length
self.breadth = breadth
self.unit_cost = unit_cost
def get_area(self):
return self.length * self.breadth
def calculate_cost(self):
area = self.get_area()
return area * self.unit_cost... |
'''
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.
Example 1:
Input:
s = "barfoothefoobarman",
words = ["foo","bar"]
Output: [0... |
# URLs processed simultaneously
class Batch():
def __init__(self):
self._batch = 0
def set_batch(self, n_batch):
try:
self._batch = n_batch
except BaseException:
print("[ERROR] Can't set task batch number.")
def get_batch(self):
try:
r... |
playerFilesWin = {
"lib/avcodec-56.dll" : { "flag_deps" : True, "should_be_removed" : True },
"lib/avformat-56.dll" : { "flag_deps" : True, "should_be_removed" : True },
"lib/avutil-54.dll" : { "flag_deps" : True, "should_be_removed" : True },
"lib/swscale-3.dll" : { "flag_deps" : True, "shou... |
# Hello world program to demonstrate running PYthon files
print('Hello, world!')
print('I live on a volcano!')
|
class Productivity:
def __init__(self, irradiance, hours,capacity):
self.irradiance = irradiance
self.hours = hours
self.capacity = capacity
def getUnits(self):
print(self.irradiance)
totalpower = 0
print(totalpower)
for i in self.irradiance... |
def create_platform_routes(server):
metrics = server._augur.metrics
|
__version__ = '0.1.7'
default_app_config = 'dynamic_databases.apps.DynamicDatabasesConfig'
|
PHYSICS_TECHS = {
"tech_databank_uplinks",
"tech_basic_science_lab_1",
"tech_curator_lab",
"tech_archeology_lab",
"tech_physics_lab_1",
"tech_physics_lab_2",
"tech_physics_lab_3",
"tech_global_research_initiative",
"tech_administrative_ai",
"tech_cryostasis_1",
"tech_cryostas... |
# Custom errors in classes.
class TooManyPagesReadError(ValueError):
pass
class Book:
def __init__(self, title, page_count):
self.title = title
self.page_count = page_count
self.pages_read = 0
def __repr__(self):
return (
f"<Book {self.title}, read {self.pages_... |
""" Trapping rain water: Given an array of non negative integers, they are height of bars.
Find how much water can you collect between there bars """
"""Solution: """
def rain_water(a) -> int:
n = len(a)
res = 0
for i in range(1, n-1):
lmax = a[i]
for j in range(i):
lmax ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.