content
stringlengths
7
1.05M
def seq_search(lst, element): pos = 0 found = False while pos < len(lst) and not found: if lst[pos] == element: found = True else: pos += 1 return found arr = [1,2,3,4,5,56] print(seq_search(arr,3)) print(seq_search(arr,56)) print(seq_search(arr,1)) print(se...
#!/usr/bin/env python3 # https://abc061.contest.atcoder.jp/tasks/abc061_b n, m = map(int, input().split()) a = [0] * n for _ in range(m): u, v = map(int, input().split()) a[u - 1] += 1 a[v - 1] += 1 for x in a: print(x)
languages = [ { 'language' : 'lang_cpp', 'display_name' : 'C++', 'build_configurations' : [ { 'compiler': 'msvc', 'builder': 'build_cpp_sources_with_msvc', }, { 'compiler': 'gcc', 'bui...
""" This module contains the various utilities that may be useful in lab anaylysis and operating on the waveforms. """
# Python Comments # Single line comment print("End of line comment, which will ignore anything after # and treat is as comment \n\n") # End of line comments # This # is # Multi line comments print("Multi line comment is nothing but using the # to be prefixed at start of the line.\n\n") """ Well this is also a...
# %% # Ensure the target is unchanged # assert all(y_tr.sort_index() == original_y_train.sort_index()) # Ensure the target is unchanged (unshuffled!) # assert all(y_tr == original_y_train) # %% Predict on X_tr for comparison y_tr_predicted = clf_grid_BEST.predict(X_tr) # original_y_train.value_counts() # y_tr.cat.cod...
def fun(a,b,c,d,e,f): if(a>=d and b>=e and c>=f) and (a>d or b>e or c>f): return 1 elif(a<=d and b<=e and c<=f) and (a<d or b<e or c<f): return 1 return 0 for i in range(int(input())): a = [int(j) for j in input().split()] b = [int(j) for j in input().split()] c = [int(j) for j ...
""" Demos on some detailed use cases for Dragonfly. We use domains and configurations from an electrolyte design task, but use synthetic functions instead. -- kirthevasank """
class TwoSum: def __init__(self, arr , target: int) : self.arr = arr self.target = target def get_to_sum(self): i = 0 while i<len(arr): val = target - arr[i] if val in arr[i+1:]: return [i, arr.index(val, i+1)] else: ...
def all_are_none(*args) -> bool: """ Return True if all args are None. """ return all([arg is None for arg in args]) def none_are_none(*args) -> bool: """ Return True if no args are None. """ return not any([arg is None for arg in args]) def any_are_not_none(*args) -> bool: """ ...
mod = pow(10, 9)+7 match = dict() for i in range(26): match[chr(i+97)] = i+1 def rabin_karp(text, pattern): n, m = len(text), len(pattern) if n < m: return False hash_pattern = 0 i = 0 for p in pattern[::-1]: hash_pattern = (hash_pattern + pow(26, i, mod) * match[p]) % mod ...
class GenericRetriesHandler: def __init__(self, *args, **kwargs): self.count = 0 def is_eligible(self, response): raise NotImplementedError def increment(self): self.count += 1
class Solution(object): def rotateString(self, A, B): """ :type A: str :type B: str :rtype: bool """ if not all([A, B]): return A == B if len(A) != len(B): return False pos = B.rfind(A[0]) while pos != -1: if...
def get_answer(lines): # print(lines) lowwater = 0 highwater = len(lines) - 1 j = highwater # print(f"highwater= {highwater}, lowwater= {lowwater}") while lowwater < j: sum = lines[lowwater] + lines[j] if sum == 2020: return(lines[lowwater] * lines[j]) elif ...
#=========================================================================== # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # This library is distributed in the hope tha...
defaults = { "Wiki homepage": "Contents", "Default tab on page load": ("History", "Articles", "Tabs"), "Save pasted images as": ("JPEG", "PNG"), } DB_SCHEMA = 0 PRODUCT_NAME = "Folio" PRODUCT_VERSION = "0.0.7a" PRODUCT = f"{PRODUCT_NAME} ver {PRODUCT_VERSION}"
qtd=(int(input("Enter with the quantity: "))) if(qtd<1): while True: print("Error! The quantity needs to be positive") qtd=(int(input("Enter with the quantity: "))) if not(qtd<1): break def converter(number): return number*-1 number=[] for i in range(qtd): ...
# Largest palindrome product # Problem 4 # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is # 9009 = 91 × 99. # # Find the largest palindrome made from the product of two 3-digit numbers. LOWER = 100 UPPER = 999 def is_palindrome(num): snum = s...
#Ex060 Faça um programa que leia um número qualquer e mostre o seu fatorial. #Ex: #5!=5x4x3x2x1=120 n = int(input('Qual o valor inteiro você quer saber o fatorial? \n')) c = n f = 1 print('Calculando {}!= '.format(n), end='') while c > 0: print(f'{c}', end='') print(' x ' if c >1 else ' = ', end='') f *= c ...
class Bar: def __init__( self, ticker: str, ts: int, open: float, high: float, low: float, close: float, adj_close: float, volume: int, _id: int = None ) -> None: self.id = _id self.ticker = ticker self.date ...
"""Hello World https://exercism.org/tracks/python/exercises/hello-world """ def hello() -> str: """Hello. Returns: str: Hello world response. """ return "Hello, World!"
#quick Sorting def quick_sort(list): if len(list)<2: return list else: pivot=int(list.pop()) right_items,left_items=[],[] for item in list: if int(item)>pivot: right_items.append(int(item)) else: left_items.append(int(item))...
TABLE_CLOTH_DELTA = 0.6 TABLE_CLOTH_TEXTILE_PRICE = 7 CARRE_TEXTILE_PRICE = 9 USD_TO_BGN = 1.85 number_of_tables = int(input('Rectangular tables')) table_length = float(input('Tables length')) table_width = float(input('Table width')) area_table_cloth = (table_length + TABLE_CLOTH_DELTA) * (table_width + TAB...
# 插值 f-string,插值表达式 key = 'my_var' value = '1.234' formatted = f'{key}: {value}' print(formatted) formatted = f'{key} = {value}' print(formatted)
# Copyright 2009-2017 Ram Rachum. # This program is distributed under the MIT license. data = '''James John Robert Michael William David Richard Charles Joseph Thomas Christopher Daniel Paul Mark Donald George Kenneth Steven Edward Brian Ronald Anthony Kevin Jason Matthew Gary Timothy Jose Larry Jeffrey Frank Scott Er...
n = int(input()) grid = [] for i in range(n): grid.append([int(x) for x in input().split(' ')]) def valid(g): for y in range(n): for x in range(n): if (x+1 < n): if not (g[y][x] < g[y][x+1]): return False if (y+1 < n): if not ...
# https://atcoder.jp/contests/math-and-algorithm/tasks/typical90_n n = int(input()) aa = list(sorted(map(int, input().split()))) bb = list(sorted(map(int, input().split()))) print(sum([abs(aa[i] - bb[i]) for i in range(n)]))
nmetros = float(input("Digite o numero em metros :")) ncent = (nmetros* 100) nmili = (nmetros * 1000) print("O numero digitado em centimetros e milimitros é de respectivamente : ", ncent, nmili)
class RegistObject(object): def __init__(self,object_name,scope=None,params=None): self.object_name=object_name self.scope=scope self.params=params class RegistObjectName(object): def __init__(self,object_name,scope=None): self.object_name=object_name self.scope=scope c...
# LEER panchofile = open('panchofile.txt', 'w') print(panchofile) # r = panchofile.readlines() # panchofile.write("\nVerso 1") panchofile.close()
"""Constants for readme.""" # Base component constants DOMAIN = "readme" DOMAIN_DATA = f"{DOMAIN}_data" VERSION = "0.2.1" REQUIRED_FILES = [ "translations/en.json", "const.py", "config_flow.py", "default.j2", "manifest.json", "services.yaml", ] ISSUE_URL = "https://github.com/custom-components/r...
exp = str(input("Digite a expressão: ")) prnt = [] for simb in exp: if simb == '(': prnt.append('(') elif simb == ')': if len(prnt) > 0: prnt.pop() else: prnt.append(')') break if len(prnt) == 0: print("Sua expressão está válida!") else: print...
class Foo: @staticmethod def bar(x): """bar() can be called without instantiating from Foo""" print(x, "on class") def nbar(self, x): """nbar() can be used on an instance of Foo""" print(x, "on", self) Foo.bar("class bar") # Foo.nbar("class nbar") # Foo.nbar(Foo, "class nb...
"""Double linked list class defined.""" class DoublylinkedList: def __init__(self): self.head = None self.tail = None def set_head_to(self, node): if self.head == node: return elif self.head is None: self.head = node self.tail = node ...
palavras = ('aprender','programar','linguagem','python','curso','gratis','estudar','praticar','trabalhar','mercado','programador','futudo','velejar','dingue','ancora','vento','represa','alheta','fiel') for pal in palavras: print('\nNa palavra {} temos as vogáis: '.format(pal),end='') # print(pal) for i in ...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @author: jayzhen @license: Apache Licence @version: v1.0 @contact: jayzhen_testing@163.com @site: http://blog.csdn.net/u013948858 @file: __init__.py.py @time: 2017/10/27 22:50 """
class State: def __init__(self, words_following_dict, name, type_dict): self.words_following_dict = words_following_dict # Dictionary of words which lead to new states self.name = name # name of the state self.type_dict = type_dict #dict of type "State_name" : State to avoid circular problem...
#################################################################################### # Larabot Discord Bot # MIT License # Copyright (c) 2017 Devitgg # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the So...
class Solution(object): def longestValidParentheses(self, s): """ :type s: str :rtype: int """ k = [0] c = 0 ans = 0 for i in range(len(s)): if s[i] == '(': c += 1 else: c -= 1 k.appen...
employee_one = int(input()) employee_two = int(input()) employee_three = int(input()) people_count = int(input()) all_employees = employee_one + employee_two + employee_three # this many per hour people_answered = 0 hours_needed =0 while people_answered < people_count: hours_needed += 1 if hours_needed % 4 =...
def loadyaml(path): ''' Read the config file with yaml :param path: the config file path :return: bidict ''' doc = [] if os.path.exists(path): with codecs.open(path, 'r') as yf: doc = yaml.safe_load(yf) return doc
n = 0 for i in range(1,6): n = n + 1 print(n) print('\n') n = 0 for i in range(1,11): n = n + 1 print(n) print('\n') n = 0 for i in range(0,6): n = n+i**2 print(n) print('\n') n = 0 for i in range(0,6): n = n+i**3 print(n) print('\n') n = 0 for i in range(0,6): n = n + (i - 1)**2 print(n) print('\n')...
# # PySNMP MIB module MY-TC (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MY-TC # Produced by pysmi-0.3.4 at Wed May 1 14:16:14 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, 09:23:15) # ...
class Organism: alive = True class Animal(Organism): def eat(self): print("This animal is eating!") class Dog(Animal): def bark(self): print("This dog is barking!") dog = Dog() print(dog.alive) dog.eat() dog.bark()
def test_firstname_lastname_address(app): contact_from_home_page = app.contact.get_contact_list()[0] contact_from_edit_page = app.contact.get_contact_info_from_edit_page(0) assert contact_from_home_page.firstname == contact_from_edit_page.firstname assert contact_from_home_page.lastname == contact_from_...
_nota=int(input("Informe uma nota de 0 a 10:\n")) while _nota> 10: print("Erro! Valor inválido.") _nota=int(input("Informe uma nota de 0 a 10:\n"))
""" 34. Search for a Range """ class Solution: def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ l, r = 0, len(nums)-1 while l<r and nums[l]!=target: mid = (l+r)>>1 if nu...
def multiples (): y = list (range(1,21)) for x in y: if x % 2 == 0: print(x) multiples()
n=str(input("Enter the string")) le=len(n) count=0 for i in range(le-1): for j in range(le): if n[j]==n[i]: count=count+1 else: continue print("%s count is :%d"%(n[i],count)) count=0
statusT = """ VAULT: {} KEY: {} PROJECT: {} ENV: {} AWS/profile? {} AWS/key? {} AWS/secret? {}""" helpT = """ 1. Run setup 2. Check that AWS environment variables for profile OR key+secret are set """
# Databricks notebook source # MAGIC %md # MAGIC References:<br> # MAGIC https://docs.azuredatabricks.net/user-guide/secrets/secrets.html<br> # MAGIC https://docs.azuredatabricks.net/spark/latest/data-sources/azure/azure-storage.html<br> # MAGIC https://docs.azuredatabricks.net/user-guide/dbfs-databricks-file-system.ht...
#!/usr/bin/env python3 """module: syllable_filter author: R Steiner license: MIT, copyright (c) 2016 R Steiner Contains class SyllableFilter. """ class SyllableFilter: """This script takes a list of words and returns only those with the specified number of syllables. Syllables will be counted heuristically,...
# -*- coding: utf-8 -*- class ConnectorException(Exception): pass class UnsupportedDriver(ConnectorException): def __init__(self, driver): message = 'Driver "%s" is not supported' % driver super(UnsupportedDriver, self).__init__(message)
# -*- coding: utf-8 -*- #------------------------------------------------------------------ # LEIA E PREENCHA O CABEÇALHO # NÃO ALTERE OS NOMES DAS FUNÇÕES # NÃO APAGUE OS DOCSTRINGS # NÃO INCLUA NENHUM import ... #------------------------------------------------------------------ ''' Nome: Rafael Prudêncio Leit...
""" Useful annotators """ def auto_str(cls): """ Add implementation of __str__ and __repr__ functions to a class """ def __str__(self): return type(self).__name__ + '{' + ','.join(f'{k}={str(v)}' for k, v, in vars(self).items()) + '}' def __repr__(self): return type(self).__qualn...
# added but not implemented. Not convinced its needed yet, """ from fabric.api import local myapp = "DictionaryOfNewZealandEnglish" def prepare_deployment(branch_name): local('python manage.py test ' + myapp) local('git add -p && git commit') local('git checkout master && git merge ' + branch_name) fro...
# Given an array of integers nums and an integer target, return indices of the t # wo numbers such that they add up to target. # # You may assume that each input would have exactly one solution, and you may n # ot use the same element twice. # # You can return the answer in any order. # # # Example 1: # # ...
class TransactCounterSingleton(object): def __new__(cls): if not hasattr(cls, 'instance'): cls.instance = super(TransactCounterSingleton, cls).__new__(cls) cls.instance.count = 0 return cls.instance @staticmethod def get_id(): result = TransactCounterSingleto...
"""Constants for the Integration - Riemann sum integral integration.""" DOMAIN = "integration" CONF_ROUND_DIGITS = "round" CONF_SOURCE_SENSOR = "source" CONF_UNIT_OF_MEASUREMENT = "unit" CONF_UNIT_PREFIX = "unit_prefix" CONF_UNIT_TIME = "unit_time" METHOD_TRAPEZOIDAL = "trapezoidal" METHOD_LEFT = "left" METHOD_RIGHT...
# Given the availability time slots arrays slots1 and slots2 of two people and a meeting duration duration, # return the earliest time slot that works for both of them and is of duration duration. # If there is no common time slot that satisfies the requirements, return an empty array. # The format of a time slot is a...
BOT_NAME = 'GroeneScrapy' SPIDER_MODULES = ['GroeneScrapy.spiders'] NEWSPIDER_MODULE = 'GroeneScrapy.spiders' LOG_LEVEL = 'ERROR' GROENE_USERNAME = 'Enter your e-mail address here' GROENE_PASSWORD = 'Enter your password here' GROENE_PDF_PATH = 'GroenePDF'
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Show that a list comprehension is just a 'for loop,' where you save the output to a variable. """ # A 'for loop' for x in range(0, 13): print(x) # The same loop, as a 'list comprehension' [x for x in range(0, 13)] # To save the output of the loop, we would do thi...
#!/usr/bin/env python3 def blocks(height, time): offset = 2 * height - 2 return time * height if time % offset == 0 else 0 if __name__ == '__main__': lines = [line.split(': ') for line in open('input').read().split('\n')] heights = {int(pos): int(height) for pos, height in lines} print(sum(map(l...
class Event: circle_event = False @property def x(self): return 0 @property def y(self): return 0 def __lt__(self, other): if self.y == other.y and self.x == other.x: return self.circle_event and not other.circle_event if self.y == other.y: ...
#Váriavel composta do tipo dicionário. dict() aluno = dict() aluno["aluno"] = str(input("Aluno(a): ").upper()) aluno["media"] = float(input("Média: ")) if aluno["media"] >= 7: aluno["situação"] = "Aprovado" elif 7 > aluno["media"] >= 5: aluno["situação"] = "Recuperação" else: aluno["situação"] = "Reprovado"...
####DEFINE COLOR SWITCH def code_to_class_string(argument): switcher = { 'n02691156': "airplane", 'n02419796': "antelope", 'n02131653': "bear", 'n02834778': "bicycle", 'n01503061': "bird", 'n0292...
class Grid: def __init__(self, matrix=None): if (matrix): self.matrix = matrix else: self.matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] def __str__(self): return str(str(self.matrix[0][0]) + str(self.matrix[1][0]) + str(self.matrix[2][0]) + "\n" + ...
class HttpCodes(dict): http_100 = (100, 'Continue') http_101 = (101, 'Switching Protocols') http_102 = (102, 'Processing (WebDAV)') http_200 = (200, 'OK') http_201 = (201, 'Created') http_202 = (202, 'Accepted') http_203 = (203, 'Non-Authoritative Information') http_204 = (204, 'No Conte...
#!/usr/bin/env python # -*-coding: utf-8 -*- #config.py #Dave Landay #LAST UPDATED: 01-01-2020 DEBUG = True SQLALCHEMY_DATABASE_URI = '<PATH_TO_DATABASE.DB>' SECRET_KEY = '<SOME_SECRET_KEY>'
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"ShuffleBlock": "00_core.ipynb", "OprtType": "00_core.ipynb", "conv_unit": "00_core.ipynb", "conv": "00_core.ipynb", "relu_conv_bn": "00_core.ipynb", "conv_bn_relu...
# Open input, and split each line into list of 0 or 1 integers with open('./input', encoding='utf8') as file: vent_lines = [[[int(val) for val in endpoint.split(',')] for endpoint in line.split(' -> ')] for line in file] dims = [0, 0] for line in vent_lines: for val in line: dims[0] ...
""" https://docs.opencv.org/master/d4/d86/group__imgproc__filter.html#ga67493776e3ad1a3df63883829375201f void cv::morphologyEx ( InputArray src, OutputArray dst, int op, InputArray kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, const Scalar & ...
'''https://leetcode.com/problems/plus-one/''' class Solution: def plusOne(self, digits: List[int]) -> List[int]: digits.reverse() ans = [] c = 1 for d in digits: t = d+c if t>9: t = t-10 c=1 else: c=...
""" Pattern: Enter the number of rows: 5 EEEEE DDDD CCC BB A """ print('Alphabet Pattern: ') number_rows=int(input('Enter number of rows: ')) for row in range(1,number_rows+1): print(' '*(row-1),str(chr(65+(number_rows-row))+'')*(number_rows+1-row))
class Action(): """ ``Action`` own the code intended for modify synergies objects. """ _listen = None """The ``Event`` class to listen.""" _depend = [] """List of ``Action`` who need to be executed before this.""" @classmethod def get_listened_class(cls): """ :retu...
x = 5 print(5) print(x) print('x') message = 'Hello World!' print(message) message = 'Goodbye cruel world...' print(message)
''' dummy recommender ''' def recommend_random(movies, k=10): """ Dummy recommender that recommends a list of random movies. Ignores the actual query. """ return movies['title'].sample(k).to_list()
class Dobradura: def get_dobrar(self, numero_dobradura): self.numero_dobradura = 1 if type(numero_dobradura) == int and numero_dobradura > 0: for i in range(0,numero_dobradura): self.numero_dobradura = 2**numero_dobradura return self.numero_dobradura el...
""" Wrapper """ class Trainer(object): def __init__(self, cfg, model, dataloader_dict, logger): self.cfg = cfg self.modes = self.cfg.MODES self.model = model self.dataloader_dict = dataloader_dict self.logger = logger self.current_epoch = cfg.RESUME_EPOCH_ID if cfg....
cont = s = media = maior = menor = 0 op = 'S' while op == 'S': num = int(input('Digite um número: ')) cont += 1 s += num if cont == 1: maior = menor = num else: if num > maior: maior = num elif num < menor: menor = num op = str(input('Quer Continu...
# Apresentação print('Programa para identificar se 3 medidas permitem formar um triângulo') print('Se formam, determina também qual o tipo de triângulo formado') print() # Entradas lado_a = float(input('Informe a medida do lado A: ')) lado_b = float(input('Informe a medida do lado B: ')) lado_c = float(input('Informe ...
""" Ex - 078 - Faça um programa que leia 5 valores numéricos e guarde-os em uma lista. No final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista.""" # Como eu Fiz. # Lista: lista = [] for i in range(0, 5): ...
def normal_old_school_method(a,b,tmp): tmp = a a = b b = tmp return a,b def pythonic_swap(a,b): a,b = b,a return a,b if __name__ == '__main__': a,b = 10,25 tmp = 0 print('Original [Before Swap Values]:\t',a,b) print('Old School Method:',normal_old_school_method(a,b,tmp)) p...
class Vehicle: def __init__(self, max_speed, mileage): self.max_speed = max_speed self.mileage = mileage modelS = Vehicle(200,20) print(modelS.max_speed, modelS.mileage)
class Solution(object): def calPoints(self, ops): """ :type ops: List[str] :rtype: int """ listvalue = [] last1 = 0 last2 = 0 sum = 0 for i in range(len(ops)): if (ops[i] == '+'): sum = listvalue[len(listvalue)-1] + ...
""" A Python CLI for Atlas-Checks tools """ __version__ = '1.0'
class MyOwnExceptionError(Exception): pass def do_exception(): try: 1/0 except ZeroDivisionError as error: raise MyOwnExceptionError from error if __name__ == "__main__": try: do_exception() except MyOwnExceptionError: print("My exception was caught!")
temperature_change_rate = -2.3 * units.delta_degF / (10 * units.minutes) temperature = 25 * units.degC dt = 1.5 * units.hours print(temperature + temperature_change_rate * dt)
# pylint: disable=no-member # -*- encoding: utf-8 -*- ''' @File : zones.py @Time : 2020/03/17 12:45:54 @Author : Kellan Fan @Version : 1.0 @Contact : kellanfan1989@gmail.com @Desc : None ''' # here put the import lib class Zones(object): def __init__(self, status='active'): self.__da...
# youtube-search-requests # parser/related_video_data.py # for mobile user-agent def parse_related_video_data1(data): try: d = data['contents']['singleColumnWatchNextResults']['results']['results']['contents'] except KeyError: return None for i in d: try: c = i['itemSect...
t = int(input()) while(t!=0): n = input() if(n=='b' or n=='B'): print('BattleShip') elif(n=='c' or n=='C'): print('Cruiser') elif(n=='d' or n=='D'): print('Destroyer') elif(n=='f' or n=='F'): print('Frigate') t-=1
""" not solved """ def get_prime(max_number): number_tiles = set(range(2, max_number)) prime_list = list() while len(number_tiles) > 0: min_number = min(number_tiles) prime_list.append(min_number) delete_tiles = set(range(min_number, max_number, min_number)) number_tiles ...
class NoSuchFileOrDirectory(Exception): def __init__(self): super().__init__("no such file or directory") class FileOrDirectoryAlreadyExist(Exception): def __init__(self): super().__init__("file or directory already exist") class NotAnDirectory(Exception): def __init__(self): sup...
class Solution: def findTheDifference(self, s: str, t: str) -> str: seen = {} for ch in s: if ch not in seen: seen[ch] = 0 seen[ch] += 1 for ch in t: if ch in seen and seen[ch] > 0: seen[ch] -= 1 else: ...
"""Framework errors.""" class Error(Exception): """Base error type.""" class ConfigError(Error): """Raised on configuration error.""" class DocumentError(Error): """Base class for all document related errors.""" message = "document error" def __init__(self, message=None, document=None, field=...
""" This file references all the environment variables that can be passed to the application, and their default value. Kubemen will load its configuration from this file first, and then will try to override each variable with what is defined in the process environment. If a matching variable is found in the environmen...
AL = 'AL' NL = 'NL' MLB = 'MLB' LEAGUES = [AL, NL, MLB] def mlb_teams(year): """ For given year return teams active in the majors. Caveat, list is not complete; those included are only those with a current team still active. """ year = int(year) return sorted(al_teams(year) + nl_teams(y...
# https://dmoj.ca/problem/dwite09c1p3 # https://dmoj.ca/submission/2184915 for i in range(5): n = int(input()) nums = [] for j in range(n): nums.append(int(input())) m = 0 for j in range(1,n+2): try: nums.index(j) except ValueError: m = j ...
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: res = 0 n = len(matrix) if n==0: return res m = len(matrix[0]) dp = [[0 for k in range(m)] for l in range(n)] for i in range(n): for j in ran...
# -*- coding:utf-8 -*- # https://leetcode.com/problems/length-of-last-word/description/ class Solution(object): def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ ret = 0 pos = len(s) - 1 while pos >= 0 and s[pos] == ' ': ...