content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class ApiKeyManager( object ):
def __init__( self, app ):
self.app = app
def create_api_key( self, user ):
guid = self.app.security.get_new_guid()
new_key = self.app.model.APIKeys()
new_key.user_id = user.id
new_key.key = guid
sa_session = self.app.model.conte... | class Apikeymanager(object):
def __init__(self, app):
self.app = app
def create_api_key(self, user):
guid = self.app.security.get_new_guid()
new_key = self.app.model.APIKeys()
new_key.user_id = user.id
new_key.key = guid
sa_session = self.app.model.context
... |
totalSegundos = int(input())
quantidadeHoras = totalSegundos//60//60
segundosHoras = quantidadeHoras*60*60
restante = totalSegundos - segundosHoras
quantidadeMinutos = restante//60
segundosMinutos = quantidadeMinutos*60
quantidadeSegundos = restante - segundosMinutos
print('{}:{}:{}'.format(quantidadeHoras, quantidad... | total_segundos = int(input())
quantidade_horas = totalSegundos // 60 // 60
segundos_horas = quantidadeHoras * 60 * 60
restante = totalSegundos - segundosHoras
quantidade_minutos = restante // 60
segundos_minutos = quantidadeMinutos * 60
quantidade_segundos = restante - segundosMinutos
print('{}:{}:{}'.format(quantidade... |
class Solution:
def threeSumClosest(self, nums,target):
nums.sort()
out=0
for i in range(len(nums)-1):
j=i+1
k=len(nums)-1
while j<k:
# print(nums[i]+nums[j]+nums[k],out)
if i==0 and j==1 and k==len(nums)-1:
... | class Solution:
def three_sum_closest(self, nums, target):
nums.sort()
out = 0
for i in range(len(nums) - 1):
j = i + 1
k = len(nums) - 1
while j < k:
if i == 0 and j == 1 and (k == len(nums) - 1):
out = nums[i] + nums[... |
# -*- coding: utf-8 -*-
DDD_TABLE = {
'61' : 'Brasilia',
'71' : 'Salvador',
'11' : 'Sao Paulo',
'21' : 'Rio de Janeiro',
'32' : 'Juiz de Fora',
'19' : 'Campinas',
'27' : 'Vitoria',
'31' : 'Belo Horizonte'
}
def main():
ddd = input()
if ddd in DDD_TABLE:
print(DDD_TABLE... | ddd_table = {'61': 'Brasilia', '71': 'Salvador', '11': 'Sao Paulo', '21': 'Rio de Janeiro', '32': 'Juiz de Fora', '19': 'Campinas', '27': 'Vitoria', '31': 'Belo Horizonte'}
def main():
ddd = input()
if ddd in DDD_TABLE:
print(DDD_TABLE[ddd])
else:
print('DDD nao cadastrado')
if __name__ == ... |
with open('09.txt') as fd:
data = fd.readline().strip()
pos = 0
current = []
stack = []
in_garbage = False
garbage = 0
while pos < len(data):
c = data[pos]
pos += 1
if in_garbage:
if c == '!': pos += 1
elif c == '>': in_garbage = False
else: garbage += 1
else:
if c == '{':
... | with open('09.txt') as fd:
data = fd.readline().strip()
pos = 0
current = []
stack = []
in_garbage = False
garbage = 0
while pos < len(data):
c = data[pos]
pos += 1
if in_garbage:
if c == '!':
pos += 1
elif c == '>':
in_garbage = False
else:
ga... |
# Use the range function to loop through a code set 6 times.
for x in range(6):
print(x)
| for x in range(6):
print(x) |
#!/bin/zsh
while True:
OldmanAge = input()
def AgetoDays(age):
result = int(age) * 365
return result
print(AgetoDays(OldmanAge))
break | while True:
oldman_age = input()
def ageto_days(age):
result = int(age) * 365
return result
print(ageto_days(OldmanAge))
break |
# -*- coding: utf-8 -*-
class Solution:
INTEGER_TO_ALPHABET = {n: chr(ord('a') + n - 1) for n in range(1, 27)}
def freqAlphabets(self, s: str) -> str:
i, result = 0, []
while i < len(s):
if i + 2 < len(s) and s[i + 2] == '#':
result.append(self.INTEGER_TO_ALPHABET[... | class Solution:
integer_to_alphabet = {n: chr(ord('a') + n - 1) for n in range(1, 27)}
def freq_alphabets(self, s: str) -> str:
(i, result) = (0, [])
while i < len(s):
if i + 2 < len(s) and s[i + 2] == '#':
result.append(self.INTEGER_TO_ALPHABET[int(s[i:i + 2])])
... |
def test_get_all_offices(fineract):
offices = [office for office in fineract.get_offices()]
assert len(offices) == 3
def test_get_single_office(fineract):
office = fineract.get_offices(2)
assert office
assert office.name == 'Merida'
def test_get_all_staff(fineract):
staff = [staff for staff ... | def test_get_all_offices(fineract):
offices = [office for office in fineract.get_offices()]
assert len(offices) == 3
def test_get_single_office(fineract):
office = fineract.get_offices(2)
assert office
assert office.name == 'Merida'
def test_get_all_staff(fineract):
staff = [staff for staff in... |
print("\n\t\t-----> Welcome to Matias list changer <-----\t\t\n")
listn = [1,2,3,4,5,6,7,8,9,10]
print(f"\nThis is the list without changes ===> {listn}\n")
listn[4] *= 2
listn[7] *= 2
listn[9] *= 2
print(f"\nThis is the modified list ===> {listn}\n") | print('\n\t\t-----> Welcome to Matias list changer <-----\t\t\n')
listn = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(f'\nThis is the list without changes ===> {listn}\n')
listn[4] *= 2
listn[7] *= 2
listn[9] *= 2
print(f'\nThis is the modified list ===> {listn}\n') |
class PizzaDelivery:
def __init__(self, name, price, ingredients):
self.name = name
self.price = price
self.ingredients = ingredients
self.ordered = False
def add_extra(self, ingredient, quantity, price_per_ingredient):
if self.ordered:
return f"Pizza {self.... | class Pizzadelivery:
def __init__(self, name, price, ingredients):
self.name = name
self.price = price
self.ingredients = ingredients
self.ordered = False
def add_extra(self, ingredient, quantity, price_per_ingredient):
if self.ordered:
return f"Pizza {self.... |
## CITIES
cities = ['London', 'Constantinople', 'Sydney', 'Leningrad', 'Peking']
# Use bracket notation to change:
# Constantinople to Istanbul
# Leningrad to Saint Petersburg
# Peking to Beijing
cities[1] = 'Istanbul'
cities[3] = 'Saint Petersburg'
cities[4] = 'Beijing'
## DINOSAURS
dinos = ['Tyrannosaurus rex', 'T... | cities = ['London', 'Constantinople', 'Sydney', 'Leningrad', 'Peking']
cities[1] = 'Istanbul'
cities[3] = 'Saint Petersburg'
cities[4] = 'Beijing'
dinos = ['Tyrannosaurus rex', 'Torosaurus', 'Stegosaurus', 'Brontosaurus']
dinos[1] = 'Triceratops'
dinos[3] = 'Apatosaurus'
planets = ['Mercury', 'Venus', 'Earth', 'Mars', ... |
class Constants:
FW_VERSION = 4
LIGHT_TRANSITION_DURATION = 320
FAST_RECONNECT_WAIT_TIME_BEFORE_RESETING_LIGHTS = 5
HEARTBEAT_INTERVAL = 120
HEARTBEAT_MAX_RESPONSE_TIME = 5
| class Constants:
fw_version = 4
light_transition_duration = 320
fast_reconnect_wait_time_before_reseting_lights = 5
heartbeat_interval = 120
heartbeat_max_response_time = 5 |
class UI_Draw:
def draw(self, context):
layout = self.layout
layout.prop(self, 'auto_presets')
layout.separator()
split = layout.split()
split.prop(self, 'handle', text='Handle')
col = split.column(align=True)
col.prop(self, 'handle_z_top', text='Top')
if self.shape_rnd or self.shape_sq:
col.pr... | class Ui_Draw:
def draw(self, context):
layout = self.layout
layout.prop(self, 'auto_presets')
layout.separator()
split = layout.split()
split.prop(self, 'handle', text='Handle')
col = split.column(align=True)
col.prop(self, 'handle_z_top', text='Top')
... |
TWITTER_DIR = "twitter_data"
TWITTER_RAW_DIR = "raw"
TWITTER_PARQUET_DIR = "parquet"
TWITTER_RAW_SCHEMA = "twitter_schema.json" | twitter_dir = 'twitter_data'
twitter_raw_dir = 'raw'
twitter_parquet_dir = 'parquet'
twitter_raw_schema = 'twitter_schema.json' |
matriz = []
for i in range(2):
matriz.append(list(map(int, input().split())))
linhaMaior, colMaior = 0, 0
for linha in range(len(matriz)):
for elemento in range(len(matriz[linha])):
if matriz[linha][elemento] > matriz[linhaMaior][colMaior]:
linhaMaior, colMaior = linha, elemento... | matriz = []
for i in range(2):
matriz.append(list(map(int, input().split())))
(linha_maior, col_maior) = (0, 0)
for linha in range(len(matriz)):
for elemento in range(len(matriz[linha])):
if matriz[linha][elemento] > matriz[linhaMaior][colMaior]:
(linha_maior, col_maior) = (linha, elemento)
... |
SLIP39_WORDS = [
"academic",
"acid",
"acne",
"acquire",
"acrobat",
"activity",
"actress",
"adapt",
"adequate",
"adjust",
"admit",
"adorn",
"adult",
"advance",
"advocate",
"afraid",
"again",
"agency",
"agree",
"aide",
"aircraft",
"ai... | slip39_words = ['academic', 'acid', 'acne', 'acquire', 'acrobat', 'activity', 'actress', 'adapt', 'adequate', 'adjust', 'admit', 'adorn', 'adult', 'advance', 'advocate', 'afraid', 'again', 'agency', 'agree', 'aide', 'aircraft', 'airline', 'airport', 'ajar', 'alarm', 'album', 'alcohol', 'alien', 'alive', 'alpha', 'alrea... |
class Model:
def __init__(self):
self.SoC = 0.0
self.io = 0.0
def step(self, value):
if self.SoC > 0.95 and self.io == 1.0:
self.io = 0.0
if self.SoC < 0.05 and self.io == 0.0:
self.io = 1.0
| class Model:
def __init__(self):
self.SoC = 0.0
self.io = 0.0
def step(self, value):
if self.SoC > 0.95 and self.io == 1.0:
self.io = 0.0
if self.SoC < 0.05 and self.io == 0.0:
self.io = 1.0 |
def is_valid_index(r, c, board_size):
return r in range(board_size) and c in range(board_size)
def calculate_kills(matrix, r, c):
kills = 0
possible_moves = [
(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (2, -1), (2, 1), (1, 2)
]
for idx in range(len(possible_moves)):
row = r + p... | def is_valid_index(r, c, board_size):
return r in range(board_size) and c in range(board_size)
def calculate_kills(matrix, r, c):
kills = 0
possible_moves = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (2, -1), (2, 1), (1, 2)]
for idx in range(len(possible_moves)):
row = r + possible_moves[i... |
# settings.py
#
# aws-clean will not destroy things in the whitelist for global resources
# please put under the global region. I recommend just adding to the lists provided
# unless you are trying to provide a new cleaner.
#
#
# What value do I put in for each resource>
#
# s3_buckets - BucketName
# ec2_instances - In... | whitelist = {'global': {'s3_buckets': []}, 'us-east-1': {'ec2_instances': [], 'rds_instances': [], 'lambda_functions': [], 'dynamo_tables': [], 'redshift_clusters': [], 'ecs_clusters': [], 'efs': []}, 'us-east-2': {'ec2_instances': [], 'rds_instances': [], 'lambda_functions': [], 'dynamo_tables': [], 'redshift_clusters... |
### YOUR CODE FOR openLocks() FUNCTION GOES HERE ###
def openLocks(number_of_lockers , number_of_students):
if type(number_of_lockers) == str or type(number_of_students) == str or number_of_lockers < 0 or number_of_students <0:
return None
if number_of_lockers == 0 or number_of_students == 0:
re... | def open_locks(number_of_lockers, number_of_students):
if type(number_of_lockers) == str or type(number_of_students) == str or number_of_lockers < 0 or (number_of_students < 0):
return None
if number_of_lockers == 0 or number_of_students == 0:
return 0
locks = [1] * number_of_lockers
ope... |
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = str(input())
if query_name in student_marks:
l=list(student_marks[query_name])
sum=0
... | if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
(name, *line) = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = str(input())
if query_name in student_marks:
l = list(student_marks[query_name])
sum... |
fname = input("Enter the file name: ")
fh = open(fname)
count = 0
for line in fh:
line = line.rstrip()
if line.startswith('From '):
count = count + 1
words = line.split()
emails = words[1]
print(emails)
print("There were",count, "lines in the file with From as the first word") | fname = input('Enter the file name: ')
fh = open(fname)
count = 0
for line in fh:
line = line.rstrip()
if line.startswith('From '):
count = count + 1
words = line.split()
emails = words[1]
print(emails)
print('There were', count, 'lines in the file with From as the first word') |
def add_title(self):
square = Square(side_length=2 * self.L)
title = TextMobject("Brownian motion")
title.scale(1.5)
title.next_to(square, UP)
self.add(square)
self.add(title)
| def add_title(self):
square = square(side_length=2 * self.L)
title = text_mobject('Brownian motion')
title.scale(1.5)
title.next_to(square, UP)
self.add(square)
self.add(title) |
## PETRglobals.py [module]
##
# Global variable initializations for the PETRARCH event coder
#
# SYSTEM REQUIREMENTS
# This program has been successfully run under Mac OS 10.10; it is standard Python 2.7
# so it should also run in Unix or Windows.
#
# INITIAL PROVENANCE:
# Programmer: Philip A. Schrodt
# Parus Ana... | verb_dict = {'verbs': {}, 'phrases': {}, 'transformations': {}}
actor_dict = {}
actor_codes = []
agent_dict = {}
discard_list = {}
issue_list = []
issue_codes = []
config_file_name = 'PETR_config.ini'
verb_file_name = ''
actor_file_list = []
agent_file_name = ''
discard_file_name = ''
text_file_list = []
event_file_nam... |
# pylint: disable=W0622
def sum(arg):
total = 0
for val in arg:
total += val
return total
| def sum(arg):
total = 0
for val in arg:
total += val
return total |
class Wallet():
def __init__(self, initial_amount = 0):
self.balance = initial_amount
def spend_cash(self, amount):
if self.balance < amount:
print("insuffienct amount")
else:
self.balance -= amount
def add_cash(self, amount):
self.balance += amount | class Wallet:
def __init__(self, initial_amount=0):
self.balance = initial_amount
def spend_cash(self, amount):
if self.balance < amount:
print('insuffienct amount')
else:
self.balance -= amount
def add_cash(self, amount):
self.balance += amount |
a = int(input(""))
b = int(input(""))
c = int(input(""))
d = int(input(""))
x = (a*b-c*d)
print("DIFERENCA = %d" %x)
| a = int(input(''))
b = int(input(''))
c = int(input(''))
d = int(input(''))
x = a * b - c * d
print('DIFERENCA = %d' % x) |
# Webhook content types
HTTP_CONTENT_TYPE_JSON = "application/json"
# Registerable extras features
EXTRAS_FEATURES = [
"config_context_owners",
"custom_fields",
"custom_links",
"custom_validators",
"export_template_owners",
"export_templates",
"graphql",
"job_results",
"relationship... | http_content_type_json = 'application/json'
extras_features = ['config_context_owners', 'custom_fields', 'custom_links', 'custom_validators', 'export_template_owners', 'export_templates', 'graphql', 'job_results', 'relationships', 'statuses', 'webhooks']
job_log_max_grouping_length = 100
job_log_max_log_object_length =... |
def _pretty_after(a, k):
positional = ", ".join(repr(arg) for arg in a)
keyword = ", ".join(
"{}={!r}".format(name, value) for name, value in k.items()
)
if positional:
if keyword:
return ", {}, {}".format(positional, keyword)
else:
return ", {}".format(po... | def _pretty_after(a, k):
positional = ', '.join((repr(arg) for arg in a))
keyword = ', '.join(('{}={!r}'.format(name, value) for (name, value) in k.items()))
if positional:
if keyword:
return ', {}, {}'.format(positional, keyword)
else:
return ', {}'.format(positional... |
# (regname, regsize, is_big_endian, arch_name, branches)
# PowerPC CPU REGS
PPCREGS = [[], 4, True, "ppc", ["bl "]]
for i in range(32):
PPCREGS[0].append("r"+str(i))
for i in range(32):
PPCREGS[0].append(None)
PPCREGS[0].append("lr")
PPCREGS[0].append("ctr")
for i in range(8):
PPCREGS[0].append("cr"+str(i))
# A... | ppcregs = [[], 4, True, 'ppc', ['bl ']]
for i in range(32):
PPCREGS[0].append('r' + str(i))
for i in range(32):
PPCREGS[0].append(None)
PPCREGS[0].append('lr')
PPCREGS[0].append('ctr')
for i in range(8):
PPCREGS[0].append('cr' + str(i))
aarch64_regs = [[], 8, False, 'aarch64', ['bl ', 'blx ']]
for i in rang... |
# -*- coding: utf8 -*
'''
A Simple Extractor Key Note for SPED Fiscal
created by Matheus Tavares
'''
# Abrindo arquivo Sped para ler e Criando arquivo com notas separadas
sped = open("sped.txt", "r")
noteLine =[]
# Encontrando linhas C100 e salvando em Lista
for line in sped:
if line[0:6] == '|C... | """
A Simple Extractor Key Note for SPED Fiscal
created by Matheus Tavares
"""
sped = open('sped.txt', 'r')
note_line = []
for line in sped:
if line[0:6] == '|C100|':
noteLine.append(line)
sep_note = []
for line in noteLine:
sepNote.append(line.split('|'))
key_notes = open('./keys.txt', 'w')
for i in ... |
DATA_FOLDER = 'data'
DATA_INPUT_ZIP = 'stanford-dogs-dataset.zip'
DATA_OUTPUT_ZIP = 'dataset_unzipped'
DATASET_FOLDER = 'dataset'
IMAGES_LIST_FILE_NAME = 'images.txt'
INDEX_FILE_NAME = 'index.nmslib'
INPUT_IMAGE_FILE_NAME = 'input_image.jpg'
OUTPUT_IMAGE_FILE_NAME = 'output_image.jpg'
DEFAULT_IMAGES_PER_RACE = 1
IMAG... | data_folder = 'data'
data_input_zip = 'stanford-dogs-dataset.zip'
data_output_zip = 'dataset_unzipped'
dataset_folder = 'dataset'
images_list_file_name = 'images.txt'
index_file_name = 'index.nmslib'
input_image_file_name = 'input_image.jpg'
output_image_file_name = 'output_image.jpg'
default_images_per_race = 1
image_... |
class Solution:
def threeSumClosest(self, nums: [int], target: int) -> int:
nums = sorted(nums)
visited = []
difference = float('inf')
result = 0
for i, num_1 in enumerate(nums):
if num_1 in visited:
continue
else:
visi... | class Solution:
def three_sum_closest(self, nums: [int], target: int) -> int:
nums = sorted(nums)
visited = []
difference = float('inf')
result = 0
for (i, num_1) in enumerate(nums):
if num_1 in visited:
continue
else:
... |
class Note(object):
def __init__(self, content = None):
self.content = content
def write_content(self, content):
self.content = content
def remove_all(self):
self.content=""
def __str__(self):
return self.content
class NoteBook(object):
def __init__(self, title):
... | class Note(object):
def __init__(self, content=None):
self.content = content
def write_content(self, content):
self.content = content
def remove_all(self):
self.content = ''
def __str__(self):
return self.content
class Notebook(object):
def __init__(self, title)... |
USER_ALREADY_EXISTS = "USER_ALREADY_EXISTS"
USER_SIGNUP_SUCCESSFUL = "USER_SIGNUP_SUCCESSFUL"
CREDENTIALS_INCORRECT = "CREDENTIALS_INCORRECT"
USER_UNREGISTERED = "USER_UNREGISTERED"
ROLL_NUMBER_REQUIRED = "ROLL_NUMBER_REQUIRED"
PASSWORD_REQUIRED = "PASSWORD_REQUIRED"
| user_already_exists = 'USER_ALREADY_EXISTS'
user_signup_successful = 'USER_SIGNUP_SUCCESSFUL'
credentials_incorrect = 'CREDENTIALS_INCORRECT'
user_unregistered = 'USER_UNREGISTERED'
roll_number_required = 'ROLL_NUMBER_REQUIRED'
password_required = 'PASSWORD_REQUIRED' |
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def has_path(root, stack, x):
if not root:
return False
stack.append(root.val)
if root.val == x:
return True
if has_path(root.left, stack, x) or has_path(root.right, s... | class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def has_path(root, stack, x):
if not root:
return False
stack.append(root.val)
if root.val == x:
return True
if has_path(root.left, stack, x) or has_path(root.right, stack... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
# O(h) time | O(h) space - where h is the height of tree
def deleteNode(self, root: Optional[TreeNode], ... | class Solution:
def delete_node(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if root is None:
return root
if key > root.val:
root.right = self.deleteNode(root.right, key)
elif key < root.val:
root.left = self.deleteNode(root.left, key)... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
self.nodes_sorted = []
self.index = -1
... | class Bstiterator:
def __init__(self, root: Optional[TreeNode]):
self.nodes_sorted = []
self.index = -1
self._inorder(root)
def _inorder(self, root):
if not root:
return
self._inorder(root.left)
self.nodes_sorted.append(root.val)
self._inorde... |
class Solution:
def isValidSequence(self, root: TreeNode, arr: List[int]) -> bool:
if len(arr) == 1:
return root and root.val == arr[0] and not root.left and not root.right
if not root or root.val != arr[0]:
return False
return self.isValidSequence(root.left, arr[1:])... | class Solution:
def is_valid_sequence(self, root: TreeNode, arr: List[int]) -> bool:
if len(arr) == 1:
return root and root.val == arr[0] and (not root.left) and (not root.right)
if not root or root.val != arr[0]:
return False
return self.isValidSequence(root.left, a... |
#import osgeo._gdal
#import osgeo._gdalconst
#import osgeo._ogr
#import osgeo._osr
#import osgeo
#import gdal
#import gdalconst
#import ogr
#import osr
#
#cnt = ogr.GetDriverCount()
#for i in xrange(cnt):
# print ogr.GetDriver(i).GetName()
#
#import os1_hw
pass
| pass |
class Solution:
def numberOfSteps(self, ans: int) -> int:
steps = 0
while ans != 0:
if ans % 2 == 0:
ans = ans / 2
steps += 1
else:
ans -= 1
steps += 1
return steps
| class Solution:
def number_of_steps(self, ans: int) -> int:
steps = 0
while ans != 0:
if ans % 2 == 0:
ans = ans / 2
steps += 1
else:
ans -= 1
steps += 1
return steps |
SEQUENCE = [
'webhooktarget_extra_state',
'webhooktarget_extra_data_null',
'manytomanyfield_rm_null',
]
| sequence = ['webhooktarget_extra_state', 'webhooktarget_extra_data_null', 'manytomanyfield_rm_null'] |
# https://www.codewars.com/kata/5868b2de442e3fb2bb000119
def closest(strng):
if not strng:
return []
arr = [i for i in strng.split()]
arr_num = []
for i in arr:
sum_num = 0
for j in i:
sum_num += int(j)
arr_num.append(sum_num)
arr = [int(i) for i in arr]
... | def closest(strng):
if not strng:
return []
arr = [i for i in strng.split()]
arr_num = []
for i in arr:
sum_num = 0
for j in i:
sum_num += int(j)
arr_num.append(sum_num)
arr = [int(i) for i in arr]
n = len(arr)
new_arr = sorted(list(zip(arr_num, ra... |
#
# PySNMP MIB module PCSYSTEMSMIF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PCSYSTEMSMIF-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:37:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, constraints_union, single_value_constraint, value_size_constraint) ... |
# output: ok
count = 0
total = 0
last = 0
for i in (1, 2, 3):
count += 1
total += i
last = i
assert count == 3
assert total == 6
assert last == 3
count = 0
total = 0
last = 0
i = 1
while i <= 3:
count += 1
total += i
last = i
i += 1
assert count == 3
assert total == 6
assert last == 3
cou... | count = 0
total = 0
last = 0
for i in (1, 2, 3):
count += 1
total += i
last = i
assert count == 3
assert total == 6
assert last == 3
count = 0
total = 0
last = 0
i = 1
while i <= 3:
count += 1
total += i
last = i
i += 1
assert count == 3
assert total == 6
assert last == 3
count = 0
total = 0... |
ix.enable_command_history()
ix.api.SdkHelpers.create_shading_layer_for_items_selected(ix.application, 3)
ix.disable_command_history() | ix.enable_command_history()
ix.api.SdkHelpers.create_shading_layer_for_items_selected(ix.application, 3)
ix.disable_command_history() |
# If we list all the natural numbers below 10 that are multiples
# of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
if __name__ == "__main__":
numbers = [ n for n in range(1,1000) if n % 3 == 0 or n % 5 == 0 ]
print(sum(numbers))
| if __name__ == '__main__':
numbers = [n for n in range(1, 1000) if n % 3 == 0 or n % 5 == 0]
print(sum(numbers)) |
class Solver:
def __init__(self, cells):
self.cells = cells
def determine_cell_possibilities(self):
for cell in self.cells:
candidates = list(range(1, 10))
for association in cell.get_unique_associations():
if association.number is not None:
if association.number in candidates... | class Solver:
def __init__(self, cells):
self.cells = cells
def determine_cell_possibilities(self):
for cell in self.cells:
candidates = list(range(1, 10))
for association in cell.get_unique_associations():
if association.number is not None:
... |
n = int(input())
arr = []
i = list(map(int, input().split()))
arr = list(range(i[0], i[1]+1))
for each in range(n - 1):
i = list(map(int, input().split()))
for c,every in enumerate(arr):
if every < i[0]:
arr[c] = -1
elif every > i[1]:
arr[c] = -1
if sum(arr) == (-1*len(ar... | n = int(input())
arr = []
i = list(map(int, input().split()))
arr = list(range(i[0], i[1] + 1))
for each in range(n - 1):
i = list(map(int, input().split()))
for (c, every) in enumerate(arr):
if every < i[0]:
arr[c] = -1
elif every > i[1]:
arr[c] = -1
if sum(arr) == -1 * ... |
# __author__ = 'tusharmakkar08'
class Wallet:
def __init__(self):
self.amount = 0 # TODO: get init amount on the basis of user name from db
def load_money(self, amount):
self.amount += amount
def deduct_money(self, amount):
self.amount -= amount
def get_money(self):
... | class Wallet:
def __init__(self):
self.amount = 0
def load_money(self, amount):
self.amount += amount
def deduct_money(self, amount):
self.amount -= amount
def get_money(self):
return self.amount |
r_TPC = 0.664
r_FSWires = 0.668
r_FSGuards = 0.680
path_main = '/dali/lgrandi/peres/efieldsim/'
path_cache = path_main + 'cache/'
path_root_files = path_main + '/solved_outputs/EField_SR0/' | r_tpc = 0.664
r_fs_wires = 0.668
r_fs_guards = 0.68
path_main = '/dali/lgrandi/peres/efieldsim/'
path_cache = path_main + 'cache/'
path_root_files = path_main + '/solved_outputs/EField_SR0/' |
# The following is used as a global constant to represent
# the contribution rate.
CONTRIBUTION_RATE = 0.05
def main():
gross_pay = float(input('Enter the gross pay: '))
bonus = float(input('Enter the amount of bonuses: '))
show_pay_contrib(gross_pay)
show_bonus_contrib(bonus)
# The show_pay_contrib f... | contribution_rate = 0.05
def main():
gross_pay = float(input('Enter the gross pay: '))
bonus = float(input('Enter the amount of bonuses: '))
show_pay_contrib(gross_pay)
show_bonus_contrib(bonus)
def show_pay_contrib(gross):
contrib = gross * CONTRIBUTION_RATE
print('Contribution for gross pay:... |
def test_create_stat_table():
pass
def test_get_latest_successful_ts():
pass
def test_update_latest_successful_ts():
pass
| def test_create_stat_table():
pass
def test_get_latest_successful_ts():
pass
def test_update_latest_successful_ts():
pass |
books = int(input("How many books do you want to buy? "))
amount = int(input("How much do you have? "))
amount_required = 100
if books == amount_required > amount:
print("you can purchase the books")
else:
print("You donot have sufficient funds to buy the books")
print(f"You will need {amount} to buy the book... | books = int(input('How many books do you want to buy? '))
amount = int(input('How much do you have? '))
amount_required = 100
if books == amount_required > amount:
print('you can purchase the books')
else:
print('You donot have sufficient funds to buy the books')
print(f'You will need {amount} to buy the b... |
class i18n(object):
def __init__(self):
# Default domain
self._domain = 'idn'
def domain(self, country):
self._domain = country
def translate(self, domain):
dic = {}
dic['idn'] = {
# Month
'Januari': 'January',
'Februari': 'Febru... | class I18N(object):
def __init__(self):
self._domain = 'idn'
def domain(self, country):
self._domain = country
def translate(self, domain):
dic = {}
dic['idn'] = {'Januari': 'January', 'Februari': 'February', 'Maret': 'March', 'April': 'April', 'Mei': 'May', 'Juni': 'June'... |
#
# @lc app=leetcode.cn id=1700 lang=python3
#
# [1700] minimum-deletion-cost-to-avoid-repeating-letters
#
None
# @lc code=end | None |
#
# Code property of Jared Scarito
#
testCases = int(input())
outCases = []
for i in range(testCases):
weights = []
dataSet = str(input())
case = dataSet.split(" ")[0]
maxWeight = int(dataSet.split(" ")[1])
for weightIndex in range(len(dataSet.split(" "))):
if int(weightIndex) > 1:
... | test_cases = int(input())
out_cases = []
for i in range(testCases):
weights = []
data_set = str(input())
case = dataSet.split(' ')[0]
max_weight = int(dataSet.split(' ')[1])
for weight_index in range(len(dataSet.split(' '))):
if int(weightIndex) > 1:
weight = dataSet.split(' ')[i... |
SMS_setting = {
'secretId':'',
'secretKey':'',
'req_Appid':'',
'req_Sign':'',
'req_SessionContext':'',
'req_NumberSet':[],
'req_TemplateID':'',
'req_TemplateParmSet':[],
}
| sms_setting = {'secretId': '', 'secretKey': '', 'req_Appid': '', 'req_Sign': '', 'req_SessionContext': '', 'req_NumberSet': [], 'req_TemplateID': '', 'req_TemplateParmSet': []} |
LEFT = 0
UP = 1
RIGHT = 2
DOWN = 3
vectors = [(-1, 0), (0, 1), (1, 0), (0, -1)]
class Laser:
def __init__(self, board, x, y):
self.board = board
class Board:
def __init__(self, size):
self.size = size
self.real = [[False for _ in range(size)] for _ in range(size)]
def set_mirro... | left = 0
up = 1
right = 2
down = 3
vectors = [(-1, 0), (0, 1), (1, 0), (0, -1)]
class Laser:
def __init__(self, board, x, y):
self.board = board
class Board:
def __init__(self, size):
self.size = size
self.real = [[False for _ in range(size)] for _ in range(size)]
def set_mirror... |
#!/usr/bin/env python3
# Based on the code in
# https://www.cs.princeton.edu/courses/archive/spr09/cos333/beautiful.html
# by Rob Pike.
def match(regexp, text):
if regexp and regexp[0] == '^':
return match_here(regexp[1:], text)
while text:
print('\nmatch({!r}, {!r})'.format(regexp, text))
... | def match(regexp, text):
if regexp and regexp[0] == '^':
return match_here(regexp[1:], text)
while text:
print('\nmatch({!r}, {!r})'.format(regexp, text))
if match_here(regexp, text):
return True
text = text[1:]
return False
def match_here(regexp, text):
prin... |
expected_output = {
'socket_connections': {
'total_socket_connections': 4,
'sockets_in_listen_state': ['Tunnel1-head-0', 'Tunnel2-head-0', 'Tunnel3-head-0', 'Tunnel20-head-0'],
'Tu1': {
'peers': {
'remote_ip': '10.0.0.2',
'local_ip': '85... | expected_output = {'socket_connections': {'total_socket_connections': 4, 'sockets_in_listen_state': ['Tunnel1-head-0', 'Tunnel2-head-0', 'Tunnel3-head-0', 'Tunnel20-head-0'], 'Tu1': {'peers': {'remote_ip': '10.0.0.2', 'local_ip': '85.45.1.1'}, 'local_ident': {'protocol': 47, 'mask': '255.255.255.255', 'port': 0, 'addre... |
def list_function(x):
return x
n = [3, 5, 7]
print(list_function(n))
| def list_function(x):
return x
n = [3, 5, 7]
print(list_function(n)) |
t = int(input())
for i in range(t):
n = int(input())
m = n-1
arr = []
# print(arr)
uparr = list(range(1,n)) + list(range(n-1,0,-1))
down = 2
up = 0
# print(uparr)
start = 1
for j in range(n):
if j>0:
start += down
down += 1
temp = []
... | t = int(input())
for i in range(t):
n = int(input())
m = n - 1
arr = []
uparr = list(range(1, n)) + list(range(n - 1, 0, -1))
down = 2
up = 0
start = 1
for j in range(n):
if j > 0:
start += down
down += 1
temp = []
temp2 = start
for... |
def sum(a , b):
return a + b
def getAllData():
listOfCategory = [
{
'id': 1,
'cat_name': 'Cell phone',
'products': [
{
'product_id': 1,
'product_name': 'iPhone 12 Pro Max'
},
{
... | def sum(a, b):
return a + b
def get_all_data():
list_of_category = [{'id': 1, 'cat_name': 'Cell phone', 'products': [{'product_id': 1, 'product_name': 'iPhone 12 Pro Max'}, {'product_id': 2, 'product_name': 'iPhone 11 Pro'}, {'product_id': 3, 'product_name': 'iPhone XS'}]}, {'id': 2, 'cate_name': 'Tablet'}]
... |
class MULT18X18():
def __init__(self, clk=True, site=None, **kwargs):
self.inst = inst("MULT18X18SIO", site, **kwargs)
self.setcfgs({
"AREG": "0",
"BREG": "0",
"B_INPUT": "DIRECT",
"CEAINV": "CEA",
"CEBINV": "CEB",
"CEPINV": "... | class Mult18X18:
def __init__(self, clk=True, site=None, **kwargs):
self.inst = inst('MULT18X18SIO', site, **kwargs)
self.setcfgs({'AREG': '0', 'BREG': '0', 'B_INPUT': 'DIRECT', 'CEAINV': 'CEA', 'CEBINV': 'CEB', 'CEPINV': 'CEP', 'CLKINV': 'CLK', 'PREG': '0', 'PREG_CLKINVERSION': '0', 'RSTAINV': 'RS... |
# NBA Game Predictor
# File: baseline.py
# Authors: Tarmily Wen & Andrew Petrosky
#
# A baseline predictor based purely of winning percentage
def model(train_x, train_y, test_x, test_y):
# Train test
print("Testing on training data...")
correct = 0.0
total = 0.0
for i in range(len(train_x)):
... | def model(train_x, train_y, test_x, test_y):
print('Testing on training data...')
correct = 0.0
total = 0.0
for i in range(len(train_x)):
t = 0 if train_x[i][-2] < train_x[i][-1] else 1
if t == train_y[i]:
correct += 1.0
total += 1.0
acc = correct / total
prin... |
def name_file(fmt, nbr, start):
if not isinstance(nbr, int) or not isinstance(start, int) or nbr <= 0:
return []
filename = fmt.replace('<index_no>', '{0}').format
return [filename(a) for a in xrange(start, start + nbr)]
| def name_file(fmt, nbr, start):
if not isinstance(nbr, int) or not isinstance(start, int) or nbr <= 0:
return []
filename = fmt.replace('<index_no>', '{0}').format
return [filename(a) for a in xrange(start, start + nbr)] |
SHARD_COUNT = 2**10 # 1024
EPOCH_LENGTH = 2**6 # 64 slots, 6.4 minutes
TARGET_COMMITTEE_SIZE = 2**8 # 256 validators
| shard_count = 2 ** 10
epoch_length = 2 ** 6
target_committee_size = 2 ** 8 |
class Stack:
'''Visual FX Stack'''
def __init__(self, layers=[]):
self.layers = layers
def apply(self, frame):
'''Return the frame with the fx layers applied.'''
output = frame.copy()
for layer in self.layers:
if layer.active:
output = layer.app... | class Stack:
"""Visual FX Stack"""
def __init__(self, layers=[]):
self.layers = layers
def apply(self, frame):
"""Return the frame with the fx layers applied."""
output = frame.copy()
for layer in self.layers:
if layer.active:
output = layer.appl... |
class Solution:
def searchRange(self, nums: list[int], target: int) -> list[int]:
first,last = -1,-1
def search(lo,hi):
nonlocal first,last
if nums[lo]<=target<=nums[hi]:
mid = (lo+hi)//2
if nums[mid]==target:
if fi... | class Solution:
def search_range(self, nums: list[int], target: int) -> list[int]:
(first, last) = (-1, -1)
def search(lo, hi):
nonlocal first, last
if nums[lo] <= target <= nums[hi]:
mid = (lo + hi) // 2
if nums[mid] == target:
... |
regions = {'jp': 'amazon.co.jp',
'uk': 'amazon.co.uk',
'de': 'amazon.de',
'eu': 'amazon.co.uk',
'us': 'amazon.com',
'na': 'amazon.com'}
| regions = {'jp': 'amazon.co.jp', 'uk': 'amazon.co.uk', 'de': 'amazon.de', 'eu': 'amazon.co.uk', 'us': 'amazon.com', 'na': 'amazon.com'} |
# coding: utf-8
n, m = [int(i) for i in input().split()]
d = {}
for i in range(m):
tmp = input().split()
d[tmp[0]] = tmp[1]
s = input().split()
for i in range(n):
if len(s[i])>len(d[s[i]]):
s[i] = d[s[i]]
print(' '.join(s))
| (n, m) = [int(i) for i in input().split()]
d = {}
for i in range(m):
tmp = input().split()
d[tmp[0]] = tmp[1]
s = input().split()
for i in range(n):
if len(s[i]) > len(d[s[i]]):
s[i] = d[s[i]]
print(' '.join(s)) |
#MergeSort.py
# 20 Oct 2017
#written by Amin dehghan
#DS & Algorithms With Python
def merge(seq,start,mid,stop):
lst=[]
i=start
j=mid
while i<mid and j<stop:
if seq[i]<seq[j]:
lst.append(seq[i])
i+=1
else:
lst.append(seq[j])
j+=1
... | def merge(seq, start, mid, stop):
lst = []
i = start
j = mid
while i < mid and j < stop:
if seq[i] < seq[j]:
lst.append(seq[i])
i += 1
else:
lst.append(seq[j])
j += 1
while i < mid:
lst.append(seq[i])
i += 1
for i in... |
# A Dynamic Programming based Python Program for the Egg Dropping Puzzle
INT_MAX = 32767
# Function to get minimum number of trials needed in worst
# case with n eggs and k floors
def eggDrop(n, k):
# A 2D table where entery eggFloor[i][j] will represent minimum
# number of trials needed for i eggs and j flo... | int_max = 32767
def egg_drop(n, k):
egg_floor = [[0 for x in range(k + 1)] for x in range(n + 1)]
for i in range(1, n + 1):
eggFloor[i][1] = 1
eggFloor[i][0] = 0
for j in range(1, k + 1):
eggFloor[1][j] = j
for i in range(2, n + 1):
for j in range(2, k + 1):
... |
def my_map(transformation_function, sequence):
for elt in sequence:
yield transformation_function(elt)
powers_of_two = my_map(lambda x: x**2, range(1,11))
print(powers_of_two)
print(next(powers_of_two))
print(list(powers_of_two)) | def my_map(transformation_function, sequence):
for elt in sequence:
yield transformation_function(elt)
powers_of_two = my_map(lambda x: x ** 2, range(1, 11))
print(powers_of_two)
print(next(powers_of_two))
print(list(powers_of_two)) |
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return f'{self.value}'
class Stack:
def __init__(self):
self.top = None
self.bottom = None
self.length = 0
def isEmpty(self):
return self.top == Non... | class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return f'{self.value}'
class Stack:
def __init__(self):
self.top = None
self.bottom = None
self.length = 0
def is_empty(self):
return self.top == No... |
#
# PySNMP MIB module HPN-ICF-LswQos-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-LswQos-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:27:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_intersection, single_value_constraint, constraints_union) ... |
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
self.bt(nums, [], res)
return res
def bt(self, nums, tempList, res):
if len(tempList) == len(nums):
res.append(tempList)
return
for i in range(len(nums)):
... | class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
self.bt(nums, [], res)
return res
def bt(self, nums, tempList, res):
if len(tempList) == len(nums):
res.append(tempList)
return
for i in range(len(nums)):
... |
def bubble_sort(alist):
for _ in range(len(alist)-1,0,-1):
for i in range(_):
if alist[i] > alist[i+1]:
alist[i+1],alist[i] = alist[i],alist[i+1]
return alist
print(bubble_sort([1,4,2,3,9,0]))
| def bubble_sort(alist):
for _ in range(len(alist) - 1, 0, -1):
for i in range(_):
if alist[i] > alist[i + 1]:
(alist[i + 1], alist[i]) = (alist[i], alist[i + 1])
return alist
print(bubble_sort([1, 4, 2, 3, 9, 0])) |
(n, k) = map(int, input().split())
cnt = 0
arr = [0 for _ in range(0, n + 1)]
for i in range(2, n + 1):
for j in range(i, n + 1, i):
if arr[j] != 0:
continue
arr[j] = 1
cnt += 1
if cnt == k:
print(j)
exit(0) | (n, k) = map(int, input().split())
cnt = 0
arr = [0 for _ in range(0, n + 1)]
for i in range(2, n + 1):
for j in range(i, n + 1, i):
if arr[j] != 0:
continue
arr[j] = 1
cnt += 1
if cnt == k:
print(j)
exit(0) |
def strangeCounter(t):
initial = 3
j = 3 + 1
time = 0
while True:
time += 1
j -= 1
if t > time -1 + initial:
time += initial -1
initial = initial * 2
j = initial + 1
continue
return j - (t - time)
if __name__ =... | def strange_counter(t):
initial = 3
j = 3 + 1
time = 0
while True:
time += 1
j -= 1
if t > time - 1 + initial:
time += initial - 1
initial = initial * 2
j = initial + 1
continue
return j - (t - time)
if __name__ == '__main__... |
'''
Description: exercise: day old bread
Version: 1.0.1.20210114
Author: Arvin Zhao
Date: 2021-01-13 06:12:15
Last Editors: Arvin Zhao
LastEditTime: 2021-01-14 03:49:47
'''
def print_receipt(loaf_num: int, regular_per_price: float, discount_rate: float) -> None:
'''
Calculate and print the regular price for lo... | """
Description: exercise: day old bread
Version: 1.0.1.20210114
Author: Arvin Zhao
Date: 2021-01-13 06:12:15
Last Editors: Arvin Zhao
LastEditTime: 2021-01-14 03:49:47
"""
def print_receipt(loaf_num: int, regular_per_price: float, discount_rate: float) -> None:
"""
Calculate and print the regular price for lo... |
{
"includes": [
"../../common.gypi"
],
'target_defaults': {
'default_configuration': 'Release',
'cflags':[
'-std=c99'
],
'configurations': {
'Debug': {
'defines': [ 'DEBUG', '_DEBUG' ],
},
'Release': {
'defines': [ 'NDEBUG' ],
}
},
'conditions'... | {'includes': ['../../common.gypi'], 'target_defaults': {'default_configuration': 'Release', 'cflags': ['-std=c99'], 'configurations': {'Debug': {'defines': ['DEBUG', '_DEBUG']}, 'Release': {'defines': ['NDEBUG']}}, 'conditions': [['OS == "win"', {'defines': ['WIN32']}]]}, 'targets': [{'target_name': 'libsqlite', 'type'... |
data = [
["Total Bill","Tip","Payer Gender","Payer Smoker","Day of Week","Meal","Party Size"],
[16.99,1.01,"Female","Non-Smoker","Sunday","Dinner",2],
[10.34,1.66,"Male","Non-Smoker","Sunday","Dinner",3],
[21.01,3.5,"Male","Non-Smoker","Sunday","Dinner",3],
[23.68,3.31,"Male","Non-Smoker","Sunday","Dinner",2],
[24.59,3... | data = [['Total Bill', 'Tip', 'Payer Gender', 'Payer Smoker', 'Day of Week', 'Meal', 'Party Size'], [16.99, 1.01, 'Female', 'Non-Smoker', 'Sunday', 'Dinner', 2], [10.34, 1.66, 'Male', 'Non-Smoker', 'Sunday', 'Dinner', 3], [21.01, 3.5, 'Male', 'Non-Smoker', 'Sunday', 'Dinner', 3], [23.68, 3.31, 'Male', 'Non-Smoker', 'Su... |
discord_token = 'NDQyNTQ3OTY0MDI0NzE3MzEy.DdAacQ._iDLpBSxzKb8T5rZDh4De9A1sXc'
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0'
goat_url = 'https://2fwotdvm2o-dsn.algolia.net/1/indexes/ProductTemplateSearch/query'
stockx_url = 'https://xw7sbct9v6-dsn.algolia.net/1/inde... | discord_token = 'NDQyNTQ3OTY0MDI0NzE3MzEy.DdAacQ._iDLpBSxzKb8T5rZDh4De9A1sXc'
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0'
goat_url = 'https://2fwotdvm2o-dsn.algolia.net/1/indexes/ProductTemplateSearch/query'
stockx_url = 'https://xw7sbct9v6-dsn.algolia.net/1/indexes/pro... |
lista=[]
for i in range(1,101):
if(i%7!=0):
lista.append(i)
print(lista)
| lista = []
for i in range(1, 101):
if i % 7 != 0:
lista.append(i)
print(lista) |
def fizz_buzz(fizz, buzz, highest):
result = []
for i in range(1, highest + 1):
letter = ''
# If divisible by fizz or buzz, add F or B appropriately.
if i % fizz == 0:
letter += 'F'
if i % buzz == 0:
letter += 'B'
# If neither F or B has been la... | def fizz_buzz(fizz, buzz, highest):
result = []
for i in range(1, highest + 1):
letter = ''
if i % fizz == 0:
letter += 'F'
if i % buzz == 0:
letter += 'B'
if letter == '':
letter = str(i)
result.append(letter)
return ' '.join(resul... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
maxProfit = 0
minValue = 10**5
for price in prices:
minValue = min(price, minValue)
maxProfit = max(price - minValue, maxProfit)
return maxProfit | class Solution:
def max_profit(self, prices: List[int]) -> int:
max_profit = 0
min_value = 10 ** 5
for price in prices:
min_value = min(price, minValue)
max_profit = max(price - minValue, maxProfit)
return maxProfit |
class Node:
def __init__(self, element):
self.item = element
self.next_link = None
self.prev_link = None
class DoubleLinkedList:
def __init__(self):
self.first_node = None
def is_empty(self):
if self.first_node is None:
print("Error! The list is empty!"... | class Node:
def __init__(self, element):
self.item = element
self.next_link = None
self.prev_link = None
class Doublelinkedlist:
def __init__(self):
self.first_node = None
def is_empty(self):
if self.first_node is None:
print('Error! The list is empty!... |
# Import the library that makes it easier to write context managers
# Implement a context manager that writes to a text file
# using a class:
class MyContextManager:
pass
# Implement a context manager using a method with a decorator
def my_context_manager():
raise Exception("Method not implemented")
def c... | class Mycontextmanager:
pass
def my_context_manager():
raise exception('Method not implemented')
def call_class_context_manager(file_name='class_hi.txt', text='hello', access_mode='w'):
with my_context_manager(file_name, access_mode) as f:
f.write(text)
def call_function_context_manager(file_name... |
# items implementation
class Item:
def __init__(self, item_name, item_description):
self.item_name = item_name
self.item_description = item_description
def __str__(self):
return '%s, %s' % (self.item_name, self.item_description)
| class Item:
def __init__(self, item_name, item_description):
self.item_name = item_name
self.item_description = item_description
def __str__(self):
return '%s, %s' % (self.item_name, self.item_description) |
# tiles
ONE_MAN = 0
TWO_MAN = 1
THREE_MAN = 2
FOUR_MAN = 3
FIVE_MAN = 4
SIX_MAN = 5
SEVEN_MAN = 6
EIGHT_MAN = 7
NINE_MAN = 8
ONE_PIN = 9
TWO_PIN = 10
THREE_PIN = 11
FOUR_PIN = 12
FIVE_PIN = 13
SIX_PIN = 14
SEVEN_PIN = 15
EIGHT_PIN = 16
NINE_PIN = 17
ONE_SOU = 18
TWO_SOU = 19
THREE_SOU = 20
FOUR_SOU = 21
FIVE_SOU = 22
S... | one_man = 0
two_man = 1
three_man = 2
four_man = 3
five_man = 4
six_man = 5
seven_man = 6
eight_man = 7
nine_man = 8
one_pin = 9
two_pin = 10
three_pin = 11
four_pin = 12
five_pin = 13
six_pin = 14
seven_pin = 15
eight_pin = 16
nine_pin = 17
one_sou = 18
two_sou = 19
three_sou = 20
four_sou = 21
five_sou = 22
six_sou =... |
garden_waitlist = ["Jiho", "Adam", "Sonny", "Alisha"]
garden_waitlist[1] = "Calla"
garden_waitlist[-1] = "Alex"
print(garden_waitlist)
| garden_waitlist = ['Jiho', 'Adam', 'Sonny', 'Alisha']
garden_waitlist[1] = 'Calla'
garden_waitlist[-1] = 'Alex'
print(garden_waitlist) |
def one2two(digit):
if len(digit) == 1:
return "0" + digit
else:
return digit
def result(pt, st):
rt = ""
second, minute, hour = 0, 0, 0
sc, mc = 0, 0
if st[2] - pt[2] >= 0:
second = st[2] - pt[2]
else:
second = st[2] - pt[2] + 60
sc = 1
if st[... | def one2two(digit):
if len(digit) == 1:
return '0' + digit
else:
return digit
def result(pt, st):
rt = ''
(second, minute, hour) = (0, 0, 0)
(sc, mc) = (0, 0)
if st[2] - pt[2] >= 0:
second = st[2] - pt[2]
else:
second = st[2] - pt[2] + 60
sc = 1
i... |
n, m = map(int, input().split())
trees = list(map(int, input().split()))
minH = 0
maxH = max(trees)
ans = 0
while minH <= maxH:
cutH = (minH+maxH)//2
cutMount = 0
for tree in trees:
cutMount += (tree - cutH if tree >= cutH else 0)
if cutMount >= m:
ans = cutH
minH = cutH + 1
... | (n, m) = map(int, input().split())
trees = list(map(int, input().split()))
min_h = 0
max_h = max(trees)
ans = 0
while minH <= maxH:
cut_h = (minH + maxH) // 2
cut_mount = 0
for tree in trees:
cut_mount += tree - cutH if tree >= cutH else 0
if cutMount >= m:
ans = cutH
min_h = cut... |
# Python - 2.7.6
def logical_calc(array, op):
logic = {
'AND': all,
'OR': any,
'XOR': lambda arr: bool(arr.count(True) & 1)
}
if op in logic:
return logic[op](array)
return False
| def logical_calc(array, op):
logic = {'AND': all, 'OR': any, 'XOR': lambda arr: bool(arr.count(True) & 1)}
if op in logic:
return logic[op](array)
return False |
# bluetooth device attributes
DEVICE_NAME = "TT Camera Slider"
MIN_POS = 0
MAX_POS = 0.9
MIN_DURATION = 0
MAX_DURATION = 500
MIN_SPEED = 0.002
MAX_SPEED = 0.25
# motor attributes
STEP_ANGLE = 1.8
VEL_TO_RPS = 9.88319028614 * 2 # 1/(2pi(r))
DIST_TO_STEPS = 1976.63805723 # (360)/(1.8*2pi(r)) ONLY for ms=0
RADIUS = 0.01... | device_name = 'TT Camera Slider'
min_pos = 0
max_pos = 0.9
min_duration = 0
max_duration = 500
min_speed = 0.002
max_speed = 0.25
step_angle = 1.8
vel_to_rps = 9.88319028614 * 2
dist_to_steps = 1976.63805723
radius = 0.0161036
default_velocity = 0.1
sleep_between_move = 2
dist_to_steps_e = 2.58064516129
vel_to_rps_e = ... |
def combinations_fixed_sum(fixed_sum, length_of_list, lst=[]):
if length_of_list == 1:
lst += [fixed_sum]
yield lst
else:
for i in range(fixed_sum+1):
yield from combinations_fixed_sum(i, length_of_list-1, lst + [fixed_sum-i])
def combinations_fixed_sum_limits(fixed_sum, length_of_list, minimum,... | def combinations_fixed_sum(fixed_sum, length_of_list, lst=[]):
if length_of_list == 1:
lst += [fixed_sum]
yield lst
else:
for i in range(fixed_sum + 1):
yield from combinations_fixed_sum(i, length_of_list - 1, lst + [fixed_sum - i])
def combinations_fixed_sum_limits(fixed_su... |
class LoginProviders:
google = "google"
facebook = "facebook"
github = "github"
twitter = "twitter"
login_providers = LoginProviders()
| class Loginproviders:
google = 'google'
facebook = 'facebook'
github = 'github'
twitter = 'twitter'
login_providers = login_providers() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.