content stringlengths 7 1.05M |
|---|
#!/usr/bin/python3
# -*- coding: cp949 -*-
def solution(n: int, words: [str]) -> [int]:
ans = [0, 0]
prev = words[0]
history = [words[0]]
pid = 0
turn = 0
for word in words[1:]:
pid = (pid + 1) % n
turn += 1
if prev[-1] != word[0] or word in history:
ans =... |
# color.py
# string is the original string
# type determines the color/label added
# style can be color or text
class color(object):
GREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
def format(self, string, type, style='color'):
formatted_str... |
"""
Construct removes deletes from a list
"""
def filterList(values, filter):
""""
Returns a new list based on the filter.
:param list values:
:param list-of-bool filter: remove from list if ele is True
:return list:
"""
return [x for (x, b) in zip(values, filter) if not b]
|
"""Frequently used constants for tokenization."""
# Special tokens.
PAD = "[PAD]"
OOV = "[OOV]"
START = "[START]"
END = "[END]" |
class Query(object):
def __init__(self, session_id, time_passed, query_id, region_id, documents):
self.query_id = query_id
self.session_id = session_id
self.time_passed = time_passed
self.region_id = region_id
self.documents = documents
def add_documents(self, documents):
self.documents.append(documents)... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def splitListToParts(self, head: ListNode, k: int) -> List[ListNode]:
n = 0
newhead = head
while newhead:
newhead... |
UserStat={
"planned":{
"id":1,
"name":"В планах",
},
"watch":{
"id":2,
"name":"Смотрю",
},
"rewatch":{
"id":4,
"name":"Пересматриваю",
},
"watched": {
"id": 3,
"name": "Просмотрено",
},
"drop": {
"id": 5,
... |
# Sets - A set is an unordered collection of unique and immutable objects.
# Sets are mutable because you add object to it.
# Sample Sets
set_nums = {1, 5, 2, 4, 4, 5}
set_names = {'John', 'Kim', 'Kelly', 'Dora', 'Kim'}
set_cities = set(('Boston', 'Chicago', 'Houston', 'Denver', 'Boston', 'Houston', 'Denver', 'Miami')... |
class WaitBot:
def __init__(self):
self.iteration = 0
self.minute = 0
self.do_something_after = 0
|
vendors = ['johnson', 'siemens', 'tridium']
scripts = [{
}]
def get_vendor(vendor_key):
for name in vendors:
if name in vendor_key.lower():
return name
return ''
|
#
# PySNMP MIB module IEEE8021-AS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IEEE8021-AS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:40:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.push_stack = []
self.pop_stack = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.push_stack.append(x)
def pop(s... |
name = input()
salary = float(input())
cash = float(input())
print("TOTAL = R$ %.2f" % (salary + (cash * 0.15))) |
# This file was automatically generated from "zigZagLevel.ma"
points = {}
boxes = {}
boxes['areaOfInterestBounds'] = (-1.807378035, 3.943412768, -1.61304303) + (0.0, 0.0, 0.0) + (23.01413538, 13.27980464, 10.0098376)
points['ffaSpawn1'] = (-9.523537347, 4.645005984, -3.193868606) + (0.8511546708, 1.0, 1.303629055)
poin... |
class Manager(object):
def setup(self):
return
def update(self):
return
def stop(self):
return |
#Ciclo "while"
#La diferencia semántica es más importante:
# cuando se cumple la condición, "if" realiza sus declaraciones sólo una vez;
# "while" repite la ejecución siempre que la condición se evalúe como "True".
# Almacenaremos el número más grande actual aquí
numeroMayor = -999999999
# Ingresa el primer valor
nume... |
"""
📁 Object Detection Collator
"""
class ObjectDetectionCollator:
def __init__(self, feature_extractor):
self.feature_extractor = feature_extractor
def __call__(self, batch):
# Get all the pixel matrix
pixel_values = [item[0] for item in batch]
# Create a ... |
#py_dict_1.py
mydict={}
mydict['team'] = 'Cubs'
#another way to add elements us via update(). For input, just about
# any iterable that's comprised of 2-element iterables will work.
mydict.update([('town', 'Chicago'), ('rival', 'Cards')])
#we can print it out using the items() method (it returns a tuple)
for ke... |
days = int(input())
type_room = input()
grade = input()
nights = days - 1
if type_room == 'room for one person' and grade == 'positive':
price = nights * 18
price += price * 0.25
print(f'{price:.2f}')
elif type_room == 'room for one person' and grade =='negative':
price = nights * 18
price -= price ... |
'''https://github.com/be-unkind/skyscrapers_ucu'''
def read_input(path: str) -> list:
'''
Read game board file from path.
Return list of str.
'''
result = []
with open(path, 'r') as file:
for line in file:
line = line.replace('\n', '')
result.append(line... |
# print("Hello World")
# print("Done")
print("HelloWorld")
print("Done")
|
# !/usr/bin/env python3
#######################################################################################
# #
# Program purpose: Convert the distance (in feet) to inches, yards, and miles. #
# Program Author : Happi... |
#calcular el numero de vocales de una frase
frase = str(input("Digita la frase: "))
vocales = "aeiouAEIOU"
num = 0
for i in frase:
if i == "a" or i == "e" or i == "i" or i == "o" or i == "u":
num = num + 1
print ("La frase tiene: {} vocales" .format(str(num))) |
mark = float(input('mark on test?'))
if mark >= 50:
print('congratulations you passed')
else:
print('sorry you failed')
|
board_width = 4000
board_height = 1600
screen_width = 800
screen_height = 600
|
# This test verifies that calling locals() does not pollute
# the local namespace of the class with free variables. Old
# versions of Python had a bug, where a free variable being
# passed through a class namespace would be inserted into
# locals() by locals() or exec or a trace function.
#
# The real bug lies in fram... |
"""Exceptions for NSDU-specific errors.
"""
class NSDUError(Exception):
"""NSDU general error.
"""
class ConfigError(NSDUError):
"""NSDU general config error.
"""
class LoaderNotFound(NSDUError):
"""Loader source file not found.
"""
class LoaderError(NSDUError):
"""Error of loader pl... |
# PNG ADDRESS
PNG = "0x60781C2586D68229fde47564546784ab3fACA982"
# PGL PNG/AVAX
LP_PNG_AVAX = "0xd7538cABBf8605BdE1f4901B47B8D42c61DE0367"
# FACTORY ADDRESS
FACTORY = '0xefa94DE7a4656D787667C749f7E1223D71E9FD88'
# STAKING CONTRACTS
# EARN AVAX
STAKING_AVAX = "0xD49B406A7A29D64e081164F6C3353C599A2EeAE9"
# EARN OOE
STAKI... |
#!/usr/bin/env python3
serial_number = 7511
grid_size = 300
power_levels = {}
fuel_cells = {}
def power_level(cell):
return (
((((cell[0] + 10) * cell[1] + serial_number) * (cell[0] + 10)) % 1000) // 100
) - 5
def power_of_cell(cell):
power = 0
for xx in range(3):
for yy in range(3... |
# Literally the same problem as 2020 Day 13, part 2. Here is a better constructed version of that solution.
# Originally, I just brute forced every configuration until I found the right one (i.e a different approach to what I did before)...
# but that ended up being only one line of code less than this, whilst this... |
class ServiceInterface(object):
def __init__(self, **kargs):
pass
def update(self, **kargs):
raise Exception("Not implemented for this class")
def load(self, **kargs):
raise Exception("Not implemented for this class")
def check(self, domain=None, **kargs):
raise Exce... |
# Django settings for cbc_website project.
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'django_esv_tests.db'
INSTALLED_APPS = [
'esv',
'core',
]
TEMPLATE_LOADERS = (
'django.template.loaders.app_directories.load_template_source',
)
|
def fibonnacijeva_stevila(n):
stevila = [1,1]
i = 2
while len(str(stevila[-1])) < n:
stevila.append(stevila[-1] + stevila[-2])
i += 1
return i
print(fibonnacijeva_stevila(1000)) |
class SwaggerParser:
def __init__(self, spec: dict):
self.spec = spec
@property
def operations(self) -> dict:
_operations = {}
for uri, resources in self.spec['paths'].items():
for method, resource in resources.items():
op = SwaggerOperation(method, uri,... |
#
# PySNMP MIB module CPQPOWER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CPQPOWER-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:27:50 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,... |
"""Arguments for pytest"""
def pytest_addoption(parser) -> None: # type: ignore
"""arguments for pytest"""
parser.addoption("--db_type", default="mysql")
# mysql database connection options
parser.addoption("--mysql_user", default="root")
parser.addoption("--mysql_password", default="")
pars... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
# GN version: //components/mime_util/mime_util
'target_name': 'mime_util',
'type': 'static_library',
'dependen... |
# TLE
N = int(input())
sq = int(N ** 0.5)
s = set()
for a in range(2, sq + 1):
x = a * a
while x <= N:
s.add(x)
x *= a
print(N - len(s)) |
# coding=utf-8
# Definición de diccionarios y etiquetas para los contaminantes.
# Esto se define de manera manual para que cada grupo de O3, PM10 y PM2.5 tengan una paleta de colores consistente
def dic_etiquetas():
dic_etiquetas= {'o3_max': 'O3',
'o3_predicted_historico': 'O3 pronóstico histó... |
#Escreva um programa que pergunte a quantidade de Km percorridas por um carro alugado e a quantidade de dias que pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$ 60,00 por dia e R$ 0,15 por KM rodado.
AlugCarDias = int(input('Informe a quantidades de dias que o carro ficou em sua poss... |
# user-defined function for sorting the list
# it has List as parameter
def selectionSort(List):
#n is the length of the list
n=len(List)
#if list is empty
if n==0:
return(List)
#if list is not empty
for i in range(n-1):
#we are finding minimum of the sublist from List[i] to e... |
class MyHashMap:
def __init__(self):
self.arr = [-1 for _ in range(10 ** 6)]
def put(self, key: int, value: int):
self.arr[key] = value
def get(self, key):
return self.arr[key]
def remove(self, key):
self.arr[key] = -1
# Your MyHashMap object will be instantiated and... |
print("Hello world!")
print("What is your name?")
name = input()
print("It is good to meet you,", name)
|
# This lab demonstrates how to creates lists in Python
# The list will be used in ways that relate to real life scenarios
# It will also aim to format, add and remove items from the list
line_break = "\n"
# declare a list that includes the names of users
users = ['lamin', 'sally', 'bakay', 'satou', 'sainey']
... |
'''Crie um programa que leia o nome completo de uma pessoa e mostre:
O nome com todas as letras maiúsculas e minúsculas.
Quantas letras ao todo sem considerar espaços.
Quantas letras tem o primeiro nome.'''
nome = str(input("Digite o seu nome completo: ")).strip()
print("Analisando seu nome...")
print("Seu nome em mai... |
#!/usr/bin/env python3
def solution(a: list) -> int:
"""
>>> solution([1, 3])
2
"""
counter = [0] * (len(a) + 1)
for x in a:
counter[x-1] += 1
for x, count in enumerate(counter, 1):
if not count:
return x
if __name__ == '__main__':
for n in range(10):
... |
# Hackerrank challenges
''' Task
The provided code stub reads two integers a,b from STDIN:
Add logic to print two lines; No rounding or formatting is necessary:
* The first line should contain the result of integer division, // .
* The second line should contain the result of float division, / '''
# División
''' T... |
# -*- coding: utf-8 -*-
{
' ': ' ',
' %s, остаток %s': ' %s, остаток %s',
' (курс по счету: %s)': ' (курс по счету: %s)',
' - лучшая цена не доступна.': ' - лучшая цена не доступна.',
' - потому что время "жизни" заказа на курс только 20 минут, после чего заказ становится недействительным. ': ' - потому что время... |
class BaseError(Exception):
"""Base Error"""
class ArgumentError(BaseError):
"""Arguments error"""
class ConfigError(BaseError):
"""raise config error"""
|
'''
Created on 2016年1月30日
@author: Darren
'''
'''
Given an array A={a1,a2,…,aN} of N elements, find the maximum possible sum of a
1.Contiguous subarray
2.Non-contiguous (not necessarily contiguous) subarray.
Empty subarrays/subsequences should not be considered.
This Youtube video by Ben Wright might be useful to u... |
# https://leetcode.com/problems/implement-rand10-using-rand7/
#
# algorithms
# Medium (45.6%)
# Total Accepted: 630
# Total Submissions: 1.4K
# The rand7() API is already defined for you.
# def rand7():
# @return a random integer in the range 1 to 7
class Solution(object):
def rand10(self):
"""
... |
class UserDataStorage:
def __init__(self):
self._users = {}
def for_user(self, user_id: int):
result = self._users.get(user_id)
if result is None:
user_data = {}
self._users[user_id] = user_data
return user_data
return result
|
# Host to initialise the application on
HOST = "0.0.0.0"
# set the webapp mode to debug on startup?
DEBUG = False
# port to deploy the webapp on
PORT = 5000
# apply SSL to the site?
SSL = True
# Start the webapp with threading enabled?
THREADED = False |
class C:
"""
Namespace for constants.
"""
TEST_INT = 1
TEST_FLOAT = 1.0
TEST_FALSE = False
TEST_TRUE = True
TEST_STR = '1'
TEST_BYTE = b'1'
TEST_DICT = {1}
TEST_CLASS = object()
# PyStratum
TST_ID_EGGS = 2
TST_ID_SPAM = 1
TST_TST_C00 = 11
|
#Olivetti metricas
#Get the font
thisFont = Glyphs.font
#Get the masters
allMasters = thisFont.masters
#Get The glyphs
allGlyphs = thisFont.glyphs
ascendentes = 780
capHeight = 700
xHeight = 510
descendentes = -220
#Loop in masters /// enumerate ayuda a iterar sobre el indice de las capas
for index, master in enumer... |
"""
File: boggle.py
Name: Karnen Huang
----------------------------------------
This file helps user find word whose length is more than 4 and in dictionary by using 16 characters entered
by user.
"""
# This is the file name of the dictionary txt file
# we will be checking if a word exists by searching through it
FILE... |
class BaseDeployAzureVMResourceModel(object):
def __init__(self):
self.vm_size = '' # type: str
self.autoload = False # type: bool
self.add_public_ip = False # type: bool
self.inbound_ports = '' # type: str
self.public_ip_type = '' # type: str
self.app_name = '' ... |
"""
author: Alice Francener
problem: The Dark Elf
url: https://www.urionlinejudge.com.br/judge/en/problems/view/1766
"""
class Rena:
def __init__(self, nome, peso, idade, altura):
self.nome = nome
self.peso = peso
self.idade = idade
self.altura = altura
casos_teste = int(in... |
class Solution:
def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
mp = collections.defaultdict(int)
intervals.sort()
h = []
i = 0
for q in sorted([i for i in queries]):
while i < len(intervals) and intervals[i][0] <= q:
... |
num_rows = 8
num_cols = 20
rows = 1 #create a number to start counting from for rows
while rows <= num_rows: #start iterating through number of rows
cols = 1 #create a number to start counting from for columns
alpha = 'A' #starting point for alphabe... |
# Chapter03_04
# Python Tuple
# Should know about difference with List
# Cannot modify or remove
# Declaring Tuple
a = ()
b = (1,)
c = (11, 12, 13, 14)
d = (100, 1000, 'Ace', 'Base', 'Captine')
e = (100, 1000, ('Ace', 'Base', 'Captine'))
# Indexing
print('>>>>>')
print('d - ', d[1])
print('d - ', d[0] + d[1] + d[1])... |
def digitize(n: int) -> list:
num = []
for el in str(n):
num.append((int(el)))
return list(reversed(num)) |
class DwightException(Exception):
pass
class CommandFailed(DwightException):
pass
class UsageException(DwightException):
pass
class NotRootException(UsageException):
pass
class ConfigurationException(DwightException):
pass
class CannotLoadConfiguration(ConfigurationException):
pass
class I... |
__all__ = ['list_property']
class ListProperty(property):
"""Property that is really just a list index. This can turn a list into an object like a named tuple only a list
is mutable.
"""
def __init__(self, index=None, default=ValueError("Invalid list_property value"),
fget=None, fse... |
masses = {'H':'1.008',
'He':'4.003',
'Li':'6.941',
'Be':'9.012',
'B':'10.81',
'C':'12.01',
'N':'14.01',
'O':'16.00',
'F':'19.00',
'Ne':'20.18',
'Na':'22.99',
'Mg':'24.31',
'Al':'26.98',
'Si':'28.09',
'P':'30.97',
'S':'32.07',
'Cl':'35.45',
'Ar':'39.95',
'K':'39.10',
'Ca':'40.08',
'Sc':'44.96',
'Ti':'47.87',
'V':'50.94'... |
# Ternary Operator
# condition_if_true if condition else condition_if_else
is_friend = True
can_message = "message allowed" if is_friend else "not allowed"
print(can_message)
|
"""
because of the special porperty of the tree, the question basically is asking to find
the smallest element in the subtree of root. So, we can recursively find left and right
value that is not equal to the root's value, and then return the smaller one of them
"""
def findSecondMinimumValue(self, root):
if not ro... |
names = ['Jack', 'John', 'Joe']
ages = [18, 19, 20]
for name, age in zip(names, ages):
print(name, age)
|
#Here we package everything up into functions and set a loop so we can run it again and again. We also start using zodiacDescriptions2.txt so that descriptions of the signs are included.
#Open the zodiac file
def ZodiacSetup():
zodiacText = open('zodiacDescriptions2.txt')
#for line in zodiacText:
# pr... |
jungle_template = {
0 : {
"entity_type" : {"base": "room", "group": "jungle", "model": None, "sub_model": None},
"ship_id" : None,
"name" : "Thinned Jungle",
"description" : "The jungle here is thinner.",
"region" : "Jungle",
"zone" : "jungle",
"elevation" : "",
"effects" : "",
"owner" :... |
class VenepaikkaPaymentError(Exception):
"""Base for payment specific exceptions"""
class OrderStatusTransitionError(VenepaikkaPaymentError):
"""Attempting an Order from-to status transition that isn't allowed"""
class ServiceUnavailableError(VenepaikkaPaymentError):
"""When payment service is unreachab... |
def update_doc_with_invalid_hype_hint(doc: str):
postfix = '(Note: parameter type can be wrong)'
separator = ' ' if doc else ''
return separator.join((doc, postfix))
|
def frame_is_montecarlo(frame):
return ("MCInIcePrimary" in frame) or ("I3MCTree" in frame)
def frame_is_noise(frame):
try:
frame["I3MCTree"][0].energy
return False
except: # noqa: E722
try:
frame["MCInIcePrimary"].energy
return False
except: # noq... |
try:
score = float(input('enter score'))
# A program that prompts a user to enter a score from 0 to 1 and prints the corresponding grade
if 0 <= score < 0.6:
print(score, 'F')
elif 0.6 <= score < 0.7:
print(score, 'D')
elif 0.7 <= score < 0.8:
print(score, 'C')
elif 0.8 <... |
"""
The ska_tmc_cdm.messages.subarray_node package holds modules containing classes
that represent arguments, requests, and responses for TMC SubArrayNode
devices.
"""
|
class SlashException(Exception):
@classmethod
def throw(cls, *args, **kwargs):
raise cls(*args, **kwargs)
class NoActiveSession(SlashException):
pass
class CannotLoadTests(SlashException):
pass
class FixtureException(CannotLoadTests):
pass
class CyclicFixtureDependency(FixtureExcep... |
class Carro:
"""Representacion basica de un carro"""
def __init__(self, marca, modelo, anio):
"""Atributos del carro"""
self.marca = marca
self.modelo = modelo
self.anio = anio
self.kilometraje = 0 # Se define un atributo por defecto
def descripcion(self):
... |
def motif(dna, frag):
'''
Function that looks for a defined
DNA fragment in a DNA sequence and
gives the position of the start of each
instance of the fragment within the
DNA sequence.
Input params:
dna = dna sequence
frag = fragment to be searched for within
the sequence
... |
N = int(input())
s = set()
for i in range(2, int(N ** 0.5) + 1):
for j in range(2, N + 1):
t = i ** j
if t > N:
break
s.add(t)
print(N - len(s))
|
'''
cardcountvalue.py
Name: Wengel Gemu
Collaborators: None
Date: September 6th, 2019
Description: This program takes user input of a card value and prints
the card counting number for that card.
'''
# MIT card counting values:
#
# 2 - 6 should add one to the count, so their value is 1
# 7 - 9 have no effect o... |
class Solution:
def mySqrt(self, x):
high = x
low = 1
if x == 0:
return 0
# digit-by-digit calculation
while high - low > 1:
mid = (low + high)//2
#print("+++ ",mid)
if mid**2 > x:
high = mid
... |
class StringI(file):
pass
def StringIO(s=''):
return StringI(s)
|
print('-'*17)
print('Análise de dados')
print('-'*17)
cont = 1
mais18 = 0
homens = 0
mul20 = 0
while True:
idade = int(input(f'Qual a idade da {cont}º pessoa? '))
sexo = str(input(f'Qual o sexo da {cont}º pessoa? ')).strip().upper()
cont += 1
if idade > 18:
mais18 += 1
if sexo == 'M':
... |
def match(instruction, blanks):
"""
Procedure that returns the coordinates of the box that is best linked to the specific instruction
Ideas: Check upper left coordinate, or lower right coordinate
"""
return closestK(instruction, blanks, k=1)
def get_center(coords):
return ((coords[0][0] + c... |
# -*- coding: utf-8 -*-
class NotReadyError(Exception):
pass
|
a = float(input('Digite o primeiro segmento: '))
b = float(input('Digite o segundo segmento: '))
c= float(input('Digite o terceiro segmento: '))
if (a + b) > c:
area = a + b + c
print('Essas retas formam um triângulo de área {}'.format(area))
else:
print('Essas retas não formam um triângulo.') |
# Portfolio Task 2 - Recursive Palindrome Checker
def PalindromeChecker(String):
# Removing empty spaces and converting string to lowercase
str = String.replace(" ", "").lower()
if len(str) < 2:
return True
if str[0] != str[-1]:
return False
return PalindromeChecker(str[1:-1])
# Te... |
def setup():
size(1000, 1000)
stroke(0)
background(255)
def draw():
if (keyPressed):
x = ord(key) - 32
line(x, 0, x, height)
def draw():
pass
# pass just tells Python mode to not do anything here, draw() keeps the program running
def mousePressed():
fill(... |
#runas solve(2, 100)
#pythran export solve(int, int)
'''
How many distinct terms are in the sequence generated by ab for 2 <= a <= 100 and 2 <= b <= 100
'''
def solve(start, end):
terms = {}
count = 0
for a in xrange(start, end + 1):
for b in xrange(start, end + 1):
c = pow(long(a),b)
if not ... |
a, b, c = [int(input()) for i in range(3)]
if a + b == c or b + c == a or a + c == b:
print("HAPPY CROWD")
else:
print("UNHAPPY CROWD")
|
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
url=input("Enter the website url: ") # The full website URL (e.g. https://www.example.com)
campaign_source=input("Enter the Campaign Source: ") #The referrer: (e.g. google, newsletter,facebook,reddit)
campaign_medium=input("Enter the campaign medium: "... |
"""
Time utilities for the manipulation of time.
@author: John Berroa
"""
class Converter:
"""
Converts times from one measurement to another, and also parses or creates strings related to time
"""
@staticmethod
def sec2min(secs):
mins = secs // 60
return mins
@staticmethod
... |
"""
https://leetcode.com/problems/hamming-distance/description/
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:... |
class Classification:
# The leaf nodes of the decision tree
def __init__(self, c=0, label="NONE", threshold=None):
self.c = c
self.label = label
self.threshold = threshold
def getClass(self):
return self.c
def getLabel(self):
return self.label
def setClass(... |
# Python3
# 有限制修改區域
def permutationCipher(password, key):
table = str.maketrans(''.join(map(chr, range(ord('a'), ord('z') + 1))), key)
return password.translate(table)
|
""" Module for visualizations of MPTs.
"""
def to_tikz(mpt):
""" Generate tikz code for given MPT
Parameters
----------
mpt : MPT
MPT to be translated to tikz
code_path : str
specify where to save the tikz code
"""
def recursive_translation(node):
""" Recursivel... |
# Copyright 2021 Google LLC
#
# Use of this source code is governed by an MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
def parse_tvs(tvdir):
p = tvdir / "external" / "polyval.txt"
with p.open() as f:
d = None
k = None
v = None
... |
# -*- coding: utf-8 -*-
#
# COMMON
#
page_action_basket = "Корзина"
page_action_enter = "Войти"
page_action_add = "Добавить"
page_action_cancel = "Отмена"
page_action_yes = "Да"
page_action_save = "Сохранить"
page_action_action = "Действие"
page_action_modify = "изменить"
page_action_remove = "удалить"
page_message_e... |
def is_git_url(url):
if url.startswith('http'):
return True
elif url.startswith('https'):
return True
elif url.startswith('git'):
return True
elif url.startswith('ssh'):
return True
return False
def is_not_git_url(url):
return not is_git_url(url)
class Filter... |
################################ Units #########################################
DESCR_VILLAGER = """Villagers have poor fighting skills but
are able to build villages, windmills,
bridges, towers and walls."""
DESCR_INFANTRY = """Infantry is composed of soldiers with
basic fighting skills. Infantry can
capture places... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.