content
stringlengths
7
1.05M
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"get_pandas": "01_klass.ipynb", "avled_tverrvar": "03_sporre.ipynb", "df": "04_proc.ipynb", "freq": "04_proc.ipynb"} modules = ["klass.py", "sporre.py", "proc...
km = float(input('quantos Km rodas:')) dias = int(input('quantos dias utlizados:')) valor = (60*dias)+(km*0.15) print('o valor do aluguel é R${:.2f}'.format(valor))
# tb retorna valores booleanos set_1 = {1,2,3,4,5,6,7} set_2 = {0,3,4,5,6,7,8,9} set_3={1,2,3,4,7,0,9} print(set_1) print(set_2) print(set_3) set_4={77,33} print(set_4) print(set_2.isdisjoint(set_3)) print(set_3.isdisjoint(set_1)) print(set_3.isdisjoint(set_4))
# fail history: I tried so much because memory limit error(MLE) # it is better to process a number than a string T = int(input()) def solution(N): A = 0 B = 0 if N % 2 == 0: A, B = N//2, N//2 else: A, B = N//2+1, (N//2) _A = A _B = B len_N = len(str(N)) for i in range(l...
# -*- coding: utf-8 -*-# # ------------------------------------------------------------------------------- # Name: insertSort # Author: xiaohuo # Date: 2020/4/9 # Prohect_Name: data_structure # IEDA_Name: PyCharm # Create_Time: 23:31 # --------------------------------------------------...
class Solution: def reversePrefix(self, word: str, ch: str) -> str: if(ch in word): return ch+word.split(ch, 1)[0][::-1]+word.split(ch, 1)[1] else: return word
class Solution(object): def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ candidates.sort() return self.adding(candidates, 0, target, []) def adding(self, candidate...
''' QUESTION: 125. Valid Palindrome Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "rac...
"""Top-level package for pre-dl.""" __author__ = """skylight-hm""" __email__ = '465784936@qq.com' __version__ = '0.1.0'
__author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>" __date__ = "$May 18, 2015 22:05:20 EDT$"
#!/usr/bin/env python # # This is the Python 'module' that contains the # disposition criteria for Yara and jq filters the scanner framework # will work on. Each member is the name of a # high fidelity detection. # # default - Modules that are always run on a returned buffer value # triggers - List of tuples that are...
# authorization user not abonement class AutopaymentMailRu(object): def __init__(self, driver): self.driver = driver def enter_email(self, user_name="autopayment@mail.ru"): self.driver.find_element_by_xpath("//div/label[1]/input").send_keys(user_name) def enter_password(self, password="123...
frase = 'Curso em Vídeo Python' #FATIAMENTO print('FATIAMENTO') print(frase[9:15]) print(frase[9:]) print(frase[:9]) print(frase[9::3]) print(frase[9:21:2]) print('--'*20) #ANÁLISE print('ANÁLISE') print(len(frase),'caracteres') #caracteres print('--'*20) print(frase.count('o',0,13),'quantos >o< minu...
class CalculateVarianceService: def __init__(self, rows): self.rows = rows def call(self): """ Calculate the variance of numbers in the result column """ if not len(self.rows): return 0 data = [float(row[-1]) for row in self.rows] mean = sum(...
src = Split(''' port.c portISR.c port_aos.c startup.c panic.c backtrace.c vectors.S os_cpu_a.S ''') component = aos_component('andes', src) component.add_global_includes('./include')
class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: def twoSum(i,j): target2 = target - nums[i] - nums[j] left = j+1 right = n-1 while left < right: total = nums[left] + nums[right] if total == ta...
class CraigslistApartmentListing: def __init__(self): self.properties = { "datapid": None, "datetime": None, "title": None, "housing" : None, "ft" : None, "ad_url" : None, "hoo...
escolha = '' maioresdeidade = 0 quantidadeHomens = 0 MulheresMais20 = 0 idade = 0 sexo = '' while escolha != "N": idade = int(input("Digite sua idade: ")) if idade > 110 or idade < 0: print("Dado digitado é inválido, digite novamente") continue sexo = str(input("Digite seu sexo: ")).upper()...
#!/usr/bin/env python3 def rev_str(inp): str = "" length = len(inp) for i in range(length,0,-1): str = str + inp[i] return str str = input("Enter a string:") print(rev_str(str))
class ConnectorType(Enum, IComparable, IFormattable, IConvertible): """ An enumerated type listing all connector types for a connection enum ConnectorType,values: AllModes (16777215),AnyEnd (129),BlankEnd (128),Curve (2),End (1),EndSurface (17),Family (49),Invalid (0),Logical (4),MasterSurface (32),Node...
t = int(input()) while t > 0: t -= 1 n = int(input()) l = list(map(int, input().split())) l_ = {} for i in range(n): for j in range(i, n): ind_ = tuple(l[i:j+1]) if ind_ in l_: l_[ind_]+=1 else: l_[ind_]=1 l1= ...
# !/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created by Mengqi.Ye on 2020/12/21 """ class WhateverName: r""" Let this be a thread - safe object. """ def __init__(self): self.shared_env = None self.asynchronous_env_list = [] def init_hyper_parameters(self): pass ...
SSID1 = 'AP1' SALASANA1 = 'pass' SSID2 = 'AP2' SALASANA2 = 'word' MQTT_SERVERI = 'raspi' MQTT_PORTTI = '1883' MQTT_KAYTTAJA = 'user' MQTT_SALASANA = 'sala' CLIENT_ID = "ESP32-kaasuanturi" DHCP_NIMI = "ESP32-kaasuanturi" MQ135_PINNI = 36 SISA_LAMPO = b'kanala/sisa/lampo' SISA_KOSTEUS = b'kanala/sisa/kosteus'...
for _ in range(0,int(input())): s = input() es="" os="" for i in range(len(s)): if i % 2 == 0: es = es + s[i] else: os = os + s[i] print(es,os)
notas_acima7 =[] for i in range(1,11): notas = [] print(f"aluno {i}") for i in range(1,5): nota = notas.append(float(input(f"Digite a {i}º: "))) media = sum(notas) / len(notas) if media >= 7: notas_acima7.append(media) print(f"Obtivemos {len(notas_acima7)} alunos com nota maior ou ig...
class PC: def __init__(self): self.codigo = None self.caracteristico = '' self.sequencia = '' self.descricao = '' self.latitude = '' self.longitude = '' self.auxiliar = '' self.chave = '' self.tipo = ''
# -*- coding: utf_8 -*- class Stack(object): def __init__(self): self.values = [] def __len__(self): return len(self.values) def push(self, value): self.values.append(value) def pop(self): value = self.values[-1] del self.values[-1] return value
class Solution: def __init__(self): self.cache = {} def fib(self, N: int) -> int: if N in self.cache: return self.cache[N] if N < 2: self.cache[N] = N return N self.cache[N] = self.fib(N - 1) + self.fib(N - 2) return self.cache[N]
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """This module defines service related errors.""" class ServiceError(Exception): """Error raised from the service.""" class SessionNotF...
# This module is used to map the old Python 2 names to the new names used in # Python 3 for the pickle module. This needed to make pickle streams # generated with Python 2 loadable by Python 3. # This is a copy of lib2to3.fixes.fix_imports.MAPPING. We cannot import # lib2to3 and use the mapping defined there, becaus...
"""Constants for Graphvy""" SFDP_SETTINGS = dict(init_step=0.005, # move step; increase for sfdp to converge more quickly K=0.5, # preferred edge length C=0.3, # relative strength repulsive forces p=2.0, # repulsive force ...
class Solution: def findRadius(self, houses: List[int], heaters: List[int]) -> int: houses.sort() heaters.sort() heaters = [float('-inf')] + heaters p = 0 res = 0 for i in range(len(houses)): h = houses[i] while p+1 < len(heaters)-1 and heaters...
""" Matchers extract common logic into helpers that can be referenced in multiple rules. For example, if we write an osquery rule that is specific for the `prod` environment, we can define a matcher and add it to our rules' `matchers` keyword argument: from rules.matchers import matchers @rule('root_logins', logs=['...
def factorial(num): if num >= 0: if num == 0: return 1 return num * factorial(num -1) else: return -1
#Written by: Karim shoair - D4Vinci ( Dr0p1t-Framework ) #This module aims to run vbs scripts #Start def F522F(tobe): f = open("SMB_Service.vbs","w") f.write(tobe) f.write("\nDim objShell") f.write('\nSet objShell = WScript.CreateObject ("WScript.shell")') f.write('\nobjShell.run "cmd /c break>SMB_Service.vbs && ...
def get_power_set(numbers): if len(numbers) == 0: return [set([])] power_set = list() current_number = numbers[0] child_power_set = get_power_set(numbers[1:]) power_set.extend(child_power_set) for child_set in child_power_set: new_set = child_set.copy() new_set.add(cur...
print('=== DESAFIO 008 ===') print('Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros:') medida = float(input('Digite um valor em metros: ')) print(f'A medida de {medida}m equivale a {medida*100}cm e {medida *1000}mm') print() medida = float(input('Digite outro valor em ...
""" + = soma - = subtração * = multiplicação / = divisão // = divisão inteira ** = exponenciação ou potenciação % = resto da divisão () = parenteses """ print('Soma entre 10 + 10 =', 10 + 10) print('Subtracao entre 10 - 10 =', 10 - 10) print('Multiplicacao entre 10 * 10 =', 10 * 10) print('Divisao entre 10 / 10 =', 10...
def oxford_join(iterable, sep=", ", couple_sep=" and ", last_sep=", and ", quotes=False): """ Joins a list of string to a comma-separated sentence in a more english fashion than the builtin `.join()`. Examples: ```python from flashback.formatting import oxford_join oxford_join(...
for i in range(100, -1, -1): print(i) print("Décollage !")
def glyphs(): return 96 _font =\ b'\x00\x4a\x5a\x21\x4d\x58\x56\x46\x55\x46\x54\x47\x52\x54\x20'\ b'\x52\x56\x47\x55\x47\x52\x54\x20\x52\x56\x47\x56\x48\x52\x54'\ b'\x20\x52\x56\x46\x57\x47\x57\x48\x52\x54\x20\x52\x50\x58\x4f'\ b'\x59\x4f\x5a\x50\x5b\x51\x5b\x52\x5a\x52\x59\x51\x58\x50\x58'\ b'\x20\x52\x50\x59\x50\x5...
ll = [1, 2, 3, 4] def increment(x): return x + 1 print(map(increment, ll)) for x in map(increment, ll): print(x)
"""Seed module doc""" __descr__ = "seeddescription" __version__ = "seedversion" __license__ = "seedlicense" __author__ = u"seedauthor" __author_email__ = "seed@email" __copyright__ = u"seedcopyright seedauthor" __url__ = "seedurl"
def add_prune_to_parser(parser): parser.add_argument('-bp', '--batch-size-prune', default=128, type=int, metavar='N', help='mini-batch size (default: 256)') parser.add_argument('--prune', action='store_true', default=False, help='Prune the network') parser.add...
class Person: def __init__(self, name): self.name = name def say_hi(self): print('Hello, my name is', self.name) p = Person('Swaroop') p.say_hi() # The previous 2 lines can also be written as # Person('Swaroop').say_hi() str = 'abcdefghijklmnopqrstuvwxyz' s = slice(5, 20, 2) i = s.indices(10...
nome=str(input('Qual o seu nome:')).title().strip() if nome=='Carlos': print('Que nome bonito!') elif nome=='João' or nome=='Maria' or nome=='Enzo': print('Seu nome é bem popular no Brasil.') elif nome in 'Ana Juliana Valeime Dolores': print('Belo nome feminino.') else: print('Seu nome é bem comum.') pr...
""" Lucky Numbers Problem Description A lucky number is a number which has exactly 2 distinct prime divisors. You are given a number A and you need to determine the count of lucky numbers between the range 1 to A (both inclusive). Problem Constraints 1 <= A <= 5000 Input Format The first and only argument is an i...
a = 1 b = 2 def myfun(): x = 1 x print(myfun())
'''Custom exceptions''' class ConstructorException(Exception): '''Custom Constructor.io Exception''' class HttpException(ConstructorException): '''Custom HTTP exception''' def __init__(self, message, status, status_text, url, headers): # pylint: disable=too-many-arguments self.message = message ...
print('='*5, 'Conversor', '='*5) m = int(input('Digite uma distância em metros: ')) print(' A distância digitada foi: {}(m). \n Distância em centímetros: {}(cm). \n Distância em milímetro: {}(mm).'.format(m, m*100, m*1000)) print(f' Distância em quilômetros: {m/1000}(km).') print(f' Distância em hectômetro: {m/100}(hm)...
def health_calculator(age, apples_ate, cigs_smoked): awnser = (100 * age) + (apples_ate * 3.5) - (cigs_smoked * 2) print(awnser) buckys_data = [27, 70, 0] health_calculator(buckys_data[0], buckys_data[1], buckys_data[2]) health_calculator(*buckys_data)
num = input('Digite um número: ') unidade = num[3] dezena = num[2] centena = num[1] milhar = num[0] print('Analisando o número {}'.format(num)) print('Unidade: {}\nDezena: {}\nCentena: {}\nMilhar: {}'.format(unidade, centena, dezena, milhar))
# -*- coding: utf-8 -*- pinyin_bopomofo = { 'vacabulary': u'ㄅㄆㄇㄈㄉㄊㄋㄌㄍㄎㄏㄐㄑㄒㄓㄔㄕㄖㄗㄘㄙㄚㄛㄜㄝㄞㄟㄠㄡㄢㄣㄤㄥㄦㄧㄨㄩ', 'consonants': [ ('b', u'ㄅ'), ('p', u'ㄆ'), ('m', u'ㄇ'), ('f', u'ㄈ'), ('d', u'ㄉ'), ('t', u'ㄊ'), ('n', u'ㄋ'), ('l', u'ㄌ'), ('g', u'ㄍ'), ...
while True: try: x = int(input()) coe = list(map(int,input().split())) # the following method gives TLE #n = len(coe) #ans = 0 # for i in range(n-1): # ans += (coe[i]*(n-i-1)) * pow(x,n-i-2) # for optimization, we use horner's rule # http...
x,y,n = map(int, input().split()) for i in range(1,n+1): if not(i%x) and not(i%y): print("FizzBuzz") elif not(i%x): print("Fizz") elif not(i%y): print("Buzz") else: print(i)
class Solution: def findUnsortedSubarray(self, nums: List[int]) -> int: num2 = sorted(nums) start = 0 end = (len(nums) - 1) while(start <= end): if nums[start] == num2[start]: start += 1 elif nums[end] == num2[end]: end -= 1 ...
#La clase cell define cada celda del arreglo class cell(): def __init__(self, index, t = None): #El índice de esta celda en el arreglo self.index = index #Se toma la tortuga de dibujo self.t = t #El estado actual de la celda (True para negro y False para blanco) s...
primes: List[int] = [] captain: str # Note: no initial value! class Starship: stats: Dict[str, int] = {} header: str kind: int body: Optional[List[str]] header, kind, body = message def f(): a: int print(a) # raises UnboundLocalError # Commenting out the a: int makes it a NameError. a: int a: s...
""" &nbsp; &lsquo; &rsquo; &ldquo; &rdquo; &laquo; &raquo; &hellip; &ndash; &mdash; """
''' Created on 1.12.2016 @author: Darren '''''' Given an integer array nums, find the sum of the elements between indices i and j (i &le; j), inclusive. The update(i, val) function modifies nums by updating the element at index i to val. Example: Given nums = [1, 3, 5] sumRange(0, 2) -> 9 up...
shopping_list = ["milk", "pasta", "eggs", "spam", "bread","rice"] item_to_find = "spam" # use None when does not have a value found_at = None # last value in range is not included # for index in range(len(shopping_list)): # # len is length # if shopping_list[index] == item_to_find: # found_at = index #...
#47. Faça um programa que mostre todos os números pares entre 1 e 50. def Main047(): for x in range(0,51,2): print(f'{x}..', end=' ') Main047()
""" Implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). The function prototype should be: bool is_match(const char *s, const char *p) Some examples: i...
key = int(input("Enter shift key: ")) # noinspection DuplicatedCode encrypt_dict = {chr(a % 26 + 97): chr((a + key) % 26 + 97) for a in range(27)} decrypt_dict = {v: k for k, v in encrypt_dict.items()} to_encrypt = input("Enter text to encrypt:").lower() crypt = "" for i in to_encrypt: crypt += encrypt_dict[i] pr...
# @desc Triangle practice # @desc by Bernie '21 def pythagSolve(side_A, side_B): side_A = side_A ** 2 side_B = side_B ** 2 side_C= (side_A + side_B) ** 0.5 return side_C def main(): print(pythagSolve(8, 6)) print(pythagSolve(3, 4)) print(pythagSolve(4, 3)) print(pythagSolve(5, 12)) ...
# Needed to allow import # # Copyright (C) 2006 British Broadcasting Corporation and Kamaelia Contributors(1) # All Rights Reserved. # # You may only modify and redistribute this under the terms of any of the # following licenses(2): Mozilla Public License, V1.1, GNU General # Public License, V2.0, GNU Lesser Gener...
r=float(input())*3.5 pi=float(input())*7.5 a = (pi + r)/(11.0) print("MEDIA = {0:.5f}".format(a))
# py_adventure config scrypt # Стартовые навыки: # базовые навыки игрока: player_level = 1 # Уровень игрока player_strength = 1 # Сила игрока player_agility = 1 # Ловкость игрока player_vitality = 1 # Живучесть игрока player_intelligence = 1 # Интеллект игрока player_luck = 1 # Удача игрока # Скрытые навыки иг...
class QueryDictMixin(object): """ Simple query based dictionary mixin. This extends the standard Python dictionary objects to allow you to easily query nested dictionaries for a particular value. This is especially useful if you don't know the structure beforehand allowing you to dynamically r...
def view(): return dict() def list(): return dict(hunt_id=request.vars.hunt_id) def approve_request(): """Approves a request from another user.""" hunt_id = request.vars.hunt_id user = request.vars.user if hunt_id and user: return dict(hunt_id=hunt_id, user=user) def hunts_clients...
# coding: utf-8 """ Classification of Sugar exit codes. These are intended to augment universal exit codes (found in Python's `os` module with the `EX_` prefix or in `sysexits.h`). """ # The os.EX_* exit codes are Unix only so in the interest of cross-platform # compatiblility define them explicitly here. # # These c...
# Copyright (c) Vera Galstyan Jan 25,2018 people = ['jen', 'vera','phil','ofa','sarah'] languages = { 'jen': 'c', 'sarah':'python', 'edward':'ruby', 'phil':'python' } for name in people: if name in languages.keys(): print(name + " , thank you for your particiaption") else: print(name + " , you should ta...
opt_use_idf = "use_idf" opt_idf_boosting_threshold = "idf_boosting_threshold" opt_intensify_factor_m = "intensify_factor_m" opt_intensify_factor_p = "intensify_factor_p" opt_ceiling = "ceiling" opt_multiprocessing = "multiprocessing"
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"product_moment_corr": "encoding.ipynb", "get_model_plus_scores": "encoding.ipynb", "BlockMultiOutput": "encoding.ipynb", "preprocess_bold_fmri": "preprocessing.ipynb", "ge...
class Cella: def __init__(self, init_str): cols = {82: "red", 66: "blue", 71: "green", 32: "white"} self.x = init_str['userX'] self.y = init_str['userY'] self.color = cols[init_str['userVal']] def __repr__(self) -> str: str_ = f"x: {self.x}\ty: {self.y}\tcolor: {self.co...
def reduce_namedtuples_for_httpRequest(tpdict): kvfinal = {} for key in tpdict._fields: _val = getattr(tpdict, (key)) if isinstance(_val, list): kvfinal.update({key: _val.pop()}) else: kvfinal.update({key: _val}) return tpdict._replace(**kvfinal)
ROW_LIMIT = 5000 SUPERSET_WEBSERVER_PORT = 8088 SUPERSET_WEBSERVER_TIMEOUT = 60 SECRET_KEY = "XPivhoGODD" SQLALCHEMY_DATABASE_URI = "sqlite:////superset/superset.db" WTF_CSRF_ENABLED = True
def memorize(func): memo = {} def helper(x): if not (x in memo): memo[x] = func(x) return memo[x] return helper def tripnach(n): if n == 1: return 0 elif n == 2: return 0 elif n == 3: return 1 else: return tripnach(n-1) + tripnach...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Time-stamp: "2017-08-03 15:29:09 jlenain" """ Extras functions for FLaapLUC @author Jean-Philippe Lenain <mailto:jlenain@in2p3.fr> """ def met2mjd(met): """ Converts Mission Elapsed Time (MET, in seconds) in Modified Julian Day. Cf. http://fermi.gsfc.nasa...
Import("env") optimze_flags = [s for s in env.GetProjectOption("system_flags", "").splitlines() if s] linker_flags = [] common_flags = [ "-Wdouble-promotion", "-fsingle-precision-constant", "-fno-exceptions", "-fno-strict-aliasing", "-fstack-usage", "-fno-stack-protector", "-fomit-frame-pointer", "-fno-...
#! /usr/bin/env python3 """ This file contains variable and parameter definitions for the task-tool """ # Dict with field names with their sql data type, python data type, # display label and whether they are automatically generated task_fields = {} task_fields['name'] = { 'sql_type': 'TEXT PRIM...
# https://open.kattis.com/problems/pet largest = 0 index = 1 for i in range(5): s = sum(map(int, input().split())) if s > largest: largest = s index = i + 1 print('%s %s' % (index, largest))
# # PySNMP MIB module CTRON-SFPS-PKTMGR-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-SFPS-PKTMGR-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:15:27 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
# _____ _____ _____ _______ _____ # /\ \ /\ \ /\ \ /::\ \ /\ \ # /::\ \ /::\____\ /::\ \ /::::\ \ ...
class DbObject(object): def __init__(self, **args): for (column, value) in args.iteritems(): setattr(self, column, value)
__author__ = 'NovikovII' #!/usr/bin/env python3 # -*- coding: utf-8 -*- #print ("This line will be printed.") #Считать несколько имен людей одной строкой, записанных латиницей, через пробел, например: str = input() #Вывести их одной строкой в порядке возрастания «Anna Maria Peter». print(" ".join(sorted(str.split())))...
# -*- coding: utf-8 -*- """ @author: Anil Sen & Beyza Arslan """ font="Roboto" title_font_size=12 #bubbles' colors color_discrete_sequence_bubble=["blue", "red", "green", "magenta", "goldenrod"] #If you want the graphics prepared as html to be opened automatically, type True auto_open=False
list1=[1,2,4,5,6] print(list1[0:2]) print(list1[4]) list1[1]=9 print(list1) # adds data in a particular position #updating in list names=['Kiran','Ravi',1996,2001] print(names) print("Value at index 2",names[2]) names[2]=2013 print("New Value at index 2 now" , names[2]) print(names) print(names[:2]) print(names[1...
# creates the salt for security !!change this!! on the config.py file config = { 'secret': 'secret-sauce' }
''' Projeto: Dissecando uma variável ''' entrada = input('Digite algo: ') print('O tipo primitivo desse valor é: {}'.format(type(entrada))) print('Só tem espaço: {}'.format(entrada.isspace())) print('É número: {}'.format(entrada.isnumeric())) print('É alfabético: {}'.format(entrada.isalpha())) print('É alfanumérico: ...
""" the problem will be to find the longest substring in S that's in A. then replace with B idea1: check if A exist in S by iterate through all chars in s for all char in key in each key tatal number of keys = k total number of characters in s = n average length of keys = key_length # of occurances of keys in s: occu...
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: for i in range(len(nums)): index = abs(nums[i]) - 1 if nums[index] > 0: nums[index] = -nums[index] return [i + 1 for i in range(len(nums)) if nums[i] > 0]
''' This directory contains libraries and code for reading file formats using vendorized dependencies, not necessarily for MS vendor binary files. These vendorized libraries may still require other platform-dependent resources such as installed DLLs or 3rd party programs. Each reader has had it's author's license prep...
# Curso em vídeo - Desafio 052 - FOR ''' Faça um programa que leia um número inteiro e diga se ele é ou não um número primo. ''' c = 0 num = int(input('Digite um número: ')) if num <= 1: print(f'O número {num} não é primo.') else: for i in range(1, num+1): if (num % i) == 0: c += 1 ...
class MyService: def __init__(self, sso_registry): self.sso_registry = sso_registry def handle_request_correctly(self, request, token): if self.sso_registry.is_valid(token): return "hello world" return "please enter your login details" def handle_request_wrong...
class Contract(object): def __init__(self, provider): self._provider = provider self._number = None @property def provider(self): return self._provider.calculate() @property def number(self): return self._number @number.setter def number(self,value): self._number = value
class OpenTrackingSubstitutionTag(object): """The open tracking substitution tag of an SubscriptionTracking object.""" def __init__(self, open_tracking_substitution_tag=None): """Create a OpenTrackingSubstitutionTag object :param open_tracking_substitution_tag: Allows you to specify a ...
three = ['A', 'E', 'I', 'O', 'S', 'a', 'e', 'i', 'o', 's'] for k in range(int(input())): res = 1 for w in input(): if w in three: res *= 3 else: res *= 2 print(res)
def get_lines_from_file(path): with open(path, 'r') as fh: return fh.read().splitlines() def write_lines_to_file(path, lines): """ Takes a list of strings and writes them to <path> with a \n after each element :param path: str: The filepath to write to :param lines: list: The list of strin...
# -*- coding: utf-8 -*- def hello(): print("Hello World") return True def add_two_things(a, b): return a+b