content
stringlengths
7
1.05M
class Solution: def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: dp = [0]*n for i,j,k in bookings: dp[i-1]+=k if j!=n: dp[j]-=k for i in range(1,n): dp[i]+=dp[i-1] return dp
def buildFibonacciSequence(items): actual = 0 next = 1 sequence = [] for index in range(items): sequence.append(actual) actual, next = next, actual+next return sequence
""" Given two strings str1 and str2 of the same length, determine whether you can transform str1 into str2 by doing zero or more conversions. In one conversion you can convert all occurrences of one character in str1 to any other lowercase English character. Return true if and only if you can transform str1 into str2...
class Animation: def __init__(self, sprites, time_interval): self.sprites = tuple(sprites) self.time_interval = time_interval self.index = 0 self.time = 0 def restart_at(self, index): self.time = 0 self.index = index % len(self.sprites) def update(self, dt)...
NoOfLines=int(input()) for Row in range(0,NoOfLines): for Column in range(0,NoOfLines): if(Row%2==0 and Column+1==NoOfLines)or(Row%2==1 and Column==0): print("%2d"%(Row+2),end=" ") else: print("%2d"%(Row+1),end=" ") else: print(end="\n") #second code N...
# Module: FeatureEngineering # Author: Adrian Antico <adrianantico@gmail.com> # License: MIT # Release: retrofit 0.1.7 # Last modified : 2021-09-21 class FeatureEngineering: """ Base class that the library specific classes inherit from. """ def __init__(self) -> None: self.lag_args = {} ...
''' * Exercício: Desconto progressivo * Repositório: Lógica de Programação e Algoritmos em Python * GitHub: @michelelozada Para este exercício, procurei os preços de uma loja de produtos do ramo de lembrancinhas/souvenirs, que trabalhasse com o chamado desconto progressivo à medida que a quantidade encomendada ...
particles_file = "particles.txt" particle_coords = [] with open(particles_file, 'r') as pf: for y, line in enumerate(pf.readlines()): for x, char in enumerate(line): if char == '•': particle_coords.append((x, y)) def manhattan_distance(p1, p2): return abs(p1[0]-p2[0]) + abs...
# --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- def get_workspace_dependent_resource_location(location): if location == "centraluseuap": return "eastus" return lo...
# 1.5 One Away # There are three types of edits that can be performed on strings: # insert a character, remove a character, or replace a character. # Given two strings, write a function to check if they are one edit (or zero edits) away. def one_away(string_1, string_2): if string_1 == string_2: return ...
def permune(orignal, chosen): if not orignal: print(chosen) else: for i in range(len(orignal)): c=orignal[i] chosen+=c lt=list(orignal) lt.pop(i) orignal=''.join(lt) permune(orignal,chosen) orignal=orignal[:i]+c+orignal[i:] chosen=chosen[:len(chosen)-1] permune('lit','')
entity_id = 'sensor.next_train_to_wim' attributes = hass.states.get(entity_id).attributes my_early_train_current_status = hass.states.get('sensor.my_early_train').state scheduled = False # Check if train scheduled for train in attributes['next_trains']: if train['scheduled'] == '07:15': scheduled = Tru...
#!/usr/bin/env python3 ## Algorithm: # # We have ZSUM = Z(n) + Z(n-1) - Z(n-2), where: # - Z(n) = S(n) + P(n) # - S(n) = 1^k + 2^k + 3^k + … + n^k # - P(n) = 1^1 + 2^2 + 3^3 + … + n^n # The elements of Z(n-2) are also present in Z(n) and Z(n-1). # Hence, in ZSUM we effectively have the last elem...
def obter_dados_canal(lista): for _ in range(lista): nome,inscritos,monetizacao,ehpremium = input().split(';') inscritos = int(inscritos) monetizacao = float(monetizacao) ehpremium = ehpremium == 'sim' canais.append([nome, inscritos, monetizacao, ehpremium]) def calcular_bonificacao(valor...
# ------------------------------ # 300. Longest Increasing Subsequence # # Description: # Given an unsorted array of integers, find the length of longest increasing subsequence. # # Example: # Input: [10,9,2,5,3,7,101,18] # Output: 4 # Explanation: The longest increasing subsequence is [2,3,7,101], therefore the len...
#print('\033[34mOlá, mundo!\033[m') '''a = 3 b = 5 print('Os valores são \033[32m{}\033[m e \033[31m{}\033[m!!!'.format(a,b))''' '''nome = 'Guanabara' print('Olá ! Muito prazer em te conhecer, {}{}{}!!!'.format('\033[30m',nome,'\033[m'))''' nome = 'Guanabara' cores = {'limpa':'\033[m', 'azul':'\033[34m'...
class Node: def __init__(self,key=None,val=None,nxt=None,prev=None): self.key = key self.val = val self.nxt = nxt self.prev = prev class DLL: def __init__(self): self.head = Node() self.tail = Node() self.head.nxt = self.tail self.tail.prev = self...
class Command(object): def get_option(self, name): pass def run(self, ): raise NotImplementedError
a, b, c, d = map(int, input().split()) if a+b > c+d: print("Left") elif a+b < c+d: print("Right") else: print("Balanced")
# pyre-ignore-all-errors # TODO: Change `pyre-ignore-all-errors` to `pyre-strict` on line 1, so we get # to see all type errors in this file. # A (hypothetical) Python developer is having trouble with a typing-related # issue. Here is what the code looks like: class ConfigA: pass class ConfigB: some_attri...
""" Euclid's algorithm """ def modinv(a0, n0): """ Modular inverse algorithm """ (a, b) = (a0, n0) (aa, ba) = (1, 0) while True: q = a // b if a == (b * q): if b != 1: print("modinv({}, {}) = fail".format(a0, n0)) return -1 else: ...
# 10 Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos Dólares ela pode comprar. # Considere US$ 1,00 = R$ 3,27 ;( *2017 , R$ 5,36 em 2020. r = float(input('Digite um valor em Reais: ')) d = float(input('Digite o valor do Dólar na cotação atual: ')) e = float(input('Digite o valor do...
# # PySNMP MIB module CISCO-LWAPP-LOCAL-AUTH-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LWAPP-LOCAL-AUTH-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:48:42 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
class Human: def method(self): return print(f'Hello - {self}') @classmethod def classmethod(cls): return print('it is a species of "Homo sapiens"') @staticmethod def staticmethod(): return print('Congratulations') name_human = input('Enter your name: ') Human.method(na...
""" Created on Oct 13, 2019 @author: majdukovic """ class UrlGenerator: """ This class builds urls """ def __init__(self): self.urls_map = { 'POST_TOKEN': 'auth', 'GET_BOOKING': 'booking', 'POST_BOOKING': 'booking', 'PUT_BOOKING': 'booking', ...
class DeviceBaseException(Exception): ''' device base exception for device info ''' message_base = 'device exception' class DeviceNotFoundException(DeviceBaseException): def __init__(self, device_name=None): self.message = f'device {device_name} not found!' def __str__(self): ...
""" Views for the admin interface """ def includeme(config): config.scan("admin.views")
#!/usr/bin/env python # -*- coding: utf-8 -*- SUCCESS = "0" NEED_SMS = "1" SMS_FAIL = "2"
#Vigenere cipher + b64 - substitution ''' method = sys.argv[1] key = sys.argv[2] string = sys.argv[3] ''' def encode(key, string) : encoded_chars = [] for i in range(len(string)) : key_c = key[i % len(key)] encoded_c = chr(ord(string[i]) + ord(key_c) % 256) encoded_chars.append(encoded...
"""TCS module""" #def hello(who): # """function that greats""" # return "hello " + who def tcs(d): """TCS test function""" return d
def ForceDefaultLocale(get_response): """ Ignore Accept-Language HTTP headers This will force the I18N machinery to always choose settings.LANGUAGE_CODE as the default initial language, unless another one is set via sessions or cookies Should be installed *before* any middleware that check...
def mult_by_two(num): return num * 2 def mult_by_five(num): return num * 5 def square(num): return num * num def add_one(num): return num + 1 def apply(num, func): return func(num) result = apply(10, mult_by_two) print(result) print(apply(10, mult_by_five)) print(apply(10, square)) print(...
class BisectionMap(object): __slots__ = ('nodes') #//-------------------------------------------------------// def __init__(self, dict = {} ): self.nodes = [] for key, value in dict.iteritems(): self[ key ] = value #//----------------------------...
# YASS, Yet Another Subdomainer Software # Copyright 2015-2019 Francesco Marano (@mrnfrancesco) and individual contributors. # # 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.apa...
# Copyright 2017 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...
# -*- coding: utf-8 -*- test = 0 while True: test += 1 deposits = int(input()) if deposits == 0: break delta = 0 print("Teste %d" % test) for i in range(deposits): values = input().split() a = int(values[0]) b = int(values[1]) delta += a - b ...
#LEETOCDE: 104. Maximum Depth of Binary Tree class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def maxDepth(root: TreeNode) -> int: if not root: return 0 else: return max(1+maxDepth(root.left), 1+maxDepth(root.right)) #TODO: Implement iterativ...
# Definition for a binary tree node. # from typing import List # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def solve(self, preorder: List[int], inorder: List[int]) -> TreeNode: if not preorder: r...
#Tuplas, variável composta entre parenteses, são imutáveis lanche = ('hambúrger', 'suco', 'pizza', 'pudim') print(lanche) #todos os itens print(lanche[3]) #item na posição 4 (item 3) print(lanche[-1])#de trás p frente print(lanche[:2]) #vai do 0 até o 1, ignorando o ultimo elemente, neste caso o 2 print(lanche[1:3])#va...
# sorting algorithms # mergeSort def merge_sort(a): n = len(a) if n < 2: return a q = int(n / 2) left = a[:q] right = a[q:] # print("left : {%s} , right : {%s}, A : {%s}" % (left, right, a)) merge_sort(left) merge_sort(right) a = merge(a, left, right) # print("Result ...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"file_exists": "01_data.ipynb", "ds_file_exists": "01_data.ipynb", "filter_for_exists": "01_data.ipynb", "drop_missing_files": "01_data.ipynb", "add_ds": "01_data.ipynb", ...
# Copyright 2021 Jason Rumney # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
def cria_matriz(linhas, colunas, valor): matriz = [] for i in range(linhas): lin = [] for j in range(colunas): lin.append(valor) matriz.append(lin) return matriz def le_matriz(): linhas = int(input("Digite a quantidade de linhas: ")) colunas = int(input("Digite a qu...
def check(s): if s: print(s) else: print('文字列 s は None または 空文字 です。') check('') check(None) check('abcdefg')
ELECTION_HOME="election@home" ELECTION_VIEW="election@view" ELECTION_META="election@meta" ELECTION_EDIT="election@edit" ELECTION_SCHEDULE="election@schedule" ELECTION_EXTEND="election@extend" ELECTION_ARCHIVE="election@archive" ELECTION_COPY="election@copy" ELECTION_BADGE="election@badge" ELECTION_TRUSTEES_HOME="elect...
class IdentifierLabels: ID = "CMPLNT_NUM" class DateTimeEventLabels: EVENT_START_TIMESTAMP = "CMPLNT_FR_DT" EVENT_END_TIMESTAMP = "CMPLNT_TO_DT" class DateTimeSubmissionLabels: SUBMISSION_TO_POLICE_TIMESTAMP = "RPT_DT" class LawBreakingLabels: KEY_CODE = "KY_CD" PD_CODE = "PD_CD" LAW_B...
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: if len(A) <= 2: return len(A) ans = 2 dp = collections.defaultdict(set) for i, num in enumerate(A): if num in dp: for d, cnt in dp.pop(num): dp[num + d].a...
""" - Os valores podem ser formatados utilizando a função format ou até mesmo com f strings - As formatações obedecem as regras - :s -> Texto(strings) - :d -> Inteiros(int) - :f -> Números de pinto flutuante """ number1 = 10 number2 = 3 divison = number1 / number2 # Formatando em casas decimais com format print('{:.2f...
H, W = map(int, input().split()) A = [list(map(int, input().split())) for _ in range(H)] for i1 in range(H): for i2 in range(i1 + 1, H): for j1 in range(W): for j2 in range(j1 + 1, W): if A[i1][j1] + A[i2][j2] > A[i2][j1] + A[i1][j2]: print('No') ...
# s.remove(0) s = {1, 2, 3} s.remove(0) print(s) # bug as it should return a KeyError exception !!!
#! /usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2019/3/9 2:26 PM # @Author : xiaoliji # @Email : yutian9527@gmail.com """ 替换空格 >>> s = 'We are happy.' >>> replace_space(s) 'We%20are%20happy.' >>> s1 = 'We are very happy!' >>> replace_space(s1) 'We%20are%20very%20%20happy!' "...
""" Créations d'un dictionnaire vide""" d = dict() d = {} """ Création d'un dictionnaire avec des clés et valeurs""" d1 = {"P1" : ["Marie", "Smith"], "P2": ["John", "Smith"]} """ ajout d'un couple clé/valeur""" d1["P3"]= ["John", "Doe"] d1[-13]= "Hello world" # les clés et valeur peuvent être de n'importe quel type ...
# NÃO ESTÁ COMPLETO E NEM GARANTO CERTEZA EM TODOS OS VALORES LUCRO_LIQUIDO = { 'ambev_2019_1T.pdf': 2749.1, 'engie_2019_2T.pdf': 385.4, 'engie_2020_2T.pdf': 765.8, 'fleury_2019_3T.pdf': 94.8, 'fleury_2020_2T.pdf': -73.3, ...
class Contacts: def __init__(self, first_name=None, last_name=None, id=None, email_1=None, email_2=None, email_3=None, home_phone=None, mobile_phone=None, work_phone=None): self.first_name = first_name self.last_name = last_name self.mobile_phone = mobile_phone self...
# Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) # and lower right corner (row2, col2). # Range Sum Query 2D # The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), # which contains sum = 8. ...
""" CRUD system for Task Create, Read, Update, Delete """ # Create Task def create_task(): """ Create a task into the database """
''' The rows of levels in the .azr file are converted to list of strings. These indices make it more convenient to access the desired parameter. ''' J_INDEX = 0 PI_INDEX = 1 ENERGY_INDEX = 2 ENERGY_FIXED_INDEX = 3 CHANNEL_INDEX = 5 WIDTH_INDEX = 11 WIDTH_FIXED_INDEX = 10 SEPARATION_ENERGY_INDEX = 21 CHANNEL_RADIUS_INDE...
class ModelMinxi: def to_dict(self,*exclude): attr_dict = {} for field in self._meta.fields: name = field.attname if name not in exclude: attr_dict[name] = getattr(self,name) return attr_dict
""" ********** LESSON 1A ********** In the following code (lines 12-17), change x to 10, and then print out whether or not x is 10. """ x = 5 if x == 5: print("x is five!") else: print("x is not five...") """ Expected solution: x = 10 if x == 10: print("x is ten!") else: print("x is not ten..."...
# in not in 重载 # contains class MyList: def __init__(self, iterator): self.data = [x for x in iterator] def __repr__(self): return "MyList(%r)" % self.data def __contains__(self, e): return e in self.data l1 = MyList([1, 2, 3]) print(1 in l1) # True print(1 not in l1) # Fals...
"""248-Get current file name and path. Download all snippets so far: https://wp.me/Pa5TU8-1yg Blog: stevepython.wordpress.com requirements: None. origin: Various. """ # To get the name and path of the current file in use: print(__file__)
numbers = [] for i in range(1,101) : numbers.append(i) prime_number = [] for number in numbers : zero_mod = [] if number == 1 : continue else : for divider in range(1,number+1) : remain = number % divider if remain == 0 : zero_mod.append(divider) ...
def get_data(): data = [] data_file = open("data.txt") # data_file = open("test.txt") for val in data_file: data.append(val.strip()) data_file.close() cubes = {} for row in range(len(data)): for col in range(len(data[row])): if data[row][col] == '#': ...
# Write a python program to get a single string from two givan string, separated by a space # and swap a first two char of each string # Simple string = "abc", "xyz" # Expected result = "xyc", "abz" # st = "abc", "xyz" # print(st[1][:2] + st[0][-1:]) # print(st[0][:2] + st[1][-1:]) def char_swap(a, b): x = b[:2...
''' Write a function that takes variable number of arguments and returns the sum , sum of squares, sum of cubes, average, multiplication, multiplication of squares, multiplication of cubes of that numbers. ''' def calc(*a): sum = 0 mul = 1 sumSQR = 0 sumCubes = 0 mulSQR = 1 mulCubes...
# URLs MEXC_BASE_URL = "https://www.mexc.com" MEXC_SYMBOL_URL = '/open/api/v2/market/symbols' MEXC_TICKERS_URL = '/open/api/v2/market/ticker' MEXC_DEPTH_URL = '/open/api/v2/market/depth?symbol={trading_pair}&depth=200' MEXC_PRICE_URL = '/open/api/v2/market/ticker?symbol={trading_pair}' MEXC_PING_URL = '/open/api/v2/...
CONFUSION_MATRIX = "confusion_matrix" AP = "ap" DETECTION_AP = "detection_mAP" DETECTION_APS = "detection_APs" MOTA = "MOTA" MOTP = "MOTP" FALSE_POSITIVES = "false_positives" FALSE_NEGATIVES = "false_negatives" ID_SWITCHES = "id_switches" AP_INTERPOLATED = "ap_interpolated" ERRORS = "errors" IOU = "iou" BINARY_IOU = "b...
class GitRequire(object): def __init__(self, git_url=None, branch=None, submodule=False): self.git_url = git_url self.submodule = submodule self.branch = branch def clone_params(self): clone_params = {"single_branch": True} if self.branch is not None: clone_p...
# Object in Python do not have a fixed layout. class X: def __init__(self, a): self.a = a x = X(1) print(x.a) # 1 # For example, we can add new attributes to objects: x.b = 5 print(x.b) # 5 # Or even new methods into a class: X.foo = lambda self: 10 print(x.foo()) # 10 # Or even changing base classes d...
# encoding: utf-8 # module _locale # from (built-in) # by generator 1.145 """ Support for POSIX locales. """ # no imports # Variables with simple values ABDAY_1 = 131072 ABDAY_2 = 131073 ABDAY_3 = 131074 ABDAY_4 = 131075 ABDAY_5 = 131076 ABDAY_6 = 131077 ABDAY_7 = 131078 ABMON_1 = 131086 ABMON_10 = 131095 ABMON_11 =...
class Solution: # @param A : list of strings # @return a strings def longestCommonPrefix(self, A): common_substring = "" if A: common_substring = A[0] for s in A[1:]: i = 0 l = len(min(common_substring, s)) while i < l: ...
# Link to the problem: https://www.codechef.com/LTIME63B/problems/EID def EID(): _ = input() A = list(map(int, input().split())) A.sort() size = len(A) diff = A[size - 1] for i in range(size - 1): tempDiff = A[i + 1] - A[i] if tempDiff < diff: diff = tempDiff return diff def main(): T = ...
monster = ['fairy', 'goblin', 'ogre', 'werewolf', 'vampire', 'gargoyle', 'pirate', 'undead'] weapon1 = ['dagger', 'stone', 'pistol', 'knife'] weapon2 = ['sword', 'war hammer', 'machine gun', 'battle axe', 'war scythe'] scene = ['grass and yellow wildflowers.', 'sand and sea shells', ...
# if-elif-else ladder ''' if is a conditional statement that is used to perform different actions based on different conditions. ''' if (5 < 6): print('5 is less than 6') print() print() a = 6 if (a == 5): print('a is equal to 5') else: print('a is not equal to 5') print() print() a = 6 b = 5 if ...
def conta_votos(lista_candidatos_numeros, lista_votos, numeros): brancos = 0 nulos = 0 contagem_geral = [] for i in range(len(lista_candidatos_numeros)): contagem_individual = [lista_candidatos_numeros[i][0], numeros[i], 0] contagem_geral.append(contagem_individual) for v in votos: ...
global T_D,EPS,MU,ETA,dt T_D = 12.0 L0 = 1.0 EPS = 0.05 # Osborne 2017 params MU = -50. ETA = 1.0 dt = 0.005 #hours
class Solution: def numberOfArithmeticSlices(self, nums: List[int]) -> int: if len(nums)<3: return 0 output=[] slices=[nums[0], nums[1]] for num in nums[2:]: if num-slices[-1]==slices[1]-slices[0]: slices.append(num) else: ...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: if not root: return True return self.isSymmetricHelper(root.left, root.r...
value = int(input("请输入你的成绩:")) if value > 60: print("你的成绩及格了") else: print("你的成绩有待重新确认")
# Copyright 2019 The TensorFlow 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 applica...
### Insertion Sort - Part 2 - Solution def insertionSort2(nums): for i in range(1, len(nums)): comp, prev = nums[i], i-1 while (prev >= 0) and (nums[prev] > comp): nums[prev+1] = nums[prev] prev -= 1 nums[prev+1] = comp print(*nums) n = int(input()) nums = ...
### CLASSES class TrackPoint: def __init__(self, time, coordinates, alt): self.time = time self.coordinates = coordinates self.alt = alt def __repr__(self): return "%s %s %dm" % (self.time.strftime("%H:%m:%S"), self.coordinates, self.alt)
VARS = [ {'name': 'script_name', 'required': True, 'example': 'fancy_script'}, {'name': 'description', 'example': 'Super fancy script'} ]
# Programação Orientada a Objetos # AC01 ADS-EaD - Números especiais # # Email Impacta: lucas.2103070@aluno.faculdadeimpacta.com.br def eh_primo(n): qtd_divisores = 0 candidato = 1 while candidato <= n: if n % candidato == 0: qtd_divisores += 1 candidato += 1 if qtd_divis...
def test_api_docs(api_client): rv = api_client.get("/apidocs", follow_redirects=True) assert rv.status_code == 200 assert b"JournalsDB API Docs" in rv.data
# Solution A class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: i = 0 name += "1" for s in typed: if s == name[i]: i += 1 elif s != name[i - 1]: return False return i == len(name) - 1 # Solution B clas...
#!/usr/bin/env python # coding: utf-8 # # Re-implement some Python built-in functions # In[1]: def my_max(l1): max_number = l1[0] for number in l1: if number > max_number: max_number = number return max_number # In[2]: def my_min(l1): min_number = l1[0] for number in l1: ...
dinheiro = int(input('Quanto será sacado? ')) total = dinheiro contar_as_cedulas = 0 cedula = 50 while True: if total >= cedula: total -= cedula contar_as_cedulas += 1 else: if contar_as_cedulas > 0: print('Serão {} cedulas de {}'.format(contar_as_cedulas, cedula)) ...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def __init__(self): self.maxval=0 def countbst(self,root,minval,maxval): if not root: return...
#!/usr/bin/python """ Custom counting functions """ def ptcount(particledatalist, ptypelist, ptsums, ypoint=0.0, deltay=2.0): """ Particle pT counter for mean pT calculation. Input: particledatalist -- List of ParticleData objects ptypelist -- List of particle types for which to do the count ...
print('\033[1m>>> CALCULADORA DE JUROS <<<\033[m') parcela = float(input('- VALOR DA PARCELA: R$ ')) dias = int(input('- DIAS DE ATRASO: ')) juros = float(input('- JUROS AO DIA: ')) acrescimo = ((juros*dias) * parcela) / 100 total = parcela + acrescimo print('\033[1mRESULTADO:\033[m\n' f'ACRÉSCIMO: R$ {acr...
# Copyright 2021 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. register_npcx_project( project_name="herobrine_npcx9", zephyr_board="herobrine_npcx9", dts_overlays=[ "gpio.dts", "battery.dts...
class No: def __init__(self, valor): self.valor = valor self.esquerda = None self.direita = None def mostra_no(self): print(self.valor) class ArvoreBinariaBusca: def __init__(self): self.raiz = None self.ligacoes = [] def inserir(self, valor): novo = No(valor) # Se a árvore e...
num1=num2=res=0 def cn(): global canal canal="CFB Cursos" cn() print(canal)
SPARK_SESSION = {"default": {}} """ PySpark session definition Local Session:: SPARK_SESSION = { "default": { "master": "local", "appName": "Word Count", "config": { "spark.some.config.option": "some-value", } } } Cluster:: ...
class Db: def __init__(self): self._db = None self._connection = None @property def db(self): return self._db @db.setter def db(self, db): self._db = db async def _make_connection(self): self._connection = await self.db.acquire() async def _close_c...
# -*- coding: utf-8 -*- # 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, softw...
"""A string is good if there are no repeated characters. Given a string s​​​​​, return the number of good substrings of length three in s​​​​​​. Note that if there are multiple occurrences of the same substring, every occurrence should be counted. A substring is a contiguous sequence of characters in a string. E...
# # PySNMP MIB module CISCO-MEDIATRACE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-MEDIATRACE-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:07:08 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
# DFS class Solution: def numIslands(self, grid: List[List[str]]) -> int: if not grid: return 0 m, n = len(grid), len(grid[0]) dirs = [(0,1), (0,-1), (1,0), (-1,0)] res = 0 for i in range(m): for j in range(n): if grid[i][j] == '1': ...