content
stringlengths
7
1.05M
# Data processing with open('input') as f: in_data = [line.rstrip() for line in f] for i in range(25, len(in_data)): pre_i = in_data[i-25:i] summed_pair_found = False for a in pre_i: for b in pre_i: if a != b: if int(a)+int(b) == int(in_data[i]): ...
#! python3 pessoas = [ {'nome': 'Pedro', 'idade': 11}, {'nome': 'Mariana', 'idade': 18}, {'nome': 'Arthur', 'idade': 26}, {'nome': 'Rebeca', 'idade': 6}, {'nome': 'Tiago', 'idade': 19}, {'nome': 'Gabriela', 'idade': 17}, ] menores = filter(lambda p: p['idade'] < 18, pessoas) print(list(menores...
#!/usr/bin/python3 # python实现集合 # Date: 2020-07-13 class Set: """列表实现集合""" def __init__(self): self.items = [] def add(self, item): if item not in self.items: self.items.append(item) def clear(self): self.items = [] def discard(self, item): if item in ...
class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ if x < 0: return -1 elif x == 0: return 0 start, end = 1, x while start + 1 < end: mid = start + (end - start) / 2 if mid**2 ...
line = input() a, b = line.split() a = int(a) b = int(b) print(a + b)
def load(opt, splits): """ Load the TUF train dataset :return: """ return {"train": [], "val": []}
class Solution: def strStr(self, haystack: str, needle: str) -> int: """ Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. >>> Solution().strStr("asdf", "") 0 >>> Solution().strStr("h...
class ContentTypeSerializer(object): """ A ContentTypeSerializer handles the conversion from a python data structure to a bytes object representing the content in a particular content type. """ def content_type(self): """ return back what a list of content types this ser...
employees_happiness = [int(happiness) for happiness in input().split()] factor = int(input()) factored_employees_happiness = list(map(lambda h: h * factor, employees_happiness)) find_average_happiness = sum(factored_employees_happiness) / len(factored_employees_happiness) happy_employees = [e for e in factored_employe...
db_config = { 'user': 'user', 'password': 'password', 'host': 'host.com', 'port': 12345, 'database': 'db-name', "autocommit": True }
class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ ''' T: O(m * n) S: (m + n) ''' nrow = len(matrix) ncol = len(matrix[0]) rows, cols = set(), s...
# encoding: utf-8 """ @version: v1.0 @author: Richard @license: Apache Licence @contact: billions.richard@qq.com @site: @software: PyCharm @time: 2019/9/8 9:37 """ def get_remove_len(node_pth: list) -> int: reversed_pth = list(reversed(node_pth)) pth_len = 0 lst_node = reversed_pth[0] for ...
VALUE_TYPES = { 'short', 'int', 'long', 'uchar', 'ushort', 'uint', 'ulong', 'bool', 'float', 'double', 'size_t', 'uint8', 'int8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64', } VALA_TYPES = VALUE_TYPES | { 'char', 'string', 'void*', 'void**', 'time_t', } VALA_ALIASES = { 'unsigne...
num = float(input("Enter a Number: ")) if num > 0: print("This is a Positive Number") elif num == 0: print("Zero") else: print("This is a Negative Number")
""" borg.algorithms =============== This package is intended for hash and checksum functions. """
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @AUTHOR:Joselyn Zhao @CONTACT:zhaojing17@foxmail.com @HOME_PAGE:joselynzhao.top @SOFTWERE:PyCharm @FILE:20060402.py @TIME:2020/6/4 21:17 @DES:7. 整数反转 ''' '''简单粗暴的错误方法''' # def reverse(self, x: int) -> int: # n = x # listn = [] # while (n != 0): # k = n ...
""" Working with Binary Search Trees (BSTs). The height of a binary search tree is the number of edges between the tree's root and its furthest leaf. You are given a pointer, root, pointing to the root of a binary search tree. Complete the getHeight function provided in your editor so that it returns the height of...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. class ContentType: O365_CONNECTOR_CARD = "application/vnd.microsoft.teams.card.o365connector" FILE_CONSENT_CARD = "application/vnd.microsoft.teams.card.file.consent" FILE_DOWNLOAD_INFO = "application/vnd.microsof...
class Log: lines = [] def __init__(self): self.lines = [] def add(self, line): self.lines.append(line) def flush(self): for line in self.lines: print(line) self.lines = [] battle_log = Log() general_log = Log()
num1 = 111 num2 = 222 num3 = 333333 num3 = 333 num4 = 4444
"""This module contains a collection of functions related to flood data. """ #ml2015 def stations_level_over_threshold(stations,tol): """For Task 2B - returns a list of tuples The tuples contain a station and then a relative water level the relative water level must be greater than tol returned list s...
class MaterialPropertyMap: def __init__(self): self._lowCutoffs = [] self._highCutoffs = [] self._properties = [] def error_check(self, cutoff, conductivity): if not isinstance(cutoff, tuple) or len(cutoff) != 2: raise Exception("Cutoff has to be a tuple(int,int) spe...
class EncodingApiCommunicator(object): def __init__(self, inner): self.inner = inner def call(self, path, command, arguments=None, queries=None, additional_queries=()): path = path.encode() command = command.encode() arguments = self.transform_dictionary(argum...
class Person: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name self.age = 0 def full_name(self): return self.first_name + " " + self.last_name def record_info(self): return self.last_name + ", " + self.first_name perso...
class Node: def __init__(self, data) -> None: self.data = data self.nextNode = None class LinkedList: def __init__(self): self.head = None self.numOfNodes = 0 def insert_new(self, data): self.numOfNodes += 1 new_node = Node(data) if not self.head: ...
adventures = [ {"id": 1, "name": "Test Location"}, {"id": 12, "name": "The Sewer"}, {"id": 15, "name": "The Spooky Forest"}, {"id": 16, "name": "The Haiku Dungeon"}, {"id": 17, "name": "The Hidden Temple"}, {"id": 18, "name": "Degrassi Knoll"}, {"id": 19, "name": "The Limerick Dungeon"}, ...
font = { ' ' : [ ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ], '!' : [ ' ', ' ', ' OO ', ' 88 ', ' || ', ' || ', " `' ", ' ,, ', ' db ', ' ', ' ', ], '"' : [ ' ', ' gp gp ', ' \\/ \\/ ', " `' `' ", ' ', ' ', ' ', ' ', ' ...
class Solution: def amendSentence(self, s): # code here ans = "" string = "" for i in range(len(s)): if 97 <= ord(s[i]) <= 122: string += s[i] else: if string: ans += string ans += "...
# Copyright (c) 2021 Qualcomm Technologies, Inc. # All Rights Reserved. def _tb_advance_global_step(module): if hasattr(module, 'global_step'): module.global_step += 1 return module def _tb_advance_token_counters(module, tensor, verbose=False): token_count = getattr(module, 'tb_token_count', Non...
def getMapCommon(): common = """SYMBOLSET "./etc/symbols.sym" FONTSET "./etc/fonts/fonts.list" IMAGETYPE "png" """ return common def getPng(): output = """OUTPUTFORMAT NAME "png" DRIVER "AGG/PNG" MIMETYPE "image/png" IMAGEMODE RGB EXTE...
nome = str(input('Qual é o seu nome? ')).strip() print('''O seu nome apenas em letras garrafais (porém amigáveis) é {} Já em letras minusculas {}. Seu nome possuí {} letras. Seu primeiro nome tem {} '''.format(nome.upper(), nome.lower(), len(nome) - nome.count(' '), nome.find(' '))) #separa = nome.split() #print('Seu ...
# -*- coding: utf-8 -*- """SDP Tango Master Release info.""" __subsystem__ = 'TangoControl' __service_name__ = 'SDPMaster' __version_info__ = (0, 1, 0) __version__ = '.'.join(map(str, __version_info__)) __service_id__ = ':'.join(map(str, (__subsystem__, __service_name__, ...
# -*- coding: utf-8 -*- """ Created on Fri Sep 10 15:18:19 2021 @author: qizhe """ class Solution: def climbStairs(self, n: int) -> int: if n <= 1: return n pre = 1 cur = 2 for _ in range(2,n): cur, pre = cur + pre, cur return cur if __name__ == '...
class ExpressionReader: priorityComparision = ['='] andOrComparision = ['OR'] operations = [] operations.extend(priorityComparision) operations.extend(andOrComparision) def read(expression): lst = ExpressionReader.__split(expression) #lst = ExpressionReader.__parsePriorityExpre...
'''A large FizzBuzz as an output using small FizzBuzz numbers.(FizzBuzz=FizBuz for better alignment and make sure your output terminal covers the entire length of the screen to avoid automatic newlines)''' # Author: @AmanMatrix def iCheck(i): if i%15==0: i='FizBuz' elif i%3==0: i='Fizz' eli...
i = 1.0 print(i) print("Hello world!") print(type(i)) a = "Hello" print(type(a)) # print(a+i) <-Error! a += "world!" print(a) print("this is string: {}, {}".format(3, "ala bala")) print("pi = %f" % 3.14)
MACHINE_A = 'MachineA' MACHINE_B = 'MachineB' INIT = 'Init' E_STOP = 'stop' E_INCREASE = 'increase' E_DECREASE = 'decrease'
lista = str(input('Digite uma frase com parenteses: ')) pilha = [] for simbolo in lista: if simbolo == '(': pilha.append('(') elif lista == ')': if len(pilha) > 0: pilha.pop() else: pilha.append(')') break if len(pilha) == 0: print('Sua expressão ...
#============================================================================= ## Automatic Repository Version Generation Utility ## Author: Zhenyu Wu ## Revision 1: Apr 28. 2016 - Initial Implementation #============================================================================= __all__ = [ 'VersionLint' ]
print('='*10,'LOJA ART','='*10) compras = float(input('Preço das compras: R$')) print('''FORMAS DE PAGAMENTO [ 1 ] À vista dinheiro/cheque: [ 2 ] À vista cartão: [ 3 ] 2X no cartão: [ 4 ] 3X no cartão ou mais:''') opção = int(input('Qual a opção?')) if opção == 1: desconto = compras-(compras*10/100) p...
def fun(f): #string # Some functions need zero or more # arguements then we have to use # *args & **kwargs def wrapper(*args, **kwargs): print("Start") #print(string) # to return the values that are passed values = f(*args, **kwargs) print("End") return va...
symbols = [ 'TSLA', 'GOOG', 'FB', 'NFLX', 'PFE', 'KO', 'AAPL', 'MSFT', 'DIS', 'UBER', 'AMZN', 'TWTR', 'SBUX', 'F', 'XOM', 'GFINBURO.MX', 'BIMBOA.MX', 'GFNORTEO.MX', 'TLEVISACPO.MX', 'AZTECACPO.MX', 'ALSEA.MX', 'ORBIA.MX', 'POSA...
# ADD BINARY LEETCODE SOLUTION: # creating a class. class Solution(object): # creating a function to solve the problem. def addBinary(self, a, b): # using the 'bin' function to convert each integer into its binary format. sum = bin(int(a, 2) + int(b, 2)) # returning the va...
mywords = ['Krishna', 'Rameshwar Dass', 'Usha', 'Ramesh'] for w in mywords: print(w, end='') #Krishna Rameshwar Dass Usha Ramesh
C = set( """ I [и] a aли a҃ i iли ̕И ͑И ι ιли І Ї А Дa Да И ЛІ Ли Лі Неже Ни Ниже Но Нъ Ні Ніже Таже Ти а а. а͑ али ами ато а҅ а҆ д дa да же и и͑ и͑ли и͑лі и͗ иж иже ии ил илi или илї ино и҃ и҅ и҅ ли и҅ли и҆ и҆ли й ли либо любо лі лї н на не не бо нъ неже ни ни же ниa ниж ниже но нъ нъ҅ нъ҆ нь нь͗ нь҆ ні нї нѫ ...
#!/usr/bin/env python3 SQL92_reserved = [ "ABSOLUTE", "ACTION", "ADD", "ALL", "ALLOCATE", "ALTER", "AND", "ANY", "ARE", "AS", "ASC", "ASSERTION", "AT", "AUTHORIZATION", "AVG", "BEGIN", "BETWEEN", "BIT", "BIT_LENGTH", "BOTH", "BY", "CASCADE", "CASCADED", "CASE", "CAST", "CATALOG", "CHAR", "CHARACTER", "CHAR...
def can_build(env, platform): return True def configure(env): pass def is_enabled(): # Disabled by default being experimental at the moment. # Enable manually with `module_gdscript_transpiler_enabled=yes` option. return False
# @Title: 递增的三元子序列 (Increasing Triplet Subsequence) # @Author: KivenC # @Date: 2019-03-15 16:56:39 # @Runtime: 84 ms # @Memory: 13.5 MB class Solution: def increasingTriplet(self, nums: List[int]) -> bool: if len(nums) < 3: return False i, j = float('inf'), float('inf') for num...
class PERIOD: DAILY = "daily" WEEKLY = "weekly" MONTHLY = "monthly" # Converting BYTES to KB, MB, GB BYTES_TO_KBYTES = 1024 BYTES_TO_MBYTES = 1048576 BYTES_TO_GBYTES = 1073741824
""" Job initialization. """ class Job(): """ Performs general statistics over the crowdsourcing jobs. """ @staticmethod def aggregate(units, judgments, config): """ Aggregates information about the total number of units, total number of judgments, total number of workers th...
class MyClass: '''This is the docstring for this class''' def __init__(self): # setup per-instance variables self.x = 1 self.y = 2 self.z = 3 class MySecondClass: '''This is the docstring for this second class''' def __init__(self): # setup per-instance varia...
# coding: utf8 class InvalidUnitToDXAException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class Unit(object): @classmethod def to_dxa(cls, val): if len(val) < 2: return 0 else: unit = ...
input = """ c num blocks = 1 c num vars = 150 c minblockids[0] = 1 c maxblockids[0] = 150 p cnf 150 617 90 -20 8 0 -111 -68 -13 0 8 -150 -9 0 -66 63 -93 0 -135 40 81 0 106 -127 134 0 -54 123 45 0 24 -77 59 0 -82 48 71 0 12 75 87 0 127 -29 88 0 -120 -33 60 0 -126 -102 31 0 134 9 -150 0 62 -56 -83 0 92 27 75 0 -133 -52 5...
def count(word, letter): count = 0 for i in word: if i == letter: count = count + 1 return count word = input('Enter a word:') letter = input('Enter a letter to count in word:') print("There are {} {}'s in your word".format(count(word,letter), letter))
class Square: def __init__(self, side): self.side = side def perimeter(self): return self.side * 4 def area(self): return self.side ** 2 pass class Rectangle: def __init__(self, width, height): self.width, self.height = width, height def perimeter(self): ...
def first_function(values): ''' (list of int) -> NoneType ''' for i in range(len(values)): if values[i] % 2 == 1: values[i] += 1 def second_function(value): ''' (int) -> int ''' if value % 2 == 1: value += 1 return value def snippet_1(): a = [1, 2,...
# -*- coding: utf-8 -*- vagrant = 'vagrant' def up(): return '{} up'.format(vagrant) def ssh(): return '{} ssh'.format(vagrant) def suspend(): return '{} suspend'.format(vagrant) def status(): return '{} status'.format(vagrant) def halt(): return '{} halt'.format(vagrant) def destroy(fo...
def split_block (string:str, seps:(str, str)) -> str: _, content = string.split (seps[0]) block, _ = content.split (seps[1]) return block def is_not_empty (value): return value != '' def contens_colons (value:str) -> bool: return value.count(":") == 0 content = "" with open ("examples/add.asm") ...
class Solution: def sumOfDistancesInTree(self, N, edges): """ :type N: int :type edges: List[List[int]] :rtype: List[int] """ graph = collections.defaultdict(list) for u, v in edges: graph[u].append(v) graph[v].append(u) sums = ...
class Solution: # @return an integer def threeSumClosest(self, num, target): num.sort() res = sum(num[:3]) if res > target: diff = res-target elif res < target: diff = target-res else: return res n = len(num) for i in x...
# -*- encoding:utf-8 -*- """Autogenerated file, do not edit. Submit translations on Transifex.""" MESSAGES = { "%d min remaining to read": "%dminutas de lectura remanente", "(active)": "(active)", "Also available in:": "Anque disponibile in:", "Archive": "Archivo", "Atom feed": "Fluxo Atom", "A...
''' Prompt: Given two strings, s1 and s2, write code to check if s2 is a rotation of s1. (e.g., "waterbottle" is a rotation of "erbottlewat"). Follow up: What if you could use one call of a helper method isSubstring? ''' # Time: O(n), Space: O(n) def isStringRotation(s1, s2): if len(s1) != len(s2): return False...
# Instantiate Cache information n = 10 cache = [None] * (n + 1) def fib_dyn(n): # Base Case if n == 0 or n == 1: return n # Check cache if cache[n] != None: return cache[n] # Keep setting cache cache[n] = fib_dyn(n-1) + fib_dyn(n-2) ret...
pessoa = {} pessoas = [] soma = cont = 0 mulher = [] maior = [] while True: pessoa['nome'] = str(input('Nome: ')) pessoa['sexo'] = str(input('Sexo: [M/F] '))[0].upper().strip() if pessoa['sexo'] in 'F': mulher.append(pessoa['nome']) pessoa['idade'] = int(input('Idade: ')) soma += pes...
""" The ``refstate`` module ========================= Provides integral models for boundary layer computations Available functions ------------------- """ class refstate: def __init__(self, **kwargs): self._dict = kwargs #def Reynolds(self):
# -*- coding: utf-8 -*- # TODO: datetime support ### ### DO NOT CHANGE THIS FILE ### ### The code is auto generated, your change will be overwritten by ### code generating. ### DefinitionsNewrun = {'required': ['name'], 'type': 'object', 'properties': {'count': {'type': 'boolean'}, 'prePro': {'type': 'boolean'}, ...
class Callback(object): def __init__(self, fire_rate=1.0, fire_interval=None): self.FireRate = fire_rate self.NextFire = self.FireInterval = fire_interval self.FireLevel = 0.0 self.FireCount = 0 def __call__(self, event, *params, **args): self.FireCount += 1...
class A(Exception): def __init__(s, err, *args): s.err = err s.d = 2323 @property def message(s): return 'kawabunga' def __str__(s): return s.message class B(A): pass try: raise A('hh', 89) except B as e: print(1)
"""Classifier calibration techniques. https://arxiv.org/pdf/1902.06977.pdf https://arxiv.org/abs/1706.04599 """
string = input() for i in range(len(string)): emoticon = '' if string[i] == ':': emoticon += string[i] + string[i + 1] print(emoticon)
# -*- encoding: utf-8 -*- ####################################################################################################################### # DESCRIPTION: ####################################################################################################################### # TODO #############################...
"""7. Reverse Integer https://leetcode.com/problems/reverse-integer/ Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (s...
""" Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could ...
''' For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0. ...
altPulo, qntdCano = map(int, input().split()) canos = list(map(int, input().split())) atual = canos.pop(0) for cano in canos: if max([cano, atual]) - min([cano, atual]) > altPulo: print('GAME OVER') quit() atual = cano print('YOU WIN')
# this graph to check the algorithm graph={ 'S':['B','D','A'], 'A':['C'], 'B':['D'], 'C':['G','D'], 'S':['G'], } #function of BFS def BFS(graph,start,goal): Visited=[] queue=[[start]] while queue: path=queue.pop(0) node=path[-1] if node in Visited: ...
# -*- coding: utf-8 -*- """ cvtToC2Dict.py ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Convert ToC (Table of Content from Word document) text to List of Dict in Python Sample of Source file: 1 宏观经济学 1 1.1 商业银行理论 1 1.1.1 银行存款准备金率的概念 1 1.1.2 存款准备金率变动对商业银行的影响 1 :copyright: (c) 2020/11/06 by wanglei. :license: MI...
print('Vamos analisar.') a = input('Escreva uma palavra: ') print(f'O tipo primitivo é {type(a)}') print(f'Tem espaço: {a.isspace()}') print(f'É um número: {a.isnumeric()}') print(f'É alphabetico: {a.isalpha()}') print(f'É alphanumérico: {a.isalnum()}') print(f'É maiuscula: {a.isupper()}') print(f'É minuscula: {a.islow...
""" 1184. Distance Between Bus Stops Easy A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n. The bus goes along both directions i.e. clockwise and counterclockwise. Re...
class Solution: def solve(self, nums): sameIndexAfterSortingCount = 0 sortedNums = sorted(nums) for i in range(len(nums)): if sortedNums[i] == nums[i]: sameIndexAfterSortingCount += 1 return sameIndexAfterSortingCount
S = 'shrubbery' L = list(S) print('L', L)
coffee =10 while True: money = int(input("돈을 넣어 주세요: ")) payback = money-300 more_money = 300-money if money == 300: print("결재 완료. 커피를 줍니다.") coffee -= 1 elif money >300: print(f'거스름돈 {payback}를 주고 커피를 줍니다.') coffee -= 1 elif (1< money <300 ): print(f'커피는`...
def get_binary_nmubmer(decimal_number): assert isinstance(decimal_number, int) return bin(decimal_number) print(get_binary_nmubmer(10.5))
def is_kadomatsu(a): if a[0] == a[1] or a[1] == a[2] or a[0] == a[2]: return False return min(a) == a[1] or max(a) == a[1] a = list(map(int, input().split())) b = list(map(int, input().split())) for i in range(3): for j in range(3): a[i], b[j] = b[j], a[i] if is_kadomatsu(a) and i...
# In Part B, you had a chance to explore how both the percentage of your salary that you save each month # and your annual raise affect how long it takes you to save for a down payment. This is nice, but # suppose you want to set a particular goal, e.g. to be able to afford the down payment in three years. # How much...
class Tesla: # WRITE YOUR CODE HERE def __init__(self, model: str, color: str, autopilot: bool = False, seats_count: int = 5, is_locked: bool = True, battery_charge: float = 99.9, efficiency: float = 0.3): self.__model = model self.__color = color self.__autopilot = autopilot sel...
def sum(*args): total_sum = 0 for number in args: total_sum += number return total_sum result = sum(1, 3, 4, 5, 8, 9, 16) print({ 'result': result })
class VangError(Exception): def __init__(self, msg=None, key=None): self.msg = msg or {} self.key = key class InitError(Exception): pass
BOS_TOKEN = '[unused98]' EOS_TOKEN = '[unused99]' CLS_TOKEN = '[CLS]' SPACE_TOKEN = '[unused1]' UNK_TOKEN = '[UNK]' SPECIAL_TOKENS = [BOS_TOKEN, EOS_TOKEN, CLS_TOKEN, SPACE_TOKEN, UNK_TOKEN] TRAIN = 'train' EVAL = 'eval' PREDICT = 'infer' MODAL_LIST = ['image', 'others']
class Solution: def reverseStr(self, s, k): """ :type s: str :type k: int :rtype: str """ ans = [] i = 0 while i < len(s): di = min(len(s) - i, k) ans.append(s[i:i + di][::-1]) i += di di = min(len(s) - i...
def saveHigh(whatyouwant): file = open('HighPriorityIssues.txt', 'a') file.write(formatError(whatyouwant)) file.close() def saveMedium(whatyouwant): file = open('MediumPriorityIssues.txt', 'a') file.write(formatError(whatyouwant)) file.close() def saveLow(whatyouwant): file = open('LowPriorityIssues.txt', 'a...
#!/usr/bin/python3 def add(*matrices): def check(data): if data == 1: return True else: raise ValueError return [[sum(slice) for slice in zip(*row) if check(len(set(map(len, row))))] for row in zip(*matrices) if check(len(set(map(len, matrices))))]
""" :py:mod:`pypara` is a Python library for - encoding currencies and monetary value objects, - performing monetary arithmetic and conversions, and - running rudimentary accounting operations. Furthermore, there are some type convenience for general use. The source code is organised in sub-packages and sub-modules....
# By Websten from forums # # Given your birthday and the current date, calculate your age in days. # Account for leap days. # # Assume that the birthday and current date are correct dates (and no # time travel). # def daysBetweenDates(year1, month1, day1, year2, month2, day2): daysOfMonths = [ 31, ...
class HWriter(object): def __init__(self): self.__bIsNewLine = True # are we at a new line position? self.__bHasContent = False # do we already have content in this line? self.__allParts = [] self.__prefix = "" self.__nIndent = 0 # def incrementIndent(self): self.__nIndent += 1 if self.__nInde...
class Symbol: def __init__(self, name): self.name = name def __hash__(self): return hash(self.name) def __eq__(self, other): return self.name == other.name class SymbolTable: def __init__(self): self._symbol_table = dict() def put_symbol(self, symbol): se...
#Faça um programa que leia 2 notas de um aluno, verifique #se as notas são válidas e exiba na tela a média destas #notas. Uma nota válida deve ser, obrigatoriamente, um #valor entre 0.0 e 10.0, onde caso a nota não possua #um valor válido, este fato deve ser informado ao #usuário e o programa termina. notas=[] i=0 f...
""" Chovin Carlson - House by the Waves: https://www.youtube.com/watch?v=nkU8r5QKN3Y How to: - Run the statements line by line (alt+enter), go to the next one whenever you feel like - The "#### > run block <" blocks should be executed together (ctrl+enter) - If you want to fast-forward through the ...
#Max retorna o maior numero de um iteravel ou o maior de 2 ou mais elementos #Min retorna o menor numero de um iteravel ou o menor de 2 ou mais elementos lista=[9,5,2,1,4,5,3,6,21,5,4,55,0] print(max(lista)) print(max(8,9,5,7,4,5,6)) dicionario={'a':0,'b':1,'f':51,'g':12,'q':5,'u':3,'d':2} print(max(dicionario)) prin...
# Input your Wi-Fi credentials here, if applicable, and rename to "secrets.py" ssid = '' wpa = ''