content
stringlengths
7
1.05M
class Pessoa: olhos = 2 def __init__(self, *filhos, nome=None, idade=None): self.idade = idade self.nome = nome self.filhos = list(filhos) def cumprimentar(self): return f'Olá {id(self)}' if __name__ == '__main__': maite = Pessoa(nome='Maite', idade=0) denian = Pes...
# program to split email to username and domain name # made by itsmeevil print("***Email Splitter***") email = input("\nEnter an email: ") sliced = email.split("@") # split string at "@" which will put it in an array- ["username", "domain name"] print(f"\nUsername: {sliced[0]}\nDomain name: {sliced[1]}")
class SocialMedia: def __init__(self): pass def GetSocialMediaSites_NiceNames(self): return { 'add.this':'AddThis', 'blogger':'Blogger', 'buffer':'Buffer', 'diaspora':'Diaspora', 'douban':'Douban', 'email':'EMail', ...
"""QwikSwitch USB Modem library for Python. See: http://www.qwikswitch.co.za/qs-usb.php Currently supports relays, buttons and LED dimmers Source: http://www.github.com/kellerza/pyqwikswitch """
class ResistanceValue: RESISTANCE_VALUES = [ (10, ["brown", "black"]), (12, ["brown", "red"]), (15, ["brown", "green"]), (18, ["brown", "grey"]), (22, ["red", "red"]), (27, ["red", "purple"]), (33, ["orange", "orange"]), (39, ["orange", "white"]), ...
""" 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """ num = 2520 def divideby(numbers): for div in range(1,11): if not(numbers %div == 0): ...
# -*- coding: utf-8 -*- # @Author : LG """ 执行用时:88 ms, 在所有 Python3 提交中击败了46.93% 的用户 内存消耗:23.3 MB, 在所有 Python3 提交中击败了5.02% 的用户 解题思路: 动态规划 """ class Solution: def maxSubArray(self, nums: List[int]) -> int: n = len(nums) if n == 0: return 0 dp = [[] for _ in range(n)] ...
def url(your_url): root = 'https://sandboxapi.fsi.ng' if your_url: root = your_url return root
N = int(input()) print("*"*N) for i in range(N//2-1): print("*"*((N//2-i)) + " "*(N-2*(N//2-i)) + "*"*((N//2-i))) print("*" + " "*(N-2) + "*") for i in range(N//2-2, -1, -1): print("*"*((N//2-i)) + " "*(N-2*(N//2-i)) + "*"*((N//2-i))) print("*"*N)
""" LeetCode Problem: 692. Top K Frequent Words Link: https://leetcode.com/problems/top-k-frequent-words/ Language: Python Written by: Mostofa Adib Shakib Approach: Use dict to find count of words Add words and count to heap with negative count[by-default its min-heap, and we want max heap] For adding...
class Solution: def isMatch(self, s: str, p: str) -> bool: dp = [[False for _ in range(len(s) + 1)] for _ in range(len(p) + 1)] dp[0][0] = True for i in range(1,len(p)+1): if p[i-1] == '*': dp[i][0] = dp[i-1][0] else: break ...
class Solution: """ @param num: a string @param k: an integer @return: return a string """ def removeKdigits(self, num, k): # write your code here St = [] for c in num: while St and c < St[-1] and k > 0: St.pop() k -= 1 ...
#!/usr/bin/env python # encoding=utf-8 """ Copyright (c) 2021 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFT...
# Leo colorizer control file for md mode. # This file is in the public domain. # Properties for md mode. # Important: most of this file is actually an html colorizer. properties = { "commentEnd": "-->", "commentStart": "<!--", "indentSize": "4", "maxLineLen": "120", "tabSize": "4", } ...
####################################################################################################### ## ## ## Script name: linear_eq_solver.py ## ## Purp...
lista = ('APRENDER', 'PROGRAMA', 'LINGUAGES', 'PYTHON', 'CURSO', 'GRATIS', 'ESTUDAR', 'PRATICAR', 'TRABALHAR', 'MERCAADO', 'PROGRAMADOR', 'FUTURO') for palavras in lista: print(f'\nNa palavra {palavras} temos: ', end='') for vogais in palavras: if vogais in 'AEIOU': pri...
# Strings - this is how you type a comment in python 'Hello world using single quotes' "Hello world using double quotes" """Hello world using triple quotes, also known as multi-line strings""" # To print an object to the screen, use the print function print('Hello world') # This will print Hello World in the terminal...
# -*- coding: utf-8 -*- # package information. INFO = dict( name='coil', description='Scheme interpreter written in Python', author='coilo', author_email='coilo.dev@gmail.com', license='MIT License', url='https://github.com/coilo/coil', classifiers=[ 'Programming Language :: Python...
text = """ //---------------------------------Spheral++----------------------------------// // HatKernel -- The B spline interpolation kernel. // // Created by JMO, Wed Dec 11 17:33:57 PST 2002 //----------------------------------------------------------------------------// #include "Kernel.hh" #include "HatKernel.hh" ...
def foo(x): def bar(x, y): return lambda y: y(x) return lambda y: bar(x, y) print(foo(lambda x: x**3)(lambda x: x**2)(lambda x: x)(4))
# 190. Reverse Bits # ttungl@gmail.com # Reverse bits of a given 32 bits unsigned integer. # For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), # return 964176192 (represented in binary as 00111001011110000010100101000000). # Follow up: # If this function is called many ti...
class Movie: def __init__(self,title,year,imdb_score,have_seen): self.title = title self.year = year self.imdb_score = imdb_score self.have_seen = have_seen def nice_print(self): print("Title: ", self.title) print("Year of production: ", self.year) pr...
#!/usr/bin/env python3 class AppException(Exception): status_code = 400 def __init__(self, message): Exception.__init__(self) self.message = message def to_dict(self): return {'message': self.message} class DeviceNotFoundException(AppException): status_code = 404 class Ups...
# Copyright Pincer 2021-Present # Full MIT License can be found in `LICENSE` at the project root. """sent when the client's voice settings update""" # TODO: Implement event
saludo = "buenos dias" for i in range(20): print(saludo)
# Напишите программу, которая считывает целое число и выводит текст, аналогичный приведенному в примере # #(пробелы важны!). Первая строка содержит следующее значение, а втора строка содержит предыдущее значение введёного # #числа # # Please enter an integer number: 1234 # # The next number for the number...
def test_spec_gui(specviz_gui): """ Generic test to ensure the pytest fixture is properly feeding an instance of the specviz application. """ assert specviz_gui is not None
string = input("텍스트를 입력하고 엔터를 눌러주세요: ") print("입력하신 텍스트는 " + string + " 입니다.")
class ModuleBase(): # Invalid slot for modular chassis MODULE_INVALID_SLOT = -1 # Possible card types for modular chassis MODULE_TYPE_SUPERVISOR = "SUPERVISOR" MODULE_TYPE_LINE = "LINE-CARD" MODULE_TYPE_FABRIC = "FABRIC-CARD" # Possible card status for modular chassis # Module stat...
#!/usr/bin/env python3 class Furnishings: def __init__(self,room): self.room = room class Sofa(Furnishings): pass class Bookshelf(Furnishings): pass class Bed(Furnishings): pass class Table(Furnishings): pass def map_the_home(home): home_map = {} for fu...
def setToken(): """Authentication TOKEN for Telegram API """ token = "" return token
# -*- coding: utf-8 -*- """spear2sc.spear_utils: Utitlity methods to read SPEAR files""" def process_line(line): """ (list of str) -> list of list of float Parses line, a line of time, frequency and amplitude data output by SPEAR in the 'text - partials' format. Returns a list of timepoints. Each ti...
def extractGsekkatranslationBlogspotCom(item): ''' Parser for 'gsekkatranslation.blogspot.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('skkn', 'Saikyou Ke...
#! /usr/bin/python3.6 class CATIAMeasurable: """ The interface to access a CATIAMeasurable Get measurements on the object. .. note:: CAA V5 Visual Basic help Two types of measurement can be done: | itself : gives dimensions related to the object itself (ex the radius of a circle...
inputstart = int(input('Enter the beginning of the interval: ')) inputend = int(input('Enter the end of the interval: ')) for i in range(inputstart, inputend): # Iterating over numbers from a given interval firstnum = 0 # The sum of the divisors of the second number = The first number of the pair ...
class QvaPayException(Exception): def __init__(self, status_code: int, *args: object) -> None: super().__init__(*args) self.status_code = status_code
def mutable_or_immutable(para): para += '1' a = 'a' b = ['b'] mutable_or_immutable(a) print(a) mutable_or_immutable(b) print(b)
# # PySNMP MIB module HPR-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPR-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:42:27 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:15)...
RESULT = "result" SUCCESS = "success" ERROR = "error" MESSAGE = "message" CODE = "code" PROPERTIES = 'properties' MISSED_KEYS = { "format": { "type": "string" }, "$ref": { "type": "string", "format": "uri" } }
# We just put it here to get the checks to shut up MIDDLEWARE_CLASSES = [] INSTALLED_APPS = ( 'django.contrib.sites', 'absoluteuri', ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } } SITE_ID = 1 ROOT_URLCONF = 'absoluteuri.tests' TEMPLATES = [ { 'BACKEND':...
underworld_graph = { 992: { "title": "Darkness", "description": "You are standing on grass and surrounded by darkness.", "terrain": "NORMAL", "coordinates": "(75,61)", "elevation": 0, "w": 966 }, 966: { "title": "Darkness", "description": "You ...
class Tape: """ Allows writing to end of a file-like object while maintaining the read pointer accurately. The read operation actually removes characters read from the buffer. """ def __init__(self, initial_value:str=''): """ :param initial_value: initialize the Tape with a preset s...
class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: ''' T: O(n!) and S: O(n!) ''' def permute(nums): n = len(nums) if n <= 1: return [nums] out = [] for i in range(n): first = [nums[...
"""Constants for the Sure Petcare component.""" DOMAIN = "sureha" SPC = "spc" # platforms TOPIC_UPDATE = f"{DOMAIN}_data_update" # sure petcare api SURE_API_TIMEOUT = 60 # device info SURE_MANUFACTURER = "Sure Petcare" # batteries ATTR_VOLTAGE_FULL = "voltage_full" ATTR_VOLTAGE_LOW = "voltage_low" SURE_BATT_VOLTAG...
__HEXCODE = "0123456789abcdef" def byteToHex(someValue:int) -> str: assert isinstance(someValue, int) someValue = someValue & 255 return __HEXCODE[int(someValue / 16)] + __HEXCODE[someValue % 16] def byteArrayToHexStr(someByteArray) -> str: assert isinstance(someByteArray, (bytes, bytearray)) ret = "" for...
def trap(height): '''Algo: Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. Output: Number of units of water trapped Input: List of the brick walls position Steps: Observations: find all subsequences s...
def combination(n, r): if n < r: return 0 if r == 0: return 1 tmp_n = 1 for i in range(r): tmp_n *= n - i tmp_r = 1 for i in range(r): tmp_r *= r - i return tmp_n // tmp_r n, r = map(int, input().split()) print(combination(n, r)) def cmb(n, r): if n - r ...
''' Created on Apr 20, 2017 @author: simulant '''
def iSort(lst,newl = [],n=1): if len(lst)>0: # print(newl,lst) compInsert(newl,lst.pop(0),len(newl)-1) if len(newl)>1: print(newl,end=" ") if len(lst)>0: print(lst) else: print('\n',"sorted\n",newl,sep="") iSort(lst,...
# ============================================================================= # Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/ # FileName: 12930.py # Description: UVa Online Judge - 12930 # ============================================================================= nt = 0 whil...
consumer_key = '123456' consumer_secret = '123456' flickr_key = '123456' flickr_secret = '123456'
grades = [] sum = 0 colors = {'none': '\033[01;m', 'red': '\033[01;31m', 'purple': '\033[01;35m'} def message(text, color='none', line=False): print(colors[color]) if line == True: print('✧----' * 12) print(text.center(65)) print('✧----' * 12) else: prin...
class TerminalColours: """ Colours for displaying success or failure of request on stdout """ GREEN = '\033[92m' RED = '\033[91m' PURPLE = '\033[95m' YELLOW = '\033[33m' BLUE = '\033[96m'
'''69-crie um programa que leia a idade e o sexo de varias pessoas.a cada pessoa cadastrada, o programa devera perguntar se o usuario quer ou nao continuar.no final mostre: A- quantas pessoas tem mais de 18 anos. B- quantos homensforam cadastrados. C- quantas mulheres tem menos de 20 anos. ''' tot18=toth=totm20=0 c...
# define variables a = 10 b = 20 # swap numbers a,b = b,a # print result print(a, b)
''' ATRIBUTOS DE UM ARQUIVO''' arquivo = open('dados1.txt', 'r') conteudo = arquivo.readlines() print('tipo de conteudo, ', type (conteudo)) print('conteudo retornado pelo realines: ') print(repr(conteudo)) arquivo.close()
# Convert algebraic infix notation to revese polish notation (postfix) def infixToPostfix(expr): rpn = "" stack = [] oper = "(+-*/^" for e in expr: if e.lower() >= "a" and e <= "z": rpn += e elif e == ")": while len(stack) > 0: op = stack.pop() ...
class Action_Keys(): def __init__(self, game_name): self.game_name = game_name def action_keys_Convert(self, key): if self.game_name == 'Enduro': return action_keys_Convert_Enduro(key) elif self.game_name == 'SpaceInvaders': return action_keys_C...
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@build_bazel_rules_nodejs//:index.bzl", "yarn_install") def rules_typescript_proto_dependencies(): """ Installs rules_typescript_proto dependencies. Usage: # WORKSPACE load("@rules_typescript_proto//:index.bzl", "rules_typ...
def prod(numbers): """ Find the product of a sequence :param numbers: Sequence of numbers :return: Their product """ ret = 1 for number in numbers: ret *= number return ret
class Slave: """ define slaves in socket programing. """ def __init__(self, host_port: str): if ":" not in host_port: raise ValueError( "The format of slave definition is incorrect, should be <host>:<port>") splits = host_port.lstrip().rstrip().split(":") ...
def hex_to_rgb(hex_color, base=256): return tuple(int(hex_color[i:i + 2], 16) for i in (1, 3, 5)) def rgb_to_hex(rgb, with_sharp=False, upper=True): hex_code = ''.join([hex(one_channel)[2:] for one_channel in rgb]) if with_sharp: hex_code = '#' + hex_code if upper: hex_code = hex_code...
# add two numbers using function without return '''def add(x,y): print("addition is : ",(x+y)) x = int(input("Enter a first number for addition : ")) y = int(input("Enter a second number for addition : ")) add(x,y)''' # add two numbers using function with return '''def add(x,y): return (x+y) x = int(input("Ent...
""" blobcli ---- Command line interface for easy operation with blobs in Azure Blob Storage. """ __version__ = '0.0.6'
string = input("Ingrese la palabra a enmarcar: ") num = int(input("Ingrese la cantidad de espacios entre el marco y la palabra")) arribaAbajo = "*" * (len(string) + (num*2)+2)+ "\n" laterales = "*" + " " * (len(string) + num*2) + "*\n" resultado = arribaAbajo for i in range(num): resultado += laterales resultado +=...
# At each point 3 choice possible # 1. ith element. # 2. max -ve before ith * ith element # 3. max +ve before ith * ith element # TC: O(n) | SC: O(1) def solution_1(arr): max_product = arr[0] min_product = arr[0] answer = arr[0] for i in range(1, len(arr)): choice1 = min_product*...
# set of rules that are expected to work for all supported frameworks # Supported Frameworks: Mxnet, Pytorch, Tensorflow, Xgboost UNIVERSAL_RULES = { "AllZero", "ClassImbalance", "Confusion", "LossNotDecreasing", "Overfit", "Overtraining", "SimilarAcrossRuns", "StalledTrainingRule", ...
__author__ = 'surya' prey="This will give the list of prey protein used in the experiment" bait="This will give all information of the Bait protein used in the experiment" molecule="This will give all information store in the database about small molecule, if used in the experiment" SdFound="This will give the list o...
# # PySNMP MIB module CISCO-TCPOFFLOAD-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-TCPOFFLOAD-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:14:11 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
'''given an array of integers, return indices of the two numbers such that they add up to a specific problem given nums = [2, 7, 11, 15], target = 9 because nums[0] + nums[1] = 2 + 7 = 9 return [0, 1] ''' #this is a great time to use a hash table #class Solution(object): def twoSum(nums, target): index_mapping...
def arrayMaximalAdjacentDifference(inputArray): return max([abs(inputArray[x] - inputArray[x + 1]) for x in range(len(inputArray) - 1)]) # [2. 4, 1, 0] => 3 # [1, 1, 1, 1] => 1 # [-1, 4, 10, 3, -2] => 7 # [10, 11, 13] => 2 print(arrayMaximalAdjacentDifference([1, 1, 1, 1]))
[ {'base_name': 'PanSTARRS', 'service_type': 'xcone', 'adql': '', 'access_url': 'https://catalogs.mast.stsci.edu/api/v0.1/panstarrs/dr2/' 'mean.votable?flatten_response=false&raw=false&sort_by=distance' '&ra={}&dec={}&radius={}' } ]
# <code># -- coding:UTF-8 --<code> # # 把srt字幕处理成无时间的txt # path = "./assets/files/jojo.txt" # newFile = open("./assets/files/newFile.txt", 'w') # with open(path,'r',encoding='utf-8') as fc: # for line in fc.readlines()[2::4]: # newFile.write(line) # newFile.close() # # 读取文件名中的信息并重名命 # import o...
def test(): assert ( "from spacy.tokens import Doc" in __solution__ ), "¿Estás importando la clase Doc correctamente?" assert ( len(spaces) == 5 ), "Parece que el número de espacios no concuerda con el número de palabras." assert all(isinstance(s, bool) for s in spaces), "Los espacio...
""" Question: Search in Rotated Sorted Array Difficulty: Medium Link: https://leetcode.com/problems/search-in-rotated-sorted-array/ Ref: https://xiaozhuanlan.com/topic/2039467185 Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might ...
# https://www.codewars.com/kata/5174a4c0f2769dd8b1000003 # Finish the solution so that it sorts the passed in array of numbers. If the function passes in an empty array or null/nil value then it should return an empty array. # For example: # solution([1,2,3,10,5]) # should return [1,2,3,5,10] # solution(None) # should ...
""" File: similarity.py Name: ---------------------------- This program compares short dna sequence, s2, with sub sequences of a long dna sequence, s1 The way of approaching this task is the same as what people are doing in the bio industry. """ def main(): """ find the best match of the long DNA strand to th...
# File for describing the Cab entity. class Cab: def __init__(self, city:str, brand: str, hourly_price: int, is_available: bool = True, id=None) -> None: self.city = city self.brand = brand self.hourly_price = hourly_price self.is_available = is_available self.id = id
class ChangeAxis(): def __init__(self,width, height, c_w, c_h, bias_x=0, bias_y=0): """picture: 원본 해상도 크기 want_change: 바꾼 해상도 크기 bias: 영점 조절정도""" self.picture_width = width self.picture_height = -height self.want_change_width = c_w self.want_change_heigh...
# coding:utf8 """ @author Nemo @time 2021/08/23 01:42 """ class _QueryConst: """ 一些查询相关常量定义 """ def __init__(self): pass # 连接符 collection_or = "OR" collection_and = "AND" collection_and_quota = "AND (%s)" collection_or_quota = "OR (%s)" # 标识符 quota_equals = "=" ...
def get_sensor_bands(target_sensor): """ get_sensor_bands returns a list of the band definitions from the PredfinedWavelengths function for a list of different sensors availalbe definitions for target_sensor are: custom, ali, aster, er2_mas, gli, landsat_etm, *_mss, *_oli, *_tm, mer...
print_('Voltages') for a in ['CH1','CH2','CH3','AN8','CAP','SEN']: button('Voltage : %s'%a,"get_voltage('%s')"%a,"display_number") print('') #Just to get a newline print('') print_('Passive Elements') button('Capacitance_:',"get_capacitance()","display_number") print('') button('Resistance__:',"get_resistance()","d...
ASCII_BYTE = ' !"#\\$%&\'\\(\\)\\*\\+,-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\\\~\t' # Directory structure MAIN_TRACE = 'cor1_1' SECOND_TRACE = 'cor1_2' DIFF_TRACE = 'cor2_1' INPUT1 = 'input1' INPUT2 = 'input2' FUNCTYPE = 'functype' HEADER...
def main(): total = None serie = input("What's your favorite serie?: ") seasons = int(input("How much seasons have?: ")) number_chap = int(input("How much chapter have?: ")) duration_chap = int(input("How much minuts chapters have?: ")) total = seasons * number_chap * duration_chap / 60 p...
list_name_row_add_father = [ 'Имя', 'Инвертарный номер', 'Хозяйство', 'BM1818', 'BM1824', 'BM2113', 'CSRM60', 'CSSM66', 'CYP21', 'ETH10', 'ETH225', 'ETH3', 'ILSTS6', 'INRA023', 'RM067', 'SPS115', 'TGLA122', 'TGLA126', 'TGLA227', 'TGLA53', ...
BASE_LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "console": { "format": "{module}: {message}", "datefmt": "%d/%b/%Y %H:%M:%S", "style": "{", }, }, "handlers": { "console": { "level": "DEBUG", ...
newdata = [] with open("requirements.txt") as f: data = f.read() data = data.split("\n") for i in data: if "@" not in i: newdata.append(i) # print(newdata) file = open("requirements.txt", "w") # print("".join(newdata) + "\n") for i in newdata: print(i) file.write(i + "\n"...
source = r'''#include <cstdio> #include "mylib.h" void do_something_else() { printf("something else\n"); }''' print(source)
print(' ') print('-------Menghitung laba seorang pengusaha-------') a=100000000 sum=0 b=0 laba=[int(0),int(0),int(a)*.1,int(a)*.1,int(a)*.5,int(a)*.5,int(a)*.5,int(a)*.2] print('') print('Modal seorang pengusaha :',a) print(' ') for i in laba: sum=sum+i b+=1 print('Laba Bulan ke -',b,'...
# # @lc app=leetcode id=214 lang=python3 # # [214] Shortest Palindrome # # https://leetcode.com/problems/shortest-palindrome/description/ # # algorithms # Hard (30.96%) # Likes: 1756 # Dislikes: 156 # Total Accepted: 118.6K # Total Submissions: 382.7K # Testcase Example: '"aacecaaa"' # # You are given a string s...
#!python3 msn = 0 for x in range(3,1000000) : n = x csn = 0 while n != 1 : if n % 2 == 0 : n = int(n / 2) else : n = n * 3 +1 csn += 1 if csn > msn : msn = csn sn = x print(sn)
def day01_1(input_data): result = 0 for i in range(len(input_data)): if int(input_data[i]) == int(input_data[(i + 1) % len(input_data)]): result += int(input_data[i]) return result def day01_2(input_data): result = 0 for i in range(len(input_data)): if int(input_data[i...
class Solution: def minimumDeleteSum(self, s1, s2): """ :type s1: str :type s2: str :rtype: int """ w1 = len(s1) w2 = len(s2) dp = [[0 for j in range(w2 + 1)] for i in range(w1 + 1)] dp[0][0] = 0 for i in range(1, w2 + 1): d...
class Fuzzy_logical_relationship(object): def __init__(self, lhs, rhs): self.lhs = lhs self.rhs = rhs def __str__(self): return str(self.lhs) + " -> " + str(self.rhs)
random_list = tuple(range(0, 1000)) def just_mean(x): total = 0 for xi in x: total += xi return total / len(x) mean_output = just_mean(random_list)
INVALID_INPUT = 1 DOCKER_ERROR = 2 UNKNOWN_ERROR = 3 class DkrException(Exception): def __init__(self, message, exit_code): self.message = message self.exit_code = exit_code
""" link: https://leetcode.com/problems/search-a-2d-matrix-ii problem: 矩阵matrix满足 matrix[i][k] < matrix[i][k+1] and matrix[k][i] < matrix[k][i+1] 求检查target是否存在矩阵中 solution: 从上至下,逐行二分,时间复杂度O(nlogm) solution-fix: 对矩阵,其右上角数字k满足为一列中的最小值,一行中的最大值; 若k>target,则当前行不可能存在target,i+=1排除一行; 若...
""" Написать функцию XOR_cipher, принимающая 2 аргумента: строку, которую нужно зашифровать, и ключ шифрования, которая возвращает строку, зашифрованную путем применения функции XOR (^) над символами строки с ключом. Написать также функцию XOR_uncipher, которая по зашифрованной строке и ключу восстанавливает исходную с...
#Faça um Programa para uma loja de tintas. O programa deverá pedir o tamanho em metros # quadrados da área a ser pintada. Considere que a cobertura da tinta é de 1 litro para # cada 6 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00 # ou em galões de 3,6 litros, que custam R$ 25,00....
class Action: def __init__(self, unit, target): self.unit = unit self.target = target def complete(self): self.unit.walked = [] self.unit.action = None self.unit._flee_or_fight_if_enemy() def update(self): pass class MoveAction(Action): def u...