content
stringlengths
7
1.05M
class Token(object): def __init__(self, access_token, refresh_token, lifetime): self.access_token = access_token # Access token value self.refresh_token = refresh_token # Token needed for refreshing access token self.lifetime = lifetime # Access token lifetime
def main(): print(hi) if __name__ == '__main__': main()
""" - Sção pequenas partes de código que realizam tarefas específicas - Pode ou nõa receber entrada de dados e retornar uma saída de dados - Muito úteis para para executar procedimentos similares por repetidas vezes OBS.: Se a função realiza várias tarefas dentro dela, é bom fazer uma verificação para que a função sej...
class Node: def __init__(self, data): self.data = data self.next = None def __repr__(self): return self.data class LinkedList: def __init__(self): self.front = None self.rear = None def __repr__(self): current = self.front nodes = [] wh...
def f(): a = 10 result = 0 result = sum_squares(a, result) print("Sum of squares: " + result) def sum_squares(a_new, result_new): while a_new < 10: result_new += a_new * a_new a_new += 1 return result_new
m = float(input('Digite um tamanho (em metros): ')) dm = m * 10 cm = m * 100 mm = m * 1000 dam = m / 10 hm = m / 100 km = m / 1000 print('convertendo...') print('[dm] =', dm) print('[cm] =', cm) print('[mm] =', mm) print('[dam] =', dam) print('[hm] =', hm) print('[km] =', km)
''' NAME Busqueda del Codón inicial y secuencia transcrita VERSION 1.0 AUTHOR Rodrigo Daniel Hernández Barrera DESCRIPTION Find the start codon and the transcribed sequence CATEGORY Genomic sequence INPUT Read a DNA sequence entered by the user OUTPUT Returns as ou...
#Input, arguments def add(x,y): z = x + y b = 'I am here' a = 'hello' return z,b,a x = 20 y = 5 # Calling function print(add(x,y)) z = add(x,y) #same thing print(z) print(add(10,5)) #same thing
n1 = float(input('Insira o primeiro valor desejado: ')) n2 = float(input('Insira o segundo valor desejado: ')) n3 = float(input('Insira o terceiro valor desejado: ')) if n1 > n2 != n3 and n1 > n3: n4 = (n2 + n3) if n4 > n1: print('É possivel formar um triangulo com esses valores.') else: pri...
def main(request, response): referrer = request.headers.get("referer", "") response_headers = [("Content-Type", "text/javascript")]; return (200, response_headers, "window.referrer = '" + referrer + "'")
#!/usr/bin/python #coding=utf-8 ''' @author: sheng @license: ''' SPELL=u'qūzé' CN=u'曲泽' NAME=u'quze12' CHANNEL='pericardium' CHANNEL_FULLNAME='PericardiumChannelofHand-Jueyin' SEQ='PC3' if __name__ == '__main__': pass
# # PySNMP MIB module IANA-ADDRESS-FAMILY-NUMBERS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IANA-ADDRESS-FAMILY-NUMBERS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 16:50:53 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Pytho...
# regular assignment foo = 7 print(foo) # annotated assignmnet bar: number = 9 print(bar)
VERSION = "0.7.0" LICENSE = "MIT - Copyright (c) 2021 Alex Vellone" MOTORS_CHECK_PER_SECOND = 20 MOTORS_POINT_TO_POINT_CHECK_PER_SECOND = 10 WEB_SOCKET_SEND_PER_SECOND = 10 SOCKET_SEND_PER_SECOND = 20 SOCKET_INCOMING_LIMIT = 5 SLEEP_AVOID_CPU_WASTE = 0.80
def sumoftwo(a, b): """ This is an sumoftwo function to add two number :param int a: first number to add :param int b: first number to add :return: return addition of the integer :rtype: int :example: >>> r = sumoftwo(2, 3) >>> r 5 """ return a + b
model_fn = model_fn_builder( bert_config=bert_config, init_checkpoint=init_checkpoint, layer_indexes=layer_indexes, use_tpu=False, use_one_hot_embeddings=False) # If TPU is not available, this will fall back to normal Estimator on CPU # or GPU. estimator = tf.contrib.tpu.TPUEsti...
# Exercico 1 - listas # Escreva program que leia a nome de 10 alunos # Armezene os nomes em uma lista # Imprema a lista nomes =[] for i in range(1,11): nome = [input(f'Informe o {i} Nome')] nomes.append(nome) for d in nomes: print(f' Nomes informados {d}')
""" We consider a string programmer string if some subset of its letters can be rearranged to form the word programmer. They are anagrams. Given a long string determine the number of indices within the string that are in between two programmer strings. The character 'x' inside an anagram are considered redundant and no...
# -*- coding: utf-8 -*- # Scrapy settings for MavenScrapy project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://doc.scrapy.org/en/latest/topics/settings.html # https://doc.scrapy.org/en/latest/t...
pesos = [] for p in range(1,6): peso = int(input("Digite o peso: ")) pesos.append(peso) print("o menor peso é {} e o menor peso é {}".format(min(pesos), max(pesos)))
class Solution: def XXX(self, x: int) -> int: if x == 0: return 0 res = str(x) sign = 1 if res[0] == '-': res = res[1:] sign = -1 res = res[::-1] if res[0] == '0': res = res[1:] resint = int(res)*sign ...
#Making a nice litte x o o o x o o o x tic tac toe board def printer(board): for i in range(3): for j in range (3): print(board[i][j], end="") if j<2: print(" | ", end="") print() if i<2: print("--+----+--") def main(): tictactoe=[[...
#!/usr/bin/python # create_dict.py weekend = { "Sun": "Sunday", "Mon": "Monday" } vals = dict(one=1, two=2) capitals = {} capitals["svk"] = "Bratislava" capitals["deu"] = "Berlin" capitals["dnk"] = "Copenhagen" d = { i: object() for i in range(4) } print (weekend) print (vals) print (capitals) print (d)
# to jest komentarz WIDTH = 550 HEIGHT = 550
# # @lc app=leetcode.cn id=617 lang=python3 # # [617] merge-two-binary-trees # None # @lc code=end
class Solution: def generatePossibleNextMoves(self, s: str) -> List[str]: results = [] for i in range(len(s) - 1): if s[i: i + 2] == "++": results.append(s[:i] + "--" + s[i + 2:]) return results
class MyStack(object): def __init__(self): """ Initialize your data structure here. """ self.data = [] def push(self, x): """ Push element x onto stack. :type x: int :rtype: None """ q = [x] while self.data: q....
heatmap_1_r = imresize(heatmap_1, (50,80)).astype("float32") heatmap_2_r = imresize(heatmap_2, (50,80)).astype("float32") heatmap_3_r = imresize(heatmap_3, (50,80)).astype("float32") heatmap_geom_avg = np.power(heatmap_1_r * heatmap_2_r * heatmap_3_r, 0.333) display_img_and_heatmap("dog.jpg", heatmap_geom_avg)
quantidade, menor, maior, soma = 0,0,0,0 quantidade = int(input()) while(quantidade>0): menor, maior, soma, final= 10,0,0,0 nome = input() dificuldade = float(input()) notas = input().split() notas = list(notas) for i in range(len(notas)): notas[i] = float(notas[i]) notas.sort() cont = 0 for i in range(len(n...
ALLERGIES_SCORE = ['eggs', 'peanuts', 'shellfish', 'strawberries', 'tomatoes', 'chocolate', 'pollen', 'cats'] class Allergies: def __init__(self, score: int): self.score = score self.lst = self.list_of_allergies() def allergic_to(self, item: str) -> bool: retur...
class Number: def __init__(self, start): self.data = start def __sub__(self, other): return Number(self.data - other) class Indexer: data = [5, 6, 7, 8, 9] def __getitem__(self, item): print('getitem:', item) return self.data[item] def __setitem__(self, index, va...
# This helper file, setups the rules and rewards for the mouse grid system # State = 1, start point # Action - 1: Top, 2:Left, 3:Right, 4:Down def transition_rules(state, action): # For state 1 if state == 1 and (action == 3 or action == 4): state = 1 elif state == 1 and action == 1: state...
# # PySNMP MIB module HUAWEI-BRAS-SBC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-BRAS-SBC-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:31:26 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
# A variável "oi" recebe o valor "Hi" em bytes oi = b'Hi' # Retorna o valor da variável print(oi) # b'Hi' # Retorna o tipo print(type(oi)) # <class 'bytes'>
description = 'Aircontrol PLC devices' group = 'optional' tango_base = 'tango://kompasshw.kompass.frm2:10000/kompass/aircontrol/plc_' devices = dict( spare_motor_x2 = device('nicos.devices.entangle.Motor', description = 'spare motor', tangodevice = tango_base + 'spare_mot_x2', fmtstr = '%...
#8 - LISTA DE COMPONENTES -> PC GAMER comp = ["Nvidia GeForce GTX 2080Ti", "Gabinete Cooler Master", "Kit RAM GSkill DDR4 3.6GHz 8x2GB", "Placa Mãe ASUSTeK ROG MAXIMUS XI EXTREME", "Processador Intel i9", "SSD NVMe Samsung 970 1TB"] del comp[0] del comp[0] print(comp)
# 4. Faça um programa que calcule o salário de um colaborador na empresa XYZ. O salário # é pago conforme a quantidade de horas trabalhadas. Quando um funcionário trabalha # mais de 40 horas ele recebe um adicional de 1.5 nas horas extras trabalhadas. def calcSalario(salario:float, horaExtra:float): if horaExtra > ...
def make_prime_table(n): sieve = list(range(n + 1)) sieve[0] = -1 sieve[1] = -1 for i in range(4, n + 1, 2): sieve[i] = 2 for i in range(3, int(n ** 0.5) + 1, 2): if sieve[i] != i: continue for j in range(i * i, n + 1, i * 2): if sieve[j] == j: ...
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'publics', 'USER': 'publics_read_only', 'PASSWORD': r'read-only', 'HOST': '5.153.9.51', 'PORT': '5432', } } INSTALLED_APPS = ( 'contracts', 'law', 'deputies' ) # ...
body_max_width = 15 body_max_height = 15 def validate_body_str_profile(body: str): body_lines = body.splitlines() width = len(body_lines[0]) height = len(body_lines) if width > body_max_width or height > body_max_height: raise ValueError("Body string is too big")
# -*- coding: utf-8 -*- def userinfo( authority, otherwise='' ): """Extracts the user info (user:pass).""" end = authority.find('@') if -1 == end: return otherwise return authority[0:end] def location( authority ): """Extracts the location (host:port).""" end = authority.find('@') ...
class TrieNode: def __init__(self): self.children = {} self.isEnd = False class WordDictionary: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() def addWord(self, word: str) -> None: """ Adds a...
user_info = { "ok": 1, "data": { "avatar_guide": [], "isStarStyle": 0, "userInfo": { "id": 3112824195, "screen_name": "琪琪琪咩Sickey", "profile_image_url": "https:\/\/tvax3.sinaimg.cn\/crop.0.0.996.996.180\/b989ed83ly8gcdemg2y21j20ro0rotas.jpg?KID=imgbed,...
n, x = map(int, input().split()) if (x > n // 2 and n % 2 == 0) or (x > (n + 1) // 2 and n % 2 == 1): x = n - x A = n - x B = x k = 0 m = -1 ans = n while m != 0: k = A // B m = A % B ans += B * k * 2 if m == 0: ans -= B A = B B = m print(ans)
string_1 = input("String 1? ") string_2 = input("String 2? ") string_3 = input("String 3? ") print(string_1 + string_2 + string_3)
''' URL: https://leetcode.com/problems/slowest-key/ Difficulty: Easy Description: Slowest Key A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a so...
''' Faça um Programa que peça um número e então mostre a mensagem: O número informado foi [número]. ''' numero = input('Digite um número: ') print('O número informado foi: {}'.format(numero))
# Copyright 2015 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. class Shell(object): """Represents an abstract Mojo shell.""" def serve_local_directories(self, mappings, port, reuse_servers=False): """Serves the...
# LeetCode #437 - Path Sum III # https://leetcode.com/problems/path-sum-iii/ # Prefix-sum hashing solution. Runs in linear time. # 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 = righ...
class SearchToursData: def __init__(self, destination, tour_type, start_year, start_month, start_day, adults_num): self.destination = destination self.tour_type = tour_type self.start_year = start_year self.start_month = start_month self.start_day = start_day self.ad...
def first_non_repeating_letter(string): lowercase_string = string.lower() result = [] for i in lowercase_string: if (lowercase_string.count(i) == 1): result.append(i) if (len(result) == 0): return "" else: if (string.find(result[0]) == -1 ): return re...
datasets = ('source',) def synthesis(job): d = {} agg = 0 for dt, x in datasets.source.iterate('roundrobin', ('DATE_OF_INTEREST', 'CASE_COUNT')): agg += x d[dt] = agg return d
''' Created on 16 ago 2017 @author: Hamza ''' class MyClass(object): ''' classdocs ''' def __init__(self, params): ''' Constructor '''
class Solution: def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int: working = 0 for i, stu in enumerate(startTime): if stu <= queryTime and endTime[i] >= queryTime: working += 1 return working
#!/usr/bin/python # -*-coding:utf-8-*- """ @author: smartgang @contact: zhangxingang92@qq.com @file: data_analyse_nba.py @time: 2017/12/5 11:02 """
class Solution: def makeEqual(self, words: List[str]) -> bool: n = len(words) words = ''.join(words) letterCounter = Counter(words) print(letterCounter ) for letter in letterCounter: if letterCounter[letter] % n !=0: return False ...
""" File: complement.py Name:鄭凱元 ---------------------------- This program uses string manipulation to tackle a real world problem - finding the complement strand of a DNA sequence. THe program asks uses for a DNA sequence as a python string that is case-insensitive. Your job is to output the complement of it. """ de...
EARTH = 6371000 MOON = 1737100 MARS = 3389500 JUPITER = 69911000
# -*- coding: utf-8 -*- # @File : constants.py # @Author : Xie # @Date : 9/15/18 # @Desc : # email验证的过期时间 VERIFY_EMAIL_TOKEN_EXPIRES = 24 * 60 * 60 # 每个用户收货地址界面显示的最大地址数量 USER_ADDRESS_COUNTS_LIMIT = 20 # 用户浏览记录最大展示数量 USER_BROWSING_HISTORY_COUNTS_LIMIT = 5
#=============================================================================== # Created: 22 May 2019 # @author: AP (adapated from Jesse Wilson) # Description: Class to contain Anaplan connection details required for all API calls # Input: Authorization header string, workspace ID string, an...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def sumRootToLeaf(self, root: TreeNode) -> int: if root is None: return 0 sum = 0 def plusAllLeaves(...
"""Utility module that defines the :class:`Singleton` class.""" class Singleton: """ Singleton class. The :class:`Singleton` class is used to force a unique instantiation. """ _instance = None def __new__(cls, *args) -> "Singleton": """Control single instance creation.""" if...
DEFAULT_POSTGREST_CLIENT_HEADERS = { "Accept": "application/json", "Content-Type": "application/json", } DEFAULT_POSTGREST_CLIENT_TIMEOUT = 5
# https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ class TreeNode: def __init__(self, x, left=None, right=None): self.val = x self.left = left self.right = right class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'Tr...
# buildifier: disable=module-docstring def _provider_text(symbols): return """ WRAPPER = provider( doc = "Wrapper to hold imported methods", fields = [{}] ) """.format(", ".join(["\"%s\"" % symbol_ for symbol_ in symbols])) def _getter_text(): return """ def id_from_file(file_name): (before, middle, af...
class Solution(object): def searchMatrix(self, matrix, target): if not matrix or target is None: return False rows, cols = len(matrix), len(matrix[0]) low, high = 0, rows* cols - 1 while low <= high: mid = (low + high) / 2 num = matrix[mid / cols...
class SWTestCase: def __init__(self): pass @classmethod def configure(cls): pass def setUp(self): pass def tearDown(self): pass def run_all_test_case(self): for test in self.test_to_run: self.setUp() test() self.te...
def even_odd(*args): args = list(args) command = args.pop() if command == "even": return [x for x in args if x % 2 == 0] return [x for x in args if not x % 2 == 0] print(even_odd(1, 2, 3, 4, 5, 6, "even")) print(even_odd(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "odd"))
"""werf_chart_repo_doit_tasks - Doit Tasks for managing Werf chart repo""" __version__ = '1.0.6' __author__ = 'Ilya Lesikov <ilya@lesikov.com>' __all__ = []
class UnionFind(): def __init__(self, n) -> None: self.par = [-1] * n self.siz = [1] * n # return root of x def root(self, x): if self.par[x] == -1: return x else: self.par[x] = self.root(self.par[x]) return self.par[x] # ret...
""" A custom immutable dictionary data structure """ class CustomImmutableDict(dict): def __getattr__(self, key): try: return self[key] except KeyError as k: raise AttributeError(k) def __setattr__(self, key, value): # self[key] = value return self._imm...
# Attribute Critter # Demonstrates creating and accessing object attributes # Зверюшка с атрибутами # Демонстрирует создание атрибутов объекта и доступ к ним class Critter(object): """Виртуальный питомец""" # """A virtual pet""" def __init__(self, name): # print("A new critter has been born!") ...
class Node: def __init__(self, k, v): self.key = k self.val = v self.pre = None self.nxt = None class LRUCache: def __init__(self, capacity: int): self.store = {} self.curCap = 0 self.cap = capacity self.tail = Node(0, 0) self.head = Nod...
# Lab 5 ''' G=(V,E) Let V be the set v0,v1,v2,... (i.e., with ascending non-negative indices) and E be the set e0,e1,e2,... (i.e., with ascending non-negative indices) ''' class stack: def __init__(self): self.lifo = [] def push(self,ele): self.lifo = self.lifo + [ele] return True def po...
# omnibool.py # https://www.codewars.com/kata/5a5f9f80f5dc3f942b002309/train/python class Omnibool(): def __eq__(self, x): return True if __name__ == "__main__": omnibool = Omnibool() print(omnibool == True and omnibool == False)
def get_test_accounts() -> dict: return { 'development': { 'color': '#388E3C', 'team': 'awesome-team', 'region': 'us-east-1', 'profiles': [ { 'profile': 'developer', 'account': '123495678901', ...
''' Created on 2016年7月27日 @author: Administrator 元组:tuple。tuple和list非常类似,但是tuple一旦初始化就不能修改 ''' classmates = ('Michael', 'Bob', 'Tracy') print(classmates) print(len(classmates)) print(classmates[0]) print(classmates[-1]) #只有1个元素的tuple定义时必须加一个逗号,,来消除歧义 t = (1,) print(t) t = ('a', 'b', ['A', 'B']) t[2][0] = 'X' t[2][1...
def NoC(): paid = int(input()) moneyL = [500, 100, 50, 10, 5, 1] count = 0 leftOver = 1000 - paid for each in moneyL: n = leftOver//each if n > 0: count += n leftOver -= n * each elif n == 0: pass return count print(NoC())
class SourceDto: """Data transfer object class for Source-type Airbyte abstractions""" def __init__(self): self.source_definition_id = None self.source_id = None self.workspace_id = None self.connection_configuration = {} self.name = None self.source_name = None ...
def get_average(g): return sum(g) / len(g) n = int(input()) students_record = {} for _ in range(n): student, grade = input().split() if student not in students_record: students_record[student] = [] students_record[student].append(float(grade)) for s, g in students_record.items(): ave...
names = ["Alan", "Bruce", "Carlos", "David", "Emma"] scores = [90, 80, 85, 92, 81] for name in names: print("hello, %s!" % name)
""" This module takes an adapter as data supplier, pack data and provide data for data iterators """ class ProviderBaseclass(object): """ This is the baseclass of packer. Any other detailed packer must inherit this class. """ def __init__(self): pass def __str__(self): return se...
def insertShiftArray(arr, num): count = len(arr) middle = len(arr) // 2 shift_arr = [] for i in range(count): if i != middle: shift_arr.append(arr[i]) else: if count % 2 == 0: shift_arr.append(num) shift_arr.append(arr[i]) ...
"""Reusable unique item gatherer. Returns unique values with optional list_in and blacklists""" class GatherUnique: """ Reusable unique item gatherer. Returns unique values with optional list_in and blacklists """ def __init__(self): self._header = '' """Optional header to display to...
""" consensys_utils.flask.config ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ App configuration :copyright: Copyright 2017 by ConsenSys France. :license: BSD, see :ref:`license` for more details. """ def set_app_config(app, config=None): """Set application configuration :param app: Flask application ...
# Carve # sigs = [255,214,124,179,233] # msks = [0,9,3,12,6] # Door # sigs = [192,48] # msks = [15,15] # Freestanding # sigs=[0,0,0,0,16,64,32,128,161,104,84,146] # msks=[8,4,2,1,6,12,9,3,10,5,10,5] # Walls sigs=[251,233,253,84,146,80,16,144,112,208,241,248,210,177,225,120,179,0,124,104,161,64,240,128,224,176,242,24...
# -*- coding: utf-8 -*- """ authors: Dawud Hage, Joost Meulenbeld, Joost Dorscheidt and Dennis van der Hoff written for the NN course IN4015 of the TUDelft """ ##### SETTINGS: ##### # Number of epochs to train the network over n_epoch = 0 # Folder where the training superbatches are stored training_folder= 'selecti...
# # PySNMP MIB module ZONE-DEFENSE-MGMT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZONE-DEFENSE-MGMT-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:48:06 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
class ToolStripItemEventArgs(EventArgs): """ Provides data for System.Windows.Forms.ToolStripItem events. ToolStripItemEventArgs(item: ToolStripItem) """ def __getitem__(self, *args): """ x.__getitem__(y) <==> x[y] """ pass @staticmethod def __new__(self, item): ...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. class ClassPropertyDescriptor: def __init__(self, fget): self.fget = fget def __get__(self, obj, klass=None): if klass is None: klass = type(obj) return self.fget.__get__(obj, kl...
print('4. testing integrated scan functions:') print('testing xanes') xanes(erange = [7112-30, 7112-20, 7112+30], estep = [2, 5], harmonic = None, acqtime=0.2, roinum=1, i0scale = 1e8, itscale = 1e8,samplename='test',filename='test')
class CouldNotConfigureException(BaseException): def __str__(self): return "Could not configure the repository." class NotABinaryExecutableException(BaseException): def __str__(self): return "The file given is not a binary executable" class ParametersNotAcceptedException(BaseException): ...
''' 8-10. Sending Messages: Start with a copy of your program from Exercise 8-9. Write a function called send_messages() that prints each text message and moves each message to a new list called sent_messages as it’s printed. After calling the function, print both of your lists to make sure the messages were moved co...
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ n = len(prices) #从图像上来看更好解决,最大盈利是吃到每一个波谷到波峰 if n <= 1: return 0 count = 0 i = 1 while i != n: diff = max((prices[i] - pr...
# # PySNMP MIB module Nortel-MsCarrier-MscPassport-BaseSnmpMIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-BaseSnmpMIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:19:57 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davw...
c = open("__21_d03.txt") lin = c.readlines() ## Part 1 klin = [list([lin[i].split("\n")[0] for i in range(len(lin))][j]) for j in range(len(lin))] k2 = [1 if [klin[jj][len(klin[0])-ii-1] for jj in range(len(lin))].count('1') > [klin[jj][len(klin[0])-ii-1] for jj in range(len(lin))].count('0') else 0 for ii in range(...
# config.py # encoding:utf-8 DEBUG = True JSON_AS_ASCII = False
num = 42 list_of_numbers = [] for i in range(1, num+1): list_of_numbers.append(i) print(list_of_numbers) death = 3 for i in list_of_numbers: if i == num: if i == death: print("XX") else: print(i) elif i < 10: if i == death: print(f"XX", end=" -...
def FizzBuzz(n): if (n % 5) == 0 and (n % 3) == 0: return f'{n} FizzBuzz' if (n % 3) == 0: return f'{n} é fizz' if (n % 5) == 0: return f'{n} buzz' return n print(FizzBuzz(25))
class Solution: def numMovesStonesII(self, stones: List[int]) -> List[int]: def helper(): n = len(stones) if (stones[-2] - stones[0] == n - 2 and stones[-1] - stones[-2] > 2) or (stones[-1] - stones[1] == n - 2 and stones[1] - stones[0] > 2): return 2 dq =...