content
stringlengths
7
1.05M
#!/usr/bin/env python # -*- coding: UTF-8 -*- # This file is part of the jetson_stats package (https://github.com/rbonghi/jetson_stats or http://rnext.it). # Copyright (c) 2020 Raffaello Bonghi. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Publi...
# Crie um programa que leia nome, sexo e idade de várias pessoas, guardando os dados de cada pessoa em um dicionário e todos os dicionários em uma lista. No final, mostre: A) Quantas pessoas foram cadastradas B) A média de idade C) Uma lista com as mulheres D) Uma lista de pessoas com idade acima da média cadastro = li...
#python code #list of numbers list=[1,3,14,5,19,66,2,53,105,10,24,27,6,5,85,34,56,3,2,35,78,2,3,98,43,2,1,56,8,43,22,12] print("\n \nThe list of numbers to be fitered through:\n" + str(list) + "\n\n") #get the user tp input minimum value specifiedNumber = int(input("Please specify a minimum number: ")) #create a n...
# -*-coding:utf-8 -*- #Reference:********************************************** # @Time    : 2019-09-23 19:40 # @Author  : Fabrice LI # @File    : 539_move_zeroes.py # @User    : liyihao # @Software: PyCharm # @Description: Given an array nums, write a function to move all 0's to # the end of it while...
begin_unit comment|'# Copyright 2011 Justin Santa Barbara' nl|'\n' comment|'# All Rights Reserved.' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in compliance with the License. You may obtain' nl|'\n' co...
class Song(object): def __init__(self, lyrics): #super(self, lyrics).__init__() self.lyrics = lyrics def sing_me_a_song(): for line in self.lyrics: print(line) hap = Song(["Happy birthday to you", "I don't want to get sued", "So I'll stop right there...
def set_figure_for_paper(figure): figure.xaxis.axis_label_text_font_size = "24pt" figure.yaxis.axis_label_text_font_size = "24pt" figure.legend.label_text_font_size = "22pt" figure.xaxis.major_label_text_font_size = "18pt" figure.yaxis.major_label_text_font_size = "18pt"
# -*- coding: utf-8 -*- """ # # DATE : 03,October 2017 # # AUTHOR : AMIT.JAIN@LNTTECHSERVICES.COM # # DESCRIPTION : This script is used to for Static Constants variables. # # """ class Constants: # # File Name Constants CONFIG_LIST = ['Config1_KeyON_OFF.xlsx', 'Config2_KeyON_N...
MQTT_SUB_OPT_NO_LOCAL = 0x04 MQTT_SUB_OPT_RETAIN_AS_PUBLISHED = 0x08 MQTT_SUB_OPT_SEND_RETAIN_ALWAYS = 0x00 MQTT_SUB_OPT_SEND_RETAIN_NEW = 0x10 MQTT_SUB_OPT_SEND_RETAIN_NEVER = 0x20
# Faça um Programa que verifique se uma letra digitada é vogal ou consoante # Ivo Dias # Recebe a letra letra = input("Informe uma letra: ") # Faz a verificação if ('AEIOU'.find(letra.upper()) >= 0): print("VOGAL") else: print("CONSOANTE")
#Exercício040 nota1 = float(input('\033[36mDigite sua nota em portugues: \033[m')) nota2 = float(input('\033[36mDigite sua nota em matematica: \033[m')) media = (nota1 + nota2)/2 if media < 5.0: print('\033[31mREPROVADO\nSua média foi {:.1f}\033[m'.format(media)) elif media >= 5.0 and media <= 6.9: print('\033[33mR...
# buildifier: disable=module-docstring # buildifier: disable=provider-params ProtoInfo = provider() def proto_library(**args): pass
""" [4/16/2014] Challenge #158 [Intermediate] Part 1 - The ASCII Architect https://www.reddit.com/r/dailyprogrammer/comments/236va2/4162014_challenge_158_intermediate_part_1_the/ #Description In the far future, demand for pre-manufactured housing, particularly in planets such as Mars, has risen very high. In fact, th...
''' +-----+ +------+ +--------+ B +---------+ D +---------+ | +-+---+ X+--+---+ | | | XX | | +--+--+ | XX | +-+--+ | A | | XX | | F | +--+--+ | XX | ...
sol_space = {} def foo(team_i, start, end): global teams global p_win global sol_space assert team_i >= start and team_i < end num_teams = end - start if num_teams == 1: return 1 if (team_i, start, end) in sol_space: return sol_space[(team_i, start, end)] psum = 0 # team_i becomes champio...
"""hxlm.core.io.hxl is an syntatic sugar for the fantastic libhxl-python This file at the moment is an draft. But is on IO submodule because libhxl package from the HXLStandard already is able to work to manipulate files from remote sources. It _only_ does not write on remote sources alone. See: - https://github.com/...
class SGD(dict): """This is the Stochastic Gradien Descent optimizer used to train the networks """ def __init__(self, epoch_size = 0, minibatch_size = 1, learning_ratesPerMB = "0.1", \ learning_rates_per_sample = None, momentum_per_mb = "0.9", \ momentum_per_sample = Non...
def solution(N, A): result = [0]*N # The list to be returned max_counter = 0 # The used value in previous max_counter command current_max = 0 # The current maximum value of any counter for command in A: if 1 <= command <= N: # increase(X) command if max_counter > r...
# -*- coding: utf-8 -*- class Total(object): """docstring for Total""" def __init__(self): self.p_buy = 0.0 # 買った額(jpy) self.n_buy = 0.0 # 買った数(currency) self.p_sell = 0.0 # 売った額(jpy) self.n_sell = 0.0 # 売った数(currency) def getBuyPrice(self): return self.p_buy ...
''' You can run it directly to see results. ''' def rob2(nums): # This problem is similar to Rober_I. # # However, for N houses, # the 1st house and the Nth house # can be robbed at the same time. # # So the tricky point is that this # problem can be divided into two # case...
""" # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children """ # class Solution(object): # def levelOrder(self, root): # q, ret = [root], [] # while any(q): # ret.append([node.val for node in q]) # ...
# -*- coding: utf-8 -*- def log(client, message): # print(message) out = "%d # %s (%d): \"%s\"" % ( message.chat.id, message.from_user.username, message.from_user.id, message.text, ) print(out)
#encoding: utf-8 def main(): print('hello, pyinstaller') if __name__ == '__main__': main()
# -*- coding: utf-8 -*- # @Author: 何睿 # @Create Date: 2018-12-23 11:15:08 # @Last Modified by: 何睿 # @Last Modified time: 2018-12-23 16:13:18 class Solution: def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: bool """ ...
string = "88be350-804b000-80489c3-f7f93d80-ffffffff-1-88bc160-f7fa1110-f7f93dc7-0-88bd180-3b-88be330-88be350-6f636970-7b465443-306c5f49-345f7435-6d5f6c6c-306d5f79-5f79336e-38343136-34356562-fff2007d-f7fceaf8-f7fa1440-df64fb00-1-0-f7e30ce9-f7fa20c0-f7f935c0-f7f93000-fff291c8-f7e2168d-f7f935c0-8048eca-fff291d4-0-f7fb5f0...
__author__ = 'Aaron Yang' __email__ = 'byang971@usc.edu' __date__ = '8/7/2020 11:46 PM' def find_all_prime(num): res = set() for val in range(2, num + 1): prime = True for y in range(2, val): if val % y == 0: prime = False if prime: res.add(val) ...
# MANEIRA UM: TAMBEM ESTA CERTA,POREM A SEGUNDA VAI SER MAIS SIMPLIFICADA.VEJA a = int(input('Digite o primeiro valor: ')) b = int(input('Digite o segundo valor: ')) c = int(input('Digite o terceiro valor: ')) if a < b and a < c: menor = a if b < c and b < a: menor = b if c < a and c < b: menor = c print('...
class Viewport: def __init__(self, posx=0, posy=0): self.posx = posx self.posy = posy class MessageLog: def __init__(self, entity_id=0, message_log_change=False): self.entity_id = entity_id self.message_log_change = message_log_change # ---------------------------------------...
''' Description: Given a function f(x, y) and a value z, return all positive integer pairs x and y where f(x,y) == z. The function is constantly increasing, i.e.: f(x, y) < f(x + 1, y) f(x, y) < f(x, y + 1) The function interface is defined like this: interface CustomFunction { public: // Returns positive inte...
class BaseError(Exception): pass class InvalidFormatError(BaseError): pass class InvalidPluginError(BaseError): pass class InvalidPageError(BaseError): def __init__(self, pages): super().__init__('Invalid page range: %i-%i' % pages)
#!/usr/bin/env python #-*- coding:utf-8 -*- # class Chinese(object): # country = "China" # def __init__(self,name,age): # self.name = name # self.age = age # def talk(self): # print("speak Chinese") # print(Chinese) # # # ####### 模拟类的创建过程 ####### # # 类的三要素:1、类名 2、继承的父类 3、类体的执行结果(类的名...
# # PySNMP MIB module CISCO-LIVEDATA-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LIVEDATA-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:47:36 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
Cortes = Goalkeeper('Francisco Cortes', 79, 74, 79, 69) Enrique = Outfield_Player('Sergio Enrique', 'DF', 51, 79, 77, 73, 79, 69) Alegre = Outfield_Player('David Alegre', 'MF', 75, 68, 75, 73, 74, 76) Carrera = Outfield_Player('Jardi Carrera', 'MF', 71, 73, 76, 74, 79, 78) Lleonart = Outfield_Player('Xavi Lleonart'...
""" Item 76: Verify Related Behaviors in TestCase SubClasses This item required different files. Look for the following files in the Item76 folder: utils.py utils_test.py assert_test.py data_driven_test.py You can create tests by subclasses the TestCase class from the unittest built-int module. Define one method ...
__author__ = 'author' info = { "title": "Cartoview Workforce Manager", "description": "Cartoview app to manage project/work group tasks. It provides a full management of a task status, priority, location ,attachments, comments", "author": 'Cartologic', "home_page": 'http://cartoview.org/apps/cart...
class Solution: def main(self, n, k): for i in range(1, k+1): for j in range(0, n+1): if i == 1: dp[i][j] = 1 continue for l in range(0, j+1): dp[i][j] += dp[i-1][j-l] % 1000000000 ...
class FakeLogger(object): def debug(self, *argv, **kwargs): pass def info(self, *argv, **kwargs): pass def warn(self, *argv, **kwargs): pass def error(self, *argv, **kwargs): pass class FakeWorkerCommand(object): def __init__(self): self.commands = [] def __call__(self, *args):...
def partition(x, left, right): i = left - 1 point = x[right] for j in range(left, right): if x[j] < point: i += 1 x[i], x[j] = x[j], x[i] x[i + 1], x[right] = x[right], x[i + 1] return i + 1 def quicksort(lst, left, right): if left < right: pi = partition(lst, left, right) quic...
class Cities: def __init__(self): self._cities = ['New York', 'Newark', 'New Delhi', 'Newcastle'] def __len__(self): return len(self._cities) def __iter__(self) -> iter: # Calling the Iterator Protocol with its instance print('Calling Cities instance __iter__' ) return ...
def parse(data): result=[] temp=0 for i in data: if i=="i": temp+=1 elif i=="d": temp-=1 elif i=="s": temp=temp**2 elif i=="o": result.append(temp) return result
async def test_neo4j_smoke(neo4j): data = await neo4j.data() assert 'node' in data
# Program showing some examples of lambda functions in python double_number = lambda num: num*2 reverse_string = lambda string: string[::-1] add_numbers = lambda x,y: x+y print(double_number(5)) print(reverse_string("Hi, this is a test !")) print(add_numbers(10, 23))
# # PySNMP MIB module Unisphere-Data-Router-CONF (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-Router-CONF # Produced by pysmi-0.3.4 at Mon Apr 29 21:25:35 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
class StandardScaler: def __init__(self): self.mean = [] self.scale = [] self.scale_nonzero = [] def fit(self, features): self.mean = features.mean(0) self.scale = features.std(0) self.scale_nonzero = self.scale != 0 def transform(self, features): sc...
""" There is an array with some numbers. All numbers are equal except for one. Try to find it! ``` find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2 find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55 ``` It’s guaranteed that array contains at least 3 numbers. The tests contain some very huge arrays, so think about performance. """ # My mos...
class Header: filename = "" filesize = 0 class MsgPacket: username = "" msg = "" def parsear(com): ######### The structure of a command is: COMMAND PARAMETER1 PARAMETER2 [...] PARAMETER-N ######### The user can also use "" to simbolize that spaces are considered part of a parameter, like this: COMMAND PARAMETE...
class DatenbankEinstellung(object): def __init__(self): self.name = '' self.beschreibung = '' self.wert = '' self.typ = 'Text' #Text, Float, Int oder Bool self.isUserAdded = True def __eq__(self, other) : if self.__class__ != other.__class__: return False ...
array = [9, 2, 3, 6] result = 2 def find_minimum(arr): min_value = arr[0] for x in arr: if x < min_value: min_value = x return min_value def main(): print("Input: " + str(array)) print("Expected: " + str(result)) print("Output: " + str(find_minimum(array))) if __name__...
'''Desenvolva um proframa que leia o comprimento de tres retas e diga ao usuario se elas podem ou nao forma um triangulo''' print("_-_"*20) print("analisador de trinagulos") print("_-_"*20) comprimento1 = float(input("Digite um comprimento: ")) comprimento2 = float(input("Digite outro comprimento: ")) comprimento3 = ...
""" Best Time to Buy and Sell Stock with Cooldown Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following re...
# some constants used for table naming TABLE_PREFIX = "tbl_" UNIFIED_PREFIX = "unified_" ETSI_PREFIX = "etsi_" ONEM2M_PREFIX = "onem2m_" SHELVE_PREFIX = "shelve_" SHELVE_KEYNAME = "shelve_key" def create_table_name(table_name, type="default"): if (type == "unified"): return TABLE_PREFIX + UNIFIED_PREFIX...
# -*- coding: utf-8 -*- # # Copyright (C) 2019 Edward Lau <elau1004@netscape.net> # Licensed under the MIT License. # """ The engine to orchestrate job executions. The orchestration is define as DAG of collections notated using the following brackets: [] - A list of jobs to be executed in sequence. {} - A set ...
factors = { 1 :{ 2: ("E" ,2) , 3: ("E" ,2) ,7: ("E" ,2) ,11: ("E" ,2) ,18: ("E" ,2) ,19: ("E" ,2) ,20: ("E" ,2) ,22: ("E" ,2) , 1:("E",1), 6:("E",1) , 21:("E",1) , 23:("E",1), 24:("E",1) , 25:("E",1) , 15: ("E",0) , 12: ("I",2), 13: ("I",2), 17: ("I",2), 5: ("I",1), 8: (...
# UNIDAD 05.D04 - D05 # Funciones print('\n\n---[Diapo 05]---------------------') print('Funciones') def saludar(): print('Hola! Estoy saludando desde la función') print('Antes de la función "saludar()" ') saludar() print('Después de la función "saludar()" ') print('\n\n---[Diapo 06]---------------------') pr...
class RequestsHolder: def __init__(self): self.requests = [] def __len__(self): return len(self.requests) def pop(self): return self.requests.pop() def push(self, request): self.requests.append(request)
class EnvWrapper(object): def __init__(self, env): self.env = env def __getattr__(self, item): return getattr(self.env, item)
# !/usr/bin/env python # -*-coding:utf-8 -*- # PROJECT : Question-Steo # Time :2020/12/17 22:26 # Warning :The Hard Way Is Easier def output(args): print("[最终结果为]: {}".format(args)) """ 台阶问题: 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。 """ """ A: 求多少种可能的题目,一般有递推性质,即 f(n) 和 f(n-1)...f(1)之间有关系 所以,从f(...
class Calc: def __init__(self, mensagem): self.mensagem = mensagem def soma(num1, num2): return num1 + num2 def mult(num1, num2): return num1 * num2 def sub(num1, num2): return num1 - num2 def div(num1, num2): return num1 / num2 def mensagem_designP(s...
# l_numbers = [list(range(1, 101))] # r_numbers = range(1, 101) # t_key_numbers = ( (1, "one"), (2, "Two"), (3, "Three"), (4, "Four"), (5, "Five"), (6, "Six"), (7, "Seven"), (8, "Eight"), (9, "Nine"), (10, "Ten"), (11, "Eleven"), (12, "Twelve"), (13, "Thirteen"), ...
def decode_test(session, decode_op, network, dataset, label_type, rate=1.0): """Visualize label outputs. Args: session: session of training model decode_op: operation for decoding network: network to evaluate dataset: Dataset class label_type: original or phone1 or phone2...
# Copyright (C) 2017-2019 New York University, # University at Buffalo, # Illinois Institute of Technology. # # 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 th...
# Escreva uma programa que converta uma temperatura digitada em ºC para ºF. print('-'*45) tempC = float(input('Digite a temperatrura em ºC : ')) tempF = (tempC * 1.8)+32 print('A temperatura de {}ºC equivale a {}ºF'.format(tempC, tempF)) print('-'*45)
# standards.py """ setting standards for the pipeline """ def get_img_xycenter(img, center_mode='n/2'): """ use the convention of alignshift to define img center. If nx, ny are even, the center is on [nx/2., ny/2.] Otherwise if odd, the center is on [(nx-1)/2.,(ny-1)/2.] Params -------- i...
""" You will be given a 2D matrix of English lower case letters. Your mission today is to find the longest path that following these rules below. The path can only be straight line or form a 90 degree corner; In each step, the next letter must be different from the current letter; The path cannot cut itself or form a ...
# minimal configuration, just to be able to run django-admin and create migrations SECRET_KEY = 'please-dont-use-this-settings-file' INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.co...
dicionario = {1: 'primeiro', 2: 'segundo', 3: 'terceiro', 4: 'quarto', 5: 'quinto', 6: 'sexto', 7: 'sétimo' } menorPeso = 3000 maiorPeso = 0 for i in range(1, 6): peso = float( input('Insira o peso do {} indi...
the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges' , 'pears' ,'apricots'] change = [1, 'pennies', 2,'dimes',3 ,'quarters'] for number in the_count: print("This is count %r" %number) for fruit in fruits: print("A fruit of type : %r "%fruit) for i in change: print("I got %r "%i) elements = [ ] ...
resp = '' cont = maior = menor = total = media = 0 while resp in 'Ss': n = int(input('Digite um número: ')) total += n cont += 1 if cont == 1: maior = menor = n else: if n > maior: maior = n elif n < menor: menor = n resp = str(input('Quer continua...
class Node: def __init__(self, value): self.value = value self.right = None self.left = None class BinaryTree: def __init__(self): self.root = None self.maxVal = 0 def pre_order(self): output = [] def _walk(node): output.append(node.val...
try: name=input("Enter file name:") file=open(fr"C:\Users\Frank\Desktop\GROUP-4\BSE-2021\src\files\{name}","r") read=file.read() print(read.upper()) except: print("File name doesn't exist in current directory")
class Solution: def multiply(self, num1: str, num2: str) -> str: val1, val2 = 0, 0 for i in num1: val1 = val1 * 10 + int(i) for i in num2: val2 = val2 * 10 + int(i) return str(val1 * val2)
''' Week-1: While Exercise -1 In this problem you'll be given a chance to practice writing some while loops. 1. Convert the following into code that uses a while loop. print 2 prints 4 prints 6 prints 8 prints 10 prints Goodbye! ''' n = 2 while ( n >= 2 and n <=10): print(n) n += 2 print("Goodbye!") ''' ...
name = "John" def func1(): print(name) def greet(name: str) -> str: return f'Hello, {name}' def main(): name = 'Mike' print(greet(name)) if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Copyright 2020, Yutong Xie, UIUC. Using recursion to delete node in BST ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # se...
def pytest_addoption(parser): parser.addoption("--epics", action="store", required=True, help="The target pysmurf server's epics prefix") parser.addoption("--config", action="store", default="/usr/local/src/pysmurf/cfg_files/stanford/" "exp...
""" Maintain context: short term memory about conversation history and the state of the chatbot's world """ class Context(dict): pass
class Reader: def __init__(self, filename): self.filename = filename self.data = [] #Case where we are using 8x8 if "8" in self.filename: with open(self.filename) as f: for line in f: digits = line.split(",") temp_dict = {"data": [int(i) for i in digits[:-1]], "answer": int(digits[-1:][0].st...
# -*- coding: utf-8 -*- def sparkline(actions, c_symbol=u'█', d_symbol=u' '): return u''.join([ c_symbol if play == 'C' else d_symbol for play in actions]) class Match(object): def __init__(self, players, turns, deterministic_cache=None, cache_mutable=True, noise=0): """ ...
# # PySNMP MIB module CX-IPX-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CX-IPX-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:32:02 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:...
# 006 - Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada: num = int(input('Digite um número: ')) print(f'O dobro de {num} é {2*num}, o triplo é {3*num} e a raiz quadrada é {(num**(1/2))}')
'''2) Dado um conjunto de n registros e cada registro contendo um valor real, faça um programa que calcule a média dos valores maiores que 10.''' #Verificando valor do loop registros = int(input('Quantidade de registros: ')) contador = 1 maior10 = [] #Criando loop while contador != registros+1: while True: ...
# 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 = { "additional_annotations": "additionalAnnotations", "additional_labels": "additionalLabels", "admission_controller": "admiss...
#Hola Mundo desde Python print("Hola Mundo!") #Declaración de variables saludo = "Hola, estamos en el año" año = 2021 print(saludo, año)
# # PySNMP MIB module WRS-MASTER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WRS-MASTER-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:23:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
# PROBLEM LINK:- https://leetcode.com/problems/two-sum/ class Solution: def twoSum(self, v, x): n = len(v) r = [] for i in range(0,n): for j in range(i+1,n): if(i != j and v[i] + v[j] == x): r.append(i) r.append(j) ...
class BenchmarkOperatorError(Exception): """ Base class for all benchmark operator error classes. All exceptions raised by the benchmark runner library should inherit from this class. """ pass class ODFNonInstalled(BenchmarkOperatorError): """ This class is error that ODF operator is not inst...
''' My initial solution not very fast and uses quite a bit of memory will look over to try and improve ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: ...
""" LeetCode 655. Print Binary Tree Print a binary tree in an m*n 2D string array following these rules: The row number m should be equal to the height of the given binary tree. The column number n should always be an odd number. The root node's value (in string format) should be put in the exactly middle of the firs...
"""packer_builder/specs/builders/common.py""" # pylint: disable=line-too-long def common_builder(**kwargs): """Common builder specs.""" # Setup vars from kwargs build_dir = kwargs['data']['build_dir'] builder_spec = kwargs['data']['builder_spec'] distro = kwargs['data']['distro'] builder_sp...
class Factor(object): def __init__(self, o, f=1.0): self.o = o self.f = f def __repr__(self): return "Factor()" def get_distance(self, point): return self.f * self.o.get_distance(point) def get_distance_numpy(self, x, y, z): return self.f * self.o.get_d...
# # PySNMP MIB module RFC1233-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RFC1233-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:56:30 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, 0...
#并不是只有open()函数返回的fp对象才能使用with语句。实际上,任何对象,只要正确实现了上下文管理,就可以用于with语句。 class Leilei(object): def __init__(self ,name): self.name=name #"""实现上下文管理是通过__enter__和__exit__这两个方法实现的。例如,下面的class实现了这两个方法:""" def __enter__(self): print("Leilei") return self def __exit__(self, exc_type, ex...
''' 0 이동시키기 여러개의 0과 양의 정수들이 섞여 있는 배열이 주어졌다고 합시다. 이 배열에서 0들은 전부 뒤로 빼내고, 나머지 숫자들의 순서는 그대로 유지한 배열을 반환하는 함수를 만들어 봅시다. 예를 들어서, [0, 8, 0, 37, 4, 5, 0, 50, 0, 34, 0, 0] 가 입력으로 주어졌을 경우 [8, 37, 4, 5, 50, 34, 0, 0, 0, 0, 0, 0] 을 반환하면 됩니다. 이 문제는 공간 복잡도를 고려하면서 풀어 보도록 합시다. 공간 복잡도 O(1)으로 이 문제를 풀 수 있을까요? ''' def moveZerosToEnd(...
""" Copyright Government of Canada 2018 Written by: Matthew Fogel, National Microbiology Laboratory, Public Health Agency of Canada Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. You may obtain a copy of the License at: http://www.apac...
# The isBadVersion API is already defined for you. # @param version, an integer # @return a bool def isBadVersion(version): pass class Solution(object): def firstBadVersion(self, n): """ :type n: int :rtype: int """ start = 1 end = n while start<=end: ...
""" 2.3 - Write a function to delete middle node of a LL """ # definition of ListNode class ListNode(): def __init__(self, val): self.val = val self.next = None # original question is somewhat misphrased # you just have to delete the provided node def deleteNode(n: ListNode): if n == No...
nota = [] aluno_e_nota = [] boletim = [] while True: aluno = str(input('Nome: ')).capitalize() aluno_e_nota.append(aluno) nota_1 = float(input('Nota 1: ')) nota.append(nota_1) nota_2 = float(input('Nota 2:')) nota.append(nota_2) media = (nota_1 + nota_2) / 2 aluno_e_nota.append(media)...
config_DTP = { "lr": 6.185037324617764e-05, "target_stepsize": 0.21951187497378802, "beta1": 0.9, "beta2": 0.999, "epsilon": 1.0170111936290766e-08, "lr_fb": 0.0019584756448113774, "sigma": 0.08372453893037193, "beta1_fb": 0.9, "beta2_fb": 0.999, "epsilon_fb": 7.541132645747324e-...
l, arr, moves = int(input()), [int(x) for x in input().split()], 0 for i in range(1, l): while arr[i] < arr[i-1]: arr[i] += 1 moves += 1 print(moves)
class Restaurante: def __init__ (self, nombre, tipo, number_served): self.nombre = nombre self.tipo = tipo self.number_served = 0 def describe_restaurant(self): print(self.nombre.title() + self.tipo.title()) def set_number_served(self): print(self.number_served.title()) def increment_number_served...