content
stringlengths
7
1.05M
# -*- coding: utf-8 -*- ''' File name: code\47smooth_triangular_numbers\sol_581.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #581 :: 47-smooth triangular numbers # # For more information see: # https://projecteuler.net/problem=581 # P...
# -*- coding: utf-8 -*- # @Time : 2019-08-14 14:05 # @Author : Kai Zhang # @Email : kai.zhang@lizhiweike.com # @File : ex4-string_to_integer.py # @Software: PyCharm class Solution: def myAtoi(self, string: str) -> int: # 去空格 string = string.strip() if not string: retur...
x = int(input("Please enter x: ")) y = int(input("Please enter y: ")) # Wrong way print("Wrong way") if x < y: print("x is less than y") else: if x > y: print("x is greater than y") else: print("x and y must be equal") # Correct way using elif print("Correct way") if x < y: print("x is...
# throws KeyError students = {'John': 18, 'Jack': 19} print(students['Joe']) # try/catch KeyError students = {'John': 18, 'Jack': 19} try: print(students['Joe']) except KeyError: print('you tried to access an entry that does not exists')
""" Write a function that reverses characters in (possibly nested) parentheses in the input string. Input strings will always be well-formed with matching ()s. Example For inputString = "(bar)", the output should be reverseInParentheses(inputString) = "rab"; For inputString = "foo(bar)baz", the output should be reve...
# 在计算个数时使用便利的方法导致 judge 用了 500+ms,还没有想到优化方法。 class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: List[int] """ nums_len = len(nums) result_list = list() if nums_len == 0: return [] while True: ...
_base_ = '../_base_/default_runtime.py' # dataset settings dataset_type = 'CocoPanopticDataset' data_root = 'data/coco/' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) # file_client_args = dict(backend='disk',) # file_client_args = dict( # backend='petrel', # ...
STATUS_MAPPER = [ "Success", "Unknown HCI Command", "Unknown Connection Identifier", "Hardware Failure", "Page Timeout", "Authentication Failure", "PIN or Key Missing", "Memory Capacity Exceeded", "Connection Timeout", "Connection Limit Exceeded", "Synchronous Connection Limit to a Device Exceeded...
# Proszę zaimplementować algorytm QuickSort do sortowania n elementowej tablicy tak, żeby zawsze # używał najwyżej O(log(n)) dodatkowej pamięci na stosie, niezależnie od jakości podziałów w funkcji # partition. def partition(T, p, r): pivot = T[r] i = p - 1 for j in range(p, r): if T[j] <= pivot: ...
# __init__ __version__ = '1.1.0'
'''Desenvolva um lógica que leia o peso e a altura de uma pessoa, calcule o IMC e mostre o status, de acordo com a tabela abaixo: - Abaixo de 18.5: Abaixo do peso - Entre 18.5 e 25: Peso ideal - 25 até 30: Sobrepeso - 30 até 40: Obesidade - Acima de 40: Obesidade mórbida.''' peso = float(input('Digite o seu peso em Kg...
def test_get_public_key(cmd, button, model): pub_key, address = cmd.get_public_key( bip32_path="44'/5741565'/0'/0'/1'", network_byte='V', display=True, button=button, model=model ) # type: bytes, bytes assert len(pub_key) == 32 assert len(address) == 35
#faça um programa que peça a temperatura em farenheit, transforme e mostre a temperatura em celsius.. print ("escolha uma das opçoes abaixo") print ("1- celsius---farenheit") print ("2- farenheit---celsius") print ("3- celsius---kelvin") print ("4- kelvin---celsius") t = float(input ("escolha uma das opço...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Решить поставленную задачу: написать функцию, вычисляющую среднее геометрическое своих аргументов a1, a2, ... an Если функции передается пустой список аргументов, то она должна возвращать значение None """ def mean(*arg): if arg: a = 1.0 for i i...
x = [1,2,3] name = "/tests/fixtures/data/names/{name_id}.txt" output = "/tests/fixtures/data/salutations/{name_id}-{x}.txt" def main(): return "Hello {name} for the {x} time!".format(name=name, x=x)
###Titulo: Validando número em lista ###Função: Este programa identifica se dois números estão na lista e qual foi achado primeiro ###Autor: Valmor Mantelli Jr. ###Data: 01/01/2019 ###Versão: 0.0.6 ### Declaração de variáve list = [15, 7, 27, 39] n = 0 s = 0 x = 0 fn = False fs = False find = 0 ### Atribuição...
# Skin info and colours theme_name = "Future Bloo" theme_author = "Lucas." theme_version = "1.0" theme_bio = "Bloo" # A long bio will get cut off, keep it simple. window_theme = "Black" button_colour = "black" attacks_theme = {"background": "Black", "button_colour": ('black', 'cyan')} banner_size = (600, 100) banner_p...
''' crie um programa que leia nome e duas notas de vários alunos e guarde tudo em uma lista composta. no final, mostre um boletim contendo a média de cada um e permita que o usuário possa mostrar as notas de cada aluno individualmente. ''' ficha = [] while True: nome = str(input('nome: ')).strip().title() nota...
""" Some functions about numbers """ ############################################### def is_number(v): try: v = float(v) return True except ValueError: return False except TypeError: return False ############################################### def get_number(v): defaul...
# Apresentação print('Programa para determinar se um número é par ou ímpar') print() # Entradas numero = int(input('Informe um valor: ')) # Processamento e saídas if (numero % 2 == 0): print('Número par') else: print('Número ímpar')
""" There is a fence with n posts, each post can be painted with one of the k colors. You have to paint all the posts such that no more than two adjacent fence posts have the same color. Return the total number of ways you can paint the fence. Note: n and k are non-negative integers. """ class Solution(object): ...
ENTRY_POINT = 'f' #[PROMPT] def f(n): """ Implement the function f that takes n as a parameter, and returns a list of size n, such that the value of the element at index i is the factorial of i if i is even or the sum of numbers from 1 to i otherwise. i starts from 1. the factorial of i is the mult...
def fibonacci(): """generartor of fibonacci numbers""" a, b, n = 0, 1, 1 yield n, b while True: n += 1 a, b = b, b + a yield n, b def triangle(): n = 1 while True: yield n, n * (n + 1) // 2 n += 1
DATA = { "website": None, "myspace_name": None, "last_name": "Bizness", "reposts_count": 0, "public_favorites_count": 0, "followings_count": 2, "full_name": "Nonya Bizness", "id": 12345, "city": "Los Angeles", "first_name": "Nonya", "track_count": 123, "playlist_count": 0...
# parsetab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'leftpuntobipuntoleftcomarightigualleftcor1cor2leftmasmenosleftasteriscodivporcentajeleftpotrightumenosumasleftpar1par2leftt_orleftt_andleftdiferenteleftmayormenormayori...
""" @Author: huuuuusy @GitHub: https://github.com/huuuuusy 系统: Ubuntu 18.04 IDE: VS Code 1.37.1 工具: python == 3.7.3 """ """ 思路: 数字N如果是奇数,它的约数必然都是奇数;若为偶数,则其约数可奇可偶。 无论N初始为多大的值,游戏最终只会进行到N=2时结束,那么谁轮到N=2时谁就会赢。 因为爱丽丝先手,N初始若为偶数,爱丽丝则只需一直选1,使鲍勃一直面临N为奇数的情况,这样爱丽丝稳赢; N初始若为奇数,那么爱丽丝第一次选完之后N必为偶数,那么鲍勃只需一直选1就会稳赢。 ...
""" This hard-coded list would need to be maintained differently if/when the available units, available upgrades or their in-game IDs change. """ codeMap = { "protoss" : { "ground" : { 4 : "Colossus", 73 : "Zealot", 74 : "Stalker", ...
items = "ABCDE" pairs = [] for a in range(len(items)): for b in range(len(items)): pairs.append((items[a], items[b])) print(pairs) ret = [(items[a], items[b]) for a in range(len(items)) for b in range( len(items))] print(ret) ret2 = [(x, y) for x in range(2) for y in range(2)] ret3 = [(x, y) for x in r...
# 此处可 import 模块 """ @param string line 为单行测试数据 @return string 处理后的结果 """ def solution(line): # 缩进请使用 4 个空格,遵循 PEP8 规范 # please write your code here # return 'your_answer' int_10 = int(line) int_2 = bin(int_10).replace('0b', '') int_2_r = int_2[::-1] x = 32 - len(int_2_r) int_2_r += '0'*x ret...
# -*- coding: utf-8 -*- def skip(model, layer, inputs): inputs[layer.name] = inputs[layer.input.name] return model, layer, inputs
def fixing_float(size, n_float): fmt = ".{n}f" fix = [None] for i in range(size): fix.append(fmt.format(n=n_float)) return fix
# # PySNMP MIB module UPS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/UPS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:50:47 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)...
# # PySNMP MIB module ELTEX-MES-SNMP-COMMUNITY-EXT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-MES-SNMP-COMMUNITY-EXT-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:01:57 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Pyt...
def fun(x): return 2*x fun(4)
# Define a class for the maze board class Maze: # Initialize number of rows, cols and start position def __init__(self, rows, cols, start): self.rows = rows self.cols = cols self.i = start[0] self.j = start[1] self.start = start def set(self, rewards, actions): ...
SUPPORTED_TRANS = { "height": "h", "width": "w", "aspect_ratio": "ar", "quality": "q", "crop": "c", "crop_mode": "cm", "x": "x", "y": "y", "focus": "fo", "format": "f", "radius": "r", "background": "bg", "border": "bo", "rotation": "rt", "blur": "bl", "nam...
# As cordenadas são dadas pelas variaveis que guardão a posição do mouse def setup(): size(480, 120) fill(0, 102) noStroke() def draw(): background(204) ellipse(mouseX, mouseY, 9,9)
""" Datos de entrada edad_uno-->e1-->int edad_dos-->e2-->int edad_tres-->e3-->int Datos de salida promedio-->p-->float """ #Entradas e1=int(input("Ingrese la edad de la primera persona: ")) e2=int(input("Ingrese la edad de la segunda persona: ")) e3=int(input("Ingrese la edad de la tercera persona: ")) #Caja negra p=(e...
""" Vigenere Cipher The Vigenere Cipher is a poly-alphabetic substitution cipher that uses a set of shift ciphers and a keyword. One of the simplest ciphers is the Caesar/shift cipher, where each letter in the plaintext message is replaced by the letter a particular number of positions up, or downstream in the alphabe...
#! /usr/bin/env python3 n = input("Entrez un nombre :") n = int(n) if(n == 42): print("C'est LA réponse") if((n % 2) == 0): print("Pair !") else: print("Impair") if(n>0): print("Positif") elif(n<0): print("Négatif") else: print("Nul") print( "Pair" if (n%2 == 0) else "Impair" )
""" Asked by: Google [Medium]. On our special chessboard, two bishops attack each other if they share the same diagonal. This includes bishops that have another bishop located between them, i.e. bishops can attack through pieces. You are given N bishops, represented as (row, column) tuples on a M by M chessboard. W...
class Agent: ''' Base class for all agents ''' def __init__(self, player): self.player = player pass def get_next_action(self, game_env): ''' Evaluates the game environment and returns the next best action according to the agent Arguments: ...
class InvalidTag(Exception): pass class IgnoreObject(Exception): def __init__(self, original_exception=None, trback=None, *args, **kwargs): super(Exception, self).__init__(*args, **kwargs) self.original_exception = original_exception self.trback = trback class UnknownProtocol(Except...
""" 小明买一个西瓜还差5元,小花买这个西瓜还差10元,两人的钱加在一起还差3元。请问西瓜多少钱? """ def qian(a, b, c): x = a - c y = x + b return y z = qian(5, 10, 3) print(z)
commands = { 'app': { 'label': 'Application', 'actions': { 'neweditor': { 'label': 'New SQL editor', 'description': 'Open new SQL editor', 'icon': 'document-new-symbolic', 'shortcut': '<Control>N', 'callback'...
"""Wrapper service for kraken api.""" class ApiService: """Serivce for kraken api call.""" def __init__(self): """Create service object.""" pass
# squares = [] # for value in range(1,11): # squares.append(value ** 2); # print(squares); squares = [value ** 2 for value in range(1,11)] print(squares)
""" LeetCode Problem: 79. Word Search Link: https://leetcode.com/problems/word-search/ Language: Python Written by: Mostofa Adib Shakib Number of rows = M Number of columns = N Average time complexity: O(M*N * dfs complexity) Space Complexity: O(M*N) Worst-case time complexity: If the dfs traverses in a zigzag fash...
# Copyright (C) 2016-2017 Perceval Wajsburt <perceval.wajsburt@gmail.com> # # This module is part of SublimeTerm and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php class SpecialChar: NEW_LINE = '\n' TAB = '\t' BEL = '\x07' BACKSPACE = '\x08' DEL = '\x7f' ...
''' Exercício Python 070: Crie um programa que leia o nome e o preço de vários produtos. O programa deverá perguntar se o usuário vai continuar ou não. No final, mostre: A) qual é o total gasto na compra. ''' print('-' * 30) print('{:^30}'.format(' LOJA SUPER BARATÃO ')) print('-' * 30) menorPreco = preco = totPreco ...
class Passenger: def __init__(self, passenger_id, source, destination, spawn_time, controller): self.passenger_id = passenger_id self.destination = destination self.source = source self.spawn_time = spawn_time self.current_stop = source self.controller = controller ...
n = int(input()) x = int(input()) li = list(map(int, input().split())) l = [0]*n print(*l,sep=" ") if (x): print("YES") else: print("NO")
print('-'* 30) print('\033[:31mCALCULADOR AUMENTO DE SALÁRIO\033[m') print('-'* 30) salario = float(input('Qual o salário? ')) aumento = salario + (salario * 15 / 100) print(f'O funcionário que recebia {salario:.2f} com 15% de aumento\n' f'agora vai receber {aumento:.2f}')
VERIFY_EMAIL_TOKEN_EXPIRES = 24*60*60 # 用户地址数据上限 USER_ADDRESS_COUNTS_LIMIT = 20 #用户浏览历史 USER_BROWSING_HISTORY_COUNTS_LIMIT = 5
distance = 1.500 years = 1 days_training = 200 times_year = years * days_training sum_distance = 0 kkal_ksu = 0 kkal_mity = 0 kkal_km = [50, 110] for i in range(times_year): sum_distance += distance kkal_ksu = kkal_km[0] * sum_distance kkal_mity = kkal_km[1] * sum_distance print('Количество тренировок:', times_...
print("holis") #TODO agregar la linea intermedia print("holis") #print("holis") print("holis") print("holis") #TODO agregar la linea numero 6
class TrainingStatus: NEW = "NEW" NEW_LOAD_MODEL = "NEW_LOAD_MODEL" STARTED = "STARTED" FINISHED = "FINISHED"
# # PySNMP MIB module ALTIGA-HARDWARE-STATS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALTIGA-HARDWARE-STATS-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:21:29 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3....
def Adj2GraphID(adj): n = adj.shape[0] GraphID = str(n)+"_" binID = '' for i in range(n): for j in range(i+1,n): binID += str(int(adj[i][j])) GraphID += hex(int(binID,2)).split('x')[1] return GraphID.upper() def GraphID2Adj(GraphID): n_str, hexID = GraphID.split("_") ...
#-*- coding: utf-8 -*- class INSERT(object): def __init__(self, schema, target): self._sql = u"INSERT INTO {}.{}".format( schema, target) def VALUES(self, fields): values = ", ".join(["%(" + field + ")s" for field in fields]) self._sql += "({}) values({})".format(", ".joi...
def calculateEMA(period, data): returnData = {} emaList = [] key = 'ema' + str(period) if data: historicalEma = data[0] e = 2/(period + 1) for i in range(len(data)): ema = (data[i] - historicalEma) * e + historicalEma historicalEma = ema emaLi...
""" Tema: Complejidad Algoritmica. Conteo abstracto Curso: Pensamiento Computacional, 2da entrega. Plataforma: Platzi. Profesor: David Aroesti. Alumno: @edinsonrequena. """ def f(x): respuesta = 0 for i in range(1000): print(i) respuesta += 1 for i in range(x): respuesta += x ...
def test(): # Here we can either check objects created in the solution code, or the # string value of the solution, available as __solution__. A helper for # printing formatted messages is available as __msg__. See the testTemplate # in the meta.json for details. # If an assertion fails, the messag...
############################################################ # # uploadhaddocks # Copyright (C) 2017, Richard Cook # Released under MIT License # https://github.com/rcook/upload-haddocks # ############################################################ __project_name__ = "upload-haddocks" __version__ = "0.5" __descriptio...
# エラトステネスの篩, 素因数分解 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 sie...
''' ''' # Implement a quicksort items = [20, 6, 8, 53, 56, 23, 87, 41, 49, 19] def quickSort(dataset, first, last): # Comparo el inificio y el final. if first < last: # calculate the split point pivotIdx = partition(dataset, first, last) # now sort the two partitions #Izqu...
# standard libraries pass # third party libraries pass # first party libraries pass alphanumeric = 'abcdefghijklmnopqrstuvwxyz' \ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \ '123456789' # alphanumerics unlikely to be mistaken for each other legible = 'abcdefghijkmnopqrstuvwxyz' \ 'ABCDEFGH...
self.description = "Upgrade packages with various reasons" lp1 = pmpkg("pkg1") lp1.reason = 0 lp2 = pmpkg("pkg2") lp2.reason = 1 for p in lp1, lp2: self.addpkg2db("local", p) p1 = pmpkg("pkg1", "1.0-2") p2 = pmpkg("pkg2", "1.0-2") for p in p1, p2: self.addpkg(p) self.args = "-U %s" % " ".join([p.filename() for p...
class Interval: def __init__(self, start=0, end=0): self.start = start self.end = end
PATH_TRAIN = "../../data/train.csv" PATH_VALID = "../../data/valid.csv" PICKLES_PATH = "./pickles" TRAIN = "../../data/train.tsv" TEST = "../../data/test.tsv" DEV = "../../data/dev.tsv"
class Libro: #definimos todos los atributos que caracteizan a un libro isbn=0 #texto autor=0 titito=0 #texto año_de_publicacion=0 #texto idioma=0 #texto editor=0 ejemplares=0 #texto #ahora creamos el constructor def __init__(self, isbn,autor, titulo, año_de_publi...
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def deps(repo_mapping = {}): if "com_github_nodejs_http_parser" not in native.existing_rules(): http_archive( name = "com_github_nodejs_http_parser", # This commit includes fix for # https://github.com/...
def BaseHTTPRequestHandler(*args, **kwargs): pass def Camera(*args, **kwargs): pass def GSprint(*args, **kwargs): pass def GSversion(*args, **kwargs): pass def GW(*args, **kwargs): pass def GlowWidget(*args, **kwargs): pass def HTTPServer(*args, **kwargs): pass def INTERACT_PERIOD(*args, **kwargs): pass def MAX_RENDERS...
spreadsheet = [[5806,6444,1281,38,267,1835,223,4912,5995,230,4395,2986,6048,4719,216,1201], [74,127,226,84,174,280,94,159,198,305,124,106,205,99,177,294], [1332,52,54,655,56,170,843,707,1273,1163,89,23,43,1300,1383,1229], [5653,236,1944,3807,5356,246,222,1999,4872,206,5265,5397,5220,5538,286,917], [3512,3132,2826,3664,...
#!/usr/bin/python # coding=UTF-8 """ Criado em 16 de Janeiro de 2017 Descricao: esta biblioteca possui as seguintes funcoes: readArq_DadosTemporais: esta funcao faz a leitura do arquivo Arquivo_DadosTemporais gerado pela funcao criaArq_DadosTemporais, retornando os parametros e tabelas nela contidos. re...
a = [0] for i in range(1000000): a[0] = i
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ret = [[]...
pkgname = "nasm" pkgver = "2.15.05" pkgrel = 0 build_style = "gnu_configure" make_cmd = "gmake" make_dir = "." make_check_target = "test" hostmakedepends = ["gmake"] checkdepends = ["perl"] pkgdesc = "80x86 assembler designed for portability and modularity" maintainer = "q66 <q66@chimera-linux.org>" license = "BSD-2-Cl...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: l=[] l1=list1 l2=list2 ...
class CifsBcVersionControl(basestring): """ Versions of CIFS BranchCache that are currently supported. """ @staticmethod def get_api_name(): return "cifs-bc-version-control"
# coding: utf-8 n = int(input()) sta = [i for i in ''.join(input().split()).split('0') if i != ''] ans = 0 for i in sta: ans += 2+len(i)-1 if ans != 0: print(ans-1) else: print(0)
#Question Link #https://practice.geeksforgeeks.org/problems/find-pair-given-difference/0 for _ in range(t): L,N = map(int,input().split()) arr = list(map(int,input().split())) arr.sort() flag = -1 i =0 j = L-1 for i in range(len(arr)): for j in range(i+1,len(arr)): if ...
class Solution(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ dict = {} for word in strs: sorted_word = ''.join(sorted(word[:])) if sorted_word in dict: dict[sorted_word].append(wor...
def glen(generator): """ len implementation for generators. """ return sum(1 for _ in generator)
''' https://practice.geeksforgeeks.org/problems/sort-an-array-of-0s-1s-and-2s/0 ''' def sort_z_o_t(A): count = [0 for i in range(3)] for i in A: count[i] += 1 aIdx = 0 for i, n in enumerate(count): while n > 0: A[aIdx] = i n -= 1 aIdx += 1 if __name...
ll = [] for i in range(0, 3): ll.append(int((input('Digite um número: ')))) print('Lista 1:', ll) # Inverte a lista ll.reverse() print('Lista 2:', ll)
def for_a(): """printing small 'a' using for loop""" for row in range(7): for col in range(4): if col==3 and row!=0 or col==0 and row not in(0,2,3,6) or row==3 and col in(1,2) or row==6 and col in(1,2) or row==0 and col in(1,2): print("*",end=" ") else: ...
class Algorithm: def __init__(self, np, ic, h, force, params): self.np = np self.h = h self.sq2h = np.sqrt(2 * h) self.sqh2 = np.sqrt(h / 2) self.h2 = h / 2 self.force = force self.acc = 0 fres = self.force(ic) self.v, self.f, self.ff = ( ...
expected_output = { 'type': { 'BYTE': { 'allocated': 7045122, 'allocations': 737743, 'frees': 734750, 'requested': 6877514, }, 'BYTE*': { 'allocated': 29128, 'allocations': 345, 'frees': 309, 'req...
"""bin 405. Convert a Number to Hexadecimal Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used. Note: All letters in hexadecimal (a-f) must be in lowercase. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is repr...
class Solution: def validPalindrome(self, s: str) -> bool: def isValid (s,i,j): while i < j: if s[i] != s[j]: return False i += 1 j -= 1 return True i ,j = 0,len(s) while i < j: if s[i] != s[j]: return isValid(s, i + 1, j) or isValid(s, i , j - 1...
#!/usr/bin/env python3 #A palindromic number reads the same both ways. #The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. # #Find the largest palindrome made from the product of two 3-digit numbers. def find_palindrome(n_digits): is_palendrome = lambda s: s[:len(s)] == s[le...
class QueryDeviceGroupsInDTO(object): def __init__(self): self.accessAppId = None self.pageNo = None self.pageSize = None self.name = None def getAccessAppId(self): return self.accessAppId def setAccessAppId(self, accessAppId): self.accessAppId = accessAppI...
''' The MIT License (MIT) Copyright (c) 2016 WavyCloud Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, p...
# parsetab.py # This file is automatically generated. Do not edit. _lr_method = 'LALR' _lr_signature = 'XP\xd6":$v\xd1\xacQ\xe2\x1d\xc8\x10T\xa2' _lr_action_items = {'VOID':([118,261,15,238,171,3,50,37,359,33,170,24,68,197,284,328,361,12,2,141,39,29,73,173,232,288,222,60,166,8,21,281,82,135,65,168,239,0,13,388,27,2...
""" Author: Srayan Gangopadhyay 2020-08-06 met.no symbol names mapped to emoji """ symbols = { 'fog': '🌫', 'heavyrain': '🌧', 'heavyrainandthunder': '⛈', 'heavyrainshowers_day': '🌧', 'heavyrainshowers_night': '🌧', 'heavyrainshowers_polartwilight': '🌧', 'heavyrainshowersandthunder_day':...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # @author JourWon # @date 2021/12/29 # @file pyIf.py if __name__ == "__main__": n = 10 if n < 0: print(-1) elif n == 0: print(0) else: print(1)
n=int(input()) s=input() s=s.split(' ') m=int(input()) v=0 p=0 b=input() b=b.split(' ') for x in range(0,m): a=int(b[x]) for i in range(0,n): if a==int(s[i]): v=v+i+1 p=p+n-i print(str(v)+' '+str(p))
# Uzd. Nr.3 num = int(input("Please Enter a number that you would like to check: ")) #input a number to check if num > 1: # to exclude all numbers < 2, those are not prime numbers for i in range(2, int(num**0.5)+1): #loop for checking the number (square root) # same result will be ### for...
class Solution: def isAnagram(self, s: str, t: str) -> bool: len1, len2 = len(s), len(t) if len1 != len2: return False elif len1 == 1: if s!= t: return False else: return True else: dict1 = {} ...