content
stringlengths
7
1.05M
""" ______ __ ____ ____/ / __/ ____ ____ ____ ___ _________ _/ /_____ _____ / __ \/ __ / /_ / __ `/ _ \/ __ \/ _ \/ ___/ __ `/ __/ __ \/ ___/ / /_/ / /_/ / __/ / /_/ / __/ / / / __/ / / /_/ / /_/ /_/ / / / .___/\__,_/_/_____\__, /\___/...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def getMinimumDifference(self, root: TreeNode) -> int: def dfs(root): if not root: return ...
# -*- coding: utf-8 -*- __author__ = 'Andile Jaden Mbele' __email__ = 'andilembele020@gmail.com' __github__ = 'https://github.com/xeroxzen/genuine-fake' __package__ = 'genuine-fake' __version__ = '1.2.20'
""" You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable. You are also given some queries, where queries[j] = [Cj, Dj] represents the jt...
def b2d(number): decimal_number = 0 i = 0 while number > 0: decimal_number += number % 10*(2**i) number = int(number / 10) i += 1 return decimal_number def d2b(number): binary_number = 0 i = 0 while number > 0: binary_number += number % 2*(10**i) nu...
''' 06 - Treating duplicates In the last exercise, you were able to verify that the new update feeding into ride_sharing contains a bug generating both complete and incomplete duplicated rows for some values of the ride_id column, with occasional discrepant values for the user_birth_year and duration colu...
{ "name": """Website login background""", "summary": """Random background image to your taste at the website login page""", "category": "Website", "images": ["images/5.png"], "version": "14.0.1.0.3", "author": "IT-Projects LLC", "support": "help@itpp.dev", "website": "https://twitter.com...
""" This file will host global variables of config strings for the sims. We will only be varying one or two parameters, but we will need to write several copies of the all the parameters we have to specify. I believe this is the easiest way to do that. """ # NOTE with the class python wrapper this one is not necessar...
""" impyute.util.errors """ class BadInputError(Exception): "Error thrown when input args don't match spec" pass
print("Welcome to RollerCoaster") height = int(input("Enter your height in cm : ")) bill = 0 # Comparison operators are used more > , <= , == , > , >= , != if height >= 120 : print("You can ride the RollerCoaster") age = int(input("Enter your age : ")) if age < 12 : bill = 5 print("Childe...
class Revoked(Exception): pass class MintingNotAllowed(Exception): pass
class Time: def __init__(self): self.hours=0 self.minutes=0 self.seconds=0 def input_values(self): self.hours=int(input('Enter the hours: ')) self.minutes=int(input('Enter the minutes: ')) self.seconds=int(input('Enter the seconds: ')) def print_details(self): print(self.hours,':',self.minutes,':',self...
#!/usr/bin/env python # encoding: utf-8 """ __init__.py Creating models for testing. See ticket for more detail. http://code.djangoproject.com/ticket/7835 """
#!/usr/bin/python # -*- coding : utf-8 -*- """ pattern: Factory method: Define an interface for creating an object, but let subclasses decide which class to instantiate.Factory Method lets a class defer instantiation to subclasses. AbstractProduct1 < = > AbstractProduct2 | | ...
# Shape of number 2 using fucntions def for_2(): """ *'s printed in the shape of number 2 """ for row in range(9): for col in range(9): if row ==8 or row+col ==8 and row !=0 or row ==0 and col%8 !=0 or row ==1 and col ==0 or row ==2 and col ==0: print('*',end =' ') ...
""" Ex - 055 - Faça um programa que leia o peso de cinco pessoas. No final, mostre qual foi o maior e o menor pesos lidos.""" # Como eu fiz # Cabeçalho: print(f'{"":=^40}') print(f'{"> MAIOR PESO LIDO <":=^40}') print(f'{"":=^40}') # Var: maior_peso = 0 menor_peso = 1000 # ...
""" You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique. The right interval for an interval i is an interval j such that startj >= endi and startj is minimized. Return an array of right interval indices for each interval i. If no right interval exists for int...
class Solution: def wiggleSort(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ nums.sort() ans = nums[:] for i in range(1, len(nums), 2): nums[i] = ans.pop() for i in range(0, len(nums), 2): ...
PANEL_GROUP = 'default' PANEL_DASHBOARD = 'billing' PANEL = 'billing_invoices' # Python panel class of the PANEL to be added. ADD_PANEL = 'astutedashboard.dashboards.billing.invoices.panel.BillingInvoices'
def isPrime(n): if n <= 1: return False for i in range(2,int(n**.5)+1): if n % i == 0: return False return True def findPrime(n): k=1 for i in range(n): if isPrime(i): if(k>=10001):return i k+=1 print(findPrime(300000))
dict={'A': ['B', 'CB', 'D', 'E', 'F', 'GD', 'H', 'IE'], 'B': ['A', 'C', 'D', 'E', 'F', 'G', 'HE', 'I'], 'C': ['AB', 'GE', 'D', 'E', 'F', 'B', 'H', 'IF'], 'D': ['A', 'B', 'C', 'E', 'FE', 'G', 'H', 'I'], 'E': ['A', 'B', 'C', 'D', 'F', 'G', 'H', 'I'], 'F': ['A', 'B', 'C', 'DE', 'E', 'G',...
test = { 'name': 'q4c', 'points': 10, 'suites': [ { 'cases': [ { 'code': '>>> len(prophet_forecast) == ' '5863\n' 'True', 'hidden': False, ...
def solve_discrete_logarithm(g: int, y: int, m: int) -> int: """find x >= 0 s.t. g^x≡y (mod m) by baby-step giant-step """ if m == 1: return 0 if y == 1: return 0 if g == 0 and y == 0: return 1 sqrt_m = int(pow(m, 0.5) + 100) # Baby-step memo = {} baby = 1 ...
def read_blob(blob, bucket): return bucket.blob(blob).download_as_string().decode("utf-8", errors="ignore") def download_blob(blob, file_obj, bucket): return bucket.blob(blob).download_to_file(file_obj) def write_blob(key, file_obj, bucket): return bucket.blob(key).upload_from_file(file_obj)
''' Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. You may return any answer array that satisfies this condition. Example 1: Input: [3,1,2,4] Output: [2,4,3,1] The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] wo...
# https://www.hackerrank.com/challenges/compare-the-triplets/problem?h_r=internal-search A = input().split() B = input().split() def compare(a, b): alice = 0 bob = 0 x = len(a) for i in range(x): if int(a[i]) > int(b[i]): alice += 1 elif int(a[i]) < int(b[i]): b...
class Attachment: def __init__( self, fallback: str, color: str = None, pretext: str = None, text: str = None, author_name: str = None, author_link: str = None, author_icon: str = None, title: str = None, title_link: str = None, ...
infile = open("sud3_results.csv","r") outfile = open("sud4_results.csv","w") keywords = infile.readline().strip().split(",")[1:] outfile.write("%s, %s" % ("filename", ",".join("Environment+Social+Economic", "Environment+Social+Economic+Cultural", "Environment+Social+Economic+Cultural+Institutional"))) three_pillars_k...
class EnvInfo(object): def __init__(self, frame_id, time_stamp, road_path, obstacle_array): # default params self.frame_id = frame_id self.time_stamp = time_stamp self.road_path = road_path self.obstacle_array = obstacle_array
# Module for implementing gradients used in the autograd system __all__ = ["GradFunc"] def forward_grad(tensor): ## tensor here should be an AutogradTensor or a Tensor where we can set .grad try: grad_fn = tensor.grad_fn except AttributeError: return None # If a tensor doesn't have ...
class KeywordsOnlyMeta(type): def __call__(cls, *args, **kwargs): if args: raise TypeError("Constructor for class {!r} does not accept positional arguments.".format(cls)) return super().__call__(cls, **kwargs) class ConstrainedToKeywords(metaclass=KeywordsOnlyMeta): def __init__...
if __name__ == "__main__": ans = "" for n in range(2, 10): for i in range(1, 10**(9 // n)): s = "".join(str(i * j) for j in range(1, n + 1)) if "".join(sorted(s)) == "123456789": ans = max(s, ans) print(ans)
""" The module identify push-down method refactoring opportunities in Java projects """ # Todo: Implementing a decent push-down method identification algorithm.
COLORS = { 'Black': u'\u001b[30m', 'Red': u'\u001b[31m', 'Green': u'\u001b[32m', 'Yellow': u'\u001b[33m', 'Blue': u'\u001b[34m', 'Magenta': u'\u001b[35m', 'Cyan': u'\u001b[36m', 'White': u'\u001b[37m', 'Reset': u'\u001b[0m', }
def mmc(x, y): if a == 0 or b == 0: return 0 return a * b // mdc(a, b) def mdc(a, b): if b == 0: return a return mdc(b, a % b) a, b = input().split() a, b = int(a), int(b) while a >= 0 and b >= 0: print(mmc(a, b)) a, b = input().split() a, b = int(a), int(b)
# Puzzle Input with open('Day20_Input.txt') as puzzle_input: tiles = puzzle_input.read().split('\n\n') # Parse the tiles: Separate the ID and get the 4 sides: parsed_tiles = [] tiles_IDs = [] for original_tile in tiles: # For every tile: original_tile = original_tile.split('\n') # Spl...
"""Contains the package version number """ __version__ = '0.1.0-dev'
# FLOYD TRIANGLE limit = int(input("Enter the limit: ")) n = 1 for i in range(1, limit+1): for j in range(1, i+1): print(n, ' ', end='') # print on same line n += 1 print('')
# 008: Make a program that reads a value in meter and convert to centimeter and millimeter n = float(input('Write a number in meter: ')) print(f'{n} is: {n*100:.1f}cm and {n*1000:.1f}mm')
def restar(x,y): resta = x-y return resta def multiplicar(x,y): mult = x*y return mult def dividir(x,y): div = x/y return div
if 1: print("1 is ") else: print("???")
print(''' _ _ _ _ _ | || | __ _ _ _ ___ | |_ (_) | |_ | __ | / _` | | '_| (_-< | ' \ | | | _| |_||_| \__,_| |_| /__/ |_||_| |_| \__| ''') print("IP \t Date time \t Request \t") with open("website.log...
sumTotal = 0 nameNum = '' a = 1 b = 2 c = 3 d = 4 e = 5 f = 6 g = 7 h = 8 i = 9 j = 10 k = 11 l = 12 m = 13 n = 14 o = 15 p = 16 q = 17 r = 18 s = 19 t = 20 u = 21 v = 22 w = 23 x = 24 y = 25 z = 26 A = '1' B = '2' C = '3' D = '4' E = '5' F = '6' G = '7' H = '8' I = '9' J = '10' K = '11' L = '12' M = '13' N ...
""" Validate BST: Implement a function to check if a binary tree is a binary search tree. """ # idea: if BST, inorder traversal gives a nondecreasing sorted list class BTNode: def __init__(self, val: int, left=None, right=None): self.val = val self.left: BTNode = left self.righ...
############################################################################ # # Copyright (C) 2016 The Qt Company Ltd. # Contact: https://www.qt.io/licensing/ # # This file is part of Qt Creator. # # Commercial License Usage # Licensees holding valid commercial Qt licenses may use this file in # accordance with the co...
class MessageConfig: """ メッセージの設定 """ class FontColors: """ 標準出力の文字色 """ RED: str = '\033[31m' GREEN: str = '\033[32m' YELLOW: str = '\033[33m' RESET: str = '\033[0m' @classmethod def HOW_TO_START_RECORDING(cls) -> str: return "録...
""" @Author: huuuuusy @GitHub: https://github.com/huuuuusy 系统: Ubuntu 18.04 IDE: VS Code 1.36 工具: python == 3.7.3 """ """ 思路: 双指针 第一个指针负责遍历所有元素,当前元素等于目标值则跳过,不等于目标值则将其复制到第二个指针的位置 然后第二个指针向后移动一位,其最终位置即为非目标元素的个数 结果: 执行用时 : 44 ms, 在所有 Python3 提交中击败了96.19%的用户 内存消耗 : 13.1 MB, 在所有 Python3 提交中击败了67.95%的用户...
#State Codes area_codes = [("Alabama",[205, 251, 256, 334, 659, 938]), ("Alaska",[907]), ("Arizona",[480, 520, 602, 623, 928]), ("Arkansas",[327, 479, 501, 870]), ("California",[209, 213, 310, 323, 341, 369, 408, 415, 424, 442, 510, 530, 559, 562, 619, 626, 627, 628, 650, 657, 661, 669, 707, 714, 747, 760, 764, 805, 81...
#!/usr/bin/python '''the -O turns off the assertions''' def myFunc(a,b,c,d): ''' this is my function with the formula (2*a+b)/(c-d) ''' assert c!=d, "c should not equal d" return (2*a+b)/(c-d) myFunc(1,2,3,3)
# # PySNMP MIB module H3C-IKE-MONITOR-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/H3C-IKE-MONITOR-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:09:27 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
"""Perform any setup needed here. """ __author__ = 'dmontemayor'
print("Hello World") print("Hello again.\n") print("Hello BCC!") print("My name is Andy.\n") print("single 'quotes' <-- in double quotes") print('double "quotes" <-- in single quotes\n') print("Python docs @ --> https://docs/python.org/3") print("Type --> python3 ex1.py <-- in terminal to run this program.\n") # print(...
# # PySNMP MIB module Wellfleet-QOS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-QOS-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:41:23 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
class Solution: """ @param: nums: a list of integers @return: find a majority number """ def majorityNumber(self, nums): # write your code here length = len(nums) for i in range(int(length / 2) + 1): count = 1 for j in range(i + 1, length): ...
def main(): n = int(input('Number to count to: ')) fizzbuzz(n) def fizzbuzz(n): for number in range(1, n + 1): if number % 5 == 0: if number % 3 == 0: print('FizzBuzz') if number % 3 == 0: print('Fizz') elif number % 5 == 0: p...
## setup MQTT MQTT_BROKER = "" # Ip adress of the MQTT Broker MQTT_USERNAME = "" # Username MQTT_PASSWD = "" # Password MQTT_TOPIC = "" # MQTT Topic ## setup RGB NUMBER_OF_LEDS= 100 #int
# Copyright 2021 Nate Gay # # 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, so...
def parseFileTypes(rawTypes): out = [] for rtype in rawTypes: if isinstance(rtype, str): out.append({'name': rtype, 'ext': rtype}) else: assert 'name' in rtype assert 'ext' in rtype out.append({'name': rtype['name'], 'ext': rtype['ext']}) ret...
class Solution(object): def threeConsecutiveOdds(self, arr): """ :type arr: List[int] :rtype: bool """ # Runtime: 32 ms # Memory: 13.4 MB for idx in range(len(arr) - 2): if arr[idx] % 2 == 1 and arr[idx + 1] % 2 == 1 and arr[idx + 2] % 2 == 1: ...
def _syswrite(fh, scalar, length=None, offset=0): """Implementation of perl syswrite""" if length is None and hasattr(scalar, 'len'): length = len(scalar)-offset if isinstance(scalar, str): return os.write(fh.fileno(), scalar[offset:length+offset].encode()) elif isinstance(scalar...
keycode = { 'up': 72, 'down': 80, 'left': 75, 'right': 77, 'P': 25 }
''' Given two strings, determine if they share a common substring. A substring may be as small as one character. For example, the words "a", "and", "art" share the common substring . The words "be" and "cat" do not share a substring. ''' #this has the best runtime out of initial coding varieties def twoStrings(s1,...
class Solution: def numJewelsInStones(self, J: str, S: str) -> int: ans = 0 for i in range(0, len(S)): if(J.find(S[i])!=-1): ans += 1 return ans
# This is an Adventure Game about The Digital Sweet Shop # The program was written by Dr. Aung Win Htut # Date: 04-03-2022 # Green Hackers Online Traing Courses # 0-robot.py, 1-adgame3.py, 2-entershop.py, 3-ifelse2.py, 4-input.py, 5-ad62.py, 6-ad63.py # The next few lines give the introduction # Greetings m...
class Solution(object): def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ counter = 1 for i in range(len(nums)-1): counter -= 1 counter = max(counter,nums[i]) if counter <= 0: return False ...
# @Title: 两两交换链表中的节点 (Swap Nodes in Pairs) # @Author: KivenC # @Date: 2019-01-27 18:19:05 # @Runtime: 44 ms # @Memory: 6.5 MB # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def swapPairs(self, head): ""...
class Solution: def longestPalindrome(self, s: 'str') -> 'str': if len(s) <= 1: return s start = end = 0 length = len(s) for i in range(length): max_len_1 = self.get_max_len(s, i, i + 1) max_len_2 = self.get_max_len(s, i, i) max_len = m...
class Patient: def __init__(self, pathology, gender, weight, height, images): self.pathology = pathology self.gender = gender self.weight = weight self.height = height self.images = images
class Solution(object): def numSpecialEquivGroups(self, A): """ :type A: List[str] :rtype: int """ st = set() for s in A: lstA = [] lstB = [] for i in range(len(s)): if i % 2 == 0: lstA.append(s[i...
def determinant_recursive(A, total=0): # Store indices in list for row referencing indices = list(range(len(A))) # When at 2x2, submatrices recursive calls end if len(A) == 2 and len(A[0]) == 2: val = A[0][0] * A[1][1] - A[1][0] * A[0][1] return val # Define submatrix for ...
__all__ = [ "_is_ltag", "_is_not_ltag", "_is_rtag", "_is_not_rtag", "_is_tag", "_is_not_tag", "_is_ltag_of", "_is_not_ltag_of", "_is_rtag_of", "_is_not_rtag_of", "_is_pair_of", "_is_not_pair_of", "_is_not_ltag_and_not_rtag_of" ] #### def _is_ltag(tag,tag_pairs): ...
int_const = 5 bool_const = True string_const = 'abc' unicode_const = u'abc' float_const = 1.23
class Foo: """docstring""" @property def prop1(self) -> int: """docstring""" @classmethod @property def prop2(self) -> int: """docstring"""
a, b = input().split() new_a = '' new_b = '' new_a += a[2] new_a += a[1] new_a += a[0] new_b += b[2] new_b += b[1] new_b += b[0] if int(new_a) > int(new_b): print(int(new_a)) else: print(int(new_b)) # 거꾸로 뒤집기 # print(a[::-1]) # print("".join(reversed(a)))
# 面试题 17.10. 主要元素 # 数组中占比超过一半的元素称之为主要元素。给你一个 整数 数组,找出其中的主要元素。若没有,返回 -1 。请设计时间复杂度为 O(N) 、空间复杂度为 O(1) 的解决方案。 # 示例 1: # 输入:[1,2,5,9,5,9,5,5,5] # 输出:5 # 示例 2: # 输入:[3,2] # 输出:-1 # 示例 3: # 输入:[2,2,1,1,1,2,2] # 输出:2 # 通过次数56,453提交次数99,866 def majorityElement(nums): candidate = -1 count = 0 for num in nu...
#Даны цифры двух десятичных целых чисел: трехзначного и двузначного , где а1 и в1 – число единиц, а2 и в2 – число десятков,а3 – число сотен. Получить цифры числа, равного сумме заданных чисел (известно, что это число трехзначное). Числа-слагаемые и число-результат не определять; условный оператор не использовать. a1 = ...
''' https://practice.geeksforgeeks.org/problems/subarray-with-given-sum/0/?ref=self Given an unsorted array of non-negative integers, find a continuous sub-array which adds to a given number. Input: The first line of input contains an integer T denoting the number of test cases. Then T test ...
""" Given a string, compute recursively (no loops) the number of lowercase 'x' chars in the string. countX("xxhixx") → 4 countX("xhixhix") → 3 countX("hi") → 0 """ def countX_for(s): if len(s): for i in range (0, len(s)): if s[i] == 'x': return 1 + countX(s[i + 1:]) r...
class Solution(object): def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ return n > 0 and not (n & (n - 1)) class Solution2(object): def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ ...
messageResources = {} messageResources['it'] = { 'browse':'Sfoglia', 'play':'Play', 'open.file':'Apri file', 'file':'File', 'edit':'Modifica', 'audio':'Audio', 'video':'Video', 'open':'Apri...', 'quit':'Esci', 'clear.file.list':'Cancella la lista dei file', 'output.audio':'Uscita audio...
def simple(request): return { 'simple': { 'boolean': True, 'list': [1, 2, 3], } } def is_authenticated(request): is_authenticated = request.user and request.user.is_authenticated if callable(is_authenticated): is_authenticated = is_authenticated() r...
class Pessoa: olhos = 2 def __init__(self, *filhos, nome=None, idade=35): self.idade = idade self.nome = nome self.filhos = list(filhos) def cumprimentar(self): return f'Olá {id(self)}' @staticmethod def metodo_estatico(): return 42 @classmethod de...
class Generating: def __init__(self, node): self._node = node def generatetoaddress(self, nblocks, address, maxtries=1): # 01 return self._node._rpc.call("generatetoaddress", nblocks, address, maxtries)
"""Tools """ def _create_dirtree(a,chunksize=2): """create a directory tree from a single, long name e.g. "12345" --> ["1", "23", "45"] """ b = a[::-1] # reverse i = 0 l = [] while i < len(b): l.append(b[i:i+chunksize]) i += chunksize return [e[::-1] for e in l[::-1]] ...
"""Project metadata.""" package = "humilis_secrets_vault" project = "humilis-secrets-vault" version = '0.2.4' description = "Humilis layer that deploys a secrets vault" authors = ["German Gomez-Herrero"] authors_string = ', '.join(authors) emails = ["german@findhotel.net"] license = "MIT" copyright = "2016 FindHotel B...
## # \namespace cross3d.classes.valuerange # # \remarks This module holds the ValueRange class to handle value ranges. # # \author douglas # \author Blur Studio # \date 02/17/16 # #----------------------------------------------------------------------------------------------------...
def draw_line(tick_length, tick_label=''): """Draw one line with given tick length (followed by optional label)""" line = '-' * tick_length if tick_label: line += ' ' + tick_label print(line) def draw_interval(center_length): """Draw tick interval based upon a central tick len...
# -*- coding: utf-8 -*- """Top-level package for ebr-trackerbot.""" __project__ = "ebr-trackerbot" __author__ = "Milan Hradil" __email__ = "milan.hradil@tomtom.com" __version__ = "0.1.5-dev"
# -*- coding: utf-8 -*- """ Created on Sat Oct 12 01:33:53 2019 @author: Caio """ #Taxa Selic taxaselic=(5.5/36500) # ( 5.5/100 ) 365 para transformar de ano para dia #Tabela regressiva do IR IR1=22.5/100 IR2=20/100 IR3=17.5/100 IR4=15/100 IOF=1 Valoraplicado=float(input('Insira o valor aplicado')) ...
n_h1=100 n_h2=100 n_h3=100 batch_size=20
class URI: prefix = { 'dbpedia': 'http://dbpedia.org/page/', 'dbr': 'http://dbpedia.org/resource/', 'dbo': 'http://dbpedia.org/ontology/', 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', 'xsd': 'http://www.w3.org/2001/XMLSchema#', 'dt': 'http://dbpedia.org/datatype/'...
class Solution: def myPow(self, x: float, n: int) -> float: if n < 0: val = 1 / self._myPow(x, -n) else: val = self._myPow(x, n) return val def _myPow(self, x: float, n: int) -> float: if n == 1: return x if n == 0: return ...
#1. Idea is we use a stack, where each element in the stack is a list, the list contains the current string and current repeat value, we know it is the current string because we have not yet hit a closed bracket because once we hit the closed bracket we pop off. #2. Initialize a stack which contains an empty string an...
T = int(input()) for _ in range(T): h = 1 for i in range(int(input())): if i % 2 == 0: h *= 2 else: h += 1 print(h)
class Queue(object): def __init__(self): self.queue = [] self.size = 0 def isEmpty(self): return self.queue == [] def enqueue(self, item): self.queue.insert(0, item) self.size += 1 def dequeu(self): if not self.isEmpty(): self.size -= 1 ...
class HttpListenerTimeoutManager(object): # no doc def ZZZ(self): """hardcoded/mock instance of the class""" return HttpListenerTimeoutManager() instance=ZZZ() """hardcoded/returns an instance of the class""" DrainEntityBody=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get:...
#!/usr/bin/env python ord_numbers = [] for i in range(1,50): ord_numbers.append(i) print(ord_numbers) for j in ord_numbers: if j == 13: continue elif j > 39: break else: print(j)
doc(title="PaddlePaddle Use-Cases", underline_char="=", entries=[ "resnet50/paddle-resnet50.rst", "ssd/paddle-ssd.rst", "tsm/paddle-tsm.rst", ])
def generate_worklist(n, n_process, generate_mode="random", time_weights=None): works_type = {} works = [] if generate_mode == "random": minimum_time = 10 maximum_time = 300 reset_time_weights_prob = 0.05 time_weights = [random.randint(minimum_time, maximum_time) for i in range(n_process)] type_name = ti...
class Node: def __init__(self, item): self.item = item self.left = None self.right = None class BinaryTree: def __init__(self, root): self.root = root def insert(self, root, node): if node.item < root.item: i...