content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# TODO: *3 @task def setupNetwork(ifaces): interfaces = '''auto lo iface lo inet loopback ''' for iface, config in ifaces.items(): interfaces += ''' auto %s iface %s inet static address %s netmask %s ''' % (iface, iface, config[0], config[1]) if iface == 'eth1': interfaces ...
@task def setup_network(ifaces): interfaces = 'auto lo\niface lo inet loopback\n' for (iface, config) in ifaces.items(): interfaces += '\nauto %s\niface %s inet static\n address %s\n netmask %s\n' % (iface, iface, config[0], config[1]) if iface == 'eth1': interfaces += ' gat...
OCTICON_SHARE = """ <svg class="octicon octicon-share" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M7.823.177L4.927 3.073a.25.25 0 00.177.427H7.25v5.75a.75.75 0 001.5 0V3.5h2.146a.25.25 0 00.177-.427L8.177.177a.25.25 0 00-.354 0zM3.75 6.5a.25.25 0 00-.25.2...
octicon_share = '\n<svg class="octicon octicon-share" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M7.823.177L4.927 3.073a.25.25 0 00.177.427H7.25v5.75a.75.75 0 001.5 0V3.5h2.146a.25.25 0 00.177-.427L8.177.177a.25.25 0 00-.354 0zM3.75 6.5a.25.25 0 00-.25.25v...
#pylint: disable=invalid-name,missing-docstring # Basic test with a list TEST_LIST1 = ['a' 'b'] # [implicit-str-concat] # Testing with unicode strings in a tuple, with a comma AFTER concatenation TEST_LIST2 = (u"a" u"b", u"c") # [implicit-str-concat] # Testing with raw strings in a set, with a comma BEFORE concatena...
test_list1 = ['ab'] test_list2 = (u'ab', u'c') test_list3 = {'a', 'bc'} test_list4 = ['a', 'bc', 'd'] print('a', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbccc') test_list5 = ('a', 'bc') test_list6 = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb ccc' test_list7 = 'abbbbbbbb...
class LexpyError(Exception): pass class InvalidWildCardExpressionError(LexpyError): def __init__(self, expr, message): self.expr = expr self.message = message def __str__(self): return repr(': '.join([self.message, self.expr]))
class Lexpyerror(Exception): pass class Invalidwildcardexpressionerror(LexpyError): def __init__(self, expr, message): self.expr = expr self.message = message def __str__(self): return repr(': '.join([self.message, self.expr]))
# Python program to create a bytearray from a list nums = [10, 20, 56, 35, 17, 99] values = bytearray(nums) for x in values: print(x)
nums = [10, 20, 56, 35, 17, 99] values = bytearray(nums) for x in values: print(x)
#!/usr/bin/env python3 x = 0 y = (-1/4)*(x-1)+3 print(y)
x = 0 y = -1 / 4 * (x - 1) + 3 print(y)
"""Constants for Camera component.""" DOMAIN = "camera" DATA_CAMERA_PREFS = "camera_prefs" PREF_PRELOAD_STREAM = "preload_stream"
"""Constants for Camera component.""" domain = 'camera' data_camera_prefs = 'camera_prefs' pref_preload_stream = 'preload_stream'
#!/usr/bin/env python """ Problem 38 daily-coding-problem.com """ def n_queens(n, board=[]): ''' see https://www.dailycodingproblem.com/blog/an-introduction-to-backtracking/''' if n == len(board): return 1 count = 0 for col in range(n): board.append(col) if is_valid(board): ...
""" Problem 38 daily-coding-problem.com """ def n_queens(n, board=[]): """ see https://www.dailycodingproblem.com/blog/an-introduction-to-backtracking/""" if n == len(board): return 1 count = 0 for col in range(n): board.append(col) if is_valid(board): count += n_que...
class American(object): pass class NewYorker(American): pass anAmerican = American() aNewYorker = NewYorker()
class American(object): pass class Newyorker(American): pass an_american = american() a_new_yorker = new_yorker()
# [7 kyu] Descending Order # # Author: Hsins # Date: 2019/12/31 def descending_order(num): return int("".join(sorted(str(num), reverse=True)))
def descending_order(num): return int(''.join(sorted(str(num), reverse=True)))
def minimum_bracket_reversals(input_string): if len(input_string) % 2 == 1: return -1 stack = Stack() count = 0 for bracket in input_string: if stack.is_empty(): stack.push(bracket) else: top = stack.top() if top != bracket: if...
def minimum_bracket_reversals(input_string): if len(input_string) % 2 == 1: return -1 stack = stack() count = 0 for bracket in input_string: if stack.is_empty(): stack.push(bracket) else: top = stack.top() if top != bracket: if ...
# -*- coding: utf-8 -*- """ 460. LFU Cache Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the following operations: get and set. """ class LFUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.capacity = ca...
""" 460. LFU Cache Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the following operations: get and set. """ class Lfucache(object): def __init__(self, capacity): """ :type capacity: int """ self.capacity = capacity def get(self...
def intercalaEmOrdem(lista1, lista2): intercalada = [] lista1.sort() lista2.sort() while len(lista1) > 0 and len(lista2) > 0: if lista1[0] < lista2[0]: intercalada.append(lista1.pop(0)) else: intercalada.append(lista2.pop(0)) if len(lista1) > 0: inte...
def intercala_em_ordem(lista1, lista2): intercalada = [] lista1.sort() lista2.sort() while len(lista1) > 0 and len(lista2) > 0: if lista1[0] < lista2[0]: intercalada.append(lista1.pop(0)) else: intercalada.append(lista2.pop(0)) if len(lista1) > 0: inte...
def f2(a): global b print(a) print(b) b = 9 print(b) b = 5 f2(3)
def f2(a): global b print(a) print(b) b = 9 print(b) b = 5 f2(3)
# # PySNMP MIB module CPQCLUSTER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CPQCLUSTER-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:27:15 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_union, constraints_intersection, single_value_constraint, value_range_constraint) ...
#!/usr/bin/env python f = open('/Users/kosta/dev/advent-of-code-17/day10/input.txt') lengths = list(map(int, f.readline().split(','))) hash_list = list(range(256)) skip = 0 cur_index = 0 for length in lengths: if cur_index + length > len(hash_list): sub_list = hash_list[cur_index:] sub_list.exten...
f = open('/Users/kosta/dev/advent-of-code-17/day10/input.txt') lengths = list(map(int, f.readline().split(','))) hash_list = list(range(256)) skip = 0 cur_index = 0 for length in lengths: if cur_index + length > len(hash_list): sub_list = hash_list[cur_index:] sub_list.extend(hash_list[:cur_index + ...
def softmax(x): t = np.exp(x) return t/t.sum() q_relu = softmax(C @ relu(A @ x + b) + d) q_sigmoid = softmax(C @ sigmoid(A @ x + b) + d)
def softmax(x): t = np.exp(x) return t / t.sum() q_relu = softmax(C @ relu(A @ x + b) + d) q_sigmoid = softmax(C @ sigmoid(A @ x + b) + d)
"""Image-to-text implementation based on http://arxiv.org/abs/1411.4555. "Show and Tell: A Neural Image Caption Generator" Oriol Vinyals, Alexander Toshev, Samy Bengio, Dumitru Erhan """ class ShowAndTellModel(object): """Image-to-text implementation based on http://arxiv.org/abs/1411.4555. "Show and Tell: A Neural ...
"""Image-to-text implementation based on http://arxiv.org/abs/1411.4555. "Show and Tell: A Neural Image Caption Generator" Oriol Vinyals, Alexander Toshev, Samy Bengio, Dumitru Erhan """ class Showandtellmodel(object): """Image-to-text implementation based on http://arxiv.org/abs/1411.4555. "Show and Tell: A Neu...
# Filters and the expression register are two really cool ways of calling arbitrary code from vim. # Filters are just anything that takes your text via stdin and gives you something via stdout # Filters can be invoked via `!{motion}` or `!` while selecting, and can call arbitrary scripts # Examples with either `!}` or...
"""The quick brown fox jumps over the lazy dog""" 'The quick brown fox jumps over the lazy dog' 'The quick brown fox jumps over the lazy cat' 'The quick brown fox jumps over the lazy dog'
#encoding:utf-8 subreddit = 'india' t_channel = '@r_indiaa' def send_post(submission, r2t): return r2t.send_simple(submission)
subreddit = 'india' t_channel = '@r_indiaa' def send_post(submission, r2t): return r2t.send_simple(submission)
""" Problem: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. Implementation: An initial solution might check for all three cases s...
""" Problem: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. Implementation: An initial solution might check for all three cases s...
microcode = ''' def macroop VCVTSD2SS_XMM_XMM { cvtf2f xmm0, xmm0m, destSize=4, srcSize=8, ext=Scalar movfph2h xmm0, xmm0v, dataSize=4 movfp xmm1, xmm1v, dataSize=8 vclear dest=xmm2, destVL=16 }; def macroop VCVTSD2SS_XMM_M { ldfp ufp1, seg, sib, disp, dataSize=8 cvtf2f xmm0, ufp1, destSize=4...
microcode = '\n\ndef macroop VCVTSD2SS_XMM_XMM {\n cvtf2f xmm0, xmm0m, destSize=4, srcSize=8, ext=Scalar\n movfph2h xmm0, xmm0v, dataSize=4\n movfp xmm1, xmm1v, dataSize=8\n vclear dest=xmm2, destVL=16\n};\n\ndef macroop VCVTSD2SS_XMM_M {\n ldfp ufp1, seg, sib, disp, dataSize=8\n cvtf2f xmm0, ufp1, d...
# --- Day 2: I Was Told There Would Be No Math --- def createLineList(input): lineList = [line.rstrip('\r\n') for line in open(input)] return lineList def createDimList(lines): dimList = [] for L in lines: dim = L.split("x") for i in range(0, len(dim)): dim[i] = int(dim[i]) dimList.append(dim) return di...
def create_line_list(input): line_list = [line.rstrip('\r\n') for line in open(input)] return lineList def create_dim_list(lines): dim_list = [] for l in lines: dim = L.split('x') for i in range(0, len(dim)): dim[i] = int(dim[i]) dimList.append(dim) return dimLis...
""" Problem: Write a function that returns the bitwise AND of all integers between M and N, inclusive. """ def bitwise_and_on_range(start: int, end: int) -> int: # using naive approach result = start for num in range(start + 1, end + 1): result = result & num return result if __name__ == "_...
""" Problem: Write a function that returns the bitwise AND of all integers between M and N, inclusive. """ def bitwise_and_on_range(start: int, end: int) -> int: result = start for num in range(start + 1, end + 1): result = result & num return result if __name__ == '__main__': print(bitwise_an...
__author__ = 'burakks41' line1 = input().split() line2 = input().split() flowers = int(line1[0]) persons = int(line1[1]) person = [0] * persons flowers_cost = sorted([int(n) for n in line2],reverse=True) sum = 0 for i in range(flowers): x, person[i % persons] = person[i % persons], person[i % persons] + 1 su...
__author__ = 'burakks41' line1 = input().split() line2 = input().split() flowers = int(line1[0]) persons = int(line1[1]) person = [0] * persons flowers_cost = sorted([int(n) for n in line2], reverse=True) sum = 0 for i in range(flowers): (x, person[i % persons]) = (person[i % persons], person[i % persons] + 1) ...
# You are given an array of non-negative integers numbers. You are allowed to choose any number from this array and swap any two digits in it. If after the swap operation the number contains leading zeros, they can be omitted and not considered (eg: 010 will be considered just 10). # Your task is to check whether it...
def compare(arr1, arr2): store = [] for i in range(len(arr1)): if arr1[i] != arr2[i]: store.append(i) return store def get_options(str): store = [] for i in range(len(str) - 1): store.append(int(str[i + 1:] + str[:i + 1])) return store def check(i, arr): curr = ...
def balanced_split_exists(arr): if len(arr) < 2 or sum(arr) % 2 != 0: return False arr.sort() # n log n l, r = 0, len(arr) - 1 left_sum, right_sum = arr[l], arr[r] while l <= r: if arr[l] >= arr[r]: return False if left_sum < right_sum: l += 1 ...
def balanced_split_exists(arr): if len(arr) < 2 or sum(arr) % 2 != 0: return False arr.sort() (l, r) = (0, len(arr) - 1) (left_sum, right_sum) = (arr[l], arr[r]) while l <= r: if arr[l] >= arr[r]: return False if left_sum < right_sum: l += 1 ...
def get_hours_since_midnight(total_seconds): hours = total_seconds // 3600 return hours total_seconds = int(input('Enter a number of seconds: ')) hours = get_hours_since_midnight(total_seconds) format(hours,'02d') def get_minutes(total_seconds): minutes = ( total_seconds % 3600) minutes //= 60 re...
def get_hours_since_midnight(total_seconds): hours = total_seconds // 3600 return hours total_seconds = int(input('Enter a number of seconds: ')) hours = get_hours_since_midnight(total_seconds) format(hours, '02d') def get_minutes(total_seconds): minutes = total_seconds % 3600 minutes //= 60 return...
# Copyright (C) 2018-present ichenq@outlook.com. All rights reserved. # Distributed under the terms and conditions of the Apache License. # See accompanying files LICENSE. CSHARP_MANAGER_TEMPLATE = """ public class %s { public const char TABUGEN_CSV_SEP = '%s'; // CSV field delimiter public con...
csharp_manager_template = '\npublic class %s \n{ \n public const char TABUGEN_CSV_SEP = \'%s\'; // CSV field delimiter\n public const char TABUGEN_CSV_QUOTE = \'"\'; // CSV field quote\n public const char TABUGEN_ARRAY_DELIM = \'%s\'; // array item delimiter\n public const char T...
brd = { 'name': ('Raspberry Pi B+/2'), 'port': { 'rpigpio': { 'gpio' : { # BCM/Functional RPi pin names. 'bcm2_sda' : '3', 'bcm3_scl' : '5', 'bcm4_gpclk0': '7', 'bcm17' : '11', ...
brd = {'name': 'Raspberry Pi B+/2', 'port': {'rpigpio': {'gpio': {'bcm2_sda': '3', 'bcm3_scl': '5', 'bcm4_gpclk0': '7', 'bcm17': '11', 'bcm27_pcm_d': '13', 'bcm22': '15', 'bcm10_mosi': '19', 'bcm9_miso': '21', 'bcm11_sclk': '23', 'bcm5': '29', 'bcm6': '31', 'bcm13': '33', 'bcm19_miso': '35', 'bcm26': '37', 'bcm21_sclk'...
n = int(input()) X = list(map(int, input().split())) X.sort() def median(n, X): if n % 2 == 0: numerator = X[int(n / 2)] + X[int(n / 2 - 1)] median_value = numerator / 2 else: median_value = X[int(n / 2)] return int(median_value) print(median(int(n / 2), X[: int(n / 2)])) prin...
n = int(input()) x = list(map(int, input().split())) X.sort() def median(n, X): if n % 2 == 0: numerator = X[int(n / 2)] + X[int(n / 2 - 1)] median_value = numerator / 2 else: median_value = X[int(n / 2)] return int(median_value) print(median(int(n / 2), X[:int(n / 2)])) print(media...
{ 'includes': [ '../common.gyp' ], 'targets': [ { 'target_name': 'libzxing', 'type': 'static_library', 'include_dirs': [ 'core/src', ], 'sources': [ 'core/src/bigint/BigInteger.cc', 'core/src/bigint/BigIntegerAlgorithms.cc', 'core/src/bigint/BigInteg...
{'includes': ['../common.gyp'], 'targets': [{'target_name': 'libzxing', 'type': 'static_library', 'include_dirs': ['core/src'], 'sources': ['core/src/bigint/BigInteger.cc', 'core/src/bigint/BigIntegerAlgorithms.cc', 'core/src/bigint/BigIntegerUtils.cc', 'core/src/bigint/BigUnsigned.cc', 'core/src/bigint/BigUnsignedInAB...
# -*- coding: utf-8 -*- """ Created on Tue Feb 1 10:11:25 2022 @author: User """ # contadore de 1 en 1 cont = 0 cont +=1 #--> cont= cont + 1 # 1.- contar numero del 1 al 10 y mostrar en la pantalla while cont < 10: cont = cont + 1 print(cont) # 2.- Sumar los numeros del 1 al 10 # list = {1,2,3,.....
""" Created on Tue Feb 1 10:11:25 2022 @author: User """ cont = 0 cont += 1 while cont < 10: cont = cont + 1 print(cont) sum = 0 for num in range(1, 11): sum = sum + num print(f'La suma total del 1 al 10 es: {sum}') mult = 1 for num in range(1, 11): mult = mult * num print(f'la multiplicacion es: {mul...
# -------------- # Code starts here class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes'] new_class = (class_1 + class_2) print (new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_c...
class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) courses = {'Math': 65, 'English...
def increment(x, by=1): return x + by def tokenize(sentence): return pos_tag(word_tokenize(sentence)) def synsets(sentence): tokens = tokenize(sentence) return remove_none(tagged_to_synset(*t) for t in tokens) def remove_none(xs): return [x for x in xs if x is not None] def score(synset, syn...
def increment(x, by=1): return x + by def tokenize(sentence): return pos_tag(word_tokenize(sentence)) def synsets(sentence): tokens = tokenize(sentence) return remove_none((tagged_to_synset(*t) for t in tokens)) def remove_none(xs): return [x for x in xs if x is not None] def score(synset, synse...
class Solution(object): def bruteforce(self, strs): """ :type strs: List[str] :rtype: str """ result = '' if len(strs) == 0: return '' i = 0 d = {i: len(v) for i,v in enumerate(strs)} count = min(d.values()) for i i...
class Solution(object): def bruteforce(self, strs): """ :type strs: List[str] :rtype: str """ result = '' if len(strs) == 0: return '' i = 0 d = {i: len(v) for (i, v) in enumerate(strs)} count = min(d.values()) for i in ran...
s1 = input() s2 = input() pairs = set() for i in range(len(s2) - 1): pairs.add(s2[i:i + 2]) ans = 0 for i in range(len(s1) - 1): if s1[i: i + 2] in pairs: ans += 1 print(ans)
s1 = input() s2 = input() pairs = set() for i in range(len(s2) - 1): pairs.add(s2[i:i + 2]) ans = 0 for i in range(len(s1) - 1): if s1[i:i + 2] in pairs: ans += 1 print(ans)
# makes a BST from an array class Node: def __init__(self, value, left, right): self.value = value self.left = left self.right = right def bst_from_array(array, start, end): if start >= end: return None mid = (start + end) // 2 value = array[mid] left = bst_from_arra...
class Node: def __init__(self, value, left, right): self.value = value self.left = left self.right = right def bst_from_array(array, start, end): if start >= end: return None mid = (start + end) // 2 value = array[mid] left = bst_from_array(array, start, mid) ri...
# Author: Tianyao (Till) Chen # Email: tillchen417@gmail.com # File: settings.py class Settings: """The class to store all the settings for Alien Invasion.""" def __init__(self): """Initialize the static settings.""" # Screen settings. self.screen_width = 1200 self.screen_height...
class Settings: """The class to store all the settings for Alien Invasion.""" def __init__(self): """Initialize the static settings.""" self.screen_width = 1200 self.screen_height = 800 self.bg_color = (230, 230, 230) self.ship_limit = 3 self.bullet_width = 3 ...
''' Created on 24.05.2011 @author: Sergey Khayrulin ''' class Position(object): ''' Definition for position of point ''' def __init__(self,proximal_point=None,distal_point=None): ''' Constructor ''' self.distal_point = distal_point self.pr...
""" Created on 24.05.2011 @author: Sergey Khayrulin """ class Position(object): """ Definition for position of point """ def __init__(self, proximal_point=None, distal_point=None): """ Constructor """ self.distal_point = distal_point self.proximal_point = prox...
sum_counter = 0 # 600851475143 number = 600851475143 for i in range(2, 10000): for j in range(1, i + 1): if i % j == 0: sum_counter += 1 if sum_counter == 2: # print(i, end= " ") if number % i == 0: print() print(f"prime factors for {number} : {i}", ...
sum_counter = 0 number = 600851475143 for i in range(2, 10000): for j in range(1, i + 1): if i % j == 0: sum_counter += 1 if sum_counter == 2: if number % i == 0: print() print(f'prime factors for {number} : {i}', end=' ') print() sum_counter =...
class MemoryItem: def __init__(self, observation, action, next_observation, reward, done, info): self.observation = observation self.action = action self.next_observation = next_observation self.reward = reward self.done = done self.info = info
class Memoryitem: def __init__(self, observation, action, next_observation, reward, done, info): self.observation = observation self.action = action self.next_observation = next_observation self.reward = reward self.done = done self.info = info
class Queen: def __init__(self, pos, visited): self.pos = pos self.visited = visited
class Queen: def __init__(self, pos, visited): self.pos = pos self.visited = visited
VALID_USER = { "username": "Test", "email": "test@email.com", "password": "Test@123", "password2": "Test@123", }
valid_user = {'username': 'Test', 'email': 'test@email.com', 'password': 'Test@123', 'password2': 'Test@123'}
class Solution: def minJumps(self, arr, n): jumps = [-1] * n jumps[0] = 0 front = 0 rear = 0 while rear < n : remaining_jumps = arr[rear] - (front - rear) while remaining_jumps > 0 and front < n-1: front += 1 j...
class Solution: def min_jumps(self, arr, n): jumps = [-1] * n jumps[0] = 0 front = 0 rear = 0 while rear < n: remaining_jumps = arr[rear] - (front - rear) while remaining_jumps > 0 and front < n - 1: front += 1 j = jump...
# # Copyright (c) 2013-2014, PagerDuty, Inc. <info@pagerduty.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notic...
class Mockqueue: def __init__(self, event=None, status=None, detailed_snapshot=None, cleanup_age_secs=None): self.event = event self.status = status self.expected_detailed_snapshot = detailed_snapshot self.expected_cleanup_age = cleanup_age_secs self.consume_code = None ...
# 3. File Writer # Create a program that creates a file called my_first_file.txt. # In that file write a single line with the content: 'I just created my first file!' # file = open("my_first_file.txt", "w") # # file.write('I just created my first file!') # # file.close() # With manager is better than just open as it ...
with open('my_first_file.txt', 'w') as file: file.write('I just created my first file!')
# 4-5. Summing a Million: Make a list of the numbers from one to one million, and then use min() and max() # to make sure your list actually starts at one and ends at one million. # Also, use the sum() function to see how quickly Python can add a million numbers. numbers = list(range(1, 1000001)) print(min(numbers)) ...
numbers = list(range(1, 1000001)) print(min(numbers)) print(max(numbers)) print(sum(numbers))
def print_formatted(number): # your code goes here if number in range (1,100): l = len(bin(number)[2:]) for i in range (1,n+1): decimal = str(i).rjust(l) octal = str(oct(i)[2:]).rjust(l) hexadecimal = hex(i)[2:].rjust(l) binary = bin(i)[2:].rjust(l...
def print_formatted(number): if number in range(1, 100): l = len(bin(number)[2:]) for i in range(1, n + 1): decimal = str(i).rjust(l) octal = str(oct(i)[2:]).rjust(l) hexadecimal = hex(i)[2:].rjust(l) binary = bin(i)[2:].rjust(l) print(deci...
def get_city_year(p0, perc, delta, p): years = 1 curr = p0 + p0 * (0.01 * perc) + delta if curr <= p0: # remember == would imply stagnation return -1 else: while curr < p: curr = curr + curr * (0.01 * perc) + delta years += 1 return years print(get_cit...
def get_city_year(p0, perc, delta, p): years = 1 curr = p0 + p0 * (0.01 * perc) + delta if curr <= p0: return -1 else: while curr < p: curr = curr + curr * (0.01 * perc) + delta years += 1 return years print(get_city_year(1000, 2, -50, 5000)) print(get_cit...
#First Example - uncomment lines or change values to test the code phone_balance = 7.62 bank_balance = 104.39 #phone_balance = 12.34 #bank_balance = 25 if phone_balance < 10: phone_balance += 10 bank_balance -= 10 print(phone_balance) print(bank_balance) #Second Example #change the number to experiment! numbe...
phone_balance = 7.62 bank_balance = 104.39 if phone_balance < 10: phone_balance += 10 bank_balance -= 10 print(phone_balance) print(bank_balance) number = 145346334 if number % 2 == 0: print('The number ' + str(number) + ' is even.') else: print('The number ' + str(number) + ' is odd.') age = 35 free_up...
print('pypypy') print('pypypy111') print('pycharm1111') print('pycharm222') print('pypypy222') print('pycharm3333') print('pypypy333') hheheheh # zuishuaidezishi ssshhhhhhh
print('pypypy') print('pypypy111') print('pycharm1111') print('pycharm222') print('pypypy222') print('pycharm3333') print('pypypy333') hheheheh ssshhhhhhh
# Design # a # stack # that # supports # push, pop, top, and retrieving # the # minimum # element in constant # time. # # Implement # the # MinStack # # # class: # # # MinStack() # initializes # the # stack # object. # void # push(int # val) pushes # the # element # val # onto # the # stack. # void # pop() # removes # ...
class Minstack: def __init__(self): self.stack = [] def push(self, val: int) -> None: self.stack.append(val) def pop(self) -> None: if len(self.stack) > 0: self.stack.pop() def top(self) -> int: if len(self.stack) > 0: return self.stack[-1] ...
def baseline_opt_default_args(prob_type): defaults = {} defaults['simpleVar'] = 100 defaults['simpleIneq'] = 50 defaults['simpleEq'] = 50 defaults['simpleEx'] = 10000 defaults['nonconvexVar'] = 100 defaults['nonconvexIneq'] = 50 defaults['nonconvexEq'] = 50 defaults['nonconvexEx'] = ...
def baseline_opt_default_args(prob_type): defaults = {} defaults['simpleVar'] = 100 defaults['simpleIneq'] = 50 defaults['simpleEq'] = 50 defaults['simpleEx'] = 10000 defaults['nonconvexVar'] = 100 defaults['nonconvexIneq'] = 50 defaults['nonconvexEq'] = 50 defaults['nonconvexEx'] = ...
class S1C1(): @staticmethod def ret_true(): return True @staticmethod def hex_to_base64(hx): return "x"
class S1C1: @staticmethod def ret_true(): return True @staticmethod def hex_to_base64(hx): return 'x'
def get_client_ip(request): 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') return ip def calc_hba1c(value): """ Calculate the HbA1c from the given average blood glucose...
def get_client_ip(request): 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') return ip def calc_hba1c(value): """ Calculate the HbA1c from the given average blood glucose ...
s = input() answer = len(s) k = s.count('a') for i in range(len(s)): cnt = 0 for j in range(k): if s[(i+j)%len(s)] == 'b': cnt+=1 if cnt < answer: answer = cnt print(answer)
s = input() answer = len(s) k = s.count('a') for i in range(len(s)): cnt = 0 for j in range(k): if s[(i + j) % len(s)] == 'b': cnt += 1 if cnt < answer: answer = cnt print(answer)
def math(): i_put = input() if len(i_put) <= 140: print('TWEET') else: print('MUTE') if __name__ == '__main__': math()
def math(): i_put = input() if len(i_put) <= 140: print('TWEET') else: print('MUTE') if __name__ == '__main__': math()
''' A better way to implement the fibonacci series T(n) = 2n + 2 ''' def fibonacci(n): # Taking 1st two fibonacci nubers as 0 and 1 FibArray = [0, 1] while len(FibArray) < n + 1: FibArray.append(0) if n <= 1: return n else: if FibArray[n...
""" A better way to implement the fibonacci series T(n) = 2n + 2 """ def fibonacci(n): fib_array = [0, 1] while len(FibArray) < n + 1: FibArray.append(0) if n <= 1: return n else: if FibArray[n - 1] == 0: FibArray[n - 1] = fibonacci(n - 1) if FibArray[n - 2...
eval_cfgs = [ dict( metrics=dict(type='OPE'), dataset=dict(type='OTB100'), hypers=dict( epoch=list(range(31, 51, 2)), window=dict( weight=[0.200, 0.300, 0.400] ) ) ), ]
eval_cfgs = [dict(metrics=dict(type='OPE'), dataset=dict(type='OTB100'), hypers=dict(epoch=list(range(31, 51, 2)), window=dict(weight=[0.2, 0.3, 0.4])))]
class Solution: # Enumerate shortest length (Accepted), O(n*l) time, O(l) space (n = len(strs), l = len(shortest str)) def longestCommonPrefix(self, strs: List[str]) -> str: min_len = min(len(s) for s in strs) res = "" for i in range(min_len): c = strs[0][i] for s...
class Solution: def longest_common_prefix(self, strs: List[str]) -> str: min_len = min((len(s) for s in strs)) res = '' for i in range(min_len): c = strs[0][i] for s in strs: if s[i] != c: return res res += c re...
n = int(input("Please enter the size of the table: ")) # print the first row (header) print(" ", end = "") for i in range(1, n + 1): print(" ", i, end = "") print() # new line # print the actual table for row in range(1, n + 1): # print row number at the beginning of each row print(" ", row, end =...
n = int(input('Please enter the size of the table: ')) print(' ', end='') for i in range(1, n + 1): print(' ', i, end='') print() for row in range(1, n + 1): print(' ', row, end='') for col in range(1, n + 1): if col % row == 0: print(' X', end='') else: print(...
# Copyright 2018 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # DO NOT MANUALLY EDIT! # Generated by //scripts/sdk/bazel/generate.py. load("@io_bazel_rules_dart//dart/build_rules/internal:pub.bzl", "pub_repository") d...
load('@io_bazel_rules_dart//dart/build_rules/internal:pub.bzl', 'pub_repository') def setup_dart(): pub_repository(name='vendor_meta', output='.', package='meta', version='1.1.6', pub_deps=[]) pub_repository(name='vendor_logging', output='.', package='logging', version='0.11.3+2', pub_deps=[]) pub_reposito...
def split(list): n = len(list) if n == 1: return list, [] middle = int(n/2) return list[0:middle], list[middle:n] def merge_sort(list): if len(list) == 0: return list a, b = split(list) if a == list: return a else: new_a = merge_sort(a) ...
def split(list): n = len(list) if n == 1: return (list, []) middle = int(n / 2) return (list[0:middle], list[middle:n]) def merge_sort(list): if len(list) == 0: return list (a, b) = split(list) if a == list: return a else: new_a = merge_sort(a) ne...
# 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 # We would need to create an map out of in-order array to access index easily class Solution: # Faster solution def bu...
class Solution: def build_tree(self, preorder: List[int], inorder: List[int]) -> TreeNode: def helper(in_left=0, in_right=len(inorder)): nonlocal pre_idx if in_right <= in_left: return None node_val = preorder[pre_idx] node = tree_node(node_v...
""" Buffer the StreetTrees feature class by 20 meters """ # Import modules # Set variables # Execute operation
""" Buffer the StreetTrees feature class by 20 meters """
class Solution: def partitionLabels(self, S): """ :type S: str :rtype: List[int] """ positions = dict() for i, c in enumerate(S): if c not in positions: positions[c] = [] positions[c].append(i) result = [] end =...
class Solution: def partition_labels(self, S): """ :type S: str :rtype: List[int] """ positions = dict() for (i, c) in enumerate(S): if c not in positions: positions[c] = [] positions[c].append(i) result = [] en...
a = 3 b = 4 z = a + b print(z)
a = 3 b = 4 z = a + b print(z)
expected = 'Jana III Sobieskiego' a = ' Jana III Sobieskiego ' b = 'ul Jana III SobIESkiego' c = '\tul. Jana trzeciego Sobieskiego' d = 'ulicaJana III Sobieskiego' e = 'UL. JA\tNA 3 SOBIES\tKIEGO' f = 'UL. jana III SOBiesKIEGO' g = 'ULICA JANA III SOBIESKIEGO ' h = 'ULICA. JANA III SOBIeskieGO' i = ' Jana 3 Sobieski...
expected = 'Jana III Sobieskiego' a = ' Jana III Sobieskiego ' b = 'ul Jana III SobIESkiego' c = '\tul. Jana trzeciego Sobieskiego' d = 'ulicaJana III Sobieskiego' e = 'UL. JA\tNA 3 SOBIES\tKIEGO' f = 'UL. jana III SOBiesKIEGO' g = 'ULICA JANA III SOBIESKIEGO ' h = 'ULICA. JANA III SOBIeskieGO' i = ' Jana 3 Sobieskie...
# # PySNMP MIB module CISCO-CALL-TRACKER-TCP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CALL-TRACKER-TCP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:34:55 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_union, value_size_constraint, constraints_intersection, single_value_constraint) ...
def test_index(client): res = client.get("/") json_data = res.get_json() assert json_data["msg"] == "Don't panic" assert res.status_code == 200
def test_index(client): res = client.get('/') json_data = res.get_json() assert json_data['msg'] == "Don't panic" assert res.status_code == 200
#!/usr/bin/env python numbers = [1,2,3,4,5,8,3,2,3,1,1,1] def bubblesort(numbers): # Keep a boolean to determine if we switched switched = True # One round of sorting while switched: switched = False indexA = 0 indexB = 1 while indexB < len(numbers): num...
numbers = [1, 2, 3, 4, 5, 8, 3, 2, 3, 1, 1, 1] def bubblesort(numbers): switched = True while switched: switched = False index_a = 0 index_b = 1 while indexB < len(numbers): number_a = numbers[indexA] number_b = numbers[indexB] if numberA > nu...
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ res = None count = 0 for n in nums: if res is None: res = n count = 1 elif res == n: coun...
class Solution(object): def majority_element(self, nums): """ :type nums: List[int] :rtype: int """ res = None count = 0 for n in nums: if res is None: res = n count = 1 elif res == n: co...
class Solution: def transpose(self, A: List[List[int]]) -> List[List[int]]: output=[] rows=len(A) cols=len(A[0]) output=[[0]*rows for i in range(cols)] for i in range(0,len(A)): for j in range(0,len(A[0])): output[j][i]=A[i][j] return outp...
class Solution: def transpose(self, A: List[List[int]]) -> List[List[int]]: output = [] rows = len(A) cols = len(A[0]) output = [[0] * rows for i in range(cols)] for i in range(0, len(A)): for j in range(0, len(A[0])): output[j][i] = A[i][j] ...
""" spin multiplicities """ def spin(mult): """ number of unpaired electrons """ return mult - 1
""" spin multiplicities """ def spin(mult): """ number of unpaired electrons """ return mult - 1
def missing_values1 (data): """ Deals in place with missing values in specified columns: 'fields_of_study', 'title', 'abstract', 'authors', 'venue', 'references', 'topics' """ data.loc[data['fields_of_study'].isnull(), 'fields_of_study'] = "" data.loc[data['title'].isnull(), 'title'] = "" ...
def missing_values1(data): """ Deals in place with missing values in specified columns: 'fields_of_study', 'title', 'abstract', 'authors', 'venue', 'references', 'topics' """ data.loc[data['fields_of_study'].isnull(), 'fields_of_study'] = '' data.loc[data['title'].isnull(), 'title'] = '' da...
def Settings( **kwargs ): return { 'flags': [ '-O3', '-std=gnu11', '-fms-extensions', '-Wno-microsoft-anon-tag', '-Iinclude/', '-Ilib/', '-pthread', '-Wall', '-Werror', '-pedantic'] }
def settings(**kwargs): return {'flags': ['-O3', '-std=gnu11', '-fms-extensions', '-Wno-microsoft-anon-tag', '-Iinclude/', '-Ilib/', '-pthread', '-Wall', '-Werror', '-pedantic']}
schema = { # Schema definition, of the CLARA items. 'main_scale': { 'type': 'string', 'minlength': 1, 'maxlength': 20, 'required': True }, 'itembank_id': { 'type': 'string', 'minlength': 1, 'maxlength': 4, 'required': True }, 'prese...
schema = {'main_scale': {'type': 'string', 'minlength': 1, 'maxlength': 20, 'required': True}, 'itembank_id': {'type': 'string', 'minlength': 1, 'maxlength': 4, 'required': True}, 'presenting_order': {'type': 'integer', 'required': True}, 'clara_item': {'type': 'string', 'minlength': 1, 'maxlength': 255, 'required': Tr...
n,d = map(int,raw_input().split()) c = map(int,raw_input().split(' ')) gc = 0 for i in range(len(c)): if c[i]+d in c and c[i]+2*d in c: gc+=1 print (gc)
(n, d) = map(int, raw_input().split()) c = map(int, raw_input().split(' ')) gc = 0 for i in range(len(c)): if c[i] + d in c and c[i] + 2 * d in c: gc += 1 print(gc)
{ "targets": [ { "target_name": "glace", "sources": [ "target/glace.cc", ], "include_dirs": [ "target/deps/include", ], "libraries": [], "library_dirs": [ "/usr/local/lib" ...
{'targets': [{'target_name': 'glace', 'sources': ['target/glace.cc'], 'include_dirs': ['target/deps/include'], 'libraries': [], 'library_dirs': ['/usr/local/lib']}]}
OUT_FORMAT_CONVERSION = { "t": "", "b": "b", "u": "bu", }
out_format_conversion = {'t': '', 'b': 'b', 'u': 'bu'}
Scale.default = Scale.egyptian Root.default = 0 Clock.bpm = 110 ~p1 >> play('m', dur=PDur(3,16), sample=[0,2,3]) ~p2 >> play('V', dur=1, pan=[-1,1], sample=var([0,2],[24,8])) ~p3 >> play('n', dur=var([.5,.25,.125,2/3],[24,4,2,2])) p_all.lpf = 0 p_all.rate = .5 ~s1 >> space(P[0,3,5,1]+(0,3), dur=4, chop=6, slide=0, e...
Scale.default = Scale.egyptian Root.default = 0 Clock.bpm = 110 ~p1 >> play('m', dur=p_dur(3, 16), sample=[0, 2, 3]) ~p2 >> play('V', dur=1, pan=[-1, 1], sample=var([0, 2], [24, 8])) ~p3 >> play('n', dur=var([0.5, 0.25, 0.125, 2 / 3], [24, 4, 2, 2])) p_all.lpf = 0 p_all.rate = 0.5 ~s1 >> space(P[0, 3, 5, 1] + (0, 3), d...
"""" Copyright 2019 by J. Christopher Wagner (jwag). All rights reserved. :license: MIT, see LICENSE for more details. This packages contains OPTIONAL models for various ORMs/databases that can be used to quickly get the required DB models setup. These models have the fields for ALL features. This makes it easy for a...
"""" Copyright 2019 by J. Christopher Wagner (jwag). All rights reserved. :license: MIT, see LICENSE for more details. This packages contains OPTIONAL models for various ORMs/databases that can be used to quickly get the required DB models setup. These models have the fields for ALL features. This makes it easy for a...
params = { # file to load wav from 'file': 'C:/Users/qweis/Documents/GitHub/unknown-pleasures/wavs/famous.wav', # output file for images 'save_loc': 'covers/frame.png', # save location for video 'vid_save': 'time_test.mp4', # number of spacers between each data point 'spacers': 5, # ...
params = {'file': 'C:/Users/qweis/Documents/GitHub/unknown-pleasures/wavs/famous.wav', 'save_loc': 'covers/frame.png', 'vid_save': 'time_test.mp4', 'spacers': 5, 'offset': 10, 'data_line': 40, 'n_lines': 80, 'noise_frac': 1, 'min_ticks': 5, 'random_noise_range': 1, 'connecting_line_range': 6, 'fps': 30, 'line_width': 3...
input = """-1,-1,-4,-1 0,1,8,5 -8,-5,2,-6 -1,3,-2,-3 -1,1,6,1 4,-8,0,-5 8,-6,-5,6 -6,2,-8,1 -5,6,-2,-5 3,-8,0,0 -3,-7,-5,-6 -1,-4,-7,-5 -7,3,1,-6 -5,4,-4,0 1,-7,0,-6 4,-1,1,2 6,1,6,-2 2,1,-8,-6 -7,-7,3,2 -8,-5,8,-5 -8,2,-1,4 8,6,7,1 6,-4,-1,-7 8,-2,2,4 0,8,8,3 6,-7,-6,8 -8,-2,8,6 1,-8,-6,-8 -6,-1,5,-6 5,2,7,-3 5,7,0,-3...
input = '-1,-1,-4,-1\n0,1,8,5\n-8,-5,2,-6\n-1,3,-2,-3\n-1,1,6,1\n4,-8,0,-5\n8,-6,-5,6\n-6,2,-8,1\n-5,6,-2,-5\n3,-8,0,0\n-3,-7,-5,-6\n-1,-4,-7,-5\n-7,3,1,-6\n-5,4,-4,0\n1,-7,0,-6\n4,-1,1,2\n6,1,6,-2\n2,1,-8,-6\n-7,-7,3,2\n-8,-5,8,-5\n-8,2,-1,4\n8,6,7,1\n6,-4,-1,-7\n8,-2,2,4\n0,8,8,3\n6,-7,-6,8\n-8,-2,8,6\n1,-8,-6,-8\n-6...
# The Twitter API keys needed to send tweets # Two applications for the same account are needed, # since two streamers can't be run on the same account # main account. needs all privileges CONSUMER_KEY = "enter your consumer key here" CONSUMER_SECRET = "enter your secret consumer key here" ACCESS_TOKEN = "enter your ...
consumer_key = 'enter your consumer key here' consumer_secret = 'enter your secret consumer key here' access_token = 'enter your access token here' access_token_secret = 'enter your secret access token here' mine_consumer_key = 'enter your consumer key here' mine_consumer_secret = 'enter your secret consumer key here' ...
CATEGORIES = { "all", "arts", "automotive", "baby", "beauty", "books", "boys", "computers", "electronics", "girls", "health", "kitchen", "industrial", "mens", "pets", "sports", "games", "travel", "womens", } CATEGORIES_CHOICES = [ ("all",...
categories = {'all', 'arts', 'automotive', 'baby', 'beauty', 'books', 'boys', 'computers', 'electronics', 'girls', 'health', 'kitchen', 'industrial', 'mens', 'pets', 'sports', 'games', 'travel', 'womens'} categories_choices = [('all', 'All'), ('arts', 'Arts'), ('automotive', 'Automotive'), ('baby', 'Baby'), ('beauty', ...
"""#ip 2 addi 2 16 2 seti 1 2 4 seti 1 8 1 mulr 4 1 5 eqrr 5 3 5 addr 5 2 2 addi 2 1 2 addr 4 0 0 addi 1 1 1 gtrr 1 3 5 addr 2 5 2 seti 2 6 2 addi 4 1 4 gtrr 4 3 5 addr 5 2 2 seti 1 2 2 mulr 2 2 2 addi 3 2 3 mulr 3 3 3 mulr 2 3 3 muli 3 11 3 addi 5 2 5 mulr 5 2 5 addi 5 8 5 addr 3 5 3 addr 2 0 2 seti 0 4 2 setr 2 5 5 m...
"""#ip 2 addi 2 16 2 seti 1 2 4 seti 1 8 1 mulr 4 1 5 eqrr 5 3 5 addr 5 2 2 addi 2 1 2 addr 4 0 0 addi 1 1 1 gtrr 1 3 5 addr 2 5 2 seti 2 6 2 addi 4 1 4 gtrr 4 3 5 addr 5 2 2 seti 1 2 2 mulr 2 2 2 addi 3 2 3 mulr 3 3 3 mulr 2 3 3 muli 3 11 3 addi 5 2 5 mulr 5 2 5 addi 5 8 5 addr 3 5 3 addr 2 0 2 seti 0 4 2 setr 2 5 5 m...
mensaje = "Registre el nombre del estudiante " estudiantes = [] estudiante = input(mensaje) estudiantes.append(estudiante) estudiante = input(mensaje) estudiantes.append(estudiante) estudiante = input(mensaje) estudiantes.append(estudiante) estudiante = input(mensaje) estudiantes.append(estudiante) estudiante = input(m...
mensaje = 'Registre el nombre del estudiante ' estudiantes = [] estudiante = input(mensaje) estudiantes.append(estudiante) estudiante = input(mensaje) estudiantes.append(estudiante) estudiante = input(mensaje) estudiantes.append(estudiante) estudiante = input(mensaje) estudiantes.append(estudiante) estudiante = input(m...
# from https://www.ngdc.noaa.gov/geomag/WMM/data/WMM2020/WMM2020_Report.pdf EQUATOR_RADIUS = 6378137 FLATTENING = 1 / 298.257223563 EE2 = FLATTENING * (2 - FLATTENING) # eecentricity squared N_MAX = 12 # degree of expansion
equator_radius = 6378137 flattening = 1 / 298.257223563 ee2 = FLATTENING * (2 - FLATTENING) n_max = 12
# -*- coding: utf-8 -*- def suma(num1, num2): sm = num1 + num2 return sm print(suma(2,3))
def suma(num1, num2): sm = num1 + num2 return sm print(suma(2, 3))
myVariable = 0 def when_started1(): global myVariable fork_motor_group.spin_to_position(1100, DEGREES, wait=False) drivetrain.turn_for(RIGHT, 22, DEGREES, wait=True) # Get goalpost with 2 rings into our zone (22 points) drivetrain.drive_for(FORWARD, 1200, MM, wait=True) drivetrain.set...
my_variable = 0 def when_started1(): global myVariable fork_motor_group.spin_to_position(1100, DEGREES, wait=False) drivetrain.turn_for(RIGHT, 22, DEGREES, wait=True) drivetrain.drive_for(FORWARD, 1200, MM, wait=True) drivetrain.set_drive_velocity(100, PERCENT) drivetrain.set_turn_velocity(100,...
def search(f, k, ma): la = 0 r = ma while r - la > 1: d = (la + r) // 2 t = f(d) if t >= k: r = d else: la = d return r a, b, c, x, k = map(int, input().split()) def f(t): if t > b: rp = t elif a <= t and t * (1 + c / 100) >...
def search(f, k, ma): la = 0 r = ma while r - la > 1: d = (la + r) // 2 t = f(d) if t >= k: r = d else: la = d return r (a, b, c, x, k) = map(int, input().split()) def f(t): if t > b: rp = t elif a <= t and t * (1 + c / 100) > b + ...
def startup(addPluginHook, addHook, world) : addPluginHook(world, "list", main, 1, ["self", "info", "args", "world"]) def main(self, info, args, world) : """list The list command lists all plugins""" pluginlist = world.plugins.keys() pluginlist.sort() self.msg(info["channel"], "I will send you the l...
def startup(addPluginHook, addHook, world): add_plugin_hook(world, 'list', main, 1, ['self', 'info', 'args', 'world']) def main(self, info, args, world): """list The list command lists all plugins""" pluginlist = world.plugins.keys() pluginlist.sort() self.msg(info['channel'], 'I will send you the ...
#!/usr/bin/env python class H2O: def __init__(self): pass def hydrogen(self, releaseHydrogen: 'Callable[[], None]') -> None: # releaseHydrogen() outputs "H". Do not change or remove this line. releaseHydrogen() def oxygen(self, releaseOxygen: 'Callable[[], None]') -> No...
class H2O: def __init__(self): pass def hydrogen(self, releaseHydrogen: 'Callable[[], None]') -> None: release_hydrogen() def oxygen(self, releaseOxygen: 'Callable[[], None]') -> None: release_oxygen()
def recursive_update(default, custom): """A recursive version of Python dict#update""" if not isinstance(default, dict) or not isinstance(custom, dict): raise TypeError('Params of recursive_update() must be a dictionnaries.') for key in custom: if isinstance(custom[key], dict) and isinstanc...
def recursive_update(default, custom): """A recursive version of Python dict#update""" if not isinstance(default, dict) or not isinstance(custom, dict): raise type_error('Params of recursive_update() must be a dictionnaries.') for key in custom: if isinstance(custom[key], dict) and isinstanc...
def longestValidParentheses(s: str) -> int: result = 0 if not s: return result n = len(s) stack = [-1] for i in range(n): if s[i] == "(": stack.append(i) else: stack.pop() if not stack: stack.append(i) else: ...
def longest_valid_parentheses(s: str) -> int: result = 0 if not s: return result n = len(s) stack = [-1] for i in range(n): if s[i] == '(': stack.append(i) else: stack.pop() if not stack: stack.append(i) else: ...
""" Selection Sort https://en.wikipedia.org/wiki/Selection_sort Worst-case performance: O(N^2) If you call selection_sort(arr,True), you can see the process of the sort Default is simulation = False """ def selection_sort(arr, simulation=False): iteration = 0 if simulation: print("iteration",iter...
""" Selection Sort https://en.wikipedia.org/wiki/Selection_sort Worst-case performance: O(N^2) If you call selection_sort(arr,True), you can see the process of the sort Default is simulation = False """ def selection_sort(arr, simulation=False): iteration = 0 if simulation: print('iteration', iter...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ i...
class Solution(object): def binary_tree_paths(self, root): """ :type root: TreeNode :rtype: List[str] """ if root == None: return [] if root.left == None and root.right == None: return [str(root.val)] ret = [] if root.left != N...
# -*- coding: utf-8 -*- # Visigoth: A lightweight Python3 library for rendering data visualizations in SVG # Copyright (C) 2020-2021 Visigoth Developers # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software # and associated documentation files (the "Software"), to...
class Multithing(object): """ Base class for an object (point,line,polygon) Arguments: id (str): an ID associated with the polygon category (str): a category associated with the polygon label (str): a label associated with these polygons tooltip (str): a tooltip associated w...