content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Group the Numbers
# Partitioning : quicksort !!
# Time - O(n), Space- O(1)
# Lomuto's partitioning O(n) time, in-place
def solve(arr):
even = -1 # index from the beginning (r -- red == even)
i = 0 # current pointer
while i < len(arr): # O(n)
if arr[i] % 2 == 0:
even += 1
... | def solve(arr):
even = -1
i = 0
while i < len(arr):
if arr[i] % 2 == 0:
even += 1
(arr[i], arr[even]) = (arr[even], arr[i])
i += 1
return arr
if __name__ == '__main__':
arr = [1, 5, 2, 3, 4, 4, 4, 5, 2, 6, 8, 9, 9]
def solve(arr):
left_pointer = -1
cu... |
class Learner(object):
"""docstring for Learner"""
def __init__(self, model, seed=None):
super(Learner, self).__init__()
self.model = model
self.seed = seed
def next(self, pool, step):
raise Exception("Undefined next function")
def fit(self, X, y):
raise Ex... | class Learner(object):
"""docstring for Learner"""
def __init__(self, model, seed=None):
super(Learner, self).__init__()
self.model = model
self.seed = seed
def next(self, pool, step):
raise exception('Undefined next function')
def fit(self, X, y):
raise except... |
# see https://www.codewars.com/kata/5a092d9e46d843b9db000064/solutions/python
def solve(arr):
arr = sorted(arr)
i, j = 0, -1
while True:
if arr[i] + arr[j] != 0:
print(arr[i], arr[j], arr[i+1], arr[j-1])
if arr[i+1] + arr[j] == 0:
return arr[i]
el... | def solve(arr):
arr = sorted(arr)
(i, j) = (0, -1)
while True:
if arr[i] + arr[j] != 0:
print(arr[i], arr[j], arr[i + 1], arr[j - 1])
if arr[i + 1] + arr[j] == 0:
return arr[i]
elif arr[i + 1] != arr[i]:
return arr[j]
el... |
'''
Assigment No: 1 - Grading Logic Assigment
Author's Name: Umaima Khurshid Ahmad
Youtube Link: https://youtu.be/SY_c813y6H0
Date: 04/05/2020
'I have not given or received any unauthorized assistance on this assignment'
'''
def computeFinalGrade():
'''returns total score and grade of the student
... | """
Assigment No: 1 - Grading Logic Assigment
Author's Name: Umaima Khurshid Ahmad
Youtube Link: https://youtu.be/SY_c813y6H0
Date: 04/05/2020
'I have not given or received any unauthorized assistance on this assignment'
"""
def compute_final_grade():
"""returns total score and grade of the student
it giv... |
class ShootingProblem:
def __init__(self, initialState, runningModels, terminalModel):
""" Declare a shooting problem.
:param initialState: initial state
:param runningModels: running action models
:param terminalModel: terminal action model
"""
self.T = len(runningM... | class Shootingproblem:
def __init__(self, initialState, runningModels, terminalModel):
""" Declare a shooting problem.
:param initialState: initial state
:param runningModels: running action models
:param terminalModel: terminal action model
"""
self.T = len(running... |
class CRITsOperationalError(Exception):
""" Critical error oh shiiiii"""
pass
class CRITsInvalidTypeError(Exception):
"""Raised when an invalid TLO type is specified"""
pass
| class Critsoperationalerror(Exception):
""" Critical error oh shiiiii"""
pass
class Critsinvalidtypeerror(Exception):
"""Raised when an invalid TLO type is specified"""
pass |
def parse_table(table):
data = []
table_body = table.find('tbody')
rows = table_body.find_all('tr')
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
data.append([ele for ele in cols if ele]) # Get rid of empty values
return data
| def parse_table(table):
data = []
table_body = table.find('tbody')
rows = table_body.find_all('tr')
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
data.append([ele for ele in cols if ele])
return data |
# -*- coding: utf-8 -*-
class ExecutionDisabled(Exception):
""" Exception thrown if the manager cannot execute task because execution is disabled """
pass
class NotFound(Exception):
""" Exception thrown if a requested object is not found in a collection """
pass
class ProcessNotFound(NotFound):
"... | class Executiondisabled(Exception):
""" Exception thrown if the manager cannot execute task because execution is disabled """
pass
class Notfound(Exception):
""" Exception thrown if a requested object is not found in a collection """
pass
class Processnotfound(NotFound):
""" Exception thrown when ... |
x = int(input())
_ = ((x) + (3))
_ = ((x) * (6))
_ = ((x) & (2))
_ = ((x) ^ (1))
_ = ((x) | (3))
_ = ((x) + (10))
| x = int(input())
_ = x + 3
_ = x * 6
_ = x & 2
_ = x ^ 1
_ = x | 3
_ = x + 10 |
def swap_case(s):
t=""
for i in s:
if i.isalpha():
if i.isupper():
t=t+i.lower()
else:
t=t+i.upper()
else:
t=t+i
return (t)
| def swap_case(s):
t = ''
for i in s:
if i.isalpha():
if i.isupper():
t = t + i.lower()
else:
t = t + i.upper()
else:
t = t + i
return t |
#!/usr/bin/env python
EXPECTED_NUM_TESTS = 4
METRICS_FILE_PATH = "./svqc/tests/test_metrics.txt"
CRITERIA_FILE_PATH = "./svqc/tests/test_criteria.txt"
EXPECTED_OUT_FILE_PATH = "./svqc/tests/test_out.txt"
OUT_FILE_PATH = "./svqc/tests/test.out"
| expected_num_tests = 4
metrics_file_path = './svqc/tests/test_metrics.txt'
criteria_file_path = './svqc/tests/test_criteria.txt'
expected_out_file_path = './svqc/tests/test_out.txt'
out_file_path = './svqc/tests/test.out' |
class CacheVocabulary:
def __init__(self, vocab_data, vocab_dict, cache_number, unknown_word, blank_word):
self.word_value = {}
self.word_value[unknown_word] = 0
self.word_value[blank_word] = 1
count = 0
for key in vocab_dict.keys():
word = vocab_data.vocab.itos[... | class Cachevocabulary:
def __init__(self, vocab_data, vocab_dict, cache_number, unknown_word, blank_word):
self.word_value = {}
self.word_value[unknown_word] = 0
self.word_value[blank_word] = 1
count = 0
for key in vocab_dict.keys():
word = vocab_data.vocab.itos[... |
def relax():
neopixel.setAnimation("Color Wipe", 0, 0, 20, 1)
sleep(2)
neopixel.setAnimation("Ironman", 0, 0, 255, 1)
if (i01.eyesTracking.getOpenCV().capturing):
global MoveBodyRandom
MoveBodyRandom=0
global MoveHeadRandom
MoveHeadRandom=0
i01.setHandSpeed("left", 0.85, 0.85, ... | def relax():
neopixel.setAnimation('Color Wipe', 0, 0, 20, 1)
sleep(2)
neopixel.setAnimation('Ironman', 0, 0, 255, 1)
if i01.eyesTracking.getOpenCV().capturing:
global MoveBodyRandom
move_body_random = 0
global MoveHeadRandom
move_head_random = 0
i01.setHandSpeed(... |
class OdbAnalysisWarning:
"""The OdbAnalysisWarning object stores the description of different warnings encountered
during the analysis.
Notes
-----
This object can be accessed by:
.. code-block:: python
import visualization
session.odbData[name].diagnosticData.an... | class Odbanalysiswarning:
"""The OdbAnalysisWarning object stores the description of different warnings encountered
during the analysis.
Notes
-----
This object can be accessed by:
.. code-block:: python
import visualization
session.odbData[name].diagnosticData.an... |
class Director:
__builder = None
def setBuilder(self, builder):
self.__builder = builder
def getOrden(self):
orden = Orden()
pan = self.__builder.preparaPan()
orden.setPan(pan)
carne = self.__builder.agregaCarne()
orden.setCarne(carne)
verduras = self.... | class Director:
__builder = None
def set_builder(self, builder):
self.__builder = builder
def get_orden(self):
orden = orden()
pan = self.__builder.preparaPan()
orden.setPan(pan)
carne = self.__builder.agregaCarne()
orden.setCarne(carne)
verduras = s... |
"""
Classes for user pers.
Classes
Personality
Conditional
"""
class Personality:
"""
Represents a user's decision making.
The idea is to get all Conditional objects in goals to be true and false in limits.
This allows a user to make decisions by mapping functions to changed output.
:pa... | """
Classes for user pers.
Classes
Personality
Conditional
"""
class Personality:
"""
Represents a user's decision making.
The idea is to get all Conditional objects in goals to be true and false in limits.
This allows a user to make decisions by mapping functions to changed output.
:par... |
class Room:
room_cost = 0
def __init__(self, name: str, budget: float, members_count: int):
self.family_name = name
self.budget = budget
self.members_count = members_count
self.children = []
self.expenses = 0
@property
def total_monthly_cost(self):
retur... | class Room:
room_cost = 0
def __init__(self, name: str, budget: float, members_count: int):
self.family_name = name
self.budget = budget
self.members_count = members_count
self.children = []
self.expenses = 0
@property
def total_monthly_cost(self):
retur... |
class Solution:
def nthUglyNumber(self, n: int) -> int:
if n < 0: return 0
dp = [1] * n
index2 = index3 = index5 = 0
for i in range(1, n):
dp[i] = min(2 * dp[index2], 3 * dp[index3], 5 * dp[index5])
if dp[i] == 2 * dp[index2]: index2 += 1
if dp[i] ... | class Solution:
def nth_ugly_number(self, n: int) -> int:
if n < 0:
return 0
dp = [1] * n
index2 = index3 = index5 = 0
for i in range(1, n):
dp[i] = min(2 * dp[index2], 3 * dp[index3], 5 * dp[index5])
if dp[i] == 2 * dp[index2]:
in... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 18 06:40:34 2018
@author: boele
"""
# 02, reading text files and converting from NED to XYZ
# open xyz file
f = open('test.xyz', 'r')
data = f.read()
xyz = data.split('\n')
# print first 5 rows
print(xyz[0:5])
# create empty ned list
ned = []
# f... | """
Created on Wed Jan 18 06:40:34 2018
@author: boele
"""
f = open('test.xyz', 'r')
data = f.read()
xyz = data.split('\n')
print(xyz[0:5])
ned = []
for row in xyz:
values = row.split(' ')
ned.append([values[1], values[0], '-' + values[2]])
print(ned[0:5])
print(ned[16][2]) |
##sequence = [1,1]
##length_expection = int(input("Please enter the length\
## of Fibonacci to generate:"))
##i = 1
##j = 2
##while len(sequence) <= length_expection:
## sequence.append(i+j)
## i += 1
## j += 1
##print(element for element in sequence)
a = 1
b = 1
while a < 1000:
... | a = 1
b = 1
while a < 1000:
print(a)
(a, b) = (b, a + b) |
def draw():
rows = int(pow(2, int(random(1, 6))))
u = int(height / (rows + 4))
thickness = int(pow(2, int(random(1, 4))))
uth1 = int(u / thickness)
uth2 = u + uth1
startX = int(-u * .75)
startY = int(height / 2 + rows / 2 * u)
endX = width + u
endY = height / 2 + rows / 2 * u
fo... | def draw():
rows = int(pow(2, int(random(1, 6))))
u = int(height / (rows + 4))
thickness = int(pow(2, int(random(1, 4))))
uth1 = int(u / thickness)
uth2 = u + uth1
start_x = int(-u * 0.75)
start_y = int(height / 2 + rows / 2 * u)
end_x = width + u
end_y = height / 2 + rows / 2 * u
... |
__all__ = [
'base_controller',
'cdrs_controller',
'numbers_controller',
'routes_controller',
'messages_controller',
] | __all__ = ['base_controller', 'cdrs_controller', 'numbers_controller', 'routes_controller', 'messages_controller'] |
#!/usr/bin/python3
"""Meowth - A Discord helper bot for Pokemon Go communities.
Meowth is a Discord bot written in Python 3.5 using version 0.16.12 of the discord.py library.
It assists with the organisation of local Pokemon Go Discord servers and their members."""
__author__ = "FoglyOgly, Scragly and BrenenP"
__copyr... | """Meowth - A Discord helper bot for Pokemon Go communities.
Meowth is a Discord bot written in Python 3.5 using version 0.16.12 of the discord.py library.
It assists with the organisation of local Pokemon Go Discord servers and their members."""
__author__ = 'FoglyOgly, Scragly and BrenenP'
__copyright__ = 'Copyright... |
#!/usr/bin/env python3
"""Zig Zag.
Given an array A (distinct elements) of size N.
Rearrange the elements of array in zig-zag fashion.
The converted array should be in form a < b > c < d > e < f.
The relative order of elements is same in the output
i.e you have to iterate on the original array only.
Source:
https://p... | """Zig Zag.
Given an array A (distinct elements) of size N.
Rearrange the elements of array in zig-zag fashion.
The converted array should be in form a < b > c < d > e < f.
The relative order of elements is same in the output
i.e you have to iterate on the original array only.
Source:
https://practice.geeksforgeeks.or... |
__author__ = 'Chintalagiri Shashank'
__email__ = 'shashank@chintal.in'
__version__ = '0.1.0'
| __author__ = 'Chintalagiri Shashank'
__email__ = 'shashank@chintal.in'
__version__ = '0.1.0' |
def make_bold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def make_italic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
def make_underline(fn):
def wrapped():
return "<u>" + fn() + "</u>"
return wrapped
@make_bold
@ma... | def make_bold(fn):
def wrapped():
return '<b>' + fn() + '</b>'
return wrapped
def make_italic(fn):
def wrapped():
return '<i>' + fn() + '</i>'
return wrapped
def make_underline(fn):
def wrapped():
return '<u>' + fn() + '</u>'
return wrapped
@make_bold
@make_italic
@... |
# 000577_30_Dict_add_rem
customer_29876 = {'first name': 'David', 'last name': 'Elliott', 'address': '4803 Wellesley St.', 'city': 'Toronto'}
print("initial dict", customer_29876)
# rem
del customer_29876["address"]
print('remove "address"',customer_29876)
# add "street"
print("add street")
customer_29876["street"] = "... | customer_29876 = {'first name': 'David', 'last name': 'Elliott', 'address': '4803 Wellesley St.', 'city': 'Toronto'}
print('initial dict', customer_29876)
del customer_29876['address']
print('remove "address"', customer_29876)
print('add street')
customer_29876['street'] = 'Park Avenue'
print(customer_29876)
print('cha... |
def user_selection(message, options):
# taken from https://github.com/Asana/python-asana/blob/master/examples/example-create-task.py
option_list = list(options)
print(message)
for i, option in enumerate(option_list):
print(i, ": " + option["name"])
index = int(input("Enter choice (default 0)... | def user_selection(message, options):
option_list = list(options)
print(message)
for (i, option) in enumerate(option_list):
print(i, ': ' + option['name'])
index = int(input('Enter choice (default 0): ') or 0)
return option_list[index] |
"""
Name: exception.py
Author: Charles Zhang <694556046@qq.com>
Propose: PyGrading exceptions
Coding: UTF-8
"""
class DataTypeError(Exception):
pass
class FunctionsTypeError(Exception):
pass
class FieldMissingError(Exception):
pass
class ExecError(Exception):
pass
class Functio... | """
Name: exception.py
Author: Charles Zhang <694556046@qq.com>
Propose: PyGrading exceptions
Coding: UTF-8
"""
class Datatypeerror(Exception):
pass
class Functionstypeerror(Exception):
pass
class Fieldmissingerror(Exception):
pass
class Execerror(Exception):
pass
class Functionargs... |
"""
Miscellaneous utility classes and functions.
"""
class Location:
@classmethod
def location_from_pos(cls, src, pos, name=None, filename=None):
loc = Location(src, name=name, filename=filename, ln=0, col=0, pos=0)
for c in src:
loc._inc_pos()
if c == '\n':
... | """
Miscellaneous utility classes and functions.
"""
class Location:
@classmethod
def location_from_pos(cls, src, pos, name=None, filename=None):
loc = location(src, name=name, filename=filename, ln=0, col=0, pos=0)
for c in src:
loc._inc_pos()
if c == '\n':
... |
class Object:
"""
Represents a detected object
"""
# (x, y) is the top left coordinate
x = None
y = None
# (x2, y2) is the bottom right coordinate
x2 = None
y2 = None
width = None
height = None
label = None
score = None
def to_string(self):
return "x={}, ... | class Object:
"""
Represents a detected object
"""
x = None
y = None
x2 = None
y2 = None
width = None
height = None
label = None
score = None
def to_string(self):
return "x={}, y={}\nx2={}, y2={}\nwidth={}, height={}\nlabel='{}'\nscore={}\n".format(self.x, self.y... |
class MenuItem(object):
def __init__(self, type: str, title: str, **kwargs):
if not isinstance(type, str):
raise TypeError('type must be an instance of str')
if not isinstance(title, str):
raise TypeError('title must be an instance of str')
self.type = type
se... | class Menuitem(object):
def __init__(self, type: str, title: str, **kwargs):
if not isinstance(type, str):
raise type_error('type must be an instance of str')
if not isinstance(title, str):
raise type_error('title must be an instance of str')
self.type = type
... |
class dotUndoOperation_t(object):
# no doc
Operation=None
| class Dotundooperation_T(object):
operation = None |
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/master/LICENSE
def indent_code(code, indent):
finalcode = ""
for line in code.splitlines():
finalcode += " " * indent + line + "\n"
return finalcode
| def indent_code(code, indent):
finalcode = ''
for line in code.splitlines():
finalcode += ' ' * indent + line + '\n'
return finalcode |
'''
lec4
dict
tuple
'''
my_tuple = 'a','b','c','d','e'
print(my_tuple)
my_2nd_tuple= ('a','b','c','d','e')
print (my_2nd_tuple)
is_a_tuple= ('a',)
print ( type(is_a_tuple) )
print (my_tuple[1])
my_car = {
'color' : 'red',
'maker': 'toyota',
'year': 2015
}
print (my_car)
print (my_car ['color'])... | """
lec4
dict
tuple
"""
my_tuple = ('a', 'b', 'c', 'd', 'e')
print(my_tuple)
my_2nd_tuple = ('a', 'b', 'c', 'd', 'e')
print(my_2nd_tuple)
is_a_tuple = ('a',)
print(type(is_a_tuple))
print(my_tuple[1])
my_car = {'color': 'red', 'maker': 'toyota', 'year': 2015}
print(my_car)
print(my_car['color'])
print(my_car['year'])
p... |
class Credentials:
def __init__(self, appkey, secretkey, accountkey=None):
self.appkey = appkey
self.secretkey = secretkey
self.account_key = accountkey
def __eq__(self, other: object) -> bool:
if isinstance(other, Credentials):
return self.appkey == other.appkey \
... | class Credentials:
def __init__(self, appkey, secretkey, accountkey=None):
self.appkey = appkey
self.secretkey = secretkey
self.account_key = accountkey
def __eq__(self, other: object) -> bool:
if isinstance(other, Credentials):
return self.appkey == other.appkey an... |
i = 1
pool = 3
entFormat = open("play_script.txt", "w")
while i == 1:
readLine = input()
if readLine == "stop":
i = 0
entFormat.close()
else:
if readLine == "":
wool = "{}".format(pool)
entFormat.write(" elseif time < "+wool+" then\n")
pool = p... | i = 1
pool = 3
ent_format = open('play_script.txt', 'w')
while i == 1:
read_line = input()
if readLine == 'stop':
i = 0
entFormat.close()
elif readLine == '':
wool = '{}'.format(pool)
entFormat.write(' elseif time < ' + wool + ' then\n')
pool = pool + 1
elif re... |
# Uses python3
def edit_distance(s, t, memo = {}):
if len(s) == 0: return len(t)
if len(t) == 0: return len(s)
if (len(s), len(t)) in memo:
return memo[(len(s), len(t))]
delta = 1 if s[-1] != t[-1] else 0
diag = edit_distance(s[:-1], t[:-1], memo) + delta
vert = edit_distance(s[:-1], t... | def edit_distance(s, t, memo={}):
if len(s) == 0:
return len(t)
if len(t) == 0:
return len(s)
if (len(s), len(t)) in memo:
return memo[len(s), len(t)]
delta = 1 if s[-1] != t[-1] else 0
diag = edit_distance(s[:-1], t[:-1], memo) + delta
vert = edit_distance(s[:-1], t, mem... |
#
# @lc app=leetcode id=280 lang=python3
#
# [280] Wiggle Sort
#
# @lc code=start
class Solution:
def wiggleSort(self, nums):
"""
Do not return anything, modify nums in-place instead.
"""
if nums:
nums.sort()
for i in range(1, len(nums) - 1, 2):
... | class Solution:
def wiggle_sort(self, nums):
"""
Do not return anything, modify nums in-place instead.
"""
if nums:
nums.sort()
for i in range(1, len(nums) - 1, 2):
(nums[i], nums[i + 1]) = (nums[i + 1], nums[i]) |
# Examen Parcial 1 Algoritmos y Estructuras 2 Seccion 305C1
# ----- Programacion Modular -----
def factorial(numero):
fact = 1
for i in range (1, numero + 1):
fact *= i
return (fact)
def coseno(num, termino):
bandera = True
result = 1
if(termino % 2 == 0):
... | def factorial(numero):
fact = 1
for i in range(1, numero + 1):
fact *= i
return fact
def coseno(num, termino):
bandera = True
result = 1
if termino % 2 == 0:
for i in range(2, termino + 2, 2):
if bandera:
result -= pow(num, i) / factorial(i)
... |
# -*- coding: utf-8 -*-
"""
mothpy - moth-inspired navigation models flying in `pompy` (Puff Odour-plume Model in Python)
@author: Noam Benelli and Alex Liberzon
"""
name = "mothpy"
| """
mothpy - moth-inspired navigation models flying in `pompy` (Puff Odour-plume Model in Python)
@author: Noam Benelli and Alex Liberzon
"""
name = 'mothpy' |
# HEAD
# Classes - Metaclasses for class modification
# DESCRIPTION
# Describes how to use metaclasses dynamically to modify classes during instatiation
# Describes how to add attributes to a metaclass
# or re-implement the type __call__ methods
# Public
# RESOURCES
#
# /opt/pycharm/pycharm-community-2019.2.... | class Modelbase(type):
def hello(cls):
print('Test', type(cls))
def __init__(cls, name, bases, dct):
print('bases', bases)
print('name', name)
print('dict', dct)
print('cls.__dict__', cls.__dict__)
return super(ModelBase, cls).__init__(cls)
def __call__(sel... |
# Challenge 036 - 04/21/2021 - Henrique Matheus Alves Pereira
# Write a program to approve the bank loan for the purchase of a home.
# Ask the price of the house, the buyer's salary and how many years he will pay.
# The monthly installment cannot exceed 30% of the salary or the loan will be denied.
print("Challenge 036... | print('Challenge 036')
print('Please, for the following information, enter only two digits after the comma.')
price_house = float(input('1 - Please, enter the purchase price of the home (R$):'))
financing_time = float(input('2 - Please, enter the financing time of the home (Years):'))
salary = float(input('3 - Please, ... |
abeceda = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
def abecedna_vrednost(ime):
seznam = list(str(ime))
vrednost = 0
for i in range(len(seznam)):
vrednost = vrednost + abeceda.index(seznam[i]) + 1
return vr... | abeceda = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
def abecedna_vrednost(ime):
seznam = list(str(ime))
vrednost = 0
for i in range(len(seznam)):
vrednost = vrednost + abeceda.index(seznam[i]) + 1
return vr... |
wt3_3_7 = {'192.168.122.110': [5.3551, 8.3352, 7.3783, 6.9324, 6.6606, 6.4673, 6.5077, 6.6393, 7.3012, 7.1319, 6.7323, 6.3639, 6.33, 6.6602, 6.9711, 6.8935, 7.1543, 7.3671, 7.2675, 7.223, 7.1379, 7.3225, 7.2638, 7.4282, 7.435, 7.3821, 7.5459, 7.4728, 7.4688, 7.4658, 7.3986, 7.347, 7.4649, 7.4186, 7.4119, 7.358, 7.3216... | wt3_3_7 = {'192.168.122.110': [5.3551, 8.3352, 7.3783, 6.9324, 6.6606, 6.4673, 6.5077, 6.6393, 7.3012, 7.1319, 6.7323, 6.3639, 6.33, 6.6602, 6.9711, 6.8935, 7.1543, 7.3671, 7.2675, 7.223, 7.1379, 7.3225, 7.2638, 7.4282, 7.435, 7.3821, 7.5459, 7.4728, 7.4688, 7.4658, 7.3986, 7.347, 7.4649, 7.4186, 7.4119, 7.358, 7.3216,... |
class RaceRegistry:
"""Race Registry includes runners' information
Attributes:
@type under_20: list
emails of under_20 category
@type under_30: list
emails of under_30 category
@type under_40: list
emails of under_40 category
@type over_40: list
e... | class Raceregistry:
"""Race Registry includes runners' information
Attributes:
@type under_20: list
emails of under_20 category
@type under_30: list
emails of under_30 category
@type under_40: list
emails of under_40 category
@type over_40: list
e... |
num = int(input('Digite o numero para a tabuada: '))
contador = 0
print('-' * 12)
print('{} * {:2} = {:2}'.format(num, contador, (num*contador)))
contador = contador + 1
print('{} * {:2} = {:2}'.format(num, contador, (num*contador)))
contador = contador + 1
print('{} * {:2} = {:2}'.format(num, contador, (num*contador))... | num = int(input('Digite o numero para a tabuada: '))
contador = 0
print('-' * 12)
print('{} * {:2} = {:2}'.format(num, contador, num * contador))
contador = contador + 1
print('{} * {:2} = {:2}'.format(num, contador, num * contador))
contador = contador + 1
print('{} * {:2} = {:2}'.format(num, contador, num * contador)... |
class BetelError(Exception):
"""Raise when an exception occurs."""
class PlayScrapingError(BetelError):
"""Raise when certain attributes can't be found within the Play page."""
class AccessError(BetelError):
"""Raise on URL or HTTP errors."""
def __init__(self, message, exception):
super(Acc... | class Betelerror(Exception):
"""Raise when an exception occurs."""
class Playscrapingerror(BetelError):
"""Raise when certain attributes can't be found within the Play page."""
class Accesserror(BetelError):
"""Raise on URL or HTTP errors."""
def __init__(self, message, exception):
super(Acce... |
class DeviceModelDoesnotExistException(Exception):
def __str__(self):
return "Target device model doesn't exist."
class ParameterCannotBeNone(Exception):
def __str__(self):
return "Parameter cannot all be None."
| class Devicemodeldoesnotexistexception(Exception):
def __str__(self):
return "Target device model doesn't exist."
class Parametercannotbenone(Exception):
def __str__(self):
return 'Parameter cannot all be None.' |
level = 3
name = 'Margahayu'
capital = 'Sukamenak'
area = 10.54
| level = 3
name = 'Margahayu'
capital = 'Sukamenak'
area = 10.54 |
"""A dictonary containing every option/button in the map.
xStart, yStart, xEnd, yEnd are all percentiles, which are later multipled by the total width and
height of the map.
Activated is a boolean which changes when the button is placed on the screen.
Ending is a boolean which determines if that option/button is the fi... | """A dictonary containing every option/button in the map.
xStart, yStart, xEnd, yEnd are all percentiles, which are later multipled by the total width and
height of the map.
Activated is a boolean which changes when the button is placed on the screen.
Ending is a boolean which determines if that option/button is the fi... |
'''
Loops let you walk through a sequence of items, such as items in a list
'''
#
# looping through a list
#
colors = ['black', 'blue', 'brown', 'green', 'purple', 'white', 'yellow']
for color in colors:
print(color)
#
# Looping through a range of numbers
#
for num in range(5):
print(num) # Prints th... | """
Loops let you walk through a sequence of items, such as items in a list
"""
colors = ['black', 'blue', 'brown', 'green', 'purple', 'white', 'yellow']
for color in colors:
print(color)
for num in range(5):
print(num)
for num in range(10, 16):
print(num)
for num in range(20, 31, 2):
print(num) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def get_palindromic(n_s, n_e):
n_1 = n_s
f_1 = -1
f_2 = -1
f = -1
while n_1 <= n_e:
for n_2 in range(n_1, n_e+1):
n = n_1 * n_2
if is_palindromic(n) and n > f:
f_1 = n_1
f_2 = n_2
... | def get_palindromic(n_s, n_e):
n_1 = n_s
f_1 = -1
f_2 = -1
f = -1
while n_1 <= n_e:
for n_2 in range(n_1, n_e + 1):
n = n_1 * n_2
if is_palindromic(n) and n > f:
f_1 = n_1
f_2 = n_2
f = n
n_1 += 1
return (f, ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Author - Samar Srivastava (https://samacker77.github.io)
Problem Link - https://www.hackerrank.com/challenges/s10-quartiles/problem
Problem Statement - Given an array, X, of n integers, calculate the respective first quartile (Q1), second quartile (Q2), and third qua... | """
Author - Samar Srivastava (https://samacker77.github.io)
Problem Link - https://www.hackerrank.com/challenges/s10-quartiles/problem
Problem Statement - Given an array, X, of n integers, calculate the respective first quartile (Q1), second quartile (Q2), and third quartile (Q3).
It is guaranteed that Q1, Q2,and Q3... |
def edit_distance(s1, s2):
"""Calculates the Levenshtein distance between two strings."""
if s1 == s2: # if equal, then distance is zero
return 0
m, n = len(s1), len(s2)
# if one string is empty, then distance is the length of the other string
if not s1:
return n
elif not s2:... | def edit_distance(s1, s2):
"""Calculates the Levenshtein distance between two strings."""
if s1 == s2:
return 0
(m, n) = (len(s1), len(s2))
if not s1:
return n
elif not s2:
return m
c = None
d = range(n + 1)
for i in range(1, m + 1):
(c, d) = (d, [i] + [0]... |
"""
map() toma un iterable y devuelve otro iterable
"""
friends = ['Juan', 'Carlos', 'Daniel', 'Ricardo', 'Jhon']
friends_lower = map(lambda x: x.lower(), friends)
print(next(friends_lower))
print(next(friends_lower))
class User:
def __init__(self, username, password):
self.username = username
s... | """
map() toma un iterable y devuelve otro iterable
"""
friends = ['Juan', 'Carlos', 'Daniel', 'Ricardo', 'Jhon']
friends_lower = map(lambda x: x.lower(), friends)
print(next(friends_lower))
print(next(friends_lower))
class User:
def __init__(self, username, password):
self.username = username
sel... |
'''
Piling Up!
https://www.hackerrank.com/challenges/piling-up/problem
There is a horizontal row of n cubes. The length of each cube is given. You need to create a new vertical pile of cubes. The new pile should follow these directions: if cube(i) is on top of cube(j) then sideLength(j) >= sideLength(i).
When stack... | """
Piling Up!
https://www.hackerrank.com/challenges/piling-up/problem
There is a horizontal row of n cubes. The length of each cube is given. You need to create a new vertical pile of cubes. The new pile should follow these directions: if cube(i) is on top of cube(j) then sideLength(j) >= sideLength(i).
When stacki... |
"""
lab2
"""
#3.1
my_name = 'Tom'
print(my_name.upper())
#3.2
my_id = 123
print(my_id)
#3.3
my_id = your_id = 123
print(my_id)
print(your_id)
#3.4
my_id_str = "123"
print(my_id_str)
#3.5
#print(my_name + my_id) Cannot add string and variable
#3.6
print(my_name + my_id_str)
#3.7
print(my_name * 3)
#3.8
print... | """
lab2
"""
my_name = 'Tom'
print(my_name.upper())
my_id = 123
print(my_id)
my_id = your_id = 123
print(my_id)
print(your_id)
my_id_str = '123'
print(my_id_str)
print(my_name + my_id_str)
print(my_name * 3)
print('hello, world. This is my first python string.'.split('.'))
message = "Tom's ID is 123"
print(message) |
def get_average_inventory_worth(current, production, consumption, processing, queued, missing, trade):
results = {"P1": 0, "P2": 0, "P3": 0, "E4": 0, "E5": 0, "E6": 0, "E7": 0, "E8": 0, "E9": 0, "E10": 0, "E11": 0, "E12": 0, "E13": 0, "E14": 0, "E15": 0,
"E16": 0, "E17": 0, "E18": 0, "E19": 0, "E20"... | def get_average_inventory_worth(current, production, consumption, processing, queued, missing, trade):
results = {'P1': 0, 'P2': 0, 'P3': 0, 'E4': 0, 'E5': 0, 'E6': 0, 'E7': 0, 'E8': 0, 'E9': 0, 'E10': 0, 'E11': 0, 'E12': 0, 'E13': 0, 'E14': 0, 'E15': 0, 'E16': 0, 'E17': 0, 'E18': 0, 'E19': 0, 'E20': 0, 'K21': 0, '... |
#! /usr/bin/env python3
'''
Problem 1 - Project Euler
http://projecteuler.net/index.php?section=problems&id=001
'''
def summul(n, x):
return int(x * (n // x) * (n // x + 1) / 2)
if __name__ == '__main__':
N = 1000 - 1
print(summul(N, 3) + summul(N, 5) - summul(N, 3 * 5))
| """
Problem 1 - Project Euler
http://projecteuler.net/index.php?section=problems&id=001
"""
def summul(n, x):
return int(x * (n // x) * (n // x + 1) / 2)
if __name__ == '__main__':
n = 1000 - 1
print(summul(N, 3) + summul(N, 5) - summul(N, 3 * 5)) |
for t in range(int(input())):
A,B=input().split()
L=[[0]*(len(A)+1) for i in range((len(B)+1))]
for i in range(len(B)):
for j in range(len(A)):
if B[i]==A[j]:
L[i+1][j+1]=L[i][j]+1
else :
L[i+1][j+1]=max(L[i][j+1],L[i+1][j])
print(f"#{t+1}... | for t in range(int(input())):
(a, b) = input().split()
l = [[0] * (len(A) + 1) for i in range(len(B) + 1)]
for i in range(len(B)):
for j in range(len(A)):
if B[i] == A[j]:
L[i + 1][j + 1] = L[i][j] + 1
else:
L[i + 1][j + 1] = max(L[i][j + 1], L... |
with Flow(bypass_sub_flows=True,
add_flow_enable="enabled",
environment="probe") as flow:
flow.description = '''
An example of creating an entire test program from a single source file
'''
#unless Origen.app.environment.name == 'v93k_global'
flow.set_resources_filename('prb2')
... | with flow(bypass_sub_flows=True, add_flow_enable='enabled', environment='probe') as flow:
flow.description = '\n An example of creating an entire test program from a single source file\n '
flow.set_resources_filename('prb2')
flow.func('erase_all', duration='dynamic', number=10000)
flow.func('mar... |
__title__ = 'campy'
__description__ = 'ACM Graphical Libraries in Python'
__url__ = 'https://campy.sredmond.io/'
__license__ = 'MIT'
__version__ = '0.0.1.dev3'
__build__ = 0x000001
__status__ = 'Prototype'
__author__ = 'Sam Redmond'
__maintainer__ = 'Sam Redmond'
__email__ = 'sredmond@stanford.edu'
__copyright__ = '(... | __title__ = 'campy'
__description__ = 'ACM Graphical Libraries in Python'
__url__ = 'https://campy.sredmond.io/'
__license__ = 'MIT'
__version__ = '0.0.1.dev3'
__build__ = 1
__status__ = 'Prototype'
__author__ = 'Sam Redmond'
__maintainer__ = 'Sam Redmond'
__email__ = 'sredmond@stanford.edu'
__copyright__ = '(c) 2016-2... |
#!/usr/bin/env python3
def solve(data):
allowed = []
test_num = 0
prv_rng = range(0, 0)
for rng in sorted(data, key=lambda x: x.start):
if rng.stop in prv_rng:
continue
while not test_num in rng:
allowed.append(test_num)
test_num += 1
prv_rng ... | def solve(data):
allowed = []
test_num = 0
prv_rng = range(0, 0)
for rng in sorted(data, key=lambda x: x.start):
if rng.stop in prv_rng:
continue
while not test_num in rng:
allowed.append(test_num)
test_num += 1
prv_rng = rng
test_num =... |
S = input()
A = input()
if len(S) < len(A):
print('UNRESTORABLE')
exit(0)
for i in reversed(range(len(S)-len(A)+1)):
for j in range(len(A)):
if not(S[i+j] == A[j] or S[i+j] == '?'):
break
else:
ans = S[:i] + A + S[i+len(A):]
ans = ans.replace('?', 'a')
prin... | s = input()
a = input()
if len(S) < len(A):
print('UNRESTORABLE')
exit(0)
for i in reversed(range(len(S) - len(A) + 1)):
for j in range(len(A)):
if not (S[i + j] == A[j] or S[i + j] == '?'):
break
else:
ans = S[:i] + A + S[i + len(A):]
ans = ans.replace('?', 'a')
... |
def to_celsius(x):
return (x-32)*5/9
for x in range(0,101,10):
print(x,to_celsius(x))
| def to_celsius(x):
return (x - 32) * 5 / 9
for x in range(0, 101, 10):
print(x, to_celsius(x)) |
def selection_sort(array):
length = len(array)
for i in range(0, length, 1):
higher = i
for j in range(i+1, length, 1):
if array[higher] > array[j]:
higher = j
if higher != i:
tmp = array[higher]
array[higher] = array[i]
... | def selection_sort(array):
length = len(array)
for i in range(0, length, 1):
higher = i
for j in range(i + 1, length, 1):
if array[higher] > array[j]:
higher = j
if higher != i:
tmp = array[higher]
array[higher] = array[i]
a... |
class ToolStripItem(
Component,
IComponent,
IDisposable,
IDropTarget,
ISupportOleDropSource,
IArrangedElement,
):
""" Represents the abstract base class that manages events and layout for all the elements that a System.Windows.Forms.ToolStrip or System.Windows.Forms.ToolStripDropDown... | class Toolstripitem(Component, IComponent, IDisposable, IDropTarget, ISupportOleDropSource, IArrangedElement):
""" Represents the abstract base class that manages events and layout for all the elements that a System.Windows.Forms.ToolStrip or System.Windows.Forms.ToolStripDropDown can contain. """
def create_a... |
"""Global errors:
Global error codes are negative, with four decimal digits, where the two most significant ones indicate
which analyzer is generating them:
-10__: NumberAnalyzer (num_analyzer.py)
-11__: CharAnalyzer (string_analyzer.py)
-12__: StringAnalyzer ... | """Global errors:
Global error codes are negative, with four decimal digits, where the two most significant ones indicate
which analyzer is generating them:
-10__: NumberAnalyzer (num_analyzer.py)
-11__: CharAnalyzer (string_analyzer.py)
-12__: StringAnalyzer ... |
# 315. Count of Smaller Numbers After Self
# ttungl@gmail.com
# You are given an integer array nums and you have to return a new counts array.
# The counts array has the property where counts[i] is the number of smaller elements
# to the right of nums[i].
# Example:
# Given nums = [5, 2, 6, 1]
# To the right of 5 ... | class Solution(object):
def count_smaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
(res, sort_arr) = ([], [])
for i in nums[::-1]:
res.append(bisect.bisect_left(sortArr, i))
bisect.insort(sortArr, i)
return res[::-1... |
"""You would probably keep your configuration out of the git repo, but
this works for a simple script.
See the docs for information on Flask configuration.
"""
DATABASE_NAME = 'flask_mongo_example'
| """You would probably keep your configuration out of the git repo, but
this works for a simple script.
See the docs for information on Flask configuration.
"""
database_name = 'flask_mongo_example' |
class Unit(object):
def __init__(self, name, attack, defend):
self.name = name
self.attack = attack
self.defend = defend
def __repr__(self):
return self.name
units = {
'droid': Unit('droid', 42, 41),
'gorgul': Unit('gorgul', 24, 20),
'pushkar': Unit('pushkar', 55, ... | class Unit(object):
def __init__(self, name, attack, defend):
self.name = name
self.attack = attack
self.defend = defend
def __repr__(self):
return self.name
units = {'droid': unit('droid', 42, 41), 'gorgul': unit('gorgul', 24, 20), 'pushkar': unit('pushkar', 55, 37), 'giant': ... |
# Solutions for Radon tutorial - PyData Global 2020 Tutorial
def radon_noise():
"""Create noise to add to projections
"""
sigman = 5e-1 # play with this...
n = np.random.normal(0., sigman, projection.shape)
projection_n = projection + n
projection1_n = projection1 + \
n[pro... | def radon_noise():
"""Create noise to add to projections
"""
sigman = 0.5
n = np.random.normal(0.0, sigman, projection.shape)
projection_n = projection + n
projection1_n = projection1 + n[projection.shape[0] // 2 - (nx - inner) // 2:projection.shape[0] // 2 + (nx - inner) // 2].T
def radon_more... |
X, Y = map(int, input().split())
X += 2
if Y >= 30:
X += 1
Y -= 30
else:
Y += 30
X %= 24
print('%02d:%02d' % (X, Y))
| (x, y) = map(int, input().split())
x += 2
if Y >= 30:
x += 1
y -= 30
else:
y += 30
x %= 24
print('%02d:%02d' % (X, Y)) |
class Node:
def __init__(self, key) -> None:
self.val = key
self.left = None
self.right = None
def printInorder(node):
if node == None:
return
else:
printInorder(node.left)
print(node.val, end=' ')
right_node = printInorder(node.right)
def pre... | class Node:
def __init__(self, key) -> None:
self.val = key
self.left = None
self.right = None
def print_inorder(node):
if node == None:
return
else:
print_inorder(node.left)
print(node.val, end=' ')
right_node = print_inorder(node.right)
def pre_or... |
filenames = ['file1.txt', 'file2.txt', ...]
with open('path/to/output/file', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
outfile.write(infile.read())
| filenames = ['file1.txt', 'file2.txt', ...]
with open('path/to/output/file', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
outfile.write(infile.read()) |
"""
To sort the array to count the set bits in binary representation
of array elements.
"""
def count_set_bits(num):
count = 0
while num:
if num & 1:
count += 1
num = num >> 1
return count
def sort_setbit_based(array):
count = []
for i in range(len(array)):
... | """
To sort the array to count the set bits in binary representation
of array elements.
"""
def count_set_bits(num):
count = 0
while num:
if num & 1:
count += 1
num = num >> 1
return count
def sort_setbit_based(array):
count = []
for i in range(len(array)):
... |
class Parent:
def __init__(self, name):
print("Parent Object Created")
self.testFunc(name)
def testFunc(self, name):
print("Parent testFunc called {}", name)
class Child(Parent):
def __init__(self, name):
print("Child Object Created")
self.testFunc(name)
# def testFunc(self, name):
# print("Child testF... | class Parent:
def __init__(self, name):
print('Parent Object Created')
self.testFunc(name)
def test_func(self, name):
print('Parent testFunc called {}', name)
class Child(Parent):
def __init__(self, name):
print('Child Object Created')
self.testFunc(name)
class O... |
'''
Write a Python program to find the largest product of the pair of
adjacent elements from a given list of integers.
Sample Input:
[1,2,3,4,5,6]
[1,2,3,4,5]
[2,3]
Sample Output:
30
20
6
'''
'''
The zip() function returns a zip object, which is an
iterator of tuples where the first item in each passed iterator is p... | """
Write a Python program to find the largest product of the pair of
adjacent elements from a given list of integers.
Sample Input:
[1,2,3,4,5,6]
[1,2,3,4,5]
[2,3]
Sample Output:
30
20
6
"""
'\nThe zip() function returns a zip object, which is an \niterator of tuples where the first item in each passed iterator is pa... |
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: TreeNode):
self.stack = []
self.getLeftMostNode(root)
def getLeftMostNode(self, 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: TreeNode):
self.stack = []
self.getLeftMostNode(root)
def get_left_most_node(self, node: TreeNode) -> N... |
def longestPeak(array):
# Write your code here.
maxPeakLength=0
i=1
while(i<len(array)-1):
# print(i)
isPeak= array[i]>array[i-1] and array[i]>array[i+1]
if not isPeak:
i+=1
continue
leftIdx=i-2
while(leftIdx>=0 and array[leftIdx]<array[... | def longest_peak(array):
max_peak_length = 0
i = 1
while i < len(array) - 1:
is_peak = array[i] > array[i - 1] and array[i] > array[i + 1]
if not isPeak:
i += 1
continue
left_idx = i - 2
while leftIdx >= 0 and array[leftIdx] < array[leftIdx + 1]:
... |
'''
Array uses one-based indexing to access elements
Implements Max-Heap Tree
Can be used for max priority queue
'''
class HeapTree:
def __init__(self, value:int):
self.array = [0]
self.heap_size = 0
self.max_size = value
def left_child(self, index:int):
'''
... | """
Array uses one-based indexing to access elements
Implements Max-Heap Tree
Can be used for max priority queue
"""
class Heaptree:
def __init__(self, value: int):
self.array = [0]
self.heap_size = 0
self.max_size = value
def left_child(self, index: int):
"""
... |
class Page:
__index__ = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{title}}</title>
<!-- ADD YOUR CSS & CDN HERE WHICH IS APPLICABLE TO ALL... | class Page:
__index__ = '<!DOCTYPE html>\n<html lang="en">\n\n<head>\n <meta charset="UTF-8">\n <meta http-equiv="X-UA-Compatible" content="IE=edge">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n <title>{{title}}</title>\n <!-- ADD YOUR CSS & CDN HERE WHICH IS APPLICABLE ... |
def display(g):
for y in range(g.height):
for x in range(g.width):
digit, snake = g(x, y)
if snake:
print("[{}]".format(digit), end="")
else:
print(" {} ".format(digit), end="")
if x % 3 == 2:
print(" ", end="")
... | def display(g):
for y in range(g.height):
for x in range(g.width):
(digit, snake) = g(x, y)
if snake:
print('[{}]'.format(digit), end='')
else:
print(' {} '.format(digit), end='')
if x % 3 == 2:
print(' ', end=''... |
#===============================================================
# DMXIS Macro (c) 2010 db audioware limited
#===============================================================
found = False
for ch in GetAllSelCh(True):
nm = GetChName(ch)
if nm=="Pan" or nm=="Tilt":
SelectCh(ch, 1)
found ... | found = False
for ch in get_all_sel_ch(True):
nm = get_ch_name(ch)
if nm == 'Pan' or nm == 'Tilt':
select_ch(ch, 1)
found = True
else:
select_ch(ch, 0)
if not found:
message('No Pan/Tilt channels found!') |
s = ''
i = 1
while (True):
s = s + str(i)
i = i + 1
if len(s) > 1000000:
break
print(i)
r = 1
r = r * int(s[1 - 1])
r = r * int(s[10 - 1])
r = r * int(s[100 - 1])
r = r * int(s[1000 - 1])
r = r * int(s[10000 - 1])
r = r * int(s[100000 - 1])
r = r * int(s[1000000 - 1])
print("result = ", r)
| s = ''
i = 1
while True:
s = s + str(i)
i = i + 1
if len(s) > 1000000:
break
print(i)
r = 1
r = r * int(s[1 - 1])
r = r * int(s[10 - 1])
r = r * int(s[100 - 1])
r = r * int(s[1000 - 1])
r = r * int(s[10000 - 1])
r = r * int(s[100000 - 1])
r = r * int(s[1000000 - 1])
print('result = ', r) |
ENTRY_POINT = 'maximum'
#[PROMPT]
def maximum(arr, k):
"""
Given an array arr of integers and a positive integer k, return a sorted list
of length k with the maximum k numbers in arr.
Example 1:
Input: arr = [-3, -4, 5], k = 3
Output: [-4, -3, 5]
Example 2:
Input: arr =... | entry_point = 'maximum'
def maximum(arr, k):
"""
Given an array arr of integers and a positive integer k, return a sorted list
of length k with the maximum k numbers in arr.
Example 1:
Input: arr = [-3, -4, 5], k = 3
Output: [-4, -3, 5]
Example 2:
Input: arr = [4, -4, 4... |
class WeightedFalseNegativeLossMetric:
def map(self, predicted, actual, weight, offset, model):
cost_tp = 5000 # set prior to use
cost_tn = 0 # do not change
cost_fp = cost_tp # do not change
cost_fn = weight # do not change
y = actual[0]
p = predicted[2] # [clas... | class Weightedfalsenegativelossmetric:
def map(self, predicted, actual, weight, offset, model):
cost_tp = 5000
cost_tn = 0
cost_fp = cost_tp
cost_fn = weight
y = actual[0]
p = predicted[2]
if y == 1:
denom = cost_fn
else:
denom... |
# refer from:
# https://leetcode.com/problems/flatten-binary-tree-to-linked-list/solution/
# 2. Iterative Morris traversal
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
# Handle the null scena... | class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if not root:
return None
node = root
while node:
if node.left:
rightmost = node.left
while... |
""" Grading """
def gradingStudents(grades):
result = []
for rec in grades:
if rec < 38:
result.append(rec)
else:
reminder = rec % 5
quotient = rec // 5
result.append(5*(quotient+1) if reminder > 2 else rec)
return result
if __name__ == "_... | """ Grading """
def grading_students(grades):
result = []
for rec in grades:
if rec < 38:
result.append(rec)
else:
reminder = rec % 5
quotient = rec // 5
result.append(5 * (quotient + 1) if reminder > 2 else rec)
return result
if __name__ == '... |
# PROBLEM LINK:- https://leetcode.com/problems/reach-a-number/
class Solution:
def reachNumber(self, target: int) -> int:
target = abs(target)
res = 0
sum = 0
while sum < target or (sum - target)%2 != 0:
res += 1
sum += res
return res
| class Solution:
def reach_number(self, target: int) -> int:
target = abs(target)
res = 0
sum = 0
while sum < target or (sum - target) % 2 != 0:
res += 1
sum += res
return res |
def sanitize_supply_cost(a, cost, name):
if cost is None:
cost = a.default_cost
if len(a.cost_names) > 1:
a.log.info("Using default cost, {}, for {}.".format(cost, name))
if cost not in a.cost_names:
raise ValueError("{} not an available cost.".format(cost))
return c... | def sanitize_supply_cost(a, cost, name):
if cost is None:
cost = a.default_cost
if len(a.cost_names) > 1:
a.log.info('Using default cost, {}, for {}.'.format(cost, name))
if cost not in a.cost_names:
raise value_error('{} not an available cost.'.format(cost))
return cost
... |
# Copyright (c) 2011-2020, Manfred Moitzi
# License: MIT License
class Options:
def __init__(self):
self.filter_invalid_xdata_group_codes = False
self.default_text_style = 'OpenSans'
self.default_dimension_text_style = 'OpenSansCondensed-Light'
# debugging
self.log_unproce... | class Options:
def __init__(self):
self.filter_invalid_xdata_group_codes = False
self.default_text_style = 'OpenSans'
self.default_dimension_text_style = 'OpenSansCondensed-Light'
self.log_unprocessed_tags = True
self.load_proxy_graphics = False
self.store_proxy_grap... |
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for c in s:
if c in ('(', '[', '{'):
stack.append(c)
else:
if not stack:
return False
... | class Solution(object):
def is_valid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for c in s:
if c in ('(', '[', '{'):
stack.append(c)
else:
if not stack:
return False
... |
class Solution:
def longestPalindrome(self, s):
slen = len(s)
longest = ''
longest_len = 0
for i in range(1, slen-1):
loops+=1
l, r = i-1, i+1
subs = s[i]
while l >= 0 and r < slen:
if s[l] != s[r]:
... | class Solution:
def longest_palindrome(self, s):
slen = len(s)
longest = ''
longest_len = 0
for i in range(1, slen - 1):
loops += 1
(l, r) = (i - 1, i + 1)
subs = s[i]
while l >= 0 and r < slen:
if s[l] != s[r]:
... |
class TrieNode:
def __init__(self):
self.children = {}
self.word = None
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
root = TrieNode()
r, c = len(board), len(board[0])
for w in words:
cur = root
for ... | class Trienode:
def __init__(self):
self.children = {}
self.word = None
class Solution:
def find_words(self, board: List[List[str]], words: List[str]) -> List[str]:
root = trie_node()
(r, c) = (len(board), len(board[0]))
for w in words:
cur = root
... |
#
# PySNMP MIB module Unisphere-Data-DVMRP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-DVMRP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:23:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, constraints_intersection, value_range_constraint, single_value_constraint) ... |
def longestRepeatedSubSeq(str):
n = len(str)
dp = [[0 for i in range(n + 1)] for j in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, n + 1):
if (str[i - 1] == str[j - 1] and i != j):
dp[i][j] = 1 + dp[i - 1][j - 1]
else:
dp[i][j] = ... | def longest_repeated_sub_seq(str):
n = len(str)
dp = [[0 for i in range(n + 1)] for j in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, n + 1):
if str[i - 1] == str[j - 1] and i != j:
dp[i][j] = 1 + dp[i - 1][j - 1]
else:
dp[i][j] = ... |
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
if not grid or not grid[0]:
return 0
result = 0
def dfs(x, y):
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
count = 1
for k in range(4):
nx, ny = dx[k... | class Solution:
def max_area_of_island(self, grid: List[List[int]]) -> int:
if not grid or not grid[0]:
return 0
result = 0
def dfs(x, y):
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
count = 1
for k in range(4):
(nx, ny)... |
"""
A trie (pronounced as 'try') or prefix tree is a tree data structure used to efficiently store and retrieve keys in a
dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
- Trie() Initializes the trie object.
- void insert(String... | """
A trie (pronounced as 'try') or prefix tree is a tree data structure used to efficiently store and retrieve keys in a
dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
- Trie() Initializes the trie object.
- void insert(String... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.