content
stringlengths
7
1.05M
# Project Euler Problem 7- 10001st prime # https://projecteuler.net/problem=7 # Answer = 104743 def is_prime(num): for i in range(2, num): if (num % i) == 0: return False return True def prime_list(): prime_list = [] num = 2 while True: if is_prime(num): p...
# Approach 2 - Greedy with Stack # Time: O(N) # Space: O(N) class Solution: def removeKdigits(self, num: str, k: int) -> str: num_stack = [] for digit in num: while k and num_stack and num_stack[-1] > digit: num_stack.pop() k -= 1 ...
def get_keys(filename): with open(filename) as f: data = f.read() doc = data.split("\n") res = [] li = [] for i in doc: if i != "": li.append(i) else: res.append(li) li=[] return res if __name__=="__main__": filename = './input.txt' input = get_keys(filen...
expected_output = { "mac_table": { "vlans": { "100": { "mac_addresses": { "ecbd.1dff.5f92": { "drop": {"drop": True, "entry_type": "dynamic"}, "mac_address": "ecbd.1dff.5f92", }, ...
""" This module contains the default settings that stand unless overridden. """ # ## Gateway Daemon Settings # # Default port to listen for HTTP uploads on. GATEWAY_WEB_PORT = 8080 # PUB - Connect GATEWAY_SENDER_BINDINGS = ["ipc:///tmp/announcer-receiver.sock"] # If set as a string, this value is used as the salt to ...
package = FreeDesktopPackage('%{name}', 'pkg-config', '0.27', configure_flags=["--with-internal-glib"]) if package.profile.name == 'darwin': package.m64_only = True
def task_format(): return { "actions": ["black .", "isort ."], "verbosity": 2, } def task_test(): return { "actions": ["tox -e py39"], "verbosity": 2, } def task_fulltest(): return { "actions": ["tox --skip-missing-interpreters"], "verbosity": 2, ...
''' This class takes a dictionnary as arg Converts it into a list This list will contain args that will be given to FileConstructor class This list allows to build the core of the new file ''' class RecursivePackager: ''' arg_dict argument = dictionnary This dictionnary has to be built by ParseIntoCreate...
vezesInput = 0 valoresPositivos = 0 soma = 0 for c in range(0, 6, 1): valor = float(input()) if valor > 0: valoresPositivos += 1 soma += valor print(f'{valoresPositivos} valores positivos') print(f'{soma/valoresPositivos:.1f}') '''lista = list() vezesInput = 0 while vezesInput < 6: valor = ...
# coding=utf8 # Copyright 2018 JDCLOUD.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.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ firstRowHasZero = not all(matrix[0]) for i in range(1,len(matrix)): for j in range(len(matrix[0])): if matrix[i][j...
# Python Functions # Three types of functions # Built in functions # User-defined functions # Anonymous functions # i.e. lambada functions; not declared with def(): # Method vs function # Method --> function that is part of a class #can only access said method with an instance or object of said class # A s...
# Copyright (c) OpenMMLab. All rights reserved. model = dict( type='DBNet', backbone=dict( type='mmdet.ResNet', depth=18, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=-1, norm_cfg=dict(type='BN', requires_grad=True), init_cfg=dict(type='Pretrained...
class HttpRequest: """ HTTP request class. Attributes: method (str): the HTTP method. request_uri (str): the request URI. query_string (str): the query string. http_version (str): the HTTP version. headers (dict of str: str): a `dict` containing the headers. ...
for i in range(1, 6): for j in range(1, 6): if(i == 1 or i == 5): print(j, end="") elif(j == 6 - i): print(6 - i, end="") else: print(" ", end="") print()
#!/usr/bin/env python3.4 # # Copyright 2016 - Google # # 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 appl...
# Fit image to screen height, optionally stretched horizontally def fit_to_screen(image, loaded_image, is_full_width): # Resize to fill height and width image_w, image_h = loaded_image.size target_w = image_w target_h = image_h image_ratio = float(image_w / image_h) if target_h > image.height: target_h ...
def setup_parser(common_parser, subparsers): parser = subparsers.add_parser("genotype", parents=[common_parser]) parser.add_argument( "-i", "--gram_dir", help="Directory containing outputs from gramtools `build`", dest="gram_dir", type=str, required=True, ) ...
#coding=utf-8 class Solution: def longestCommonPrefix(self, strs): res = "" strs.sort(key=lambda i: len(i)) # print(strs) for i in range(len(strs[0])): tmp = res + strs[0][i] # print("tmp=",tmp) for each in strs: if each.startsw...
FILE_NAME = 1 # Імя файла для запису даних SHOW_INFO = True DISPLAY_POSITION = (50,30) DISPLAY_SIZE = (1700, 1030) DISPLAY_COLOR = (48, 189, 221) FPS = 240 MAX_COUNTER = 3000 # Кількість циклів в 1 еопосі MAX_EPOCH = 1000 # Кількість епох START_POPULATION = 10 # Кількість осіб взагалі COUNT_OF_ALIVE_AFTER_EPOCH = 10...
def da_sort(lst): count = 0 # replica = [x for x in lst] result = sorted(array) for char in lst: if char != result[0]: count += 1 else: result.pop(0) return count T = int(input()) for _ in range(T): k, n = map(int, input().split()) array...
# Aula 10 - Operadores relacionais + IF/ELIF/ELSE # == > >= < <= != # == comparação de Igualdade, perguntando se uma coisa é igual a outra. numero1 = 2 numero2 = 2 print(2 == 2) print(2 == 1) print(2 == '2') expressao = numero1 == numero2 print(f'numero1 == numero2: {expressao}') # > ver numero1 é 'maior que' numero 2...
def netmiko_config(device, configuration=None, **kwargs): if configuration: output = device['nc'].send_config_set(configuration) else: output = "No configuration to send." return output
# funcao1.py, definimos uma função chamada multiplica, que multiplica a variável global valor por um fator passado como parâmetro. # O valor do resultado é atribuído à variável valor novamente (linha 5), que é impresso em seguida (linha 6). # Ao chamarmos a função multiplica(3) pela primeira vez (linha 8), obtemos a sa...
class SmTransferPriorityEnum(basestring): """ low|normal Possible values: <ul> <li> "low" , <li> "normal" </ul> """ @staticmethod def get_api_name(): return "sm-transfer-priority-enum"
# x = 5 # # # def print_x(): # print(f'Print {x}') # # # print(x) # print_x() # # # def f1(): # def nested_f1(): # # nonlocal y # # y += 1 # y = 88 # ll.append(3) # # ll = [3] # z = 7 # print('From nested f1') # print(x) # print(y) # ...
def get_int_value(text): text = text.strip() if len(text) > 1 and text[:1] == '0': second_char = text[1:2] if second_char == 'x' or second_char == 'X': # hexa-decimal value return int(text[2:], 16) elif second_char == 'b' or second_char == 'B': # binar...
"""Exercício Python 37: Escreva um programa em Python que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: 1 para binário, 2 para octal e 3 para hexadecimal.""" num = int(input('Digite um numero inteiro: ')) print('ESCOLHA 1 DAS 3 OPÇÕES ABAIXO:') print('[ 1 ] converte para...
class AdvancedArithmetic(object): def divisorSum(n): raise NotImplementedError class Calculator(AdvancedArithmetic): def getDivisors(self, n): if n == 1: return [1] maximum, num = n, 2 result = [1, n] while num < maximum: if not n % num: ...
class Node: def __init__(self, item, next=None): self.value = item self.next = next def linked_list_to_array(LList): item = [] if LList is None: return [] item = item + [LList.value] zz = LList while zz.next is not None: item = item + [zz.next.value] zz ...
# /* vim: set tabstop=2 softtabstop=2 shiftwidth=2 expandtab : */ class d: def __init__(i, tag, txt, nl="", kl=None): i.tag, i.nl, i.kl, i.txt = tag, nl, kl, txt def __repr__(i): s="" if isinstance(i.txt,(list,tuple)): s = ''.join([str(x) for x in i.txt]) else: s = str(i.txt) kl = ...
# Nosso time de futebol terminou o campeonato. O resultado de cada correspondência é semelhante a "x: y". # Os resultados de todas as partidas são registrados na coleção. # Escreva uma função que leve essa arrecadação e conte os pontos da nossa # equipe no campeonato. Regras para contagem de pontos para cada partida:...
print('\033[1;32m APRENDENDO FUNÇÕES EM PYTHON\033[m') def escreva(msg): print('-' * (len(msg) + 2)) print(f'{ msg}') print('-' * (len(msg) + 2)) x = str(input('Digite uma frase: ')) escreva(x)
""" 数据暂存 """ class DataPool: def __init__(self): self.data = dict() def save(self, key, value): self.data[key] = value def remove(self, key): self.data.pop(key) def exist(self, key): return key in self.data
students = [ { "name": "John Doe", "age": 15, "sex": "male" }, { "name": "Jane Doe", "age": 12, "sex": "female" }, { "name": "Lockle Rory", "age": 18, "sex": "male" }, { "name": "Seyi Pedro", "age": 10, ...
# 66. 加一 class Solution: def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ for i in range(len(digits)-1, -1, -1): if digits[i] != 9: digits[i] += 1 return digits digits[i] = 0 digits[0]...
# 832 SLoC v = FormValidator( firstname=Unicode(), surname=Unicode(required="Please enter your surname"), age=Int(greaterthan(18, "You must be at least 18 to proceed"), required=False), ) input_data = { 'firstname': u'Fred', 'surname': u'Jones', 'age': u'21', } v.process(input_data) == {'age': 21, 'firstn...
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate...
def most_frequent_days(year): days=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"] if year==2000: return ['Saturday', 'Sunday'] check=2000 if year>check: day=6 while check<year: check+=1 day+=2 if leap(check) else 1 if day%7==0: ...
class Solution: # @param {integer[]} nums # @return {string} def largestNumber(self, nums): nums = sorted(nums, cmp=self.compare) res, j = '', 0 for i in range(len(nums) - 1): if nums[i] != 0: break else: j += 1 for k in...
n = int(input()) sequence = [] for i in range(n): sequence.append(int(input())) print(f"Max number: {max(sequence)}\nMin number: {min(sequence)}")
#python evt = lx.args()[0] if evt == 'onDo': lx.eval("?kelvin.quickScale") elif evt == 'onDrop': pass
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def largestBSTSubtree(self, root): """ :type root: TreeNode :rtype: int """ def f...
""" An implementation of a very simple Twitter Standard v1.1 API client based on :mod:`requests`. See https://developer.twitter.com/en/docs/twitter-api/v1 for more information. """
class Solution: def lexicalOrder(self, n: int) -> List[int]: ans = [1] while len(ans) < n: nxt = ans[-1] * 10 while nxt > n: nxt //= 10 nxt += 1 while nxt % 10 == 0: nxt //= 10 ans.append(nxt) ...
# Advent of Code - Day 2 # day_2_advent_2020.py # 2020.12.02 # Jimmy Taylor # Reading data from text file, spliting each value as separate lines without line break input_data = open('inputs/day2.txt').read().splitlines() # Cleaning up the data in each row to make it easier to parse later as individual rows modified_da...
for t in range(int(input())): G = int(input()) for g in range(G): I,N,Q = map(int,input().split()) if I == 1 : if N%2: heads = N//2 tails = N - N//2 if Q == 1: print(heads) else: ...
class Tile(): def __init__(self, pos): self.white = True self.pos = pos def flip(self): self.white = not self.white def get_new_coord(from_tile, instructions): curr = [from_tile.pos[0], from_tile.pos[1]] for instruction in instructions: if instruction == "ne": ...
# Example 1: # Input: digits = "23" # Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] # Example 2: # Input: digits = "" # Output: [] # Example 3: # Input: digits = "2" # Output: ["a","b","c"] class Solution: def letterCombinations(self, digits: str) -> List[str]: phone_keyboard = {2: 'abc', 3: 'de...
class Solution(object): def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ res = [1] * (len(nums)) prefix = 1 for i in range(len(nums)): res[i] = prefix prefix *= nums[i] postfix = 1 for ...
# Write a program to read through the mbox-short.txt and figure out who has sent # the greatest number of mail messages. The program looks for 'From ' lines and # takes the second word of those lines as the person who sent the mail # The program creates a Python dictionary that maps the sender's mail address to a ' \ #...
class FindAnswer: def __init__(self, db): self.db = db # 검색 쿼리 생성 def _make_query(self, intent_name, ner_tags): sql = "select * from chatbot_train_data" if intent_name != None and ner_tags == None: sql = sql + " where intent='{}' ".format(intent_name) elif inten...
#List of Numbers list1 = [12, -7, 5, 64, -14] #Iterating each number in the lsit for i in list1: #checking the condition if i >= 0: print(i, end = " ")
def Rotate2DArray(arr): n = len(arr[0]) for i in range(0, n//2): for j in range(i, n-i-1): temp = arr[i][j] arr[i][j] = arr[n-1-j][i] arr[n-j-1][i] = arr[n-1-i][n-j-1] arr[n-i-1][n-j-1] = arr[j][n-i-1] arr[j][n-i-1] = temp return ar...
class Scene: def __init__(self, name="svg", height=400, width=400): self.name = name self.items = [] self.height = height self.width = width return def add(self, item): self.items.append(item) def strarray(self): var = ["<?xml version=\"1.0\"?>\n", ...
#Leia uma temperatura em graus celsius e apresente-a convertida em fahrenheit. # A formula da conversao eh: F=C*(9/5)+32, # sendo F a temperatura em fahrenheit e c a temperatura em celsius. C=float(input("Informe a temperatura em Celsius: ")) F=C*(9/5)+32 print(f"A temperatura em Fahrenheit eh {round(F,1)}")
def main(j, args, params, tags, tasklet): page = args.page action = args.requestContext.params.get('action') domain = args.requestContext.params.get('domain') name = args.requestContext.params.get('name') version = args.requestContext.params.get('version') nid = args.requestContext.params.get('n...
STATS = [ { "num_node_expansions": 25, "plan_length": 20, "search_time": 0.04, "total_time": 0.04 }, { "num_node_expansions": 22, "plan_length": 18, "search_time": 0.04, "total_time": 0.04 }, { "num_node_expansions": 24, ...
# -*- coding: utf-8 -*- # @Author: 何睿 # @Create Date: 2019-01-20 21:12:46 # @Last Modified by: 何睿 # @Last Modified time: 2019-01-20 21:23:10 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def remo...
def rotate(angle): """Rotates the context""" raise NotImplementedError("rotate() is not implemented") def translate(x, y): """Translates the context by x and y""" raise NotImplementedError("translate() is not implemented") def scale(factor): """Scales the context by the provided factor""" r...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- 'WEB编程的练习' __author__ = 'Jacklee' """ WSGI(Web Server Gateway Interface) 是一个接口规范 包括了Server端、Middleware中间件、Applicatioin客户端 1. 使用WSGI规范开发的简单的WEB处理程序 hello.py myserver.py 2. Web App 就是一个WSGI的处理函数,针对每种HTTP请求进行响应 A. 对不同HTTP请求(GET、PUT、POST、DELETE)进行处理 B. 对不同的请求路径P...
print(14514) for i in range(3, 121): for j in range(1, i + 1): print(i, j, -1) print(i, j, 1)
obj_row, obj_col = 2978, 3083 first_code = 20151125 def generate(obj_row, obj_col): x_row= obj_row + obj_col - 1 x_n = sum(range(1, x_row + 1)) - (x_row - obj_col) print(x_n) previous = first_code aux = first_code for i in range(1, x_n) : aux = (previous * 252533) % 33554393 ...
def wait(t, c): while c < t: c += c return c s, t, n = [int(i) for i in raw_input().split()] d = map(int, raw_input().split()) b = map(int, raw_input().split()) c = map(int, raw_input().split()) time = s time += d[0] for i in range(n): time = wait(time, c[i]) time += b[i] time += d[i+1] pri...
#Grantham, R. Science. 185, 862–864 (1974) #(amino acid side chain composition, polarity and molecular volume) grantham = { 'ALA': 0.000, 'ARG': 0.650, 'ASN': 1.330, 'ASP': 1.380, 'CYS': 2.750, 'GLN': 0.890, 'GLU': 0.920, 'GLY': 0.740, 'HIS': 0.580, 'ILE': 0.000, 'LEU': 0.0...
class Config: SECRET_KEY = 'a22912297e93845c6cf4776991df63ec' SQLALCHEMY_DATABASE_URI = 'sqlite:///site.db' MAIL_SERVER = 'smtp.gmail.com' MAIL_PORT = 587 MAIL_USE_TLS = True MAIL_USERNAME = "noreplya006@gmail.com" MAIL_PASSWORD = "#@1234abcd"
# https://practice.geeksforgeeks.org/problems/circular-tour-1587115620/1 # 4 6 7 4 # 6 5 3 5 # -2 1 4 -1 class Solution: def tour(self, lis, n): sum = 0 j = 0 for i in range(len(lis)): pair = lis[i] sum += pair[0]-pair[1] if sum < 0: sum =...
MESSAGES = { # name -> (message send, expected response) "ping request": (b'd1:ad2:id20:\x16\x01\xfb\xa7\xca\x18P\x9e\xe5\x1d\xcc\x0e\xf8\xc6Z\x1a\xfe<s\x81e1:q4:ping1:t2:aa1:y1:qe', b'^d1:t2:aa1:y1:r1:rd2:id20:.{20}ee$'), "ping request missing id": (b'd1:ade1:q4:ping1:t2:XX1:y1:qe', b'^d1:t2:X...
#!/usr/bin/env python # PoC1.py junk = "A"*1000 payload = junk f = open('exploit.plf','w') f.write(payload) f.close()
""" Misc ASCII art """ WARNING = r""" _mBma sQf "QL jW( -$g. jW' -$m, .y@' _aa. 4m, .mD` ]QQWQ. 4Q, _mP` ]QQQQ ?Q/ _QF )WQQ@ ?Qc <QF QQQF )Qa jW( QQQf "QL jW' ]H...
""" summary: code to be run right after IDAPython initialization description: The `idapythonrc.py` file: * %APPDATA%\Hex-Rays\IDA Pro\idapythonrc.py (on Windows) * ~/.idapro/idapythonrc.py (on Linux & Mac) can contain any IDAPython code that will be run as soon as IDAPython is done successfully initial...
#coding: utf-8 number = [] print("1부터 100사이의 숫자를 입력하시오.") for i in range(10): while(True): newnum = int(input(str(i+1)+"번째 숫자를 입력하시오. ")) if not newnum in number: number.append(newnum) break else: print("잘못 입력하셨습니다. 다시 입력하세요.") for i in range(10): print(str(i+1)+"번째 숫자는",number[i],"입니다.")
''' Created on 22 Oct 2019 @author: Yvo ''' name = "Rom Filter";
class State: MOTION_STATIONARY = 0 MOTION_WALKING = 1 MOTION_RUNNING = 2 MOTION_DRIVING = 3 MOTION_BIKING = 4 LOCATION_HOME = 0 LOCATION_WORK = 1 LOCATION_OTHER = 2 RINGER_MODE_SILENT = 0 RINGER_MODE_VIBRATE = 1 RINGER_MODE_NORMAL = 2 SCREEN_STATUS_ON = 0 SCREEN_S...
num1 =int(input('Primeiro Numero')) num2 = int(input('Segundo Numero')) if num1 > num2: print('O Primeiro numero é maior') elif num1 < num2: print('O Segundo Numero é maior') else: print('Os Dois São o Mesmo Valor')
class Shortener(): """ The shortner API provides three functions, create, retrive and update shortened URL token. """ def __init__(self, shortener, store, validator) -> None: self.__shortener = shortener self.__store = store self.__validator = validator self.__default_pr...
""" FILE: read_switches.py AUTHOR: Ben Simcox PROJECT: verbose-waffle (github.com/bnsmcx/verbose-waffle) PURPOSE: Currently simulates reading of switches. This functionality will change when prototyping moves to hardware but the use of a list of lists to capture the switch posit...
# -*- coding: utf-8 -*- TVS = [{ 'number': 1, 'title': 'Asteroid Blues', 'airdate': 'October 24, 1998', 'content': """In a flashback, Spike Spiegel is shown waiting near a church holding a bouquet of flowers, before leaving as the church bell rings. As he walks away, images of a gunfight he participat...
class LinkParserResult: uri: str = "" relationship: str = "" link_type: str = "" datetime: str = "" title: str = "" link_from: str = "" link_until: str = "" def __init__(self, uri: str = "", relationship: str = "", link_type: str = "", ...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ p1, p2 = headA, headB len1, len2 = 1, 1 ...
class Solution: def confusingNumberII(self, N: int) -> int: table = {0:0, 1:1, 6:9, 8:8, 9:6} keys = [0, 1, 6, 8, 9] def dfs(num, rotation, base): count = 0 if num != rotation: count += 1 for d in keys: if num == 0 and d == ...
# -*- coding: utf-8 -*- APPLIANCE_SECTION_START = '# BEGIN AUTOGENERATED' APPLIANCE_SECTION_END = '# END AUTOGENERATED' class UpScript(object): """ Parser and generator for tinc-up scripts. This is pretty basic: It assumes that somewhere in the script, there is a section initiated by '# BEGIN AUTOGE...
# 无法访问: # class Base(object): # __secret = "受贿" # # class Foo(Base): # def func(self): # print(self.__secret) # print(Foo.__secret) # # obj = Foo() # obj.func() # 可以访问: class Base(object): __secret = "受贿" def zt(self): print(Base.__secret) class Foo(Base): def func(self): ...
def or_else(lhs, rhs): if lhs != None: return lhs else: return rhs def fold(function, arguments, initializer, accumulator = None): if len(arguments) == 0: return accumulator else: return fold( function, arguments[1:], initializer, function( or_else(accumulator, initializer), arg...
lst = """75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40...
## https://leetcode.com/problems/path-sum # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def hasPathSum(self, root: Optional[TreeNode], targetSum: int) ->...
class Solution: def groupAnagrams(self, strs: 'List[str]') -> 'List[List[str]]': dic = {} for anagram in strs: key = ''.join(sorted(anagram)) if key in dic.keys(): dic[key].append(anagram) else: dic[key] = [anagram] result =...
""" https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/23/dynamic-programming/57/ 题目:打家劫舍 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。 示例 1: 输入: [1,2,3,1] 输出: 4 解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 ...
class unknown_dungeon(): @staticmethod def on_entry(user_id): db.add_rating(user_id, -5) text = '🔥Ты упал в это подземелье. Не очень верится, что ты сможешь выйти отсюда живым, но удачи.' text += '\nПервое что ты тут встречаешь, это развилка. Выбирай куда ступишь, налево или направо.' ...
# Stream are lazy linked list # A stream is a linked list, but the rest of the list is computed on demand ''' Link- First element is anything - second element is a Link instance or Link.empty Stream -First element can be anything - Second element is a zero-argument function that returns a Stream or Strea...
def help(update, context): text = "Внимание! Все действия происходят для активной команды.\n\n"\ \ \ "/add_question [QUESTION]\n"\ "Добавить новый вопрос.\n"\ "Параметр [QUESTION] - текст вопроса.\n\n"\ \ \ "/question_list\n"\ ...
#!/usr/bin/env python3 def format_log_level(level): return [ 'DEBUG', 'INFO ', 'WARN ', 'ERROR', 'FATAL', ][level] def format_log_type(log_type): return log_type.lstrip('TI') def format_log_entry(log_entry): return '{} {} {}:{} {}'.format( log_entry['lo...
def sieve(max): primes = [] for n in range(2, max + 1): if any(n % p > 0 for p in primes): primes.append(n) return primes """ Sieve of Eratosthenes prime-sieve Input: max: A positive int representing an upper bound. Output: A list containing all primes up to and including max ...
print('==== PROGRAMA PARA DESCOBRIR ANTECESSOR E SUCESSOR DE UM NUMERO ====') num = int(input('\033[30;7m Digite um número:\033[m')) anter = num - 1 suces = num + 1 print(' O número \033[1m{}\033[m tem como o antecessor ' 'o numero \033[1m{}\033[m e sucessor o número \033[1;3m{}.'.format(num, anter,suces,))
# app/utils.py def make_step_iter(step, max_): num = 0 while True: yield num num = (num + step) % max_
PASILLO_DID = "A1" CUARTO_ESTE_DID = "A2" CUARTO_OESTE_DID = "A4" SALON_DID = "A5" HEATER_DID = "C1" HEATER_PROTOCOL = "X10" HEATER_API = "http://localhost" HEATER_USERNAME = "raton" HEATER_PASSWORD = "xxxx" HEATER_MARGIN = 0.0 HEATER_INCREMENT = 0.5 AWS_CREDS_PATH = "/etc/aws.keys" AWS_ZONE = "us-east-1" MINUTES...
# best solution: # https://leetcode.com/problems/merge-two-sorted-lists/discuss/9735/Python-solutions-(iteratively-recursively-iteratively-in-place). # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeTwoL...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Copyright 2021, Yutong Xie, UIUC. Using for loop to find maximum product of three numbers ''' class Solution(object): def maximumProduct(self, nums): """ :type nums: List[int] :rtype: int """ min1, min2 = float("inf"...
class Article(): def __init__(self, title, description, author, site, link): """Init the article model""" self.title = title self.description = description self.author = author self.site = site self.link = link
# Given an array, rotate the array to the right by k steps, where k is non-negative. # Example 1: # Input: [1,2,3,4,5,6,7] and k = 3 # Output: [5,6,7,1,2,3,4] # Explanation: # rotate 1 steps to the right: [7,1,2,3,4,5,6] # rotate 2 steps to the right: [6,7,1,2,3,4,5] # rotate 3 steps to the right: [5,6,7,1,2,3,4] ...