content
stringlengths
7
1.05M
#!/usr/bin/env python3 if __name__ == '__main__': n = int(input().strip()) for _ in range(n): i, k = map(int, input().split()) print(k - 1 if ((k - 1) | k) <= i else k - 2)
class Classification: pass class Knn: def __init__(self, n): self.knn=n
#!/usr/bin/env python3 a = 11220 b = 2002 while b > 0: temp = b b = a % b a = temp print("lnko =", a) # 1. A változó értéke a program végén 11. # 2. A szorzat változó értéke ilyenkor 6720. # 3. A b változó értéke ilyenkor 44.
""" 0222. Count Complete Tree Nodes Given a complete binary tree, count the number of nodes. Note: Definition of a complete binary tree from Wikipedia: In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have betwee...
class Embeddings(): def __init__(self, model, vocab): """ @embeddings: Pre-trained word2vec embeddings @vocab: The entire vocabulary @return: Words representable by word2vec, Embeddings of the representable vocabulary, Unknown words not representab...
# TODO - can we enforce a singleton pattern on the class? class SessionHandler: def __init__(self): self.client = None self.session_id = None def requires_session_id(method): """ TODO """ pass """ @wraps(method) def wrapper_requires_session(*args, **kwargs): pa...
# 1109. Corporate Flight Bookings class Solution: def corpFlightBookings(self, bookings, n: int): res = [0] * (n + 1) for i, j, k in bookings: res[i-1] += k res[j] -= k for i in range(1, n): res[i] += res[i-1] return res[:-1] print(Solution().corp...
# This binary search function will look for a book on a bookshelf by iteratively narrowing down the area where it might find the book, until it finds the book. def binary_search(lst, search_val): if len(lst) == 0: print("Book is not on the shelf!") return print("Checking the bookshelf and findin...
def is_host(ip): """ Checks whether an address is a subnet address or a single address :param ip: ip address or subnet :return: True if host """ r = ip.split("/") if len(r) > 1: return False return True
class User: @classmethod def deserialize(cls) -> "User": return cls() def do_a_user_thing(self): print("doing a user thing") user = User.deserialize() user.do_a_user_thing() class Product: @classmethod def deserialize(cls) -> "Product": return cls() def do_a_product...
nome: str = input('Digite seu nome: ') print('Olá', nome, 'Prazer em conhecer-lo!') idade = input('Digite sau idade: ') print('Sua idade é, {} anos'.format(idade))
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...
#!/usr/bin/env python3 # coding=utf-8 # # Copyright (c) 2020-2021 Huawei Device Co., Ltd. # 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 # #...
# this segment tree will support two operations: # 1. Set element i equal to v. # 2. Find maximum sum of subarray of # original array (in fact we can answer this question for all subarrays, not only for original one) we will keep # tuple (seg, pref, suf, sum) for each node # use fast IO to get AC on PyPy27 class Segm...
def _switch(app_connection, enable=None): params = {"secret": "changeme"} if enable is not None: params["enable"] = "1" if enable else "0" answer = app_connection.get_json("c2c/sql_profiler", params=params, cors=False) assert answer["status"] == 200 return answer["enabled"] def test_ok(app...
num_classes = 3 # dataset settings dataset_type = 'UWMGITDataset' data_root = './data/mmseg_train/' classes = ['large_bowel', 'small_bowel', 'stomach'] palette = [[0, 0, 0], [128, 128, 128], [255, 255, 255]] img_norm_cfg = dict(mean=[0, 0, 0], std=[1, 1, 1], to_rgb=True) size = 256 albu_train_transforms = [ dict(ty...
#10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. #You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon. #From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008...
# from .termapp import TermApp class Display: def __init__(self): pass def report(self): pass def __call__(self, msg): key, status, data, err_msg = msg getattr(self, status)(key, data, err_msg) def __enter__(self): pass def __exit__(self, exc_type, exc_v...
def Tag(tag: str): """ Decorator that adds the given tag to the decorated function. :param tag: The tag to add to the function. """ def apply_tag(method): if not hasattr(method, '__tags'): method.__tags = set() method.__tags.add(tag) return method return...
# $ gyp src/iroha.gyp --depth=. -f make # maybe with --generator-output=src { 'make_global_settings': [ ], 'target_defaults': { 'cflags': ['-fPIC', '-Wall', '-Wno-sign-compare'], 'defines': ['PACKAGE="iroha"', 'VERSION="0.0.1"'], 'xcode_settings': { 'OTHER_CFLAGS': [ ...
numbers = [4, 8, 2, 5, 1, 9] numbers.sort() ''' sort modifies the existing list ''' print("Sort using sort() : ", numbers) names = ["foo", "qux", "bar", "buz", "quux"] ''' sorted created a new list for sorted entries ''' print("Sort using sorted() : ", sorted(names)) print("Print names list : after sorting : ", names) ...
#!/usr/bin/python3 # Carrega todo arquivo na memória. arquivo = open('pessoas.csv') dados = arquivo.read() arquivo.close() for registro in dados.splitlines(): print('Nome: {}, idade: {}'.format(*registro.split(',')))
TOP_LEVEL_OSM_TAGS = [ "aerialway", "aeroway", "amenity", "barrier", "boundary", "building", "craft", "emergency", "geological", "healthcare", "highway", "historic", "landuse", "leisure", "man_made", "military", "natural", "office", "place", ...
''' made by: Aayush 9029 created at: April 3, 2020 A module that converts string to morse code and vice versa ''' class Morse: def __init__(self, words): ''' Takes in one parameter either morse code or letter / number / symbols and assings it to self.words ''' self.codes = { ...
class LineOperation: def runOn(self, line: str) -> str: return line class CheckIfRead(LineOperation): def __init__(self): return def runOn(self, line: str) -> str: X = input(line) if X == "Y": line += " --" return line class BulkString(LineOperation):...
class Solution(object): def generateTrees(self, n): def generate_trees(start, end): if start > end: return [None,] all_trees = [] for i in range(start, end +1): left_trees = generate_trees(start, i-1) right_trees =...
#from random import choice #books = [' ya robot', 'lunnaya pil', 'tainstvenniy ostrov'] #for i in books: # print(i) class Student: name = "Vladislav" birthday = "20.01.2002" adress = "bluxera 10" def start(self): print("Студент 33 группы")
def print_formatted(number): # your code goes here width=len(str(bin(number))[2:]) for i in range(1,number+1): print(str(i).rjust(width," "),oct(i)[2:].rjust(width," "),hex(i)[2:].upper().rjust(width," "),bin(i)[2:].rjust(width," ")) if __name__ == '__main__': n = int(input()) print_formatt...
#!/usr/bin/python # ============================================================================== # Author: Tao Li (taoli@ucsd.edu) # Date: Jun 15, 2015 # Question: 155-Min-Stack # Link: https://leetcode.com/problems/min-stack/ # ============================================================================== ...
#!/usr/bin/env python """ Useful utilities for IO. """ def read_samples_list(path, fail_on_empty=True): with open(path, 'r') as f: samples = f.read().splitlines() if fail_on_empty and len(samples) == 0: raise ValueError("Samples list empty") return samples def read_contig_list(path, fail...
# Course Schedule class Solution: def hasCycle(self, graph, start, checked, visited): if checked[start]: return False visited[start] = True for adj in graph[start]: if visited[adj]: return True if self.hasCycle(graph, adj, checked, visit...
playerNamePath = "Data/Brain/playerName.txt" assistantNamePath = "Data/Brain/assistantName.txt" audioPath = "Audios/Audio.mp3" quinnMail = "assistantquinn@gmail.com" ibrahimMail = "ibrahimalbayrak812@gmail.com" sendPassword = "jupubpuqnehtlsji" playerName = "" assistantName = ""
class SchemaFilesNotFound(Exception): pass class SchemaNotPresent(Exception): pass class ModuleNotPresent(Exception): pass class SchemaPathNotFound(Exception): pass
total_seats = int(input("Number of seats: ")) MIN_PERCENTAGE = int(input("Minimum percentage: ")) raw_parties = [] raw_votes = [] while True: inputs = str(input("")).split(" ") if inputs[0] == "exit": break elif len(inputs) == 2: party = inputs[0] num_votes = int(inputs[...
# Task: # # Determine if a string is a palindrome # # Examples of palindromes: # "", "a", "madam", "Mr. Owl ate my metal worm", "Was it a car or a cat I saw?" # Lines that are not palindromes: "london", "random", "Not a palindrome!" class PalindromeChecker: def check(self, line): return False
""""2.Faça um programa que exiba seu nome na tela """ Nome = input("Qual o seu nome? ") print(Nome)
#@auth.requires_login() def index(): form = FORM('Your name:', INPUT(_name='name'), INPUT(_type='submit')) return dict(form=form)
#!/usr/bin/env python3 ###################################################################################### # # # Program purpose: Computes the area of the polygon. # # Program Author : Happi Yva...
'''Settings file''' # settings.py # Variables definition # SNMP Community HOSTS = ["10.70.8.173/255.255.255.255","10.70.8.117/255.255.255.255"] INTERFACE = "internal" COMMUNITY = "private" # SysInfo LOCATION = "Company" DESCRIPTION = "FortiSwitch device - Company property." CONTACT = "admin@Company.pl" # Import PATH...
peso = float(input('Qual é o seu peso? (Kg): ')) altura = float(input('Qual é a sua altura? (m): ')) imc = peso / (altura ** 2) print('Seu IMC é de {:.1f}.'.format(imc)) if imc < 18.5: print('Abaixo do peso.') elif imc >= 18.5 and imc < 25: print('Parabéns, você está na faixa de peso ideal.') elif imc > 25 and ...
""" LeetCode Problem: 129. Sum Root to Leaf Numbers Link: https://leetcode.com/problems/sum-root-to-leaf-numbers/ Language: Python Written by: Mostofa Adib Shakib Leaf Node: Both the left and right child is a Null Node Algorithm: 1) Check if the node passed is a Null Node if so return from the recursive call 2) Con...
class StanModels: hmnl = """ # Hierarchical multinomial logit model # from https://github.com/ksvanhorn/ART-Forum-2017-Stan-Tutorial/blob/master/3_hmnl/hmnl.stan data { int<lower=2> C; // # of alternatives (choices) in each scenario int<lower=1> K; // # of covariates of alte...
""" Torsion Class definition Author: Israel Cabeza de Vaca Lopez Email: israel.cabezadevaca@icm.uu.se """ class Torsion(object): """ Torsion Class """ def __init__(self, atomA, atomB, atomC, atomD, typeInitial, typeFinal, V1, V2, V3, V4, phase1, phase2, phase3, displacement, improper=False): ...
# https://leetcode.com/problems/jump-game/ class Solution: def canJump(self, nums: list[int]) -> bool: curr_pos = len(nums) - 1 for i in reversed(range(len(nums) - 1)): if i + nums[i] >= curr_pos: curr_pos = i return curr_pos == 0
# Crie um programa que leia uma frase qualquer # e diga se ela é um PALINDROMO, desconsiderando os espaços. frase = str(input('Digite uma frase: ')).lower().strip() f1 =frase[::-1] sf1 = frase.split() sf2 = f1.split() jf1 = ''.join(sf1) jf2 = ''.join(sf2) print(f'A frase {jf1} vira {jf2}') if jf1 == jf2: print('É ...
CONTINUOUS = 'Continuous' CATEGORICAL = 'Categorical' ORDINAL = 'Ordinal' INTEGER = 'Integer' FLOAT = 'Float' STRING = 'String'
class MomentumGradientDescent(GradientDescent): def __init__(self, params, lr=0.1, momentum=.9): super(MomentumGradientDescent, self).__init__(params, lr) self.momentum = momentum self.velocities = [param.data.new(param.shape).zero_() for param in params] def...
changes = list() with open("input.txt", "r") as lines: for line in lines: if line[0] == '+': changes.append(int(line[1:])) elif line[0] == '-': changes.append(-int(line[1:])) sum = 0 frequenturies = set() frequenturies.add(sum) while True: for change in changes: sum += change if (sum in frequenturies)...
people = [ {"name":"Harry", "house":"Gryffindor"}, {"name":"Cho", "house": "Ravenclaw"}, {"name":"Draco", "house":"Slytherin"} ] ##### #def f(person): # return person["name"] ###### people.sort(key=lambda person: person["name"]) print(people)
def knapsack(items, capacity, debug=None): values = [[0] * (capacity + 1) for _ in range(len(items)+1)] # values[i][j] = max { values[i-1][j] if does not fit # values[i-1][j-w] + v if w < j rows, columns = len(values), len(values[0]) for i in range(1, rows): value, we...
string_without_line_breaks = "" with open('foo.txt', "r+") as file: for line in file: stripped_line = line.rstrip() + " " string_without_line_breaks += stripped_line with open ("oneLine.md", "w") as file: file.write(string_without_line_breaks) # print(string_without_line_breaks...
class BoardError(StandardError): pass class tile: """This is the tile class. tileType is a string designating the tile type. health is how much health this tile is given wallValues is a length 6 list designating the type of walls around the tile. This is the inde...
# Live Session - 5/10/2020 - 4CSE05 # Question 2 # Mark m = int(input("Enter a mark: ")) if m < 40: print("Fail") else: print("Pass") # Temperature temp = int(input("Temperature: ")) if temp > 19: print("Hot") else: print("Cold") # Number n = int(input("Number: ")) if (n % 2 == 0): print...
def chain(*iters): for l in iters: print(l) print(chain([1, 2, 3, 4, 5], [5, 6, 7, 8]))
#Friends Madlib Game def madlib(): #Defining Blanks that the user has to enter Adj1=input("Adjective = ") Adj2=input("Adjective = ") Adj3=input("Adjective = ") Adj4=input("Adjective = ") verb1=input("Verb in continuous tense = ") verb2=input("Verb in past tense = ") ...
# Demo Python Operators ''' Python Membership Operators Membership operators are used to test if a sequence is presented in an object: Operator Description Example in Returns True if a sequence with the specified x in y value is present in ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- mytext = "Hello world" print(len(mytext)) print(mytext[0]) print(mytext[1]) num = 142 try: print(mytext[num]) except IndexError: print("I am so sorry, there is no character", num, "in the string") print("end")
largura = int(input("Digite a largura da parede: ")) altura = int(input("Digite a altura da parede: ")) area = (largura*altura) metros = (area/2) print("A precisará de: ",metros, "litros de tinta")
pessoa = input("fale seu nome: ") def diz_ola(nome): print("olá, " + nome) diz_ola(pessoa)
""" """ class Stack : def __init__(self, max = -1): self._list = [] self._max = max def get(self) : if 0 == len(self._list): raise IndexError() return self._list.pop() def put(self, *values): if self._max > 0 and self.size() + len(values) > self._m...
# Copyright (c) 2012 Adi Roiban. # See LICENSE for details. """ Tests executed under elevated accounts. """
''' Created on Jul. 4, 2019 @author: kjnether '''
# An array A consisting of N integers is given. # Rotation of the array means that each element is shifted right by one index, # and the last element of the array is moved to the first place. # For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] # (elements are shifted right by one index and 6...
def HexBlock(data, width=8): i = 0 count = 0 result = '' currentHexLine = '' currentChrLine = '' for byte in data: # next line, if required if (i == width): result += f'{currentHexLine} {currentChrLine}\n' currentHexLine = '' currentChrLine =...
def generate_multiple_datasets_for_multiple_epochs(tabGAN, dataset_dir, n_synthetic_datasets, n_epochs_vec, restart = False, path_finished_epochs_counter = None, redo_n_epochs_vec = [], plot_only_new_progress = True,...
def check(s): idx1, idx2 = s.find("@"), s.find(".") ok = idx1>0 and all(it.isalnum() or it=="@" or it=="-" or it=="_" for it in s[:idx1]) ok &= ~idx2 and idx2-idx1>1 and all(it.isalnum() for it in s[idx1+1:idx2]) ok &= ~idx2 and 1<=len(s[idx2+1:])<=3 and s.count("@")==1 and s.count(".")==1 return ok...
""" 037 Ask the user to enter their name and display each letter in their name on a separate line. """ i = "0" name = input("Enter your name please : ") name = list(name) #print(name) for i in list(name): print(i)
# parsetab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'leftOROleftANDOleftNOIGUALIGUALIGUALleftMAYORMENORMAYORIGUALMENORIGUALleftMAYMAYMENMENleftMASMENOSleftMULTDIVleftNOTOGNOTleftPARIZQPARDRADD ALTER AND ANDO AS BETWEEN BI...
load("//bloop/private:bloop_target.bzl", "bloop_target_test") def bloop_target(**kwargs): bloop_target_test( name = "%s.bloop" % kwargs["name"], target = kwargs["name"], tags = ["manual"], )
class Solution: def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int: # Time complexity O(n) # Iterate over the list and check matches matches = 0 rule = {"type": 0, "color": 1, "name": 2} for item in items: if item[rule[ruleKey]] ==...
def load(h): return (88.288379267609017, 86.071116222001365, 83.840759055046817, 81.607443388287237, 79.373005516593935, 77.138024633267776, 74.902740311570923, 72.667269403298718, 70.431675646397252, 68.1959...
numbers=input(); n=int(input()) numbersList=[] k=0; output="" while k<len(numbers): num="" if numbers[k]!=" ": for j in range(k,len(numbers)): if numbers[j]==" ": k+=1 break else: k+=1 num+=numbers[j] ...
# Copyright Notice: # Copyright 2018 Dell, Inc. All rights reserved. # License: BSD License. For full license text see link: https://github.com/RedDrum-Redfish-Project/RedDrum-Simulator/LICENSE.txt # BullRed-RackManager chassisBackend resources # class RdChassisBackend(): # class for backend chassis resou...
class IMachineWorker(object): """ Base class for objects that provide pluggable service to others. """ def boot(self, *args): """ Prepare for providing the service. After this call, it may be requested by others. """ pass def run(self): """ Called by reactor's loop when this obj...
# -*- coding: utf-8 -*- """five: six, redux""" PY2 = (str is bytes) PY3 = (str is not bytes) # provide a symettrical `text` type to `bytes` if PY2: # pragma: no cover text = unicode # noqa def n(s): if isinstance(s, bytes): return s else: return s.encode('UTF-8') els...
# flake8: noqa class STALibValidationError(Exception): """ Algorithm data validation raised Error. if the data is not homogenous. """ def __init__(self, _type: str = None) ->None: self._type = _type super().__init__() def __str__(self): return "For Algorithms Data sh...
t=int(input()) while(t): t-=1 n=int(input()) if(n%6==0): print("Misha") else: print("Chef")
"""Backwards compat aliases for rules_proto_grpc Node.js rules.""" load("//js:defs.bzl", "js_grpc_node_compile", "js_grpc_node_library", "js_proto_compile", "js_proto_library") def nodejs_proto_compile(**kwargs): print("Rule nodejs_proto_compile from @rules_proto_grpc//nodejs:defs.bzl has been deprecated, please ...
def product(arr): prods = [1] * len(arr) temp = 1 for i in range(len(arr)): prods[i] = temp temp = temp * prods[i] temp = 1 for i in reversed(range(len(arr))): prods[i] = prods[i] * temp temp = temp * arr[i]
# Copyright 2020 by Christophe Lambin # All rights reserved. # dummy file to test RPi.GPIO functions on Mac BCM = 0 IN = 0 OUT = 1 def setwarnings(set): pass def setmode(mode): pass def setup(pin, mode): if pin == -1: raise RuntimeError pass def input(pin): return 0
# Explore the data print(cellphone.head()) # Create a scatter plot of the data from the DataFrame cellphone plt.scatter(cellphone.x, cellphone.y) # Add labels plt.ylabel('Latitude') plt.xlabel('Longitude') # Display the plot plt.show() # Change the marker color to red plt.scatter(cellphone.x, cellph...
class ShotgunError(Exception): """Exception for all server logic.""" pass class Fault(ShotgunError): """Exception for all remote API logic; unused in this mock.""" _default_code = 999 @property def code(self): try: return self.args[1] except IndexError: ...
def solution(l, t): for i in range(len(l) + 1): for j in range(i+1, len(l)+1): s = sum(l[i:j]) if s == t: return [i, j-1] if s > t: break return [-1, -1] data = [4, 3, 10, 2, 8] n = 12 print(solution(data, n))
class FontStretch(object,IFormattable): """ Describes the degree to which a font has been stretched compared to the normal aspect ratio of that font. """ @staticmethod def Compare(left,right): """ Compare(left: FontStretch,right: FontStretch) -> int Compares two instances of System.Windows.FontStr...
#!/usr/bin/env python3 def generator(factor, seed=0, modulus=2147483647, multiple_of=1): assert multiple_of != 0 while True: seed *= factor seed %= modulus if multiple_of == 1 or seed % multiple_of == 0: yield seed def judge(gen_a, gen_b, num_comparisons, bits=16): ma...
info = [] with open("AoC2.txt", 'r') as File1: for line in File1: info.append([int(line[:-1].split("-")[0]), int(line[:-1].split(" ")[0].split("-")[1]), line[:-1].split(":")[0][-1], line[:-1].split(" ")[-1]]) i = 0 print(info) for password in info:...
class QLayer(): def get_quant_weight(self): raise NotImplementedError def set_quant_weight(self): raise NotImplementedError def restore_weight(self): raise NotImplementedError
#PROGRAM TO WRITE INTO A FILE text = "SAMPLE FOR A TESTING \n NEW LINE" SaveFile = open("exampleFile.txt","w") SaveFile.write(text) SaveFile.close
d = 1000 b = bin(d).replace('0b','') h = hex(int(b)) c = 0 for i in b: if i=='1': c+=1 print(c) # list comprehension print(sum(1 for x in b if x=='1'))
def cheese_and_crackers(cheese_count, boxes_of_crackers): print(f"You have {cheese_count} cheeses!") print(f"You have {boxes_of_crackers} boxes of crackers!") print("Man, that's enough for a party!") print("Get a blanket.\n") def calculate_area(x, y): area = x * y print(f"Given lengths of {x} and {y}, the ...
# -*- coding: utf-8 -*- def chainable(items): class Chain(object): def __init__(self, items): self._items = items def map(self, a): return Chain(map(a, self._items)) def filter(self, a): return Chain(filter(a, self._items)) def reduce(self, a)...
shopping_list = ['milk', 'eggs', 'pasta', 'spam', 'bread', 'rice', 'pasta'] item_to_find = "spam" found_at = None for index in range(len(shopping_list)): if shopping_list[index] != item_to_find: continue if shopping_list[index] == item_to_find: found_at = index break if found_at != No...
#!/usr/bin/env python def look_for_key(main_box): """Non-recursive code example.""" pile = main_box.make_a_pile_to_look_through() while pile is not pile.is_empty(): box = pile.grab_a_box() for item in box: if item.is_a_box(): pile.append(item) elif i...
TEST( """ . [ . 2 * 3 * 4 ] evaluate ( ) == 24 """ ) TEST( """ . [ ( . 11 * 2 ) 12 ] flatten ( ) value == 22 """ ) TEST( """ . [ f ] evaluate ( Function @ f ( Closure @ () [ . 1313 ] ) ) == 1313 """ ) TEST( """ . [ f ] evaluate ( Union @ ( . [ ( Function @ f ( Closure @ () [ . 1414 ] ) ) ] flatten () ) ) == 1414 """...
# # pystylus/ast/conditional.py # """ Contains the ConditionalNode element of the pystylus AST - handling if statements """ class ConditionalNode: """ Node handling an if statement or if+elif+else chain of statements. The object is constructed from a 'conditional statement' and the node to be run if t...
#!/usr/bin/env python3 ''' Implement and algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? ''' def is_unique(string): # O(n) s = set() for c in string: # go through characters if c in s: # if character already seen return False...
""" Implement an union find data structure. """ class UnionFind: """An union find data structure. Args: n (int): Number of items in the union find object. """ def __init__(self, n: int) -> None: self.parent = [i for i in range(n)] self.rank = [0 for _ in range(n)] def fi...
def check_roles(msg, roles): if not roles: return True for role in msg.author.roles: if role.id in roles: return True return False def check_scope(msg, channels, categories): if not channels and not categories: return True if channels and msg.channel.id in channels: return True category_id = geta...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ ...
"""Module containing an implementation of a priority queue""" def _parent(i): return (i - 1) // 2 def _right_child(i): return 2*i + 2 def _left_child(i): return 2*i + 1 class PriorityQueue(): """This class represents a priority queue""" def __init__(self): self.items = [] def __l...