content
stringlengths
7
1.05M
# A simple color module I wrote for my projects # Feel free to copy this script and use it for your own projects! class Color: purple = '\033[95m' blue = '\033[94m' green = '\033[92m' yellow = '\033[93m' red = '\033[91m' white = '\033[0m' class textType: bold = '\033[1m' underline = ...
# LC 1268 class TrieNode: def __init__(self): self.next = dict() self.words = list() class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for char in word: # node = node.next.setdefault(char, TrieNode()) ...
x = int(input()) y = int(input()) print(y % x)
# number_list = [str(x) for x in range(1000 +1)] # number_list_str = ''.join(number_list) # print(number_list_str.count('1')) # print(''.join([str(x) for x in range(1000 +1)]).count('1')) # format(n, '+') # format(n, '-') # format(n, ',') 천단위마다 콤마 # format(n, '_') 천단위마다 언더바 # format(n, 'b') 바이너리로 # format...
mediaidade = 0 maioridade = 0 nomevelho = '' totmulher = 0 for p in range(1, 5): print('----{}ª pessoa----'.format(p)) nome = str(input('Digite seu nome: ')) .strip() idade = int(input('Digite sua idade: ')) sexo = str(input('Sexo[M/F]: ')) .strip() mediaidade += idade if p == 1 and sexo in ...
class OutputBase: def __init__(self): self.output_buffer = [] def __call__(self, obj): self.write(obj) def write(self, obj): pass def clear(self): self.output_buffer = []
#!/usr/bin/python # https://po.kattis.com/problems/vandrarhem class Bed(object): def __init__(self, price, available_beds): """ Constructor for Bed """ self.price = int(price) self.available_beds = int(available_beds) def is_full(self): """ Checks if there is a bed of this ty...
DEBUG = False # if False, "0" will be used ENABLE_STRING_SEEDING = True # use headless evaluator HEADLESS = False # === Emulator === DEVICE_NUM = 1 AVD_BOOT_DELAY = 30 AVD_SERIES = "api19_" EVAL_TIMEOUT = 120 # if run on Mac OS, use "gtimeout" TIMEOUT_CMD = "timeout" # === Env. Paths === # path should end with a '/...
""" Remove metainfo files in folders, only if they're associated with torrents registered in Transmission. Usage: clutchless prune folder [--dry-run] <metainfo> ... Arguments: <metainfo> ... Folders to search for metainfo files to remove. Options: --dry-run Doesn't delete any files, only outputs w...
class InvalidDataFrameException(Exception): pass class InvalidCheckTypeException(Exception): pass
#!/usr/bin/python # vim: set ts=4: # vim: set shiftwidth=4: # vim: set expandtab: #------------------------------------------------------------------------------- #---> Elections supported #------------------------------------------------------------------------------- # election id - base_url - election type - year -...
def ortho_locs(row, col): offsets = [(-1,0), (0,-1), (0,1), (1,0)] for row_offset, col_offset in offsets: yield row + row_offset, col + col_offset def adj_locs(row, col): offsets = [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)] for row_offset, col_offset in offsets: yiel...
def GetByTitle(type, title): type = type.upper() if type != 'ANIME' and type != 'MANGA': return False variables = { 'type' : type, 'search' : title } return variables
class BaseModel(object): @classmethod def connect(cls): """ Args: None Returns: None """ raise NotImplementedError('model.connect not implemented!') @classmethod def create(cls, data): """ Args: data(dict) ...
def queryValue(cur, sql, fields=None, error=None) : row = queryRow(cur, sql, fields, error); if row is None : return None return row[0] def queryRow(cur, sql, fields=None, error=None) : row = doQuery(cur, sql, fields) try: row = cur.fetchone() return row except Exception as e: ...
HEADERS_FOR_HTTP_GET = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' } AGE_CATEGORIES = [ 'JM10', 'JW10', 'JM11-14', 'JW11-14', 'JM15-17', 'JW15-17', 'SM18-19', 'SW18-19', 'SM20-24', 'SW20-24', 'SM25...
# # PySNMP MIB module MICOM-IFDNA-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MICOM-IFDNA-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:02:03 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
a = 5 b = 3 def timeit_1(): print(a + b) c = 8 def timeit_2(): print(a + b + c)
def some_but_not_all(seq, pred): has = [False,False] for it in seq: has[bool(pred(it))] = True # exit as fast as possible if all(has): return True # sequennce is scanned with only True or False predictions. return False
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' A short description of this file A slightly longer description of this file can be found under the shorter desription. ''' def get_code(): ''' Get mysterious code... ''' return '100111011111101010110110101100'
class StdoutMock(): def __init__(self, *args, **kwargs): self.content = '' def write(self, content): self.content += content def read(self): return self.content def __str__(self): return self.read()
""" uci_bootcamp_2021/examples/functions.py examples on how to use functions """ def y(x, slope, initial_offset): """ This is a docstring. it is a piece of living documentation that is attached to the function. Note: different companies have different styles for docstrings, and this one doesn't fit any o...
def flatten(list): final = [] for item in list: final += item return final def flattenN(list): if type(list[0]) != type([]): return list return flattenN(flatten(list)) list = [[[1,2],[3,4]],[[3,4],["hello","there"]]] result = flattenN(list) print(result)
def imp_notas(quantidade, valor): return '{:.0f} nota(s) de R$ {:.2f}'.format(quantidade, valor) def imp_moedas(quantidade, valor): return '{:.0f} moeda(s) de R$ {:.2f}'.format(quantidade, valor) numero = float(input()) numero += 0.0001 if numero >= 0 or numero <= 1000000.00: notas = [100.00, 50.00, 20....
class Wizard: def __init__(self, app): self.app = app def skip_wizard(self): driver = self.app.driver driver.find_element_by_class_name("skip").click()
def linked_sort(a_to_sort, a_linked, key=str): res = sorted(zip(a_to_sort, a_linked), key=key) for i in range(len(a_to_sort)): a_to_sort[i], a_linked[i] = res[i] return a_to_sort
# -*- coding: utf-8 -*- # :copyright: (c) 2011 - 2015 by Arezqui Belaid. # :license: MPL 2.0, see COPYING for more details. __version__ = '1.0.3' __author__ = "Arezqui Belaid" __contact__ = "info@star2billing.com" __homepage__ = "http://www.star2billing.org" __docformat__ = "restructuredtext"
def print_stats(num_broke, num_profitors, sample_size, profits, loses, type): broke_percent = (num_broke / sample_size) * 100 profit_percent = (num_profitors / sample_size) * 100 try: survive_profit_percent = (num_profitors / (sample_size - num_broke)) * 100 except ZeroDivisionError: ...
class Similarity: def __init__(self, path, score): self.path = path self.score = score @classmethod def from_dict(cls, adict): return cls( path=adict['path'], score=adict['score'], ) def to_dict(self): return { 'path':...
"""Aluguel por KM e dia""" # Uso de operadores aritmeticos dia = float(input('Quantos dias passou com o carro: ')) km = float(input('Quantos Km você andou com o carro: ')) pdia = dia * 60 # Cobrança p/dia pkm = km * 0.15 # cobrança po km pfim = pdia + pkm # Soma final print('Você passou {} dias com o carro e rodo...
EFFICIENTDET = { 'efficientdet-d0': {'input_size': 512, 'backbone': 'B0', 'W_bifpn': 64, 'D_bifpn': 2, 'D_class': 3}, 'efficientdet-d1': {'input_size': 640, 'backbone': 'B1', ...
# Refaça o DESAFIO 9, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for. n = int(input('Quer a tabuada de que número? ')) print(f'{"=" * 30}') print(f'A tabuada do número {n} é: ') print(f'{"=" * 30}') for i in range(0, 11): print(f'{n} X {i} = {n * i}') print(f'{"=" * 30...
month = int(input("Enter month: ")) year = int(input("Enter year: ")) if month == 1: monthName = "January" numberOfDaysInMonth = 31 elif month == 2: monthName = "February" if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0): numberOfDaysInMonth = 29 else: numberOfDa...
n1 = int(input('Digite um valor: ')) n2 = int(input('Digite outro valor: ')) # print('A soma vale {}'.format(n1 + n2)) s = n1 + n2 sub = n1 - n2 m = n1 * n2 d = n1 / n2 di = n1 // n2 e = n1 ** n2 print('A soma é {}, a subtração é {}, a multiplicação é {} e a divisão é {}'.format(s, sub, m, d)) print('A divisão inteira ...
''' Reversed OBS: Não confunda com a função reserve() que estudamos nas listas. Afunção reverse() só funciona em listas. Já a função reversed() funciona com qualquer iterável. Sua função é inverter o iterável. A função reversed() retorna um iterável chamado List Reverse Iterator ''' # Exemplos lista = [1, 2, 4, ...
# Problem: Given as an input two strings, X = x_{1} x_{2}... x_{m}, and Y = y_{1} y_{2}... y_{m}, output the alignment of the strings, character by character, # so that the net penalty is minimised. gap_penalty = 3 # cost of gap mismatch_penalty = 2 # cost of mismatch memoScore = {} memoSe...
A = int(input()) B = set("aeiou") for i in range(A): S = input() count = 0 for j in range(len(S)): if S[j] in B: count += 1 print(count)
# Configuration for running the Avalon Music Server under Gunicorn # http://docs.gunicorn.org # Note that this configuration omits a bunch of features that Gunicorn # has (such as running as a daemon, changing users, error and access # logging) because it is designed to be used when running Gunicorn # with supervisord...
""" Generator expressions are lazily evaluated, which means that they generate and return each value only when the generator is iterated. This is often useful when ITERATING THROUGH LARGE DATEBASES, avoiding the need to create a duplicate of the dataset in memory. """ for square in (x**2 for x in range(100)): prin...
#check if number is prime or not n = int(input("enter a number ")) for i in range(2, n): if n % i == 0: print("not a prime number") break else: print("it is a prime number")
# # PySNMP MIB module EXTREME-EAPS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EXTREME-BASE-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:07:14 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
# -*- coding: utf-8 -*- operation = input() total = 0 for i in range(144): N = float(input()) line = i // 12 if (i > (13 * line)): total += N answer = total if (operation == 'S') else (total / 66) print("%.1f" % answer)
# -*- coding: utf-8 -*- """Top-level package for light_tester.""" __author__ = """Gary Cremins""" __email__ = 'gary.cremins1@ucdconnect.ie' __version__ = '0.1.0'
S = [3, 1, 3, 1] N = len(S)-1 big_val = 1 << 62 # left bitwise shift is equivalent to raising 2 to the power of the positions shifted. so, big_val = 2 ^ 62. A = [[big_val for i in range(N+1)] for j in range(N+1)] def matrix_chain_cost(i, j): global A if i == j: return 0 if A[i][j] != big_val: ...
# Function: flips a pattern by mirror image # Input: # string - string pattern # direction - flip horizontally or vertically # Ouput: modified string pattern def flip(st, direction): row_strings = st.split("\n") row_strings = row_strings[:-1] st_out = '' if (direction == 'Flip Horizo...
matrix = [[dot == '#' for dot in line.strip()] for line in open('input.txt')] diffs = [(x, y) for x in (-1, 0, 1) for y in (-1, 0, 1) if (x, y) != (0, 0)] corners = [(x, y) for x in (0, len(matrix)-1) for y in (0, len(matrix[0])-1)] for x, y in corners: matrix[x][y] = True def neighbors(matrix, x, y): for i, j...
def multiply(a, b): c = [[0] * 3 for _ in range(3)] for i in range(3): for j in range(3): for k in range(3): c[i][j] += a[i][k] * b[k][j] return c q = int(input()) for _ in range(q): x, y, z, t = input().split() x = float(x) y = float(y) z = float(z) ...
""" exchanges. this acts as a routing table """ BITMEX = "BITMEX" DERIBIT = "DERIBIT" DELTA = "DELTA" BITTREX = "BITTREX" KUCOIN = "KUCOIN" BINANCE = "BINANCE" KRAKEN = "KRAKEN" HITBTC = "HITBTC" CRYPTOPIA = "CRYPTOPIA" OKEX = "OKEX" NAMES = [BITMEX, DERIBIT, DELTA, OKEX, BINANCE] def exchange_exists(name): retu...
# Exercise 3.1: Rewrite your pay computation to give the employee 1.5 times the # rate for hours worked above 40 hours. # Enter Hours: 45 # Enter Rate: 10 # Pay: 475.0 # Python for Everybody: Exploring Data Using Python 3 # by Charles R. Severance hours = float(input("Enter hours: ")) rate_per_hour = float(input("En...
class BaseEmployee(): "The base class for an employee." # Note: Unlike c#, on initiliazing a child class, the base contructor is not called # unless specifically called. def __init__(self, id, city): "Constructor for the base employee class." print('Base constructor called.'); s...
ix.enable_command_history() app = ix.application clarisse_win = app.get_event_window() ix.application.open_edit_color_space_window(clarisse_win) ix.disable_command_history()
distanca = int(input()) tempo = (2 * distanca) print('%d minutos' %tempo)
def sayhello(name=None): if name is None: return "Hello World, Everyone!" else: return f"Hello World, {name}"
def binary_and(a: int , b: int) -> str: """ Take in 2 integers, convert them to binary, return a binary number that is the result of a binary and operation on the integers provided. """ if a < 0 or b < 0: raise ValueError('The value of both number must be positive') a_bin = str(b...
def imgcd(m,n): for i in range(1,min(m,n)+1): if m%i==0 and n%i==0: mcrf=i return mcrf a=input() b=input() c=imgcd(int(a),int(b)) print(c)
class Tape(object): blank = " " def __init__(self, tape): self.tape = tape self.head = 0
def extractOntimestoryWordpressCom(item): ''' Parser for 'ontimestory.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None if chp == 2019: return None badwords = [ 'Dark Blue Kiss', '2moo...
'''' Problem: Determine if two strings are permutations. Assumptions: String is composed of lower 128 ASCII characters. Capitalization matters. ''' def isPerm(s1, s2): if len(s1) != len(s2): return False arr1 = [0] * 128 arr2 = [0] * 128 for c, d in zip(s1, s2): arr1[ord(c...
#Write a function to find the longest common prefix string amongst an array of strings. #If there is no common prefix, return an empty string "". def longest_common_prefix(strs) -> str: common = "" strs.sort() for i in range(0, len(strs[0])): if strs[0][i] == strs[-1][i]: common +=...
class RestApiBaseTest(object): def assert_items(self, items, cls): """Asserts that all items in a collection are instances of a class """ for item in items: assert isinstance(item, cls) def assert_has_valid_head(self, response, expected): ...
'''Programa clássico sobre média de notas de um aluno''' n1 = float(input('Prineira nota: ')) n2 = float(input('Segunda nota: ')) media = (n1 + n2)/ 2 print('Sua média foi: {}'.format(media)) if media < 5.0: print('Você está reprovado.') elif media >= 7.0: print("Você está aprovado. Parabéns!") else: pr...
def target_file(): return ".html" def target_domain(): return "https://lyricsmania.com/" def artist_query(name): return target_domain() + str.lower(name) + "_lyrics" + target_file() if __name__ == "__main__": print(artist_query("Lizzo"))
load("@bazel_skylib//lib:paths.bzl", "paths") GlslLibraryInfo = provider("Set of GLSL header files", fields = ["hdrs", "includes"]) SpirvLibraryInfo = provider("Set of Spirv files", fields = ["spvs", "includes"]) def _export_headers(ctx, virtual_header_prefix): strip_include_prefix = ctx.attr.strip_include_prefix...
node = S(input, "application/json") node.prop("comment", "42!") propertyNode = node.prop("comment") value = propertyNode.stringValue()
def moeda(funcao, moeda='R$'): return f'{moeda}{funcao:.2f}'.replace('.', ',') def aumentar(p, taxa): res = p * (1 + taxa/100) return res def diminuir(p, taxa): res = p * (1 - taxa/100) return res def dobro(p): res = p * 2 return res def metade(p): res = p / 2 return res
class Solution: def naive(self,root): self.res = 0 def dfs(tree,s): s_ = s*10+tree.val if tree.left==None and tree.right==None: self.res+=s_ return if tree.left: dfs(tree.left,s_) if tree.right: ...
class Solution: def getSmallestString(self, n: int, k: int) -> str: op=['a']*n k=k-n i=n-1 while k: k+=1 if k/26>=1: op[i]='z' i-=1 k=k-26 else: op[i]=chr(k+96) k=0 ...
# -*- coding: utf-8 -*- """An implementation of learning priority sort algorithm_learning with NTM. Input sequence length: "1 ~ 20: (1*2+1)=3 ~ (20*2+1)=41" Input dimension: "8" Output sequence length: equal to input sequence length. Output dimension: equal to input dimension. """
def summation(n,term): total,k=0,1 while k<=n: total,k = term(k) + total, k+1 return total def square(x): return x*x def pi_summantion(n): return summation(n, lambda x: 8 / ((4*x-3) * (4*x-1))) def suqare_summantio(n): return summation(n, square) print(pi_summantion(1e6)) print(s...
# -*- coding: utf-8 -*- """ Created on Fri Nov 13 14:05:03 2020 Introduction to Computation and Programming Using Python. John V. Guttag, 2016, 2nd ed Book Chapter 2 Finger Exercises Using While Loop @author: Atanas Kozarev - github.com/ultraasi-atanas """ numXs = int(input('How many times should I print the letter ...
def sort_2d_np(edges): """ edges: (m x 2) Sort ascendngly according to each column. Example: edges = array( [[9, 8], [3, 6], [1, 3], [8, 6], [3, 2], [9, 1], [5, 1]] ) sorte...
# Der größte gemeinsame Teiler (ggT) von zwei Zahlen # ist die größte Zahl, durch die man beide Zahlen teilen kann. # Beispiel: Größter gemeinsamer Teiler von 4 und 6 ist 2. # Die englische Bezeichnung ist greatest common divisor (gcd) für ggT. def gcd(a, b): while a != b: if b > a: a, b = b, a...
class PhotoAlbum: def __init__(self, pages: int): self.pages = pages self.photos = [[] for _ in range(self.pages)] @classmethod def from_photos_count(cls, photos_count: int): pages_count = photos_count // 4 if photos_count % 4 != 0: pages_count += 1 retur...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # filename: PB/error.py # # 错误类 # __all__ = [ "PBError", "PBStateCodeError", ] class PBError(Exception): """ PB 错误类 """ pass class PBStateCodeError(PBError): """ PB 异常请求码 """ pass
print('hii'+str(5)) print(int(8)+5); print(float(8.5)+5); print(int(8.5)+5); #print(int('C'))
def compare(v1, operator, v2): if operator == ">": return v1 > v2 elif operator == "<": return v1 < v2 elif operator == ">=": return v1 >= v2 elif operator == "<=": return v1 <= v2 elif operator == "=" or "==": return v1 == v2 elif operator == "!=": ...
# 変数を文字列に埋め込んで出力 : 文字列メソッドformat() s = 'Alice' i = 25 print('{} is {} years old'.format(s, i)) # インデックスを指定 print('{0} is {1} years old / {0}{0}{0}'.format(s, i)) # キーワード引数として指定 print('{name} is {age} years old / {age}{age}{age}'.format(name=s, age=i))
def return_load(**kwargs): if kwargs['_type'] == 'Point': load = PointLoad(**kwargs) elif kwargs['_type'] == 'Uniform': load = UniformLoad(**kwargs) else: print('Invalid type: returned default `PointLoad`') return PointLoad() return load class PointLoad(object): """...
#pythran export fib_pythran(int) def fib_pythran(n): i, sum, last, curr = 0, 0, 0, 1 if n <= 2: return 1 while i < n - 1: sum = last + curr last = curr curr = sum i += 1 return sum #pythran export count_doubles_pythran_zip(str, int) def count_doubles_pythran_zip...
# # PySNMP MIB module PNNI-EXT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PNNI-EXT-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:41:07 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,...
""" @author Huaze Shen @date 2019-10-05 """ class ListNode: def __init__(self, x): self.val = x self.next = None def delete_duplicates(head): if head is None or head.next is None: return head pre = head while pre: cur = pre while cur.next and cur.val == cur.ne...
# flake8: noqa bm25 = BatchRetrieve(index, "BM25") axiom = (ArgUC() & QTArg() & QTPArg()) | ORIG() # Re-rank top-20 documents with KwikSort. kwiksort = bm25 % 20 >> \ KwikSortReranker(axiom, index) pipeline = kwiksort ^ bm25
ciphertext = "WAPSD EXTCO EEREF SELIO RSARC LIETE OIHHP VASTF EGBER IPAPN TOEGI AIATH DDHIY EACYE RQAEN OHRTE TEVME BGHMF EIOWS GFHCL XEUUC OMTOT LERES SDEWW ORCCS HEURE ATTEG ALSEB APXET IURWV RTEEH IOTLO SNACN NULCV LCMTH HHCOH TIOTD ASNAL TSANA CASOR LEKAS TATCW INTLO TRYER YLTND RILER AOMAX OITDE ECOIA HAALS TYIOA ...
class PractitionerTemplate: def __init__(self): super().__init__() def practitioner_default(self, data_list): keys = [] for data in data_list: key = f"{data.get('rowid')},{data.get('employee_id')}" keys.append(key) return keys
def update_bit(num, bit, value): mask = ~(1 << bit) return (num & mask) | (value << bit) def get_bit(num, bit): return (num & (1 << bit)) != 0 def insert_bits(n, m, i, j): for bit in range(i, j + 1): n = update_bit(n, bit, get_bit(m, bit - i)) return n def insert_bits_mask(n, m, i, j): mask = (~0 ...
nodes = [[1,3], [0,2], [1,3], [0,2]] otherNodes = [[1,2,3], [0,2], [0,1,3], [0,2]] def isBipartite(nodes): colors = [0] * len(nodes) for index, node in enumerate(nodes): if colors[index] == 0 and not properColor(nodes, colors, 1, index): return False return True def properColor(graph, colors, color, n...
manipulated_string = input() while True: line = input() if line == "end": break command_element = line.split(' ') command = command_element[0] first_condition = int(command_element[1]) if command == 'Right': for i in range(first_condition): manipulated_string = manipu...
c = {a: 1, b: 2} fun(a, b, **c) # EXPECTED: [ ..., LOAD_NAME('fun'), ..., BUILD_TUPLE(2), ..., CALL_FUNCTION_EX(1), ..., ]
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def partition(self, head, x): """ :type head: ListNode :type x: int :rtype: ListNode """ if not head:...
entrada = 'Gilberto' saida = '{:+^12}'.format(entrada) print(saida) entrada = 'sensoriamento remoto' saida = entrada.capitalize() print(saida) entrada = 'sensoriamento remoto' saida = entrada.title() print(saida) entrada = 'GilberTo' saida = entrada.lower() print(saida) entrada = 'Gilberto' saida =...
n = int(input()) l = {} for i in range(n): k = input() if k in l: l[k] += 1 else: l[k] = 1 print(len(l)) for i in l: print(l[i], end=" ")
# @Time: 2022/4/12 20:29 # @Author: chang liu # @Email: chang_liu_tamu@gmail.com # @File:4-3-Creating-New-Iteration-Patterns-With-Generators.py def frange(start, stop, increment): x = start while x < stop: yield x x += increment # for n in frange(1, 5, 0.6): # print(n) def countdown(n):...
""" Created on 20 Feb 2019 @author: Frank Ypma """ class Location: """ Simple x,y coordinate wrapper """ def __init__(self, x=0, y=0): self.x = x self.y = y
def test_get_key(case_data): """ Test :meth:`.get_key`. Parameters ---------- case_data : :class:`.CaseDat` A test case. Holds the key maker to test and the correct key it should produce. Returns ------- None : :class`NoneType` """ _test_get_key( key_m...
# https://leetcode.com/explore/learn/card/fun-with-arrays/527/searching-for-items-in-an-array/3251/ class Solution: def validMountainArray(self, arr: List[int]) -> bool: inc = True incd = False decd = False for i,elmnt in enumerate(arr): if i == 0:continue if ...
def get_input() -> list: with open(f"{__file__.rstrip('code.py')}input.txt") as f: return [int(l[:-1]) for l in f.readlines()] def has_pair(sum_val: int, vals: list) -> bool: for idx_i, i in enumerate(vals): for j in vals[idx_i+1:]: if i + j == sum_val: return True ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ############################################## # Institut Villebon, UE 3.1 # Projet : mon_via_navigo # Auteur : C.Lavrat, B. Marie Joseph, S. Sonko # Date de creation : 27/12/15 # Date de derniere modification : 27/12/15 ############################################## cla...
""" Profile ../profile-datasets-py/div52_zen50deg/034.py file automaticaly created by prof_gen.py script """ self["ID"] = "../profile-datasets-py/div52_zen50deg/034.py" self["Q"] = numpy.array([ 1.607768, 4.15376 , 5.83064 , 7.181963, 6.558055, 7.26391 , 9.444143, 8.659606, ...
#--- Exercicio 1 - Impressão de dados com a função Print #--- Imprima nome, sobrenome e idade cada um em uma nova linha nome = 'Pablo' sobrenome = 'Schumacher' idade=16 print(f'Nome: {nome}\nSobrenom: {sobrenome}\nIdade: {idade}')
"""The markdown module.""" # pylint: disable=invalid-name def bold(text): """Bold. Args: text (str): text to make bold. Returns: str: bold text. """ return '**' + text + '**' def code(text, inline=False, lang=''): """Code. Args: text (str): text to make code. ...