content
stringlengths
7
1.05M
def selection_sort(array): """Program for selection sort Inplace sorting Space Complexity O(1) only constant number of variables is used Time complexity O(n^2) >>> arr = [1, 5, 0, -3, 5, 7, 2, 0, 9, 1] >>> print(arr) [1, 5, 0, -3, 5, 7, 2, 0, 9, 1] >>> selection_sort(arr) >>> print...
#NOTE: LIST - Secuence of mutable values names = ["Harry", "Hik", "Linkin", "Park"] #ADDS ANOTHER ITEM IN THE LIST names.append("Paramore") #SORT THE LIST IN APLHABETIC ORDER names.sort() #PRINTS THE LIST print(names)
subor = open("17_1input.txt", "r") r = [x.strip() for x in subor.readlines()] n=6 roz=(n+1)*2+len(r[0]) pole=[[["." for a in range(roz)] for a in range(roz)]for a in range((n+1)*2+1)] #vypisanie pola def vypis(x): for a in x: for b in a: for c in b: print(c,end=" ") ...
__author__ = "Ian Goodfellow" class Agent(object): pass
def pytest_report_header(): return """ ------------------------ EXECUTING WEB UI TESTS ------------------------ """
c = 41 # THE VARIABLE C equals 41 c == 40 # c eqauls 40 which is false becasue of the variable above c != 40 and c <41 #c does not equal 40 is a true statement but the other statement is false, making it a false statement c != 40 or c <41 #True statement in an or statement not c == 40 #this is a true statement not c > ...
dna = 'ACGTN' rna = 'ACGUN' # dictionary nucleotide acronym to full name nuc2name = { 'A': 'Adenosine', 'C': 'Cysteine', 'T': 'Thymine', 'G': 'Guanine', 'U': 'Uracil', 'N': 'Unknown' }
print("Checking Imports") import_list = ['signal', 'psutil', 'time', 'pypresence', 'random'] modules = {} for package in import_list: try: modules[package] = __import__(package) except ImportError: print(f"Package: {package} is missing please install") print("Loading CONFIG\n") # # # # # # # # ...
# A linked list node class Node: def __init__(self, value=None, next=None): self.value = value self.next = next # Helper function to print given linked list def printList(head): ptr = head while ptr: print(ptr.value, end=" -> ") ptr = ptr.next print("None") # Function to remove duplicates from a sorted...
#!/usr/bin/env python3 # https://www.urionlinejudge.com.br/judge/en/problems/view/1014 def main(): X = int(input()) Y = float(input()) CONSUMPTION = X / Y print(format(CONSUMPTION, '.3f'), "km/l") # Start the execution if it's the main script if __name__ == "__main__": main()
''' Data Columns - Exercise 1 The file reads the file with neuron lengths (neuron_data.txt) and saves an identical copy of the file. ''' Infile = open('neuron_data.txt') Outfile = open('neuron_data-copy.txt', 'w') for line in Infile: Outfile.write(line) Outfile.close()
"""In this bite you will work with a list of names. First you will write a function to take out duplicates and title case them. Then you will sort the list in alphabetical descending order by surname and lastly determine what the shortest first name is. For this exercise you can assume there is always one name and on...
# coding: utf-8 """***************************************************************************** * Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your...
# 000404_02_04_step16_code04_formOutput.py # Напишите программу, которая выводит частное целых переменных a/b и b/а # с разделителем "***" в формате 9 знаковых позиций и 5 знаков после запятой a=int(input()) b=int(input()) print('{:9.5f}'.format(a/b),'{:9.5f}'.format(b/a), sep=' ***') # print('{:9.5f}'.format(b/a))
class Video: def __init__(self, files): self.files = files def setFiles(self, files): self.files = files def getFiles(self): return self.files
class JsonUtil: @staticmethod def list_obj_dict(list): new_list = [] for obj in list: new_list.append(obj.__dict__) return new_list
# pylint: disable=inconsistent-return-statements def sanitize(value, output_type): """ Handy wrapper function for individual sanitize functions. :param value: Input value to be sanitized :param output_type: Class of required output :type output_type: bool or int """ # pylint: disable=no-e...
class Solution(object): def findClosestElements(self, arr, k, x): """ :type arr: List[int] :type k: int :type x: int :rtype: List[int] """ start = 0 end = len(arr) - 1 while start < end: mid = (start + end) // 2 if arr[m...
# 1 x = float(input("First number: ")) y = float(input("Second number: ")) if x > y: print(f"{x} is greater than {y}") elif x < y: print(f"{x} is less than {y}") else: print(f"{x} is equal to {y}") # bb quiz = float(input("quiz: ")) mid_term = float(input("midterm: ")) final = float(input("final: ")) avg ...
palavra = str(input('Digite uma frase: ')).strip().upper() frase = palavra.split() junto = ''.join(frase) inverso = '' for letra in range(len(junto) - 1, -1, -1): inverso += junto[letra] if inverso == palavra: print('é um palindroma') else: print('não é um palindroma')
''' um contador indo pela contagem regressiva e outro tendo incremento a cada passagem pelo loop ''' contrario = 10 for var in range(0, 9): print(var, contrario) contrario -= 1 print('\nresolução do professor') for i, r in enumerate(range(10, 1, -1)): print(i, r)
x = {} print(type(x)) file_counts = {"jpg":10, "txt":14, "csv":2, "py":23} print(file_counts) print(file_counts["txt"]) print("html" in file_counts) #true if found #dictionaries are mutable file_counts["cfg"] = 8 #add item print(file_counts) file_counts["csv"] = 17 #replaces value for already assigned csv print...
# Tweepy # Copyright 2010-2021 Joshua Roesslein # See LICENSE for details. def list_to_csv(item_list): if item_list: return ','.join(map(str, item_list))
#Leia uma data de nascimento de uma pessoa fornecida #através de três números inteiros: #Dia, Mês e Ano. Teste a validade desta data para saber se #esta é uma data válida. Teste se o dia fornecido é um dia #válido: dia > O, dia < 28 para o mês de fevereiro (29 se o #ano for bissexto), dia < 30 em abril, junho, setembr...
''' Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity ''' class Solution: def searchRange(self, nums: List[int], target...
def knapsack(limit, values, weights): """Returns the maximum value that can be reached using given weights""" n = len(weights) dp = [0]*(limit+1) for i in range(n): for j in range(limit, weights[i]-1, -1): dp[j] = max(dp[j], values[i] + dp[j - weights[i]]) return dp[-1]
_base_ = [ '../_base_/models/resnet50.py', '../_base_/datasets/imagenet_bs32.py', '../_base_/schedules/imagenet_bs256.py', '../_base_/default_runtime.py' ] load_from = "https://download.openmmlab.com/mmclassification/v0/resnet/resnet50_8xb32_in1k_20210831-ea4938fc.pth"
x = int(input("Please enter a number: ")) if x % 2 == 0 : print(x, "is even") else : print(x, "is odd")
class Memoization: allow_attr_memoization = False def _set_attr(obj, attr_name, value_func): setattr(obj, attr_name, value_func()) return getattr(obj, attr_name) def _memoize_attr(obj, attr_name, value_func): if not Memoization.allow_attr_memoization: return value_func() try: return getattr(obj, a...
class BotConfiguration(object): def __init__(self, auth_token, name, avatar): self._auth_token = auth_token self._name = name self._avatar = avatar @property def name(self): return self._name @property def avatar(self): return self._avatar @property def auth_token(self): return self._auth_token
gatitos = {'Padrão': [' ', ' ,_ _ ', ' |\\\\_,-// ', ' / _ _ | ,--.', '( @ @ ) / ,-\'', ' \ _T_/-._( ( ', ' / `. \\ ', ...
#author SANKALP SAXENA # Complete the has_cycle function below. # # For your reference: # # SinglyLinkedListNode: # int data # SinglyLinkedListNode next # # def has_cycle(head): s = set() temp = head while True: if temp.next == None: return False if temp.next not i...
''' URL: https://leetcode.com/problems/hamming-distance/ Difficulty: Easy Description: Hamming Distance The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. Note: 0 ≤ x, y < 231. Example: In...
{ 'targets': [ { 'target_name': 'test_new_target', 'defines': [ 'V8_DEPRECATION_WARNINGS=1' ], 'sources': [ '../entry_point.c', 'test_new_target.c' ] } ] }
# -*-coding:utf-8 -*- #Reference:********************************************** # @Time    : 2019-10-11 00:00 # @Author  : Fabrice LI # @File    : 578_lowest_common_ancestor_III.py # @User    : liyihao # @Software : PyCharm # @Description: Given the root and two nodes in a Binary Tree. Find the lowest common ancest...
x = 10 print(x) """ tests here """
usa = ['atlanta','new york','chicago','baltimore'] uk = ['london','bristol','cambridge'] india = ['mumbai','delhi','banglore'] ''' #(a) i=input("Enter city name: ") if i in usa: print('city is in USA') elif i in uk: print('city is in UK') elif i in india: print('city is in INDIA') else: print('idk the ...
h = float(input('Altura [m]: ')) w = float(input('Largura [m]: ')) a = w * h print('Área: {:.2f}m²'.format(a)) print('Tinta: {}L'.format(a/2))
#Base Class, Uses a descriptor to set a value class Descriptor: def __init__(self, name=None, **opts): self.name = name for key, value in opts.items(): setattr( self, key, value) def __set__(self, instance, value): instance.__dict__[self.name] = value #Descriptor for enforci...
{ "targets": [ { "target_name": "napi_test", "sources": [ "napi.test.c" ] }, { "target_name": "napi_arguments", "sources": [ "napi_arguments.c" ] }, { "target_name": "napi_async", "sources": [ "napi_async.cc" ] }, { "target_name": "napi_construct",...
__title__ = 'Django Platform Data Service' __version__ = '0.0.4' __author__ = 'Komol Nath Roy' __license__ = 'MIT' __copyright__ = 'Copyright 2020 Komol Nath Roy' VERSION = __version__ default_app_config = 'django_pds.apps.DjangoPdsConfig'
#!C:\Python27 # For 500,000 mutables, this takes WAY to long. Look for better options orgFile = open('InputList.txt', 'r') newFile = open('SortedList.txt', 'w') unsortedList = [line.strip() for line in orgFile] def bubble_sort(list): for i in reversed(range(len(list))): finished = True ...
students = [] def displayMenu(): print("What would you like to do?") print("\t(a) Add new student: ") print("\t(v) View students: ") print("\t(q) Quit: ") choice = input("Type one letter (a/v/q): ").strip() return choice #test the function def doAdd(): currentstudent = {} currentstude...
def collect(items, item): if item in collecting_items: return collecting_items.append(item) return def drop(items, item): if item in collecting_items: collecting_items.remove(item) return return def combine_items(old, new): if old in collecting_items: for el i...
# Make this unique, and don't share it with anybody. SECRET_KEY = '' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '', # Or path to database file if using sqlite3. 'USER': '...
#* Asked by Facebook #? Given a list of sorted numbers, build a list of strings displaying numbers, #? Where each string is first and last number of linearly increasing numbers. #! Example: #? Input: [0,1,2,2,5,7,8,9,9,10,11,15] #? Output: ['0 -> 2','5 -> 5','7 -> 11','15 -> 15'] #! Note that numbers will not be l...
# Copyright (c) 2018-2019 Arizona Board of Regents # # 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 ...
#!/usr/bin/env python3 """ Advent of Code 2018 Puzzle #2 - 2018-12-02: Find two strings with hamming distance of one # https://adventofcode.com/2018/day/2 Input (via stdin): A series of strings. e.g.: abcdef hijklm uvwxyz azcdef Output: One of two strings that differ by exactly one character, with the matching char...
""" Navigation provides the basic functionality of a page navigation to navigate between sites """ class Navigation: TEMPLATE = 'nav.j2' def __init__(self, env, pages): self._env = env self._pages = pages def render(self, name, current_page, tpl_file=None): if tpl_file i...
expected_output = { "session_type": { "AnyConnect": { "username": { "lee": { "index": { 1: { "assigned_ip": "192.168.246.1", "bytes": {"rx": 4942, "tx": 11079}, ...
num = int(input('Digite um número: ')) n = num % 2 if n == 0: print('O número {} é par.'.format(num)) else: print('O número {} é ímpar.'.format(num))
""" @name: Modules/House/Lighting/Lights/__init__.py @author: D. Brian Kimmel @contact: D.BrianKimmel@gmail.com @copyright: (c) 2020-2020 by D. Brian Kimmel @license: MIT License @note: Created on Feb 5, 2020 """ __updated__ = '2020-02-09' __version_info__ = (20, 2, 9) __version__ = '.'.join(map(str...
""" Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water. Not...
""" A pytest plugin for testing Tornado apps using plain (undecorated) coroutine tests. """ __version_info__ = (0, 6, 0, 'post2') __version__ = '.'.join(map(str, __version_info__))
eventsA = [ { "end_time": "2020-05-20T17:30:00+0200", "start_time": "2020-05-20T17:00:00+0200", "location": "Peaky Blinders - Barber Shop, Antoniego Józefa Madalińskiego 5, Kraków, małopolskie, PL, 33-332", }, { "end_time": "2020-05-20T16:30:00+0200", "start_time": "2...
##!FAIL: HeterogenousElementError[str]@23:20 def renverse(L): """ list[alpha] -> list[alpha] renverse la liste (l'itérable) L. """ # LR : list[alpha] (liste résultat) LR = [] # i : int (position) i = len(L) - 1 while i >= 0: LR.append(L[i]) i = i - 1 return LR ...
class XtbOutputParser: """Class for parsing xtb output""" def __init__(self, output): self.output = output self.lines = output.split('\n') def parse(self): # output variable xtb_output_data = {} # go through lines to find targets for i in...
# Author: Jochen Gast <jochen.gast@visinf.tu-darmstadt.de> class MovingAverage: postfix = "avg" def __init__(self): self.sum = 0.0 self.count = 0 def add_value(self, sigma, addcount=1): self.sum += sigma self.count += addcount def add_average(self, avg, addcount): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2020/2/25 15:45 # @Author : Vodka0629 # @Email : 563511@qq.com, ZhangXiangming@gmail.com # @FileName: mj_value.py # @Software: Mahjong II # @Blog : class MjValue(object): __slots__ = ("meld", "orphan", "is_ready", "listening", "mahj...
""" link: https://leetcode-cn.com/problems/minimum-unique-word-abbreviation problem: 给定长为 m 的 target 字符串,与长为 n 的字符串数组,求 target 的最短缩写,且该缩写不为数组中任一子串的缩写。log2(n) + m ≤ 20。 solution: 搜索。搜索上限为 n * 2^m == 2^(log_2(n)) * 2^m == 2^(log_2(n) + m) <= 2^20。 枚举 target 的每个缩写(遍历 [0, 1 << m),用 0 代表该位压缩,1代表不压缩)并检查是否是有其他字符串...
ejem = "esto es un ejemplo" print (ejem) print (ejem[8:18], ejem[5:7], ejem[0:4]) subejem = ejem[8:18] + ejem[4:8] + ejem[0:4] print (subejem) #ejem = ejem.split(" ") #print (ejem[2:4], ejem[1::-1])
"""Constants for the Almond integration.""" DOMAIN = "almond" TYPE_OAUTH2 = "oauth2" TYPE_LOCAL = "local"
# 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, ...
"""Top-level package for Proto Wind.""" __author__ = """Kais Sghari""" __email__ = 'kais.sghari@gmail.com' __version__ = '0.1.0'
""" pytokio implements its command-line tools within this package. Each such CLI tool either implements some useful analysis on top of pytokio connectors, tools, or analysis or maps some of the internal python APIs to command-line arguments. Most of these tools implement a ``--help`` option to explain the command-lin...
max_char = 105 sample_rate = 22050 n_fft = 1024 hop_length = 256 win_length = 1024 preemphasis = 0.97 ref_db = 20 max_db = 100 mel_dim = 80 max_length = 780 reduction = 4 embedding_dim = 128 symbol_length = 70 d = 256 c = 512 f = n_fft // 2 + 1 batch_size = 16 checkpoint_step = 500 max_T = 160 learning_rate = 0.0002 be...
"""Testes para as rotas de auth""" def test_authentication(fake_user, client_auth_with_one): """Testando a rota authentication""" url = "/api/auth/" data = {"email": fake_user.email, "password": fake_user.password} response = client_auth_with_one.post(url=url, json=data) assert response.status_...
#Crie um programa que leia a veloiade do carro #Se ele assar de 80km/h mostre umamensagem dizendo que ele levou uma multa #A multa va custar R$7,00 por ca da km acima do permitido '''from random import randint#eu fiz como se um radar ou o propio corro lesse a velcidade sozinho vc = randint(0,250) print('Seu carro esta ...
''' Problem Description The program takes two dictionaries and concatenates them into one dictionary. Problem Solution 1. Declare and initialize two dictionaries with some key-value pairs 2. Use the update() function to add the key-value pair from the second dictionary to the first dictionary. 3. Print ...
LOC_RECENT = u'/AppData/Roaming/Microsoft/Windows/Recent/' LOC_REG = u'/Windows/System32/config/' LOC_WINEVT = LOC_REG LOC_WINEVTX = u'/Windows/System32/winevt/logs/' LOC_AMCACHE = u'/Windows/AppCompat/Programs/' SYSTEM_FILE = [ # [artifact, src_path, dest_dir] # registry hives ['regb', LOC_REG + u'RegBack/SA...
"""The code template to supply to the front end. This is what the user will be asked to complete and submit for grading. Do not include any imports. This is not a REPL environment so include explicit 'print' statements for any outputs you want to be displayed back to the user. Use triple single q...
"""escreva um programa que pergunte o salário de funcionário e calcule o valor do aumento para salários superiores a R$ 1250,00, 10% de aumento para salários menores ou iguais a R$ 1250,00, aumento de 15%""" s = float(input('Informe o salário: ')) if s > 1250: s = s * (10/100+1) else: s = s * (15/100+1) print...
# trabajando con sobre carga de operadores para una clase class Persona: def __init__(self, nombre, edad): self.nombre = nombre self.edad = edad def __str__(self): return "{} tiene {} años".format(self.nombre, self.edad) def __add__(self, other): return "Al unir los nombre...
#coding=utf-8 #熟食店P113 2017.4.17 sandwichOrders = ['fruitSandwich','baconicSandwich','beefSandwich','pastrmiSandwich'] finishedSandwiches = [] print("Now we have") print(sandwichOrders) print("\nOpps!The pastramiSandwich is sold out!") for sandwichOrder in sandwichOrders: if sandwichOrder == 'pastrmiSandwich': sandw...
class Config(): appId = None apiKey = None domain = None def __init__(self, appId, apiKey, domain): self.appId = appId self.apiKey = apiKey self.domain = domain
""" A utility for summing up two numbers. """ def add_two_numbers(first, second): """Adds up both numbers and return the sum. Input values must be numbers.""" if not isinstance(first, (int, float)) or not (isinstance(second, (int, float))): raise ValueError("Inputs must be numbers.") return fi...
for i in range(int(input())): array_length = int(input()) array = map(int, input().split()) s = sum(array) if s < array_length: print(1) else: print(s - array_length)
def _get_value(obj, key): list_end = key.find("]") is_list = list_end > 0 if is_list: list_index = int(key[list_end - 1]) return obj[list_index] return obj[key] def find(obj, path): try: # Base case if len(path) == 0: return obj key = str(path[0]...
GRAPH = { "A":["B","D","E"], "B":["A","C","D"], "C":["B","G"], "D":["A","B","E","F"], "E":["A","D"], "F":["D"], "G":["C"] } visited_list = [] # an empty list of visited nodes def dfs(graph, current_vertex, visited): visited.append(current_vertex) for vertex in graph[current_vertex]...
class Solution: def minCostClimbingStairs(self, cost): dp = [0] * (len(cost) + 1) for i in range(2, len(dp)): dp[i] = min(dp[i - 2] + cost[i - 2], dp[i - 1] + cost[i - 1]) return dp[-1] s = Solution() print(s.minCostClimbingStairs([10, 15, 20])) print(s.minCostClimbingStairs([1...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # Version Number # ------------------------------------------------------------------------------ major_version = "1" minor_version = "2" patch_version = "0" # -------------------------------...
''' @Author : Jin Yuhan @Date : 2020-05-02 22:01:34 @LastEditors : Jin Yuhan @LastEditTime : 2020-05-02 23:12:38 @Description : 字幕 ''' class Captions: """ 用于保存字幕 """ def __init__(self, *captions): self.captions = captions self.index = -1 def get(self, count=1, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org) # See "Python, Petit guide à l'usage du développeur agile", Tarek Ziadé, Ed. Dunod (2007) class Observable(object): """The subject.""" def __init__(self): raise NotImplementedError def regis...
def save_transcriptions(path, transcriptions): with open(path, 'w') as f: for key in transcriptions: f.write('{} {}\n'.format(key, transcriptions[key])) def load_transcriptions(path): transcriptions = {} with open(path, "r") as f: for line_no, line in enumerate(f): ...
class Halo_Status_Class(): def __init__(self): # Halos information exist? self.HalosDataExist = False # AGNs information exist? self.AGNsDataExist = False # Solved for Lx, T, flux? self.LxTxSolved = False # Trasformed into XCat prefered coordinate? self.XCatPr...
def load(info): info['config']['/jquery'] = { 'tools.staticdir.on': 'True', 'tools.staticdir.dir': 'clients/jquery' }
class Foo(object): def __init__(self): with open('b.py'): self.scope = "a" pass def get_scope(self): return self.scope
def shell(arr): gap = len(arr) // 2 while gap >= 1: for i in xrange(len(arr)): if i + gap > len(arr) - 1: break insertion_sort_gap(arr, i, gap) gap //= 2 def insertion_sort_gap(arr, start, gap): pos = start + gap while pos - gap >= 0 and arr[pos]...
# This program says hello and asks for my name and show my age. print('Hello, World!') print('What is your name?') #ask for name myName = input() print('It is good to meet you ' + myName) print('The length of your name is :') print(len(myName)) print('Please tell your age:') # ask for age myAge = input() print('Yo...
# -*- coding: utf-8 -*- """ _app_name_.manage.stores ~~~~~~~~~~~~~~~~~~~~~~ store management commands """
class Message: snkrs_pass_message = "<!channel> 【SNKRS PASS Flying Get!!!】" + "\n" snkrs_pass_message += "SNKRS PASSが発行されました!急げ!!:snkrspass:" + "\n" snkrs_pass_message += "{}" + "\n" @classmethod def make_message(cls, url): return cls.snkrs_pass_message.format(url)
load("//:third_party/org_sonatype_sisu.bzl", org_sonatype_sisu_deps = "dependencies") load("//:third_party/org_eclipse_sisu.bzl", org_eclipse_sisu_deps = "dependencies") load("//:third_party/org_eclipse_aether.bzl", org_eclipse_aether_deps = "dependencies") load("//:third_party/org_checkerframework.bzl", org_checkerfra...
#-*-coding:utf-8-*- class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ if n == 0: return 1 if n < 0: n = -n x = 1.0 / x return self.myPow(x * x, n/2) if n % 2 == 0 else ...
""" 1. Clarification 2. Possible solutions - Binary Search 3. Coding 4. Tests """ # T=O(nlg(sigma(w))), S=O(1) class Solution: def shipWithinDays(self, weights: List[int], D: int) -> int: if not weights or D < 1: return 0 left, right = max(weights), sum(weights) while left < right: ...
def getFuel(mass): return int(mass/3)-2 def getTotalFuel_1(values): total = 0 for v in values: total += getFuel(v) return total def getTotalFuel_2(values): total = 0 for v in values: while(True): v = getFuel(v) if v < 0: break ...
# -*- coding: utf-8 -*- { 'name': "Merced Report", 'summary': """Informe de Presupuesto""", 'description': """ Este informe imprime el nombre del usuario logueado, el cual crea el informe del presupuesto """, 'author': "Soluciones4G", 'website': "http://www.soluciones4g.com", ...
# parsetab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'leftIGUALDADDESIGUALDADleftMAYORMENORMAYORIGUALMENORIGUALleftSUMARESTAleftMULTIPLICACIONDIVISIONleftPAR_ABREPAR_CIERRALLAVE_ABRELLAVE_CIERRACADENA DECIMAL DESIGUALDAD D...
def calculate(expr: str) -> int: """Evaluate 'expr', which contains only non-negative integers, {+,-,*,/} operators and empty spaces.""" plusOrMinus = {'+': lambda x, y: x + y , '-': lambda x, y: x - y} mulOrDiv = {'*': lambda x, y: x * y , '/': lambda x, y: x // y} ...
# Python support inheritance from multiple classes. This part will show you: # how multiple inheritance works # how to use super() to call methods inherited from multiple parents # what complexities derive from multiple inheritance # how to write a mixin, which is a common use of multiple inheritance class RightPyram...
# -*- coding: utf-8 -*- E = int(input()) N = int(input()) P = float(input()) SALARY = N * P print("NUMBER = %d" % (E)) print("SALARY = U$ %.2f" % (SALARY))