content stringlengths 7 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
tubデータを扱うためのクラス。
"""
class Record:
"""
tubデータのrecordファイルの1ファイルをあらわすクラス。
辞書データ化が簡単になる。
"""
# JSONデータとなる定数
USER_THROTTLE = 'user/throttle'
USER_ANGLE = 'user/angle'
CAM_IMAGE_ARRAY = 'cam/image_array'
USER_MODE = 'user/mode'
TIMESTAMP = 'timestamp'
... |
class Solution:
def numDecodings(self, s: str) -> int:
if not s or s[0] == '0': return 0
dp = [1, 1]
for i in range(2, len(s) + 1):
if '10' < s[i - 2: i] <= '26' and s[i - 1] != '0':
dp.append(dp[i - 1] + dp[i - 2])
elif s[i - 2: i] == '10' or s[i - 2:... |
version = "0.1.0" # Application version
class Signal(object):
"""
A "Observer" implementation.
Note: ONLY works with class methods.
Example:
from loremdb.common import Signal
class Observed(object):
def __init__(self):
self.changed = Signal()
... |
print("Welcome to the birthday dictionary. We know the birthdays of:")
birthdays = {"Albert Einstein": "03/14/1879", "Benjamin Franklin": "01/17/1706", "Ada Lovelace": "12/10/1815"}
for person in birthdays:
print(person)
name = input("Who's birthday do you want to look up? ")
if(name in birthdays):
print(... |
JAVA_LANGUAGE_LEVEL = "1.8"
KOTLIN_LANGUAGE_LEVEL = "1.3"
KOTLINC_VERSION = "1.3.41"
KOTLINC_ROOT = "https://github.com/JetBrains/kotlin/releases/download"
KOTLINC_SHA = "c44ab6866895606e408b60934ebe45d4befcbc33ea0e4ea73c4b3b89ad770132"
KOTLIN_RULES_VERSION = "legacy-modded-0_26_1-02"
KOTLIN_RULES_SHA = "245d0bc1511048... |
"Listing of all e2e tests, used to set up their repositories in /WORKSPACE"
ALL_E2E = [
"bazel_managed_deps",
"fine_grained_symlinks",
"jasmine",
"karma",
"karma_stack_trace",
"karma_typescript",
"less",
"node_loader_no_preserve_symlinks",
"node_loader_preserve_symlinks",
"packag... |
# Ian McLoughlin
# A program that displays Fibonacci numbers using people's names.
# Exercise executed by Simona Vasiliauskaite
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
name = "Vasiliauskaite"
first... |
# Copyright (c) 2021 Gerald E. Fux
#
# Licensed under the MIT License
"""
This module just defines what version of example_py_package we are currently
looking at.
"""
__version__ = '0.0.1'
|
[
{
'date': '2018-01-01',
'description': 'Yılbaşı',
'locale': 'tr-TR',
'notes': '',
'region': '',
'type': 'NF'
},
{
'date': '2018-04-23',
'description': 'Ulusal Egemenlik ve Çocuk Bayramı',
'locale': 'tr-TR',
'notes': '',
... |
# Time: O(nlogn)
# Space: O(1)
class Solution(object):
def videoStitching(self, clips, T):
"""
:type clips: List[List[int]]
:type T: int
:rtype: int
"""
if T == 0:
return 0
result = 1
curr_reachable, reachable = 0, 0
clips.sort()
... |
base_api = "https://myanimelist.net/"
#Anime
anime = base_api + "api/animelist/"
search_anime = base_api + "api/anime/search.xml"
add_anime = anime + "add/{}.xml"
update_anime = anime + "update/{}.xml"
delete_anime = anime + "delete/{}.xml"
#Manga
manga = base_api + "api/mangalist/"
search_manga = base_api + "api/ma... |
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "Untitled16.ipynb",
"provenance": [],
"collapsed_sections": [],
"authorship_tag": "ABX9TyOm2YDBa+1KtqbwxKRFb+3Y",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_n... |
BEARER_KEY = "BEARER_KEY"
MECAB_DICT_PATH = "MECAB_DICT_PATH" # MeCabの辞書ファイルへのパス
FONT_PATH = "./font/ヒラギノ角ゴシック W3.ttc" # WordCloud用のフォントファイルへのパス
TWEET_COUNT = 5 # * 100
|
#WAP to accept the following data in a dictionary:
#Item_Name, CP, SP
#Displaying
#Item_Name, Profit or Loss
#The program should continue as long as the user wishes to.
itemInt = int(input("Enter number of items to be stored: "))
x = "y"
shopping = dict()
while x == "y" or x == "Y":
Item_name = input("Enter... |
class Group(object):
def __init__(self, _name):
self.name = _name
self.groups = []
self.users = []
def add_group(self, group):
self.groups.append(group)
def add_user(self, user):
self.users.append(user)
def get_groups(self):
return self.groups
def ... |
#carriers [ x ]
# substrates [ x ]
guanine_mods = {'G_to_m7G' : {'name' : '7-methylguanosine', 'input' : 'G', 'output' : 'm7G',
'machines' : {'RlmL_dim' : {'proteins' : {'b0948' : 'RlmKL'},
'RNA_position_substrates' :{'rRNA' : {2... |
doc = dict(
__class__="""Performs k-means clustering on an H2O dataset.""",
)
examples = dict(
categorical_encoding="""
>>> prostate = h2o.import_file("http://s3.amazonaws.com/h2o-public-test-data/smalldata/prostate/prostate.csv")
>>> predictors = ["AGE", "RACE", "DPROS", "DCAPS", "PSA", "VOL", "GLEASON"]
>>> ... |
list1=[]
limit=int(input('Enter the size of list'))
for i in range(1,limit+1,1):
items=input('Enter the items of list:')
list1.append(items)
for i in list1:
print(i)
del list1[0]
print(list1)
|
class Sudoku:
"""
Predstavlja mrežo za posamezen sudoku
"""
def __init__(self, mreza):
self.mreza = mreza
self.velikost = len(self.mreza)
self.mala_velikost = round(self.velikost ** 0.5)
def lep_izpis(self):
"""
Vrne niz, ki vsebuje lepo izpisan sudoku
... |
def get_me():
print('hi')
if __name__ == '__main__':
# This is executed you run via terminal
print('Running other_module.py...')
|
options = {0 : "zero",
1 : "sqr",
4 : "sqr",
9 : "sqr",
2 : "even",
3 : "prime",
5 : "prime",
7 : "prime",
}
def zero():
print ("You typed zero.\n")
def sqr():
print ("n is a perfect square\n")
def... |
def escreva(msg):
tam = len(msg) + 4
print('~' * tam)
print(f' {msg}')
print('~' * tam)
escreva('João Emanuel')
escreva('oi')
escreva('Massa')
|
"""
TESTS:
Test consistency between modular forms and modular symbols Eisenstein
series charpolys, which are computed in completely separate ways. ::
sage: for N in range(25,33):
....: m = ModularForms(N)
....: e = m.eisenstein_subspace()
....: f = e.hecke_polynomial(2)
....: g = Modul... |
model_imp = DecisionTreeClassifier(random_state=22)
model_imp.fit(X_Smote_train,Y_Smote_train)
importance = model_imp.feature_importances_
for i,v in enumerate(importance):
print('Feature: %0d, Score: %.5f' % (i,v))
plt.bar([x for x in range(len(importance))], importance)
plt.show()
np.where(importance>0.015)
X_Smote... |
class Solution:
"""
Level0: []
level1: [1] [2] [3]
level2: [1,2] [1,3] [2,1] [2,3] [3,1] [3,2]
level3: [1,2,3] [1,3,2] [2,1,3][2,3,1] [3,1,2][3,2,1]
"""
def permute(self, nums: List[int]) -> List[List[int]]:
visit... |
n1 = int
n2 = int
n3 = int
n4 = int
n5 = int
n6 = int
n7 = int
n8 = int
n9 = int
n = int(input("Digite un Numero: "))
n1 = n*1
n2 = n*2
n3 = n*3
n4 = n*4
n5 = n*5
n6 = n*6
n7 = n*7
n8 = n*8
n9 = n*9
n10 = n*10
print ("El calculo Uno es: ", n1)
print ("El calculo dos es: ", n2)
print ("El calculo tres es: "... |
"""
Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
Example:
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
Expl... |
# QUICK SORT
# BEST: O(nlogn) time, O(logn) space
# AVERAGE: O(nlogn) time, O(logn) space
# WORST: O(n^2) time, O(logn) space
def quickSort(array):
# Write your code here.
partition(array, 0, len(array) - 1)
return array
def partition(array, low, high):
if low < high:
print("Inside partition")
pivot =... |
#!/usr/bin/python3
def list_division(my_list_1, my_list_2, list_length):
"divides element by element 2 lists"
i = result = 0
list = []
for i in range(list_length):
try:
result = (my_list_1[i] / my_list_2[i])
except TypeError:
result = 0
print("wrong ty... |
"""
Given an array of values, determine whether a subset of the array adds up to a target
sum.
This problem is NP-Complete. However, it can be solved in pseudo-polynomial time, as
shown below. Pseudo-polynomial means that the complexity is determined by the actual
value of the input (in this case, the target number) a... |
print('How old are you?') #ask the age
my_Age = input() # input age
if int(my_Age) < 18: # age comparision
print('You are not on age')
elif int(my_Age) >= 18:
print('You are on age')
if int(my_Age) >= 100:
print('You are a vampire or maybe inmortal')
if int(my_Age) >= 500:
... |
# https://github.com/tensorflow/tensorflow/issues/2169
# MAX Unpooling in tensorflow
# Solution from fabianbormann:
# Limitations:
# 1. //, argmax run ONLY on GPUs.
def unravel_argmax(argmax, shape):
output_list = []
output_list.append(argmax // (shape[2] * shape[3]))
output_list.append(argmax % (shape[2]... |
primeiroTermo=(int(input('Digite o primeiro termo da P.A.: ')))
razao=(int(input('Digite a razão da P.A.: ')))
decimo=int(primeiroTermo+9*razao)
termo=primeiroTermo
while termo<=decimo:
print(termo, end=' ')
termo=termo+razao |
# -*- coding: utf-8 -*-
"""
Created on Fri May 15 01:20:46 2020
@author: Dilay Ercelik
"""
# Practice
# Given 2 ints, a and b, return their sum.
# However, sums in the range 10..19 inclusive, are forbidden, so in that case just return 20.
# Examples:
## sorta_sum(3, 4) → 7
## sorta_sum(9, 4) → 20... |
#Task No. 02
print('3rd graph')
graph_3 = {7:[11,8],2:[],3:[8,10],11:[2,9,10],5:[11],9:[],8:[9]}
keys_3 = list(graph_3.keys())
##
##for i in range(len(keys_3)):
## temp = graph_3.get(keys_3[i])
## print(str(keys_3[i]) + ' is connected with ' + str(temp) + ' and has degree of ' + str(len(temp)))
for i in graph_3:... |
print('Hello World')
name = input('Please enter your name: ')
print('Welcome', name)
input1 = int(input('Please enter a number: '))
input2 = int(input('Please enter another number: '))
value = input1 + input2
print(f'The result of {input1} + {input2} is', value)
print('The type of the value is', type(value))
input_s... |
class Solution:
def maxProfit(self, prices, fee):
N = len(prices)
if N < 2:
return 0
ans = 0
minimum = prices[0]
for i in range(1, N):
if prices[i] < minimum:
minimum = prices[i]
elif prices[i] > minimum + fee:
... |
medida = float(input('Digite uma distância em metros: '))
km = medida * 0.001
hm = medida * 0.01
dam = medida * 0.1
dm = medida * 10
cm = medida * 100
mm = medida * 1000
print('{:=^50}'.format(' Start '))
print('{:.0f}m equivale a: '.format(medida), end ='\n')
print( '{}km \n{}hm \n{}dam \n{}dm \n{}cm \n{}mm '.... |
ARGUMENT_PROCESS_NAME = 'process_name'
ARGUMENT_FLOW_NAME = 'flow_name'
ARGUMENT_STEP_NAME = 'step_name'
ARGUMENT_TIMEPERIOD = 'timeperiod'
ARGUMENT_START_TIMEPERIOD = 'start_timeperiod'
ARGUMENT_END_TIMEPERIOD = 'end_timeperiod'
ARGUMENT_UNIT_OF_WORK_TYPE = 'unit_of_work_type' # whether the unit_of_work is TYPE_MA... |
class Plot(object):
def __init__(self):
pass
def __call__(self):
pass
|
x = input('Digite algo:')
print('o tipo da variavel é', type(x))
print('é apenas numerico?', x.isnumeric())
print('é apenas alfabetico?', x.isalpha())
print('é apenas maiusculo?', x.isupper())
print('é apenas minusculo?', x.islower())
print('é numerico e alfabetico?', x.isalnum())
print('Só tem espaços?', x.isspace()) |
'''
Erros específicos dos módulos do DadosAbertosBrasil.
'''
class DAB_DataError(TypeError):
'''
Erro gerado quando o usuário insere um valor inválido para a data.
'''
class DAB_LocalidadeError(TypeError):
'''
Erro gerado quando o usuário insere um valor inválido para a localidade.
'''
... |
#
# PySNMP MIB module EQLEXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EQLEXT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:05:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... |
#Open file
file = open('inputs\input4.txt')
data = file.read().split('\n\n')
file.close()
#Clean input
dataClean = []
for x in data:
dataClean.append(x.split()) #Split with no argument splits on whitespace
#Solution 1
reqFields = ['byr','iyr','eyr','hgt','hcl','ecl','pid']
valid = 0
for passport in dataClean:... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
"""
class Math():
def addition(value1, value2):
if not isinstance(value1, int) and not isinstance(value2, int):
return 'Invalid input'
else:
return value1 + value2
def soustraction (val... |
""" focli exceptions """
class FoliException(Exception):
""" Base exception """
def __init__(self, message):
self.message = message
class FoliStopNameException(FoliException):
""" Stop name error """
class FoliServerException(FoliException):
""" Stop name error """
class FoliParseDataErr... |
def get_input(file):
with open(file, 'rt', encoding='utf8') as f:
lines = [line.strip() for line in f]
p1_cars = get_player_cards(lines, 1)
p2_cars = get_player_cards(lines, 2)
return p1_cars, p2_cars
def get_player_cards(lines, player):
start = lines.index(f'Player {player}:') + 1
en... |
__all__ = [
"int_to_bytes",
"bytes_to_int",
"bytes_to_hex",
"hex_to_bytes"
]
def bytes_to_hex(src: bytes, with0x: bool = True, max_length: int = None) -> str:
if max_length is not None:
assert len(src) <= max_length, f"input bytes length is too long ({len(src)} > {max_length})"
res = s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Assignment 3 Binary Search Tree."""
class NullBinaryTreeNode(object):
"""Null object pattern for a BST."""
SINGLETON = None
def __new__(cls):
"""__new__."""
if NullBinaryTreeNode.SINGLETON is not None:
return NullBinaryTreeNod... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 3 11:19:30 2019
@author: DEVANSH JAIN
"""
x=input('Enter first number')
y=input('Second Number')
z=x+y
print(z) |
class Solution:
def longestPalindrome(self, s: str) -> str:
lst = []
for ch in s:
lst.append('#')
lst.append(ch)
lst.append('#')
S = ''.join(lst)
def helper(S):
mx = 0
n = len(S)
P = [0] * n
c = 0
... |
LOG_DIR = "/tmp/mylogdir"
def write_message(filename, message):
try:
path = os.path.join(LOG_DIR, filename)
with open(path, 'a') as writer:
writer.write(message)
except OSError as error:
print('Unable to write log message to {}: {}'.format(path, error))
|
#!/usr/bin/env python3
n1 = int(input("Enter 1st subject degree: "))
n2 = int(input("Enter 2nd subject degree: "))
n3 = int(input("Enter 3rd subject degree: "))
if n1 >= 50 and n2 >= 50 and n3 >= 50:
print("Pass")
else:
print("Fail")
|
class Solution(object):
# O(N^2) solution TLE
# def maxArea(self, height):
# """
# :type height: List[int]
# :rtype: int
# """
# maxcap = 0
# length = len(height)
# for left in range(length - 1):
# for right in range(left + 1, length):
# ... |
# Python3
def bishopAndPawn(bishop, pawn):
getPos = lambda s: ('abcdefgh'.index(s[0]), '12345678'.index(s[1]))
bishopPos = getPos(bishop)
pawnPos = getPos(pawn)
return abs(bishopPos[0] - pawnPos[0]) == abs(bishopPos[1] - pawnPos[1])
|
#30
val_br = float(input("Digite um valor monetário em reais: "))
cot_us = float(input("Digite a cotação atual do dólar: "))
val_us = val_br*cot_us
data_atual = date.today()
print("R${:.2f} = US${:.2f} ({})".format(val_br, val_us, data_atual.strftime("%d/%m/%Y"))) |
"""
Faça um programa que apresente um menu de opções para o cálculo das seguintes operações entre dois números:
- adição (opção 1)
- subtração (opção 2)
- multiplicação (opção 3)
- divisão (opção 4)
- saída (opção 5)
O programa deve possibilitar ao usuário a escolha da operação desejada, a exibição... |
"""
Instructions:
1. Create a class named ReversedString that inherits from StringOperations class
2. Implement the function reverse
3. reverse function should be a one liner function that returns the reverse string to_be_reversed
4. Instantiate the class ReversedString
5. Print to show your function implementation re... |
class Solution:
# @param A : integer
# @param B : integer
# @return an integer
def gcd(self,A, B):
if(B==0):
return A
return self.gcd(B,A%B)
|
class Solution:
# @param A : list of strings
# @return a strings
def longestCommonPrefix(self, A):
A.sort()
minLen = min(len(A[0]), len(A[len(A) - 1]))
prefix = ''
for i in range(minLen):
if A[0][i] == A[len(A) - 1][i]:
prefix += A[0][i]
... |
k = int(input())
q = input()
cut = [0]
topset = set([q[0]])
for i in range(1, len(q)):
if len(cut) == k:
break
if q[i] not in topset:
cut.append(i)
topset.add(q[i])
if len(cut) < k:
print('NO')
else:
print('YES')
for i in range(k-1):
print(q[cut[i]:cut[i+1]])... |
def new():
return {}
def to_map(raw_metadata):
return {tuple(md['breadcrumb']): md['metadata'] for md in raw_metadata}
def to_list(compiled_metadata):
return [{'breadcrumb': k, 'metadata': v} for k, v in compiled_metadata.items()]
def delete(compiled_metadata, breadcrumb, k):
del compiled_metadata[br... |
"""
Escreva um programa que leia a velocidade de um carro
se ele ultrapassar 80km/h mostre a mensagem dizendo que ele foi multado
a multa custa R$ 7,00 por cada km acima do limite
"""
speed = float(input('Qual a velocidade do carro: '))
if speed <= 80:
print('Está dentro do limite!!!')
else:
print('Você foi mul... |
"""Top-level package for ICBC Test to Anki."""
__author__ = """genzj"""
__email__ = 'zj0512@gmail.com'
__version__ = '0.1.0'
|
batch_sizes = [4, 16, 128]
def get_iterations(starting_size, batch_size, compute_budget):
compute_budget_without_starting_size = compute_budget - starting_size
iterations_without_start = compute_budget_without_starting_size // batch_size
if (iterations_without_start) == 0:
raise Exception(f"Compu... |
# noinspection PyUnusedLocal
# skus = unicode string
def checkout(skus):
"""
I am assuming products are sepereted by commas
and their quantity follows as an int sperated with an asterisk
e.g. skus="A*3,B*1"
the server tests will reveal the input string's format after the penalty
I also have no... |
class DebuggerInterface:
def is_debug_mode_enabled(self) -> bool:
"""Determines if debug mode is enabled for the application.
The value is based on the configurations.
Returns
-------
bool
True, if debug mode is enabled.
"""
raise NotImp... |
text = input("Text: ")
letters = 0
for letter in text:
if letter.isalpha():
letters += 1
# Assign words to 1 if user actually typed a word at the start but not a space
words = 1 if (len(text) > 0 and text[0] != ' ') else 0
print(words)
print(letters)
|
class MonteCarlo(object):
def __init__(self, board, **kwargs):
# Takes an instance of a Board and optionally some keyword
# arguments. Initializes the list of game states and the
# statistics tables.
milliseconds = kwargs.get('calculation_ms', 10)
self.calculation_time_ms =... |
print("Welcome to Python")
print("Welcome to Python")
print("Welcome to Python")
print("Welcome to Python")
print("Welcome to Python")
|
def test_win10(helpers):
caps = {}
caps['browserName'] = 'internet explorer'
caps['platform'] = 'Windows 10'
caps['version'] = '11'
driver = helpers.start_driver(caps)
helpers.validate_google(driver)
def test_late_win7(helpers):
caps = {}
caps['browserName'] = 'internet explorer'
c... |
#The provided code stub reads two integers from STDIN, a and b. Add code to print three lines where:
#1.The first line contains the sum of the two numbers.
#2.The second line contains the difference of the two numbers (first - second).
#3.The third line contains the product of the two numbers.
#code
a=int(raw_input())... |
"""
These routines only appear to be used by the peering_speed tests.
"""
def gen_args(name, args):
"""
Called from argify to generate arguments.
"""
usage = [""]
usage += [name + ':']
usage += \
[" {key}: <{usage}> ({default})".format(
key=key, usage=_usage, default=defau... |
def route_allow_all(*args, **kwargs):
return args, kwargs
def route_defarg(reqarg, defarg=1):
return defarg
def route_json_dict(jsondict, dbg=False):
pass
def route_validator(alphanum, filepath, key, novalidation):
"""
put descriptive docstring here
"""
pass
def route... |
class Jugador():
def __init__(self, nombre):
self.nombre = nombre
def __str__(self):
return self.nombre
def elegirTargetsDeLaPartida(self, partida):
"""Recibe el estado del juego, NO LO MODIFICA (dummy/copy/simulacion)
Devuelve todos los turnos a jugar"""
raise NotImplementedError |
#Desafio Simulador de caixa eletronico
# Crie um progama que simule o funcionamento de um caixaeletrônico. No inicio, pergunte ao usuario
# qual será o valor a ser sacado (número inteiro) e o progama vai informar quantas cedulas de cada valor
# serão entregues. OBS: Considere o caixa possui cedulas de R$100,00 / R$50,0... |
"""
Problem Statement
Given arrival and departure times of trains on a single day in a railway platform,
find out the minimum number of platforms required so that no train has to wait for
the other(s) to leave. In other words, when a train is about to arrive, at least
one platform must be available to accommodate i... |
def main():
f = [line.rstrip("\n") for line in open("Data.txt")]
map_ = [list(line) for line in f]
info = []
for i in range(len(map_)):
for j in range(len(map_[0])):
if map_[i][j] == "v":
info.append([i, j, "down", "left"])
map_[i][j] = "|"
... |
def escape_librtmp(value):
if isinstance(value, bool):
value = "1" if value else "0"
if isinstance(value, int):
value = str(value)
# librtmp expects some characters to be escaped
value = value.replace("\\", "\\5c")
value = value.replace(" ", "\\20")
value = value.replace('"', "\... |
coordinates_E0E1E1 = ((125, 114),
(126, 93), (126, 114), (126, 130), (126, 132), (127, 92), (127, 93), (127, 104), (127, 114), (127, 115), (127, 130), (128, 91), (128, 92), (128, 102), (128, 104), (128, 114), (128, 117), (128, 119), (128, 131), (128, 132), (129, 91), (129, 101), (129, 114), (129, 119), (129, 131), (1... |
# Be sure to update these values if you decide to run this bot!
APP_NAME = "Boston Snowbot"
REPO_URL = "https://github.com/molly/snowbot"
# Precipitation probability above which we will add snowfall to prediction
PROBABILITY_THRESHOLD = 0
# Get these values from hitting this URL with your latitude and longitude:
# h... |
# Given two lists of equal sizes, sum all the corresponding index elements and return a new list.
# Lis1 = [1,2,3,4,5] List2=[6,7,8,9,0]
# new list output = [7, 9, 11,13,5]
def sum_index_elements(alist, blist):
new_list = []
for a in range(len(alist)):
new_list.append(alist[a]+blist[a])
return new_list
t... |
# Copyright 2021 Google LLC
#
# 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 agreed to in writing, ... |
class LinearCongruentialGenerator:
mul = 1103515245 # a, 0 < a < m
inc = 12345 # c, 0 <= c < m
mod = 2 ** 31 # m, 0 < m
def __init__(self, seed):
self.seed_ = seed % self.mod # X[0], 0 <= X[0] < m
def rand(self):
# X[n + 1] = (a * X[n] + c) mod m
self.seed_ = (s... |
#Search in a 2D Matrix
class Solution(object):
def searchMatrix(self, matrix, target):
if not len(matrix) or not len(matrix[0]):
return False
m, n = len(matrix) , len(matrix[0])
#Start adaptive search from left bottom corner
x,y = m-1 , 0
... |
"""This problem was asked by Pinterest.
Given a binary tree, write a function to determine whether the tree is a
mirror image of itself.
Two trees are a mirror image if their root values are the same and the
left subtree is a mirror image of the right subtree.
""" |
alphabet = [
"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",
]
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:... |
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
w_size = len(s1)
n = len(s2)
if n<w_size:
return False
rem_counts = collections.defaultdict(int)
for i in range(w_size):
if rem_counts[s1[i]] == -1:
... |
class Product(object):
def __init__(self, name, base_price):
self.name = name
self.base_price = base_price
def get_price(self, item_quantities):
return item_quantities[self.name] * self.base_price
class DiscountedProduct(Product):
def __init__(self, name, base_pric... |
def lengthN(n, cache):
count = 1
while n > 1:
if len(cache) >= n:
count = count + cache[n-1]
break
if n % 2:
n = 3*n + 1
else:
n /= 2
count += 1
cache[int(n)-1] = count
return count, cache
if __name__ == '__main__':
n... |
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
results = []
def Combination(permutation, counter):
if len(permutation) == len(nums):
results.append(list(permutation))
return
for num in counter:
if ... |
#using this for test values for config
class TestConfig:
host = "irc.rizon.net"
port = 6667
nickname = "testNickName8462"
username = "testUserName8462"
hostname = "testHostName8462"
servername = "testServerName8462"
realname = "testRealName8462"
|
# Copyright (C) 2020 The Dagger Authors.
#
# 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 agreed to in w... |
load("@rules_python//python:defs.bzl", "py_test")
load("@bazel_skylib//rules:write_file.bzl", "write_file")
# End to end "Shell" test that a breakpoint can resolve a location
# Consider just allow running a breakpoint without crashing
# It does the following
# 1. Take the (compiled) application and boot up a sim match... |
"""
Tests for qal.common
:copyright: Copyright 2010-2014 by Nicklas Boerjesson
:license: BSD, see LICENSE for details.
"""
|
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
# Add "Jake" to the phonebook with the phone number 938273443, and remove Jill from the phonebook
phonebook["Jake"] = 938273443
del phonebook["Jill"]
# testing code
if "Jake" in phonebook:
print("Jake is listed in the phonebook... |
"""
Given a binary search tree and the lowest and highest boundaries as L and R,
trim the tree so that all its elements lies in [L, R] (R >= L).
You might need to change the root of the tree, so the result should
return the new root of the trimmed binary search tree.
Example 1:
Input:
1
/ \
0 2
L = 1
R... |
#! /usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2019/3/9 2:37 PM
# @Author : xiaoliji
# @Email : yutian9527@gmail.com
class ListNode:
def __init__(self, x: int):
self.val = x
self.next = None
def construct_linklist(nodes: 'iterable')-> 'LinkedList':
vals = list(nodes)
head... |
class Shape:
@staticmethod #define a static method before initiating an instance
def add_ally(x,y):
x.append(y)
return x
def __init__(self, shape_type):
self.shape_type=shape_type
self.__allies=[] #initiate a private empty list in an instance
@property
def allies_public(self): #make it accessibl... |
def vogal(letra):
if(letra=='a') or (letra=='A'):
return True
if (letra=='e') or (letra=='E'):
return True
if (letra=='i') or (letra=='I'):
return True
if (letra=='o') or (letra=='O'):
return True
if (letra=='u') or (letra=='U'):
return True
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.