content
stringlengths
7
1.05M
class StoreDoesNotExist(Exception): def __init__(self): super(StoreDoesNotExist, self).__init__("Store with the given query does not exist")
class Blend(GenericForm, IDisposable): """ A blend solid or void form. """ def Dispose(self): """ Dispose(self: Element,A_0: bool) """ pass def getBoundingBox(self, *args): """ getBoundingBox(self: Element,view: View) -> BoundingBoxXYZ """ pass def GetVertex...
class LexerFileWriter(): def __init__(self, tokens: dict, lexical_errors: dict, symbol_table: dict, token_filename="tokens.txt", lexical_error_filename="lexical_errors.txt", symbol_table_filename="symbol_table.txt"): self.tokens = tokens self.lexical_errors = lexical_errors ...
classes = { # layout = ["name", [attacks],[item_drops], [changes]] 0: ["soldier", [0], [2, 4, 5, 11], ["h+10", "d+2"]], 1: ["mage", [0, 2], [3, 7], ["m+40"]], 2: ["tank", [0], [1, 2, 6, 11], ["h*2", "d*0.7"]], 3: ["archer", [0, 1], [0, 3, 4, 11], ["a+10"]], 100: ["boss", [], [], ["h*1.3", "d*1.5...
def common_settings(args, plt): # Common options if args['--title']: plt.title(args['--title']) plt.ylabel(args['--ylabel']) plt.xlabel(args['--xlabel']) if args['--xlog']: plt.xscale('log') if args['--ylog']: plt.yscale('log')
#This assignment will allow you to practice writing #Python Generator functions and a small GUI using tkinter #Title: Generator Function of Powers of Two #Author: Anthony Narlock #Prof: Lisa Minogue #Class: CSCI 2061 #Date: Nov 14, 2020 #Powers of two is a gen function that can take multiple parameters, 1 or 2, gives...
# -*- coding: utf-8 -*- # 入力値を任意の刻み幅に変換 def Tick_int(num:int, tick): mod = num % 10 # 入力値の最小桁 times = int(mod / tick) # 最小桁はtick何個分か? result = tick * times # 最小桁 = tick刻みでの最大値 change = num - num % 10 + result # 最小桁をtick刻みに変換 return change
class FileNames(object): '''standardize and handle all file names/types encountered by pipeline''' def __init__(self, name): '''do everything upon instantiation''' # determine root file name self.root = name self.root = self.root.replace('_c.fit','') self.root = self.ro...
# -*- coding: utf-8 -*- class Hero(object): def __init__(self, forename, surname, hero): self.forename = forename self.surname = surname self.heroname = hero def __repr__(self): return 'Hero({0}, {1}, {2})'.format( self.forename, self.surname, self.heroname)
result = [] with open(FILE, mode='r') as file: reader = csv.reader(file, lineterminator='\n') for *features, label in reader: label = SPECIES[int(label)] row = tuple(features) + (label,) result.append(row)
def spec(x, y, color="run ID"): def subfigure(params, x_kwargs, y_kwargs): return { "height": 400, "width": 600, "encoding": { "x": {"type": "quantitative", "field": x, **x_kwargs}, "y": {"type": "quantitative", "field": y, **y_kwargs}, ...
"""Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00. Informe ao usuário a quantidades de latas de tinta a ...
# Option for variable 'simulation_type': # 1: cylindrical roller bearing # 2: # 3: cylindrical roller thrust bearing # 4: ball on disk (currently not fully supported) # 5: pin on disk # 6: 4 ball # 7: ball on three plates # 8: ring on ring # global simulation setup simulation_type = 8 # one of the above type numbers ...
class TestAuth: """ Test all functions relating to authentication in api.py. Logout is designed always to return success (even if user not logged in), since its job is to clear session data. """ def test_1(self, auth): # login and logout: correct input and method res = auth.login(uname="U1...
e={'Eid':100120,'name':'vijay','age':21} e1={'Eid':100121,'name':'vijay','age':21} e3={'Eid':100122,'name':'vijay','age':21} print(e) print(e.get('name')) e['age']=22; for i in e.keys(): print(e[i]) for i,j in e.items(): print(i,j)
class Solution(object): def islandPerimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ island_num = neighbor_num = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 1: island_n...
def all_doe_stake_transactions(): data = { 'module': 'account', 'action': 'txlist', 'address':'0x60C6b5DC066E33801F2D9F2830595490A3086B4e', 'startblock':'13554136', 'endblock':'99999999', # 'page': '1', # 'offset': '5', 'sort': 'asc', 'apikey'...
''' Created on 2018年1月31日 @author: lenovo ''' if __name__ == '__main__': opposite = {'(': ')', '[': ']', '{': '}'} print(opposite)
#Crie um pgm q tenha a função leiaint(), que vai funcionar de forma semelhante à função input() do Python, só q fazendo a validação para aceitar apenas um valor numérico. #n=leiaint('Digite um n') def leiaint(msg): num = input(msg) while num.isnumeric() is False: print(f'ERRO! {num} não é um número inte...
# -*- coding: utf-8 -*- """ Spyderエディタ これは一時的なスクリプトファイルです """ print('hello world') print('I like 6.00.1x!') a = 0 b = 1 if a < b: print ("True") else: print ("false")
n = int(input('Digite um numero! ')) m = n-1 s = n+1 print('O numero escolhido é {} seu antecessor é {} e seu sucessor é {}!' .format(n, m, s))
# -*- coding: utf-8 -*- class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 last = 0 for i in range(1, len(nums)): if nums[i] != nums[last]: ...
""" 53. How to get the last n rows of a dataframe with row sum > 100? """ """ Difficulty Level: L2 """ """ Get the last two rows of df whose row sum is greater than 100. """ """ df = pd.DataFrame(np.random.randint(10, 40, 60).reshape(-1, 4)) """
class Thinker: def __init__(self): self.velocity = 0 def viewDistance(self): return 20 def step(self, deltaTime): self.velocity = 30 def getVelocity(self): return self.velocity
__author__ = 'fernando' class BaseAuth(object): def has_data(self): raise NotImplementedError() def get_username(self): raise NotImplementedError() def get_password(self): raise NotImplementedError()
# -*- coding: utf-8 -*- def test_readuntil(monkey): pass
class dotRebarSpacing_t(object): # no doc EndOffset = None EndOffsetIsAutomatic = None EndOffsetIsFixed = None NumberSpacingZones = None StartOffset = None StartOffsetIsAutomatic = None StartOffsetIsFixed = None Zones = None
# from (Book) OpenCV-Python으로 배우는 영상 처리 및 응용 '''# 01.variable.py - 변수의 자료형''' variable1 = 100 # 정수 변수 선언 variable2 = 3.14 # 실수 변수 선언 variable3 = -200 # 정수 변수 선언 variable4 = 1.2 + 3.4j # 복소수 변수 선언 variable5 = 'Th...
# You can create a generator using a generator expression like a lambda function. # This function does not need or use a yield keyword. # Syntax : Y = ([ Expression ]) y = [1,2,3,4,5] print([x**2 for x in y]) print("\nDoing this without using the generator expressions :") length = len(y) print((x**2 for x in y).__ne...
# Mock out starturls for ../spiders.py file class MockGenerator(object): def __init__(self, *args, **kwargs): pass def __call__(self, *args, **kwargs): return [] class FeedGenerator(MockGenerator): pass class FragmentGenerator(MockGenerator): pass
class Time: def gettime(self): self.hour=int(input("Enter hour: ")) self.minute=int(input("Enter minute: ")) self.second=int(input("Enter seconds: ")) def display(self): print(f"Time is {self.hour}:{self.minute}:{self.second}\n") def __add__(self,other): sum=Time() sum.hour=self.hour+other.hour ...
n = int(input()) for i in range(n): a = input() set1 = set(input().split()) b = input() set2 = set(input().split()) print(set1.issubset(set2))
def estimator(data): reportedCases=data['reportedCases'] totalHospitalBeds=data['totalHospitalBeds'] output={"data": {},"impact": {},"severeImpact":{}} output['impact']['currentlyInfected']=reportedCases * 10 output['severeImpact']['currentlyInfected']=reportedCases * 50 days=28 if days: factor=int(da...
class Location(object): """ Represents a Location where an Action could be taken. """ def __init__(self, location_id: str): """ Create a new Location. :param location_id: The id of the Location. """ self._location_id: str = location_id @property def loca...
# The base class for all widgets class Widget: def __init__(self, name): self.name = name pass def press_on(self, key): """Called with the argument `key`""" pass def release_on(self, k): pass # Text related methods def start_text_on(self, ...
""" Space : O(n) Time : O(n) Hackerrank competition """ def getMinimumUniqueSum(arr): ans = 0 dp = [0] * 7000 for i in arr: dp[i] += 1 n = len(dp) for i in range(n-1): if dp[i] > 1: dp[i+1] += dp[i] - 1 dp[i] = 1 for j in range(n): if dp[j...
num1=int(input('Enter the first number:')) num2=int(input('Enter the second number:')) sum=lambda num1,num2:num1+num2 diff=lambda num1,num2:num1-num2 mul=lambda num1,num2:num1*num2 div=lambda num1,num2:num1//num2 print("Sum is:",sum(num1,num2)) print("Difference is:",diff(num1,num2)) print("Multiply is",mul(num1,num2...
""" command line function stuff @author: matt milunski """ def check_refresh(input): if input >= 1: return input else: return 1 def check_currency(input): assert len(input) > 0, "you forgot to specify the crypto to track" return input
SECRET_KEY='development-key' MYSQL_DATABASE_USER='root' MYSQL_DATABASE_PASSWORD='classroom' MYSQL_DATABASE_DB='Ascott_InvMgmt' MYSQL_DATABASE_HOST='dogfood.coxb3venarbl.ap-southeast-1.rds.amazonaws.com' UPLOADS_DEFAULT_DEST = 'static/img/items/' UPLOADS_DEFAULT_URL = 'http://localhost:5000/static/img/items/' UPLOADE...
class ThreadModule(object): '''docstring for ThreadModule''' def __init__(self, ): super().__init__()
# Copyright (c) 2014, MapR Technologies # # 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 agree...
def Analysis(cipherText): alphabet = dict(zip('ABCDEFGHIJKLMNOPQRSTUVWXYZ', [0] * 27)) for letter in cipherText: if letter.isalpha(): alphabet[letter] += 1 for key, value in alphabet.items(): alphabet[key] = value * (value - 1) IC = sum(alphabet.values()) / (len(cipherT...
# find nth fibonacci number using recursion. # sample output: # 21 def findnthfibnumber(n, map={1: 0, 2: 1}): if n in map: return map[n] else: map[n] = findnthfibnumber(n-1, map) + findnthfibnumber(n-2, map) return map[n] print (findnthfibnumber(9))
class Solution: def countElements(self, arr: List[int]) -> int: d = {} count = 0 for i in arr: d[i] = 1 for x in arr: if x+1 in d.keys(): count += 1 return count
def part_1() -> None: h_pos: int = 0 v_pos: int = 0 with open("../data/day2.txt", "r") as dFile: for row in dFile.readlines(): value: int = int(row.split(" ")[1]) match row.split(" ")[0]: case "forward": h_pos += ...
pkgname = "libffi8" pkgver = "3.4.2" pkgrel = 0 build_style = "gnu_configure" configure_args = [ "--includedir=/usr/include", "--disable-multi-os-directory", "--with-pic" ] hostmakedepends = ["pkgconf"] # actually only on x86 and arm (tramp.c code) but it does not hurt makedepends = ["linux-headers"] checkdepends =...
# # PySNMP MIB module HPN-ICF-L2VPN-PWE3-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-L2VPN-PWE3-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:27:17 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
""" This file contains misc functions that are used throughout the project... """ def print_dict(d, level=0): # Prints a dictionary for k, v in d.items(): if isinstance(v, dict): print(level * '\t', k, ':') print_dict(v, level + 1) else: print(level * '\t', ...
{ "targets": [ { "target_name": "gameLauncher", "conditions": [ ["OS==\"win\"", { "sources": [ "srcs/windows/GameLauncher.cpp" ] }], ["OS==\"linux\"", { "sources": [ "srcs/linux/GameLauncher.cpp" ] }] ...
# pylint: disable=undefined-variable ## Whether to include output from clients other than this one sharing the same # kernel. # Required for jupyter-vim, see: # https://github.com/jupyter-vim/jupyter-vim#jupyter-configuration c.ZMQTerminalInteractiveShell.include_other_output = True ## Text to display before the f...
# Function to count number of substrings # with exactly k unique characters def countkDist(str1, k): n = len(str1) # Initialize result res = 0 # Consider all substrings beginning # with str[i] for i in range(0, n): dist_count = 0 # Initializing array with 0 cnt = [0] ...
# -*- coding: utf-8 -*- @bot.message_handler(commands=['qrcode', 'Qrcode']) def qr_image(message): userlang = redisserver.get("settings:user:language:" + str(message.from_user.id)) userid = message.from_user.id banlist = redisserver.sismember('zigzag_banlist', '{}'.format(userid)) if banlist: return if l...
def check_order(scale_list): ascending_list = sorted(scale_list) descending_list = sorted(scale_list, reverse=True) if scale_list == ascending_list: return "ascending" elif scale_list == descending_list: return "descending" else: return "mixed" def main(): scale_list = i...
#! /usr/bin/env python3 # -*- coding: UTF-8 -*- #------------------------------------------------------------------------------ def asSeparator () : return "//" + ("-" * 78) + "\n" #------------------------------------------------------------------------------ def generateInterruptSection (interruptSectionName) : ...
class Solution(object): # Empty list + join (Accepted + Top Voted), O(n) space and time def restoreString(self, s, indices): """ :type s: str :type indices: List[int] :rtype: str """ ret = [None] * len(s) for i in range(len(s)): ret[indices[i]]...
''' File name: jr_utils.py Author: Tyche Analytics Co. Note: truncated file, suitable for model inference, but not development ''' """Collect various utility functions for JR model""" def mean(xs): if hasattr(xs,"__len__"): return sum(xs)/float(len(xs)) else: acc = 0 n = 0 ...
def two_fer(name="you"): """Returns a string in the two-fer format.""" return "One for " + name + ", one for me."
""" © https://sudipghimire.com.np Sets Exercises Please read the note carefully and try to solve the problem below: """ """ 1. Write a program to create two different set of countries i. rich: {'USA', 'China', 'Japan', 'Germany', 'France', 'Australia', 'Italy'} ii. europe: {'Germany', 'France', 'England', ...
in_str = list(str(input())) str_len = len(in_str) # letters set set_letters = set(in_str) set_len = len(set_letters) if str_len == set_len: print("Unique") else: print("Deja Vu")
# Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All contributing project au...
txtFile=open("/Users/chenchaoyang/Desktop/python/Python/content/content.txt","r") while True: line=txtFile.readline() if not line: break else: print(line) txtFile.close()
class DatabaseException(Exception): """Base exception for this package.""" pass class NoDataFoundException(DatabaseException): """Should be used when no data has been found.""" pass class BadDataException(DatabaseException): """Should be used when incorrect data is being submitted.""" pass
def beautify_parameter_name(s: str) -> str: """Make a parameter name look better. Good for parameter names that have words separated by _ . 1. change _ by spaces. 2. First letter is uppercased. """ new_s = " ".join(s.split("_")) return new_s.capitalize()
# Extra parsing for markdown (Highlighting and alert boxes) def parse(rtxt, look, control): txtl = rtxt.split(look) i, j = 0, 0 ret_text = "" while i < len(txtl): if j == 0: # This is the start before the specified tag, add it normally ret_text += control.start(txtl[i]) ...
# Copyright 2021, Google LLC # 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 to in writing, sof...
class TxtReader: def __init__(self, f): self.f = f def parse(self): file = open(self.f) line = file.readline() while line: print(line) line = file.readline() file.close #t = TxtReader('sample.txt') #t.parse()
sal = float(input('Digite o valor do seu salário: R$')) if(sal > 1250): print('Seu salário agora é R${:.2f}'.format(sal + (sal * 0.10))) else: print('Seu salário agora é R${:.2f}'.format(sal + (sal * 0.15)))
#!/usr/bin/env python # encoding: utf-8 """ search_in_2d_matrix.py Created by Shengwei on 2014-07-24. """ # https://oj.leetcode.com/problems/search-a-2d-matrix/ # tags: easy / medium, matrix, search, edge cases """ Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the followi...
# -*- coding: utf-8 -*- def greet(name): i =0 # while True: # i +=1 first_name, surname = name.split(' ') return 'Hello {0}, {1}'.format(surname, first_name) def suggest_travel(distance): if distance > 5: return 'You should take the train.' elif distance > 2: return...
# Para criar uma lista com 5 elementos '_' # ex. ['_', '_', '_', '_', '_'] print("Lista com elementos iguais") lista = [] for i in range(5): lista.append('_') print("Lista: ", lista) # Alternativa lista_alternativa = ['_' for i in range(5)] print("Modo Alternativdo de criar lista: ", lista_alternativa) # Para cr...
#hack RSA, caluclate the p,q,d in order by given t,n,e def finitePrimeHack(t, n, e): res_list = [] # find p & q for i in range(2, t): if n % i == 0: p = i q = n//p res_list.append(p) res_list.append(q) #sort the list as p <= q res_list.sort() # find the d whic...
d1 = {0:1, 1:1, 2:2, 3:3} pent_nums = [] for i in range(1, 100): val1 = ((3*(i**2))-i)/2 val2 = ((3*((-i)**2))+i)/2 pent_nums.append(val1) pent_nums.append(val2) for n in range(4, 101): ite = 0 p_t = d1[n-pent_nums[ite]] step = 1 stop = False rolling_sum = 0 while not stop: ...
n1 = int(input()) n2 = int(input()) n3 = int(input()) if n1 > n2 > n3: print(n3) print(n2) print(n1) elif n2 > n1 > n3: print(n3) print(n1) print(n2) elif n1 > n3 > n2: print(n2) print(n3) print(n1) elif n2 > n3 > n1: print(n1) print(n3) print(n2) elif n3 > n2 > n1: ...
RBNF = r""" NEWLINE := '' ENDMARKER := '' NAME := '' INDENT := '' DEDENT := '' NUMBER := '' STRING := '' single_input ::= it=NEWLINE | seq=simple_stmt | it=compound_stmt NEWLINE file_input ::= (NEWLINE | seqs<<stmt)* [ENDMARKER] -> mod=Module(sum(seqs or [], [])); fix_missing_locations(mod); return mod eval_input ...
# https://codeforces.com/problemset/problem/959/A n = int(input()) print('Mahmoud' if n%2 == 0 else 'Ehab')
# # Copyright (c) 2017-2018 Joy Diamond. All rights reserved. # @gem('Sapphire.Parse1Atom') def gem(): show = 7 @share def parse1_map_element(): if qk() is not none: #my_line('qk: %r', qk()) raise_unknown_line() token = parse1_atom() if token.is_right_b...
def calculateFuel(weight): return int(weight / 3)-2 # Part 1 total = 0 with open("/Users/a318196/Code/AdventOfCode2020/20191201/input.txt") as file: for line in file: total += calculateFuel(int(line)) print ('Total part 1: ' + str(total)) # Part 2 total = 0 with open("/Users/a318196/Code/AdventOfCode20...
class FLAG_OPTIONS: MUTLIPLE_SEGMENTS_EXIST = 0x1 ALL_PROPERLY_ALIGNED = 0x2 SEG_UNMAPPED = 0x4 NEXT_SEG_UNMAPPED = 0x8 SEQ_REV_COMP = 0x10 NEXT_SEQ_REV_COMP = 0x20 FIRST_SEQ_IN_TEMP = 0x40 LAST_SEQ_IN_TEMP = 0x80 SECONDARY_ALG = 0x100 POOR_QUALITY = 0x200 DUPLICATE_READ = 0x...
secure_log_path = "/var/log/secure"; secure_log_score_tokens = \ { "Invalid user": 3, "User root": 5, "Failed password": 2 }; secure_log_score_limit = 10; #firewall-cmd --permanent --ipset=some_set --add-entry=xxx.xxx.xxx.xxx firewalld_ipset_name = "ips2drop"; ##########################################...
__doc__ = "Menu class that represents a MenuComponent. It has a list of items, that could be other MenuComponents, or Actions(leafs)" class Menu: def __init__(self, label): self.items = [] self.label = label self.items.append(GoBackAction()) def execute(self): i = 0 op...
a, b, c, d = map(int, input().split()) s = a + b + c + d a, b, c, d = map(int, input().split()) t = a + b + c + d print(max(s, t))
""" # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children """ class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: Node :rtype: str """ vals = ...
# Copyright (c) Nikita Sychev, 29.04.2017 # Licensed by MIT a = input() b = input() c = input() n = len(a) a_new = "" b_new = "" c_new = "" for i in range(n): unused = chr(ord('A') + ord('B') + ord('C') + ord('?') - ord(a[i]) - ord(b[i]) - ord(c[i])) if a[i] == '?': a_new += u...
def sum(x,y): print("sum"," =",(x+y)) def subtract(x,y): print("difference"," =",(x-y)) def divide(x,y): print("division"," =",(x/y)) def multiply(x,y): print("multiplication"," =",(x/y))
def plug_in(symbol_values): s = symbol_values['s'] p = len(s.sites) / s.volume rho = float(s.density) mbar = rho / p v_a = 1 / p return {'p': len(s.sites) / s.volume, 'rho': float(s.density), 'v_a': v_a, 'mbar': mbar} DESCRIPTION = """ Model calculating the ...
# 110. Balanced Binary Tree # Runtime: 3232 ms, faster than 5.10% of Python3 online submissions for Balanced Binary Tree. # Memory Usage: 17.6 MB, less than 100.00% of Python3 online submissions for Balanced Binary Tree. # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=Non...
# Link: https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/ # Time: O(N) # Space: O(N) def reverse_parentheses(s): stack, queue = [], [] for char in s: if char == ")": while stack[-1] != "(": queue.append(stack.pop()) stack.pop() ...
x = input("Enter a string") y = input("Enter a string") z = input("Enter a string") for i in range(10): print("This is some output from the lab ",i) print("Your input was " + x) print("Your input was " + y) print("Your input was " + z)
"""Load dependencies needed to compile CLIF as a 3rd-party consumer.""" load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") LLVM_COMMIT = "1f21de535d37997c41b9b1ecb2f7ca0e472e9f77" # 2021-01-15 LLVM_BAZEL_TAG = "llvm-project-%s" % (LLVM_COMMIT,) LLVM_BAZEL_SHA256 = "f2fd051574fdddae8f8fff81f986d1165...
class Solution: def reverseBits(self, n): result = 0 for i in range(32): result <<= 1 if n & 1 > 0: result += 1 n >>= 1 return result
i = 1 n = 1 S = int(0) while i <= 39: somar = i/n S = S + somar n = n*2 i = i + 2 print('%.2f'%S)
n = input('Digite um valor:\n') print(type(n)) print('É um alfanumerico?',n.isalnum()) print('É alfabetico?',n.isalpha()) print('É um numero?', n.isnumeric()) print('Ésta em maiusculo?', n.isupper()) print("Está em minusculo?", n.islower())
''' Class to define a LIFO Stack ''' class UnderflowException(Exception): ''' Raised when any element access operation is attempted on an empty stack. ''' pass class Stack(object): ''' Implements a Stack or a LIFO-style collection of elements. ''' def __init__(self): self....
#!/usr/bin/env python3 def eval_jumps1(jumps): cloned = list(jumps) pc = 0 i = 0 while 0 <= pc < len(cloned): old_pc = cloned[pc] cloned[pc] += 1 pc += old_pc i += 1 return i def eval_jumps2(jumps): cloned = list(jumps) pc = 0 i = 0 while 0 <= pc <...
class Solution: def solve(self, n, k): ans = [] for i in range(k): ans.append(x := max(1,n-26*(k-i-1))) n -= x return "".join(chr(ord('a')+x-1) for x in ans)
load("@build_bazel_rules_nodejs//:index.bzl", "pkg_web") load(":tools/ngsw_config.bzl", _ngsw_config = "ngsw_config") def pkg_pwa( name, srcs, index_html, ngsw_config, additional_root_paths = []): pkg_web( name = "%s_web" % name, srcs = srcs + ["@npm//:node_m...
def rearranjar(l): return [-l[0],-l[1],l[2]] def partition(l, p, r): pivot = l[r] #ultimo elemento da lista i = p-1#inicio da janelinha for j in range(p,r): #limite da janelinha if rearranjar(l[j]) <= rearranjar(pivot): i +=1 #afasta janelinha para direita l[i],l[j] = l[j...
def calculate_amstrong_numbers_3_digits(): result = [] for item in range(100, 1000): sum = 0 for number in str(item): sum += int(number) ** 3 if sum == item: result.append(item) return result print("3-digit Amstrong Numbers:") print(calculate_amstrong_numb...
def int_to_Roman(num): val = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ] syb = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" ] roman_num = '' i = 0 while num > 0: for _ in range(num...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 5 19:33:09 2019 @author: sodatab MITx: 6.00.1x """ """ Midterm-03 Closest Power ------------------------- Implement a function called closest_power that meets the specifications below. def closest_power(base, num): ''' base: base of the ...