content
stringlengths
7
1.05M
dicionario_sites = {"Diego": "diegomariano.com"} print(dicionario_sites['Diego']) dicionario_sites = {"Diego": "diegomariano.com", "Google": "google.com", "Udemy": "udemy.com", "Luiz Carlin" : "luizcarlin.com.br"} print ("-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=") for chave in dicionario_sites: print (chave + " -...
# -*- coding: utf-8 -*- # Author: Tonio Teran <tonio@stateoftheart.ai> # Copyright: Stateoftheart AI PBC 2021. '''RLlib's library wrapper.''' SOURCE_METADATA = { 'name': 'rllib', 'original_name': 'RLlib', 'url': 'https://docs.ray.io/en/master/rllib.html' } MODELS = { 'discrete': [ 'A2C', 'A3C'...
# Recursive, O(2^n) def LCS(X, Y, m, n): if m == 0 or n == 0: return 0 elif X[m - 1] == Y[n - 1]: return 1 + LCS(X, Y, m - 1, n - 1) else: return max(LCS(X, Y, m - 1, n), LCS(X, Y, m, n - 1)) X = "AGGTAB" Y = "GXTXAYB" print("Length of LCS is ", LCS(X, Y, len(X), len(Y))) # Overl...
class CalculoZ(): def calcular_z(self, n1, n2, x, y, ux, uy, ox, oy): arriba = (x-y)-(ux-uy) abajo = (((ox)**2/(n1))+((oy)**2/(n2)))**0.5 z = arriba/abajo return z
""" 입력으로 주어지는 리스트의 첫 원소와 마지막 원소의 합을 리턴 """ def solution(x): assert isinstance(x, list) and x and all(isinstance(i, int) for i in x), 'Value error!!!' first_element = x[0] last_element = x[-1] return first_element + last_element res = solution([i for i in range(11)]) print(f'해는 {res}')
class Solution: def intToRoman(self, num: int) -> str: res = "" s = ['I', 'V', 'X', 'L', 'C', 'D', 'M'] index = 0 while num > 0: x = num % 10 if x < 5: if x == 4: temp = s[index] + s[index + 1] else: ...
class BasicScript(object): def __init__(self, parser): """ Initialize the class :param parser: ArgumentParser """ super(BasicScript, self).__init__() self._parser = parser def get_arguments(self): """ Get the arguments to configure current script,...
def test(): # Here we can either check objects created in the solution code, or the # string value of the solution, available as __solution__. A helper for # printing formatted messages is available as __msg__. See the testTemplate # in the meta.json for details. # If an assertion fails, the messag...
class ApiError(Exception): """ Exception raised when user does not have appropriate credentials Used for 301 & 401 HTTP Status codes """ def __init__(self, response): if 'error_description' in response: self.message = response['error_description'] else: ...
""" Ejercicio: hacer un juego "Guess The number" PARTE 1: Pedir al usuario que introduzca un número entre 0 y 100 PARTE 2: Adivinar el número por parte del usuario Usar una función para capitalizar el código común """ MIN = 0 MAX = 99 def solicitar_introducir_numero(invite): # Completar la entrada: invite ...
N, X, T = map(int, input().split()) time = N // X if(N%X == 0): print(time * T) else: print((time+1) * T)
class Token: __slots__ = ('start', 'end') def __init__(self, start: int=None, end: int=None): self.start = start self.end = end @property def type(self): "Type of current token" return self.__class__.__name__ def to_json(self): return dict([(k, self.__getat...
literals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,.?/:;{[]}-=_+~!@#$%^&*()" #obfuscated literals = "tJ;EM mKrFzQ_SOT?]B[U@$yqec~fhd{=is&alxPIbnuRkC%Z(jDw#G:/)L,*.V!pov+HNYA^g-}WX" key = 7 def shuffle(plaintext): shuffled = "" # shuffle plaintext for i in range(int(len(plaintext) / 3)): ...
# apis_v1/documentation_source/organization_suggestion_tasks_doc.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- def organization_suggestion_tasks_doc_template_values(url_root): """ Show documentation about organizationSuggestionTask """ required_query_parameter_list = [ { ...
peso = float(input('Qual é seu peso? ')) altura = float(input('Qual é sua altura? ')) imc = peso / (altura * altura) if imc < 18.5: print(f'IMC {imc:.1f} Abaixo do Peso') elif imc < 25: print(f'IMC {imc:.1f} Peso Ideal') elif imc < 30: print(f'IMC {imc:.1f} Sobrepeso') elif imc < 40: print(f'IMC {imc...
#!/usr/bin/env python # -*- coding: UTF-8 -*- class ConstraintSyntaxError(SyntaxError): """A generic error indicating an improperly defined constraint.""" pass class ConstraintValueError(ValueError): """A generic error indicating a value violates a constraint.""" pass
curupira = int(input()) boitata = int(input()) boto = int(input()) mapinguari = int(input()) lara = int(input()) total = 225 + (curupira * 300) + (boitata *1500) + (boto * 600) + (mapinguari * 1000)+(lara*150) print(total)
class Sibling: pass
if True: foo = 42 else: foo = None
#!/usr/bin/python3 print("Sum of even-valued terms less than four million in the Fibonacci sequence:") a, b, sum = 1, 1, 0 while b < 4000000: sum += b if b % 2 == 0 else 0 a, b = b, a + b print(sum)
class Solution: def numFactoredBinaryTrees(self, A): """ :type A: List[int] :rtype: int """ A.sort() nums, res, trees, factors = set(A), 0, {}, collections.defaultdict(set) for i, num in enumerate(A): for n in A[:i]: if num % n == 0...
#LeetCode problem 200: Number of Islands class Solution: def check(self,grid,nodesVisited,row,col,m,n): return (row>=0 and row<m and col>=0 and col<n and grid[row][col]=="1" and nodesVisited[row][col]==0) def dfs(self,grid,nodesVisited,row,col,m,n): a=[-1,1,0,0] b=[0,0,1,-1] ...
# -*- coding: utf-8 -*- """ En este paquete se situarán distintas clases de utilidad para el resto del proyecto. """ __author__ = "T. Teijeiro" __date__ = "$30-nov-2011 17:50:53$"
''' ################ # 55. Jump Game ################ class Solution: def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ if not nums or (nums[0]==0 and len(nums)>1): return False if len(nums)==1: return True l = len(num...
''' Create exceptions based on your inputs. Please follow the tasks below. - Capture and handle system exceptions - Create custom user-based exceptions ''' class CustomInputError(Exception): def __init__(self, *args, **kwargs): print("Going through my own CustomInputError") # Exception.__init_...
""" This folder contains help-functions to Bokeh visualizations in Python. There are functions that align 2nd-ary y-axis to primary y-axis as well as functions that align 3 y-axes. """ __credits__ = "ICOS Carbon Portal" __license__ = "GPL-3.0" __version__ = "0.1.0" __maintainer__ = "I...
def computador_escolhe_jogada(n, m): pc_remove = 1 while pc_remove != m: if (n - pc_remove) % (m+1) == 0: return pc_remove else: pc_remove += 1 return pc_remove def usuario_escolhe_jogada(n, m): while True: usuario_removeu = int(input('Quantas peças você...
"""Collection of all documented ADS constants. Only a small subset of these are used by code in this library. Source: http://infosys.beckhoff.com/english.php?content=../content/1033/tcplclibsystem/html/tcplclibsys_constants.htm&id= # nopep8 """ """Port numbers""" # Port number of the standard loggers. AMSP...
# https://www.acmicpc.net/problem/8393 a = int(input()) result = 0 for i in range(a + 1): result = result + i print(result)
# conf.py/Open GoPro, Version 1.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro). # This copyright was auto-generated on Tue May 18 22:08:50 UTC 2021 project = "Open GoPro Python SDK" copyright = "2020, GoPro Inc." author = "Tim Camise" version = "0.5.8" release = "0.5.8" templates_path = ["_templates"] s...
# Link --> https://www.hackerrank.com/challenges/maximum-element/problem # Code: def getMax(operations): maximum = 0 temp = [] answer = [] for i in operations: if i != '2' and i != '3': numbers = i.split() number = int(numbers[1]) temp.append(number) ...
# 양방향 연결 리스트 노드 삽입 (insertBefore() 구현) class Node: def __init__(self, item): self.data = item self.prev = None self.next = None class DoublyLinkedList: def __init__(self): self.nodeCount = 0 self.head = Node(None) self.tail = Node(None) self.head.prev ...
# -*- coding: utf-8 -*- """ Created on Mon Aug 30 15:49:24 2021 @author: alann """ arr = [[1,1,0,1,0], [0,1,1,1,0], [1,1,1,1,0], [0,1,1,1,1]] def largestSquare(arr ) -> int: if len(arr) < 1 or len(arr[0]) < 1: return 0 largest = 0 cache = [[0 for i in range(len(arr[0]))] for j in range(len(a...
s = 0 for i in range(1, 500+1, 2): m = i + 3 s += m print(s) # imprime 63250 na tela ''' soma = 0 for c in range(1, 501, 2) if c%3 == 0: soma = soma + c print('A soma de todos os valores solicitados é {}'.format(soma) '''
# -*- coding: utf-8 -*- """ Created on Sun May 12 19:10:03 2019 @author: DiPu """ shopping_list=[] print("enter items to add in list and type quit when you arew done") while True: ip=input("enter list") if ip=="QUIT": break elif ip.upper()=="SHOW": print(shopping_list) elif ip.upper()==...
#!/usr/bin/env python3 if __name__ == "__main__": N = int(input().strip()) stamps = set() for _ in range(N): stamp = input().strip() stamps.add(stamp) print(len(stamps))
"""Provide a class for yWriter chapter representation. Copyright (c) 2021 Peter Triesberger For further information see https://github.com/peter88213/PyWriter Published under the MIT License (https://opensource.org/licenses/mit-license.php) """ class Chapter(): """yWriter chapter representation. # ...
""" """ # TODO: make this list complete [exclude stuffs ending with 's'] conditionals = [ "cmp", "cmn", "tst", "teq" ] class CMP(object): def __init__(self, line_no, text): self.line_no = line_no self.text = text class Branch(object): def __init__(self, line_no, text, label...
# coding: utf-8 """ Union-Find (Disjoint Set) https://en.wikipedia.org/wiki/Disjoint-set_data_structure """ class QuickFindUnionFind: def __init__(self, union_pairs=()): self.num_groups = 0 self.auto_increment_id = 1 self.element_groups = { # element: group_id, } ...
class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ if not nums: return None i = len(nums)-1 j = -1 # j is set to -1 for case `4321`, so need to reverse all i...
def sort_data_by_cumulus(data): """ Sort data by submitted_by field, which holds the cumulus number (or id), Parameters: data (list): A list containing the report data. Returns: (dict): A dict containg the data sorted by the cumulus ...
# -*- coding: utf-8 -*- # Copyright (C) 2017 Intel Corporation. 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 # # ...
""" Configuration file """ class Config: """ Base Configuration """ DEBUG = True SECRET_KEY = r'f\x13\xd9fM\xdc\x82\x01b\xdb\x03' SQLALCHEMY_POOL_SIZE = 5 SQLALCHEMY_POOL_TIMEOUT = 120 SQLALCHEMY_POOL_RECYCLE = 280 MAIL_SERVER = 'smtp.gmail.com' MAIL_PORT = 465 MAIL_USERNA...
# -*- coding:utf-8 -*- # https://leetcode.com/problems/permutation-sequence/description/ class Solution(object): def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ factorial = [1] for i in range(1, n): factor...
datasetDir = '../dataset/' model = '../model/lenet' modelDir = '../model/' epochs = 20 batchSize = 128 rate = 0.001 mu = 0 sigma = 0.1
"""A board is a list of list of str. For example, the board ANTT XSOB is represented as the list [['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']] A word list is a list of str. For example, the list of words ANT BOX SOB TO is represented as the list ['ANT', 'BOX', 'SOB', 'TO'] """ def is_va...
# flake8: noqa _JULIA_V1 = { "$schema": "http://json-schema.org/draft-04/schema#", "title": "PythonRuntimeMetadata v1.0", "description": "PythonRuntimeMetadata runtime/metadata.json schema.", "type": "object", "properties": { "metadata_version": { "description": "The metadata ver...
# Copyright 2009 Moyshe BenRabi # # 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 ...
class Singleton: __instance = None @classmethod def __get_instance(cls): return cls.__instance @classmethod def instance(cls, *args, **kargs): cls.__instance = cls(*args, **kargs) cls.instance = cls.__get_instance return cls.__instance """"" class MyClass(BaseClass...
dadosd = dict() jogadores = list() gols = list() while True: dadosd['nome'] = str(input('Nome: ')) total = int(input('Quantas partidas {} jogou? '.format(dadosd['nome']))) for c in range(0, total): gols.append(int(input('Quantos gols no {}º jogo? '.format(c+1)))) dadosd['gols'] = gols[:] ...
test_cases = int(input()) for t in range(1, test_cases + 1): nums = list(map(int, input().strip().split())) result = [] for i in range(0, 5): for j in range(i + 1, 6): for k in range(j + 1, 7): result.append(nums[i] + nums[j] + nums[k]) result = sorted(list(set(resul...
# atomic level def get_idx(list, key): for idx in range(len(list)): if key == list[idx][0]: return idx def ins(list, key, val): list.append([key, val]) return list def ret(list, key): idx = get_idx(list, key) return list[idx][1] def upd(list, key, val): new_item = [key....
class Example: def __init__(self): self.name = "" pass def greet(self, name): self.name = name print("hello " + name)
class Carrinho_de_compras: def __init__(self): self.produtos = [] def inserir_produto(self, produto): self.produtos.append(produto) def listar_produtos(self): for produto in self.produtos: print(produto.nome, produto.valor) def soma_total(self): total = 0 ...
class Solution(object): def longestValidParentheses(self, s): """ :type s: str :rtype: int """ i = 0 maxlen = 0 self.longest = {} while i < len(s): if s[i] == ")": i = i + 1 continue else: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This module represent logic of detection and conversion of cheats. """ # py_ver : [3.5.2] # date : [02.11.2016] # author : [Aleksey Yakovlev] # email : [nothscr@gmail.com] class AntiCheater(object): """ Help to detect and convert text cheats. ...
#!/usr/bin/env python3 visited = set() visited.add((0, 0)) turn = 0 # Santa = 0, Robo-Santa = 1 locations = [[0, 0], [0, 0]] with open('input.txt', 'r') as f: for line in f: for ch in line: pos = locations[turn] turn = (turn + 1) % 2 if ch == '^': pos[...
# import pytest class TestBaseReplacerMixin: def test_target(self): # synced assert True def test_write(self): # synced assert True def test_flush(self): # synced assert True def test_close(self): # synced assert True class TestStdOutReplacerMixin: def test...
# coding: utf8 db.define_table('post', Field('Email',requires=IS_EMAIL()), Field('filen','upload'), auth.signature)
class Solution: def dfs(self,row_cnt:int, col_cnt:int, i:int, j:int, obs_arr:list, solve_dict:dict): if (i, j) in solve_dict: return solve_dict[(i,j)] right_cnt = 0 down_cnt = 0 #right if i + 1 < row_cnt and not obs_arr[i + 1][j]: if (i + 1, j) in sol...
class MkDocsTyperException(Exception): """ Generic exception class for mkdocs-typer errors. """
dataset_type = 'ShipRSImageNet_Level2' # data_root = 'data/Ship_ImageNet/' data_root = './data/ShipRSImageNet/' CLASSES = ('Other Ship', 'Other Warship', 'Submarine', 'Aircraft Carrier', 'Cruiser', 'Destroyer', 'Frigate', 'Patrol', 'Landing', 'Commander', 'Auxiliary Ships', 'Other Merchant', 'Con...
class Solution: def minFlips(self, mat: List[List[int]]) -> int: # 放到 flip 函数外面可以减少计算 mapper = {"0": "1", "1": "0"} def flip(state: List[str], i: int) -> None: state[i] = mapper[state[i]] if i % n != 0: state[i - 1] = mapper[state[i - 1]] ...
#https://programmers.co.kr/learn/courses/30/lessons/64061 # 크레인 인형뽑기 def solution(board, moves): answer = 0 size = len(board[0]) a = [] for m in moves: for i in range(size): if board[i][m-1] != 0: a.append(board[i][m-1]) board[i][m-1] = 0 ...
def dbapi_subscription(dbsession, action, input_dict, action_filter={}, caller_area={}): _api_name = "dbapi_subscription" _api_entity = 'SUBSCRIPTION' _api_action = action _api_msgID = set_msgID(_api_name, _api_action, _api_entity) _process_identity_kwargs = {'type': 'api', 'module': module_id, 'na...
def recursiveCalc(n, counter=0, steps=''): if n<10: steps += 'Total Steps: ' + str(counter) + '.' return steps, counter counter+=1 result = calc(n) steps += str(result)+', ' return recursiveCalc(result, counter, steps) def calc(n): result = 1 while (n>0): mod = n % 1...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Question: Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example 1: Given the following tr...
def ifPossible(a): while a%2==0: a/=2 return a test=int(input()) while test: a,b = input().split() a=int(a) b=int(b) if a>b: n=b b=a a=n num=ifPossible(b) ans=0 if num!=ifPossible(a): print("-1") else: b/=a while b>=8: b/=8 ans+=1 if b>1: ans+=1 print(ans) test-=1
#!/usr/bin/python3 class Student(): """Student class with name and age""" def __init__(self, first_name, last_name, age): """initializes new instance of Student""" self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): "...
def bubble_sort(arr): swapped = True while swapped: swapped = False for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] swapped = True def selection_sort(arr): for i in range(len(arr)): minpos =...
class Project(): def __init__(self, client, project_id=None): self.client = client self.project_id = project_id def get_details(self, project_id=None): """ Get information about a specific project http://developer.dribbble.com/v1/projects/#get-a-project ...
class AllennlpReaderToDict: def __init__(self, **kwargs): self.kwargs = kwargs def __call__(self, *args_ignore, **kwargs_ignore): kwargs = self.kwargs reader = kwargs.get("reader") file_path = kwargs.get("file_path") n_samples = kwargs.get("n_samples") instances...
def one_hot_encode(_df, _col): _values = set(_df[_col].values) for v in _values: _df[_col + str(v)] = _df[_col].apply(lambda x : float(x == v) ) return _df
class Solution(object): def sumOddLengthSubarrays(self, arr): """ :type arr: List[int] :rtype: int """ # Runtime: 32 ms # Memory: 13.4 MB prefix_sum = [] last_sum = 0 for item in arr: last_sum += item prefix_sum.append(...
""" This code was written by JonECope Using Python 3035 in Processing 3.3.7 """ color_choice = color(0, 0, 0) circ = True instructions = "Press Mouse to draw, Right-click to erase, Q to exit, R, O, Y, G, B, V for colors. Press S for square brush or C for circle brush. Press Enter to save." def setup(): #size(800, 8...
def differ(string_1, string_2): new_string = "" for i in range(len(string_1)): if string_1[i] == string_2[i]: new_string += string_1[i] return new_string def main(): f = [line.rstrip("\n") for line in open("Data.txt")] for i in range(len(f)): for j in range(i + 1, len...
""" 字符串字面值 """ # 1. 各种写法 # 双引号 name01 = "悟空" # 单引号 name02 = '悟空' # 三引号: 可见即所得 name03 = ''' 孙 悟 空''' print(name03) name03 = """悟空""" # 2. 引号冲突 message = '我是"孙悟空"同学.' message = "我是'孙悟空'同学." message = """我是'孙'悟"空"同学.""" # 3. 转义字符:能够改变含义的特殊字符 # \" \' \\ 换行\n message = "我是\"孙悟空\"同\n学." print(message) url = "...
class UpgradeInfo(): def __init__(self): self.baseCost_mineral = 100 self.baseCost_gas = 100 self.baseCost_time = 266 self.upgradeFactor_mineral = 50 self.upgradeFactor_gas = 50 self.upgradeFactor_time = 32 def GetInfo(self): res = f'초기비용 : {self.baseCost_...
class Car(object): # setting some default values num_of_doors = 4 num_of_wheels = 4 def __init__(self, name='General', model='GM', car_type='saloon', speed=0): self.name = name self.model = model self.car_type = car_type self.speed = speed if self.name is 'Porshe...
class Tree: def __init__(self,data): self.tree = [data, [],[]] def left_subtree(self,branch): left_list = self.tree.pop(1) if len(left_list) > 1: branch.tree[1]=left_list self.tree.insert(1,branch.tree) else: self.tree.insert(1,bra...
peso = float(input("digite aqui o seu peso(kg): ")) altura = float(input("digite sua altura: ")) imc = peso/altura**2 print("seu imc é {:3.2f}".format(imc)) if imc < 18.5: print("você está abaixo do peso") elif 18.5 <= imc < 25: print("parabéns, você está no peso ideal!") elif 25 <= imc < 30: print("sobrepe...
def get_input(): EF1 = float(input("введите значения жесткостей элементов: " + "\n" + "EF1 = ")) EF2 = float(input("EF2 = ")) F = float(input("введите значение усилия:" + "\n" + "F = ")) return EF1, EF2, F
class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"[{self.x},{self.y}]" class X(Point): def __init__(self, x, y): super().__init__(x, y) def __str__(self): return "X" + super().__str__() class O(Point): def __init__(...
print('=' * 12 + 'Desafio 73' + '=' * 12) tabelabrasileirao = ( "Flamengo", "Santos", "Palmeiras", "Grêmio", "Athletico-PR", "São Paulo", "Internacional", "Corinthians", "Fortaleza", "Goiás", "Bahia", "Vasco", "Atlético-MG", "Fluminense", "Botafogo", "Ceará", "Cruzeiro", "CSA", "Chapecoense", "Avaí") print(...
def input_dimension(): while True: dimension = input("Enter your board dimensions: ").split() len_x1 = 0 len_y1 = 0 if len(dimension) != 2: print("Invalid dimensions!") continue try: len_x1 = int(dimension[0]) len_y1 =...
# coding: utf-8 # # Using Python to investigate data # ![Python overview](python.png "Python") # ![Standard library](standard_lib.png "Standard library") # # MANY important non-standard packages # ![Science stack](science_stack.jpg "Science stack") # ![ecosytem](python_ecosystem.png "Ecosytem") # ## Which Pytho...
"""Mirror of release info TODO: generate this file from GitHub API""" # The integrity hashes can be computed with # shasum -b -a 384 [downloaded file] | awk '{ print $1 }' | xxd -r -p | base64 TOOL_VERSIONS = { "7.0.1-rc1": { "darwin_arm64": "sha384-PMTl7GMV01JnwQ0yoURCuEVq+xUUlhayLzBFzqId8ebIBQ8g8aWnbiRX...
with open("input.txt") as file: data = file.read() m = [-1, 0, 1] def neight(grid, x, y): for a in m: for b in m: if a == b == 0: continue xx = x+a yy = y+b if 0 <= xx < len(grid) and 0 <= yy < len(grid[xx]): yield grid[xx]...
# # This file contains the Python code from Program 6.2 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm06_02.txt # class StackAsArray(...
class DefaultConfig(object): env = 'default' # visdom 环境 model = 'SimpleCGH' # 使用的模型,名字必须与models/__init__.py中的名字一致 train_data_root = './data/training_set/' # 训练集存放路径 # test_data_root = './data/test1' # 测试集存放路径 load_model_path =None# 'checkpoints/model.pth' # 加载预训练的模型的路径,为None代表不加载 batch_size = 10...
n = input() split =n.split() limak = int(split[0]) bob = int(split[-1]) years = 0 while True: limak*=3 bob*=2 years+=1 if limak>bob: break print(years)
fizz = 3 buzz = 5 upto = 100 for n in range(1,(upto + 1)): if n % fizz == 0: if n % buzz == 0: print("FizzBuzz") else: print("Fizz") elif n % buzz == 0: print("Buzz") else: print(n)
#!/usr/bin/env python3 def count_combos(coins, total): len_coins = len(coins) memo = {} def count(tot, i): if tot == 0: return 1 if i == len_coins: return 0 subproblem = (tot, i) try: return memo[subproblem] except KeyError: ...
ans = [] n = int(input()) for i in range(n): a, b = list(map(int, input().split())) ans.append(a + b) for i in range(len(ans)): print("Case #{}: {}".format(i+1, ans[i]))
SYSDIGERR = -1 NOPROCESS = -2 NOFUNCS = -3 NOATTACH = -4 CONSTOP = -5 HSTOPS = -6 HLOGLEN = -7 HNOKILL = -8 HNORUN = -9 CACHE = ".cache" LIBFILENAME = "libs.out" LANGFILENAME = ".lang.cache" BINLISTCACHE = ".binlist.cache" LIBLISTCACHE = ".liblist.cache" BINTOLIBCACHE = ".bintolib.cache" TOOLNAME = "CONF...
''' Uma rainha requisitou os serviços de um monge e disse-lhe que pagaria qualquer preço. O monge, necessitando de alimentos, perguntou a rainha se o pagamento poderia ser feito em grãos de trigo dispostos em um tabuleiro de damas, de forma que o primeiro quadrado tivesse apenas um grão, e os quadrados subseqüentes, o ...
class ChatObject: def __init__(self, service, json): """Base class for objects emmitted from chat services.""" self.json = json self.service = service
""" Author : HarperHao TIME : 2020/10/ FUNCTION: """
def test_tcp_id(self): """ Comprobacion de que el puerto (objeto heredado) coincide con el asociado al Protocolos Returns: """ port = Ports.objects.get(Tag="ssh") tcp = Tcp.objects.get(id=port) self.assertEqual(tcp.get_id(), port)
class GMHazardError(BaseException): """Base GMHazard error""" def __init__(self, message: str): self.message = message class ExceedanceOutOfRangeError(GMHazardError): """Raised when the specified exceedance value is out of range when going from exceedance to IM on the hazard curve""" def...