content
stringlengths
7
1.05M
''' Created on 1.12.2016 @author: Darren '''''' Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 But the following is not: 1 / \ 2 2...
def find_substring(string: str, substring: str) -> int: l1 = len(string) l2 = len(substring) for i in range(l1 - l2 + 1): status = True for j in range(l2): if string[i+j] != substring[j]: status = False if status: return i if ...
def list_headers(catalog, headers=True): result = [] if isinstance(headers, set): for header in catalog: if header in headers: result.append(header) else: result = catalog.keys() return set(result)
folium.Marker([42.333600, -71.109500], popup='<strong>Location Two</strong>', tooltip=tooltip, icon=folium.Icon(icon='cloud')).add_to(m), folium.Marker([42.377120, -71.062400], popup='<strong>Location Three</strong>', tooltip=tooltip, i...
"""kockatykalendar - API, tools and utilities for working with KockatyKalendar.sk""" __author__ = 'Adam Zahradník <adam@zahradnik.xyz>' __version__ = '0.1.2' scheme_version = '0.0.3' __all__ = ['scheme_version']
# Create a list of strings: fellowship fellowship = ['frodo', 'samwise', 'merry', 'aragorn', 'legolas', 'boromir', 'gimli'] # Create dict comprehension: new_fellowship new_fellowship = { member:len(member) for member in fellowship } # Print the new dictionary print(new_fellowship)
# @params: # str - string to perform subsets breakdown # n (optional) - nth order to break def get_string_subsets(str): subsets = [] for index in range(len(str)): if(index == 0): subsets.append(str[index]) else: subsets.append(subsets[index-1] + str[index]) ret...
#!python3.6 #coding:utf-8 #class complex([real[, imag]]) print(complex(3, 2))
# Python INTRO for TD Users # Kike Ramírez # May, 2018 # Understanding Tuples # Creating a tuple with person information -> (name, surname, birth year, favorite movie and year, profession, birthplace) tup1 = ('Lionel', 'Messi','1983','Terminator 1995', 'Football Player','Rosario'); print(tup1) print(tup1[0]) # Creat...
# # PySNMP MIB module ELTEX-MES-CFM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-MES-CFM-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:01:03 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
def mean(num_list): try: return sum(num_list)/len(num_list) except ZeroDivisionError: return 0 except TypeError: raise TypeError("Cannot get mean for non-number elements")
#!/usr/bin/env python3 # Some data formatters that I seem to need from time to time... def rat(n, d, nan=float('nan'), mul=1.0): """ Calculate a ratio while avoiding division by zero errors. Strictly speaking we should have nan=float('nan') but for practical purposes we'll maybe want to report Non...
""" :author: Jinfen Li :url: https://github.com/LiJinfen """
recent = { 9: (1, 1), 3: (2, 2), 1: (3, 3), 0: (4, 4), 8: (5, 5), 4: (6, 6) } last = 4 for turn in range(len(recent.keys()) + 1, 30_000_001): last = recent[last][1] - recent[last][0] recent[last] = (recent[last][1] if last in recent else turn, turn) print(last)
def clean_empty(pkg, dpath): empty = True for f in dpath.iterdir(): if f.is_dir() and not f.is_symlink(): if not clean_empty(pkg, f): empty = False else: empty = False if empty and dpath != pkg.destdir: pr = dpath.relative_to(pkg.destdir) ...
def find_disappeared_numbers(nums): """ :type nums: List[int] :rtype: List[int] """ result1 = [0]*len(nums) result2 = [] for i in range(0, len(nums)): if result1[nums[i]-1]==0: result1[nums[i]-1] = nums[i] else: pass ...
if __name__ == '__main__': fin = open('input.txt', 'r') fout = open('output.txt', 'w') k = int(fin.readline()) s = ['1' for i in range(k)] counts = set() counts.add('1' * k) need = 2 ** k have = 1 while have < need: ss = s[-k+1:] if ''.join(ss) + '0' in counts: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Options: def __init__(self, telegram_bot_token: str): self.telegram_bot_token = telegram_bot_token
# noinspection PyUnusedLocal # friend_name = unicode string def hello(friend_name): """ Return hello message for a friend :param: friend_name: the person's name :return: String containing the message """ return f'Hello, {friend_name}!'
def knight_move(row, col): """knight_move (row, col) - returns all possible movements for the knight in chess based on the parameters of its current row and column""" # Deltas and Column Names columns = ["A", "B", "C", "D", "E", "F", "G", "H"] possible_moves = [(2, -1), (2, 1), (1, 2), (-1, 2), (-2...
# -*- coding: utf-8 -*- # This is Testaction 2 def main(args): number = args.get("number") square = number+number print(square) return {"number":square} #if __name__=="__main__": # main({"number":4})
""" Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto. """ valor = float(input('Qual o valor do produto? R$ ')) des = valor * 0.95 print(f'O produto que custava R$ {valor:.2f} reais, com o desconte de 5% sai por R$ {des:.2f} reais')
""" Written in Python 3. This program is all yours now! Have fun experimenting!! This program accepts a sentence and prints the frequency of all the letters in the sentence. teaches: creating functions, function calling, loops, bubble sort algorithm, lists (arrays), dictionary. """ def main(): sentence = input("\...
d = {} l = [1] try: d[l] = 2 except TypeError: pass else: print('Should not be able to use a list as a dict key!') a = {} try: d[a] = 2 except TypeError: pass else: print('Should not be able to use a dict as a dict key!')
class Error(Exception): """Main error class to be inherited in all app's custom errors.""" def __init__(self, message: str = '', status_code: int = 400) -> None: super().__init__(message) if type(message) is str: self.message: str = message else: raise TypeError( ...
def getIpBin(ip): ipBin = '' for index, octet in enumerate(ip.split("."), 1): ipBin += str(format(int(octet), '08b')) if index != 4: ipBin += "." return ipBin def getIpClass(ip): octet = ip.split(".") if 1 <= int(octet[0]) < 128: return 'A' elif 128 <= int(octet[0])...
OCTICON_PLUS_CIRCLE = """ <svg class="octicon octicon-plus-circle" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M1.5 8a6.5 6.5 0 1113 0 6.5 6.5 0 01-13 0zM8 0a8 8 0 100 16A8 8 0 008 0zm.75 4.75a.75.75 0 00-1.5 0v2.5h-2.5a.75.75 0 000 1.5h2.5v2.5a.75.75 0 00...
# -*- coding: utf-8 -*- """ Created on Sun Oct 4 23:51:51 2020 @author: heziy """
# Ex: 063 - Faça um programa que leia um número qualquer e mostre o seu fatorial. # (ex: 5! = 5x4x3x2x1 = 120) print(''' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- --Seja bem-vindo! --Exercício 063 -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ''') termo = int(input('Quantidade de termos: ')) valor1, valor2, cont = 0, 1...
pi = 3.14159 R = float(input()) volume = (4/3) * pi * R ** 3 print('VOLUME = {:.3f}'.format(volume))
''' Extracted and modified from https://github.com/dirkmoors/drf-tus available under MIT License, Copyright (c) 2017, Dirk Moors ''' default_app_config = 'froide.upload.apps.UploadConfig' tus_api_version = '1.0.0' tus_api_version_supported = ['1.0.0'] tus_api_extensions = ['creation', 'creation-defer-length', 'ter...
for _ in range(int(input())): n=int(input()) s=input() for i in range(5): if s[0:i]+s[n-(4-i):n]=='2020': print('YES') break else: print('NO')
""" Created by akiselev on 2019-06-17 Task You are given three integers: a, b, and m , respectively. Print two lines. The first line should print the result of pow(a,b). The second line should print the result of pow(a,b,m). Input Format The first line contains a , the second line contains b, and the third line co...
stockCount = int(input()) stock = [] for x in range(stockCount): info = input().split(",") tupleVersion = (info[0], info[1], info[2]) stock.append(tupleVersion) stock = sorted(stock, key=lambda a: a[0]) companyNames = [] for i in stock: if i[0] not in companyNames: companyNames.append(i[0]) comp...
# -------------- "solution" # -------------- "solution"
# # PySNMP MIB module TRIPPLITE-PRODUCTS (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRIPPLITE-PRODUCTS # Produced by pysmi-0.3.4 at Wed May 1 15:27:41 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
class AccountEditor: """Account用Interface 兼 動作確認の出来るモック """ def __init__(self): self.name = "default" def get_name(self): return self.name def post_name(self, name): self.name = name print(name) return True
def _tool_config( executable, additional_tools = [], args = [], env = {}, execution_requirements = {}): return struct( executable = executable, additional_tools = additional_tools, args = args, env = env, execution_requirements = execut...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' # TODO: from dev_window # from PySide.QtWebKit import * # # QWebSettings.globalSettings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True) # # self.view = QWebView() # self.setCentralWidget(self.view) # # self.view.load('https://twitter.c...
"""Defines the exceptions used by xnat sub-modules""" class XnatException(Exception): """Default exception for xnat errors""" def __init__(self, msg, study=None, session=None): # Call the base class constructor with the parameters it needs super().__init__(msg) # Now for your custom ...
# -------------- # settings pw = ph = 500 amount = 24 factor = 1/3 regular = False cell_s = pw / (amount + 2) # -------------- # function(s) def I(pos, s): x, y = pos polygon( (-s/2, -s/2), (-s/2, +s/2), (-s/2 * factor, +s/2), (-s/2 * factor, +s/2 * (1 - factor)/2), ...
""" # Definition for a Node. class Node: def __init__(self, val = 0, neighbors = None): self.val = val self.neighbors = neighbors if neighbors is not None else [] """ class Solution: def cloneGraph(self, node: 'Node') -> 'Node': if node==None: return None stack = deq...
# -*- coding: utf-8 -*- # .-. .-. .-. . . .-. .-. .-. .-. # |( |- |.| | | |- `-. | `-. # ' ' `-' `-`.`-' `-' `-' ' `-' __title__ = 'requests' __description__ = 'Python HTTP for Humans.' __url__ = 'http://python-requests.org' __version__ = '2.14.2' __build__ = 0x021402 __author__ = 'Kenneth Reitz' __author_emai...
print('Hello World!') #fazendo um print com formatação, variáveis e função. def main(): mensagem = input('Digite a mensagem de apresentação : ') print(f' A mensagem digitada foi : {mensagem} !') main()
newline = "\n" with open("AoC6.txt", 'r') as File1: info = [] for line in File1: if line == "\n": info.append("\n\n") else: info.append(f'''{line.split(newline)[0]}\n''') # print(info) customs = [] customs = "".join(info).split("\n\n") # print(customs) for i in range(le...
sum0 = 0 # If i is divisible by 3 or 5, add to sum for i in range(100): if (i%3 == 0 or i%5==0): sum0 += i # Print answer print('The sum is: ' + str(sum0))
{ 'targets': [ { 'target_name': 'kexec', 'sources': [ 'src/kexec.cc' ], 'defines': [ '<!@(node -v |grep "v4" > /dev/null && echo "__NODE_V4__" || true)', '<!@(node -v |grep "v0.1[12]" > /dev/null && echo "__NODE_V0_11_OR_12__" || true)', '<!@(command -v iojs > /dev/null &...
# Dictionary for TTS main = { "(´・ω・`)":"しょぼん", "改8号機":"かいはちごうき", "禍津御建鳴神命":"まがつみたけなるかみのみこと", "NREV":"ねるふ", "WILLE":"ヴィレ", "EURO":"ゆーろ", "広有射怪鳥事":"ひろありけちょうをいること", "Ура":"うらあ", "EVANGELION":"エヴァンゲリオン" }
class Solution: def chalkReplacer(self, chalk: List[int], k: int) -> int: i = 0 sumchalk = sum(chalk) k = k % sumchalk while k >= 0: k -= chalk[i] i = (i + 1) % len(chalk) return (i + len(chalk) - 1) % len(chalk)
class AMAUtils(): def __init__(self, ws): self.ws = ws def _confirm_ws_type(self, ref): """confirm whether 'ref' is of type 'KBaseMetagenomes.AnnotatedMetagenomeAssembly if not, throw error. """ if ref is None: raise ValueError(" 'ref' argument must be specified.") ...
expected_output = { "instance": { "master": { "areas": { "0.0.0.1": { "interfaces": { "ge-0/0/4.0": { "state": "PtToPt", "dr_id": "10.16.2.1", "bdr_id":...
# Вводятся три разных числа. Найти, какое из них является средним # (Больше одного, но меньше другого) print ("Введите три разных числа") number_1 = float (input ("Введите первое число: ")) number_2 = float (input ("Введите второе число: ")) number_3 = float (input ("Введите третье число: ")) if (number_1 == number_2 o...
""" Given two stings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote. Example 1: Input: ransomNote = "a", magazine = "b" Output: false Example 2: Input: ransomNote = "aa", magazine = "ab" Output: ...
""" https://leetcode.com/problems/binary-tree-inorder-traversal/ Given a binary tree, return the inorder traversal of its nodes' values. Example: Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2] Follow up: Recursive solution is trivial, could you do it iteratively? """ # time complexity: O(n), space...
class TrainData: def __init__(self, batch_size): self.batch_size = batch_size self.train_size = 0 self.validation_size = 0 def next_batch(self): raise NotImplementedError def validation_data(self): # validation data for early stopping of vae training # shoul...
cars = ['bmw', 'audi', 'toyota', 'subaru'] print(cars) print(sorted(cars)) print(cars) cars.sort() print(cars)
print(' ') print('------- Exercício 001 -------') print('Olá Mudo!') print(' ')
"""Tests for coverage-related command line flags under various configs.""" load( "@build_bazel_rules_swift//test/rules:action_command_line_test.bzl", "make_action_command_line_test_rule", ) default_coverage_test = make_action_command_line_test_rule( config_settings = { "//command_line_option:colle...
""" Description: Combines the list of different stopwords files Author: Harshit Varma """ with open("smart_stop_list.txt", "r", encoding = "ascii") as f: ssl = f.readlines() ssl = [w.strip() for w in ssl[1:]] # Skip the first line with open("names.txt", "r", encoding = "ascii") as f: names = f.readlin...
#todo:将数组线段树修改为动态开点线段树 class SegSumTree: ''' 线段树(区间和) 适用场景:区间和 ''' def __init__(self, nums): n = len(nums) self.n = n self.seg = [0] * (n * 4) self.build(nums, 0, 0, n - 1) def build(self, nums, node: int, s: int, e: int): if s == e: self.seg[...
HOST_SORUCE = "ip_of_the_mysql_host" SCHEMA_SORUCE = "world" USER_SORUCE = "root" PASSWORD_SORUCE = "rootpassword" PORT_SORUCE = 6603 HOST_METADATA = "ip_of_the_mysql_host" SCHEMA_METADATA = "demo" USER_METADATA = "demo" PASSWORD_METADATA = "metadata" PORT_METADATA = 6603
class ServiceBase(object): def __init__(self, protocol, ports, flags): self.service_protocol = protocol self.flags = flags self.ports = ports #TODO: check if return path needs to be enabled self.enable_return_path = False @property def IsReturnPathEnabled(self): ...
class Mode: ANY = -1 #used in api to disable mode filtering ALL = ANY STD = 0 TAIKO = 1 CTB = 2 MANIA = 3 OSU = STD CATCHTHEBEAT = CTB LAST = MANIA class Mods: MASK_NM = 0 MASK_NF = 1 << 0 MASK_EZ = 1 << 1 MASK_TD = 1 << 2 MASK_HD = 1 << 3 MASK_HR = 1 << 4 MASK_SD = 1 << 5 MASK_DT = 1 << 6 MASK_RL = ...
# Copyright 2013, 2014 Rackspace # 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 ...
class Session: """ This class is dummy for static analysis. This should be dynamically overridden by sessionmaker(bind=engine). """ def commit(self): pass def rollback(self): pass def close(self): pass
class MyTest: def __init__(self): self.__foo = 1 self.__bar = "hello" def get_foo(self): return self.__foo def get_bar(self): return self.__bar
number = int(input()) first = number%10 variable = number%100 second = variable//10 third = number//100 result = 2*(first*100 + second*10 + third) print(result)
# # PySNMP MIB module PWG-IMAGING-COUNTER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PWG-IMAGING-COUNTER-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:34:17 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 ...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
a = [1, "Hallo", 12.5] print(a) b = range(1, 10, 1) print(b) for i in b: print(i) c = [2, 4, 6, 8] d = [a, c] print(d) # Indizes print(a[1]) print(d[0][1]) # -> "Hallo" print(d[1][2]) # -> 6 c.append(10) print(c)
''' Exercício 2: Soma de matrizes Escreva a função soma_matrizes(m1, m2) que recebe 2 matrizes e devolve uma matriz que represente sua soma caso as matrizes tenham dimensões iguais. Caso contrário, a função deve devolver False. Exemplos: m1 = [[1, 2, 3], [4, 5, 6]] m2 = [[2, 3, 4], [5, 6, 7]] soma_matrizes(m1, m2) =>...
#!/usr/bin/env python3 """Easy statistics The main class `Statistics` just extends dict{str:function}, function here will act on the object of statistics. The values of dict have not to be a function. If it is a string, then the attribute of object will be called. Please see the following example and the function `_...
class Calculator: __result = 1 def __init__(self): pass def add(self, i): self.__result = self.__result + i def subtract(self, i): self.__result = self.__result - i def getResult(self): return self.__result
#!/usr/bin/python """ Truncatable primes https://projecteuler.net/problem=37 """ def ispalindrome(n): return n == n[::-1] def int2bin(n): return "{0:b}".format(n) def main(): total = 0 for i in range(1000000): if ispalindrome(str(i)) and ispalindrome(str(int2bin(i))): total = t...
class FirstClass(object): """docstring for FirstClass""" def setdata(self, value): """just set a value""" self.data = value def display(self): """just show the value""" print("data is {0}".format(self.data)) class SecondClass(FirstClass): """display it differently""" ...
#range new_list = list(range(0,100)) print(new_list) print("\n") #join sentence = "!" new_sentence = sentence.join(["hello","I","am","JoJo"]) print(new_sentence) print("\n") new_sentence = " ".join(["hello","I","am","JoJo"]) print(new_sentence)
pets = { 'dogs': [ { 'name': 'Spot', 'age': 2, 'breed': 'Dalmatian', 'description': 'Spot is an energetic puppy who seeks fun and adventure!', 'url': 'https://content.codecademy.com/programs/flask/introduction-to-flask/dog-spot.jpeg' }, ...
""" Revision Date: 08/10/2018 Author: Bevan Glynn Language: Python 2.7 Style: PEP8 Repo: https://github.com/Bayesian-thought/code-sample Overview: This code demonstrations the use of functions and class structures that return specific elements based on user input and inheritance """ def main(): brand_options = {...
S = input() t = 0 result = 0 for c in S: if c == '…': t += 1 else: t = 0 result = max(result, t) print(result)
def travel(map_size, journey): # 초기 위치 x, y = 1, 1 # 좌표 이동 수치 설정 (L, R, U, D) dx = [0, 0, -1, 1] dy = [-1, 1, 0, 0] # 여정 유형 선언 move_types = ['L', 'R', 'U', 'D'] # 여정 확인 for position in journey: next_x = 0 next_y = 0 # 이동 후 좌표 구하기 for i in range(len...
N = int(input()) phone_book = {} for i in range(N): a = str(input()).split(" ") name = a[0] phone = int(a[1]) phone_book[name] = phone # for j in range(N): while True: try: name = str(input()) if name in phone_book: phone = phone_book[name] print(name + "=" + str(phone)) else: print("Not found") ...
CP_SERVICE_PORT = 5000 LG_SERVICE_URL = "http://127.0.0.1:5001" RM_SERVICE_URL = "http://127.0.0.1:5002" OC_SERVICE_URL = "http://127.0.0.1:5003" LC_SERVICE_URL = "http://127.0.0.1:5004"
def can_access(event, ssm_client, is_header=False) -> bool: store = event["headers"] if is_header else event["queryStringParameters"] request_token = store.get("Authorization") if request_token is None: return False resp = ssm_client.get_parameter(Name="BookmarksPassword", WithDecryption=True) ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: TreeNode) -> bool: # 1st recursive solution def helper(node, lowe...
__auther__ = 'jamfly' def encrypt(text, shift): result = "" for char in text: if char.isalpha(): if char.isupper(): result += chr((ord(char) + shift - 65) % 26 + 65) else: result += chr((ord(char) + shift - 97) % 26 + 97) else: result += char return result def decrypt(t...
registry = [] def register(klass): """Adds the wrapped class to the registry""" registry.append(klass) return klass
APPLICATION_STATUS_CHOICES = ( ('Pending', 'Pending'), ('Accept', 'Accept'), ('Reject', 'Reject'), ) KNOWN_MEASURE_CHOICES = ( ('Years', 'Years'), ('Months', 'Months'), ) REFERENCE_TYPE_CHOICES = ( ('Professional', 'Professional'), ('Academic', 'Academic'), ('Social', 'Social') )
def extractWwwIllanovelsCom(item): ''' Parser for 'www.illanovels.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('my little happiness', 'my little happiness', 'tr...
"""Classes defining the states for the state machine of the flashcards application. """ __all__ = ['State', 'MainMenu', 'AddCard', 'Practice', 'End'] class State: """General state. """ pass class MainMenu(State): """Main menu, asking the user what to do. """ pass class AddCard(State): ...
def dms_to_dd(coordinate): """ coordinate: '40°48′31″N' """ degrees, remainder = coordinate.split("°") if "′" in remainder: minutes, remainder = remainder.split("′") if "″" in remainder: seconds, remainder = remainder.split("″") else: seconds = 0 e...
# Time: O(n) # Space: O(1) # prefix sum, math class Solution(object): def maximumSumScore(self, nums): """ :type nums: List[int] :rtype: int """ prefix = suffix = 0 result = float("-inf") right = len(nums)-1 for left in xrange(len(nums)): ...
__author__ = 'Andy' class DevicePollingProcess(object): def __init__(self, poll_fn, output_queue, kill_event): self.poll_fn = poll_fn self.output_queue = output_queue self.kill_event = kill_event def read(self): while not self.kill_event.is_set(): self.output_queue...
''' This is python implementation of largest rectangle in histogram problem ''' ''' Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. ''' def largestRectangleArea(lst: List[int]) -> int: if len(lst)==0: ...
class Solution: def numJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ return (len(re.split(''.join([str(n)+'|' for n in J]),S))-1)
# Basic data types x = 3 print(type(x)) # Prints "<class 'int'>" print(x) # Prints "3" print(x + 1) # Addition; prints "4" print(x - 1) # Subtraction; prints "2" print(x * 2) # Mul...
''' Created on Nov 2, 2013 @author: peterb ''' TOPIC = "topic" QUEUE = "queue" COUNT = "count" METHOD = "method" OPTIONS = "options" LOG_FORMAT = "[%(levelname)1.1s %(asctime)s %(process)d %(thread)x %(module)s:%(lineno)d] %(message)s"
''' LeetCode Strings Q.415 Add Strings Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. Without using builtin libraries. ''' def addStrings(num1, num2): num1 = num1[::-1] num2 = num2[::-1] def solve(num1, num2): n1 = len(num1) n2 = ...
# # PySNMP MIB module PowerConnect3248-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PowerConnect3248-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:34:29 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
# This script proves that we are allowed to have scripts # with the same name as a built-in site package, e.g. `site.py`. # This script also shows that the module doesn't load until called. print("Super secret script output") # noqa: T001
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 19 14:49:58 2019 @author: thomas """ for a in range(32,48): print(str(a)+' $\leftarrow$ '+chr(a)+' & '+str(a+16)+' $\leftarrow$ '+chr(a+16)+' & ' +str(a+32)+' $\leftarrow$ '+chr(a+32)+' & ' +str(a+48)+' $\leftarrow$ '+chr(a+...