content
stringlengths
7
1.05M
largura = float(input('Digite a largura da parede:')) altura = float(input('Digite a altura da parede:')) area = altura * largura qntd = area / 2 print('A área da parede é:{} m^2'.format(area)) print('São necessários {} litros de tinta'.format(qntd))
"""The ofx parser package. A package to parse OpenFlow messages. This package is a library that parses and creates OpenFlow Messages. It contains all implemented versions of OpenFlow protocol """ __version__ = '2020.2b3'
stormtrooper = r''' ,ooo888888888888888oooo, o8888YYYYYY77iiiiooo8888888o 8888YYYY77iiYY8888888888888888 [88YYY77iiY88888888888888888888] 88YY7iYY888888888888888888888888 ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeZeroSumSublists(self, head: ListNode) -> ListNode: stack = [] cur = head while cur: stack.append(cur) ...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
# -*- coding: utf-8 -*- """ bandwidth This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). """ class ConferenceEventMethodEnum(object): """Implementation of the 'ConferenceEventMethod' enum. TODO: type enum description here. Attributes: POST: T...
# -*- coding: utf-8 -*- """" Author: Jean Pierre Last Edited: """
# add your QUIC implementation here IMPLEMENTATIONS = { # name => [ docker image, role ]; role: 0 == 'client', 1 == 'server', 2 == both "quicgo": {"url": "martenseemann/quic-go-interop:latest", "role": 2}, "quicly": {"url": "janaiyengar/quicly:interop", "role": 2}, "ngtcp2": {"url": "ngtcp2/ngtcp2-interop:...
class WorksharingDisplayMode(Enum,IComparable,IFormattable,IConvertible): """ Indicates which worksharing display mode a view is in. enum WorksharingDisplayMode,values: CheckoutStatus (1),ModelUpdates (3),Off (0),Owners (2),Worksets (4) """ def __eq__(self,*args): """ x.__eq__(y) <==> x==yx.__eq__(y) ...
class Solution: def arrayNesting(self, nums): """ :type nums: List[int] :rtype: int """ dic={} for i in range(len(nums)): if i in dic: continue j=i dic[j]=1 while nums[i]!=j: dic[j]+=1 ...
class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: """ [1,2],[2,3],[3,4],[1,3] [(1,s), (1,s), (2,e), (2, s), (3, e), (3, e), (3, s), (4,e)] """ events = [] for start, end in intervals: events.append((start...
# https://stackoverflow.com/questions/16017397/injecting-function-call-after-init-with-decorator # define a new metaclass which overrides the "__call__" function class InitModifier(type): def __call__(cls, *args, **kwargs): """Called when you call MyNewClass() """ obj = type.__call__(cls, *args, **k...
# # PySNMP MIB module ADTRAN-AOS (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-AOS # Produced by pysmi-0.3.4 at Mon Apr 29 16:58:35 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:...
chars_to_remove = ["-", ",", ".", "!", "?"] with open('text.txt') as text_file: for i, line in enumerate(text_file): if i % 2 == 0: for char in line: if char in chars_to_remove: line = line.replace(char, '@') print(' '.join(reversed(line.split()))...
def hvplot_with_buffer(gdf, buffer_size, *args, **kwargs): """ Convenience function for plotting a GeoPandas point GeoDataFrame using point markers plus buffer polygons Parameters ---------- gdf : geopandas.GeoDataFrame point GeoDataFrame to plot buffer_size : numeric size o...
# (C) Datadog, Inc. 2019 # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) STANDARD = [ 'sap_hana.backup.latest', 'sap_hana.connection.idle', 'sap_hana.connection.open', 'sap_hana.connection.running', 'sap_hana.cpu.service.utilized', 'sap_hana.disk.free', 'sap...
def boxes_packing(length, width, height): total=[sorted((i,j,k)) for i,j,k in zip(length, width, height)] res=sorted(total, key=lambda x: -min(x)) for i,j in enumerate(res[1:]): if any((k-l)<=0 for k,l in zip(res[i], j)): return False return True
{ 'includes': [ '../common.gyp' ], 'targets': [ { 'target_name': 'libjpeg', 'type': 'static_library', 'include_dirs': [ '.', ], 'sources': [ 'ckconfig.c', 'jcapimin.c', 'jcapistd.c', 'jccoefct.c', 'jccolor.c', 'jcdctmgr.c', ...
# Copyright (c) 2009 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. { 'target_defaults': { 'defines': [ '_LIB', 'XML_STATIC', # Compile for static linkage. ], 'include_dirs': [ 'files/lib'...
""" BSD 3-Clause License Copyright (c) 2018, Jerrad Genson All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of condit...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** _SNAKE_TO_CAMEL_CASE_TABLE = { "acceleration_status": "accelerationStatus", "accelerator_arn": "acceleratorArn", "accept_st...
N, *S = open(0).read().split() t = 1 f = 1 for s in S: if s == 'AND': f = t + f * 2 elif s == 'OR': t = t * 2 + f print(t)
# %% [1221. Split a String in Balanced Strings](https://leetcode.com/problems/split-a-string-in-balanced-strings/) class Solution: def balancedStringSplit(self, s: str) -> int: res = cnt = 0 for c in s: cnt += (c == "L") * 2 - 1 res += not cnt return res
words = ['cat', 'window', "defenestrate"] for w in words : print(w, len(w)) users = ['A', "B", "C"] for i in users : print(i) for i in range(5): print(i)
COOK_LABEL_LIST = [ "Cook", ] MOVIE_LABEL_LIST = [ "Movie", ] READ_LABEL_LIST = [ "Read", ] DRAMA_LABEL_LIST = [ "Drama", ] PUSHUP_LABEL_LIST = [ "PushUps", ] BANGUMI_LABEL_LIST = [ "Bangumi", ] GAME_LABEL_LIST = [ "Game", ] MONEY_LABEL_LIST = [ "Money", ] MEDITATION_LABEL_LIST = [ "...
lista_de_compras = ["gabinete cooler master", "placa devídeo GeForce RTX 2080Ti"] print(lista_de_compras) lista_de_compras.remove("gabinete cooler master") lista_de_compras.remove("placa devídeo GeForce RTX 2080Ti") print(lista_de_compras)
""" You can use this file as a template to store your api credentials. Just copy (or rename) this file to `api_credentials.py` and fill in your key and secret. `api_credentials.py` is in this repository's `.gitignore` file. """ PAYONEER_ESCROW_API_KEY = 'ENTER_YOUR_API_KEY_HERE' PAYONEER_ESCROW_SECRET = 'ENTER_YOUR_AP...
#Kunal Gautam #Codewars : @Kunalpod #Problem name: Valid Braces #Problem level: 4 kyu valid = {'(': ')', '[': ']', '{': '}'} def validBraces(string): li=[] for item in string: if item in valid: li.append(item) elif li and valid[li[-1]] == item: li.pop() else: return False r...
summultiples = 0 for i in range(1000): if i % 3 == 0 or i % 5 == 0: summultiples += i print(summultiples)
def say_hello(name: str = 'Lucas'): print(f'Hello {name} ') def ask_age(): user_age = input('Age?') return user_age def say_hello_mp(name, age_user=25): print(f'Hello {name} {age_user}') if __name__ == '__main__': say_hello() say_hello(123) print(say_hello('Pierre')) say_hello_m...
# Prints arithmetic progression of 10 numbers print('10 Termos de uma PA') number = int(input('Primeiro termo: ')) constant = int(input('Razão: ')) total = 0 for c in range (1, 11): total = number + (c - 1) * constant print('{}'.format(total), end = ' → ') print('ACABOU')
# -*- coding: utf-8 -*- ######################################################################## # # License: BSD # Created: October 19, 2004 # Author: Ivan Vilata i Balaguer - reverse:net.selidor@ivan # # $Id$ # ######################################################################## """Special node behaviours for ...
class News: # 允许绑定的对象 __slots__ = ('__id', '__time', '__department', '__info') # 构造函数 def __init__(self, url, time, department, info): self.__id = url self.__time = time self.__department = department self.__info = info @property def id(self): return sel...
# -*- coding: utf-8 -*- """ Created on Thu Oct 1 13:12:08 2020 @author: Abhishek Parashar """ stack=[] vector=[] arr=[4,5,2,10,8] for i in range(len(arr)-1): if (len(stack)==0): vector.append(-1) elif (len(stack)>0 and stack[-1]<arr[i]): vector.append(stack[-1]) elif (len(s...
def foo(t1, t2, t3): return str(t1)+str(t2) res = foo(t1,t2,t3) print("Testing output!")
""" * Copyright 2007,2008,2009 John C. Gunther * Copyright (C) 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net> * * 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/lic...
''' @file: __init__.py.py @author: qxLiu @time: 2020/3/14 9:37 '''
__author__ = 'Ahmfrkyvz' def vigerene_cipher(plainText, key): i = 0 encryptedText = "" key = key.lower() plainText = plainText.replace('İ', 'i') plainText = plainText.lower() while i < len(plainText): char = ord(plainText[i]) charOfKey = ord(key[i%(len(key))]) if cha...
def set(name): ret = { 'name': name, 'changes': {}, 'result': False, 'comment': '' } current_name = __salt__['c_hostname.get_hostname']() if name == current_name: ret['result'] = True ret['comment'] = "Hostname \"{0}\" already set.".format(name) r...
class Solution: def canCross(self, stones: List[int]) -> bool: n = len(stones) # dp[i][j] := True if a frog can make a size j jump to stones[i] dp = [[False] * (n + 1) for _ in range(n)] dp[0][0] = True for i in range(1, n): for j in range(i): k = stones[i] - stones[j] if k ...
class PPSTimingCalibrationModeEnum: CondDB = 0 JSON = 1 SQLite = 2
a = input() i = ord(a) for i in range(i-96): print(chr(i+97),end=" ")
number = 16#71398757 base = 16#12 #должно получиться 35699370 def getZerosCount(number, base): #находим простые делители системы счисления i = 2 b = base dividers = [] degrees = [] ps_i = 0 step = 0 #степень - т.е. количество раз повторения делителя while i <= base: if b...
n=int(input("From number")) n1=int(input("To number")) for i in range(n,n1): for j in range(2,i): if i%j==0: break else: print(i)
# Recursive implementation to find the gcd (greatest common divisor) of two integers using the euclidean algorithm. # For more than two numbers, e.g. three, you can box it like this: gcd(a,gcd(b,greatest_common_divisor.c)) etc. # This runs in O(log(n)) where n is the maximum of a and b. # :param a: the first integer # ...
def _build(**kwargs): kwargs.setdefault("mac_src", '00.00.00.00.00.01') kwargs.setdefault("mac_dst", '00.00.00.00.00.02') kwargs.setdefault("mac_src_step", '00.00.00.00.00.01') kwargs.setdefault("mac_dst_step", '00.00.00.00.00.01') kwargs.setdefault("arp_src_hw_addr", '01.00.00.00.00.01') kwarg...
#Weird algorithm for matrix multiplication. just addition will produce result matrix class Solution: def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int: row = [0] * n col = [0] * m ans = 0 for r,c in indices: row[r] += 1 col[c] += 1 fo...
# -*- coding: utf-8 -*- """ Created on Tue Oct 13 20:04:26 2020 @author: ninjaac """ def count_substring(string, sub_string): return string.count(sub_string) #return (''.join(string)).count(''.join(sub_string)) if __name__ == '__main__': string = input().strip() sub_string = input().stri...
unavailable_dict = { "0": { ("11", "12", "13"): [ "message_1", "message_4" ], ("21", "22", "23"): [ "message_3", "message_6" ], ("24",): [ "message_2", "message_5" ], ("0", "blank",): [ ...
# In theory, RightScale's API is discoverable through ``links`` in responses. # In practice, we have to help our robots along with the following hints: RS_DEFAULT_ACTIONS = { 'index': { 'http_method': 'get', }, 'show': { 'http_method': 'get', 'extra_path':...
''' Created on Oct 1, 2011 @author: jose '''
""" Union and Intersection of Two Linked Lists Your task for this problem is to fill out the union and intersection functions. The union of two sets A and B is the set of elements which are in A, in B, or in both A and B. The intersection of two sets A and B, denoted by A ∩ B, is the set of all objects that are members...
"""binary tree """ #https://www.hackerrank.com/challenges/tree-preorder-traversal/problem #recrusive: def preOrder(root): print(root.info,end=' ') if root.left: preOrder(root.left) if root.right: preOrder(root.right) #itrative: def preOrder(root): stack=[root] while(stack): ...
# Definition for a undirected graph node class UndirectedGraphNode: def __init__(self, x): self.label = x self.neighbors = [] def __str__(self): return "({} -> {})".format(self.label, [nb.label for nb in self.neighbors]) def __repr__(self): ...
class Salary: def __init__(self,pay,bonus): self.pay=pay self.bonus=bonus def annual(self): return (self.pay*12)+self.bonus class employee: def __init__(self,name,age,pay,bonus): self.name=name self.age=age self.pay=pay self.bonus=bonus ...
# 给定一个整数数组,判断是否存在重复元素。 # 如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。 # 示例 1: # 输入: [1,2,3,1] # 输出: true class Solution: def containsDuplicate(self, nums: list) -> bool: return len(nums) != len(set(nums)) v = Solution().containsDuplicate([1,1,1,3,3,4,3,2,4,2]) print(v)
try: n = int(input('Numerador: ')) n2 = int(input('Denominador: ')) r = n / n2 except (ValueError, TypeError): print(f'Tivemos um problema com o tipo de dado que você digitou!') except ZeroDivisionError: print(f'Você não pode dividir por zero!') except KeyboardInterrupt: print(f'O usuário prefer...
test = { 'name': 'smallest-int', 'points': 0, 'suites': [ { 'cases': [ { 'code': r""" sqlite> SELECT * FROM smallest_int; 11/11/2015 10:01:03|7 11/11/2015 13:53:36|7 11/11/2015 14:52:07|7 11/11/2015 15:36:00|7 11/11/2015 15:46...
# Christian Piper # 11/11/19 # This will accept algebra equations on the input and solve for the variable def main(): equation = input("Input your equation: ") variable = input("Input the variable to be solved for: ") solveAlgebraEquation(equation, variable) def solveAlgebraEquation(equation, variable): ...
# Location of exported xml playlist from itunes # Update username and directory to their appropriate path e.g C:/users/bob/desktop/file.xml xml_playlist_loc = 'C:/users/username/directory/_MyMusic_.xml' # name of user directory where your Music folder is located # example: C:/users/bob/music/itunes music_folder_dir = '...
#!/usr/bin/env python # -*- coding: utf-8 -*- class Address(dict): """ Dictionary class that provides some convenience wrappers for accessing commonly used data elements on an Address. """ def __init__(self, address_dict, order="lat"): super(Address, self).__init__(address_dict) s...
def backtickify(s): return '`{}`'.format(s) def bind_exercises(g, exercises, start=1): for i, ex in enumerate(exercises): qno = i + start varname = 'q{}'.format(qno) assert varname not in g g[varname] = ex yield varname
# -*- coding: utf-8 -*- """ Created on Sat Jul 31 17:42:50 2021 @author: tan_k """
# LER O PESO DE 5 PESSOAS E MOSTRE O MAIOR E O MENOR maior = 0 menor = 0 for pessoa in range(1, 6): peso = float(input(f'Digite o {pessoa}° peso: ')) # SEMPRE NO 1° LAÇO O VALOR SERA O MAIOR E O MENOR POIS NAO HA REFERENCIA if pessoa == 1: maior = peso menor = peso # A PARTIR DO 2° LAÇO ...
# # PySNMP MIB module RBN-CONFIG-FILE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBN-CONFIG-FILE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:44:14 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
lista = ['Intel Core i9-9900KF.','Gigabyte B360M-Gaming 3','32GB DDR4 GDDR6','GeForce RTX 2080Ti','1TB de HD + 480GB de SSD','80PLUS 600W','Noctua NH-D15'] print('lista de todas as suas compras :', (lista)) print('Notamos que o preço da compra ultrapassou o orçamento limite definido pelo cliente, por isso, tomamos a li...
# 1이 될 때까지 # 하 # 그리드 N, K = map(int, input().split()) result = 0 while N >= K: while N % K != 0: N -= 1 result += 1 N //= K result += 1 while N > 1: result += 1 print(result)
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: dummy = ListNode(-1) dummy.next = head def t(d): if d.ne...
# nxn chessboard n = 10 # number of dragons on the chessboard dragons = 10 solution = [-1]*n captured = [[0 for i in range(n)] for i in range(n)] number = 0 local_calls = 0 total_calls = 0 def init(): global captured def isCaptured(x, y): global captured return captured[x][y] def capture(...
class ApiException(Exception): pass class Forbidden(ApiException): def __init__(self, message): self.message = message self.status_code = 403 class NotFound(ApiException): def __init__(self, message): self.message = message self.status_code = 404 class BadRequest(A...
# # Copyright (C) 2018 The Android Open Source Project # # 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 la...
# -*- coding: utf-8 -*- # # Copyright (C) 2005-2018 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.com/license.html. # # This software consists ...
class LDAP_record: """ consume LDAP record and provide methods for accessing interesting data """ def __init__(self, unid): self.error = False ldap_dict = {} # # request complete user record from LDAP cmd = "/Users/" + unid try: raw_data = sub...
NAME='nagios' CFLAGS = [] LDFLAGS = [] LIBS = [] GCC_LIST = ['nagios']
class Solution: def find_permutation(self, S): S = sorted(S) self.res = [] visited = [False] * len(S) self.find_permutationUtil(S, visited, '') return self.res def find_permutationUtil(self, S, visited, str): if len(str) == len(S): self.res.append(str...
s = set(map(int, input().split())) print(s) print("max is: ",max(s)) print("min is: ",min(s))
def transact(environment, t, to_agent, from_agent, settlement_type, amount, description): "Function that ensures a correct transaction between agents" environment.measurement['period'].append(t) environment.measurement['to_agent'].append(to_agent) environment.measurement['from_agent'].append(from_agent)...
class NSGA2: def __init__(self, initializer, evaluator, selector, crossover, mutator, stopper): self.initializer = initializer self.evaluator = evaluator self.selector = selector self.crossover = crossover self.mutator = mutator self.stopper = stopper self.po...
class RetrievalError(Exception): pass class SetterError(Exception): pass class ControlError(SetterError): pass class AuthentificationError(Exception): pass class TemporaryAuthentificationError(AuthentificationError): pass class APICompatibilityError(Exception): pass class APIError(Ex...
# Based on largest_rectangle_in_histagram 84 def maximal_rectrangle_in_matrix(matrix): if len(matrix) == 0 or len(matrix[0]) == 0: return 0 # Append extra 0 to the end, to mark the end of the curr row curr_row = [0] * (len(matrix[0]) + 1) ans = 0 for row in range(len(matrix)): for ...
class Deque(object): """A deque (double-ended queue) is a linear structure of ordered items where the addition and removal of items can take place on any end. Thus deques can work as FIFO (First In, First Out) or LIFO (Last In, First Out) Examples: >>> d = Deque() >>> d.is_...
""" Sampler metadata """ class Sampler(object): method_name = None def __init__(self): pass class GibbsSampler(Sampler): method_name = 'gibbs' def __init__(self, n_iter=1000, n_burnin=100, n_thread=1): # super(GibbsSampler, self).__init__() self.n_iter = n_iter self...
# A program to check if the number is odd or even def even_or_odd(num): if num == "q": return "Invalid" elif num % 2 == 0: return "Even" else: return "Odd" while True: try: user_input = float(input("Enter then number you would like to check is odd or even")) except...
# -*- coding: utf-8 -*- """ Created on Mon Feb 13 16:43:18 2017 @author: coskun """ def closest_power(base, num): ''' base: base of the exponential, integer > 1 num: number you want to be closest to, integer > 0 Find the integer exponent such that base**exponent is closest to num. Note that the ba...
class Solution: def minCut(self, s: str) -> int: if not s: return 0 memo = dict() def helper(l,r): if l > r: return 0 minVal = float('inf') for i in range(l,r+1,1): strs = s[l:i+1] if strs == str...
'''https://practice.geeksforgeeks.org/problems/cyclically-rotate-an-array-by-one2614/1 Cyclically rotate an array by one Basic Accuracy: 64.05% Submissions: 66795 Points: 1 Given an array, rotate the array by one position in clock-wise direction. Example 1: Input: N = 5 A[] = {1, 2, 3, 4, 5} Output: 5 1 2 3 4 E...
#!/usr/bin/env python # -*- coding:utf-8 -*- def max_min(v): m_min, m_max = min(v[0], v[-1]), max(v[0], v[-1]) for i in v[1:len(v)-1]: if i<m_min: m_min = i elif i > m_max: m_max = i return m_min, m_max if __name__ == '__main__': m_min, m_max = max_min([9, ...
# -*- coding: utf-8 -*- """ seqansphinx ~~~~~~~~~~~~~ This package is a namespace package that contains all extensions distributed in the ``seqansphinx`` distribution. :copyright: Copyright 2014 by Manuel Holtgrewe :license: MIT, see LICENSE for details. """ __import__('pkg_resources').declar...
print(f'\033[1:33m{"-"*40:^40}\033[m') print(f'\033[1:33m{"CADASTRO DE JOGADOR DE FUTEBOL - v2.0":^40}\033[m') print(f'\033[1:33m{"-"*40:^40}\033[m') player = dict() matches = list() team = list() status = 'o' allMatches = allGoals = 0 while status not in 'nN': player['Nome'] = str(input('Nome do jogador: ')) ...
string = [x for x in input()] string_list_after = [] index = 0 power = 0 for el in range(len(string)): if string[index] == ">": expl = int(string[el + 1]) power += int(expl) string.pop(el+1) string.append('') power -= 1 while power > 0: index = el ...
"""Exceptions for cmd_utils.""" class CommandException(Exception): """ Base Exception for cmd_utils exceptions. Attributes: exc - string message return_code - return code of command """ def __init__(self, exc, return_code=None): Exception.__init__(self) ...
#A more compact version of the algorithm that can be executed parallelly. list1 = [0x58, 0x76, 0x54, 0x3a, 0xbe, 0x58, 0x76, 0x54, 0xbe, 0xcd, 0x45, 0x66, 0x85, 0x65] # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ # Par=4: bulk bulk bulk bulk bulk bulk bulk bulk bu...
#!/usr/bin/env python # coding: utf-8 # In[ ]: # In[4]: def fib(n): a, b = 0,1 while a < n: print(a) a, b = b, a + b # In[8]: def primos(n): numbers = [True, True] + [True] * (n-1) last_prime_number = 2 i = last_prime_number while last_prime_number**2 <= n: ...
""" Number of Provinces There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c. A province is a group of directly or indirectly connected cities and no other citi...
class CliError(RuntimeError): pass
class AjaxableResponseMixin(object): """ Mixin to add AJAX support to a form. Must be used with an object-based FormView (e.g. CreateView) """ def form_invalid(self, form): response = super(AjaxableResponseMixin, self).form_invalid(form) if self.request.is_ajax(): return ...
#!/usr/bin/env python __author__ = "Giuseppe Chiesa" __copyright__ = "Copyright 2017-2021, Giuseppe Chiesa" __credits__ = ["Giuseppe Chiesa"] __license__ = "BSD" __maintainer__ = "Giuseppe Chiesa" __email__ = "mail@giuseppechiesa.it" __status__ = "PerpetualBeta" def write_with_modecheck(file_handler, data): if f...
#!/usr/bin/env python # -*- coding: UTF-8 -*- class BaseEmitter(object): '''Base for emitters of the *data-migrator*. Attributes: manager (BaseManager): reference to the manager that is calling this emitter to export objects from that manager model_class (Model): reference to the ...
""" LeetCode Problem: 833. Find And Replace in String Link: https://leetcode.com/problems/find-and-replace-in-string/ Language: Python Written by: Mostofa Adib Shakib Time complexity: O(n) Space Complexity: O(n) """ class Solution: def findReplaceString(self, S: str, indexes: List[int], sources: List[str], target...
class Stack(object): def __init__(self): self.stack = [] def is_empty(self): return not self.stack def push(self, v): self.stack.append(v) def pop(self): data = self.stack[-1] del self.stack[-1] return data def peek(self): return self.stac...