content
stringlengths
7
1.05M
pallet_color = [ (231, 234, 238), # 010 White (252, 166, 0), # 020Golden yellow (232, 167, 0), # 019 Signal yellow (254, 198, 0), # 021 Yellow (242, 203, 0), # 022 Light yellow (241, 225, 14), # 025 Brimstone yellow (116, 2, 16), # 312 Burgundy (145, 8, 20), # 030 Dark red (1...
# All metrics are treated as gauge as the counter instrument don't provide a set # method and for performance, it's always good to avoid calculation when ever it's possible. # Using the inc() method require the diff to be calculated! metrics = [ ## Custom metrics ("up", "the status of the node (1=running, ...
a = int(input('Digite o primeiro número: ')) b = int(input('Digite o segundo número: ')) c = int(input('Digite o terceiro número: ')) menor = a if b<a and b<c: menor = b if c<a and c<b: menor = c maior = a if b>a and b>c: maior = b if c>a and c>b: maior = c print(f'O maior valor é {maior}.') print(f'O menor valor é...
""" Reference: https://leetcode.com/problems/strange-printer/discuss/106810/Java-O(n3)-DP-Solution-with-Explanation-and-Simple-Optimization """ class Solution: def strangePrinter(self, s: str) -> int: str_size = len(s) if str_size == 0: return 0 # init with the value...
def test_slash_request_forbidden(client): assert client.get("/").status_code == 404 def test_api_root_request_forbidden(client): assert client.get("/api").status_code == 404 assert client.get("/api/").status_code == 404 def test_auth_root_request_forbidden(client): assert client.get("/auth").status_...
def search_staff(): query = """ query ($id: Int, $search: String, $type: MediaType) { Media(search: $search, id: $id, type: $type) { id idMal type title { romaji english } staff { edge...
# 2. Реализовать функцию, принимающую несколько параметров, # описывающих данные пользователя: имя, фамилия, год рождения, город проживания, email, телефон. # Функция должна принимать параметры как именованные аргументы. # Реализовать вывод данных о пользователе одной строкой. def statistic(name, surname, year, count...
a, b, c = map(int, input().split()) if (a == b and a != c) or (a ==c and a != b) or (b == c and b != a): print("Yes") else: print("No")
def count(): fs = [] for i in range(1, 4): def f(): print(i) return i * i fs.append(f) return fs # fs = [function f1, function f2, function f3] f = count() print(f) f1, f2, f3 = count() # 返回的函数引用了变量i,等到3个函数都返回时,i变成了3,再调用f函数结果为9 # 执行f(): i = 3 print(f1, f1(...
#Check for the existence of file no_of_items=0 try: f=open("./TODO (CLI-VER)/todolist.txt") p=0 for i in f.readlines():#Counting the number of items if the file exists already p+=1 no_of_items=p-2 except: f=open("./TODO (CLI-VER)/todolist.txt",'w') f.write("_________TODO LIST__________\...
#exercicío que cria uma espécie de Menu em um restaurante tecnológico lanche = ['Hamburguer R$ 9,50', 'Hot-Dog R$ 7,00', 'Bauru R$ 25,00', 'Pizza R$ 22,00']; bebida = ['Refrigerante R$ 5,00', 'Suco R$ 6,00', 'MilkShake R$ 8,00'] print ("COMITECH\n") for i in lanche: print (i) print ("\n\nBEBITECH\n") for i in bebida...
class Solution: def minFlips(self, target: str) -> int: nflips = 0 for ison in map(lambda x : x == '1', target): if ((not ison) and nflips % 2 == 1) or (ison and nflips % 2 == 0): nflips += 1 return nflips
""" Leetcode #464 """ class Solution: def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool: seen = {} def helper(choices, total): if choices[-1] >= total: return True # check if subproblem is already solved key = tuple(ch...
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: for i in matrix: for j in i: if j==target:return True return False
class FermiDataGetter(object): def __init__(self) -> None: raise NotImplementedError()
# -*- coding: utf-8 -*- ''' >>> from pycm import * >>> import os >>> import json >>> y_actu = [2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2] >>> y_pred = [0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2] >>> cm = ConfusionMatrix(y_actu, y_pred) >>> cm pycm.ConfusionMatrix(classes: [0, 1, 2]) >>> len(cm) 3 >>> print(cm) Predict 0 ...
#encoding:utf-8 subreddit = 'talesfromtechsupport' t_channel = '@r_talesfromtechsupport' def send_post(submission, r2t): return r2t.send_simple(submission)
def factors(n): factorlist=[] for i in range(1,n+1): if n%i==0: factorlist=factorlist+[i] return(factorlist) def isprime(n): return(factors(n)==[1,n]) def sumprimes(l): sum=0 for i in range(0,len(l)): if isprime(l[i]): sum=s...
""" 复习 MVC class XXModel: # 封装数据 def __init__(self,参数1,参数2,参数3): self.数据1 = 参数1 self.数据2 = 参数2 self.数据3 = 参数3 class XXView: def __init__(self): self.controller = XXController() # 界面逻辑:输入...
def for_A(): """We are creating user defined function for alphabetical pattern of capital A with "*" symbol""" row=7 col=5 for i in range(row): for j in range(col): if ((j==0 or j==4)and i>0)or ((i==0 or i==4)and j>0 and j<4): print("*",end=" ") else: ...
# A python method for an optimized Bubble Sort Algorithm def bubble_sort(arr): n = len(arr) # Traverse through all array elements for i in range(n): swapped = False # Last i elements are already in place for j in range(0, n-i-1): # Traverse the array from - to n-i-1 ...
def swap(array,i,j): #this simply swaps the values array[i],array[j]=array[j],array[i] '''HeapifyMax function, our root node is at index i. We will first assume that the value at index 'i' is the largest. Then we will find index of left and right child. Then we will check if left and right child exist or not.Now...
print('Введите меню (через пробелы)') menu = input().split(' ') string = 'test0' for string in menu: if(string[0].isupper() == True): print(string)
# Time: O(n) # Space: O(1) class Solution(object): def maxSumDivThree(self, nums): """ :type nums: List[int] :rtype: int """ dp = [0, 0, 0] for num in nums: for i in [num+x for x in dp]: dp[i%3] = max(dp[i%3], i) return dp[0]
# https://app.codesignal.com/arcade/intro/level-5/g6dc9KJyxmFjB98dL def areEquallyStrong(your_left, your_right, friends_left, friends_right): # Two arms are equally strong if the heaviest weights they each are # able to lift are equal. Two people are equally strong if their # strongest arms are equally stro...
# -*- coding: utf-8 -*- """ Created on Tue Nov 12 10:03:50 2019 @author: Caio """ # Livro Assaf - Mercado Financeiro #Capítulo 7.6.1 - Desmembramento da taxa básica de juros i_pura = float(input('Insira a taxa livre de risco da economia')) i_risco = float(input('Insira a taxa de risco mínimo da economia')) i_real = f...
# Source : https://leetcode.com/problems/4sum/ # Author : YipingPan # Date : 2020-08-16 ##################################################################################################### # # Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums # such that a + b + c ...
dict_rhythms = { "E(2,3)" : "A common Afro-Cuban drum pattern when started on the second onset as in [101]. For example, it is the conga rhythm of the (6/8)-time Swing Tumbao. It is common in Latin American music, as for example in the Cueca, and the coros de clave. It is common in Arabic music, as for example in the...
def fun(a, b): return 1 fun(1, 2)
# Create a program to check if an integer is a perfect square. # 4, 9, 25 any ideas? Use Square Root # input num = int(input('Enter a value: ')) # processing & output if (num ** 0.5) % 1 != 0: print(num, 'is not a perfect square.') else: print(num, 'is a perfect square.')
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # Copyright 2018 The AnPyLar Team. All Rights Reserved. # Use of this source code is governed by an MIT-style license that # can be found in the LICENSE file at http://anpyla...
def Insertion_Sort(lst): l = len(lst) for i in range(1,l): temp = lst[i] j = i-1 while j>=0: if temp[0]<lst[j][0]: lst[j+1] = lst[j] lst[j] = temp j = j-1 return lst lst = [] lst = ['Tininha', 'Dudinha','Carlinhos','Marquinhos','Joaozinho','Bruninha','Fernandinha','Rafinha','Pedrinho','Aninh...
# parsetab.py # This file is automatically generated. Do not edit. _tabversion = '3.2' _lr_method = 'LALR' _lr_signature = 'D\xccZ\x0b=\xf2\xd6\x89\x1e\xeb\xa3n\xa2z\xd6n' _lr_action_items = {'PEEK':([179,250,251,256,296,303,325,346,351,358,361,372,374,375,376,378,381,382,],[244,244,-98,-82,-81,-88,-97,-95,-89,...
def hoopCount(n): if n > 9: return "Great, now move on to tricks" else: return "Keep at it until you get it"
# # PySNMP MIB module Dell-LAN-TRAP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Dell-LAN-TRAP-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:56:05 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
class DummyClass: dummy_var = 'original' def __init__(self, init_param=0): pass def __call__(self, call_param=0): return 'not_mocked_call' def some_method(self): # def some_method(self, some_method_param): return 'not_mocked_some_method' def some_other_method(self, so...
def for_p(): """printing small 'p' using for loop""" for row in range(7): for col in range(4): if col==0 or col==3 and row in(2,3) or row==1 and col in(1,2) or row==4 and col in(1,2): print("*",end=" ") else: print(" ",end=" ") prin...
H, W, A, B = map(int, input().split()) board = [[0] * W for _ in range(H)] for i in range(B): for j in range(A): board[i][j] = 1 for i in range(B, H): for j in range(A, W): board[i][j] = 1 assert all(sum(row) in [A, W-A] for row in board) assert all(sum(board[i][j] for i in range(H)) in [B, H-B...
def genSubsets(L): ''' L: list Returns: all subsets of L ''' # base case if len(L) == 0: return [[]] # recursive block # all the subsets of smaller + all the subsets of smaller combined with extra = all subsets of L extra = L[0:1] smaller = genSubsets(L[1:]) combine ...
class Solution(object): def isUgly(self, num): if not num: return False for factor in (2, 3, 5): while num % factor == 0: num /= factor return num == 1
# Please change this appropriately TRAIN_DATA = "../input/train.csv" TEST_DATA = "../input/test.csv" HTML_DATA = "../input/html_data.csv" CLEAN_TRAIN_DATA = "../input2/train_v2.csv" CLEAN_TEST_DATA = "../input2/test_v2.csv" TRAIN_TEXT_MODEL_PATH = "../input2/train_text_preds.csv" TEST_TEXT_MODEL_PATH = "../input2/tes...
class Solution(object): def kthSmallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ stack = [root] BST_vals = [] while stack: curr = stack.pop() BST_vals.append(curr.val) ...
""" # Definition for a Node. class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random """ class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': oldToCopy = {None: N...
_day_bands = ['n2_lbh' , 'n2_vk' , 'n2_1pg' , 'n2_2pg' , 'n2p_1ng' , 'n2p_mnl' , 'no_bands' ] _night_bands = ['o2_nglow','o2_atm'] _bands = _day_bands + _night_bands _band_cmd = {'n2_lbh':'syn_lbh' , 'n2_vk':'syn_vk' , 'n2_1pg':'sy...
class BaseGordonException(Exception): code = 1 hint = u"Something went't wrong" def get_hint(self): return self.hint.format(*self.args) class ResourceSettingRequiredError(BaseGordonException): code = 2 hint = u"Resource {} requires you to define '{}' in it's settings." class InvalidStr...
print('-=-=- Aluguel de carros -=-=-') dias = int(input('Quantos dias usou o veículo? ')) kms = int(input('Quantos Kms rodou? ')) print(f'O valor a ser pago é de --> R${(60*dias) + (0.15*kms)}')
#!/usr/bin/env python # coding: utf-8 # # Conjuntos # # - Conjuntos são coleções de elementos únicos # - Principais características: # - Os elementos não são armazenados em uma ordem específica # - Conjuntos não contém elementos repetidos # - Conjuntos não suportam indexação como as listas e tuplas # # O que...
# Aaron Donnelly # This program will count the number of re-occurences of the letter 'e' in a txt file selected by the user. f= open(input("Insert a .txt filename "), "r") x= f.read().count('e') print("There are",x, "e's in this text")
# # PySNMP MIB module WWP-COMMUNITY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-COMMUNITY-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:30:41 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
#!/usr/bin/python # -*- coding: utf-8 -*- class ChessPiece(object): """ This is a super class for chess pieces """ def __init__(self, letter, value, x, y): self.letter = letter self.color = self.getColor() self.value = value self.x = x self.y = y def __str__...
""" File: hailstone.py Name: Jade Yeh ----------------------- This program should implement a console program that simulates the execution of the Hailstone sequence, as defined by Douglas Hofstadter. Output format should match what is shown in the sample run in the Assignment 2 Handout. """ # This constant controls wh...
# coding:utf-8 class IAgent(object): ''' 负责调用Model和env,控制训练流程 ''' def save(self): raise NotImplementedError() def load(self): raise NotImplementedError()
#!/usr/bin/env python """ Assignment 2, Exercise 2, INF1340, Fall, 2015. DNA Sequencing This module converts performs substring matching for DNA sequencing """ __author__ = 'Susan Sim' __email__ = "ses@drsusansim.org" __copyright__ = "2015 Susan Sim" __license__ = "MIT License" def find(input_string, substring, s...
# -*- coding: utf-8 -*- def repeat_print(n): ''' 重复打印 str, n 次, str 是匿名参数 :param n: 重复次数 :return: ''' return lambda str: str * n def main(): pow_x_y = lambda x, y: pow(x, y) print("2^3 = ", pow_x_y(2, 3)) repeat_print_2 = repeat_print(2) print(repeat_print_2("hi~ ")) if __...
# -*- coding: utf-8 -*- ''' File name: code\rigid_graphs\sol_434.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #434 :: Rigid graphs # # For more information see: # https://projecteuler.net/problem=434 # Problem Statement ''' Recall th...
class Solution: def XXX(self, nums: List[int]) -> List[List[int]]: return [[n] + sub for i, n in enumerate(nums) for sub in self.XXX(nums[:i] + nums[i+1:])] or [nums]
# A RouteTrie will store our routes and their associated handlers class RouteTrie: def __init__(self): # Initialize the trie with an root node and a handler, this is the root path or home page node self.root = RouteTrieNode() def insert(self, path): paths = split_path(path) # Si...
# -*- coding: utf-8 -*- #--------------------------CLASSE GRAFO-------------------------- class Grafo: """ Classe destinada para armazenar lista de adjacencia de representação do grafo """ def __init__(self, vertices=0, arestas=0): """ Construtor de Lista. Inicializa uma list...
''' Created on Nov 6, 2013 @author: agreen This module is used by the cubing_tests module as a data store. ''' enabled = True class DAR: xfibre_pos = False yfibre_pos = False
class Field(object): def __init__(self, name=None, default=None, data_type=None): self.name = name self.default = default self.required = self.default is None self.type = data_type def build(self): result = {key: value for key, value in self.__dict__.items() if value is...
COLORS = dict([ ('CLEANUP', '\033[94m'), ('CREATE', '\033[92m'), ('INSTALL', '\033[92m'), ('SKIP', '\033[93m'), ('FAIL', '\033[31m'), ('DEFAULT', '\033[39m'), ('UNDEFINED', '\033[37m'), ('STATUS', '\033[36m') ]) def typed_message(message, message_type=None): color = COLORS.setdefaul...
# # MIT License # # Copyright (c) 2018-2020 Franck Nijhof # Copyright (c) 2020 Andrey "Limych" Khrolenok # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including witho...
# Принимает параметр U, например, [1,2,3,4,5,6,7,8,9,10,11] # Принимает параметр A, например, [1,3,4,7] # Возвращает сгенерированную маску A: [1,0,1,1,0,0,1,0,0,0,0] def generateMask(U, A): maskA = [] for i in range(len(U)): maskA.append(0) for i in range(len(U)): for j in range(len(A)): ...
class Solution: def reverse(self, x: int) -> int: rev = 0 y = abs(x) while y: rev = rev*10 + y % 10 y //= 10 sign = -1 if x < 0 else 1 if(rev > 0x7fffffff): return 0 return sign * rev
greater = 0 less = 0 for c in range (1,6): weight = float (input (f'Insert the weight of {c} º person ')) if c == 1: greater = weight less = weight else: if weight > greater: greater = weight if weight < less: less = weight print (f'The biggest...
# {} d = dict() # {'a': 1, 'test': 'Monday', 'abc': 3} d1 = dict(a=1, test='Monday', abc=3) print(d) print(d1) # {'one': 1, 'two': 2, 'three': 3} 可迭代对象方式来构造字典 d3 = dict([('one', 1), ('two', 2), ('three', 3)]) print(d3) # {'one': 1, 'two': 2, 'three': 3, 4: 4} 映射函数方式来构造字典 d4 = dict(zip(['one', 'two', 'thr...
"""Unit tests configuration.""" pytest_plugins = [ "tests.fixtures.aws", "tests.fixtures.click" ]
# device present global variables DS3231_Present = False BMP280_Present = False AM2315_Present = False ADS1015_Present = False ADS1115_Present = False
__title__ = 'xmind2testcase2021' __description__ = 'xmind2testcase2021基于Python实现,提供了一个高效测试用例设计的解决方案!' __keywords__ = 'xmind2testcase2021, testcase, test, testing, xmind, 思维导图, XMind思维导图', __url__ = 'https://pypi.org/project/xmind2testcase2021/1.0.3/' __author__ = 'Devin' __author_email__ = 'lovpuss@163.com' __version__...
ObjectId = int class Object: def __init__(self, id_): self.id: ObjectId = id_ self.count = 1 self.neighbors = {self} @property def neighbor_count(self): return sum([neighbor.count for neighbor in self.neighbors]) def __repr__(self): return f'{self.id}_'
# Linear search algorithm # @ra1ski def linear_search(item, _list): index = None for idx, val in enumerate(_list): if val == item: index = idx break return index if __name__ == '__main__': _list = ['chrome', 'firefox', 'opera', 'ie', 'netscape'] item = input('Ty...
# -*- coding: utf-8 -*- """ Created on Tue Dec 24 16:33:43 2019 @author: Steve Bremer """ STATE = 0 HISTORY = 1 SCORE = 2 class ConvolutionalCode(): def __init__(self, gen_poly): if len(gen_poly) > 0: poly_len = len(gen_poly[0]) else: # Raise an error? poly_len...
city = input("Enter the name of the city: ") sales = float(input("Enter the percentage of sales: ")) commission = 0 if 0 <= sales <= 500: if city == "Sofia": commission = 0.05 elif city == "Varna": commission == 0.045 elif city == "Plovdiv": commission == 0.055 elif 500 < sales <= 1...
def get_dotted_mask_split(ip_address_mask_cidr): p = int(ip_address_mask_cidr) ip_address_mask_dotted_split = [] for i in range(4): if p >= 0: if p - 8 >= 0: ip_address_mask_dotted_split.append('255') p -= 8 else: b...
#!/usr/bin/python class Node: def __init__(self, value): self.left = None self.right = None self.value = value class Tree: def __init__(self): self.root = None @property def root_node(self): return self.root def add(self, value): if self.root is ...
#Conor O'Riordan # Write a program that asks the user to input any positive integer and outputs the successive values of the following calculation. # At each step calculate the next value by taking the current value and # if it is even, divide it by two, but if it is odd, multiply it by three and add one. # Have the pr...
IMPORTED_METERINGPOINT_DATA = """ { "result": [ { "meteringPointId": "571313180400240049", "typeOfMP": "E18", "accessFrom": "02/05/2016 00:00:00", "accessTo": "04/23/2023 00:00:00", "streetCode": "6595", "streetName": "Lærkevej", ...
#!/usr/bin/python3 # https://practice.geeksforgeeks.org/problems/odd-even-level-difference/1 def getLevelDiff(root): h = {0: 0, 1: 0} level = 0 populateDiff(root, level, h) return h[0]-h[1] def populateDiff(root, level, h): if root == None: return l = level%2 h[l] += root....
def BenchmarkNan(df): """Replace NaN by Benchmark.""" # Compute the inverse of the distance distance_inv_df = (1. / df.filter(regex='^distance*', axis=1)).values # Extract the value at the nearest station values_df = df.filter(regex='value_*', axis=1) # Compute the benchmark numer_df = (d...
# # PySNMP MIB module Vsm-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Vsm-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:35:46 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)...
# -*- coding: utf-8 -*- """ Created on Sat Sep 8 15:20:24 2018 @author: Charles Yang """
class Conta: def __init__(self, numero, titular, saldo, limite): self._numero = numero self._titular = titular self._saldo = saldo self._limite = limite def deposita(self, valor): self._saldo += valor if valor <= 0: return 'Não foi possí...
""" A module with with two list functions. These functions have been fully implemented. Author: Walker M. White Date: April 15, 2019 """ def sum(lst): """ Returns: the sum of all elements in the list Example: sum([1,2,3]) returns 6 sum([5]) returns 5 Parameter lst: the list to sum ...
def camelcase(sentence): """ Convert sentence to camelCase, for example, "Display all books" is converted to "displayAllBooks" """ title_case = sentence.title() # Uppercase first letter of each word upper_camel_cased = title_case.replace(' ', '') # remove spaces # Lowercase first letter, join with rest of...
'''1. Write a Python program to compute the greatest common divisor (GCD) of two positive integers.''' def lcm(x, y): if x > y: z = x else: z = y while(True): if((z % x == 0) and (z % y == 0)): lcm = z break z += 1 return lcm print(lcm(4, 6)) pr...
for t in range(int(input())): n = int(input()) L = list(map(int,input().split())) L.sort() d = dict() for i in L: d[i] = 1 cnt = 0 for i in range(n): for j in range(i+1,n): try: if d[L[i] - (L[j]-L[i])] == 1: cnt+=1 ...
''' Remove Smallest ''' t = int(input()) for ll in range(t): n = int(input()) integers = set(map(int, input().split(' '))) integers = list(integers) integers.sort() for i in range(1,len(integers)): if abs(integers[i]-integers[i-1]) > 1: print('NO') break else: ...
{ "targets": [ { "target_name": "test_constructor", "sources": [ "test_constructor.c" ] }, { "target_name": "test_constructor_name", "sources": [ "test_constructor_name.c" ] } ] }
""" True and True -> True otro caso -> False Con or minimo un True da true Negacion not(True) -> False not (False) -> True 1. Not 2. And 3. Or ...
#__________________ Script Python - versão 3.8 _____________________# # Autor |> Abraão A.da Silva # Data |> 05 de Março de 2021 # Paradigma |> Procedural # Objetivo |> Calculando média #___________________________________________________________________# def recebendo_numeros(arm): "A função colherá as notas...
class Logger: def __init__(self, filepath): self.filepath = filepath def write(self, msg): with open(self.filepath, "a") as logfile: logfile.write("{}\n".format(msg))
''' contains functions that convenient math stuff, usually involving operations that are not defined in normal mathematics but could be useful @author: Klint ''' # matrix stuff, collapse matrix in interesting ways def collapse_matrix_cols(matrix: [list])-> list: '''flatten a matrix by m by n into a array of size...
def write (name, stream): stream.write("#include <unico.h>\n") stream.write("#include <stddef.h>\n") stream.write("extern int %s (size_t, size_t, unicos*);\n" % name)
#! /usr/bin/env python3 # coding: utf-8 # Thanks to imbadatreading, should have through about LCM def add_step_size(buses): buses_with_step = list() for num in range(len(buses)): if buses[num] != 'x': buses_with_step.append((int(buses[num]), num)) return buses_with_step def find_aweso...
#!/usr/bin/env python3 f = open("input.txt", "r").read().splitlines() REGISTERS_MAP = {"w": 0, "x": 1, "y": 2, "z": 3} def checker(number): num_str = str(number) if "0" in num_str: return False if len(num_str) != 14: return False # Registers are in form [w,x,y,z] counter = 0 ...
# Crie um programa onde o usuário possa digitar cinco valores numéricos e cadastre-os em uma lista, já na posição correta de inserção (sem usar o sort()). No final, mostre a lista ordenada na tela. numeros = [] for x in range(0,5): valor = int(input('Digite valor: ')) # verifica se a lista esta vazia ou se o v...
"""This module loads the monkeypatch from gevent and applies it. Nothing fancy, but it's useful and more readable to put this in a separate module and give and explicit name to it. """ # Re-add sslwrap to Python 2.7.9 # import socket # __getaddrinfo = socket.getaddrinfo # # # kudos to http://stackoverflow.com/a/1...
# bunch of color constants class Color: WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) BLUE = (0, 128, 255) GREEN = (0, 153, 0) YELLOW = (255, 255, 0) BROWN = (204, 102, 0) PINK = (255, 102, 178) PURPLE = (153, 51, 255) GREY = (128, 128, 128) colors = { ...
VERSION = "0.2" if __name__ == '__main__': print(VERSION)
class NumMatrix: def __init__(self, matrix: List[List[int]]): if not matrix: return self.presum = [[0] * (1 + len(matrix[0])) for _ in range(1 + len(matrix))] for i in range(len(matrix)): for j in range(len(matrix[0])): self.presum[i + 1][j + 1] =...