content
stringlengths
7
1.05M
"""Exercise 6: Using Objects""" class Person: def __init__(self, name, age): self.name = name self.age = age def introduce_self(self): print(f"I am {self.name} and I am {self.age} years old") def compare_to(self, other_person): if self.age > other_person.age: ...
n = int(input()) listx = [] for i in range(n): x,y = input().split() listx.append(int(x)%int(y)) for i in range(n): print(listx[i])
pkgname = "xwd" pkgver = "1.0.8" pkgrel = 0 build_style = "gnu_configure" hostmakedepends = ["pkgconf"] makedepends = ["libx11-devel", "libxkbfile-devel"] pkgdesc = "Dump an image of an X window" maintainer = "q66 <q66@chimera-linux.org>" license = "MIT" url = "https://xorg.freedesktop.org" source = f"$(XORG_SITE)/app/...
# Solved 05/27/2020 # Hackerrank # https://www.hackerrank.com/challenges/sherlock-and-valid-string/ def is_valid(s): # create a frequency count # if there are 3 plus frequencies return false # if there are two frequencies, but the difference in frequencies # is more than 1 return false # if there a...
""" Module: 'urequests' on micropython-esp32-1.14 """ # MCU: {'ver': '1.14', 'port': 'esp32', 'arch': 'xtensawin', 'sysname': 'esp32', 'release': '1.14.0', 'name': 'micropython', 'mpy': 10757, 'version': '1.14.0', 'machine': 'ESP32 module (spiram) with ESP32', 'build': '', 'nodename': 'esp32', 'platform': 'esp32', 'fam...
def solution(prices): answer = [] for i in range(len(prices)): pri = 0 for j in range(i+1, len(prices)): pri += 1 if prices[i] > prices[j]: break answer.append(pri) return answer
""" :Author: Arthur Goldberg <Arthur.Goldberg@mssm.edu> :Date: 2019-10-02 :Copyright: 2016-2019, Karr Lab :License: MIT """ class TestMultialgorithmSimulation(unittest.TestCase): def test_partition_species(self): self.multialgorithm_simulation.partition_species() priv_species = self.multialgorith...
"""Controls Jiachang Switch devices. """ class JcSwitch: def __init__(self, JcDirector, item_id): """Creates a Jiachang Switch object. Parameters: `JcDirector` - A `jcapi.director.JcDirector` object that corresponds to the Jiachang Director that the switch is connected to. ...
""" Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 14 + 64 + 34 + 44 8208 = 84 + 24 + 04 + 84 9474 = 94 + 44 + 74 + 44 As 1 = 14 is not a sum it is not included. The sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all the numbers ...
# KVM-based Discoverable Cloudlet (KD-Cloudlet) # Copyright (c) 2015 Carnegie Mellon University. # All Rights Reserved. # # THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANTIE...
""" Error/Exception definition. Author: Gary-Hertel Date: 2020/08/12 Email: interstella.ranger2020@gmail.com """ class CunstomException(Exception): """自定义异常类""" defaul_msg = "一个错误发生了!" def __init__(self, msg=None): self.msg = msg if msg is not None else self.defaul_msg def __str__(self): ...
class TagsTestCase(TestCase): def setUp(self): Tags.objects.create(Description="Urgent Pointer", Tag="URGP")
d = mark_safe(c) b = execute(a, c, d) d = get_object_or_404(d) send_mail_jinja(d)
#!/usr/local/bin/python3 def main(): # Test suite tests = [None, '', 'AABBCC', 'AAABCCDDDD'] results = [None, '', 'AABBCC', 'A3BCCD4'] for i in range(len(tests)): temp_result = compress_string(tests[i]) if temp_result == results[i]: print('PASS: {} returned {}'.format(tes...
# # These are some Basic methods of Strings in Python3 # # # Method - 1 : find("string", beg, end) # It returns “-1 ” if string is not found in given range. # It returns first occurrence of string if found. # Desc - Finds the first occurrence of the given String. str = "My name is Phantom Boy. I'm an Awesome Boy" # pr...
def load_dotdoe(doe_path=None): if doe_path is None: f = open('.doe', 'r') else: f = open(doe_path, 'r') text = f.read() lines = text.split('\n') dictionary = {} for line in lines: if line == '': pass else: variable = line.split(' > ')[...
gols = list() jogador = dict() tot = 0 jogador['nome'] = str(input('Nome do jogador: ')) partidas = int(input('Quantas partidas jogou: ')) for c in range(0, partidas): gol = int(input(f' ->> Quntidade de gols na partida {c}: ')) tot += gol gols.append(gol) jogador['gols'] = gols jogador['total'] = tot # M...
ROOT = "https://coursemology.org" LOGIN = "/users/sign_in" COURSE = "/courses/{}" ASSESSMENTS = "/assessments" SUBMISSIONS = "/submissions" MATERIALS = "/materials" FOLDERS = "/folders" def login(): return ROOT + LOGIN def course(id): return ROOT + COURSE.format(id) def assessments(id): return course...
""" 777. Swap Adjacent in LR String In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there exi...
# -*- coding: utf-8 -*- def killTree(n, k): if n < 1: return k return killTree(n-1, (k+1)*2) aa=int(input()) for s in range(0, aa): nm,cc = list(map(int,input().split(" "))) print("%d" % killTree(nm,cc))
# enhanced version class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ dct = {} max_so_far = curr_max = start = 0 for index, i in enumerate(s): if i in dct and dct[i] >= start: max_so_far = max(max...
def doPost(request,session): tagPaths = system.util.jsonDecode(request['postData'])['tagPaths'] tagValues = [] qualifiedValues = system.tag.readAll(tagPaths) tagValues = [{'value': qv.value, 'quality': qv.quality.toString(), 'timestamp': qv.timestamp} for qv in qualifiedValues] tagData = {} for i in range(len(t...
# Stores data about professor class Professor: # Initializes professor data def __init__(self, id, name): self.Id = id self.Name = name self.CourseClasses = [] # Bind professor to course def addCourseClass(self, courseClass): self.CourseClasses.append(courseClass) ...
# exc - 1.4.2 (rolling mission) print("""picture 1: x-------x""") print("""picture 2: x-------x | | | | |""") print("""picture 3: x-------x | | | 0 | | |""") print("""picture 4: x-------x | | | ...
def get_short_answer(unswer): return unswer.replace( ',', '.').replace( '(', '.').replace('"', '.').split('.')[0].strip().lower() def get_explanation(right_answer): index = 0 for char in right_answer: if char == '.': index += 1 break if char == ',': ...
_map_axis_values = { -11: -3, -9: -3, -7: -2, -5: -2, -3: -1, -1: -1, 1: 1, 3: 1, 5: 2, 7: 2, 9: 3, 11: 3, } class Learner: def __init__(self, id, lower_time, upper_time, active_reflexive, sensory_intuitive, visual_verbal, sequential_global, learning_goals): ...
f = open("all_ref.fa", "r") linear_ref = open("linear_all_ref.fa", "w") linear_GFP = '' linear_gacS = '' linear_pME6010 = '' linear_pUC18 = '' linear_control = '' content = [x.strip('\n') for x in f.readlines()] for i, line in enumerate(content): if line.startswith(">gi|211909964"): # print line lin...
""" First Approach: Two Pointer Approach Time Complexity O(n*n), Space Complexity O(n) """ class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: if len(nums) <3: return [] ans = [] nums = sorted(nums) print(sorted(nums)) self.twoSum(nums, 0, ans...
class Difference: def __init__(self, a): self.__elements = a def computeDifference(self): max = self.__elements[0] min = self.__elements[0] for num in self.__elements: if num > max: max = num if num < min: min = num ...
{ "targets": [{ "target_name": "heartbleed", "include_dirs": [ "src", "<(node_root_dir)/deps/openssl/openssl/include", ], "sources": [ "src/heartbleed.cc", ], }], }
class computerAgent(object): """doc string""" def __init__(self,game): self.game=game pass
### Attribute IDS CONTROLLER = 500 RULES = 1000 IS_PREMADE_GAME = 1001 PARTIES_PRIVATE = 2000 PARTIES_PREMADE = 2001 PARTIES_PREMADE_1V1 = 2002 PARTIES_PREMADE_2V2 = 2003 PARTIES_PREMADE_3V3 = 2004 PARTIES_PREMADE_4V4 = 2005 PARTIES_PREMADE_FFA = 2006 PARTIES_PREMADE_5V5 = 2007 PARTIES_PREMADE_6V6 = 2008 PARTIES_PRIVAT...
adapters = [] for line in open('input.txt', 'r').readlines(): adapters.append(int(line.strip())) adapters = sorted(adapters) device_joltage = adapters[-1] + 3 adapters.append(device_joltage) joltage, one_diff, three_diff = 0, 0, 0 for adapter in adapters: if adapter - joltage == 1: one_diff += 1 elif adapter - ...
class Peak: def __init__(self, startidx): self.born = self.left = self.right = startidx self.died = None def get_persistence(self, seq): return seq[self.born] if self.died is None else seq[self.born] - seq[self.died] def get_persistent_homology(seq): peaks = [] # Maps indices t...
"""********************************************************************* * * * Description: Implementing a python client for proxy list * * Date: 12/05/2021 * * Author: Marc...
# 141, Суптеля Владислав # 【Дата】:「03.06.20」 # 5. Створити клас з двома змінними. Додати конструктор з вхідними параметрами. # Додати конструктор, не започатковано члени класу за замовчуванням. # Додати деструкцію, що виводить на екран повідомлення про видалення об'єкта. class Var: def __init__(self, var1, var2): ...
##faça um for em x, onde cada palavra da lista ficará armazenada ##em x e utiliza o len(para contar as letras) que possui no x ## naquele momento , e isso é retornado como uma lista def contador_letras(listas_palavras): contador = [] for x in listas_palavras: quantidade = len(x) contador.append(...
class hparams: train_or_test = 'train' # 'train' or 'test' # total_epochs = 5000000 total_epochs = 300 epochs_per_checkpoint = 10 # 已经添加了每轮都保存,这个不用管 small_sample = False # 使用较少数量的样本,用于调试,启用下面的小数 small_sample_split = 0.01 # small_sample = True时生效,本次采用的数据量/总数据量 # 剩下的就是训练集的个数 see_predic...
a = input() lst = input() ans = [] for i in lst: if i != 'J' and i != 'A' and i != 'V': ans.append(i) if not ans: print("nojava") else: print(*ans,sep='')
# -*- coding: utf-8 -*- pokemon_constants = { 1: "BULBASAUR", 2: "IVYSAUR", 3: "VENUSAUR", 4: "CHARMANDER", 5: "CHARMELEON", 6: "CHARIZARD", 7: "SQUIRTLE", 8: "WARTORTLE", 9: "BLASTOISE", 10: "CATERPIE", 11: "METAPOD", 12: "BUTTERFREE", 13: "WEEDLE", 14: "KAKUNA", 15: "BEEDRILL", 16: "PIDGEY", 17: "PIDGEOTTO", 18: "PI...
# # PySNMP MIB module CISCO-LWAPP-DOT11-LDAP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LWAPP-DOT11-LDAP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:48:27 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
# k = 0 # string = "**A31" # while k < len(string): # valid_letters = ["A"," ","X","Y","*","1","2","3","4","5","6","7","8","9","W","F"] # if string[k] not in valid_letters: # raise ValueError("Bad letter in configuration file: {}".format(string[k])) # k += 1 # lines = ['**X**', '*...
# encoding: UTF-8 DATA_RECORDER = u'Data Recorder' TICK_RECORD = u'Tick Record' BAR_RECORD = u'Bar Record' CONTRACT_SYMBOL = u'Contract Symbol' GATEWAY = u'Gateway' DOMINANT_CONTRACT = u'Dominant Contract' DOMINANT_SYMBOL = u'Dominant Symbol' TICK_LOGGING_MESSAGE = u'Record Tick Data {symbol}, Time:{time}, last:{l...
# The yield statement suspends function’s execution and sends a value back to caller, # but retains enough state to enable function to resume where it is left off. When resumed, # the function continues execution immediately after the last yield run. # This allows its code to produce a series of values over time, # rat...
__version__ = "4.2.1" __doc__ = ''' # Table of Contents - Introduction - [EnviroMS](#EnviroMS) - [Version](#current-version) - [Data Input](#data-input-formats) - [Data Output](#data-output-formats) - [Data Structure](#data-structure-types) - [Features](#molecular-formulae-search-and-assignment)...
# encoding: utf-8 # module _hashlib # from (pre-generated) # by generator 1.147 # no doc # no imports # functions def new(*args, **kwargs): # real signature unknown """ Return a new hash object using the named algorithm. An optional string argument may be provided and will be automatically hashed. ...
# Leemos las dos cadenas primera = input("Ingrese su primer cadena\n") segunda = input("Ingrese su segunda cadena cadena\n") # Intentamos obtener las cadenas try: # Obtenemos el ultimo elemento de la primera ultimo_primera = primera[-1] # Obtenemos el primer elemento de la segunda primero_segunda = se...
class LabelsHelper(object): @staticmethod def create_label_from_uint(label_uint): raise Exception("Not implemented") @staticmethod def create_label_from_relations(relation_labels, label_creation_mode): raise Exception("Not implemented") @staticmethod def create_label_from_op...
class Event(): def __init__(self, correspondingEvents: dict, objects: list, characters: list, name:str, description:str): self.correspondingEvents = correspondingEvents self.objects = objects self.characters = characters self.name = name self.description= description def...
def binary(a): decimal = 0 for i in a: decimal = decimal * 2 + int(i) print(decimal) def main(): n = input("nhập số nhị phân: ") binary(n) if __name__ == '__main__': main()
soluciones = [] billetes, participantes = [int(x) for x in input().split()] while billetes and participantes: lista_billetes = [int(x) for x in input().split()] reparto = [[] for _ in range(participantes)] for posicion, billete in enumerate(lista_billetes): reparto[posicion % participantes].append(b...
# -------------- ##File path for the file file_path def read_file(path): file=open(path,'r') sentence=file.readline() file.close() return sentence sample_message=read_file(file_path) print(sample_message) #Code starts here # -------------- #Code starts here message_1=str(re...
class Solution: def _find_upper(self, arr, cnt, key): start = 0 end = cnt - 1 while start < end: mid = (start + end) // 2 if key < arr[mid]: end = mid elif key == arr[mid]: start = mid + 1 else: s...
class Match(object): def __init__(self, span, match): pass
#la diferencia entre estas dos variables "__dict__": # la de la clase y la del objeto. # class ClaseEjemplo: varia = 1 def __init__(self, val): ClaseEjemplo.varia = val self.__varia = val print(ClaseEjemplo.__dict__) objetoEjemplo = ClaseEjemplo(2) print(ClaseEjemplo.__dict__) print(objetoEjem...
# coding: utf-8 # file generated by setuptools_scm # don't change, don't track in version control version = '0.1.dev133+g3c58c47.d20220526' version_tuple = (0, 1, 'dev133', 'g3c58c47.d20220526')
# generates a list of 5 letter words from /usr/share/dict/words def main(): filtered = set() with open("/usr/share/dict/words", 'r') as file: for line in file: word = line.strip().replace("'", '').lower() if len(word) == 5: filtered.add(word) print(f"{len(fi...
# -*- coding: utf-8 -*- ENVELOPE_XMLNS = 'http://schemas.xmlsoap.org/soap/envelope/' def strip_xmlns(root): def iter_node(n): nsmap = n.nsmap for child in n: nsmap.update(iter_node(child)) return nsmap xmlns = list('{' + item + '}' for item in iter_node(root).values()) ...
def flatten(master): """ :param dict master: a multilevel dictionary :return: a flattened dictionary :rtype: dict Flattens a multilevel dictionary into a single-level one so that:: {'foo': {'bar': { 'a': 1, 'b': True, ...
#!/usr/bin/env python3 # represents the noteblocks of a certain instrument and pitch # may need to be split (further), because it may contain more than one of the same note playing at once # or for other reasons class UnsplitLine: def __init__(self, key, instrument): self.key = key self.instru...
""" 30 Effective Approach - https://codeforces.com/problemset/problem/227/B """ n = int(input()) l = list(map(int,input().split())) m = int(input()) v=list(map(int,input().split())) a,b=0,0 d = [0]*(n+1) for i in range(n) : d[l[i]] = i for q in v: a += d[q]+1 b += n-d[q] print(a,b)
# Classe Foguete # Desenvolva em Python uma classe Foguete. Essa classe deve ser iniciada com a velocidade do foguete em km/h. Supondo agora que o foguete tem uma velocidade constante (desde a partida), crie um método atualizar() que recebe como argumento o tempo decorrido em segundos desde a última vez que este método...
class Solution: def divide(self, dividend: int, divisor: int) -> int: negative = False if dividend < 0 and divisor < 0: negative = False elif dividend < 0 or divisor < 0: negative = True dividend, divisor = abs(dividend), abs(divisor) ...
a = 3 b = 4.4 print(a + b) texto = 'Sua idade é...' idade = 23 # print(texto + str(idade)) print(f'{texto} {idade}') saudação = 'Bom dia ' print(3 * saudação) PI = 3.14 raio = float(input('Informe o raio da circ: ')) area = PI * raio * raio print(f'A área da circunferência é {area}')
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:java.bzl", "java_import_external") def ts_repositories(): http_archive( name = "io_bazel_rules_closure", sha256 = "d66deed38a0bb20581c15664f0ab62270af5940786855c7adc3087b27168b529", strip_...
# 认证类型 AUTH_TYPE = 'WECHATPAY2-SHA256-RSA2048' # 请求url prefix URL_PREFIX = 'https://api.mch.weixin.qq.com' # 支付密钥路径 CLIENT_KEY = 'client_key/apiclient_key.pem' # 微信支付平台证书路径 CERT_PATH = 'cert/{}.pem' # 商户号 MCH_ID = '' # APIv3密钥,不同于API密钥,需要单独配置 API_V3_KEY = '' # 商户私钥证书序列号 SERIAL_NO = '' # 微信用户在商户对应appid下的唯一标识。 OPE...
# Input: String="aabccbb" # Output: 3 # Explanation: The longest substring with distinct characters is "abc". class DistinctCharMap(dict): def __missing__(self, v): return 0 def find_the_longest_substring_distinct(string, k=1): distinct_char_map = DistinctCharMap() temp_substring = "" longest...
n,m,k = map(int, input().split()) aa = list(map(int, input().split())) a = [] for i in range(n): a.append([aa[i], i+1]) a.sort() if not(k%m): t = int(k/m) if t < 1: print("impossible") exit() se =n - t if n == 1: if t == 1: print(1) exit() else...
# coding: utf-8 RESOURCE_MAPPING = { 'bookings': { 'resource': 'bookings/', 'docs': 'http://www.documentation.com/link/to/resource/documentation', 'methods': ['GET', 'POST'] }, }
""" Script that contains the story code """ class Color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' nerveGear = CYAN + "Nerve Ge...
class Solution: def minAddToMakeValid(self, S: str) -> int: stack1=[] stack2=[] for i in range(len(S)): if S[i] =="(": stack1.append(S[i]) elif S[i]==")" and stack1: stack1.pop() else: stack2.append(...
#!/usr/bin/env python # _*_ coding:utf-8 _*_ TAG_XML = 'xml' TAG_TESTSUITE = 'testsuite' TAG_DETAILS = 'details' TAG_TESTCASE = 'testcase' TAG_VERSION = 'version' TAG_SUMMARY = 'summary' TAG_PRECONDITIONS = 'preconditions' TAG_IMPORTANCE = 'importance' TAG_ESTIMATED_EXEC_DURATION = 'estimated_exec_duration' TAG_STAT...
class credit_scrore_calculator_and_saver(): age = input("What's your age?\n") gender = input("What's your gender?\n") payment_history = input("How many loans you have you paid\n") loans = input("How many loans do you have?\n") loans_paid = input("How many loans you have paid\n") credit_car...
print('===========Digite a Placa e a Hora==========') placa = input('Digite sua placa :') hora =float(input('Digite a hora de entrada :')) registro = placa horas = hora * 3600 horaf = horas // 3600 placaSaida = input('Digite sua placa, para liberar, seu automovel! :') horaSaida = int(input('Digite a hora de saida :'))...
# ex014: Escreva um programa que converta uma temperatura digitada em ºC e converta para ºF print('\033[1;30mEste programa irá ler a temperatura digitada e ira converte-la.\033[m') cstr = input('\033[0;32mDigite a temperatura em graus celsius: ') c = float(cstr) f = (9 * (c / 5)) + 32 print('\033[0;36m°.°.°.°.°.°' * 6...
settings = { 'launch_path': '', 'auto_generate': False, 'auto_backup': False, 'JsonRpcUser': '', 'JsonRpcPassword': '', 'observer': '', 'num_addresses': 10, 'destination': '', } # Info about the settings are in ...
x = 7 y = 11 print("x={}, y={}".format(x, y)) # swap: nonpythonic # temp = x # x = y # y = temp y, x = x, y print("x={}, y={}".format(x, y))
# -*- coding: utf-8 -*- def make_urls(urlsource, *args, **kwargs): if urlsource.kind == 'single': return urlsource.url raise NotImplementedError
"""Jaden Smith, the son of Will Smith, is the star of films such as The Karate Kid (2010) and After Earth (2013). Jaden is also known or some of his philosophy that he delivers via Twitter. When writing on Twitter, he is known for almost always capitalizing every word. For simplicity, you'll have to capitalize each wor...
''' Author: Fabián Camp Mussa Github: https://github.com/fcampm Date: May 9, 2021 Topic: Operators and operands ''' print(1 + 2) # Addition operand, result will be 3 print(2 - 2) # Substraction operand, result will be 0 print(5 * 3) # Times operator, result will be 15 print(2 ** 3) # Exponentiation operator,...
points1 = { ")": 3, "]": 57, "}": 1197, ">": 25137 } part1 = 0 points2 = { "(": 1, "[": 2, "{": 3, "<": 4 } scores2 = [] for line in open("input.txt").readlines(): stack = [] score2 = 0 for c in line.strip(): if c in "(<[{": stack.append(c) else: b = stack.pop() ...
alarms = { "0x00": { "Category": "Public Alarm", "Name": "Reset Alarm", "SetCondition": " After the system reset, the reset alarm will be set automatically", "ResetCondition": " Protocol instruction is cleared" }, "0x01": { "Category": "Public Alarm", "Name": ...
# d - cijeli broj # 13d - cijeli broj koji zauzima sveukupno 13 znakova u tekstu # 8s - string koji zauzima sveukupno 8 znakova # 10f - realni broj koji zauzima 10 znakova u tekstu uključujući decimalnu točku (decimalni dio će biti prikazan sa 6 znamenaka ukoliko nije drugačije navedeno) # 10.2f - realni broj koji zauz...
print('Vamos verificar qual é o maior número dentre os 3.') p = int(input('Digite o primeiro número:')) s = int(input('Digite o segundo número:')) t = int(input('Digite o terceiro número:')) menor = p if s < p and s < t: menor = s if t < p and t < s: menor = t if s > p and s > t: maior = s if t > s and t > ...
"""Base Class for Knowledge Base Query""" class KBquery: def __init__(self): pass def query(self, constrains): return []
class StandInLine: def getWays(self, n, a, b): if n <= 1: return [0, 0] a1, a2 = 1, 1 if n > 2: for i in range(1, n + 1): a1 *= i a1 /= 2 a2 = a1 * 2 / n return [a1, a2]
class Solution: def convert(self, s: str, numRows: int) -> str: res = ['' for _ in range(numRows)] curr_row = 0 for c in s: res[curr_row] += c if curr_row == 0: direction = 1 elif curr_row == numRows - 1: direction = -1 curr_row = (direction + ...
class Solution: """ @param nums: @param k: @return: return the length of subarray """ def smallestLengthII(self, nums, k): n = len(nums) prefixSum = [0 for _ in range(n + 1)] for i in range(n): prefixSum[i + 1] = prefixSum[i] + nums[i] start = 1 ...
isLoggedIn = False credentials = {} currentViewedRant = "" feedItemId = 2 currentFeed = "" rantToPost = "" commentToPost = "" notifs = [] notifInterval = 60 # interval in seconds comments = [] commentLen = 0 commentInterval = 30 # interval in seconds # threads check_notifs = "" check_comments = ""
n = int(input()) coelhos = 0 ratos = 0 sapos = 0 for i in range(n): quantia, tipo = input().split() quantia = int(quantia) if tipo == 'C': coelhos += quantia elif tipo == 'R': ratos += quantia else: sapos += quantia total = coelhos + ratos + sapos print(f"Total: {total}...
class ScoreSaberException(Exception): def __init__(self, status: int, url: str) -> None: self.status = status self.url = url super().__init__(f"Score Saber returned {self.status} for {self.url}") class NotFoundException(ScoreSaberException): pass class ServerException(ScoreSaberExce...
# Exercício 4.7 Rastreie o programa da listagem 4.7. Compare seu resultado ao apresentado na tabela 4.2. categoria = int(input('\nInforme a categoria do produto: ')) if categoria == 1: preco = 10 elif categoria == 2: preco = 18 elif categoria == 3: preco = 23 elif categoria == 4: preco = 26 elif categ...
#Finding the percentage #https://www.hackerrank.com/challenges/finding-the-percentage/problem if __name__ == '__main__': n = int(raw_input()) student_marks = {} for _ in range(n): line = raw_input().split() name, scores = line[0], line[1:] scores = map(float, scores) student...
""" default variables for cbstools """ TOPOLOGY_LUT_DIR = "/home/chris/Documents/code/python/cbstools-python/ToloplogyLUT/" ATLAS_DIR = "/home/chris/mipav/plugins/atlases/brain-segmentation-prior3.0/" DEFAULT_ATLAS = "brain-atlas-3.0.3.txt"
""" Common data structures used in the Bavard ecosystem, especially on the machine learning side of things. Includes data structures related to chatbot conversations (in the :mod:`~bavard_ml_utils.types.conversations.conversation` module), chatbot configuration and training data (in the :mod:`~bavard_ml_utils.types.age...
grades = [80, 75, 90] grades.append(100) total = sum(grades) length = len(grades) average = total / length grades_as_strings = [ str(grade) for grade in grades ] grades_as_string = ', '.join(grades_as_strings) print(f'Grades are: {grades_as_string}') print(f'Average is {average}')
''' Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row. Example 1: Input: triangle = [[2],[3,4],[6,5,7],[4...
PASSAGES = {} # type:ignore START = None INIT_STATE = None
class MonteCarloFrameSummary: def __init__(self): pass @staticmethod def closing_stockout_percentage(closing_stock: list, period_length: int): """ Calculates the percentage of stock out that occurred during the period specified. Args: period_length (int): length of ...
pass