content
stringlengths
7
1.05M
class Error(Exception): def __init__(self, basemessage="Unspecified Error", message=""): self.basemessage = basemessage self.message = message super().__init__(basemessage, message) class NotImplementedError(Error): """An error to indicate that the requested operation has not yet been ...
"""Import, export, compare different project exports.""" __author__ = """Fabian Göttel""" __email__ = "fabian.goettel@gmail.com" __version__ = "0.3.0"
x,y=map(int,input().split()) if(x < y): print('<') elif(x > y): print('>') elif(x==y): print('==')
def somar(num1, num2): n1 = str(num1) n2 = str(num2) print(n1, n2) opcao = int(input("""\nEscolha a conversão: [1] Decimal > Binario [2] Decimal > Octal [3] Decimal > Hexadecimal [4] Binario > Decimal [5] Octal > Decimal [6] Hexadecimal > Decimal ========================== [7] Somar Binarios [8] Subtrair...
class Settings(): # APP SETTINGS # /////////////////////////////////////////////////////////////// ENABLE_CUSTOM_TITLE_BAR = False MENU_WIDTH = 240 TIME_ANIMATION = 400 # BTNS LEFT AND RIGHT BOX COLORS BTN_LEFT_BOX_COLOR = "background-color: rgb(44, 49, 58);" BTN_RIGHT_BOX_COLOR = "back...
""" Dicionários OBS: Em algumas linguagens de programação, os dicionários Python são conhecidos por mapas. Dicionários são coleções do tipo chave/valor. (Mapeamento entre chave e valor) #Tuplas [0, 1, 2] [1, 2, 3] # Listas (0, 1, 2) (1, 2, 3) Dicionários são representados por chaves {}. print(type({})) OBS: Sobr...
# This program is free software: you can redistribute it and/or modify it under the # terms of the Apache License (v2.0) as published by the Apache Software Foundation. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or...
class MonoidLawTester: def __init__(self, monoid, value): self.monoid = monoid self.value = value def left_identity_test(self): monoid = self.monoid(self.value) assert monoid.concat(monoid.neutral()) == monoid def right_identity_test(self): monoid = self.monoid(sel...
class Circulo: pi = 3.14 # variable de clase (sin self), puede ser utilizadas por las instancias def __init__(self,radio): self.radio = radio # radio es una variable de instancia circle1 = Circulo(10) circle2 = Circulo(20) print(circle1.radio) circle2.radio = 100 print(circle2.radio) # uso de la va...
''' 在一个火车旅行很受欢迎的国度,你提前一年计划了一些火车旅行。在接下来的一年里,你要旅行的日子将以一个名为 days 的数组给出。每一项是一个从 1 到 365 的整数。 火车票有三种不同的销售方式: 一张为期一天的通行证售价为 costs[0] 美元; 一张为期七天的通行证售价为 costs[1] 美元; 一张为期三十天的通行证售价为 costs[2] 美元。 通行证允许数天无限制的旅行。 例如,如果我们在第 2 天获得一张为期 7 天的通行证,那么我们可以连着旅行 7 天:第 2 天、第 3 天、第 4 天、第 5 天、第 6 天、第 7 天和第 8 天。 返回你想要完成在给定的列表 days 中列出的每一天的旅行所...
# -*- coding:utf-8 -*- class Type: id = '' word_id = '' name = '' meanings = [] def desc(self): name = self.name if self.name is not None else '' return '(\'' + self.word_id + '\', \'' + name + '\')'
##Clock in pt2thon## t1 = input("Init schedule : ") # first schedule HH1 = int(t1[0] + t1[1]) MM1 = int(t1[3] + t1[4]) SS1 = int(t1[6] + t1[7]) t2 = input("Final schedule : ") # second schedule HH2 = int(t2[0] + t2[1]) MM2 = int(t2[3] + t2[4]) SS2 = int(t2[6] + t2[7]) tt1 = (HH1 * 3600) + (MM1 * 60) + SS1 # total...
# PySNMP SMI module. Autogenerated from smidump -f python IANA-MAU-MIB # by libsmi2pysnmp-0.1.3 at Thu May 22 11:57:41 2014, # Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) # Imports ( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", ...
# gemato: Utility functions # vim:fileencoding=utf-8 # (c) 2017 Michał Górny # Licensed under the terms of 2-clause BSD license def path_starts_with(path, prefix): """ Returns True if the specified @path starts with the @prefix, performing component-wide comparison. Otherwise returns False. """ re...
# name: Exes and Ohs # url: https://www.codewars.com/kata/55908aad6620c066bc00002a # Check to see if a string has the same amount of 'x's and 'o's. The method # must return a boolean and be case insensitive. The string can contain any char. def xo(s): lowerStr = s.lower() return lowerStr.count('o') == lowerStr....
BASE_URL = "https://paper-api.alpaca.markets" KEY = "your key here" SECRET_KEY = "your secret key here" HEADERS = {"APCA-API-KEY-ID": KEY, "APCA-API-SECRET-KEY": SECRET_KEY} # headers are used to authenticate our request
# coding: utf-8 # Copyright 2014 jeoliva author. All rights reserved. # Use of this source code is governed by a MIT License # license that can be found in the LICENSE file. class RangedUri(object): def __init__(self): self.start = 0 self.length = -1 self.baseUri = "" self.referenc...
#coding=utf-8 """ c module 文档 """ class c_cc(object): """ c_cc类说明 """ def func_c_cc(self): """ func说明 :return: """ return None
class Solution: def wordPatternV1(self, pattern: str, str: str) -> bool: p2s, s2p, words = {}, {}, str.split() if len(pattern) != len(words): return False for p, s in zip(pattern, words): if p in p2s and p2s[p] != s: return False else: ...
#------------------------------------------------------------------------------- # Name: powerlaw.py # Purpose: This is a set of power law coefficients(a,b) for the calculation of # empirical rain attenuation model A = a*R^b. #------------------------------------------------------------------------------- ...
"""18 - Em campeonato de futebol por pontos corridos, as pontuações funcionam da seguinte forma: 0 pontos por derrota, 1 ponto por empate e 3 pontos por vitória. Construa uma função que receba a quantidade de vitórias, derrotas e empates de um time e retorne a sua pontuação total ao fim do campeonato""" def pontuacao...
def isPalindrome(x): #x = x.casefold() rev_str = reversed(x) if list(x) == list(rev_str): print("It is palindrome") return True else: print("It is not palindrome") return False isPalindrome("SSAASS")
'''Application Data (bpy.app) This module contains application values that remain unchanged during runtime. ''' debug = None '''Boolean, for debug info (started with --debug / --debug_* matching this attribute name) ''' debug_events = None '''Boolean, for debug info (started with --debug / -...
############################################## # parameters than can be defined by the user # ############################################## # parameters modifying the behaviour of the network global weight_multiplicator # multiplicator of a returned observation, allow to scale observations in ...
preço = 0 preço_total = 0 blá = '' gleb = [] pedido = [] print('Lukepe: Eae mulekão!! Bem vindo ao restaurante do Lukepe') print('Gleb: Eae mulekão!! Tem oq nesse cardápio?') while True: garçon_preço = [input('o que tem no cardápio garçon?: '), float(input('qual é o preço?: '))] pedido.append(garçon_pr...
# -*- coding: utf-8 -*- name = 'nuke_ML_server' version = '0.1.3' build_requires = [ 'cmake-3.10+' ] variants = [ ['platform-linux', 'arch-x86_64', 'nuke-12.2'] ] def commands(): env.NUKE_PATH.append('{root}/lib') env.LDD_LIBRARY_PATH.append(env.NUKE_LOCATION)
input() x = list(map(int, input().split())) N = len(x) for i in range(0, N - 1): for j in range(0, N - i - 1): if x[j] > x[j + 1]: x[j], x[j + 1] = x[j + 1], x[j] print(' '.join(map(str, x)))
class Solution: def reverseString(self, s): """ :type s: str :rtype: str """ output = list(s) output = output[::-1] output = "".join(output) return output
# author: Bilal El Uneis # since: April 2018 # bilaleluneis@gmail.com class Methods: number_of_instances = 0 # this is a class level property # initializer with default values (constructor) def __init__(self, method_name="anonymous", method_return_type="void"): self.method_name = method_name ...
n = int(input()) a = list(map(int, input().split())) total = sum(a) if total % n != 0: print(-1) exit() num = total // n ans = 0 for i in range(n - 1): left = sum(a[:i + 1]) right = sum(a[i + 1:]) if left < num * (i + 1) or right < num * (n - i - 1): ans += 1 print(ans)
#encoding:utf-8 subreddit = 'KamenRider' t_channel = '@r_KamenRider' def send_post(submission, r2t): return r2t.send_simple(submission)
"""Python implementation of Binary Search Tree.""" class BST(): # pragma: no cover """Binary Search Tree.""" def __init__(self): """Initialize Binary Search tree.""" self._root = None self._length = 0 self._rdepth = 0 self._ldepth = 0 self._depth = 0 s...
t = int(input()) tests = [] def fact(n): if n == 1: return n else: return n * fact(n - 1) while t > 0: n = int(input()) tests.append(fact(n)) t -= 1 for x in tests: print(x % 10)
class Distribution: def __init__(self, mu=0, sigma=1): """ Genertic distribution class for calculating and visualizing a probability disttribution. Attributes: mean (float) representing the mean value of the distribution. stdev (float) represent...
#!/usr/bin/env python # 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 # # Authors: # - Paul Nilsson, paul.nilsson@cern.ch, 2018-2021 def allow_mem...
# ирішити в цілих числах рівняння: $$(ax + b) / (cx + d) = 0$$ # # # Формат введення # # водяться 4 числа: $$a, b, c, d; c і d$$ не рівні нулю одночасно. # # # Формат виведення # # еобхідно вивести всі рішення, якщо їх число звичайно, "NO" (без лапок), якщо рішень немає, і "INF" (без лапок), якщо рішень нескінченно баг...
# dictionary, emoji convertion, split method message = input(">") words = message.split(' ') print(words) # get a seperated words of the msg emojis = { ":)": "😄", ":(": "😟" } output = "" for word in words: output += emojis.get(word, word) + " " print(output)
# Adapted from byterun test_functions.py test # Tests returning from a generator """This program is self-checking!""" def gen(): yield 1 return 2 x = gen() while True: try: assert next(x) == 1 except StopIteration as e: assert e.value == 2 break
""" Class for holding and accessing a "Named Entity" for a relation """ class NamedEntity: def __init__(self, entity, doc): self.entity = entity """ Gets the type of entity this object represents. "PERSON", "ORG", etc. """ @property def entity_type(self): return N...
for _ in range(int(input())): a,b,q=map(int,input().split()) arr=[] for i in range(q): arr+=[list(map(int,input().split()))] res=0 if a!=b: for j in range(arr[i][0],arr[i][1]+1): if (j%a)%b!=(j%b)%a: res+=1 ...
#!/anaconda3/envs/nlp python3.8 # -*- coding: utf-8 -*- # --- # @File: sentiment_predict.py # @Author: HW Shen # @Time: 9月 15, 2020 # --- class SentimentModel(object): def __init__(self): self.gloveEmbedding = 0
# The isBadVersion API is already defined for you. # @param version, an integer # @return a bool def isBadVersion(version): pass class Solution: def firstBadVersion(self, n): left, right = 0, n while left <= right: mid = (left + right) // 2 if not isBadVersion(mid): ...
""" LC 26 Given an array of sorted numbers, remove all duplicates from it. You should not use any extra space; after removing the duplicates in-place return the length of the subarray that has no duplicate in it. Example 1: Input: [2, 3, 3, 3, 6, 9, 9] Output: 4 Explanation: The first four elements after removing th...
def takeInstInput(S): degrees = [] inputS = S.split(" ") inputS = [int(x) for x in inputS] for i in range(len(inputS)): degrees.append((inputS[i], i)) return degrees def takeFileInput(FileName): fileI = open(FileName, 'r') inputS = fileI.readline() degrees = takeInstInput(inputS...
""" Given a N cross M matrix in which each row is sorted, find the overall median of the matrix. Assume N*M is odd. For example, Matrix= [1, 3, 5] [2, 6, 9] [3, 6, 9] A = [1, 2, 3, 3, 5, 6, 6, 9, 9] Median is 5. So, we return 5. """ def median_matrix(A): if len(A) == 1: vec = A[0] return vec[len(vec)//2] else: ...
"""arbmod.py just a sample module for use with tests.""" def arbmod_attribute(): """Do nothing.""" pass
""" The Borg Pattern Notes: Originally proposed by Alex Martelli, the Borg Pattern improves upon the classical Singleton pattern by questioning the point of a Singleton. While a Singleton design pattern mandates that all objects representing a Singleton must share the same identity (point to the same instance of a c...
class Solution: def intToRoman(self, num: int) -> str: ''' T: O(1) and S: O(1) ''' int2rom = {1000:'M', 900:'CM', 500:'D', 400:'CD', 100:'C', 90:'XC', 50:'L', ...
""" One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #. _9_ / \ 3 2 / \ / \ 4 1 # 6 / \ / \ / \ # # # # # # For example, the above binary tree c...
# # config.py: configuration for semantic segmentation # (c) Neil Nie, 2017 # All Rights Reserved. # batch_size = 8 img_height = 512 img_width = 1024 display_height = 512 display_width = 1024 nb_classes = 34 learning_rate = 1e-4 nb_epoch = 10
# # @lc app=leetcode id=485 lang=python3 # # [485] Max Consecutive Ones # # @lc code=start class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: res = 0 count = 0 for i in nums: if i == 0: count = 0 else: count += 1...
''' module for calculating greatest common divisor (GCD) and lowest common multiple (LCM) ''' def gcd(x: int, y: int): ''' Calculating GCD of x and y using Euclid's algorithm ''' if (x > y): while (y != 0): x, y = y, x % y return x else: while (x != 0)...
course = "Python Programming" message = """ east n west, cats are the best!🐈 """ print(message) print(len(course)) print(course[0]) print(course[-1]) print(course[1:4]) # including 1, excluding 4 print(course[3:]) # erases before 3 print(course[:3]) print(course[:]) # copy of the original
""" For a string and pattern, count for each pattern the number of times it appears in the string """ def check_pattern_count(string, pattern): pattern_count = 0 string_length, pattern_length = len(string), len(pattern) for i in range(0, string_length - pattern_length - 1): temp_pattern_extract = ...
#!/bin/python3 #I think this needs to run in c def addTuple(t1, t2): return [t1i + t2i for t1i, t2i in zip(t1, t2)] def compareTuple(t1, t2): return all([t1i <= t2i for t1i, t2i in zip(t1, t2)]) def theHackathon(n, m, a, b, f, s, t): # Participant code here people = {} groups = {} max_de...
# Mostrar o valor em dólar. real = float(input('Digite o valor em Real: R$')) def real_hoje(real): dol = real / 5.44 return dol def euro_hoje(real): euro = real / 6.55 return euro print('Você consegue comprar {:.2f} euros' .format(euro_hoje(real))) print('e {:.2f} dólares' .format(real_hoje(real))...
# https://www.geeksforgeeks.org/merge-sort/ # merge(arr,l,m,r) is a key process assuming that arr[l..m] and arr[m+1..r] are sorted and merges the sub-arrays into one # Recursive implementation # Space complexity is O(n)+O(logn) counting stack frames -> still O(n) in case of arrays def mergeSort(arr): # base cas...
# list of lists matrix = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]] # get element from list of lists x = matrix[0][0] # slice a list of lists x = matrix[0][0:2] # update element in list matrix[0][0] = -1 # remove element in list matrix[0].remove(-1) # get number of lists x = len(matrix)
def finished_hook_for_mp3(d): if d['status'] == 'finished': print('다운로드가 완료되었습니다. 컨버팅을 시작합니다.') def finished_hook_for_mp4(d): if d['status'] == 'finished': print('다운로드가 완료되었습니다.')
# A little about strings # Often programmers face a problem that can be solved by # analogy. You are already familiar with the string data type, # Now you need to study the relevant section of the # documentation about strings to solve this problem. In the # documentation you will find the necessary similar examples. ...
def stringfixer(sentence): sentence = sentence.split() symbollst = [".","!","?"] flag = False count = 0 final = "" for elm in sentence: if count ==0: elm = elm.capitalize() count += 1 if flag: elm = elm.capitalize() flag = False ...
class Node: """ this is the constructor. """ def __init__ (self, val = None, next = None): self.val = val self.next = next class LinkedList: """ stores reference to head node, and interacts with nodes, but is not a node. """ def __init__(self): self.head = None ...
test_json = [] test_json.append("""{"log":[ {"user_responses":[ {"description":"test autologging 2 "}, ]}, {"autogeneratated":[ {"status":""}, {"files":[ {"name":"./sample/interface_deck_2D_decomp/head/interface_deck_2D_decomp.cc","size":79168,"last_modified":1528904996}, {"name":"./s...
def positive_or_negative(value): if value > 0: return "Positive!" elif value < 0: return "Negative!" else: return "It's zero!" number = int(input("Wprowadz liczbe: ")) print(positive_or_negative(number))
"""Traffic generator package using scapy Scapy Documentation: http://www.secdev.org/projects/scapy/doc/ """
""" Draw tree like structures using Space Colonization algorithm https://www.youtube.com/watch?v=kKT0v3qhIQY https://medium.com/@jason.webb/space-colonization-algorithm-in-javascript-6f683b743dc5 """ add_library('svg') leaf_prob = 0.01 # ratio of non-white pixels that are converted to leaves max_dist = 50 # max dist...
command = input().split("|") energy = 100 coins = 100 clear_event = True for current_command in command: current_command = current_command.split("-") event = current_command[0] number = int(current_command[1]) if event == "rest": needed_energy = 100 - energy gained_energy = min(numbe...
class EventLogEntryCollection(object): """ Defines size and enumerators for a collection of System.Diagnostics.EventLogEntry instances. """ def ZZZ(self): """hardcoded/mock instance of the class""" return EventLogEntryCollection() instance=ZZZ() """hardcoded/returns an instance of the class""" def CopyT...
def diff_tests(input_files): tests = [] updates = [] for input_file in input_files: genrule_name = "gen_{}.actual".format(input_file) actual_file = "{}.actual".format(input_file) native.genrule( name = genrule_name, srcs = [input_file], outs = [a...
#----------------------------------------------------------------------------- # Name: Looping Structures - While (loopingWhile.py) # Purpose: To provide information about how while loops work as a looping # structure in Python # # Author: Mr. Seidel # Created: 17-Aug-2018 # Updated: 22-Aug...
print("Akshitha Sai"); print("AM.EN.U4CSE18122"); print("CSE"); print("marvel rocks");
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'chromium_code': 1, }, 'targets': [ { # GN version: //ios/net:ios_net_unittests 'target_name': 'ios_net_unittests',...
def test_password(con): """Called by GitHub Actions with auth method password. We just need to check that we can get a connection. """ pass
n = int(input("Enter N: ")) l = [] for i in range(0 , n): inp = int(input("Enter numbers: ")) l.append(inp) l.sort() a = 0 b = 0 for i in range(0 , n): if i % 2 != 0: a = a * 10 + l[i] else: b = b * 10 + l[i] c = a + b print(c)
help = '''tdo -- A todo list tool for the terminal. Available commands: tdo Lists all undone tasks, sorted by category. tdo all Lists all tasks. tdo add "task" [list] Add a task to a certain list or the default list. tdo edit id Edit a task description. tdo done id ...
game_list = { "games": [ "4story", "8bitmmo", "9dragons", "9lives-arena", "a-tale-in-the-desert", "a3", "a3-still-alive", "aberoth", "ace-online", "achaea", "ad2460", "adventure-land", "adventure-quest-3d", "adventurequest-worlds", ...
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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 # # Unless required by applicable law or agreed ...
# For demonstration this will serve as the database of partners # For real implementation this will come from a database. # Both partnerId and key should be shared between services. partners = { 'abcd123' : { # this is partner ssoId (abcd123) 'name': 'Partner 1 inc.', 'shared_key' : '5f4dcc3b...
#!/usr/bin/env python3 steps = 10 with open('input.txt', 'r') as f: lines = f.read().splitlines() initial_string = lines[0] mapping = {} for line in lines: if '->' in line: x,y=line.split(" -> ") replacement_text = x[0]+y mapping[x] = replacement_text for _ in range(1, steps+1): processed_string = '' fo...
#Occurance of a word in text file Text = open("abc.txt","r") d = dict() #Dictionary to store words(keys) and its iterations(values) # iterate through each line in txt file for line in Text: line = line.strip() #remove leading space and \n chrtr line = line.lower() #convert to lower case words = line.spl...
# Easy horntail gem sm.spawnMob(8810102, 95, 260, False) sm.spawnMob(8810103, 95, 260, False) sm.spawnMob(8810104, 95, 260, False) sm.spawnMob(8810105, 95, 260, False) sm.spawnMob(8810106, 95, 260, False) sm.spawnMob(8810107, 95, 260, False) sm.spawnMob(8810108, 95, 260, False) sm.spawnMob(8810109, 95, 260, False) sm.s...
# file generated by setuptools_scm # don't change, don't track in version control version = "0.1.dev1+ga7b326d.d20210618" version_tuple = (0, 1, "dev1+ga7b326d", "d20210618")
""" Prepare arguments for goldclip pipeline """ def args_init(args=None, demx=False, trim=False, align=False, call_peak=False): """Inititate the arguments, assign the default values to arg """ if isinstance(args, dict): pass elif args is None: args = {} # init d...
pattern_zero=[0.0, 0.024983563445, 0.048652202498, 0.051282051282, 0.07100591716, 0.076265614727, 0.092044707429, 0.09993425378, 0.102564102564, 0.111768573307, 0.122287968442, 0.127547666009, 0.130177514793, 0.143326758711, 0.147271531887, 0.151216305062, 0.153846153846, 0.163050624589, 0.173570019724, 0.177514792899,...
class Solution: def findRepeatNumber(self, nums: List[int]) -> int: s = set() for _ in nums: if _ not in s: s.add(_) else: return _
def dfs(vertex): global reachable_vertex global visited_vertex if visited_vertex[vertex] is True: return visited_vertex[vertex] = True reachable_vertex.append(vertex) for i in range(0, vertex_num): if adjacent_matrix[vertex][i] is True: dfs(i) vertex_num = int(inp...
# 14.2.5 Python Implementation class Graph: """Representation of a simple graph using an adjacency map.""" #------------------------- nested Vertex class ------------------------- class Vertex: """Lightweight vertex structure for a graph.""" __slots__ = '_element' def __init__(sel...
N, K=map(int, input().split()) arr=[] result=0 for i in range(N): arr.append(int(input())) for i in range(N-1, -1, -1): if K==0: break else: result+=K//arr[i] K=K%arr[i] print(result)
''' Crie um programa que leia números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre elas (desconsiderando o flag). ''' # Iniciar as variaveis n = s = 0 contador = 0 # Laço whi...
""" 413. Reverse Integer https://www.lintcode.com/problem/reverse-integer/description?_from=ladder&&fromId=37 """ class Solution: """ @param n: the integer to be reversed @return: the reversed integer """ def reverseInteger(self, n): # write your code here a = str(abs(n)) ...
class Token: """Token representation class""" def __init__(self, token_type, lexeme, literal, line): self.type = token_type self.lexeme = lexeme self.literal = literal self.line = line def __str__(self): if self.lexeme: return self.lexeme else: ...
myl1 = [12,10,38,22] myl1.sort(reverse = True) print(myl1) myl1.sort(reverse = False) print(myl1)
"""Bundles all exceptions and warnings used in the package prodsim""" class InvalidValue(Exception): """ Raises when a value is not within the permissible range """ pass class InvalidType(Exception): """ Raises when a value has the wrong type """ pass class MissingParameter(Exception): """ Raised...
# coding=utf-8 """ 二叉树的最小深度 给定一个二叉树,找出其最小深度。 二叉树的最小深度为根节点到最近叶子节点的最短路径上的节点数量。 思路: 有这几种情况 1.有左右树的 2.只有左树的 3.只有右树的 4.无树的 针对 1 找到min就行了 针对2,3,4找到max就行了 """ """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: ...
def minSwap(arr, n, k) : # Find count of elements # which are less than # equals to k count = 0 for i in range(0, n) : if (arr[i] <= k) : count = count + 1 # Find unwanted elements # in current window of # size 'count' bad = ...
'''veiculos = ['carro'] #lista print(veiculos)#mostra''' '''alunos = ['João', 22, '13/07/1997'] #lista print(len(alunos)) #mostra quantidade print(alunos [0], "\n", alunos [1], "\n", alunos [2]) #mostra informações da lista usando a posição''' #maisfunçaodalista '''nome = input("Digite seu nome: ") idade = input("Dig...
#!/usr/bin/python # -*- coding: utf-8 -*- """CatSystem 2 PE executable information WARNING: This module is deprecated, and will be changed or removed, once it's made obsolete. """ __version__ = '0.0.1' __date__ = '2020-01-01' __author__ = 'Robert Jordan' #################################################...
class CSVWriter: """Class that represents the structure of a CSV file writer Author: Luis Marques """ def __init__(self, filename: str, header: tuple, file_type: str = "w"): """Creates an instance of a CSV file writer Args: filename (str): string to define the name of the ...
class Product: def __init__(self, name="", price=0.0, discountPercent=0): self.name = name self.price = price self.discountPercent = discountPercent def getDiscountAmount(self): return self.price * self.discountPercent / 100 def getDiscountPrice(self): return self.p...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def isPalindrome(self, head: ListNode) -> bool: slow, fast = head, head tot = 0 while fast and fast.next: fast = ...