content stringlengths 7 1.05M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 21:10:52 2019
@author: felix
"""
def minimum_skew(genome):
"""
GC-skew such a useful tool for identifying the location of ori
"""
val = [0]
j = 0
_min = 0
for i in genome:
if i == 'C':
j -= 1
... |
class ComplexNumber(object):
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __add__(self, other):
return ComplexNumber(self.real+other.real, self.imag+other.imag)
def __sub__(self, other):
return ComplexNumber(self.real-other.real, self.imag-other.ima... |
# https://leetcode.com/problems/first-bad-version/
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return an integer
# def isBadVersion(version):
class Solution:
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
if isBadVersio... |
"""# Providers
Defines providers and related types used throughout the rules in this
repository.
Most users will not need to use these providers to simply create Xcode projects,
but if you want to write your own custom rules that interact with these
rules, then you will use these providers to communicate between them... |
"""
Utilities for visualization plugins.
"""
# =============================================================================
class OpenObject(dict):
# note: not a Bunch
# TODO: move to util.data_structures
"""
A dict that allows assignment and attribute retrieval using the dot
operator.
If an... |
rec3 = 0
rec4 = 0
def hanoi3num(n, origem, destino, trabalho):
global rec3
rec3 += 1
if n == 1:
return rec3
hanoi3num(n-1, origem, trabalho, destino)
hanoi3num(n-1, trabalho, destino, origem)
return rec3
def hanoi4num(n, origem, destino, trabalho1, trabalho2):
global rec4
i... |
class Solution:
def strMultiply(self, s, char):
bonus = 0
n = int(char)
newStr = ''
for i in range(len(s) - 1, -1, -1):
m = int(s[i])
result = n * m + bonus
newChar, bonus = str(result % 10), result // 10
newStr = newChar + newStr
... |
# These commands are the saved state of coot. You can evaluate them
# using "Calculate->Run Script...".
#;;molecule-info: 0_PO4b.pdb
#;;molecule-info: 1_PO4b.pdb
#;;molecule-info: 2_PO4b.pdb
#;;molecule-info: PO4.pdb
#;;molecule-info: PO4_O.pdb
#;;molecule-info: 0_PO4e.pdb
#;;molecule-info: 1_PO4e.pdb
#;;molecule-info... |
#!/usr/bin/env python
# coding: utf-8
# This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# # Solution Notebook
# ## Problem: Find the length of the longest substring with at most k disti... |
class DBPrefix:
DATA_Block = b'\x01'
DATA_Transaction = b'\x02'
ST_Account = b'\x40'
ST_Coin = b'\x44'
ST_SpentCoin = b'\x45'
ST_Validator = b'\x48'
ST_Asset = b'\x4c'
ST_Contract = b'\x50'
ST_Storage = b'\x70'
IX_HeaderHashList = b'\x80'
SYS_CurrentBlock = b'\xc0'
SY... |
#
# @lc app=leetcode.cn id=1 lang=python3
#
# [1] 两数之和
#
# https://leetcode-cn.com/problems/two-sum/description/
#
# algorithms
# Easy (43.97%)
# Total Accepted: 226K
# Total Submissions: 513.8K
# Testcase Example: '[2,7,11,15]\n9'
#
# 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
#
# 你可以假设每种输入只会对... |
"""
The constants.py namespace contains constants used throughout the repo
These values are assigned at the start of analysis using the "metadata.MetaData" class
Set the values by populating the .xml or .xlsx file as per documentation
"""
# === runtime arguments ===
EXTRACT_OD = None
ANALYZE_OD = None
INPUT_FOL... |
#Programa que leia o nome de uma cidade e diga se ela começa ou não com santo
cidade = input('Digite o nome de uma cidade:').title()
splt = cidade.split()
if splt[0] == 'Santo':
print('{} começa com Santo.'.format(cidade))
else:
print('{} não começa com Santo.'.format(cidade)) |
class Flight:
def __init__(self, segments):
"""
Creates a new Flight wrapper object from an arbitrary number of segments.
:param segments: a list of segments in this flight—normally just one.
"""
self.segments = segments
def __repr__(self):
stops = [self.seg... |
#!/usr/bin/env python3
_DEFAULT_DEPENDENCIES = [
"packages/data/**/*",
"packages/common/**/*",
"packages/course-landing/**/*",
"packages/{{site}}/**/*",
"yarn.lock",
]
_COURSE_LANDING_DEPENDENCIES = [
"packages/data/training/sessions.yml",
"packages/data/training/recommendations/**/*",
... |
class Board:
"""
Author: MBoss
Date: Jan 17, 2018.
Board class.
Board data:
1=white, -1=black, 0=empty
first dim is column , 2nd is row:
pieces[1][7] is the square in column 2,
at the opposite end of the board in row 8.
Squares are stored and manipulated as (x,y) tu... |
'''程序错误码'''
OK = 0 # 正常
class LogicError(Exception):
code = OK
data = 'OK'
def __init__(self, data=None):
cls_name = self.__class__.__name__
self.data = data or cls_name
def gen_logic_err(name, code):
'''生成一个 LogicError 的子类 (LogicError 的工厂函数)'''
err_cls = type(name, (LogicErro... |
class EthTokenTransferV2(object):
def __init__(self):
self.contract_address = None
self.from_address = None
self.to_address = None
self.token_type = None
self.token_id = None
self.amount = None
self.transaction_hash = None
self.log_index = None
... |
""" tests module for the FIX-specific modules for the fixtest tool.
Copyright (c) 2014 Kenn Takara
See LICENSE for details
"""
|
class PlasterError(Exception):
"""
A base exception for any error generated by plaster.
"""
class InvalidURI(PlasterError, ValueError):
"""
Raised by :func:`plaster.parse_uri` when failing to parse a ``config_uri``.
:ivar uri: The user-supplied ``config_uri`` string.
"""
def __init__... |
# Aumentos múltiplos
'''Escreva um programa que pergunte o salário
de um funcionário e calcule o valor do seu aumento.
Para salários superiores a R$ 1.250,00, calcule um
aumento de 10%. Para os inferiores ou iguais, o aumento é de 15%'''
salario = float(input('Informe o valor do seu salário atual: '))
print('O seu sal... |
print('Manipulando cadeias de textos ou caracteres')
print('Operações de manipulação de textos')
print('1º FATIAMENTO:')
frase ='Curso em video'
print(frase[9]) # aparecerá o corte de uma letra na posição indicada
print(frase[:6]) # os dois pontos apresenta um intervalo atéa posição indicada
print(frase[9:14]) # inte... |
class Node(object):
def __init__(self, value=None, pointer=None):
self.value = value
self.pointer = None
class Queue(object):
def __init__(self):
self.head = None
self.tail = None
def isEmpty(self):
return not bool(self.head)
def enqueue(self, value):
nod... |
def reverseList(self, head: ListNode) -> ListNode:
# begin with temporary node
cur = ListNode(-1)
# continue while list exists
while head is not None:
# create temp and make temp the new cur
temp = ListNode(-1)
cur.val = head.val
temp.next = cur
cur = temp
... |
# terrascript/data/hashicorp/random.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:25:40 UTC)
__all__ = []
|
class CommonRescale():
def get_factor(self, a):
raise NotImplementedError
def __call__(self, init, mask):
init_copy = init.clone()
init_copy[~mask] = 1e-12
return self.get_factor(init) / self.get_factor(init_copy)
class L1GlobalRescale(CommonRescale):
def get_factor(self, ... |
#
# PySNMP MIB module BEGEMOT-WIRELESS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BEGEMOT-WIRELESS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:20:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
epochs = 7
tau = 1.0
dropout = 0.2
validation_split = None
batch_size = 32
lengthscale = 0.01
|
# MEDIUM
# TLE if decrement divisor only
# Bit manipulation.
# input: 100 / 3
# times = 0
# 3 << 0 = 3
# 3 << 1 = 6
# 3 << 2 = 12
# 3 << 3 = 24
# 3 << 4 = 48
# 3 << 5 = 96
# 3 << 6 = 192 => greater than dividend 100 => stop here
# times -=1 becaus... |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 ... |
def parse_data(data, objects_format, separator=" "):
"""
Takes a list of strings and a list of objects format and returns a list of objects formatted according to the objects format.
Example:
parse_data(['forward 10', 'left 90', 'right 90'], [{'key': 'command, 'format': str}, {'key': 'value', 'forma... |
class Test:
def __init__(self):
self.prop1 = None
raise Exception('Interrupt init')
def __del__(self):
print('instance deleted')
print(self.prop1)
class Test2(Test):
pass
Test2()
|
def compress_image(image, n_colors=64):
"""Compress an image
Parameters
==========
image : numpy array
array of shape (height, width, 3) with integer values between 0 and 255
n_colors : integer
the number of colors in the final compressed image
(i.e. the number of KMeans clu... |
def custom_filter(record):
info = record.INFO
support = info['SU'][0]
paired_end_support = info['PE'][0]
split_read_support = info['SR'][0]
if support > 10 and paired_end_support > 5 and split_read_support > 5:
yield record
|
def from_socket(node, socket):
pass
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Blackbox Hardware Driver',
'version': '1.0',
'category': 'Hardware Drivers',
'sequence': 6,
'summary': 'Hardware Driver for Belgian Fiscal Data Modules',
'website': 'https://www.odoo.com... |
"""
---> Longest Consecutive Sequence
---> Medium
"""
class Solution:
def longestConsecutive(self, nums) -> int:
nums = set(nums)
ans = 0
for num in nums:
if num - 1 not in nums:
curr = num
while curr in nums:
ans = max(ans,... |
frase = str(input('Digite uma frase: ')).strip().upper()
palavras = frase.split()
junto = ''.join(palavras)
print('\033[32mVocê digitou a frase:\033[m {}.'.format(frase))
print('\033[32mVocê digitou a frase:\033[m {}.'.format(palavras))
print('\033[32mVocê digitou a frase:\033[m {}.'.format(junto))
inverso = ''
for let... |
def append_helper(initial_list, append_this):
if type(initial_list) is not list:
raise TypeError("initial_list must be a list")
if type(append_this) == list:
return initial_list + append_this
else:
initial_list.append(append_this)
return initial_list
|
#
# Solution to Project Euler problem 6
# Copyright (c) Süleyman Onur Dinçel. All rights reserved.
#
# https://github.com/onurdincel/Project-Euler-Solutions
#
"""The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2... |
def imageF():
image = imread(r"E:\Python Working\png")
if __name__ =="__main__":
imageF() |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" This file will contain the webui endpoints for the web Application
Too small so moved for now.
"""
|
# Time: O(n)
# Space: O(1)
# We have two integer sequences A and B of the same non-zero length.
#
# We are allowed to swap elements A[i] and B[i].
# Note that both elements are in the same index position in their respective sequences.
#
# At the end of some number of swaps, A and B are both strictly increasing.
# (A ... |
class IGetCurrencies:
def __init__(self, data):
self.success = data.get('success')
self.message = data.get('message', '')
self.currencies_raw = data.get('currencies', {})
self.earbuds = Currency(self.currencies_raw.get('earbuds', {}))
self.keys = Currency(self.currencies_raw... |
def pytest_benchmark_scale_unit(config, unit, benchmarks, best, worst, sort):
"""
To have custom time scaling do something like this:
.. sourcecode:: python
def pytest_benchmark_scale_unit(config, unit, benchmarks, best, worst, sort):
if unit == 'seconds':
prefix = ''
... |
class TestFile():
test = temp
def temp_method():
print('temp_method')
|
"""
Vulnerabilities are divided into 2 main categories.
MITRE Category
--------------
Vulnerability that correlates to a method in the official MITRE ATT&CK matrix for kubernetes
CVE Category
-------------
"General" category definition. The category is usually determined by the severity of the CVE
"""
class MITRECa... |
WORKER_THREAD = 'thread'
WORKER_GREENLET = 'greenlet'
WORKER_PROCESS = 'process'
WORKER_TYPES = (WORKER_THREAD, WORKER_GREENLET, WORKER_PROCESS)
class EmptyData(object):
pass
|
description = 'RESI NICOS startup setup'
group = 'basic'
includes = ['system'] #, 'lakeshore', 'cascade', 'detector']
modules = ['nicos_mlz.resi.scan']
devices = dict(
resi = device('nicos_mlz.resi.devices.residevice.ResiDevice',
description = 'main RESI device',
unit = 'special',
),
theta ... |
def translate(phrase):
translation = ""
for letter in phrase:
if letter in "AEIOUaeiou":
if letter.isupper():
translation = translation + "M"
else:
translation = translation + "m"
else:
translation = translation + letter
ret... |
class Quote(object):
def __init__(self, root, **kwargs):
self._data = kwargs
self._root = root
def __getattr__(self, item):
return self._data.get(item, None)
def to_primitive(self):
return self._data
@staticmethod
def from_primitive(root, primitive):
if pri... |
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
INSTALLED_APPS = [
'django_nose',
'tests.testapp',
]
ROOT_URLCONF = 'tests.urls'
SECRET_KEY = "shh...it's a seakret"
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION... |
# Example test module for nose
# run with: nosetests -v
# or: nosetests -s
# Simple test functions first:
def test_ok():
print("test_ok")
# def fail_test():
# print "fail_test: will always fail"
# assert False
# Private functions are however not recognized:
def _test_notseen():
print("_test_notseen")
... |
#!/usr/bin/env python3
num = int(input())
if num % 3 == 0 and num % 5 == 0:
print('fizzbuzz')
elif num % 3 == 0:
print("fizz")
elif num % 5 == 0:
print("buzz")
else:
print('you are wrong kiddo')
# the point of fizzbuzz is to see if a number is divisible by 3 and 5, or just one, or neither.
# for more info c... |
class BuildError(Exception):
def __init__(self, message: str):
super().__init__(message)
class MissedRequiredParamError(BuildError):
def __init__(self, param_name: str):
message = f'Required param "{param_name}" is missed'
super().__init__(message)
class FunctionNotExistError(BuildEr... |
def func(arg, opt=1, *args, **kwargs):
print(arg, opt, args, kwargs)
func(0)
func(0, 10)
func(0, 10, 20)
func(0, 10, 20, 30)
func(0, 10, 20, 30, key='value')
func(0, 10, 20, 30, key='value', key2='v2')
|
# class definition
class MyClass:
pass
# The __init__() Method
# attributes
# methods
class People:
def __init__(self, name, age):
self.__name = name
self.__age = age
def sayhi(self):
print("Hi, my name is %s, and I'm %s" % (self.__name, self.__age))
def get_age(self):
... |
print('Opening dummy.txt')
#open dummy.txt to read it as "in_stream" (in_stream is the variable)
with open('dummy.txt', 'r') as in_stream:
print('Opening output.txt')
#open output.txt to write in it, call it "out_stream"
with open('output.txt', 'w') as out_stream:
#for every line in the dummy.txt input file
#en... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
This module defines input/output functions.
Text
----
.. automodule:: tunacell.io.text
:members:
Sniff
-----
.. automodule:: tunacell.io.sniff
:members:
HDF5
----
.. automodule:: tunacell.io.h5
:members:
"""
|
count = int(input())
numbers_list = []
for _x in range(count):
numbers_list.append(int(input()))
sum_numbers = 0
count_numbers = len(numbers_list)
for x in numbers_list:
sum_numbers += x
mean = sum_numbers / count_numbers
print(mean)
|
#! /usr/bin/env python3
AsciiBinFmt, AsciiGrayFmt, AsciiPixelFmt = range(1, 4)
BinBinFmt, BinGrayFmt, BinPixelFmt = range(4, 7)
ext = ["", "pbm", "pgm", "ppm", "pbm", "pgm", "ppm"]
def isBinFmt(fmt):
return fmt % 3 == 1
def isGrayFmt(fmt):
return fmt % 3 == 2
def isPixelFmt(fmt):
return fmt % 3 == 0
c... |
'''
The function has been made even more general by parameterizing the size of one sub box.
'''
def drawBox(length, cellSize):
for i in range(length):
printBoxLines(length, cellSize, "*", "---", 1)
printBoxLines(length, cellSize, "|", " ", cellSize)
printBoxLines(length, cellSize, "*", "---"... |
GRID_SIZE = 5
# Bingo numbers and grids.
def get_b_and_g(lines):
bingo_numbers = []
grids = []
is_first = True
for line in lines:
if is_first:
bingo_numbers = [int(s) for s in line.split(",") if s.isdigit()]
is_first = False
continue
if line == "":
... |
# Even Fibonacci numbers
# Each new term in the Fibonacci sequence is generated
# by adding the previous two terms. By starting with
# 1 and 2, the first 10 terms will be:
#
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# By considering the terms in the Fibonacci sequence
# whose values do not exceed four million, find th... |
""" Lab 05: Mutable Sequences and Trees """
# Q1
def acorn_finder(t):
"""Returns True if t contains a node with the value 'acorn' and
False otherwise.
>>> scrat = tree('acorn')
>>> acorn_finder(scrat)
True
>>> sproul = tree('roots', [tree('branch1', [tree('leaf'), tree('acorn')]), tree('branch... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def f1(a,b,c=0,*args,**kwargs):
print('a=',a,'b=',b,'c=',c,'args=',args,'kwargs=',kwargs)
def f2(a,b,c=0,*,d,**kw):
print('a=',a,'b=',b,'c=',c,'d=',d,'kw=',kw)
#f1(1,2,3,'a','b',x=99)
#f2(1,2,d=99,ext=None)
args=(1,2,3,4)
kw={'d':99,'x':'#'}
f1(*args,**kw)
args=(... |
""" Proměnné
Proměnné jsou objekty, datové typy jsou třídy.
"""
age = 36 # celé číslo, proměnná age je objekt třídy int
bodyHeight = float(1.78) # reálné číslo (typ float), proměnná bodyHeight je objekt třídy float
firstName, lastName = "Gal", 'Gadot'
fullName = firstName + " " + lastName # operace sčítá... |
#!/usr/bin/env python3
#
# Copyright 2019 Vojtech Horky
#
# 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 o... |
# Copyright 2015 The Bazel Authors. 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 la... |
# Robot variable file using Python syntax
# Installed browser selection
# BROWSER = "chrome"
# BROWSER = "firefox"
BROWSER = "headlessfirefox"
# Helmi login credentials:
# replace <helmiurl> with your area specific value https://alue.helmi.fi
# replace <user> and <pass> with your Helmi username and password
HELMI_LO... |
print("000560_03_06_FuncAsObj.py")
print()
print("000560_03_06_ex01_")
def shout(word):
return word + "!"
speak = shout
output = speak ("lol")
print(output)
print()
print("000560_03_06_ex01_functions_objects")
# функции как объекты
def myltiply(x,y):
return x*y
a=4
b=7
operation=myltiply
print (operation(a,b))
... |
class Solution:
"""
@param: s: A string
@return: A string
"""
def reverseWords(self, s):
return " ".join(list(filter(lambda x: x != "", s.split(" ")))[::-1]) |
class Solution:
def printMinNumberForPattern(ob, S):
# code here
count = 1
stack = []
ans = ""
for i in S:
if i == "D":
stack.append(count)
count += 1
else:
stack.append(count)
coun... |
# UNIDAD 06.D19 - D21
# Programación Orientada a Objetos (POO)
print('\n\n---[Diapo 19]---------------------')
print('POO - Constructor')
class Galletita:
sabor = 'Dulce'
color = 'Negra'
chips_chocolate = False
def __init__(self):
print('Se acaba de crear una galletita')
mi_galletita = ... |
class Solution:
def removeDuplicates(self, nums):
if len(nums) == 0:
return 0
nextAvail = 1
for i in range(1, len(nums)):
if nums[i] == nums[nextAvail-1]:
i += 1
else:
nums[nextAvail] = nums[i]
nextAvail += 1... |
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
dp = 0
ans = 0
n = len(nums)
for i in range(2, n):
pre = nums[i - 1] - nums[i - 2]
now = nums[i] - nums[i - 1]
if now == pre:
dp += 1
ans +=... |
def findMax(some_dict):
positions = set() # output variable
max_value = -1
for k, v in some_dict.items():
if v == max_value:
positions.add(k)
if v > max_value:
max_value = v
positions = set() # output variable
positions.add(k)
return positions, max_value
def getChangeTimes(cowL... |
"""
Test all functionality related to authorization, e.g. logging in, logging out, registering etc.
"""
def test_nonexisting_account(client):
response = client.get('/v0/whoami')
assert response.status_code == 401
response = client.post('/v0/login', json={
'username': 'a',
'password': 'a'
... |
def mdc(a,b):
if a<b:
return mdc(b,a)
else:
if b==0:
return a
else:
return mdc(b, a % b)
print(mdc(12,8))
print(mdc(12,10))
|
# -*- coding: utf-8 -*-
'''
module used while testing mock hubs provided in 'testing'.
'''
__contracts__ = ['testing']
def noparam(hub):
pass
def echo(hub, param):
return param
def signature_func(hub, param1, param2='default'):
pass
def attr_func(hub):
pass
attr_func.test = True
attr_func._... |
def add(first,second):
"""Adds two numbers"""
return first + second
if __name__ == "__main__":
add(2,3)
|
code = "he.elk.set.to"
decode = code.split("e")
print(decode[-1])
|
"""Infer read orientation from sample data."""
def infer():
"""Main function coordinating the execution of all other functions.
Should be imported/called from main app and return results to it.
"""
# implement me
|
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(M, A):
hash = [0] * (M + 1)
slices = 0
max_slices = 1000000000
head = 0
for tail in range(len(A)):
while head < len(A) and ( not hash[A[head]]):
hash[A[head]] = 1
s... |
"""P7E10 VICTORIA PEÑAS
Escribe un programa que te pida una palabra o número, pase por parámetro
estos datos a una función, y ésta te diga si es o no palíndroma o
capicúa. El programa principal imprimirá el resultado de la función:
':: significa dame la totalidad\del elemento, el -1 hacia atras' """
def comprobarPalind... |
"""
Author: Alberto Marci
"""
class DecimalToRoman:
# convert number from 0 to 9
def __zero_to_nine(self, number):
if number == '0':
return ''
if number == '1':
return 'I'
if number == '2':
return 'II'
if number == '3':
... |
class Solution:
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if not board:
return board
last = copy.deepcopy(board)
for i in range(len(board)):
... |
#less than operator
print(4<10) # --- L1
print(10<4) # --- L2
print(4<4.0) # --- L3
print(4.0<4) # --- L4
print('python'<'Python') #--- L5
print('python'<'python') # --- L6
print('Python'<'python') #--- L7
|
DIGITS = "0123456789abcdef"
def convert_base_stack(decimal_number, base):
remainder_stack = []
while decimal_number > 0:
remainder = decimal_number % base
remainder_stack.append(remainder)
decimal_number = decimal_number // base
new_digits = []
while remainder_stack:
... |
def add(a,b):
return a+b
def substract(a,b):
return a * b
## Imagine I made a valid change
def absolut(a,b):
return np.abs(a,b)
|
class Solution:
def findRestaurant(self, list1, list2):
mp1, mp2 = {x: i for i, x in enumerate(list1)}, {x: i for i, x in enumerate(list2)}
ans = [10 ** 4, []]
for k, v in mp1.items():
if k in mp2 and v + mp2[k] == ans[0]: ans[1].append(k)
elif k in mp2 and v + mp2[k]... |
# Solution 1
# O(n) time / O(n) space
def branchSums(root):
sums = []
calculateBranchSums(root, 0, sums)
return sums
def calculateBranchSums(node, runningSum, sums):
if node is None:
return sums
newRunningSum = runningSum + node.value
if node.left is None and node.right is None:
... |
class Context(dict):
"""docstring for _Context"""
def __init__(self, name, parameters={}, lifespan=5):
self.name = name
self.parameters = parameters
self.lifespan = lifespan
# def __getattr__(self, param):
# if param in ['name', 'parameters', 'lifespan']:
# ... |
def minInsertions(s: str) -> int:
dp = [[0] * len(s) for _ in range(len(s))]
for left in range(len(s) - 1, -1, -1):
for right in range(0, len(s)):
if left >= right:
continue
if s[left] == s[right]:
dp[left][right] = dp[left+1][right-1]
... |
# -*- coding: UTF-8 -*-
PROXYSOCKET = ''
RETRY_TIMES = 5
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Accept': 'application/json,application/xml'
}
INPUT_FILE = 'dependencies/input.xlsx'
API_DEBUG = True
AP... |
N = int(input(""))
for x in range(0, N):
if N > 0:
s = input("")
s = s.split() #separar
if s[0] == s[1]:
print("empate")
else:
if s[0] == "tesoura":
if s[1] == "papel" or s[1] =="lagarto":
print("rajesh")
... |
def extract_organization_id_from_request_query(request):
return request.query_params.get('organization') or request.query_params.get('organization_id')
def extract_organization_id_from_request_data(request) -> (int, bool):
"""
Returns the organization id from the request.data and a bool indicating if the ... |
"""Provides the repository macro to import rocksdb."""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def repo():
"""Imports rocksdb."""
ROCKSDB_VERSION = "6.15.5"
ROCKSDB_SHA256 = "d7b994e1eb4dff9dfefcd51a63f86630282e1927fc42a300b93c573c853aa5d0"
http_archive(
name = "... |
#===============================================================================
# Copyright 2020 Intel Corporation
#
# 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.o... |
def intersects(line1, line2):
def onSeg(p, q, r):
if (q[0] <= max(p[0],r[0]) and q[0] >= min(p[0],r[0]) and
q[0] <= max(p[1],r[1]) and q[1] >= min(p[1],r[1])):
return True
return False
#0 -> colinear, 1 -> clockwise, 2 -> ccw
def orientation(p,q,r):
v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.