content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
TOKEN = "1807234388:AAHbvU9Crr6BURnLMwT8m4hrneGgxGvbm8A"
pochta_api_login = "YadBdduZvCLDvZ"
pochta_api_password = "oAD8k3MpRHq5" | token = '1807234388:AAHbvU9Crr6BURnLMwT8m4hrneGgxGvbm8A'
pochta_api_login = 'YadBdduZvCLDvZ'
pochta_api_password = 'oAD8k3MpRHq5' |
def escape(text):
return text.replace('\\', '\\\\').replace('"', '\\"')
opposites = {
'north': 'south',
'east': 'west',
'south': 'north',
'west': 'east'
}
class Rel:
def __init__(self, offset=0):
self.offset = offset
def __add__(self, other):
return Rel(self.offset + othe... | def escape(text):
return text.replace('\\', '\\\\').replace('"', '\\"')
opposites = {'north': 'south', 'east': 'west', 'south': 'north', 'west': 'east'}
class Rel:
def __init__(self, offset=0):
self.offset = offset
def __add__(self, other):
return rel(self.offset + other)
def __sub__... |
# /General
# api: Allows return the results in json.
# db_name_f: Name of data base file.
api_return = True
db_name_f = 'data.db'
# /APIs
# Enables or disables the API.
situacaoIntelx = False
situacaoHaveIPwned = False
situacaoScylla = True
# /Notification E-mail account
# id_f3: E-mail.
# id_f4: Password.
id_f3 = 'E... | api_return = True
db_name_f = 'data.db'
situacao_intelx = False
situacao_have_i_pwned = False
situacao_scylla = True
id_f3 = 'EMAIL'
id_f4 = 'PASS' |
#Write a Python program to print without newline or space.
print("The Lord is good.", end="")
print("All the time")
| print('The Lord is good.', end='')
print('All the time') |
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
length = len(nums)
hashmap = {}
for i in range(length):
if target - nums[i] in hashmap:
return [hash... | class Solution(object):
def two_sum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
length = len(nums)
hashmap = {}
for i in range(length):
if target - nums[i] in hashmap:
return [hash... |
#!/usr/bin/env python
"""Tools to updates list of data."""
def update_month_index(entries, updated_entry):
"""Update the Monthly index of blog posts.
Take a dictionaries and adjust its values
by inserting at the right place.
"""
new_uri = list(updated_entry)[0]
try:
entries[new_uri]['... | """Tools to updates list of data."""
def update_month_index(entries, updated_entry):
"""Update the Monthly index of blog posts.
Take a dictionaries and adjust its values
by inserting at the right place.
"""
new_uri = list(updated_entry)[0]
try:
entries[new_uri]['updated'] = updated_ent... |
#!/usr/bin/env python3
# https://www.hackerrank.com/challenges/py-if-else
if __name__ == '__main__':
n = int(input())
r = n % 2
if r == 0:
if n > 20 or (n >= 2 and n <= 5):
print ("Not Weird")
elif n >= 6 and n <= 20:
print ("Weird")
else:
print ("Weird"... | if __name__ == '__main__':
n = int(input())
r = n % 2
if r == 0:
if n > 20 or (n >= 2 and n <= 5):
print('Not Weird')
elif n >= 6 and n <= 20:
print('Weird')
else:
print('Weird') |
### Written by Jason-Silla ###
### https://github.com/Jason-Silla/JohnAI ###
class Fraction:
numerator = 1
denominatior = 1
def __init__(self, *info):
if len(info) == 2:
self.numerator = numerator
self.denominator = denominator
elif len(info) == 0:
pass
... | class Fraction:
numerator = 1
denominatior = 1
def __init__(self, *info):
if len(info) == 2:
self.numerator = numerator
self.denominator = denominator
elif len(info) == 0:
pass
else:
raise ValueError
def simplify(self):
nu... |
def resolve():
n, m, l = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]
b = [list(map(int, input().split())) for i in range(m)]
c = []
for i in range(n):
tmp = []
for j in range(l):
x = 0
for k in range(m):
... | def resolve():
(n, m, l) = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]
b = [list(map(int, input().split())) for i in range(m)]
c = []
for i in range(n):
tmp = []
for j in range(l):
x = 0
for k in range(m):
... |
# -*- coding: utf-8 -*-
'''
Sort and save unique values to a new file. Ignore rows that do not have a value.
Sample values in a file might look like this
02/02/2018 23:15:12, 1234567889
02/02/2018 23:15:13, 1234568889
02/02/2018 23:15:18, 1234568889
02/02/2018 23:15:19,
02/02/2018 23:15:25, 1234545889
02/02/2018 23:1... | """
Sort and save unique values to a new file. Ignore rows that do not have a value.
Sample values in a file might look like this
02/02/2018 23:15:12, 1234567889
02/02/2018 23:15:13, 1234568889
02/02/2018 23:15:18, 1234568889
02/02/2018 23:15:19,
02/02/2018 23:15:25, 1234545889
02/02/2018 23:17:12, 1234512889
02/02/2... |
__author__ = 'Tony Beltramelli - www.tonybeltramelli.com'
CONTEXT_LENGTH = 64
IMAGE_SIZE = 256
BATCH_SIZE = 64
EPOCHS = 10
STEPS_PER_EPOCH = 72000
IMG_DATA_TYPE = ".jpg"
| __author__ = 'Tony Beltramelli - www.tonybeltramelli.com'
context_length = 64
image_size = 256
batch_size = 64
epochs = 10
steps_per_epoch = 72000
img_data_type = '.jpg' |
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
l = list()
for x in range(1, n + 1):
if x % 3 == 0 and x % 5 == 0:
l.append('FizzBuzz')
elif x % 3 == 0:
l.append('Fizz')
elif x % 5 == 0:
l.append('B... | class Solution:
def fizz_buzz(self, n: int) -> List[str]:
l = list()
for x in range(1, n + 1):
if x % 3 == 0 and x % 5 == 0:
l.append('FizzBuzz')
elif x % 3 == 0:
l.append('Fizz')
elif x % 5 == 0:
l.append('Buzz')
... |
class Label:
def __init__(self, name):
self.name = name
class LabelAccess:
def __init__(self, name, lower_byte):
self.name = name
self.lower_byte = lower_byte
def high(name):
return LabelAccess(name, False)
def low(name):
return LabelAccess(name, True) | class Label:
def __init__(self, name):
self.name = name
class Labelaccess:
def __init__(self, name, lower_byte):
self.name = name
self.lower_byte = lower_byte
def high(name):
return label_access(name, False)
def low(name):
return label_access(name, True) |
widths = {'Alpha': 722,
'Beta': 667,
'Chi': 722,
'Delta': 612,
'Epsilon': 611,
'Eta': 722,
'Euro': 750,
'Gamma': 603,
'Ifraktur': 686,
'Iota': 333,
'Kappa': 722,
'Lambda': 686,
'Mu': 889,
'Nu': 722,
'Omega': 768,
'Omicron': 722,
'Phi': 763,
'Pi': 768,
'Psi': 795,
'Rfraktur': 795,
... | widths = {'Alpha': 722, 'Beta': 667, 'Chi': 722, 'Delta': 612, 'Epsilon': 611, 'Eta': 722, 'Euro': 750, 'Gamma': 603, 'Ifraktur': 686, 'Iota': 333, 'Kappa': 722, 'Lambda': 686, 'Mu': 889, 'Nu': 722, 'Omega': 768, 'Omicron': 722, 'Phi': 763, 'Pi': 768, 'Psi': 795, 'Rfraktur': 795, 'Rho': 556, 'Sigma': 592, 'Tau': 611, '... |
def dfNoHdr(df):
# INPUT: df with a header
# OUTPUT: dfNH without a header
dict={}
for column in df.columns:
dict[column] = df.columns.get_loc(column)
df.rename(columns = dict, inplace = True)
return df | def df_no_hdr(df):
dict = {}
for column in df.columns:
dict[column] = df.columns.get_loc(column)
df.rename(columns=dict, inplace=True)
return df |
# Write a python function which accepts a linked list of whole numbers,
# moves the last element of the linked list to front and returns the linked list.
# Sample Input Expected Output
# 9->3->56->6->2->7->4 4->9->3->56->6->2->7
#DSA-Prac-1
class Node:
def __init__(self, data):
self.__data = data
... | class Node:
def __init__(self, data):
self.__data = data
self.__next = None
def get_data(self):
return self.__data
def set_data(self, data):
self.__data = data
def get_next(self):
return self.__next
def set_next(self, next_node):
self.__next = nex... |
NEW_AIRTABLE_REQUEST_JSON = {
"Skillsets": "C / C++,Web (Frontend Development),Mobile (iOS),Java,DevOps",
"Slack User": "ic4rusX",
"Details": " Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin blandit porttitor nulla eu consectetur."
" Maecenas consectetur erat at odio iaculis, ... | new_airtable_request_json = {'Skillsets': 'C / C++,Web (Frontend Development),Mobile (iOS),Java,DevOps', 'Slack User': 'ic4rusX', 'Details': ' Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin blandit porttitor nulla eu consectetur. Maecenas consectetur erat at odio iaculis, ac auctor nunc imperdiet. Sed n... |
# -*- coding: utf-8 -*-
#
# Copyright 2014-2021 BigML
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | """Options for BigMLer cluster
"""
def get_cluster_options(defaults=None):
"""Adding arguments for the cluster subcommand
"""
if defaults is None:
defaults = {}
options = {'--cluster-fields': {'action': 'store', 'dest': 'cluster_fields', 'default': defaults.get('cluster_fields', None), 'help'... |
# 1
# 12
# 123
# 1234
# 12345
n = int (input("Enter the number "))
for i in range(1,n+1):
for j in range(1,i+1):
print(j,end="")
print() | n = int(input('Enter the number '))
for i in range(1, n + 1):
for j in range(1, i + 1):
print(j, end='')
print() |
INCREASE: int = 1 # global namespace
DECREASE: int = -1
space = ' '
sign = '* '
def print_rhombus(n: int): # global namespace
# fn-in-fn: closure
def print_line(i: int, direction: int): # local namespace visible in print_rhombus
if i == 0: # i is part of the local namespace of print_line
... | increase: int = 1
decrease: int = -1
space = ' '
sign = '* '
def print_rhombus(n: int):
def print_line(i: int, direction: int):
if i == 0:
return
line = (n - i) * space + i * sign
print(line.rstrip())
if i == n:
direction = DECREASE
print_line(i + di... |
# _________________________________________________________________________
#
# PyUtilib: A Python utility library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the BSD License.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains ... | class Excelspreadsheet_Base(object):
def can_read(self):
return False
def can_write(self):
return False
def can_calculate(self):
return False |
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | """Command line options for meta optimization."""
def setup_args(parser):
parser.add_argument('--metaoptimizer', type=str, default='es')
parser.add_argument('-n', '--num_samples', type=int, default=10000)
parser.add_argument('--worker_mode', type=str, default='cmd')
parser.add_argument('--num_procs', t... |
def method1(n: int) -> int:
if n <= 2:
return []
else:
sieve = [True] * (n + 1)
for x in range(3, int(n ** 0.5) + 1, 2):
for y in range(3, (n // x) + 1, 2):
sieve[(x * y)] = False
return [2] + [i for i in range(3, n, 2) if sieve[i]]
if __name__ == "__mai... | def method1(n: int) -> int:
if n <= 2:
return []
else:
sieve = [True] * (n + 1)
for x in range(3, int(n ** 0.5) + 1, 2):
for y in range(3, n // x + 1, 2):
sieve[x * y] = False
return [2] + [i for i in range(3, n, 2) if sieve[i]]
if __name__ == '__main__':
... |
"""This file contains all defined containers and heat sources as variables.
All variables are strings, so there are no docstrings available.
In case you are wondering, this is the text in the module docstring of /tools/equipments.py .
"""
# containers
pewter_cauldron = 'pewter_cauldron'
copper_cauldron = 'copper_cau... | """This file contains all defined containers and heat sources as variables.
All variables are strings, so there are no docstrings available.
In case you are wondering, this is the text in the module docstring of /tools/equipments.py .
"""
pewter_cauldron = 'pewter_cauldron'
copper_cauldron = 'copper_cauldron'
martini... |
#!/usr/bin/env python3
_ = input()
_v, *v = sorted(map(int, input().split()))
for i in v:
_v = (_v + i) / 2
print(_v) | _ = input()
(_v, *v) = sorted(map(int, input().split()))
for i in v:
_v = (_v + i) / 2
print(_v) |
#
# PySNMP MIB module TRIPPLITE-PRODUCTS (http://pysnmp.sf.net)
# ASN.1 source file://./TRIPPLITE-PRODUCTS.MIB
# Produced by pysmi-0.2.2 at Wed Apr 11 14:12:10 2018
# On host Tim platform Linux version 4.15.15-1-ARCH by user syp
# Using Python version 2.7.13 (default, Oct 26 2017, 17:04:19)
#
Integer, ObjectIdentifier... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) ... |
# Raised when VT-100 can't be enabled
class VT100Error( Exception ):
def __init__( self ):
super().__init__( "Couldn't enable VT-100 terminal emulation" )
| class Vt100Error(Exception):
def __init__(self):
super().__init__("Couldn't enable VT-100 terminal emulation") |
class Solution:
"""
@param pid: the process id
@param ppid: the parent process id
@param kill: a PID you want to kill
@return: a list of PIDs of processes that will be killed in the end
"""
def killProcess(self, pid, ppid, kill):
groupByPPID = {}
index = 0
while inde... | class Solution:
"""
@param pid: the process id
@param ppid: the parent process id
@param kill: a PID you want to kill
@return: a list of PIDs of processes that will be killed in the end
"""
def kill_process(self, pid, ppid, kill):
group_by_ppid = {}
index = 0
while i... |
"""
spiel.data
Module for organizing input data to the SPieL system
"""
class ParseError(ValueError):
""" Raised by bad values for a new instance """
class Instance:
"""
Represents a single end-to-end training instance
"""
def __init__(self, shape, segments, labels):
"""
Initial... | """
spiel.data
Module for organizing input data to the SPieL system
"""
class Parseerror(ValueError):
""" Raised by bad values for a new instance """
class Instance:
"""
Represents a single end-to-end training instance
"""
def __init__(self, shape, segments, labels):
"""
Initiali... |
test1 = 6 # True
test2 = 11 # False
test3 = 25 # True
test4 = 330 # 165 33
dividers = [2, 3, 5]
def is_ugly(n):
result = n
i = 0
while result > 1:
i += 1
print(i)
divided = False
for divisor in (5, 3, 2):
quotent, reminder = divmod(result, divisor)
... | test1 = 6
test2 = 11
test3 = 25
test4 = 330
dividers = [2, 3, 5]
def is_ugly(n):
result = n
i = 0
while result > 1:
i += 1
print(i)
divided = False
for divisor in (5, 3, 2):
(quotent, reminder) = divmod(result, divisor)
if reminder == 0:
... |
# here the assumption is the user will give "n"
# the function has to print all dice rolls possible for "n" dices
def collect_all_dice_rolls(n):
result_set = []
helper(n, [], result_set)
return result_set
def helper(n, roll_set, result_set):
if n == 0:
result_set.append(list(roll_set))
else:
... | def collect_all_dice_rolls(n):
result_set = []
helper(n, [], result_set)
return result_set
def helper(n, roll_set, result_set):
if n == 0:
result_set.append(list(roll_set))
else:
for i in range(1, 7):
roll_set.append(i)
helper(n - 1, roll_set, result_set)
... |
"""
This sub-package holds the Scripts system. Scripts are database
entities that can store data both in connection to Objects and Accounts
or globally. They may also have a timer-component to execute various
timed effects.
"""
| """
This sub-package holds the Scripts system. Scripts are database
entities that can store data both in connection to Objects and Accounts
or globally. They may also have a timer-component to execute various
timed effects.
""" |
SAMPLE_YEAR = 1983
SAMPLE_YEAR_SHORT = 83
SAMPLE_MONTH = 1
SAMPLE_DAY = 2
SAMPLE_HOUR = 15
SAMPLE_UTC_HOUR = 20
SAMPLE_HOUR_12H = 3
SAMPLE_MINUTE = 4
SAMPLE_SECOND = 5
SAMPLE_PERIOD = 'PM'
SAMPLE_OFFSET = '-00'
SAMPLE_LONG_TZ = 'UTC'
def create_sample(template: str) -> str:
return (
template
.repl... | sample_year = 1983
sample_year_short = 83
sample_month = 1
sample_day = 2
sample_hour = 15
sample_utc_hour = 20
sample_hour_12_h = 3
sample_minute = 4
sample_second = 5
sample_period = 'PM'
sample_offset = '-00'
sample_long_tz = 'UTC'
def create_sample(template: str) -> str:
return template.replace('YYYY', str(SAM... |
# https://leetcode.com/problems/largest-triangle-area/submissions/
# Time:26.45% Memory:100%
class Solution(object):
def largest_triangle_area(self, points):
max_area = 0
for i in range(len(points) - 2):
for j in range(i+1, len(points) - 1):
for k in range(j+1, len(point... | class Solution(object):
def largest_triangle_area(self, points):
max_area = 0
for i in range(len(points) - 2):
for j in range(i + 1, len(points) - 1):
for k in range(j + 1, len(points)):
three_points = [points[i], points[j], points[k]]
... |
# -*- coding: utf-8 -*-
BOT_NAME = 'p1_pipeline'
SPIDER_MODULES = ['p1_pipeline.spiders']
NEWSPIDER_MODULE = 'p1_pipeline.spiders'
ROBOTSTXT_OBEY = True
# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'p1_pipeline.pipelines.DropNoTagsPipelin... | bot_name = 'p1_pipeline'
spider_modules = ['p1_pipeline.spiders']
newspider_module = 'p1_pipeline.spiders'
robotstxt_obey = True
item_pipelines = {'p1_pipeline.pipelines.DropNoTagsPipeline': 300} |
# blanyal, hiimbex :)
'''
The goal of binary ssearch is to divide the search space in half every iteration
Binary search also assumes you have a sorted list of integers and goes through every
time and determines if the item you are searching for is greater than or less than your
mid point and jumps to... | """
The goal of binary ssearch is to divide the search space in half every iteration
Binary search also assumes you have a sorted list of integers and goes through every
time and determines if the item you are searching for is greater than or less than your
mid point and jumps to the respective side fr... |
class NoBranchSelected(Exception):
def __init__(self, message: str = ''):
self.message: str = message
def __str__(self):
return """
No git Branch Selected
{0!s}
""".format(self.message)
| class Nobranchselected(Exception):
def __init__(self, message: str=''):
self.message: str = message
def __str__(self):
return '\nNo git Branch Selected\n{0!s}\n'.format(self.message) |
{
"targets" : [
{
"target_name" : "leveled",
"sources" : ["src/leveled.cc", "src/batch.cc"],
"dependencies" : [
"deps/leveldb/binding.gyp:leveldb"
]
}
]
}
| {'targets': [{'target_name': 'leveled', 'sources': ['src/leveled.cc', 'src/batch.cc'], 'dependencies': ['deps/leveldb/binding.gyp:leveldb']}]} |
class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
"""
[1,1,2,2,2] total = 8, k = 4, subset = 2
subproblems:
Can I make 4 subsets with equal sum out of the given numbers?
Find all subsets, starting from 0 .... | class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
"""
[1,1,2,2,2] total = 8, k = 4, subset = 2
subproblems:
Can I make 4 subsets with equal sum out of the given numbers?
Find all subsets, starting from 0 ... |
posts = [
{
"id": 1,
"title": "Pancake",
"content": "Lorem Ipsum ..."
}
]
users = [] | posts = [{'id': 1, 'title': 'Pancake', 'content': 'Lorem Ipsum ...'}]
users = [] |
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
max_area = 0
stack = [] #(index, height)
for i, h in enumerate(heights):
start = i
while stack and stack[-1][1] > h:
index, height = stack.pop()
max_are... | class Solution:
def largest_rectangle_area(self, heights: List[int]) -> int:
max_area = 0
stack = []
for (i, h) in enumerate(heights):
start = i
while stack and stack[-1][1] > h:
(index, height) = stack.pop()
max_area = max(max_area, h... |
#!/usr/bin/python3
# Generators
def genFibonacci():
"""
Fibonacci generator
"""
yield 0
yield 1
cnt = 2
a = 0
b = 1
c = a + b
while cnt < 10:
c = a + b
yield c
a = b
b = c
cnt += 1
def genPrimes():
n = 1000
primes = [True]*(n+1... | def gen_fibonacci():
"""
Fibonacci generator
"""
yield 0
yield 1
cnt = 2
a = 0
b = 1
c = a + b
while cnt < 10:
c = a + b
yield c
a = b
b = c
cnt += 1
def gen_primes():
n = 1000
primes = [True] * (n + 1)
primes[0] = False
pr... |
## @package AssociateJoint Association joint that used by gait recorder
## The class that has all the information about associations
class AssociateJoint:
## Constructor
# @param self Object pointer
# @param module Module name string
# @param node Node index
# @param corr Bool, correaltion: True for positive; Fal... | class Associatejoint:
def __init__(self, module, node, corr, ratio):
self.ModuleName = module
self.Node = node
self.Correlation = corr
self.Ratio = ratio
def to_string(self):
return self.ModuleName + '::' + self.NodeToString(self.Node) + '::' + self.CorrelationToStr(sel... |
class Solution:
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
matrix = [[0 for _ in range(n)] for _ in range(n)]
lvl, c = 0, 1
while lvl <= n//2:
if c <= n*n:
for i in range(lvl, n-lvl):
... | class Solution:
def generate_matrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
matrix = [[0 for _ in range(n)] for _ in range(n)]
(lvl, c) = (0, 1)
while lvl <= n // 2:
if c <= n * n:
for i in range(lvl, n - lvl):
... |
def modify_input_for_multiple_files(hotel, image):
dict = {}
dict['hotel'] = hotel
dict['image'] = image
return dict
def modify_input_for_multiple_room_files(room, image):
dict = {}
dict['room'] = room
dict['image'] = image
return dict
def modify_input_for_multiple_pack... | def modify_input_for_multiple_files(hotel, image):
dict = {}
dict['hotel'] = hotel
dict['image'] = image
return dict
def modify_input_for_multiple_room_files(room, image):
dict = {}
dict['room'] = room
dict['image'] = image
return dict
def modify_input_for_multiple_package_files(packag... |
class Solution:
def judgeCircle(self, moves: str) -> bool:
x = y = 0
for m in moves:
if m == 'R':
x += 1
elif m == 'L':
x -= 1
elif m == 'U':
y -= 1
else:
y += 1
return x == 0 and ... | class Solution:
def judge_circle(self, moves: str) -> bool:
x = y = 0
for m in moves:
if m == 'R':
x += 1
elif m == 'L':
x -= 1
elif m == 'U':
y -= 1
else:
y += 1
return x == 0 an... |
for _ in range(int(input())):
n = int(input())
l = list(map(int, input().split(" ")))
is_true = False
for i in range(1, n):
if l[i] >= l[i-1]:
is_true = True
break
if is_true:
print("YES")
else:
print("NO")
| for _ in range(int(input())):
n = int(input())
l = list(map(int, input().split(' ')))
is_true = False
for i in range(1, n):
if l[i] >= l[i - 1]:
is_true = True
break
if is_true:
print('YES')
else:
print('NO') |
# stops the current iteration in a loop
class MinorException(Exception):
pass
# stops the bot
class CriticalException(Exception):
pass | class Minorexception(Exception):
pass
class Criticalexception(Exception):
pass |
measured_values = [None] * N
for i in range(N):
# Intercept qubits from Alice
qubit = conn.recvQubit()
# Measure all qubits in standard basis
measured_values[i] = qubit.measure(inplace=True)
# Forward qubits to Bob
conn.sendQubit(qubit, "Bob")
| measured_values = [None] * N
for i in range(N):
qubit = conn.recvQubit()
measured_values[i] = qubit.measure(inplace=True)
conn.sendQubit(qubit, 'Bob') |
# Here list comprehension is used
# all() is used to make sure that the list
# goes through all the values of x and y
n = input()
print([x for x in range(2, int(n))
if all(x % y != 0 for y in range(2, int(x**0.5)+1))])
# These lines make sure the program doesn't close
# before you even see the output!
... | n = input()
print([x for x in range(2, int(n)) if all((x % y != 0 for y in range(2, int(x ** 0.5) + 1)))])
print('\n\n\n\n\nA program by Karthikeshwar\n\n')
input('Press enter to exit') |
class IFrameworkInputElement(IInputElement):
""" Declares a namescope contract for framework elements. """
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
Name=property(lambda self... | class Iframeworkinputelement(IInputElement):
""" Declares a namescope contract for framework elements. """
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
name = ... |
names = ["Serena",
"Andrew",
"Bobbie",
"Cason",
"David",
"Farzana",
"Frank",
"Hannah",
"Ida",
"Irene",
"Jim",
"Jose",
"Keith",
"Laura",
"Lucy",
"Meredith",
"Nick",
"Ad... | names = ['Serena', 'Andrew', 'Bobbie', 'Cason', 'David', 'Farzana', 'Frank', 'Hannah', 'Ida', 'Irene', 'Jim', 'Jose', 'Keith', 'Laura', 'Lucy', 'Meredith', 'Nick', 'Ada', 'Yeeling', 'Yan']
pre_nouns = ['an', 'a', 'the', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'much', 'every', 'any... |
params = {
'model_name': 'NCP', # model name
'cluster_generator': "MFM", # or CRP
'maxK': 12, # max number of clusters to generate
# MFM
"poisson_lambda": 3 - 1, # K ~ Pk(k) = Poisson(lambda) + 1
"dirichlet_alpha": 1, # prior for cluster proportions
# CRP
'crp_alpha': .7, # dis... | params = {'model_name': 'NCP', 'cluster_generator': 'MFM', 'maxK': 12, 'poisson_lambda': 3 - 1, 'dirichlet_alpha': 1, 'crp_alpha': 0.7, 'n_timesteps': 32, 'n_channels': 7, 'resnet_blocks': [1, 1, 1, 1], 'resnet_planes': 32, 'Nmin': 200, 'Nmax': 500, 'h_dim': 256, 'g_dim': 512, 'H_dim': 128} |
VCF_CONFIG = {
"load_modules": ["samtools/1.4.1", "bcftools/1.4.1"],
"ref_genome": "/external/malaria_SciRep2018/ref_genomes/Plasmodium_falciparum_3D7.fasta",
"data_directory": "/external/malaria_SciRep2018/R7.3_fastq",
"save_directory": "/processed/variant_call_v1/",
} | vcf_config = {'load_modules': ['samtools/1.4.1', 'bcftools/1.4.1'], 'ref_genome': '/external/malaria_SciRep2018/ref_genomes/Plasmodium_falciparum_3D7.fasta', 'data_directory': '/external/malaria_SciRep2018/R7.3_fastq', 'save_directory': '/processed/variant_call_v1/'} |
# coding:utf-8
"""
Name : config.py
Author : blu
Time : 2022/3/7 16:19
Desc :
"""
Debug = False
filter_host = "http://192.168.9.166:5000"
class DatabaseConfig:
mongo_host = 'XXXX'
mongo_user = 'XXXX'
mongo_pwd = 'XXXXX'
mongo_database = 'XXXX'
| """
Name : config.py
Author : blu
Time : 2022/3/7 16:19
Desc :
"""
debug = False
filter_host = 'http://192.168.9.166:5000'
class Databaseconfig:
mongo_host = 'XXXX'
mongo_user = 'XXXX'
mongo_pwd = 'XXXXX'
mongo_database = 'XXXX' |
"""Import Variants and some misconceptions
# module1.py
import math
is marth in sys.
""" | """Import Variants and some misconceptions
# module1.py
import math
is marth in sys.
""" |
class Config:
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_DB = ''
DATABASE_HOST = ''
DATABASE_PORT = 3306
LOG_FILE = '' | class Config:
database_user = ''
database_password = ''
database_db = ''
database_host = ''
database_port = 3306
log_file = '' |
#
def __init__(self):
super().__init__(abc)
#
| def __init__(self):
super().__init__(abc) |
class Solution:
def findDisappearedNumbers(self, nums: [int]) -> [int]:
return list(set(range(1, len(nums) + 1)) - set(nums))
s = Solution()
print(s.findDisappearedNumbers([1, 1])) | class Solution:
def find_disappeared_numbers(self, nums: [int]) -> [int]:
return list(set(range(1, len(nums) + 1)) - set(nums))
s = solution()
print(s.findDisappearedNumbers([1, 1])) |
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10 001st prime number?
primes = [2]
next = 3
def isPrime(n):
for i in primes:
if n % i == 0:
return False
return True
while (len(primes) < 10001):
if isPrime(next):
primes.append(next)
nex... | primes = [2]
next = 3
def is_prime(n):
for i in primes:
if n % i == 0:
return False
return True
while len(primes) < 10001:
if is_prime(next):
primes.append(next)
next += 2
print(primes[10000]) |
def test_address_on_home_page(app):
address_from_home_page = app.contact.get_contact_list()[0]
address_from_edit_page = app.contact.get_contact_info_from_edit_page(0)
assert address_from_home_page.address == address_from_edit_page.address
| def test_address_on_home_page(app):
address_from_home_page = app.contact.get_contact_list()[0]
address_from_edit_page = app.contact.get_contact_info_from_edit_page(0)
assert address_from_home_page.address == address_from_edit_page.address |
class Dataset(object):
"""An abstract class representing a Dataset.
All other datasets should subclass it. All subclasses should override
``__len__``, that provides the size of the dataset, and ``__getitem__``,
supporting integer indexing in range from 0 to len(self) exclusive.
"""
def __geti... | class Dataset(object):
"""An abstract class representing a Dataset.
All other datasets should subclass it. All subclasses should override
``__len__``, that provides the size of the dataset, and ``__getitem__``,
supporting integer indexing in range from 0 to len(self) exclusive.
"""
def __getit... |
class Error(Exception):
def __init__(self, basemessage="Unspecified Error", message=""):
self.basemessage = basemessage
self.message = message
super().__init__(basemessage, message)
class NotImplementedError(Error):
"""An error to indicate that the requested operation has not yet been ... | class Error(Exception):
def __init__(self, basemessage='Unspecified Error', message=''):
self.basemessage = basemessage
self.message = message
super().__init__(basemessage, message)
class Notimplementederror(Error):
"""An error to indicate that the requested operation has not yet been ... |
x,y=map(int,input().split())
if(x < y):
print('<')
elif(x > y):
print('>')
elif(x==y):
print('==')
| (x, y) = map(int, input().split())
if x < y:
print('<')
elif x > y:
print('>')
elif x == y:
print('==') |
class Settings():
# APP SETTINGS
# ///////////////////////////////////////////////////////////////
ENABLE_CUSTOM_TITLE_BAR = False
MENU_WIDTH = 240
TIME_ANIMATION = 400
# BTNS LEFT AND RIGHT BOX COLORS
BTN_LEFT_BOX_COLOR = "background-color: rgb(44, 49, 58);"
BTN_RIGHT_BOX_COLOR = "back... | class Settings:
enable_custom_title_bar = False
menu_width = 240
time_animation = 400
btn_left_box_color = 'background-color: rgb(44, 49, 58);'
btn_right_box_color = 'background-color: #81A1C1;'
menu_selected_stylesheet = '\n border-left: 30px solid qlineargradient(spread:pad, x1:0.034, y1:0,... |
# This program is free software: you can redistribute it and/or modify it under the
# terms of the Apache License (v2.0) as published by the Apache Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or... | """Initialization for resource-monitor."""
__appname__ = 'monitor'
__version__ = '2.3.1'
__authors__ = 'Geoffrey Lentner'
__contact__ = 'glentner@purdue.edu'
__license__ = 'Apache Software License 2.0'
__website__ = 'https://resource-monitor.readthedocs.io'
__copyright__ = 'Geoffrey Lentner 2019. All rights reserved.'
... |
class MonoidLawTester:
def __init__(self, monoid, value):
self.monoid = monoid
self.value = value
def left_identity_test(self):
monoid = self.monoid(self.value)
assert monoid.concat(monoid.neutral()) == monoid
def right_identity_test(self):
monoid = self.monoid(sel... | class Monoidlawtester:
def __init__(self, monoid, value):
self.monoid = monoid
self.value = value
def left_identity_test(self):
monoid = self.monoid(self.value)
assert monoid.concat(monoid.neutral()) == monoid
def right_identity_test(self):
monoid = self.monoid(sel... |
class Circulo:
pi = 3.14 # variable de clase (sin self), puede ser utilizadas por las instancias
def __init__(self,radio):
self.radio = radio # radio es una variable de instancia
circle1 = Circulo(10)
circle2 = Circulo(20)
print(circle1.radio)
circle2.radio = 100
print(circle2.radio)
# uso de la va... | class Circulo:
pi = 3.14
def __init__(self, radio):
self.radio = radio
circle1 = circulo(10)
circle2 = circulo(20)
print(circle1.radio)
circle2.radio = 100
print(circle2.radio)
print(Circulo.pi) |
# -*- coding:utf-8 -*-
class Type:
id = ''
word_id = ''
name = ''
meanings = []
def desc(self):
name = self.name if self.name is not None else ''
return '(\'' + self.word_id + '\', \'' + name + '\')'
| class Type:
id = ''
word_id = ''
name = ''
meanings = []
def desc(self):
name = self.name if self.name is not None else ''
return "('" + self.word_id + "', '" + name + "')" |
##Clock in pt2thon##
t1 = input("Init schedule : ") # first schedule
HH1 = int(t1[0] + t1[1])
MM1 = int(t1[3] + t1[4])
SS1 = int(t1[6] + t1[7])
t2 = input("Final schedule : ") # second schedule
HH2 = int(t2[0] + t2[1])
MM2 = int(t2[3] + t2[4])
SS2 = int(t2[6] + t2[7])
tt1 = (HH1 * 3600) + (MM1 * 60) + SS1 # total... | t1 = input('Init schedule : ')
hh1 = int(t1[0] + t1[1])
mm1 = int(t1[3] + t1[4])
ss1 = int(t1[6] + t1[7])
t2 = input('Final schedule : ')
hh2 = int(t2[0] + t2[1])
mm2 = int(t2[3] + t2[4])
ss2 = int(t2[6] + t2[7])
tt1 = HH1 * 3600 + MM1 * 60 + SS1
tt2 = HH2 * 3600 + MM2 * 60 + SS2
tt3 = tt2 - tt1
if tt3 < 0:
a = 864... |
# PySNMP SMI module. Autogenerated from smidump -f python IANA-MAU-MIB
# by libsmi2pysnmp-0.1.3 at Thu May 22 11:57:41 2014,
# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
# Imports
( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", ... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, single_value_constraint, value_range_constraint, value_size_constraint) ... |
# name: Exes and Ohs
# url: https://www.codewars.com/kata/55908aad6620c066bc00002a
# Check to see if a string has the same amount of 'x's and 'o's. The method
# must return a boolean and be case insensitive. The string can contain any char.
def xo(s):
lowerStr = s.lower()
return lowerStr.count('o') == lowerStr.... | def xo(s):
lower_str = s.lower()
return lowerStr.count('o') == lowerStr.count('x')
if __name__ == '__main__':
print(xo('ooxx'))
print(xo('xooxx'))
print(xo('ooxXm'))
print(xo('zpzpzpp'))
print(xo('zzoo')) |
BASE_URL = "https://paper-api.alpaca.markets"
KEY = "your key here"
SECRET_KEY = "your secret key here"
HEADERS = {"APCA-API-KEY-ID": KEY, "APCA-API-SECRET-KEY": SECRET_KEY}
# headers are used to authenticate our request | base_url = 'https://paper-api.alpaca.markets'
key = 'your key here'
secret_key = 'your secret key here'
headers = {'APCA-API-KEY-ID': KEY, 'APCA-API-SECRET-KEY': SECRET_KEY} |
# coding: utf-8
# Copyright 2014 jeoliva author. All rights reserved.
# Use of this source code is governed by a MIT License
# license that can be found in the LICENSE file.
class RangedUri(object):
def __init__(self):
self.start = 0
self.length = -1
self.baseUri = ""
self.referenc... | class Rangeduri(object):
def __init__(self):
self.start = 0
self.length = -1
self.baseUri = ''
self.referenceUri = '' |
class Solution:
def wordPatternV1(self, pattern: str, str: str) -> bool:
p2s, s2p, words = {}, {}, str.split()
if len(pattern) != len(words):
return False
for p, s in zip(pattern, words):
if p in p2s and p2s[p] != s:
return False
else:
... | class Solution:
def word_pattern_v1(self, pattern: str, str: str) -> bool:
(p2s, s2p, words) = ({}, {}, str.split())
if len(pattern) != len(words):
return False
for (p, s) in zip(pattern, words):
if p in p2s and p2s[p] != s:
return False
e... |
#-------------------------------------------------------------------------------
# Name: powerlaw.py
# Purpose: This is a set of power law coefficients(a,b) for the calculation of
# empirical rain attenuation model A = a*R^b.
#-------------------------------------------------------------------------------
... | def get_coef_ab(freq, mod_type='MP'):
"""
Returns power law coefficients according to model type (mod_type)
at a given frequency[Hz].
Input:
freq - frequency, [Hz].
Optional:
mod_type - model type for power law. This can be 'ITU_R2005',
'MP','GAMMA'. By default, mo... |
def isPalindrome(x):
#x = x.casefold()
rev_str = reversed(x)
if list(x) == list(rev_str):
print("It is palindrome")
return True
else:
print("It is not palindrome")
return False
isPalindrome("SSAASS") | def is_palindrome(x):
rev_str = reversed(x)
if list(x) == list(rev_str):
print('It is palindrome')
return True
else:
print('It is not palindrome')
return False
is_palindrome('SSAASS') |
'''Application Data (bpy.app)
This module contains application values that remain unchanged during runtime.
'''
debug = None
'''Boolean, for debug info (started with --debug / --debug_* matching this attribute name)
'''
debug_events = None
'''Boolean, for debug info (started with --debug / -... | """Application Data (bpy.app)
This module contains application values that remain unchanged during runtime.
"""
debug = None
'Boolean, for debug info (started with --debug / --debug_* matching this attribute name)\n \n'
debug_events = None
'Boolean, for debug info (started with --debug / --debug_* matching thi... |
##############################################
# parameters than can be defined by the user #
##############################################
# parameters modifying the behaviour of the network
global weight_multiplicator # multiplicator of a returned observation, allow to scale observations in ... | global weight_multiplicator
weight_multiplicator = 0.25
global victory_reward
victory_reward = 0
global defeat_punishment
defeat_punishment = 1
global network_param
network_param = [4]
network_type = 'mlp'
max_score = 200
nb_seq = 1000
nb_simulation = 10
save_frequency = 100
gamma = 0.6
hyperopt = 0
pro_level_exists = ... |
# -*- coding: utf-8 -*-
name = 'nuke_ML_server'
version = '0.1.3'
build_requires = [
'cmake-3.10+'
]
variants = [
['platform-linux', 'arch-x86_64', 'nuke-12.2']
]
def commands():
env.NUKE_PATH.append('{root}/lib')
env.LDD_LIBRARY_PATH.append(env.NUKE_LOCATION)
| name = 'nuke_ML_server'
version = '0.1.3'
build_requires = ['cmake-3.10+']
variants = [['platform-linux', 'arch-x86_64', 'nuke-12.2']]
def commands():
env.NUKE_PATH.append('{root}/lib')
env.LDD_LIBRARY_PATH.append(env.NUKE_LOCATION) |
input()
x = list(map(int, input().split()))
N = len(x)
for i in range(0, N - 1):
for j in range(0, N - i - 1):
if x[j] > x[j + 1]:
x[j], x[j + 1] = x[j + 1], x[j]
print(' '.join(map(str, x)))
| input()
x = list(map(int, input().split()))
n = len(x)
for i in range(0, N - 1):
for j in range(0, N - i - 1):
if x[j] > x[j + 1]:
(x[j], x[j + 1]) = (x[j + 1], x[j])
print(' '.join(map(str, x))) |
class Solution:
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
output = list(s)
output = output[::-1]
output = "".join(output)
return output
| class Solution:
def reverse_string(self, s):
"""
:type s: str
:rtype: str
"""
output = list(s)
output = output[::-1]
output = ''.join(output)
return output |
# author: Bilal El Uneis
# since: April 2018
# bilaleluneis@gmail.com
class Methods:
number_of_instances = 0 # this is a class level property
# initializer with default values (constructor)
def __init__(self, method_name="anonymous", method_return_type="void"):
self.method_name = method_name
... | class Methods:
number_of_instances = 0
def __init__(self, method_name='anonymous', method_return_type='void'):
self.method_name = method_name
self.method_return_type = method_return_type
type(self).number_of_instances += 1
def __del__(self):
type(self).number_of_instances -... |
n = int(input())
a = list(map(int, input().split()))
total = sum(a)
if total % n != 0:
print(-1)
exit()
num = total // n
ans = 0
for i in range(n - 1):
left = sum(a[:i + 1])
right = sum(a[i + 1:])
if left < num * (i + 1) or right < num * (n - i - 1):
ans += 1
print(ans)
| n = int(input())
a = list(map(int, input().split()))
total = sum(a)
if total % n != 0:
print(-1)
exit()
num = total // n
ans = 0
for i in range(n - 1):
left = sum(a[:i + 1])
right = sum(a[i + 1:])
if left < num * (i + 1) or right < num * (n - i - 1):
ans += 1
print(ans) |
#encoding:utf-8
subreddit = 'KamenRider'
t_channel = '@r_KamenRider'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| subreddit = 'KamenRider'
t_channel = '@r_KamenRider'
def send_post(submission, r2t):
return r2t.send_simple(submission) |
"""Python implementation of Binary Search Tree."""
class BST(): # pragma: no cover
"""Binary Search Tree."""
def __init__(self):
"""Initialize Binary Search tree."""
self._root = None
self._length = 0
self._rdepth = 0
self._ldepth = 0
self._depth = 0
s... | """Python implementation of Binary Search Tree."""
class Bst:
"""Binary Search Tree."""
def __init__(self):
"""Initialize Binary Search tree."""
self._root = None
self._length = 0
self._rdepth = 0
self._ldepth = 0
self._depth = 0
self._balance = 0
d... |
t = int(input())
tests = []
def fact(n):
if n == 1:
return n
else:
return n * fact(n - 1)
while t > 0:
n = int(input())
tests.append(fact(n))
t -= 1
for x in tests:
print(x % 10) | t = int(input())
tests = []
def fact(n):
if n == 1:
return n
else:
return n * fact(n - 1)
while t > 0:
n = int(input())
tests.append(fact(n))
t -= 1
for x in tests:
print(x % 10) |
class Distribution:
def __init__(self, mu=0, sigma=1):
""" Genertic distribution class for calculating and visualizing
a probability disttribution.
Attributes:
mean (float) representing the mean value of the distribution.
stdev (float) represent... | class Distribution:
def __init__(self, mu=0, sigma=1):
""" Genertic distribution class for calculating and visualizing
a probability disttribution.
Attributes:
mean (float) representing the mean value of the distribution.
stdev (float) representing the stand... |
#!/usr/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Authors:
# - Paul Nilsson, paul.nilsson@cern.ch, 2018-2021
def allow_mem... | def allow_memory_usage_verifications():
"""
Should memory usage verifications be performed?
:return: boolean.
"""
return False
def memory_usage(job):
"""
Perform memory usage verification.
:param job: job object
:return: exit code (int), diagnostics (string).
"""
exit_code... |
# Adapted from byterun test_functions.py test
# Tests returning from a generator
"""This program is self-checking!"""
def gen():
yield 1
return 2
x = gen()
while True:
try:
assert next(x) == 1
except StopIteration as e:
assert e.value == 2
break
| """This program is self-checking!"""
def gen():
yield 1
return 2
x = gen()
while True:
try:
assert next(x) == 1
except StopIteration as e:
assert e.value == 2
break |
"""
Class for holding and accessing a
"Named Entity" for a relation
"""
class NamedEntity:
def __init__(self, entity, doc):
self.entity = entity
"""
Gets the type of entity
this object represents.
"PERSON", "ORG", etc.
"""
@property
def entity_type(self):
return N... | """
Class for holding and accessing a
"Named Entity" for a relation
"""
class Namedentity:
def __init__(self, entity, doc):
self.entity = entity
'\n Gets the type of entity\n this object represents.\n\n "PERSON", "ORG", etc.\n '
@property
def entity_type(self):
return None... |
for _ in range(int(input())):
a,b,q=map(int,input().split())
arr=[]
for i in range(q):
arr+=[list(map(int,input().split()))]
res=0
if a!=b:
for j in range(arr[i][0],arr[i][1]+1):
if (j%a)%b!=(j%b)%a:
res+=1
... | for _ in range(int(input())):
(a, b, q) = map(int, input().split())
arr = []
for i in range(q):
arr += [list(map(int, input().split()))]
res = 0
if a != b:
for j in range(arr[i][0], arr[i][1] + 1):
if j % a % b != j % b % a:
res += 1
... |
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
def isBadVersion(version):
pass
class Solution:
def firstBadVersion(self, n):
left, right = 0, n
while left <= right:
mid = (left + right) // 2
if not isBadVersion(mid):
... | def is_bad_version(version):
pass
class Solution:
def first_bad_version(self, n):
(left, right) = (0, n)
while left <= right:
mid = (left + right) // 2
if not is_bad_version(mid):
left = mid + 1
else:
right = mid - 1
r... |
"""
LC 26
Given an array of sorted numbers,
remove all duplicates from it. You should not use any extra space;
after removing the duplicates in-place return the length of the subarray that has no duplicate in it.
Example 1:
Input: [2, 3, 3, 3, 6, 9, 9]
Output: 4
Explanation: The first four elements after removing th... | """
LC 26
Given an array of sorted numbers,
remove all duplicates from it. You should not use any extra space;
after removing the duplicates in-place return the length of the subarray that has no duplicate in it.
Example 1:
Input: [2, 3, 3, 3, 6, 9, 9]
Output: 4
Explanation: The first four elements after removing th... |
def takeInstInput(S):
degrees = []
inputS = S.split(" ")
inputS = [int(x) for x in inputS]
for i in range(len(inputS)):
degrees.append((inputS[i], i))
return degrees
def takeFileInput(FileName):
fileI = open(FileName, 'r')
inputS = fileI.readline()
degrees = takeInstInput(inputS... | def take_inst_input(S):
degrees = []
input_s = S.split(' ')
input_s = [int(x) for x in inputS]
for i in range(len(inputS)):
degrees.append((inputS[i], i))
return degrees
def take_file_input(FileName):
file_i = open(FileName, 'r')
input_s = fileI.readline()
degrees = take_inst_in... |
"""
Given a N cross M matrix in which each row is sorted, find the overall median of the matrix.
Assume N*M is odd.
For example,
Matrix=
[1, 3, 5]
[2, 6, 9]
[3, 6, 9]
A = [1, 2, 3, 3, 5, 6, 6, 9, 9]
Median is 5. So, we return 5.
"""
def median_matrix(A):
if len(A) == 1:
vec = A[0]
return vec[len(vec)//2]
else:
... | """
Given a N cross M matrix in which each row is sorted, find the overall median of the matrix.
Assume N*M is odd.
For example,
Matrix=
[1, 3, 5]
[2, 6, 9]
[3, 6, 9]
A = [1, 2, 3, 3, 5, 6, 6, 9, 9]
Median is 5. So, we return 5.
"""
def median_matrix(A):
if len(A) == 1:
vec = A[0]
return vec[len(ve... |
"""arbmod.py just a sample module for use with tests."""
def arbmod_attribute():
"""Do nothing."""
pass
| """arbmod.py just a sample module for use with tests."""
def arbmod_attribute():
"""Do nothing."""
pass |
""" The Borg Pattern
Notes:
Originally proposed by Alex Martelli, the Borg Pattern improves upon the classical
Singleton pattern by questioning the point of a Singleton. While a Singleton
design pattern mandates that all objects representing a Singleton must share
the same identity (point to the same instance of a c... | """ The Borg Pattern
Notes:
Originally proposed by Alex Martelli, the Borg Pattern improves upon the classical
Singleton pattern by questioning the point of a Singleton. While a Singleton
design pattern mandates that all objects representing a Singleton must share
the same identity (point to the same instance of a c... |
class Solution:
def intToRoman(self, num: int) -> str:
'''
T: O(1) and S: O(1)
'''
int2rom = {1000:'M',
900:'CM',
500:'D',
400:'CD',
100:'C',
90:'XC',
50:'L',
... | class Solution:
def int_to_roman(self, num: int) -> str:
"""
T: O(1) and S: O(1)
"""
int2rom = {1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 100: 'C', 90: 'XC', 50: 'L', 40: 'XL', 10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I'}
result = ''
for divisor in int2rom:
... |
"""
One way to serialize a binary tree is to use pre-order traversal.
When we encounter a non-null node, we record the node's value.
If it is a null node, we record using a sentinel value such as #.
_9_
/ \
3 2
/ \ / \
4 1 # 6
/ \ / \ / \
# # # # # #
For example, the above binary tree c... | """
One way to serialize a binary tree is to use pre-order traversal.
When we encounter a non-null node, we record the node's value.
If it is a null node, we record using a sentinel value such as #.
_9_
/ 3 2
/ \\ / 4 1 # 6
/ \\ / \\ / # # # # # #
For example, the above binary tree can ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.