content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Solution: def canCross(self, stones: List[int]) -> bool: n = len(stones) # dp[i][j] := True if a frog can make a size j jump to stones[i] dp = [[False] * (n + 1) for _ in range(n)] dp[0][0] = True for i in range(1, n): for j in range(i): k = stones[i] - stones[j] if k ...
class Solution: def can_cross(self, stones: List[int]) -> bool: n = len(stones) dp = [[False] * (n + 1) for _ in range(n)] dp[0][0] = True for i in range(1, n): for j in range(i): k = stones[i] - stones[j] if k > n: con...
class PPSTimingCalibrationModeEnum: CondDB = 0 JSON = 1 SQLite = 2
class Ppstimingcalibrationmodeenum: cond_db = 0 json = 1 sq_lite = 2
a = input() i = ord(a) for i in range(i-96): print(chr(i+97),end=" ")
a = input() i = ord(a) for i in range(i - 96): print(chr(i + 97), end=' ')
n=int(input("From number")) n1=int(input("To number")) for i in range(n,n1): for j in range(2,i): if i%j==0: break else: print(i)
n = int(input('From number')) n1 = int(input('To number')) for i in range(n, n1): for j in range(2, i): if i % j == 0: break else: print(i)
# Recursive implementation to find the gcd (greatest common divisor) of two integers using the euclidean algorithm. # For more than two numbers, e.g. three, you can box it like this: gcd(a,gcd(b,greatest_common_divisor.c)) etc. # This runs in O(log(n)) where n is the maximum of a and b. # :param a: the first integer # ...
def gcd(a, b): if b == 0: return a return gcd(b, a % b)
def _build(**kwargs): kwargs.setdefault("mac_src", '00.00.00.00.00.01') kwargs.setdefault("mac_dst", '00.00.00.00.00.02') kwargs.setdefault("mac_src_step", '00.00.00.00.00.01') kwargs.setdefault("mac_dst_step", '00.00.00.00.00.01') kwargs.setdefault("arp_src_hw_addr", '01.00.00.00.00.01') kwarg...
def _build(**kwargs): kwargs.setdefault('mac_src', '00.00.00.00.00.01') kwargs.setdefault('mac_dst', '00.00.00.00.00.02') kwargs.setdefault('mac_src_step', '00.00.00.00.00.01') kwargs.setdefault('mac_dst_step', '00.00.00.00.00.01') kwargs.setdefault('arp_src_hw_addr', '01.00.00.00.00.01') kwargs...
#Weird algorithm for matrix multiplication. just addition will produce result matrix class Solution: def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int: row = [0] * n col = [0] * m ans = 0 for r,c in indices: row[r] += 1 col[c] += 1 fo...
class Solution: def odd_cells(self, n: int, m: int, indices: List[List[int]]) -> int: row = [0] * n col = [0] * m ans = 0 for (r, c) in indices: row[r] += 1 col[c] += 1 for i in range(n): for j in range(m): ans += (row[i] +...
# -*- coding: utf-8 -*- """ Created on Tue Oct 13 20:04:26 2020 @author: ninjaac """ def count_substring(string, sub_string): return string.count(sub_string) #return (''.join(string)).count(''.join(sub_string)) if __name__ == '__main__': string = input().strip() sub_string = input().stri...
""" Created on Tue Oct 13 20:04:26 2020 @author: ninjaac """ def count_substring(string, sub_string): return string.count(sub_string) if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(string, sub_string) print(count)
unavailable_dict = { "0": { ("11", "12", "13"): [ "message_1", "message_4" ], ("21", "22", "23"): [ "message_3", "message_6" ], ("24",): [ "message_2", "message_5" ], ("0", "blank",): [ ...
unavailable_dict = {'0': {('11', '12', '13'): ['message_1', 'message_4'], ('21', '22', '23'): ['message_3', 'message_6'], ('24',): ['message_2', 'message_5'], ('0', 'blank'): ['message_7']}, '1': {('11', '12', '13'): ['message_8'], ('21', '22', '23'): ['message_9'], ('0', 'blank'): ['message_10']}, '2': {('0', 'blank')...
# In theory, RightScale's API is discoverable through ``links`` in responses. # In practice, we have to help our robots along with the following hints: RS_DEFAULT_ACTIONS = { 'index': { 'http_method': 'get', }, 'show': { 'http_method': 'get', 'extra_path':...
rs_default_actions = {'index': {'http_method': 'get'}, 'show': {'http_method': 'get', 'extra_path': '/%(res_id)s'}, 'create': {'http_method': 'post'}, 'update': {'http_method': 'put', 'extra_path': '/%(res_id)s'}, 'destroy': {'http_method': 'delete', 'extra_path': '/%(res_id)s'}} alert_actions = {'disable': {'http_meth...
''' Created on Oct 1, 2011 @author: jose '''
""" Created on Oct 1, 2011 @author: jose """
"""binary tree """ #https://www.hackerrank.com/challenges/tree-preorder-traversal/problem #recrusive: def preOrder(root): print(root.info,end=' ') if root.left: preOrder(root.left) if root.right: preOrder(root.right) #itrative: def preOrder(root): stack=[root] while(stack): ...
"""binary tree """ def pre_order(root): print(root.info, end=' ') if root.left: pre_order(root.left) if root.right: pre_order(root.right) def pre_order(root): stack = [root] while stack: a = stack.pop() print(a.info, end=' ') if a.right: stack....
# Definition for a undirected graph node class UndirectedGraphNode: def __init__(self, x): self.label = x self.neighbors = [] def __str__(self): return "({} -> {})".format(self.label, [nb.label for nb in self.neighbors]) def __repr__(self): ...
class Undirectedgraphnode: def __init__(self, x): self.label = x self.neighbors = [] def __str__(self): return '({} -> {})'.format(self.label, [nb.label for nb in self.neighbors]) def __repr__(self): return self.__str__() class Solution: def clone_graph(self, node): ...
class Salary: def __init__(self,pay,bonus): self.pay=pay self.bonus=bonus def annual(self): return (self.pay*12)+self.bonus class employee: def __init__(self,name,age,pay,bonus): self.name=name self.age=age self.pay=pay self.bonus=bonus ...
class Salary: def __init__(self, pay, bonus): self.pay = pay self.bonus = bonus def annual(self): return self.pay * 12 + self.bonus class Employee: def __init__(self, name, age, pay, bonus): self.name = name self.age = age self.pay = pay self.bonus...
test = { 'name': 'smallest-int', 'points': 0, 'suites': [ { 'cases': [ { 'code': r""" sqlite> SELECT * FROM smallest_int; 11/11/2015 10:01:03|7 11/11/2015 13:53:36|7 11/11/2015 14:52:07|7 11/11/2015 15:36:00|7 11/11/2015 15:46...
test = {'name': 'smallest-int', 'points': 0, 'suites': [{'cases': [{'code': '\n sqlite> SELECT * FROM smallest_int;\n 11/11/2015 10:01:03|7\n 11/11/2015 13:53:36|7\n 11/11/2015 14:52:07|7\n 11/11/2015 15:36:00|7\n 11/11/2015 15:46:03|7\n 11/11/2015 16:11:56...
# Christian Piper # 11/11/19 # This will accept algebra equations on the input and solve for the variable def main(): equation = input("Input your equation: ") variable = input("Input the variable to be solved for: ") solveAlgebraEquation(equation, variable) def solveAlgebraEquation(equation, variable): ...
def main(): equation = input('Input your equation: ') variable = input('Input the variable to be solved for: ') solve_algebra_equation(equation, variable) def solve_algebra_equation(equation, variable): collector = ['', '', '', '', '', ''] iteration = 0 for char in equation: if char == ...
# Location of exported xml playlist from itunes # Update username and directory to their appropriate path e.g C:/users/bob/desktop/file.xml xml_playlist_loc = 'C:/users/username/directory/_MyMusic_.xml' # name of user directory where your Music folder is located # example: C:/users/bob/music/itunes music_folder_dir = '...
xml_playlist_loc = 'C:/users/username/directory/_MyMusic_.xml' music_folder_dir = 'name'
#!/usr/bin/env python # -*- coding: utf-8 -*- class Address(dict): """ Dictionary class that provides some convenience wrappers for accessing commonly used data elements on an Address. """ def __init__(self, address_dict, order="lat"): super(Address, self).__init__(address_dict) s...
class Address(dict): """ Dictionary class that provides some convenience wrappers for accessing commonly used data elements on an Address. """ def __init__(self, address_dict, order='lat'): super(Address, self).__init__(address_dict) self.order = order @property def coords(...
def backtickify(s): return '`{}`'.format(s) def bind_exercises(g, exercises, start=1): for i, ex in enumerate(exercises): qno = i + start varname = 'q{}'.format(qno) assert varname not in g g[varname] = ex yield varname
def backtickify(s): return '`{}`'.format(s) def bind_exercises(g, exercises, start=1): for (i, ex) in enumerate(exercises): qno = i + start varname = 'q{}'.format(qno) assert varname not in g g[varname] = ex yield varname
# -*- coding: utf-8 -*- """ Created on Sat Jul 31 17:42:50 2021 @author: tan_k """
""" Created on Sat Jul 31 17:42:50 2021 @author: tan_k """
# # PySNMP MIB module RBN-CONFIG-FILE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBN-CONFIG-FILE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:44:14 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_range_constraint, constraints_intersection, constraints_union, value_size_constraint) ...
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: dummy = ListNode(-1) dummy.next = head def t(d): if d.ne...
class Listnode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def remove_elements(self, head: ListNode, val: int) -> ListNode: dummy = list_node(-1) dummy.next = head def t(d): if d.next: if d.next.va...
# nxn chessboard n = 10 # number of dragons on the chessboard dragons = 10 solution = [-1]*n captured = [[0 for i in range(n)] for i in range(n)] number = 0 local_calls = 0 total_calls = 0 def init(): global captured def isCaptured(x, y): global captured return captured[x][y] def capture(...
n = 10 dragons = 10 solution = [-1] * n captured = [[0 for i in range(n)] for i in range(n)] number = 0 local_calls = 0 total_calls = 0 def init(): global captured def is_captured(x, y): global captured return captured[x][y] def capture(x, y): for i in range(n): captured[i][y] += 1 ca...
class ApiException(Exception): pass class Forbidden(ApiException): def __init__(self, message): self.message = message self.status_code = 403 class NotFound(ApiException): def __init__(self, message): self.message = message self.status_code = 404 class BadRequest(A...
class Apiexception(Exception): pass class Forbidden(ApiException): def __init__(self, message): self.message = message self.status_code = 403 class Notfound(ApiException): def __init__(self, message): self.message = message self.status_code = 404 class Badrequest(ApiExce...
# # Copyright (C) 2018 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
def test(name, input0, input1, input2, output0, input0_data, input1_data, input2_data, output_data): model = model().Operation('SELECT', input0, input1, input2).To(output0) quant8 = data_type_converter().Identify({input1: ['TENSOR_QUANT8_ASYMM', 1.5, 129], input2: ['TENSOR_QUANT8_ASYMM', 0.5, 127], output0: ['T...
# -*- coding: utf-8 -*- # # Copyright (C) 2005-2018 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.com/license.html. # # This software consists ...
sql = ['CREATE TEMPORARY TABLE node_change_old AS SELECT * FROM node_change;', 'DROP TABLE node_change;', 'CREATE TABLE node_change (\n rev text,\n path text,\n kind char(1),\n change char(1),\n base_path text,\n base_rev text,\n UNIQUE(rev, p...
class LDAP_record: """ consume LDAP record and provide methods for accessing interesting data """ def __init__(self, unid): self.error = False ldap_dict = {} # # request complete user record from LDAP cmd = "/Users/" + unid try: raw_data = sub...
class Ldap_Record: """ consume LDAP record and provide methods for accessing interesting data """ def __init__(self, unid): self.error = False ldap_dict = {} cmd = '/Users/' + unid try: raw_data = subprocess.check_output(['/usr/bin/dscl', '/LDAPv3/your.ldap.s...
NAME='nagios' CFLAGS = [] LDFLAGS = [] LIBS = [] GCC_LIST = ['nagios']
name = 'nagios' cflags = [] ldflags = [] libs = [] gcc_list = ['nagios']
class Solution: def find_permutation(self, S): S = sorted(S) self.res = [] visited = [False] * len(S) self.find_permutationUtil(S, visited, '') return self.res def find_permutationUtil(self, S, visited, str): if len(str) == len(S): self.res.append(str...
class Solution: def find_permutation(self, S): s = sorted(S) self.res = [] visited = [False] * len(S) self.find_permutationUtil(S, visited, '') return self.res def find_permutation_util(self, S, visited, str): if len(str) == len(S): self.res.append(s...
s = set(map(int, input().split())) print(s) print("max is: ",max(s)) print("min is: ",min(s))
s = set(map(int, input().split())) print(s) print('max is: ', max(s)) print('min is: ', min(s))
def transact(environment, t, to_agent, from_agent, settlement_type, amount, description): "Function that ensures a correct transaction between agents" environment.measurement['period'].append(t) environment.measurement['to_agent'].append(to_agent) environment.measurement['from_agent'].append(from_agent)...
def transact(environment, t, to_agent, from_agent, settlement_type, amount, description): """Function that ensures a correct transaction between agents""" environment.measurement['period'].append(t) environment.measurement['to_agent'].append(to_agent) environment.measurement['from_agent'].append(from_ag...
class NSGA2: def __init__(self, initializer, evaluator, selector, crossover, mutator, stopper): self.initializer = initializer self.evaluator = evaluator self.selector = selector self.crossover = crossover self.mutator = mutator self.stopper = stopper self.po...
class Nsga2: def __init__(self, initializer, evaluator, selector, crossover, mutator, stopper): self.initializer = initializer self.evaluator = evaluator self.selector = selector self.crossover = crossover self.mutator = mutator self.stopper = stopper self.po...
class RetrievalError(Exception): pass class SetterError(Exception): pass class ControlError(SetterError): pass class AuthentificationError(Exception): pass class TemporaryAuthentificationError(AuthentificationError): pass class APICompatibilityError(Exception): pass class APIError(Ex...
class Retrievalerror(Exception): pass class Settererror(Exception): pass class Controlerror(SetterError): pass class Authentificationerror(Exception): pass class Temporaryauthentificationerror(AuthentificationError): pass class Apicompatibilityerror(Exception): pass class Apierror(Exceptio...
# Based on largest_rectangle_in_histagram 84 def maximal_rectrangle_in_matrix(matrix): if len(matrix) == 0 or len(matrix[0]) == 0: return 0 # Append extra 0 to the end, to mark the end of the curr row curr_row = [0] * (len(matrix[0]) + 1) ans = 0 for row in range(len(matrix)): for ...
def maximal_rectrangle_in_matrix(matrix): if len(matrix) == 0 or len(matrix[0]) == 0: return 0 curr_row = [0] * (len(matrix[0]) + 1) ans = 0 for row in range(len(matrix)): for column in range(len(matrix[0])): if matrix[row][column] == '1': curr_row[column] += ...
class Deque(object): """A deque (double-ended queue) is a linear structure of ordered items where the addition and removal of items can take place on any end. Thus deques can work as FIFO (First In, First Out) or LIFO (Last In, First Out) Examples: >>> d = Deque() >>> d.is_...
class Deque(object): """A deque (double-ended queue) is a linear structure of ordered items where the addition and removal of items can take place on any end. Thus deques can work as FIFO (First In, First Out) or LIFO (Last In, First Out) Examples: >>> d = Deque() >>> d.is_...
""" Sampler metadata """ class Sampler(object): method_name = None def __init__(self): pass class GibbsSampler(Sampler): method_name = 'gibbs' def __init__(self, n_iter=1000, n_burnin=100, n_thread=1): # super(GibbsSampler, self).__init__() self.n_iter = n_iter self...
""" Sampler metadata """ class Sampler(object): method_name = None def __init__(self): pass class Gibbssampler(Sampler): method_name = 'gibbs' def __init__(self, n_iter=1000, n_burnin=100, n_thread=1): self.n_iter = n_iter self.n_burnin = n_burnin self.n_thread = n_th...
# A program to check if the number is odd or even def even_or_odd(num): if num == "q": return "Invalid" elif num % 2 == 0: return "Even" else: return "Odd" while True: try: user_input = float(input("Enter then number you would like to check is odd or even")) except...
def even_or_odd(num): if num == 'q': return 'Invalid' elif num % 2 == 0: return 'Even' else: return 'Odd' while True: try: user_input = float(input('Enter then number you would like to check is odd or even')) except ValueError or TypeError: user_input = 'q' ...
# -*- coding: utf-8 -*- """ Created on Mon Feb 13 16:43:18 2017 @author: coskun """ def closest_power(base, num): ''' base: base of the exponential, integer > 1 num: number you want to be closest to, integer > 0 Find the integer exponent such that base**exponent is closest to num. Note that the ba...
""" Created on Mon Feb 13 16:43:18 2017 @author: coskun """ def closest_power(base, num): """ base: base of the exponential, integer > 1 num: number you want to be closest to, integer > 0 Find the integer exponent such that base**exponent is closest to num. Note that the base**exponent may be eith...
class Solution: def minCut(self, s: str) -> int: if not s: return 0 memo = dict() def helper(l,r): if l > r: return 0 minVal = float('inf') for i in range(l,r+1,1): strs = s[l:i+1] if strs == str...
class Solution: def min_cut(self, s: str) -> int: if not s: return 0 memo = dict() def helper(l, r): if l > r: return 0 min_val = float('inf') for i in range(l, r + 1, 1): strs = s[l:i + 1] if s...
'''https://practice.geeksforgeeks.org/problems/cyclically-rotate-an-array-by-one2614/1 Cyclically rotate an array by one Basic Accuracy: 64.05% Submissions: 66795 Points: 1 Given an array, rotate the array by one position in clock-wise direction. Example 1: Input: N = 5 A[] = {1, 2, 3, 4, 5} Output: 5 1 2 3 4 E...
"""https://practice.geeksforgeeks.org/problems/cyclically-rotate-an-array-by-one2614/1 Cyclically rotate an array by one Basic Accuracy: 64.05% Submissions: 66795 Points: 1 Given an array, rotate the array by one position in clock-wise direction. Example 1: Input: N = 5 A[] = {1, 2, 3, 4, 5} Output: 5 1 2 3 4 E...
#!/usr/bin/env python # -*- coding:utf-8 -*- def max_min(v): m_min, m_max = min(v[0], v[-1]), max(v[0], v[-1]) for i in v[1:len(v)-1]: if i<m_min: m_min = i elif i > m_max: m_max = i return m_min, m_max if __name__ == '__main__': m_min, m_max = max_min([9, ...
def max_min(v): (m_min, m_max) = (min(v[0], v[-1]), max(v[0], v[-1])) for i in v[1:len(v) - 1]: if i < m_min: m_min = i elif i > m_max: m_max = i return (m_min, m_max) if __name__ == '__main__': (m_min, m_max) = max_min([9, 3, 4, 7, 2, 0]) print(m_min, m_max)
# -*- coding: utf-8 -*- """ seqansphinx ~~~~~~~~~~~~~ This package is a namespace package that contains all extensions distributed in the ``seqansphinx`` distribution. :copyright: Copyright 2014 by Manuel Holtgrewe :license: MIT, see LICENSE for details. """ __import__('pkg_resources').declar...
""" seqansphinx ~~~~~~~~~~~~~ This package is a namespace package that contains all extensions distributed in the ``seqansphinx`` distribution. :copyright: Copyright 2014 by Manuel Holtgrewe :license: MIT, see LICENSE for details. """ __import__('pkg_resources').declare_namespace(__name__)
string = [x for x in input()] string_list_after = [] index = 0 power = 0 for el in range(len(string)): if string[index] == ">": expl = int(string[el + 1]) power += int(expl) string.pop(el+1) string.append('') power -= 1 while power > 0: index = el ...
string = [x for x in input()] string_list_after = [] index = 0 power = 0 for el in range(len(string)): if string[index] == '>': expl = int(string[el + 1]) power += int(expl) string.pop(el + 1) string.append('') power -= 1 while power > 0: index = el ...
"""Exceptions for cmd_utils.""" class CommandException(Exception): """ Base Exception for cmd_utils exceptions. Attributes: exc - string message return_code - return code of command """ def __init__(self, exc, return_code=None): Exception.__init__(self) ...
"""Exceptions for cmd_utils.""" class Commandexception(Exception): """ Base Exception for cmd_utils exceptions. Attributes: exc - string message return_code - return code of command """ def __init__(self, exc, return_code=None): Exception.__init__(self) se...
#A more compact version of the algorithm that can be executed parallelly. list1 = [0x58, 0x76, 0x54, 0x3a, 0xbe, 0x58, 0x76, 0x54, 0xbe, 0xcd, 0x45, 0x66, 0x85, 0x65] # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ # Par=4: bulk bulk bulk bulk bulk bulk bulk bulk bu...
list1 = [88, 118, 84, 58, 190, 88, 118, 84, 190, 205, 69, 102, 133, 101] def parallel_roling_mac_hash(list, par): multiplier = 16777619 hash = [0 for x in range(par)] mult_powers = [multiplier ** (x + 1) for x in range(par)] list_length = len(list) bulk = list_length // par rest = list_length %...
#!/usr/bin/env python # coding: utf-8 # In[ ]: # In[4]: def fib(n): a, b = 0,1 while a < n: print(a) a, b = b, a + b # In[8]: def primos(n): numbers = [True, True] + [True] * (n-1) last_prime_number = 2 i = last_prime_number while last_prime_number**2 <= n: ...
def fib(n): (a, b) = (0, 1) while a < n: print(a) (a, b) = (b, a + b) def primos(n): numbers = [True, True] + [True] * (n - 1) last_prime_number = 2 i = last_prime_number while last_prime_number ** 2 <= n: i += last_prime_number while i <= n: numbers[...
""" Number of Provinces There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c. A province is a group of directly or indirectly connected cities and no other citi...
""" Number of Provinces There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c. A province is a group of directly or indirectly connected cities and no other citi...
class CliError(RuntimeError): pass
class Clierror(RuntimeError): pass
class AjaxableResponseMixin(object): """ Mixin to add AJAX support to a form. Must be used with an object-based FormView (e.g. CreateView) """ def form_invalid(self, form): response = super(AjaxableResponseMixin, self).form_invalid(form) if self.request.is_ajax(): return ...
class Ajaxableresponsemixin(object): """ Mixin to add AJAX support to a form. Must be used with an object-based FormView (e.g. CreateView) """ def form_invalid(self, form): response = super(AjaxableResponseMixin, self).form_invalid(form) if self.request.is_ajax(): return...
#!/usr/bin/env python __author__ = "Giuseppe Chiesa" __copyright__ = "Copyright 2017-2021, Giuseppe Chiesa" __credits__ = ["Giuseppe Chiesa"] __license__ = "BSD" __maintainer__ = "Giuseppe Chiesa" __email__ = "mail@giuseppechiesa.it" __status__ = "PerpetualBeta" def write_with_modecheck(file_handler, data): if f...
__author__ = 'Giuseppe Chiesa' __copyright__ = 'Copyright 2017-2021, Giuseppe Chiesa' __credits__ = ['Giuseppe Chiesa'] __license__ = 'BSD' __maintainer__ = 'Giuseppe Chiesa' __email__ = 'mail@giuseppechiesa.it' __status__ = 'PerpetualBeta' def write_with_modecheck(file_handler, data): if file_handler.mode == 'w':...
#!/usr/bin/env python # -*- coding: UTF-8 -*- class BaseEmitter(object): '''Base for emitters of the *data-migrator*. Attributes: manager (BaseManager): reference to the manager that is calling this emitter to export objects from that manager model_class (Model): reference to the ...
class Baseemitter(object): """Base for emitters of the *data-migrator*. Attributes: manager (BaseManager): reference to the manager that is calling this emitter to export objects from that manager model_class (Model): reference to the model linked to the class extension (str...
""" LeetCode Problem: 833. Find And Replace in String Link: https://leetcode.com/problems/find-and-replace-in-string/ Language: Python Written by: Mostofa Adib Shakib Time complexity: O(n) Space Complexity: O(n) """ class Solution: def findReplaceString(self, S: str, indexes: List[int], sources: List[str], target...
""" LeetCode Problem: 833. Find And Replace in String Link: https://leetcode.com/problems/find-and-replace-in-string/ Language: Python Written by: Mostofa Adib Shakib Time complexity: O(n) Space Complexity: O(n) """ class Solution: def find_replace_string(self, S: str, indexes: List[int], sources: List[str], tar...
class Stack(object): def __init__(self): self.stack = [] def is_empty(self): return not self.stack def push(self, v): self.stack.append(v) def pop(self): data = self.stack[-1] del self.stack[-1] return data def peek(self): return self.stac...
class Stack(object): def __init__(self): self.stack = [] def is_empty(self): return not self.stack def push(self, v): self.stack.append(v) def pop(self): data = self.stack[-1] del self.stack[-1] return data def peek(self): return self.stac...
array = [0,0,1,1,1,1,2,2,2,2,3,3] indexEqualCurrentUsage = [] for index in range(len(array)): if array[index] == 1: indexEqualCurrentUsage.append(index) print(indexEqualCurrentUsage)
array = [0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3] index_equal_current_usage = [] for index in range(len(array)): if array[index] == 1: indexEqualCurrentUsage.append(index) print(indexEqualCurrentUsage)
""" We see many sharp peaks in the training set, but these peaks are not always present in the test set, suggesting that they are due to noise. Therefore, ignoring this noise, we might have expected the neural responses to be a sum of only a few different filters and only at a few different positions. This would mean ...
""" We see many sharp peaks in the training set, but these peaks are not always present in the test set, suggesting that they are due to noise. Therefore, ignoring this noise, we might have expected the neural responses to be a sum of only a few different filters and only at a few different positions. This would mean t...
### do not use these settings and passwords for production! # these settings are required to connect the postgres-db to metabase POSTGRES_USER='postgres' POSTGRES_PASSWORD='1234' POSTGRES_HOST='postgresdb' POSTGRES_PORT='5432' POSTGRES_DB_NAME='postgres'
postgres_user = 'postgres' postgres_password = '1234' postgres_host = 'postgresdb' postgres_port = '5432' postgres_db_name = 'postgres'
# # Sunny data # outFeaturesPath = "models/features_40_sun_only" # outLabelsPath = "models/labels_sun_only" # imageFolderName = 'IMG_sun_only' # features_directory = '../data/' # labels_file = '../data/driving_log_sun_only.csv' # modelPath = 'models/MsAutopilot_sun_only.h5' # NoColumns = 3 # steering value index in csv...
out_features_path = 'models/features_40_fog_only' out_labels_path = 'models/labels_fog_only' image_folder_name = 'IMG_fog_only' features_directory = '../data/' labels_file = '../data/driving_log_fog_only.csv' no_columns = 3 model_path_foggy = 'models/MsAutopilot_foggy.h5' model_path_sun_only = 'models/MsAutopilot_sun_o...
with open('inputs/input2.txt') as fin: raw = fin.read() def parse(raw): start = [(x[:3], int(x[4:])) for x in (raw.split('\n'))] return start a = parse(raw) def part_1(arr): indices = set() acc = 0 i = 0 while i < len(arr): pair = arr[i] if i in indices: bre...
with open('inputs/input2.txt') as fin: raw = fin.read() def parse(raw): start = [(x[:3], int(x[4:])) for x in raw.split('\n')] return start a = parse(raw) def part_1(arr): indices = set() acc = 0 i = 0 while i < len(arr): pair = arr[i] if i in indices: break ...
################################ A Library of Functions ################################## ################################################################################################## #simple function which displays a matrix def matrixDisplay(M): for i in range(len(M)): for j in range(len...
def matrix_display(M): for i in range(len(M)): for j in range(len(M[i])): print(M[i][j], end=' ') print() def matrix_product(L, M): if len(L[0]) != len(M): print('Matrix multiplication not possible.') else: print('Multiplying the two matrices: ') p = [[0 ...
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: def DFS(root): if not root: return 0 if not root.left and not root.right : return int(root.val) if root.left: root.left.val = 10 * root.val + root.left.val if root.right: root.right.val = 1...
class Solution: def sum_numbers(self, root: Optional[TreeNode]) -> int: def dfs(root): if not root: return 0 if not root.left and (not root.right): return int(root.val) if root.left: root.left.val = 10 * root.val + root.le...
# Copyright (c) 2010-2022 openpyxl """ List of builtin formulae """ FORMULAE = ("CUBEKPIMEMBER", "CUBEMEMBER", "CUBEMEMBERPROPERTY", "CUBERANKEDMEMBER", "CUBESET", "CUBESETCOUNT", "CUBEVALUE", "DAVERAGE", "DCOUNT", "DCOUNTA", "DGET", "DMAX", "DMIN", "DPRODUCT", "DSTDEV", "DSTDEVP", "DSUM", "DVAR", "DVARP", "DATE", "D...
""" List of builtin formulae """ formulae = ('CUBEKPIMEMBER', 'CUBEMEMBER', 'CUBEMEMBERPROPERTY', 'CUBERANKEDMEMBER', 'CUBESET', 'CUBESETCOUNT', 'CUBEVALUE', 'DAVERAGE', 'DCOUNT', 'DCOUNTA', 'DGET', 'DMAX', 'DMIN', 'DPRODUCT', 'DSTDEV', 'DSTDEVP', 'DSUM', 'DVAR', 'DVARP', 'DATE', 'DATEDIF', 'DATEVALUE', 'DAY', 'DAYS360...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2021, Cisco Systems # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) DOCUMENTATION = r""" --- module: network_device short_description: Resource module for Network Device description: - Manage operations create, upda...
documentation = "\n---\nmodule: network_device\nshort_description: Resource module for Network Device\ndescription:\n- Manage operations create, update and delete of the resource Network Device.\nversion_added: '1.0.0'\nauthor: Rafael Campos (@racampos)\noptions:\n NetworkDeviceGroupList:\n description: List of Net...
class OrderCodeAlreadyExists(Exception): pass class DealerDoesNotExist(Exception): pass class OrderDoesNotExist(Exception): pass class StatusNotAllowed(Exception): pass
class Ordercodealreadyexists(Exception): pass class Dealerdoesnotexist(Exception): pass class Orderdoesnotexist(Exception): pass class Statusnotallowed(Exception): pass
# -*- coding: utf-8 -*- # Copyright (c) 2017-18 Richard Hull and contributors # See LICENSE.rst for details. _DIGITS = { ' ': 0x00, '-': 0x01, '_': 0x08, '\'': 0x02, '0': 0x7e, '1': 0x30, '2': 0x6d, '3': 0x79, '4': 0x33, '5': 0x5b, '6': 0x5f, '7': 0x70, '8': 0x7f, ...
_digits = {' ': 0, '-': 1, '_': 8, "'": 2, '0': 126, '1': 48, '2': 109, '3': 121, '4': 51, '5': 91, '6': 95, '7': 112, '8': 127, '9': 123, 'a': 125, 'b': 31, 'c': 13, 'd': 61, 'e': 111, 'f': 71, 'g': 123, 'h': 23, 'i': 16, 'j': 24, 'l': 6, 'n': 21, 'o': 29, 'p': 103, 'q': 115, 'r': 5, 's': 91, 't': 15, 'u': 28, 'v': 28...
"""Hex Grid, by Al Sweigart al@inventwithpython.com Displays a simple tessellation of a hexagon grid. This and other games are available at https://nostarch.com/XX Tags: tiny, beginner, artistic""" __version__ = 0 # Set up the constants: # (!) Try changing these values to other numbers: X_REPEAT = 19 # How many times ...
"""Hex Grid, by Al Sweigart al@inventwithpython.com Displays a simple tessellation of a hexagon grid. This and other games are available at https://nostarch.com/XX Tags: tiny, beginner, artistic""" __version__ = 0 x_repeat = 19 y_repeat = 12 for y in range(Y_REPEAT): for x in range(X_REPEAT): print('/ \\_',...
class FlameTextEdit(QtWidgets.QTextEdit): """ Custom Qt Flame Text Edit Widget To use: text_edit = FlameTextEdit('some_text_here', True_or_False, window) """ def __init__(self, text, read_only, parent_window, *args, **kwargs): super(FlameTextEdit, self).__init__(*args, **kwargs) ...
class Flametextedit(QtWidgets.QTextEdit): """ Custom Qt Flame Text Edit Widget To use: text_edit = FlameTextEdit('some_text_here', True_or_False, window) """ def __init__(self, text, read_only, parent_window, *args, **kwargs): super(FlameTextEdit, self).__init__(*args, **kwargs) ...
# merge sort # h/t https://www.thecrazyprogrammer.com/2017/12/python-merge-sort.html # h/t https://www.youtube.com/watch?v=Nso25TkBsYI def merge_sort(array): n = len(array) if n > 1: mid = n//2 left = array[0:mid] right = array[mid:n] print(mid, left, right, array) ...
def merge_sort(array): n = len(array) if n > 1: mid = n // 2 left = array[0:mid] right = array[mid:n] print(mid, left, right, array) merge_sort(left) merge_sort(right) merge(left, right, array, n) def merge(left, right, array, array_length): right_len...
# Lucas Sequence Using Recursion def recur_luc(n): if n == 1: return n if n == 0: return 2 return (recur_luc(n-1) + recur_luc(n-2)) limit = int(input("How many terms to include in Lucas series:")) print("Lucas series:") for i in range(limit): print(recur_luc(i))
def recur_luc(n): if n == 1: return n if n == 0: return 2 return recur_luc(n - 1) + recur_luc(n - 2) limit = int(input('How many terms to include in Lucas series:')) print('Lucas series:') for i in range(limit): print(recur_luc(i))
# encoding: utf-8 """Exceptions used by marrow.mailer to report common errors.""" __all__ = [ 'MailException', 'MailConfigurationException', 'TransportException', 'TransportFailedException', 'MessageFailedException', 'TransportExhaustedException', 'ManagerExcep...
"""Exceptions used by marrow.mailer to report common errors.""" __all__ = ['MailException', 'MailConfigurationException', 'TransportException', 'TransportFailedException', 'MessageFailedException', 'TransportExhaustedException', 'ManagerException'] class Mailexception(Exception): """The base for all marrow.mailer ...
# # PySNMP MIB module RBN-SYS-SECURITY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBN-SYS-SECURITY-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:53:26 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, constraints_union, single_value_constraint, value_size_constraint, value_range_constraint) ...
lines = open('input.txt').read().splitlines() matches = {'(': ')', '[': ']', '{': '}', '<': '>'} penalty = {')': 3, ']': 57, '}': 1197, '>': 25137} costs = {')': 1, ']': 2, '}': 3, '>': 4} errors = [] incpl_costs = [] for i, l in enumerate(lines): expected_closings = [] for c in l: if c in matches.key...
lines = open('input.txt').read().splitlines() matches = {'(': ')', '[': ']', '{': '}', '<': '>'} penalty = {')': 3, ']': 57, '}': 1197, '>': 25137} costs = {')': 1, ']': 2, '}': 3, '>': 4} errors = [] incpl_costs = [] for (i, l) in enumerate(lines): expected_closings = [] for c in l: if c in matches.key...
# Time: O(n^2) # Space: O(1) # 892 # On a N * N grid, we place some 1 * 1 * 1 cubes. # # Each value v = grid[i][j] represents a tower of v cubes # placed on top of grid cell (i, j). # # Return the total surface area of the resulting shapes. # # Example 1: # # Input: [[2]] # Output: 10 # Example 2: # # Input: [[1,2],[...
class Solution(object): def surface_area(self, grid): """ :type grid: List[List[int]] :rtype: int """ result = 0 for i in xrange(len(grid)): for j in xrange(len(grid)): if grid[i][j]: result += 2 + grid[i][j] * 4 ...
# 1109. Corporate Flight Bookings # Weekly Contest 144 # Time: O(len(n)) # Space: O(n) class Solution: def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: """ Shorter solution: """ res = [0]*(n+1) for i,j,k in bookings: res[i-1]+=k ...
class Solution: def corp_flight_bookings(self, bookings: List[List[int]], n: int) -> List[int]: """ Shorter solution: """ res = [0] * (n + 1) for (i, j, k) in bookings: res[i - 1] += k res[j] -= k for i in range(1, n): res[i] += re...
# Given a sorted array of integers, find the starting and ending position of a given target value. # Your algorithm's runtime complexity must be in the order of O(log n). # If the target is not found in the array, return [-1, -1]. # For example, # Given [5, 7, 7, 8, 8, 10] and target value 8, # return [3, 4]. ...
def search_range(numbers, target): result = [-1, -1] if len(numbers) == 0: return result low = 0 high = len(numbers) - 1 while low <= high: mid = low + (high - low) // 2 if numbers[mid] >= target: high = mid - 1 else: low = mid + 1 if low <...
# -*- coding: utf-8 -*- """ flaskbb.core.exceptions ~~~~~~~~~~~~~~~~~~~~~~~ Exceptions raised by flaskbb.core, forms the root of all exceptions in FlaskBB. :copyright: (c) 2014-2018 the FlaskBB Team :license: BSD, see LICENSE for more details """ class BaseFlaskBBError(Exception): ""...
""" flaskbb.core.exceptions ~~~~~~~~~~~~~~~~~~~~~~~ Exceptions raised by flaskbb.core, forms the root of all exceptions in FlaskBB. :copyright: (c) 2014-2018 the FlaskBB Team :license: BSD, see LICENSE for more details """ class Baseflaskbberror(Exception): """ Root exception for ...
class Solution(object): def romanToInt(self, s): """ :type s: str :rtype: int """ lm2int = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} s_len_num = len(s) ans = 0 # for i in range(s_len_num-1): # if lm...
class Solution(object): def roman_to_int(self, s): """ :type s: str :rtype: int """ lm2int = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} s_len_num = len(s) ans = 0 lm2int = {'I': 1, 'IV': 3, 'V': 5, 'IX': 8, 'X': 10, 'XL': 30, 'L...
# https://leetcode.com/problems/climbing-stairs/ # --------------------------------------------------- # Runtime Complexity: O(n) # Space Complexity: O(1) class Solution: def climbStairs(self, n: int) -> int: if n <= 2: return n prev_prev = 1 prev = 2 cur = 0 f...
class Solution: def climb_stairs(self, n: int) -> int: if n <= 2: return n prev_prev = 1 prev = 2 cur = 0 for i in range(3, n + 1): cur = prev_prev + prev (prev_prev, prev) = (prev, cur) return cur solution = solution() print(solut...
""" Behavioral pattern: Iterator => 1.Iterable 2.Iteration Requirements that should know: __iter__ , __next__ """ class Iteration: def __init__(self, value): self.value = value def __next__(self): if self.value == 0: raise StopIteration('End of sequence') ...
""" Behavioral pattern: Iterator => 1.Iterable 2.Iteration Requirements that should know: __iter__ , __next__ """ class Iteration: def __init__(self, value): self.value = value def __next__(self): if self.value == 0: raise stop_iteration('End of sequence')...
def urlify(s, i): p1, p2 = len(s) - 1, i while p1 >= 0 and p2 >= 0: if s[p2] != " ": s[p1] = s[p2] else: for i in reversed("%20"): s[p1] = i p1 -= 1 p1 -= 1 p2 -= 1
def urlify(s, i): (p1, p2) = (len(s) - 1, i) while p1 >= 0 and p2 >= 0: if s[p2] != ' ': s[p1] = s[p2] else: for i in reversed('%20'): s[p1] = i p1 -= 1 p1 -= 1 p2 -= 1
# Example 1: # Input: candidates = [2,3,6,7], target = 7 # Output: [[2,2,3],[7]] # Explanation: # 2 and 3 are candidates, and 2 + 2 + 3 = 7. # Note that 2 can be used multiple times. # 7 is a candidate, and 7 = 7. # These are the only two combinations. # Example 2: # Input: candidates = [2,3,5], target = 8 # Output: [...
class Solution: def combination_sum(self, candidates: List[int], target: int) -> List[List[int]]: comb = [[] if i > 0 else [[]] for i in range(target + 1)] for candidate in candidates: for i in range(candidate, len(comb)): comb[i].extend((comb + [candidate] for comb in c...
################################################# # Unit helpers # ################################################# class Length(float): unit2m = dict(mm=0.001, cm=0.01, dm=0.1, m=1, km=1000) def __new__(cls, val, unit): return float.__new__(cls, val) def __init...
class Length(float): unit2m = dict(mm=0.001, cm=0.01, dm=0.1, m=1, km=1000) def __new__(cls, val, unit): return float.__new__(cls, val) def __init__(self, val, unit): assert unit in Length.unit2m, 'Unknown units' self.unit = unit def __str__(self): return f'{float(self...
command = input() student_ticket = 0 standard_ticket = 0 kid_ticket = 0 while command != "Finish": seats = int(input()) ticket_type = input() tickets_sold = 0 while seats > tickets_sold: tickets_sold += 1 if ticket_type == "student": student_ticket += 1 elif ticke...
command = input() student_ticket = 0 standard_ticket = 0 kid_ticket = 0 while command != 'Finish': seats = int(input()) ticket_type = input() tickets_sold = 0 while seats > tickets_sold: tickets_sold += 1 if ticket_type == 'student': student_ticket += 1 elif ticket_ty...
META_SITE_DOMAIN = 'www.geocoptix.com' META_USE_OG_PROPERTIES = True META_USE_TWITTER_PROPERTIES = True META_TWITTER_AUTHOR = 'geocoptix' META_FB_AUTHOR_URL = 'https://facebook.com/geocoptix'
meta_site_domain = 'www.geocoptix.com' meta_use_og_properties = True meta_use_twitter_properties = True meta_twitter_author = 'geocoptix' meta_fb_author_url = 'https://facebook.com/geocoptix'
def extractMyFirstTimeTranslating(item): """ 'My First Time Translating' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None return False
def extract_my_first_time_translating(item): """ 'My First Time Translating' """ (vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None return False
class Toggle_Button(QPushButton): sent_fix = pyqtSignal(bool, int, bool) def __init__(self, currentRowCount): QPushButton.__init__(self, "ON") # self.setFixedSize(100, 100) self.currentRowCount = self.rowCount() self.setStyleSheet("background-color: green") self.setChecka...
class Toggle_Button(QPushButton): sent_fix = pyqt_signal(bool, int, bool) def __init__(self, currentRowCount): QPushButton.__init__(self, 'ON') self.currentRowCount = self.rowCount() self.setStyleSheet('background-color: green') self.setCheckable(True) self.toggled.conne...
TBD = None img_norm_cfg = dict(mean=TBD, std=TBD, to_rgb=TBD) train_pipeline = TBD test_pipeline = TBD # dataset settings dataset_type = 'VOCDataset' data_root = 'data/VOCdevkit/' dataset_repeats = 10 data = dict( samples_per_gpu=TBD, workers_per_gpu=TBD, train=dict( type='RepeatDataset', ...
tbd = None img_norm_cfg = dict(mean=TBD, std=TBD, to_rgb=TBD) train_pipeline = TBD test_pipeline = TBD dataset_type = 'VOCDataset' data_root = 'data/VOCdevkit/' dataset_repeats = 10 data = dict(samples_per_gpu=TBD, workers_per_gpu=TBD, train=dict(type='RepeatDataset', times=dataset_repeats, dataset=dict(type=dataset_ty...
load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest") load( "//:coursier.bzl", "add_netrc_entries_from_mirror_urls", "compute_dependency_inputs_signature", "extract_netrc_from_auth_url", "get_coursier_cache_or_default", "get_netrc_lines_from_entries", "remove_auth_from_url", "sp...
load('@bazel_skylib//lib:unittest.bzl', 'asserts', 'unittest') load('//:coursier.bzl', 'add_netrc_entries_from_mirror_urls', 'compute_dependency_inputs_signature', 'extract_netrc_from_auth_url', 'get_coursier_cache_or_default', 'get_netrc_lines_from_entries', 'remove_auth_from_url', 'split_url', infer='infer_artifact_p...
# ------------------------------------------------------------------------------ # class Attributes (object) : # FIXME: add method sigs # -------------------------------------------------------------------------- # def __init__ (self, vals={}) : raise Exception ("%s is not implemented" % se...
class Attributes(object): def __init__(self, vals={}): raise exception('%s is not implemented' % self.__class__.__name__)
class IdGenerator(object): number = 0 @staticmethod def next(): tmp = IdGenerator.number IdGenerator.number += 1 return str(tmp)
class Idgenerator(object): number = 0 @staticmethod def next(): tmp = IdGenerator.number IdGenerator.number += 1 return str(tmp)
# Copyright (c) 2016 Vivaldi Technologies AS. All rights reserved { 'targets': [ { 'target_name': 'vivaldi_browser', 'type': 'static_library', 'dependencies': [ 'app/vivaldi_resources.gyp:*', 'chromium/base/base.gyp:base', 'chromium/components/components.gyp:search_engine...
{'targets': [{'target_name': 'vivaldi_browser', 'type': 'static_library', 'dependencies': ['app/vivaldi_resources.gyp:*', 'chromium/base/base.gyp:base', 'chromium/components/components.gyp:search_engines', 'chromium/chrome/chrome_resources.gyp:chrome_resources', 'chromium/chrome/chrome_resources.gyp:chrome_strings', 'c...
# Definition for singly-linked list. class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ ...
class Listnode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def rotate_right(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ current = head length = 0 ...
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
def split(arr, size): """Splits an array to smaller arrays of size""" arrays = [] while len(arr) > size: piece = arr[:size] arrays.append(piece) arr = arr[size:] arrays.append(arr) return arrays def take_out_elements(list_object, indices): """Removes elements from list i...
# -*- coding: utf-8 -*- """ 1287. Element Appearing More Than 25% In Sorted Array Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time. Return that integer. Constraints: 1 <= arr.length <= 10^4 0 <= arr[i] <= 10^5 """ class Solution...
""" 1287. Element Appearing More Than 25% In Sorted Array Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time. Return that integer. Constraints: 1 <= arr.length <= 10^4 0 <= arr[i] <= 10^5 """ class Solution: def find_special_i...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ib.ext.cfg.CommissionReport -> config module for CommissionReport.java. """
""" ib.ext.cfg.CommissionReport -> config module for CommissionReport.java. """
class Solution: def plusOne(self, digits): """ 66. Plus One https://leetcode.com/problems/plus-one """ for i in range(len(digits)): if digits[-i] < 9: digits[-i] += 1 return digits digits[-i] = 0 return [1] + [0]...
class Solution: def plus_one(self, digits): """ 66. Plus One https://leetcode.com/problems/plus-one """ for i in range(len(digits)): if digits[-i] < 9: digits[-i] += 1 return digits digits[-i] = 0 return [1] + [...
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'chromium_code': 1, }, 'targets': [], 'conditions': [ # The CrNet build is ninja-only because of the hack in # ios/build...
{'variables': {'chromium_code': 1}, 'targets': [], 'conditions': [['OS=="ios" and "<(GENERATOR)"=="ninja"', {'targets': [{'target_name': 'crnet_test', 'type': 'executable', 'dependencies': ['../../../ios/crnet/crnet.gyp:crnet', '../../../ios/third_party/gcdwebserver/gcdwebserver.gyp:gcdwebserver', '../../../testing/gte...
input = """ d(1). d(2). d(3). d(4) :- #count{V : d(V)} > 2. """ output = """ d(1). d(2). d(3). d(4) :- #count{V : d(V)} > 2. """
input = '\nd(1).\nd(2).\nd(3).\n\nd(4) :- #count{V : d(V)} > 2.\n\n' output = '\nd(1).\nd(2).\nd(3).\n\nd(4) :- #count{V : d(V)} > 2.\n\n'
def parse_map(in_file): with open(in_file) as f: lines = f.read().splitlines() width = len(lines[0]) height = len(lines) points = {} for x in range(width): for y in range(height): points[(x, y)] = lines[y][x] return points, width, height def solve(in_file): (poi...
def parse_map(in_file): with open(in_file) as f: lines = f.read().splitlines() width = len(lines[0]) height = len(lines) points = {} for x in range(width): for y in range(height): points[x, y] = lines[y][x] return (points, width, height) def solve(in_file): (poin...
"""125. Backpack II """ class Solution: """ @param m: An integer m denotes the size of a backpack @param A: Given n items with size A[i] @param V: Given n items with value V[i] @return: The maximum value """ def backPackII(self, m, A, V): # write your code here dp = [[float('...
"""125. Backpack II """ class Solution: """ @param m: An integer m denotes the size of a backpack @param A: Given n items with size A[i] @param V: Given n items with value V[i] @return: The maximum value """ def back_pack_ii(self, m, A, V): dp = [[float('-inf')] * (m + 1) for _ in ...
a1=input("whats your age") a2=input("whats your age") int(a1) int(a2) age=int(a1)-int(a2) print(abs(age))
a1 = input('whats your age') a2 = input('whats your age') int(a1) int(a2) age = int(a1) - int(a2) print(abs(age))