content
stringlengths
7
1.05M
""" Illustrates various methods of associating multiple types of parents with a particular child object. The examples all use the declarative extension along with declarative mixins. Each one presents the identical use case at the end - two classes, ``Customer`` and ``Supplier``, both subclassing the ``HasAddresse...
# Created by Artem Manchenkov # artyom@manchenkoff.me # # Copyright © 2019 # # Циклические конструкции # # Цикл while step = 0 max_steps = 5 while step < max_steps: print(f"I'm working on ... {max_steps - step} remaining") step += 1 # Цикл for in persons = ['Jim', 'Adam', 'Kate', 'Peter'] for person in ...
#wapp to find factorial of a number provided by the user num=int(input("enter a number:")) if(num<0): print("enter positive number") elif(num==0): print("ans=",1) else: fact=1 for i in range(1,num+1): fact=fact*i print("ans=",fact)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 7 12:46:44 2020 @author: esteban """ pathInformesRegiones='../datos/informes_diarios_regiones/' pathInformesComunas='../datos/informes_diarios_comunas/' formatoArchivoRegiones='-InformeDiarioRegiones-COVID19.csv' formatoArchivoComunas='-InformeDi...
''' Tips:1. We don't have to count the lengths of the linked-list. We just need to set the condition of the while loop as (l1 or l2) In the while loop, we need to set the [if l1] and [ if l2] to select that whether the linked-list is vaild or None. 2. We use dummy and set it as the node before th...
# -*- coding: utf-8 -*- # Copyright © 2013 Jens Schmer, Michael Engelhard class Move(object): """description of a move""" cols = "abcde" rows = "123456" def __init__(self, fr, to): """ fr and to are tuples in the form "(x, y)" """ self.start = fr se...
# # @lc app=leetcode.cn id=110 lang=python3 # # [110] 平衡二叉树 # # https://leetcode-cn.com/problems/balanced-binary-tree/description/ # # algorithms # Easy (46.37%) # Total Accepted: 11.8K # Total Submissions: 25.5K # Testcase Example: '[3,9,20,null,null,15,7]' # # 给定一个二叉树,判断它是否是高度平衡的二叉树。 # # 本题中,一棵高度平衡二叉树定义为: # # # 一...
def part1(data): coordinateData = {} coordinateData2 = {} coordinates = set() xmin, xmax, ymin, ymax = 1000, 0, 1000, 0 for eachLine in data.splitlines(): splitLine = eachLine.split(', ') coordinates.add((int(splitLine[0]), int(splitLine[1]))) coordinateData[f"{int(splitLine[...
"""Contains material property indices Obtained from: /usr/ansys_inc/v202/ansys/customize/include/mpcom.inc These indices are used when reading in results using ptrMAT from a binary result file. """ # order is critical here mp_keys = ['EX', 'EY', 'EZ', 'NUXY', 'NUYZ', 'NUXZ', 'GXY', 'GYZ', 'GXZ', 'ALPX', ...
# Copyright (c) 2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'includes': [ '../../build/common.gypi', ], 'targets': [ { 'target_name': 'harfbuzz', 'type': '<(library)', 'sources': ...
""" https://leetcode.com/problems/combination-sum/ Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. The same repeated number may be chosen from candidates unlimited number of times. N...
km = float(input('Digite quantos km: ')) fuel = float(input('Informe o combustivel consumido: ')) cons = km / fuel print(f'O consumo por litro é de : {cons}, por litro ')
# # Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/ # Written by Angelos Katharopoulos <angelos.katharopoulos@idiap.ch> # class Event(object): """The Event is the base class for all events that are dispatched from any transformer module. This class defines only the basic attributes of a...
# -*- coding: utf-8 -*- n = float(input()) if (0 <= n <=25): print('Intervalo [0,25]') elif (25 < n <=50): print('Intervalo (25,50]') elif (50 < n <=75): print('Intervalo (50,75]') elif (75 < n <=100): print('Intervalo (75,100]') else: print('Fora de intervalo')
valort = float(input("Digite o valor total do prêmio: ")) vestado = (valort * 0.07) vestado2 = (valort * 0.93) primeiro = (vestado2 * 0.46) segundo = (vestado2 * 0.32) terceiro = (vestado2 * 0.22) print("Valor do premio é igual a {}, teve um desconto de {}, Primeiro, Segundo e Terceiro ganhram respectivamente : {}, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- def is_a_invalid_id(feature_id): """ Check if the id of some feature is valid or not. For a id to be valid, it needs to be: (1) not None; (2) a integer (a digit); (3) if is a integer, so different of 0. IDs are integer numbers greater than zero. ...
media = 0 velho = 0 idm = 0 nomev = '' print('='*20) for c in range(1, 6): nome = str(input('Qual seu nome: ')).strip() idade = int(input('Qual sua idade: ')) sexo = str(input('''[ M ] Masculino. [ F ] Feminino. Qual e seu sexo: ''')).strip() print('='*20) if c == 1 and sexo in 'Mm': velho =...
def get_priorities(client, db_rid=None, priority_name=None, page_size=1000, verbose=False): conditionstring = "" if db_rid: conditionstring = client._add_condition(conditionstring, 'id', db_rid, verbose) if priority_name: conditionstring = client._add_condition(conditionstring, 'name', prio...
def maior(* num): print('=' * 30) print('Analisando os respectivos valores . . . ') cont = maior = 0 for n in num: print(f'{n} ', end='') if cont == 0: maior = n else: if n > maior: maior = n cont += 1 print(f' Foram digitados {...
# -*- coding: utf-8 -*- """ Created on Sun May 12 19:36:25 2019 @author: Administrator """ # import time # time1 = time.perf_counter() # #class Solution(): #19:50 - 20:40 # # def longestPalindrome(self, s): # ## st = {} # ## p = 0 # ## for k in range(len(s)): # ## if s[k] in st.ke...
# # Licensed to Big Data Genomics (BDG) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The BDG licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this fil...
_base_ = [ '../_base_/models/spatialflow_r50_fpn.py', '../_base_/datasets/coco_panoptic.py', '../_base_/schedules/schedule_20e.py', '../_base_/default_runtime.py' ] # optimizer optimizer = dict(type='SGD', lr=0.005, momentum=0.9, weight_decay=0.0001) # panoptic settings segmentations_folder='./work_dirs/spa...
#!/usr/bin/env python3 # This script is to learn how to manipulate lists my_list = ['192.168.0.5', 5060, 'UP'] print( "THe first item in teh list (IP): " + my_list[0] ) print( "The second item in teh list (state): " + my_list[2] ) new_list = [ 5060, '80', 55, '10.0.0.1', '10.20.30.1', 'ssh' ] #my code to use a single ...
# Crie um programa que leia o nome e o preço de vários produtos. # O programa deverá perguntar se o usuário vai continuar ou não. No final, mostre: # A) qual é o total gasto na compra. # B) quantos produtos custam mais de R$1000. # C) qual é o nome do produto mais barato. total = maisMil = 0 cont = caro = barato = 0 p...
languages = [ { "Language": "Bengali", "ISO-639-1 Code": "bn" }, { "Language": "Gujarati", "ISO-639-1 Code": "gu" }, { "Language": "Hindi", "ISO-639-1 Code": "hi" }, { "Language": "Malayalam", "ISO-639-1 Code": "ml" }, { "Language": "Marathi", "ISO-639-1 Code": "mr" }, { "Lan...
''' isEven takes a single integer parameter a returning true if a is even and false if a is odd ''' def isEven(a): return a % 2 == 0 ''' print(isEven(-1)) print(isEven(-2)) print(isEven(1)) print(isEven(8)) ''' ''' missing_char takes a non-empty string, str, and returns the str without the character at index n '...
# Objetivo do algorítmo: # O usuário deverá digitar o valor do produto # e em seguida o valor do desconto a ser aplicado. # O algorítimo deverá calcular o valor com o desconto. # Exercicio pensado por: Gustavo Guanabará / Curso Em Vídeo def calculaDec(valorProduto, desconto): valorProdutoComDesc = valorProduto -...
# generated from catkin/cmake/template/order_packages.context.py.in source_root_dir = "/home/robotpt/QTRobotTester/src" whitelisted_packages = "".split(';') if "" != "" else [] blacklisted_packages = "".split(';') if "" != "" else [] underlay_workspaces = "/home/robotpt/QTRobotTester/devel;/home/robotpt/HumanProjectorI...
# -*- coding: utf-8 -*- # Copyright 2017, A10 Networks # Author: Mike Thompson: @mike @t @a10@networks!com # image1 = '''Funded By: ``........` `.--:////////...
# network HOST = '127.0.0.1' # or '0:0:0:0:0:0:0:1' PORT = 9999 # UI DEFAULT_POWERED = False # powered off DEFAULT_COLOR = '#000000' # black BACKGROUND_COLOR = '#FFFFFF' # white DIMENSIONS = "200x200" REFRESH_RATE = 100 # UI refresh every 100 milliseconds # misc LOGGING = { 'level': 'INFO', 'handler': '...
def menorMaior(): primeiro = int(input('Informe o Primeiro número: ')) segundo = int(input('Informe o Segundo número : ')) terceiro = int(input('Informe o Terceiro número: ')) quarto = int(input('Informe o Quarto número: ')) quinto = int(input('Informe o quinto número: ')) maior = primeiro ...
""" Questions : EASY 1528. [Shuffle String](https://leetcode.com/problems/shuffle-string/) Given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string. Return the shuffled string. Example 1: In...
""" 60 / 60 test cases passed. Runtime: 36 ms Memory Usage: 15 MB """ class Solution: def canReorderDoubled(self, arr: List[int]) -> bool: cnt = Counter(arr) for x in sorted(cnt, key=abs): if cnt[x << 1] < cnt[x]: return False cnt[x << 1] -= cnt[x] ret...
# 闭包,将内嵌函数的语句和这些语句的执行环境打包在一起,得到的函数对象成为闭包 # 三个条件: # 1、有一个内嵌函数 # 2、内嵌函数引用外部函数中的变量 # 3、外部函数返回值是内嵌函数 # 如下例 def make_power(y): def fn(x): return x ** y return fn pow2 = make_power(2) print("5的2次方是:", pow2(5)) pow3 = make_power(3) print("5的3次方是:", pow3(5))
class RangeStack: def __init__(self) -> None: self.stack = [] self.add = [] self.cursum = 0 def push(self, v : int) -> None: self.cursum += v self.stack.append(v) self.add.append(0) def pop(self) -> int: if not self.add: return -1 ...
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'cloudbuildhelper', 'recipe_engine/path', ] def RunSteps(api): paths = api.cloudbuildhelper.discover_manifests( root=api.path['cache']...
# -*- coding: utf-8 -*- """ Created on Wed Sep 30 16:11:31 2020 @author: Abhishek Parashar """ def subsetutil(arr, subset, index,target,ans): if(target<0): return elif(target==0): ans.append(subset[:]) for i in range(index,len(arr)): if (i>index and arr[i]==arr[i-1])...
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Author: Niccolò Bonacchi # @Date: Tuesday, November 27th 2018, 2:10:03 pm """ Main settings file for water calibration protocol """ IBLRIG_FOLDER = "C:\\iblrig" IBLRIG_DATA_FOLDER = None # If None will be ..\\iblrig_data from IBLRIG_FOLDER OAHUS_SCALE_PORT = None # 'COM...
# Exemplo de um dicionário para representar um cadastro de uma pessoa. pessoa = {"nome": 'Rodrigo', 'idade': 29, 'cidade': 'Campina Grande'} print(pessoa) print(type(pessoa)) print('') # Não é possível acessar um elemento de um dicionário por um índice como na lista. # Devemos acessar por sua "chave": print(pessoa['n...
class Solution: def __init__(self): self.tribo = {0:0,1:1,2:1} def tribonacci(self, n: int) -> int: if(n in self.tribo): return self.tribo[n] else: res = self.tribonacci(n-1)+self.tribonacci(n-2)+self.tribonacci(n-3) self.tribo[n] = res return ...
#Exercise 3: Write a program to read through a mail log, build a histogram using a dictionary #to count how many messages have come from each email address, and print the dictionary. #Exercise 5: This program records the domain name (instead of the address) where the message #was sent from instead of who the mail ca...
# output from sgtbx computed on platform win32 on 2010-04-28 sgtbx = { 'p 2 3': [ (1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0) , (0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0) , (0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0) , (0.0, -1.0, 0.0, 0.0, 0.0, -1.0, 1.0, 0.0, 0.0, 0...
# ------------------------------------------------------------ # imaparchiver/config.py # # imap-archiver config object # # This file is part of imaparchiver. # See the LICENSE file for the software license. # (C) Copyright 2015-2019, Oliver Maurhart, dyle71@gmail.com # -------------------------------------------------...
print('-' * 12) num = int(input('Digite um numero da tabuada: ')) print('{} x 1 = {}'.format(num, num*1)) print('{} x 2 = {}'. format(num, num*2)) print('{} x 3 = {}'.format(num, num*3)) print('{} x 4 = {}'.format(num,num*4)) print('{} x 5 = {}'.format(num, num*5)) print('{} x 6 = {}'.format(num, num*6)) print('{} x 7 ...
"""Template strings to simplify code formatting""" mapfile_layer_template = """ # LAYER: {feature} LEVEL: {layer} LAYER NAME "{feature}_{layer}" GROUP "{group}" METADATA "ows_title" "{feature}" "ows_enable_request" "*" "gml_include_items" "all" "wms_feature_mime_type" "t...
T=int(input()) N=int(input()) A=list(map(int,input().split())) M=int(input()) B=list(map(int,input().split())) k=0 for i in range(N): if k!=M and 0<=B[k]-A[i]<=T:k+=1 print("yes" if k==M else "no")
def NX(LENS, X = .50): tot = sum(LENS) for L in LENS: a = sum([x for x in LENS if x >= L]) if a >= tot * X: NX = L return NX if __name__ == "__main__": FASTA_file = open('MRSA_k85/contigs.fasta') LENS = [] for line in FASTA_file: if line.startswith('>'): ...
""" Use recursion to write a function that accepts an array of strings and returns the total number of characters across all the strings. For example, if the input array is ["ab", "c", "def", "ghij"], the output should be 10 since there are 10 characters in total. sub-problem: arr[1:] base cas...
"""Constants related to IStorage and related interfaces This file was generated by h2py from d:\msdev\include\objbase.h then hand edited, a few extra constants added, etc. """ STGC_DEFAULT = 0 STGC_OVERWRITE = 1 STGC_ONLYIFCURRENT = 2 STGC_DANGEROUSLYCOMMITMERELYTODISKCACHE = 4 STGC_CONSOLIDATE...
# --- Day 3: Perfectly Spherical Houses in a Vacuum --- f = open("input.txt", "r").read() def getSantasUniquePositions(file, numSantas): x = 0 y = 0 start = [x, y] santaPositions = [start] roboPositions = [start] i = 0 santaX = roboX = x santaY = roboY = y for c in file: if i % numSantas == 0: sant...
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython Escriba un programa que le solicite al usuario la edad actual, la edad a la qu desea retirar, el monto que desea tener en su cuenta bancaria a la edad de su retiro y la tasa de interes que le ofrecen. Su programa deberá informarle el monto del deposito anua...
total_tickets = 0 student_tickets = 0 standart_tickets = 0 kids_tickets = 0 count_seats = 0 while True: command = input() if command == "Finish": print(f"Total tickets: {total_tickets}") percent_student = student_tickets / total_tickets * 100 percent_standart = standart_ticke...
class Structure: # Class variable that specifies expected fields _fields= [] def __init__(self, *args): if len(args) != len(self._fields): raise TypeError('Expected {} arguments'.format(len(self._fields))) # Set the arguments for name, value in zip(self._fields, args): ...
def tax_brackets(gross_income, deduc=12700): # married only # deduc is for itemizing in 2017 (majority would be from income tax) brackets_17 = ( (18650, 0.1), (75900-18650, 0.15), (153100-75900, 0.25), (233350-153100, 0.28), (416700-233350, 0.33), (470700-4167...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"count_errors": "00_core.ipynb", "map_dtypes_to_choices": "00_core.ipynb", "AsType": "00_core.ipynb", "Row": "00_core.ipynb", "get_smallest_valid_conversion": "00_core.ipyn...
class Solution: def solve(self, nums): is_strictly_increasing = True for i in range(len(nums)-1): if nums[i+1] <= nums[i]: is_strictly_increasing = False if is_strictly_increasing: return True is_strictly_decreasing = True ...
# # PySNMP MIB module NETBOTZ-DEVICE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NETBOTZ-DEVICE-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:18:29 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
class Trigger(object): """ English: Static class of game triggers Русский: """ @staticmethod def is_in_faction(value = bool()): """ English: Checks that country is in some faction Русский: Проверяет, что государства cостоит в альянсе """ if value == Tru...
# Copyright 2019 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
""" While em Python Utilizado para realizar ações enquanto uma condição for verdadeira. Requisitos: Entender condições e operadores """ while True: print() num_1 = input('Digite um numero: ') num_2 = input('Digite outro numero: ') operador = input('Digite um operador: ') sair = input('Deseja sair ...
""" Trivial utilities """ def get_metarget_version(): try: with open("VERSION", "r") as f: return f.read().strip() except FileNotFoundError: return "unknown"
num= 89 cont= 0 while num <= 150: if num % 2 == 0: print('par', num) cont = cont + 1 num = num + 1 print('quantidade= ',cont)
""" Global constants module """ DEFAULT_HOST = "http://localhost:8080/" DEFAULT_USER_NAMESPACE = "kubeflow-user-example-com" DEFAULT_USERNAME = "user@example.com" DEFAULT_PASSWORD = "12341234" KUBEFLOW_GROUP = "kubeflow.org" KUBEFLOW_NAMESPACE = "kubeflow"
# Reference: https://runestone.academy/runestone/books/published/pythonds/Recursion/pythondsConvertinganIntegertoaStringinAnyBase.html # if num < base (2, 8, 10, 16) then we can directly lookup the corresponding # string value # hence base case = if num < base then lookup # To reduce the problem towards base case, we ...
# These are local default variables for development # In deployment on Heroku's systems, these variables are changed DEBUG = True SECRET_KEY = "super_secret_key" LILLINK_REDIS_URL = "redis://localhost:6379/0"
numeroA = int(input('Digite um numero...')) outroNumero = int(input('Digite outro numero')) sum = numeroA + outroNumero print('A soma de {} e {} eh igual a {}' .format(numeroA, outroNumero, sum))
file = open('2021\D8\input.txt','r').read().splitlines() s = [] mapcode = { 'a':'', 'b':'', 'c':'', 'd':'', 'e':'', 'f':'', 'g':'' } wirecode = { 0:'', 1:'', 2:'', 3:'', 4:'', 5:'', 6:'', 7:'', 8:'', 9:'' } numcode = { 0:'abcefg', 1:'cf', 2:'ac...
class TelemetryTCPDialOutServerError(Exception): """Generic Error for TCP Dial out server""" pass class IODefinedError(Exception): """User didn't define an input and output in the configuration file""" pass class DecodeError(Exception): pass class ElasticSearchUploaderError(Exception): pas...
#!/usr/bin/env python # -*- coding: utf-8 -*- n = list(map(int, input().split())) def slove1(): ans, tmp = 0, -1 lmax,rmax = [0]*len(n), [0]*len(n) for i in range(1, len(n)): tmp = max(tmp, n[i-1]) lmax[i] = tmp tmp = -1 for i in range(len(n)-2, -1, -1): tmp = max(tmp, n[i+...
# listFunctions.py # Contains basic list manipulation functions # J. Hassler Thurston # 26 November 2013 (Adapted from Mathematica code written in 2010/2011) # Python 2.7.6 # returns a running sum of the elements in ls def cumulativeSum(ls): total = 0 answer = [] for i in ls: total += i ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def getDecimalValue(self, head: ListNode) -> int: binary_list = [] current = head while current: ...
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http: // www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
_item_fullname_='Bio.Seq.Seq' def is_biopython_Seq(item): item_fullname = item.__class__.__module__+'.'+item.__class__.__name__ return _item_fullname_==item_fullname
def ci(A, l, r, k): while r-l > 1: mid = (l + (r-l))//2 if A[mid] >= k: r=mid else: l=mid return r def longestSubsequence(a,n): t = [0 for _ in range(n+1)] l=0 t[0] = a[0] l=1 for i in range(1, n): if a[i] < t[0]: t[0] = a[...
passmark=0 # declaring variables defer=0 fail=0 all=0 def all(): try: #this won't let strings to pass while True: passmark=int(input("Enter the Pass mark :")) # getting the user's passmark if passmark == 0 or passmark == 20 or passmark == 40 or passmark == ...
def extract(graph): ''' Generate a dictionary from a NetworkX Graph. The key is the index (primary node identifier) of the node in the graph. The value is a dict with index, label (original node identifier), room (a node attribute from the source data), and a list of neighbors (by graph index v...
def dobra_lista(lista): nova_lista = [] for valor in lista: novo_elemento = 2 * valor nova_lista.append(novo_elemento) return nova_lista #---------------------------------------------------------------- numeros = [3, 6, 10] numeros_emdobro = dobra_lista(numeros) print(numeros) print(numeros...
def test_length(devnetwork, chain): assert len(chain) == 1 chain.mine(4) assert len(chain) == 5 def test_length_after_revert(devnetwork, chain): chain.mine(4) chain.snapshot() chain.mine(20) assert len(chain) == 25 chain.revert() assert len(chain) == 5 def test_getitem_negative_...
""" Given k sorted arrays, merge them into a single sorted array eg. merge({{1,4,7}, {2,5,8}, {3,6,9}}) {1,2,3,4,5,6,7,8,9} """ def merge(arrays: list): return _merger(arrays) def _merger(arrays): if len(arrays) == 1: return arrays if len(arrays) == 2: array = merge_2_sorted(arrays[0...
input = """ bad :- r1, r2. bad :- g1, g2. bad :- b1, b2. bad :- r2, r3. bad :- g2, g3. bad :- b2, b3. bad :- r3, r1. bad :- g3, g1. bad :- b3, b1. r1 :- not g1, not b1. g1 :- not b1, not r1. b1 :- not r1, not g1. r2 :- not g2, not b2. g2 :- not b2, not r2. b2 :- not r2, not g2. r3 :- not g3, not b3. g3 ...
''' Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example: Given binary tree {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 return its bottom-up level order traversal as: [ [15,7], [9,20], [3] ] ''...
class Node: __slots__ = ['key','value','prev','next'] def __init__(self, key, value): self.key = key self.value = value self.prev = None self.next = None class LRUCache: def __init__(self, capacity): self.capacity = capacity self.size = 0 self.mapp...
#Um programa que calcula a soma de todos os números ímpares entre 1 e 500 soma = 0 count = 0 for i in range (1, 501, 2): if i % 3 == 0: soma+=i count+=1 print('A soma dos {} valores ímpares múltiplos de 3 entre 1 e 500 é {}'.format(count,soma))
stype = """ /* === Shared === */ QStackedWidget, QLabel, QPushButton, QRadioButton, QCheckBox, QGroupBox, QStatusBar, QToolButton, QComboBox, QDialog { background-color: #222222; color: #BBBBBB; font-family: "Segoe UI"; } /* === QWidget === */ QWidget:window { background: #222222; colo...
# Aprimore o desafio 93 para que ele funcione com vários jogadores, incluindo um sistema de visualização de detalhes do aproveitamento de cada jogador total = npc = 0 gols = list() jogador = dict() jogadores = list() while True: print('-=' * 22) jogador['nome'] = str(input('Nome do Jogador: ')).strip() np...
#!/usr/bin/env python3 # https://abc067.contest.atcoder.jp/tasks/arc078_a n = int(input()) a = [int(x) for x in input().split()] s = sum(a) b = a[0] m = abs(s - 2 * b) for i in range(1, n - 1): b += a[i] m = min(m, abs(s - 2 * b)) print(m)
# SPDX-License-Identifier: MIT # # keys.py - includes Discord bot token # # Copyright (c) 2019 Joe Dai. TOKEN = ''
class Plugin(object): def __init__(self, dogen, args): self.dogen = dogen self.log = dogen.log self.descriptor = dogen.descriptor self.output = dogen.output self.args = args @staticmethod def inject_args(parser): return parser def prepare(self, **kwargs...
#셀프 넘버는 1949년 인도 수학자 D.R. Kaprekar가 이름 붙였다. 양의 정수 n에 대해서 d(n)을 n과 n의 각 자리수를 더하는 함수라고 정의하자. 예를 들어, d(75) = 75+7+5 = 87이다. #양의 정수 n이 주어졌을 때, 이 수를 시작해서 n, d(n), d(d(n)), d(d(d(n))), ...과 같은 무한 수열을 만들 수 있다. #예를 들어, 33으로 시작한다면 다음 수는 33 + 3 + 3 = 39이고, 그 다음 수는 39 + 3 + 9 = 51, 다음 수는 51 + 5 + 1 = 57이다. 이런식으로 다음과 같은 수열을 만들 ...
def generate_images(autoencoder, K, n_images=1): """Generate n_images 'new' images from the decoder part of the given autoencoder. returns (n_images, channels, height, width) tensor of images """ # Concatenate tuples to get (n_images, channels, height, width) output_shape = (n_images,) + data_shape with ...
# coding: utf8 # try something like orcadb=DAL("sqlite://orca.db") current_user_alias = (auth.user and auth.user.first_name+" "+auth.user.last_name) or "Anónimo" orcadb.define_table("type_graph", SQLField("name", notnull=True, default=None), SQLField("description", "text", default=None), SQLField("f...
model = Model() i1 = Input("input", "TENSOR_FLOAT32", "{3,4,2}") perms = Parameter("perms", "TENSOR_INT32", "{3}", [1, 0, 2]) output = Output("output", "TENSOR_FLOAT32", "{4,3,2}") model = model.Operation("TRANSPOSE", i1, perms).To(output) # Example 1. Input in operand 0, input0 = {i1: # input 0 [0, 1, 2, 3...
[ { 'date': '2016-01-01', 'description': 'Neujahr', 'locale': 'de-BE', 'notes': '', 'region': '', 'type': 'NF' }, { 'date': '2016-03-27', 'description': 'Ostern', 'locale': 'de-BE', 'notes': '', 'region': '', 'ty...
description = 'TOF counter devices' group = 'lowlevel' tango_base = 'tango://cpci3.toftof.frm2:10000/' devices = dict( timer = device('nicos.devices.entangle.TimerChannel', description = 'The TOFTOF timer', tangodevice = tango_base + 'toftof/det/timer', fmtstr = '%.1f', visibility...
def colorify(s, color): color_map = { "grey": "\033[90m", "red": "\033[91m", "green": "\033[92m", "yellow": "\033[93m", "purple": "\033[94m", "pink": "\033[95m", "blue": "\033[96m", } return color_map[color] + s + "\033[0m" def underline(s): ret...
class ItemAlreadyStored(Exception): pass class ItemNotStored(Exception): pass
#!/usr/bin/env python3 def execute(): with open('./input/day.1.txt') as inp: lines = inp.readlines() data = [l.strip() for l in lines if len(l.strip()) > 0] return count_increasing(data), count_increasing(data, 3) tests_failed = 0 tests_executed = 0 def verify(a, b): global tests_executed ...
_base_="../base-chexpert-chest_xray_kids-config.py" # epoch related total_iters=5000 checkpoint_config = dict(interval=total_iters) model = dict( pretrained='work_dirs/hpt-pretrain/resisc/moco_v2_800ep_basetrain/50000-iters/moco_v2_800ep_basetrain-resisc_50000it.pth', backbone=dict( norm_train=True, frozen_...
def extractHikkinoMoriTranslations(item): """ # 'Hikki no Mori Translations' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None if item['title'].lower().startswith('chapter') or item['title'].lower().starts...
# # Copyright 2021 Splunk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...