content
stringlengths
7
1.05M
''' Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo. ''' reta1 = float(input('Digite o comprimento da primeira reta: ')) reta2 = float(input('Digite o comprimento da segunda reta: ')) reta3 = float(input('Digite o comprimento da terceira reta: ')) ...
# POKEMING - GON'NA CATCH 'EM ALL # -- A simple hack 'n slash game in console # -- This class is handles all utility related things class Utility: # This allows to see important message of the game def pause(message): print(message) input('Press any key to continue.')
str1 = "Python" str2 = "Python" print("\nMemory location of str1 =", hex(id(str1))) print("Memory location of str2 =", hex(id(str2))) print()
config = dict() config['fixed_cpu_frequency'] = "@ 3700 MHz" config['frequency'] = 3.7e9 config['maxflops_sisd'] = 2 config['maxflops_sisd_fma'] = 4 config['maxflops_simd'] = 16 config['maxflops_simd_fma'] = 32 config['roofline_beta'] = 64 # According to WikiChip (Skylake) config['figure_size'] = (20,9) config...
class Location: def __init__(self, location_id, borough, zone, lat, lng): self.location_id = location_id self.borough = borough self.zone = zone self.lat = lat self.lng = lng @property def json(self): return { "location_id": self.location_id, ...
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. # # What is the 10 001st prime number? primes = [] for i in range(2, 100): if len(primes) == 10001: break x = list(map(lambda y: i % y == 0, range(2,i))) if sum(x) == False: primes.a...
# Converts a given temperature from Celsius to Fahrenheit # Prompt user for Celsius temperature degreesCelsius = float(input('\nEnter the temperature in Celsius: ')) # Calculate and display the converted # temperature in Fahrenheit degreesFahrenheit = ((9.0 / 5.0) * degreesCelsius) + 32 print('Fahrenheit equivalent:...
#Refaça o DESAFIO 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado: #- EQUILÁTERO: todos os lados iguais #- ISÓSCELES: dois lados iguais, um diferente #- ESCALENO: todos os lados diferentes print('-' * 20, 'Programa Analisador de Triângulos', '-' * 20) seg1 = float(input('Digite...
class Solution: def subtractProductAndSum(self, n: int) -> int: x = n add = 0 mul = 1 while x > 0 : add += x%10 mul *= x%10 x = x//10 return mul - add
"""Helper initialising functions """ #pylint: disable=I0011, C0321, C0301, C0103, C0325, R0902, R0913, no-member, E0213 def init_fuel_tech_p_by(all_enduses_with_fuels, nr_of_fueltypes): """Helper function to define stocks for all enduse and fueltype Parameters ---------- all_enduses_with_fuels : dict ...
# Implementation of Shell Sort algorithm in Python def shellSort(arr): interval = 1 # Initializes interval while (interval < (len(arr) // 3)): interval = (interval * 3) + 1 while (interval > 0): for i in range(interval, len(arr)): # Select val to be inserted ...
''' 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 注意: 不能使用代码库中的排序函数来解决这道题。 示例: 输入: [2,0,2,1,1,0] 输出: [0,0,1,1,2,2] 进阶: 一个直观的解决方案是使用计数排序的两趟扫描算法。 首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。 你能想出一个仅使用常数空间的一趟扫描算法吗? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problem...
"""Classes implementing the descriptor protocol.""" __all__ = ("classproperty",) class classproperty: """Like the builtin :py:func:`property` but takes a single classmethod. Essentially, it allows you to use a property on a class itself- not just on its instances. Used like this: >>> from sna...
TASK_STATUS = [ ('TD', 'To Do'), ('IP', 'In Progress'), ('QA', 'Testing'), ('DO', 'Done'), ] TASK_PRIORITY = [ ('ME', 'Medium'), ('HI', 'Highest'), ('HG', 'High'), ('LO', 'Lowest'), ]
def main(): total = 0 for i in range(0, 1000): if i % 3 == 0: total += i elif i % 5 == 0: total += i print(total) if __name__ == '__main__': main()
class BaseTransform: def transform_s(self, s, training=True): return s def transform_batch(self, batch, training=True): return batch def write_logs(self, logger): pass
elements = { 'em': '', 'blockquote': '<br/>' }
def rate_diff_percentage(previous_rate, current_rate, percentage=False): diff_percentage = (current_rate - previous_rate) / previous_rate if percentage: return diff_percentage * 100 return diff_percentage
# Assume that we execute the following assignment statements # width = 17 # height = 12.0 width = 17 height = 12.0 value_1 = width // 2 value_2 = width / 2.0 value_3 = height / 3 value_4 = 1 + 2 * 5 print(f"value_1 is {value_1} and it's type is {type(value_1)}") print(f"value_2 is {value_2} and it's type is {type(va...
# 执行用时 : 68 ms # 内存消耗 : 16.6 MB # 方案:哨兵结点 sentinel,插入在head结点之前 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: # 哨兵结点 sentinel,插入在head结点之前...
""" 2338. 긴자리 계산 작성자: xCrypt0r 언어: Python 3 사용 메모리: 29,380 KB 소요 시간: 72 ms 해결 날짜: 2020년 9월 13일 """ def main(): A, B = int(input()), int(input()) print(A + B, A - B, A * B, sep='\n') if __name__ == '__main__': main()
class Solution: def mostVisited(self, n: int, rounds: List[int]) -> List[int]: start, end = rounds[0], rounds[-1] if end >= start: return list(range(start, end + 1)) else: return list(range(1, end + 1)) + list(range(start, n + 1))
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2010 Nathanael C. Fritz This file is part of SleekXMPP. See the file LICENSE for copying permission. """ __all__ = ['xep_0004', 'xep_0012', 'xep_0030', 'xep_0033', 'xep_0045', 'xep_0050', 'xep_0085', 'xep_0092', 'xep_0199', 'gmail_notify', ...
class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ vowels = set("aeiouAEIOU") s = list(s) i = 0 j = len(s) - 1 while i < j: while i < j and s[i] not in vowels: i +=...
__author__ = 'Evan Cordell' __copyright__ = 'Copyright 2012-2015 Localmed, Inc.' __version__ = "0.1.6" __version_info__ = tuple(__version__.split('.')) __short_version__ = __version__
# -*- coding: utf-8 -*- # Copyright (c) 2013 Australian Government, Department of the Environment # # 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...
def is_true(a,b,c,d,e,f,g): if a>10: print(10)
""" Sliding window Given a string S, return the number of substrings of length K with no repeated characters. Example 1: Input: S = "havefunonleetcode", K = 5 Output: 6 Explanation: There are 6 substrings they are : 'havef','avefu','vefun','efuno','etcod','tcode'. cou...
#~ Copyright 2014 Wieger Wesselink. #~ Distributed under the Boost Software License, Version 1.0. #~ (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) def read_text(filename): with open(filename, 'r') as f: return f.read() def write_text(filename, text): with open(filenam...
def is_descending(input_list: list, step: int = -1) -> bool: r"""llogic.is_descending(input_list[, step]) This function returns True if the input list is descending with a fixed step, otherwise it returns False. Usage: >>> alist = [3, 2, 1, 0] >>> llogic.is_descending(alist) True The fina...
class Solution: ''' 格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。 给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。格雷编码序列必须以 0 开头。 输入: 2 输出: [0,1,3,2] 解释: 00 - 0, 01 - 1, 11 - 3, 10 - 2 ''' def grayCode(self, n: int): # 观察连续数值对应的格雷编码序列对应的关系 # 追加二进制位到首位, 0: 数值仍为前一个数组的值, 1: 前一个数组的每个元素 + 2的(n-1)次幂 ...
class FeatureRegistration: def __init__(self, key, failoverVariant, variants=[]): """docstring for __init__""" self.key = key self.failoverVariant = failoverVariant self.variants = [v.toJSON() for v in variants] def toJSON(self): """docstring for toJSON""" self._...
_base_ = "./resnest50d_AugCosyAAEGray_BG05_visib10_mlBCE_DoubleMask_ycbvPbr100e_SO_01_02MasterChefCan.py" OUTPUT_DIR = ( "output/gdrn/ycbvPbrSO/resnest50d_AugCosyAAEGray_BG05_visib10_mlBCE_DoubleMask_ycbvPbr100e_SO/09_10PottedMeatCan" ) DATASETS = dict(TRAIN=("ycbv_010_potted_meat_can_train_pbr",))
# https://leetcode.com/problems/palindrome-partitioning/ class Solution(object): def partition(self, s): """ :type s: str :rtype: List[List[str]] """
"""Information for the outgoing response code - the HTTP response code (default is "200 Ok") headers - a list of key/value pairs used for the WSGI start_response """ code = None headers = [] def add_header(key, value): """Helper function to append (key, value) to the list of response headers""" headers....
jog = {} #pegando dados jog['Nome do jogador'] = str(input('Digite o nome do jogador: ')).strip().title() jog['Total partidas'] = int(input('Quantas partidas jogou: ')) #lista de gol gols = [] #Quantos gols em cada partida for i in range(0, jog['Total partidas']): gols.append(int(input(f'Quantos gols na partida ...
# -*- coding: utf-8 -*- # __author__= "Ruda" # Date: 2018/10/16 ''' import os from rongcloud import RongCloud app_key = os.environ['APP_KEY'] app_secret = os.environ['APP_SECRET'] rcloud = RongCloud(app_key, app_secret) r = rcloud.User.getToken(userId='userid1', name='username', portraitUri='http://www.rongcloud.c...
''' If the child is currently on the nth step, then there are three possibilites as to how it reached there: 1. Reached (n-3)th step and hopped 3 steps in one time 2. Reached (n-2)th step and hopped 2 steps in one time 3. Reached (n-1)th step and hopped 2 steps in one time The total number of possibilities is the sum...
class Solution: def runningSum(self, nums: List[int]) -> List[int]: for index in range(1, len(nums)): nums[index] = nums[index - 1] + nums[index] return nums
class PrefabError(Exception): pass class HashAlgorithmNotFound(PrefabError): pass class ImageAccessError(PrefabError): pass class ImageBuildError(PrefabError): pass class ImageNotFoundError(PrefabError): pass class ImagePushError(PrefabError): pass class ImageValidationError(PrefabEr...
class Opt: def __init__(self): self.dataset = "fashion200k" self.dataset_path = "./dataset/Fashion200k" self.batch_size = 32 self.embed_dim = 512 self.hashing = False self.retrieve_by_random = True
# Two children, Lily and Ron, want to share a chocolate bar. Each of the squares has an integer on it. # Lily decides to share a contiguous segment of the bar selected such that: # The length of the segment matches Ron's birth month, and, # The sum of the integers on the squares is equal to his birth day. # Determine...
N = int(input()) entry = [input().split() for _ in range(N)] phoneBook = {name: number for name, number in entry} while True: try: name = input() if name in phoneBook: print(f"{name}={phoneBook[name]}") else: print("Not found") except: break
pet = { "name":"Doggo", "animal":"dog", "species":"labrador", "age":"5" } class Pet(object): def __init__(self, name, age, animal): self.name = name self.age = age self.animal = animal self.hungry = False self.mood= "happy" def eat(self): print("> %s is eating....
resposta = 'S' soma = quant = media = maior = menor = 0 while resposta in 'Ss': n = int(input('Digite um número: ')) soma += n quant += 1 if quant == 1: maior = menor = n else: if n > maior: maior = n elif n < menor: menor = n resposta = str(input(...
# Definition for binary tree with next pointer. class TreeLinkNode: def __init__(self, x): self.val = x self.left = None self.right = None self.next = None class Solution: # @param root, a tree link node # @return nothing def connect(self, root): node = root ...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"get_device": "00_basics.ipynb", "settings_template": "00_basics.ipynb", "read_settings": "00_basics.ipynb", "DEVICE": "00_basics.ipynb", "settings": "00_basics.ipynb", ...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Turkey - Accounting', 'version': '1.0', 'category': 'Localization', 'description': """ Türkiye için Tek düzen hesap planı şablonu Odoo Modülü. ==================================================...
class Solution: def canArrange(self, arr: List[int], k: int) -> bool: """Hash table. Running time: O(n) where n == len(arr). """ d = collections.defaultdict(int) for a in arr: d[a % k] += 1 for key, v in d.items(): if key == 0 and v % 2 == 1: ...
# Define a procedure, fibonacci, that takes a natural number as its input, and # returns the value of that fibonacci number. # Two Base Cases: # fibonacci(0) => 0 # fibonacci(1) => 1 # Recursive Case: # n > 1 : fibonacci(n) => fibonacci(n-1) + fibonacci(n-2) def fibonacci(n): return n if n ==...
#!/usr/bin/python # -*- coding: UTF-8 -*- """ @file : __init__.py.py @Time : 2020/11/12 13:37 @Author: Tao.Xu @Email : tao.xu2008@outlook.com """ """ phoronix-test-suite: Main for Performance Test =================== https://github.com/phoronix-test-suite/phoronix-test-suite The Phoronix Test Suite is the most compr...
errorFound = False def hasError(): global errorFound return errorFound def clearError(): global errorFound errorFound = False def error(message, lineNo = 0): report(lineNo, "", message) def report(lineNo, where, message): global errorFound errorFound = True if lineNo == 0: ...
""" 模板语言: {{ 变量 }} {% 代码段 %} {% 一个参数时:变量|过滤器, Book.id | add: 1 <= 2 当前id+1来和2比较 两个参数时:变量|过滤器:参数 %}, 过滤器最多只能传2个参数,过滤器用来对传入的变量进行修改 {% if book.name|length > 4 %} 管道|符号的左右不能有多余的空格,否则报错,其次并不是name.length而是通过管道来过滤 {{ book.pub_date|date:'Y年m月j日' }} 日期的转换管道 """ """ CSRF 跨站请求伪造, 盗用...
# -*- coding:utf-8 -*- # /usr/bin/env python """ Author: Albert King date: 2019/10/20 10:58 contact: jindaxiang@163.com desc: 外汇配置文件 """ # headers SHORT_HEADERS = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36' } # url FX_SPOT_URL ...
dia = int(input('Dia = ')) mes = str(input('Mês = ')) ano = int(input('Ano = ')) print('Você nasceu no dia {} de {} de {}. Correto?' .format(dia, mes, ano))
class AnythingType(set): def __contains__(self, other): return True def intersection(self, other): return other def union(self, other): return self def __str__(self): return '*' def __repr__(self): return "Anything" Anything = AnythingType()
allct_dat = { "TYR": { "HB2":{'torsion': 300.0, 'tree': 'E', 'NC': 4, 'NB': 6, 'NA': 8, 'I': 9, 'angle': 109.5, 'blen': 1.09, 'charge': 0.038, 'type': 'HC'}, "HB3":{'torsion': 60.0, 'tree': 'E', 'NC': 4, 'NB': 6, 'NA': 8, 'I': 10, 'angle': 109.5, 'blen': 1.09, 'charge': 0.038, 'type': 'HC'}, "impropTors":[['-M', 'CA'...
def kelime_sayisi(string): counter = 1 for i in range(0,len(string)): if string[i] == ' ': counter += 1 return counter cumle = input("Cumlenizi giriniz : ") print("Cumlenizdeki kelime sayisi = {}".format(kelime_sayisi(cumle)))
class Solution: def paintHouse(self, cost:list, houses:int, colors:int)->int: if houses == 0: # no houses to paint return 0 if colors == 0: # no colors to paint houses return 0 dp = [[0]*colors for _ in range(houses)] dp[0] = cost[0]...
''' Created on Dec 21, 2014 @author: Ben ''' def create_new_default(directory: str, dest: dict, param: dict): ''' Creates new default parameter file based on parameter settings ''' with open(directory, 'w') as new_default: new_default.write( '''TARGET DESTINATION = {} SAVE DESTINATION = {}...
class Solution(object): def intToRoman(self, num): """ 数字到罗马数字的转换 :type num: int :rtype: str """ dic = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"] nums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]#两个数组,从高到低 res = "" ...
"""Exceptions for Renault API.""" class RenaultException(Exception): # noqa: N818 """Base exception for Renault API errors.""" pass class NotAuthenticatedException(RenaultException): # noqa: N818 """You are not authenticated, or authentication has expired.""" pass
def grayscale(image): for row in range(image.shape[0]): for col in range(image.shape[1]): avg = sum(image[row][col][i] for i in range(3)) // 3 image[row][col] = [avg for _ in range(3)]
def get_cross_sum(n): start = 1 total = 1 for i in range(1, n): step = i * 2 start = start + step total += start * 4 + step * 6 start = start + step * 3 return total print(get_cross_sum(501))
# -*- coding: utf-8 -*- """ Created on Sat Oct 10 15:31:57 2020 @author: Tarun Jaiswal """ dictone = { "bookname": "Recursion Sutras", "subject": "Recursion", "author": "Champak Roy" } dicttwo = dict(dictone) print(dicttwo)
class Analyser: def __init__(self, callbacks, notifiers, state): self.cbs = callbacks self.state = state self.notifiers = notifiers def on_begin_analyse(self, timestamp): pass def on_end_analyse(self, timestamp): pass def analyse(self, event): event_nam...
def retorno(): resp=input('Deseja executar o programa novamente?[s/n] ') if(resp=='S' or resp=='s'): verificar() else: print('Processo finalizado com sucesso!') pass def cabecalho(titulo): print('-'*30) print(' '*9+titulo+' '*15) print('-'*30) pass def mensage...
GOV_AIRPORTS = { "Antananarivo/Ivato": "big", "Antsiranana/Diego": "small", "Fianarantsoa": "small", "Tolagnaro/Ft. Dauphin": "small", "Mahajanga": "medium", "Mananjary": "small", "Nosy Be": "medium", "Morondava": "small", "Sainte Marie": "small", "Sambava": "small", "Toamasi...
def fibonacci(n): fibonacci = np.zeros(10, dtype=np.int32) fibonacci_pow = np.zeros(10, dtype=np.int32) fibonacci[0] = 0 fibonacci[1] = 1 for i in np.arange(2, 10): fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2] fibonacci[i] = int(fibonacci[i]) print(fibonacci) for i in np.arange(10): fibonacci_pow[i] ...
# Copyright (c) 2020 NVIDIA Corporation # 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, merge, publish, d...
def split_in_three(data_real, data_fake): min_v = min(data_fake.min(), data_real.min()) max_v = max(data_fake.max(), data_real.max()) tercio = (max_v - min_v) / 3 # Calculate 1/3 th_one = min_v + tercio # Calculate 2/3 th_two = max_v - tercio first_f, second_f, third_f = split_data(th_...
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ nums_set = set(nums) full_length = len(nums) + 1 for num in range(full_length): if num not in nums_set: return num
# O Departamento Estadual de Meteorologia lhe contratou para desenvolver um programa que leia as um conjunto indeterminado de temperaturas, e informe ao final a menor e a maior temperaturas informadas, bem como a média das temperaturas. temperaturas = [] while True: graus = float(input("Digite a temperatura em gr...
"""Below Python Programme demonstrate rpartition functions in a string""" string = "Python is fun" # 'is' separator is found print(string.rpartition('is ')) # 'not' separator is not found print(string.rpartition('not ')) string = "Python is fun, isn't it" # splits at last occurence of 'is' print(string.rpartition('...
data = ( 'Mie ', # 0x00 'Xu ', # 0x01 'Mang ', # 0x02 'Chi ', # 0x03 'Ge ', # 0x04 'Xuan ', # 0x05 'Yao ', # 0x06 'Zi ', # 0x07 'He ', # 0x08 'Ji ', # 0x09 'Diao ', # 0x0a 'Cun ', # 0x0b 'Tong ', # 0x0c 'Ming ', # 0x0d 'Hou ', # 0x0e 'Li ', # 0x0f 'Tu ', # 0x10 'Xiang ...
divisor = int(input()) bound = int(input()) for num in range(bound, 0, -1): if num % divisor == 0: print(num) break
cities = [ 'Budapest', 'Debrecen', 'Miskolc', 'Szeged', 'Pecs', 'Zuglo', 'Gyor', 'Nyiregyhaza', 'Kecskemet', 'Szekesfehervar', 'Szombathely', 'Jozsefvaros', 'Paradsasvar', 'Szolnok', 'Tatabanya', 'Kaposvar', 'Bekescsaba', 'Erd', 'Veszprem', ...
def read_file(test = True): if test: filename = '../tests/day1.txt' else: filename = '../input/day1.txt' with open(filename) as file: temp = list() for line in file: temp.append(line.strip()) return temp def puzzle1(): temp = read_file(False)[0] floo...
""" The key is to use a set to remember if we seen the node or not. Next, think about how we are going to *remove* the duplicate node? The answer is to simply link the previous node to the next node. So we need to keep a pointer `prev` on the previous node as we iterate the linked list. So, the solution. Create a set ...
def firstDuplicate(a): number_frequencies, number_indices, duplicate_index = {}, {}, {} # Iterate through list and increment frequency count # if number not in dict. Also, note the index asscoiated # with the value for i in range(len(a)): if a[i] not in number_frequencies: numbe...
""" CONFIGURATION FILE This is being developed for the MF2C Project: http://www.mf2c-project.eu/ Copyright: Roi Sucasas Font, Atos Research and Innovation, 2017. This code is licensed under an Apache 2.0 license. Please, refer to the LICENSE.TXT file for more information Created on 18 oct. 2018 @author: Roi Sucasas...
# # PySNMP MIB module IANA-MALLOC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IANA-MALLOC-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:50:25 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
""" 1208. Get Equal Substrings Within Budget Straight forward. Asked the max len, so count the max each time. """ class Solution: def equalSubstring(self, s: str, t: str, maxCost: int) -> int: cost = 0 window_start = 0 result = 0 for window_end in range(...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2011 OpenERP s.a. (<http://openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the G...
class File: @staticmethod def tail(self, file_path, lines=10): with open(file_path, 'rb') as f: total_lines_wanted = lines block_size = 1024 f.seek(0, 2) block_end_byte = f.tell() lines_to_go = total_lines_wanted block_number = -1 ...
"""Reverse stack is using a list where the top is at the beginning instead of at the end.""" class Reverse_Stack: def __init__(self): self.items = [] def is_empty(self): # test to see whether the stack is empty. return self.items == [] def push(self, item): # adds a new item to the bas...
class Solution: def isStrobogrammatic(self, num: str) -> bool: strobogrammatic = { '1': '1', '0': '0', '6': '9', '9': '6', '8': '8' } for idx, digit in enumerate(num): if digit not in strobogrammatic or strobogrammatic[...
class Solution(object): def dfs(self,stones,graph,curpos,lastjump): if curpos==stones[-1]: return True # since the jump need based on lastjump # only forward,get rid of the stay at the same pos rstart=max(curpos+lastjump-1,curpos+1) rend=min(curpos+lastjump+1,ston...
def check_candidate(a, candidate, callback_when_different, *args, **kwargs): control_result = None candidate_result = None control_exception = None candidate_exception = None reason = None try: control_result = a(*args, **kwargs) except BaseException as e: control_exception ...
n = int(input()) % 8 if n == 0: print(2) elif n <= 5: print(n) else: print(10 - n)
""" A fixed-capacity queue implemented as circular queue. Queue can become full. * enqueue is O(1) * dequeue is O(1) """ class Queue: """ Implementation of a Queue using a circular buffer. """ def __init__(self, size): self.size = size self.storage = [None] * size self.first =...
def área(larg, comp): a = larg * comp print(f'A área de um terreno {larg}x{comp} é de {a}m²') print('Controle de Terrenos') print('--------------------') l = float(input('Largura (m): ')) c = float(input('Comprimento (m): ')) área(l, c)
""" A simple script for numbering nUp tickets for the print shop. """ def numbering_main() -> None: """ Gets numbering sequences for nUp ticket numbering. Gets the total number of tickets requested along with now many will fit on a sheet (n_up) as well as the starting ticket number and prints the tic...
def arg_to_step(arg): if isinstance(arg, str): return {'run': arg} else: return dict(zip(['run', 'parameters', 'cache'], arg)) def steps(*args): return [arg_to_step(arg) for arg in args]
#inputFile = 'sand.407' inputFile = 'sand.407' outputFile= 'sand.out' def joinLine(): pass with open(inputFile) as OF: lines = OF.readlines() print(lines[0:3])
class MergeSort: def __init__(self, lst): self.lst = lst def mergeSort(self, a): midPoint = len(a) // 2 if a[len(a) - 1] < a[0]: left = self.mergeSort(a[:midPoint]) right = self.mergeSort(a[midPoint:]) return self.merge(left, right) else: ...
''' There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. ''' ### Nature: the meaning of MEDIAN, is that, the number of elements less than it, ##...
# Copyright 2019 The SQLNet Company GmbH # 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, merge, publish, ...
def container_image_is_external(biocontainers, app): """ Return a boolean: is this container going to be run using an external URL (quay.io/biocontainers), or is it going to use a local, named Docker image? """ d = biocontainers[app] if (('use_local' in d) and (d['use_local'] is True)): ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def hasPathSum(self, root: 'TreeNode', sum: 'int') -> 'bool': if not root: return False def helper(node,val):...