content stringlengths 7 1.05M |
|---|
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
class SpecialStrings:
"""Special strings in stringified turn parts.
"""
# an empty value (we need it since some library doesn't like an empty string)
NULL = "__NULL"
# indicates there is a break between the two utterance s... |
#
# @lc app=leetcode.cn id=1389 lang=python3
#
# [1389] minimum-moves-to-move-a-box-to-their-target-location
#
None
# @lc code=end |
class Post():
def __init__(self, post_json):
self.post_id = post_json["id"]
self.annotations = {}
if "annotations" in post_json:
self.annotations = post_json["annotations"]
self.user_id = post_json["user"]["id"]
self.user_followers_count = post_json["user"]["foll... |
class EntropyException(Exception):
pass
class EntropyHttpUnauthorizedException(EntropyException):
pass
class EntropyHttpMkcolException(EntropyException):
pass
class EntropyHttpPropFindException(EntropyException):
pass
class EntropyHttpNoContentException(EntropyException):
pass
class EntropyHttp... |
class Dog:
def __init__(self, name):
self.name = name
class Cat:
def __init__(self, age):
self.age = age
def classify(pet):
match pet:
case Cat(age=age):
print("A cat that's {} years old".format(age))
case Dog:
print("A dog named {}".format(pet.name))
def number(x):
match x... |
comprimento = float(input('Qual o comprimento da parede? '))
largura = float(input('Qual a largura da parede? '))
area = comprimento * largura
print(f'A parede tem a deminsão de {comprimento}x{largura} e sua área é de {area}m².')
tinta = area / 2
print(f'Para pintar a parede, você precisará de {tinta:.2f}L de tinta.'... |
# Exercise 1 and 2, PROGRAMMING AND SCRIPTING
# A program that displays Fibonacci numbers using people's names.
# Exercise 1:
# My name is David, so the fist and last letters of my name (d + d = 4 + 4) give 8.
# Fibonacci number 8 is 21.
# Exercise 2
def fib(n):
"""This function returns the nth Fibonacci numbe... |
###############EXAMPLE 4: Inputs #################
#input() function waits for an input from the keyboard
salutation = "Hello"
name = input("Tell me your name: ")
complete_salut = salutation + ', ' + name + '!'
print (complete_salut)
weight = input("Enter your weight in lb: ")
weight = int(weight) #what am I doing he... |
"""
Crie um programa que leia uma frase e diga se ela é um palindromo, a mesma coisa de frente pra tras e tras pra frente
desconsiderando os espaços
"""
frase = input('Diga uma frase: ').strip().upper()
palavras = frase.split()
palin = ''.join(palavras)
inverso = palin[::-1]
print(f'O inverso de {palin} é {inverso}.')... |
# Importação de bibliotecas
# Título do programa
print('\033[1;34;40mTUPLAS COM TIMES DE FUTEBOL\033[m')
# Objetos
times = ('Corinthians', 'Palmeiras', 'Santos', 'Grêmio', 'Cruzeiro', 'Flamengo', 'Vasco', 'Chapecoense', 'Atlético', 'Botafogo', 'Atlético-PR', 'Bahia', 'São Paulo', 'Fluminense', 'Sport Recife', 'EC Vi... |
class LegacyDatabaseRouter(object):
"""
This implements the Django DatabaseRouter protocol though we are using it to know which
role to use for the same db and to turn off migrations.
Though our underlying DB is new. We refer to this as "Legacy" because most of the time
when someone is looking to ... |
class CachePolicy:
def __init__(self):
self.cache = []
self.cache_size = 5
|
cube = lambda x: x ** 3
def fibonacci(n):
first, second = 0, 1
for i in range(n):
yield first
first, second = second, first + second
if __name__ == '__main__':
n = int(input())
print(list(map(cube, fibonacci(n))))
|
FACE_CASCADE = "C:/openCV/sources/data/haarcascades/haarcascade_frontalface_alt.xml"
EYE_CASCADE = "C:/openCV/sources/data/haarcascades/haarcascade_eye.xml"
DEFAULT_FACE_SIZE = (200, 200)
RECOGNIZER_OUTPUT_FILE = "train_result.out" |
'''
* @Author: csy
* @Date: 2019-04-28 08:29:11
* @Last Modified by: csy
* @Last Modified time: 2019-04-28 08:29:11
'''
# pizza = {
# 'crust': 'thick',
# 'toppings': ['mushrooms', 'extra cheese']
# }
# print('You order a '+pizza['crust'] +'-crust pizza with the following toppings:')
# for topping in pizza... |
split = 'exp'
dataset = 'folder'
height = 320
width = 640
disparity_smoothness = 1e-3
scales = [0, 1, 2, 3, 4]
min_depth = 0.1
max_depth = 100.0
frame_ids = [0, -1, 1]
learning_rate = 1e-4
depth_num_layers = 50
pose_num_layers = 18
total_epochs = 45
device_ids = range(8)
depth_pretrained_path = './weights/resnet{}.pth... |
def kadane(a):
max_current = max_global = a[0]
for i in range(1, len(a)):
max_current = max(a[i], max_current + a[i])
if max_current > max_global:
max_global = max_current
return max_global
n = int(input())
a = [int(x) for x in input().split()]
print(kadane(a))
|
#
# @lc app=leetcode id=22 lang=python3
#
# [22] Generate Parentheses
#
class Solution:
def parse(self, acc: str):
nl, nr = 0, 0
for c in acc:
if c == '(':
nl += 1
else:
nr += 1
return nl, nr
def gen(self, n: int, acc: str) -> List... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: certificate_profile
short_description: Resource module for Certificate Profile
description:
- Manage operations cr... |
def math():
test_case = int(input())
for i in range(test_case):
i_put = input()
count = len(i_put)
res = (count/100).__format__('.2f')
print(res)
if __name__ == '__main__':
math()
|
# Empty Box (2002016) | Treasure Room of Queen (926000010)
reactor.incHitCount()
reactor.increaseState()
if reactor.getHitCount() >= 4:
sm.removeReactor()
|
def on_bluetooth_connected():
basic.show_leds("""
. # # # .
# . . . .
# . . . .
# . . . .
. # # # .
""")
bluetooth.on_bluetooth_connected(on_bluetooth_connected)
def on_bluetooth_disconnected():
basic.show_leds("""
# # # . .
# . . # .
# . ... |
NONE_ENUM_INDEX = 0
ACTIVATE_ENUM_INDEX = 1
ABORT_ENUM_INDEX = 2
SUSPEND_ENUM_INDEX = 3
RESUME_ENUM_INDEX = 4
STOP_ENUM_INDEX = 5
TERMINATE_ENUM_INDEX = 6
REMOVE_ENUM_INDEX = 7
|
# -*- coding: utf-8 -*-
def goes_after(word: str, first: str, second: str) -> bool:
if first in word and second in word:
if word.index(second) - word.index(first) == 1:
result = True
else:
result = False
else:
result = False
return result
# another patte... |
class Solution(object):
# Time Complexity: O(n)
# Space Complexity: O(1)
@staticmethod
def remove_element(nums, val):
size = len(nums)
j = size -1 # going backwards
i = 0
while i <= j:
if nums[i] == val:
if nums[j] != val:
... |
def strongest(to_assign, pins_to_match, strength):
def matches(segment):
a,b = segment
return a == pins_to_match or b == pins_to_match
compatible_segments = [s for s in to_assign if matches(s)]
if(len(compatible_segments) == 0):
return strength
def next(segment):
a,b = se... |
# API messages
MATCH_DOES_NOT_EXIST_ERROR = "Match does not exist"
MATCH_WAS_NOT_FOUND_ERROR = "Match was not found"
MORE_THAN_ONE_MATCH_FOUND_ERROR = "More than one match was found to be similar. Try to increase similarity threshold"
BET_DOES_NOT_EXIST_ERROR = "Bet does not exist" |
all_attentions_list = []
for model_name, attentions4players in best_attentions_dict.items():
for player_id, attentions4player in attentions4players.items():
all_attentions_list = all_attentions_list + [attentions4player]#.reshape(15, 1)
# mean_att = np.mean(attention_sum_list_dict['30_300_16_32_2_1_3... |
class VggFaceDetector(object):
"""
preform prediction
"""
def __init__(self, model):
super().__init__()
self.model = model
def make_prediction(self, data):
image = data['image']
bbox = self.model.detect_faces(image)
data.update({'predictions': bbox})
... |
def mult(x, y):
result_mult = 0
i = 0
while i < y: # Here I choose 'y' (witch is the base) to show how many times 'x' going to be sum with itself.
i += 1
result_mult += x
return result_mult
def expo():
base = int(input("Type a base: "))
expo = int(input("Type an exponen... |
#8 Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês.
Salario = int(input("Quanto você ganha por hora?: "));
Horas = int(input("Quantas horas você trabalha no mês?: "));
SalarioMensal = Salario * Horas;
print("Seu ... |
# -*- coding: utf-8 -*-
class JsonerException(Exception):
"""
Base Exception class
"""
pass
class JsonEncodingError(JsonerException):
"""
This error occurs if *Jsoner* cannot encode your object to json.
"""
|
"""
以下列出了 Python 网络编程的一些重要模块:
协议 功能用处 端口号 Python 模块
HTTP 网页访问 80 httplib, urllib, xmlrpclib
NNTP 阅读和张贴新闻文章,俗称为"帖子" 119 nntplib
FTP 文件传输 20 ftplib, urllib
SMTP 发送邮件 25 smtplib
POP3 接收邮件 110 poplib
... |
# -*- coding: utf-8 -*-
'''
File name: code\linear_combinations_of_semiprimes\sol_278.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #278 :: Linear Combinations of Semiprimes
#
# For more information see:
# https://projecteuler.net/probl... |
def magicalWell(a, b, n):
total = 0
for i in range(n):
total += a * b
a += 1
b += 1
return total
|
#!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
COHORTE Repositories of bundles and component factories
:author: Thomas Calmant
:license: Apache Software License 2.0
..
Copyright 2014 isandlaTech
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except i... |
"""
This Bazel extension contains the set of rule definitions to deal with generic IO.
"""
def _print_files_impl(ctx):
"""
An executable rule to print to the terminal the files passed via the 'srcs' property.
"""
executable = ctx.actions.declare_file(ctx.attr.name)
contents = "cat {}".format(" ".jo... |
# n is not required in this program
# to meet the requirements of STDIN of hackerrank we are using n variable
def soln(a, scores):
scores = sorted(list(dict.fromkeys(scores)))
print(scores[-2])
if __name__ == "__main__":
n = int(input())
arr = map(int, input().split())
soln(n, arr)
|
# Copyright (c) 2020. Brendan Johnson. All Rights Reserved.
#import connect
#import config
class ReportTemplates:
def __init__(self, config, connection):
self._config=config
self._connection = connection
##EventBasedTasks
def list(self):
return self._connection.get(url='/reporttem... |
frase = input('Informe uma frase para ver se é palíndromo: ').strip().lower()
frasejunta = frase.split()
frasejunta = ''.join(frasejunta)
novafrase = frasejunta[::-1]
print(f'O inverso de {frasejunta} é {novafrase}')
if frasejunta == novafrase:
print(f'A frase informada é um palíndromo.')
else:
print(f'A fras... |
print ('GERADOR DE PA')
print ('-='*20)
n = int(input ('DIGITE UM NUMERO: '))
p = int(input ('DIGITE A RAZÃO DA PA: '))
c = 1
t = n
mais = 10
total = 0
while mais != 0:
total = total + mais
while c <= total:
c = c + 1
t = t + p
print ('{} - '.format (t), end = '')
print ('PAUSA')
... |
#!/usr/bin/env python
def clamp(low, x, high):
return low if x < low else high if x > high else x
def unwrap(txt):
return ' '.join(( s.strip() for s in txt.strip().splitlines() ))
|
class Package:
"""
Data structure for repo packages.
Attributes:
name (str): The name of the package.
version (str): Version number of the package.
size (int): Size of the package.
depends (list): List of dependent package identifiers (conjunct of disju... |
"""
Ejercicio 1
- Crear dos variables: pais y continente
- Mostrar el valor por pantalla
- Poner comentario indicando tipo de dato
"""
pais = "España" # string
continente = "Europa" # String
print(f"La variable pais contiene: {pais} y es del tipo: ", type(pais ))
print(f"La variable continente contiene: {continente... |
# Zbór zadań A - zadanie 3
# Napisz program liczący silnie rekurencyjnie
# autor : Rafał D.
def silnia(n):
if n > 1:
return n*silnia(n-1)
else:
return 1
print('Program zwraca silnie podanej liczby rekurencyjnie \n')
print('Podaj liczbę dla której chcesz obliczyć silnie: ')
liczba = int(inp... |
def get_detail(param: str, field: str, message: str, err: str):
detail = [
{
'loc': [
f'{param}', # ex. body
f'{field}' # ex. title
],
"msg": message, # ex. field required, not found
"type": f"{err}.missing" # ex. value_error
... |
""" Day 07 of the 2021 Advent of Code
https://adventofcode.com/2021/day/7
https://adventofcode.com/2021/day/7/input """
def load_data(path):
data_list = []
with open(path, "r") as file:
for line in file:
data_list = data_list + [int(value.strip()) for value in line.split(",")]
return d... |
#!/bin/python3
def poisonousPlants(p):
# Complete this function
survives = list()
survives.append(p[0])
dies = list()
num_plants = len(p)
p_killed = [0]*num_plants
killed_day = [0]*num_plants
for i in range(1,num_plants):
if(p[i] > p[i - 1]):
if(p_killed[i - 1] == 1)... |
class FailureDefinitionAccessor(object, IDisposable):
""" A class that provides access to the details of a FailureDefinition after the definition has been defined. """
def Dispose(self):
""" Dispose(self: FailureDefinitionAccessor) """
pass
def GetApplicableResolutionTypes(self):
... |
def least_rotation(s):
s += s
i, ans = 0, 0
while 2*i < len(s):
ans = i
j, k = i + 1, i
while (2*j < len(s)) and (s[k] <= s[j]):
if s[k] < s[j]:
k = i
else:
k += 1
j += 1
while i <= k:
i += j -... |
'''
Title : Check Strict Superset
Subdomain : Sets
Domain : Python
Author : codeperfectplus
Created : 17 January 2020
'''
a = set(map(int, input().split()))
f = 0
for i in range(int(input())):
b = set(map(int, input().split()))
if len(b.difference(a)) != 0:
f = 1
else:
if len(b) ... |
def fizzbuzz(x):
if x%3==0:
if x%5!=0:
return("Fizz")
elif x%5==0:
return("FizzBuzz")
elif x%5==0:
if x%3!=0:
return("Buzz")
else:
return(x)
a= int(input(" Digite um número: "))
w=fizzbuzz(a)
print(w) |
'''
Methods for parsing chromosomic data
'''
def load_breaks(file_location, only_tra=False):
"""
Reads a file, storing the breaks in a dictionary.
Input:
file_location: full path to file, containing breaks in a genome
Output:
breaks_by_chromosome: dictionary {str:[int]}, where keys are... |
# change when building to switch the app to another language
SELECTED_LANG = "jp"
LANGS:list = [
"en", # english
"tr", # turkish
"jp", # japanese
]
LANG_DB:dict = {
"en":[
"6-Digit Code",
"Save Directory",
"Change Directory",
"Fetching...",
"Dow... |
# -*- coding: UTF-8 -*-
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: list
:type nums2: list
:rtype : float
"""
# may be wrong
new_nums = sorted(nums1 + nums2)
new_nums_len = len(new_nums)
if new_nums_len % 2... |
print("I will now count my chickens:") #presents the question
print("Hens", 25 + 30 / 6) #counts the Hens
print("Roosters", 100 - 25 * 3 % 4) #counts the Roosters
print("Now I will count the eggs:") #presents another question
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) #counts the eggs
print("Is it true that 3 + 2 < 5... |
# -*- coding=utf-8 -*-
'''
'''
class Solution(object):
def dailyTemperatures(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
length=len(temperatures)
result=[i for i in range(0,length)]
for i in range(0,length):
i=le... |
n_lines = int(input("How many lines? "))
counter = 1
while n_lines >= counter:
print("This is line " + str(counter))
counter += 1
# print("This is line " + str(counter))
print()
input("Press return to continue ...")
|
'''
Token class that will hold each encountered lexeme, its associated token type (e.g. TokenType.PLUS), the line number in the file where it was found as well as the actual literal value.
Note that the "literal" argument in most cases when we're creating Tokens will be empty. The only times we will care about the "l... |
def lonelyinteger(nums):
for i in range(len(nums)):
if nums.count(nums[i]) == 1:
return nums[i]
if __name__ == '__main__':
a = input()
nums = map(int, raw_input().strip().split(" "))
print(lonelyinteger(nums))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
#%%
def mirror(pair):
if type(pair) != list and \
type(pair) != str and \
type(pair) != tuple:
raise ValueError("Wrong type.\nPlease provide a str, li... |
#%%
"""
- Text Justification
- https://leetcode.com/problems/text-justification/
- Hard
"""
#%%
|
bins_met_px = {"in": "MET_px", "out": "met_px", "bins": dict(nbins=10, low=0, high=100)}
bins_py = {"in": "Jet_Py", "out": "py_leadJet", "bins": dict(edges=[0, 20., 100.], overflow=True), "index": 0}
bins_nmuon = {"in": "NMuon", "out": "nmuon"}
weight_list = ["EventWeight"]
weight_dict = dict(weighted="EventWei... |
mystr = 'TutorialsTeacher'
nums = [1,2,3,4,5,6,7,8,9,10]
portion1 = slice(9)
portion2 = slice(0, -2, None)
print('slice: ', portion1)
print('String value: ', mystr[portion1])
print('List value: ', nums[portion1])
print('slice: ', portion2)
print('String value: ', mystr[portion2])
print('List value: ', nums[portion2]... |
"""
@created_at 2017-08-12
@author Exequiel Fuentes Lettura <efulet@gmail.com>
"""
|
inp = "inH.txt"
oup = "outH.txt"
spl = []
with open(inp, "r") as f:
spl = f.readlines()
with open(oup, "w") as f:
for s in spl:
text = "<tr>\n\t<td>\n"
text += "\t\t{0}\n".format(s[:4])
text += "\t</td>\n\t<td>\n"
text += "\t\t{0}\n".format(s[13:])
text += "\t</td>\n</... |
class Guardian:
@staticmethod
def adjust_difficulty(original_difficulty: int, block_height: int):
return original_difficulty // 1000
# TODO: decide on the parameters for mainnet
# if block_height < 1000:
# return original_difficulty // 1000
# if block_height < 10000:
... |
class RepresentMixin:
def __repr__(self):
return repr(self.to_dict())
def to_dict(self):
return {f: getattr(self, f) for f in self.non_empty_fields}
|
class Profile:
def __init__(self, name, age, xp, time_on_calls):
self.__name = name
self.__age = age
self.__xp = xp
self.__time_on_calls = time_on_calls
@property
def name(self):
return self.__name
@property
def age(self):
return self.__age
@... |
larg = float(input('Digite a largura da parede: '))
alt = float(input('Digite a altura da parede: '))
area = (larg*alt)
tinta = area/2
print('Sua parede tem a dimensão de {}x{} e sua area é {}m²'.format(larg, alt, area))
print('Para pintar esta parede será necessário {}l de tinta'. format(tinta))
|
class Solution:
def memLeak(self, memory1: int, memory2: int):
count = 1
while count <= memory1 or count <= memory2:
if memory1 < memory2:
memory2 -= count
else:
memory1 -= count
count += 1
return [count, memory1, memory2]... |
def main():
# input
N, M = map(int, input().split())
As = list(map(int, input().split()))
Bs = list(map(int, input().split()))
# compute
numbers = [0] * (10**3+5)
for i in As:
numbers[i] += 1
for i in Bs:
numbers[i] += 1
anss = []
for i, figure in enumerate(numbe... |
# ELEVSTRS
for i in range(int(input())):
n,v1,v2=map(int,input().split())
time=[]
ele=2*n/v2
st=n*(2**(1/2))/v1
if(ele>st):print("Stairs")
else:print("Elevator") |
# The MIT License (MIT)
# Copyright (c) 2015 Brian Wray (brian@wrocket.org)
# 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... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
newHead = None
left_node = None
... |
#
# PySNMP MIB module CISCO-DYNAMIC-PORT-VSAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-DYNAMIC-PORT-VSAN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:56:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... |
# Title : Print alphabets from mix string
# Author : Kiran Raj R.
# Date : 04:11:2020
string_to_filter = "he712047070l13212l213*(&(ow76968o172830r%*&$d"
def check_alpha(c):
if c.isalpha():
return c
def check_num(c):
if c.isnumeric():
return c
out = "".join(list(filter(check_alpha, string... |
# Create Allergy check code
# [ ] get input for input_test variable
input_test = input("What have you eaten in the last 24hrs: ")
# [ ] print "True" message if "dairy" is in the input or False message if not
print("Your food intake of",input_test,'contains "dairy" =',"dairy".lower() in input_test.lower())
#test works... |
def largestComponent(G):
V, E = G;
vertexDeletedIndex = 0;
largestComponent = 0;
component = 0;
colour = [];
for i in range(len(V)):
Vcopy = V;
del Vcopy[i];
for v in V:
colour[v] = "white";
for v in Vcopy:
if colour[v] == "whit... |
n = int(input())
s = sum(list(map(int, input().split())))
c = 0
for i in range(1, 6):
if (s+i)%(n+1)!=1:
c += 1
print(c)
|
names = ['Christopher', 'Susan']
print(len(names)) # Get the number of items
names.insert(0, 'Bill') # Insert before index
print(names)
|
numBottles=int(input('pleas enter the number of full buttles: '))
numExchange=int(input('pleas enter number of empty bottels to exchange with full bottels: '))
fullbottels=numBottles
result=0
while numBottles>=numExchange or fullbottels>0:
result+=fullbottels
fullbottels=numBottles//numExchange
numBottles%... |
detection_data_path = os.path.join('datasets', 'detection')
# training dataset
detection_train_set = DetectionDataset(detection_data_path, mode='train', transforms=get_transform(True))
# validation dataset
detection_valid_set = DetectionDataset(detection_data_path, mode='valid', transforms=get_transform(True))
#testing... |
#######################################
# Accessing Attributes
#######################################
class Employee:
"""Common base class for all employees"""
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def dis... |
"""
j is the index to insert when a number not equal to val.
j will never catch up i, so j will not mess up the check.
"""
class Solution(object):
def removeElement(self, nums, val):
j = 0
for n in nums:
if n!=val:
nums[j] = n
j += 1
return j |
# from pynvim import attach
# nvim = attach('socket', path='/tmp/nvim')
# handle = nvim.request("nvim_create_buf",1,0)
# nvim.request("nvim_open_win",2,True,{'relative':'win','width':50,'height':3,'row':3,'col':3})
# maybe get current window's config and based on it? but resizing will make things weird, like fzf
# src... |
# Leetcode 323
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
visited = [False] * n
adj_list = [None] * n
for vertex in range(n):
adj_list[vertex] = list()
for edge in edges:
adj_list[edge[0]].append(edge[1])
adj... |
# търговски комисионни
# Фирма дава следните комисионни на търговците си според града, в който работят и обема на продажбите s:
#
# Напишете програма, която чете име на град (стринг) и обем на продажбите (десетично число) и изчислява размера на
# комисионната. Резултатът да се изведе закръглен с 2 десетични цифри след ... |
#
# PySNMP MIB module RTBRICK-SYSLOG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///home/tin/Dev/mibs.snmplabs.com/asn1/RTBRICK-SYSLOG-MIB
# Produced by pysmi-0.3.4 at Fri Jan 31 21:33:01 2020
# On host bier platform Linux version 5.4.0-3-amd64 by user tin
# Using Python version 3.7.6 (default, Jan 19 2020, 22:... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == '__main__':
with open("file.txt", 'r') as f:
content = f.read();
print(content)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
def read_line_in_str(line, number_of_loci):
"""
read str data in each line and check the format and data type (float);
return information and STR-data separately.
"""
col = line.strip().split("\t")
# check the column number
if len(col) != (number... |
class Solution(object):
def numIslands(self, grid):
if not grid:
return 0
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
self.dfs(grid, i, j)
count += 1
return c... |
class Empty:
""" An empty element. Serves the same function as None, except that it can be used to indicate that JSGNull
and AnyType attributes (which both can legitimately have None values) have not been assigned
"""
def __new__(cls):
return cls |
print('Insert first string')
string1 = input()
print('Insert second string')
string2 = input()
print(string1 + ' - ' + string2 + ' are anagrams?', sorted(string1) == sorted(string2))
'''
Check whether the strings in input are anagrams or not.
Two strings, a and b, are called anagrams if they contain all the same cha... |
class Scaler1D:
def __init__(self) -> None:
self.max_num: float = None
self.min_num: float = None
def transform(self, num_list: list) -> list:
if self.max_num is None:
self.max_num = max(num_list)
if self.min_num is None:
self.min_num = min(num_list)
... |
# 选择排序-简单选择排序
"""
在要排序的一组数中,选出最小(或者最大)的一个数与第1个位置的数交换;
然后在剩下的数当中再找最小(或者最大)的与第2个位置的数交换,依次类推,直到第n-1个元素(倒数第二个数)和第n个元素(最后一个数)比较为止。
简单选择排序的改进——二元选择排序
简单选择排序,每趟循环只能确定一个元素排序后的定位。
我们可以考虑改进为每趟循环确定两个元素(当前趟最大和最小记录)的位置,从而减少排序所需的循环次数。改进后对n个数据进行排序,最多只需进行[n/2]趟循环即可
"""
# 简单选择排序
def selectSort(numbers):
for i in range(len(number... |
"""This module defines Debian Buster dependencies."""
load("@rules_deb_packages//:deb_packages.bzl", "deb_packages")
def debian_buster_amd64():
deb_packages(
name = "debian_buster_amd64_macro",
arch = "amd64",
urls = [
"http://deb.debian.org/debian/$(package_path)",
... |
# SWAPPING THE NUMBERS
a=5
b=2
print(a,b)
a,b=b,a
print(a,b) |
BASE_URL = "https://api.labs.cognitive.microsoft.com/academic/v1.0/evaluate?expr"
PAPER_ATTRIBUTES = "AA.DAuN,DN,D,ECC,DFN,J.JN,PB,Y"
AUTHOR_ATTRIBUTES = "Id,DAuN,ECC,LKA.AfN,PC"
STUDY_FIELD_ATTRIBUTES = "Id,PC,FP.FN,ECC,DFN,FC.FN"
PAPER = 'paper'
AUTHOR = 'author'
AFFILIATION = 'affiliation'
STUDY_FIELD = 'study field... |
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
row=len(board)
col = len(board[0])
copy = [[0 for i in range(col)]for j in range(row)]
for i in range(row):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.