content
stringlengths
7
1.05M
""" Utilities for working with arrays of timestamps Generally, i = index, T = array of ordered timestamps, t = timestamp """ def get_closest_index(i1, i2, T, t0): """ Returns the index i such that abs(T[i]-t0) is minimum for i1,i2 """ if abs(T[i1]-t0) <= abs(T[i2]-t0): return i1 else: ...
def FordFulkerson(graph,start,end): n = len(graph) GPrime = [[None]*n for _ in range(n)] for v in range(n): for u, w in graph[v]: GPrime[v][u] = w for v in range(n): for u in range(n): if GPrime[v][u] != None and GPrime[u][v] == None: GPrime[u][v] ...
class AbstractCodeGen(object): def genCode(self, ast, symbolTable, **kwargs): raise NotImplementedError() def genIndex(self, mibsMap, **kwargs): raise NotImplementedError()
#Exercíco048 soma = 0 #indica onde deve começar a soma entre os números cont = 0 for c in range(1, 500 + 1, 2): #repete os números entre 1 e 500, contando de 2 em 2(assim mostrando apenas os impares) if c % 3 == 0: #faz com que o programa mostre apenas os números que sao divisiveis por 3 soma = soma + c #so...
z = 100 while z > 10: a, b = input().split(" ") a = int(a) b = int(b) if a < b : print("Crescente") elif b < a: print("Decrescente") elif a == b: exit()
def main(): palindrome = [it1*it2 for it1 in range(100,1000) for it2 in range(it1,1000) if str(it1*it2)==str(it1*it2)[::-1]] for tc in range(int(input())): N = int(input()) print(max(filter(lambda x: x<N,palindrome))) if __name__=="__main__": main()
""" This uses test262 to test the interpreter """ # pylint: disable=relative-beyond-top-level, protected-access, no-self-use, missing-function-docstring, missing-class-docstring class Test262: def test_one(self): assert True, "This parses!"
print("Starting adding") total = [1] base = 2 power = 1000 for i in range(0, power): for i in range(0, len(total)): total[i] *= base carrier = 0 for i in range(0, len(total)): total[i] += carrier head = total[i] % 10 carrier = (total[i] - head) / 10 total[i] = int(head) while carr...
# LC 735 class Solution: def collide(self, a: int, b:int) -> int: if abs(a) == abs(b): return None res = max(abs(a),abs(b)) if abs(a) < abs(b): res *= (b // abs(b)) else: res *= (a // abs(a)) return res def asteroidCollision(self, aste...
with open('c:\\mine\\No.txt') as noTxt: with open('c:\\mine\\number.txt','w') as numberTxt: for line in noTxt: nos = line.split(',') start,end = int(nos[0]), int(nos[1]) for i in range(start, end): numberTxt.write(str(i) + '\n')
lines = open("input").read().strip().splitlines() # lines = """ # ..##....... # #...#...#.. # .#....#..#. # ..#.#...#.# # .#...##..#. # ..#.##..... # .#.#.#....# # .#........# # #.##...#... # #...##....# # .#..#...#.# # """.strip().splitlines() def p1(): TREE = "#" pos = [0, 0] trees = 0 while True...
#!/usr/bin/env python #------------------------------------------------------------------------------- # # Shared utilities # # Author: Martin Paces <martin.paces@eox.at> # #------------------------------------------------------------------------------- # Copyright (C) 2016 EOX IT Services GmbH # # Permission is hereb...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def trimBST(self, root, L, R): """ :type root: TreeNode :type L: int :type R: int :rtype: TreeNode ...
def GLSL_type(a): if(isinstance(a, str)): return "int["+str(len(a))+"]" elif(isinstance(a, list)): return GLSL_type(a)+"["+str(len(a))+"]" elif(type(a) == bool): return "bool"
ano = int(input('Digite o ano a ser pesquisado (formato "aaaa"): ')) if (ano % 4) == 0 and (ano % 100) != 0 or (ano % 400) == 0: print('O ano de {} É bissexto.'.format(ano)) else: print('O ano de {} NÃO É um ano bissexto.'.format(ano))
{ "targets": [ { "target_name": "roo", "sources": [ "./src/c/roo/roo.c", "./src/c/roo/roo_node.c", "./src/c/roo/callbacks.c", "./src/c/roo/startup.c", "./src/c/roo/interface.c", "./src/c/roo/log.c", "./src/c/roo/plugin.c", "./src/c/roo/map.c", ...
""" Defines an instance of stock which is cut to produce needed pieces.""" class Stock(object): """ Defines a piece of stock, including planned cuts """ def __init__(self, length): self.pieces = [] self.length = length self.remaining_length = length def __str__(self): pie...
# 1이 될 때까지 a = int(input()); b = int(input()); count = 0; while a != 1: if a % b == 0: a //= b; count += 1; else: a -= 1; count += 1; print(count); # solution - O(logN) # a, b = map(int, input().split()); # count = 0; # while true: # target = (a//b)*b; # count += a - target # a =...
LETTER = "литера" class AddrObject(object): def __init__(self, aoguid, name, type_obj, postalcode): self.aoguid = aoguid self.name = name self.type_obj = type_obj self.postalcode = postalcode def __str__(self): return "{0} - {1}".format(self.aoguid, self.name) def...
"""Factories for the leapmotion app.""" # import factory # from ..models import YourModel
num = 1 for i in range(16): print(num<<i, end=', ') print(); print() for i in range(16): print('0x%x'%(num<<i), end=',')
maliste = [2, 1, -5, 8, 7, 3, 4] # valeur quelconque i = 0 maxi = maliste[0] # on initialise le max à maliste[0] numero = 0 # et sa position est l'indice 0 while i < len(maliste): if maliste[i] > maxi: maxi = maliste[i] numero = i # nouveau maxi, nouvelle position i = i + 1 print("Le...
x=[] for i in range(20): val=int(input()) x.append(val) x.reverse() for k in range(20): print("N[{}] = {}".format(k,x[k]))
# 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。 # 注意:答案中不可以包含重复的三元组。 #   # 示例: # 给定数组 nums = [-1, 0, 1, 2, -1, -4], # 满足要求的三元组集合为: # [ # [-1, 0, 1], # [-1, -1, 2] # ] # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/3sum # 著作权归领扣网络所有。商业转载请联系官方授权,非商业...
def swap(a, b): #function logic print("Original: ",a, b) if (a > b or a < b): #doing the swap when the two numbers aren't equal temp = a a = b b = temp print("Swapped: ",a, b) else: #just returning the numbers in same order b/c they're equal, no need to swap print("No s...
def rank(graph, res): rank_page= {} for page in res.keys(): word_count=res[page] ingoing=graph.ingoing_links(page) num_links=len(ingoing) num_in_links=0 for link in ingoing: if link in res.keys(): num_in_links+=res[link] rank_page[pa...
""" (вместо 1) Решить задачу генерации нечётных чисел от 1 до n (включительно), не используя ключевое слово yield. """ generator_length = int(input('Введите длину генератора: ')) odd_nums = (num for num in range(1, generator_length, 2)) print(*odd_nums) print(type(odd_nums))
class Student(object): """docstring for Student""" def __init__(self, name,score,*age): self.__name = name self.__score = score def print_score(self): print('%s: %s'% (self.__name,self.__score)) def get_name(self): return self.__name def get_score(self): return self.__score def set_score(self,score): ...
# Write a program which replaces all vowels in the string with '*' str=input('enter the string : ') str2='aeiou' str3='AEIOU' l=len(str) str4='' for x in str: if x in str2 or x in str3: str4=str4+'*' else: str4=str4+x print(str4)
## CONSTRUCTING GRAPH v, e = map(int, raw_input().split()) grafo = [[] for i in range(v+1)] for i in range(e): v1, v2, w = map(int, raw_input().split()) # save edges that are getting in me, not edges from me to another v grafo[v2].append((v1, w)) ## INITIALIZING beginning = input() dp = ...
def pack01(): """ 01 背包问题: 有 N 件物品和一个容积为 V 的背包。每件物品的体积为 v[i] ,每件物品的价值为 w[i] 。求解将哪些物品装入背包可使价值总和最大。 子问题: """ pass if __name__ == "__main__": pass
class Account: """ A user account Schema described here https://gerrit-review.googlesource.com/Documentation/json.html#account """ def __init__(self, jsonObject): self._name = jsonObject.get("name", None) self._email = jsonObject.get("email", None) self._username = json...
# Using one of the programs you wrote in this chapter, add several # lines to the end of the program that do the following: favorite_pizzas = ['deep dish', 'thin crust', 'new york style', 'hawaiian', 'combo'] # • Print the message The first three items in the list are:. Then use a slice to # print the first three item...
# アプリケーションのClientID client_id = '*****' # アプリケーションのClientSecret client_secret = '*****' user_id = '*****' #デバッグ用 なくても動く search_context = ['***', '***'] #検索用キーワード。ユーザ名+TwitterIDで大体絞れる call_time = 720 # 大抵の配信者さんなら12時間はチェックいらないはず
LINE_COLORS = [ (255, 127, 127), (255, 127, 182), (102, 51, 73), (214, 127, 255), (85, 51, 102), (161, 127, 255), (63, 51, 102), (127, 146, 255), (51, 58, 102), (127, 201, 255), (51, 80, 1...
Main_Quora = """<html lang="en" class="js-wf-loaded"> <head> <link rel="icon" href="https://qsf.fs.quoracdn.net/-3-images.favicon.ico-26-ae77b637b1e7ed2c.ico"> <link rel="preload" as="font" type="font/woff2" crossorigin="anonymous" href="https://qsf.fs.quoracdn.net/-3-fonts.q-icons.q-icons.woff2-26-9afc20a49e3...
class BadSetting(Exception): """ Exception raised when an invalid value is provided for one or more settings when updating settings. """ class UnknownSetting(Exception): """ Exception raised when attempting to access a setting that does not exist. """
inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} print(inventory) del inventory['pears'] # deletes a <key,value> print(inventory) inventory['apples'] = 10 # change value associated with key apples print(inventory) inventory['bananas'] = inventory['bananas'] * 2 print(inventory) num_...
"""Helper enum for defining possible states of tagging in a chat.""" class TagMode: """Helper enum for defining possible states of tagging in a chat.""" STICKER_SET = 'sticker_set' RANDOM = 'random' SINGLE_STICKER = 'single_sticker'
# # PHASE: collect jars # # DOCUMENT THIS # load( "@io_bazel_rules_scala//scala/private:rule_impls.bzl", "collect_jars_from_common_ctx", ) def phase_scalatest_collect_jars(ctx, p): args = struct( base_classpath = p.scalac_provider.default_classpath + [ctx.attr._scalatest], extra_runtime_dep...
#!/usr/bin/env python3 # https://abc059.contest.atcoder.jp/tasks/abc059_b a = int(input()) b = int(input()) if a == b: print('EQUAL') elif a < b: print('LESS') else: print('GREATER')
# noinspection DuplicatedCode class InsertConflictException(Exception): pass class OptimisticLockException(Exception): pass class UnexpectedStorageException(Exception): pass class UnsupportedCriteriaException(UnexpectedStorageException): pass class UnsupportedComputationException(UnexpectedStorageException)...
N, K, S = map(int, input().split()) str_S = str(S) str_S1 = str(S+1) ans = [] for _ in range(K): ans.append(str_S) for _ in range(N-K): if S != 1000000000: ans.append(str_S1) else: ans.append('1') print(' '.join(ans))
def epu_calib_gr1800_Aug2019(dets = [sclr, ring_curr]): print('\n\n WARNING WARNING WARNING:\n\t check if there scalar is installed or not!!!!') yield from gcdiag.diode # srs settings for diode = SRS settings: 5 x1 uA/v , time = 1.0 yield from mv(m1_simple_fbk,0) yield from mv(m3_simple_fbk,...
#!/usr/bin/python3.6 """ A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is...
# PYTHON - MIT - UNICAMP # ============================================================================= # Created By : Matheus Percário Bruder # Created Date : February 3rd, 2021 # ============================================================================= dividend = 7 divisor = 2 quocient = 0 if dividend > 0 an...
a = int(input("Введите 4 числа\n")) b = int(input()) c = int(input()) d = int(input()) secondF = a + b secondS = c + d final = secondF / secondS final = float('{:.2f}'.format(final)) print("result: ", final)
def duplicate(s): if(len(s)<=1): return s if s[0]==s[1]: return duplicate(s[1:]) return s[0]+duplicate(s[1:]) s = input() print(duplicate(s))
# %% ####################################### def access_nested_dict(thedict: dict): """Demo of how to access a nested dictionary with a two dictionary comprehensions Examples: >>> a_dictionary = { ... "1-2017": { ... "Win7": "0.47", ... "Vista": "0.2", ...
linhas = int(input('Quantas linhas vai querer?: ')) colunas = int(input('quantas colunas vai querer?: ')) m = [] n = [] for l in range(linhas): ln = [] lon = 0 for c in range(colunas): t = int(input(f'qual o valor de [{l},{c}]?: ')) ln.append(t) lon += t m.append(ln) n.appen...
tabela = ('Flamengo', 'Internacional', 'Atlético Mineiro', 'São Paulo', 'Fluminense', 'Grêmio', 'Palmeiras', 'Santos', 'Athletico-PR', 'Bragantino', 'Ceará SC', 'Corinthians', 'Atlético-GO', 'Bahia', 'Sport Recife', 'Fortaleza', 'Vasco da Gama', 'Goiás', 'Chapecoense', 'Botafogo') ...
# coding=utf-8 # *** WARNING: this file was generated by crd2pulumi. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** SNAKE_TO_CAMEL_CASE_TABLE = { "access_token_secret": "accessTokenSecret", "api_version": "apiVersion", "destroy_on_finalize": "destroyOnFinalize", "e...
def maxSubsetSumNoAdjacent(array): # Write your code here. if not array: return 0 if len(array) < 3: return max(array) dp = [0]*len(array) dp[0] = array[0] dp[1] = max(array[1], dp[0]) for i in range(2, len(array)): dp[i] = max(dp[i - 1], array[i] + dp[i - 2]) ...
# Check if string is palindrom or not....using in-built fxn a = str(input("Input String")) b = a.reverse if a==b: print("string is palindrome") else: print("String is not palindrome")
__all__ = ['batch_tasks'] def batch_tasks(n_batches, n_tasks=None, arr=None, args=None, start_idx=0, include_idx=True): """Split tasks into some number of batches to send out to workers. By default, returns index ranges that split the number of tasks into the specified number of batches. ...
def orf_single(seq): startss = [] stopss = [] starts_ = [] stop_s = [] start = 0 sslen = 0 s_len1 = 0 s_len2 = 0 newseq = seq newseq_6 = [] max_l = len(seq) l = len(seq) for i in range(len(seq)): if (seq[i:i+3]=="ATG"): start = 1 # has start co...
numerotabuada = int(input("Escreva um numero e veja sua tabuada: ")) tabuada = [] for x in range(1,10+1): mult = numerotabuada * x tabuada.append(mult) print(tabuada)
""" mpiece.renderer ~~~~~~~~~~~~~~~~~~~~~~~~~ Renderer Classes. :license: BSD, see LICENSE for details. :author: David Casado Martinez <dcasadomartinez@gmail.com> """ class Renderer(object): """ Base renderer class. All renderer classes should be subclasses of this class. This class and their subclass ...
class Sense: def __init__(self, short: str, ident: int): self.ident = ident self.short = short self.pref_label = '' self.alt_labels = [] def add_pref_label(self, pref_label: str): self.__check_pref_label_not_set(pref_label) self.pref_label = pref_label def a...
""" TFIDF + SGD Model for text classification """ class GloveRNNModel(object): """Recurrent Neural Network Model for text classification""" def __init__(self, data_dir): super(GloveRNNModel, self).__init__() self.data_dir = data_dir def get_details(self): """ Get a dictionary of ...
# Test the connection to the database def test_ping(client): response = client.get("/ping") assert response.status_code == 200 assert response.json() == {"ping": "pong!"} def test_root(client): response = client.get("/") assert response.status_code == 200 assert response.json() == {"Message": ...
class Scenario: STAGES = [ {"name": "install", "path": "build/{version}/transaction_confusion.cap",}, { "name": "send", "comment": "INS_PREPARE1", "payload": "0x80 0x01 0x00 0x00 0x00", "optional": False, }, { "name": "send"...
def power(a,b): if b==0: return 1 elif b%2 == 0: val = power(a,int(b/2)) return val*val else: oddval = power(a,b-1) return a*oddval # take base a = int(input()) #take exponent b = int(input()) # to find a^b we divide b in two halves recursively. answer=power(a,b) print(answer)
senha = int(input()) while senha != 2002: print("Senha Invalida") senha = int(input()) print("Acesso Permitido")
""" Practising classes and OOPs """ class Robot: def __init__(self, name=None, build_year=None) -> None: self.name = name self.build_year = build_year def say_hi(self): if self.name: print(f"Hi i am {self.name}") else: print("Robot without name") if self.build_year: print(f"I ...
#body_x = 120 body_x = 140 body_y = 160 bottom_z = 15 bottom_wall_thikness = 1.5 dist_between_whells = 90
DARKEST_GREEN = (15, 56, 15) DARK_GREEN = (48, 98, 48) LIGHT_GREEN = (111, 135, 12) LIGHTEST_GREEN = (155, 188, 15) DARKEST_GREEN_VAL = 3 DARK_GREEN_VAL = 2 LIGHT_GREEN_VAL = 1 LIGHTEST_GREEN_VAL = 0
RUN_CONFIGURATIONS = { "Python.DjangoServer": [ ] } class RunConfiguration: pass # workspace.xml # <?xml version="1.0" encoding="UTF-8"?> # <project version="4"> # <component name="RunManager" selected="npm.build-prod"> # <configuration name="Worker" type="Python.DjangoServer" factoryName="Django ...
# DEBUG ERROR="\033[31mERROR\033[0m" SUCCESS="\033[32mSUCCESS\033[0m" #ALGORITHM CONFIGS NUM_ATTRS = 8 NUM_TARGETS = 1 NORMALIZE_TARGETS = False TRAIN_RATIO = (2.0/3.0) INPUT_DELIMITER = ',' HAS_HEADER=False NUM_DIGITS = 5 NUM_NEIGHBOURS = 5 EXCLUDE_ATTRS= [] PREDICT_TARGET = 8 NUM_NEURONS_HIDDEN_LAYER = 9 LEARNING_RA...
CLIENT_ID_ENV_VAR = 'SPOTIFY_CLIENT_ID' CLIENT_SECRET_ENV_VAR = 'SPOTIFY_CLIENT_SECRET' USERNAME_ENV_VAR = 'SPOTIFY_USERNAME' SPOTIFY_API_SCOPE = 'playlist-modify-private,playlist-read-private,user-library-modify,user-library-read' DEFAULT_REDIRECT_URL = 'http://localhost:8888/callback'
class Data: #Class Data is designed to hold an object in a tree # name: the name of the node, generally more for the leaves and root # length: the length of the branch from its top node def __init__( self, name, length, id = 0 ): self.name = name self.length = length s...
num = [] for c in range(0, 5): num.append(int(input(f'Digite u número na {c}ª posição :'))) maior = max(num) menor = min(num) print(f'Você digitou os números: {num}') print(f'O Maior número é {maior} e está nas posições: ', end='') for p, n in enumerate(num): if maior == n: print(p, end=' ') print(f'\nO...
nested = {} for i, v in mut.iterrows(): if i not in nested: nested[i] = {} sample = v['Tumor_Sample_Barcode'] if sample not in nested[i]: nested[i][sample] = {} mut_type = v['Variant_Classification'] if mut_type not in nested[i][sample]: nested[i][sample][mut_type] = [] h...
# Config for automato # WTF config WTF_CSRF_ENABLED = True SECRET_KEY = 'the_very_secure_secret_security_key_that_no_will_ever_guess' # MySQL Config SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:alpine@127.0.0.1/automato' SQLALCHEMY_TRACK_MODIFICATIONS = False RABBITMQ_HOST = "localhost" WEBDRIVER_PATH = r"C:\Us...
# 生成器 my_integer(n) 生成1到n的整数 def my_integer(n): i = 1 # 先初始化变量 while i <= n: yield i i += 1 for x in my_integer(5): print(x)
def rmtree(root): """ Function to remove a directory and its contents :param root: The root directory :type root: pathlib.Path """ for p in root.iterdir(): if p.is_dir(): rmtree(p) else: p.unlink() root.rmdir()
class Solution: def fourSum(self, nums, target): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() results = [] self.findNsum(nums, target, 4, [], results) return results def findNsum(self, sorted_nums, target, N, result, results):...
# Problem Description # Task. Compute the last digit of 𝐹02 + 𝐹12 + · · · + 𝐹𝑛2. # Input Format. Integer 𝑛. # Constraints. 0 ≤ 𝑛 ≤ 1018. # Output Format. The last digit of 𝐹02 + 𝐹12 + · · · + 𝐹𝑛2. def pisano_period(m): a,b,c=0,1,1 for i in range(m*m): c = (a+b)%m a = b ...
# Copyright 2017 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. DEPS = [ 'raw_io', 'step', ] def RunSteps(api): # Read command's stdout and stderr. step_result = api.step('echo', ['echo', 'Hello World...
''' Muitos sites na internet adicionam uma sessão chamada “Perguntas mais Frequentes” que, como o nome já diz, contém as perguntas mais feitas pelos usuários que utilizam o site. O portal do URI costuma receber muitas perguntas de seus usuários, então Neilor imaginou que seria uma boa ideia adicionar uma sessão de Per...
numbers = [int(i) for i in input().split()] average = sum(numbers) / len(numbers) all_greater_than_average = [greater for greater in numbers if greater > average] top_five = [] for j in range(5): if len(all_greater_than_average) == 0: break top_five.append(str(max(all_greater_than_average))) all_gr...
""" @author: acfromspace """ def unique_chars_in_string(input_string): return len(set(input_string)) == len(input_string) input_string = str(input("Input a string: ")) print("unique_chars_in_string():", unique_chars_in_string(input_string))
class Solution: def maxRepeating(self, sequence: str, word: str) -> int: mx = len(sequence) // len(word) for repeat in range(1, mx + 2): sub = word * repeat if sub not in sequence: return repeat - 1 return 0
class Node(object): """simple node for a linked list""" def __init__(self, e): self.next_ = None self.e = e class LinkedList(object): """linked list with simple built-in iterator""" def __init__(self): self.first = None self.last = None self.current = None self.size = 0 def next_(sel...
"""Export2D - Export Fusion 360 model faces as PDF or DXF files""" __version__ = '0.1.0' __author__ = 'Patrick Rainsberry <patrick.rainsberry@autodesk.com>' __all__ = []
test = { 'name': 'q2a', 'points': 1, 'suites': [ { 'cases': [ {'code': '>>> 600 < num_schools < 700\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> # Come back to this, not sure if it works;\n>>> num_schools == 659\nTrue', 'hidden': False, 'locked': False}], ...
__all__ = ['__name__', '__version__', '__author__', '__author_email__', '__description__'] __name__ = 'ssec' __version__ = '2.0.0' __author__ = 'Justin Baudisch' __author_email__ = 'baudischjustin1995@gmail.com' __description__ = 'Yet another client library for server-sent events (sse).'
# calculate the hamming distance between two numbers # count the number of 1 after xor operation of two number # citation: https://leetcode.com/articles/hamming-distance/ # approach 1: using library function def hamming_distance_using_library(x, y): xor = x ^ y return bin(xor).count('1') # approach 2: using...
# -*- coding: utf-8 -*- __version__ = '1.4.0' default_app_config = 'djangocms_translations.apps.DjangocmsTranslationsConfig'
# -*- coding: utf-8 -*- """ File Name: maximum-gap.py Author : jynnezhang Date: 2020/11/26 9:38 上午 Description: https://leetcode-cn.com/problems/maximum-gap/ """ class Solution: def maximumGap(self, nums) -> int: if not nums or len(nums) < 2: return 0 nums.sort() ...
_base_ = './tood_r50_fpn_1x_coco.py' model = dict( bbox_head=dict( anchor_type='anchor_based' ) )
# https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent def array_strings_are_equal(word1, word2): return ''.join(word1) == ''.join(word2)
A=[list(map(int,input().split())) for i in range(4)] flag=0 for x in range(4): for y in range(3): if A[x][y]==A[x][y+1] or A[y][x]==A[y+1][x]:flag=1 print("CONTINUE" if flag==1 else "GAMEOVER")
# function to find media def get_media(array): arr_len = len(array) media = 0 for i in range(arr_len): media += array[i] return media / arr_len print(f'A média das notas de pedro é: {get_media([10, 5, 5, 10])}')
#!/usr/bin/env python3 def betolt(file): megallok = [] with open(file, "rt") as f: for sor in f: megallok.append(sor.rstrip("\n")) return megallok def metszi_e(alista, blista): for elem in alista: if elem in blista: return elem return None def main(): print(metszi_e(betolt("...
''' 994. Rotting Oranges Medium In a given grid, each cell can have one of three values: the value 0 representing an empty cell; the value 1 representing a fresh orange; the value 2 representing a rotten orange. Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten. Retur...
""" Algorithm (BFS): 1. Collect all positions of the zombies into a queue. Then we will use this queue for collecting positions of humans only. 2. Find adjacent humans around each enqueued position. 3. Convert them into zombies. 4. Add their positions into a turned-into-zombie queue. 5. Increase number of the hours. 6....
def sort(nums): for i in range(len(nums)-1, 0, -1): for j in range (i): if nums[j] > nums[j + 1]: temp = nums[j] nums[j] = nums[j + 1] nums[j + 1] = temp nums = [2,6,4,1,8,7] sort(nums) print(nums)
# Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. # # An example is the root-to-leaf path 1->2->3 which represents the number 123. # # Find the total sum of all root-to-leaf numbers. # # Note: A leaf is a node with no children. # # Example: # # # Input: [1,2,3]...
counter=1 def setup(): size(500,500) smooth() def draw(): global counter noStroke() fill (10, 50) rect (-1,-1, width//2 +1, height +1) ny = sin( counter ) *100+200 nx = counter *10 stroke (250) strokeWeight (20) line(nx , ny , nx , ny) counter =...