content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def even_odd(*args):
args = list(args)
command = args.pop()
if command == "even":
return [x for x in args if x % 2 == 0]
return [x for x in args if not x % 2 == 0]
print(even_odd(1, 2, 3, 4, 5, 6, "even"))
print(even_odd(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "odd"))
| def even_odd(*args):
args = list(args)
command = args.pop()
if command == 'even':
return [x for x in args if x % 2 == 0]
return [x for x in args if not x % 2 == 0]
print(even_odd(1, 2, 3, 4, 5, 6, 'even'))
print(even_odd(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'odd')) |
"""werf_chart_repo_doit_tasks - Doit Tasks for managing Werf chart repo"""
__version__ = '1.0.6'
__author__ = 'Ilya Lesikov <ilya@lesikov.com>'
__all__ = []
| """werf_chart_repo_doit_tasks - Doit Tasks for managing Werf chart repo"""
__version__ = '1.0.6'
__author__ = 'Ilya Lesikov <ilya@lesikov.com>'
__all__ = [] |
class UnionFind():
def __init__(self, n) -> None:
self.par = [-1] * n
self.siz = [1] * n
# return root of x
def root(self, x):
if self.par[x] == -1:
return x
else:
self.par[x] = self.root(self.par[x])
return self.par[x]
# ret... | class Unionfind:
def __init__(self, n) -> None:
self.par = [-1] * n
self.siz = [1] * n
def root(self, x):
if self.par[x] == -1:
return x
else:
self.par[x] = self.root(self.par[x])
return self.par[x]
def issame(self, x, y):
return... |
"""
A custom immutable dictionary data structure
"""
class CustomImmutableDict(dict):
def __getattr__(self, key):
try:
return self[key]
except KeyError as k:
raise AttributeError(k)
def __setattr__(self, key, value):
# self[key] = value
return self._imm... | """
A custom immutable dictionary data structure
"""
class Customimmutabledict(dict):
def __getattr__(self, key):
try:
return self[key]
except KeyError as k:
raise attribute_error(k)
def __setattr__(self, key, value):
return self._immutable()
def __delattr... |
class Node:
def __init__(self, k, v):
self.key = k
self.val = v
self.pre = None
self.nxt = None
class LRUCache:
def __init__(self, capacity: int):
self.store = {}
self.curCap = 0
self.cap = capacity
self.tail = Node(0, 0)
self.head = Nod... | class Node:
def __init__(self, k, v):
self.key = k
self.val = v
self.pre = None
self.nxt = None
class Lrucache:
def __init__(self, capacity: int):
self.store = {}
self.curCap = 0
self.cap = capacity
self.tail = node(0, 0)
self.head = nod... |
# Lab 5
'''
G=(V,E)
Let V be the set v0,v1,v2,...
(i.e., with ascending non-negative indices)
and E be the set e0,e1,e2,...
(i.e., with ascending non-negative indices)
'''
class stack:
def __init__(self):
self.lifo = []
def push(self,ele):
self.lifo = self.lifo + [ele]
return True
def po... | """
G=(V,E)
Let V be the set v0,v1,v2,...
(i.e., with ascending non-negative indices)
and E be the set e0,e1,e2,...
(i.e., with ascending non-negative indices)
"""
class Stack:
def __init__(self):
self.lifo = []
def push(self, ele):
self.lifo = self.lifo + [ele]
return True
def p... |
# omnibool.py
# https://www.codewars.com/kata/5a5f9f80f5dc3f942b002309/train/python
class Omnibool():
def __eq__(self, x):
return True
if __name__ == "__main__":
omnibool = Omnibool()
print(omnibool == True and omnibool == False)
| class Omnibool:
def __eq__(self, x):
return True
if __name__ == '__main__':
omnibool = omnibool()
print(omnibool == True and omnibool == False) |
def get_test_accounts() -> dict:
return {
'development': {
'color': '#388E3C',
'team': 'awesome-team',
'region': 'us-east-1',
'profiles': [
{
'profile': 'developer',
'account': '123495678901',
... | def get_test_accounts() -> dict:
return {'development': {'color': '#388E3C', 'team': 'awesome-team', 'region': 'us-east-1', 'profiles': [{'profile': 'developer', 'account': '123495678901', 'role': 'developer', 'default': 'true'}, {'profile': 'readonly', 'account': '012349567890', 'role': 'readonly'}]}, 'live': {'co... |
def NoC():
paid = int(input())
moneyL = [500, 100, 50, 10, 5, 1]
count = 0
leftOver = 1000 - paid
for each in moneyL:
n = leftOver//each
if n > 0:
count += n
leftOver -= n * each
elif n == 0:
pass
return count
print(NoC()) | def no_c():
paid = int(input())
money_l = [500, 100, 50, 10, 5, 1]
count = 0
left_over = 1000 - paid
for each in moneyL:
n = leftOver // each
if n > 0:
count += n
left_over -= n * each
elif n == 0:
pass
return count
print(no_c()) |
class SourceDto:
"""Data transfer object class for Source-type Airbyte abstractions"""
def __init__(self):
self.source_definition_id = None
self.source_id = None
self.workspace_id = None
self.connection_configuration = {}
self.name = None
self.source_name = None
... | class Sourcedto:
"""Data transfer object class for Source-type Airbyte abstractions"""
def __init__(self):
self.source_definition_id = None
self.source_id = None
self.workspace_id = None
self.connection_configuration = {}
self.name = None
self.source_name = None
... |
def get_average(g):
return sum(g) / len(g)
n = int(input())
students_record = {}
for _ in range(n):
student, grade = input().split()
if student not in students_record:
students_record[student] = []
students_record[student].append(float(grade))
for s, g in students_record.items():
ave... | def get_average(g):
return sum(g) / len(g)
n = int(input())
students_record = {}
for _ in range(n):
(student, grade) = input().split()
if student not in students_record:
students_record[student] = []
students_record[student].append(float(grade))
for (s, g) in students_record.items():
average... |
names = ["Alan", "Bruce", "Carlos", "David", "Emma"]
scores = [90, 80, 85, 92, 81]
for name in names:
print("hello, %s!" % name)
| names = ['Alan', 'Bruce', 'Carlos', 'David', 'Emma']
scores = [90, 80, 85, 92, 81]
for name in names:
print('hello, %s!' % name) |
"""
This module takes an adapter as data supplier, pack data and provide data for data iterators
"""
class ProviderBaseclass(object):
"""
This is the baseclass of packer. Any other detailed packer must inherit this class.
"""
def __init__(self):
pass
def __str__(self):
return se... | """
This module takes an adapter as data supplier, pack data and provide data for data iterators
"""
class Providerbaseclass(object):
"""
This is the baseclass of packer. Any other detailed packer must inherit this class.
"""
def __init__(self):
pass
def __str__(self):
return sel... |
def insertShiftArray(arr, num):
count = len(arr)
middle = len(arr) // 2
shift_arr = []
for i in range(count):
if i != middle:
shift_arr.append(arr[i])
else:
if count % 2 == 0:
shift_arr.append(num)
shift_arr.append(arr[i])
... | def insert_shift_array(arr, num):
count = len(arr)
middle = len(arr) // 2
shift_arr = []
for i in range(count):
if i != middle:
shift_arr.append(arr[i])
elif count % 2 == 0:
shift_arr.append(num)
shift_arr.append(arr[i])
else:
shift... |
"""Reusable unique item gatherer. Returns unique values with optional list_in and blacklists"""
class GatherUnique:
"""
Reusable unique item gatherer. Returns unique values with optional list_in and blacklists
"""
def __init__(self):
self._header = ''
"""Optional header to display to... | """Reusable unique item gatherer. Returns unique values with optional list_in and blacklists"""
class Gatherunique:
"""
Reusable unique item gatherer. Returns unique values with optional list_in and blacklists
"""
def __init__(self):
self._header = ''
'Optional header to display to use... |
"""
consensys_utils.flask.config
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
App configuration
:copyright: Copyright 2017 by ConsenSys France.
:license: BSD, see :ref:`license` for more details.
"""
def set_app_config(app, config=None):
"""Set application configuration
:param app: Flask application
... | """
consensys_utils.flask.config
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
App configuration
:copyright: Copyright 2017 by ConsenSys France.
:license: BSD, see :ref:`license` for more details.
"""
def set_app_config(app, config=None):
"""Set application configuration
:param app: Flask application
... |
# Carve
# sigs = [255,214,124,179,233]
# msks = [0,9,3,12,6]
# Door
# sigs = [192,48]
# msks = [15,15]
# Freestanding
# sigs=[0,0,0,0,16,64,32,128,161,104,84,146]
# msks=[8,4,2,1,6,12,9,3,10,5,10,5]
# Walls
sigs=[251,233,253,84,146,80,16,144,112,208,241,248,210,177,225,120,179,0,124,104,161,64,240,128,224,176,242,24... | sigs = [251, 233, 253, 84, 146, 80, 16, 144, 112, 208, 241, 248, 210, 177, 225, 120, 179, 0, 124, 104, 161, 64, 240, 128, 224, 176, 242, 244, 116, 232, 178, 212, 247, 214, 254, 192, 48, 96, 32, 160, 245, 250, 243, 249, 246, 252]
msks = [0, 6, 0, 11, 13, 11, 15, 13, 3, 9, 0, 0, 9, 12, 6, 3, 12, 15, 3, 7, 14, 15, 0, 15, ... |
# -*- coding: utf-8 -*-
"""
authors: Dawud Hage, Joost Meulenbeld, Joost Dorscheidt and Dennis van der Hoff
written for the NN course IN4015 of the TUDelft
"""
##### SETTINGS: #####
# Number of epochs to train the network over
n_epoch = 0
# Folder where the training superbatches are stored
training_folder= 'selecti... | """
authors: Dawud Hage, Joost Meulenbeld, Joost Dorscheidt and Dennis van der Hoff
written for the NN course IN4015 of the TUDelft
"""
n_epoch = 0
training_folder = 'selection'
validation_folder = 'selection'
colorspace = 'CIELab'
param_folder = 'params_final_final'
param_file = 'params_fruit_Compact_more_end_fmaps_... |
#
# PySNMP MIB module ZONE-DEFENSE-MGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZONE-DEFENSE-MGMT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:48:06 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint) ... |
class ToolStripItemEventArgs(EventArgs):
"""
Provides data for System.Windows.Forms.ToolStripItem events.
ToolStripItemEventArgs(item: ToolStripItem)
"""
def __getitem__(self, *args):
""" x.__getitem__(y) <==> x[y] """
pass
@staticmethod
def __new__(self, item):
... | class Toolstripitemeventargs(EventArgs):
"""
Provides data for System.Windows.Forms.ToolStripItem events.
ToolStripItemEventArgs(item: ToolStripItem)
"""
def __getitem__(self, *args):
""" x.__getitem__(y) <==> x[y] """
pass
@staticmethod
def __new__(self, item):
""" __ne... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
class ClassPropertyDescriptor:
def __init__(self, fget):
self.fget = fget
def __get__(self, obj, klass=None):
if klass is None:
klass = type(obj)
return self.fget.__get__(obj, kl... | class Classpropertydescriptor:
def __init__(self, fget):
self.fget = fget
def __get__(self, obj, klass=None):
if klass is None:
klass = type(obj)
return self.fget.__get__(obj, klass)()
def classproperty(func):
"""
Allow for getter property usage on classmethods
... |
print('4. testing integrated scan functions:')
print('testing xanes')
xanes(erange = [7112-30, 7112-20, 7112+30],
estep = [2, 5],
harmonic = None,
acqtime=0.2, roinum=1, i0scale = 1e8, itscale = 1e8,samplename='test',filename='test')
| print('4. testing integrated scan functions:')
print('testing xanes')
xanes(erange=[7112 - 30, 7112 - 20, 7112 + 30], estep=[2, 5], harmonic=None, acqtime=0.2, roinum=1, i0scale=100000000.0, itscale=100000000.0, samplename='test', filename='test') |
class CouldNotConfigureException(BaseException):
def __str__(self):
return "Could not configure the repository."
class NotABinaryExecutableException(BaseException):
def __str__(self):
return "The file given is not a binary executable"
class ParametersNotAcceptedException(BaseException):
... | class Couldnotconfigureexception(BaseException):
def __str__(self):
return 'Could not configure the repository.'
class Notabinaryexecutableexception(BaseException):
def __str__(self):
return 'The file given is not a binary executable'
class Parametersnotacceptedexception(BaseException):
... |
#
# PySNMP MIB module Nortel-MsCarrier-MscPassport-BaseSnmpMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-BaseSnmpMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:19:57 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davw... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_union, value_size_constraint, constraints_intersection) ... |
c = open("__21_d03.txt")
lin = c.readlines()
## Part 1
klin = [list([lin[i].split("\n")[0] for i in range(len(lin))][j]) for j in range(len(lin))]
k2 = [1 if [klin[jj][len(klin[0])-ii-1] for jj in range(len(lin))].count('1') > [klin[jj][len(klin[0])-ii-1] for jj in range(len(lin))].count('0') else 0 for ii in range(... | c = open('__21_d03.txt')
lin = c.readlines()
klin = [list([lin[i].split('\n')[0] for i in range(len(lin))][j]) for j in range(len(lin))]
k2 = [1 if [klin[jj][len(klin[0]) - ii - 1] for jj in range(len(lin))].count('1') > [klin[jj][len(klin[0]) - ii - 1] for jj in range(len(lin))].count('0') else 0 for ii in range(len(k... |
# config.py
# encoding:utf-8
DEBUG = True
JSON_AS_ASCII = False
| debug = True
json_as_ascii = False |
num = 42
list_of_numbers = []
for i in range(1, num+1):
list_of_numbers.append(i)
print(list_of_numbers)
death = 3
for i in list_of_numbers:
if i == num:
if i == death:
print("XX")
else:
print(i)
elif i < 10:
if i == death:
print(f"XX", end=" -... | num = 42
list_of_numbers = []
for i in range(1, num + 1):
list_of_numbers.append(i)
print(list_of_numbers)
death = 3
for i in list_of_numbers:
if i == num:
if i == death:
print('XX')
else:
print(i)
elif i < 10:
if i == death:
print(f'XX', end=' - '... |
class Solution:
def numMovesStonesII(self, stones: List[int]) -> List[int]:
def helper():
n = len(stones)
if (stones[-2] - stones[0] == n - 2 and stones[-1] - stones[-2] > 2) or (stones[-1] - stones[1] == n - 2 and stones[1] - stones[0] > 2):
return 2
dq =... | class Solution:
def num_moves_stones_ii(self, stones: List[int]) -> List[int]:
def helper():
n = len(stones)
if stones[-2] - stones[0] == n - 2 and stones[-1] - stones[-2] > 2 or (stones[-1] - stones[1] == n - 2 and stones[1] - stones[0] > 2):
return 2
d... |
class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
order_indx = {}
for idx,letter in enumerate(order):
order_indx[letter] = idx
# compare adjacent words
for i in range(len(words)-1):
word1 = words[i]
w... | class Solution:
def is_alien_sorted(self, words: List[str], order: str) -> bool:
order_indx = {}
for (idx, letter) in enumerate(order):
order_indx[letter] = idx
for i in range(len(words) - 1):
word1 = words[i]
word2 = words[i + 1]
if word1 == ... |
def center(win, width=100, height=100):
win.update_idletasks()
width = width
frm_width = win.winfo_rootx() - win.winfo_x()
win_width = width + 2 * frm_width
height = height
titlebar_height = win.winfo_rooty() - win.winfo_y()
win_height = height + titlebar_height + frm_width
x = win.wi... | def center(win, width=100, height=100):
win.update_idletasks()
width = width
frm_width = win.winfo_rootx() - win.winfo_x()
win_width = width + 2 * frm_width
height = height
titlebar_height = win.winfo_rooty() - win.winfo_y()
win_height = height + titlebar_height + frm_width
x = win.winfo... |
array = list(map(int, input('Enter the array of integers to be sorted(separated by spaces):').split()))
for i in range(len(array)):
min_idx = i
for j in range(i + 1, len(array)):
if array[min_idx] > array[j]:
min_idx = j
array[i], array[min_idx] = array[min_idx], array[i]
print("Sorted ... | array = list(map(int, input('Enter the array of integers to be sorted(separated by spaces):').split()))
for i in range(len(array)):
min_idx = i
for j in range(i + 1, len(array)):
if array[min_idx] > array[j]:
min_idx = j
(array[i], array[min_idx]) = (array[min_idx], array[i])
print('Sort... |
# -*- coding: utf-8 -*-
class CertstreamObject(object):
"""Base class for all the certstream data classes"""
@classmethod
def from_dict(cls, data):
"""
Returns a copy of the passed data
:param data: The dict from which an object should be created from
:return: copy of data... | class Certstreamobject(object):
"""Base class for all the certstream data classes"""
@classmethod
def from_dict(cls, data):
"""
Returns a copy of the passed data
:param data: The dict from which an object should be created from
:return: copy of data or None
"""
... |
batch_size = 192*4
config = {}
# set the parameters related to the training and testing set
data_train_opt = {}
data_train_opt['batch_size'] = batch_size
data_train_opt['unsupervised'] = True
data_train_opt['epoch_size'] = None
data_train_opt['random_sized_crop'] = False
data_train_opt['dataset_name'] = 'imagenet'
... | batch_size = 192 * 4
config = {}
data_train_opt = {}
data_train_opt['batch_size'] = batch_size
data_train_opt['unsupervised'] = True
data_train_opt['epoch_size'] = None
data_train_opt['random_sized_crop'] = False
data_train_opt['dataset_name'] = 'imagenet'
data_train_opt['split'] = 'train'
data_test_opt = {}
data_test_... |
# -*- coding: utf-8 -*-
def main():
n = int(input())
ans = 0
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0 and (i ** 2) != n:
m = n // i - 1
if n // m == n % m:
ans += m
print(ans)
if __name__ == '__main__':
main()
| def main():
n = int(input())
ans = 0
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0 and i ** 2 != n:
m = n // i - 1
if n // m == n % m:
ans += m
print(ans)
if __name__ == '__main__':
main() |
"""
Collection of lists and dicts representing types in the python C-API
"""
"""
CPython's function pointers as dict:
typename: (return_type, (args,))
"""
FUNCTIONS = {
"unaryfunc": ("PyObject*", ("PyObject*",)),
"binaryfunc": ("PyObject*", ("PyObject*", "PyObject*")),
"ternaryfunc... | """
Collection of lists and dicts representing types in the python C-API
"""
"\nCPython's function pointers as dict:\ntypename: (return_type, (args,))\n"
functions = {'unaryfunc': ('PyObject*', ('PyObject*',)), 'binaryfunc': ('PyObject*', ('PyObject*', 'PyObject*')), 'ternaryfunc': ('PyObject*', ('PyObject*', 'PyObject... |
#
# PySNMP MIB module DOT3-OAM-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/DOT3-OAM-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:10:39 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( In... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, constraints_intersection, single_value_constraint, value_size_constraint) ... |
# base
class FyException(Exception):
def __init__(s, message):
s.message = '\n;;;;;\n'
s.message += s.__class__.__name__.replace('_', ' ')
s.message += '\n'
s.message += str(message)
def __str__(s):
return s.message
# exception
class a_function_cannot_be_dotted(FyException):
pass
class cannot_indent_on_... | class Fyexception(Exception):
def __init__(s, message):
s.message = '\n;;;;;\n'
s.message += s.__class__.__name__.replace('_', ' ')
s.message += '\n'
s.message += str(message)
def __str__(s):
return s.message
class A_Function_Cannot_Be_Dotted(FyException):
pass
cl... |
# 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.
load("//antlir/bzl:shape.bzl", "shape")
load("//antlir/bzl:target_helpers.bzl", "antlir_dep")
load("//antlir/bzl:target_tagger.bzl", "new_ta... | load('//antlir/bzl:shape.bzl', 'shape')
load('//antlir/bzl:target_helpers.bzl', 'antlir_dep')
load('//antlir/bzl:target_tagger.bzl', 'new_target_tagger', 'target_tagger_to_feature')
load(':symlink.shape.bzl', 'symlink_t')
def _build_symlink_feature(link_target, link_name, symlinks_to_arg):
symlink_spec = shape.new... |
# Palanquin (9110107) | Outside Ninja Castle (800040000)
mushroomShrine = 800000000
response = sm.sendAskYesNo("Would you like to go to #m" + str(mushroomShrine) + "m#?")
if response:
sm.warp(mushroomShrine) | mushroom_shrine = 800000000
response = sm.sendAskYesNo('Would you like to go to #m' + str(mushroomShrine) + 'm#?')
if response:
sm.warp(mushroomShrine) |
f = open("./three.txt", "r")
lines = [x.strip() for x in f.readlines()]
gamma = ""
for index in range(len(lines[0])):
bits = [line[index] for line in lines]
zeros = list(bits).count('0')
ones = list(bits).count('1')
if zeros > ones:
gamma += "0"
else:
gamma += "1"
epsilon = ""
for... | f = open('./three.txt', 'r')
lines = [x.strip() for x in f.readlines()]
gamma = ''
for index in range(len(lines[0])):
bits = [line[index] for line in lines]
zeros = list(bits).count('0')
ones = list(bits).count('1')
if zeros > ones:
gamma += '0'
else:
gamma += '1'
epsilon = ''
for in... |
#!/usr/bin/python
#
# Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es)
#
# 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
... | in = None
inout = None
file_in = None
file_out = None
file_inout = None
collection_in = None
collection_inout = None
collection_out = None
type = 'type'
direction = 'direction'
std_io_stream = 'stream'
prefix = 'prefix'
depth = 'depth'
block_count = 'block_count'
block_length = 'block_length'
stride = 'stride' |
"""
Test group in a different order
.. pii: Group 1 - Annotation 1
.. pii_retirement: local_api, consumer_api
.. pii_types: id, name
"""
| """
Test group in a different order
.. pii: Group 1 - Annotation 1
.. pii_retirement: local_api, consumer_api
.. pii_types: id, name
""" |
def bin_search_lower(a, x):
l, r = -1, len(a)
while l + 1 < r:
m = (l + r) // 2
if a[m] <= x:
l = m
else:
r = m
return l
n, k = map(int, input().split())
array = list(map(int, input().split()))
for x in map(int, input().split()):
print(bin_search_lower(... | def bin_search_lower(a, x):
(l, r) = (-1, len(a))
while l + 1 < r:
m = (l + r) // 2
if a[m] <= x:
l = m
else:
r = m
return l
(n, k) = map(int, input().split())
array = list(map(int, input().split()))
for x in map(int, input().split()):
print(bin_search_low... |
class State:
def __init__(self, client) -> None:
self.client = client
def get_input_command(self):
return input(f"JogoDaVelha> ").strip().split() or [""]
def handle_input_command(self, *input_command):
pass
def handle_opponent_command(self, *command):
pass
def han... | class State:
def __init__(self, client) -> None:
self.client = client
def get_input_command(self):
return input(f'JogoDaVelha> ').strip().split() or ['']
def handle_input_command(self, *input_command):
pass
def handle_opponent_command(self, *command):
pass
def ha... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
spinMultiplicity = 2
energy = {
'CCSD(T)-F12/cc-pVTZ-F12': MolproLog('TSN09_f12.out'),
}
frequencies = GaussianLog('ts3-freq.log')
rotors = [HinderedRotor(scanLog=ScanLog('scan_0.log'), pivots=[4,10], top=[10,11,12,13,14], symmetry=1, fit='best'),
HinderedRotor(scanLog=... | spin_multiplicity = 2
energy = {'CCSD(T)-F12/cc-pVTZ-F12': molpro_log('TSN09_f12.out')}
frequencies = gaussian_log('ts3-freq.log')
rotors = [hindered_rotor(scanLog=scan_log('scan_0.log'), pivots=[4, 10], top=[10, 11, 12, 13, 14], symmetry=1, fit='best'), hindered_rotor(scanLog=scan_log('scan_1.log'), pivots=[10, 13], t... |
"""
Featurizers will always output arrays
but they will use structure-oriented methods
underneath to do it.
"""
| """
Featurizers will always output arrays
but they will use structure-oriented methods
underneath to do it.
""" |
a, b = map(int, input().split())
a = str(a)
b = str(b)
count = 0
c = int(a)
d = int(b)
for i in range(c, d + 1):
i = str(i)
if i[0] == i[4] and i[1] == i[3]:
count += 1
print(count) | (a, b) = map(int, input().split())
a = str(a)
b = str(b)
count = 0
c = int(a)
d = int(b)
for i in range(c, d + 1):
i = str(i)
if i[0] == i[4] and i[1] == i[3]:
count += 1
print(count) |
#!/usr/local/bin/python
# coding: utf-8
VERSION = '2.1.1'
# 0: CRITICAL, 1: INFO, 2: DEBUG
VERBOSE_LEVEL = 1
# 0: CONSOLE, 1: FILE, 2: CONSOLE & FILE
LOG_TYPE = 0
LOG_DIR = 'output'
HTML = False
DEBUG = True
| version = '2.1.1'
verbose_level = 1
log_type = 0
log_dir = 'output'
html = False
debug = True |
class Human:
def __init__(self, name, age):
self.name = name
self.age = age
def greeting(self):
print(f"Hello {self.name}!")
def get_name(self):
return self.name
def get_age(self):
return self.age
def set_age(self, age):
self.ag... | class Human:
def __init__(self, name, age):
self.name = name
self.age = age
def greeting(self):
print(f'Hello {self.name}!')
def get_name(self):
return self.name
def get_age(self):
return self.age
def set_age(self, age):
self.age = age
h = human('... |
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
num_len = len(nums)
prefix_products, postfix_products = [1] * (num_len + 1), [1] * (num_len + 1)
prefix_product, postfix_product = 1, 1
for prefix_index in range(num_len):
prefix_product *= nu... | class Solution:
def product_except_self(self, nums: List[int]) -> List[int]:
num_len = len(nums)
(prefix_products, postfix_products) = ([1] * (num_len + 1), [1] * (num_len + 1))
(prefix_product, postfix_product) = (1, 1)
for prefix_index in range(num_len):
prefix_product... |
CREATE_GAME = 'game_create'
JOIN_GAME = 'game_join'
LEAVE_GAME = 'game_abort'
SET_NICK = 'nickname_set'
INIT_BOARD = 'board_init'
FIRE = 'attack'
NUKE = 'special_attack'
MOVE = 'move'
SURRENDER = 'surrender'
CHAT_SEND = 'chat_send'
| create_game = 'game_create'
join_game = 'game_join'
leave_game = 'game_abort'
set_nick = 'nickname_set'
init_board = 'board_init'
fire = 'attack'
nuke = 'special_attack'
move = 'move'
surrender = 'surrender'
chat_send = 'chat_send' |
# -*- coding: utf-8 -*-
class Stack(object):
""" Implements a simple stack data structure.
Attrs:
top: object, a pointer to the top object in the stack.
count: int, a counter of the number of elements in the stack.
"""
def __init__(self):
self.top = None
self.count = 0... | class Stack(object):
""" Implements a simple stack data structure.
Attrs:
top: object, a pointer to the top object in the stack.
count: int, a counter of the number of elements in the stack.
"""
def __init__(self):
self.top = None
self.count = 0
def __len__(self):
... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1:
return l2
if not l2:
return l1
r... | class Solution:
def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1:
return l2
if not l2:
return l1
res = list_node(-1)
if l1.val < l2.val:
res.val = l1.val
res.next = self.mergeTwoLists(l1.next, l2)
el... |
# Depth-first Search
# Given an integer array, your task is to find all the different possible increasing subsequences of the given array, and the length of an increasing subsequence should be at least 2 .
#
# Example:
# Input: [4, 6, 7, 7]
# Output: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], ... | class Solution:
def find_subsequences(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
self.subsets(nums, 0, [], res)
return res
def subsets(self, nums, index, temp, res):
if len(nums) >= index and len(temp) >= 2:
... |
odds = {1, 3, 5, 7}
evens = set([0, 2, 4, 6, 8])
print(odds.union(evens))
odds.intersection()
odds.difference() | odds = {1, 3, 5, 7}
evens = set([0, 2, 4, 6, 8])
print(odds.union(evens))
odds.intersection()
odds.difference() |
def f1():
print(11)
yield
print(22)
yield
print(33)
def f2():
print(55)
yield
print(66)
yield
print(77)
v1 = f1()
v2 = f2()
next(v1) # v1.send(None)
next(v2) # v1.send(None)
next(v1) # v1.send(None)
next(v2) # v1.send(None)
next(v1) # v1.send(None)
next(v2) # v1.send(N... | def f1():
print(11)
yield
print(22)
yield
print(33)
def f2():
print(55)
yield
print(66)
yield
print(77)
v1 = f1()
v2 = f2()
next(v1)
next(v2)
next(v1)
next(v2)
next(v1)
next(v2) |
## Gerenators
def mygenerator(x):
for i in range(x):
yield i
values = mygenerator(100)
for i in values:
print(i)
print(next(mygenerator)) | def mygenerator(x):
for i in range(x):
yield i
values = mygenerator(100)
for i in values:
print(i)
print(next(mygenerator)) |
__author__ = 'yinjun'
#@see http://www.jiuzhang.com/solutions/longest-common-subsequence/
class Solution:
"""
@param A, B: Two strings.
@return: The length of longest common subsequence of A and B.
"""
def longestCommonSubsequence(self, A, B):
# write your code here
x = len(A)
... | __author__ = 'yinjun'
class Solution:
"""
@param A, B: Two strings.
@return: The length of longest common subsequence of A and B.
"""
def longest_common_subsequence(self, A, B):
x = len(A)
y = len(B)
dp = [[0 for j in range(y + 1)] for i in range(x + 1)]
for i in ra... |
class Node:
def __init__(self, key):
self.key = key
self.child = []
def newNode(key):
temp = Node(key)
return temp
def LevelOrderTraversal(root):
if (root == None):
return;
# Standard level order traversal code
# using queue
q = [] # Create a queue
q.append(... | class Node:
def __init__(self, key):
self.key = key
self.child = []
def new_node(key):
temp = node(key)
return temp
def level_order_traversal(root):
if root == None:
return
q = []
q.append(root)
while len(q) != 0:
n = len(q)
while n > 0:
... |
def add_up(nums):
return sum(nums)
def test_answer():
assert add_up([1,2,2]) == 5 | def add_up(nums):
return sum(nums)
def test_answer():
assert add_up([1, 2, 2]) == 5 |
#!/usr/bin/python3
def read_file(filename=""):
'''open a given file'''
with open(filename, 'r') as f:
print("{}".format(f.read()), end="")
| def read_file(filename=''):
"""open a given file"""
with open(filename, 'r') as f:
print('{}'.format(f.read()), end='') |
class Node:
def __init__(self, x, y):
self.g = 0
self.h = 0
self.f = 0
self.parent = None
self.cost = 1
self.x = x
self.y = y
self.left_child = None
self.right_child = None
self.top_child = None
self.down_child = None
def u... | class Node:
def __init__(self, x, y):
self.g = 0
self.h = 0
self.f = 0
self.parent = None
self.cost = 1
self.x = x
self.y = y
self.left_child = None
self.right_child = None
self.top_child = None
self.down_child = None
def ... |
def clever_format(num, format="%.2f"):
if num > 1e12:
return format % (num / 1e12) + "T"
if num > 1e9:
return format % (num / 1e9) + "G"
if num > 1e6:
return format % (num / 1e6) + "M"
if num > 1e3:
return format % (num / 1e3) + "K"
| def clever_format(num, format='%.2f'):
if num > 1000000000000.0:
return format % (num / 1000000000000.0) + 'T'
if num > 1000000000.0:
return format % (num / 1000000000.0) + 'G'
if num > 1000000.0:
return format % (num / 1000000.0) + 'M'
if num > 1000.0:
return format % (n... |
## PACKAGE THIS FUNCTION INTO MAVENN
def split_dataset(data_df,
set_col='set',
train_set_name='training',
val_set_name='validation',
test_set_name='test'):
"""
Splits dataset into
(1) `trainval_df`: training + validation set
... | def split_dataset(data_df, set_col='set', train_set_name='training', val_set_name='validation', test_set_name='test'):
"""
Splits dataset into
(1) `trainval_df`: training + validation set
(2) `train_df`: test set
based on the value of the column `set_col`, which is then dropped. Also
add... |
n,k=map(int,input().split())
x=sorted(list(map(int,input().split())))
a=[]
for i in range(n-k+1):
l=x[i]
r=x[i+k-1]
a.append(min(abs(l)+abs(r-l),abs(r)+abs(l-r)))
print(min(a)) | (n, k) = map(int, input().split())
x = sorted(list(map(int, input().split())))
a = []
for i in range(n - k + 1):
l = x[i]
r = x[i + k - 1]
a.append(min(abs(l) + abs(r - l), abs(r) + abs(l - r)))
print(min(a)) |
class Cell:
def __init__(self, alive = False):
self.currentState = alive
self.futureState = alive
def updateState(self, state):
self.futureState = state
def refresh(self):
self.currentState = self.futureState
def isAlive(self):
return self.cur... | class Cell:
def __init__(self, alive=False):
self.currentState = alive
self.futureState = alive
def update_state(self, state):
self.futureState = state
def refresh(self):
self.currentState = self.futureState
def is_alive(self):
return self.currentState
de... |
str1 = input()
str2 = input()
a = [0 for i in range(0,27)]
for i in str1:
a[ord(i)-ord('a')] += 1
for i in str2:
a[ord(i)-ord('a')] -= 1
ans = 0
for i in a:
if ( i < 0 ):
ans += -i
else:
ans += i
print(ans) | str1 = input()
str2 = input()
a = [0 for i in range(0, 27)]
for i in str1:
a[ord(i) - ord('a')] += 1
for i in str2:
a[ord(i) - ord('a')] -= 1
ans = 0
for i in a:
if i < 0:
ans += -i
else:
ans += i
print(ans) |
class GameInfo(object):
"""
holds player information for the current game
"""
def __init__(self, team_name, match_token, team_password, client_token = ''):
self.client_token = client_token
self.team_name = team_name
self.match_token = match_token
self.team_password = tea... | class Gameinfo(object):
"""
holds player information for the current game
"""
def __init__(self, team_name, match_token, team_password, client_token=''):
self.client_token = client_token
self.team_name = team_name
self.match_token = match_token
self.team_password = team_... |
#############################################################################
#
#
# RGB/A Colour webGenFramework module to BFA c7
#
#
#############################################################################
""" This is a rgb/a colour module for bfa colours.
Dependencies:
None
note:: Author(s): Mi... | """ This is a rgb/a colour module for bfa colours.
Dependencies:
None
note:: Author(s): Mitch last-check: 07.07.2021 """
def __preload__(forClient: bool=True):
pass
def __postload__(forClient: bool=True):
pass
class Colour:
""" Base class for representing any colour.
:param name:... |
def serializeCgiToServer(coors): #coors is a n by 2 2D array of doubles
string = ""
for i in range(0, len(coors)):
string += str(coors[i][0]) + "," + str(coors[i][1]) # add comma between x and y coor
string += ";" # add semicolon to seperate coors
string += "\n" #ending character
return ... | def serialize_cgi_to_server(coors):
string = ''
for i in range(0, len(coors)):
string += str(coors[i][0]) + ',' + str(coors[i][1])
string += ';'
string += '\n'
return string.encode('utf-8')
def deserialize_cgi_to_server(string):
string = string.decode('utf-8')
splitted = string.... |
#
# PySNMP MIB module CISCOSB-SENSORENTMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-SENSORENTMIB
# Produced by pysmi-0.3.4 at Wed May 1 12:23:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, single_value_constraint, value_size_constraint, value_range_constraint) ... |
count = 0
fields = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]
hex_not = "1234567890abcdef"
ecls = ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]
def check_pprt(pprt):
global count
flag = True
i = 0
while flag and i < len(fields):
flag = flag and fields[i] in pprt
i = i + 1
... | count = 0
fields = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']
hex_not = '1234567890abcdef'
ecls = ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth']
def check_pprt(pprt):
global count
flag = True
i = 0
while flag and i < len(fields):
flag = flag and fields[i] in pprt
i = i + 1
... |
#OPERATOR PENUGASAN
#input mengisi nilai
nilai_x=int(input("masukan nilai x: "))
#operator penjumlahan
nilai_x +=20
print("hasil jumlah: ", nilai_x)
nilai_x=int(input("masukan nilai x: "))
#operator pengurangan
nilai_x -=10
print("hasil kurang:",nilai_x)
nilai_x=int(input("masukan nilai x: "))
#opera... | nilai_x = int(input('masukan nilai x: '))
nilai_x += 20
print('hasil jumlah: ', nilai_x)
nilai_x = int(input('masukan nilai x: '))
nilai_x -= 10
print('hasil kurang:', nilai_x)
nilai_x = int(input('masukan nilai x: '))
nilai_x *= 10
print('hasil kali:', nilai_x)
nilai_x = int(input('masukan nilai x: '))
nilai_x /= 30
p... |
#author SANKALP SAXENA
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
s = set()
for i in range(0, n) :
s.add(input())
print(len(s))
| n = int(input())
s = set()
for i in range(0, n):
s.add(input())
print(len(s)) |
def find_prefix_entry(message, dictionary):
"""
Find the longest entry in dictionary which is a prefix of the given message
"""
for entry in dictionary[::-1]:
if message.startswith(entry[0]):
return dictionary.index(entry)
return -1
def lz78_encode(message, *args, **kwargs):
... | def find_prefix_entry(message, dictionary):
"""
Find the longest entry in dictionary which is a prefix of the given message
"""
for entry in dictionary[::-1]:
if message.startswith(entry[0]):
return dictionary.index(entry)
return -1
def lz78_encode(message, *args, **kwargs):
... |
def swap_case(s):
swapped = s.swapcase()
return swapped
| def swap_case(s):
swapped = s.swapcase()
return swapped |
#-----------------------------------------------------------------------------
# Runtime: 84ms
# Memory Usage:
# Link:
#-----------------------------------------------------------------------------
class Solution:
def multiply(self, num1: str, num2: str) -> str:
if num1 == '0' or num2 == '0':
... | class Solution:
def multiply(self, num1: str, num2: str) -> str:
if num1 == '0' or num2 == '0':
return '0'
len_num1 = len(num1)
len_num2 = len(num2)
num1 = num1[::-1]
num2 = num2[::-1]
result_list = [0] * 220
dic = {'0': 0, '1': 1, '2': 2, '3': 3,... |
"""
[7/23/2014] Challenge#172 [Intermediate] Image Rendering 101...010101000101
https://www.reddit.com/r/dailyprogrammer/comments/2ba3nf/7232014_challenge172_intermediate_image_rendering/
#Description
You may have noticed from our
[easy](http://www.reddit.com/r/dailyprogrammer/comments/2ba3g3/7212014_challenge_172_ea... | """
[7/23/2014] Challenge#172 [Intermediate] Image Rendering 101...010101000101
https://www.reddit.com/r/dailyprogrammer/comments/2ba3nf/7232014_challenge172_intermediate_image_rendering/
#Description
You may have noticed from our
[easy](http://www.reddit.com/r/dailyprogrammer/comments/2ba3g3/7212014_challenge_172_ea... |
# This file is part of the DMComm project by BladeSabre. License: MIT.
"""
`dmcomm.protocol.barcode`
=========================
Functions for generating EAN-13 patterns.
"""
# https://en.wikipedia.org/wiki/International_Article_Number
_START_END = "101"
_CENTRE = "01010"
_CODES = {
"L": ["0001101", "0011001", "00100... | """
`dmcomm.protocol.barcode`
=========================
Functions for generating EAN-13 patterns.
"""
_start_end = '101'
_centre = '01010'
_codes = {'L': ['0001101', '0011001', '0010011', '0111101', '0100011', '0110001', '0101111', '0111011', '0110111', '0001011'], 'G': ['0100111', '0110011', '0011011', '0100001', '00... |
# program that takes a text file as input and returns the number of words of a given text file.
def count_words(filepath):
with open(filepath) as f:
data = f.read()
data.replace(",", " ")
return len(data.split(" "))
print(count_words("words.txt")) | def count_words(filepath):
with open(filepath) as f:
data = f.read()
data.replace(',', ' ')
return len(data.split(' '))
print(count_words('words.txt')) |
#get the user input for Position
position = input("Position : ")
while position != "M" and position != "m" and position != "S" and position != "s":
print("Invalid Input")
position = input("Position : ")
#get the user input for sales amount
sales = input("Sales amount : ")
sales = float(sales)
#get the basic ... | position = input('Position : ')
while position != 'M' and position != 'm' and (position != 'S') and (position != 's'):
print('Invalid Input')
position = input('Position : ')
sales = input('Sales amount : ')
sales = float(sales)
if position == 'M' or position == 'm':
basic = 50000
else:
basic = 75000
if ... |
# Created by MechAviv
# Quest ID :: 23600
# Not coded yet
OBJECT_6 = sm.getIntroNpcObjectID(2159377)
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.sendDelay(900)
sm.moveCamera(False, 100, -307, -41)
sm.sendDelay(2604)
sm.setSpeakerID(2159377)
sm.remove... | object_6 = sm.getIntroNpcObjectID(2159377)
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.sendDelay(900)
sm.moveCamera(False, 100, -307, -41)
sm.sendDelay(2604)
sm.setSpeakerID(2159377)
sm.removeEscapeButton()
sm.setSpeakerType(3)
sm.sendNext('Good, very good!... |
"""
This package contains the portions of the library used only when
implementing an OpenID consumer.
"""
__all__ = ['consumer', 'discover']
| """
This package contains the portions of the library used only when
implementing an OpenID consumer.
"""
__all__ = ['consumer', 'discover'] |
rgb = input()
rgb = rgb.replace(" ", "")
if int(rgb) % 4 == 0:
print("YES")
else:
print("NO")
| rgb = input()
rgb = rgb.replace(' ', '')
if int(rgb) % 4 == 0:
print('YES')
else:
print('NO') |
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
# if it is a large {key: value} in dict, the list way is slower than dict way
# usedList = []
hashTable = {}
valueTable = {}
for i in... | class Solution(object):
def is_isomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
hash_table = {}
value_table = {}
for i in range(len(s)):
if s[i] in hashTable:
if h... |
def main() -> None:
n = int(input())
def f(a: int, b: int) -> int:
return a**3 + (a + b) * a * b + b**3
def binary_search(a: int) -> int:
lo = -1
hi = 1 << 20
while hi - lo > 1:
# print(lo, hi)
b = (lo + hi) // 2
if f(a, b) >=... | def main() -> None:
n = int(input())
def f(a: int, b: int) -> int:
return a ** 3 + (a + b) * a * b + b ** 3
def binary_search(a: int) -> int:
lo = -1
hi = 1 << 20
while hi - lo > 1:
b = (lo + hi) // 2
if f(a, b) >= n:
hi = b
... |
def raw_response(function=None):
def decorator(function):
function.raw_response = True
return function
if function:
return decorator(function)
return decorator
| def raw_response(function=None):
def decorator(function):
function.raw_response = True
return function
if function:
return decorator(function)
return decorator |
class StringBuilder(object):
def __init__(self, strr=''):
self.str_list = [s for s in strr]
def __getitem__(self, item):
return ''.join(self.str_list[item])
def __setitem__(self, key, value):
self.str_list[key] = value
def __repr__(self):
return ''.join(self.str_lis... | class Stringbuilder(object):
def __init__(self, strr=''):
self.str_list = [s for s in strr]
def __getitem__(self, item):
return ''.join(self.str_list[item])
def __setitem__(self, key, value):
self.str_list[key] = value
def __repr__(self):
return ''.join(self.str_list)... |
#from math import hypot
co = float(input('Quanto mede o cateto oposto? '))
ca = float(input('Quanto mede o cateto adjacente? '))
hi = hypot(co, ca)
print(f'A hipotenusa vai medir {hi:.2f}')
'''
import math
co = float(input('Quanto mede o cateto oposto? '))
ca = float(input('Quanto mede o cateto adjacente? '))
hi = mat... | co = float(input('Quanto mede o cateto oposto? '))
ca = float(input('Quanto mede o cateto adjacente? '))
hi = hypot(co, ca)
print(f'A hipotenusa vai medir {hi:.2f}')
"\nimport math\nco = float(input('Quanto mede o cateto oposto? '))\nca = float(input('Quanto mede o cateto adjacente? '))\nhi = math.hypot(co, ca)\nprint(... |
class Person:
IS = None
def __init__(self, name, hours, rate):
self.name = name
self.hours = hours
self.rate = rate
def __new__(cls, *args, **kwargs):
if cls.IS == None:
cls.IS = object.__new__(Person)
return cls.IS
def pay(self):
r... | class Person:
is = None
def __init__(self, name, hours, rate):
self.name = name
self.hours = hours
self.rate = rate
def __new__(cls, *args, **kwargs):
if cls.IS == None:
cls.IS = object.__new__(Person)
return cls.IS
def pay(self):
return sel... |
data_matrix = [
[2, 3, 1, 1],
[1, 2, 3, 1],
[1, 1, 2, 3],
[3, 1, 1, 2]
]
def fill_zeros(data_val):
return bin(int(data_val, 16))[2:].zfill(8)
input_hex = [0xd4, 0xbf, 0x5d, 0x30]
input_bin = []
for i, bi... | data_matrix = [[2, 3, 1, 1], [1, 2, 3, 1], [1, 1, 2, 3], [3, 1, 1, 2]]
def fill_zeros(data_val):
return bin(int(data_val, 16))[2:].zfill(8)
input_hex = [212, 191, 93, 48]
input_bin = []
for (i, bin_num) in enumerate(input_hex):
bin_num = bin(input_hex[i])[2:].zfill(8)
print(bin_num)
bin_num = int(bin_n... |
Root.default = -3
Scale.default = 'minor'
Clock.bpm=100
acordes = [(2,4,6),(-1,1,3),(0,2,4)]
escalera = P[5,4,3,2]
p1 >> space([0,0,4,2,0,0,5,2],dur=1,amp=[0,1,1,1])
d1 >> play("X ",amp=1)
pt >> play('#', dur=16,sus=4, rate=-1/2, amp=var([1,0],[16,inf],start=now))
p1 >> space([4,4,2,0,3,3,2,1],dur=1,amp=[0,1,1,1])
p... | Root.default = -3
Scale.default = 'minor'
Clock.bpm = 100
acordes = [(2, 4, 6), (-1, 1, 3), (0, 2, 4)]
escalera = P[5, 4, 3, 2]
p1 >> space([0, 0, 4, 2, 0, 0, 5, 2], dur=1, amp=[0, 1, 1, 1])
d1 >> play('X ', amp=1)
pt >> play('#', dur=16, sus=4, rate=-1 / 2, amp=var([1, 0], [16, inf], start=now))
p1 >> space([4, 4, 2, ... |
class Solution:
def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
"""
[2,2,4,3,3] A = 5, B = 5 cans = 1
1
2
[1,2,4,4,5] A = 6, B = 2 cans = 3
0,3 1,1 (c-(sum%c))
... | class Solution:
def minimum_refill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
"""
[2,2,4,3,3] A = 5, B = 5 cans = 1
1
2
[1,2,4,4,5] A = 6, B = 2 cans = 3
0,3 1,1 (c-(sum%c))
... |
def main():
totalNum = 0
totalValues = {}
filename = 'day1_1_input.txt'
found = False
while not found:
userInput = open(filename, 'r')
print ("Starting from the top")
for i in userInput:
print (i)
if i[0] == '-':
totalNum -= int(i[1:])
... | def main():
total_num = 0
total_values = {}
filename = 'day1_1_input.txt'
found = False
while not found:
user_input = open(filename, 'r')
print('Starting from the top')
for i in userInput:
print(i)
if i[0] == '-':
total_num -= int(i[1:]... |
def response(hey_bob):
hey_bob = hey_bob.strip()
if _is_silence(hey_bob):
return 'Fine. Be that way!'
if _is_shouting(hey_bob):
if _is_question(hey_bob):
return "Calm down, I know what I'm doing!"
else:
return 'Whoa, chill out!'
elif _is_question(hey_bob)... | def response(hey_bob):
hey_bob = hey_bob.strip()
if _is_silence(hey_bob):
return 'Fine. Be that way!'
if _is_shouting(hey_bob):
if _is_question(hey_bob):
return "Calm down, I know what I'm doing!"
else:
return 'Whoa, chill out!'
elif _is_question(hey_bob):... |
word = input("Enter a number: ")
word = int(word)
count =10
while True:
temp = word % 10
word = word//10
if temp % 2==0:
print(temp,end="")
if word == 0:
break | word = input('Enter a number: ')
word = int(word)
count = 10
while True:
temp = word % 10
word = word // 10
if temp % 2 == 0:
print(temp, end='')
if word == 0:
break |
data = input()
products = {}
while not data == "statistics":
product, quantity = data.split(": ")
quantity = int(quantity)
if product in products:
products[product] += quantity
else:
products[product] = quantity
data = input()
print("Products in stock:")
for product in products:
... | data = input()
products = {}
while not data == 'statistics':
(product, quantity) = data.split(': ')
quantity = int(quantity)
if product in products:
products[product] += quantity
else:
products[product] = quantity
data = input()
print('Products in stock:')
for product in products:
... |
# static methods
# use the staticmethod decorator
class Human:
@staticmethod
def speak():
print("I can speak")
Human().speak()
me = Human()
me.speak() # this line will give error
# expected an error.. but there isn't any
# static methods can be called on an instance of a class
# i didn't pass self or any arg... | class Human:
@staticmethod
def speak():
print('I can speak')
human().speak()
me = human()
me.speak() |
# Sem passar valores pelo init
class Calculadora:
# def __init__(self):
# pass
def soma(self, valor_a, valor_b):
return valor_a + valor_b
def subtracao(self, valor_a, valor_b):
return valor_a - valor_b
def multiplicacao(self, valor_a, valor_b):
return valor_a * valor_... | class Calculadora:
def soma(self, valor_a, valor_b):
return valor_a + valor_b
def subtracao(self, valor_a, valor_b):
return valor_a - valor_b
def multiplicacao(self, valor_a, valor_b):
return valor_a * valor_b
def divisao(self, valor_a, valor_b):
return valor_a / valo... |
def get_level(cell):
i = 0
while cell > (2*i+1)**2:
i += 1
return i
def find_coord(cell):
level = get_level(cell)
x = level
y = -level
current = (2*level+1)**2
while x != -level:
if current == cell:
return (x, y)
x-=1
current -= 1
while y !... | def get_level(cell):
i = 0
while cell > (2 * i + 1) ** 2:
i += 1
return i
def find_coord(cell):
level = get_level(cell)
x = level
y = -level
current = (2 * level + 1) ** 2
while x != -level:
if current == cell:
return (x, y)
x -= 1
current -= ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.