content
stringlengths
7
1.05M
real_number = {chr(el) for el in range(ord('0'), ord('9') + 1)} real_number.update(['.', ',']) required_real_number = {'.'} def real_number_is_valid(number): real_number_as_set = set(number) if not number or real_number_as_set - real_number or required_real_number - real_number_as_set: return False ...
#!/usr/bin/env python """ File name: test_CTCI_Ch4_Ex5.py Author: Matt Randazzo Date created: 2/18/2019 Date last modified: 2/18/2019 Python Version: 3.7 Description: CTCI 4.5 Validate BST Implement a function to check if a binary tree is a binary...
""" A collection of Bootstrap static files. """ __author__ = 'Peter Bittner' __email__ = 'django@bittner.it' __license__ = 'MIT' __url__ = 'https://github.com/bittner/django-bootstrap-static' __version__ = '5.0.0-beta1'
''' Problem: Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists, and should also be sorted. For example, given following linked lists : 5 -> 8 -> 20 4 -> 11 -> 15 The merged list should be : 4 -> 5 -> 8 -> 11 -> 15 -> 2...
""" 0426. Convert Binary Search Tree to Sorted Doubly Linked List Medium Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place. You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the p...
# # @lc app=leetcode id=367 lang=python3 # # [367] Valid Perfect Square # # @lc code=start class Solution: def isPerfectSquare(self, num): cur = 1 while True: multi = cur * cur if multi > num: return False if multi == num: return T...
# Convert Integer to the Sum of Two No-Zero Integers # # Source - https://leetcode.com/problems/convert-integer-to-the-sum-of-two-no-zero-integers/ class Solution: def getNoZeroIntegers(self, n): for a in range(n): if '0' not in f'{a}{n - a}': return [a, n - a] s = Solution()....
#class Solution: # def chalkReplacer(self, chalk: List[int], k: int) -> int: def chalkReplacer(chalk, k): # loop thru the list `chalk` one time first, # to know its sum. somme = 0 for i, n_i in enumerate(chalk): k -= n_i if k < 0: return i somme += n_i ...
# Copyright The OpenTelemetry Authors # # 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 to in ...
""" โ–ˆโ–€โ–€โ€ƒโ–ˆโ–€โ–€โ€ƒโ–ˆโ–„โ–‘โ–ˆโ€ƒโ–ˆโ–€โ–€โ€ƒโ–ˆโ–€โ€ƒโ–ˆโ€ƒโ–ˆโ–€โ€ƒ โ€ƒโ–ˆโ–‘โ–‘โ€ƒโ–ˆโ–€โ–€โ€ƒโ–ˆโ–€โ€ƒโ–ˆโ–€โ€ƒโ–ˆโ–€โ–ˆโ€ƒโ–ˆโ–„โ–‘โ–ˆโ€ƒโ–ˆโ–€โ€ƒ โ€ƒโ–ˆโ–‘โ–ˆโ€ƒโ–ˆโ–€โ–ˆโ€ƒโ–ˆโ–‘โ–‘โ€ƒโ–‘โ€ƒโ–„โ–ˆ โ–ˆโ–„โ–ˆโ€ƒโ–ˆโ–ˆโ–„โ€ƒโ–ˆโ–‘โ–€โ–ˆโ€ƒโ–ˆโ–ˆโ–„โ€ƒโ–„โ–ˆโ€ƒโ–ˆโ€ƒโ–„โ–ˆโ€ƒ โ€ƒโ–ˆโ–„โ–„โ€ƒโ–ˆโ–ˆโ–„โ€ƒโ–„โ–ˆโ€ƒโ–„โ–ˆโ€ƒโ–ˆโ–„โ–ˆโ€ƒโ–ˆโ–‘โ–€โ–ˆโ€ƒโ–„โ–ˆโ€ƒ โ€ƒโ–€โ–„โ–€โ€ƒโ–ˆโ–„โ–ˆโ€ƒโ–ˆโ–„โ–„โ€ƒโ–„โ€ƒโ–‘โ–ˆ Welcome to the genesis gir lesson tutorials Volume 1! Do you know me as much as you think you do? This program tests you on how well you think you know me! Select from al...
ENTRY_POINT = 'match_parens' FIX = """ Fix the bug of in solution which considers )( )( as valid. Add test case for above. """ #[PROMPT] def match_parens(lst): ''' You are given a list of two strings, both strings consist of open parentheses '(' or close parentheses ')' only. Your job is to check if ...
class ParseQuery(object): def __init__(self, ): super(ParseQuery, self).__init__() def parse_query(self, query): temp_query = query.split("=") return temp_query class ParsePayload(object): def __init__(self, ): super(ParsePayload, self).__init__() ...
""" Base utilities to build API operation managers and objects on top of. """ class Manager(object): """Manager for API service. Managers interact with a particular type of API (projects, users, reposiries,etc.) and provide CRUD operations for them. """ def __init__(self, api): self.api ...
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Education, obj[4]: Occupation, obj[5]: Bar, obj[6]: Coffeehouse, obj[7]: Restaurant20to50, obj[8]: Direction_same, obj[9]: Distance # {"feature": "Coupon", "instances": 8147, "metric_value": 0.4734, "depth": 1} if obj[2]>1: # {"feature...
class Table: def __init__(self, dealer, players): self.dealer = dealer self.players = players # self.participants = players + dealer def __repr__(self): return f'Table(dealer={self.dealer}, players={self.players})' def render(self): return f'{"".join(hand.render() f...
print ('Welcome to the Guess Game') secret_word = "giraffe" guess = "" guess_count = 0 guess_limit = 3 out_of_guesses = False while guess != secret_word and not (out_of_guesses): if guess_count < guess_limit: guess = input("Enter guess: ") guess_count += 1 else: out_of_guesses= True i...
# Escreva um programa que leia dois nรบmeros inteiros e compare-os mostrando na telauma mensagem: # - o primeiro vlorรฉ maior # - o segundo valor รฉ maior # - nรฃo existe valor maior, os dois sรฃo iguais n = int(input('Digite um numero: ')) n2 = int(input('Digite outro numero: ')) if n > n2: print('O primeiro valor รฉ ...
def isSymmetrical(str): length = len(str) mid = length // 2 if length % 2: mid = length // 2+1 return isSymmetrical(str[:mid-1] + str[mid:]) return str[mid:] == str[:mid] def isPalindrome(str): length = len(str) for i in range(length//2): if str[i] != str[length-1-i]: ...
req = """ alembic==1.4.2 astroid==2.3.3 bandit==1.6.2 click==7.1.1 colorama==0.4.3 Flask==1.1.2 Flask-Env==2.0.0 Flask-JWT-Extended==3.24.1 flask-marshmallow==0.11.0 Flask-Migrate==2.5.3 Flask-SQLAlchemy==2.4.1 gitdb==4.0.5 GitPython==3.1.3 isort==4.3.21 itsdangerous==1.1.0 Jinja2==2.11.1 lazy-object-proxy==1.4.3 Mako=...
DJIA = pd.read_csv('data/DJIA.csv', parse_dates=['DATE'], na_values='.') # Since the dataset uses '.' to signal NA valeus, pandas represented that column as a # string instead of a float DJIA.set_index('DATE', inplace=True) ax = DJIA.plot(legend=False) ax.set_ylabel('DJIA') ax.set_xlabel('Date')
"""Collection of utils for Statement Results of queries.""" def execution_time(result): """Return the execution time of a query.""" avail = result.summary().result_available_after cons = result.summary().result_consumed_after return avail + cons def total_db_hits(result): """Return th...
class Solution: def majorityElement(self, nums: List[int]) -> int: nums.sort() ans = nums[len(nums)//2] return ans
def sw_def(read, sequence): read_len = len(read) seq_len = len(sequence) dimension = (read_len + 1) * (seq_len + 1) dp_table = [0] * dimension gap_score = -2 match_score = 1 max_score = 0 max_score_coordinates = [] for i in range(read_len): i += 1 # because the dp ta...
def my_filter(predicate, sequence): for elt in sequence: if predicate(elt): yield elt even_numbers = my_filter(lambda x: x % 2 == 0, range(1, 11)) print(even_numbers) print(next(even_numbers)) print(list(even_numbers))
'''def findSum(x): for i in range(x): x = x + i return x print(str(findSum(20)))'''
#deklarasi funcion paramenter def hello(nama): print(f"heloo {nama}") #panggil hello("gamar")
class Compatibility: def __init__(self, clauses): self.clauses = clauses def check(self): return all(self.evaluate()) def evaluate(self): return [c() for c in self.clauses]
class BaseBlock: def __init__(self, value, position, branch=False, mass=None): self.value = value self.position = position self.branch = branch self.mass = mass self.extra = None def __str__(self): return self.value def __repr__(self): return self.v...
# awsflow package filename template PKG_WHEEL_FNAME = "awsflow-{version}-py3-none-any.whl" # AWS role used for Lambda functions AWS_LAMBDA_ROLE = None # SSH keyfile downloaded from AWS to ssh into the master node AWS_SSH_KEY_PATHNAME = '~/.ssh/yourkeypair.pem' # default AWS region AWS_DEFAULT_REGION = 'eu-central-1'...
def add_time(start, duration, day_of_the_week = None): new_time = '' ## IDEA ONE # split start time into hours, minutes, AM/PM # convert 60 mins to 1 hour, 24 hours to 1 day # add duration hours and minutes to start time # 11:59 AM/PM -> 12:00 PM/AM ## IDEA TWO # for start time: convert every AM/PM to total minu...
# Open terminal > python3 classEg5.py # Start typing below commands and see the output # Base class class Person: actions = [] # def __init__(self): # self.actions = [] # Cannot be accessed from Derived class instance def addActions(self, action): self.actions.append(action) # Derived class class S...
class A: vc = 123 def __init__(self): self.vc = 321 a1 = A() a2 = A() print(a1.vc) print(a2.vc) print(A.vc)
def reverse(l): if len(l) == 0: return [] return reverse(l[1:]) + [ l[0]] assert reverse([1,2,3]) == [ 3,2,1] assert reverse(["a", "b"]) == [ "b", "a"] assert reverse(list(range(1,101))) == list(range(100,0,-1))
# Special methods in Python: Use __iadd__ to increment in-place; use __add__ to increment and create a new instance. # Author: Zhuo Lu # Test suite 1 print("\nTest suite 1\n") _i = i = 0 # Test int _t = t = (1, 2) # Test tuple _l = l = [1, 2] # Test list i += 1 t += (3,) l += [3] print(_i, i, _i is i) # Output...
# Copyright (c) 2016 Rackspace, Inc. # # 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 to in wr...
class NurbsSurface(Surface,IDisposable,ISerializable,IEpsilonComparable[NurbsSurface]): """ Represents a Non Uniform Rational B-Splines (NURBS) surface. NurbsSurface(other: NurbsSurface) """ def ConstructConstObject(self,*args): """ ConstructConstObject(self: CommonObject,parentObject: object,sub...
def list_chunk(target, n): """ ๋ฆฌ์ŠคํŠธ๋ฅผ n๊ฐœ๋กœ ๋ถ„ํ• ํ•ด์ค๋‹ˆ๋‹ค. **Example** simple_utils.array.list_chunk(your_list, 5) **Parameters** * **target** (list) -- ๋ถ„ํ• ํ•  ํƒ€๊ฒŸ์ž…๋‹ˆ๋‹ค. * **n** (int) -- ๋ช‡ ๊ฐœ์”ฉ ๋ถ„ํ• ํ• ์ง€ ์ •ํ•ฉ๋‹ˆ๋‹ค. """ return [target[i:i+n] for i in range(0, len(target), n)]
ll = [12, 'exo', '12321', 'exo', 213, 34, 33] # ll.reverse() # print(ll) # # print(ll.count('exo')) print(ll) print(ll.pop()) print(ll) print(ll.pop(2)) print(ll)
""" Given a string s and an integer k, return the number of k-length substrings that occur more than once in s. Constraints n โ‰ค 100,000 where n is the length of s. k โ‰ค 10 https://binarysearch.com/problems/Repeated-K-Length-Substrings """ class Solution: def solve(self, s, k): slen, substrings = ...
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: def isok(k): count = 0 for p in piles: count += (p - 1) // k + 1 return count <= h l = 1 r = max(piles) while l < r: mid = (l + r)//2 ...
### Test Runner command # testinfra -v test_redis.py def test_redis_is_installed(Package): redis = Package("redis-server") assert redis.is_installed def test_config_file(File): config_file = File('/etc/redis/redis.conf') assert config_file.contains('bind 127.0.0.1') # todo make it a regex assert...
# Photoset ID photoset_id = u'72157713956740191' # Camera tags camera_tags = { 'CanonEOSREBELT5i' : '\"DSLR\" \"APS-C\" \"Canon EOS Rebel T5i\"' , 'CanonEOSDIGITALREBELXTi': '\"DSLR\" \"APS-C\" \"Canon EOS Digital Rebel XTi\"', 'SamsungNXmini' : '\"CSC\" \"1-inch\" \"Samsung NX mini\"...
lista1 = [] lista2 = [] tamanho = int(input("Digite a dimensรฃo dos vetores: ")) print("Digite o vetor 1:") for x in range(tamanho): x1 = int(input("")) lista1.append(x1) print("Digite o vetor 2:") for x in range(tamanho): x2 = int(input("")) lista2.append(x2) resultado = 0 for x in range(tama...
THEME_STYLESHEETS = [ 'light', 'dark', ] THEME_CHOICES = tuple([(x, x) for x in THEME_STYLESHEETS]) def stylesheet_url(syntax_highlighting_style, default=THEME_STYLESHEETS[0]): for stylesheet in THEME_STYLESHEETS: if syntax_highlighting_style == stylesheet: return 'css/%s.css' % style...
def diag_diff(arr): len_col = len(arr) sum_diag1 = sum_diag2 = 0 for row in enumerate(arr): for col in enumerate(arr): sum_diag1 += arr[row[0]][row[0]] sum_diag2 += arr[row[0]][len_col - col[0] - 1] return sum_diag1 - sum_diag2
file1 = open('reportRepair_input.txt', 'r') lines_read = file1.readlines() def calculate_answer(lines): for i in range(len(lines)): number = int(lines[i]) if number >= 2020: continue for j in range(i, len(lines)): second_number = int(lines[j]) if number ...
# -*- coding: utf-8 -*- class ScrapeError(Exception): """scraping Failed"""
class Ship: def __init__(self, shipType): self.name = shipType self.sunk = False if shipType == "Aircraft Carrier": self.size = 5 self.char = 'a' elif shipType == "Battleship": self.size = 4 self.char = 'b' elif shipType == "Destroyer": self.size = 3 self.char =...
class CifsLugImportOpStatus(basestring): """ Status of the import operation of CIFS local users and groups Possible values: <ul> <li> "unknown" , <li> "success" , <li> "success_with_warnings" , <li> "failed" , <li> "in_progress" ...
class Node: """ Tree node: left and right child + data which can be any object """ def __init__(self, data): """ Node constructor @param data node data object """ self.left = None self.right = None self.data = data def insert(se...
class A: def f(self): ''' Function descr, argument types, return type ... ''' print('Hello world') return 'Hello world'
def add(element): return def get(index): return
class AssetNotFound(Exception): pass class CircularDependencyError(Exception): pass
# pakage # __init__.py __all__ = []
def for_Trepezium(): """ Pattern for : Trepezium using for loop""" for i in range(7): for j in range(20): if i==6 or i+j==6 or j-i==13 or i==0 and j in range(6,13): print('*',end=' ') else: print(' ',end=' ') print() def while_Trepezium(): """ Pattern for : Trepezium using while loop""" ...
# Define a product function that accepts a list of numbers. # The function should return the product of the numbers. # The list will always have at least one value # # EXAMPLES # product([1, 2, 3]) => 6 # product([4, 5, 6, 7]) => 840 # product([10]) => 10 def product(lists): total = 1 for list in...
# Problem: https://projecteuler.net/problem=230 """ . Quite similar to problem 220. . Build a "Fibonacci tree" such that, . Let T(k) indicate the tree representing the k^th Fibonacci word. . T(1) and T(2) are leaf nodes. . The left node of T(k) is T(k-2), and the right node of T(k) is T...
for i in range (2,14): j=i*5-4 suma=0 print(j) suma=0 for i in range(1,13): t=5*i+1 suma=suma+t print(suma)
# Time: O(n) # Soace: O(1) # Given a non-empty string s, you may delete at most one character. # Judge whether you can make it a palindrome. # # Example 1: # Input: "aba" # Output: True # Example 2: # Input: "abca" # Output: True # Explanation: You could delete the character 'c'. # Note: # The string will only contain...
# Variables yes = ["Y", "y", "Yes", "yes"] no = ["N", "n", "No", "no"] # Starting Greeting print("Hello! How are you?") greeting = input(">>> ") print("Thats Good!") # Space print("") # Name print("What is your name?") name = input(">>> ") print("So your name is " + name + "?") choice = input(">>>") if choice in ye...
# -*- coding: utf-8 -*- """ Declaration of constants. """ # ML constants DEFAULT_BATCH_SIZE = 256 MAX_BATCH_SIZE = 2**20 DEFAULT_GRADIENT_UPDATES_PER_PASS_COUNT = 8 PATIENCE = 10 # patience for early stopping # GPU GPU_MEMORY_LIMIT_MB = 4096 # Logging INFO_LOGGING_FILE_NAME = "info.log" DEBUG_LOGGING_FILE_NAME = "d...
_config = None def get_hide_prefix() -> str: return get_config_property("style", "hidePrefix") def is_sort_attributes() -> bool: return get_config_property("style", "sort") def is_rewrite_booktitle() -> bool: return get_config_property("style", "rewriteBooktitle", "rewrite") def get_attribute_names(...
# Funciรณn que pasa el diccionario de state a un รบnico string def stateCaracteristicas(documento): try: caracteristicasEspeciales = "**Las caracterรญsticas especiales del menรบ son:** \n" diccionarioState = documento['state'] if type(diccionarioState) != dict: raise Valu...
set_name(0x8007D77C, "GetTpY__FUs", SN_NOWARN) set_name(0x8007D798, "GetTpX__FUs", SN_NOWARN) set_name(0x8007D7A4, "Remove96__Fv", SN_NOWARN) set_name(0x8007D7DC, "AppMain", SN_NOWARN) set_name(0x8007D884, "MAIN_RestartGameTask__Fv", SN_NOWARN) set_name(0x8007D8B0, "GameTask__FP4TASK", SN_NOWARN) set_name(0x8007D948, "...
n1 = float(input('Qual o seu salรกrio: ')) print(f'O seu novo salรกrio com aumento de 15% รฉ {n1 * 1.15 :.0f} Real(is),' f' houve o aumento de {(n1 * 1.15) - n1:.0f} Real(is)') n2 = 3.546372 print('O nรบmero รฉ {} e ele com uma casa รฉ {:.4f}'.format(n2, n2))
def task621(lst, addedLst): for i in range(len(addedLst)): lst.pop(0) for i in range(len(addedLst) - 1, -1, -1): lst.insert(0, addedLst[i]) return lst def task621_main(): print( """ ะ—ะฐะดะฐะฝะธะต 6 "ะกะฟะธัะบะธ" 2. ะŸัƒัั‚ัŒ ะดะฐะฝ ัะฟะธัะพะบ ะธะท 10 ัะปะตะผะตะฝั‚ะพะฒ. ะ’ะฐั€ะธะฐะฝั‚ 1. ะฃะดะฐะปะธั‚ะต ะฟะตั€ะฒั‹ะต 2 ัะปะตะผะตะฝั‚ะฐ ะธ ...
r, c, zr, zc = [int(x) for x in input().split(" ")] result = [] for i in range(r): chars = list(input()) if len(chars) == c: for i in range(len(chars)): chars[i] = chars[i] * zc for i in range(zr): result.append(chars) for x in result: s = "" for y in x: ...
# -*- coding: utf-8 -*- """Top-level package for ErnosCube.""" __author__ = """Andrew Franklin""" __email__ = "andfranklin3@gmail.com" __version__ = "0.1.0"
a, b, c = [int(x) for x in input().split()] a = a if a != 0 else 24 b = b if b != 0 else 24 c = c if c != 0 else 24 s = a + b + c print(s - 24 if s >= 24 else s)
jI = 1 k = 0 q = 0 jF = 0 summ = 0 while jI < 4000000: if (jI/2) == int(jI/2): summ = summ + jI q = k k = jI jF = k + q jI = jF print("The sum of the even terms is:") print(summ)
def age_assignment(*args, **kwargs, ): # names_age = {} # for name in args: # first_letter = name[0] # names_age[name] = kwargs[first_letter] # # return names_age return {x: kwargs[x[0]] for x in args} print(age_assignment("Peter", "George", G=26, P=19)) print(age_assignment("Amy"...
class ClassName: def instance_method(self): return self @staticmethod def static_method(): return 'nothing...' @classmethod def class_method(cls): return cls print(ClassName().instance_method()) print(ClassName().static_method()) print(ClassName().class_method()) print(C...
n1 = int(input("Digite um numero: ")) n2 = int(input("Digite outro numero: ")) n3 = int(input("Digite outro numero: ")) if n1>n2 and n1>n3: print ("{} รฉ o maior numero" .format(n1)) elif n2 >n1 and n2>n3: print ("{} รฉ o maior numero" .format(n2)) else: print ("{} รฉ o maior numero" .format(n3))
# coding=utf-8 """ parse2csv.release ~~~~~~~~~~~~~~~~~ Module containing package release information. :copyright: (c) 2018 by Ali Ghaffaari. :license: MIT, see LICENSE for more details. """ # CONSTANTS ################################################################### # Development statuses: DS...
tab = False if tab: print('chocolate') print('tabs are cool')
swap = lambda x, y : (y,x) x = int(input("Enter first number: ")) y = int(input("Enter second number: ")) x, y = swap(x, y) print("First number:", x) print("Second number:", y)
#entrada n = int(input()) #processamento n = str(n) msg = 'NO es de Mala Suerte' for i in range(0, len(n)): if n[i] == '1' and i != len(n) - 1: if n[i + 1] == '3': msg = 'es de Mala Suerte' break #saida print(n, msg)
class DrawingPatternPoint: def __init__(self, x_change: int, y_change: int, is_obligatory: bool = True): self.x_change = x_change self.y_change = y_change self.is_obligatory = is_obligatory def copy(self): return DrawingPatternPoint(self.x_change, self.y_change, self.is_obligato...
class TaskProblem(): def __init__(self, tasks, messages, processors, links): self.processors = processors self.links = links self.tasks = tasks self.messages = messages def __str__(self): res = describe('Tasks', self.tasks) res += describe('Messages', self.messag...
# Escolha a base de conversรฃo num = int(input('Digite um nรบmero inteiro: ')) print('''Escolha uma base para conversรฃo: [1] converter para BINรRIO [2] convertere para OCTAL [3] converter para HEXADECIMAL''') opรงรฃo = int (input('Sua opรงรฃo: ')) if opรงรฃo == 1: print('{} convertido para BINรRIO รฉ igual {} '.format(num,...
#output orcidFile='output/orcid.tsv' pubmedFile='output/pubmed.tsv' tfidfFile='output/orcid-tf-idf.txt' orcidToOrcid='output/orcid-to-orcid-tf-idf.tsv' #data demoPubmedFile='data/pubmed.tsv' demoOrcidFile='data/orcid.tsv' demoTfidfFile='data/orcid-tf-idf.txt' demoPurePeopleFile='data/pure_people.txt' demoPureOrcidFile...
X=int(input()) if X<=10**4: Divs=[] for a in range(1,X+1): if X%a==0: Divs.append(a) resp="" for a in Divs: resp+=str(a)+" " print(resp[0:len(resp)-1])
#!/usr/bin/env python # -*- coding: utf-8 -*- # author: huanglei # ้—ฐๅนด for year in range(1700, 2022): if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: print('{} ๆ˜ฏ้—ฐๅนด'.format(year)) else: print('{} ๆ˜ฏๅนณๅนด'.format(year))
# Fonte: https://leetcode.com/problems/single-number/ # Autor: Bruno Harlis # Data: 24/07/2021 """ PROBLEMA pROPOSTO: Dada uma matriz nรฃo vazia de inteiros nums, cada elemento aparece duas vezes, exceto um. Encontre aquele รบnico. Vocรช deve implementar uma soluรงรฃo com uma complexidade de tempo de execuรงรฃo linear e ...
def could_be_yaml(filename): return bool('.yml' in filename or '.yaml' in filename) def could_be_playbook(data): for phrase in ('hosts', 'include', 'import_playbook'): if phrase in data: return True return False def could_be_role(data): if not isinstance(data, list): re...
# -*- coding: utf8 -*- """ ะ˜ะผั: ะกั‚ั€ะพะธั‚ะตะปัŒ (Builder) ะขะธะฟ: ะŸะพั€ะพะถะดะฐัŽั‰ะธะน ะพะฑัŠะตะบั‚ั‹. ะกัƒั‚ัŒ: ะ ะฐะทะดะตะปัะตั‚ ัะพะทะดะฐะฝะธั ัะปะพะถะฝะพะณะพ ะพะฑัŠะตะบั‚ะฐ ะธ ะธะฝั†ะธะปะธะทะฐั†ะธัŽ ะตะณะพ ัะพัั‚ะพัะฝะธะต ั‚ะฐะบ, ั‡ั‚ะพ ะพะดะธะฝะฐะบะพะฒั‹ะน ะฟั€ะพั†ะตัั ะฟะพัั‚ั€ะพะตะฝะธั ะผะพะถะตั‚ ัะพะทะดะฐั‚ัŒ ะพะฑัŠะตะบั‚ั‹ ั ั€ะฐะทะฝั‹ะผะธ ัะพัั‚ะพัะฝะธัะผ. ะžั‚ ะฐะฑัั‚ั€ะฐะบั‚ะฝะพะน ั„ะฐะฑั€ะธะบะธ ะพั‚ะปะธั‡ะฐะตั‚ัั ั‚ะตะผ, ั‡ั‚ะพ ะดะตะปะฐั‚ะต ะฐะบั†ะตะฝั‚ ะฝะฐ ะฟะพัˆะฐะณะพะฒะพะผ ะบะพะฝัั‚ั€ะธั€ะพะฒะฐะฝะธะธ ะพะฑ...
""" contains all exceptions raised for package """ NoFileOrDir = ValueError('Must specify a file or directory') NotAvscFileError = ValueError() MissingFileError = OSError() NoFilesError = OSError BadReferenceError = ValueError( 'field to be referenced missing namespace or name keys' )
class Solution: def calculate(self, s: str) -> int: prevOperator = "+" num = 0 result = 0 temp = 0 for char in s+"+": if char.isdigit(): num = num * 10 + int(char) elif char in "+-*/": currOperator = ch...
#!/usr/bin/python3 # -*- coding: utf8 -*- class CommandGUI: """ Manage command events """ def quit_gui(self, *args): """ Destroy window and close app """ self.window.destroy() self.window.template = None def fullscreen(self, *args): """ Ch...
name_for_user_id = { 321: "Alice", 560: "Bob", 875: "Dilbert" } def gretting(userid): return f"Hi {name_for_user_id.get(userid, 'there')}!" print(gretting(321)) print(greetting(872132))
image_size = 224 n_channels = 3 patch_size = 14 n_classes = 10 d_model = 128 d_ffn = 768 n_blocks = 30 configs = { "Ti": { "image_size": image_size, "n_channels": n_channels, "patch_size": patch_size, "d_model": d_model, "d_ffn": d_ffn, "n_blocks": n_blocks, ...
strings_one = input().split(', ') text = input() new_strings = [word for word in strings_one if word in text] print(new_strings)
# # @lc app=leetcode id=29 lang=python3 # # [29] Divide Two Integers # class Solution: def divide(self, dividend: int, divisor: int) -> int: sign = (dividend<0) is (divisor <0) dividend, divisor = abs(dividend), abs(divisor) res= 0 while dividend >= divisor: tmp, i = div...
# the short name of the plugin, as used by the logger PLUGIN_NAME = 'link_checker' # mkdocs site build output directory MKDOCS_SITE_DIRECTORY = 'site' # list of links to exclude from validation EXCLUDED_LINKS = [ 'https://www.mkdocs.org', 'https://squidfunk.github.io/mkdocs-material/' ] # the base url of the...
# https://www.hackerrank.com/challenges/pairs/problem def pairs(k, arr): dic = {} count = 0 for i,a in enumerate(arr): if a-k in dic: count +=1 if a+k in dic: count += 1 dic[a] = i return count
""" Pyhons String template versjon Returner 'Hello, my Love!' hvis navn er Jรธrund, og 'Hello, navn!' for alle andre navn. """ def hilsen(navn): return 'Hello, {}!'.format('my Love' if navn == 'Jรธrund' else navn) #print(hilsen('Jรธrund')) #print(hilsen('Jรธran')) def hilsen_med_input(): navn = input('Hvem er du...
############################# # 8. String to Integer (atoi) ############################# class Solution: def myAtoi(self, str): """ :type str: str :rtype: int """ if not str: return 0 i = 0 while i<len(str) and str[i]==" ": i += 1 ...
""" Global Config and Constants """ __all__ = ['is_exportable', 'is_scriptable', 'set_exportable', 'set_scriptable'] # Set to True if exporting a model with Same padding via ONNX _EXPORTABLE = False # Set to True if wanting to use torch.jit.script on a model _SCRIPTABLE = True def is_exportable(): return _EXPO...
def temperature1(): rhs_Tw = '(1 / tau_w) * ((Tc - Tw) + eta * (Tp - Tw))' rhs_Tp = '(1 / tau_ps) * (Tw - Tp)' odes = {'Tw': rhs_Tw, 'Tp': rhs_Tp} return odes def temperature2(): rhs_Tw = '(1 / tau_w) * ((Tc - Tw) + eta * (Tp - Tw))' rhs_Tp = '0' rhs_Qp = 'hp * Ap * (Tw - Tmelt)' od...
num1 = float(input('Primeiro nรบmero: ')) num2 = float(input('Segundo nรบmero: ')) if num1 > num2: print('O PRIMEIRO nรบmero รฉ maior!') elif num2 > num1: print('O SEGUNDO nรบmero รฉ maior!') else: print('Os dois valores sรฃo iguais.')