content
stringlengths
7
1.05M
# Addition of numbers def add(num1, num2): return num1 + num2 # subtraction of numbers def subtract(num1, num2): return num1 - num2 # multiplication of numbers def multiply(num1, num2): return num1 * num2 # Division of numbers def divide(num1, num2): return num1 / num2 p...
class Solution: def minMeetingRooms(self, intervals: List[List[int]]) -> int: # first sorting start time and end time # two pointers, one is point to start time list, another point to end time, this means pointer to the first available room starttime = sorted(x[0] for x i...
def simulate(self, gameState, preState, level, R_s, Q_s_a): curAction = gameState.getAgentState(self.index).configuration.direction rev = Directions.REVERSE[curAction] legalActions = gameState.getLegalActions(self.index) legalActions.remove(Directions.STOP) legalActions.remove(rev) #...
''' continuação. Funções (def) em python - return - ''' def dumb(): # aqui foi criado uma função 'dumb' sem parametro() return 1 # retornado o valor '1' var = dumb() # criado uma variável para a função print(var, type(var)) # imprimido a variável e seu valor 'type' # retorno vazio def dumb(): return # ret...
times = ('Internacional', 'Atlético_MG', 'Flamengo', 'São Paulo', 'Fluminense', 'Palmeras', 'Santos', 'Grêmio', 'Sport Recife', 'Corinthians', 'Fortaleza', 'Ceará SC', 'Atlético-GO', 'Bahia', 'Coritiba', 'Bragantino-SP', 'Botafogo', 'Vasco', 'Athetico-PR', 'Goiás') print('Os top5 são...') pri...
#!/usr/bin/env python ''' Структурный шаблон проектирования, объединяющий объекты в древовидную структуру для представления иерархии от части к целому. Компоновщик позволяет клиентам обращаться к отдельным объектам и к группам объектов одинаково. ''' class MenuItem(): def __init__(self, name, action): se...
nome = str(input('digite seu nome completo :')).strip() n = nome.split() print('prazer em te conhecer!! {}'.format(nome.split()[0].capitalize())) print('seu primeiro nome e {}'.format(nome.split()[0].capitalize())) print('seu ultimo nome e {}'.format(n[len(n) - 1].capitalize())) #eu colei so um pouco na ultima
class AirdropWindowRule: def __init__(self, title, rule): self._title = title self._rule = rule def to_dict(self): return { "airdrop_window_eligibility_title": self._title, "airdrop_window_eligibility_rule": self._rule, }
n1 = int(input('Digite um numero 1 :')) n2 = int(input('Digite um numero 2 :')) soma = n1 + n2 print('A soma é {}'.format(soma))
def setup_tpu(): # Detect hardware, return appropriate distribution strategy try: # TPU detection. No parameters necessary if TPU_NAME environment variable is # set: this is always the case on Kaggle. tpu = tf.distribute.cluster_resolver.TPUClusterResolver() print('Running on TPU...
# Classification # This project asks a series of Yes/No questions in order to work out what type of phone the person owns. # Pawel Zabinski class Node: def __init__(self, type, data, yes=None, no=None): # Type may be 'Q' or 'A' ('Q' is for Question, 'A' is for Answer) self.type = type # Data is the que...
class MySingleton(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(MySingleton, cls).__new__(cls) cls.number = 10 return cls._instance x = MySingleton() print(x.number) x.number = 20 y = MySingleton() y.number = 3...
# BUILTINS # # Write a function named "filter_small_lists" that accepts an iterable # containing lists and returns a list of the lists that have more than two # elements in them. # # Use the "filter" method to do this. # # Test data is at the bottom. # WRITE YOUR CODE HERE # TEST DATA print(filter_small_lists([[1], ...
__author__ = 'olga.ostapenko' class SessionHelper: def __init__(self, app): self.app = app def login(self, username, password): wd = self.app.wd self.app.open_home_page() wd.find_element_by_id("public_site_login").click() wd.find_element_by_id("login_login").click() ...
def main(values, key): """ step 1: loop through the list (outer loop) step 2: loop through the list again (inner loop) step 3: check if value in outer loop matches second value in inner loop (don't add number to itself) step 4: if values from different indices add to key, return True step ...
# -*- coding: utf-8 -*- # # Copyright (C) 2020 CERN. # Copyright (C) 2020 Northwestern University. # # Invenio-Drafts-Resources is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see LICENSE file for more # details. """Invenio-Drafts-Resources Configuration.""" DRAFTS_RES...
class Solution: def islandPerimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ M, N = len(grid), len(grid[0]) counts = 0 neighbors = 0 for i in range(M): for j in range(N): if grid[i][j] == 1: ...
# Time: O(size(tree)) # Space: O(size(tree)), for recursion stack # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: return self.uti...
class Node(object): """A node in the suffix tree. suffix_node the index of a node with a matching suffix, representing a suffix link. -1 indicates this node has no suffix link. """ def __init__(self): self.suffix_node = -1 def __repr__(self): return "Node(su...
"""All exceptions for Simple Salesforce""" class SalesforceError(Exception): """Base Salesforce API exception""" message = "Unknown error occurred for {url}. Response content: {content}" def __init__(self, url, status, resource_name, content): """Initialize the SalesforceError exception ...
# Question # 36. Write a program to sort a list of integers using bubble sort. # Code a = input("List of integers sep with commas:\n") ints = [int(i.strip()) for i in a.split(",")] # Bubble sorting while True: swaps = False for x in range(len(ints)-1): if ints[x] > ints[x+1]: a, b = ints[x...
def rreplace(string, old_str_part, new_str_part, occurrence): split_str = string.rsplit(old_str_part, occurrence) return new_str_part.join(split_str) def rremove(string, str_part, occurrence): split_str = string.rsplit(str_part, occurrence) return split_str[0]
# location of local authentication logs to insert to db (update these paths if needed) auth_raw_files = [ '../../dataset/auth_C1DOM1.txt', '../../dataset/auth_C2DOM1.txt', '../../dataset/auth_C3DOM1.txt', '../../dataset/auth_C4DOM1.txt', '../../dataset/auth_C5DOM1.txt', '../../dataset/auth_C6DOM...
pkgname = "libmicrodns" pkgver = "0.2.0" pkgrel = 0 build_style = "meson" hostmakedepends = ["meson", "pkgconf"] pkgdesc = "Minimal mDNS resolver library" maintainer = "q66 <q66@chimera-linux.org>" license = "LGPL-2.1-or-later" url = "https://github.com/videolabs/libmicrodns" source = f"{url}/archive/{pkgver}.tar.gz" s...
''' Faça um programa que leia o peso de cinco pessoas. No final, mostre qual foi o maior e o menor peso lidos. ''' maior = 0 menor = 0 for c in range(0,5): peso = float(input('Digite o Seu Peso: ')) if c == 1: maior = peso menor = peso else: if peso > maior: maior = peso ...
# Ex. 066 cont = soma = 0 while True: num = int(input("Digite um número (999 para parar): ")) if num != 999: cont += 1 soma += num else: break print(f"\nN° digitados: {cont}") print(f"Soma dos n°: {soma}")
class Solution: def countGoodSubstrings(self, s: str) -> int: count = 0 for i in range(len(s)-2): word = s[i:i+3] if(len(set(word))== len(word)): count+=1 return count
def get_files(test_name, MAIN_AMB=""): tests = { "swap_endianness_x2": "add", "add_to_swapped": "swap_endianness", "extract": ["#ALL", "#EXCEPT:"+MAIN_AMB], "extract_swapped": "extract", "add_from_dir": "add", "edge_extracted": ["#ALL", "#EXCEPT:files.amb_extracted*"...
# -*- coding: utf-8 -*- """ Given a string with lowercase letters only, if you are allowed to replace no more than ‘k’ letters with any letter, find the length of the longest substring having the same letters after replacement. Example 1: Input: String="aabccbb", k=2 Output: 5 Explanation: Replace the two 'c' with...
""" Given an array of integers, return True or False if the array has two numbers that add up to a specific target. You may assume that each input would have exactly one solution. Input: [-2, 1, 2, 4, 7, 11], target=13 Output: True (2, 11) """ # Using two pointers (first and last index), assuming array is sorted # Ti...
def calculate_age(year_of_birth, current_year): delta = current_year - year_of_birth if delta == 0: return "You were born this very year!" year_s = "year" if abs(delta) == 1 else "years" if delta > 0: return "You are {} {} old.".format(delta, year_s) else: return "You...
# # PySNMP MIB module ACMEPACKET-TC (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ACMEPACKET-TC # Produced by pysmi-0.3.4 at Mon Apr 29 16:57:55 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
## Adding special methods to the student class # We first added the __str__() special method to get a string # representation of our student object, we also added the __len__() # and __repr__() methods, you can code out the __str__() method # to see the __repr__() method in action # The class looked like below at the ...
egui_keys = [ "ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp", "Escape", "Tab", "Backspace", "Enter", "Space", "Insert", "Delete", "Home", "End", "PageUp", "PageDown", "Num0", "Num1", "Num2", "Num3", "Num4", "Num5", "Num6", ...
class CustomResponse: """ Defines an object to handle a response from a custom or unknown endpoint. This response class is intended to provide support handling newer endpoints that may not yet be included in the production release of the library. Since this object will built on the fly, a...
# V0 class Solution: def tree2str(self, t): if not t: return '' if not t.left and not t.right: return str(t.val) ### NOTICE HERE if not t.left: return str(t.val) + '()' + '(' + self.tree2str(t.right) + ')' ### NOTICE HERE if not t.r...
def oldjsonSite(site): return { 'National ID' : site[0].national_id, 'Site Name' : site[0].site_name, 'Agency ID' : site[0].agency_id, 'latitude' : site[0].latitude, 'longitude' : site[0].longitude, 'Agency Name': site[1].name, 'Offe...
var1 = 15 print("Enter a number") var2 = int(input()) if var2>var1: print("Greater") elif var2==var1: print("Equal") else: print("Lesser") # Quiz print("Enter age") age = int(input()) if age>18: print("You can drive") elif age==18: print("We will think about it") else: print("You cannot dri...
""" 4C """ def inp(): """ For taking integer inputs. """ return(int(input())) def get_n_strings(n): """ For taking List inputs. """ result = [] i = 0 while i < n: val = input().rstrip("\n") result.append(str(val)) i += 1 return result def problem(n...
class Solution: def modifyString(self, s: str) -> str: alphabet = 'abcdefghijklmnopqrstuvwxyz' ret = list('0' + s + '0') for i in range(1, len(ret)-1): if ret[i] == '?': for j in range(26): if alphabet[j] not in {ret[i-1], ret[i+1]}: ret[i] = alphabet[j] bre...
class FightActions: def fight(self, defender): if self.power_level > defender.power_level: defender.hits_point -= self.power_level - defender.power_level elif self.power_level == defender.power_level: print("They are equal in strength!") else: self.hit_poi...
Posts= [{'File': 'images\\0.jpg', 'Title': 'Jose the "bully" #Mourinho #MUFC'}, {'File': 'images\\1.jpg', 'Title': "Former Southampton coach Jason Dodd about Luke Shaw's situation. " '#Shaw #MUFC'}]
#saida s = 0 c = 0 for i in range(3, 501, 6): s += i c += 1 print(f'A soma de todos os {c} valores solicitados é {s}')
input = """ 8 2 2 3 0 0 8 2 4 5 0 0 1 1 1 1 4 6 0 1 0 4 1 0 4 c 3 b 2 a 5 d 0 B+ 0 B- 1 0 1 """ output = """ COST 1@1 """
class Fields: """ Contains the fields that would be validated in the forms when a user is created or updated It also contains if the field can be empty and the functions to be run in order to validate it In case an error occurs, it also contains the error message to be displayed """ field = { ...
# LoRa test channel _def_thingspeak_channel_key='SGSH52UGPVAUYG3S' #Note how we can indicate a device source addr that are allowed to use the script #Use decimal between 2-255 and use 4-byte hex format for LoRaWAN devAddr #leave empty to allow all devices #source_list=["6", "7", "01020304"] source_list=[] key_associa...
"""Possible triggers for reading data from a gyroscopes.""" READ_NOT_TRIGGERED = 0 """The read will not be triggered.""" GET_ANGLE_TRIGGER_READ = 1 """Trigger the device read when requesting the angle.""" GET_ANGULAR_VELOCITY_TRIGGER_READ = 2 """Trigger the device read when requesting angular velocity.""" GET_RAW_...
#Basic Linear Search # Defines function that searches through array def linearsearch(arr, x): # Passes in target as x, and the array for i in range(len(arr)): # Creates an index for length of array if arr[i] == x: # Compares array value to searched value return i # Returns index return -1 arr = [...
class Solution: # @param {integer[]} nums # @return {integer} def singleNumber(self, nums): ans = 0 for each in nums: ans = ans ^ each; return ans
x = [12, 15, 14, 5] sum = 0 for i in x: sum += i print(sum)
# How to open a file an read the file out file_read = open('../data/text_file_handler.txt', 'r') # Now loop through the file for line in file_read: print(line.strip()) # Close the file otherwise the file is blocked file_read.close() # Now write content in a file file_write = open('../data/write_file_handler.txt'...
TC02_PER_TC = 3.67 TC_PER_TBM = 0.5 TC_PER_TBM_IPCC = {'AGB': 0.47, 'BGB': 0.47, 'dead_wood': 0.47, 'litter': 0.37} SQM_PER_HA = 10000 R = 6.371e6 EMISSIONS_FACTORS = { 'savanna_fire': 1.613, 'tropical_forest_fire': 1.580, 'extratropical_forest_fire': 1.569, }
def dec_to_bin(num): #my original method was not as nice as this one if num<2: return str(num) else: return dec_to_bin(num//2) + dec_to_bin(num%2) print(dec_to_bin(100000)) #if n gets really big a while loop may be better something along the lines of this # def dec_to_bin(number): # binary = '...
actors = { '002' : 'USA', '020' : 'CAD', '040' : 'CUB', '041' : 'HAI', '042' : 'DOM', '051' : 'JAA', '052' : 'TRI', '070' : 'MEX', '090' : 'GUA', '091' : 'HON', '092' : 'ELS', '093' : 'NIC', '094' : 'COS', '095' : 'PAA', '100' : 'COL', '101' : 'VEN', '...
""" Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). Example 1: Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1. Example 2: Input: [1, 2] Output: 2 Explanation: The third maximum ...
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations # ---------------------------------------------------------------------------------------------------------------------- # this is the main application menu add/remove items as required # ---------------------------...
""" Given an unsorted integer array, find the first missing positive integer. Example: Given [1,2,0] return 3, [3,4,-1,1] return 2, [-8, -7, -6] returns 1 Your algorithm should run in O(n) time and use constant space. """ class Solution: # @param A : list of integers # @return an integer def firstMis...
ls = [1, 2, 3] i = iter(ls) assert i.__next__() == 1 assert i.__next__() == 2 assert next(i) == 3 assert next(i, 'w00t') == 'w00t' s = '你好' i = iter(s) i.__setstate__(1) assert i.__next__() == '好' assert i.__reduce__()[2] == 2
# by Kami Bigdely # Extract class class Person: """Define fields and methods for a person.""" def __init__(self, first_name, last_name, birth_year, movies, email): self.first_name = first_name self.last_name = last_name self.birth_yr = birth_year self.movies = movies s...
class Solution: def checkPalindromeFormation(self, a: str, b: str) -> bool: """ As long as a prefix == rev(bsuffix) keep forming the split do this (a, b) and (b, a) if any of them are palindromes, then it's true """ i = 0 j = len(a) - 1 while i < j an...
def convert(fileInfo): arrays = [] with open(fileInfo["file"]) as file: linecounter = 0 for line in file: arraywidth = 0 linecounter += 1 arr = [] for bit in line: if (bit != "\n"): arr.append(int(bit)) ...
# -*- coding: utf-8 -*- def int2base(x, b, alphabet='0123456789abcdefghijklmnopqrstuvwxyz'): 'convert an integer to its string representation in a given base' if b < 2 or b > len(alphabet): if b == 64: # assume base64 rather than raise error alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi...
t = int(input()) for _ in range(t): n, a, b = map(int, input().split()) s = input() total = s.count('0') * a + s.count('1') * b print(total)
# http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_instances # This makes sure there are multiple reservations per simulated page, and # multiple instances in each reservation, and multiple pages. boto3_describe_instances_paginator_one_field = [ { 'Reservations': [ ...
""" Login and password generators """ # WeConnectResources with open('res/pass.dic') as f_pass: content = f_pass.read() password_list = content.split('\n') with open('res/usr.dic') as f_usr: content = f_usr.read() login_list = content.split('\n') def generate_popular_passwords(state): """ We ...
def uglify(text): answer = '' even = True for index in range(len(text)): if even: answer += text[index].lower() else: answer += text[index].upper() even = not even return answer if __name__ == '__main__': text = 'Some random text to uglify' prin...
class Solution: def isMatch(self, s: 'str', p: 'str') -> 'bool': ls, lp = len(s), len(p) if p == '*' or ls == 0 and lp == 0: return True elif ls == 0 or lp == 0: return False dp = [[False] * (lp + 1) for _ in range(ls + 1)] dp[0][0] = True for ...
conf_l3_agent_ini = """[DEFAULT] # Show debugging output in log (sets DEBUG log level output) # debug = False verbose = True # L3 requires that an interface driver be set. Choose the one that best # matches your plugin. interface_driver = neutron.agent.linux.interface.BridgeInterfaceDriver external_network_bridge = #...
""" Utlity functions to run Ploomber tests. This is not a public module """ def assert_no_extra_attributes_in_class(abstract_class, concrete_class, allowed=None): """ Ploomber makes heavy use of abstract classes to provide a unifo...
ficha = list() while True: nome = str(input('Nome : ')) nota1 = float(input('Nota 1 :')) nota2 = float(input('nota 2 :')) media = (nota1 + nota2) / 2 ficha.append([nome, [[nota1], [nota2]], media]) loop = str(input('Quer continuar N/S ?')) if loop in 'nN': break print('\033[34m-=' *...
""" Programa 091 Área de estudos. data 01.12.2020 (Indefinida) Hs @Autor: Abraão A. Silva """ # Lista valores = [1, 12, 34, 1, 9] # Iteração por indíce. for valor in range(1, len(valores)+1): print(valores[valor - (2*valor)], end=' ') # Opção 2; Utilizando método valores.reverse() print(valores)
# 相反数 def st201403_1(): n = int(input()) numbers=list(map(int,input().split(' '))) temp=0 for num in numbers: if num*-1 in numbers:temp+=1 print(temp//2) if __name__ == '__main__': st201403_1()
''' @author: Sergio Rojas @contact: rr.sergio@gmail.com -------------------------- Contenido bajo Atribución-NoComercial-CompartirIgual 3.0 Venezuela (CC BY-NC-SA 3.0 VE) http://creativecommons.org/licenses/by-nc-sa/3.0/ve/ Creado en abril 23, 2016 ''' # In [1]: %cpaste archivo = 'cap_06_datos_01_espacios.txt' try:...
# Get inputs a = int(input()) b = int(input()) # Calculate and print result print(a//b) print(a/b)
transprop_perms = \ [ ( 'contact.customer.firstname' , [] ) , ( 'contact.customer.function' , [] ) , ( 'contact.customer.lastname' , [] ) , ( 'contact.customer.lookalike_firstname' , [] ) , ( 'contact.customer.lookalike_function' , [] ) ...
class WIM: def __init__(self, output_dict) -> None: for k, v in output_dict.items(): setattr(self, k.replace(' ', '_'), v) def __repr__(self): return '{' + self.Name + ', ' + self.Architecture + ', ' + self.Languages + '}' def __str__(self) -> str: return self.Name ...
class BaseDataLoader(): def __init__(self): pass def load_data(): return None def initialize(self, opt): self.opt = opt
''' lab 7 while loop ''' #3.1 i = 0 while i <=5: if i !=3: print(i) i = i +1 #3.2 i = 1 result =1 while i <=5: result = result *i i + i +1 print(result) #3.3 i = 1 result =0 while i <=5: result = result +i i + i +1 print(result) #3.4 i = 3 result =1 while i <=8: result = resu...
""" Today we are gonna learn about tuples and what are the things that we can do about it. A tuple is a ordered sequence of elements, can contain anything elements. AKA. ARRAY? Immutable. You can also go into the tuple by t = (2, 3, 4) t + (6, 8) t[1:2] You can reverse tuple swap variables. (x, y) = (y, x) ""...
#flake8:noqa #PYX START """ // These are cython style comments for maintaining python compatibility cimport numpy as np ctypedef np.float64_t FLOAT64 """ #PYX MAP FLOAT_2D np.ndarray[FLOAT64, ndim=2] #PYX MAP FLOAT_1D np.ndarray[FLOAT64, ndim=1] #PYX END #--- # -------------------------------- # TODO: This is one of t...
"""python: 直接删除了列表元素 c++: 使用了approach 2的方法""" class Solution: def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ i = 0 while (i < len(nums)): if nums[i] == val: nums.pop(i) els...
POST = "POST" ROOT = "root" SPEC_VERSION = "specVersion" XML_VERSION = "<?xml version=\"1.0\"?>" XML_VERSION_PREFIX = "<?xml version=\"1.0\"" FAULT = "{http://schemas.xmlsoap.org/soap/envelope/}Fault" ENVELOPE = "{http://schemas.xmlsoap.org/soap/envelope/}Envelope" BODY = "{http://schemas.xmlsoap.org/soap/envelope/}Bod...
""" Module: 'machine' on M5 FlowUI v1.4.0-beta """ # MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module with ESP32') # Stubber: 1.3.1 class ADC: '' ATTN_0DB = 0 ATTN_11DB = 3 ATTN_2_5DB = 1 ATTN_6DB = 2 HALL = 8 WID...
print('\033[36;40mExercício Python #080 - Lista ordenada sem repetições\033[m') numeros = list() for i in range(0, 5): num = int(input('DIGITE UM VALOR: ')) if i == 0 or num > numeros[-1]: numeros.append(num) print(f'{num} foi adicionado a última posição!\n') else: pos = 0 ...
class DefaultConfigs(object): input_size = 224 lr = 0.01 batch_size = 64 workers = 8 iter_step = 5 gamma = 0.3 train_ratio = 0.2 model = "resnet50" dataset = "sd-198" class_num = 198 epochs = 50 step_size = 40 add_ratios = [0.5, 0.75, 0.9, 1.0, 1.0] config = Default...
#!/usr/bin/env python # encoding: utf-8 row_data = [ { 'sub_categorys': [ { 'sub_categorys': [ { 'code': 'yr', 'name': '羊肉' }, { 'code...
def read_article(file_name): file = open(file_name, "r") file_data = file.readlines() article = file_data[0].split(". ") sentences = [] for sentence in article: print(sentence) sentences.append(sentence.replace("[^a-zA-Z]", " ").split(" ")) sentences.pop() return sentences
#!/usr/bin/env python3 def merge_dicts(base, update, values=False): merged = dict(base, **update) return list(merged.values()) if values else merged
inicio = 97 for i in range(inicio, inicio + 26): print(str(i) + ' e ' + str(chr(i)))
expected_output = { "binding_table_configuration": { "max/box": "no limit", "max/port": "no limit", "max/vlan": "no limit", "max/mac": "no limit", }, "binding_table_count": { "dynamic": 0, "local": 0, "total": 2, }, "binding_table_state_count":...
# Define a split_in_two function that accepts a list and a number. # If the number is even, return the list elements from the third element to the end of the list. # If the number is odd, return the list elements from index 0 (inclusive) to 2 (exclusive) # # EXAMPLE: # values = ["a", "b", "c", "d", "e", "f"] # split_in...
"""Key-Value store server. The request takes "key=" and "value=" URL parameters. The key must be UUID generated by token(). - When only the "key=" is specified, serves a 200 response whose body contains the stored value specified by the key. If the stored value doesn't exist, serves a 200 response with an empty b...
# Problem Name: # Problem Description: #################################### # Sample Input: # Sample Output: #################################### """ Explain the solution: ################## Detailed explanation of the Solution: """ #################################### def solution(self): pass print(solution...
''' Binary Tree Preorder Traversal https://leetcode.com/explore/learn/card/data-structure-tree/134/traverse-a-tree/928/ https://leetcode.com/explore/learn/card/data-structure-tree/134/traverse-a-tree/929/ https://leetcode.com/explore/learn/card/data-structure-tree/134/traverse-a-tree/930/ Input: [1,null,2,3] 1 ...
{ 'targets': [ { 'target_name': 'build_all', 'type': 'none', 'dependencies': [ 'cppsrc/ImageRankerWrapper/binding.gyp:*', ] } ] }
""" 40 - Elabore um programa que faça leitura de vários números inteiros, até que se digite um número negativo. O programa tem que retornar o maior e o menor número lido. """ lista = [] numero = int(input(f'Digite o número: ')) while numero >= 0: lista.append(numero) numero = int(input(f'Digite o número: ')) p...
class Solution: def uniquePaths(self, A: int, B: int) -> int: if A==1 or B==1: return 1 if A==2 or B==2: return max(A,B) ans = 1 for i in range(max(A,B), A+B-1): ans *= i ans //= (i-max(A,B)+1) return ans # LC 62 Medium
# # [328] Odd Even Linked List # # https://leetcode.com/problems/odd-even-linked-list/description/ # # algorithms # Medium (45.01%) # Total Accepted: 96.2K # Total Submissions: 213.8K # Testcase Example: '[1,2,3,4,5]' # # Given a singly linked list, group all odd nodes together followed by the even # nodes. Please ...
# Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. # The same number may be chosen from candidates an unlimited number of times. Two combinations are u...
s=[] def sum_digits(f): s=0 c=str(f) for i in c: s+=int(i) return s for i in range(100): for j in range(100): s.append(sum_digits(i**j)) x=max(s) print("Max is ",x)