content
stringlengths
7
1.05M
#350111 #a3_p10.py #Alexander_Mchedlishvili #a.mchedlish@jacobs-university.de n=int(input("Enter the width(horizontal): ")) m=int(input("Enter the length(vertical): ")) c="c" def print_frame(n, m, c): row = n * c ln = len(row)-2 for a in range(m): if a == 0 or a == (m-1): ...
N = int(input()) A = list(map(int, input().split())) B = list(map(int, input().split())) C = list(map(int, input().split())) ans = 0 prev = -1 for i, a in enumerate(A): ans += B[a-1] if a == prev + 1: ans += C[prev - 1] prev = a print(ans)
# [기초-입출력] 실수 1개 입력받아 그대로 출력하기(설명) # minso.jeong@daum.net ''' 문제링크 : https://www.codeup.kr/problem.php?id=1012 ''' f = float(input()) # print(f) print('{:.6f}'.format(f)) # 입력 : 1.54인경우, 출력 : 1.540000 을 위해...
""" Given two numbers, find their product using recursion """ x = 5532 y = 256 def recursive_multiply(x, y): # This cuts down on the total number of # recursive calls: if x < y: return recursive_multiply(y, x) if y == 0: return 0 return x + recursive_multiply(x, y-1) print(x...
casa = float(input('Digite o valor da casa R$')) salario = float(input('Digite o valor do seu salário R$')) anos = int(input('Em quantos anos pretende pagar? '))*12 parcela = casa / anos if parcela > (salario*0.7): print('Emprestimo negado, parcela exede 30% do salário. Valor da parcela \033[31mR${:.2f}\033[m'.form...
# Title TITLE = "The Game of Life" # Screen Dimensions ROWS = 40 COLS = 40 SCREEN_WIDTH = 600 SCREEN_HEIGHT = 600 # Square (or Rectangle) Dimensions SQR_WIDTH = int(SCREEN_WIDTH // COLS) SQR_HEIGHT = int(SCREEN_HEIGHT // ROWS) # Times FPS = 10 # Text FONT_NAME = "freesansbold.ttf" FONT_SIZE = 15 TEXT_X = SCREEN_WID...
# -*- coding:utf-8; -*- class Solution: def dailyTemperatures(self, T): res = [0 for i in range(len(T))] stack = [] for i in range(len(T)): # 1. 判断应该用递减栈 # 2. 因为判断的是距离,所以栈中应该存储的是元素的位置 while stack and T[stack[-1]] < T[i]: # 说明T[i]是栈顶元素右侧的第一个...
'''from constants import * from jobs import * from download import * from convert import * from upload import * from polling import* '''
def test(): assert ( "docs = list(nlp.pipe(TEXTS))" in __solution__ ), "Verwendest du nlp.pipe in einer Liste?" __msg__.good("Gute Arbeit!")
"""Utility functions """ def get_phase_number(total_number_of_phases, phase_number): """Summary Parameters ---------- total_number_of_phases : TYPE Description phase_number : TYPE Description Returns ------- TYPE Description """ # wrap around ...
MOVES_LIMIT = 2*10**5 class Queue: def __init__(self): self.queue = [] def push(self, data): self.queue.insert(0, data) return "ok" def pop(self): return self.queue.pop() def front(self): return self.queue[-1] def size(self): return len(self.queue) def clear(self): s...
""" Contains exception base classes for Behave Restful. """ class BehaveRestfulException(Exception): """ Base class for exceptions raised by behave_restful. """ def __str__(self): return self.__repr__() def __repr__(self): return "BehaveResfulException('Unknown Error')"
__all__ = [ "ParamScheduler", "ConstantParamScheduler", "CosineParamScheduler", "LinearParamScheduler", "CompositeParamScheduler", "MultiStepParamScheduler", "StepParamScheduler", "StepWithFixedGammaParamScheduler", "PolynomialDecayParamScheduler", ]
# 5. Escreva um algoritmo que receba dois valores (raio e altura) # e calcule o valor do volume de uma lata de óleo. raio = int(input("Digite o raio: ")) altura = int(input("Digite a altura: ")) volume = (3.14 * raio**2 * altura) print("O volume do cilindro é", volume)
name = str(input("Please enter your name: ")) #These two lines ask for password and name, then store them in variable pw = str(input("Please enter a password: ")) print("Welcome", name) # Prints name pwLength = len(pw) #Checks the length of the password pwList = list(pw) #Lists each character of the string in a singl...
class DuplicateStageName(TypeError): pass class IncompleteStage(TypeError): pass class StageNotFound(ValueError): pass class ReservedNameError(TypeError): pass
class Warrior: def __init__(self, name, level, experience, rank): self.name = name self.level = level self.experience = experience self.rank = rank def __str__(self): return '[Warrior: %s, %s, %s, %s]' % (self.name, self.level, self.experience, self.rank) def ran...
# # PySNMP MIB module BayNetworks-IISIS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BayNetworks-IISIS-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:42:41 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
# CES-22: Programação Orientada a Objetos # Aluno: Guilherme Kowalczuk (COMP-23) # Descrição da Atividade: # Considerando o exemplo do CoffeShop com Padrão de Projeto Decorator. Crie um # exemplo que construa Pizzas. Ao invés de itens para um café, usar ingredientes de # pizza. O Diagrama de Classes deve ser elaborad...
""" # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail """ # Write your code here n, m = map(int, input().strip().split()) bo...
env = MDPEnvironment() for step in range(n_steps): action = exploration_policy(env.state) state = env.state next_state, reward = env.step(action) next_value = np.max(q_values[next_state]) # greedy policy q_values[state, action] = (1-alpha)*q_values[state, action] + alpha*(reward + gamma * next_value...
a = int(input()) b = int(input()) c = int(input()) d = int(input()) e = int(input()) f = int(input()) g = int(input()) h = int(input()) i = int(input()) A = [] A.append(a) A.append(b) A.append(c) A.append(d) A.append(e) A.append(f) A.append(g) A.append(h) A.append(i) B = sorted(A) maxnum = B[8] for k in range(len...
# Marcelo Campos de Medeiros # ADS UNIFIP # Estrutura de Repetição # 25/03/2020 ''' 49- Faça um programa que mostre os n termos da Série a seguir: S = 1/1 + 2/3 + 3/5 + 4/7 + 5/9 + ... + n/m. ''' print('=' * 40) print('{:=^40}'.format(" 'S = 1/1 + 2/3 + 3/5 + 4/7 + 5/9 + ... + n/m' ")) print('=' * 40, '\n') numero...
#- Hours in a year. How many hours are in a year? print (365 * 24) #for the leap year e.g 2020 print (366 * 24) #- Minutes in a decade. How many minutes are in a decade? # Year has 365 days, day has 24 hour, hour has 60 minutes and decade equels 10 years print (365 * 24 * 60 * 10) #for the leap year e.g 2020 print (366...
"""" Auth """ auth_client_id: str = 'carp' auth_client_secret: str = 'carp' auth_client_password_grant_type: str = 'password' auth_client_refresh_token_grant_type: str = 'refresh_token' auth_client_researcher_username: str = 'ossi0004@gmail.com' auth_client_researcher_password: str = 'xxxx' auth_client_researcher_new_p...
# -*- coding: utf-8 -*- """ @ author: Javad Fattahi @ detail: Configuration file for Customer Agent (The Great-DR project) """ # UNIT DETAILS MRID = '\x0a\xaf\x72\x05\x44\x04\xff\xa0\xed\x54\xc1\xab\x00\x00\x87\xb4' HEMSC_MRID = '\xE7\xF7\x5C\x8D\x24\x99\x67\x6C\x5D\x1D\x47\x5B\x00\x00\x87\xB4' SFDI = 26948382356...
languages = { 'aa':'Afar', 'ab':'Abkhazian', 'af':'Afrikaans', 'ak':'Akan', 'sq':'Albanian', 'am':'Amharic', 'ar':'Arabic', 'an':'Aragonese', 'hy':'Armenian', 'as':'Assamese', 'av':'Avaric', 'ae':'Avestan', 'ay':'Aymara', 'az':'Azerbaijani', 'ba':'Bashkir', ...
''' Given a string, find the length of the longest substring T that contains at most 2 distinct characters. For example, Given s = “eceba”, T is "ece" which its length is 3. ''' class Solution: def lengthOfLongestSubstringKDistinct(self, s, k): if k==0: return 0 j,longest,sco...
# replace the function below in sphinx.ext.autodoc.py (tested with Sphinx version 0.4.1) __author__ = "Martin Felder" def prepare_docstring(s): """ Convert a docstring into lines of parseable reST. Return it as a list of lines usable for inserting into a docutils ViewList (used as argument of nested_p...
config = { 'unit_designation' : 'SALUD', 'sleep_interval' : 300, # seconds to sleep. Increase to have less frequent updates and longer battery life 'warn_threshold' : 1000, 'alarm_threshold' : 2100, 'temperature_offset' : 3, # if you care about temp from the sensor. Probably shouldn't. ...
class Rick: def never(self) -> "Rick": print("never ", end="") return self def gonna(self) -> "Rick": print("gonna ", end="") return self def give(self) -> "Rick": print("let ", end="") return self def you(self) -> "Rick": print("you ", end="") ...
#!/usr/bin/env python3 ###################################################################################### # # # Program purpose: There are 10 vertical and horizontal squares on a plane. # # Each squa...
class NoCache(object): def process_response(self, request, response): """ set the "Cache-Control" header to "must-revalidate, no-cache" """ if request.path.startswith('/static/'): response['Cache-Control'] = 'must-revalidate, no-cache' return response
n = int(input("Enter number of terms of the series to be displayed: ")) def fibonacci(_n): if _n <= 1: return _n else: return fibonacci(_n - 1) + fibonacci(_n - 2) for i in range(n): print(fibonacci(i), end=", ")
# -*- coding: utf-8 -*- """ File Name: IsPopOrder Author : jing Date: 2020/3/23 https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106?tpId=13&tqId=11174&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking 栈的压入、弹出 """ class Solution: def ...
# -*- coding: utf-8 -*- # Copyright (c) 2018-2020 Niko Sandschneider """ easyp2p is an application for downloading and aggregating account statements from several people-to-people (P2P) lending platforms. """ __version__ = '0.0.1'
""" 面试题 46:把数字翻译成字符串 题目:给定一个数字,我们按照如下规则把它翻译为字符串:0 翻译成 "a",1 翻 译成 "b",……,11 翻译成 "l",……,25 翻译成 "z"。一个数字可能有多个翻译。例 如 12258 有 5 种不同的翻译,它们分别是 "bccfi"、"bwfi"、"bczi"、"mcfi" 和 "mzi"。请编程实现一个函数用来计算一个数字有多少种不同的翻译方法。 1 2 2 5 8 1 22 5 8 1 2 25 8 12 2 5 8 12 25 8 """ def get_translation_count1(num: int) -> int: """ Para...
# -*- coding: utf-8 -*- __description__ = u'RPZ-IR-Sensor Utility' __long_description__ = u'''RPZ-IR-Sensor Utility ''' __author__ = u'osoken' __email__ = u'osoken.devel@outlook.jp' __version__ = '0.0.0' __package_name__ = u'pyrpzirsensor'
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ ...
#Replace APIKEY with your Metoffice Datapoint API key, and LOCATION with # the location you want weather for. # Get your location from: # http://datapoint.metoffice.gov.uk/public/data/val/wxfcs/all/json/sitelist?key=<your key here> APIKEY = "<your key here>" LOCATION = "<your location here>"
# # PySNMP MIB module HUAWEI-AAA-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-AAA-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:30:41 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...
''' # 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero zeros(12) = 2 # 12! = 479001600 --> 2 trailing zeros Hint: You're not meant to calculate the factorial. Find another way to find the number of zeros. ''' # 没搞定,答案是错的 def zeros(n): count5 = 0 count10 = 0 countodd = 0 zero = 0 for x in rang...
# desenvolva um programa que leia 4 valores pelo teclado e guarde-os em uma tupla. # no final mostre: # quantas vezes apareceu o valor 4 # em que posição foi digitado o primeiro valor 3 # quais foram os números pares valores = (int(input('Insira um número: ')), int(input('Insira outro número: ')), ...
class Version(): main = 0x68000001 test = 0x98000001 mijin = 0x60000001 class TransactionType(): transfer_transaction = 0x0101 importance_transfer_transaction = 0x0801 multisig_aggregate_modification_transfer_transaction = 0x1001 multisig_signature_transaction = 0x1002 multisig_transaction = 0x1004 provision_...
# Copyright (c) 2018, MD2K Center of Excellence # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditio...
FreeSans9pt7bBitmaps = [ 0xFF, 0xFF, 0xF8, 0xC0, 0xDE, 0xF7, 0x20, 0x09, 0x86, 0x41, 0x91, 0xFF, 0x13, 0x04, 0xC3, 0x20, 0xC8, 0xFF, 0x89, 0x82, 0x61, 0x90, 0x10, 0x1F, 0x14, 0xDA, 0x3D, 0x1E, 0x83, 0x40, 0x78, 0x17, 0x08, 0xF4, 0x7A, 0x35, 0x33, 0xF0, 0x40, 0x20, 0x38, 0x10, 0xEC, 0x20, 0xC6, 0x20, 0xC...
# pop]Remove element by index [].pop planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'] print(planets) # ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'] third = planets.pop(2) print(third) # Earth print(planets) # ['Mercury', 'Venus', 'Mars', 'Jupiter'] last = planets.pop() print(last) # Jupiter print(planet...
def getmonthdays(y, m): if (m == 2): if (isleapyear(y)): return 29 else: return 28 else: return { 1: 31, 3: 31, 4: 40, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31 }[m] def isleapyear(y): r...
class GirlFriend: girlfriend = False def __init__(self,exist): self.girlfriend = exist self.girlfriend = False GirlFriend.girlfriend = False print(" No. She doesn't exist! :( ") def exists(self): return False
def miesiace(): lista=['styczeń','luty','marzec','kwiecień','maj','czerwiec','lipiec', 'sierpień','wrzesień','październik','listopad','grudzień'] for i in range(0, 12, 1): yield lista[i] gen=miesiace() for i in range(0, 12, 1): print(next(gen))
# SheetManager Exceptions class GoogleConnectionException(Exception): pass class InitSheetManagerException(Exception): pass class AuthSheetManagerException(Exception): pass class CreateSheetException(Exception): pass class OpenSheetException(Exception): pass class WriteTableException(Excep...
onnx = [] verbose = 0 header = ["include/operators"] no_header = 0 force_header = 0 resolve = ["src/operators/resolve"] no_resolve = 0 force_resolve = 0 sets = ["src/operators/"] no_sets = 0 stubs = ["src/operators/implementation"] force_sets = 0 no_stubs = 0 force_stubs = 0 info = ["src/operators/info"] no_info = 0 f...
#!/usr/bin/env-python3 print('Welcome to a hello word for python.') name = input("Please enter you name: ") print("Hi " + name + " welcome to python") print("python is very powerful")
# Build a program that create an automatic pizza order # Consider that there are three types of pizza: Small ($15), Medium ($20) and large ($25) # If you want to add pepperoni, you will need to add $2 for a small pizza # For the Medium or large one, you will need to add $3 # If you want extra cheese, the added price wi...
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified). __all__ = ['hello_world'] # Cell def hello_world(world): """ This function says hello to the `world` """ print("hello ", world)
Names = ["Jack", "Cian", "Leah", "Elliot", "Cai", "Eben"] print("Hello how are you " + Names[0]) print("Hello how are you " + Names[1]) print("Hello how are you " + Names[2]) print("Hello how are you " + Names[3]) print("Hello how are you " + Names[4]) print("Hello how are you " + Names[5])
# CABEÇALHO print("\033[1:35m-=-\033[m" * 10) print("\033[1:31mCALCULANDO VALOR A SER PAGO") print("\033[1:35m-=-\033[m" * 10) # VARIAVEIS INPUTS valor = float(input("Digite aqui o valor do produto que deseja comprar: R$")) print("Confirmado o valor de R${} do seu produto!".format(valor)) f = int(input("Agora escolha a...
''' stemdiff.const -------------- Constants for package stemdiff. ''' # Key constants # (these costants are not expected to change for given microscope # (they can be adjusted if the program is used for a different microscope DET_SIZE = 256 '''DET_SIZE = size of pixelated detector (in pixels :-)''' RESC...
# using for loops with the range function # https://www.udemy.com/course/100-days-of-code/learn/lecture/18085735#content ''' # start value a is first number # end value b is last value but is not included in range for number in range (a, b): print(number) ''' # print all values between 1 through 10 for num...
def birthday_ranges(birthdays, ranges): list_of_number_of_birthdays = [] for start, end in ranges: number = 0 for current_birthday in birthdays: if current_birthday in range(start, end): number += 1 list_of_number_of_birthdays.append(number) return list_o...
class Solution: def majorityElement(self, nums: List[int]) -> int: #using hashmap or dictionary as is called in python count = {} for i in nums: if i in count: count[i] += 1 else: count[i] = 1 if count[i] > len(nums)...
"""Variable types provided by Dakota. The module name in this package must match the keyword used by Dakota for the variable; e.g., the Dakota keyword ``continuous_design`` is used to name **continuous_design.py**. """
#uses python3 def evalt(a, b, op): if op == '+': return a + b elif op == '-': return a - b elif op == '*': return a * b else: assert False def MinMax(i, j, op, m, M): mmin = 10000 mmax = -10000 for k in range(i, j): a = evalt(M[i][k], M[k+1][j], op[k])...
## To fill these in: ## 1. Create a twitter account, or log in to your own ## 2. apps.twitter.com ## 3. Click "Create New App" ## 4. You'll see Create An Application. Fill in a name (must be unique) and a brief description (anything OK), and ANY complete website, e.g. http://programsinformationpeople.org in the website...
# -*- coding: utf-8 -*- # # This is the Robotics Language compiler # # Language.py: Definition of the language for this package # # Created on: June 22, 2017 # Author: Gabriel A. D. Lopes # Licence: Apache 2.0 # Copyright: 2014-2017 Robot Care Systems BV, The Hague, The Netherlands. All rights reser...
#!/usr/bin/env python3 # https://abc053.contest.atcoder.jp/tasks/abc053_b s = input() print(s.rindex('Z') - s.index('A') + 1)
#!/usr/bin/env python3 def charCount(ch, st): count = 0 for character in st: if character == ch: count += 1 return count st = input("Enter a string ") ch = input("Find character to be searched ") print(charCount(ch, st))
""" Given an n-ary tree, return the preorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). Follow up: Recursive solution is trivial, could you do it iteratively? Example 1: I...
# configuration file for resource "postgresql_1" # # this file exists as a reference for configuring postgresql resources # and to support self-test run of module protocol_postgresql_pg8000.py # # copy this file to your own cage, possibly renaming into # config_resource_YOUR_RESOURCE_NAME.py, then modify the copy conf...
data = test_dataset.take(15) points, labels = list(data)[0] points = points[:8, ...] labels = labels[:8, ...] # run test data through model preds = model.predict(points) preds = tf.math.argmax(preds, -1) points = points.numpy() # plot points with predicted class and label fig = plt.figure(figsize=(15, 10)) for ...
t=1 while t<=10: print(f'Tabuada do Tabuada do {t}') n=1 while n<=10: print(f'{t} x {n} ={t*n}') n=n+1 t= t+1 print()
class Statistics: def __init__( self, ): self.metrics = { 'success': 0, 'failure': 0, 'retry': 0, 'process': 0, 'heartbeat': 0, } self.workers = {} def process_report( self, message, ): ...
def in_the_matrix(): matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]] rows = len(matrix) # count # of rows for i in range(rows): col = len(matrix[i]) # count # of columns for x in range(col): print(matrix[i][x], end='') print() return
# -*- coding: utf-8 -*- """ Created on Mon Oct 12 20:22:51 2020 @author: Abhishek Parashar """ arr=[10,20,30,40] # Python3 program for optimal allocation of pages # Utility function to check if # current minimum value is feasible or not. def isPossible(arr, n, m, curr_min): studentsRequired = 1 cur...
# https://github.com/jeffmer/micropython-upybbot/blob/master/font.py ''' * This file is part of the Micro Python project, http:#micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2013, 2014 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this soft...
class Solution(object): def numPairsDivisibleBy60(self, time): """ :type time: List[int] :rtype: int """ return self.hashmap(time) def naive(self, time): count = 0 for i in range(len(time)): for j in range(i + 1, len(time)): if...
N = int(input()) if N == 1 or N == 103: print(0) else: print(N)
trabalho_terca = True trabalho_quinta = False ''' - Os dois sendo verdadeiros = TV'50 + sorvete - Só um sendo verdadeiro = TV'32 + sorvete - Nenhum verdadeiro = Fica em casa ''' tv_50 = trabalho_terca and trabalho_quinta svt = trabalho_terca or trabalho_quinta tv_32 = trabalho_terca != trabalho_quinta mais_saudavel = ...
panther = ['''\ ____ ,;|||||\ ______________ ___ |;|||:;:| ,' Time to play `----. /;,a.\\ |||||...._ `-. _ H A N G M A N; |||@@@\\\ __----,'......~\_ ,---._ ;; `-.____________...
# Create a python list containing first 5 positive even numbers. Display the list elements in the desending order. list1 = [2, 4, 6, 8, 10] list1.sort(reverse=True) print(list1) # hehe be efficient and not just do `print(list1[4])` , `print(list1[3])` etc etc
# # Copyright (C) 2020 Arm Mbed. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # """Use this module to assemble build configuration."""
class ExpertaError(Exception): def __init__(self, message): super().__init__(message) class FactNotFoundError(ExpertaError): """ """ def __init__(self): self.message = f"Fact wasn't found" super().__init__(self.message)
# Title : Simple Decorator # Author : Kiran Raj R. # Date : 12/11/2020 def my_decorator(function): def inner_function(name): print("This is a simple decorator function output") function(name) print("Finished....") return inner_function def greet_me(name): print(f"Hello, Mr.{name...
class MenuItem: def __init__(self, option: str, name: str): self.option = option self.name = name def __call__(self, action: callable, *args, **kwargs): self.action = action def inner_function(*args, **kwargs): return self.action(*args, **kwargs) return s...
"""Module that holds classes related to sets. This module contains the `Set` class. `Set` represents a set. Examples: Creating a `Set`, adding elements, and checking membership: s = Set() s.union(Set(1)) s.union(Set(2,3)) if 1 in s: print("1") Removing elements fr...
# Copyright 2016 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
__author__ = "Eli Serra" __copyright__ = "Copyright 2020, Eli Serra" __deprecated__ = False __license__ = "MIT" __status__ = "Production" # Version of realpython-reader package __version__ = "2.5.0"
class WhoisItError(Exception): ''' Parent Exception for all whoisit raised exceptions. ''' class BootstrapError(WhoisItError): ''' Raised when there are any issues with bootstrapping. ''' class QueryError(WhoisItError): ''' Raised when there are any issues with queries. ...
"""OTElib exceptions.""" class BaseOtelibException(Exception): """A base OTElib exception.""" class ApiError(BaseOtelibException): """An API Error Exception""" def __init__(self, detail: str, status: int, *args) -> None: super().__init__(detail, *args) self.detail = detail self....
with open("halting.txt") as file: lines = file.readlines() lines = [line.rstrip() for line in lines] insn = [(lines[i][:3], int(lines[i][4:])) for i in range(len(lines))] jmps = [i for i in range(len(insn)) if insn[i][0] == "jmp"] curr = 0 acc = 0 switch = 0 while switch < len(jmps): acc = 0 visited...
''' Given two strings str1 and str2, find the length of the smallest string which has both, str1 and str2 as its sub-sequences. Input: The first line of input contains an integer T denoting the number of test cases.Each test case contains two space separated strings. Output: Output the length of the required string. ...
print('Triangulos') print('=' * 20) m1 = float(input('Digtite uma Medida: ')) m2 = float(input('Digite outra Medida: ')) m3 = float(input('Digite outra Medida: ')) if m1 < m2 + m3 and m2 < m1 + m3 and m3 < m1 + m2: print('As medidas {}, {} e {} podem formar um Triangulo'.format(m1, m2, m3)) else: print('As medi...
#cari median def cariMedian(arr): totalNum=len(arr) if totalNum%2 == 0: index1=int(len(arr)/2) index2=int(index1-1) return (arr[index1]+arr[index2])/2 else: index=int((len(arr)-1)/2) return arr[index] #test case print(cariMedian([1, 2, 3, 4, 5])) # 3 print(cariMedian...
# -*- coding: utf-8 -*- def main(): s = input() n = len(s) if s == s[::-1]: t = s[:(n - 1) // 2] u = s[(n + 3) // 2 - 1:] if t == t[::-1] and u == u[::-1]: print('Yes') else: print('No') else: print('No') if __name_...
ADDRESS = { 'street': 'Elm Street', 'street_2': 'No 185', 'city': 'New York City', 'state': 'NY', 'zipcode': '10006' } ADDRESS_2 = { 'street': 'South Park', 'street_2': 'No 1', 'city': 'San Francisco', 'state': 'CA', 'zipcode': '94110' } ADMIN_USER = { 'username': 'bobs', ...
# Package exception model: # Here we subclass base Python exception overriding its constructor to # accomodate error message string as its first parameter and an open # set of keyword arguments that become exception object attributes. # While exception object is bubbling up the call stack, intermediate # exception hand...
# Python program to demonstrate working of extended # Euclidean Algorithm # function for extended Euclidean Algorithm def gcdExtended(a, b): # Base Case if a == 0 : return b, 0, 1 gcd, x1, y1 = gcdExtended(b%a, a) # Update x and y using results of recursive # call x = y1 - (b//a) * x1 y = x1 return...
# -*- coding: utf-8 -*- # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ # H. mistura2 # Sejam duas strings a e b # Retorno uma string '<a> <b>' separada por um...
"""Package version.""" # This file is part of me-types-mapper. # # # Copyright © 2021-2022 Blue Brain Project/EPFL # # # This program is free software: you can redistribute it and/or modify # it under the terms of the APACHE-2 License. # # This program is distributed in the hope that it will be useful, # but WITHOUT AN...
class Solution: @lru_cache(maxsize=None) def minCostAfter(self, index, lastColor, target): if target<0 or len(self.houses)-index+1<target: return -1 if index==self.m-1: if self.houses[index]!=0: if (target==0 and lastColor==self.houses[index]) o...