content
stringlengths
7
1.05M
def example_1(): def drop_first_last(grades): first, *middle, last = grades return sum(middle) / len(middle) print(drop_first_last([15, 20, 25, 30])) def example_2(): record = ('Dave', 'dave@example.com', '111-111', '222-222') name, email, *phone_numbers = record print(name, email...
# list 是python那种的一种数据类型:list,它是一种有序的集合,可以随时添加和删除其中的元素 _list = list(["老子", "墨子", "庄子", "孔子"]) # append方法可以往list中追加元素到末尾 _list.append("孟子") print(_list) # insert方法可以把元素插入到指定的位置,比如索引号为1的位置 _list.insert(1, "荀子") print(_list) # 要删除list末尾的元素,用pop()方法 _list.pop() print(_list) # 要删除list指定位置的元素,用pop(i)方法,其中i是索引位置 _list.pop(...
class Capability(object): def enabled_for(self, user): raise NotImplementedError() # pragma: no cover class RoleBasedCapability(Capability): def __init__(self, *roles): super(RoleBasedCapability, self).__init__() self.roles = roles def enabled_for(self, user): return any(...
'''Refaça o Ex51, lendo o primeiro termo e a razão de uma P.A mostrando os 10 primeiros termos da programação usando a estrutura while.''' ''' resolução do EX51 utilizando FOR print('TERMOS DE P.A') primeiro = int(input('1° Termo: ')) razão = int(input('Razão: ')) décimo = primeiro + (10 - 1) * razão for c in range(pr...
HTML_STRING= """<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD + dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="shortcut icon" type...
def cfgGetVal(cfgfile, section, value): secStr = "[{}]".format(section) with open(cfgfile, "r") as fh: inSec = False for line in fh: line = line.strip() if line.startswith("["): if line == secStr: inSec = True else: ...
names = ('Ariel', 'Maria', 'John', 'Paul') print(names) print(sorted(names)) print(len(names)) print(names[-1]) # This is not possible in tuples >> names[2] = 'Try' # Union names2 = ('Ana','Linda') names3 = names + names2 del(names) del(names2) print(names3) print(names3.count('Ana')) print(names3.index('Ana'))
ROOT_URL = 'https://demo.emro.info' WEBMASTER_EMAIL = 'webmaster@emro.info' SITE_TITLE = 'Null Island Public Health Surveillance' FLAGG_ABR = "null" AUTH = { "technical": [['registered'], ['demo']], "messaging": [['registered'], ['demo']], "download": [['registered'], ['demo']], "explore": [['registere...
'''input WBWBWBWBWB 9 BBBWW 1 WWWWWW 0 ''' # -*- coding: utf-8 -*- # AtCoder Beginner Contest # Problem C if __name__ == '__main__': s = input() count = 0 # See: # https://beta.atcoder.jp/contests/abc047/submissions/1007244 for i in range(len(s) - 1): if s[i] !...
class AttributeTable: def __init__(self, start, size): self.start = start self.size = size
# _*_ coding: utf-8 _*_ """ @Date: 2021/5/3 4:16 下午 @Author: wz @File: MinimumNumberOfArrowsToBurstBalloons.py @Decs: """ ''' question: 在二维空间中有许多球形的气球。对于每个气球,提供的输入是水平方向上,气球直径的开始和结束坐标。由于它是水平的,所以纵坐标并不重要,因此只要知道开始和结束的横坐标就足够了。开始坐标总是小于结束坐标。 一支弓箭可以沿着 x 轴从不同点完全垂直地射出。在坐标 x 处射出一支箭,若有一个气球的直径的开始和结束坐标为 xstart,xend,...
''' CORRIGIDO Faça um programa que leia o nome completo de uma pessoa e mostre o primeiro e último nome separadamente Ex: Ana Maria de Souza Primeiro: Ana Último: Souza ''' nome = input('Digite um nome: ').strip() print('Nome: {}'.format(nome).title()) nome = nome.split() print('Primeiro nome: {}'.format(nome[0].title(...
""" Author: Ao Wang Date: 08/20/19 Description: Merge Sort Algorithm """ def merge(left, right): result = [] leftInd = 0 rightInd = 0 resultInd = 0 while leftInd < len(left) or rightInd < len(right): if leftInd < len(left) and rightInd < len(right): if left[leftInd] < right...
# -*- coding: utf-8 -*- ADDON_MAPPING = { 'addon_list': { 'resource': 'addon/', 'docs': '', 'methods': ['GET'], }, 'addon_get': { 'resource': 'addon/{id}/', 'docs': '', 'methods': ['GET'], }, 'addon_create': { 'resource': 'addon/', 'do...
def fibonacciseries(n): if(n<=1): print(1) a, b = 1, 1 print(a) while(b<=n): print(b) a, b = b, a+b fibonacciseries(9)
TEAMS = [ 'Panthers', 'Bandits', 'Warriors', ] PLAYERS = [{ 'name': 'Karl Saygan', 'guardians': 'Heather Bledsoe', 'experience': 'YES', 'height': '42 inches' }, { 'name': 'Matt Gill', 'guardians': 'Charles Gill and Sylvia Gill', ...
def render_to_pdf(template_src, context_dict): template = get_template(template_src) context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode('utf-8')), result, show_error_as_pdf=True, encoding='UTF-8') if...
# Mostra a tabela de placar def mostrarTabela(): print('-' * 106) print('|{:^20}|{:^20}|{:^20}|{:^20}|{:^20}|'.format('Nome', 'Vitorias', 'Empates', 'Derrotas', 'Pontos')) print('-' * 106) for jogador in jogadores: calculaPontos(jogador) print('|{:^20}|{:^20}|{:^20}|{:^20}|{:^20}|'.forma...
class Solution: def minTotalDistance(self, grid): m, n = len(grid), len(grid[0]) x, y = sorted(i for i in range(m) for j in range(n) if grid[i][j]), sorted(j for i in range(m) for j in range(n) if grid[i][j]) avg_x = len(x) % 2 and x[len(x) // 2] or (x[len(x) // 2 - 1] + x[len(x) // 2]) / 2 ...
def assert_broadcastable(shape1, shape2): if len(shape1) > len(shape2): assert_broadcastable(shape2, shape1) return for a,b in zip(shape1[::-1], shape2[::-1][:len(shape1)]): assert (a == 1 or b == 1 or a == b), "The shape %s and %s are not broadcastable" % (shape1, shape2) def assert_fc...
# KMP def Dup(p): # a n = len(p) # 1 print("len: %s"%n) # 1 table = [0] * n # 0*n만큼 0 배열을 만들어요 print("table: %s"%(table)) j = 0 for i in range(1, n): print("i: %s"%i) # 1 while j > 0 and p[i] != p[j]: # 일치하지 않는 경우 이 경우를 돌아요 j = table[j - 1] # 일치했던 접두 접미의 개수 j-1 이에요(인덱...
def isCoinClose(coin): return hero.distanceTo(coin) < 20 while True: item = hero.findNearestItem() if item and isCoinClose(item): hero.moveXY(item.pos.x, item.pos.y)
#!/usr/bin/env python3 # fibonacci.py # Naive Algorithm def calc_fib(n): if (n <= 1): return n return calc_fib(n - 1) + calc_fib(n - 2) # Faster Algorithm def calc_fib_2(n): fib_list = [0, 1] if n > 1: for i in range(2, n + 1): fib_list.insert(i, fib_list[i - 1] + fib_lis...
# -*- coding: utf-8 -*- """Operations for dumping a database to file""" __all__ = ( 'dump', 'dumps', ) def _iter_dump(db_connection, schema_only=False): """\ Generator function that serializes the database associated with ``db_connection`` as formatted ``str``. Args: db_connection (sq...
#! /usr/bin/env python3 a = 1 if a == 1: pass else: print("Hello")
class IDrawingDoc: def __init__(self, system_object): self.system_object = system_object @property def _instance(self): return self.system_object
""" Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and inte...
# cache = {} # key = (r, s) # def winningRate(r, s): # """ # Code for 5800 Problem set 4, Q5-d. # We need to use dp to calculate the winning rate of a game, where: # r: int = remaining round of game # s: int = current score # The game contains two choices, flip coin X or coin Y, both are fai...
n = int(input()) s = set(map(int,input().split())) m = int(input()) t = set(map(int,input().split())) u = s.symmetric_difference(t) print(len(u))
class Solution: def boldWords(self, words, S): trie, n, mask, res = {}, len(S), set(), "" for w in words: cur = trie for c in w: if c not in cur: cur[c] = {} cur = cur[c] cur["#"] = cur.get("#", set()) | {w} ...
# TODO: Complete Recordist Log def output_report(records): # order by start pass
''' Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example ...
# 최대 힙에서의 원소 삭제 class MaxHeap: def __init__(self): self.data = [None] def remove(self): if len(self.data) > 1: self.data[1], self.data[-1] = self.data[-1], self.data[1] data = self.data.pop(-1) self.maxHeapify(1) else: data = None ...
#!/bin/env python def calc_wa(val1, val2): return val1 + val2 def calc_wari(val1, val2): return val1 / val2
#!/usr/bin/python35 fp = open('hello.txt') print('fp.fileno() = %s' % (fp.fileno())) fp.close()
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def length(self, head: Optional[ListNode]) -> int: length = 0 node = head while node: length += 1 nod...
km = float(input('Qual a distância da sua viagem? ')) print('Você está prestes a começar uma viagem de {}km'.format(km)) if km <= 200: print('Valor da viagem é {}R$'.format(km*0.50)) else: print('Valor da viagem é {}R$'.format(km*0.45))
def maxProfit(prices): return sum(max(0, x) for x in (y - x for x, y in zip(prices,prices[1:]))) if __name__ == "__main__": prices = [7,1,5,3,6,4] print(maxProfit(prices))
# Copyright 2018 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...
largura = float(input('Qual a largura da parede: ')) altura = float(input('Qual a altura da parede: ')) area = altura * largura litro = area / 2 print(f'Sua parede tem a dimensão {largura}x{altura}') print(f'A área da parede é {area}m² e é necessário {litro}L de tinta para pintá-la')
data_type_unit = 1023 weight = ['50000','60000','50000'] #D1,D3,D4 with open('lc_D1_1023_val.sh') as afile: lines = afile.readlines() for i,dtype in enumerate(['D1','D3','D4']): for j in range(6): new_file_name = 'lc_' + dtype + '_' + str(data_type_unit * (1+j)) + '_val.sh' new_file = open(new_file_name, 'w') ...
#python #Reference:D. Teare, Implementing Cisco IP Routing (ROUTE) Foundation Learning Guide: Foundation learning for the ROUTE 642-902 Exam (Self-Study Guide), 1st ed. Cisco Press, 2010. """ This formula can also be written as (108) / (bandwidth in bps). Note The OSPF RFC 2328 does not specify what the link cost shou...
""" categories: Modules,builtins description: Second argument to next() is not implemented cause: MicroPython is optimised for code space. workaround: Instead of ``val = next(it, deflt)`` use:: try: val = next(it) except StopIteration: val = deflt """ print(next(iter(range(0)), 42))
# Project metainfo __author__ = 'Andres Kasekamp' __copyright__ = 'Copyright © Maa-amet 2022' __email__ = 'andres.kasekamp@maaamet.ee' __status__ = 'Production' __description__ = 'Registritunnuse põhjal objektide xyz leidmine, tuvastamaks üleujutuspotentsiaali' __organization_est__ = 'Maa-amet' __year__ = '2022' __orga...
lr = 0.001 model_path = 'model/IC_models/baseline_lr0.001_bs256/' crop_size = 32 log_step = 50 save_step = 1500 num_epochs = 500 batch_size = 256 num_workers = 8 checkpoint = './model/IC_models/baseline_lr0.001_bs256/new_encoder-49-1500.ckpt' loading = True # Model parameters model = dict( net='resnet101', e...
"""Provide constants for use throughout the package.""" # These are the currently supported Rust target triples # # Targets are identified by their "target triple" which is the string to inform the compiler what kind of output # should be produced. A target triple consists of three strings separated by a hyphen, with ...
# constants to indicate player status UNINITIALIZED = 0 # No video file loaded READY = 1 # Video file loaded and ready to start PAUSED = 2 # Playback is paused PLAYING = 3 # Player is playing EOS = 4 # End of stream has been reached # constants to indicate clock status RUNNING = 5 # Clock is ticking # Clock uses ...
# wap to traverse a string using while loop str='This is a string' i=0 while i<len(str): print(str[i],end='') i+=1 print()
#!/usr/bin/env python # -*- coding: utf-8 -*- # ====================================================================== # # gensbo - a GENeral Simulation Based Optimizer # # 一个基于仿真的优化器 # # ====================================================================== # # author : Mingtao Li # date ...
# encoding: utf8 def publication_range(flourish, key='published'): _lowest = None _highest = None for _source in flourish.sources.all(): try: _pub = getattr(_source, key) _year = _pub.year if _lowest is None or _year < _lowest: _lowest = _year ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). class DependencyError(Exception): """The user requested something that won't be possi...
""" The MIT License (MIT) Copyright (c) 2022-present jaczerob Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, me...
class WrapAroundCounter: """Simple wrap around counter that increments an input wrapping around a max_value""" def __init__(self, max_val): self._max_val = max_val def increment(self, i: int): """ :param i: integer between 0 and max_val :return: increments i wrapping ...
accuracy_requirement = 0.75 analytical_delay = True auto_delay_chain_sizing = False bank_select = "bank_select" bitcell = "bitcell_1port" bitcell_array = "bitcell_array" buf_dec = "pbuf" check_lvsdrc = False col_cap = "col_cap" col_cap_array = "col_cap_array" column_mux_array = "column_mux_array" config_file = "/home/p...
# -*- coding: utf-8 -*- __author__ = 'Aubrey Taylor' __email__ = 'aubricus@gmail.com' __version__ = '0.0.5'
# value of directions NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3 INVALID = -1 # maximum number of visit at MCTS MAX_SEARCH = 1000 # size and channels of features input to CNN. INPUT_AREA_SIZE = 11 INPUT_CHANNELS = 98 # size of normal model. NORMAL_MODEL_CHANNELS = 64 NORMAL_MODEL_BLOCKS = 8 # size of small model. SMALL_...
#Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor seja inválido e continue pedindo até que o usuário informe um valor válido. nota = float(input("Digite uma nota entre zero e 10: ")) while nota > 10 or nota < 0: nota = float(input("Informe um valor válido: "))
config = { 'CONTEXT': 'We are in PROD context', 'Log_bucket': 'gc://bucketname_great2', 'versionNR': 'v12.333', 'zone': 'europe-west1-c', }
def helm_template(name, release_name, chart, values, namespace = None): """Locally expand a helm chart. Args: chart: build label, referencing the chart to expand. values: label. File with expand-time values. """ native.genrule( name = name, srcs = [chart, values], ou...
adapters = sorted([int(n) for n in open('input').read()[:-1].split('\n')]) adapters.insert(0, 0) adapters.append(max(adapters) + 3) joltage_dist = {k: 0 for k in range(5)} for idx in range(1, len(adapters)): joltage_diff = adapters[idx] - adapters[idx-1] if joltage_diff > 3: raise ValueError(f"Encounte...
while True: results = cursor.fetchmany(1000) if not results: break for result in results: doSomethingWith(result)
# name = input("name :") # age = input("age:") # job = input("job:") ## 字符串格式化:方式一 # info = ''' # ------------ info {_name} ----------- # name = {_name} # age = {_age} # job = {_job} # -------------------------------- # '''.format(_name = name, # _age = age, # _job = job) # # print(info) ### 字...
text = input().split("#") water = int(input()) effort = 0 total_fire = 0 count = 1 for command in text: if count == 1: print("Cells:") count += 1 convert = command.split(" = ") if convert[0] == "High": amount = int(convert[1]) if 81 <= amount <= 125: if water - ...
def solve(): n=int(input()) a=list(map(int, input().split())) l=0 t=0 c=True ms=0 for i in range(n): if a[i] < a[l]: t+=1 c=True else: l=i print(t) if __name__ == '__main__': t=int(input()) for _ in range(t): solve()
class ValueTransformer(object): ATTRIBUTE_TYPE = 'Transformable' def __init__(self, name): self.name = name def __str__(self): return self.name def __repr__(self): return '<ValueTransformer {}>'.format(self.name)
#!/usr/bin/env python # -*- coding: utf-8 -*- # This is aukro config file # Do not change this file, use instance/aukro.conf instead HOST = "localhost" PORT = 5000 BASE_URL = "http://localhost:5000" DEBUG = True TESTING = False SECRET_KEY = "DuMmY sEcReT kEy" CSRF_ENABLED = True CSRF_SESSION_KEY = "_csrf_token" ...
#create empty list for DAG wl = [] #dummy string gen = "genotype" #dummy list of fake gene names ng = ["gen1", "gen2", "gen3"] for i in range(len(ng)): temp = [gen, ng[i]] wl.append(temp) #append season and growth rate wl.append(["season", "gr"]) #create list of tuples wl_tup = list(map(tuple, wl)) print(...
class Solution: def longestPalindromeSubseq(self, s: str) -> int: n = len(s) pre = [0] * n cur = [0] * n for i in reversed(range(n)): for j in range(i, n): if i == j: cur[j] = 1 elif s[i] == s[j]: cu...
# import sys # num, length = input().strip().split(' ') # length = int(length) # s = input() # minList = [0]*26 length = 4 dp = [[0 for _ in range(length)] for _ in range(length)] # count = 0 # for line in sys.stdin: # c,add,dele = line.strip().split(' ') # minList[ord(c)-ord('a')] = min(add,dele) # count +...
# Copyright (C) 2019 Snild Dolkow # Licensed under the LICENSE. class TestShadowing(object): def setUp(self): self.heap, = self.hf.heaps self.cbase, = self.heap.classes['com.example.Base'] self.ci, = self.heap.classes['com.example.ShadowI'] self.cs, = self.heap.classes['com.example.ShadowS'] self.cii,...
#------------------- # hearth.py # made by someone #------------------- n=int(input("几只鱼人:")) * 2 a=int(input("有桐须🐴(1表示有):")) h=int(input("牌库几张:")) v=int(input("疲劳几:")) if a == 1: n=n*2 n=n-h b=0; for i in range(v+1,n+1+v): b=b+i print("你可以打:",b,"血")
male = [ 'Jakub,', 'Jan,', 'Adam,', 'Tomáš,', 'Matyáš,', 'Filip,', 'Ondřej,', 'Vojtěch,', 'Matěj,', 'David,', 'Lukáš,', 'Dominik,', 'Martin,', 'Daniel,', 'Šimon,', 'Petr,', 'Štěpán,', 'Antonín', 'Jiří', 'Marek', 'Michal', 'Kryštof',...
database = 'test_data' datasets = ['monthly_sunspots', 'metro_traffic_ts'] # datasets = ['monthly_sunspots', ] tables = { 'monthly_sunspots': f""" CREATE TABLE IF NOT EXISTS {database}.monthly_sunspots ( Month Date, Sunspots Float64 ) ENGINE = MergeTree() ORDER BY Month PARTITION BY ...
TEST_API_KEY = "" TEST_API_SECRET = "" REAL_API_KEY = "" REAL_API_SECRET = "" sleeptime = 2 #in seconds sleeptime_HTTPTooManyRequests = 10 sleeptime_HTTPServiceUnavailable = 2 use_last_symbol_as_default = True default_symbol = "XBTUSD" default_stop_inst = "IndexPrice" verbose = 1 testnet = True
class Area(SpatialElement,IDisposable): """ Provides access to the area topology in Autodesk Revit. """ def Dispose(self): """ Dispose(self: Element,A_0: bool) """ pass def getBoundingBox(self,*args): """ getBoundingBox(self: Element,view: View) -> BoundingBoxXYZ """ pass def ReleaseUnmanagedResourc...
# Create your code using this format # Create a file with a file-name of your program code # For example : sumOfTwoNumbers.py or factorialOfANumber.py # Now start hacking # Keep this as a format while coding # PROGRAM-NAME : Your-program-name # By 'your-name' # PROGRAM-CODE : # # **Start coding ..... your code fr...
chromosome_name="chr1" file_name="/home/slow/onimaru/1000genome/HG00119_1000.fa" with open(file_name, "r") as fin, open(file_name+"_"+chromosome_name, "w") as fout: WRITE=False for line in fin: if line.startswith('>'): #line1=line.split() a=line.strip('>\n') #print ...
kata1 = "Hallo" kata2 = "Dunia" hasil = kata1 + " " + kata2 print(hasil)
def make_factorial_table(n): result = [0] * (n + 1) result[0] = 1 for i in range(1, n + 1): result[i] = result[i - 1] * i % m return result def mcomb(n, k): if n == 0 and k == 0: return 1 if n < k or k < 0: return 0 return fac[n] * pow(fac[n - k], m - 2, m) * pow(fa...
class PowerException(Exception): """ An error occurred talking the the DLI Power switch """ pass
lista = [] for i in range(5): n = input('numero: ') lista.append(n) print(lista) maior = lista[0] menor = lista[0] for i in range(len(lista)): if int(lista[int(i)]) > int(maior): maior = lista[int(i)] if int(lista[int(i)]) < int(menor): menor = lista[int(i)] print(f'maior: {maior}, men...
p1 = 4 p2 = 8 #p2 = 10 rolls = { 3:1, 4:3, 5:27, 6:81, 7:27, 8:9, 9:1 } class Player: def __init__(self, pos, score, count, steps): self.pos = pos self.score = score self.count = count self.steps = steps def __repr__(self): return f"Player(pos={self.pos} score={self.sc...
#!/usr/bin/python class NumArray(object): def __init__(self, nums): self.nums = nums self.sums = [] summ = 0 for i in xrange(len(nums)): summ += self.nums[i] self.sums.append(summ) def sumRange(self, i, j): if i == j: re...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {} modules = [] doc_url = "https://fastai.github.io/embedding-gym/" git_url = "https://github.com/fastai/embedding-gym/tree/master/" def custom_doc_links(name): return None
num1 = 10 num2 = 20 num3 = 300
# Given a dictionary get all values from the dictionary and add it in a list but don’t add duplicates # My Solution speed = {'jan': 47, 'feb': 52, 'march': 47, 'April': 44, 'May': 52, 'June': 53, 'july': 54, 'Aug': 44, 'Sept': 54} newList = [] for item in speed.values(): if item not in newList: newList.ap...
# Created by Agamdeep Singh / CodeWithAgam # Youtube: CodeWithAgam # Github: CodeWithAgam # Instagram: @coderagam001 / @codewithagam # Twitter: @CoderAgam001 # Linkdin: Agamdeep Singh # Print a welcome message print(''' ******************************************************************************* | ...
class Solution: def reachNumber(self, target: int) -> int: target = abs(target) i = 0 while target > 0: i += 1 target -= i if target % 2 == 0: result = i elif i % 2 == 0: result = i + 1 else: result = i + 2 ...
# coding=utf-8 class BaseLearningRate(): """Abstract class for Learning Rate """ def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) def get_learning_rate(self): raise NotImplementedError()
# Imprimir numeros de 5 a 1 de manera descendente usando funciones recursivas. Puede ser cualquier valor positivo, ejemplo, si pasamos el valor de 5, debe imprimir: 5 4 3 2 1 Si se pasa el valor de 3, debe imprimir: 3 2 1 Si se pasan valores negativos no imprime nada def mostrar_numeros(numero): if numero > 0: ...
# Toate programarile cu numar maxim de spectacole (Greedy + backtracking) # comparator dupa ora de sfarsit a unui spectacol def cmp_spectacole(sp): return sp[2] # functie care determina numarul maxim de spectacole care pot fi programate # folosind metoda Greedy def numarMaximSpectacole(lsp): lsp.sort...
"""Map file definitions for postfix.""" class RelayDomainsMap(object): """Map file to list all relay domains.""" filename = "sql-relaydomains.cf" mysql = ( "SELECT name FROM admin_domain " "WHERE name='%s' AND type='relaydomain' AND enabled=1" ) postgres = ( "SELECT name F...
# -*- coding: utf-8 -*- """ Created on Thu Jul 29 22:18:23 2021 @author: keikei """ class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ return haystack.find(needle) # 比上面慢很多,内存也稍多 class Solu...
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ # Key-word args are list args that are dictionaries instead of tuples # Allows your function to have a variable number of named arguments def main(): kitten(Buffy = 'meow', Zilla = 'grr', Angel = 'rawr') def kitten(**kwargs): # Note two asterisks. kw...
f = open("rec_parse.ipynb.txt", mode='r') all = f.readlines() f.close() raw = open("ipynb_raw.txt", mode='w') saveNext = False for line in all: if saveNext: if " ]" in line: saveNext = False else: strippedLine = line[4:].strip('\",') raw.write(strippedLine) ...
n,k = list(map(int,input().split())) tree_adj_list = {} for i in range(n-1): u,v = list(map(int,input().split())) try: tree_adj_list[u].append(v) except: tree_adj_list[u] = [v] try: tree_adj_list[v].append(u) except: tree_adj_list[v] = [u] ltk = [] for i in tree...
# add to the dictionary a name with its phone number # result should be phone_book = {'Python': 1} phone_book = {} phone_book['Python'] = 1 print(phone_book)
'''input 5 10 3 0 ''' inp = -1 while True: inp = int(input()) if inp == 0: exit() out = [] for i in range(1, inp+1): out.append(str(i)) print("{}".format(" ".join(out)))
''' A noob programmer was given two simple tasks: sum and sort the elements of the given array a = [a1, a2, ..., an]. He started with summing and did it easily, but decided to store the sum he found in some random position of the original array which was a bad idea. Now he needs to cope with the second task, sorting th...
"""Generates and compiles C++ grpc stubs from proto_library rules.""" load("//:bazel/generate_cc.bzl", "generate_cc") def cc_grpc_library(name, srcs, deps, proto_only, well_known_protos, use_external = False, **kwargs): """Generates C++ grpc classes from a .proto file. Assumes the generated classes will be used ...