content
stringlengths
7
1.05M
def parse_rules(filename): rule_text = open(filename).read().strip().split('\n') return dict([r.split(' bags contain ') for r in rule_text]) rules = parse_rules('input.txt') queue = ['shiny gold'] seen = [] while len(queue): item = queue.pop(0) for key, val in rules.items(): if key not in se...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # metaclass是创建类,所以必须从`type`类型派生: class ListMetaclass(type): def __new__(cls, name, bases, attrs): attrs["add"] = lambda self, value: self.append(value) return type.__new__(cls, name, bases, attrs) # 指示使用ListMetaclass来定制类 class MyList(list, metaclass=...
class UserFacingError(Exception): """An error suitable for presenting to the user. The message of a UserFacingError must be appropriate for displaying to the end user, e.g. it should not reference class or method names. An example of a UserFacingError is a setting value that has the wrong type. ...
class RuntimeProtocol (object): def __init__ (self, transport): self.transport = transport def send (self, topic, payload, context): self.transport.send('runtime', topic, payload, context) def receive (self, topic, payload, context): if topic == 'getruntime': return self.getRuntim...
# -*- encoding: utf-8 -*- SUCCESS = (0, "Success") ERR_PARAM_ERROR = (40000, "Params error") ERR_AUTH_ERROR = (40001, "Unauthorized") ERR_PERMISSION_ERROR = (40003, "Forbidden") ERR_NOT_FOUND_ERROR = (40004, "Not Found") ERR_METHOD_NOT_ALLOWED = (40005, "Method Not Allowed") ERR_TOKEN_CHANGED_ERROR = (40006, "Token h...
# Ex. 099 += def maior(nums): # nums é uma lista print(f"Foi(ram) digitado(s) {len(nums)} número(s)") if len(nums) > 0: print(f" -> {nums}") print(f"O maior valor é {max(nums)}") else: print("Não há um maior valor") valores = [] while True: resp = str(input("Deseja continu...
""" Module: 'uzlib' on esp32 1.9.4 """ # MCU: (sysname='esp32', nodename='esp32', release='1.9.4', version='v1.9.4 on 2018-05-11', machine='ESP32 module with ESP32') # Stubber: 1.2.0 class DecompIO: '' def read(): pass def readinto(): pass def readline(): pass def decompress(...
#!/usr/bin/env python3 class Args : # dataset size... Use positive number to sample subset of the full dataset. dataset_sz = -1 # Archive outputs of training here for animating later. anim_dir = "anim" # images size we will work on. (sz, sz, 3) sz = 64 # alpha, used by leaky relu of ...
class QualityError(Exception): pass
# Rename this file as settings.py and set the client ID and secrets values # according to the values from https://code.google.com/apis/console/ # Client IDs, secrets, user-agents and host-messages are indexed by host name, # to allow the application to be run on different hosts, (e.g., test and production), # withou...
#----------------------------------------------------------------------------- # Copyright (c) 2013, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this softwa...
pkgname = "base-cross" pkgver = "0.1" pkgrel = 0 build_style = "meta" depends = ["clang-rt-cross", "musl-cross", "libcxx-cross"] pkgdesc = "Base metapackage for cross-compiling" maintainer = "q66 <q66@chimera-linux.org>" license = "custom:meta" url = "https://chimera-linux.org" options = ["!cross", "brokenlinks"] _tar...
""" Copyright 2018-present Open Networking Foundation 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 agre...
def isprime(n): nn = n - 1 for i in xrange(2, nn): if n % i == 0: return False return True def primes(n): count = 0 for i in xrange(2, n): if isprime(i): count = count + 1 return count N = 10 * 10000 print(primes(N))
def res_net(prod, usage): net = {res: p for res, p in prod.items()} for res, u in usage.items(): if res in net: net[res] = net[res] - u else: net[res] = -u return net
class Creature: def __init__(self, name, terror_rating): self.name = name self.terror_rating = int(terror_rating) self.item_ls = [] self.times = 1 def take(self, item): self.item_ls.append(item) self.location.item_ls.remove(item) self.terror_rat...
''' 字符串分段组合 描述 获得输入的一个字符串s,以字符减号(-)分割s,将其中首尾两段用加号(+)组合后输出。 s.split(k)以k为标记分割s,产生一个列表。通过该题目,掌握split()方法的使用,注意:k可以是单字符,也可以是字符串。 ''' s = input() ls = s.split("-") print("{}+{}".format(ls[0], ls[-1]))
def genNum(digit, times): result = digit if times>=1 and digit>0 and digit<10: for i in range(1, times): result = result*10+digit return result def sum(digit, num): result = 0 for x in range(1, num+1): result += genNum(digit, x) return result print(sum(1, 3)) def ge...
class DataLoader: pass class DataSaver: pass
# -*- coding: utf-8 -*- ''' File name: code\2x2_positive_integer_matrix\sol_420.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #420 :: 2x2 positive integer matrix # # For more information see: # https://projecteuler.net/problem=420 # Pr...
''' 找出旋转有序数列的中间值 给出一个有序数列随机旋转之后的数列,如原有序数列为:[0,1,2,4,5,6,7] ,旋转之后为[4,5,6,7,0,1,2]。 假定数列中无重复元素,且数列长度为奇数。 求出旋转数列的中间值。如数列[4,5,6,7,0,1,2]的中间值为4。 输入 4,5,6,7,0,1,2 输出 4 输入样例 1 1,2,3 4,5,6,7,0,1,2 12,13,14,5,6,7,8,9,10 输出样例 1 2 4 9 ''' """ @param string line 为单行测试数据 @return string 处理后的结果 """ def solution(line): numList = ...
class Node(object): id = None neighbours=[]#stores the ids of neighbour nodes distance_vector = [] neighbours_distance_vector = {}#stores the distance vector of neighbours def __init__(self, id): self.id = id #Initializing the distance vector and finding the neighbours def distance_from_neighbours(self,matri...
coordinates_80317C = ((155, 185), (155, 187), (155, 189), (156, 186), (156, 188), (156, 190), (157, 186), (157, 188), (157, 189), (157, 191), (158, 187), (158, 189), (158, 190), (158, 193), (159, 188), (159, 190), (159, 191), (159, 194), (159, 195), (159, 196), (160, 188), (160, 190), (160, 191), (160, 192), (160, 19...
# Maple Adjustment Period (57458) | Kanna 2nd Job haku = 9130081 cacophonous = 1142507 sm.removeEscapeButton() sm.setSpeakerID(haku) sm.setBoxChat() sm.sendNext("Finally, your real skills are coming back! I'm tired of doing all the work!") sm.flipBoxChat() sm.flipBoxChatPlayerAsSpeaker() sm.sendNext("What exactly d...
# coding: utf-8 class Solution: """ @param prices: Given an integer array @return: Maximum profit """ def maxProfit(self, prices): # write your code here ret = 0 if prices: max_profit_1, max_profit_2 = 0, 0 min_price, max_price = prices[0], prices[-1]...
"""BLPose Train: Data Utils Author: Bo Lin (@linbo0518) Date: 2021-01-02 """ """BLPose Data Format: type: List[List[int]] shape: (n_keypoints, 3) format: [[x1, y1, v1], [x2, y2, v2], ... [xk, yk, vk]] x: the x coordinate of the keypoint, dtype: int y: the y coordinate of the keypoint, dtype...
# -*- coding: utf-8 -*- ''' File name: code\problem_500\sol_500.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #500 :: Problem 500!!! # # For more information see: # https://projecteuler.net/problem=500 # Problem Statement ''' The numb...
''' 03 - barplots, pointplots and countplots The final group of categorical plots are barplots, pointplots and countplot which create statistical summaries of the data. The plots follow a similar API as the other plots and allow further customization for the specific problem at hand ''' # 1 - Countplots # Cr...
# Page Definitions # See Page Format.txt for instructions and examples on how to modify your display settings PAGES_Play = { 'name':"Play", 'pages': [ { 'name':"Album_Artist_Title", 'duration':20, 'hidewhenempty':'all', 'hidewhenemptyvars': [ "album", "artist", "title" ], ...
def test_presign_S3(_admin_client): patientID = "PH0001" payload = { "prefix": patientID, "filename": patientID + "_" + "a_file.vcf", "contentType": "multipart/form-data", } resp = _admin_client.post("/preSignS3URL", json=payload, content_type="application/json") assert resp....
# # PySNMP MIB module TIMETRA-SAS-PORT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIMETRA-SAS-PORT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:14:36 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
# https://edabit.com/challenge/jwzgYjymYK7Gmro93 # Create a function that returns the indices of all occurrences of an item in the list. def get_indices(user_list: list, item: str or int) -> list: current_indice = 0 occurence_list = [] while len(user_list): if user_list[0] == item: ...
class Rectangulo: def __init__(self, base, altura): self.base = base self.altura = altura class CalculadorArea: def __init__(self, figuras): assert isinstance(figuras, list), "`shapes` should be of type `list`." self.figuras = figuras def suma_areas(self): total ...
class Error(Exception): """Base class for simphony errors.""" pass class DuplicateModelError(Error): def __init__(self, component_type): """Error for a duplicate component type. Parameters ---------- component_type : UniqueModelName The object containing the na...
load("//az/private:rules/config.bzl", _config = "config") load("//az/private:rules/datafactory/main.bzl", _datafactory = "datafactory") load("//az/private:rules/storage/main.bzl", _storage = "storage") az_config = _config az_datafactory = _datafactory az_storage = _storage
# -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. class TypeFileSearchResultEnum(object): """Implementation of the 'Type_FileSearchResult' enum. Specifies the type of the file document such as KDirectory, kFile, etc. Attributes: KDIRECTORY: TODO: type description here. KFILE: TODO: ...
num_1 = 1 num_2 = 2 num = 276 min = 3600 for a in range(1, 21): for b in range(2, 11): min_ = abs(a * (b - 1) * 20 - num) if min_ == 0: num_1 = a num_2 = b break if min_ < min: min = min_ num_1 = a num_2 = b else: ...
# -*- coding: utf8 -*- # Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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...
# ABOUT : This program deals with the accumulation pattern # used with the help of dictionary # Here in this program we will find minimum value associated with the # key : character in the string # initialize a string words = "Welcome back. Take a look in your calendar and mark this date. Today is the day yo...
""" 1. Write a function that accepts two integers num1 and num2. The function should divide num1 by num2 and return the quotient and remainder. The output can be rounded to 2 decimal places. """ def quot_rem(num1,num2): q = round((num1 / num2), 2) r = round((num1 % num2), 2) return (q,r)
list_of_urls = [ "www.cnn.com", "www.bbc.co.uk", "nytimes.com", "ipv6.google.com" # ,"site2.example.com" ]
""" Version of Petronia. This file will become auto-generated. """ PROGRAM = 'Petronia' NAME = 'Petronia, The Cross-Platform Window Manager' VERSION = '3.0.0 alpha-1'
# -*- coding: utf-8 -*- """ Created on Wed Jul 15 11:35:30 2020 @author: Castellano """ def ExploreIsland(t1=int,m=int,n=int, neighbors=[]): coordinates = T[t1] candidates = [] if neighbors == []: neighbors.append(t1) row_candidates = [(coordinates[0],coordinates[1]-1),...
''' @author: Kittl ''' def exportLineTypes(dpf, exportProfile, tables, colHeads): # Get the index in the list of worksheets if exportProfile is 2: cmpStr = "LineType" elif exportProfile is 3: cmpStr = "" idxWs = [idx for idx,val in enumerate(tables[exportProfile-1]) if val == cm...
class cached_property(object): # noqa # From the excellent Bottle (c) Marcel Hellkamp # https://github.com/bottlepy/bottle # MIT licensed """ A property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the attribute resets the propert...
#set midpoint midpoint = 5 # make 2 empty lists lower = []; upper = [] #to terminate a line to put two statements on a single line #split the numbers into the lists based on conditional logic for i in range(10): if (i < midpoint): lower.append(i) else: upper.append(i) print("Lower values are:...
# Copyright 2012 Google Inc. All rights reserved. # -*- coding: utf-8 -*- """ Nicely formatted cipher suite definitions for TLS A list of cipher suites in the form of CipherSuite objects. These are supposed to be immutable; don't mess with them. """ class CipherSuite(object): """ Encapsulates a cipher suite....
# Time: O(n^2) # Space: O(n^2) # We are playing the Guess Game. The game is as follows: # # I pick a number from 1 to n. You have to guess which number I picked. # # Every time you guess wrong, I'll tell you whether the number I picked is higher or lower. # # However, when you guess a particular number x, and you gue...
def handle(argv): prop = properties() command_map = ('compile', 'test' , 'help') argv = argv[1:] if len(argv) == 0: raise Exception('scalu must be provided with a command to run: compile, test, help, etc') if argv[0] in command_map: prop.mode = argv[0] else: bad_arg(arg) return prop def bad_arg(arg): rai...
#https://leetcode.com/problems/maximum-subarray/ """ [0] if we know the max value of the subarray that ends at i index is Mi what is the max value of the subarray that ends at i+1 index? its either nums[i+1] or nums[i+1]+Mi so code below, maxCurrent[i] stores the max value of subarray that ends at i [1] the max value ...
#Oskar Svedlund / Oliver Stafferöd #TEINF-20 #2021-10-05 #Frankenstein spelet #Monsters tale! Murder_instinkt = False Frankenstain = True key = False x = 1 input(""" Greetings player, please pay attention to this text as it explains how to play. this game is a text only game where you play as frankenstein's mon...
tempo = int(input('\nQuantos anos tem seu carro? ')) if tempo <= 3: print('Seu carro é novo!') else: print('Seu carro é velho!') print('-'*30) #condição simplificada tempo = int(input('Quantos anos você tem? ')) print('Você está novo' if tempo <= 40 else 'Você está velho') print ('-'*30) nota1 = float(input('...
""" Performance of DFT calculation is better when array size = power of 2 arrays whose size is product of 2, 3, and 5 also quite efficient for performance: ue zero padding OpenCV - manually pad 0s Numpy - specify new size of FFT calculation, automatically pads 0s """ # to calculate optimal size: use OpenCV func...
A = 26 MASKS = (A + 1) * 4 MOD = 10**9 + 7 def solve(): m = int(input()) parts = [input() for _ in range(m)] s = "".join(parts) s = [ord(c) - ord('a') for c in s] n = len(s) edge = [True] + [False] * n i = 0 for w in parts: i += len(w) edge[i] = True a = [[[0] * MASKS for i in range(n + 1)] for j in range...
""" RetinaNet介绍: 1、是由一个主干网和两个任务子网络组成的简单同一网络。主干网使用卷积神经网络负责从整个图片提取特征, 将主干网络提取到的特征送入两个子网络: 第一个子网络使用卷积分类,第二个子网络使用卷积来边框回归。 2、分类子网络和边框回归子网络共享结构,参数独立。 3、子网络是附加在FPN的每一层的一个小的FCN;参数共享。 对于给定的金字塔层级输出的C个通道的Feature Map,子网络使用4个3×3的卷积层,每层的通道数任然是C,接着是一个ReLU激活层; 然后跟一个通道数位KA(K是类别数,A是anchor数)的3×3的卷积...
src = Glob('*.c') component = aos_component('libkm', src) component.add_global_includes('include') component.add_component_dependencis('security/plat_gen', 'security/alicrypto') component.add_prebuilt_lib('lib/' + component.get_global_arch() + '/libkm.a')
class Algo(object) : def __init__(self) : self.n_clusters = None def run(self, matrix) : """ Abstract method to be redefine on each childs """ raise NotImplemented()
myemp = { 'Name': 'Steve', 'Age':58, 'Sex': 'Male'} print(myemp)# K1 print(myemp.keys())# K2 myrem = myemp.popitem() print(myrem, 'is removed')# K3 print(myemp.keys())# K4 print(list(myemp.keys()))# K5 for key in myemp.keys(): # K6 print(key)
''' Created on 10 Feb 2016 @author: BenShelly ''' class RacecardConsoleView(object): ''' classdocs ''' def __init__(self): ''' Constructor ''' def printRacecard(self, horseOddsArray): for horseOdds in horseOddsArray: print(h...
with open('./inputs/22.txt') as f: instructions = f.readlines() def solve(part): def logic(status, part): nonlocal infected, direction if part == 1: if status == 0: infected += 1 direction *= (1 - 2*status) * 1j else: if status == 1: ...
def f(x, l=[]): for i in range(x): l.append(i * i) print(l) f(2) f(3, [3, 2, 1]) f(3)
''' This is a docstring This code subtracts 2 numbers ''' a = 3 b = 5 c = b-a print(c)
load( "//:deps.bzl", "com_github_grpc_grpc", "com_google_protobuf", "io_bazel_rules_python", "six", ) def python_proto_compile(**kwargs): com_google_protobuf(**kwargs) def python_grpc_compile(**kwargs): python_proto_compile(**kwargs) com_github_grpc_grpc(**kwargs) io_bazel_rules_py...
class Node: """Node for singly-linked list.""" def __init__(self, data): self.data = data self.next = None def __str__(self): return str(self.data) class LinkedList: """Singly-linked list with tail.""" def __init__(self, nodes=None): # nodes is a list. must learn type h...
# Time: O(n) # Space: O(h) # 337 # The thief has found himself a new place for his thievery again. # There is only one entrance to this area, called the "root." # Besides the root, each house has one and only one parent house. # After a tour, the smart thief realized that "all houses in this # place forms a binary tr...
{ "targets":[ { "target_name": "hcaptha", "conditions": [ ["OS==\"mac\"", { "sources": [ "addon/hcaptha.cc" ,"addon/cap.cc"], "libraries": [], "cflags_cc": ["-fex...
# -*- coding: utf-8 -*- class A(object): def __init__(self, parameter): self.test = parameter def set_to_None(parameter): print(parameter) parameter = None print(parameter) print('----传递list---------') l = [1, 2, 3] a = A(l) print(a.test) l.append(4) print(a.test) a.test.append(5) print(a....
class TTBusDeviceAddress: def __init__(self, address, node): self.address = address self.node = node @property def id(self): return f"{self.address:02X}_{self.node:02X}" @property def as_tuple(self): return self.address, self.node def __str__(self): ret...
def pos_to_line_col(source, pos): offset = 0 line = 0 for line in source.splitlines(): _offset = offset line += 1 offset += len(line) + 1 if offset > pos: return line, pos - _offset + 1
load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies", "go_repository") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies") def rules_helm_go_dependencies(): """Pull in external Go packages needed by Go binarie...
def validate_json(json): required_fields = ['Name', 'DateOfPublication', 'Type', 'Author', 'Description'] missing_fields = [] for key in required_fields: if key not in json.keys(): missing_fields.append(key) elif json[key] == "": missing_fields.append(key) if le...
ans=[] #create a new node class Node: def __init__(self, data): self.data = data self.left = None self.right = None #top of stack def peek(s): if len(s) > 0: return s[-1] return None def postOrderTraversal(root): # if tree is empty if root is None:...
{ "variables": { "os_linux_compiler%": "gcc", "build_v8_with_gn": "false" }, "targets": [ { "target_name": "cbor-extract", "win_delay_load_hook": "false", "sources": [ "src/extract.cpp", ], "include_dirs": [ "<!(node -e \"require('nan')\")", ], ...
""" Extension classes enhance TouchDesigner component networks with python functionality. An extension can be accessed via ext.ExtensionClassName from any operator within the extended component. If the extension is "promoted", all its attributes with capitalized names can be accessed directly through the extended ...
__author__ = 'Ralph' # import app # import canvas # import widgets
class TextWrapper(object): def __init__(self): self._wrap_chars = " " self.unwrapped = "" self.cursor_loc = [0, 0] self.prev_line_break = 0 self.rows = [] def add_line(self, end): new_line = self.unwrapped[self.prev_line_break:end].replace("\n", " ") self...
with open("input.txt", 'r') as file: file = file.read() file = file.split("\n") file = file[:-1] file = [int(i) for i in file] frequency = 0 prev = set() prev.add(0) stop = True while (stop): for n in file: frequency += n if frequency not in prev: ...
"""Top-level package for gridverse-experiments.""" __author__ = """sammie katt""" __email__ = "sammie.katt@gmail.com" __version__ = "0.1.0"
def twenty_nineteen(): """Come up with the most creative expression that evaluates to 2019, using only numbers and the +, *, and - operators. >>> twenty_nineteen() 2019 """ return 2018+1
def repeatedString(s, n): lss=n%len(s) tfs=int(n/len(s)) cnt=s.count('a') sc=s.count('a',0,lss) tc=(tfs*cnt)+sc return tc
# Helper for formatting time strings def smart_time(t): tstr = 't = ' if t < 2*60.: tstr += '{0:.4f} sec'.format(t) elif t < 90.*60: tstr += '{0:.4f} min'.format(t/60) elif t < 48.*60*60: tstr += '{0:.4f} hrs'.format(t/(60*60)) else: tstr += '{0:.4f} day'.format(t/(2...
# -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. class FileSizePolicyEnum(object): """Implementation of the 'FileSizePolicy' enum. Specifies policy to select a file to migrate based on its size. eg. A file can be selected to migrate if its size is greater than or smaller than the FileSizeBytes....
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. _BASE85_CHARACTERS = ('0123456789' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' ...
print('salut') a = 1 print(a.denominator) # print(a.to_bytes()) class Salut: def __init__(self, truc): self.truc = truc def stuff(self) -> dict: return {'truc': self.truc} s = Salut('bidule') s.truc b = s.stuff() wesh = b.pop('truc') print(wesh.replace('dule', 'de'))
students = { "Ivan": 5.00, "Alex": 3.50, "Maria": 5.50, "Georgy": 5.00, } # Print out the names of the students, which scores > 4.00 names = list(students.keys()) scores = list(students.values()) max_score = max(scores) max_score_index = scores.index(max_score) min_score = min(scores) min_score_index...
#!/usr/bin/env python3 class Event(object): pass class TickEvent(Event): def __init__(self, product, time, sequence, price, bid, ask, spread, side, size): self.type = 'TICK' self.sequence = sequence self.product = product self.time = time self.price = price se...
#!/usr/bin/env python ''' config.py NOTE: I'M INCLUDING THIS FILE IN MY REPOSITORY TO SHOW YOU ITS FORMAT, BUT YOU SHOULD NOT KEEP CONFIG FILES WITH LOGIN CREDENTIALS IN YOUR REPOSITORY. In fact, I generally put a .gitignore file with "config.py" in it in whatever directory is supposed ...
class Facade: pass facade_1 = Facade() facade_1_type = type(facade_1) print(facade_1_type)
#!/usr/bin/env python # -*- coding: utf-8 -*- # # || ____ _ __ # +------+ / __ )(_) /_______________ _____ ___ # | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ # # Copyright (C) 20...
test_cases = int(input().strip()) for t in range(1, test_cases + 1): n, m = tuple(map(int, input().strip().split())) strings = [input().strip() for _ in range(n)] for i in range(n): for j in range(n - m + 1): r_left = j r_right = j + m - 1 c_top = j ...
class Solution: def solve(self, nums, k): dp = [0] ans = 0 for i in range(len(nums)): mx = nums[i] cur_ans = 0 for j in range(i,max(-1,i-k),-1): mx = max(mx, nums[j]) cur_ans = max(cur_ans, mx*(i-j+1) + dp[j]) ...
t = 0 def calc(n): p = 0 for j in range(1, n): if n % j == 0: p += j q = 0 for j in range(1, p): if p % j == 0: q += j if n == q and n != p: return n else: return 0 for i in range(1, 10001): t += calc(i) print (t)
# @author Huaze Shen # @date 2020-01-15 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def max_depth(root): if root is None: return 0 return max(max_depth(root.left), max_depth(root.right)) + 1 if __name__ == '__main__': root_...
# coding: utf-8 # This file is a part of VK4XMPP transport # © simpleApps, 2014 (16.12.14 14:54PM GMT) — 2015. GLOBAL_USER_SETTINGS["typingreader"] = {"label": "Mark my messages as read when I compose message", "value": 0} def typingreader_watch(msg): jidFrom = msg.getFrom() source = jidFrom.getStripped() if msg.g...
class Solution: def mySqrt(self, x: int) -> int: lo = 0 hi = 2 while hi ** 2 <= x: lo = hi hi *= 2 while hi - lo > 1: mid = (hi + lo) // 2 if mid ** 2 <= x: lo = mid else: hi = mid ret...
""" 1. Clarification 2. Possible solutions - mod - log2 - bit manipulation (2 versions): get the rightmost 1-bit in n: x & (-x) set the rightmost 1-bit to 0-bit in n: x & (x - 1) 3. Coding 4. Tests """ # T=O(lgn), S=O(1) class Solution: def isPowerOfTwo(self, n: int) -> bool: i...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # # @Author: Ingu Kang # # Python 실습 20150824월 # 구구단 한글코드 def 메인함수(): 구구단출력plus() 구구단출력plus(19, 9) # 'A*B=곱셈결과' 스트링 생성 def AxB문자열생성(a, b, 좌항길이맞춤=1, 우항길이맞춤=2): 임시문자열 = '{{0:{0}}}*{{1:{0}}}={{2:{1}d}}'.format(좌항길이맞춤, 우항길이맞춤) # 줄맞춤 return 임시문자열.format(a, b...
#!usr/bin/python # -*- coding:utf8 -*- """ you can tell your celery instance to user a configuration module by calling the app.config_from_object() method """ broker_url = 'redis://127.0.0.1:6379/3' result_backend = 'redis://127.0.0.1:6379/0' task_serializer = 'json' result_serializer = 'json'
#encoding=utf-8 # appexceptions.py # This file is part of PSR Registration Shuffler # # Copyright (C) 2008 - Dennis Schulmeister <dennis -at- ncc-1701a.homelinux.net> # # This is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Soft...
# Copyright 2019 Quantapix Authors. 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 required by applicable l...