content
stringlengths
7
1.05M
freeze_as_mpy('$(MPY_DIR)/tools', 'upip.py') freeze_as_mpy('$(MPY_DIR)/tools', 'upip_utarfile.py', opt=3) freeze('$(MPY_DIR)/lib/lv_bindings/driver/linux', 'evdev.py') freeze('$(MPY_DIR)/lib/lv_bindings/lib', 'lv_colors.py') freeze('$(MPY_DIR)/lib/lv_bindings/lib', 'async_utils.py') freeze('$(MPY_DIR)/lib/lv_bindings/l...
"""Top-level package for Structured and Interactive Summarization.""" __author__ = """Mélanie Cambus, Marc-Olivier Buob, Fabien Mathieu""" __email__ = 'fabien.mathieu@normalesup.org' __version__ = '0.2.0'
NAME='fastrouter' CFLAGS = [] LDFLAGS = [] LIBS = [] REQUIRES = ['corerouter'] GCC_LIST = ['fastrouter']
# implicit conversion num_int=123 num_float=1.23 result=num_int+num_float print('datatype of num_int is',type(num_int)) print('datatype of num_float is',type(num_float)) print('datatype of result is',type(result)) # it automatically converts int to float to avoid data loss
def solution(n, votes): vote_counter = [0 for i in range(n+1)] # 각 후보가 몇 표를 받았는지 개수를 세는 것 for i in votes: vote_counter[i] += 1 # 표의 수 중에서 최대 max_val = max(vote_counter) print(f'vote_counter={vote_counter}, max_val={max_val}') answer = [] for idx in range(1, n + 1): if vot...
class Body(object): def __init__(self, mass, position, velocity, name = None): if (name != None): self.name = name self.mass = mass self.position = position self.velocity = velocity
# -- coding: utf-8 -- """Collection of defaults assumed by the download script. The defaults are all the allowed values for each of the variables. More details are available are Copernicus Climate Data Store [0]. [0] https://cds.climate.copernicus.eu/cdsapp """ def time(): return [ "00:00", "01:...
def _wrapper(page): """ Wraps some text in common HTML. """ return (""" <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <style> body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; max-width: 24em; ...
"""Kata: Sum of odd numbers Given the triangle of consecutive odd numbers \ calculate the row sums of this triangle from the row index. #1 Best Practices Solution by kevinplybon (plus 546 more warriors): def row_sum_odd_numbers(n): return n ** 3 """ def row_sum_odd_numbers(n): """function takes in number ...
"""Metadata for readcomp""" __title__ = "readcomp" __description__ = "Reading comprehension passage generator" __url__ = "https://github.com/acciochris/readcomp" __version__ = "0.1.0" __author__ = "Chang Liu" __license__ = "MIT" __copyright__ = "Copyright 2020 Chang Liu"
def config(args): """ This command configure eggs """ print("configure eggs")
"""lds-bde-loader exception classes.""" class Error(Exception): """Generic errors.""" def __init__(self, msg): super(Error, self).__init__() self.msg = msg def __str__(self): return "%s: %s" % (self.__class__.__name__, self.msg) class ConfigError(Error): """Config related err...
""" Project Euler Problem 3: Largest Prime Factor """ # What is the largest prime factor of the number 600851475143? number = 600851475143 prime_list = [2] # Declare the list of prime numbers i = 3 # First prime number j = 0 # Initialize index counter while i**2 <= number: # The largest pos...
"""Class represents response format. { status, successful/fail data, response msg, error messages } """ def ok(data): return { "data": data, "msg": None, "status": "successful" } def err(msg): return { "data": None,...
#!/usr/bin/env python3 # https://www.codechef.com/JULY18A/problems/JERRYTOM def max_clique(g): n = 0 for x in g: n = max(n, len(x)) l = [set() for _ in range(n + 1)] s = [0] * len(g) for i, x in enumerate(g): ll = len(x) l[ll].add(i) s[i] = ll m = 0 for _ in range(len...
# follow pytorch GAN-Studio, random flip is used in the dataset _base_ = [ '../_base_/models/sngan_proj_32x32.py', '../_base_/datasets/cifar10_nopad.py', '../_base_/default_runtime.py' ] num_classes = 10 model = dict( num_classes=num_classes, generator=dict( act_cfg=dict(type='ReLU', inplace=T...
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/lty/catkin_ws/src/driver/joystick/joystick_drivers/wiimote/msg/IrSourceInfo.msg;/home/lty/catkin_ws/src/driver/joystick/joystick_drivers/wiimote/msg/State.msg;/home/lty/catkin_ws/src/driver/joystick/joystick_drivers/wiimote/msg/TimedSwitch.msg" ...
num1=10 num2=20 num3=300 num3=30 num4=40
# -*- coding: utf-8 -*- def bytes(num): for x in ['bytes','KB','MB','GB']: if num < 1024.0 and num > -1024.0: return "{0:.1f} {1}".format(num, x) num /= 1024.0 return "{0:.1f} {1}".format(num, 'TB')
#inputs_pdm.py # #Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. #The Universal Permissive License (UPL), Version 1.0 # #by Joe Hahn, joe.hahn@oracle.come, 11 September 2018 #input parameters used to generate mock pdm data #turn debugging output on? debug = True #number of devices N_devices = ...
soma=0 cont=0 for c in range(1,501,2): if c%3==0: cont=cont + 1 soma=soma + c print('A soma de todos os {} valores solicitados é {}.'.format(cont,soma))
basepath = "<path to dataset>" with open(basepath+"/**/train_bg/wav.scp") as f: lines = f.read().strip().split('\n') for line in tqdm.tqdm(lines): # name, _ = line.strip().split('\t') name = line.strip().split(' ')[0] shutil.copy(basepath+"/audio/"+name+".flac", basepath+"/**/train_wav/"+name+".fl...
def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. """ result = {} for dictionary in dict_args: result.update(dictionary) return result def move_to_end(d, k): v = d.pop(k) d...
#!/usr/bin/env python code_file = 'node_modules/terser-webpack-plugin/dist/TaskRunner.js' bad_code = 'const cpus = _os2.default.cpus() || { length: 1 };' good_code = 'const cpus = { length: 1 };' new_text = None with open(code_file) as f: print('Reading %s' % code_file) file_content = f.read() if bad_co...
''' Created on 2016年1月22日 @author: Darren ''' ''' Given N integers, count the number of pairs of integers whose difference is K. Input Format The first line contains N and K. The second line contains N numbers of the set. All the N numbers are unique. Output Format An integer that tells the number of pairs of int...
class ParsimoniousError(Exception): def __init__(self, exception): """ A class for wrapping parsimonious errors to make them a bit more sensible to users of this library. :param exception: The original parsimonious exception :return: self """ self.exception = except...
A, B = map(int,input().split()) a = str(A) b = str(B) new_a1 = int(a[0]) new_a2 = int(a[1]) new_a3 = int(a[2]) new_a = new_a3 * 100 + new_a2 * 10 + new_a1 * 1 new_b1 = int(b[0]) new_b2 = int(b[1]) new_b3 = int(b[2]) new_b = new_b3 * 100 + new_b2 * 10 + new_b1 * 1 if new_a > new_b: print(new_a) else: print(n...
#!/usr/bin/env python # -*- coding: utf-8 -*- class ErrorObj: def __init__(self, code, message): self.code = code self.message = message EOBJ_PARSE_ERROR = ErrorObj(-32700, 'parse error.') EOBJ_INVALID_REQUEST = ErrorObj(-32600, 'invalid request.') EOBJ_METHOD_NOT_FOUND = ErrorObj(-32601, 'metho...
W = 25 H = 6 with open("input.txt") as fin: file = fin.read().strip() layers = [] for i in range(0, len(file), W * H): layer = [] for j in range(i, i + W * H, W): layer.append(file[j: j + W]) layers.append(layer) def p1(): zeros = float("inf") l = 0 for i, ...
# The interval between temperature readings in seconds READINGS_INTERVAL = 600 DATA_PIN = 3 SCX_PIN = 2 REDIS_HOST = 'localhost' REDIS_PORT = 6379 LAST_MEASUREMENT_KEY = 'last_measurement' LAST_MEASUREMENT_KEY_TEMPLATE = 'measurement_{}' TIME_KEY = 'time' TEMPERATURE_KEY = 'temperature' HUMIDITY_KEY = 'humidity' PREV_...
""" __init__.py ~~~~~~~~ 服务类 2020/9/2 """
mistring = 'Curso de python3' print(mistring [0:10]) palabra ="hola" print (len(palabra))
def Insertion_Sort(alist): ''' Sorting alist via Insertion Sort ''' for index in range(1, len(alist)): currentValue = alist[index] position = index while position > 0 and alist[position-1] > currentValue: alist[position] = alist[position-1] position = posi...
""" Module :module:`shelter.core.constants` contains useful constants used in Shelter. """ __all__ = ['SERVICE_PROCESS', 'TORNADO_WORKER'] SERVICE_PROCESS = 'service_process' """ Indicates that type of the process is a service process. *kwargs* argument in method :meth:`shelter.core.context.initialize_child` contains...
class ConnectGame: def __init__(self, board): self.board = board.replace(' ', '').split('\n') def get_winner(self): print(self.board) visited = set() to_visit = [] directions = [(-1, 0), (0, -1), (1, -1), (1, 0), (0, 1), (-1, 1)] ...
def get_parameter_value(fhir_operation, parameter_name): """ Find the parameter value provided in the parameters :param fhir_operation: the fhir operation definition :param parameter_name: the name of the parameter to get the value of :return: a string representation of th value """ p...
# -*- coding: utf-8 -*- loc_departments = [ "Ain","Aisne","Allier","Alpes de Hautes-Provence", "Hautes-Alpes", "Alpes-Maritimes","Ardèche","Ardennes","Ariège", "Aube","Aude", "Aveyron","Bouches-du-Rhône","Calvados","Cantal", "Charente", "Charente-Maritime","Cher","Corrèze","Corse-du-Sud", "Haute-Co...
load("//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external") def dependencies(): import_external( name = "javax_servlet_javax_servlet_api", artifact = "javax.servlet:javax.servlet-api:3.1.0", jar_sha256 = "af456b2dd41c4e82cf54f3e743bc678973d9fe35bd4d3071fa05c7e5333b8482...
primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31} def is_prime(n): if n in primes: return True else: if n == 1: return False i = 2 while i*i <= n: if n % i == 0: return False i += 1 primes.add(n) return True for _ in range(int(input())): N = int(input()) if is_prime(N): print(N, N) e...
class NaryConfig: def __init__( self, embedding_size=300, hidden_size=150, vocab_size=10000, hidden_dropout_prob=0., cell_type='lstm', use_attention=False, use_bert=False, tune_bert=False, normalize_bert_embeddings=False, xav...
class Foo: num1 : int num2 : int foo1 = Foo() id_foo1_before = id(foo1) foo1.num1 = 1 id_foo1_after = id(foo1) if id_foo1_before == id_foo1_after: print('Foo is immutable') else: print('Foo is mutable')
# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0 # which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 # """The official list of format hints that text renderers and plugins can rely upon existing within the framework. These hints allow ...
def cadicao(n1,n2): return n1 + n2 def csubtracao (n1,n2): return n1 - n2 def cdivisao (n1,n2): return n1 / n2 def cdivisaoint (n1,n2): return n1 // n2 def cmultiplicacao (n1,n2): return n1 * n2 def cpotenciacao(n1,n2): return n1 ** n2 def craiz (n1,n2): return n1 ** (1/n2) def c...
def main(): print('Please enter x as base and exp as exponent.') try: while 1: x = float(input('x = ')) exp = int(input('exp = ')) print("%.3f to the power %d is %.5f\n" % (x,exp,x ** exp)) print("Please enter next pair or q to quit.") except:print('Ho...
# !/usr/bin/python """ Copyright ©️: 2020 Seniatical / _-*™#7519 License: Apache 2.0 A permissive license whose main conditions require preservation of copyright and license notices. Contributors provide an express grant of patent rights. Licensed works, modifications, and larger works may be distributed under ...
def define_targets(rules): rules.cc_library( name = "TypeCast", srcs = ["TypeCast.cpp"], hdrs = ["TypeCast.h"], linkstatic = True, local_defines = ["C10_BUILD_MAIN_LIB"], visibility = ["//visibility:public"], deps = [ ":base", "//c10/co...
v = input("digite um valor em dias: ") a = int(int(v)/365) m = int((int(v)%365)/30) d = int((int(v)%365)%30) print(str(a)+" ano(s)") print(str(m)+" mes(es)") print(str(d)+" dias(s)")
"""Re-export of some bazel rules with repository-wide defaults.""" load("@bazel_tools//tools/build_defs/pkg:pkg.bzl", "pkg_tar") load("@build_bazel_rules_nodejs//:index.bzl", _nodejs_binary = "nodejs_binary", _pkg_npm = "pkg_npm") load("@npm_bazel_jasmine//:index.bzl", _jasmine_node_test = "jasmine_node_test") load("@...
class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: nums.sort() opt = float("inf") for i in range(len(nums)): # Fix one integer fixed = nums[i] newTarget = target-fixed l,r = i+1, len(nums)-1 while(l<r): ...
class MetricUnitError(Exception): pass class SchemaValidationError(Exception): pass class MetricValueError(Exception): pass class UniqueNamespaceError(Exception): pass
# is_lower_case # # Checks if a string is lower case. # # Convert the given string to lower case, using str.lower() method and compare it to the original. def is_lower_case(string): return string == string.lower() is_lower_case('abc') # True is_lower_case('a3@$') # True is_lower_case('Ab4') # False
""" https://leetcode.com/problems/invert-binary-tree/ Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 Trivia: This problem was inspired by this original tweet by Max Howell: Google: 90% of our engineers use the software...
# Faça um Programa que peça dois números e imprima a soma. def somar(parametro, parametro_2): return parametro + parametro_2 class Calcular: def __init__(self, numero_1=0, numero_2=0): self.numero_1 = numero_1 self.numero_2 = numero_2 def juntar(self): numero_s = self.numero_1 +...
def swap(num1, num2): num1 = int(num1) num2 = int(num2) numbers[num1], numbers[num2] = numbers[num2], numbers[num1] #print(numbers) return def multiply(num1, num2): num1 = int(num1) num2 = int(num2) mult = numbers[num1] * numbers[num2] numbers.pop(num1) numbers.insert(num1, mul...
""" 18. How to convert the first character of each element in a series to uppercase? """ """ Difficulty Level: L2 """ """ Change the first character of each word to upper case in each word of ser. """ """ ser = pd.Series(['how', 'to', 'kick', 'ass?']) """
# Class Variable class Employee: no_of_emp = 0 raise_amount = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + "." + last + "@gmail.com" Employee.no_of_emp += 1 def apply_raise(self): s...
#Written by: Karim shoair - D4Vinci ( Dr0p1t-Framework ) #In this script I store some SE tricks to use ;) #Start #Get the user password by fooling him and then uses it to run commands as the user by psexec to bypass UAC def ask_pwd(): while True: cmd = '''Powershell "$cred=$host.ui.promptforcredential('Windows fire...
main = { 'General': { 'Prop': { 'Labels': 'rw', 'AlarmStatus': 'r-' } } } cfgm = { 'Logicalport': { 'Cmd': ( 'Create', 'Delete' ) } }
model = dict( type='MonoRUnDetector', pretrained='torchvision://resnet101', backbone=dict( type='ResNet', depth=101, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='p...
#!/usr/bin/env python3 class Test: @classmethod def assert_equals(cls, func_out, expected_out): assert func_out == expected_out, f"The function out '{func_out}' != '{expected_out}'"
def max(a, b): if a > b: return a elif b > a: return b else: return 'a = b' print(max(123,445))
kernel = [1,0,1] # averaging of neighbors #kernel = np.exp(-np.linspace(-2,2,5)**2) ## Gaussian kernel /= np.sum(kernel) # normalize smooth = np.convolve(y, kernel, mode='same') # find the average value of neighbors rms_noise = np.average((y[1:]-y[:-1])**2)**.5 # estimate what the average no...
# 숫자의 표현 def solution(n): answer = 0 numSum = 0 sNum = 1 for i in range(1, n+1): numSum += i while numSum > n: numSum -= sNum sNum += 1 if numSum == n: answer += 1 return answer ''' 채점을 시작합니다. 정확성 테스트 테스트 1 〉 통과 (0.0...
def boolean_true(): return value # Change the varable named value to the correct answer print(boolean_true())
iot_devices = { "cl01": "HostName=znetinnn12ioth01.azure-devices.net;DeviceId=cl01;SharedAccessKey=C3lI2jbo0DVgPtUqMjg7BYxXpBRvGsvXCCP/33zRK34=", # Cristian's Device "js01": "HostName=znetinnn12ioth01.azure-devices.net;DeviceId=js01;SharedAccessKey=9g4Qmbfoi/WZPNTA3HqePqrCjYd1mtj15CKu8hMow9Y=", # John's Devic...
## ## Programación en Python ## =========================================================================== ## ## Para el archivo `data.csv, imprima una tabla en formato CSV que contenga ## la cantidad de registros en que aparece cada clave de la columna 5. ## ## Rta/ ## aaa,13 ## bbb,16 ## ccc,23 ## ddd,23 #...
""" Red, green or blue tiles """ def f(m, n): ways = [0] * (n + 1) for i in range(m): ways[i] = 1 for i in range(m, n + 1): ways[i] += ways[i - 1] + ways[i - m] return ways[n] - 1 if __name__ == '__main__': print(f(2, 50) + f(3, 50) + f(4, 50))
"""Constants for HTTP""" class HttpConstants: HTTP_METHOD_GET = 'GET' HTTP_METHOD_POST = 'POST' HTTP_METHOD_PUT = 'PUT' HTTP_METHOD_OPTIONS = 'OPTIONS' HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin' @staticmethod def http_method_get(): """Returns the HTT...
__title__ = 'fobi.contrib.plugins.form_elements.fields.input.constants' __author__ = 'Artur Barseghyan <artur.barseghyan@gmail.com>' __copyright__ = '2014-2017 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ( 'FORM_FIELD_TYPE_CHOICES', 'FIELD_TYPE_TO_DJANGO_FORM_FIELD_MAPPING', 'FIELD_TYPE_TO_DJAN...
t = int(input()) ans = [] for testcase in range(t): n, m = [int(i) for i in input().split()] if (n == 2) and (m == 2): folds = [] for i in range(n): folds += [int(i) for i in input().split()] for i in range(n - 1): folds += [int(i) for i in input().split()] ...
#This is ACSL 2018 ALl-Star Problem. This code is written by Robin Gan. And it is incompleted. #more info check out acsl.org #probelm name=Compressed_Tree def main(): global orgSet global editSet global targetWord global answerStr answerStr="" ipl=input() useWord=ipl[0:len(ipl)-1...
class StartAppReportObject: def __init__(self, result): self.data = result["data"] def __eq__(self, other): if type(other) != type(self): return False if self.data == other.data: return True return False
string_to_revers = input() for x in string_to_revers[::-1]: print(x, end='')
frase = str(input('Digite uma frase: ')).strip().split() junto = ''.join(frase).upper() inverso = junto[::-1] print(f'A frase {junto}') print(f'Ivertida e {inverso}') if inverso == junto: print(f'A frase digitada é um palindromo') else: print('A frase não e um palindromo')
#!/usr/bin/python # Copyright 2015 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Subcommand codes that specify the crypto module.""" # Keep these codes in sync with include/extension.h. AES = 0 HASH = 1
## Mel-filterbank mel_window_length = 50 # In milliseconds 25 mel_window_step = 10 # In milliseconds 10 mel_n_channels = 40 ## Audio sampling_rate = 16000 # Number of spectrogram frames in a partial utterance partials_n_frames = 160 # 1600 ms # Number of spectrogram frames at inference inference_n...
src = Split(''' base64.c ''') component = aos_component('base64', src)
""" Flux employs a basic data model built from basic data types. The data model consists of tables, records, columns. """ class FluxStructure: """The data model consists of tables, records, columns.""" pass class FluxTable(FluxStructure): """A table is set of records with a common set of columns and a...
jogador = {} gols = [] soma = 0 nome = input('Digite o nome do jogador: ') partidas = int(input(f'Quantas partidas o {nome} jogou: ')) for i in range(0, partidas): gol = int(input(f'Digite quantos gols na {i}: ')) soma += gol gols.append(gol) jogador['Nome'] = nome jogador['Partidas'] = partidas jogador['Go...
# Copyright (c) 2018-2020 Simons Foundation # # 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.txt # # Unless required by applicable law or agre...
def method1(n: int) -> int: divisors = [d for d in range(2, n // 2 + 1) if n % d == 0] return [d for d in divisors if all(d % od != 0 for od in divisors if od != d)] if __name__ == "__main__": """ from timeit import timeit print(timeit(lambda: method1(20), number=10000)) # 0.028740440000547096 ...
def _revisions(revs, is_dirty): revisions = revs or [] if len(revisions) <= 1: if len(revisions) == 0 and is_dirty: revisions.append("HEAD") revisions.append("working tree") return revisions def diff(repo, *args, revs=None, **kwargs): return repo.plots.show( *args, ...
# -*- encoding: utf-8 -*- """ Created by Ênio Viana at 15/10/2021 at 22:19:09 Project: py-dss-vis [out, 2021] """ class Line: def __init__(self): self._name = "Line" @property def name(self): return self._name
cities = [ 'Santa Cruz de la Sierra', 'Cochabamba', 'La Paz', 'Sucre', 'Oruro', 'Tarija', 'Potosi', 'Sacaba', 'Montero', 'Quillacollo', 'Trinidad', 'Yacuiba', 'Riberalta', 'Tiquipaya', 'Guayaramerin', 'Bermejo', 'Mizque', 'Villazon', 'Llallagua...
while(True): try: n = int(input()) if(n==2002): print("Acesso Permitido") break else: print("Senha Invalida") except EOFError: break
class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f'Person(name={self.name}, age={self.age}' def __eq__(self, other): if isinstance(other, Person): return self.name == other.name and self.age == other.age ...
# Author : Salim Suprayogi # Ref : freeCodeCamp.org ( youtube ) def translate(phrase): "mengganti huruf tertentu" translation = "" # loop for letter in phrase: # cek apakah ada huruf AEIOUaeiou # jika ada ganti dengan huruf "g" if letter.lower() in "aeiou": ...
# -*- coding: utf-8 -*- ''' File name: code\prime_subset_sums\sol_249.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #249 :: Prime Subset Sums # # For more information see: # https://projecteuler.net/problem=249 # Problem Statement '''...
#!/bin/python3 DIRECTIONS = { 'n': (0, -1), 's': (0, 1), 'e': (1, 0), 'w': (-1, 0), } def get_route(preferred_direction): x_pos, y_pos = preferred_direction return [ preferred_direction, (y_pos, x_pos), (-y_pos, -x_pos), (-x_pos, -y_pos) ] class Boar...
class Solution(object): def isUgly(self, num): """ :type num: int :rtype: bool """ if num < 1: return False bad_factors = (2, 3, 5, ) stack = [num] while len(stack) > 0: x = stack.pop() if x ...
""" 349. Intersection of Two Arrays Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. """ # binary search class Solution(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ ...
class FriendshipsStorage(object): def __init__(self): self.friendships = [] def add(self, note): pass def clear(self): pass def get_friends_of(self, name): pass
#Implemente um programa que faça a leitura de valores para uma lista com as #classificações (inteiras) de uma turma de 20 alunos. Acrescente ao programa as #seguintes funcionalidades (usando funções): #a) Calcular a média das notas. #b) Calcular o somatório de todos as notas positivas do vetor. #c) Calcular a meno...
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: anagrams = {} for i in range(len(strs)): x= ''.join(sorted(strs[i])) if x not in anagrams: anagrams[x]=[strs[i]] else: anagrams[x].append(strs[i]) ...
# 350111 # a3_p10.py # Irakli Mtvarelishvili # i.mtvarelisvhili@jacobs-university.de n = int(input("Please enter the length of rectangle: ")) m = int(input("Please enter the width of rectangle: ")) c = chr(ord(input("Please enter a character: "))) def print_rectangle(n, m, c): for i in range(m) : ...
# yacctab.py # This file is automatically generated. Do not edit. _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'translation_unit_or_emptyleftLORleftLANDleftORleftXORleftANDleftEQNEleftGTGELTLEleftRSHIFTLSHIFTleftPLUSMINUSleftTIMESDIVIDEMOD_BOOL _COMPLEX AUTO BREAK CASE CHAR CONST CONTINUE DEFAULT DO DOUB...
""" A Trie/Prefix Tree is a kind of search tree used to provide quick lookup of words/patterns in a set of words. A basic Trie however has O(n^2) space complexity making it impractical in practice. It however provides O(max(search_string, length of longest word)) lookup time making it an optimal approach when space is ...
# 环境 : dev 开发环境 TCLOUD_ENV = 'dev' # 服务 : dev 开发环境 SERVER_ENV = 'dev' # SQL 连接字符串 SQLALCHEMY_DATABASE_URI = 'mysql://root:123456@127.0.0.1:3306/demo?charset=utf8' # 密钥相关 SECRET = '####' ALGORITHM = 'HS256' TSECRET = '####' SALT = 'asjdia8938jf9wf8923' # 任务设置 JOBS = [ { # 任务 例子:资产配置检查 'id': 'credit-check...
''' write a procedure, called how_many, which returns the sum of the number of values associated with a dictionary ''' def how_many(aDict): ''' aDict: A dictionary, where all the values are lists. returns: int, how many values are in the dictionary. ''' values = 0 for i in aDict: values...
# Solution to [Check Subset](https://www.hackerrank.com/challenges/py-check-subset) def get_set() -> set: """returns set""" _ = input() return set(map(int, input().split())) def main(): for _ in range(int(input())): set_a = get_set() set_b = get_set() a_not_b = set_a.differenc...