content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
msg = "\nU cannot do it with the zero under there!!!" def mean(num_list): if len(num_list)== 0: raise Exception(msg) else: return sum(num_list)/len(num_list) def mean2(num_list): try: return sum(num_list)/len(num_list) except ZeroDivisionError as detail: raise ZeroDivisionError(detail.__str__() + msg) e...
msg = '\nU cannot do it with the zero under there!!!' def mean(num_list): if len(num_list) == 0: raise exception(msg) else: return sum(num_list) / len(num_list) def mean2(num_list): try: return sum(num_list) / len(num_list) except ZeroDivisionError as detail: raise zero...
# where output is the value per line # loop through the values # print the value of the letter plus the next letter for n number of times # n = a number (1-10) that represents how many characters are in a line # once you have printed n number of times, '\n' output = '' #for value in range(65, 91, 1): for i in range...
output = '' for i in range(5): for j in range(i + 1): print('* ', end='') print('\n')
#!/usr/bin/env python3 N, T = list(map(int, input().strip().split(' '))) width = list(map(int, input().strip().split(' '))) for _ in range(T): i, j = list(map(int, input().strip().split(' '))) print(min(width[i:j + 1]))
(n, t) = list(map(int, input().strip().split(' '))) width = list(map(int, input().strip().split(' '))) for _ in range(T): (i, j) = list(map(int, input().strip().split(' '))) print(min(width[i:j + 1]))
# Task # Apply your knowledge of the .add() operation to help your friend Rupal. # Rupal has a huge collection of country stamps. She decided to count the # total number of distinct country stamps in her collection. She asked for # your help. You pick the stamps one by one from a stack of N country stamps. # Find the t...
n = int(input()) countries = set() for i in range(N): countries.add(input()) print(len(countries))
def get_profile(name: str, age: int, *args, **kwargs): if len(list(args)) > 5: raise ValueError if not isinstance(age, int): raise ValueError profile = dict(name=name, age=age,) if args: profile.update(sports=sorted(list(args))) if kwargs: profile.update(awards=kwarg...
def get_profile(name: str, age: int, *args, **kwargs): if len(list(args)) > 5: raise ValueError if not isinstance(age, int): raise ValueError profile = dict(name=name, age=age) if args: profile.update(sports=sorted(list(args))) if kwargs: profile.update(awards=kwargs)...
class Klasse: def __init__(self, wert): self.attribut = wert def print_attribut(self): print(self.attribut) def main(): a = Klasse(3) b = Klasse(12) a.attribut = -a.attribut b.print_attribut()
class Klasse: def __init__(self, wert): self.attribut = wert def print_attribut(self): print(self.attribut) def main(): a = klasse(3) b = klasse(12) a.attribut = -a.attribut b.print_attribut()
def uninstall(distro, purge=False): packages = [ 'ceph', 'ceph-mds', 'ceph-common', 'ceph-fs-common', 'radosgw', ] extra_remove_flags = [] if purge: extra_remove_flags.append('--purge') distro.packager.remove( packages, extra_remove...
def uninstall(distro, purge=False): packages = ['ceph', 'ceph-mds', 'ceph-common', 'ceph-fs-common', 'radosgw'] extra_remove_flags = [] if purge: extra_remove_flags.append('--purge') distro.packager.remove(packages, extra_remove_flags=extra_remove_flags)
class Solution: def isPrefixOfWord(self, sentence: str, searchWord: str) -> int: sentence = sentence.split() k = len(searchWord) for i, word in enumerate(sentence): if word[:k] == searchWord: return i+1 return -1
class Solution: def is_prefix_of_word(self, sentence: str, searchWord: str) -> int: sentence = sentence.split() k = len(searchWord) for (i, word) in enumerate(sentence): if word[:k] == searchWord: return i + 1 return -1
# # PySNMP MIB module WLSX-WLAN-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WLSX-WLAN-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:36:48 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
(wlsx_enterprise_mib_modules,) = mibBuilder.importSymbols('ARUBA-MIB', 'wlsxEnterpriseMibModules') (aruba_vlan_valid_range, aruba_rogue_ap_type, aruba_ap_status, aruba_access_point_mode, aruba_monitor_mode, aruba_antenna_setting, aruba_enet1_mode, aruba_phy_type, aruba_ht_mode, aruba_voip_protocol_type, aruba_mesh_role...
class Salsa: def __init__(self,r=20): assert r >= 0 self._r = r # number of rounds self._mask = 0xffffffff # 32-bit mask def __call__(self,key=[0]*32,nonce=[0]*8,block_counter=[0]*8): assert len(key) == 32 assert len(nonce) == 8 assert len(block_counter) == 8 # init state k ...
class Salsa: def __init__(self, r=20): assert r >= 0 self._r = r self._mask = 4294967295 def __call__(self, key=[0] * 32, nonce=[0] * 8, block_counter=[0] * 8): assert len(key) == 32 assert len(nonce) == 8 assert len(block_counter) == 8 k = [self._little...
def parentheses_balance_stack_check(expression): open_list, close_list, stack = ['[', '{', '('], [']', '}', ')'], [] for i in expression: if i in open_list: stack.append(i) elif i in close_list: pos = close_list.index(i) if len(stack) > 0 and open_list[pos] == stack[len(stack) - 1]: ...
def parentheses_balance_stack_check(expression): (open_list, close_list, stack) = (['[', '{', '('], [']', '}', ')'], []) for i in expression: if i in open_list: stack.append(i) elif i in close_list: pos = close_list.index(i) if len(stack) > 0 and open_list[pos...
# -*- coding: utf-8 -*- #%% configs VOCdatasetConfig= { 'rootDir': "D:\GitHubRepos\ML_learning\VOC2007", 'imageFolder': "JPEGImages", 'imageExtension': ".jpg", 'annotationFolder': "Annotations", 'annotationExtension': ".xml", 'trainCasesPath': "ImageSets\Segmentation\\train.txt", 'valCase...
vo_cdataset_config = {'rootDir': 'D:\\GitHubRepos\\ML_learning\\VOC2007', 'imageFolder': 'JPEGImages', 'imageExtension': '.jpg', 'annotationFolder': 'Annotations', 'annotationExtension': '.xml', 'trainCasesPath': 'ImageSets\\Segmentation\\train.txt', 'valCasesPath': 'ImageSets\\Segmentation\\val.txt', 'textFileFolder':...
def get_sunday_count(): sunday_count = 0 for i in range(1901, 2000): for j in range(1, 12): for k in range(1, get_number_of_days(j, i)): if j == 2000: c = 20 else: c = 19 f = k + ((13 * j - 1) / 5) + ((i ...
def get_sunday_count(): sunday_count = 0 for i in range(1901, 2000): for j in range(1, 12): for k in range(1, get_number_of_days(j, i)): if j == 2000: c = 20 else: c = 19 f = k + (13 * j - 1) / 5 + (i - 1...
# # PySNMP MIB module PCUBE-SE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PCUBE-SE-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:11:29 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint, constraints_union) ...
MODEL_FOLDER_NAME = 'models' FASTTEXT_MODEL_NAME = 'fasttext.magnitude' GLOVE_MODEL_NAME = 'glove.magnitude' WORD2VEC_MODEL_NAME = 'word2vec.magnitude' ELMO_MODEL_NAME = 'elmo.magnitude' BERT_MODEL_NAME = '' UNIVERSAL_SENTENCE_ENCODER_MODEL_NAME = 'https://tfhub.dev/google/universal-sentence-encoder/1' DB_STORAGE_TYPE ...
model_folder_name = 'models' fasttext_model_name = 'fasttext.magnitude' glove_model_name = 'glove.magnitude' word2_vec_model_name = 'word2vec.magnitude' elmo_model_name = 'elmo.magnitude' bert_model_name = '' universal_sentence_encoder_model_name = 'https://tfhub.dev/google/universal-sentence-encoder/1' db_storage_type...
def CHECK(UNI, PWI, usernameArray, PasswordArray): for UN in usernameArray: if UN == UNI: for PW in PasswordArray: if PW == PWI: if usernameArray.index(UNI) == PasswordArray.index(PWI): return True def login(correctMessage,...
def check(UNI, PWI, usernameArray, PasswordArray): for un in usernameArray: if UN == UNI: for pw in PasswordArray: if PW == PWI: if usernameArray.index(UNI) == PasswordArray.index(PWI): return True def login(correctMessage, inCorrectMe...
m = [ 'common', 'leap' ] y = 2024 # outside in if y%4 ==0: if y%100 ==0: if y%400 ==0: y=1 else: y=0 else: y=1 else: y=0 print(m[y]) # inside out y=2024 if y%400==0: y=1 elif y%100==0: y=0 elif y%4==0: y=1 else: y=0 print(m[y])...
m = ['common', 'leap'] y = 2024 if y % 4 == 0: if y % 100 == 0: if y % 400 == 0: y = 1 else: y = 0 else: y = 1 else: y = 0 print(m[y]) y = 2024 if y % 400 == 0: y = 1 elif y % 100 == 0: y = 0 elif y % 4 == 0: y = 1 else: y = 0 print(m[y]) y = 2...
def create_markdown_content( input_file: str, import_list: list[str], global_import_table: dict[str,str], mermaid_diagrams: list[str], debug_dump: str, ) -> str: debug_block = create_markdown_debug_dump_block(debug_content=debug_dump) import_block = turn_out_the_import_list( import_...
def create_markdown_content(input_file: str, import_list: list[str], global_import_table: dict[str, str], mermaid_diagrams: list[str], debug_dump: str) -> str: debug_block = create_markdown_debug_dump_block(debug_content=debug_dump) import_block = turn_out_the_import_list(import_list=import_list, global_import_...
# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incor...
def maintenance_public_configuration_list(client): return client.list() def maintenance_public_configuration_show(client, resource_name): return client.get(resource_name=resource_name) def maintenance_applyupdate_show(client, resource_group_name, provider_name, resource_type, resource_name, apply_update_name)...
class Solution: def subarraySum(self, nums: List[int], k: int) -> int: cum_sum = [0] for num in nums: cum_sum.append(num+cum_sum[-1]) cum_sum.pop(0) seen_map = {0:1} ans = 0 for csum in cum_sum: if csum-k in seen_map: ans+=s...
class Solution: def subarray_sum(self, nums: List[int], k: int) -> int: cum_sum = [0] for num in nums: cum_sum.append(num + cum_sum[-1]) cum_sum.pop(0) seen_map = {0: 1} ans = 0 for csum in cum_sum: if csum - k in seen_map: ans...
height = float(input("Please enter the height in m: \n")) weight = float(input("Please enter the weight in kg: \n")) bmi = weight / height ** 2 print(int(bmi))
height = float(input('Please enter the height in m: \n')) weight = float(input('Please enter the weight in kg: \n')) bmi = weight / height ** 2 print(int(bmi))
#The file contains only the CTC function and the proposed model format. (Not the complete code) def ctc_lambda_func(args): y_pred, labels, input_length, label_length = args y_pred = y_pred[:, 2:, :] return K.ctc_batch_cost(labels, y_pred, input_length, label_length) def train(img_w, load=False): # I...
def ctc_lambda_func(args): (y_pred, labels, input_length, label_length) = args y_pred = y_pred[:, 2:, :] return K.ctc_batch_cost(labels, y_pred, input_length, label_length) def train(img_w, load=False): img_h = 64 conv_filters = 16 kernel_size = (3, 3) pool_size = 2 time_dense_size = 32...
# -*- coding: utf-8 -*- __title__ = 'ahegao' __description__ = 'Ahegao API wrapper' __url__ = 'https://github.com/AhegaoTeam/AhegaoAPI' __version__ = '1.0.1' __build__ = 11 __author__ = 'SantaSpeen' __author_email__ = 'admin@ahegao.ovh' __license__ = "MIT" __copyright__ = 'Copyright 2022 Ahegao Team'
__title__ = 'ahegao' __description__ = 'Ahegao API wrapper' __url__ = 'https://github.com/AhegaoTeam/AhegaoAPI' __version__ = '1.0.1' __build__ = 11 __author__ = 'SantaSpeen' __author_email__ = 'admin@ahegao.ovh' __license__ = 'MIT' __copyright__ = 'Copyright 2022 Ahegao Team'
# design in each module class Cube(object): def __init__(self): pass class Rhombic(object): def __init__(self): pass class Sphere(object): def __init__(self): pass
class Cube(object): def __init__(self): pass class Rhombic(object): def __init__(self): pass class Sphere(object): def __init__(self): pass
# write a program to print out all the numbers from 0 to 100 that are divisble by 7 for i in range(0, 101, 7): print(i)
for i in range(0, 101, 7): print(i)
class Solution: def solve(self, matrix): pq = [[0, i] for i in range(len(matrix[0]))] for r in range(len(matrix)): new_pq = [] for c in range(len(matrix[0])): if pq[0][1] == c: top = heappop(pq) heappush(new_pq, [pq[0]...
class Solution: def solve(self, matrix): pq = [[0, i] for i in range(len(matrix[0]))] for r in range(len(matrix)): new_pq = [] for c in range(len(matrix[0])): if pq[0][1] == c: top = heappop(pq) heappush(new_pq, [pq[0][...
def rotate(text, key): num_letters = 26 key = key % num_letters l_min = ord('a') u_min = ord('A') text = list( map((lambda s: s if not s.isalpha() else chr(l_min + (((ord(s) - l_min) + key) % num_letters)) ...
def rotate(text, key): num_letters = 26 key = key % num_letters l_min = ord('a') u_min = ord('A') text = list(map(lambda s: s if not s.isalpha() else chr(l_min + (ord(s) - l_min + key) % num_letters) if s.islower() else chr(u_min + (ord(s) - u_min + key) % num_letters), list(text))) return ''.jo...
# coding: utf-8 def sumSquare(n): '''takes a positive integer n and returns sum of dquares of all the positive integers smaller than n''' if n < 0: return 'Needs a positive number. But Negative given' else: return sum([x**2 for x in range(1, n)]) print(sumSquare(4))
def sum_square(n): """takes a positive integer n and returns sum of dquares of all the positive integers smaller than n""" if n < 0: return 'Needs a positive number. But Negative given' else: return sum([x ** 2 for x in range(1, n)]) print(sum_square(4))
# # @lc app=leetcode id=327 lang=python3 # # [327] Count of Range Sum # # https://leetcode.com/problems/count-of-range-sum/description/ # # algorithms # Hard (35.94%) # Likes: 995 # Dislikes: 116 # Total Accepted: 48.9K # Total Submissions: 135.4K # Testcase Example: '[-2,5,-1]\n-2\n2' # # Given an integer array...
class Solution: def __init__(self): self.prefix_sum = [0] self.count = 0 def count_range_sum(self, nums: List[int], lower: int, upper: int) -> int: running_sum = 0 for i in range(len(nums)): running_sum += nums[i] self.prefix_sum.append(running_sum) ...
# Author: btjanaka (Bryon Tjanaka) # Problem: (HackerRank) the-minion-game # Title: The Minion Game # Link: https://www.hackerrank.com/challenges/the-minion-game/ # Idea: The basic idea is to count all substrings for each player, but we can't # just list out all the substrings because that is O(n^2), and the string can...
def minion_game(string): consonants = 0 vowels = 0 for i in range(len(string)): score = len(string) - i if string[i] in 'AEIOU': vowels += score else: consonants += score if consonants > vowels: print(f'Stuart {consonants}') elif consonants < v...
class APIException(OSError): def __init__(self, message = None, url="https://Bungie.net/"): msg = "There was an error when accessing the Destiny API" if message is not None: msg += ": " + message super().__init__(msg) self._url = url self._message = msg...
class Apiexception(OSError): def __init__(self, message=None, url='https://Bungie.net/'): msg = 'There was an error when accessing the Destiny API' if message is not None: msg += ': ' + message super().__init__(msg) self._url = url self._message = msg @prope...
IN_PREFIXES = { 'BA', 'BS', 'BUS MS', 'Certificate', 'Graduate Certificate', 'MA', 'Master of Arts', 'Master\'s', 'MBA/MA', 'ME Certificate', 'ME MD/PhD Program', 'ME Program', 'MS', 'P.B.C.', 'Post Bacc Certificate', 'Post Baccalaureate Certificate', ...
in_prefixes = {'BA', 'BS', 'BUS MS', 'Certificate', 'Graduate Certificate', 'MA', 'Master of Arts', "Master's", 'MBA/MA', 'ME Certificate', 'ME MD/PhD Program', 'ME Program', 'MS', 'P.B.C.', 'Post Bacc Certificate', 'Post Baccalaureate Certificate', "Post Master's Cert", 'Post-Baccalaureate Certificate', 'Post-Masters ...
class Disc: _instance_count = 0 def __init__(self, name, symbol, code=None): cls = type(self) self.code = cls._instance_count if code is None else code self.name = name self.symbol = symbol cls._instance_count += 1 if cls._instance_count < 1000 else 0 def __int__(se...
class Disc: _instance_count = 0 def __init__(self, name, symbol, code=None): cls = type(self) self.code = cls._instance_count if code is None else code self.name = name self.symbol = symbol cls._instance_count += 1 if cls._instance_count < 1000 else 0 def __int__(se...
def list_towers(): raise NotImplementedError def create_tower(body): raise NotImplementedError def get_tower(tower_id): raise NotImplementedError def update_tower(tower_id, body): raise NotImplementedError def delete_tower(tower_id): raise NotImplementedError
def list_towers(): raise NotImplementedError def create_tower(body): raise NotImplementedError def get_tower(tower_id): raise NotImplementedError def update_tower(tower_id, body): raise NotImplementedError def delete_tower(tower_id): raise NotImplementedError
# sample input array = [ 2, 1, 2, 2, 2, 3, 4, 2 ] to_move = 2 expected = [4, 1, 3, 2, 2, 2, 2, 2] # Simple testing function def test(expected, actual): if expected == actual: print('Working') else: print('Not working, expected:', expected, 'actual:', actual) # O(n) solution def move_element_to_...
array = [2, 1, 2, 2, 2, 3, 4, 2] to_move = 2 expected = [4, 1, 3, 2, 2, 2, 2, 2] def test(expected, actual): if expected == actual: print('Working') else: print('Not working, expected:', expected, 'actual:', actual) def move_element_to_end(array, toMove): i = 0 swap = len(array) - 1 ...
# # @lc app=leetcode.cn id=72 lang=python3 # # [72] edit-distance # None # @lc code=end
None
# # PySNMP MIB module HM2-NETCONFIG-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HM2-NETCONFIG-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:19:02 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) ...
def binary_search(A, target): A = str(A) lo = 0 hi = len(A) index = None while lo <= hi: mid = round(lo + (hi - lo) / 2) mid_ele = int(A[mid]) if mid_ele == target: index = mid break if mid_ele < target: lo = mid + 1 else:...
def binary_search(A, target): a = str(A) lo = 0 hi = len(A) index = None while lo <= hi: mid = round(lo + (hi - lo) / 2) mid_ele = int(A[mid]) if mid_ele == target: index = mid break if mid_ele < target: lo = mid + 1 else: ...
tree = PipelineElement('DecisionTreeClassifier', hyperparameters={'criterion': ['gini'], 'min_samples_split': IntegerRange(2, 4)}) svc = PipelineElement('LinearSVC', hyperparameters={'C': FloatRange(0.5, 25)}) my_pipe += Stack('fin...
tree = pipeline_element('DecisionTreeClassifier', hyperparameters={'criterion': ['gini'], 'min_samples_split': integer_range(2, 4)}) svc = pipeline_element('LinearSVC', hyperparameters={'C': float_range(0.5, 25)}) my_pipe += stack('final_stack', [tree, svc], use_probabilities=True) my_pipe += pipeline_element('LinearSV...
class Solution: def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]: ans = [] free = [] # (weight, index, freeTime) used = [] # (freeTime, weight, index) for i, weight in enumerate(servers): heapq.heappush(free, (weight, i, 0)) for i, executionTime in enumerate(tasks...
class Solution: def assign_tasks(self, servers: List[int], tasks: List[int]) -> List[int]: ans = [] free = [] used = [] for (i, weight) in enumerate(servers): heapq.heappush(free, (weight, i, 0)) for (i, execution_time) in enumerate(tasks): while used...
# # PySNMP MIB module XYLAN-IP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XYLAN-IP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:38:41 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, value_range_constraint, constraints_intersection, constraints_union, single_value_constraint) ...
class A: def f(self): print("f() in A") class B: def f(self): print("f() in B") class D(A,B): pass class E(B,A): pass print(D.mro()) print(E.mro()) d = D() d.f() e = E() e.f()
class A: def f(self): print('f() in A') class B: def f(self): print('f() in B') class D(A, B): pass class E(B, A): pass print(D.mro()) print(E.mro()) d = d() d.f() e = e() e.f()
''' * @Author: csy * @Date: 2019-04-28 13:50:45 * @Last Modified by: csy * @Last Modified time: 2019-04-28 13:50:45 ''' digits = list(range(0, 10)) print(digits) print(min(digits)) print(max(digits)) print(sum(digits))
""" * @Author: csy * @Date: 2019-04-28 13:50:45 * @Last Modified by: csy * @Last Modified time: 2019-04-28 13:50:45 """ digits = list(range(0, 10)) print(digits) print(min(digits)) print(max(digits)) print(sum(digits))
class constants: NONE = 0 X = 1 O = 2 class variables: explored = 0 def print_board(board): print(simbol(board[0])+"|"+simbol(board[1])+"|"+simbol(board[2])) print("-----") print(simbol(board[3])+"|"+simbol(board[4])+"|"+simbol(board[5])) print("-----") print(simbo...
class Constants: none = 0 x = 1 o = 2 class Variables: explored = 0 def print_board(board): print(simbol(board[0]) + '|' + simbol(board[1]) + '|' + simbol(board[2])) print('-----') print(simbol(board[3]) + '|' + simbol(board[4]) + '|' + simbol(board[5])) print('-----') print(simbol...
RequiredKeyIsMissing = \ "No value was found for the required key `{key_name}`" RequiredKeyIsWrongType = ( "Required key `{key_name}` has the wrong " + "type of `{invalid_type}`. The value of this key " + "should have the type `{expected_type}`" ) DirectiveStructureError = ( "The following directi...
required_key_is_missing = 'No value was found for the required key `{key_name}`' required_key_is_wrong_type = 'Required key `{key_name}` has the wrong ' + 'type of `{invalid_type}`. The value of this key ' + 'should have the type `{expected_type}`' directive_structure_error = 'The following directive `{directive}` has ...
def source(): pass def sink(x): pass def alarm(): x = source() sink(x)
def source(): pass def sink(x): pass def alarm(): x = source() sink(x)
# from: http://www.rosettacode.org/wiki/Babbage_problem#Python def main(): print([x for x in range(30000) if (x * x) % 1000000 == 269696][0]) if __name__ == "__main__": main()
def main(): print([x for x in range(30000) if x * x % 1000000 == 269696][0]) if __name__ == '__main__': main()
def song_decoder(song): result = song.replace("WUB" , " ") result = ' '.join(result.split()) return result
def song_decoder(song): result = song.replace('WUB', ' ') result = ' '.join(result.split()) return result
def print_row(star_count): for _ in range(star_count, size - 1): print(' ', end='') for _ in range(star_count): print('*', end=' ') print('*') size = int(input()) for star_count in range(size): print_row(star_count) for star_count in range(size - 2, -1, -1): print_row(star_count...
def print_row(star_count): for _ in range(star_count, size - 1): print(' ', end='') for _ in range(star_count): print('*', end=' ') print('*') size = int(input()) for star_count in range(size): print_row(star_count) for star_count in range(size - 2, -1, -1): print_row(star_count)
def recur_fibo(n): if n <= 1: return n else: return (recur_fibo(n - 1) + recur_fibo(n - 2)) nterms = int(input('You want output many elements ')) if nterms < 0: print('Enter the positive number') else: print("fibonacci sequence") for i in range(nterms): print(recur_fibo(i))...
def recur_fibo(n): if n <= 1: return n else: return recur_fibo(n - 1) + recur_fibo(n - 2) nterms = int(input('You want output many elements ')) if nterms < 0: print('Enter the positive number') else: print('fibonacci sequence') for i in range(nterms): print(recur_fibo(i))
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: n = len(numbers) last_num = None for i in range(n): num1 = numbers[i] if num1 != last_num: for j in range(i+1, n): num2 = numbers[j] ...
class Solution: def two_sum(self, numbers: List[int], target: int) -> List[int]: n = len(numbers) last_num = None for i in range(n): num1 = numbers[i] if num1 != last_num: for j in range(i + 1, n): num2 = numbers[j] ...
NInput = int(input()) xcoor = [] ycoor = [] for i in range(NInput): x, y = map(int, input().split()) xcoor.append(x) ycoor.append(y) for i in range(0, len(xcoor)): minIndex = i for j in range(i+1, len(xcoor)): if xcoor[j] < xcoor[minIndex]: xcoor[j], xcoor[minIndex] = xcoor[minIn...
n_input = int(input()) xcoor = [] ycoor = [] for i in range(NInput): (x, y) = map(int, input().split()) xcoor.append(x) ycoor.append(y) for i in range(0, len(xcoor)): min_index = i for j in range(i + 1, len(xcoor)): if xcoor[j] < xcoor[minIndex]: (xcoor[j], xcoor[minIndex]) = (xc...
# Should only need to modify these paths in this file: # - BTFM_BASE # - LSP_DATASET_DIR # - LSPET_DATASET_DIR # - COCO_DATASET_DIR # - MPII_DATASET_DIR # - TDPW_DATASET_DIR # - MI3_DATASET_DIR # - MI3_PP_DATASET_DIR # - UPI_S1H_DATASET_DIR # Note that this relies on a filesystem that supports symli...
btfm_base = '/media/data/btfm' btfm_pp = '/pp' btfm_pp_lsp = BTFM_PP + '/lsp' btfm_pp_lspet = BTFM_PP + '/lspet' btfm_pp_mpii = BTFM_PP + '/mpii' btfm_pp_3_dpw = BTFM_PP + '/3dpw' btfm_pp_3_dpw_silhouette = BTFM_PP_3DPW + '/silhouette' btfm_pp_3_dpw_silhouette_valid = BTFM_PP_3DPW + '/good_3dpw_annotations.pkl' btfm_pp...
class Solution: def calPoints(self, ops: List[str]) -> int: array = [] for op in ops: if op == 'C': array.pop() elif op == 'D': array.append(array[-1]*2) elif op == "+": array.append(array[-1] + array[-2]) ...
class Solution: def cal_points(self, ops: List[str]) -> int: array = [] for op in ops: if op == 'C': array.pop() elif op == 'D': array.append(array[-1] * 2) elif op == '+': array.append(array[-1] + array[-2]) ...
# stringparser.py # # Ronald Rihoo def findFirstQuotationMarkFromTheLeft(string): for i in xrange(len(string) - 1, 0, -1): if string[i] == '"': return i def findFirstQuotationMarkFromTheRight(string): for i in range(len(string)): if string[i] == '"': return i def splitLeftAspect_toChar(stri...
def find_first_quotation_mark_from_the_left(string): for i in xrange(len(string) - 1, 0, -1): if string[i] == '"': return i def find_first_quotation_mark_from_the_right(string): for i in range(len(string)): if string[i] == '"': return i def split_left_aspect_to_char(str...
#!/usr/bin/python # coding=utf-8 class Fibs(object): def __init__(self): self.a = 0 self.b = 1 def next(self): self.a, self.b = self.b, self.a + self.b return self.a def __iter__(self): return self if __name__ == "__main__": fibs = Fibs() for fib in fibs:...
class Fibs(object): def __init__(self): self.a = 0 self.b = 1 def next(self): (self.a, self.b) = (self.b, self.a + self.b) return self.a def __iter__(self): return self if __name__ == '__main__': fibs = fibs() for fib in fibs: if fib > 1000: ...
# This sample tests that arbitrary expressions (including # subscripts) work for decorators. This support was added # in Python 3.9. my_decorators = (staticmethod, classmethod, property) class Foo: # This should generate an error if version < 3.9. @my_decorators[0] def my_static_method(): return 3...
my_decorators = (staticmethod, classmethod, property) class Foo: @my_decorators[0] def my_static_method(): return 3 @my_decorators[1] def my_class_method(cls): return 3 @my_decorators[2] def my_property(self): return 3 Foo.my_static_method() Foo.my_class_method() foo(...
largura=l=int(input("digite a largura: ")) altura=a=int(input("digite a altura: ")) while altura>0: largura=l while largura >0: if (altura==a or altura ==1): print("#", end="") else: if largura==1 or largura ==l: print("#", end="") else: ...
largura = l = int(input('digite a largura: ')) altura = a = int(input('digite a altura: ')) while altura > 0: largura = l while largura > 0: if altura == a or altura == 1: print('#', end='') elif largura == 1 or largura == l: print('#', end='') else: p...
''' Author: jianzhnie Date: 2021-11-08 18:25:03 LastEditTime: 2022-02-25 11:12:28 LastEditors: jianzhnie Description: '''
""" Author: jianzhnie Date: 2021-11-08 18:25:03 LastEditTime: 2022-02-25 11:12:28 LastEditors: jianzhnie Description: """
#String Rotation:Assumeyou have a method isSubstringwhich checks if oneword is a substring of another. Given two strings, sl and s2, write code to check if s2 is a rotation of sl using only one call to isSubstring (e.g., "waterbottle" is a rotation of"erbottlewat"). #do special caracters as spaces are in the strign or ...
def rotation(str1, str2): ith = 0 jth = 0 while jth < len(str2): if str1[ith] == str2[jth]: ith += 1 else: ith = 0 jth += 1 return is_substring(str2[:-ith], str1) def is_substring(str1, str2): return str1 in str2 print(rotation('terbottlewa', 'erbottl...
def fromETH(amt, px): return amt*px def toETH(amt, px): return amt/px def toOVL(amt, px): return fromETH(amt, px) def fromOVL(amt, px): return toETH(amt, px) def px_from_ret(px0: float, ret: float) -> float: '''get the new price given a return''' ret = ret/100 return (ret + 1)*px0 def pn...
def from_eth(amt, px): return amt * px def to_eth(amt, px): return amt / px def to_ovl(amt, px): return from_eth(amt, px) def from_ovl(amt, px): return to_eth(amt, px) def px_from_ret(px0: float, ret: float) -> float: """get the new price given a return""" ret = ret / 100 return (ret + 1...
class Results: def __init__(self, error, error_type, description, sequence, activity=None, activity_class=None): self.error = error self.error_type = error_type self.description = description self.sequence = sequence self.activity = activity self.activity_class = acti...
class Results: def __init__(self, error, error_type, description, sequence, activity=None, activity_class=None): self.error = error self.error_type = error_type self.description = description self.sequence = sequence self.activity = activity self.activity_class = act...
n=3 z=65 for i in range(n): k=z for j in range(n-i): print(' ',end='') for j in range(2*i+1): print(chr(k),end='') k-=1 z=z+2 print() for i in range(1,n): c=z-4 for j in range(i): print(' ',end='') for j in range((2*n)-2*i-1): prin...
n = 3 z = 65 for i in range(n): k = z for j in range(n - i): print(' ', end='') for j in range(2 * i + 1): print(chr(k), end='') k -= 1 z = z + 2 print() for i in range(1, n): c = z - 4 for j in range(i): print(' ', end='') for j in range(2 * n - 2 * i - 1...
with open("pos_tweets.txt") as input_file: text = input_file.read() text_set = set(text.split(" ")) for word in text_set: print(word,text.count(word))
with open('pos_tweets.txt') as input_file: text = input_file.read() text_set = set(text.split(' ')) for word in text_set: print(word, text.count(word))
#coding=utf-8 __all__ = ["ModelConfig", "TrainerConfig"] class ModelConfig(object): vocab_size = 104810 embedding_dim = 300 embedding_droprate = 0.3 lstm_depth = 3 lstm_hidden_dim = 300 lstm_hidden_droprate = 0.3 passage_indep_embedding_dim = 300 passage_aligned_embedding_dim = 300 ...
__all__ = ['ModelConfig', 'TrainerConfig'] class Modelconfig(object): vocab_size = 104810 embedding_dim = 300 embedding_droprate = 0.3 lstm_depth = 3 lstm_hidden_dim = 300 lstm_hidden_droprate = 0.3 passage_indep_embedding_dim = 300 passage_aligned_embedding_dim = 300 beam_size = 32...
def cipher(): user_input = input("Please provide a word: ")
def cipher(): user_input = input('Please provide a word: ')
# -*- coding: utf-8 -*- usr_number = int(input("Enter a number to calculate: ")) if usr_number > 1: for n in range(2, usr_number): if (usr_number % n == 0): print(f'{n} is not a prime number') else: print(f'{n} is a prime number')
usr_number = int(input('Enter a number to calculate: ')) if usr_number > 1: for n in range(2, usr_number): if usr_number % n == 0: print(f'{n} is not a prime number') else: print(f'{n} is a prime number')
date_fullyear = '[0-9]{4}' date_mday = '[0-9]{2}' date_month = '[0-9]{2}' full_date = f'{date_fullyear}-{date_month}-{date_mday}' time_hour = '[0-9]{2}' time_minute = '[0-9]{2}' time_second = '[0-9]{2}' time_secfrac = '\\.[0-9]+' partial_time = f'{time_hour}:{time_minute}:{time_second}({time_secfrac})?' time_numoffset ...
date_fullyear = '[0-9]{4}' date_mday = '[0-9]{2}' date_month = '[0-9]{2}' full_date = f'{date_fullyear}-{date_month}-{date_mday}' time_hour = '[0-9]{2}' time_minute = '[0-9]{2}' time_second = '[0-9]{2}' time_secfrac = '\\.[0-9]+' partial_time = f'{time_hour}:{time_minute}:{time_second}({time_secfrac})?' time_numoffset ...
__author__ = 'schien' INSTALLED_APPS += ('storages',) STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage' S3_URL = 'https://%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME STATIC_URL = S3_URL AWS_LOCATION = '/static' AWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires 'E...
__author__ = 'schien' installed_apps += ('storages',) staticfiles_storage = 'storages.backends.s3boto.S3BotoStorage' s3_url = 'https://%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME static_url = S3_URL aws_location = '/static' aws_headers = {'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', 'Cache-Control': 'max-age=9460800...
class SubMerchant: def __init__(self): self.cardAcceptorID = None self.country = None self.phoneNumber = None self.address1 = None self.postalCode = None self.locality = None self.name = None self.administrativeArea = None self.region = None ...
class Submerchant: def __init__(self): self.cardAcceptorID = None self.country = None self.phoneNumber = None self.address1 = None self.postalCode = None self.locality = None self.name = None self.administrativeArea = None self.region = None ...
environment = 'MountainCar-v0' bin_count = 9 goal_positon = 0.5 position_min = -1.2 position_max = 0.6 velocity_min = -0.07 velocity_max = 0.07 num_episodes = 10000 max_steps_in_episode = 200 verbose = 100 learning_rate = 10e-3 eps = 1 discount_factor = 0.9 panelty = -300 test_episodes = 100 bonus = 500 q_table_pa...
environment = 'MountainCar-v0' bin_count = 9 goal_positon = 0.5 position_min = -1.2 position_max = 0.6 velocity_min = -0.07 velocity_max = 0.07 num_episodes = 10000 max_steps_in_episode = 200 verbose = 100 learning_rate = 0.01 eps = 1 discount_factor = 0.9 panelty = -300 test_episodes = 100 bonus = 500 q_table_path = '...
#!/usr/bin/python def BubbleSort(val): for passnum in range(len(val)-1,0,-1): for i in range(passnum): if val[i]>val[i+1]: temp = val[i] val[i] = val[i+1] val[i+1] = temp DaftarAngka = [23,7,32,99,4,15,11,20] BubbleSort(DaftarAngka) print(DaftarAngka)
def bubble_sort(val): for passnum in range(len(val) - 1, 0, -1): for i in range(passnum): if val[i] > val[i + 1]: temp = val[i] val[i] = val[i + 1] val[i + 1] = temp daftar_angka = [23, 7, 32, 99, 4, 15, 11, 20] bubble_sort(DaftarAngka) print(Dafta...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
user_owner_type = 'User' dashboard_owner_type = 'Dashboard' name_field = 'name' description_field = 'description' json_metadata_field = 'json_metadata' owner_id_field = 'owner_id' owner_type_field = 'owner_type' dashboard_id_field = 'dashboard_id' owner_object_field = 'owner_object' dashboard_field = 'dashboard' params...
def paired_digits_count(data, skip): return sum([int(d) for i, d in enumerate(data) if data[i - skip] == d]) with open("day01.txt") as f: data = f.readline() half = int(len(data) / 2) print("2017 day 1 part 1: %d" % paired_digits_count(data, 1)) print("2017 day 1 part 2: %d" % paired_digits_count(d...
def paired_digits_count(data, skip): return sum([int(d) for (i, d) in enumerate(data) if data[i - skip] == d]) with open('day01.txt') as f: data = f.readline() half = int(len(data) / 2) print('2017 day 1 part 1: %d' % paired_digits_count(data, 1)) print('2017 day 1 part 2: %d' % paired_digits_count(...
# Soultion for Project Euler Problem #8 - https://projecteuler.net/problem=8 # (c) 2017 dpetker TEST_VAL = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950...
test_val = '73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158523863050715693290963295227443043557668966489504452445231617318564030987111217223831136222989342338030813533627661428280644448664523874930358907...
city = "narva" estonianPopulation = [ ["tallinn", 441000], ["tartu", 94000], ["narva", 58000], ["parnu", 41000] ] for p in estonianPopulation: if p[0] == city: print("Population of " + p[0].capitalize() + ": " + str(p[1])) break
city = 'narva' estonian_population = [['tallinn', 441000], ['tartu', 94000], ['narva', 58000], ['parnu', 41000]] for p in estonianPopulation: if p[0] == city: print('Population of ' + p[0].capitalize() + ': ' + str(p[1])) break
def iter_rings(data, pathcodes): ring = [] # TODO: Do this smartly by finding when pathcodes changes value and do # smart indexing on data, instead of iterating over each coordinate for point, code in zip(data, pathcodes): if code == 'M': # Emit the path and start a new one ...
def iter_rings(data, pathcodes): ring = [] for (point, code) in zip(data, pathcodes): if code == 'M': if len(ring): yield ring ring = [point] elif code == 'L': ring.append(point) else: raise value_error('Unrecognized code: {...
text = 'hello' fileName = 'data.txt' file=open(fileName, 'w') file.write(text) file.close() file = open(fileName, 'r') input_text = file.readline() file.close() print(input_text)
text = 'hello' file_name = 'data.txt' file = open(fileName, 'w') file.write(text) file.close() file = open(fileName, 'r') input_text = file.readline() file.close() print(input_text)
def sl_a_func(): pass def sl_a_func2(): pass class SlAClass(): def __init__(self): pass
def sl_a_func(): pass def sl_a_func2(): pass class Slaclass: def __init__(self): pass
#!/usr/bin/env python # -*- coding: utf-8 -*- def new_tips(argv): def tips(func): def nei(a, b): print("start %s %s" %(argv, func.__name__)) func(a, b) print("stop") return nei return tips @new_tips('add_modules') def add(a, b): print(a + b) @new_ti...
def new_tips(argv): def tips(func): def nei(a, b): print('start %s %s' % (argv, func.__name__)) func(a, b) print('stop') return nei return tips @new_tips('add_modules') def add(a, b): print(a + b) @new_tips('sub_modules') def sub(a, b): print(a - b...
N, M = map(int, input().split()) A = list(map(int, input().split())) days = N - sum(A) if days < 0: print(-1) else: print(days)
(n, m) = map(int, input().split()) a = list(map(int, input().split())) days = N - sum(A) if days < 0: print(-1) else: print(days)
a, b = map(int, input().split()) if b >= 45: print(a, b-45) elif a != 0 and b < 45: print(a-1, b+15) else: print(23, b+15)
(a, b) = map(int, input().split()) if b >= 45: print(a, b - 45) elif a != 0 and b < 45: print(a - 1, b + 15) else: print(23, b + 15)
N = int(input()) soma = 0 for k in range(N): X = int(input()) if X >= 10 and X <= 20: soma+=1 print("%d in" % (soma)) print("%d out" % (abs(N-soma)))
n = int(input()) soma = 0 for k in range(N): x = int(input()) if X >= 10 and X <= 20: soma += 1 print('%d in' % soma) print('%d out' % abs(N - soma))
class ValueType(object): '''Define _key() and inherit from this class to implement comparison and hashing''' # def __init__(self, *args, **kwargs): super(ValueType, self).__init__(*args, **kwargs) def __eq__(self, other): return type(self) == type(other) and self._key() == other._key() def __ne__(self, ...
class Valuetype(object): """Define _key() and inherit from this class to implement comparison and hashing""" def __eq__(self, other): return type(self) == type(other) and self._key() == other._key() def __ne__(self, other): return type(self) != type(other) or self._key() != other._key() ...
# # PySNMP MIB module CISCO-SRST-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-SRST-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:12:45 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') (single_value_constraint, value_size_constraint, constraints_union, constraints_intersection, value_range_constraint) ...
# bootstrap glyph icon ICON_TYPE_GLYPH = 'glyph' # image relative to Flask static folder ICON_TYPE_IMAGE = 'image' # external image ICON_TYPE_IMAGE_URL = 'image-url'
icon_type_glyph = 'glyph' icon_type_image = 'image' icon_type_image_url = 'image-url'
array = [] while True: line = input() if "DEBUG" == line: break array += list(map(int, filter(None, line.split(" ")))) for i in range(len(array) - 6): if array[i] == 32656 and array[i + 1] == 19759 and array[i + 2] == 32763: n = array[i + 4] start = i + 6 end = start +...
array = [] while True: line = input() if 'DEBUG' == line: break array += list(map(int, filter(None, line.split(' ')))) for i in range(len(array) - 6): if array[i] == 32656 and array[i + 1] == 19759 and (array[i + 2] == 32763): n = array[i + 4] start = i + 6 end = start + ...
pens_pack_price = 5.80 markers_pack_price = 7.20 whiteboard_cleaner_per_liter_price = 1.20 amount_pen_packs = int(input("Enter the amount of pen packs: ")) amount_marker_packs = int(input("Enter the amount of marker packs: ")) whiteboard_cleaner_liters = int(input("Enter the ampunt of liters of whiteboard cleaner: "))...
pens_pack_price = 5.8 markers_pack_price = 7.2 whiteboard_cleaner_per_liter_price = 1.2 amount_pen_packs = int(input('Enter the amount of pen packs: ')) amount_marker_packs = int(input('Enter the amount of marker packs: ')) whiteboard_cleaner_liters = int(input('Enter the ampunt of liters of whiteboard cleaner: ')) dis...
def configure(self): #Add Components compress = self.add('compress', CompressionSystem()) mission = self.add('mission', Mission()) pod = self.add('pod', Pod()) flow_limit = self.add('flow_limit', TubeLimitFlow()) tube_wall_temp = self.add('tube_wall_temp', TubeWallTemp()) #Boundary Input C...
def configure(self): compress = self.add('compress', compression_system()) mission = self.add('mission', mission()) pod = self.add('pod', pod()) flow_limit = self.add('flow_limit', tube_limit_flow()) tube_wall_temp = self.add('tube_wall_temp', tube_wall_temp()) self.connect('Mach_pod_max', 'comp...
n, d = [int(i) for i in input().split()] A = {} C = {} shoots = 0 def rangeD(e1, s2, e2): tmp = min(e1, e2) - s2+1 return(tmp if tmp >= 0 else -1) for _ in range(n): s, e, t, num = [i for i in input().split()] s, e, num = int(s), int(e), int(num) shoots += (e-s+1)*num if (t == "A"): ...
(n, d) = [int(i) for i in input().split()] a = {} c = {} shoots = 0 def range_d(e1, s2, e2): tmp = min(e1, e2) - s2 + 1 return tmp if tmp >= 0 else -1 for _ in range(n): (s, e, t, num) = [i for i in input().split()] (s, e, num) = (int(s), int(e), int(num)) shoots += (e - s + 1) * num if t == 'A...
name = input("Please enter your name: ") if name == 'Bob': print("You are a part of the top 1 percent!") elif name == 'Alice': print("You are a part of the top 1 percent!") else: print("Go away filthy peasent")
name = input('Please enter your name: ') if name == 'Bob': print('You are a part of the top 1 percent!') elif name == 'Alice': print('You are a part of the top 1 percent!') else: print('Go away filthy peasent')
## Integer Type num = 3 # type() print(type(num)) # <class 'int'> ## Float Type num = 3.14156 print(type(num)) # <class 'float'> ### Arithmetics operator # Addition : 3 + 2 ==> 5 # Subtraction : 3 - 2 ==> 1 # Multiplication : 3 * 10 ==> 30 # Division : 3 / 2 ...
num = 3 print(type(num)) num = 3.14156 print(type(num)) print(3 + 2) print(3 - 2) print(3 * 2) print(3 / 2) print(3 // 2) print(3 ** 2) print(3 % 2) print(4 % 2) print(5 % 2) print(abs(-3)) print(round(3.75)) print(round(3.45)) '\nHelp on built-in function round in module builtins:\n\nround(number, ndigits=None)\n R...
my_list = ["a", "b", "c", "d", "e"] item_count = len(my_list) print(f"My list has {item_count} items:") for i in my_list: print(i)
my_list = ['a', 'b', 'c', 'd', 'e'] item_count = len(my_list) print(f'My list has {item_count} items:') for i in my_list: print(i)
class Solution: def isMajorityElement(self, nums: List[int], target: int) -> bool: ''' T: O(log n) and S: O(1) ''' def binarySearch(nums, target, side): index = -1 lo, hi = 0, len(nums) - 1 while lo <= hi: mid = lo + (hi - lo) // 2 ...
class Solution: def is_majority_element(self, nums: List[int], target: int) -> bool: """ T: O(log n) and S: O(1) """ def binary_search(nums, target, side): index = -1 (lo, hi) = (0, len(nums) - 1) while lo <= hi: mid = lo + (hi - ...
class Solution: def majorityElement(self, nums: List[int]) -> int: result, count = nums[0], 1 for num in nums: if result == num: count += 1 else: if count == 1: result = num else: count -= 1 return result
class Solution: def majority_element(self, nums: List[int]) -> int: (result, count) = (nums[0], 1) for num in nums: if result == num: count += 1 elif count == 1: result = num else: count -= 1 return result
# # PySNMP MIB module ENTERASYS-THREAT-NOTIFICATION-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-THREAT-NOTIFICATION-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:04:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using P...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, single_value_constraint, constraints_union, value_range_constraint, value_size_constraint) ...
def quick_sort(items): if len(items) > 1: pivot_index = 0 smaller_items = [] larger_items = [] for i, val in enumerate(items): if i != pivot_index: if val < items[pivot_index]: smaller_items.append(val) else: ...
def quick_sort(items): if len(items) > 1: pivot_index = 0 smaller_items = [] larger_items = [] for (i, val) in enumerate(items): if i != pivot_index: if val < items[pivot_index]: smaller_items.append(val) else: ...
''' #params: 9104483 [1] train-result=0.4161, valid-result=0.4865 [62.0 s] [2] train-result=0.5830, valid-result=0.5648 [67.0 s] [3] train-result=0.6017, valid-result=0.5805 [67.7 s] [4] train-result=0.6100, valid-result=0.5874 [73.3 s] [5] train-result=0.6135, valid-result=0.5911 [66.8 s] [6] train-result=0.6151, val...
""" #params: 9104483 [1] train-result=0.4161, valid-result=0.4865 [62.0 s] [2] train-result=0.5830, valid-result=0.5648 [67.0 s] [3] train-result=0.6017, valid-result=0.5805 [67.7 s] [4] train-result=0.6100, valid-result=0.5874 [73.3 s] [5] train-result=0.6135, valid-result=0.5911 [66.8 s] [6] train-result=0.6151, vali...
def search(min_, max_, els, dec, inc): for c in els: if c == dec: max_ = (min_+max_)/2 elif c == inc: min_ = (min_+max_)/2 return min_ def getid(card): l = search(0, 128, card[:7], 'F', 'B') c = search(0, 8, card[7:], 'L', 'R') return l, c with open('in...
def search(min_, max_, els, dec, inc): for c in els: if c == dec: max_ = (min_ + max_) / 2 elif c == inc: min_ = (min_ + max_) / 2 return min_ def getid(card): l = search(0, 128, card[:7], 'F', 'B') c = search(0, 8, card[7:], 'L', 'R') return (l, c) with open...
# Binary search recursive version def rec_binary_search(arr, ele): if len(arr) == 0: return False else: mid = int(len(arr)/2) if arr[mid] == ele: return True else: if ele < arr[mid]: return rec_binary_search(arr[:mid], ele) e...
def rec_binary_search(arr, ele): if len(arr) == 0: return False else: mid = int(len(arr) / 2) if arr[mid] == ele: return True elif ele < arr[mid]: return rec_binary_search(arr[:mid], ele) else: return rec_binary_search(arr[mid + 1:], el...