content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class NumMatrix: def __init__(self, matrix: List[List[int]]): if not matrix: return self.presum = [[0] * (1 + len(matrix[0])) for _ in range(1 + len(matrix))] for i in range(len(matrix)): for j in range(len(matrix[0])): self.presum[i + 1][j + 1] =...
class Nummatrix: def __init__(self, matrix: List[List[int]]): if not matrix: return self.presum = [[0] * (1 + len(matrix[0])) for _ in range(1 + len(matrix))] for i in range(len(matrix)): for j in range(len(matrix[0])): self.presum[i + 1][j + 1] = sel...
DEFAULT: int = 2 MINIMUM: int = 0 MAXIMUM: int = 9
default: int = 2 minimum: int = 0 maximum: int = 9
def print_two(*args): arg1, arg2 = args print(f"arg1: {arg1}, arg2: {arg2}") def print_two_again(arg1, arg2): print(f"arg1: {arg1}, arg2: {arg2}") def print_one(arg1): print(f"arg1: {arg1}") def print_none(): print("I got nothing.") print_two("Kody", "Wilson") print_two_again("Kody", "Wilson") print_one("...
def print_two(*args): (arg1, arg2) = args print(f'arg1: {arg1}, arg2: {arg2}') def print_two_again(arg1, arg2): print(f'arg1: {arg1}, arg2: {arg2}') def print_one(arg1): print(f'arg1: {arg1}') def print_none(): print('I got nothing.') print_two('Kody', 'Wilson') print_two_again('Kody', 'Wilson') ...
# # PySNMP MIB module PDN-PPP-LCP-EXT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PDN-PPP-LCP-EXT-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:39:28 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_union, value_range_constraint, single_value_constraint, constraints_intersection) ...
{ 'sr1_replace' : None, 'search_replace' : '[]', 'sr2_search' : None, 'sr2_replace' : None, 'sr1_search' : None, 'sr3_search' : None, 'sr3_replace' : None, }
{'sr1_replace': None, 'search_replace': '[]', 'sr2_search': None, 'sr2_replace': None, 'sr1_search': None, 'sr3_search': None, 'sr3_replace': None}
class Node: def __init__(self, data): self.data = data self.next = None self.arb=None class Solution: def cloneList(self, head): clone_head = clone_last = None current_node = head while current_node: if clone_head == None: clone_head...
class Node: def __init__(self, data): self.data = data self.next = None self.arb = None class Solution: def clone_list(self, head): clone_head = clone_last = None current_node = head while current_node: if clone_head == None: clone_h...
x = int(input()) y = int(input()) soma = 0 if y < 0: for c in range(x, y, -1): if c % 2 != 0: soma += c print(soma) elif x > y: for c in range(y, x): if c % 2 != 0: soma += c print(soma) else: print('0')
x = int(input()) y = int(input()) soma = 0 if y < 0: for c in range(x, y, -1): if c % 2 != 0: soma += c print(soma) elif x > y: for c in range(y, x): if c % 2 != 0: soma += c print(soma) else: print('0')
class AtomClass: def __init__(self, Velocity, Element = 'C', Mass = 12.0): self.Velocity = Velocity self.Element = Element self.Mass = Mass def Momentum(self): return self.Velocity * self.Mass
class Atomclass: def __init__(self, Velocity, Element='C', Mass=12.0): self.Velocity = Velocity self.Element = Element self.Mass = Mass def momentum(self): return self.Velocity * self.Mass
N = int(input()) check = False for i in range(1, N): nums = list(map(int, str(i))) sum1 = i + sum(nums) if sum1 == N: print(i) check = True break if not check: print(0)
n = int(input()) check = False for i in range(1, N): nums = list(map(int, str(i))) sum1 = i + sum(nums) if sum1 == N: print(i) check = True break if not check: print(0)
expected_output = { "interface": { "Loopback0": { "interface_status": "Up", "ip_address": "200.0.7.1", "protocol_status": "Up" }, "MgmtEth0/RSP0/CPU0/0": { "interface_status": "Up", "ip_address": "5.25.27.1", "protocol_s...
expected_output = {'interface': {'Loopback0': {'interface_status': 'Up', 'ip_address': '200.0.7.1', 'protocol_status': 'Up'}, 'MgmtEth0/RSP0/CPU0/0': {'interface_status': 'Up', 'ip_address': '5.25.27.1', 'protocol_status': 'Up'}, 'MgmtEth0/RSP0/CPU0/1': {'interface_status': 'Shutdown', 'ip_address': 'unassigned', 'prot...
# Chino (2210013) | Colossus Road : Chino's Lift: The Road Up & Down sm.setPlayerAsSpeaker() sm.sendNext("Hey..") sm.setSpeakerID(parentID) sm.sendSayOkay("No.")
sm.setPlayerAsSpeaker() sm.sendNext('Hey..') sm.setSpeakerID(parentID) sm.sendSayOkay('No.')
class FancyPrint(object): HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def echo(stuff_to_print, style): bash_color = getattr(FancyPrint, style, None) if no...
class Fancyprint(object): header = '\x1b[95m' okblue = '\x1b[94m' okgreen = '\x1b[92m' warning = '\x1b[93m' fail = '\x1b[91m' endc = '\x1b[0m' bold = '\x1b[1m' underline = '\x1b[4m' def echo(stuff_to_print, style): bash_color = getattr(FancyPrint, style, None) if not...
class ImageGroupData: def __init__(self, start_y, start_x, y_gear_offset, x_gear_offset): self.start_y = start_y self.start_x = start_x self.y_gear_offset = y_gear_offset self.x_gear_offset = x_gear_offset class ImageTypeData: def __init__(self, size, rel_start_offset, rows=None, columns=None, p...
class Imagegroupdata: def __init__(self, start_y, start_x, y_gear_offset, x_gear_offset): self.start_y = start_y self.start_x = start_x self.y_gear_offset = y_gear_offset self.x_gear_offset = x_gear_offset class Imagetypedata: def __init__(self, size, rel_start_offset, rows=No...
text = input() save = [] for letter in text: o = ord(letter) + 3 ch = chr(o) save.append(ch) print("".join(save))
text = input() save = [] for letter in text: o = ord(letter) + 3 ch = chr(o) save.append(ch) print(''.join(save))
# # PySNMP MIB module AISYSCFGTEMP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AISYSCFGTEMP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:01:01 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, single_value_constraint, value_size_constraint, constraints_union, value_range_constraint) ...
cur_hedons = 0 cur_health = 0 last_hedons = 0 last_health = 0 cur_star = None cur_star_activity = None last_star_time = 0 bored_with_stars = False last_activity = None last_activity_duration = 0 cur_time = 0 last_finished = -1000 def initialize(): '''Initializes the global variables needed...
cur_hedons = 0 cur_health = 0 last_hedons = 0 last_health = 0 cur_star = None cur_star_activity = None last_star_time = 0 bored_with_stars = False last_activity = None last_activity_duration = 0 cur_time = 0 last_finished = -1000 def initialize(): """Initializes the global variables needed for the simulation. Inco...
def get_cycle(n): results = [] remainders = [1] val = 1 while True: result = (val*10)//n remainder = (val*10)%n results.append(result) if remainder == 0 or remainder in remainders: break remainders.append(remainder) val = remainder return (...
def get_cycle(n): results = [] remainders = [1] val = 1 while True: result = val * 10 // n remainder = val * 10 % n results.append(result) if remainder == 0 or remainder in remainders: break remainders.append(remainder) val = remainder retu...
# Databricks notebook source LWILIOBCIMDGCHFASADRRGZCLIILUWO RAZOIMPPJWANJOYLINMNWZBNP ZGJJDFPYWBFLTPDCBSYJNCJLHEJLZASADWKGDWRMJCBBBOCJBPWLLGBPKTLMNQTFQKMHEEICHICAMKGNLTSAYULKKXJFNPLKAALUFPSLDWIHHUGNWKEMGMXWBDG GSTFBJXBKRCGZHILZPJRUOFWRVWWKVAIDTEK NIKIMPVFKIFHNJSLWLJZOHICCULWGGJJSWLHQFHQQUCDPJRBGAS OBARCRYIKLKKEZ LTMF...
LWILIOBCIMDGCHFASADRRGZCLIILUWO RAZOIMPPJWANJOYLINMNWZBNP ZGJJDFPYWBFLTPDCBSYJNCJLHEJLZASADWKGDWRMJCBBBOCJBPWLLGBPKTLMNQTFQKMHEEICHICAMKGNLTSAYULKKXJFNPLKAALUFPSLDWIHHUGNWKEMGMXWBDG GSTFBJXBKRCGZHILZPJRUOFWRVWWKVAIDTEK NIKIMPVFKIFHNJSLWLJZOHICCULWGGJJSWLHQFHQQUCDPJRBGAS OBARCRYIKLKKEZ LTMFPWWTMPGTWYZSZGNJRTDSPGBIGXISXJ...
def palindromo(palabra): palabra =palabra.replace(' ','') palabra=palabra.lower() palabra_invertida = palabra[::-1] if palabra==palabra_invertida: return True else: return False def run(): palabra = input("Escribir una palabra: ") es_palindromo=palindromo(palabra) if e...
def palindromo(palabra): palabra = palabra.replace(' ', '') palabra = palabra.lower() palabra_invertida = palabra[::-1] if palabra == palabra_invertida: return True else: return False def run(): palabra = input('Escribir una palabra: ') es_palindromo = palindromo(palabra) ...
# # PySNMP MIB module CISCO-IETF-SCTP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-IETF-SCTP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:43:56 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') (constraints_intersection, value_size_constraint, constraints_union, single_value_constraint, value_range_constraint) ...
supported_types = { 'removed', 'added', 'updated', 'nested', 'unchanged' } def stringify(value): if isinstance(value, dict): return '[complex value]' if isinstance(value, bool): return str(value).lower() if value is None: return 'null' if isinstance(value, s...
supported_types = {'removed', 'added', 'updated', 'nested', 'unchanged'} def stringify(value): if isinstance(value, dict): return '[complex value]' if isinstance(value, bool): return str(value).lower() if value is None: return 'null' if isinstance(value, str): return f"'...
obj = pd.Series(np.arange(5.), index=list('abcde')) obj obj.drop(['c']) obj.drop(list('dc')) data = pd.DataFrame(np.arange(16).reshape((4,4)), index=['Ohio', 'Colorado', 'Utah', 'New York'], columns=['one', 'two', 'three', 'four']) data data.drop(['Colorado', 'Ohio']) data.drop('two', axis=1) data.drop('two', axis='col...
obj = pd.Series(np.arange(5.0), index=list('abcde')) obj obj.drop(['c']) obj.drop(list('dc')) data = pd.DataFrame(np.arange(16).reshape((4, 4)), index=['Ohio', 'Colorado', 'Utah', 'New York'], columns=['one', 'two', 'three', 'four']) data data.drop(['Colorado', 'Ohio']) data.drop('two', axis=1) data.drop('two', axis='c...
def chooseLargest(a, b): list(map(lambda tup: max(tup[0] + tup[1]), zip(a, b))) l1 = [1, 2, 3, 4, 5] l2 = [2, 2, 9, 0, 9] return list(map(lambda tup: max(tup[0] + tup[1]), zip(a, b)))
def choose_largest(a, b): list(map(lambda tup: max(tup[0] + tup[1]), zip(a, b))) l1 = [1, 2, 3, 4, 5] l2 = [2, 2, 9, 0, 9] return list(map(lambda tup: max(tup[0] + tup[1]), zip(a, b)))
# https://www.hackerrank.com/challenges/string-validators/problem string = input() print(any(c.isalnum() for c in string)) print(any(c.isalpha() for c in string)) print(any(c.isdigit() for c in string)) print(any(c.islower() for c in string)) print(any(c.isupper() for c in string))
string = input() print(any((c.isalnum() for c in string))) print(any((c.isalpha() for c in string))) print(any((c.isdigit() for c in string))) print(any((c.islower() for c in string))) print(any((c.isupper() for c in string)))
# # PySNMP MIB module Nortel-Magellan-Passport-VnetMcdnSigMIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-VnetMcdnSigMIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:19:17 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwan...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, constraints_union, single_value_constraint, value_range_constraint) ...
# Localizable strings extracted by LocalizationDemo.tscn tr("Space") tr("Exclam") tr("QuoteDbl") tr("NumberSign") tr("Dollar") tr("Percent") tr("Ampersand") tr("Apostrophe") tr("ParenLeft") tr("ParenRight") tr("Asterisk") tr("Plus") tr("Comma") tr("Minus") tr("Period") tr("Slash") tr("Colon") tr("Semicolon") tr("Less")...
tr('Space') tr('Exclam') tr('QuoteDbl') tr('NumberSign') tr('Dollar') tr('Percent') tr('Ampersand') tr('Apostrophe') tr('ParenLeft') tr('ParenRight') tr('Asterisk') tr('Plus') tr('Comma') tr('Minus') tr('Period') tr('Slash') tr('Colon') tr('Semicolon') tr('Less') tr('Equal') tr('Greater') tr('Question') tr('At') tr('Br...
class FormataTexto(object): def __init__(self, texto, formatacao='Titulo'): self.__texto = texto self.__formatacao = formatacao def __str__(self): return self.__getFormatar() def __getFormatar(self): if self.__formatacao == 'Titulo': return self.__texto....
class Formatatexto(object): def __init__(self, texto, formatacao='Titulo'): self.__texto = texto self.__formatacao = formatacao def __str__(self): return self.__getFormatar() def __get_formatar(self): if self.__formatacao == 'Titulo': return self.__texto.title(...
__title__ = 'app' __description__ = 'A Flask based microblog.' __url__ = 'https://github.com/Napchat/microblog' __version__ = '1.0' __author__ = 'Shang Nan' __author_email__ = 'shangnan543@163.com' __license__ = 'MIT License' __copyright__ = 'Copyright 2017 Shang Nan'
__title__ = 'app' __description__ = 'A Flask based microblog.' __url__ = 'https://github.com/Napchat/microblog' __version__ = '1.0' __author__ = 'Shang Nan' __author_email__ = 'shangnan543@163.com' __license__ = 'MIT License' __copyright__ = 'Copyright 2017 Shang Nan'
info_modes = {'login': 'inurl:login | inurl:signin | intitle:Login | intitle:"sign in" | inurl:auth', 'signup': 'inurl:signup | inurl:register | intitle:Signup', 'phpinfo': 'ext:php intitle:phpinfo "published by the PHP Group"'} for info in info_modes: print(info_modes[info])
info_modes = {'login': 'inurl:login | inurl:signin | intitle:Login | intitle:"sign in" | inurl:auth', 'signup': 'inurl:signup | inurl:register | intitle:Signup', 'phpinfo': 'ext:php intitle:phpinfo "published by the PHP Group"'} for info in info_modes: print(info_modes[info])
N1 = int(input("Digite o primeiro numero: ")) N2 = int(input("Digite o segundo numero:")) print(N1+N2)
n1 = int(input('Digite o primeiro numero: ')) n2 = int(input('Digite o segundo numero:')) print(N1 + N2)
OPEN_MS_SRC="/home/uschmitt/Release1.10pyopenms" OPEN_MS_BUILD_DIR="/home/uschmitt/Release1.10pyopenms" OPEN_MS_CONTRIB_BUILD_DIRS="/home/uschmitt/Release1.10pyopenms/contrib;/opt/local;/usr/local;" QT_HEADERS_DIR="/usr/include/qt4" QT_LIBRARY_DIR="/usr/lib/x86_64-linux-gnu" QT_QTCORE_INCLUDE_DIR="/usr/include/qt4/QtCo...
open_ms_src = '/home/uschmitt/Release1.10pyopenms' open_ms_build_dir = '/home/uschmitt/Release1.10pyopenms' open_ms_contrib_build_dirs = '/home/uschmitt/Release1.10pyopenms/contrib;/opt/local;/usr/local;' qt_headers_dir = '/usr/include/qt4' qt_library_dir = '/usr/lib/x86_64-linux-gnu' qt_qtcore_include_dir = '/usr/incl...
# Group the Numbers # Partitioning : quicksort !! # Time - O(n), Space- O(1) # Lomuto's partitioning O(n) time, in-place def solve(arr): even = -1 # index from the beginning (r -- red == even) i = 0 # current pointer while i < len(arr): # O(n) if arr[i] % 2 == 0: even += 1 ...
def solve(arr): even = -1 i = 0 while i < len(arr): if arr[i] % 2 == 0: even += 1 (arr[i], arr[even]) = (arr[even], arr[i]) i += 1 return arr if __name__ == '__main__': arr = [1, 5, 2, 3, 4, 4, 4, 5, 2, 6, 8, 9, 9] def solve(arr): left_pointer = -1 cu...
# see https://www.codewars.com/kata/5a092d9e46d843b9db000064/solutions/python def solve(arr): arr = sorted(arr) i, j = 0, -1 while True: if arr[i] + arr[j] != 0: print(arr[i], arr[j], arr[i+1], arr[j-1]) if arr[i+1] + arr[j] == 0: return arr[i] el...
def solve(arr): arr = sorted(arr) (i, j) = (0, -1) while True: if arr[i] + arr[j] != 0: print(arr[i], arr[j], arr[i + 1], arr[j - 1]) if arr[i + 1] + arr[j] == 0: return arr[i] elif arr[i + 1] != arr[i]: return arr[j] el...
''' Assigment No: 1 - Grading Logic Assigment Author's Name: Umaima Khurshid Ahmad Youtube Link: https://youtu.be/SY_c813y6H0 Date: 04/05/2020 'I have not given or received any unauthorized assistance on this assignment' ''' def computeFinalGrade(): '''returns total score and grade of the student ...
""" Assigment No: 1 - Grading Logic Assigment Author's Name: Umaima Khurshid Ahmad Youtube Link: https://youtu.be/SY_c813y6H0 Date: 04/05/2020 'I have not given or received any unauthorized assistance on this assignment' """ def compute_final_grade(): """returns total score and grade of the student it giv...
def parse_table(table): data = [] table_body = table.find('tbody') rows = table_body.find_all('tr') for row in rows: cols = row.find_all('td') cols = [ele.text.strip() for ele in cols] data.append([ele for ele in cols if ele]) # Get rid of empty values return data
def parse_table(table): data = [] table_body = table.find('tbody') rows = table_body.find_all('tr') for row in rows: cols = row.find_all('td') cols = [ele.text.strip() for ele in cols] data.append([ele for ele in cols if ele]) return data
x = int(input()) _ = ((x) + (3)) _ = ((x) * (6)) _ = ((x) & (2)) _ = ((x) ^ (1)) _ = ((x) | (3)) _ = ((x) + (10))
x = int(input()) _ = x + 3 _ = x * 6 _ = x & 2 _ = x ^ 1 _ = x | 3 _ = x + 10
def swap_case(s): t="" for i in s: if i.isalpha(): if i.isupper(): t=t+i.lower() else: t=t+i.upper() else: t=t+i return (t)
def swap_case(s): t = '' for i in s: if i.isalpha(): if i.isupper(): t = t + i.lower() else: t = t + i.upper() else: t = t + i return t
#!/usr/bin/env python EXPECTED_NUM_TESTS = 4 METRICS_FILE_PATH = "./svqc/tests/test_metrics.txt" CRITERIA_FILE_PATH = "./svqc/tests/test_criteria.txt" EXPECTED_OUT_FILE_PATH = "./svqc/tests/test_out.txt" OUT_FILE_PATH = "./svqc/tests/test.out"
expected_num_tests = 4 metrics_file_path = './svqc/tests/test_metrics.txt' criteria_file_path = './svqc/tests/test_criteria.txt' expected_out_file_path = './svqc/tests/test_out.txt' out_file_path = './svqc/tests/test.out'
class CacheVocabulary: def __init__(self, vocab_data, vocab_dict, cache_number, unknown_word, blank_word): self.word_value = {} self.word_value[unknown_word] = 0 self.word_value[blank_word] = 1 count = 0 for key in vocab_dict.keys(): word = vocab_data.vocab.itos[...
class Cachevocabulary: def __init__(self, vocab_data, vocab_dict, cache_number, unknown_word, blank_word): self.word_value = {} self.word_value[unknown_word] = 0 self.word_value[blank_word] = 1 count = 0 for key in vocab_dict.keys(): word = vocab_data.vocab.itos[...
def relax(): neopixel.setAnimation("Color Wipe", 0, 0, 20, 1) sleep(2) neopixel.setAnimation("Ironman", 0, 0, 255, 1) if (i01.eyesTracking.getOpenCV().capturing): global MoveBodyRandom MoveBodyRandom=0 global MoveHeadRandom MoveHeadRandom=0 i01.setHandSpeed("left", 0.85, 0.85, ...
def relax(): neopixel.setAnimation('Color Wipe', 0, 0, 20, 1) sleep(2) neopixel.setAnimation('Ironman', 0, 0, 255, 1) if i01.eyesTracking.getOpenCV().capturing: global MoveBodyRandom move_body_random = 0 global MoveHeadRandom move_head_random = 0 i01.setHandSpeed(...
class Director: __builder = None def setBuilder(self, builder): self.__builder = builder def getOrden(self): orden = Orden() pan = self.__builder.preparaPan() orden.setPan(pan) carne = self.__builder.agregaCarne() orden.setCarne(carne) verduras = self....
class Director: __builder = None def set_builder(self, builder): self.__builder = builder def get_orden(self): orden = orden() pan = self.__builder.preparaPan() orden.setPan(pan) carne = self.__builder.agregaCarne() orden.setCarne(carne) verduras = s...
class Room: room_cost = 0 def __init__(self, name: str, budget: float, members_count: int): self.family_name = name self.budget = budget self.members_count = members_count self.children = [] self.expenses = 0 @property def total_monthly_cost(self): retur...
class Room: room_cost = 0 def __init__(self, name: str, budget: float, members_count: int): self.family_name = name self.budget = budget self.members_count = members_count self.children = [] self.expenses = 0 @property def total_monthly_cost(self): retur...
class Solution: def nthUglyNumber(self, n: int) -> int: if n < 0: return 0 dp = [1] * n index2 = index3 = index5 = 0 for i in range(1, n): dp[i] = min(2 * dp[index2], 3 * dp[index3], 5 * dp[index5]) if dp[i] == 2 * dp[index2]: index2 += 1 if dp[i] ...
class Solution: def nth_ugly_number(self, n: int) -> int: if n < 0: return 0 dp = [1] * n index2 = index3 = index5 = 0 for i in range(1, n): dp[i] = min(2 * dp[index2], 3 * dp[index3], 5 * dp[index5]) if dp[i] == 2 * dp[index2]: in...
##sequence = [1,1] ##length_expection = int(input("Please enter the length\ ## of Fibonacci to generate:")) ##i = 1 ##j = 2 ##while len(sequence) <= length_expection: ## sequence.append(i+j) ## i += 1 ## j += 1 ##print(element for element in sequence) a = 1 b = 1 while a < 1000: ...
a = 1 b = 1 while a < 1000: print(a) (a, b) = (b, a + b)
def draw(): rows = int(pow(2, int(random(1, 6)))) u = int(height / (rows + 4)) thickness = int(pow(2, int(random(1, 4)))) uth1 = int(u / thickness) uth2 = u + uth1 startX = int(-u * .75) startY = int(height / 2 + rows / 2 * u) endX = width + u endY = height / 2 + rows / 2 * u fo...
def draw(): rows = int(pow(2, int(random(1, 6)))) u = int(height / (rows + 4)) thickness = int(pow(2, int(random(1, 4)))) uth1 = int(u / thickness) uth2 = u + uth1 start_x = int(-u * 0.75) start_y = int(height / 2 + rows / 2 * u) end_x = width + u end_y = height / 2 + rows / 2 * u ...
__all__ = [ 'base_controller', 'cdrs_controller', 'numbers_controller', 'routes_controller', 'messages_controller', ]
__all__ = ['base_controller', 'cdrs_controller', 'numbers_controller', 'routes_controller', 'messages_controller']
__author__ = 'Chintalagiri Shashank' __email__ = 'shashank@chintal.in' __version__ = '0.1.0'
__author__ = 'Chintalagiri Shashank' __email__ = 'shashank@chintal.in' __version__ = '0.1.0'
def make_bold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped def make_italic(fn): def wrapped(): return "<i>" + fn() + "</i>" return wrapped def make_underline(fn): def wrapped(): return "<u>" + fn() + "</u>" return wrapped @make_bold @ma...
def make_bold(fn): def wrapped(): return '<b>' + fn() + '</b>' return wrapped def make_italic(fn): def wrapped(): return '<i>' + fn() + '</i>' return wrapped def make_underline(fn): def wrapped(): return '<u>' + fn() + '</u>' return wrapped @make_bold @make_italic @...
# 000577_30_Dict_add_rem customer_29876 = {'first name': 'David', 'last name': 'Elliott', 'address': '4803 Wellesley St.', 'city': 'Toronto'} print("initial dict", customer_29876) # rem del customer_29876["address"] print('remove "address"',customer_29876) # add "street" print("add street") customer_29876["street"] = "...
customer_29876 = {'first name': 'David', 'last name': 'Elliott', 'address': '4803 Wellesley St.', 'city': 'Toronto'} print('initial dict', customer_29876) del customer_29876['address'] print('remove "address"', customer_29876) print('add street') customer_29876['street'] = 'Park Avenue' print(customer_29876) print('cha...
def user_selection(message, options): # taken from https://github.com/Asana/python-asana/blob/master/examples/example-create-task.py option_list = list(options) print(message) for i, option in enumerate(option_list): print(i, ": " + option["name"]) index = int(input("Enter choice (default 0)...
def user_selection(message, options): option_list = list(options) print(message) for (i, option) in enumerate(option_list): print(i, ': ' + option['name']) index = int(input('Enter choice (default 0): ') or 0) return option_list[index]
class MenuItem(object): def __init__(self, type: str, title: str, **kwargs): if not isinstance(type, str): raise TypeError('type must be an instance of str') if not isinstance(title, str): raise TypeError('title must be an instance of str') self.type = type se...
class Menuitem(object): def __init__(self, type: str, title: str, **kwargs): if not isinstance(type, str): raise type_error('type must be an instance of str') if not isinstance(title, str): raise type_error('title must be an instance of str') self.type = type ...
class dotUndoOperation_t(object): # no doc Operation=None
class Dotundooperation_T(object): operation = None
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/master/LICENSE def indent_code(code, indent): finalcode = "" for line in code.splitlines(): finalcode += " " * indent + line + "\n" return finalcode
def indent_code(code, indent): finalcode = '' for line in code.splitlines(): finalcode += ' ' * indent + line + '\n' return finalcode
''' lec4 dict tuple ''' my_tuple = 'a','b','c','d','e' print(my_tuple) my_2nd_tuple= ('a','b','c','d','e') print (my_2nd_tuple) is_a_tuple= ('a',) print ( type(is_a_tuple) ) print (my_tuple[1]) my_car = { 'color' : 'red', 'maker': 'toyota', 'year': 2015 } print (my_car) print (my_car ['color'])...
""" lec4 dict tuple """ my_tuple = ('a', 'b', 'c', 'd', 'e') print(my_tuple) my_2nd_tuple = ('a', 'b', 'c', 'd', 'e') print(my_2nd_tuple) is_a_tuple = ('a',) print(type(is_a_tuple)) print(my_tuple[1]) my_car = {'color': 'red', 'maker': 'toyota', 'year': 2015} print(my_car) print(my_car['color']) print(my_car['year']) p...
class Credentials: def __init__(self, appkey, secretkey, accountkey=None): self.appkey = appkey self.secretkey = secretkey self.account_key = accountkey def __eq__(self, other: object) -> bool: if isinstance(other, Credentials): return self.appkey == other.appkey \ ...
class Credentials: def __init__(self, appkey, secretkey, accountkey=None): self.appkey = appkey self.secretkey = secretkey self.account_key = accountkey def __eq__(self, other: object) -> bool: if isinstance(other, Credentials): return self.appkey == other.appkey an...
i = 1 pool = 3 entFormat = open("play_script.txt", "w") while i == 1: readLine = input() if readLine == "stop": i = 0 entFormat.close() else: if readLine == "": wool = "{}".format(pool) entFormat.write(" elseif time < "+wool+" then\n") pool = p...
i = 1 pool = 3 ent_format = open('play_script.txt', 'w') while i == 1: read_line = input() if readLine == 'stop': i = 0 entFormat.close() elif readLine == '': wool = '{}'.format(pool) entFormat.write(' elseif time < ' + wool + ' then\n') pool = pool + 1 elif re...
# Uses python3 def edit_distance(s, t, memo = {}): if len(s) == 0: return len(t) if len(t) == 0: return len(s) if (len(s), len(t)) in memo: return memo[(len(s), len(t))] delta = 1 if s[-1] != t[-1] else 0 diag = edit_distance(s[:-1], t[:-1], memo) + delta vert = edit_distance(s[:-1], t...
def edit_distance(s, t, memo={}): if len(s) == 0: return len(t) if len(t) == 0: return len(s) if (len(s), len(t)) in memo: return memo[len(s), len(t)] delta = 1 if s[-1] != t[-1] else 0 diag = edit_distance(s[:-1], t[:-1], memo) + delta vert = edit_distance(s[:-1], t, mem...
# HEAD # Classes - Metaclasses for class modification # DESCRIPTION # Describes how to use metaclasses dynamically to modify classes during instatiation # Describes how to add attributes to a metaclass # or re-implement the type __call__ methods # Public # RESOURCES # # /opt/pycharm/pycharm-community-2019.2....
class Modelbase(type): def hello(cls): print('Test', type(cls)) def __init__(cls, name, bases, dct): print('bases', bases) print('name', name) print('dict', dct) print('cls.__dict__', cls.__dict__) return super(ModelBase, cls).__init__(cls) def __call__(sel...
# Challenge 036 - 04/21/2021 - Henrique Matheus Alves Pereira # Write a program to approve the bank loan for the purchase of a home. # Ask the price of the house, the buyer's salary and how many years he will pay. # The monthly installment cannot exceed 30% of the salary or the loan will be denied. print("Challenge 036...
print('Challenge 036') print('Please, for the following information, enter only two digits after the comma.') price_house = float(input('1 - Please, enter the purchase price of the home (R$):')) financing_time = float(input('2 - Please, enter the financing time of the home (Years):')) salary = float(input('3 - Please, ...
abeceda = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] def abecedna_vrednost(ime): seznam = list(str(ime)) vrednost = 0 for i in range(len(seznam)): vrednost = vrednost + abeceda.index(seznam[i]) + 1 return vr...
abeceda = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] def abecedna_vrednost(ime): seznam = list(str(ime)) vrednost = 0 for i in range(len(seznam)): vrednost = vrednost + abeceda.index(seznam[i]) + 1 return vr...
wt3_3_7 = {'192.168.122.110': [5.3551, 8.3352, 7.3783, 6.9324, 6.6606, 6.4673, 6.5077, 6.6393, 7.3012, 7.1319, 6.7323, 6.3639, 6.33, 6.6602, 6.9711, 6.8935, 7.1543, 7.3671, 7.2675, 7.223, 7.1379, 7.3225, 7.2638, 7.4282, 7.435, 7.3821, 7.5459, 7.4728, 7.4688, 7.4658, 7.3986, 7.347, 7.4649, 7.4186, 7.4119, 7.358, 7.3216...
wt3_3_7 = {'192.168.122.110': [5.3551, 8.3352, 7.3783, 6.9324, 6.6606, 6.4673, 6.5077, 6.6393, 7.3012, 7.1319, 6.7323, 6.3639, 6.33, 6.6602, 6.9711, 6.8935, 7.1543, 7.3671, 7.2675, 7.223, 7.1379, 7.3225, 7.2638, 7.4282, 7.435, 7.3821, 7.5459, 7.4728, 7.4688, 7.4658, 7.3986, 7.347, 7.4649, 7.4186, 7.4119, 7.358, 7.3216,...
num = int(input('Digite o numero para a tabuada: ')) contador = 0 print('-' * 12) print('{} * {:2} = {:2}'.format(num, contador, (num*contador))) contador = contador + 1 print('{} * {:2} = {:2}'.format(num, contador, (num*contador))) contador = contador + 1 print('{} * {:2} = {:2}'.format(num, contador, (num*contador))...
num = int(input('Digite o numero para a tabuada: ')) contador = 0 print('-' * 12) print('{} * {:2} = {:2}'.format(num, contador, num * contador)) contador = contador + 1 print('{} * {:2} = {:2}'.format(num, contador, num * contador)) contador = contador + 1 print('{} * {:2} = {:2}'.format(num, contador, num * contador)...
class DeviceModelDoesnotExistException(Exception): def __str__(self): return "Target device model doesn't exist." class ParameterCannotBeNone(Exception): def __str__(self): return "Parameter cannot all be None."
class Devicemodeldoesnotexistexception(Exception): def __str__(self): return "Target device model doesn't exist." class Parametercannotbenone(Exception): def __str__(self): return 'Parameter cannot all be None.'
level = 3 name = 'Margahayu' capital = 'Sukamenak' area = 10.54
level = 3 name = 'Margahayu' capital = 'Sukamenak' area = 10.54
''' Loops let you walk through a sequence of items, such as items in a list ''' # # looping through a list # colors = ['black', 'blue', 'brown', 'green', 'purple', 'white', 'yellow'] for color in colors: print(color) # # Looping through a range of numbers # for num in range(5): print(num) # Prints th...
""" Loops let you walk through a sequence of items, such as items in a list """ colors = ['black', 'blue', 'brown', 'green', 'purple', 'white', 'yellow'] for color in colors: print(color) for num in range(5): print(num) for num in range(10, 16): print(num) for num in range(20, 31, 2): print(num)
#!/usr/bin/env python # -*- coding: utf-8 -*- def get_palindromic(n_s, n_e): n_1 = n_s f_1 = -1 f_2 = -1 f = -1 while n_1 <= n_e: for n_2 in range(n_1, n_e+1): n = n_1 * n_2 if is_palindromic(n) and n > f: f_1 = n_1 f_2 = n_2 ...
def get_palindromic(n_s, n_e): n_1 = n_s f_1 = -1 f_2 = -1 f = -1 while n_1 <= n_e: for n_2 in range(n_1, n_e + 1): n = n_1 * n_2 if is_palindromic(n) and n > f: f_1 = n_1 f_2 = n_2 f = n n_1 += 1 return (f, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Author - Samar Srivastava (https://samacker77.github.io) Problem Link - https://www.hackerrank.com/challenges/s10-quartiles/problem Problem Statement - Given an array, X, of n integers, calculate the respective first quartile (Q1), second quartile (Q2), and third qua...
""" Author - Samar Srivastava (https://samacker77.github.io) Problem Link - https://www.hackerrank.com/challenges/s10-quartiles/problem Problem Statement - Given an array, X, of n integers, calculate the respective first quartile (Q1), second quartile (Q2), and third quartile (Q3). It is guaranteed that Q1, Q2,and Q3...
''' Piling Up! https://www.hackerrank.com/challenges/piling-up/problem There is a horizontal row of n cubes. The length of each cube is given. You need to create a new vertical pile of cubes. The new pile should follow these directions: if cube(i) is on top of cube(j) then sideLength(j) >= sideLength(i). When stack...
""" Piling Up! https://www.hackerrank.com/challenges/piling-up/problem There is a horizontal row of n cubes. The length of each cube is given. You need to create a new vertical pile of cubes. The new pile should follow these directions: if cube(i) is on top of cube(j) then sideLength(j) >= sideLength(i). When stacki...
def get_average_inventory_worth(current, production, consumption, processing, queued, missing, trade): results = {"P1": 0, "P2": 0, "P3": 0, "E4": 0, "E5": 0, "E6": 0, "E7": 0, "E8": 0, "E9": 0, "E10": 0, "E11": 0, "E12": 0, "E13": 0, "E14": 0, "E15": 0, "E16": 0, "E17": 0, "E18": 0, "E19": 0, "E20"...
def get_average_inventory_worth(current, production, consumption, processing, queued, missing, trade): results = {'P1': 0, 'P2': 0, 'P3': 0, 'E4': 0, 'E5': 0, 'E6': 0, 'E7': 0, 'E8': 0, 'E9': 0, 'E10': 0, 'E11': 0, 'E12': 0, 'E13': 0, 'E14': 0, 'E15': 0, 'E16': 0, 'E17': 0, 'E18': 0, 'E19': 0, 'E20': 0, 'K21': 0, '...
#! /usr/bin/env python3 ''' Problem 1 - Project Euler http://projecteuler.net/index.php?section=problems&id=001 ''' def summul(n, x): return int(x * (n // x) * (n // x + 1) / 2) if __name__ == '__main__': N = 1000 - 1 print(summul(N, 3) + summul(N, 5) - summul(N, 3 * 5))
""" Problem 1 - Project Euler http://projecteuler.net/index.php?section=problems&id=001 """ def summul(n, x): return int(x * (n // x) * (n // x + 1) / 2) if __name__ == '__main__': n = 1000 - 1 print(summul(N, 3) + summul(N, 5) - summul(N, 3 * 5))
for t in range(int(input())): A,B=input().split() L=[[0]*(len(A)+1) for i in range((len(B)+1))] for i in range(len(B)): for j in range(len(A)): if B[i]==A[j]: L[i+1][j+1]=L[i][j]+1 else : L[i+1][j+1]=max(L[i][j+1],L[i+1][j]) print(f"#{t+1}...
for t in range(int(input())): (a, b) = input().split() l = [[0] * (len(A) + 1) for i in range(len(B) + 1)] for i in range(len(B)): for j in range(len(A)): if B[i] == A[j]: L[i + 1][j + 1] = L[i][j] + 1 else: L[i + 1][j + 1] = max(L[i][j + 1], L...
with Flow(bypass_sub_flows=True, add_flow_enable="enabled", environment="probe") as flow: flow.description = ''' An example of creating an entire test program from a single source file ''' #unless Origen.app.environment.name == 'v93k_global' flow.set_resources_filename('prb2') ...
with flow(bypass_sub_flows=True, add_flow_enable='enabled', environment='probe') as flow: flow.description = '\n An example of creating an entire test program from a single source file\n ' flow.set_resources_filename('prb2') flow.func('erase_all', duration='dynamic', number=10000) flow.func('mar...
__title__ = 'campy' __description__ = 'ACM Graphical Libraries in Python' __url__ = 'https://campy.sredmond.io/' __license__ = 'MIT' __version__ = '0.0.1.dev3' __build__ = 0x000001 __status__ = 'Prototype' __author__ = 'Sam Redmond' __maintainer__ = 'Sam Redmond' __email__ = 'sredmond@stanford.edu' __copyright__ = '(...
__title__ = 'campy' __description__ = 'ACM Graphical Libraries in Python' __url__ = 'https://campy.sredmond.io/' __license__ = 'MIT' __version__ = '0.0.1.dev3' __build__ = 1 __status__ = 'Prototype' __author__ = 'Sam Redmond' __maintainer__ = 'Sam Redmond' __email__ = 'sredmond@stanford.edu' __copyright__ = '(c) 2016-2...
#!/usr/bin/env python3 def solve(data): allowed = [] test_num = 0 prv_rng = range(0, 0) for rng in sorted(data, key=lambda x: x.start): if rng.stop in prv_rng: continue while not test_num in rng: allowed.append(test_num) test_num += 1 prv_rng ...
def solve(data): allowed = [] test_num = 0 prv_rng = range(0, 0) for rng in sorted(data, key=lambda x: x.start): if rng.stop in prv_rng: continue while not test_num in rng: allowed.append(test_num) test_num += 1 prv_rng = rng test_num =...
S = input() A = input() if len(S) < len(A): print('UNRESTORABLE') exit(0) for i in reversed(range(len(S)-len(A)+1)): for j in range(len(A)): if not(S[i+j] == A[j] or S[i+j] == '?'): break else: ans = S[:i] + A + S[i+len(A):] ans = ans.replace('?', 'a') prin...
s = input() a = input() if len(S) < len(A): print('UNRESTORABLE') exit(0) for i in reversed(range(len(S) - len(A) + 1)): for j in range(len(A)): if not (S[i + j] == A[j] or S[i + j] == '?'): break else: ans = S[:i] + A + S[i + len(A):] ans = ans.replace('?', 'a') ...
def to_celsius(x): return (x-32)*5/9 for x in range(0,101,10): print(x,to_celsius(x))
def to_celsius(x): return (x - 32) * 5 / 9 for x in range(0, 101, 10): print(x, to_celsius(x))
def selection_sort(array): length = len(array) for i in range(0, length, 1): higher = i for j in range(i+1, length, 1): if array[higher] > array[j]: higher = j if higher != i: tmp = array[higher] array[higher] = array[i] ...
def selection_sort(array): length = len(array) for i in range(0, length, 1): higher = i for j in range(i + 1, length, 1): if array[higher] > array[j]: higher = j if higher != i: tmp = array[higher] array[higher] = array[i] a...
class Unit(object): def __init__(self, name, attack, defend): self.name = name self.attack = attack self.defend = defend def __repr__(self): return self.name units = { 'droid': Unit('droid', 42, 41), 'gorgul': Unit('gorgul', 24, 20), 'pushkar': Unit('pushkar', 55, ...
class Unit(object): def __init__(self, name, attack, defend): self.name = name self.attack = attack self.defend = defend def __repr__(self): return self.name units = {'droid': unit('droid', 42, 41), 'gorgul': unit('gorgul', 24, 20), 'pushkar': unit('pushkar', 55, 37), 'giant': ...
X, Y = map(int, input().split()) X += 2 if Y >= 30: X += 1 Y -= 30 else: Y += 30 X %= 24 print('%02d:%02d' % (X, Y))
(x, y) = map(int, input().split()) x += 2 if Y >= 30: x += 1 y -= 30 else: y += 30 x %= 24 print('%02d:%02d' % (X, Y))
class Node: def __init__(self, key) -> None: self.val = key self.left = None self.right = None def printInorder(node): if node == None: return else: printInorder(node.left) print(node.val, end=' ') right_node = printInorder(node.right) def pre...
class Node: def __init__(self, key) -> None: self.val = key self.left = None self.right = None def print_inorder(node): if node == None: return else: print_inorder(node.left) print(node.val, end=' ') right_node = print_inorder(node.right) def pre_or...
filenames = ['file1.txt', 'file2.txt', ...] with open('path/to/output/file', 'w') as outfile: for fname in filenames: with open(fname) as infile: outfile.write(infile.read())
filenames = ['file1.txt', 'file2.txt', ...] with open('path/to/output/file', 'w') as outfile: for fname in filenames: with open(fname) as infile: outfile.write(infile.read())
class Parent: def __init__(self, name): print("Parent Object Created") self.testFunc(name) def testFunc(self, name): print("Parent testFunc called {}", name) class Child(Parent): def __init__(self, name): print("Child Object Created") self.testFunc(name) # def testFunc(self, name): # print("Child testF...
class Parent: def __init__(self, name): print('Parent Object Created') self.testFunc(name) def test_func(self, name): print('Parent testFunc called {}', name) class Child(Parent): def __init__(self, name): print('Child Object Created') self.testFunc(name) class O...
''' Write a Python program to find the largest product of the pair of adjacent elements from a given list of integers. Sample Input: [1,2,3,4,5,6] [1,2,3,4,5] [2,3] Sample Output: 30 20 6 ''' ''' The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is p...
""" Write a Python program to find the largest product of the pair of adjacent elements from a given list of integers. Sample Input: [1,2,3,4,5,6] [1,2,3,4,5] [2,3] Sample Output: 30 20 6 """ '\nThe zip() function returns a zip object, which is an \niterator of tuples where the first item in each passed iterator is pa...
def longestPeak(array): # Write your code here. maxPeakLength=0 i=1 while(i<len(array)-1): # print(i) isPeak= array[i]>array[i-1] and array[i]>array[i+1] if not isPeak: i+=1 continue leftIdx=i-2 while(leftIdx>=0 and array[leftIdx]<array[...
def longest_peak(array): max_peak_length = 0 i = 1 while i < len(array) - 1: is_peak = array[i] > array[i - 1] and array[i] > array[i + 1] if not isPeak: i += 1 continue left_idx = i - 2 while leftIdx >= 0 and array[leftIdx] < array[leftIdx + 1]: ...
''' Array uses one-based indexing to access elements Implements Max-Heap Tree Can be used for max priority queue ''' class HeapTree: def __init__(self, value:int): self.array = [0] self.heap_size = 0 self.max_size = value def left_child(self, index:int): ''' ...
""" Array uses one-based indexing to access elements Implements Max-Heap Tree Can be used for max priority queue """ class Heaptree: def __init__(self, value: int): self.array = [0] self.heap_size = 0 self.max_size = value def left_child(self, index: int): """ ...
def display(g): for y in range(g.height): for x in range(g.width): digit, snake = g(x, y) if snake: print("[{}]".format(digit), end="") else: print(" {} ".format(digit), end="") if x % 3 == 2: print(" ", end="") ...
def display(g): for y in range(g.height): for x in range(g.width): (digit, snake) = g(x, y) if snake: print('[{}]'.format(digit), end='') else: print(' {} '.format(digit), end='') if x % 3 == 2: print(' ', end=''...
#=============================================================== # DMXIS Macro (c) 2010 db audioware limited #=============================================================== found = False for ch in GetAllSelCh(True): nm = GetChName(ch) if nm=="Pan" or nm=="Tilt": SelectCh(ch, 1) found ...
found = False for ch in get_all_sel_ch(True): nm = get_ch_name(ch) if nm == 'Pan' or nm == 'Tilt': select_ch(ch, 1) found = True else: select_ch(ch, 0) if not found: message('No Pan/Tilt channels found!')
s = '' i = 1 while (True): s = s + str(i) i = i + 1 if len(s) > 1000000: break print(i) r = 1 r = r * int(s[1 - 1]) r = r * int(s[10 - 1]) r = r * int(s[100 - 1]) r = r * int(s[1000 - 1]) r = r * int(s[10000 - 1]) r = r * int(s[100000 - 1]) r = r * int(s[1000000 - 1]) print("result = ", r)
s = '' i = 1 while True: s = s + str(i) i = i + 1 if len(s) > 1000000: break print(i) r = 1 r = r * int(s[1 - 1]) r = r * int(s[10 - 1]) r = r * int(s[100 - 1]) r = r * int(s[1000 - 1]) r = r * int(s[10000 - 1]) r = r * int(s[100000 - 1]) r = r * int(s[1000000 - 1]) print('result = ', r)
class WeightedFalseNegativeLossMetric: def map(self, predicted, actual, weight, offset, model): cost_tp = 5000 # set prior to use cost_tn = 0 # do not change cost_fp = cost_tp # do not change cost_fn = weight # do not change y = actual[0] p = predicted[2] # [clas...
class Weightedfalsenegativelossmetric: def map(self, predicted, actual, weight, offset, model): cost_tp = 5000 cost_tn = 0 cost_fp = cost_tp cost_fn = weight y = actual[0] p = predicted[2] if y == 1: denom = cost_fn else: denom...
# PROBLEM LINK:- https://leetcode.com/problems/reach-a-number/ class Solution: def reachNumber(self, target: int) -> int: target = abs(target) res = 0 sum = 0 while sum < target or (sum - target)%2 != 0: res += 1 sum += res return res
class Solution: def reach_number(self, target: int) -> int: target = abs(target) res = 0 sum = 0 while sum < target or (sum - target) % 2 != 0: res += 1 sum += res return res
def sanitize_supply_cost(a, cost, name): if cost is None: cost = a.default_cost if len(a.cost_names) > 1: a.log.info("Using default cost, {}, for {}.".format(cost, name)) if cost not in a.cost_names: raise ValueError("{} not an available cost.".format(cost)) return c...
def sanitize_supply_cost(a, cost, name): if cost is None: cost = a.default_cost if len(a.cost_names) > 1: a.log.info('Using default cost, {}, for {}.'.format(cost, name)) if cost not in a.cost_names: raise value_error('{} not an available cost.'.format(cost)) return cost ...
class Solution: def longestPalindrome(self, s): slen = len(s) longest = '' longest_len = 0 for i in range(1, slen-1): loops+=1 l, r = i-1, i+1 subs = s[i] while l >= 0 and r < slen: if s[l] != s[r]: ...
class Solution: def longest_palindrome(self, s): slen = len(s) longest = '' longest_len = 0 for i in range(1, slen - 1): loops += 1 (l, r) = (i - 1, i + 1) subs = s[i] while l >= 0 and r < slen: if s[l] != s[r]: ...
class TrieNode: def __init__(self): self.children = {} self.word = None class Solution: def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: root = TrieNode() r, c = len(board), len(board[0]) for w in words: cur = root for ...
class Trienode: def __init__(self): self.children = {} self.word = None class Solution: def find_words(self, board: List[List[str]], words: List[str]) -> List[str]: root = trie_node() (r, c) = (len(board), len(board[0])) for w in words: cur = root ...
# # PySNMP MIB module Unisphere-Data-DVMRP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-DVMRP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:23:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7....
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_union, constraints_intersection, value_range_constraint, single_value_constraint) ...
def longestRepeatedSubSeq(str): n = len(str) dp = [[0 for i in range(n + 1)] for j in range(n + 1)] for i in range(1, n + 1): for j in range(1, n + 1): if (str[i - 1] == str[j - 1] and i != j): dp[i][j] = 1 + dp[i - 1][j - 1] else: dp[i][j] = ...
def longest_repeated_sub_seq(str): n = len(str) dp = [[0 for i in range(n + 1)] for j in range(n + 1)] for i in range(1, n + 1): for j in range(1, n + 1): if str[i - 1] == str[j - 1] and i != j: dp[i][j] = 1 + dp[i - 1][j - 1] else: dp[i][j] = ...
class Solution: def maxAreaOfIsland(self, grid: List[List[int]]) -> int: if not grid or not grid[0]: return 0 result = 0 def dfs(x, y): dx = [0, 0, 1, -1] dy = [1, -1, 0, 0] count = 1 for k in range(4): nx, ny = dx[k...
class Solution: def max_area_of_island(self, grid: List[List[int]]) -> int: if not grid or not grid[0]: return 0 result = 0 def dfs(x, y): dx = [0, 0, 1, -1] dy = [1, -1, 0, 0] count = 1 for k in range(4): (nx, ny)...
bandera = ["N","B","B","N","A","B","B","N","B","N","N","A","N","N","B","A","A"] print(bandera) negro = [] blanco = [] azul = [] def ordenada(bandera): if len(bandera) > 0: color = bandera.pop(0) if color =="N": negro.append(color) ordenada(bandera) elif color == "B": ...
bandera = ['N', 'B', 'B', 'N', 'A', 'B', 'B', 'N', 'B', 'N', 'N', 'A', 'N', 'N', 'B', 'A', 'A'] print(bandera) negro = [] blanco = [] azul = [] def ordenada(bandera): if len(bandera) > 0: color = bandera.pop(0) if color == 'N': negro.append(color) ordenada(bandera) e...
class Solution: def missingNumber(self, nums: List[int]) -> int: result = len(nums) for i in range(len(nums)): result ^= i ^ nums[i] return result
class Solution: def missing_number(self, nums: List[int]) -> int: result = len(nums) for i in range(len(nums)): result ^= i ^ nums[i] return result
class Solution: def __init__(self): self.inorder_p = {} self.postorder_idx = None def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: self.postorder_idx = len(postorder) - 1 for i, v in enumerate(inorder): self.inorder_p[v] = i ...
class Solution: def __init__(self): self.inorder_p = {} self.postorder_idx = None def build_tree(self, inorder: List[int], postorder: List[int]) -> TreeNode: self.postorder_idx = len(postorder) - 1 for (i, v) in enumerate(inorder): self.inorder_p[v] = i retu...
def intAdd(x): return lambda y: x + y def intMul(x): return lambda y: x * y def numAdd(x): return lambda y: x + y def numMul(x): return lambda y: x * y
def int_add(x): return lambda y: x + y def int_mul(x): return lambda y: x * y def num_add(x): return lambda y: x + y def num_mul(x): return lambda y: x * y