content
stringlengths
7
1.05M
# -*- coding: utf-8 -*- arabic_to_english_numbers = {u"٠":"0",u"١":"1",u"٢":"2",u"٣":"3",u"٤":"4",u"٥":"5",u"٦":"6",u"٧":"7",u"٨":"8",u"٩":"9"} english_to_arabic_numbers = dict((v,k) for k,v in arabic_to_english_numbers.iteritems()) def get_number_in_arabic(number): strNum = str(number) val = "" for char...
# To use this bot you need to set up the bot in here, # You need to decide the prefix you want to use, # and you need your Token and Application ID from # the discord page where you manage your apps and bots. # You need your User ID which you can get from the # context menu on your name in discord under Copy ID. # if y...
# Constants VERSION = '2.0' STATUS_GREY = 'lair-grey' STATUS_BLUE = 'lair-blue' STATUS_GREEN = 'lair-greeen' STATUS_ORANGE = 'lair-orange' STATUS_RED = 'lair-red' STATUS_MAP = [STATUS_GREY, STATUS_BLUE, STATUS_GREEN, STATUS_ORANGE, STATUS_RED] PROTOCOL_TCP = 'tcp' PROTOCOL_UDP = 'udp' PROTOCOL_ICMP = 'icmp' PRODUCT_UN...
#!/usr/bin/env python3 # https://codeforces.com/problemset/problem/996/A total = int(input()) bills = [100,20,10,5,1] nob = 0 for b in bills: nob += total//b total = total%b if total == 0: break print(nob)
# -*- coding: utf-8 -*- """ Created on Fri Oct 2 11:25:48 2020 @author: Tarun Jaiswal """ ''' a=int(input("A= ")) b=int(input("B= ")) c=int(input("C= ")) d=int(input("D= ")) max=a variablename="a= " if b>max: variablename="b= " max=b if c>max: variablename="c= " max=c if d>max: variablename="d= "...
# Copyright (c) 2020 Anastasiia Birillo class VkCity: def __init__(self, data: dict) -> None: self.id = data['id'] self.title = data.get('title') def __str__(self): return f"[{', '.join(map(lambda key: f'{key}={self.__dict__[key]}', self.__dict__))}]" class VkUser: def __init__(s...
GENDER_VALUES = (('M', 'Male'), ('F', 'Female'), ('TG', 'Transgender')) MARITAL_STATUS_VALUES = (('M', 'Married'), ('S', 'Single'), ('U', 'Unknown')) CATEGORY_VALUES = (('BR', 'Bramhachari'), ('FTT', 'Full Time Teacher'), ...
"""Brain Games. This is my Python course level 1 project. Nothing special, it's just a bundle of mini-games with common CLI. """
input = """ 8 2 2 3 0 0 1 4 2 1 3 2 1 4 2 2 2 3 6 0 1 0 4 3 0 4 c 3 b 2 a 0 B+ 0 B- 1 0 1 """ output = """ COST 0@1 """
# Every non-negative integer N has a binary representation. # For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on. # Note that except for N = 0, there are no leading zeroes in any binary representation. # The complement of a binary representation is the number in binary you get w...
""" LeetCode Problem: 215. Kth Largest Element in an Array Link: https://leetcode.com/problems/kth-largest-element-in-an-array/ Language: Python Written by: Mostofa Adib Shakib """ class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rty...
def solution(S): # write your code in Python 3.6 if not S: return 1 stack = [] for s in S: if s == '(': stack.append(s) else: if not stack: return 0 else: stack.pop() if stack: return 0 return 1
class DistributionDiscriminator: def __init__(self, dataset=None, extractor=None, criterion=None, **kwargs): super().__init__(**kwargs) self.dataset = dataset self.extractor = extractor self.criterion = criterion def judge(self, samples): return self.extractor.extract(samples) def compare(self, fe...
############################################################################## # Parte do livro Introdução à Programação com Python # Autor: Nilo Ney Coutinho Menezes # Editora Novatec (c) 2010-2017 # Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8 # Primeira reimpressão - Outubro/2011 # Segunda reimpressão - ...
class Solution: def stack(self, s: str) -> list: st = [] for x in s: if x == '#': if len(st) != 0: st.pop() continue st.append(x) return st def backspaceCompare(self, S: str, T: str) -> bool: s = self.st...
connections = {} connections["Joj"] = [] connections["Emily"] = ["Joj","Jeph","Jeff"] connections["Jeph"] = ["Joj","Geoff"] connections["Jeff"] = ["Joj","Judge"] connections["Geoff"] = ["Joj","Jebb"] connections["Jebb"] = ["Joj","Emily"] connections["Judge"] = ["Joj","Judy"] connections["Jodge"] = ["Joj","Jebb","Stepha...
class Constants: def __init__(self): pass SIMPLE_CONFIG_DIR = "/etc/simple_grid" GIT_PKG_NAME = "git" DOCKER_PKG_NAME = "docker" BOLT_PKG_NAME = "bolt"
class Solution: def longestPrefix(self, s: str) -> str: pi = [0]*len(s) for i in range(1, len(s)): k = pi[i-1] while k > 0 and s[i] != s[k]: k = pi[k-1] if s[i] == s[k]: k += 1 pi[i] = k print('pi is...
def _update_doc_distribution( X, exp_topic_word_distr, doc_topic_prior, max_doc_update_iter, mean_change_tol, cal_sstats, random_state, ): is_sparse_x = sp.issparse(X) n_samples, n_features = X.shape n_topics = exp_topic_word_distr.shape[0] if random_state: doc_topic...
''' Almost everyone in the world knows about the ancient game Chess and has at least a basic understanding of its rules. It has various units with a wide range of movement patterns allowing for a huge number of possible different game positions (for example Number of possible chess games at the end of the n-th plies. ...
def read_convert(input: str) -> list: dict_list = [] input = input.split("__::__") for lines in input: line_dict = {} line = lines.split("__$$__") for l in line: dict_value = l.split("__=__") key = dict_value[0] if len(dict_value) == 1: ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {TreeNode} root # @return {integer[]} def preorderTraversal(self, root): self.preorder = [] self.trave...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"websites_url": "01-training-data.ipynb", "m": "01-training-data.ipynb", "piece_dirs": "01-training-data.ipynb", "assert_coord": "01-training-data.ipynb", "Board": "01-trai...
n = int(input()) i = 5 while i > 0: root = 1 while root ** i < n: root = root + 1 if root ** i == n: print(root, i) i = i - 1
# -*- coding: utf-8 -*- # Authors: Y. Jia <ytjia.zju@gmail.com> """ Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. https://leetcode.com/problems/maximal-square/description/ """ class Solution(object): def maximalSquare(self, matrix): "...
a = [1, 2, 3, 4, 5] print(a[0] + 1) #length of list x = len(a) print(x) print(a[-1]) #splicing print(a[0:3]) print(a[0:]) b = "test" print(b[0:1])
def extgcd(a, b): """solve ax + by = gcd(a, b) return x, y, gcd(a, b) used in NTL1E(AOJ) """ g = a if b == 0: x, y = 1, 0 else: x, y, g = extgcd(b, a % b) x, y = y, x - a // b * y return x, y, g
class Solution(object): def toGoatLatin(self, sentence): """ :type sentence: str :rtype: str """ count = 0 res = [] for w in sentence.split(): count += 1 if w[0].lower() in ['a', 'e', 'i', 'o', 'u']: res.appen...
class Solution: def subarraySum(self, nums: List[int], k: int) -> int: count = 0 prefix_sum = 0 dic = {0: 1} for i in range(len(nums)): prefix_sum += nums[i] if prefix_sum - k in dic: count += dic[prefix_sum - k] if prefix_sum ...
""" https://leetcode.com/problems/detect-capital/ Given a word, you need to judge whether the usage of capitals in it is right or not. We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA". All letters in this word are not capita...
n = int(input()) a = list(map(int,input().split())) q,w=0,0 for i in a: if i ==25:q+=1 elif i==50:q-=1;w+=1 else: if w>0:w-=1;q-=1 else:q-=3 if q<0 or w<0:n=0;break if n==0:print("NO") else:print("YES")
datas = { 'style' : 'boost', 'prefix' : ['boost','simd'], 'has_submodules' : True, }
# This script was crated to calculate my net worth across all my accounts, including crypto wallets. I track my fiat # currency using Mint. The majority of my crypto wallets are not able to sync with Mint. With this script, I answer a # few questions regarding wallet balances, then my change in net worth (annual a...
# # PySNMP MIB module CISCO-ITP-GSP2-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ITP-GSP2-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:46:26 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
""" datos de entrada presupuesto-->p-->float datos de salida presupuesto ginecologia-->pg-->float presupuesto traumatologia-->pt-->float presupuesto pediatria-->pp-->foat """ #entradas p=float(input("digite el presupuesto total:")) #caja negra pg=p*0.4 pt=p*0.3 pp=p*0.3 #salidas print("el presupue...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 26 15:46:21 2020 @author: bezbakri """ """ |-------------------------------------------| | Problem 6: Write a program to find the | | factorial of a number | |-------------------------------------------| | Approach: ...
entries = [] def parse(line): return list(map(lambda x: tuple(x.strip().split(' ')), line.strip().split('|'))) with open("input") as file: entries = list(map(parse, file)) count = 0 total = 0 for segments, outputs in entries: dict = {} for segment in segments: length = len(segment) ...
#! /usr/bin/env python2.7 """ * Copyright (c) 2016 by Cisco Systems, Inc. * All rights reserved. Pathman init file Niklas Montin, 20141209, niklas@cisco.com odl_ip - ip address of odl controller odl_port - port for odl rest on controller log_file - file to write log to - lev...
# # Exercício Python 084: Faça um programa que leia nome e peso de várias pessoas,guardando tudo em uma lista. No final, mostre: # A) Quantas pessoas foram cadastradas. ...
# Paso 1: Código para introducir valores en la lista lista = [] contenido = 0 num = 0 while contenido != "": contenido = input("Introduce palabras en la lista, de lo contrario pulsa Enter: ") if contenido != "": lista.append(str(contenido)) print (lista[:]) #paso 2: crear una funcion para el menu de...
a = [1, 2, 3, 4, 5] print(a) a.clear() print(a)
#!/usr/bin/python n = int(input()) for i in range(0, n): row = input().strip() for j in range(0, n): if row[j] == 'm': robot_x = j robot_y = i if row[j] == 'p': princess_x = j princess_y = i for i in range(0, abs(robot_x - princess_x)...
class Solution: def reverseVowels(self, s: str) -> str: vows = [ch for ch in s[::-1] if ch.lower() in "aeiou"] chars = list(s) x = 0 for i, ch in enumerate(chars): if ch.lower() in "aeiou": chars[i] = vows[x] x += 1 return "".join(c...
## 合并两个有序链表 # 迭代法 时间:O(n) 空间:O(1) class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: preHead = ListNode(-1) prev = preHead while l1 and l2: if l1.val < l2.val: prev.next = l1 l1 = l1.next else: ...
def defaultParamSet(): class P(): def __init__(self): # MAP-Elites Parameters self.nChildren = 2**7 self.mutSigma = 0.1 self.nGens = 2**8 # Infill Parameters self.nInitialSamples = 50 self.nAdditionalSamples = 10 ...
valor = float(input("Qual o valor do produto?")) print(" ") print(''' -=-=-=-=-=-= FORMAS DE PAGAMENTO =-=-=-=-=-=- 1 - À vista no dinheiro/cheque: desconto 10% 2 - À vista no cartão: desconto 5% 3 - Em até 2x no cartão: preço valor_normal 4 - 3 x ou mais no cartão: juros 20%''') print("-"*45) print(" ") condicao_pagam...
def LCS_solution(X, Y, L): """Return the longest substring of X and Y, given LCS table L""" solution = [] j,k = lne(X), len(Y) while L[j][k] > 0: # common characters remain if X[j-1] == Y[k-1]: solution.append(X[j-1]) j -= 1 k -= 1 elif L[j-1][k] >= l[j][k-1]: j -= 1 else: k -= 1 return ""...
class JSIError(Exception): """JSIError wraps the message in html comments to be placed safely into the webpage. """ def __init__(self, message, data={}): # Wrap the message in an html comment. message = "<!-- [JSInclude Error] %s %s -->" % ( message, data.items() ...
def fatorial(n): f = 1 for i in range(n, 0, -1): f *= i return f def dobro(n): return n*2 def triplo(n): return n*3
class Solution: # @return a list of integers def getRow(self, rowIndex): tri = [1] for i in range(rowIndex): for j in range(len(tri) - 2, -1, -1): tri[j + 1] = tri[j] + tri[j + 1] tri.append(1) return tri
# # PySNMP MIB module WWP-LEOS-LLDP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-LEOS-LLDP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:31:15 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'CYX' configs = { 'server': { 'host': '0.0.0.0', 'port': 9090 }, 'qshield': { 'jars': '/home/hadoop/qshield/opaque-ext/target/scala-2.11/opaque-ext_2.11-0.1.jar,/home/hadoop/qshield/data-owner/target/scala-2.11/data-owner_2.11-0.1.jar', 'master': ...
# # PySNMP MIB module VLAN (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VLAN # Produced by pysmi-0.3.4 at Mon Apr 29 21:27:41 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Oc...
def solution(A, B): tmp = '{0:b}'.format(A * B) return list(tmp).count('1')
""" Add the scientific notation to the axes label Adapted from: https://peytondmurray.github.io/coding/fixing-matplotlibs-scientific-notation/# """ def label_offset(ax, axis=None): if axis == "y" or not axis: fmt = ax.yaxis.get_major_formatter() ax.yaxis.offsetText.set_visible(False) set_...
class Action: """ This is the Action class. It is already in the test cases, so please don't put it in your solution. """ def __init__(self, object_, transaction, is_write): self.object_ = object_ self.transaction = transaction self.is_write = is_write def __str__(self): return f"Action({sel...
class WebPermissionAttribute(CodeAccessSecurityAttribute, _Attribute): """ Specifies permission to access Internet resources. This class cannot be inherited. WebPermissionAttribute(action: SecurityAction) """ def CreatePermission(self): """ CreatePermission(self: WebPermissionAttrib...
class Pares(list): # <- estou passando pra minha classe as funções do objeto list como na aluma de Django quando usasva model def append(self, inteiro): # <- SobreEscrevendo o método append para que funciona da minha maneira! if not isinstance(inteiro,int): # <- Declarando minha variavél e deterni...
class Pagination: def __init__(self, offset, limit): self._offset = offset self._limit = limit def clean_offset(self): return self._offset >= 0 def clean_limit(self): return self._limit > 0 def clean(self): return self.clean_offset() and self.clean_limit() ...
# Copyright (c) 2018-2021 Kaiyang Zhou # SPDX-License-Identifier: MIT # # Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # __version__ = '1.2.3'
# # PySNMP MIB module E7-Fault-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/E7-Fault-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:58:57 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
def steps(number:int) -> int: if number <= 0: raise ValueError("Input must be a positive integer") steps = 0 while number != 1: if number % 2 == 0: number = int(number / 2) else: number = int(number * 3) + 1 steps += 1 return steps
class Solution: def arrangeCoins(self, n: int) -> int: k = 0 while n > 0: k += 1 n -= k return k if not n else k - 1
coordinates_E0E1E1 = ((127, 91), (127, 93), (128, 92), (128, 94), (128, 142), (129, 93), (129, 95), (129, 134), (129, 135), (129, 141), (129, 142), (130, 94), (130, 133), (130, 136), (130, 140), (130, 142), (131, 95), (131, 102), (131, 133), (131, 135), (131, 138), (131, 139), (131, 142), (132, 96), (132, 98), (132, ...
l=[] n=int(input("enter the elements:")) for i in range(0,n): l.append(int(input())) i=0 for i in range(len(l)): for j in range(i+1,len(l)): if l[i]>l[j]: l[i],l[j]=l[j],l[i] print("sorted list is",l)
class AbstractImporter(): """ Abstract class describing a file importer """ def __init__(self, file_string, file_name=None): self.file_string = file_string self.file_name = file_name def import_data(self): raise NotImplementedError("AbstractImporter is abstract.")
# Modifying 'value_error_numbers.py' program. # Using a while loop so that the user can continue to enter numbers even if # they make a mistake by entering a non-numerical input value. print("Enter two numbers, and we will add them together.") print("Enter 'q' to quit.") while True: first_number = input("\nFirst...
# Задача 3. Вариант 50. # Напишите программу, которая выводит имя "Саид-Мурадзола Садриддин", и запрашивает его псевдоним. #Программа должна сцеплять две эти строки и выводить полученную строку, #разделяя имя и псевдоним с помощью тире. # Alekseev I.S. # 15.05.2016 name = "Саид-Мурадзола Садриддин" print("Герой наше...
######################################### # Servo01_stop.py # categories: intro # more info @: http://myrobotlab.org/service/Intro ######################################### # uncomment for virtual hardware # Platform.setVirtual(True) # Every settings like limits / port number / controller are saved after initial use #...
def anonymize(person_names, should_anonymize): """ Creates a map of person names. :param person_names: List of person names :param should_anonymize: If person names should be anonymized :return: """ person_name_dict = dict() person_counter = 1 for person_name in person_names: ...
tout = np.linspace(0, 10) k_vals = 0.42, 0.17 # arbitrary in this case y0 = [1, 1, 0] yout = odeint(rhs, y0, tout, k_vals) # EXERCISE: rhs, y0, tout, k_vals
#Faça um Programa que leia três números e mostre o maior deles. valor1 = float(input("Digite o primeiro valor: ")) valor2 = float(input("Digite o segundo valor: ")) valor3 = float(input("Digite o terceiro valor: ")) valores = [valor1, valor2, valor3] print(f'O maior número é {max(valores)}')
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"Hline": "00_core.ipynb", "ImageBuffer": "00_core.ipynb", "grid_subsampling": "00_core.ipynb", "getDirctionVectorsByPCA": "00_core.ipynb", "pointsProjectAxis": "00_core.ipy...
#coding:utf-8 # 题目:请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母。 Monday Tuesday Wednesday Thursday Friday Saturday Sunday
""" 给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。 示例 1: 输入: 2 输出: 1 解释: 2 = 1 + 1, 1 × 1 = 1。 示例 2: 输入: 10 输出: 36 解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。 说明: 你可以假设 n 不小于 2 且不大于 58。 """ class Solution(object): def integerBreak(self, n): """ :type n: int :rtype: int """ # ...
# coding=utf-8 class Ranker(object): """ Сортировка ключевых слов. Можно указать свою функцию для вычисления веса ключевого слова. """ def __call__(self, terms, weight=None): if weight is None: # По умолчанию ключевые слова упорядочиваются по количеству употреблений, затем - по коли...
# faça um mini-sistema que otilize o interactive help. O usuário vai digitar a fução/lib e o manual vai aparecer. Acaba quando digitar 'fim'. Utilize cores # não tive paciência pra ficar colorindo 🥱😴 def ajuda(metodo): help(metodo) print('~'*10) print(f'{"PyHelp":^10}') print('~'*10) while True: ...
# Single Line Comment print('this is code') # another comment print('another piece of code') """ Multiple Line Comments this is avery big function it retrieves data it is very important REPL Repeat Evaluate Print Loop """
class Verse: """A class used to represent a verse from the bible.""" def __init__(self, text: str, number: int): """ Initialize a `Verse` object. :Parameters: - `text`: sting containing the text of the verse. - `number`: integer with the number of the verse. ...
# Enter your code here. Read input from STDIN. Print output to STDOUT a = list(map(int, input().split())) happy = 0 n = a[0] m = a[1] b = list(map(int, input().split())) b = b[0:n] c = list(map(int, input().split())) c = c[0:m] d = list(map(int, input().split())) d = d[0:m] for i in c: if b.count(i)!= 0: ha...
# Small alphabet w using fucntion def for_w(): """ *'s printed in the shape of w """ for row in range(5): for col in range(9): if col% 8 ==0 or row+col ==4 or col -row ==4: print('*',end=' ') else: print(' ',end=' ') print() def...
#!/usr/bin/python # -*- coding: utf-8 -*- # === About ============================================================================================================ """ readEnteredText.py Copyright © 2017 Yuto Mizutani. This software is released under the MIT License. Version: 1.0.0 TranslateAuthors: Yuto Mizutani ...
#Embedded file name: ACEStream\Video\defs.pyo PLAYBACKMODE_INTERNAL = 0 PLAYBACKMODE_EXTERNAL_DEFAULT = 1 PLAYBACKMODE_EXTERNAL_MIME = 2 OTHERTORRENTS_STOP_RESTART = 0 OTHERTORRENTS_STOP = 1 OTHERTORRENTS_CONTINUE = 2 MEDIASTATE_PLAYING = 1 MEDIASTATE_PAUSED = 2 MEDIASTATE_STOPPED = 3 BGP_STATE_IDLE = 0 BGP_STATE_PREBU...
src = Split(''' starterkitgui.c ''') component = aos_component('starterkitgui', src) component.add_comp_deps('kernel/yloop', 'tools/cli') component.add_global_macros('AOS_NO_WIFI')
""" Program for Print Number series without using any loop Problem – Givens Two number N and K, our task is to subtract a number K from N until number(N) is greater than zero, once the N becomes negative or zero then we start adding K until that number become the original number(N). Note : Not allow to use any loop. E...
def saludar(): return "Hola mundo" saludar() print(saludar()) print('----------') m = saludar() print(m) print('------------') def saludo(nombre, mensaje='hola '): print(mensaje, nombre) saludo('roberto')
# Not finished rows = int(input()) array = [[0 for x in range(3)] for y in range(rows)] for i in range(rows): line = [float(i) for i in input().split()] for j in range(3): array[i][j] = int(line[j]) totalcount = 0 for k in range(rows): counter=array[k][0] +array[k][1] +array[k][2] if(counter >= ...
""" Escreva um programa que leia a velocidade de um carro. se ele ultrapassar 80km/h, mostre uma mensagem dizendo que ele foi multado A multa vai custar R$7,00 por km acima do limite """ ve = int(input('Informe a velocidade que passou pelo radar: ')) if ve > 80: multa = (ve - 80) * 7 print(f'Você será multado...
def find_ranges(nums): if not nums: return [] first = last = nums[0] ranges = [] def append_range(first, last): ranges.append('{}->{}'.format(first, last)) for num in nums: if abs(num - last) > 1: append_range(first, last) first = num last = num # Remaining append_range(fi...
''' def find(lf_link,l1,l2): lf = [lf_link,[]] l1_title = l1[1] l2_title = l2[1] #将lf_link中的链接按照索引寻找到对应的标题和文本,如果在l1_title与l2_title冲突,则选择字数多者,并输出[链接,标题] for i in lf_link: if i in l1_title: lf[1].append([i,l1_title[l1_title.index(i)]]) elif i in l2_title: ...
# 77. Combinations # Time: k*nCk (Review: nCk combinations each of length k) # Space: k*nCk class Solution: def combine(self, n: int, k: int) -> List[List[int]]: if n==0: return [] if k==0: return [[]] if k==1: return [[i] for i in range(1,n+1)] ...
""" PASSENGERS """ numPassengers = 3190 passenger_arriving = ( (5, 7, 2, 5, 1, 0, 5, 10, 5, 3, 2, 0), # 0 (6, 14, 4, 3, 1, 0, 3, 11, 5, 4, 2, 0), # 1 (3, 6, 6, 4, 3, 0, 7, 7, 5, 3, 1, 0), # 2 (2, 1, 6, 3, 1, 0, 7, 8, 10, 3, 2, 0), # 3 (4, 4, 6, 2, 1, 0, 4, 6, 7, 2, 2, 0), # 4 (5, 12, 7, 4, 1, 0, 12, 7, 2,...
class Animation: def __init__(self, anim_type): self.anim_type = anim_type self.frames = [] self.point = 0 self.forward = True self.speed = 0 self.dt = 0 def add_frame(self, frame): self.frames.append(frame) def get_frame(self, dt): if self...
""" 面试题 59(二):队列的最大值 题目:请定义一个队列并实现函数 max 得到队列的最大值, 要求函数 max,push_back pop_front 的时间复杂度都是 O(1) """ class QueueMax: def __init__(self): self.data = [] self.maxes = [] def push_back(self, x): while self.maxes and x > self.maxes[-1]: self.maxes.pop() self.data.appe...
class DataGridView( Control, IComponent, IDisposable, IOleControl, IOleObject, IOleInPlaceObject, IOleInPlaceActiveObject, IOleWindow, IViewObject, IViewObject2, IPersist, IPersistStreamInit, IPersistPropertyBag, IPersistStorage, IQuickActivate,...
# return masked string def maskify(cc): if len(cc) < 5: return cc return '#' * int(len(cc)-4) + cc[-4:]
""" Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000. Example 1: Input: "bbbab" Output: 4 One possible longest palindromic subsequence is "bbbb". Example 2: Input: "cbbd" Output: 2 One possible longest palindromic subsequence is "bb". S...
class Solution(object): def topKFrequent(self, words, k): """ :type words: List[str] :type k: int :rtype: List[str] """ counter = collections.Counter(words) return [key for _, key in heapq.nsmallest(k, [(-cnt, key) for key, cnt in counter.items()])]
# This function gives number of notes required and remining in the database def number_of_notes(amount, c_value): global atm_amount multipal = amount // int(c_value) x = denomination[c_value] - multipal y = x + multipal updated_multi = None for i in range(multipal): if y >= 0 and denomi...
modules = dict() def register(module_name): def decorate_action(func): if module_name in modules: modules[module_name][func.__name__] = func else: modules[module_name] = dict() modules[module_name][func.__name__] = func return func return de...