content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def check_best_ways(matrix: list, row: int, col: int): direction_up = float('-inf') position_direction_up = [] up_sum = 0 for r in range(row - 1, -1, -1): if matrix[r][col] == "X": break up_sum += matrix[r][col] direction_up = up_sum position_direction_up.appe...
def check_best_ways(matrix: list, row: int, col: int): direction_up = float('-inf') position_direction_up = [] up_sum = 0 for r in range(row - 1, -1, -1): if matrix[r][col] == 'X': break up_sum += matrix[r][col] direction_up = up_sum position_direction_up.appe...
class Asset: def __init__(self, type, nameplate, project): self.type = type self.nameplate = nameplate self.project = project B02 = Asset("Tracker","none", "Saltwood Solar") print(B02.project)
class Asset: def __init__(self, type, nameplate, project): self.type = type self.nameplate = nameplate self.project = project b02 = asset('Tracker', 'none', 'Saltwood Solar') print(B02.project)
pokerNames = ('3','4','5','6','7','8','9','10','J','Q','K','A','2','B','R') pokerValues = ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 100,200,300) pokerDict = dict(zip(pokerNames, pokerValues)) def getCardValue(name): return pokerDict[name] if __name__ == '__main__': print(getCardValue('3')) ...
poker_names = ('3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A', '2', 'B', 'R') poker_values = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 100, 200, 300) poker_dict = dict(zip(pokerNames, pokerValues)) def get_card_value(name): return pokerDict[name] if __name__ == '__main__': print(get_card_value('3')) ...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 # # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without ...
""" To Use: - subclass Observable for a thing that chagnes - subclass Observer for the things that will use those changes - Observers call Observable's #addObserver to register and #removeObserver to stop - When the thing (the Observable) changes, #notifyObservers calls all the Observers """ class Observer: def...
def parse_ner_dataset_file(f): tokens = [] for i, l in enumerate(f): l_split = l.split() if len(l_split) == 0: yield tokens tokens.clear() continue if len(l_split) < 2: continue # todo: fix this else: tokens.append({'te...
def parse_ner_dataset_file(f): tokens = [] for (i, l) in enumerate(f): l_split = l.split() if len(l_split) == 0: yield tokens tokens.clear() continue if len(l_split) < 2: continue else: tokens.append({'text': l_split[0],...
config = { "-varprune":[0,int], "-recompute":[False,bool], "-sort":[False,bool], "-no-sos":[False,bool], "-no-eos":[False,bool], "-write":["./counts",str], "-gtmin":[1,int], "-gtmax":[5,int], "-ndiscount":[Fals...
config = {'-varprune': [0, int], '-recompute': [False, bool], '-sort': [False, bool], '-no-sos': [False, bool], '-no-eos': [False, bool], '-write': ['./counts', str], '-gtmin': [1, int], '-gtmax': [5, int], '-ndiscount': [False, bool], '-wbdiscount': [False, bool], '-kndiscount': [True, bool], '-ukndiscount': [False, b...
class Config: # region bug configurations PROJECT_ROOT_PATH = r"/Users/ori/pergit/defects/math_1_buggy" BUG_PROJECT = 'math' BUG_ID = 1 IGNORED_CLASS_LIST = ['FastCosineTransformerTest', 'FastSineTransformerTest', 'FastMathStrictComparisonTest', 'CorrelatedRandomVectorGener...
class Config: project_root_path = '/Users/ori/pergit/defects/math_1_buggy' bug_project = 'math' bug_id = 1 ignored_class_list = ['FastCosineTransformerTest', 'FastSineTransformerTest', 'FastMathStrictComparisonTest', 'CorrelatedRandomVectorGeneratorTest', 'FastMathTestPerformance'] actual_faults_met...
# hint: see np.diff() inter_switch_intervals = np.diff(switch_times) # plot inter-switch intervals with plt.xkcd(): plot_interswitch_interval_histogram(inter_switch_intervals)
inter_switch_intervals = np.diff(switch_times) with plt.xkcd(): plot_interswitch_interval_histogram(inter_switch_intervals)
class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: if len(piles)==0: return 0 l,r = 1,pow(10,9) while l<=r: m = (l+r)>>1 sum = 0 for i in piles: sum+=(...
class Solution: def min_eating_speed(self, piles: List[int], H: int) -> int: if len(piles) == 0: return 0 (l, r) = (1, pow(10, 9)) while l <= r: m = l + r >> 1 sum = 0 for i in piles: sum += (i + m - 1) // m if sum ...
digits = [0,1,2,3,4,5,6,7,8,9] print(digits[-1]) print(digits[-len(digits)]) print(digits[:3]) #stride mige chanta chanta beri print((digits[0:9:2])) #bayad az akhar be aval bzanim print((digits[9:0:-1])) goods = 'success,win,best_coder,elham' print(goods) l = goods.split(",") #ye string ro migire o split mikone be li...
digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(digits[-1]) print(digits[-len(digits)]) print(digits[:3]) print(digits[0:9:2]) print(digits[9:0:-1]) goods = 'success,win,best_coder,elham' print(goods) l = goods.split(',') print(l) l = goods.split('win') print(l) goods = 'success,win,best_coder,elham' l = goods.split(',')...
class Holding(object): def __init__(self, name, ticker, weight=100, sector=None, news=None, link=None): self.name = name self.ticker = ticker self.weight = weight self.sector = sector self.news = news self.link = link def set_name(self, name): self.name ...
class Holding(object): def __init__(self, name, ticker, weight=100, sector=None, news=None, link=None): self.name = name self.ticker = ticker self.weight = weight self.sector = sector self.news = news self.link = link def set_name(self, name): self.name ...
# Question : https://www.careercup.com/question?id=5754648968298496 dishes = {"Pasta":["Tomato Sauce", "Onions", "Garlic"], "Chicken Curry":["Chicken", "Curry Sauce"], "Fried Rice":["Rice", "Onions", "Nuts"], "Salad":["Spinach", "Nuts"], "Sandwich":["Cheese", "Bread"], ...
dishes = {'Pasta': ['Tomato Sauce', 'Onions', 'Garlic'], 'Chicken Curry': ['Chicken', 'Curry Sauce'], 'Fried Rice': ['Rice', 'Onions', 'Nuts'], 'Salad': ['Spinach', 'Nuts'], 'Sandwich': ['Cheese', 'Bread'], 'Quesadilla': ['Chicken', 'Cheese']} def group_by_ingredients(dishes): ingredients = {} for dish in dish...
class Funcionario: def __init__(self, nome, idade, salario): self.nome = nome self.idade = idade self.__salario = salario # atributo privado def set_salario(self, salario): if salario > 0: self.__salario = salario else: print("Valor invalido") ...
class Funcionario: def __init__(self, nome, idade, salario): self.nome = nome self.idade = idade self.__salario = salario def set_salario(self, salario): if salario > 0: self.__salario = salario else: print('Valor invalido') def get_salario(...
# phone numbers for countries phone_codes = {} phone_codes["DE"] = 49 phone_codes["TR"] = 90 phone_codes["PK"] = 92 phone_codes["IN"] = 91 code = phone_codes["IN"] print(code)
phone_codes = {} phone_codes['DE'] = 49 phone_codes['TR'] = 90 phone_codes['PK'] = 92 phone_codes['IN'] = 91 code = phone_codes['IN'] print(code)
def hello(): return hw() def hw(): cadena = "<h1>Prueba</h1>" cadena += "<h2>Probando</h2>" cadena += "<div>Hello World.</div>" return cadena
def hello(): return hw() def hw(): cadena = '<h1>Prueba</h1>' cadena += '<h2>Probando</h2>' cadena += '<div>Hello World.</div>' return cadena
def test_object(store): test_store_object(store) test_events_object(store.events) test_attendees_object(store.attendees) test_attendees_object(store.waitings) test_users_object(store.users) def test_store_object(store): assert store assert store.events assert store.attendees...
def test_object(store): test_store_object(store) test_events_object(store.events) test_attendees_object(store.attendees) test_attendees_object(store.waitings) test_users_object(store.users) def test_store_object(store): assert store assert store.events assert store.attendees assert ...
# # PySNMP MIB module BAS-PBRF-OSPF-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BAS-PBRF-OSPF-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:34:08 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, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_union, single_value_constraint, constraints_intersection, value_range_constraint) ...
# Synthetic fault scarp parameters fault_dip = 60 fault_slip = 10 fault_slip_rate = 2 fault_scarp_profile_length = 30 fault_scarp_exponential = True # True for simple fault_scarp_steps = 1 fault_scarp_step_width = 5 final_time = fault_slip / fault_slip_rate # Parameters for synthetic fault scarps and for calculating d...
fault_dip = 60 fault_slip = 10 fault_slip_rate = 2 fault_scarp_profile_length = 30 fault_scarp_exponential = True fault_scarp_steps = 1 fault_scarp_step_width = 5 final_time = fault_slip / fault_slip_rate diffusion_coefficient = 10 time_steps_between_plots = 20 change_in_distance = 1 calculation_final_time = 25
class Lit_detail: def __init__(self, lit_name, lit_author): self.title = lit_name self.author = lit_author def display(self): return "Title:" + str(self.title) + " Author:" + str(self.author) class Book(Lit_detail): unique_count = 0 total_count = 0 ...
class Lit_Detail: def __init__(self, lit_name, lit_author): self.title = lit_name self.author = lit_author def display(self): return 'Title:' + str(self.title) + ' Author:' + str(self.author) class Book(Lit_detail): unique_count = 0 total_count = 0 def __init__(self, b...
# my_string = input("Input as many values as you want separated by whitespace: ") # my_list = my_string.split(" ") # my_numbers = [int(element) for element in my_list] # print(my_numbers, sum(my_numbers), min(my_numbers), max(my_numbers)) # one liner as above but maybe a bit too dense my_nums = [int(t) for t in input(...
my_nums = [int(t) for t in input('Enter values separated by whitespace').split(' ')] print(my_nums)
with open('input18.txt') as f: maths = f.read().split('\n') ops = { '*':[2, 'l', 2, lambda x, y : y * x], '+':[3, 'l', 2, lambda x, y : y + x] } def solve(read): stack = [] out = [] numstack = [] funcstack = [] last = '' for t in read: if t.isspace(): contin...
with open('input18.txt') as f: maths = f.read().split('\n') ops = {'*': [2, 'l', 2, lambda x, y: y * x], '+': [3, 'l', 2, lambda x, y: y + x]} def solve(read): stack = [] out = [] numstack = [] funcstack = [] last = '' for t in read: if t.isspace(): continue if l...
def check_prime(integer): if integer == 1: return False if integer == 2: return True if integer % 2 == 0: return False for i in range(3, int(integer**(1/2))+1, 2): if integer % i == 0: return False else: return True num_primes = 0 n = 0 while num_...
def check_prime(integer): if integer == 1: return False if integer == 2: return True if integer % 2 == 0: return False for i in range(3, int(integer ** (1 / 2)) + 1, 2): if integer % i == 0: return False else: return True num_primes = 0 n = 0 while...
n = int(input()) upper_sum , lower_sum = 0, 0 arr = [] for _ in range(n): upper, lower = [int(x) for x in input().split()] upper_sum += upper lower_sum += lower arr.append((upper, lower)) if (upper_sum % 2) == 0 and (lower_sum % 2) == 0: print("0") else: msg = "-1" for upper, lower in arr: ...
n = int(input()) (upper_sum, lower_sum) = (0, 0) arr = [] for _ in range(n): (upper, lower) = [int(x) for x in input().split()] upper_sum += upper lower_sum += lower arr.append((upper, lower)) if upper_sum % 2 == 0 and lower_sum % 2 == 0: print('0') else: msg = '-1' for (upper, lower) in arr...
l_rate = 0.3 n_epoch = 100 loss = np.zeros(n_epoch) beta = [0.0,0.0,0.0] for epoch in range(n_epoch): sum_error = 0 for row in train: x = row[0:-1] # input features y = row[-1] # output label yhat = predict(row, beta) error = y - yhat sum_error += error**2 beta...
l_rate = 0.3 n_epoch = 100 loss = np.zeros(n_epoch) beta = [0.0, 0.0, 0.0] for epoch in range(n_epoch): sum_error = 0 for row in train: x = row[0:-1] y = row[-1] yhat = predict(row, beta) error = y - yhat sum_error += error ** 2 beta[0] += l_rate * error * yhat * ...
def fetch_data1(): return "data1" def fetch_data2(): return "data2" def process_data1(): return fetch_data1().upper() def process_data2(): return fetch_data2().upper() def process_data3(): return process_data1() + "-" + process_data2() def show_report1(): print(process_data3()) def show_re...
def fetch_data1(): return 'data1' def fetch_data2(): return 'data2' def process_data1(): return fetch_data1().upper() def process_data2(): return fetch_data2().upper() def process_data3(): return process_data1() + '-' + process_data2() def show_report1(): print(process_data3()) def show_re...
''' @author: Kittl ''' def exportStorageTypes(dpf, exportProfile, tables, colHeads): # Get the index in the list of worksheets if exportProfile is 2: cmpStr = "StorageType" elif exportProfile is 3: cmpStr = "" idxWs = [idx for idx,val in enumerate(tables[exportProfile-1]) if val == ...
""" @author: Kittl """ def export_storage_types(dpf, exportProfile, tables, colHeads): if exportProfile is 2: cmp_str = 'StorageType' elif exportProfile is 3: cmp_str = '' idx_ws = [idx for (idx, val) in enumerate(tables[exportProfile - 1]) if val == cmpStr] if not idxWs: dpf.Pr...
class MongoUsersUtils: def __init__(self, mongo): self.mongo = mongo self.collection_name = "users" def save(self, user): return self.mongo.db[self.collection_name].insert(user)
class Mongousersutils: def __init__(self, mongo): self.mongo = mongo self.collection_name = 'users' def save(self, user): return self.mongo.db[self.collection_name].insert(user)
def reverseBits(n: int) -> int: bin_n = list(bin(n)[2:]) bin_n.reverse() bin_n.extend(['0'] * (32 - len(bin_n))) return int(''.join(bin_n), 2) def reverseBits(n: int) -> int: rtn = 0 for i in range(32): rtn = (rtn << 1) | (n & 1) n >>= 1 return rtn def reverseBits(n: int)...
def reverse_bits(n: int) -> int: bin_n = list(bin(n)[2:]) bin_n.reverse() bin_n.extend(['0'] * (32 - len(bin_n))) return int(''.join(bin_n), 2) def reverse_bits(n: int) -> int: rtn = 0 for i in range(32): rtn = rtn << 1 | n & 1 n >>= 1 return rtn def reverse_bits(n: int) ->...
def get_upstream_conduits(node_id, con_df, in_col_name="InletNode", out_col_name="OutletNode"): us_nodes = get_upstream_nodes(node_id, con_df, in_col_name, out_col_name) us_cons = con_df[(con_df[in_col_name].isin(us_nodes)) | (con_df[out_col_name].isin(us_nodes))] return us_cons.index def get_upstream_nod...
def get_upstream_conduits(node_id, con_df, in_col_name='InletNode', out_col_name='OutletNode'): us_nodes = get_upstream_nodes(node_id, con_df, in_col_name, out_col_name) us_cons = con_df[con_df[in_col_name].isin(us_nodes) | con_df[out_col_name].isin(us_nodes)] return us_cons.index def get_upstream_nodes_on...
#unlicense.org #in case importing the numpy/scipy libraries should be avoided: def zeros(item, quanity): return [item] * quanity def simple_matrix(item,quanity): return [item] * quanity
def zeros(item, quanity): return [item] * quanity def simple_matrix(item, quanity): return [item] * quanity
#!/usr/bin/env python # Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
task_type = 'classification' column_names = ['age', 'workclass', 'fnlwgt', 'education', 'education_num', 'marital_status', 'occupation', 'relationship', 'race', 'gender', 'capital_gain', 'capital_loss', 'hours_per_week', 'native_country', 'income_bracket'] serving_column_names = ['age', 'workclass', 'education', 'educa...
set_name(0x801379C4, "PreGameOnlyTestRoutine__Fv", SN_NOWARN) set_name(0x80139A88, "DRLG_PlaceDoor__Fii", SN_NOWARN) set_name(0x80139F5C, "DRLG_L1Shadows__Fv", SN_NOWARN) set_name(0x8013A374, "DRLG_PlaceMiniSet__FPCUciiiiiii", SN_NOWARN) set_name(0x8013A7E0, "DRLG_L1Floor__Fv", SN_NOWARN) set_name(0x8013A8CC, "StoreBlo...
set_name(2148760004, 'PreGameOnlyTestRoutine__Fv', SN_NOWARN) set_name(2148768392, 'DRLG_PlaceDoor__Fii', SN_NOWARN) set_name(2148769628, 'DRLG_L1Shadows__Fv', SN_NOWARN) set_name(2148770676, 'DRLG_PlaceMiniSet__FPCUciiiiiii', SN_NOWARN) set_name(2148771808, 'DRLG_L1Floor__Fv', SN_NOWARN) set_name(2148772044, 'StoreBlo...
class ValidationException(Exception): pass class RepromptException(Exception): pass
class Validationexception(Exception): pass class Repromptexception(Exception): pass
m,n=map(int,input().split()) mat=[] for i in range(m): k=list(map(int,input().split())) mat.append(k) mat count=mat[0][0] i=0 j=0 while(True): if (i==m-1 and j==n-1): break if (i<m-1 and j<n-1): if (mat[i+1][j]>mat[i][j+1]): count+=mat[i+1][j] i+=1 else: count+...
(m, n) = map(int, input().split()) mat = [] for i in range(m): k = list(map(int, input().split())) mat.append(k) mat count = mat[0][0] i = 0 j = 0 while True: if i == m - 1 and j == n - 1: break if i < m - 1 and j < n - 1: if mat[i + 1][j] > mat[i][j + 1]: count += mat[i + 1]...
def generate_LAMMPS_potential(data): #potential_file = '# Potential file generated by aiida plugin (please check citation in the orignal file)\n' potential_file = '' for line in data['file_contents']: potential_file += '{}'.format(line) return potential_file def get_input_potential_lines(da...
def generate_lammps_potential(data): potential_file = '' for line in data['file_contents']: potential_file += '{}'.format(line) return potential_file def get_input_potential_lines(data, names=None, potential_filename='potential.pot'): lammps_input_text = 'pair_style eam/{}\n'.format(data['...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"div2k_path": "00_datasets.ipynb", "div2k_train_lr_path": "00_datasets.ipynb", "div2k_train_lr_x2": "00_datasets.ipynb", "div2k_train_lr_x3": "00_datasets.ipynb", "div2k_tr...
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'div2k_path': '00_datasets.ipynb', 'div2k_train_lr_path': '00_datasets.ipynb', 'div2k_train_lr_x2': '00_datasets.ipynb', 'div2k_train_lr_x3': '00_datasets.ipynb', 'div2k_train_lr_x4': '00_datasets.ipynb', 'div2k_train_hr': '00_datasets.ipynb', 'div2...
myStr = input("Enter a String: ") Str = "" for ind in range (2, len(myStr)): if ind%2 == 0: Str = Str + myStr[ind] print (myStr[0] + Str)
my_str = input('Enter a String: ') str = '' for ind in range(2, len(myStr)): if ind % 2 == 0: str = Str + myStr[ind] print(myStr[0] + Str)
# Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'shared', 'type': 'shared_library', 'sources': [ 'file.c' ], }, { 'target_name': 's...
{'targets': [{'target_name': 'shared', 'type': 'shared_library', 'sources': ['file.c']}, {'target_name': 'shared_no_so_suffix', 'product_extension': 'so.0.1', 'type': 'shared_library', 'sources': ['file.c']}, {'target_name': 'static', 'type': 'static_library', 'sources': ['file.c']}, {'target_name': 'shared_executable'...
data = pd.read_csv('/Users/djamillakhdar-hamina/Desktop/kavli_mdressel_combined_4col.csv') # Count edges to target edge_count=data.groupby('target').count() # Merge back to x using target-> target target_self_merge= pd.merge(data, edge_count, left_on='target', right_on='target') # Merge back to x using source -> tar...
data = pd.read_csv('/Users/djamillakhdar-hamina/Desktop/kavli_mdressel_combined_4col.csv') edge_count = data.groupby('target').count() target_self_merge = pd.merge(data, edge_count, left_on='target', right_on='target') source_self_merge = pd.merge(target_self_merge, edge_count, left_on='source_x', right_on='target', ho...
class Solution(object): def findMinDifference1(self, timePoints): if len(timePoints) > 1440: return 0 s = sorted(map(lambda t: int(t[:2]) * 60 + int(t[3:]), timePoints)) return min(s2 - s1 for s1,s2 in zip(s, s[1:] + [1440+s[0]])) def findMinDifference2(self, timePoints): ...
class Solution(object): def find_min_difference1(self, timePoints): if len(timePoints) > 1440: return 0 s = sorted(map(lambda t: int(t[:2]) * 60 + int(t[3:]), timePoints)) return min((s2 - s1 for (s1, s2) in zip(s, s[1:] + [1440 + s[0]]))) def find_min_difference2(self, tim...
# APIs for Windows 32-bit kernel32 library. # Format: retval, rettype, callconv, exactname, arglist(type, name) # arglist type is one of ['int', 'void *'] # arglist name is one of [None, 'funcptr', 'obj', 'ptr'] api_defs = { 'kernel32.main_entry':( 'int', None, 'stdcall', 'kernel32.main_entry', ...
api_defs = {'kernel32.main_entry': ('int', None, 'stdcall', 'kernel32.main_entry', (('int', None), ('int', None), ('int', None))), 'kernel32.activateactctx': ('int', None, 'stdcall', 'kernel32.ActivateActCtx', (('int', None), ('int', None))), 'kernel32.addatoma': ('int', None, 'stdcall', 'kernel32.AddAtomA', (('int', N...
class ObjectContext: def __init__(self) -> None: self.definedTypes = {} self.definedSymbols = {} def get_type(self, typeName: str): return self.definedTypes[typeName] def type_of(self, symbol: str): if self.definedSymbols.__contains__(symbol): return self.defin...
class Objectcontext: def __init__(self) -> None: self.definedTypes = {} self.definedSymbols = {} def get_type(self, typeName: str): return self.definedTypes[typeName] def type_of(self, symbol: str): if self.definedSymbols.__contains__(symbol): return self.defin...
class Scenario: _requests = None def __init__(self, requests): self._requests = requests def get_requests(self): return self._requests
class Scenario: _requests = None def __init__(self, requests): self._requests = requests def get_requests(self): return self._requests
#Calcular y mostrar la nota final para cada materia, y el promedio general de las tres materias def calc_matematicas(examen, tarea1, tarea2, tarea3): valor_examen = examen * 0.9 total_tareas = tarea1 + tarea2 + tarea3 promedio_tareas = total_tareas / 3 valor_tareas = promedio_tareas * 0.1 final_mate...
def calc_matematicas(examen, tarea1, tarea2, tarea3): valor_examen = examen * 0.9 total_tareas = tarea1 + tarea2 + tarea3 promedio_tareas = total_tareas / 3 valor_tareas = promedio_tareas * 0.1 final_matematicas = round(valor_examen + valor_tareas, 2) return final_matematicas def calc_fisica(ex...
my_list = [20, 39, 34, 20, 24, 20, 10, 11] my_set = sorted(set(my_list)) print(my_set)
my_list = [20, 39, 34, 20, 24, 20, 10, 11] my_set = sorted(set(my_list)) print(my_set)
settings = { 'token': 'DISCORD_BOT_TOKEN', 'id': BOT_ID, 'prefix': 'PREFIX', 'embedcolor': EMBED_COLOR_(0x123456), 'author-id': YOUR_ID, 'vk-api-token': 'VK_API_TOKEN', 'bot_avatar_url': 'BOT_AVATAR_URL', 'youtube_apikey': 'YOUTUBE_DATA_API_KEY', 'weather_token': 'OPENWEATHERMAP_TOKE...
settings = {'token': 'DISCORD_BOT_TOKEN', 'id': BOT_ID, 'prefix': 'PREFIX', 'embedcolor': embed_color_(1193046), 'author-id': YOUR_ID, 'vk-api-token': 'VK_API_TOKEN', 'bot_avatar_url': 'BOT_AVATAR_URL', 'youtube_apikey': 'YOUTUBE_DATA_API_KEY', 'weather_token': 'OPENWEATHERMAP_TOKEN'}
''' *** * *** ''' n = int(input()) while n: n=n-1 num = int(input()) if num<38 or (num%5)<3: print(num) else: print(num+(5-(num%5)))
""" *** * *** """ n = int(input()) while n: n = n - 1 num = int(input()) if num < 38 or num % 5 < 3: print(num) else: print(num + (5 - num % 5))
class GlocalMerchantRequest: def __init__(self, xgl_token_external, payload): self.xgl_token_external = xgl_token_external self.payload = payload def get_payload(self): return self.payload def get_xgl_token_external(self): return self.xgl_token_external def set_xgl_tok...
class Glocalmerchantrequest: def __init__(self, xgl_token_external, payload): self.xgl_token_external = xgl_token_external self.payload = payload def get_payload(self): return self.payload def get_xgl_token_external(self): return self.xgl_token_external def set_xgl_to...
DEFAULT_SPECIAL_TOKEN_BOXES = { "[UNK]": [0, 0, 0, 0], "[PAD]": [0, 0, 0, 0], "[CLS]": [0, 0, 0, 0], "[MASK]": [0, 0, 0, 0], "[SEP]": [1000, 1000, 1000, 1000], } MAX_LINE_PER_PAGE = 200 MAX_TOKENS_PER_LINE = 25 MAX_BLOCK_PER_PAGE = 40 MAX_TOKENS_PER_BLOCK = 100 MAX_2D_POSITION_EMBEDDINGS = 1024
default_special_token_boxes = {'[UNK]': [0, 0, 0, 0], '[PAD]': [0, 0, 0, 0], '[CLS]': [0, 0, 0, 0], '[MASK]': [0, 0, 0, 0], '[SEP]': [1000, 1000, 1000, 1000]} max_line_per_page = 200 max_tokens_per_line = 25 max_block_per_page = 40 max_tokens_per_block = 100 max_2_d_position_embeddings = 1024
#!/usr/bin/env python3 numbers = [42, 9001] letters = "ace" try: print(numbers + letters) except TypeError as err: print(err) # can only concatenate list (not "str") to list words = ["ace", "in", "hole"] print(numbers + words) # [42, 9001, 'ace', 'in', 'hole']
numbers = [42, 9001] letters = 'ace' try: print(numbers + letters) except TypeError as err: print(err) words = ['ace', 'in', 'hole'] print(numbers + words)
once = 0 res = (0,0) def calc(): global once, res if once > 0: return with open("../stream/input15.txt", "r") as file: data = [int(y) for y in [x.strip() for x in file.read().splitlines()][0].split(',')] occurences = {data[i-1]:[i] for i in range(1, len(data)+1)} current = ...
once = 0 res = (0, 0) def calc(): global once, res if once > 0: return with open('../stream/input15.txt', 'r') as file: data = [int(y) for y in [x.strip() for x in file.read().splitlines()][0].split(',')] occurences = {data[i - 1]: [i] for i in range(1, len(data) + 1)} curre...
n = int(input()) for i in range(n): c=input() lst=list(c) l=len(c) c2=[] for i2 in range(l): if(lst[i2]=='4'): lst[i2]='3' c2.append('1') else: c2.append('0') print("".join(lst)+" "+"".join(c2))
n = int(input()) for i in range(n): c = input() lst = list(c) l = len(c) c2 = [] for i2 in range(l): if lst[i2] == '4': lst[i2] = '3' c2.append('1') else: c2.append('0') print(''.join(lst) + ' ' + ''.join(c2))
def crf_pos_features(sent, i): word = sent[i][0] postag = sent[i][1] features = [ 'bias', 'word=' + word, #current word 'word[-4:]=' + word[-4:], #last 4 characters 'word[-3:]=' + word[-3:], #last 3 characters 'word...
def crf_pos_features(sent, i): word = sent[i][0] postag = sent[i][1] features = ['bias', 'word=' + word, 'word[-4:]=' + word[-4:], 'word[-3:]=' + word[-3:], 'word[-2:]=' + word[-2:], 'word.isdigit=%s' % word.isdigit()] if len(word) > 3: features.extend(['word.short=False']) if len(word) < 3:...
nop = b'\x00\x00' brk = b'\x00\xA0' lda = b'\x6A\x02' # Load 0x02 into register VA ldb = b'\x6D\xDD' # Load 0xDD into register VD ldx = b'\x8D\xA0' # Load register VA into VD with open("ldvxvytest.bin", 'wb') as f: f.write(lda) # 0x0200 <-- Load the byte 0x02 into register VA f.write(ldb) # 0x0202 <-- ...
nop = b'\x00\x00' brk = b'\x00\xa0' lda = b'j\x02' ldb = b'm\xdd' ldx = b'\x8d\xa0' with open('ldvxvytest.bin', 'wb') as f: f.write(lda) f.write(ldb) f.write(ldx) f.write(brk)
#!/usr/bin/env python2 # # Copyright 2020 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. BUNDLE_BUCKET = '${BUNDLE_BUCKET}' NOREPLY_EMAIL = '${NOREPLY_EMAIL}' FAILURE_EMAIL = '${FAILURE_EMAIL}'
bundle_bucket = '${BUNDLE_BUCKET}' noreply_email = '${NOREPLY_EMAIL}' failure_email = '${FAILURE_EMAIL}'
# Push Bullet API Token Here # https://www.pushbullet.com/#settings/account login = { 'pushbullet_api_token' : 'ITSASECRET', 'hassio_password' : 'ITSASECRET' }
login = {'pushbullet_api_token': 'ITSASECRET', 'hassio_password': 'ITSASECRET'}
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 load("@rules_rust//rust:repositories.bzl", "rules_rust_dependencies", "rust_register_toolchains", "rust_repository_set") load("//third_party/rust/crates:crates.bzl", "raze_...
load('@rules_rust//rust:repositories.bzl', 'rules_rust_dependencies', 'rust_register_toolchains', 'rust_repository_set') load('//third_party/rust/crates:crates.bzl', 'raze_fetch_remote_crates') load('@rules_rust//tools/rust_analyzer/raze:crates.bzl', 'rules_rust_tools_rust_analyzer_fetch_remote_crates') load('@safe_ftd...
'''__init__.py''' __version__ = '21.40.2dev' version = '21w40b-dev'
"""__init__.py""" __version__ = '21.40.2dev' version = '21w40b-dev'
# 9.23 def find_happy_number(num): # TODO: Write your code here fastSum, slowSum = num, num while True: # currSum = sumOfSqaures(fastSum) # nextSum = sumOfSqaures(fastSum) # if currSum == 1 or nextSum == 1: # return True fastSum = sumOfSqaures(sumOfSqaures(fastSum)) slowSum = sumOfSqaur...
def find_happy_number(num): (fast_sum, slow_sum) = (num, num) while True: fast_sum = sum_of_sqaures(sum_of_sqaures(fastSum)) slow_sum = sum_of_sqaures(slowSum) if fastSum == slowSum: break return slowSum == 1 def sum_of_sqaures(number): store_sum = 0 while number...
INFURA_PROJECT_ID = 'FILL_YOUR_KEY' # Networks # Rinkeby NETWORK = 'rinkeby' PRIVATE_KEY = 'FILL_YOUR_PRIVATE_KEY' # ETH mainnet # NETWORK = 'mainnet' PRIVATE_KEY = 'FILL_YOUR_PRIVATE_KEY'
infura_project_id = 'FILL_YOUR_KEY' network = 'rinkeby' private_key = 'FILL_YOUR_PRIVATE_KEY' private_key = 'FILL_YOUR_PRIVATE_KEY'
class UnchainedException(Exception): def __init__(self): super(UnchainedException, self).__init__(self.message) class DoesntExist(UnchainedException): message = "Attempting to get data by a key that doesn't exist"
class Unchainedexception(Exception): def __init__(self): super(UnchainedException, self).__init__(self.message) class Doesntexist(UnchainedException): message = "Attempting to get data by a key that doesn't exist"
MODELS = [ 'ConvLSTM', 'ConvLSTM_REF', 'LSTM' ] DATASETS = [ 'GeneratedSins', 'GeneratedNoise', 'Stocks', 'MovingMNIST', 'KTH', 'BAIR' ] KTH_CLASSES = [ 'boxing', 'handclapping', 'handwaving', 'jogging', 'running', 'walking' ] OPTS = { 'model': { ...
models = ['ConvLSTM', 'ConvLSTM_REF', 'LSTM'] datasets = ['GeneratedSins', 'GeneratedNoise', 'Stocks', 'MovingMNIST', 'KTH', 'BAIR'] kth_classes = ['boxing', 'handclapping', 'handwaving', 'jogging', 'running', 'walking'] opts = {'model': {'description': 'Model architecture'}, 'dataset': {'description': 'Dataset'}, 'dev...
# -*- coding: utf-8 -*- # http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address REGEX_IPADDR = "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])" REGEX_HOSTNAME = "(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-...
regex_ipaddr = '(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])' regex_hostname = '(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])' regex_jid = '([0-9]{20})'
'''https://leetcode.com/problems/generate-parentheses/''' #iterative solution class Solution: def generateParenthesis(self, n: int) -> List[str]: res = [] stack = [("(", 1, 0)] while stack: x, l, r = stack.pop() if r>l or l>n or r>n: continue ...
"""https://leetcode.com/problems/generate-parentheses/""" class Solution: def generate_parenthesis(self, n: int) -> List[str]: res = [] stack = [('(', 1, 0)] while stack: (x, l, r) = stack.pop() if r > l or l > n or r > n: continue if l =...
def bumpVersion(file_loc, which="patch", dry_run = False, all_matching_lines = False, write_loc = None): if which not in ["major", "minor", "patch"]: print(f"Argument must be one of major, minor, or patch, instead was {which}") raise ValueError(which) with open(file_loc, "r") as f: lines = [] lines...
def bump_version(file_loc, which='patch', dry_run=False, all_matching_lines=False, write_loc=None): if which not in ['major', 'minor', 'patch']: print(f'Argument must be one of major, minor, or patch, instead was {which}') raise value_error(which) with open(file_loc, 'r') as f: lines = [...
''' Python program to find the number of zeros at the end of a factorial of a given positive number ''' def factendzero (n): factorial = 1 x = n // 5 y = x if n < 0: print("Sorry, factorial does not exist for negative numbers") elif n == 0: print("The factorial of 0 is 1") else: ...
""" Python program to find the number of zeros at the end of a factorial of a given positive number """ def factendzero(n): factorial = 1 x = n // 5 y = x if n < 0: print('Sorry, factorial does not exist for negative numbers') elif n == 0: print('The factorial of 0 is 1') else: ...
class ReplayBuffer(object): pass
class Replaybuffer(object): pass
# Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
def all_tests(tests, deps, tags=[], shard_count=1, data=[]): for file in tests: relative_target = file[:-5] suffix = relative_target.replace('/', '.') pos = native.package_name().rfind('javatests/') + len('javatests/') test_class = native.package_name()[pos:].replace('/', '.') + '.' ...
def init_lst(): return [i for i in range(0, 256)] class KnotTier: def __init__(self): self.pos = 0 self.skip = 0 def tie_a_knot(self, start, length, lst): if length < 2: return end = (start + length - 1) % len(lst) lst[start], lst[end] = lst[end], lst[s...
def init_lst(): return [i for i in range(0, 256)] class Knottier: def __init__(self): self.pos = 0 self.skip = 0 def tie_a_knot(self, start, length, lst): if length < 2: return end = (start + length - 1) % len(lst) (lst[start], lst[end]) = (lst[end], ls...
# # PySNMP MIB module TPT-ATA-REG-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPT-ATA-REG-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:26:14 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_union, value_size_constraint, single_value_constraint, constraints_intersection) ...
#!/usr/bin/python3 def test_ternery1(evmtester, branch_results): evmtester.terneryBranches(1, True, False, False, False) results = branch_results() assert [2582, 2583] in results[True] assert [2610, 2611] in results[False] evmtester.terneryBranches(1, False, False, False, False) results = bra...
def test_ternery1(evmtester, branch_results): evmtester.terneryBranches(1, True, False, False, False) results = branch_results() assert [2582, 2583] in results[True] assert [2610, 2611] in results[False] evmtester.terneryBranches(1, False, False, False, False) results = branch_results() asse...
class Solution: def letterCombinations(self, digits: str) -> List[str]: answer = [] keypad = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'] def helper(prefix, idx): # reached end of this current backtrack and isn't just '' ...
class Solution: def letter_combinations(self, digits: str) -> List[str]: answer = [] keypad = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'] def helper(prefix, idx): if idx == len(digits): if prefix != '': answer.append(pr...
def parse_page_obj(raw_obj): return { "wiki_db": raw_obj['wiki_db'], "event_entity": raw_obj['event_entity'], "event_type": raw_obj['event_type'], "event_timestamp": raw_obj['event_timestamp'], "event_comment": raw_obj['event_comment'], "event_user": { "i...
def parse_page_obj(raw_obj): return {'wiki_db': raw_obj['wiki_db'], 'event_entity': raw_obj['event_entity'], 'event_type': raw_obj['event_type'], 'event_timestamp': raw_obj['event_timestamp'], 'event_comment': raw_obj['event_comment'], 'event_user': {'id': raw_obj['event_user_id'], 'text_historical': raw_obj['event...
while True: try: user_input = int(input("Please enter a integer between 0 to 1000: ")) except: print("Please enter a numeric value") continue if user_input < 1: print("Please enter a positive integer") continue break if (user_input % 2) == 0: print("Th...
while True: try: user_input = int(input('Please enter a integer between 0 to 1000: ')) except: print('Please enter a numeric value') continue if user_input < 1: print('Please enter a positive integer') continue break if user_input % 2 == 0: print("That's an ev...
run = [''' <PhysicsModeling>: name: "physicsmodel" # canvas.before: # Color: # rgb: .2, .2, .2 # Rectangle: # size: self.size # source: '/background.png' # this below is variables in the .py file being assigned to the id's # below in the .kv file here to al...
run = ['\n<PhysicsModeling>:\n name: "physicsmodel"\n# canvas.before:\n# Color:\n# rgb: .2, .2, .2\n# Rectangle:\n# size: self.size\n# source: \'/background.png\'\n\n # this below is variables in the .py file being assigned to the id\'s\n # below in the .kv fil...
# The following function returns by recursion the length L of the longest palindromic substring of a given string s def lps(s): n = len(s) # basic cases: L = 0 if s is an empty substring, L = 1 if s has only one character if n == 0 or n == 1: L = n # the recursion goes a...
def lps(s): n = len(s) if n == 0 or n == 1: l = n elif s[0] == s[-1]: return 2 + lps(s[1:-1]) else: return max(lps(s[:-1]), lps(s[1:])) return L
#!/usr/bin/python def displayPathtoPrincess(n, grid): # print all the moves here counter = 1 for row in grid: if 'p' in row: px = row.index('p') + 1 py = n - counter + 1 if 'm' in row: mx = row.index('m') + 1 my = n - counter + 1 count...
def display_pathto_princess(n, grid): counter = 1 for row in grid: if 'p' in row: px = row.index('p') + 1 py = n - counter + 1 if 'm' in row: mx = row.index('m') + 1 my = n - counter + 1 counter += 1 dx = px - mx dy = py - my if...
def profile_update(request): user = request.user if request.method == 'POST': form = UpdateProfile( request.POST, request.FILES or None, instance=request.user,) if form.is_valid(): username = form.cleaned_data.get('username') obj = form.save(commit=False) ...
def profile_update(request): user = request.user if request.method == 'POST': form = update_profile(request.POST, request.FILES or None, instance=request.user) if form.is_valid(): username = form.cleaned_data.get('username') obj = form.save(commit=False) print...
try: error= open("dummy.txt","r") print(error.read())# perform file operations finally: error.close()
try: error = open('dummy.txt', 'r') print(error.read()) finally: error.close()
__author__ = 'Sushant' class ClusterIndices(object): @staticmethod def calculate_EI_index(graph, cluster_nodes, standardize=True): all_edges = graph.get_edges() external_connections_strength = 0.0 internal_connections_strength = 0.0 internal_nodes = len(cluster_nodes) e...
__author__ = 'Sushant' class Clusterindices(object): @staticmethod def calculate_ei_index(graph, cluster_nodes, standardize=True): all_edges = graph.get_edges() external_connections_strength = 0.0 internal_connections_strength = 0.0 internal_nodes = len(cluster_nodes) e...
num = int(input('Enter a number: ')) x = 0 y = 1 # 0 1 1 2 3 5 7 z = x + y for i in range(num): print(z) x = y y = z z = x + y
num = int(input('Enter a number: ')) x = 0 y = 1 z = x + y for i in range(num): print(z) x = y y = z z = x + y
# This is an input class. Do not edit. class BinaryTree: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right # Solution # O(n) time / O(h) space # n - number of nodes in the binary tree # h - height of the binary tree class TreeInfo: ...
class Binarytree: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right class Treeinfo: def __init__(self, isBalanced, height): self.isBalanced = isBalanced self.height = height def height_balanced_binary_tree(tree): ...
''' 33. Search in Rotated Sorted Array Medium Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no du...
""" 33. Search in Rotated Sorted Array Medium Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no du...
load("@wix_oss_infra//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external") def dependencies(): import_external( name = "com_fasterxml_jackson_core_jackson_annotations", artifact = "com.fasterxml.jackson.core:jackson-annotations:2.9.0", artifact_sha256 = "45d32ac...
load('@wix_oss_infra//:import_external.bzl', import_external='safe_wix_scala_maven_import_external') def dependencies(): import_external(name='com_fasterxml_jackson_core_jackson_annotations', artifact='com.fasterxml.jackson.core:jackson-annotations:2.9.0', artifact_sha256='45d32ac61ef8a744b464c54c2b3414be571016dd4...
uni_cars = set() while True: command = input() if command == 'END': break else: direction, plate = command.split(', ') if direction == 'IN': uni_cars.add(plate) elif direction == 'OUT': if plate in uni_cars: uni_cars.remove(p...
uni_cars = set() while True: command = input() if command == 'END': break else: (direction, plate) = command.split(', ') if direction == 'IN': uni_cars.add(plate) elif direction == 'OUT': if plate in uni_cars: uni_cars.remove(plate) if ...
#!/usr/bin/env python # -*- coding: utf-8 -*- spinMultiplicity = 2 opticalIsomers = 1 energy = { 'CCSD(T)-F12/cc-pVTZ-F12': MolproLog('TS8c_f12.out'), #'CCSD(T)-F12/cc-pVTZ-F12': -382.9338341073141 } frequencies = GaussianLog('TSfreq.log') rotors = [HinderedRotor(scanLog=ScanLog('scan_0.log'), ...
spin_multiplicity = 2 optical_isomers = 1 energy = {'CCSD(T)-F12/cc-pVTZ-F12': molpro_log('TS8c_f12.out')} frequencies = gaussian_log('TSfreq.log') rotors = [hindered_rotor(scanLog=scan_log('scan_0.log'), pivots=[6, 7], top=[7, 16]), hindered_rotor(scanLog=scan_log('scan_1.log'), pivots=[2, 3], top=[3, 11, 12, 13], sym...
def arrayMode(sequence): count = [] answer = 0 for i in range(10): count.append(0) for i in range(len(sequence)): count[sequence[i] - 1] += 1 if count[sequence[i] - 1] > count[answer]: answer = sequence[i] - 1 return answer+1
def array_mode(sequence): count = [] answer = 0 for i in range(10): count.append(0) for i in range(len(sequence)): count[sequence[i] - 1] += 1 if count[sequence[i] - 1] > count[answer]: answer = sequence[i] - 1 return answer + 1
async def get_params(request): method = request.method if method == 'POST': params = await request.post() elif method == 'GET': params = request.rel_url.query else: raise ValueError("Unsupported HTTP method: %s" % method) return params
async def get_params(request): method = request.method if method == 'POST': params = await request.post() elif method == 'GET': params = request.rel_url.query else: raise value_error('Unsupported HTTP method: %s' % method) return params
def maybeBuildTrap(x, y): hero.moveXY(x, y) if hero.findNearestEnemy(): hero.buildXY("fire-trap", x, y) while True: maybeBuildTrap(20, 34) maybeBuildTrap(38, 20) maybeBuildTrap(68, 34)
def maybe_build_trap(x, y): hero.moveXY(x, y) if hero.findNearestEnemy(): hero.buildXY('fire-trap', x, y) while True: maybe_build_trap(20, 34) maybe_build_trap(38, 20) maybe_build_trap(68, 34)
def binary_search(array, x, low, high): while low < high: mid = low + (high - low)//2 if array[mid] == x: return mid elif array[mid] < x: low = mid + 1 else: high = mid - 1 return -1 array = [12, 15, 17, 24, 56, 89, 90] x = 24 result = bina...
def binary_search(array, x, low, high): while low < high: mid = low + (high - low) // 2 if array[mid] == x: return mid elif array[mid] < x: low = mid + 1 else: high = mid - 1 return -1 array = [12, 15, 17, 24, 56, 89, 90] x = 24 result = binary...
print ("hola word") nome = input('Nome: ') sobrenome = input() email = input () print (nome,"\n Sobrenome:",sobrenome,"\n E-mail:",email)
print('hola word') nome = input('Nome: ') sobrenome = input() email = input() print(nome, '\n Sobrenome:', sobrenome, '\n E-mail:', email)
# coding: utf-8 n = int(input()) d = [int(i) for i in input().split()] s, t = [int(i) for i in input().split()] if s > t: s, t = t, s circu = sum(d) len1 = sum(d[s-1:t-1]) len2 = circu-len1 print(min(len1,len2))
n = int(input()) d = [int(i) for i in input().split()] (s, t) = [int(i) for i in input().split()] if s > t: (s, t) = (t, s) circu = sum(d) len1 = sum(d[s - 1:t - 1]) len2 = circu - len1 print(min(len1, len2))
#makes a smaller dataset for testing n = 20000 with open("tests/data/combined_data_3.txt", "r") as f: lines = f.readlines() print(len(lines)) with open("tests/data/combined_data_3_small.txt", "w") as f: for i in range(n): f.write(lines[i])
n = 20000 with open('tests/data/combined_data_3.txt', 'r') as f: lines = f.readlines() print(len(lines)) with open('tests/data/combined_data_3_small.txt', 'w') as f: for i in range(n): f.write(lines[i])
class WorkflowCommand(object): def __init__(self, command, arguments): self._command = command self._arguments = arguments def encode(self): return {'command': self._command, 'arguments': self._arguments} class SkipPhasesUntilCommand(WorkflowCommand): COMMAND = 'skip_phases_until'...
class Workflowcommand(object): def __init__(self, command, arguments): self._command = command self._arguments = arguments def encode(self): return {'command': self._command, 'arguments': self._arguments} class Skipphasesuntilcommand(WorkflowCommand): command = 'skip_phases_until'...
# # O(n^2) time | O(n) space # brute force class MyClass: def __init__(self, string:str) -> bool: self.string = string def isPalindrome(self): reversedString = "" for i in reversed(range(len(self.string))): reversedString += self.string[i] # creating newString -> increase...
class Myclass: def __init__(self, string: str) -> bool: self.string = string def is_palindrome(self): reversed_string = '' for i in reversed(range(len(self.string))): reversed_string += self.string[i] return self.string == reversedString def main(): string_name...
#1 def RemoveDuplicates(arr: list) -> list: if len(arr) <= 1: return arr else: i = 1 n = len(arr) while i < n : if arr[i] == arr[i-1]: arr.pop(i) n -= 1 continue i += 1 return arr print(RemoveDuplicates([1,1,1,1,1,1,1,1,1,2,3,4,5,5,5,6,6,7,8]))
def remove_duplicates(arr: list) -> list: if len(arr) <= 1: return arr else: i = 1 n = len(arr) while i < n: if arr[i] == arr[i - 1]: arr.pop(i) n -= 1 continue i += 1 return arr print(remove_duplicates([...
def potencia(func): def wrapper(voltaje, resistencia): intensidad = func(voltaje, resistencia) potencia = intensidad*voltaje print(f"La intensidad es {intensidad} A") print(f"La potencia es {potencia} W") return wrapper @potencia def corriente(voltaje, resistencia): return v...
def potencia(func): def wrapper(voltaje, resistencia): intensidad = func(voltaje, resistencia) potencia = intensidad * voltaje print(f'La intensidad es {intensidad} A') print(f'La potencia es {potencia} W') return wrapper @potencia def corriente(voltaje, resistencia): retur...
Pi1 ='10.0.0.1' Pi2 ='10.0.0.2' Pi3 ='10.0.0.3' Pi4 ='10.0.0.4' Pi5 ='10.0.0.5' Pi6 ='10.0.0.6' GW1 ='10.0.0.8' GW2 ='10.0.0.9' R1=[GW1,Pi1] R2=[GW1,Pi4] R3=[Pi1,Pi4] R4=[Pi1,Pi2] R5=[Pi4,Pi5] R6=[Pi2,Pi5] R7=[Pi3,Pi2] R8=[Pi6,Pi5] R9=[Pi3,Pi6] R10=[GW2,Pi3] R11=[GW2,Pi6] N = 10 S1=[R1] S2=[R2] S3=[R3,R9] S4=[R4] S5...
pi1 = '10.0.0.1' pi2 = '10.0.0.2' pi3 = '10.0.0.3' pi4 = '10.0.0.4' pi5 = '10.0.0.5' pi6 = '10.0.0.6' gw1 = '10.0.0.8' gw2 = '10.0.0.9' r1 = [GW1, Pi1] r2 = [GW1, Pi4] r3 = [Pi1, Pi4] r4 = [Pi1, Pi2] r5 = [Pi4, Pi5] r6 = [Pi2, Pi5] r7 = [Pi3, Pi2] r8 = [Pi6, Pi5] r9 = [Pi3, Pi6] r10 = [GW2, Pi3] r11 = [GW2, Pi6] n = 10...
def should_discard_line(l): patterns = ['${PROJECT_NAME}_tests', '${PROJECT_NAME}_cli', '${PROJECT_NAME}_shared', 'CONFIGURATION_DUMMY'] for p in patterns: if p in l: return True return False f = open('botan/CMakeLists.txt', 'r') content = f.read() f.close() f = open('botan/CMakeLists.txt', 'w') for l in co...
def should_discard_line(l): patterns = ['${PROJECT_NAME}_tests', '${PROJECT_NAME}_cli', '${PROJECT_NAME}_shared', 'CONFIGURATION_DUMMY'] for p in patterns: if p in l: return True return False f = open('botan/CMakeLists.txt', 'r') content = f.read() f.close() f = open('botan/CMakeLists.tx...
class Solution: # @param {integer} numRows # @return {integer[][]} def generate(self, numRows): res = [] row = [] for i in range(0,numRows): n = len(row) row =[1]+[row[j-1] + (row[j] if j<n else 0) for j in range(1,n+1)] res.append(row) ret...
class Solution: def generate(self, numRows): res = [] row = [] for i in range(0, numRows): n = len(row) row = [1] + [row[j - 1] + (row[j] if j < n else 0) for j in range(1, n + 1)] res.append(row) return res