content
stringlengths
7
1.05M
''' >>>>>>. LISTAS EM PYTHON <<<<<<<< -> Para declarar a lista, bastas abrir colchetes []. Exemplo var = [] # Listas ao contrário de tuplas, São mutáveis e podem ser alteradas. Exemplos: -> O camando abaixo, lanche[3] = 'Picole', vai substituir o elemento no índice 3, no caso o Pudim, pe...
def default_key(x): """ Default comparison function.""" return x def order(seq, key=default_key, reverse=False): """ Return the order in which to take the items to obtained a sorted sequence.""" o = list(range(len(seq))) def wrap_key(x): x = seq[x] return key(x) o.sort(ke...
class HierarchicalSettingsDefault(object): """ Good for dealing with dark matter halos between 10^5 - 10^10 M_sun with small source sizes <10 pc """ def __init__(self): self.set_aperture_units('ANGLES') def set_aperture_units(self, units): self._aperture_units = units @pr...
class WeirdException(Exception): """ exception will be used everytime something weird happens, which should not happen. """ def __init__(self, message): """ call the parent class :param message: """ self.message = message super(Exception, self).__init__(...
midade = Hmaior = nomevelho = contM20 = 0 for p in range(1, 5): print('-=-' * 10) print(f'{p}º pessoa ') nome = str(input('Nome: ')).strip() idade = int(input('Idade: ')) sexo = str(input('Sexo [F/M]: ')).strip()[0] midade += idade if p == 1 and sexo in 'Mm': Hmaior = idade n...
#!/usr/bin/env python # encoding: utf-8 __author__ = 'sunny' #######################交易类型######################## #账户相关 #普通转账 TRX_TYPE_TRANSFER = 0 #代理领工资 TRX_TYPE_WITHDRAW_PAY = 1 #注册账户 TRX_TYPE_REGISTER_ACCOUNT = 2 #注册代理 TRX_TYPE_REGISTER_DELEGATE = 3 #升级代理 TRX_TYPE_UPGRADE_ACCOUNT = 4 #更新账户 TRX_TYPE_UPDATE_ACCOUNT...
def test_del_all_group(app, db): all_group = db.get_group_list() if len(all_group) == 0: pass else: for x in range(len(all_group)): app.group.delete_first_group()
class Solution: def findMaxLength(nums): maxlen = 0 for start in range(0, len(nums)): zeroes = 0 ones = 0 for end in range(start, len(nums)): if nums[end] == 0: zeroes += 1 else: ones += 1 ...
#import numpy as np class HTMLtable: """ HTML Table helper class. """ CELLTYPE = 'type' CELLCONTENTS = 'contents' CELLSPANDOWN = 'spandown' CELLSPANRIGHT = 'spanright' CELLTYPE_NORMAL = 0 CELLTYPE_BEGINSPANRIGHT = 1 CELLTYPE_BEGINSPANDOWN = 2 CELLTYPE_SPANNED ...
student_scores = input( "Input a list of student scores, separated by spaces:\n").split() for n in range(0, len(student_scores)): student_scores[n] = int(student_scores[n]) print(student_scores) highest_score = 0 for score in student_scores: if score > highest_score: highest_score = score print...
# encoding: utf-8 # module GH_Util.MetaBall calls itself MetaBall # from GH_Util, Version=1.0.0.0, Culture=neutral, PublicKeyToken=dda4f5ec2cd80803 # by generator 1.145 """ NamespaceTracker represent a CLS namespace. """ # no imports # no functions # classes class GH_CellInfo(object): """ GH_CellI...
def parse_command(data): direction, steps = data.strip().split(" ") return ( direction, int(steps), ) cmds = [] with open("input") as input: cmds = list(map(parse_command, input)) horizontal = 0 depth = 0 for direction, steps in cmds: if direction == "forward": horizontal ...
class Development(object): DEBUG = True # Turns on debugging features in Flask
#coding:utf-8 #这个脚本从同义词词林中生成例子 fPos = open("../../data/woodWikiTestPos1000") linesPos = list(fPos) fConf = open("../../data/woodWikiTestDiffClass1000") linesConf = list(fConf) fDiff = open("../../data/woodWikiTestConfused1000") linesDiff = list(fDiff) dictMap = map()
# @author:leacoder # @des: Trie (前缀树,字典树) 单词搜索 II # 将words存入 Trie 中,然后将board 中的字母 按顺序依次DFS 与 Trie 中字母比较 class Trie: #辅助 Trie def __init__(self): self.root = {} self.endofword = "#" def insert(self, word: str) -> None: node = self.root for char in word: node =...
class Pai: def __init__(self, nome, peso): self.nome = nome self.peso = peso class Filha(Pai): def __init__(self, nome, peso, cabelo): super().__init__(nome, peso) self.cabelo = cabelo pessoa1 = Pai('Alcimar', 95) filha1 = Filha('Mirella', 13, 'Loiro') print(filha1.nome) pri...
def One(num): for i in num: # Only creates one variable and that's it so Space Complexity: O(1) print(i) One([1, 2, 3, 4, 5]) # Space Complexity: O(1) def Two(num): array = [] # Creates array once O(1) for j in num: # O(1) array.insert(j, j) # Assigns value to index in array N times so Spa...
def hook_at_step(system, integrator, ar, gt, args, k): if k == 0: print('Deactivation reaction 2 3') ar.get_reaction(2).active = False ar.get_reaction(3).active = False if k == 1000000: print('Deactivate reactions 0, 1') ar.get_reaction(0).active = False ar.get_...
#!/usr/bin/python3 """ Python lists """ def main(): """ Main func """ # lists can contains multiple elements # in python these elements can be anything, to fully appreciate this feature you should tune yourself # to python duck typing mentality :) li1 = ["list", "set", "dictionary"] li2 = ["on...
x = 1 class Foo(): z = 3 def __init__(self): self.y = 2 def bar(self): print(x) print(self.x) print(self.z) @property def x(self): return self.y if __name__ == '__main__': Foo().bar()
__title__ = "pyNfsClient" __description__ = "Pure python NFS client" __version__ = "0.1.5" __license__ = "MIT" __url__ = "https://github.com/CharmingYang0/NfsClient" __author__ = "Cooper Yang" __author_email__ = "cm_yang@yeah.net"
class Project: """ INCEpTION's Project object """ def __init__(self, project_id: int, project_name: str): self.project_id = project_id self.project_name = project_name def __eq__(self, other): return isinstance(other, Project) and \ other.project_id == self.p...
""" The latest way to print to the screen in Python (>= 3.6) is with f-strings. In this Bite we'll get you to calculate whether a person is able to drive or not based on their minimum age which is stored in the constant MIN_DRIVING_AGE. Print name is allowed to drive or name is not allowed to drive based on the age b...
# Copyright (c) 2014 The Sippet Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'All', 'type': 'none', 'dependencies': [ 'sippet.gyp:*', 'sippet_phone.g...
def get_optimizer_lr_str(cfg, optimizer): if cfg.log.only_base_lr is False: lr_strs = ['{:.6f}'.format(g['lr']).rstrip('0') for g in optimizer.param_groups] lr_str = ', '.join(lr_strs) else: lr_str = '{:.6f}'.format(optimizer.param_groups[0]['lr']) return lr_str
#!/usr/bin/python # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def partition(self, head, x): """ :type head: ListNode :type x: int :rtype: ListNode """ if not head or not head.next: ...
""" Constants. Constants for feeds and feed entries. """ ATTR_ID = "id" ATTR_GUID = "guid" ATTR_PUB_DATE = "pubDate" ATTR_TIME = "time" ATTR_TITLE = "title" ATTR_UPDATED = "updated"
class Solution: def bitwiseComplement(self, N: int) -> int: n = bin(N) return 2 ** (len(n) - 2) - 1 - N if __name__ == "__main__": s = Solution() print(s.bitwiseComplement(5))
dados = [] listacompleta = [] listamaispesadas = [] listamaisleves = [] contador = 0 #contador de pessoas cadastradas maiorpeso = 0 #numero do maior peso menorpeso = 0 #numero do menor peso nomemaior = '' #nome do mais pesado nomemenor = '' #nome do menos pesado while True: dados.append(str(input('NOME: ')).upper(...
x1=int(input("enter a x1 value:")) x2=int(input("enter a x2 value:")) y1=int(input("enter a y1 value:")) y2=int(input("enter a y2 value:")) result= ((((x2-x1)**2)+((y2-y1)**2))**0.5) print("distance between two points",result)
server_ip = "192.168.1.10" port_drone_control = 20001 port_drone_video = 20006 port_operator_control = 20000 port_operator_video = 20005 CMD_START = 'start' CMD_STOP = 'stop'
# -*- coding: utf-8 -*- """ PM status data structure module. Provides a orderable data structure for point mutation status. e.g. Y > Conserved is True; Y(aa_pm=0) > Y(aa_pm=None) is True. NOTE: PM status objects with inconsistent stdseq are not orderable, and it regards sequences which gaps, '-', has been re...
# -*- coding: utf-8 -*- """ Simple transfomer: the C{@about=""} is added to the C{<head>} and C{<body>} elements (unless something is already there). Note that this transformer is always invoked by the parser because this behaviour is mandated by the RDFa syntax. @summary: Add a top "about" to <head> and <body> @requi...
matriz = [] valor = [] # ou matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for x in range(0, 3): for y in range(0, 3): valor.append(int(input(f'Digite um valor para [{x}, {y}]: '))) matriz.append(valor[:]) valor.clear() print('-='*30) for x in range(0, 3): for y in range(0, 3): print(f'[{mat...
class GameExited(BaseException): pass class PlayerDied(BaseException): pass
times = ('corinthians', 'palmeiras', 'santos', 'gremio') print(f'Esta é a lista de times do brasileirão: {times}') print('-='*15) print(f'Este são os dois primeiros times {times[0:2]}') print('-='*15) print(f'Este são os dois ultimos: {times[-2:]}') print(f'Esta e a ordem alfabética deles {sorted(times)}') print(f'O co...
""" 33.39% 75.45% 实际是斐波拉契数列 第一种方法 时间,空间复杂度都是 O(n) 第二种递推法更厉害,不需要空间换时间,时间复杂度 O(n),空间复杂度 O(1) 至于这题为什么动态转移方程是斐波拉契 Because from the [n-1] point, we can take one single step to reach [n]. And from the [n-2] point, we could take two steps to get there. There is NO overlapping between these two solution sets, because we di...
''' Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 ''' # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x ...
in_file = open("watch-history.html", "r") vids = 0 line = in_file.readline() while line != "": if "https://www.youtube.com/watch" in line: break line = in_file.readline() in_file.close() refs = line.split("href") outstring = "" for i in range(1, len(refs)): link = refs[i][2:45] outstring += link + "\n" vids+...
# # @lc app=leetcode.cn id=51 lang=python3 # # [51] n-queens # None # @lc code=end
numeros = list() maior = 0 maiorposi = list() menor = 0 menorposi = list() for c in range(0, 5): numeros.append(int(input(f'Digite um valor para a posição {c}:'))) for pos, num in enumerate(numeros): # Verificando Maior if numeros[pos] == max(numeros): maior = numeros[pos] if numeros[pos] == m...
#! /usr/bin/env python3 # Copyright(c) 2019 Intel Corporation. # License: MIT See LICENSE file in root directory. # Get class color map for road segmentation # classes_color_map = [ (150, 150, 150), (58, 55, 169), (211, 51, 17), (157, 80, 44), (23, 95, 189), (210, 133, 34), (76, 226, 202),...
# 33. Search in Rotated Sorted Array solution improvised per # https://leetcode.com/problems/search-in-rotated-sorted-array/discuss/14425/Concise-O(log-N)-Binary-search-solution def binarysearch(array,target,pivotindex): low=0 high=len(array)-1 result=-1 while low<=high: mid=(low+high)//2 ...
#Julian Conneely 23/03/18 #using len (list) #print the first element of the list, if it contains even number of elements. list = [1, 2, 3, 4] if len(list) % 2 == 0: print(list[0])
viagem = float(input("digite a distancia de sua viagem em km")) if viagem >= 200: print("Sua viagem será de {}KM o valor de sua viagem será de R${:.2f}".format(viagem, viagem*0.45)) else: print("sua viagem será de {}km o valor de sua viagem será de R${:.2f}".format(viagem, viagem*0.50))
class Transaction: def __init__(self, first_name, last_name, username, email, address, address2, country, postal, payment_method, cc_name, cc_number, cc_expiration, cc_cvv, ): self.__first_name = first_name self.__last_name = last_name self.__username = username self.__email = email ...
#Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. #Calcule e mostre o total do seu salário no referido mês. valor = float(input('Digite o valor que ganha por hora: ')) horas = float(input('Digite quantas horas trabalhadas fez hoje: ')) dias = int(input('Quantos dias voc...
# # PySNMP MIB module CISCO-TCP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-TCP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:57:36 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
# maybe worked with network_x def get_maxx_maxy_non_pythonic(self, node_dict, nodes): maxx = -999999 maxy = -999999 for node, i in enumerate(nodes): # certainly a more pythonic way exists x = node_dict[i][0] if x > maxx: maxx = x y = node_dict[i][1] if y >...
x = [1, 2] print (x) print (x[0]) x[0] = 33 print (x) my_list = [101, 20, 10, 50, 60] for item in my_list: print(item) my_list = ["Spoon", "Fork", "Knife"] for item in my_list: print(item) my_list.append ("Ladle") for item in my_list: print(item) print (my_list[3]) # Copy of the array to sum my_list ...
# Do not edit this file directly. # It was auto-generated by: code/programs/reflexivity/reflexive_refresh load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def halley(): http_archive( name="halley" , build_file="//bazel/deps/halley:build.BUILD" , sha256="f4ff28208cb144e...
def solution(arr): answer = [arr[0]] for num in arr: if answer[len(answer)-1] != num: answer.append(num) return answer
# Copyright (c) 2013, Jeff Terrace # All rights reserved. """Module for connecting to and controlling the Logitech Harmony Link"""
''' Provides the minimal behaviors for a Cell. @author: Quinn Liu (quinnliu@vt.edu) @author: Michael Cogswell (cogswell@vt.edu) @version: July 22, 2013 ''' class Cell(object): def __init__(self, isActive=None, wasActive=None): self.isActive = False # biologically equivalent to # generating 1 or more spikes s...
#!/usr/bin/env python DESCRIPTION = "FNV1a hash (64-bit)" TYPE = 'unsigned_long' TEST_1 = 14074705352429455374 def hash(data): val = 0xcbf29ce484222325 for c in data: val = (0x100000001b3 * (c ^ val)) & 0xffffffffffffffff return val
def text_box(self, str): box = TextMobject(str).scale(0.3) box.add(SurroundingRectangle(box, stroke_color = DARK_GREY)) return box
#Crie um programa que leia dois valores e mostre um menu na tela: #[ 1 ]somar #[ 2 ]multiplicar #[ 3 ]maior #[ 4 ]novos numeros #[ 5 ]sair do programa #seu programa devera realizar a opercao solicitada em cada caso. #minha resposta #from time import sleep #print('\033[36m=-=\033[m'*20) #print('\033[7;33m{:^80}'.format...
def separador(): print('*' * 50) def print_centralizado(txt): print(f'{txt}'.center(50)) def print_personalizado(txt): print('*' * 50) print_centralizado(txt) print('*' * 50) def continuar(): input('Pressione enter para continuar...') def gerar_numero(txt='lul'): entrada = int(input(...
#EJEMPLO 2 RETORNO DE DATOS #retorno de datos se devuelven a la llamada de la función que recoge los datos def retorno_superficie(lado): sup=lado*lado return sup # con la instrucción return se retorna los datos de la función va=int(input("introduce el valor del cuadrado:")) superficie=retorno_superficie(va) #...
class ManagerInterface(object): def __init__(self): self._state = {} @property def state(self): return self._state def _get_state_data(self, obj): raise NotImplementedError def subscribe(self, obj): key, value = self._get_state_data(obj) self._subscribe(key...
class Point3D(): def __init__(self, x, y, z): self.coord = [x, y, z] #1 def __ne__(self, other): if (self.coord[0] != other.coord[0]) or (self.coord[1] != other.coord[1]) or (self.coord[2] != other.coord[2]): return True else: return False #2 def __eq...
class Node(object): def __init__(self, value): self.val = value self.left = None self.right = None def validateBST(node, min, max): if not node: return True if node.val < min or node.val > max: return False return validateBST(node.left, min, node.val) and valida...
""" 4. Task Your provided code section should find a meaning of a word from a dictionary containing key/value pairs of word: value. line. """ input_word = input('Enter a word(Passed/Failed/Other) = ') dictionary = {'Passed':'You have practiced at home.', 'Failed': 'You was not serious.', 'Other': 'Write your own meanin...
name = 'Zed A. Shaw' age = 35 # years height = 74 # inches weight = 180 # lbs eyes = 'Blue' teeth = 'White' hair = 'Brown' height_cm = 74 * 2.54 # height in centimeters weight_kg = 180 * 0.45359237 # weight in kilograms print(f"Let's talk about {name}.") print(f"He's {height_cm} centimeters tall.") p...
class Stack: def __init__(self): self.stack = [] self.max_stack = [] def push(self, val): self.stack.append(val) if not self.max_stack or val > self.stack[self.max_stack[-1]]: self.max_stack.append(len(self.stack) - 1) def pop(self): if not self.stack: ...
key_dict = {"k_kp_minus": 269, "k_2": 50, "k_pageup": 280, "k_capslock": 301, "k_rmeta": 309, "k_hash": 35, "k_space": 32, "k_caret": 94, "k_end": 279, "k_leftbracket": 91, "k_euro": 321, "k_6": 54, "k_semicolon": 59, "k_9": 57, "k_pagedown": 281, ...
# https://leetcode.com/problems/valid-parentheses/ class Solution: def isValid(self, s: str) -> bool: # This question will be solved using a stack. # The idea is: a valid push to the stack consists of a left paren (of any type). # We will process the string one e...
_base_ = "./FlowNet512_1.5AugCosyAAEGray_AdamW_ClipGrad_AvgMaxMin_Pbr_01_ape.py" OUTPUT_DIR = "output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_AdamW_ClipGrad_AvgMaxMin_lmPbr_SO/lamp" DATASETS = dict(TRAIN=("lm_pbr_lamp_train",), TEST=("lm_real_lamp_test",)) # rl3 # objects lamp Avg(1) # ad_2 0.96 0.96 # ad...
str_1 = "HelloWorld" str_2 = "Hello World" str_3 = "one\ntwo\rthree\r\nfour\vfive\x0bsix\fseven\x0ceight\x1cnine\x1dten\x1eeleven\x85twelve\u2028thirteen\u2029" print("str_1 : ") print(str_1.splitlines()) print(str_1.splitlines(keepends = True)) print("str_2 : ") print(str_2.splitlines()) print(str_2.splitlines(kee...
def isPrime(numb): dil = 2 while dil * dil <= numb and numb % dil != 0: dil += 1 return dil * dil > numb def generator(number): res, first, second = [2], 2, 1 while len(res) < number: # first, second = second, first + second LucasNumber = first + second first = secon...
pkgname = "firmware-ipw2200" pkgver = "3.1" pkgrel = 0 pkgdesc = "Firmware for the Intel PRO/Wireless 2200BG wifi cards" maintainer = "q66 <q66@chimera-linux.org>" license = "custom:ipw2200" url = "http://ipw2200.sourceforge.net" source = f"http://firmware.openbsd.org/firmware-dist/ipw2200-fw-{pkgver}.tgz" sha256 = "c6...
class Data: def __init__(self, in_path: str, out_path: str): self.in_path = in_path self.out_path = out_path self.all_data = [] @staticmethod def treat_data(data): unwanted_chars = 'áãâêéíóõôú' wanted_chars = 'aaaeiooou' for i, char in enumerate(unwanted...
def search(ordered_list, term): ordered_list_size = len(ordered_list) for i in range(ordered_list_size): if term == ordered_list[i]: return i elif ordered_list[i] > term: return None return None scores = [2, 3, 4, 6, 7] search_term = 5 position = search(scores, ...
""" Represents a TicTacToe Board """ def _pretty_print_item(item): if item is not None: return item return "-" class Board: """ A TicTacToe Board """ def __init__(self, win_condition, valid_move, max_moves: int, width: int, height: int, depth: int = 1): self.width = width ...
# In hr.py class PayrollSystem: def calculate_payroll(self, employees): print('Calculating Payroll') print('===================') for employee in employees: print(f'Payroll for: {employee.id} - {employee.name}') print(f'- Check amount: {employee.calculate_payroll()}'...
class Triangulo: def __init__(self, a, b, c): self.a = a self.b = b self.c = c def perimetro(self): return self.a + self.b + self.c def tipo_lado(self): if self.a == self.b == self.c: return "equilátero" elif self.a == self.b or self.a == self.c or self.b == se...
'''Faça um programa que leia um número qualquer e mostre o seu fatorial. ex:. 5! = 5 x 4 x 3 x 2 x 1 = 120 (while é for)''' print('\033[1;33m-=\033[m' * 20) n1 = int(input('\033[36mDigite um número:\033[m ')) fatorial = 1 contador = 1 while contador <= n1: fatorial = fatorial * contador contador += 1 print('O ...
# # PySNMP MIB module PPP-IP-NCP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PPP-IP-NCP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:32:57 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...
# Color palettes palettes = {} palettes['palette_0'] = ["rgba(134, 149, 184, 0.5)", "rgba(184, 179, 134, 0.5)", "rgba(184, 134, 134, 0.5)", "rgba(134, 184, 132, 0.5)", "rgba(140, 134, 184, 0.5)", "rgba(184, 134, 176, 0.5)"] palettes['Tableau10'] = ["#4e79a7", "#f28e2...
class stack: def __init__(self): self.stack = [] def push(self, obj): self.stack.append(obj) def pull(self): if len(self.stack) > 0: return self.stack.pop() return None def top(self): if len(self.stack) > 0: return self.stack[-1] ...
""" Lowest Common Ancestor in Binary Tree """ class Node: """ Node contains actual data and address to left and right node """ def __init__(self, data): self.data = data self.left = None self.right = None def lowest_common_ancestor(root, a, b): """ lowest common ancestor in BST "...
def pop_row(df, limit): _filter = df['hour']!=limit df = df[_filter] return df.reset_index(drop=True) def get_by_hour(df, hour): tmp = df['hour']==hour return df[tmp]
class HEX2HSL: def __init__(self,RGB): self.RGB = RGB self.R = int((self.RGB[1:3]),16) self.G = int((self.RGB[3:5]),16) self.B = int((self.RGB[5:7]),16) self.H = 0; self.S = 0; self.L = 0; R = (self.R/255) G = (self.G/255) B = (self.B/...
class SparkConf: vals: dict = {} def set(self, key: str, val: str): self.vals[key] = val def get(self, key: str): if key not in self.vals: raise Exception(f"Conf value not found for {key}") return self.vals[key] class SparkSessionMock: def __init__(self): ...
print ("This is Han") print ("This is Bin") for x in range(10): print (x) print (x)
x=int(input("enter an integer:")) y=float(input("enter an fload number:")) z=input("enter another number:") def main(x,y,z): if x>y and x>z: print ("bigest number: ",x) elif y>x and y>z: print ("bigest: ", y) elif z>x and z>y: print ("bigest: ",z) else: p...
def MinMax(temperaturas): print('A menor temperatura do mês foi: ',mínima(temperaturas), 'C.') print('A maior temperatura do mês foi: ',máxima(temperaturas), 'C.') def mínima(temps): min = temps[0] i = 1 while i < len(temps): if temps[i] < min: min = temps[i] i = i + 1 ...
def aumentar(valor, taxa): return valor + (valor * (taxa/100)) def diminuir(valor, taxa): return valor - (valor * (taxa / 100)) def dobro(valor): return valor * 2 def metade(valor): return valor / 2
class TaxonomyTreeNode: def __init__(self, taxId, parent, name, rank): self.taxId = taxId self.name = name self.rank = rank self.parent = parent self.children = [] def addChild(self, child): self.children.append(child) def setChildren(self, children): ...
# Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd # number of characters then it should replace the missing second character of the final pair with an underscore ('_'). # # Examples: # # solution('abc') # should return ['ab', 'c_'] # solution('abcdef') # sh...
''' This is the main entry point for the clubadmin package as a whole and provides the launching pad for the sub-packages that may be installed. '''
"""contains custom scrapy pipelines.""" class TypePipeline(object): """This class renames _type field.""" def process_item(self, item, spider): """implements https://doc.scrapy.org/en/latest/topics/item-pipeline.html#process_item""" if item['_type']: item['schema'] = item.pop('_t...
def test_locals(): d1 = locals() d2 = locals() assert d1 is d2
""" Day 4: Binomial Distribution II A manufacturer of metal pistons finds that, on average 12% of the pistons they manufacture are rejected because they are incorrectly sized. What is the probability that a batch of 10 pistons will contain: 1. no more than 2 rejects? 2. At least 2 rejects? b(x,n,p) = (n p)...
def eq(a, b): return a == b def le(a, b): return a <= b def lt(a, b): return a < b def ge(a, b): return a >= b def gt(a, b): return a > b def itemgetter(*items): if len(items) == 1: item = items[0] def g(obj): return obj[item] else: def g(obj): return tuple(obj[item] for ...
# # PySNMP MIB module ZYXEL-MAC-AUTHENTICATION-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-MAC-AUTHENTICATION-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:50:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python vers...
def one_moov(right, left, up): if up == None: pass else: return up if right == None: pass else: return right if left == None: pass else: return left def get_nb_moov(right, left, up): nb_moov = 3 if right == None: nb_moov -= 1 if left == None: nb_moov -= 1 if up == None...
N = int(input()) li = list(map(int, input().split())) # N = 6 # li = [5, 2, 4, 6, 1, 3] for i in range(1, N): print(*li) v = li[i] for j in reversed(range(0, i)): if li[j] > v: li[j + 1] = li[j] li[j] = v else: break print(*li)
def readable_timedelta(days): # insert your docstring here """Returns a string of the number of week(s) and day(s) in the given days. Args: days (int): number of days to convert """ weeks = days // 7 remainder = days % 7 return "{} week(s) and {} day(s)".format(weeks, remainder)
#--------- Training ---------# # parameters size = 10 fov = 3 n_agents = 3 train_episodes = 5000 max_steps = size * size r = 0.0005 batch_size = 32 gamma = 0.99 buffer_limit = 50000 log_interval = 20 max_episodes = 30000 max_epsilon = 0.9 min_epsilon = 0.1 warm_up_steps = 2000 update_iter = 10 coverage_threshold = 0....