content
stringlengths
7
1.05M
# https://www.codechef.com/LTIME98C/problems/REDALERT for T in range(int(input())): n,d,h=map(int,input().split()) l,check=list(map(int,input().split())),0 for i in l: if(i==0): if(check<d): check=0 else: check-=d continue check+=i if(check>h): ...
"""Represent models quotes.""" class QuoteModel: """A quote model that houses the body and author.""" def __init__(self, body, author): """Create a new `QuoteModel`. :param body: The body of the quote model :param author: The author of the quote model """ ...
# print("Hello") # print("Hello") i = 0 while i < 5: print("Hello No.", i) i += 1 print("Always happens once loop is finished") print("i is now", i) i = 10 while i > 0: print("Going down the floor:", i) # i could do more stuff i -= 2 print("Whew we are done with this i:", i) i = 20 while True: ...
""" categories: Syntax description: Argument unpacking does not work if the argument being unpacked is the nth or greater argument where n is the number of bits in an MP_SMALL_INT. cause: The implementation uses an MP_SMALL_INT to flag args that need to be unpacked. workaround: Use fewer arguments. """ def example(*a...
# -*- coding: utf-8 -*- class RpcSetPassword: def __init__(self, hashed_password): self.hashed_password = hashed_password def out_rpc_set_password(self, pack): pack.add_value("HashedPassword", self.hashed_password)
class LinkedList: class _Node: def __init__(self, e=None, node_next=None): self.e = e self.next = node_next def __str__(self): return str(self.e) def __repr__(self): return self.__str__() def __init__(self): self._dummy_head = se...
#================================================================ # Runge-Kutta 4th Order Function for Spring Damping # # Author: Bayu R. J. (remove this lol) # Version: 1.0 *initial release # Level: Beginner # Python : IDLE 3.6.3 (use 'new file' to make a whole script) #=========================================...
n = 9 while n>=1: if(n>1): print(str(n) + " bottles of beer on the wall, " + str(n) + " bottles of beer.") n-=1 print("take one down and pass it around, " + str(n) + " bottles of beer on the wall.\n\n") else: print(str(n) + " bottles of beer on the wall, " + str(n) + " bottle of ...
dy_import_module_symbols("testdatalimit_helper") # Send 10MB of data through with a high limit of 3MB. Which means as soon as it sends # 3MB, the shim should block until the time limit (in this case 20 seconds) is up. UPLOAD_LIMIT = 1024 * 1024 * 3 # 3MB DOWNLOAD_LIMIT = 1024 * 1024 * 3 # 3MB TIME_LIMIT = 10 DATA_TO_...
def check_ignition(b_grid, f_grid, h_grid, i_threshold, w_direction, i, j): # TODO implement this function """ returns True if that cell will catch fire at time t + 1 and False otherwise. """ # Only cells that are located within the bounds of the land scape grid # can contribute to a cell'...
class Hand: def __init__(self, stay=False): self.stay = stay self.cards = [] def drawCard(self, deck): self.cards.append(deck.dealCard()) def displayHand(self): return f"{[f'{card.num}{card.face},' for card in self.cards]}" # Corner case to be resol...
class Fee(object): def __init__(self, currency, fastest, slowest): self.currency = currency self.fastest = fastest self.slowest = slowest def __str__(self): return "Fees for %s [Fastest %s] [Slowest %s]" % (self.currency, self.fastest, self.slowest) def __repr__(self): ...
f = open("input.txt",'r') L = [] for item in f: L.append(item.strip()) # Construct arrays of possible keys: creden = ["ecl","eyr","hcl","byr","iyr","pid","hgt"] creden_plus = ["ecl","eyr","hcl","byr","iyr","pid","hgt","cid"] creden.sort() creden_plus.sort() # stores all passports passports = [] # stores key-va...
# Auxiliary def goodness(x,y): xx = x-np.average(x) yy = y-np.average(y) A = np.sqrt(np.inner(xx,xx)) B = np.sqrt(np.inner(yy,yy)) return np.inner(xx/A,yy/B) def argminrnd(items, target): # Returns the argmin item. if there are many, returns one at random. # items and target must be the s...
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # ...
#!/usr/bin/python3 # file: mini_frame.py # Created by Guang at 19-7-19 # description: # *-* coding:utf8 *-* # def application(environ, start_response): # start_response('200 OK', [('Content-Type', 'text/html')]) # return 'Hello World!' # def application(environ, start_response): # start_response('200 O...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # @license # Copyright 2017 Adán Mauri Ungaro <adan.mauri@gmail.com> # # 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...
zahlen = [] with open('AdventOfCode_01_1_Input.txt') as f: for zeile in f: zahlen.append(int(zeile)) print(sum(zahlen))
class SungJukService: sjdb=[] #성적데이터 저장하는 리스트 #[(no,n,k,e,m,t,a,g,r),(no,n,k,e,m,t,a,g,r),(no,n,k,e,m,t,a,g,r)] #성적처리 총점 평균 학점 계산 def computeSungJuk(self, sj): sj.tot = sj.kor + sj.eng + sj.mat sj.avg = sj.tot / 3 grd_list = 'FFFFFDCBAA' var = int(sj.avg / 10) ...
if __name__ == '__main__': a = 2,4 b = 1, c = b d = c # a, b = c, d print(c) print(d) a, b = b, a print(a, b) # Sets contains non duplicate items
class BitDecoder: def encode(self, morse_msg, morse_format, timing): if isinstance(morse_msg, int): morse_msg = bin(morse_msg)[2:] symbol_gap = '0' * timing.intra_char char_gap = '0' * timing.inter_char word_gap = '0' * timing.inter_word words = morse_msg.split...
class Dog: def __init__(self, name, age): self.name = name self.age = age # print(name) # below method will return us the attribute value of the object # getter def get_name(self): return self.name def get_age(self): return self.age # setter # set ...
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Computes the sum and average of n integer numbers (input from the # # ...
library_list = [ 'esoctiostan', 'esohststan', 'esookestan', 'esowdstan', 'esoxshooter', 'ing_oke', 'ing_sto', 'ing_og', 'ing_mas', 'ing_fg', 'irafblackbody', 'irafbstdscal', 'irafctiocal', 'irafctionewcal', 'irafiidscal', 'irafirscal', 'irafoke1990', 'irafredcal', 'irafspec16cal', 'irafspec50cal', '...
class CharacterComponent: def __init__(self, name): self.name=name def equip(self): pass class CharacterConcreteComponent(CharacterComponent): def equip(self): return f'{self.name} equipment:' class Decorator(CharacterComponent): _character: CharacterComponent def __init__(...
# Code on Python 3.7.4 # Working @ Dec, 2020 # david-boo.github.io # Define sequences. Then put two strings together to produce the list of pairs that we wish to compare, and a filter returns just those pairs for which seq1 != seq2 # Taking the length of the filtered list gives us the Hamming distance seq1=...
class Solution: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: x={} f=[] z=[] for i in pieces: x[i[0]]=i l=0 while l<len(arr): if arr[l] in x: f.append(x[arr[l]]) print(f) el...
#!/usr/bin/env python DEF_TASKDB_CONF = {'timeout': 10.0, # seconds 'task_checkout_delay': 1.0, # seconds 'task_checkout_num_tries': 10} class TASK_STATES(object): QUEUED_NO_DEP = 'QUEUED_NO_DEP' RUNNING = 'RUNNING' FAILED = 'FAILED' SUCCEEDED = 'SUCCEEDED' ...
#!/usr/bin/env python3 ####################################################################################### # # # Program purpose: Finds the first appearance of the substring 'not' and 'poor' # # from a...
symbol1 = input() symbol2 = input() def return_characters(symbol1, symbol2): symbol1 = ord(symbol1) symbol2 = ord(symbol2) result = [] for i in range(symbol1 + 1, symbol2): char = chr(i) result.append(char) result = " ".join(result) return result print(return_characters(sy...
class Messages: help = "How can I help you?" hello = "Hello!" welcome = "Welcome {name}! I'm VK-Reminder-Bot." done = "I have set the reminder!" updated = "I have updated the reminder!" missed = "I didn't get that!" get_title = "Please enter Reminder Title:" get_time = "When should I rem...
class Solution: def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]: start = pow(10, (intLength + 1) // 2 - 1) end = pow(10, (intLength + 1) // 2) mul = pow(10, intLength // 2) def reverse(num: int) -> int: res = 0 while num: res = res * 10 + num % 10 ...
def checkMagazine(magazine, note): if len(magazine) < len(note): print("No") # Program would not stop if not return return None note_dict = {} for word in note: if word not in note_dict: note_dict[word] = 1 else: note_dict[word] += ...
#!/usr/bin/env python # definitions of packets that go from the App to Artoo or App to Solo and vice versa. # All packets are of the form (in little endian) # 32-bit type identifier # 32-bit length # n bytes value # https://docs.google.com/a/3drobotics.com/document/d/1rA1zs3T7X1n9ip9YMGZEcLCW6Mx1RR1bNlh9gF0i8nM/edit#h...
tempo_em_segundo = int(input()) horas = tempo_em_segundo//3600 tempo_em_segundo -= horas*3600 minutos = tempo_em_segundo//60 segundos = tempo_em_segundo - minutos*60 print(f"{horas}:{minutos}:{segundos}")
#!/usr/bin/env python def rev(stack): return stack[::-1] def cut(stack, n): return stack[n:] + stack[:n] def incr(stack, n): size = len(stack) new_stack = [-1] * size i = 0 for a in range(size): new_stack[i % size] = stack[a] i += n return new_stack def solve(inp, siz...
def multiply(a, b): """ Takes two values and returns the product :param a: :param b: :return: product """ res = a * b return res def add(a, b, c): """ Takes two values and returns the addition :param c: :param a: :param b: :return: addition ...
words = ["а", "абад", "абадий", "абадийлашмоқ", "абадийлик", "абадия", "абадиян", "абадият", "абадулабад", "абадулобод", "абажур", "абажурли", "абас", "аббат", "аббосий", "аббревиатура", "абгор", "абгорлик", "абдол", "абдолваш", "аберрацион", "аберрация", "абёт", "абжад", "абжадхон", "абжадхнонлик", "абжақ", "абжақламо...
class ParseError(Exception): pass class UnsupportedFile(Exception): pass class MultipleParentsGFF(UnsupportedFile): pass
#Done by Carlos Amaral in 02/07/2020 #Imports def show_messages(text_messages): """Prints the text message in the list.""" print("Showing messages:") for text_message in text_messages: print(text_message) def send_messages(text_messages, sent_messages): """Prints each text message and moves ...
class MissingGraphicSettings(Exception): """Error raised when there is no `graphic_settings` dictionary available. """ def __init__(self, msg: str): """Initializes MissingGraphicSettings with an error message. Parameters ---------- msg : str The error message. ...
class MongoDBConfig: g_server_ip = '127.0.0.1' # mongodb数据库地址 g_server_port = 27017 # 数据库端口 g_db_name = 'socialdb' # 数据库名 ALLOWED_EXTENSIONS = ['txt', 'csv'] # 允许上传的类型 error_line_file = 'E:\Socialdb\backend\test.log' # 错误日志路径
def show_message(unread_books, read_books): """ List all the book to be read. Print the book to be read, move to read_books. """ while unread_books: toread_book = unread_books.pop() print(f"To read books: {toread_book}") read_books.append(toread_book) def send_message(read_...
""" Finding the percentage https://www.hackerrank.com/challenges/finding-the-percentage/problem """ if __name__ == '__main__': n = int(input()) student_marks = {} for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores query...
# m row X n col # Quadrant 1 | Quadrant 2 # ---------------------> # Quadrant 4 | Quadrant 3 # Q1: (x, y) # Q2: (y, m - 1 - x) # Q3: (m - 1 - x, n - 1 - y) # Q4: (n - 1 - y, x) in Q4 # rotate +90 mirror up and down, and switch x and y # rotate -90 mirror left and right, and switch x and y class Solution(object): ...
mariadb = dict( ip_address = 'localhost', port = 3307, user = 'root', password = 'password', db = 'cego', users_table = 'users' ) test = dict( query = 'SELECT id, firstName, lastName, email FROM users', filename = 'Test.txt' )
pessoas = [] qtd = maiorp = menorp = 0 nomesgordos = nomesmagros = [] while True: nome = str(input('Digite um nome:\n')) pessoas.append(nome) peso = int(input('Digite o peso:\n')) pessoas.append(peso) if qtd == 0: maiorp = peso menorp = peso elif peso > maiorp: maiorp = p...
class Graph: def __init__ (self, adj = None): ''' Creates new graph from adjacency list. ''' if adj is None: adj = [] self.adj = adj def GetEdges (self): ''' Returns list of the graph's edges. ''' edges = [] ...
def euler8(): """Solves problem 7 of Project Euler.""" big = "73167176531330624919225119674426574742355349194934" big += "96983520312774506326239578318016984801869478851843" big += "85861560789112949495459501737958331952853208805511" big += "12540698747158523863050715693290963295227443043557" b...
def philosophy(statement): def thought(): return statement return thought question = philosophy('To B, or not to B. It depends where the bomb is.') print(question())
def extractElementalCobalt(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None if item['title'].lower().startswith('arifureta chapter') or 'Arifureta Translation' in item['tags']: return buildRe...
miDiccionario = {"Alemania": "Berlin", "Francia": "Paris", "UK": "Londres", "España": "Madrid"} print("Consulto la cap de Francia") print(miDiccionario["Francia"]) print("Agrego Argentina al diccionario") miDiccionario["Argentina"] = "Buenos Aires" print("Consulto la capital de Argentina") print(miDiccionario...
class Solution: def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ def foo(l, r, path): if l == 0 and r == 0 : res.append(path[:]) return if r >= l: if l != 0: f...
class Solution: def numMatchingSubseq(self, S, words): """ :type S: str :type words: List[str] :rtype: int """ d = collections.defaultdict(list) for word in words: d[word[0]].append(word[1:]) cnt = 0 for ch in S: if ch i...
# Databricks notebook source # MAGIC %md # MAGIC ## Project Description # MAGIC In this final project, you and your group will be developing an end-to-end Data-Intensive Application (DIA) that recommends ERC-20 Tokens that a given wallet address may be interested in based on their historic similarity to other wallets o...
pass # import os # from unittest.mock import MagicMock, patch # import pytest # from JumpscaleZrobot.test.utils import ZrobotBaseTest, mock_decorator # from node_port_manager import NODE_CLIENT, NodePortManager # from zerorobot.template.state import StateCheckError # import itertools # class TestNodePortManagerTemp...
# Índice de massa corporal (adaptado) print('=' * 5, 'EX_043', '=' * 5) massa = float(input('Qual é a sua massa? (Kg): ')) altura = float(input('Qual é a sua altura? (m): ')) imc = massa / (altura ** 2) print('O IMC dessa pessoa é de {:.1f}'.format(imc)) if imc < 18.5: print('Está abaixo do peso.') elif 18.5 <=...
# -- coding : utf-8 -- # @Time:2022/2/28 17:51 # @Author: Jianing Gou(goujianing19@mails.ucas.ac.cn) """Python3 implementation of QuickSort Main idea: 1、find a pivot(Last number in a array); 2、partition, split the original array into two subarray, one is the number below the pivot, one is over the pivot; 3、recursive t...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2016, 2017, 2018 Guenter Bartsch # # 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....
test = { 'name': 'q41', 'points': 1, 'suites': [ { 'cases': [ { 'code': '>>> # Oops, your name is assigned to the wrong data type!;\n' '>>> type(year_population_crossed_6_billion) == int or type(year_population_crossed_6_billion) == np.int32\n' ...
class RtlSignalBase(): """ Main base class for all rtl signals """ pass class RtlMemoryBase(RtlSignalBase): """ Main base class for all rtl memories """ pass
class UrlConstructor: def __init__(self, key='', base_url='https://androzoo.uni.lu/api/download?apikey={0}&sha256={01}'): self.base_url = base_url self.key = key def construct(self, apk): return self.base_url.format(self.key, apk.sha256)
class Node: def __init__(self,data=None,next=None,position = 0): self.data = data self.next = next self.position = position class LinkedList: def __init__(self) -> None: self.head = None # Initialising the head as None def insetElement(self,data): newNode = ...
def solution(A): count = [] len_a = len(A) for i in range(len_a): sub_count = 0 for j in range(len_a): if i != j and A[i] % A[j] != 0: sub_count += 1 count.append(sub_count) return count print(solution([3, 1, 2, 3, 6]))
""" Module: 'array' on esp32 1.12.0 """ # MCU: (sysname='esp32', nodename='esp32', release='1.12.0', version='v1.12 on 2019-12-26', machine='ESP32 module with ESP32') # Stubber: 1.3.2 class array: '' def append(): pass def decode(): pass def extend(): pass
# def isPrime(number): # counter = 2 # isPrime = True # # while counter < number: # if number % counter == 0: # isPrime = False # break # # counter = counter + 1 # # return isPrime # function isPrime def isPrime(number): counter = 2 while counter < numb...
i = 0 num = int(input("Enter your number:- ")) while i <= num: if num > 0: print("it is positive") elif num < 0: print("it is negative") else : print("zero") i = i + 1
DATA = { "B01003_001E": "Total Population", "B01002_001E": "Median Age", "B11005_001E": "Total Households Age", "B11005_002E": "Total Households With Under 18", # household income "B19013_001E": "Median Household Income", "B19001_001E": "Total Households Income", "B19001_002E": "Hou...
'''Basic object to store the agents and auxiliary content in the agent system graph. The object should be considered to be replaced with namedtuple at some point, once the default field has matured ''' class Node(object): '''Basic object to store agent and auxiliary content in the agent system. Parameters ...
masuk=int(input("Masukkan Jam Masuk = ")) keluar=int(input("Masukkan Jam Keluar =")) lama=keluar-masuk payment=12000 print("Lama Mengajar = ", lama, "jam") if lama <=1: satu_jam_pertama=payment print("Biaya Mengajar= Rp", satu_jam_pertama) elif lama <10: biaya_selanjutnya = (lama+1)*3000+payment print("...
# dataset settings dataset_type = 'PhoneDataset' data_root = '/home/ubuntu/tienpv/datasets/PhoneDatasets/COCO2017/' ann_files = '/home/ubuntu/tienpv/datasets/PhoneDatasets/COCO2017/annotations/instances_train2017_cell_phone_format_widerface.txt' val_data_root = '/home/ubuntu/tienpv/datasets/PhoneDatasets/COCO2017/' va...
# 6. Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, # но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. Продолжить работу над заданием. В # программу должна попадать строка из слов, разделенных пробелом. Каждое слово состоит из латинских букв ...
def longestPeak(array): max_size = 0 i = 1 while i < len(array) - 1: peak = array[i - 1] < array[i] > array[i + 1] if not peak: i += 1 continue left = i - 1 right = i + 1 while left >= 0 and array[left] < array[left + 1]: left ...
class Agent: """An abstract class defining the interface for a Reversi agent.""" def __init__(self, reversi, color): raise NotImplementedError def get_action(self, game_state, legal_moves=None): raise NotImplementedError def observe_win(self, state, winner): raise NotImplement...
# ======================== # Information # ======================== # Direct Link: https://www.hackerrank.com/challenges/s10-standard-deviation # Difficulty: Easy # Max Score: 30 # Language: Python # ======================== # Solution # ======================== N = int(input()) X = list(map(int, input...
class Entity(object): def __init__(self, name, represented_class_name=None, parent_entity=None, is_abstract=False, attributes=None, relationships=None): self.name = name self.represented_class_name = represented_class_name or name self.parent_entity = parent_entity self.i...
class Solution: def answer(self, current, end, scalar): if current == end: return scalar self.visited.add(current) if current in self.graph: for i in self.graph[current]: if i[0] not in self.visited: a = self.answer(i[0], end, scala...
# -*- coding: utf-8 -*- """Test strategy with hashing mutiple shift invariant aligned patches See: https://stackoverflow.com/a/20316789/51627 """ def main(): pass if __name__ == "__main__": main()
def isIsosceles(x, y, z): if x <= 0 or y <=0 or z <=0: return False if x == y: return True if y == z: return True if x == z: return True else: return False print(isIsosceles(-2, -2, 3)) print(isIsosceles(2, 3, 2)) def isIsosceles(x, y, z): if x <= 0 or y <=...
# -*- coding: utf-8 -*- __author__ = 'lycheng' __email__ = "lycheng997@gmail.com" class Solution(object): def wordPattern(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ words = str.split(" ") if len(pattern) != len(words): ...
# Copyright 2017 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. inline = """ <map> <name>adc_mux</name> <doc>valid mux values for DUT's two banks of INA219 off PCA9540 ADCs</doc> <params clobber_ok="" ...
class CmdResponse: __status: bool __type: str __data: dict __content: str def __init__(self, status: bool, contentType: str): self.__status = status self.__type = contentType self.__data = {'status': status} self.__content = None def setData(self, ...
with open("pytest_results.xml", "w") as f: f.write("<?xml version='1.0' encoding='utf-8'?>") f.write("<test>") f.write("<!-- No tests executed -->") f.write("</test>")
def exec(path: str, data: bytes) -> None: fs = open(path, 'wb') fs.write(data) fs.close()
class TernarySearchTrie: """Implements https://en.wikipedia.org/wiki/Ternary_search_tree""" def __init__(self): self.root = None def get(self, s: str) -> bool: """Return True if string s is in trie, else False""" return self._get(s, 0, self.root) def put(self, s: str, label): ...
# model batch = 1 in_chans = 1 out_chans = 1 in_rows = 4 in_cols = 4 out_rows = 8 out_cols = 8 ker_rows = 3 ker_cols = 3 stride = 2 # pad is 0 (left: 0 right: 1 top: 0 bottom: 1) input_table = [x for x in range(batch * in_rows * in_cols * in_chans)] kernel_table = [x for x in range(out_chans * ker_rows * ker_cols * in...
# NOTE: this needs work male = [ 'AAREN', 'AARON', 'ABE', 'ABEL', 'ABNER', 'ABRAHAM', 'ABRAM', 'ACE', 'ADAIR', 'ADAM', 'ADDISON', 'ADEN', 'ADOLPH', 'ADRIAN', 'AIDAN', 'AIDEN', 'AINSLEY', 'AL', 'ALAN', 'ALBAN', 'ALBERT', 'ALBIE', ...
def main(): # input css = [[*map(int, input().split())] for _ in range(3)] # compute for i in range(3): if css[i-1][i-1]+css[i][i] != css[i-1][i]+css[i][i-1]: print('No') exit() # output print('Yes') if __name__ == '__main__': main()
''' This is a math Module Do Some thing ''' def add(a=0, b=0): return a + b; def minus(a=0, b=0): return a - b; def multy(a=1, b=1): return a * b;
win = ''' ██╗ ██╗ █████╗ ██╗ ██╗   ╚██╗ ██╔╝██╔══██╗██║ ██║   ╚████╔╝ ██║ ██║██║ ██║   ╚██╔╝ ██║ ██║██║ ██║   ██║ ╚█████╔╝╚██████╔╝   ╚═╝ ╚════╝ ╚═════╝   ...
# Time: O(n) # Space: O(1) class Solution(object): def maxDepthAfterSplit(self, seq): """ :type seq: str :rtype: List[int] """ return [(i & 1) ^ (seq[i] == '(') for i, c in enumerate(seq)] # Time: O(n) # Space: O(1) class Solution2(object): def maxDepthAfterSplit(sel...
class MyClass: data = 3 a = MyClass() b = MyClass() a.data = 5 print(a.data) print(b.data)
class Solution: def findLHS(self, nums) -> int: nums.sort() pre_num, pre_length = -1, 0 cur_num, cur_length = -1, 0 i = 0 max_length = 0 while i < len(nums): if nums[i] == cur_num: cur_length += 1 else: if cur_nu...
def validate_count(d): print(len([0 for e in d if((c:=e[2].count(e[1]))>e[0][0])and(c<e[0][1])])) def validate_position(d): print(len([0 for e in d if(e[2][e[0][0]-1]==e[1])^(e[2][e[0][1]-1]==e[1])])) if __name__ == "__main__": with open('2020/input/day02.txt') as f: database = [[[*map(int, (e := ...
# Copyright 2017 Brocade Communications Systems, 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 also obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
{ "includes": [ "../common.gypi" ], "targets": [ { "configurations": { "Release": { "defines": [ "NDEBUG" ] } }, "include_dirs": [ ...
# Programowanie I R # Łańcuchy tekstowe # Dokumentacja: # https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str # https://docs.python.org/3/library/string.html # Określanie łańcuchów 'Amicus Plato, sed magis amica veritas' "Amicus Plato, sed magis amica veritas" # Stosowanie znaków ' i " wewnątrz ła...
""" @Author: huuuuusy @GitHub: https://github.com/huuuuusy 系统: Ubuntu 18.04 IDE: VS Code 1.36 工具: python == 3.7.3 """ """ 思路: 解决这类 “最优子结构” 问题,可以考虑使用 “动态规划”: 1、定义 “状态”; 2、找到 “状态转移方程”。 记号说明: 下文中,使用记号 s[l, r] 表示原始字符串的一个子串,l、r 分别是区间的左右边界的索引值,使用左闭、右闭区间表示左右边界可以取到。 举个例子,当 s = 'baba...
"""  Created on Tue Apr 23 2019   Copyright (c) 2019 João Eduardo Montandon """ __name__ = "stackoverflow-jobs" __version__ = "0.1.0"
def flatten_forest(forest): flat_forest = [] for row in forest: flat_forest += row return flat_forest def deflatten_forest(forest_1d, rows): cols = len(forest_1d) // rows forest_2d = [] for i in range(cols): forest_slice = forest_1d[i*cols: (i+1)*cols] forest_2d.append(...