content stringlengths 7 1.05M |
|---|
class Mobile:
def make_call(self):
print("i am making a call")
def play_game(self):
print("i am playing games")
m1=Mobile()
m1.make_call()
m1.play_game()
class Mobile:
def set_color(self,color):
self.color=color
def set_cost(self,cost):
self.cost=cost
def show_col... |
"""Transform array to -> X
- create_balanced_bst_from_sorted_array(sorted_array)
"""
# Input "array" - sorted array
# Output "root" - root of the tree
"""
Create a balanced BST from a sorted array.
Or split elements from array to have a balanced
binary tree.
Example:
array = [1, 3, 7, 20, 100, 111, 121]
b... |
'''
Find the continuous sequence in array with mix of positive and negative integers
with the largest sum: Return the sum
'''
def max_subseq(arr):
sum = 0
maxSum = 0
start = 0
end = 0
for i in range(1, len(arr)):
sum += arr[i]
if maxSum < sum:
maxSum = sum
... |
"""
The following code is not meant to be run because
there's no input. Instead, analyze it's running time
in terms of Big-O. The first two lines are already
analyzed for you. Do the same for all the other lines.
At the end, put the total running time of code.
The input of the problem is ex_2d_list, and assume
it has n... |
# =========================================================
# DOCS
# =========================================================
"""Software for the study of Cosmic Microwave Foregrounds (CMFG)
"""
__version__ = "0.0.1"
|
class AuthenticateViews:
def authenticate_product(self,name, qty, min_stock, price, units, category):
if not name or not isinstance(name, str):
return "product name missing or must be a string."
if name.isspace() or not name.isalpha():
return "product name should onl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'Administrator'
__mtime__ = '2018/12/3'
# code is far away from bugs with the god animal protecting
I love animals. They taste delicious.
"""
# 冒泡排序 升序
lst =[98,2,4,78,12,1,6,3,10,34,55]
for i in range(len(lst)):
for j in r... |
# question can be found at leetcode.com/problems/minimum-time-visiting-all-points/
# it's basically a fancy way of asking for a binary search algorithm
# actually, you prob can implement different searches too
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return an integer
def isBa... |
class LogHandler:
def __init__(self, log_location):
self.log_location = log_location
self.__init_files()
self.log_index = self.get_recent_index()
self.log_commit_index = self.get_recent_index()
def __init_files(self):
open(self.log_location, 'a').close()
self.del... |
# md5 : 157b3267a46a79dd900104f241da8c4c
# sha1 : 178271eaf8c48384e206cbaebcbbc12030980410
# sha256 : 8611dc1b60ae5c383bba6cb3ffd8a51aeebff23b95844f0ab3d6e5ecd0fadc84
ord_names = {
100: b'ThunRTMain',
101: b'VBDllUnRegisterServer',
102: b'VBDllCanUnloadNow',
103: b'VBDllRegisterServer',
104: b'VBDl... |
"""
ID: fufa0001
LANG: PYTHON3
TASK: crypt1
"""
fin = open("crypt1.in","r")
fout = open("crypt1.out","w")
def test_num(num, strict=True):
if strict and (num > 999 or num < 100):
return False
for char in str(num):
if char not in digits:
return False
return True
dig_count, digits =... |
print('\033[30mEx: Digite um nome de uma cidade e mostre se ela começa com SANTO.')
print('\033[1;31m=-'*20)
cid = str(input('\033[1;34mDigite o nome da cidade em que você nasceu: '))
div = cid.split()
print('1° método: Começa com Santo?','Santo' in div[0].title())
print('2° método: Começa com SANTO?', div[0].upper()... |
# model
model = Model()
i0 = Input("op_shape", "TENSOR_INT32", "{4}")
weights = Parameter("ker", "TENSOR_FLOAT32", "{2, 3, 3, 1}",
[1.0, 3.0, 5.0, 7.0, 9.0, 11.0,
13.0, 15.0, 17.0, 2.0, 4.0, 6.0,
8.0, 10.0, 12.0, 14.0, 16.0, 18.0])
i1 = Input("in", "TENSOR_FLOAT32", "{1, 2, 2, 1}" )
pad = Int32Scalar("pad_valid",... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"Intake": "01_Download_and_Load.ipynb",
"mergeDatasets": "02_Merge_Data.ipynb",
"workWithGeometryData": "03_Map_Basics_Intake_and_Operations.ipynb",
"readInGeometryData": "03_Map_Ba... |
def main():
age = int(input('Enter your age: '))
name = input('Enter your name: ')
if age < 30:
print('Hello', name)
print('I see you are less than 30.')
print('You are so young.') |
file = open("IntegerArray.txt")
data = []
n = 0
while 1:
line = file.readline()
if not line:
break
data.append(int(line))
n += 1
def InverseCount(data):
n = len(data)
if n <= 1:
return data,0
n1 = int(n/2+0.5)
A = data[:n1]
B = data[n1:]
A,m1 = InverseCount(A)
B,m2 = InverseCount(... |
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
print(tabby_cat)
print(persian_cat)
print(backslash_cat)
print(fat_cat)
air_quote = 'She is my "special" friend.\a'
print(air_quote)... |
#
# PySNMP MIB module Wellfleet-X25PAD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-X25PAD-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:35:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
# -*- coding: utf-8 -*-
"""
Model Map table glazing
:author: Sergio Aparicio Vegas
:version: 0.1
:date: 24 Oct. 2017
"""
__docformat__ = "restructuredtext"
class Glazing():
""" DB Entity glazing to Python object Glazing """
def __init__(self):
self.__id = 0... |
def sqr(n):
""" Find square of a number
"""
return n*n
def main():
print("Square of 2 is {}".format(sqr(2)))
if __name__ == "__main__":
main()
|
class HumanPlayer:
def __init__(self, start_position, boundary):
self.size = 3
self.cycleSpeed = 4
self.cycleInterval = 0
pos = int(start_position - self.size / 2)
self.positions = range(pos, pos + self.size)
self.startPosition = start_position
self.boundary... |
# Exercício Python 057: Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores 'M' ou 'F'.
# Caso esteja errado, peça a digitação novamente até ter um valor correto.
sexo = 0
while sexo != 1:
s = str(input('Digite o seu sexo: ')).upper()
if s == 'F' or s == 'M':
sexo = 1
else:
... |
class Solution:
def missingNumber(self, nums: List[int]) -> int:
numsLen = len(nums)
sumAll = numsLen * (numsLen + 1) // 2
sumReal = sum(nums)
return sumAll - sumReal |
class TransformError(Exception):
def __init__(self, func_name, reason, context=''):
self.func_name = func_name
self.reason = reason
self.context = context
|
#
# PySNMP MIB module DES3052P-L2MGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DES3052P-L2MGMT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:24:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
a = int(input('Digite um número inteiro: '))
tot = 0
for c in range(1, a+1):
if a % c == 0:
tot += 1
print('\033[32m', end=' ')
else:
print('\033[31m', end=' ')
print(f'{c}', end=' ')
print('\033[m')
if tot != 2:
print(f'O número {a} foi dividido {tot} vezes, portanto não é Primo... |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 4 13:20:05 2018
@author: 16023
"""
#拉格朗日(Lagrange)插值
def lagr_interpolation_basis_func(Range, x, k, n):
'''
拉格朗日插值基函数
input:
Range:已知点的横纵坐标tuple,类型list
x:插值点,类型float
k:需要计算的第k个基函数值
n:n次插值, int
output:
... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
def fedora_storage_config(release):
return {
"bucket": "antlir",
"key": "s3",
"kind": "s3",
"prefix": "s... |
#!/usr/bin/env python3
# Complete the superDigit function below.
def superDigit(n, k):
x = int(n) * k % 9
return x if x else 9
if __name__ == "__main__":
nk = input().split()
n = nk[0]
k = int(nk[1])
result = superDigit(n, k)
print(result)
|
class Operation(object):
def __eq__(self, other):
return self.__class__ == other.__class__ and self.__dict__ == other.__dict__
class Update(Operation):
def __init__(self, from_package, to_package):
self.from_package = from_package
self.to_package = to_package
def __repr__(self):
... |
#
class MARKET_PRESET:
def __init__(self):
pass
# 手续费比例
def get_commission_coeff(self, code, dtype):
pass
# 印花税系数
def get_tax_coeff(self, code, dtype):
pass
# 交易时间
def get_trade_time(self, code, dtype):
pass
# 交易日期
def get_trade_day(self, code, ... |
#DESCOBRINDO A SOMA DOS IMPARES MULTIPLOS DE 3 DE 1 ATE 500
soma = 0
cont = 0
for c in range(1,501, 2):
if c % 3 == 0:
cont += 1
soma += c
print(f'a soma dos {cont} numeros solicitados é {soma} ')
|
""" Utility methods for making assertions about Galaxy API responses, etc...
"""
ASSERT_FAIL_ERROR_CODE = "Expected Galaxy error code %d, obtained %d"
ASSERT_FAIL_STATUS_CODE = "Request status code (%d) was not expected value %s. Body was %s"
def assert_status_code_is(response, expected_status_code):
response_sta... |
contact_address = 'crowd.group.mturk@gmail.com'
COGNITIVE_TEST_STROOP = 'stroop'
COGNITIVE_TEST_FLANKER = 'flanker'
COGNITIVE_TEST_TASK_SWITCHING = 'task-switching'
COGNITIVE_TEST_POINTING = 'pointing'
COGNITIVE_TEST_N_BACK = 'n-back'
CROWD_TASK_SENTIMENT = 'sentiment'
CROWD_TASK_TRANSCRIPTION = 'transcription'
CROWD... |
class Node:
def __init__(self, key, next=None):
self.key = key
self.next = next
class Queue:
def __init__(self):
self._head = self._tail = None
self._count: int = 0
def enqueue(self, item):
if self.is_empty():
self._head = self._tail = Node(item)
... |
"""Constants for the Mill heater component."""
ATTR_AWAY_TEMP = "away_temp"
ATTR_COMFORT_TEMP = "comfort_temp"
ATTR_ROOM_NAME = "room_name"
ATTR_SLEEP_TEMP = "sleep_temp"
CONSUMPTION_TODAY = "consumption_today"
CONSUMPTION_YEAR = "consumption_year"
DOMAIN = "mill"
MANUFACTURER = "Mill"
MAX_TEMP = 35
MIN_TEMP = 5
SERVI... |
# Approach 1:
def Cloning_List(Given_List):
Result = Given_List[:]
return Result
Given_List = [4, 5, 7, 8, 9, 6, 10, 15]
print(Cloning_List(Given_List))
# Approach 2:
def Cloning_List(Given_List):
Result = []
Result.extend(Given_List)
return Result
Given_List = [4, 5, 7,... |
# Description: List Comprehensions
# Note
# 1. List comprehensions provide a concise way to create lists.
# 2. A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for
# or if clauses.
# Method 1: Create a list
squares = []
for x in range(10):
squares.a... |
class StaticRoute:
def __init__(self, interface_name, network_uuid, network_name, gateway_host):
self.static_route = {
"interfaceName": interface_name,
"selectedNetworks": [{"type": "Network", "overridable": False, "id": network_uuid, "name": network_name}],
"gateway": {"... |
N = int(input())
arr = list(map(int, input().split()))
tmp = [2] * len(arr)
for i in range(2, len(tmp)):
if not (arr[i - 2] <= arr[i - 1] and arr[i - 1] <= arr[i]) and not (arr[i - 2] >= arr[i - 1] and arr[i - 1] >= arr[i]):
tmp[i] = tmp[i - 1] + 1
print(max(tmp))
|
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/1223/A
t = int(input())
for _ in range(t):
n = int(input())
print(n%2 if n>3 else 4-n)
|
#Faça um programa que leia um número Inteiro qualquer e mostre na tela a sua tabuada.
n=int(input('Digite um número para mostrar sua tabuada :'))
print('-'*12)
print('{} x {}={}'.format(n,1,n*1))
print('{} x {}={}'.format(n,1,n*2))
print('{} x {}={}'.format(n,1,n*3))
print('{} x {}={}'.format(n,1,n*4))
print('{} x {}={... |
# encoding: utf-8
__doc__ = 'Data Importer'
__version__ = '3.1.1'
__author__ = 'Valder Gallo <valdergallo@gmail.com>'
|
S = input()
T = input()
count = 0
if S[0] == T[0]:
count += 1
if S[1] == T[1]:
count += 1
if S[2] == T[2]:
count += 1
print(count) |
class Solution:
# @return an integer
def maxArea(self, height):
left = 0
right = len(height) - 1
max = 0
while left < right:
h = height[left]
if height[right] < h:
h = height[right]
s = ( right - left ) * h
if ... |
class AbstractConfigProvider:
"""
Abstract provider defining methods for loading and writing configuration.
for upto 3 levels:
root level: Defaults for totem for all clusters.
cluster level: Defaults for particular cluster.
organization level: Defaults for particular organization
reposit... |
def banner_text(text=' ',screen_width=80):
"""
This will create a banner with text with the string and width provided.
example:
banner_text('*',10)
banner_text('Hello',10)
banner_text('*',10)
`int`
if no width is provided... it will default to 80
example:
b... |
_base_ = [
'./_base_/default_runtime.py'
]
# dataset settings
dataset_type = 'Filelist'
img_norm_cfg = dict(
mean=[125.09, 102.01, 93.19],
std=[71.35, 63.75, 61.46],
to_rgb=True)
train_pipeline = [
# dict(type='RandomCrop', size=32, padding=4),
dict(type='LoadImageFromFile'),
dict(type='Res... |
#! /usr/bin/env python2
#
# Copyright 2015 Google Inc. 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 require... |
def parse_dict(args, attr, default_ok=True):
'''Parse an "nargs='*'" field from an ArgumentParser's parsed arguments
Each argument value should be of the form <k>=<v>, and a dict() of those mappings will be returned
At most one argument value can simply be of the form <v>, in which case it will be assign... |
my_string = "abc"
id(my_string)
#Output = 22838720
"""
By checking the id of the object, we can determine that any time we assign a new value to the
variable, its identity changes.
"""
|
#!/usr/bin/env python
# -*- coding: utf8 -*-
def echo(bot, update):
"""
Description: echoes the string that follows the command /echo.
Hand: command
"""
bot.sendMessage(update.message.chat_id, text=update.message.text[6:])
|
# When we delete the max element and all elements to its right,
# the new max element must be the max before the deleted element was
# added to the array.
for case in range(int(input())):
N = int(input())
max_x, peaks = 0, 0
for x in map(int, input().split()):
if x > max_x:
max_x = x
peaks += 1
... |
def set_and_shift_values(big_muddy_io, values):
for value in values:
set_and_shift_single(big_muddy_io, value)
def set_and_shift_single(big_muddy_io, value):
big_muddy_io.set_data_pins(value)
big_muddy_io.shifting.pulse() |
sizes = [
5000,
2353,
43234,
3634,
23421,
324,
23432,
2342,
2341
]
for i, value in enumerate(sizes):
sizes[i] = value * 0.3
print(sizes)
|
def main():
start, end = map(int, input().split())
hours = (end - start + 24) % 24
if hours == 0:
hours = 24
print('O JOGO DUROU {} HORA(S)'.format(hours))
if __name__ == '__main__':
main()
|
#https://www.acmicpc.net/problem/4673
a = [0 for i in range(10000)]
def d(n):
total = n
n10000 = n//10000
if n10000 != 0:
n -= 10000*n10000
n1000 = n//1000
if n1000 != 0:
n -= 1000*n1000
n100 = n//100
if n100 != 0:
n -= 100*n100
n10 = n//10
if n10 != 0:
... |
# Different versions of Bazel (e.g. 4.2.2 vs 5.0-pre) can output the query results
# in a different order. It does not appear to be possible to provide a value for
# `--order_output` to `genquery`. So, we will sort the results using this macro.
def sorted_genquery(name, expression, scope, testonly):
raw_query_name... |
def test_empty_build(flamingo_env):
flamingo_env.setup()
flamingo_env.build()
def test_basic_build(flamingo_env):
flamingo_env.write('/content/home.png', '1')
flamingo_env.write('/content/home-2.png', '2')
flamingo_env.write('/theme/static/test.css', '3')
flamingo_env.write('/content/home.rst... |
# -*- coding: utf-8 -*-
{
'!langcode!': 'pt-br',
'!langname!': 'Português (do Brasil)',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" é uma expressão opcional como "campo1=\'novovalor\'". Você não pode atualizar ou apagar os resultados de u... |
segundos = int(input(""))
horas = segundos/3600
minutos = (segundos%3600)/60
segundos = (segundos%60)
print("%d:%d:%d" %(horas,minutos,segundos))
|
class equation:
def __init__(self, a, b, c):
self.__a = a
self.__b = b
self.__c = c
def GetA(self):
return self.__a
def GetB(self):
return self.__b
def GetC(self):
return self.__c
def GetDiscriminant(self): #근의 공식 D값의 제곱
return self.__b ** 2 - 4 * self.__a * self.__c
def GetRoot1(self):
return (-... |
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
leftIndex = 0
rightIndex = len(nums) - 1
result = [0] * len(nums)
resultIndex = len(nums) - 1
while leftIndex <= rightIndex:
if nums[leftIndex] ** 2 > nums[rightIndex] ** 2:
res... |
#!/usr/bin/python3
def new_in_list(my_list, idx, element):
if idx < 0 or (len(my_list) - 1) < idx:
return (my_list)
new_list = my_list.copy()
new_list[idx] = element
return (new_list)
|
class Exchange(object):
def __init__(self, name, asset_types, country_code):
'''
Parameters
----------
name : str
asset_types : list
country_code : str
'''
self._name = name
self._asset_types = asset_types
self._country_code = country_... |
def summa1(jarjend):
tulemus = jarjend[0]
if isinstance(jarjend[1], int):
tulemus += jarjend[1]
else:
tulemus += summa1(jarjend[1])
return tulemus
def summa2(jarjend):
tulemus = jarjend[0]
while isinstance(jarjend[1], list):
jarjend = jarjend[1]
tulemus += jarjen... |
line_input1, line_input2 = sorted(input().split(), key=lambda x: -len(x))
result = 0
for ch in range(len(line_input1)):
if ch < len(line_input2):
result += (ord(line_input1[ch]) * ord(line_input2[ch]))
else:
result += ord(line_input1[ch])
print(result)
|
pyliterals = {
'for': 'The Loop King',
'if': 'The Conditional Master',
'tuple': 'Too Stubborn to be changed',
'list': 'As free as water',
'dictionary': 'Emperor of Information Storage'
}
for literal in pyliterals:
print(literal+": "+pyliterals[literal]+"\n") |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Silvio Peroni <essepuntato@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any purpose
# with or without fee is hereby granted, provided that the above copyright notice
# and this permission notice appear in all copies.
#
# THE SOFTWARE I... |
class Solution:
# @return a list of lists of integers
def generate(self, numRows):
if numRows < 1:
return []
result = [[1]]
for i in range(numRows - 1):
tri = [1]
result.append(tri)
preTri = result[len(result) - 2]
for j in ran... |
# -*- coding: utf-8 -*-
class GildedRose(object):
MAX_QUALITY = 50
MIN_QUALITY = 0
def __init__(self, items):
self.items = items
def update_quality_brie(self, item):
item.sell_in -= 1
item.quality = min(self.MAX_QUALITY, item.quality +1 )
def update_quality_backsta... |
class GenericRecordError(Exception):
pass
class ValidationError(GenericRecordError):
pass
class TableNotSupported(GenericRecordError):
pass
class DuplicateSignature(GenericRecordError):
pass
class GenericVBRError(Exception):
pass
class ConnectionFailedError(GenericVBRError):
pass
cla... |
class DBSPEC(object):
TB_CHECKIN = "bk_checkin"
TB_USER = "bk_user"
TB_FRIENDSHIP = "bk_friendship"
|
# Copyright (c) 2001-2013, Scott D. Peckham
#
#-----------------------------------------------------------------------
#
# unit_test()
#
#-----------------------------------------------------------------------
def unit_test( n_steps=10 ):
c = erosion_component()
c.CCA = False
c.DEBUG = False
c.SI... |
def all_clans():
return {
'Legendary Monks':'#PCCUPG9R',
'SN JAIN':'#2029V92QV',
'Brute Force':'#22PQL2L0R',
'PBfPN':'#22QL8YUC8',
'Wookies':'#298092P99',
'Mini Matter':'#2PJYCQYV9',
'Endor':'#2YLL8UVPY',
'Mos Eisley':'#2YUVPQQCU',
'Killer_Black_Wf':'#8VQYR2LR',
'Golden Clan':'#C2QPR82Q',
'Optimu... |
"""
URL: https://codeforces.com/problemset/problem/1206/B
Author: Safiul Kabir [safiulanik at gmail.com]
Tags: dp, implementation, *900
"""
n = int(input())
a = map(int, input().split())
move_count, count_gtz, count_ltz, count_zero = 0, 0, 0, 0
for i in a:
if i == 0:
count_zero += 1
elif i > 0:
... |
expressao = ''.join(input("Digite sua expressão:").strip().split())
print(expressao)
lista=[]
parenteses_abertos = expressao.count('(')
parenteses_fechados = expressao.count(')')
if parenteses_abertos > parenteses_fechados:
print("Faltou fechar")
elif parenteses_fechados > parenteses_abertos:
print("Faltou abr... |
rus = {
"ek": "й",
"ek": "ё",
}
def _build_letter(let):
return rus[let]
def create_letter(letter=""):
return _build_letter(let)
|
img_size = (992, 736)
img_norm_cfg = dict(mean=[0, 0, 0], std=[255, 255, 255], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True),
dict(
type='MinIoURandomCrop',
min_ious=(0.1, 0.3, 0.5, 0.7, 0.9),
min_crop_size=0.3),
dic... |
ENGLISH_STOPWORDS = '''
i
me
my
myself
we
our
ours
ourselves
you
your
yours
yourself
yourselves
he
him
his
himself
she
her
hers
herself
it
its
itself
they
them
their
theirs
th... |
print('\033[1m>>> MÉDIA ARITMÉTICA <<<\033[m')
n1 = float(input('1ª NOTA: '))
n2 = float(input('2ª NOTA: '))
media = (n1+n2)/2
print('\033[1mRESULTADO FINAL:\033[m')
if media >= 7 and media <10:
print(f'MÉDIA: {media:.2f}.')
print('APROVADO!')
elif media < 7:
print(f'MÉDIA: {media:.2f}.')
prin... |
global edge_id
edge_id = 0
class Edge:
def __init__(self, source, target, weight=1):
global edge_id
self.id = edge_id
edge_id += 1
self.source = source
self.target = target
self.weight = weight
|
def main():
# input
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = list(map(int, input().split()))
# compute
DA = [0]*N
DBC =[0]*N
for i in range(N):
DA[A[i]-1] += 1
for i in range(N):
DBC[B[C[i]-1]-1... |
"""List of API endpoints for OPEN XBL."""
API_PATH = {
"account": "/account",
"account_xuid": "/account/{xuid}",
"achievements": "/achievements",
"achievements_game": "/achievements/title/{titleId}",
"achievements_game_xuid": "/achievements/player/{xuid}/title/{titleid}",
"achievements_history"... |
#This is given a list of mutations, and get the read names that contain the mutation
#Note: We use the CS tag in the alignments, thus each alignment should contain this tag.
class ReadsTracer():
def __init__(self):
pass
#
def trace_reads_from_mutation(self):
pass
#only catch mismatch h... |
code ={
"CONTINUE":100,
"SWITCHING_PROTOCOLS":101,
"PROCESSING":101,
"OK":200,
"CREATED":201,
"ACCEPTED":202,
"NON_AUTHORITATIVE_INFORMATION":203,
"NO_CONTENT":204,
"RESET_CONTENT":205,
"PARTIAL_CONTENT":206,
"MULTI_STATUS":207,
"ALREADY_REPORTED":208,
... |
"""
A file to contain helper functions.
"""
def get_answer():
"""Get an answer."""
return True
|
#lovely lovesea descriotion
lovely_loveseat_description = """ Lovely Loveseat. Tufted polyester blend on wood. 32 inches high x 40 inches wide x inches deep. Red or white"""
lovely_loveseat_price = 254.00
#Stylish settee
stylish_sette_description = """ Stylish settee. Faux leaather on brich. 29.50 inches high x 54.75... |
# Space: O(n)
# Time: O(n)
class Solution:
def maxArea(self, h, w, horizontalCuts, verticalCuts):
horizontalCuts = [0] + horizontalCuts + [h]
verticalCuts = [0] + verticalCuts + [w]
horizontalCuts = sorted(horizontalCuts)
verticalCuts = sorted(verticalCuts)
h_max = max(ho... |
class UndoRedoException(Exception):
"""
Here we create UndoRedoService exceptions that may occur.
"""
def __init__(self, message=''):
self.message = message
# def __str__(self):
# return self.message
class UndoRedoService:
"""
This is undo & redo class.
"""
def __... |
#coding:utf-8
def predict(market,profit,hold,cur_profit_present,stop):
"""
一个极其简单的示例策略,如果空仓则买入,如果有仓位就卖出
"""
if hold==0:
return {'if_buy':1}
else:
return {'if_buy':0}
|
class chipManager():
def __init__(self,chipsize,chipNums):
self.player1chips = chipNums
self.player2chips = chipNums
self.chipsize = chipsize
def getP1Chips():
return self.player1chips
def getP2Chips():
return self.player2chips
def transferToDealer(txToDealer):
if txToDealer:
self.player1chips = s... |
'''
Catalan number `cat(n)`.
Recursive formula:
cat(5) = cat(0)*cat(4) + cat(1)*cat(3) + .. cat(4)*cat(0)
Direct formula:
cat(n) = (2n)! / (n+1)!(n)!
Answer for:
- Number of BST given the number of unique keys.
- Number of binary trees with the same preorder traversal.
- Number of balanced parantheses sequence -... |
# Input : arr[] = {15, 18, 2, 3, 6, 12}
# Output: 2
# Explanation : Initial array must be {2, 3,
# 6, 12, 15, 18}. We get the given array after
# rotating the initial array twice.
# Input : arr[] = {7, 9, 11, 12, 5}
# Output: 4
# Input: arr[] = {7, 9, 11, 12, 15};
# Output: 0
def single_rotation(arr, l):
temp =... |
__version__ = (1, 0, 0, "final", 0)
ADMIN_PIPELINE_CSS = {
'admin_bs3': {
'source_filenames': (
'admintools_bootstrap/chosen/chosen.css',
'admintools_bootstrap/lib/bootstrap-datetimepicker.css',
'admintools_bootstrap/lib/bootstrap-fileupload.scss',
'adminto... |
class DataGenerator(KU.Sequence):
"""An iterable that returns images and corresponding target class ids,
bounding box deltas, and masks. It inherits from keras.utils.Sequence to avoid data redundancy
when multiprocessing=True.
dataset: The Dataset object to pick data from
config: Th... |
# TODO: move this into backend function
def tuple2str(tuple_in):
"""Converts a tuple into a string.
:param tuple_in: tuple to convert
:type tuple_in: tuple
:returns: concatenated string version of the tuple
:rtype: str
"""
string = ''
for i in tuple_in:
string += str(i)
retu... |
t = int(input())
for _ in range(t):
s = [s_temp for s_temp in input().strip()]
#s_len = len(s)
#s_first_half = s[:s_len//2]
#s_second_half = s[s_len//2+s_len%2:][::-1]
op = 0
for i in range(len(s)//2):
#op += ord(max(s_first_half[i], s_second_half[i])) - ord(min(s_first_half[i],... |
def is_macro_action(unit_command_action, abilities):
"""
This function determines if a unit_command action is a macro action
based on the following criteria: if the action is related to training, morphing,
researching or building units or technologies, then it is a macro action. It
returns a boolean.
Feel fr... |
def n_lower_cases(string):
return sum([int(c.islower()) for c in string])
def n_upper_cases(string):
return sum([int(c.isupper()) for c in string])
def n_whitespace(string):
cnt = 0.0
for c in string:
if c == '_':
cnt += 1
return cnt
string = input()
symb_amt = n_whitespace(str... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.