content
stringlengths
7
1.05M
print('Digite [1] para doar R$ 10,00') print('Digite [2] para doar R$ 20,00') print('Digite [3] para doar R$ 30,00') op = input('Digite uma opção: ') if op == '1': print('Você doou R$ 10,00!') else: if op == '2': print('Você doou R$ 20,00!') else: if op == '3': pri...
# Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. # Example 1: # Input: # [ # [1,1,1], # [1,0,1], # [1,1,1] # ] # Output: # [ # [1,0,1], # [0,0,0], # [1,0,1] # ] class Solution: def setZeroes(self, matrix): """ :type matrix: List[List[in...
class Function(object): """Data-class to hold meta information about a registered back-end function. """ def __init__(self, rule, f): self.rule = rule self.f = f
# 작성일 : 21-06-14 # 주제 : 문자열 # 난이도 : 하 # 문제 : 대소문자 상관없이 입력값에서 제일 많이 사용된 알파벳을 반환하셈 # 백준 코드번호 : 1157 # 배운점 # # # 알파벳을 우선 소문자로 통일시킨다. # input_text = input().upper() # # # 알파벳 사용 빈도수를 저장할 수 있는 배열을 만든다. # occurrence_list = [0] * 26 # start_index = ord('A') # # # 문자가 사용된 횟수을 배열에 저장한다. # for char in input_text: # index =...
def cell2pdf(argument): print() print("Привет, меня зовут cell2pdf и я не реализована") print() def cell2pdf_print(ProcData): print() print("Привет, меня зовут cell2pdf") print("Мне передали аргументы:") for i in ProcData: print(i) print()
class Location(object): """docstring for Location""" def __init__(self, lat=0, lon=0): self._lat = lat self._lon = lon def __str__(self): return "Location(%s,%s)" % (self._lat, self._lon) def __unicode__(self): return u"Location(%s,%s)" % (self._lat, self._lon) @property def lat(self): return self._l...
A_COMMA = "," A_QUOTE = "'" DOUBLE_QUOTES = '"' A_TAB = " " AN_ESCAPED_TAB = "\t" NEWLINE = """ """ AN_ESCAPED_NEWLINE = "\n"
load("//ruby/private:constants.bzl", "RULES_RUBY_WORKSPACE_NAME") load("//ruby/private:providers.bzl", "RubyRuntimeContext") DEFAULT_BUNDLER_VERSION = "2.1.2" BUNDLE_BIN_PATH = "bin" BUNDLE_PATH = "lib" BUNDLE_BINARY = "bundler/exe/bundler" SCRIPT_INSTALL_GEM = "download_gem.rb" SCRIPT_BUILD_FILE_GENERATOR = "create_...
""" [4/14/2014] Challenge #158 [Easy] The Torn Number https://www.reddit.com/r/dailyprogrammer/comments/230m05/4142014_challenge_158_easy_the_torn_number/ #Description: I had the other day in my possession a label bearing the number 3 0 2 5 in large figures. This got accidentally torn in half, so that 3 0 was on one ...
def zebra_2(x,y): pattern=["/","/","/","-","-","-"] z=0 while z<y: for i in range(0,x): print(pattern[i % len(pattern)], end='') z+=1 print("\n") x=int(input("give me a number of charcters in the row:" )) y=int(input("give me a number of rows:" )) zebra_2(x,y)
weather_appid = "12345678" weather_appsecret = "abcdefg" baidu_map_ak = "dfjkal;fjalskf;as"
#Escreva um programa que leia a velocidade de um carro. # Se ele ultapassar 80Km/h, mostre uma mensagem dizendo que ele foi multado. # A multa deve custar R$7.00 por cada Km acima do limite. velocidade = float(input('Qual a velocidade do carro? Km: ')) multa = (velocidade - 80) * 7 if velocidade > 80: print(f'Você fo...
class FailedRunException(Exception): """ raised when an a run has not succeeded """ class BackendNotAvailableException(Exception): """ raise when a Backend is ill-configured """
first, second, year = map(int, input().split()) if first == second: print(1) elif first < 13 and second < 13: print(0) else: print(1)
# Converts the rows of data, with the specified # headers, into an easily human readable csv string. def readable_csv(rows, headers, digits=None): if digits is not None: for i, row in enumerate(rows): for j, col in enumerate(row): if isinstance(col, float): rows[i][j] = round(col, digits) # First, stri...
# Short help def display_summary(): print("{:<13}{}".format( 'mount', "Creates a semi-tracked/local copy of a SCM Repository" )) # DOCOPT command line definition USAGE = """ Creates a semi-tracked/local copy of the specified repository/branch/reference ==============================================================...
# Marcelo Campos de Medeiros # ADS UNIFIP 2020.1 # Patos-PB 21/04/2020 ''' Leia 3 valores de ponto flutuante e efetue o cálculo das raízes da equação de Bhaskara. Se não for possível calcular as raízes, mostre a mensagem correspondente “Impossivel calcular”, caso haja uma divisão por 0 ou raiz de numero negativo. E...
class PLSR_SSS_Helper(object): def __init__(self,train_data,X,mse,msemin,component,y,y_c,y_cv,attribute,importance, prediction,dir_path,reportpath,prediction_map,modelsavepath,img_path,tran_path): self.train_data = train_data self.X = X self.mse = mse self.msemin = ...
# -*- coding: utf-8 -*- """ Created on Tue Nov 20 07:12:02 2018 @author: vishn """
# Symmetric Difference # Problem Link: https://www.hackerrank.com/challenges/symmetric-difference/problem m = int(input()) marr = set(map(int, input().split())) n = int(input()) narr = set(map(int, input().split())) for x in sorted(marr ^ narr): print(x)
class Scene: def __init__(self, camera, shapes, materials, lights): self.camera = camera self.shapes = shapes self.materials = materials self.lights = lights
""" entradas salario-->int-->s categoria-->int-->c Salidas aumento-->str-->au salario nuevo-->str-->sn """ s = int(input("Digite el salario $")) c = int(input("Digite una categoria del 1 al 5: ")) if (c == 1): a = s*0.10 if (c == 2): a = s*0.15 if (c == 3): a = s*0.20 if (c == 4): a = s*0.40 if (c == 5): a = ...
""" Set of processes for being in mult-processor mode within spatial package # Author: Antonio Martinez-Sanchez (Max Planck Institute for Biochemistry) # Date: 11.01.17 """ __author__ = 'martinez' ####### HELPING FUNCTIONS ####### PROCESSES # Radial Averaged Fourier Transform alone process # points: array with poi...
# Copyright 2017 The Bazel Authors. All rights reserved. # # 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 la...
# https://leetcode.com/problems/climbing-stairs/ class Solution: # def climbStairs(self, n: int) -> int: # array = [1, 2] # for i in range(2, n+1): # array.append(array[i-1] + array[i-2]) # return array[n-1] def climbStairs(self, n: int) -> int: if n <= 2: ...
""" The ska_tmc_cdm.messages.mccssubarray contains code that models the structured command arguments, command responses, and attribute values for the MCCSSubarray Tango device. """
def filter_data(data): """ Front function to filter data to perform a train Args: data (pd.DataFrame): a pandas dataframe with the non-filtered data Returns: filtered_data (pd.DataFrame): a pandas dataframe with the filtered data """ filtered_data = data.copy() ...
# HAUL Resources def get(i): return None def use(filename): # Do nothing, it is overridden when testing; in order to load resources at runtime return -1
def failure_message(message=None, user=None, user_group=None): resp = '''Message failed to send, please try again later or contact administrator from: Broadcast Admin - Only you can see this message ''' return resp
n_str = input() n = int(n_str) if (n == 1): print(1.000000000000) else: sum = 0.000000000000 for i in range(1, n+1): sum += round((1.000000000000)/i, 12) print(sum)
def is_rotation(s, t): """ Returns True iff s is a rotated version of t. """ return len(s) == len(t) and s in t + t if __name__ == "__main__": testStringPairs = [ ("", ""), ("stackoverflow", "flowstackover"), ("12345", "5xy1234"), ("stackoverflaw", "overflowstack") ...
class Redirect: def __init__(self, url: str = ""): self.redirect_url = url def to_dict(self): tmp_dict = { "redirect_url": self.redirect_url, } return tmp_dict
# Copyright 2020 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, ...
#!/usr/bin/python array = [0] * 43 Top = 1 Bottom = 2 Far = 4 Near = 8 Left = 16 Right = 32 scopeName = 'FDataConstants::' #Edge map array[Top + Far] = 'TopFar' array[Top + Near] = 'TopNear' array[Top + Left] = 'FTopLeft' array[Top + Right] = 'TopRigh...
class Website(object): def __init__(self, site): self.URL = site class Internet(object): def __init__(self): self.url_list = dict() def add_url(self, website): if website.URL in self.url_list: self.url_list[website.URL] += 1 else: self.url_list[webs...
# 实现二分查找 def binary_search(nums, n): low = 0 high = len(nums) - 1 while low <= high: mid = int((low + high) / 2) if nums[mid] == n: return mid if nums[mid] > n: # mid too big, change high high = mid - 1 else: # mid too small, change low ...
max= 0 a = 2 b = 3 if a < b: max= b if b < a: max= a assert (max == a or max == b) and max >= a and max >= b
def rotateLeft(array_list , num_rotate ): alist = list(array_list) rotated_list = alist[num_rotate :]+alist[:num_rotate ] return rotated_list array_list = [] n = int(input("Enter number of elements in array list : ")) for i in range(0, n): elem = int(input()) array_list.append(elem) num_rotate=int...
"""Module describes keys and types of nodes for an internal structure which is used to render the difference using formatters""" # left part of the dictionary KEY = 'KEY' VALUE = 'VALUE' STATE = 'STATE' # if the type is CHANGED then the left part consists # of these two keys instead of VALUE VALUE_LEFT = 'VALUE_LEFT'...
class RefBuilderBackend: def __init__(self, ref_name): self.ref_name = ref_name def resolve_attr(self, attr): return getattr(RefBuilder(self.ref_name), attr) def resolve_item(self, item): return RefBuilder(self.ref_name)[item] class DataBackend: def __init__(self, data):...
#!/usr/bin/python # -*- coding: utf-8 -*- class MyClass(object): pass def unpredictable(obj): """Returns a new list containing obj. >>> unpredictable(MyClass()) <doctest_unpredictable.MyClass object at 0x10055a2d0> """ return obj
#createMinMaxFunction.py def minimum_value(lst): #check if any ints or floats are in the list type_list = check_list_types(lst) #if not, return error if float not in type_list and int not in type_list: return "error" # if not create check every value in list against the value assigned to mi...
class CQueue: def __init__(self): self.A = [] self.B = [] # def appendTail(self, value: int) -> None: self.A.append(value) def deleteHead(self) -> int: if self.B:return self.B.pop() # self.B里面有数字 if not self.A:return -1 # ...
# Created by Egor Kostan. # GitHub: https://github.com/ikostan # LinkedIn: https://www.linkedin.com/in/egor-kostan/ primes = [2, 3, 5, 7] def is_prime(n): """ A function that checks if a given number n is a prime looping through it and, possibly, expanding the array/list of known primes only if/when necessary...
# Кириллов Алексей, ИУ7-12 # Найти сумму ряда -1<x<1 с точностью Е try: e = float(input('Введите требуемую точность: ')) x = float(input('Введите коэффициент х: ')) if -1>=x or x>=1: print('Некорректный х'); raise ValueError z = x; s = 0; k = 0 while z>e: ...
# -*- coding: utf-8 -*- """ Created on Mon Jul 9 01:37:45 2018 @author: 51667 """ qzMoneyCnsmpt = [0 for i in range(41)] qzMoneyCnsmpt[1] = 43 for i in range(1,40): qzMoneyCnsmpt[i + 1] = qzMoneyCnsmpt[i] + i + 5.5 qzCumMoneyCnsmpt = [0 for i in range(41)] for i in range(40): qzCumMoneyCnsmpt[i + 1] = ...
def main(): n = int(input()) p = [] for _ in range(n): p.append(input()) k = p.copy() k.sort() # print(k, p) if k == p: print("INCREASING") return # print(reversed(k), p, reversed(k) == p) if list(reversed(k)) == p: print("DECREASING")...
nome = input('Qual o seu nome? ') sobrenome = input('Qual o seu sobrenome? ') print('Seja bem-vindo(a), {} {}!'.format(nome, sobrenome)) print('Ordem natural: {0} {1}'.format(nome, sobrenome)) print('Ordem inversa: {1} {0}'.format(nome, sobrenome)) print('Outra forma: {0} {1} {other}'.format(nome, sobrenome, other = 'S...
print("¿Cuántos días tarda una rana en salir de un pozo de cierta profundidad?. Si consideramos que de día avanza una determinada cantidad de metros y por la noche retrocede una cierta cantidad de metros.\n") metrosAltura = float(input("Ingrese la altura en metros del pozo (en metros): ")) metrosAvanza = float (input...
# import time # import os # import stat # import random # import string # # import pytest # # import cattle # # from kubernetes import client as k8sclient, config as k8sconfig # BASE_URL = "http://%ip%:9333/v1" token = "" fqdn = "" create_param = { 'fqdn': '', 'hosts': ["1.1.1.1", "2.2.2.2"] } update_param = ...
a, b, i = 0, 1, 2 fibo = [a, b] while i < 100: i = i + 1 a, b = b, a+b fibo.append(b)
# Recursive solution for permutation class Solution: def permute(self, nums: List[int]) -> List[List[int]]: result = [] self.permu_helper(nums, [], result) return result def permu_helper(self, new_list, temp, result): if len(new_list) == 0: result.append(temp) ...
rankDict = { '1': 'A', '11': 'J', '12': 'Q', '13': 'K' } class Rank: def __init__(self, number): if not (1 <= number <= 13): raise Exception("number is out of range") self.number = number def __str__(self): return rankDict.get(str(self.number), str(self.number))
def server(host, port, symmetricKey): sockVanilla = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sockVanilla.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sockVanilla.bind((host, port)) sockVanilla.listen(5) while True: sockClientVanilla, source = sockVanilla.accept() ...
name_list= ['Sharon','Mic','Josh','Hannah','Hansel'] height_list = [172,166,187,200,166] weight_list = [59.5,65.6,49.8,64.2,47.5] size_list = ['M','L','S','M','S'] bmi_list = [] for i in range(len(name_list)): bmi = weight_list[i]/((height_list[i]/100)**2) bmi_list.append('{:.2f}'.format(bmi)) print("{:<10} {...
# ----------Inicializa vetor----------# numeros = list() tam = int(input("Digite o tamanh do vetor: ")) for i in range(tam): valor = int(input(f"Digite o valor do vetro na posição {i}: ")) numeros.append(valor) # -----------Selection Sort----------- # for i in range(tam): indice_menor = i # atrib...
def get_fuel(fuel): fuel = ((fuel // 3) - 2) if fuel <= 0: return 0 return fuel + get_fuel(fuel) total = 0 with open("d1.txt", "r") as f: for line in f: total += get_fuel(int(line)) print(total)
print(""" Note! A matrix is said to be sparse matrix if most of the elements of that matrix are 0. It implies that it contains very less non-zero elements. """) # To check whether the given matrix is the sparse matrix or not, # we first count the number of zero elements present in the matrix. # Then calculate ...
""" 15740 : A+B - 9 URL : https://www.acmicpc.net/problem/15750 Input #1 : 1 2 Output #1 : 3 Input #2 : -60 40 Output #2 : -20 Input #3 : -999999999 1000000000 Output #3 : 1 Input #4 : 1099511627776 1073741824 Output #4 : ...
def impares_no_intervalo(intervalo: tuple, lista: list): inicial, final = intervalo return [numero for numero in lista if numero % 2 != 0 and inicial <= numero <= final] limite = (0,10) l = [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] # --- OUTPUT --- # [1, 3, 5, 7, 9] print(impares_no_intervalo(...
# -- coding:utf-8-- class DL(object): def __init__(self): self.dlcs = 0 def q(self): self.dlcs = self.dlcs + 1 print(str(self.dlcs)) def a(self): self.dlcs = 0 print(str(self.dlcs)) hi = DL() hi.q() hi.q() hi.q() hi.q() hi.q() hi.a()
# # This file contains the Python code from Program 8.20 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm08_20.txt # class OpenScatterT...
# CodeWars Count_Of_Positives_/_Sum_Of_Negatives def count_positives_sum_negatives(arr): null_list = [] sum_of_positives = 0 sum_of_negatives = 0 if arr == [0, 0] or arr == []: return null_list for i in arr: if i > 0: sum_of_positives += 1 elif i < 0: ...
""" best time to use this times you're pretty sure list is almost sorted o(n) worst case(o(n^2)) """ array = [99, 44, 6, 2, 1, 5, 63, 87, 283, 40] def insertionSort(array): count = 0 for i in range(1, len(array)): first = array[i] last = array[i-1] # store the last element which is sorted ...
class Student: email = 'default@redi-school.org' def __init__(self, name, birthday, courses): # class public attributes self.full_name = name self.first_name = name.split(' ')[0] self.birthday = birthday self.courses = courses self.attendance = [] # Objects joh...
""" Creational : Builder => every builders designed patterns has director class to attach each side of objects """ class Director: __builder = None def set_builder(self, builder): self.__builder = builder def get_car(self): car = Car() body = self....
class NumArray(object): def __init__(self, nums): """ initialize your data structure here. :type nums: List[int] """ self.nums = [0] * len(nums) self.sums = [0] * (len(nums) + 1) for i, num in enumerate(nums): self.update(i, num) def update(s...
def get_ip_address(request): """use request object to fetch client machine's IP Address""" x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR") if x_forwarded_for: ip = x_forwarded_for.split(",")[0] else: ip = request.META.get("REMOTE_ADDR") ### Real IP address of client Machine ...
# Task # Given sets of integers, M and N, print their symmetric difference in ascending order. # The term symmetric difference indicates those values that exist in either M or N but do not # exist in both. # # Input Format # The first line of input contains an integer, M. # The second line contains M space-separated i...
SOC_IRAM_LOW = 0x4037c000 SOC_IRAM_HIGH = 0x403e0000 SOC_DRAM_LOW = 0x3fc80000 SOC_DRAM_HIGH = 0x3fce0000 SOC_RTC_DRAM_LOW = 0x50000000 SOC_RTC_DRAM_HIGH = 0x50002000 SOC_RTC_DATA_LOW = 0x50000000 SOC_RTC_DATA_HIGH = 0x50002000
class Node: def __init__(self, data, next=None): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None def insert_first(self, data): node = Node(data, self.head) self.head = node def __repr__(self): return str(sel...
"""Configuration Values""" # DRIVER = 'mysql+pymysql://' # URL_PARAMS = { # 'username': 'root', # 'password': 'root', # 'host': 'localhost', # 'port': '3306', # 'database_name': 'hydro' # } # URL = DRIVER + '{username}:{password}@{host}:{port}/{database_name}'.format( # **URL_PARAMS) class ...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # Base exception class class QlibException(Exception): pass class RecorderInitializationError(QlibException): """Error type for re-initialization when starting an experiment""" class LoadObjectError(QlibException): """Error type ...
""" Given an integer n and an integer start. Define an array nums where nums[i] = start + 2*i (0-indexed) and n == nums.length. Return the bitwise XOR of all elements of nums. Example: Input: n = 5, start = 0 Output: 8 Explanation...
# 计算1到n的和(n为读取的正整数) print('计算1到n的和。') while True: n = int(input('n的值:')) if n > 0: break sum = 0 i = 1 while i <= n: sum += i # sum加i i += 1 # i加1 print('1到', n, '的和是', sum, '。')
#! /usr/bin/env python3 """control the whitespaces in string""" s = 'The Little Price' # justify string to be at least width wide # by adding whitespaces width = 20 s1 = s.ljust(width) s2 = s.rjust(width) s3 = s.center(width) print(s1) # 'The Little Price ' print(s2) # ' The Little Price' print(s3) # ' T...
"""exercism armstrong numbers module.""" def is_armstrong_number(number): """ Determine if the number provided is an Armstrong Number. An Armstrong Number is a number that is the sum of its own digits each raised to the power of the number of digits :param number int - Number to check. :return b...
"""Generic Models.""" class CaseInsensitiveString(str): """A case insensitive string to aid comparison.""" def __eq__(self, other: object) -> bool: """Determine whether this object and another object are equal. Parameters: other: The object to compare this one to. Raises...
def make_withdraw(balance): """Return a withdraw function with a starting balance.""" def withdraw(amount): nonlocal balance if amount > balance: return 'Insufficient funds' balance = balance - amount return balance return withdraw def make_withdraw_list(balance)...
#!/usr/bin/env python class DataHelper: """ Helper to retrieve data from particular nodes """ @staticmethod def get_bucket(root, parents): """Get bucket name from root and parent nodes""" path = root.get("path", "") if path: # assume path like /pools/default ...
""" You are given an m x n integer matrix heights representing the height of each unit cell in a continent. The Pacific ocean touches the continent's left and top edges, and the Atlantic ocean touches the continent's right and bottom edges. Water can only flow in four directions: up, down, left, and right. Water fl...
# [Grand Athenaeum] sm.removeEscapeButton() sm.flipDialoguePlayerAsSpeaker() sm.sendNext("Supposedly the White Mage was last seen in Ellin Forest. If that's true, there must be evidence.") sm.sendSay("Ephenia the Fairy Queen's dwelling is nearby. I'll see if she knows anything.") sm.startQuest(parentID)
lista_geral_vacinados = [] lista_vacinados_pfizer = [] lista_vacinados_coronavac = [] lista_vacinados_astrazeneca = [] lista_estoque_pfizer = [0] lista_estoque_coronavac = [0] lista_estoque_astrazeneca = [0] media_geral = 0 media_pfizer = 0 media_coronavac = 0 media_astrazeneca = 0 print('~-' * 32) print(f'{"Programa ...
# reference.py # This script is for image references cookieurl = ["https://media1.tenor.com/images/45fe45f75ec523c2abf4e75ca2ac2fe2/tenor.gif?itemid=11797931", "https://media1.tenor.com/images/de6a49b999216fbda779cd27a24919c3/tenor.gif?itemid=19073253"] cookiesurl = ["https://media1.tenor.com/images/30c8c...
def D(): n = int(input()) neighbours = [None] #Asi puedo manejar numero de personas como index for i in range(n): neighbours.append([int(x) for x in input().split()]) visited = set() ans = [None,1] visited.add(1) a , b = neighbours[1][0] , neighbours[1][1] if(b in neighbours[a]): ans+=[a,b] else: ans...
# Count total cars per company # My Solution df.groupby('company').count() # Given Solution df['company'].value_counts()
''' Python Program to Remove the Duplicate Items from a List ''' lst = [3,5,2,7,5,4,3,7,8,2,5,4,7,2,1] print(lst) def method(): new_lst = [] for item in lst: if item not in new_lst: new_lst.append(item) print(new_lst) method()
# this module is the template of all environment in this project # some basic and common features are listed in this class class ENVError(Exception): def __init__(self, value_): self.__value = value_ def __str__(self): print('Environment error occur: ' + self.__value) class ENV: def __ini...
p = int(input('Primeiro termo: ')) r = int(input('Razão: ')) d = p + (10 - 1) * r for c in range(p, d + r, r): print('{} '.format(c), end='')
'''Identify whether the given input is polindrome''' def is_polindrome_word(input_word): """Check whether the given word is polindrome or not""" status = True input_word = input_word.replace(' ', '').lower() index = 0 while index < (len(input_word)/2): if input_word[index] != input_word[(in...
#Given two strings s and t, determine if they are isomorphic. # #Two strings are isomorphic if the characters in s can be replaced to get t. # #All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character...
C_ENDINGS = ('.c', '.i', ) CXX_ENDINGS = ('.cpp', '.cxx', '.cc', '.c++', '.CPP', '.CXX', '.C', '.CC', '.C++', '.ii', ) OBJC_ENDINGS = ('.m', '.mi', ) OBJCXX_ENDINGS = ('.mm', '.mii', ) FORTRAN_ENDINGS = ('.f', '.for', '.ftn', '.f77', '.f90', '.f95', '.f03', '.f08', '.F', '.FOR', '.FTN', '.F77', '.F90', '.F95',...
def calculate_max_people(area): """Calculates the max number of people allowed in a building""" stadard_capacity = area*2 # This numbers are defined for the 4th level of flexibilization of São Paulo state quarantine pandemic_capacity = stadard_capacity * 0.6 return int(pandemic_capacity) def is_n...
#Python solution for AoC qn 2 f = open("2.txt","r") strings = f.readlines() #Part 1 freq_total = { "2":0, "3":0 } for s in strings: s = s.strip().lower() freq_indv = {} #Count how many of each letter is inside for ch in s: if ch in freq_indv: freq_indv[ch]+=1 el...
class Solution: @staticmethod def naive(prices): maxReturn = 0 minVal = prices[0] for i in range(1,len(prices)): if prices[i]-minVal > maxReturn: maxReturn = prices[i]-minVal if prices[i]<minVal: minVal = prices[i] return m...
''' subsets and subarrays subarrays: a = [10,20,30] => [ [10], [20], [30] [10,20], [10,20,30], [20,30], ] subsets: a = [10,20,30] => [ [], [10,20,30] [10], [20], [30], [10, 20], [10, 30], [20, 30] ] ''' def print_subsets(a): limit = 2 ** len(a) for i in ra...
# -*- coding: utf-8 -*- # blue to red diverging set blue_to_red_diverging = ['#d7191c', '#fdae61', '#ffffbf', '#abd9e9', '#2c7bb6'] # red oragne sequential single hue: orange_sequential = ['#fff5eb', '#fee6ce', '#fdd0a2', '#fdae6b', '#fd8d3c', '#f16913', '#d94801', '#a63603', '#7f2704'] # blue s...
''' Author : Hemant Rana Date : 30th Aug 2020 link : https://leetcode.com/problems/container-with-most-water ''' class Solution: def maxArea(self, height: List[int]) -> int: h_len=len(height) max_area=0 b,e=0,h_len-1 while(b<e): area=min(height[b],height[e])*(e-...
class Struct(object): def __init__(self, data=None, **kwds): if not data: data = {} for name, value in data.items(): if name: setattr(self, name, self._wrap(value)) for name, value in kwds.items(): if name: setattr(self, nam...
# Задача №2952. Разность времен # Даны значения двух моментов времени, принадлежащих одним и тем же суткам: часы, # минуты и секунды для каждого из моментов времени. # Известно, что второй момент времени наступил не раньше первого. # Определите, сколько секунд прошло между двумя моментами времени. # # Входные данные # ...