content
stringlengths
7
1.05M
test_data = """ 939 7,13,x,x,59,x,31,19 """.strip() data = """ 1001612 19,x,x,x,x,x,x,x,x,41,x,x,x,37,x,x,x,x,x,821,x,x,x,x,x,x,x,x,x,x,x,x,13,x,x,x,17,x,x,x,x,x,x,x,x,x,x,x,29,x,463,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,23 """.strip() def test_aoc13_p1t(): time, schedule = test_data.splitlines() time ...
# # @lc app=leetcode id=485 lang=python3 # # [485] Max Consecutive Ones # # https://leetcode.com/problems/max-consecutive-ones/description/ # # algorithms # Easy (55.74%) # Likes: 573 # Dislikes: 349 # Total Accepted: 200.8K # Total Submissions: 360.6K # Testcase Example: '[1,0,1,1,0,1]' # # Given a binary array...
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ x = 0 y = 0 xx = len(matrix) - 1 yy = len(matrix[0]) - 1 rows = xx + 1 cols = yy + 1 w...
# Sanitize a dependency so that it works correctly from code that includes # QCraft as a submodule. def clean_dep(dep): return str(Label(dep))
def unatrag(s): if len(s)==0: return s else: return unatrag(s[1:]) + s[0] s=input("Unesite rijec: ") print(unatrag(s))
file_obj = open("squares.txt", "w") #Usar w de writing for number in range (13): square = number * number file_obj.write(str(square)) file_obj.write('\n') file_obj.close()
# Exercise 4: Assume that we execute the following assignment statements: # width = 17 # height = 12.0 # For each of the following expressions, write the value of the expression and the type (of the value of the expression). # 1. width//2 # 2. width/2.0 # 3. height/3 # 4. 1 + 2 * 5 width = 17; height = 12.0; one = wi...
altitude = int(input("Enter Altitude in ft:")) if altitude<=1000: print("Safe to land") elif altitude< 5000: print("Bring down to 1000") else: print("Turn Around and Try Again")
# -*- coding: utf-8 -*- def test_dummy(cmd, initproj, monkeypatch): monkeypatch.delenv(str("TOXENV"), raising=False) path = initproj( 'envreport_123', filedefs={ 'tox.ini': """ [tox] envlist = a [testenv] deps=tox-envreport ...
# -*- coding: utf-8 -*- ''' File name: code\comfortable_distance\sol_364.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #364 :: Comfortable distance # # For more information see: # https://projecteuler.net/problem=364 # Problem Statemen...
class Water(): regions = None outline_points = None def __init__(self): self.regions = [] self.outline_points = []
1 "test" "equality" == "equality" 1.5 * 10 int
class Classe: atributo_da_classe = 0 print(Classe.atributo_da_classe) Classe.atributo_da_classe = 5 print(Classe.atributo_da_classe)
# 917. Reverse Only Letters def reverseOnlyLetters(S): def isLetter(c): if (ord(c) >= 65 and ord(c) < 91) or (ord(c) >= 97 and ord(c) < 123): return True return False A = list(S) i, j = 0, len(A) - 1 while i < j: if isLetter(A[i]) and isLetter(A[j]): A[i]...
a=str(input('Enter string')) if(a==a[::-1]): print('palindrome') else: print('not a palindrome')
# # PySNMP MIB module CTRON-SSR-SMI-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-SSR-SMI-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:15:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
PROCESSOR_VERSION = "0.7.0" # Entities AREAS = "areas" CAMERAS = "cameras" ALL_AREAS = "ALL" # Metrics OCCUPANCY = "occupancy" SOCIAL_DISTANCING = "social-distancing" FACEMASK_USAGE = "facemask-usage" IN_OUT = "in-out" DWELL_TIME = "dwell-time"
print('Digite um número entre 1 e 7, para ver o dia da semana') diaSemana = ['1-Domingo', '2-Segunda-feira', '3-Terça-feira', '4-Quarta-feira', '5-Quinta-feira', '6-Sexta-feira', '7-Sábado'] dia = int(input('Número: ')) if 1 < dia < 7: print('Dia da semana inválido') else: print(f'O dia da semana é: {diaSemana[...
class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ if n == 1: return 1 if n == 2: return 2 a = 1 b = 2 for i in range(3, n + 1): c = a + b a = b b = c ...
''' URL: https://leetcode.com/problems/delete-columns-to-make-sorted/ Difficulty: Easy Description: Delete Columns to Make Sorted We are given an array A of N lowercase letter strings, all of the same length. Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those ...
ACTIVE_CLASS = 'active' SELECTED_CLASS = 'selected' class MenuItem: def __init__(self, label, url, css_classes='', submenu=None): self.label = label self.url = url self.css_classes = css_classes self.submenu = submenu def status_class(self, request): css_class = '' ...
class Hyparams: user_count= 192403 item_count= 63001 cate_count= 801 predict_batch_size = 120 predict_ads_num = 100 batch_size = 128 hidden_units = 64 train_batch_size = 32 test_batch_size = 512 predict_batch_size = 32 predict_users_num = 1000 predict_ads_num = 100 ...
''' Created on 1.12.2016 @author: Darren '''''' Follow up for problem "Populating Next Right Pointers in Each Node". What if the given tree could be any binary tree? Would your previous solution still work? Note: You may only use constant extra space. For example, Given the following binary tre...
def set_template(args): # task category args.task = 'VideoBDE' # network parameters args.n_feat = 32 # loss args.loss = '1*L1+2*HEM' # learning rata strategy args.lr = 1e-4 args.lr_decay = 100 args.gamma = 0.1 # data parameters args.data_train = 'SDR4K' args.data_test...
""" Write a program by the following: 1. Define a function that accepts a string and prints every other word 2. Define a function that accepts a string and translates it into pig latin 3. If time, implement them into a main loop """
# # PySNMP MIB module UNCDZ-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/UNCDZ-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:28:43 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat May 23 17:49:24 2020 @author: ahmad """ x = [5, 9, 8, -8, 7, 8, 10] #print(x[4]) #for i in range(0,len(x)): # print(x[i]) # write a code to show the sum og the numbers in the Array sum = 0 for i in range(0,len(x)): sum += x[i] print("array su...
""" 600. Smallest Rectangle Enclosing Black Pixels https://www.lintcode.com/problem/smallest-rectangle-enclosing-black-pixels/description 九章算法课上的方法 """ class Solution: """ @param image: a binary matrix with '0' and '1' @param x: the location of one of the black pixels @param y: the location of one of t...
"""State: Abstract class that defines the desired state of inventory in a target system""" class State(object): def __init__(self): self.logger = None self.verify_connectivity() def verify_connectivity(self): raise NotImplementedError def set_logger(self): raise NotImplem...
class BaseBuilding(object): """ boilder-plate class used to initiale the various building in municipality """ def __init__(self, location=None, land_rate=500): if not isinstance(location, str) and location is not None: raise TypeError("Location should be of type str") ...
"""adds Buffer functionality to Loader""" class BufferMixin(object): """stuff""" def __init__(self, *args, **kwargs): """initializes base data loader""" super(BufferMixin, self).__init__(*args, **kwargs) self._buffered_values = None #set _buffered_values self._reset_b...
''' Exercício Python 26: Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra “A”, em que posição ela aparece a primeira vez e em que posição ela aparece a última vez. ''' frase = str(input('Digite uma frase: ')).upper().strip() print('A letra "A" aparece {} vezes na frase'.format(f...
NB_GRADER_CONFIG_TEMPLATE = """ c = get_config() c.CourseDirectory.root = '/home/{grader_name}/{course_id}' c.CourseDirectory.course_id = '{course_id}' """
class Settings: def __init__( self, workdir: str, outdir: str, threads: int, debug: bool): self.workdir = workdir self.outdir = outdir self.threads = threads self.debug = debug class Logger: def __i...
# -*- coding: utf-8 -*- """ Created on Mon Jan 15 01:40:25 2018 @author: kennedy """ #sample --> 'kennedy':'ify1', 'andy': 'best56', 'great': 'op3' #create new user system = {} #database system option = "" def newusers(): uname= input("Enter a username: ") if uname in system: print("User a...
"""Cached evaluation of integrals of monomials over the unit simplex. """ # Integrals of all monomial basis polynomials for the space P_r(R^n) over the n-dimensional unit simplex, # given as a list. monomial_integrals_unit_simplex_all_cache = { # (n, r) = (1, 1) (1, 1): [ 1, 1 / 2 ], # ...
#import base64 # #data = "abc123!?$*&()'-=@~" # ## Standard Base64 Encoding #encodedBytes = base64.b64encode(data.encode("utf-8")) #encodedStr = str(encodedBytes, "utf-8") # #print(encodedStr) # l = [x for x in range(10)] for x in range(10): l.pop(0) print(l)
load(":collection_results.bzl", "collection_results") load(":collect_module_members.bzl", "collect_module_members") load(":declarations.bzl", "declarations") load(":errors.bzl", "errors") load(":tokens.bzl", "tokens", rws = "reserved_words", tts = "token_types") # MARK: - Attribute Collection def _collect_attribute(p...
f = open('input.txt') adapters = [] for line in f: adapters.append(int(line[:-1])) adapters.sort() adapters.append(adapters[-1] + 3) differences = {} previous = 0 for adapter in adapters: current_difference = adapter - previous if not current_difference in differences: differences[current_difference] = ...
class Solution: def peakIndexInMountainArray(self, A): """ :type A: List[int] :rtype: int """ A_new = sorted(A) return A.index(A_new[-1]) # # other solutions # # 1. # class Solution: # def peakIndexInMountainArray(self, A): # """ # :type A: List[...
# LinkNode/Marker ID Table # -1: Unassigned (Temporary) # 0 ~ 50: Reserved for Joint ID # FRAME_ID = 'viz_frame'
""" strategy_observer.py Copyright 2015 Andres Riancho This file is part of w3af, http://w3af.org/ . w3af is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 2 of the License. w3af is distributed in the hop...
students = ['Lilly', 'Olivia', 'Emily', 'Sophia'] students.pop() # ['Lilly', 'Olivia', 'Emily'] (пособие) print(students) # ['Lilly', 'Olivia', 'Emily'] students.pop(1) # ['Lilly', 'Emily', 'Sophia'] (пособие) print(students) # ['Lilly', 'Emily']
VBA = \ r""" Function ExecuteCmdSync(targetPath As String) 'Run a shell command, returning the output as a string' ' Using a hidden window, pipe the output of the command to the CLIP.EXE utility... ' Necessary because normal usage with oShell.Exec("cmd.exe /C " & sCmd) always pops a windows Dim instr...
''' Statement Given a list of numbers, find and print the elements that appear in it only once. Such elements should be printed in the order in which they occur in the original list. Example input 4 3 5 2 5 1 3 5 Example output 4 2 1 ''' arr = input().split() for i in arr: if arr.count(i) == 1: print(i, ...
# Matrix Tracing # How many ways can you trace a given matrix? - 30 Points # # https://www.hackerrank.com/challenges/matrix-tracing/problem # MOD = 1000000007 def fact(n): """ calcule n! mod MOD """ f = 1 for i in range(2, n + 1): f = (f * i) % MOD return f def pow(a, b): """ calcule a^b ...
age = 17 name = 'Nicolay' print('Возраст {0} - - {1} лет.'.format(name, age)) print('Почему {0} забавляется с этим Python?'.format(name)) # второй способ age =100 name = 'Nicolay' print('Возраст {} - - {} лет.'.format(name,age)) print('Почему {} забавляется с этим Python?'.format(name))
class Source: pass class URL(Source): def __init__(self, url, method="GET", data=None): self.url = url self.method = method self.data = data def get_data(self, scraper): return scraper.request(method=self.method, url=self.url, data=self.data).content def __str__(self)...
fs = 44100. dt = 1. / fs def rawsco_to_ndf(rawsco): clock, rate, nsamps, score = rawsco if rate == 44100: ar = True else: ar = False max_i = score.shape[0] samp = 0 t = 0. # ('apu', ch, func, func_val, natoms, offset) ndf = [ ('clock', int(clock)), ('apu', 'ch', 'p1', 0, 0, 0),...
#Write a program to input a string and check if it is a palindrome or not. #This solution is in python programing language str = input("Enter the string: ") if str == str[::-1]: print("String is Palindrome") else: print("String is not Palindrome")
buddy= "extremely loyal and cute" print(len(buddy)) print(buddy[0]) print(buddy[0:10]) print(buddy[0:]) print(buddy[:15]) print(buddy[:]) # len gives you the length or number of characters of the string. # So (len(buddy)) when printed = 24 as even spaces are counted. # [] these brackets help to dissect the components o...
class Secret: # Dajngo secret key SECRET_KEY = '' # Amazone S3 AWS_STORAGE_BUCKET_NAME = '' AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = ''
""" leetcode 232 Stack implementation Queue """ def __init__(self): self.instack = [] self.outstack = [] def push(self, x: int) -> None: self.instack.append(x) def pop(self) -> int: if not self.outstack: while self.instack: self.outstack.append(self.instack.pop()) return self....
class MessageHandler: def __init__(self, name: str): self.name = name self.broker = None def process_message(self, data: bytes): pass
self.description = "Sysupgrade with same version, different epochs" sp = pmpkg("dummy", "2:2.0-1") sp.files = ["bin/dummynew"] self.addpkg2db("sync", sp) lp = pmpkg("dummy", "1:2.0-1") lp.files = ["bin/dummyold"] self.addpkg2db("local", lp) self.args = "-Su" self.addrule("PACMAN_RETCODE=0") self.addrule("PKG_VERSIO...
a = int(input('Digite um número: ')) b = int(input('Digite outro número: ')) c = int(input('Digite mais um número: ')) d = int(input('Digite o último número: ')) n = a,b,c,d print(f'Você digitou os valores: {n}') print(f'O valor 9 apareceu {n.count(9)} vezes.') if 3 in n: print(f'O valor 3 apareceu na {n.index(3)+1...
def commonCharacterCount(s1, s2): dic1 = {} dic2 = {} sums = 0 for letter in s1: dic1[letter] = dic1.get(letter,0) + 1 for letter in s2: dic2[letter] = dic2.get(letter,0) + 1 for letter in dic1: if letter in dic2: sums = sums + min(dic1[letter],dic2[letter]) ...
class QuickReplyButton: def __init__(self, title: str, payload: str): if not isinstance(title, str): raise TypeError("QuickReplyButton.title must be an instance of str") if not isinstance(payload, str): raise TypeError("QuickReplyButton.payload must be an instance of str") ...
class EnigmaException(Exception): pass class PlugboardException(EnigmaException): pass class ReflectorException(EnigmaException): pass class RotorException(EnigmaException): pass
def checks_in_string(string, check_list): for check in check_list: if check in string: return True return False
def find_strongest_eggs(*args): eggs = args[0] div = args[1] res = [] strongest = [] is_strong = True n = div for _ in range(n): res.append([]) for i in range(1): if div == 1: res.append(eggs) break else: for j i...
############################################################################################### # 因为边权一样,可以用广搜;一下时间复杂度分析可见非常unreasonable # 但由于n的范围不大于12,所以总的时间消耗小于10^6,可接收 ########### # 时间复杂度:O((n^2)*(2^n)),广搜常规本来是n+m,对每个点循环其所有边,但此题不一样;看循环次数,不止是循环n次 # 因为增加了状态的维度,到达每个点,状态可能有2^n种,所以一共可走的点有n*2^n种,而每次走一个点,边和点同一数量级 # 所...
##PUT ALL INFO BETWEEN QUOTES BELOW AND RENAME THIS FILE TO 'creds.py' #Twilio API Account info ACCOUNT_SID = "" AUTH_TOKEN = "" # your cell phone number below (must begin with '+', example: "+15555555555") TO_PHONE = "" # your Twilio phone number below (must begin with '+', example: "+15555555555") FROM_PHONE = "" ...
class ModeException(Exception): def __init__(self, message: str): super().__init__(message) class SizeException(Exception): def __init__(self, message: str): super().__init__(message) class PaddingException(Exception): def __init__(self, message: str): super().__init__(message) ...
#!/usr/bin/env python """ Aluguel de carro Escreva um programa que pergunte a quantidade de km percorridos por um carro alugado pelo usuario, assim como a quantidade de dias pelos quais o carro foi alugado. Calcule o preco a pagar, sabendo que o carro custa R$ 60,00 por dia e R$ 0,15 por km rodado. """ def pay(km, da...
def function(a): pass function(10)
""" Datos de entrada P-->p-->int Q-->q-->int Datos de salida mensaje-->m-->float """ p=int(input("Ingrese el valor de p ")) q=int(input("Ingrese el valor de q ")) if(p**3+q**4-2*p**2>680): print(str(p)+" y "+ str(q)+" satisfacen la expresión") else: (p**3+q**4-2*p**2<680) print(str(p)+" y "+ str(q)+" no s...
sal = float(input('Digite seu salário: R$')) if sal <= 1250: novo = sal * 1.15 else: novo = sal * 1.1 print(f'Seu antigo salário era \033[1;37m{sal}\033[m e o seu novo salário é \033[36;1m{novo:.2f}')
# To use the tinypng API you must provide your API key. # https://tinypng.com/developers API_KEY = "key" # Raw-images directory USER_INPUT_PATH = r"C:\raw_images" # Save directory USER_OUTPUT_PATH = r"C:\compressed_images" # METADATA ——————————————————————————————————————————————————————————— # Copyright informat...
class NullAttributeException(Exception): """Raised when the attribute which is not nullable is missing.""" pass class ItemNotFoundException(Exception): """Raised when the item is not found""" pass class ConditionNotRecognizedException(Exception): """Raised when the condition is not found""" ...
[ { 'date': '2014-01-01', 'description': 'Nový rok', 'locale': 'cs-CZ', 'notes': '', 'region': '', 'type': 'NF' }, { 'date': '2014-01-01', 'description': 'Den obnovy samostatného českého státu', 'locale': 'cs-CZ', 'notes': '', ...
class Base1: def __init__(self, *args): print("Base1.__init__",args) class Clist1(Base1, list): pass class Ctuple1(Base1, tuple): pass a = Clist1() print(len(a)) a = Clist1([1, 2, 3]) print(len(a)) a = Ctuple1() print(len(a)) a = Ctuple1([1, 2, 3]) # TODO: Faults #print(len(a)) print("---") cl...
# 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, software # distributed under the Li...
def hash_function(s=b''): a, b, c, d = 0xa0, 0xb1, 0x11, 0x4d for byte in bytearray(s): a ^= byte b = b ^ a ^ 0x55 c = b ^ 0x94 d = c ^ byte ^ 0x74 return format(d << 24 | c << 16 | a << 8 | b, '08x')
# -*- coding: utf-8 -*- """ lswifi.constants ~~~~~~~~~~~~~~~~ define app constant values """ APNAMEACKFILE = "apnames.ack" APNAMEJSONFILE = "apnames.json" CIPHER_SUITE_DICT = { 0: "Use group cipher suite", 1: "WEP-40", # WEP 2: "TKIP", # WPA-Personal (TKIP is limited to 54 Mbps) 3: "Reserved", ...
#!/usr/bin/env python3 # coding: utf8 """ constants.py Date: 08-21-2019 Description: Defines the codes required for ansi code generation """ START = "\033[" END = "\033[0m" COLOR_CODES = { "k": "black", "b": "blue", "r": "red", "g": "green", "p": "purple", "y": "yellow", "c": "cyan", ...
def buy_card(n: int, p: list): d = [0]*(n+1) for i in range(1, n+1): for j in range(1, i+1): d[i] = max(d[i], d[i-j] + p[j-1]) return d[n] def test_buy_card(): assert buy_card(4, [1, 5, 6, 7]) == 10 assert buy_card(5, [10, 9, 8, 7, 6]) == 50 assert buy_card(10, [1, 1, 2, ...
class Item: item_id = 1 def __init__(self, name): self.name = name self.item_id = Item.item_id Item.item_id += 1 tv = Item('LG 42') computer = Item('Dell XPS') print(tv.item_id) print(computer.item_id) # prints: # 1 # 2
#!/usr/bin/env python3 """Remove vowels and whitespace from a string and put the vowels at the end. Title: Disemvoweler Description: Make a program that removes every vowel and whitespace found in a string. It should output the resulting disemvoweled string with the removed vowels concatenated to the end of it. For e...
# Dit is weer een encoder, dus gebruik instellinen die daarbij horen. real_encoder = tf.keras.models.Sequential([ tf.keras.layers.Dense(784, activation=tf.nn.relu), tf.keras.layers.Dense(128, activation=tf.nn.relu), tf.keras.layers.Dense(2, activation=tf.nn.relu), tf.keras.layers.Dense(128, activation=tf.nn.rel...
SLOTS = [ [ 0, 5460, ["172.17.0.2", 7000, "cf0da23bbea0ac65fd93d272358b59cd7ce3af25"], ["172.17.0.2", 7003, "ab35b1210fcae1010a463c65e1616b51d3d7a00b"], ], [ 9995, 9995, ["172.17.0.2", 7000, "cf0da23bbea0ac65fd93d272358b59cd7ce3af25"], ["172.17...
def emulate_catchup(replica, ppSeqNo=100): if replica.isMaster: replica.caught_up_till_3pc((replica.viewNo, ppSeqNo)) else: replica.catchup_clear_for_backup() def emulate_select_primaries(replica): replica.primaryName = 'SomeAnotherNode' replica._setup_for_non_master_after_view_change(r...
# this is the module which i will be #calling and using again and again def kolar(): print("I am a new module which will work i am call") # this file save with same python path with new file name
f = open('Log-A.strace') lines = f.readlines() term = ' read(' term2 = 'pipe' term3 = 'tty' def extract_name(line, start_delimiter, end_delimiter): name_start = line.find(start_delimiter) name_end = line.find(end_delimiter, name_start + 1) name = line[name_start + 1 : name_end] return name names = [...
TEMPLATE_SOURCE_TYPE = "TemplateSourceType" # stairlight.yaml STAIRLIGHT_CONFIG_FILE_PREFIX = "stairlight" STAIRLIGHT_CONFIG_INCLUDE_SECTION = "Include" STAIRLIGHT_CONFIG_EXCLUDE_SECTION = "Exclude" STAIRLIGHT_CONFIG_SETTING_SECTION = "Settings" DEFAULT_TABLE_PREFIX = "DefaultTablePrefix" FILE_SYSTEM_PATH = "FileSyst...
# # @lc app=leetcode id=696 lang=python3 # # [696] Count Binary Substrings # # https://leetcode.com/problems/count-binary-substrings/description/ # # algorithms # Easy (61.31%) # Total Accepted: 81.6K # Total Submissions: 132.8K # Testcase Example: '"00110011"' # # Give a binary string s, return the number of non-e...
#Desenvolva um programa que leia o primeiro termo e a razão de uma PA. # No final mostre os 10 prmeiros termos dessa progressão. n = int(input('Digite um numero: ')) razao = int(input('Digite uma razao: ')) dec = n + (10-1) * razao for c in range (n, dec+razao, razao): print(c, end=' ')
def reverse(s): target = list(s) for i in range(int(len(s) / 2)): swap = target[i] target[i] = target[len(s) - i - 1] target[len(s) - i - 1] = swap return ''.join(target) if __name__ == '__main__': s = 'abcdef' print(reverse(s)) print(s[::-1])
"""피보나치 수열 Memoization""" def fib_memo(n, cache): if n < 3: return 1 if n in cache: return cache[n] cache[n] = fib_memo(n - 2, cache) + fib_memo(n - 1, cache) return cache[n] def fib(n): # n번째 피보나치 수를 담는 사전 fib_cache = {} return fib_memo(n, fib_cache) if __name__ ...
valor_casa = float(input("Qual o valor do imovel? ")) salario = float(input("Qual salário do comprador? ")) anos = int(input("Em quantos anos deseja pagar? ")) print(f"{'ANALISANDO DADOS':~^50}") print(f"Valor do imóvel: R$ {valor_casa:.2f}") prestacao = valor_casa / (anos*12) print(f"Valor da prestação: {prestacao:.2...
# -*- coding: utf-8 -*- def bubble_sort(arr): """ Sorts the input array using the bubble sort method. The idea is to raise each value to it's final position through successive swaps. Complexity: O(n^2) in time, O(n) in space (sorting is done in place) Args: arr: list of keys to sort ...
### Build String ### class Solution1: def backspaceCompare(self, S: str, T: str) -> bool: def check(S): S_new = [] for w in S: if w != "#": S_new.append(w) elif len(S_new): S_new.pop() return...
class DiGraph: def __init__(self): self.nodes = dict() self.edges = [] def copy(self): H_ = __class__() H_.add_edges_from(self.edges) return H_ def __eq__(self, other): return len(set(self.edges) ^ set(other.edges)) == 0 def __str__(self): retu...
''' Problem 34 @author: Kevin Ji ''' FACTORIALS = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800] def factorial(number): return FACTORIALS[number] def is_curious_num(number): temp_num = number curious_sum = 0 while temp_num > 0: curious_sum += factorial(temp_num % 10) tem...
n= int(input("Digite o valor de n: ")) sub = n - 1 fat = n while n != 0: while sub != 1: fat = fat * sub sub = sub -1 print(fat)
class Neuron: # TODO: Create abstraction of generic unsupervised neuron pass
""" Melhore o desafio061, perguntando para o usuário se ele quer mostrar mais alguns termos. O programa encerra quando ele disser que quer mostrar 0 termos.""" pr_termo = int(input('Primeiro termo: ')) razao = int(input('Razão: ')) print('PROGRESSÃO ARITMETICA =', end=' ') c = 1 total = 0 mais = 10 while mais != 0: ...
expected_output = { 'switch': { "1": { 'system_temperature_state': 'ok', } } }
def addition(x: int, y: int) -> int: """Adds two integers together and returns the result.""" return x + y if __name__ == '__main__': a, b = 1, 2 result = addition(a, b) print(result)
# 9093 단어 뒤집기 line = int(input()) sentances = [input() for _ in range(line)] print("\n".join([" ".join([s[::-1] for s in sentance.split()]) for sentance in sentances]))