content
stringlengths
7
1.05M
class BTNode: __slots__ = "value", "left", "right" def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def test_BTNode(): parent = BTNode(10) left = BTNode(20) right = BTNode(30) parent.left = left parent.right =...
""" Convenience classes for returning multiple values from functions Examples: Success w/ data: return ok_resp(some_obj) Success w/ data and a message: return ok_resp(some_obj, 'It worked') Error w/ message: return err_resp('some error message') Error w/ message and data: return err_resp('some error m...
#!/usr/bin/python # -*- coding: utf-8 -*- DEBUG = True USE_TZ = True SECRET_KEY = "KEY" DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } } ROOT_URLCONF = "tests.urls" INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.messages", "d...
#!/home/rob/.pyenv/shims/python3 def example(param): """param must be greater than 0""" assert param > 0 #if __debug__: # if not param > 0: # raise AssertionError # do stuff here... if __name__ == '__main__': example(0)
""" VIS_DATA """ #def get_img_figure(n_subplots=1): def plot_img(ax, img, **kwargs): title = kwargs.pop('title', 'Image') ax.imshow(img) ax.set_title(title)
# -*- coding: utf-8 -*- """ /*************************************************************************** Configuration file The PlanHeat tool was implemented as part of the PLANHEAT project. This file contains several global variables used inside the different sub-modules. -------------...
''' pequeno script que informa se é possivel ou não formar um triangulo com base nos angulos ''' a = int(input('digite seu primeiro angulo: ')) b = int(input('digite seu segundo angulo: ')) c = int(input('digite seu terceiro angulo: ')) res = a + b if res > c: print('é possivel formar um triangulo!') else: p...
class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): n = len(prices) if n < 2: return 0 min_price = prices[0] res = 0 for i in xrange(1, n): res = max(res, prices[i]-min_price) min_pr...
# Python 3: Simple output (with Unicode) print("Hello, I'm Python!") # Input, assignment name = input('What is your name?\n') print('Hi, %s.' % name)
# Time complexity: O(n) where n is number of nodes in Tree # Approach: Checking binary search tree conditions on each node recursively. # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right...
""" 1. Clarification 2. Possible solutions - simulation - math 3. Coding 4. Tests """ # T=O(n), S=O(n) class Solution: def totalMoney(self, n: int) -> int: return sum(i%7 + 1 + i//7 for i in range(n)) # # T=O(1), S=O(1) # class Solution: # def totalMoney(self, n: int) -> int: # extra, weeks ...
class Node(): def __init__(self): self.children = {} self.endofword = False self.string = "" class Trie(): def __init__(self): self.root = Node() def insert(self, word): pointer = self.root for char in word: if char not in pointer.children: ...
#----------------------------------------------------------------------- # helper modules for argparse: # - check if values are in a certain range, are positive, etc. # - https://github.com/Sorbus/artichoke #----------------------------------------------------------------------- def check_range(value): ivalue = in...
#logaritmica #No. de digitos de un numero def digitos(i): cont=0 if i == 0: return '0' while i > 0: cont=cont+1 i = i//10 return cont numeros=list(range(1,1000)) print(numeros) ite=[] for a in numeros: ite.append(digitos(a)) print(digitos(a))
# -*- coding: utf-8 -*- """ Created on Mon Oct 21 00:23:43 2019 @author: yanxi """ def addDummyNP(fname): res=[] with open(fname) as f: for line in f: l = line.split(',') l.insert(2,'0') res.append(','.join(l)) if len(res) != 0: with open(fname, 'w') as ...
# Guess Number Higher or Lower II class Solution(object): def getMoneyAmount(self, n): """ the strategy is to choose the option that if the worst consequence of that option occurs, it's the least worst case among all options specifically, if picking any number in a range, find the h...
class FakeSerial: def __init__( self, port=None, baudrate = 19200, timeout=1, bytesize = 8, parity = 'N', stopbits = 1, xonxoff=0, rtscts = 0): print("Port is ", port) self.halfduplex = True self.name = port self.port = port self.ti...
""" Recipes which illustrate augmentation of ORM SELECT behavior as used by :meth:`_orm.Session.execute` with :term:`2.0 style` use of :func:`_sql.select`, as well as the :term:`1.x style` :class:`_orm.Query` object. Examples include demonstrations of the :func:`_orm.with_loader_criteria` option as well as the :meth:`...
class CustomException(Exception): def __init__(self, *args): if args: self.message = args[0] else: self.message = None def get_str(self, class_name): if self.message: return '{0}, {1} '.format(self.message, class_name) else: return...
# Copyright 2014 Cloudera Inc. # # 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, so...
# Faça um programa em que troque todas as ocorrencias de uma letra L1 pela letra L2 em uma string. A string e as letras L1 e L2 devem ser fornecidas pelo usuario. palavra = input('\nDigite uma palavra: ') print(f'A palavra fornecida foi: {palavra}') resp1 = input('\nDigite a letra a ser substituida: ') resp2 = input...
# -*- coding: utf-8 -*- """Top-level package for Grbl Link.""" __author__ = """Darius Montez""" __email__ = 'darius.montez@gmail.com' __version__ = '0.1.4'
H = {0: [0], 1: [1, 2, 4, 8], 2: [3, 5, 6, 9, 10], 3: [7, 11]} M = {0: [0], 1: [1, 2, 4, 8, 16, 32], 2: [3, 5, 6, 9, 10, 12, 17, 18, 20, 24, 33, 34, 36, 40, 48], 3: [7, 11, 13, 14, 19, 21, 22, 25, 26, 28, 35, 37, 38, 41, 42, 44, 49, 50, 52, 56], 4: [15, 23, 27, 29, 30, 39, 43, 45, 46, 51, 53, 54, 57, 58], 5: ...
class SDCMeter(object): """Stores the SDCs probabilities""" def __init__(self): self.reset() def updateAcc(self, acc1, acc5): self.acc1 = acc1 self.acc5 = acc5 def updateGoldenData(self, scoreTensors): for scores in scoreTensors.cpu().numpy(): self.goldenSco...
yusuke_power = {"Yusuke Urameshi": "Spirit Gun"} hiei_power = {"Hiei": "Jagan Eye"} powers = dict() # Iteration for dictionary in (yusuke_power, hiei_power): for key, value in dictionary.items(): powers[key] = value # Dictionary Comprehension powers = {key: value for d in (yusuke_power, hiei_power) for key, v...
SIMPLE_QUEUE = 'simple' WORK_QUEUE = 'work_queue' RABBITMQ_HOST = '0.0.0.0' LOG_EXCHANGE = 'logs' ROUTING_EXCHANGE = 'direct_exchange' TOPIC_EXCHANGE = 'topic_exchange' SEVERITIES = ['err', 'info', 'debug'] FACILITIES = ['kern', 'mail', 'user', 'local0']
# triple nested exceptions passed = 1 def f(): try: foo() passed = 0 except: print("except 1") try: bar() passed = 0 except: print("except 2") try: baz() passed = 0 except: ...
""" Take Home Project 1. Write a program for an e-commerce store. The program must accept at least 10 products on the first run. The storekeeper should be given the option to Add a product, remove a product, empty the product catalog and close the program. 2. Create a membership system that allows users to re...
class MetaSingleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(MetaSingleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class Processing(metaclass=MetaSingleton): def __init__(self): ...
uctable = [ [ 194, 178 ], [ 194, 179 ], [ 194, 185 ], [ 194, 188 ], [ 194, 189 ], [ 194, 190 ], [ 224, 167, 180 ], [ 224, 167, 181 ], [ 224, 167, 182 ], [ 224, 167, 183 ], [ 224, 167, 184 ], [ 224, 167, 185 ], [ 224, 173, 178 ], [ 224, 173, 179 ], [ 224, 173, 180 ], [ 224, 173, 181 ], [ ...
#A def greeting(x :str) -> str: return "hello, "+ x def main(): # input s = input() # compute # output print(greeting(s)) if __name__ == '__main__': main()
# Calculadora de desconto valor_prod = float(input('Valor do produto: ')) desc = float(input('Valor do desconto: ')) valor_final = valor_prod * (desc / 100) print(f'O valor final do produto com desconto é {valor_final:.2f}')
def test_delete_first__group(app): app.session.open_home_page() app.session.login("admin", "secret") app.group.delete_first_group() app.session.logout()
#####count freq of words in text file word_count= dict() with open(r'C:/Users/Jen/Downloads/resumes/PracticeCodeM/cantrbry/plrabn12.txt', 'r') as fi: for line in fi: words = line.split() prepared_words = [w.lower() for w in words] for w in prepared_words: word_count[w] =...
""" Writing to a textfile: 1. open the file as either "w" or "a" (write or append) 2. write the data """ with open("hello.txt", "w") as fout: fout.write("Hello World\n") with open("/etc/shells", "r") as fin: with open("hello.txt", "a") as fout: for line in fin: fout.write(line)
# Do not edit. bazel-deps autogenerates this file from dependencies.yaml. def _jar_artifact_impl(ctx): jar_name = "%s.jar" % ctx.name ctx.download( output=ctx.path("jar/%s" % jar_name), url=ctx.attr.urls, sha256=ctx.attr.sha256, executable=False ) src_name="%s-sources.jar...
# Copyright 2018 Oinam Romesh Meitei. All Rights Reserved. # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under th...
Dev = { "db_server": "Dbsed4555", "user": "<db_username>", "passwd": "<password>", "driver": "SQL Server", "port": "1433" } Oracle = { "db_server": "es20-scan01", "port": "1521", "user": "<db_username>", "passwd": "<password>", "service_name": "cmc1st01svc.uhc.com" } Sybase = { ...
message_id = { b"\x00\x00": "init", b"\x00\x01": "ping", b"\x00\x02": "pong", b"\x00\x03": "give nodes", b"\x00\x04": "take nodes", b"\x00\x05": "give next headers", b"\x00\x06": "take the headers", b"\x00\x07": "give blocks", b"\x00\x08": "take the blocks", b"\x00\x09": "give the txos", b"\x00\x0a": "take the txos", b...
""" math 模块提供了对 C 标准定义的数学函数的访问。 本模块需要带有硬件 FPU,精度是32位,这个模块需要浮点功能支持。 """ e = ... # type: int pi = ... # type: int def acos(x) -> None: """传入弧度值,计算cos(x)的反三角函数。""" ... def acosh(x) -> None: """返回 x 的逆双曲余弦。""" ... def asin(x) -> None: """传入弧度值,计算sin(x)的反三角函数。 示例: - x = math.a...
def accuracy(y_test, y): cont = 0 for i in range(len(y)): if y[i] == y_test[i]: cont += 1 return cont / float(len(y)) def f_measure(y_test, y, beta=1): tp = 0.0 # true pos fp = 0.0 # false pos tn = 0.0 # true neg fn = 0.0 # false neg for i in range(len(y)): if y_test[i] == 1.0 and y[i] =...
# MIT License # (C) Copyright 2021 Hewlett Packard Enterprise Development LP. # # applianceCrashHistory : returns and posts all Appliances crash history def appliance_crash_history( self, action: str = None, ): """Get appliance crash history. Can optionally send crash reports to Cloud Portal .. l...
name0_1_1_0_1_0_0 = None name0_1_1_0_1_0_1 = None name0_1_1_0_1_0_2 = None name0_1_1_0_1_0_3 = None name0_1_1_0_1_0_4 = None
class HandResponse: cost = None han = None fu = None fu_details = None yaku = None error = None is_open_hand = False def __init__(self, cost=None, han=None, fu=None, yaku=None, error=None, fu_details=None, is_open_hand=False): """ :param cost: dict :param han: in...
''' - Leetcode problem: 653 - Difficulty: Easy - Brief problem description: Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target. Example 1: Input: 5 / \ 3 6 / \ \ 2 4 7 Target = 9 Output: ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSymmetric(self, root: Optional[TreeNode]) -> bool: # both does not exist if not root.l...
load("@bazel_gazelle//:deps.bzl", "go_repository") def go_dependencies(): go_repository( name = "com_github_aws_aws_sdk_go", importpath = "github.com/aws/aws-sdk-go", sum = "h1:3+AsCrxxnhiUQEhWV+j3kEs7aBCIn2qkDjA+elpxYPU=", version = "v1.33.13", ) go_repository( name...
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. def source(): pass def sinkA(x): pass def sinkB(x): pass def sinkC(x): pass def sinkD(x): pass def split(x): ...
x=[11,12,13,14] y=[50,60,70] for i in range(1,10,2): x.append("Item# "+str(i)) for i in x: print(i) x.extend(y) print(x) x.append(y) print(x) x.remove(y) print(x) """ this is multiine comment operator... for i in x: #if int(i.replace("Item# ",""))%2!=0: if(isinstance(i,str)==False): if(i%2...
# @file motion_sensor.py # @author marco # @date 07 Oct 2021 class MotionSensor: def __init__(self, pin): self._pin = pin pinMode(self._pin, INPUT) def movement_detected(self): """Return True if motion has been detected""" return digitalRead(self._pin) == 1 def value(se...
#output comments variables input calculations output constants def display_output(): print('hello') def test_config(): return True
n = int(input()) f = {} while n > 1: i = 2 while True: if n % i == 0: if i not in f: f[i] = 0 f[i] += 1 n = n // i break i = i + 1 s = "" for k, v in f.items(): s += "{}".format(k) if v != 1: s += "^{}".format(v) ...
def divisors(x): divisorList = [] for i in range(1, x+1): if x%i == 0: divisorList.append(i) return divisorList def main(): while True: try: x = int(input("Type a number please:")) break except ValueError: pass y = divisors(x)...
# Exercise 8.2 # You can call a method directly on the string, as well as on a variable # of type string. So here I call count directly on 'banana', with the # argument 'a' as the letter/substring to count. print('banana'.count('a')) # Exercise 8.3 def is_palindrome(s): # The slice uses the entire string if the ...
''' Created on 30 de nov de 2018 @author: filiped ''' class Base: def __init__(self): self.s="" self.p=0 self.fim="@" self.pilha = ["z0"] def le_palavra(self,palavra="@"): self.p=0 self.s = palavra+"@" def xp(self,c=""): print(s...
class ConsumptionTax: def __init__(self, tax_rate): self.tax_rate = tax_rate def apply(self, price): return int((price * self.tax_rate) / 100) + price
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' def dict_to_url_params(json_data, root): def deep(node, root, items): if isinstance(node, list): for i, value in enumerate(node): node_root = root + f'[{i}]' deep(value, node_root, items) ...
# -*- coding: utf-8 -*- #センサデバイスに送信するためのコマンドを生成し、文字列として返す。 #文字列の終わりには改行も含まれているため、そのままwriteで使える #during_sec:何秒ごとにデータを送るか。(最低でも60以上の数字を入れること) #send_no:何回送った後に夜間休暇に入るか(例:10分おきで10時間(600秒)連続稼働の場合は 600/10 = 60と入力) #wait_sec:夜間休暇の秒数 #なお、夜間休暇明けには再度スタートコマンドを送る必要があります def make_senser_start_cmd(during_sec,send_no,wait_sec)...
# -*- coding: utf-8 -*- __author__ = 'gzp' class Solution: def maxTurbulenceSize(self, A): """ :type A: List[int] :rtype: int """ len_a = len(A) dp = {0: 1} i = 1 last_cmp = None while i < len_a: if A[i - 1] < A[i] and last_cmp ...
# Nach einer Idee von Kevin Workman # (https://happycoding.io/examples/p5js/images/image-palette) WIDTH = 800 HEIGHT = 640 palette = ["#264653", "#2a9d8f", "#e9c46a", "#f4a261", "#e76f51"] def setup(): global img size(WIDTH, HEIGHT) this.surface.setTitle("Image Palette") img = loadImage("akt.jpg") ...
def front_and_back_search(lst, item): rear=0 front=len(lst)-1 u=None if rear>front: return False else: while rear<=front: if item==lst[rear] or item==lst[front]: u='' return True elif item!=lst[rear] and item!=lst[front]: ...
# Darren Keenan 2018-02-27 # Exercise 4 - Project Euler 5 # What is the smallest number divisible by 1 to 20 def divisibleby1to20(n): for i in range(1, 21): if n % i != 0: return False return True n = 1 while True: if divisibleby1to20(n): break n += 1 print(n) # The smallest ...
#Entrada de dados numero = int(input('Digite um número :')) #Processamento e Saida de dados if numero % 2 == 0: print('O número é PAR') else: print('O número é IMPAR')
# Three number sum def threeSumProblem(arr: list, target: int) : arr.sort() result = list() for i in range(0, len(arr) - 2) : left = i+1;right=len(arr)-1 while left < right : curren_sum = arr[i] + arr[left] + arr[right] if curren_sum == target : ...
class animal: def eat(self): print("eat") class mammal(animal): def walk(self): print("walk") class fish(animal): def swim(self): print("swim") moka = mammal() moka.eat() moka.walk()
# Copyright 2018 Cyril Roelandt # # Licensed under the 3-clause BSD license. See the LICENSE file. class InvalidPackageNameError(Exception): """Invalid package name or non-existing package.""" def __init__(self, frontend, pkg_name): self.frontend = frontend self.pkg_name = pkg_name d...
g1 = 1 def display(): global g1 g1 = 2 print(g1) print("inside",id(g1)) display() print(g1) print("outside",id(g1))
showroom = set() showroom.add('Chevrolet SS') showroom.add('Mazda Miata') showroom.add('GMC Yukon XL Denali') showroom.add('Porsche Cayman') # print(showroom) # print (len(showroom)) showroom.update(['Jaguar F-Type', 'Ariel Atom 3']) # print (showroom) showroom.remove('GMC Yukon XL Denali') # print (showroom) junky...
class Solution: def validSquare(self, p1, p2, p3, p4): """ :type p1: List[int] :type p2: List[int] :type p3: List[int] :type p4: List[int] :rtype: bool """ def dis(P, Q): "Return distance between two points." return sum((p - q) ...
""" From Kapil Sharma's lecture 11 Jun 2020 Given the head of a sll and a value, delete the node with that value. Return True if successful; False otherwise. """ class Node: def __init__(self, data): self.data = data self.next = None def delete_node_given_value(value, head): # Edge cases ...
input = """ 8 2 2 3 0 0 8 2 4 5 0 0 8 2 6 7 0 0 6 0 4 0 2 3 4 5 1 1 1 1 0 4 c 3 b 7 f 2 a 6 e 5 d 0 B+ 0 B- 1 0 1 """ output = """ COST 2@1 """
TARGET_COL = 'class' ID_COL = 'id' N_FOLD = 5 N_CLASS = 3 SEED = 42
# # PySNMP MIB module ROHC-UNCOMPRESSED-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ROHC-UNCOMPRESSED-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:49:54 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
# 11. print(list(range(1, 10))) # 12. print(list(range(100, 20, -5)))
#Crie um programa onde o usuário possa digitar sete valores numéricos # e cadastre-os em uma lista única que mantenha separados os valores pares e ímpares. # No final, mostre os valores pares e ímpares em ordem crescente. lista = [[], []] for c in range(0, 7): valor = int(input(f'Digite o valor número {c}:')) ...
def A(m, n): if m == 0: return n + 1 if m > 0 and n == 0: return A(m - 1, 1) if m > 0 and n > 0: return A(m - 1, A(m, n - 1)) def main() -> None: print(A(2, 2)) if __name__ == "__main__": main()
"""Test for W0623, overwriting names in exception handlers.""" __revision__ = '' class MyError(Exception): """Special exception class.""" pass def some_function(): """A function.""" try: {}["a"] except KeyError as some_function: # W0623 pass
# input -1 n = int(input('input nilai: ')) if n <= 0: # Menentukan pengecualian & teks yang akan di tampilkan raise ValueError('nilai n harus bilangan positif') try: n = int(input('input nilai: ')) if n <= 0: # Menentukan pengecualian & teks yang akan di tampilkan raise ValueError('nil...
# # PySNMP MIB module CYCLONE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CYCLONE-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:34:24 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, 0...
def tapcode_to_fingers(tapcode:int): return '{0:05b}'.format(1)[::-1] def mouse_data_msg(data: bytearray): vx = int.from_bytes(data[1:3],"little", signed=True) vy = int.from_bytes(data[3:5],"little", signed=True) prox = data[9] == 1 return vx, vy, prox def air_gesture_data_msg(data: bytearray): return [data[0]]...
# Copyright 2019 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...
class DBConnector: def save_graph(self, local_graph): pass def get_reader_endpoint(self): pass def get_writer_endpoint(self): pass def disconnect(self): pass
test = { 'name': 'contains?', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" scm> (contains? odds 3) ; True or False True """, 'hidden': False, 'locked': False }, { 'code': r""" scm> (contains...
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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 applicab...
input = """ 1 2 2 1 3 4 1 3 2 1 2 4 1 4 0 0 1 5 1 0 2 1 6 1 0 5 1 5 1 0 6 0 3 d 2 c 6 b 5 a 0 B+ 0 B- 1 0 1 """ output = """ {d} {c, a, b} """
#! python # Problem # : 50A # Created on : 2019-01-14 21:29:26 def Main(): m, n = map(int, input().split(' ')) val = m * n cnt = int(val / 2) print(cnt) if __name__ == '__main__': Main()
# Maximum Absolute Difference # https://www.interviewbit.com/problems/maximum-absolute-difference/ # # You are given an array of N integers, A1, A2 ,…, AN. Return maximum value of f(i, j) for all 1 ≤ i, j ≤ N. # # f(i, j) is defined as |A[i] - A[j]| + |i - j|, where |x| denotes absolute value of x. # # For example, # #...
def organize_data(lines): max_x = 0 max_y = 0 line_segments = [] # store all of the line segments for line in lines: points = line.split(" -> ") point1 = points[0].split(",") point2 = points[1].split(",") x1 = int(point1[0].strip()) y1 = int(point1[1].strip()...
class Config: def __init__(self, name:str=None, username:str=None, pin:int=2, email:str=None, password:str=None, set_password:bool=False, set_email_notify:bool=False): self.name = name self.username = username self.pin = pin self.email = email self.password = password ...
# https://leetcode.com/problems/longest-increasing-subsequence/ class Solution: def lengthOfLIS(self, nums: list[int]) -> int: # Patience sorting-like approach, but keeping track # only of the topmost element at each stack. stack_tops = [nums[0]] for num in nums[1:]: for...
# -*- coding: utf-8 -*- """ Created on Wed Dec 30 13:55:35 2020 @author: SethHarden BINARY SEARCH - ITERATIVE """ # Iterative Binary Search Function # It returns index of x in given array arr if present, # else returns -1 def binary_search(arr, x): low = 0 high = len(arr) - 1 mid = 0 while low...
l = float(input('Qual a largura da parede (em m)? ')) h = float(input('Qual a altura da parede (em m)? ')) m = float(l*h) print('A quantida de litros necessária para pintar essa parede é {:.2f}'.format(m/2))
""" This is the helper module. The attributes of this module do not interact withy facebook rather help get better info about the objects fethced from facebook. """ D=type( {1:1} ) L=type( [1,2] ) def get_fields(d, s): if type(d) == D: for i in d.keys(): if type(d[i]) =...
# # @lc app=leetcode id=497 lang=python3 # # [497] Random Point in Non-overlapping Rectangles # # @lc code=start class Solution: def __init__(self, rects): """ :type rects: List[List[int]] """ self.rects = rects self.N = len(rects) areas = [(x2 - x1 + 1) * (y2 -...
""" Осуществить программу работы с органическими клетками, состоящими из ячеек. Необходимо создать класс «Клетка». В его конструкторе инициализировать параметр, соответствующий количеству ячеек клетки (целое число). В классе должны быть реализованы методы перегрузки арифметических операторов: сложение (__add__()), вычи...
{ "targets": [{ "target_name": "binding", "sources": ["binding.cc"], "include_dirs": [ "<!(node -e \"require('nan')\")", "/opt/vc/include", "/opt/vc/include/interface/vcos/pthreads", "/opt/vc/include/interface/vmcs_host/linux" ], ...
RES_SPA_MASSAGE_PARLOR = [ "spa", "table", "shower", "nuru", "slide", "therapy", "therapist", "bodyrub", "sauna", "gel", "shiatsu", "jacuzzi" ]
'''function in python ''' print('=== function in python ===') def func_args(*args): print('* function *args') for x in args: print(x) def func_kwargs(**kwargs): print('* function **kwargs') print('kwargs[name]', kwargs['name']) func_args('hainv', '23') func_kwargs(name="Tobias", lname="Re...
# config.py class Config(object): num_channels = 256 linear_size = 256 output_size = 4 max_epochs = 10 lr = 0.001 batch_size = 128 seq_len = 300 # 1014 in original paper dropout_keep = 0.5
arr = input() for i in range(0, len(arr), 7): bits = arr[i:i + 7] result = 0 n = 1 for b in bits[::-1]: result += n * int(b) n *= 2 print(result)