content
stringlengths
7
1.05M
""" 0224. Basic Calculator Hard Given a string s representing an expression, implement a basic calculator to evaluate it. Example 1: Input: s = "1 + 1" Output: 2 Example 2: Input: s = " 2-1 + 2 " Output: 3 Example 3: Input: s = "(1+(4+5+2)-3)+(6+8)" Output: 23 Constraints: 1 <= s.length <= 3 * 105 s consist...
def str_to_disct(st): """[return dict containing each letter and its occurrence in string] Args: st ([str]): [string] Returns: [dict]: [dict] """ s = set(list(st)) dic = {} for key in s: dic[key] = 0 for value in st: dic[value] += 1 return dic
class Solution: def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ lo = 0 high = (int(len(str(n)) / 3) + 1) * 10 while lo <= high: mid = int((lo + high) / 2) print(mid) if 2 ** mid == n: return True elif ...
# -*- coding = utf-8 -*- class Config: BLUEPRINTS = ( "app.blueprint.tyfo:tyfo", ) # tyfo的数据库 TYFO_SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://root:root@127.0.0.1:3306/tyfo_data?charset=utf8" TYFO_SQLALCHEMY_POOL_SIZE = 30 TYFO_SQLALCHEMY_MAX_OVERFLOW = 5 TYFO_SQLALCHEMY_PO...
#!/usr/bin/env python # coding: utf-8 # This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). # # Solution Notebook # ## Problem: Implement depth-first search on a graph. # # * [Constraints]...
class LEDMatrixOperationUtils(): ### 정수 체크 def integer_check(self, number, option=None) -> None: if not isinstance(number, int): is_integer = False else: is_integer = True if not is_integer: if option: raise ValueError("Please enter in...
class TransportException(Exception): pass class ServiceException(Exception): code = -2 class RemoteServiceException(Exception): pass class ProtocolException(Exception): pass class MethodNotFoundException(ServiceException): code = -3
num = int(input("숫자를 입력하세요 ")) divisors = [] for i in range(1,num+1): if num % i == 0: divisors.append(i) print(divisors)
#!/usr/bin/python3 """ Compute min cut of the graph with Karger algorithm. Problem answer: 17 """
# Rachit Agarwal # 1001664316 # Jacobi method # u1 = lambda a, b, c, p, q, r: (5-r+2*b)/6 # u2 = lambda a, b, c, p, q, r: (3+2*a+2*c-q)/6 # u3 = lambda a, b, c, p, q, r: (1+b+p)/3 # u4 = lambda a, b, c, p, q, r: (1+c+q)/3 # u5 = lambda a, b, c, p, q, r: (3-b+2*p+2*r)/6 # u6 = lambda a, b, c, p, q, r: (5-a+2*q)/6 # a0 ...
def leiaDinheiro(msg=''): """ :param msg: Mensagem para solicitar o dado do usuario :return: Retorna o numero digitado. """ while True: dado = input(str(msg)).strip().replace(',', '.') if dado.isalpha() or dado.strip() == '' or not dado.replace('.', '').isnumeric(): prin...
bicyles = ['trek', 'cannondale', 'redline', 'specialized'] message = f"My first bicycle was a {bicyles[0].title()}" print(bicyles[0].title()) print(bicyles[1]) print(bicyles[3]) print(bicyles[-1]) print(message)
# population data def main(): # read the population file pop_file = open("USPopulation.txt", "r") # read the lines pop_list = pop_file.readlines() # read each line as an integer index = 0 while index < len(pop_list): pop_list[index] = int(pop_list[index]) index += 1 #...
name = "ilmbase" version = "2.2.0" authors = [ "ILM" ] description = \ """ Utility libraries from ILM used by OpenEXR. """ private_build_requires = [ "gcc-4.8.2+" ] variants = [ ["platform-linux", "arch-x86_64", "os-CentOS-7"] ] uuid = "repository.ilmbase" def commands(): env.LD_LIBRA...
def Main( ARC ): return None
def leiaInt(txt): while True: try: n = int(input(txt)) except (ValueError, TypeError): print('\033[31mERRO! Por favor digite um número inteiro válido.\033[m') continue except KeyboardInterrupt: print('\n\033[31mEntrada de dados interrompida pel...
my_list = ['apple', 'banana', 'grapes', 'pear'] for c, value in enumerate(my_list, 1): print(c, value) print(list(enumerate(my_list, 0)))
_base_ = './mask_rcnn_r50_fpn_1x_coco.py' model = dict( pretrained='open-mmlab://detectron2/resnet50_caffe', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=-1, norm_cfg=dict(type='SyncBN', requires_grad=True), ...
STATS = [ { "num_node_expansions": 51, "plan_length": 33, "search_time": 0.04, "total_time": 0.04 }, { "num_node_expansions": 87, "plan_length": 35, "search_time": 0.07, "total_time": 0.07 }, { "num_node_expansions": 104, ...
def delimited(fyle, delimiter='\n', bufsize=4096): ''' generator to yield records of a text file ''' buf = '' while True: newbuf = fyle.read(bufsize) if not newbuf: yield buf return buf += newbuf lines = buf.split(delimiter) for line in lines[:...
# ~*~ coding: utf-8 ~*~ __doc__ = """ `opencannabis.geo` --------------------------- Objects and definitions related to geography. """ # `opencannabis.geo`
GQL_SCHEMA = """ enum Episode { NEWHOPE EMPIRE JEDI } enum LengthUnit { METER } type Character { name: String! appearsIn: [Episode!]! } type Starship { id: ID! name: String! length(unit: LengthUnit = METER): Float } type Query { hero(episode: Episode): Character } """ SOURCE_CODE = """ class ...
# -*- coding: utf-8 -*- """ Created on Fri Mar 31 11:57:54 2017 @author: Chandan Adiga This module is designed assuming: 1) first two rows are to be neglected as they contain meta data.(title, desc etc. in this case, heading and attributes name) 2) Attributes are seperated with tab('\t') and 5th item is class name. ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: fPtr = head sPtr = head counter = 0 result = []...
''' Encoding and decoding to user-readable identifiers ("codes") from integer identifiers Created 2019-05-31 by NGnius ''' READABLE_CHARS = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9...
# @Title: 设计链表 (Design Linked List) # @Author: 18015528893 # @Date: 2021-02-05 19:51:02 # @Runtime: 208 ms # @Memory: 15.8 MB class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class MyLinkedList: def __init__(self): """ Initialize your da...
class People(object): def __init__(self, name, age): self.name = name self.age = age def speak(self): print('{}说:我{}岁'.format(self.name, self.age)) class Speaker(object): def __init__(self, name, career, topic): self.name = name self.career = career se...
edad = int(input("¿Cuántos años tiene? ")) if edad < 18: print("Es usted menor de edad") else: print("Es usted mayor de edad") print("¡Hasta la próxima!")
def is_allowed(fname): allowed_ext = fname.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS return '.' in fname and allowed_ext def generate_random_name(fname): ext = fname.split('.')[-1] rns = [random.randint(0, len(CHAR_SET)-1) for _ in range(6)] chars = ''.join(CHAR_SET[rn] for rn in rns) ne...
# STRING DATA TYPE # strings are arrays of bytes representing unicode characters s1="text" # string is created with double quotation marks s2='this is also a string' # single quotation marks are the same thing s3='abc123!# "/(@£$.. ""abc123ABC' # strings can contain any characters s4="""one liner""" # three " or '-ch...
#!/usr/bin/env python # -*- coding:utf-8 -*- """ FileName: 142. Linked List Cycle II.py Author: Kimberly Gao Date: 2021/07/20 6:31 PM Version: 0.1 """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def detectCy...
#Problem 507 def perfect_number(num): divisor_sum = 1 if num == 1: return False for i in range(2, int(num**0.5)): if num%i == 0: divisor_sum = divisor_sum + i + num/i if divisor_sum == num: return True return False #Tests def perfect_number_test(): input_nums1 = 28 input_nums2...
# coding=utf-8 """ Just version so that if this is run, there is no side effects. """ __version__ = "0.1.6" # Jiggle Version Was Here
# # PySNMP MIB module CISCO-LES-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LES-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:04:28 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ idx = 0 m_idx = 0 n_idx = len(input_list)-1 while idx <= n_idx: if input_list[n_idx] == 2:...
# # @lc app=leetcode.cn id=283 lang=python3 # # [283] 移动零 # # @lc code=start class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ for num in nums[:]: if num == 0: nums.append(0) ...
# # PySNMP MIB module IDT1-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IDT1-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:51:57 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:1...
# creating a Class of name Employee class Employee: # creating a Class Variable increament = 1.5 # Creating a Constructor of the Class Employee def __init__(self, fname, lname, salary): # setting Values to the variables self.fname = fname # setting Values to the variables ...
def add_digits(num): if num < 10: return num else: return add_digits(sum(map(int, str(num)))) if __name__ == "__main__": input_number = 38 print(add_digits(input_number))
# Python code to insert a node in AVL tree class TreeNode(object): def __init__(self, val): self.value = val self.left = None self.right = None #self.parent = none self.height = 1 class AVL_Tree(object): def insert(self, root, key): #Step 1 - perf...
# -*- python -*- # # Copyright (C) 2012, Pigeon Point Systems # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. This # file and program are licensed under a BSD style license....
def decreaseBlue(picture): for pixel in getPixels(picture): blue = getBlue(pixel) new_blue = blue * 0.1 setBlue(pixel, new_blue) repaint(picture) def swapColor(picture): for pixel in getPixels(picture): blue = getBlue(pixel) red = getRed(pixel) setBlue(pixel, red) setRed...
# stack using a Linked List # Push - adds data to the “top” of the stack # Pop - returns and removes data from the “top” of the stack # Peek - returns data from the “top” of the stack without removing it # Last in, First Out # What happens to peek() or pop() when our stack is empty? # How do we stop from push()...
""" This program turns a string into all capital or all lowercase letters. """ first_string = "hello" second_string = first_string.upper() third_string = second_string.lower() print(first_string) print(second_string) print(third_string)
# -*- coding: utf-8 -*- """ @Time : 2020-03-17 17:35 @Author : QDY @FileName: LinearList.py @Software: PyCharm """ class SequenceList: def __init__(self): self.SeqL = [] def __str__(self): return str(self.SeqL) def isEmpty(self): return self.SeqL == [] def input(sel...
class Solution: def XXX(self, nums: List[int]) -> List[List[int]]: path,res= [],[] def backtrack(start): if len(path)==len(nums): res.append(path[:]) return res # 每一层的元素允许比父节点的数字小,所以从0开始 for i in range(len(nums)): #枝...
name = input("please enter name: ") ''' count = 0 for i in name: if i == ",": count +=1 print("you entered " + str(count + 1) + " names") ''' a = name.count(",") b = a + 1 print (b)
""" International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on. For convenience, the full table for the 26 letters of the English alphabet is given below: [ ".-","-...","-.-.","-....
class AgeError(Exception): def __init__(self,message): Exception.__init__(self,message) try: # Write the code whose exceptions need handling d = {1:"One"} print(d[1]) age= int(input("Enter Age: ")) if age < 0: raise AgeError('Age is Negative')# Throw your own exception f = 100/2...
# pyinfra # File: pyinfra/api/exceptions.py # Desc: pyinfra's exceptions! class PyinfraError(Exception): ''' Generic pyinfra exception. ''' class OperationError(PyinfraError): ''' Exception raised during fact gathering staging if an operation is unable to generate output/change state. ''...
__project__ = 'checkio' __version__ = '0.72.0' VERSION = "{0} v{1}".format(__project__, __version__)
# -*- coding: utf-8 -*- """ @author: yuan_xin @contact: yuanxin9997@qq.com @file: node.py @time: 2020/10/19 17:24 @description: """ class Node(object): ''' 顾客点类: c_id:Number,顾客点编号(任务点编号)(TaskNo) x:Number,点的横坐标 y:Number,点的纵坐标 demand:Number,点的需求量 ready_time:Number,点的最早访问时间 due_time:Numbe...
class MinPQ(): def __init__(self): self.a = [None] self.n = 0 self.size = 0 def insert(self, item): if self.n == self.size: self._resize(max(1, self.n) * 2) self.n += 1 self.a[self.n] = item self._swim(self.n) return None def del_...
with open("input.txt") as f: data = f.read().splitlines() horizontal, vertical, aim = 0, 0, 0 for command in data: direction, amount = command.split() match direction: case "forward": horizontal += int(amount) vertical += int(amount) * aim case "down": ...
APP_PATH = '/var/www/Capstone/' LANDS_PATH = APP_PATH + 'var/landmarks/face_landmarks_68.dat' RATIOS_PATH = APP_PATH + 'var/data/ratios.json' RATIOS_AVG_PATH = APP_PATH + 'var/data/ratios_avg.json' RATIOS_STDS_PATH = APP_PATH + 'var/data/ratios_stdevs.json' ANGLES_PATH = APP_PATH + 'var/data/angles.json' ANGLES_AVG_P...
class MethodDoc(): def __init__(self, namespace, method_sig): self.__namespace = namespace self.__method_sig = method_sig self.__description = '' self.__signature = '' self.__parameters = {} self.__return_type = '' self.__return_description = '' self._...
# Inteiro para Romano def int_to_roman(num): """ https://www.w3resource.com/python-exercises/class-exercises/python-class-exercise-1.php :param num: :return: """ lookup = [ (1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'),...
lanche=("hamburguer", "suco", "pizza", "pudim") #TUPLAS SÃO IMUTÁVEIS #print(lanche) #print(lanche[2]) #print(lanche[1:3]) #print(lanche[-2:]) #for comida in lanche: # print(f"Eu vou comer {comida}.") #for cont in range(0, len(lanche)): #print(cont) # print(f"Eu vou comer {lanche[cont]} na posição {cont}.") fo...
# Python Program To Create A New Object Inside The Function Does Not Modify Outside Object ''' Function Name : Create New Object Inside Function Does Not Modify Outside Object. Function Date : 6 Sep 2020 Function Author : Prasad Dangare Input : Integer Output : Integer ''' ...
# # PySNMP MIB module LSF-SNMP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LSF-SNMP-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:08:56 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,...
class BeaconDBException(Exception): """ Base class for exceptions raised by this package. """ pass class HeadStateSlotNotFound(BeaconDBException): """ Exception raised if head state slot does not exist. """ pass class StateNotFound(BeaconDBException): """ Exception raised i...
class TopVotedCandidate: def __init__(self, persons, times): votes = collections.defaultdict(int) winner = 0 self.winners = [None] * len(times) self.times = times for i, person in enumerate(persons): votes[person] += 1 if votes[person] >= votes[winne...
def get_shortest_path(graph: dict, start, goal) -> str: # keep track of visited nodes visited = [] # keep track of all the paths to be checked queue = [[start]] # return path if start is goal if start == goal: return start # keeps looping until all possible paths have been checked ...
""" Madau, P., & Dickinson, M. 2014, ARA&A, 52, 415 """ pars_ml = \ { 'a': 0.015, 'b': 2.7, 'c': 2.9, 'd': 5.6, } #pars_err = \ #{ # 'a': 0.001, # 'b': 0.21, # 'c': 0.14, # 'd': 0.19, #} def _SFRD(z, a=None, b=None, c=None, d=None): return a * (1. + z)**b / (1 + ((1 + z) / c)**d) def SFRD(z): return _SF...
expected_output = { 'vrf': { 'vrf_104': { 'address_family': { 'ipv4': { 'no_group_ranges': 5, 'no_g_routes': 1, 'no_s_g_routes': 100, 'no_route_x_interfaces': 100, 'total_no_inte...
# Specify output formats. At least one must = True STL = True # [True, False] WEB = False # [True, False] STEP = False # [True, False] # Set Standard Dimensions std_d = 40.0 # Diameter of the base [5.0 to 100.0] (mm) std_h = 48.0 # Height of the neck [10.0 to 200.0 ] (mm) NOTE: this is the height of the bisho...
# 트럼프 대통령 트윗을 공백 기준으로 분리한 리스트 trump_tweets = ['america', 'is', 'back', 'and', 'we', 'are', 'coming', 'back', 'bigger', 'and', 'better', 'and', 'stronger', 'than', 'ever', 'before'] def make_new_list(text): new_list = [] for word in text: if word[0] == 'b': # if word.startswith('b'): ...
# def find_similar_in_3_arrays(a, b, c): # ii, jj, kk = 0, 0, 0 # result = [] # while (ii <= len(a)) and (jj <= len(b)) and (kk <= len(c)): # ii # if a[ii] > b[jj] and a[ii] > c[kk]: # print("a i ", a[ii]) # jj += 1 # kk += 1 # elif b[jj] > a[ii] ...
""" Author: Resul Emre AYGAN """ """ Project Description: Directions Reduction Once upon a time, on a way through the old wild mountainous west,… … a man was given directions to go from one point to another. The directions were "NORTH", "SOUTH", "WEST", "EAST". Clearly "NORTH" and "SOUTH" are opposite, "WEST" and "EA...
class ComboBoxData(RibbonItemData): """ This class contains information necessary to construct a combo box in the Ribbon. ComboBoxData(name: str) """ @staticmethod def __new__(self,name): """ __new__(cls: type,name: str) """ pass Image=property(lambda self: object(),lambda self,v: None,lambda...
""" Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. """ __author__ = 'Daniel' class ListNode:...
nome=input("digite seu nome: ") idade=int(input("digite a idade ")) if idade>=65: print("o paciente " + nome + " POSSUI atendimento prioritario") else: print("O paciente " + nome + " NÃO possui atendimento prioritário")
# A function is a block of code which only runs when it is called. In Python, # we do not use parentheses and curly brackets, we use indentation with tabs or spaces # Create function def sayHello(name = 'Sam'): """ Prints Hello and then name. """ print('Hello ' + name) # Return value def getSum(num1, num2): ...
# increment i by one i += 1 def sentence_similarity(sentence1, sentence2): """ compute the sentence similarity using Wordnet """ # Tokenize and tag sentence1 = pos_tag(word_tokenize(sentence1)) sentence2 = pos_tag(word_tokenize(sentence2)) # Get the synsets for the tagged words synsets1 = [ta...
class IStorageOption: @staticmethod def config_has_api(request) -> bool: """check if the api exists""" pass # Create new redis key @staticmethod def config_load_headers(cache_key, val, exp): """Creates the header object from storage""" pass # Get value of key ...
name = 'dong' SEX = 'MAN' print('hello world') a = 1 print(a, type(a)) # <class 'int'> s1 = 'day01' s2 = 'day02' s3 = ''' 可以换行 ''' print(s1 , type(s1)) # <class 'str'> print(s2) print(s3) print(s1 + s2) # day01day02 print(s2 * 2) # day02day02 print(2 > a, type(2 > a)) # True <class 'bool'> username = in...
# Python INTRO for TD Users # Kike Ramírez # May, 2018 # Understanding Operators #Arithmetic Operators x= 4 y= 5 print (x + y) #Comparison Operators x = 4 y = 5 print('x > y is',x>y) #Assignment Operators num1 = 4 num2 = 5 print ("Line 1 - Value of num1 : ", num1) print ("Line 2 - Value of num2 : ", num2) #compo...
texto_ordem_saltos = ['Primeiro salto', 'Segundo salto', 'Terceiro salto', 'Quarto salto', 'Quinto salto'] saltos_atleta = [0.0, 0.0, 0.0, 0.0, 0.0] atleta = input("Atleta: ") if atleta != '': for c in range(0, 5): saltos_atleta[c] = float(input(f"{texto_ordem_saltos[c]}: ")) media_saltos = (saltos...
# # PySNMP MIB module BAY-STACK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BAY-STACK-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:35: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 201...
def filter_noncruising(trip_list, keep_only_driving=True, keep_all_fhv=False, silent=True): # keep_list = np.repeat(0, len(trip_list)) # for i in range(len(trip_list)): if keep_all_fhv == True: # if trip_list[i]['label'] == 'cruising' or \ # trip_list[i]['fhv'] == True: trip...
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Reverses a string obtained from user. # # Program ...
# -*- coding: utf-8 -*- """ Created on Wed Jul 7 12:26:07 2021 @author: aymer """ data
""" Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode" return 2. Note: You may assume the string contains only lowercase English letters. """ #Difficulty: Easy #104 / ...
# -*- coding: utf-8 -*- """ Created on Sat May 23 15:47:06 2020 @author: Christopher Cheng """ # Define an object type via class # parenthesis of object means your class is going to be a python object class Circle (object): # Must initialize parameters of a class afterwards # this is aka method # self i...
class CoffeeMachine: # Constructor that initializes a CoffeeMachine with default values. def __init__(self): self.water = 400 self.milk = 540 self.coffee_beans = 120 self.cups = 9 self.money = 550 self.state = 'await_command' # Determines if the coffee machin...
class options(): mitm = True sniffer = True srv_ = "192.168.0.100" port = 5777 gui = False
def find_subarray(A, i): k = A[i] solutions = [A.pop(i)] for n in range(i - 1, -1, -1): # search left if k >= A[n]: solutions.insert(0, A.pop(n)) else: break for n in range(-(len(A) - i - 1), 0): # search right if k >= A[n]: solutions.append(A...
class abstractstatic(staticmethod): __slots__ = () def __init__(self, function): super(abstractstatic, self).__init__(function) function.__isabstractmethod__ = True __isabstractmethod__ = True
ACCOUNTS = [ { 'email': 'grrr', 'password': 'grrr', }, ]
class Heap: """Base class for heap object.""" def __init__(self): """Initialize constructor for heap object.""" self.heap = [] def parent(self, index: int) -> int: return (index - 1) // 2 def left_child(self, index: int) -> int: return (2 * index) + 1 # pragma: no cove...
######## Return Statement ######## def cube(num): return num*num*num print(cube(3)) result = cube(4) print(result)
def bubbleSort(lst): for i in range(len(lst)-1): for j in range(len(lst)-1, i, -1): if lst[j] < lst[j-1]: lst[j-1], lst[j] = lst[j], lst[j-1] return lst if __name__ == '__main__': lst = [8, 11, 2, 1, 4, 19, 9, 14, 13, 5, 6, 22] lst = bubbleSort(lst) print(lst)
#program to perform ceaser cipher ch='y' while ch=='y' or ch=='Y': print("Menu:") #menu for asking choice print("1.Cipher a message") print("2.Decipher a message") choice=int(input("Enter your choice: ")) if choice==1: string=input("Enter the string: ") k=i...
#!/usr/bin/env python3 # Add two link-lists of integers, this time in python # # found here: # https://leetcode.com/problems/add-two-numbers/ # class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: Lis...
class MixTapeError(Exception): """Mixtape exception base clase""" class PlayerNotConfigured(MixTapeError): """Player setup not completed""" class PlayerAlreadyConfigured(MixTapeError): """Player has already been setup""" class PlayerSetStateError(MixTapeError): """Setting the pipeline state has fa...
# -*- coding: utf-8 -*- """ Clases utilizadas en la generación de un archivo Graphviz DOT con el árbol de sintáxis abstracta creado a partir de un programa Tiger. """ class DotGenerator(object): """ Clase utilizada para la generación de grafos en formato Graphviz DOT. """ def __init__(self): ...
class DisplayFilter: def __init__(self): self.log_level_set = set() def Update_Filter(self, log_level_set): self.log_level_set = log_level_set def IsValidForFilter(self, log_message): if log_message.level in self.log_level_set: return True return False
#!/usr/bin/env python3 """ João Papo-de-Pescador, homem de bem, comprou um microcomputador para controlar o rendimento diário de seu trabalho. Toda vez que ele traz um peso de peixes maior que o estabelecido pelo regulamento de pesca do estado de São Paulo (50 quilos) deve pagar uma multa de R$ 4,00 por quilo excedente...
def two_sum_hastable(nums, target): hashtable = {} for i, num in enumerate(nums): remaining = target - num if remaining not in hashtable: hashtable[num] = i else: return [hashtable[remaining], i]
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...