content
stringlengths
7
1.05M
# Calculates the total cost of a restaurant bill # including the meal cost, tip amount, and sales tax # Declare variables tipRate = 0.18 # 18% salesTaxRate = 0.07 # 7% # Prompt user for cost of meal mealCost = float(input('\nEnter total cost of meal: $')) # Calculate and display total tip, # total sales...
#!/usr/bin/env python __author__ = "yangyanzhan" __email__ = "yangyanzhan@gmail.com" __url__ = "https://github.com/yangyanzhan/code-camp" __blog__ = "https://yanzhan.site" __youtube__ = "https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber" __twitter__ = "https://twitter.com/YangYanzhan" mappin...
# Copyright (c) 2016 Ericsson AB. # 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 w...
#!/usr/bin/python3 """Student to JSON""" class Student: """representation of a student""" def __init__(self, first_name, last_name, age): """instantiation of the student""" self.first_name = first_name self.last_name = last_name self.age = age def to_json(self): ""...
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- def get_package_data(): # pragma: no cover return { str(_PACKAGE_NAME_ + '.tags.core.tests'): ['data/*.yaml']}
t = ( 10, 11, 12, 34, 99, 4, 98) print (t[0]) t1 = (1, 1, 1, 2, 3, 4, 65, 65, 3, 2) #tuple with single element print (t1.count(1)) print (t1.index(65))
connChoices=( {'name':'automatic', 'rate':{'min':0, 'max':5000, 'def': 0}, 'conn':{'min':0, 'max':100, 'def': 0}, 'automatic':1}, {'name':'unlimited', 'rate':{'min':0, 'max':5000, 'def': 0, 'div': 50}, 'conn':{'min':4, 'max':100, 'def': 4}}, {'name':'dialup/isdn', 'r...
# apis_v1/documentation_source/voter_ballot_list_retrieve_doc.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- def voter_ballot_list_retrieve_doc_template_values(url_root): """ Show documentation about voterBallotListRetrieve """ required_query_parameter_list = [ { ...
# "sb" pytest fixture test in a method with no class def test_sb_fixture_with_no_class(sb): sb.open("https://google.com/ncr") sb.type('input[title="Search"]', "SeleniumBase GitHub\n") sb.click('a[href*="github.com/seleniumbase/SeleniumBase"]') sb.click('a[title="seleniumbase"]') # "sb" pytest fixture ...
# Copyright 2017 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
template = ' <!DOCTYPE html> \ <html lang="en"> \ <head> \ <title>AssiStudy</title> \ <meta charset="UTF-8"> \ <meta name="viewport" co ntent="width=device-width, initial-scale=1"> \ <!--===============================================================================================--> \ <link rel="icon" type...
class Config: # dataset related exemplar_size = 127 # exemplar size instance_size = 255 # instance size context_amount = 0.5 # context amount # training related num_per_epoch = 53200 # num of samples per epoch train_r...
__all__ = ('indent_string',) def indent_string(s, num_spaces): add_newline = False if s[-1] == '\n': add_newline = True s = s[:-1] s = '\n'.join(num_spaces * ' ' + line for line in s.split('\n')) if add_newline: s += '\n' return s
# model settings model = dict( type='MAE', backbone=dict( type='MAEViT', arch='small', patch_size=16, mask_ratio=0.75), neck=dict( type='MAEPretrainDecoder', patch_size=16, in_chans=3, embed_dim=768, decoder_embed_dim=512, decoder_depth=6, # 3...
class Student(object): def __init__(self) -> None: # 私有属性 self.__age = 0 @property # 当调用age属性时会调用下面的方法(方法转属性) def age(self): print("获取属性") return self.__age @age.setter # 当调用属性修改时会调用以下方法 def age(self, new_age): print("设置属性") if new_age >= 0 and ...
expected_output = { "report_id":{ "1634211151":{ "metric_name":"ENTITLEMENT", "feature_name":"dna-advantage", "metric_value":"regid.2017-05.com.cisco.c9300_dna_advantage,1.0_411773c3-2116-4c10-94a4-5d357fe6ff18", "udi":{ "pid":"C9300-24UX", "s...
""" Technique - Sum of all multiples of 3 + Sum of all those multiples of 5 that are not multiple of 3 - This Multiples of 15 should be subtracted as that has been added twice. - A Pythonic implementation which uses a list comprehension. Note - The optimisation that only those multiples of 5 are added which are not th...
nome= input("Digite o nome do aluno: ") nota1 = float(input("Digite a primeira nota: " )) nota2 = float(input("Digite a segunda nota: " )) media = (nota1 + nota2)/2 print("A média do aluno é",nome, ":", media)
''' Encrypt and decrypt a string ''' def encrypt(s): return s.encode('hex') def decrypt(s): return s.decode('hex')
test = { 'name': 'List Indexing', 'points': 0, 'suites': [ { 'cases': [ { 'code': r""" >>> x = [1, 3, [5, 7], 9] # Write the expression that indexes into x to output the 7 3450d5df7f6d639c9dc883cf31cc62bd # locked >>> x = [[7]] # Write the expres...
class NotFoundError(Exception): """ Class of custom Exception about Not Found Args: data (all types): input data """ def __init__(self, data): self.data = data def __str__(self): return f"Not Found {self.data}, please check the name again" class CollisionError(Exc...
# Defines number of epochs n_epochs = 200 losses = [] for epoch in range(n_epochs): # inner loop loss = mini_batch(device, train_loader, train_step) losses.append(loss)
#----------------------------------------------------------------------------- # Runtime: 32ms # Memory Usage: # Link: #----------------------------------------------------------------------------- class Solution: def canJump(self, nums: [int]) -> bool: max_right = 0 for i, num in enumerate(nums...
def floyd_warshall(start): d = [float("Inf") for i in range(n)] dist = [[graph[j][i] for i in range(n)] for j in range(n)] for k in range(n): for i in range(n): for j in range(n): dist[i][j] = min(dist[i][j], dist[j][k] + dist[k][j]) return dist if __name__ == "__ma...
__revision__ = '$Id: __init__.py,v 1.2 2006/08/12 15:56:26 jkloth Exp $' __all__ = ['XmlFormatter', 'ApiFormatter', 'ExtensionFormatter', 'CommandLineFormatter', ]
display = { 0: 'ABCEFG', 1: 'CF', 2: 'ACDEG', 3: 'ACDFG', 4: 'BCDF', 5: 'ABDFG', 6: 'ABDEFG', 7: 'ACF', 8: 'ABCDEFG', 9: 'ABCDFG' } solve_it = { 'a': 'C', 'b': 'F', 'c': 'G', 'd': 'A', 'e': 'B', 'f': 'D', 'g': 'E' } def part1(input_str: str) -> None...
numero = float(input('Digite um numero: ')) raio = 3.14 * numero ** 2 print(f' o raio é {raio}')
# Escape Sequence Characters:? # Sequence of characters after backslash ‘\’ [Escape Sequence Characters] # Escape Sequence Characters comprises of more than one character but represents one character when used within the string. # Examples: \n (new line), \t (tab), \’ (single quote), \\ (backslash), etc. #Escape seq...
n = input("value of n\n") n = int(n) if n < 5: print("n is less than 5") elif n == 5: print("n is equal to 5") else: print("n is greater than 5")
""" List of languages. Auto-generated with `python -m scripts`. """ # START langs = { "AE.": "American English", "AG.": "Austrian German", "Acadian French": "Acadian French", "American English": "American English", "Austrian German": "Austrian German", "BE.": "British English", "Borders Sco...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Дано предложение. Составить программу, которая печатает «столбиком» все вхождения в # предложение некоторого символа if __name__ == '__main__': sentence = list(input("Введите предложение ").split()) symbol = input("Введите символ который хотите проверит...
""" Dictionary of supported JIRA events and output friendly format """ jira_events = { "project_created": "New Project Created", "jira:issue_created": "New Issue Created", "jira:issue_updated": "Issue Updated" } issue_events = { "issue_commented": "Comment Added", "issue_comment_edited": "Comment E...
''' practice qusestion from chapter 1 Module 5 of IBM Digital Nation Courses by Aashik J Krishnan/Aash Gates ''' #testing variable x = 8 print(x) x = "seven" #assigning the Sring to variable x print(x) x = 6 #end of the Program
class ApiKeyManager( object ): def __init__( self, app ): self.app = app def create_api_key( self, user ): guid = self.app.security.get_new_guid() new_key = self.app.model.APIKeys() new_key.user_id = user.id new_key.key = guid sa_session = self.app.model.conte...
class Solution(object): def uniquePathsWithObstacles(self, obstacleGrid): """ :type obstacleGrid: List[List[int]] :rtype: int """ rslt = [] for i in range(len(obstacleGrid)): r = [] for j in range(len(obstacleGrid[i])): if obsta...
'''3) Para cada nota de compra, tem-se o Nome do produto comprado, o valor e o imposto. Faça um programa em Python que escreva o valor total do produto, o valor total do imposto e o valor total cobrado de todas as notas. Considere 10 notas fiscais.''' #Definindo variaveis impostos = [] valores = [] cont = 0 print('-='...
totalSegundos = int(input()) quantidadeHoras = totalSegundos//60//60 segundosHoras = quantidadeHoras*60*60 restante = totalSegundos - segundosHoras quantidadeMinutos = restante//60 segundosMinutos = quantidadeMinutos*60 quantidadeSegundos = restante - segundosMinutos print('{}:{}:{}'.format(quantidadeHoras, quantidad...
class Solution: def threeSumClosest(self, nums,target): nums.sort() out=0 for i in range(len(nums)-1): j=i+1 k=len(nums)-1 while j<k: # print(nums[i]+nums[j]+nums[k],out) if i==0 and j==1 and k==len(nums)-1: ...
""" Test the health check endpoints """ def test_live(mini_sentry, relay): """Internal endpoint used by kubernetes """ relay = relay(mini_sentry) response = relay.get("/api/relay/healthcheck/live/") assert response.status_code == 200 def test_external_live(mini_sentry, relay): """Endpoint called...
# -*- coding: utf-8 -*- DDD_TABLE = { '61' : 'Brasilia', '71' : 'Salvador', '11' : 'Sao Paulo', '21' : 'Rio de Janeiro', '32' : 'Juiz de Fora', '19' : 'Campinas', '27' : 'Vitoria', '31' : 'Belo Horizonte' } def main(): ddd = input() if ddd in DDD_TABLE: print(DDD_TABLE...
minimal_message = """ { "$schema": "../../harmony/app/schemas/data-operation/0.7.0/data-operation-v0.7.0.json", "version": "0.7.0", "callback": "http://localhost/some-path", "stagingLocation": "s3://example-bucket/public/some-org/some-service/some-uuid/", "user": "jdoe", ...
with open('09.txt') as fd: data = fd.readline().strip() pos = 0 current = [] stack = [] in_garbage = False garbage = 0 while pos < len(data): c = data[pos] pos += 1 if in_garbage: if c == '!': pos += 1 elif c == '>': in_garbage = False else: garbage += 1 else: if c == '{': ...
""" Test Case 1 def main(): LL = [] print('Original List: ', LL) LL.reverse() print('Reversed List: ', LL) """ """ Test Case 1 - Results Original List: [] Reversed List: [] """ """ Test Case 2 def main(): LL = [1, 2, 3] print('Original List:', LL) LL.reverse() print('Reversed List:', LL...
Zero = [' *** ', ' * * ', '* *', '* *', '* *', ' * * ', ' *** ' ] One = [' * ', ' ** ', ' * ', ' * ', ' * ', ' * ', ' *** '] Two = [' *** ', '* *', '* * ', ...
f""" Temperature Conversions - SOLUTIONS """ # You're studying climate change, and over the last 3 years, you've recorded the temperature at noon every day in degrees Fahrenheit (F). The var sampleF holds a portion of those recordings. sampleF = [91.4, 82.4, 71.6, 107.6, 115.6] # Convert each item in this list into...
# Use the range function to loop through a code set 6 times. for x in range(6): print(x)
""" File for providing static messages or data """ def get_app_message(key): all_messages = { 'register_success': 'We will be working hard to process your request.', 'register_error': 'Invalid Data', 'register_error_message': 'Sorry, we are unable to process your request. Please make sure ...
def _kubectl_impl(ctx): executable = ctx.actions.declare_file(ctx.attr.name) contents = """ set -o errexit export KUBECTL="{kubectl}" export RESOURCE="{resource}" export NAMESPACE="{namespace}" "{script}" """.format( kubectl = ctx.executable._kubectl.short_pat...
# -*- coding: utf-8 -*- """ Created on Tue Feb 22 14:50:22 2022 @author: Riedel """ # ============================================================================= # # import setuptools # from readreflex import _version # # with open("README.md", "r") as fh: # long_description = fh.read() # # setuptools.setup( ...
#!/bin/zsh while True: OldmanAge = input() def AgetoDays(age): result = int(age) * 365 return result print(AgetoDays(OldmanAge)) break
class JobDoesNotExist(RuntimeError): """The reduce mode job doesn't exist (set_total has not been run). """ class JobFailed(RuntimeError): """Skip, the reduce mode job has already been marked as failed. """ class ProgressTypeError(TypeError): """Progress argument is not of the correct type"""
# -*- coding: utf-8 -*- class Solution: INTEGER_TO_ALPHABET = {n: chr(ord('a') + n - 1) for n in range(1, 27)} def freqAlphabets(self, s: str) -> str: i, result = 0, [] while i < len(s): if i + 2 < len(s) and s[i + 2] == '#': result.append(self.INTEGER_TO_ALPHABET[...
def test_get_all_offices(fineract): offices = [office for office in fineract.get_offices()] assert len(offices) == 3 def test_get_single_office(fineract): office = fineract.get_offices(2) assert office assert office.name == 'Merida' def test_get_all_staff(fineract): staff = [staff for staff ...
print("\n\t\t-----> Welcome to Matias list changer <-----\t\t\n") listn = [1,2,3,4,5,6,7,8,9,10] print(f"\nThis is the list without changes ===> {listn}\n") listn[4] *= 2 listn[7] *= 2 listn[9] *= 2 print(f"\nThis is the modified list ===> {listn}\n")
def shiftCalc(n): if n < 0x40: n = n - 1 n = n ^ 0x10 n = n + 1 else: n = n ^ 0x20 return n keys = """ 1 ! 2 " 3 # 4 $ 5 % 6 & 7 ' 8 ( 9 ) 0 @ : * - = ; + , < . > / ? """.replace("\t"," ").split("\n") keys = [x.strip() for x in keys if x.strip() != ""] for i in range(0,26): keys.append(...
class PizzaDelivery: def __init__(self, name, price, ingredients): self.name = name self.price = price self.ingredients = ingredients self.ordered = False def add_extra(self, ingredient, quantity, price_per_ingredient): if self.ordered: return f"Pizza {self....
## CITIES cities = ['London', 'Constantinople', 'Sydney', 'Leningrad', 'Peking'] # Use bracket notation to change: # Constantinople to Istanbul # Leningrad to Saint Petersburg # Peking to Beijing cities[1] = 'Istanbul' cities[3] = 'Saint Petersburg' cities[4] = 'Beijing' ## DINOSAURS dinos = ['Tyrannosaurus rex', 'T...
class Constants: FW_VERSION = 4 LIGHT_TRANSITION_DURATION = 320 FAST_RECONNECT_WAIT_TIME_BEFORE_RESETING_LIGHTS = 5 HEARTBEAT_INTERVAL = 120 HEARTBEAT_MAX_RESPONSE_TIME = 5
class GoogleAnalyticsClientError(Exception): """ General Google Analytics error (error accessing GA) """ def __init__(self, reason): self.reason = reason def __repr__(self): return 'GAError: %s' % self.reason def __str__(self): return 'GAError: %s' % self.reason
class UI_Draw: def draw(self, context): layout = self.layout layout.prop(self, 'auto_presets') layout.separator() split = layout.split() split.prop(self, 'handle', text='Handle') col = split.column(align=True) col.prop(self, 'handle_z_top', text='Top') if self.shape_rnd or self.shape_sq: col.pr...
# 2级 # 问题:编写一个程序,接受逗号分隔的单词序列作为输入,按字母顺序排序后按逗号分隔的序列打印单词。假设向程序提供以下输入: # without,hello,bag,worl # 则输出为: # bag,hello,without,world # 提示:在为问题提供输入数据的情况下,应该假设它是控制台输入。 # 解决方案: print("Please enter a few words") itmes = [ x for x in input().split(',')] itmes.sort() print (",".join(itmes))
""" Basic Configurations """ def configs(): configs_dict = {} configs_dict['cdsign'] = '/' configs_dict['path_root'] = './VQA_Project/' configs_dict['path_datasets'] ...
TWITTER_DIR = "twitter_data" TWITTER_RAW_DIR = "raw" TWITTER_PARQUET_DIR = "parquet" TWITTER_RAW_SCHEMA = "twitter_schema.json"
matriz = [] for i in range(2): matriz.append(list(map(int, input().split()))) linhaMaior, colMaior = 0, 0 for linha in range(len(matriz)): for elemento in range(len(matriz[linha])): if matriz[linha][elemento] > matriz[linhaMaior][colMaior]: linhaMaior, colMaior = linha, elemento...
SLIP39_WORDS = [ "academic", "acid", "acne", "acquire", "acrobat", "activity", "actress", "adapt", "adequate", "adjust", "admit", "adorn", "adult", "advance", "advocate", "afraid", "again", "agency", "agree", "aide", "aircraft", "ai...
class Model: def __init__(self): self.SoC = 0.0 self.io = 0.0 def step(self, value): if self.SoC > 0.95 and self.io == 1.0: self.io = 0.0 if self.SoC < 0.05 and self.io == 0.0: self.io = 1.0
def is_valid_index(r, c, board_size): return r in range(board_size) and c in range(board_size) def calculate_kills(matrix, r, c): kills = 0 possible_moves = [ (-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (2, -1), (2, 1), (1, 2) ] for idx in range(len(possible_moves)): row = r + p...
''' Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. Example 1: Input: nums = [1,2,3,1], k = 3 Output: true Example 2: Input: nums = [1,0,1,1], k = 1 Output: true ...
# Crie um programa que leia um número inteiro e mostre na tela se ele é PAR ou ÍMPAR n = int(input('Me diga um número qualquer: ')) if (n % 2) == 0: print('O número {} é PAR' .format(n)) else: print('O número {} é ÍMPAR' .format(n))
#función para realizar la descomposición en factores primos de un número ingresado por el usuario. def factors(n:int, fact:list = []) -> list: x = {n: [i for i in range(1, n+1) if n % i == 0] for n in range(1,1000)} for key, value in x.items(): if len(value) == 2: fact.append(key) def d...
# settings.py # # aws-clean will not destroy things in the whitelist for global resources # please put under the global region. I recommend just adding to the lists provided # unless you are trying to provide a new cleaner. # # # What value do I put in for each resource> # # s3_buckets - BucketName # ec2_instances - In...
### YOUR CODE FOR openLocks() FUNCTION GOES HERE ### def openLocks(number_of_lockers , number_of_students): if type(number_of_lockers) == str or type(number_of_students) == str or number_of_lockers < 0 or number_of_students <0: return None if number_of_lockers == 0 or number_of_students == 0: re...
test = { 'name': 'Question32', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" >>> from datascience import * >>> retweets_likes_age.num_rows 7 """, 'hidden': False, 'locked': False }, { 'code...
if __name__ == '__main__': n = int(input()) student_marks = {} for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores query_name = str(input()) if query_name in student_marks: l=list(student_marks[query_name]) sum=0 ...
fname = input("Enter the file name: ") fh = open(fname) count = 0 for line in fh: line = line.rstrip() if line.startswith('From '): count = count + 1 words = line.split() emails = words[1] print(emails) print("There were",count, "lines in the file with From as the first word")
def add_title(self): square = Square(side_length=2 * self.L) title = TextMobject("Brownian motion") title.scale(1.5) title.next_to(square, UP) self.add(square) self.add(title)
class Solution(object): def reverseBitsBitManipulation(self, n): """ Time - O(length(n)) = O(32) Space - O(1) :type n: integer :rtype: integer """ result = 0 for _ in range(32): result <<= 1 result |= n & 1 n >>= 1 ...
print('==' * 20) print(f'{"FUNÇÃO TXT ADAPTÁVEL":^40}') print('==' * 20) def escreva(txt): x = str(txt).strip().title() tamanho = len(txt) + 4 print('~' * tamanho) print(f' {x}') print('~' * tamanho) while True: texto = str(input('Digite o título: ')) if texto == '': break e...
## PETRglobals.py [module] ## # Global variable initializations for the PETRARCH event coder # # SYSTEM REQUIREMENTS # This program has been successfully run under Mac OS 10.10; it is standard Python 2.7 # so it should also run in Unix or Windows. # # INITIAL PROVENANCE: # Programmer: Philip A. Schrodt # Parus Ana...
# pylint: disable=W0622 def sum(arg): total = 0 for val in arg: total += val return total
class Wallet(): def __init__(self, initial_amount = 0): self.balance = initial_amount def spend_cash(self, amount): if self.balance < amount: print("insuffienct amount") else: self.balance -= amount def add_cash(self, amount): self.balance += amount
""" For / Else em python """ variavel = ['Luiz Otavio', 'Joãozinho', 'Maria'] for valor in variavel: print(valor) if valor.startswith('M'): print('Começa com J', valor) else: print('Não começa com J')
a = int(input("")) b = int(input("")) c = int(input("")) d = int(input("")) x = (a*b-c*d) print("DIFERENCA = %d" %x)
""" CSS Grid Template """ class CSSGridMixin(object): """ A mixin for adding css grid to any standard CBV """ grid_wrapper = None grid_template_columns = None grid_template_areas = None grid_gap = None def get_context_data(self, **kwargs): """ Insert the single object...
# Criando uma tabuada print('#'*30) n = int(input('Digite um número: ')) print('#'*30) print('[1] - Soma \n[2] - Subtração \n[3] - Multiplicação \n[4] - Divisão') print('#'*30) tab = int(input('Escolha sua tabuada: ')) if tab == 1: n1 = n+1 n2 = n+2 n3 = n+3 n4 = n+4 n5 = n+5 n6 = n+6 n7 = ...
# Webhook content types HTTP_CONTENT_TYPE_JSON = "application/json" # Registerable extras features EXTRAS_FEATURES = [ "config_context_owners", "custom_fields", "custom_links", "custom_validators", "export_template_owners", "export_templates", "graphql", "job_results", "relationship...
def _pretty_after(a, k): positional = ", ".join(repr(arg) for arg in a) keyword = ", ".join( "{}={!r}".format(name, value) for name, value in k.items() ) if positional: if keyword: return ", {}, {}".format(positional, keyword) else: return ", {}".format(po...
""" Global wikipedia excpetion and warning classes. """ class PageError(Exception): """Exception raised when no Wikipedia matched a query.""" def __init__(self, page_title): self.title = page_title def __str__(self): return "\"%s\" does not match any pages. Try another query!" % self.title class Disambiguati...
""" CONFIG module We put here things that we might vary depending on which machine we are running on, or whether we are in debugging mode, etc. """ COOKIE_KEY = "A random string would be better" DEBUG = True PORT = 5000 # The default Flask port; change for shared server machines
# (regname, regsize, is_big_endian, arch_name, branches) # PowerPC CPU REGS PPCREGS = [[], 4, True, "ppc", ["bl "]] for i in range(32): PPCREGS[0].append("r"+str(i)) for i in range(32): PPCREGS[0].append(None) PPCREGS[0].append("lr") PPCREGS[0].append("ctr") for i in range(8): PPCREGS[0].append("cr"+str(i)) # A...
# 丢失的数字 # https://leetcode-cn.com/problems/missing-number class Solution: # 排序之后再依次遍历查找 def missingNumber_1(self, nums: List[int]) -> int: nums.sort() for i, v in enumerate(nums): if i != v: return i return len(nums) # 使用一个哈希表 def missingNumber_1(s...
""" Swagger documentation for comment resources """ class CommentResourceDoc: """ Comment resources swagger documentation """ @staticmethod def get_by_id_docs(): """ Get by id endpoint documentation """ return { 'tags': ['comment'], 'description': 'Returns json', ...
# -*- coding: utf8 -* ''' A Simple Extractor Key Note for SPED Fiscal created by Matheus Tavares ''' # Abrindo arquivo Sped para ler e Criando arquivo com notas separadas sped = open("sped.txt", "r") noteLine =[] # Encontrando linhas C100 e salvando em Lista for line in sped: if line[0:6] == '|C...
DATA_FOLDER = 'data' DATA_INPUT_ZIP = 'stanford-dogs-dataset.zip' DATA_OUTPUT_ZIP = 'dataset_unzipped' DATASET_FOLDER = 'dataset' IMAGES_LIST_FILE_NAME = 'images.txt' INDEX_FILE_NAME = 'index.nmslib' INPUT_IMAGE_FILE_NAME = 'input_image.jpg' OUTPUT_IMAGE_FILE_NAME = 'output_image.jpg' DEFAULT_IMAGES_PER_RACE = 1 IMAG...
#Ex005 Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e seu antecessor. n = int(input('Digite um número inteiro: ')) a = n - 1 s = n + 1 print(f'O número que você digitou é {n} tendo seu antecessor {a} e seu sucessor {s}')
class Solution: def threeSumClosest(self, nums: [int], target: int) -> int: nums = sorted(nums) visited = [] difference = float('inf') result = 0 for i, num_1 in enumerate(nums): if num_1 in visited: continue else: visi...
class Note(object): def __init__(self, content = None): self.content = content def write_content(self, content): self.content = content def remove_all(self): self.content="" def __str__(self): return self.content class NoteBook(object): def __init__(self, title): ...
class DataPacket: """ UDP başlığının veri kısmını bu classın bir nesnesi şeklinde yollayacağım. COMMAND = > MESAJIN AMACI SEQNUMBER = > ARKA ARKAYA GELMESİ GEREKEN PAKETLERİ SIRALAYACAĞIM NUMARA DATA = > YOLLANAN İŞLENECEK OLAN VERİ """ def __init__(self,command,seqNumber,data): sel...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Invenio search errors.""" class IndexAlreadyExistsError(Exception): """Raised whe...
USER_ALREADY_EXISTS = "USER_ALREADY_EXISTS" USER_SIGNUP_SUCCESSFUL = "USER_SIGNUP_SUCCESSFUL" CREDENTIALS_INCORRECT = "CREDENTIALS_INCORRECT" USER_UNREGISTERED = "USER_UNREGISTERED" ROLL_NUMBER_REQUIRED = "ROLL_NUMBER_REQUIRED" PASSWORD_REQUIRED = "PASSWORD_REQUIRED"