content
stringlengths
7
1.05M
EXCHANGE_MAX_NAME_LENGTH = 100 EXCHANGE_MAX_DESCRIPTION_LENGTH = 1000 FOLDER_FORBIDDEN_CHARS = {'/', '\\', ':', '*', '"', '<', '>', '?', '|'} FOLDER_MAX_NAME_LENGTH = 60 def validate_folder(folder): if 'name' not in folder: raise Exception('No name') for c in VALIDATE_FOLDER_FORBIDDEN_CHARS: ...
class OperationStaResult(object): def __init__(self): self.total = None self.wait = None self.processing = None self.success = None self.fail = None self.stop = None self.timeout = None def getTotal(self): return self.total def setTotal(self...
CHEESES = { "brie": ( "Brie", "France", "Brie is a soft cow's-milk cheese named after Brie, the French region from which it originated.", ), "valdeon": ( "Valdeón", "Spain", " A Spanish blue cheese from León. It is wrapped in sycamore leaves before being sent ...
""" This very high-level module determines/implements the specific behavior of the "standard" Necrobot running on the Crypt of the Necrobot server. Package Requirements -------------------- botbase util daily race stats user Dependencies ------------ mainchannel botbase/ ...
def yield_test(n): for j in range(n): yield call(j) print("j=",j) #做一些其它的事情 print("do something.") print("end.") def call(j): return j*2 #使用for循环 # for i in yield_test(5): # print(i,",") def createGenerator(): mylist = range(3) for i in mylist: yield i*i m...
# Copyright 2018 Google LLC # # 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 to in writing, s...
""" Project: algorithms-exercises-using-python Created by robin1885@github on 17-2-20. """ def anagram_solution3(s1, s2): """ @rtype : bool @param s1: str1 @param s2: str2 @return: True or False """ pass
nome = input('Digite o nome do funcionário: ') sal = float(input('Digite o salário do funcionário: ')) if (sal > 1250): aumento = sal * 1.1 print('O funcionário {} receberá o novo salário no valor de R$ {:.2f}'.format(nome, aumento)) else: aumento = sal * 1.15 print('O funcionário {} receberá o novo...
# Medium # https://leetcode.com/problems/next-greater-element-ii/ # TC: O(N) # SC: O(N) class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: nums = nums + nums stack = [] out = [-1 for _ in nums] for index, num in enumerate(nums): while len(stack) ...
days = ["Mon", "Thu", "Wed", "Thur", "Fri"] # list(mutable sequence) print(days) days.append("Sat") days.reverse() print(days)
class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() n = len(nums) ans = [] for i in range(0, n-2): if i > 0 and nums[i] == nums[i-1]: continue j,k ...
"""Custom exceptions for money operations""" # pylint: disable=missing-docstring class InvalidAmountError(ValueError): def __init__(self): super().__init__("Invalid amount for currency") class CurrencyMismatchError(ValueError): def __init__(self): super().__init__("Currencies must match") ...
# -*- coding: utf-8 -*- """ file: gromacs_ti.py Functions for setting up a Gromacs based Thermodynamic Integration (TI) calculation. """
class StreamPredictorConsumer(object): def __init__(self, name, algorithm=None, **kw): self.algorithm = algorithm self.name = name self.run_count = 0 self.runs = [] async def handle(self, payload): self.run_count += 1 try: results, err = await self.a...
group_template_tag_prefix = 'DRKNS_GROUP_TEMPLATE_' # BEGIN / END unit_template_tag_prefix = 'DRKNS_UNIT_TEMPLATE_' # BEGIN / END groups_tag = 'DRKNS_GROUPS' group_units_tag = 'DRKNS_GROUP_UNITS' group_name_tag = 'DRKNS_GROUP_NAME' unit_name_tag = 'DRKNS_UNIT_NAME' dependency_groups_names_tag = 'DRKNS_DEPENDENCY_G...
#!/usr/bin/env python3 def main(): for i in range(1,11): for j in range(1,11): if(j==10): print(i*j) else: print(i*j, end=" ") if __name__ == "__main__": main()
def require(*types): ''' Return a decorator function that requires specified types. types -- tuple each element of which is a type or class or a tuple of several types or classes. Example to require a string then a numeric argument @require(str, (int, long, float)) will do the tric...
def try_if(l): ret = 0 for x in l: if x == 1: ret += 2 elif x == 0: ret += 4 else: ret -= 2 return ret try_if([0, 1, 0, 1, 2, 3])
class Solution(object): def XXX(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ i, j, k = 0, len(nums) - 1, 0 while k < len(nums): if nums[k] == 0 and k > i: nums[k], nums[i] = n...
class World: def __init__(self): pass def get_state(self): pass def execute_action(self,a): pass class GameTree: class GameNode: def __init__(self, state, action, par): self.state = state self.action = action self....
namespace = '/map' routes = { 'getAllObjectDest': '/', }
# 최고의 집합 def solution(n, s): if s // n < 1: return [-1] number = s // n left = s % n arr = [number] * n for i in range(n - 1, n - 1 - left, -1): arr[i] += 1 return arr if __name__ == "__main__": n = 2 s = 1 print(solution(n, s))
#Creacion de clase padre class Vehiculo: def __init__(self, color, ruedas): self.color = color self.ruedas = ruedas def __str__(self): return "Color : "+self.color+" ruedas: "+str(self.ruedas) #creacion de una clase hija/o class Coche(Vehiculo): def __init__(self, color, ruedas, v...
""" Exercise 1 Many of the built-in functions use variable-length argument tuples. For example, max and min can take any number of arguments: >>> max(1,2,3) 3 But sum does not. >>> sum(1,2,3) TypeError: sum expected at most 2 arguments, got 3 Write a function called sumall that takes any number of argu...
# Validar uma string def valida_str(texto, min, max): tam = len(texto) if tam < min or tam > max: return False else: return True # Programa Principal texto = input('Digite um string (3-15 caracteres): ') while valida_str(texto, 3, 15): texto = input('Digite uma string (3-15 caracteres)...
# # PySNMP MIB module HH3C-STACK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-STACK-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:29:46 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
l1=[1,2,3,4,5,6,7,8,9,10] l2=list(map(lambda n:n*n,l1)) print('l2:',l2) l3=list((map(lambda n,m:n*m,l1,l2)))#map function can take more than one sequence argument print('l3:',l3) #if the length of the sequence is not equal then function will perform till same length l3.pop() print('popped l3:',l3) l4=list(map(lambda n,...
{ 'targets': [ { 'target_name': 'gpiobcm2835nodejs', 'sources': [ 'src/gpiobcm2835nodejs.cc' ], "cflags" : [ "-lrt -lbcm2835" ], 'conditions': [ ['OS=="linux"', { 'cflags!': [ '-lrt -lbcm2835', ], ...
# -*- coding: utf-8 -*- # @Author: 何睿 # @Create Date: 2018-11-12 14:46:42 # @Last Modified by: 何睿 # @Last Modified time: 2018-11-12 14:46:42 class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def middleNode(self, head): ...
class SpekulatioError(Exception): pass class FrontmatterError(SpekulatioError): pass
class Sql: make_itemdb = ''' CREATE TABLE IF NOT EXISTS ITEMDB ( ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, PRICE REAL, REGDATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ''' insert_itemdb = ''' INSERT INTO ITEMDB (NAME, PRICE) VALUES ...
def getbounds(img): return tuple([min((si[i] for si in img)) for i in range(2)]), \ tuple([max((si[i] for si in img)) for i in range(2)]) def enhance(img, setval, algo): bounds = getbounds(img) offsets = ((1, 1), (0, 1), (-1, 1), (1, 0), (0, 0), (-1, 0), (1, -1), (0, -1), (-1, -1)) overhang...
class TrieNode: def __init__(self): self.children = collections.defaultdict(TrieNode) self.is_word = False class Solution: def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: root = TrieNode() for word in words: cur = root for ch i...
def rotate(matrix): #code here for i in range(len(matrix)): listt = list(reversed(matrix[i])) for j in range(len(matrix[i])): matrix[i][j] = listt[j] # print(matrix) for i in range(len(matrix)): for j in range(i, len(matrix[i])): matrix[i][j], matrix...
# Like list we can have set and dict comprehensions. # Set comprehensions. # The below set is not ordered. square_set = {num * num for num in range(11)} print(square_set) # Dict Comprehension dict_square = {num: num * num for num in range(11)} print(dict_square) # Use f"string to create a set and dict f_string_squar...
## -*- encoding: utf-8 -*- """ This file (./sol/linalg_doctest.sage) was *autogenerated* from ./sol/linalg.tex, with sagetex.sty version 2011/05/27 v2.3.1. It contains the contents of all the sageexample environments from this file. You should be able to doctest this file with: sage -t ./sol/linalg_doctest.sage It is a...
#ANSI Foreground colors black = u"\u001b[30m" red = u"\u001b[31m" green = u"\u001b[32m" yellow = u"\u001b[33m" blue = u"\u001b[34m" magneta = u"\u001b[35m" magenta = magneta cyan = u"\u001b[36m" white = u"\u001b[37m" #ANSI Background colors blackB = u"\u001b[40m" redB = u"\u001b[41m" greenB = u"\u001b[42m" yellowB = u"...
LAB_STYLE = """ body { --jp-layout-color0: transparent; --jp-layout-color1: transparent; --jp-layout-color2: transparent; --jp-layout-color3: transparent; --jp-cell-editor-background: transparent; --jp-border-width: 0; --jp-border-color0: transparent; ...
#!/usr/bin/env python """ Find the greatest product of five consecutive digits in the 1000-digit number """ num = '\ 73167176531330624919225119674426574742355349194934\ 96983520312774506326239578318016984801869478851843\ 85861560789112949495459501737958331952853208805511\ 125406987471585238630507156932909632952274430...
athlete_1 = int(input()) athlete_2 = int(input()) athlete_3 = int(input()) podium = [] if (athlete_1 < athlete_2 and athlete_1 < athlete_3): podium.append(1) if(athlete_2 < athlete_3): podium.append(2) podium.append(3) else: podium.append(3) podium.append(2) elif (athlete...
Number = int(input("\nPlease Enter the Range Number: ")) First_Value = 0 Second_Value = 1 for Num in range(0, Number): if (Num <= 1): Next = Num else: Next = First_Value + Second_Value First_Value = Second_Value Second_Value = Next print(Next)
# -*- coding: utf-8 -*- """ aomie ~~~~~ aomie is a simple Python package to ease the handling of Iberian electricity market data published by the market operator OMIE. :copyright: © 2019 by Guillermo Lozano Branger. :license: MIT, see LICENSE for more details. """ __version__ = '0.0.0'
def Spell_0_10(n): refTuple = ("zero","one","two","three","four","five", "six","seven","eight","nine","ten") return refTuple[n] print(1, " is spelt as ", Spell_0_10(1)) for i in range(11): print("{} is spelt as {}".format(i,Spell_0_10(i))) for i in range (-9,0,1): print("{} i...
"""Registry for behavior configurables.""" _BEHAVIOR_LIST = [] def behaviors(): """Yields the currently registered behaviors in the order in which they were defined.""" for name, cls, brief, level in _BEHAVIOR_LIST: yield name, cls, brief, level def behavior(name, brief, level=0): """Decorato...
"""excpetions.py""" class GTMManagerException(Exception): """GTMManagerException""" pass class AuthError(GTMManagerException): pass class VariableNotFound(GTMManagerException): """VariableNotFound""" def __init__(self, variable_name, parent): super(VariableNotFound, self).__init__() ...
#Plugin to handle dialogues for men and women #Written by Owain for Runefate #31/01/18 #I want to give every spawned NPC a use, and not do what most servers have with useless non functioning NPCs. #Even small things such as NPC dialogues can help make Runefate more rounded and enjoyable. npc_ids = [3078, 3079] dialo...
class ReferenceDummy(): def __init__(self, *args): return def _to_dict(self, *args): return "dummy"
# #1 # def make_negative( number ): # return number if number < 0 else - number # #2 def make_negative( number ): return -abs(number)
# This class parses a gtfs text file class Reader: def __init__(self, file): self.fields = [] self.fp = open(file, "r") self.fields.extend(self.fp.readline().rstrip().split(",")) def get_line(self): data = {} line = self.fp.readline().rstrip().split(",") for e...
# Cajones es una aplicacion que calcula el listado de partes # de una cajonera # unidad de medida en mm # constantes hol_lado = 13 # variables h = 900 a = 600 prof_c = 400 h_c = 120 a_c = 200 hol_sup = 20 hol_inf = 10 hol_int = 40 hol_lateral = 2 esp_lado = 18 esp_sup = 18 esp_inf = 18 esp...
#!/usr/bin/env python class TwitterError(Exception): """Base class for Twitter errors""" @property def message(self): '''Returns the first argument used to construct this error.''' return self.args[0] class PythonTwitterDeprecationWarning(DeprecationWarning): """Base class for pytho...
def middle(t): '''Write a function called middle that takes a list and returns a new list that contains all but the first and last elements''' return t[1: -1] if __name__ == '__main__': t = [1, 2, 30, 400, 5000] print(t) print(middle(t))
print('\033[34m^=\033[m' * 27) print('Conversor de decimal para binário, octol e hexadecimal') print('\033[34m=^\033[m' * 27) print("""Opção [1] Binário Opção [2] Octal Opção [3] Hexadecimal""") print('\033[34m^=\033[m' * 27) num = int(input('Digite o valor que deseja converter: ')) op = int(input('Digite a opção de co...
""" File: hailstone.py ----------------------- This program should implement a console program that simulates the execution of the Hailstone sequence, as defined by Douglas Hofstadter. Output format should match what is shown in the sample run in the Assignment 2 Handout. """ def main(): """ This program will...
print("Size of list"); list1 = [1,23,5,2,42,526,52]; print(list1); print(len(list1));
#!/usr/bin/env python # # Copyright 2015 British Broadcasting Corporation # # 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 requ...
FANARTTV_PROJECTKEY = '' TADB_PROJECTKEY = '' TMDB_PROJECTKEY = '' THETVDB_PROJECTKEY = ''
# Regards, Takeda Shingen (Sengoku Era) Questline | Near Momiji Hills 1 (811000001) # Author: Tiger TAKEDA = 9000427 if "1" in sm.getQRValue(58901): # Regards, Takeda Shingen sm.setSpeakerID(TAKEDA) sm.flipDialogue() sm.sendNext("Good, you're here! I was about to pick another fight") sm.flipDialogue...
array = [3,5,-4,8,11,-1,6] targetSum = 10 def twoNumberSum(array, targetSum): #for loop to iterate the array for i in range(len(array) - 1): firstNum = array[i] for j in range(i + 1, len(array)): secondNum = array[j] if firstNum + secondNum == targetSum: r...
def can_create_a_Fibonacci_number(int_1, int_2): """ This function checks to see if the sum, difference, product, or module of the two inputs product a Fibonacci number. 1, 1, 2, 3, 5, 8, 13, 21, 34 ... The two inputs are assumed to be integers """ sum = int_1 + int_2 product = int_1 ...
""" The constants module contains some numerical constants for use in the module. Note that modifying these may yield unpredictable results. """ # Force zero values to this amount, for numerical stability MIN_SITE_FRACTION = 1e-12 MIN_PHASE_FRACTION = 1e-12 # Phases with mole fractions less than COMP_DIFFERENCE_TOL apa...
""" The set-covering problem Book: Grokking Algorithms Chapter 8: Greedy Algorithms Suppose you're starting a radio show. You want to reach listeners in all 50 states. You have to decide what stations to play on to reach all those listeners. It costs money to be on each station, so you're trying to minimize the number...
#!/usr/bin/env python major_version = 0 minor_version = 0 patch_version = 10 def format_version(): return "{0}.{1}.{2}".format(major_version, minor_version, patch_version)
#Um gerenciador de pagementos simples preco = float(input('Qual o valor da compra? ')) pagamento = int(input("""Qual será a forma de pagamento? Digite 0 para pagamento à vista no dinheiro ou cheque Digite 1 para pagamento à vista no cartão Digite 2 para pagamento parcelado em até 2x Digite 3 para pagamento parcelado ...
# BIP39 Wordlist Validator - A tool to validate BIP39 wordlists in Latin # languages. # bip39validator/data_structs.py: Program data structures. # Copyright 2020 Ali Sherief # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Softw...
class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: """ Ideas: 1. Count the frequencies, sort and take top k -> O(N) + O(N log N) 2. heapq.nlargest -> O(N) + O(N log N) 3. Count the frequencies and keep only top k elements in the heap -> ...
#!/bin/python3 FAVORITE_NUMBER = 1362 GRID = [[0 for j in range(50)] for i in range(50)] TARGET = (31, 39) def check_wall(coordinates): x, y = coordinates if x < 0 or y < 0 or x >= 50 or y >= 50: return False elif GRID[x][y] != 0: return False current = x * x + 3 * x + 2 * x * y + ...
# Marcelo Campos de Medeiros # ADS UNIFIP 2020.1 # Patos-PB 03/04/2020 ''' Leia um valor inteiro correspondente à idade de uma pessoa em dias e informe-a em anos, meses e dias Obs.: apenas para facilitar o cálculo, considere todo ano com 365 dias e todo mês com 30 dias. Nos casos de teste nunca haverá uma situação qu...
# coding: utf-8 # author: Fei Gao # # Search A 2d Matrix Ii # Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: # Integers in each row are sorted in ascending from left to right. # Integers in each column are sorted in ascending from top to bottom. # ...
""" https://www.hackerrank.com/challenges/dynamic-array/problem """ def dynamicArray(n, queries): seqList = [[] for x in range(n)] lastAnswer = 0 result = [] for q in queries: [qType, seqIndex, number] = q index = (seqIndex ^ lastAnswer) % n seq = seqList[index] if q...
valor = float(input('Qual é o valor do produto? R$')) # desconto = valor * 0.05 Pode fazer desses dois jeitos # preco = valor - desconto novo = valor - (valor * 5 / 100) print("O produto que custavo R${:.2f}, na promoção de 5% vai custar R${:.2f}".format(valor, novo))
# Criando Exceções - Classes de erros personalizados no python class TaErradoErros(Exception): pass def testar(): raise TaErradoErros('Errado') try: testar() except TaErradoErros as error: print(f'Erro: {error}')
_title = 'KleenExtractor' _description = 'Clean extract system to export folder content and sub content.' _version = '0.1.2' _author = 'Edenskull' _license = 'MIT'
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 1 10:46:16 2020 @author: AzureD Useful tools to splitting and cleaning up input text. """ def cleanly(text: str): """ Splits the text into words at spaces, removing excess spaces. """ segmented = text.split(' ') clean = [s for...
q = int(input()) for _ in range(q): n = int(input()) m = [] for _ in range(n*2): m.append(list(map(int, input().split(' ')))) # Sorcery here... bigMax = 0 for i in range(n): for j in range(n): try: bigMax += max(m[i][j], m[i][2*...
secret = 'BEEF0123456789a' skipped_sequential_false_positive = '0123456789a' print('second line') var = 'third line'
#http://www.pythonchallenge.com/pc/def/ocr.html s = "" with open("3.html") as f: for line in f.readlines(): s += line for el in s: if el >= 'a' and el <= 'z': print(el),
# feel free to change these settings APP_NAME = 'Deep Vision' # any string: The application title (desktop and web). ABOUT_TITLE = "Deep Vision" # any string: The about box title (desktop and web). ABOUT_MESSAGE = "Created By : FastAI Student" # any string: The about box contents (desktop and web). APP_TYPE = 'deskt...
# coding=utf-8 # Author: Jianghan LI # Question: 114.Flatten_Binary_Tree_to_Linked_List # Date: 2017-04-19 9:15 - 9:21 # 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): ...
num = soma = cont = 0 while True: num = int(input('Digite um número: ')) if num == 999: break soma = soma + num cont = cont + 1 print(f'A soma dos {cont} números digitados é: {soma}')
ch=input(('Enter any alphabet or digit ')) if ch in 'aeiouAEIOU': print(ch,'is a vowel.') elif ch in '0123456789': print(ch,'is a digit.') else: print(ch,'is a consonant.')
''' Write a program to read two integers that are the date and month of birth. They are used to find the user's zodiac sign. The program should print type the birth signs on the screen. The details of each zodiac are as follows. 22 Dec - 19 Jan Capricorn 20 Jan - 18 Feb Aquarius 19 Feb - 20 Mar Pisces 21 Mar - 19 Apr A...
class MessageWriter: """ This class allows a "message" to be sent to an external recipient. """ def __init__(self, *args, **kwargs): pass def send_message(self, message): """ Sends a message to an external recipient. Usually, this involves creating a connection to a...
comp = float(input('Digite o Comptrimento da parede em metros:')) alt = float(input('Digite a altura da parede em metros: ')) rend = float(input('digite o rendimento da tinta em metros quadrados:')) print('Você possui uma area de {} m².'.format(comp*alt)) print('Sabendo que o rendimento da tinta é de {}m² por litros.'....
LOCAL_STATE_PATH = "/state" DEFAULT_INSTANCE_TYPE_TRAINING = "ml.m5.large" DEFAULT_INSTANCE_TYPE_PROCESSING = "ml.t3.medium" DEFAULT_INSTANCE_COUNT = 1 DEFAULT_VOLUME_SIZE = 30 # GB DEFAULT_USE_SPOT = True DEFAULT_MAX_RUN = 24 * 60 DEFAULT_MAX_WAIT = 0 DEFAULT_IAM_ROLE = "SageMakerIAMRole" DEFAULT_IAM_BUCKET_POLICY_...
""" *Coarsen* """ __all__ = ["Coarsen"] class Coarsen( TensorOperator, ): pass
""" Faça um programa que leia um número de 0 a 9999 e moste na tela cada um dos digitos separados. ex: Digite um número: 1834 Unidade: 4 Dezena: 3 centena: 8 milhar: 1 """ num = int(input('Informe um número: ')) u = num // 1 % 10 d = num // 10 % 10 c = num // 100 % 10 m = num // 1000 % 10 print(f'Analisando o número...
def avg(values): return sum(values) / len(values) def input_to_list(count): lines = [] for _ in range(count): lines.append(input()) return lines n = int(input()) students_grades_lines = input_to_list(n) students_grades = {} for line in students_grades_lines: student, grade = line.spl...
""" ## OSBot-Utils Project with multiple Util classes (to streamline development) Main GitHub repo: https://github.com/owasp-sbot/OSBot-Utils [![Coverage Status](https://coveralls.io/repos/github/owasp-sbot/OSBot-Utils/badge.svg?branch=master)](https://coveralls.io/github/owasp-sbot/OSBot-Utils?branch=master) """
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2022/3/20 4:18 下午 # @Author : xinming # @File : 91_num_decodings.py class Solution(object): def numDecodings(self, s): if not s: return None if s[0]=='0': return 0 n = len(s) dp = [0 for i in ran...
class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: weight = dict() for x in people: if x in weight: weight[x] += 1 else: weight[x] = 1 ans = 0 for x in people: if weight[x] > 0: ...
n=int(input()) l=[] k=[] e=[] for i in range (n): t=input() l.append(t) print(l) for j in l: if j not in k: k.append(j) print(k) print(len(k)) for m in range(len(k)): c=0 for d in l: if( k[m]==d): c=c+1 e.append(c) print(e) for i in e: ...
""" format: def request(login, password): return bool(...) """
class Shop: _small_shop_capacity = 10 def __init__(self, name, shop_type, capacity): self.name = name self.type = shop_type self.capacity = capacity self.items_count = 0 self.items = {} @classmethod def small_shop(cls, name, shop_type): return cls(name, ...
for row in range(5,0): for col in range(1,row+1): print(col,end=" ") print()
n = int(input('Primeiro número: ')) r = int(input('Razão: ')) valor = n for c in range(0, 10): print(valor, end=' -> ') valor += r print('ACABOU')
IDENTIFIED_COMMANDS = { 'NS STATUS %s': ['STATUS {username} (\d)', '3'], 'PRIVMSG NickServ ACC %s': ['{username} ACC (\d)', '3'], } IRC_AUTHS = { # 'localhost': {'username': 'Botname', 'realname': 'Bot Real Name'}, } IRC_GROUPCHATS = [ # 'groupchat@localhost', ] IRC_PERMISSIONS = { # 'nekmo@loca...
class Solution: def decompressRLElist(self, nums: List[int]) -> List[int]: result = [] for i in range(0, len(nums), 2): freq, val = nums[i:i+2] for n in range(freq): result.append(val) return result
# Global Level Configuration File. # Flask Settings # http://flask.pocoo.org/docs/0.12/config/ ''' enable/disable debug mode ''' DEBUG = True ''' enable/disable testing mode ''' TESTING = False ''' explicitly enable or disable the propagation of exceptions. If not set or explicitly set to None th...
# -*- coding: utf-8 -*- """ Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. Note that the row index starts from 0. Example: Input: 3 Output: [1,3,3,1] Follow up: Could you optimize your algorithm to use only O(k) extra space? 构造杨辉三角 """ class Solution: def genRow(s...