content
stringlengths
7
1.05M
abeceda = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] def abecedna_vrednost(ime): seznam = list(str(ime)) vrednost = 0 for i in range(len(seznam)): vrednost = vrednost + abeceda.index(seznam[i]) + 1 return vr...
#If the bill was $150.00, split between 5 people, with 12% tip. #Each person should pay (150.00 / 5) * 1.12 = 33.6 #Format the result to 2 decimal places = 33.60 #Tip: There are 2 ways to round a number. You might have to do some Googling to solve this.💪 #HINT 1: https://www.google.com/search?q=how+to+round+number+to+...
wt3_3_7 = {'192.168.122.110': [5.3551, 8.3352, 7.3783, 6.9324, 6.6606, 6.4673, 6.5077, 6.6393, 7.3012, 7.1319, 6.7323, 6.3639, 6.33, 6.6602, 6.9711, 6.8935, 7.1543, 7.3671, 7.2675, 7.223, 7.1379, 7.3225, 7.2638, 7.4282, 7.435, 7.3821, 7.5459, 7.4728, 7.4688, 7.4658, 7.3986, 7.347, 7.4649, 7.4186, 7.4119, 7.358, 7.3216...
des = 'Desafio-034 estruturas condicionais' print ('{}'.format(des)) #Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários superiores a R$1250,00, calcule um aumento de 10%. Para os inferiores ou iguais, o aumento é de 15%. salario = (float(input('Digite seu salá...
class RaceRegistry: """Race Registry includes runners' information Attributes: @type under_20: list emails of under_20 category @type under_30: list emails of under_30 category @type under_40: list emails of under_40 category @type over_40: list e...
num = int(input('Digite o numero para a tabuada: ')) contador = 0 print('-' * 12) print('{} * {:2} = {:2}'.format(num, contador, (num*contador))) contador = contador + 1 print('{} * {:2} = {:2}'.format(num, contador, (num*contador))) contador = contador + 1 print('{} * {:2} = {:2}'.format(num, contador, (num*contador))...
class BetelError(Exception): """Raise when an exception occurs.""" class PlayScrapingError(BetelError): """Raise when certain attributes can't be found within the Play page.""" class AccessError(BetelError): """Raise on URL or HTTP errors.""" def __init__(self, message, exception): super(Acc...
class DeviceModelDoesnotExistException(Exception): def __str__(self): return "Target device model doesn't exist." class ParameterCannotBeNone(Exception): def __str__(self): return "Parameter cannot all be None."
level = 3 name = 'Margahayu' capital = 'Sukamenak' area = 10.54
"""A dictonary containing every option/button in the map. xStart, yStart, xEnd, yEnd are all percentiles, which are later multipled by the total width and height of the map. Activated is a boolean which changes when the button is placed on the screen. Ending is a boolean which determines if that option/button is the fi...
''' Loops let you walk through a sequence of items, such as items in a list ''' # # looping through a list # colors = ['black', 'blue', 'brown', 'green', 'purple', 'white', 'yellow'] for color in colors: print(color) # # Looping through a range of numbers # for num in range(5): print(num) # Prints th...
#!/usr/bin/env python # -*- coding: utf-8 -*- def get_palindromic(n_s, n_e): n_1 = n_s f_1 = -1 f_2 = -1 f = -1 while n_1 <= n_e: for n_2 in range(n_1, n_e+1): n = n_1 * n_2 if is_palindromic(n) and n > f: f_1 = n_1 f_2 = n_2 ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Author - Samar Srivastava (https://samacker77.github.io) Problem Link - https://www.hackerrank.com/challenges/s10-quartiles/problem Problem Statement - Given an array, X, of n integers, calculate the respective first quartile (Q1), second quartile (Q2), and third qua...
def edit_distance(s1, s2): """Calculates the Levenshtein distance between two strings.""" if s1 == s2: # if equal, then distance is zero return 0 m, n = len(s1), len(s2) # if one string is empty, then distance is the length of the other string if not s1: return n elif not s2:...
""" map() toma un iterable y devuelve otro iterable """ friends = ['Juan', 'Carlos', 'Daniel', 'Ricardo', 'Jhon'] friends_lower = map(lambda x: x.lower(), friends) print(next(friends_lower)) print(next(friends_lower)) class User: def __init__(self, username, password): self.username = username s...
''' Piling Up! https://www.hackerrank.com/challenges/piling-up/problem There is a horizontal row of n cubes. The length of each cube is given. You need to create a new vertical pile of cubes. The new pile should follow these directions: if cube(i) is on top of cube(j) then sideLength(j) >= sideLength(i). When stack...
""" lab2 """ #3.1 my_name = 'Tom' print(my_name.upper()) #3.2 my_id = 123 print(my_id) #3.3 my_id = your_id = 123 print(my_id) print(your_id) #3.4 my_id_str = "123" print(my_id_str) #3.5 #print(my_name + my_id) Cannot add string and variable #3.6 print(my_name + my_id_str) #3.7 print(my_name * 3) #3.8 print...
def get_average_inventory_worth(current, production, consumption, processing, queued, missing, trade): results = {"P1": 0, "P2": 0, "P3": 0, "E4": 0, "E5": 0, "E6": 0, "E7": 0, "E8": 0, "E9": 0, "E10": 0, "E11": 0, "E12": 0, "E13": 0, "E14": 0, "E15": 0, "E16": 0, "E17": 0, "E18": 0, "E19": 0, "E20"...
#! /usr/bin/env python3 ''' Problem 1 - Project Euler http://projecteuler.net/index.php?section=problems&id=001 ''' def summul(n, x): return int(x * (n // x) * (n // x + 1) / 2) if __name__ == '__main__': N = 1000 - 1 print(summul(N, 3) + summul(N, 5) - summul(N, 3 * 5))
for t in range(int(input())): A,B=input().split() L=[[0]*(len(A)+1) for i in range((len(B)+1))] for i in range(len(B)): for j in range(len(A)): if B[i]==A[j]: L[i+1][j+1]=L[i][j]+1 else : L[i+1][j+1]=max(L[i][j+1],L[i+1][j]) print(f"#{t+1}...
""" Temperature unit """ CELSIUS = "°C" FAHRENHEIT = "°F" _units = (CELSIUS, FAHRENHEIT) def _fahrenheit_to_celsius(fahrenheit: float): return (fahrenheit - 32.0) / 1.8 def _celsius_to_fahrenheit(celsius: float): return celsius * 1.8 + 32.0 class Temperature: def __init__(self, value: float, unit:...
with Flow(bypass_sub_flows=True, add_flow_enable="enabled", environment="probe") as flow: flow.description = ''' An example of creating an entire test program from a single source file ''' #unless Origen.app.environment.name == 'v93k_global' flow.set_resources_filename('prb2') ...
__title__ = 'campy' __description__ = 'ACM Graphical Libraries in Python' __url__ = 'https://campy.sredmond.io/' __license__ = 'MIT' __version__ = '0.0.1.dev3' __build__ = 0x000001 __status__ = 'Prototype' __author__ = 'Sam Redmond' __maintainer__ = 'Sam Redmond' __email__ = 'sredmond@stanford.edu' __copyright__ = '(...
print('POR FAVOR, INFORME DOIS VALORES!') n1 = int(input('VALOR 1: ')) n2 = int(input('VALOR 2: ')) print('_'*40) print('\033[1:33m{:^40}'.format('RESULTADO')) print(f'\033[m>>> A soma de {n1} e {n2} é igual a \033[1m{n1+n2}.')
#!/usr/bin/env python3 def solve(data): allowed = [] test_num = 0 prv_rng = range(0, 0) for rng in sorted(data, key=lambda x: x.start): if rng.stop in prv_rng: continue while not test_num in rng: allowed.append(test_num) test_num += 1 prv_rng ...
S = input() A = input() if len(S) < len(A): print('UNRESTORABLE') exit(0) for i in reversed(range(len(S)-len(A)+1)): for j in range(len(A)): if not(S[i+j] == A[j] or S[i+j] == '?'): break else: ans = S[:i] + A + S[i+len(A):] ans = ans.replace('?', 'a') prin...
idade = int(input('digite sua idade: ')) if idade < 18: tf = 18 - idade print ('Ainda não é hora de fazer o alistamento') print ('O alistamento será necessario daqui {} anos'.format(tf)) elif idade == 18: print ('Esta na hora de se alistar') else: tf = idade - 18 print ('Passou do tempo para se ...
def to_celsius(x): return (x-32)*5/9 for x in range(0,101,10): print(x,to_celsius(x))
def selection_sort(array): length = len(array) for i in range(0, length, 1): higher = i for j in range(i+1, length, 1): if array[higher] > array[j]: higher = j if higher != i: tmp = array[higher] array[higher] = array[i] ...
class ToolStripItem( Component, IComponent, IDisposable, IDropTarget, ISupportOleDropSource, IArrangedElement, ): """ Represents the abstract base class that manages events and layout for all the elements that a System.Windows.Forms.ToolStrip or System.Windows.Forms.ToolStripDropDown...
"""Global errors: Global error codes are negative, with four decimal digits, where the two most significant ones indicate which analyzer is generating them: -10__: NumberAnalyzer (num_analyzer.py) -11__: CharAnalyzer (string_analyzer.py) -12__: StringAnalyzer ...
# 315. Count of Smaller Numbers After Self # ttungl@gmail.com # You are given an integer array nums and you have to return a new counts array. # The counts array has the property where counts[i] is the number of smaller elements # to the right of nums[i]. # Example: # Given nums = [5, 2, 6, 1] # To the right of 5 ...
"""You would probably keep your configuration out of the git repo, but this works for a simple script. See the docs for information on Flask configuration. """ DATABASE_NAME = 'flask_mongo_example'
class Unit(object): def __init__(self, name, attack, defend): self.name = name self.attack = attack self.defend = defend def __repr__(self): return self.name units = { 'droid': Unit('droid', 42, 41), 'gorgul': Unit('gorgul', 24, 20), 'pushkar': Unit('pushkar', 55, ...
# Solutions for Radon tutorial - PyData Global 2020 Tutorial def radon_noise(): """Create noise to add to projections """ sigman = 5e-1 # play with this... n = np.random.normal(0., sigman, projection.shape) projection_n = projection + n projection1_n = projection1 + \ n[pro...
X, Y = map(int, input().split()) X += 2 if Y >= 30: X += 1 Y -= 30 else: Y += 30 X %= 24 print('%02d:%02d' % (X, Y))
class Node: def __init__(self, key) -> None: self.val = key self.left = None self.right = None def printInorder(node): if node == None: return else: printInorder(node.left) print(node.val, end=' ') right_node = printInorder(node.right) def pre...
diaria=int(input('Quantos dias você ficou com o carro? ')) km=float(input('Quantos KM você rodou com o carro? ')) pago = (diaria * 60) + (km * 0.15) print('total a pagar é de R$: ',pago)
filenames = ['file1.txt', 'file2.txt', ...] with open('path/to/output/file', 'w') as outfile: for fname in filenames: with open(fname) as infile: outfile.write(infile.read())
""" To sort the array to count the set bits in binary representation of array elements. """ def count_set_bits(num): count = 0 while num: if num & 1: count += 1 num = num >> 1 return count def sort_setbit_based(array): count = [] for i in range(len(array)): ...
#다섯개 입력받아서 #앞의 세 개 중 가장 싼 거 + 뒤의 두 개 중 가장 싼거 - 50 출력 price = [int(input()) for i in range(5)] print(min(price[:3]) + min(price[3:]) - 50)
class Parent: def __init__(self, name): print("Parent Object Created") self.testFunc(name) def testFunc(self, name): print("Parent testFunc called {}", name) class Child(Parent): def __init__(self, name): print("Child Object Created") self.testFunc(name) # def testFunc(self, name): # print("Child testF...
# -*- coding: utf-8 -*- """ MIMEタイプ """ TEXT = "text/plain" HTML = "text/html" CSS = "text/css" JS = "application/javascript" XML = "application/xml" XHTML = "application/xhtml+xml" JSON = "application/json" SVG = "image/svg+xml" def needs_charset(mime_type): """ charset指定が必要なMIMEタイプか? """ return mime_t...
n1 = int(input('primeiro numero: ')) n2 = int(input('segundo numero: ')) n3 = int(input('terceiro numero: ')) lista = (n1,n2,n3) c = 1 menor = 0 meio = 0 maior = 0 for n in lista: if c == 1 or n < menor: menor = n if c == 1 or n > maior: maior = n if c == 1 or menor < n < maior: mei...
''' Write a Python program to find the largest product of the pair of adjacent elements from a given list of integers. Sample Input: [1,2,3,4,5,6] [1,2,3,4,5] [2,3] Sample Output: 30 20 6 ''' ''' The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is p...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class BSTIterator: def __init__(self, root: TreeNode): self.stack = [] self.getLeftMostNode(root) def getLeftMostNode(self, node: ...
def longestPeak(array): # Write your code here. maxPeakLength=0 i=1 while(i<len(array)-1): # print(i) isPeak= array[i]>array[i-1] and array[i]>array[i+1] if not isPeak: i+=1 continue leftIdx=i-2 while(leftIdx>=0 and array[leftIdx]<array[...
''' Array uses one-based indexing to access elements Implements Max-Heap Tree Can be used for max priority queue ''' class HeapTree: def __init__(self, value:int): self.array = [0] self.heap_size = 0 self.max_size = value def left_child(self, index:int): ''' ...
# Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar. #considerando dólar a 3,27 dinheiro = float(input('Digite o valor em Reais para conversão em Dólares: ')) dolar = 3.27 soma = dinheiro/dolar print('Com o valor de R$ {:.2f}, você pode comprar ${:.2f}...
class Page: __index__ = """<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{title}}</title> <!-- ADD YOUR CSS & CDN HERE WHICH IS APPLICABLE TO ALL...
def display(g): for y in range(g.height): for x in range(g.width): digit, snake = g(x, y) if snake: print("[{}]".format(digit), end="") else: print(" {} ".format(digit), end="") if x % 3 == 2: print(" ", end="") ...
#=============================================================== # DMXIS Macro (c) 2010 db audioware limited #=============================================================== found = False for ch in GetAllSelCh(True): nm = GetChName(ch) if nm=="Pan" or nm=="Tilt": SelectCh(ch, 1) found ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2020/7/10 9:05 # @Author : 一叶知秋 # @File : HeapSort2.py.py # @Software: PyCharm def heapify(unsorted, index, heap_size): largest = index left_index = 2 * index + 1 right_index = 2 * index + 2 if left_index < heap_size and unsorted[left_index...
s = '' i = 1 while (True): s = s + str(i) i = i + 1 if len(s) > 1000000: break print(i) r = 1 r = r * int(s[1 - 1]) r = r * int(s[10 - 1]) r = r * int(s[100 - 1]) r = r * int(s[1000 - 1]) r = r * int(s[10000 - 1]) r = r * int(s[100000 - 1]) r = r * int(s[1000000 - 1]) print("result = ", r)
ENTRY_POINT = 'maximum' #[PROMPT] def maximum(arr, k): """ Given an array arr of integers and a positive integer k, return a sorted list of length k with the maximum k numbers in arr. Example 1: Input: arr = [-3, -4, 5], k = 3 Output: [-4, -3, 5] Example 2: Input: arr =...
class WeightedFalseNegativeLossMetric: def map(self, predicted, actual, weight, offset, model): cost_tp = 5000 # set prior to use cost_tn = 0 # do not change cost_fp = cost_tp # do not change cost_fn = weight # do not change y = actual[0] p = predicted[2] # [clas...
# refer from: # https://leetcode.com/problems/flatten-binary-tree-to-linked-list/solution/ # 2. Iterative Morris traversal class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ # Handle the null scena...
""" Grading """ def gradingStudents(grades): result = [] for rec in grades: if rec < 38: result.append(rec) else: reminder = rec % 5 quotient = rec // 5 result.append(5*(quotient+1) if reminder > 2 else rec) return result if __name__ == "_...
igrok1 = 0 igrok2 = 0 win = 0 draw = 0 lose = 0 list_choises = ['Камень', 'Ножницы', 'Бумага'] print("(Камень - 1, Ножницы - 2, Бумага - 3) Игрок 1, введите ваш номер:") igrok1 = int(input()) while 1 < igrok1 > 3: print("Введен некорректный номер") print("(Камень - 1, Ножницы - 2, Бумага - 3) Игрок 1, введите...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Solution(): def isPalindrome(self, x: int) -> bool: ''' 注意特殊情况 1. x小于0 2. 最后一位为0 3. x为0 ''' if x < 0 or (x % 10 == 0 and x != 0): return False rev = 0 while x > rev: ...
# PROBLEM LINK:- https://leetcode.com/problems/reach-a-number/ class Solution: def reachNumber(self, target: int) -> int: target = abs(target) res = 0 sum = 0 while sum < target or (sum - target)%2 != 0: res += 1 sum += res return res
def sanitize_supply_cost(a, cost, name): if cost is None: cost = a.default_cost if len(a.cost_names) > 1: a.log.info("Using default cost, {}, for {}.".format(cost, name)) if cost not in a.cost_names: raise ValueError("{} not an available cost.".format(cost)) return c...
# Copyright (c) 2011-2020, Manfred Moitzi # License: MIT License class Options: def __init__(self): self.filter_invalid_xdata_group_codes = False self.default_text_style = 'OpenSans' self.default_dimension_text_style = 'OpenSansCondensed-Light' # debugging self.log_unproce...
#!/usr/local/bin/python3 a = 2 + 2; print(a); for i in range(1, 10): print(i); a = 123; b = 12.34; c = "Hello"; d = 'Hello'; e = True; #x = input("Enter Value:"); #print(type(x)); #print("輸入值為:",x); tempC = input("Enter temp in C:"); tempF = int(tempC) * 9 / 5 + 32; print("華氏:",str(tempF),"度F");
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] for c in s: if c in ('(', '[', '{'): stack.append(c) else: if not stack: return False ...
class Solution: def longestPalindrome(self, s): slen = len(s) longest = '' longest_len = 0 for i in range(1, slen-1): loops+=1 l, r = i-1, i+1 subs = s[i] while l >= 0 and r < slen: if s[l] != s[r]: ...
class TrieNode: def __init__(self): self.children = {} self.word = None class Solution: def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: root = TrieNode() r, c = len(board), len(board[0]) for w in words: cur = root for ...
# # PySNMP MIB module Unisphere-Data-DVMRP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-DVMRP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:23:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7....
def longestRepeatedSubSeq(str): n = len(str) dp = [[0 for i in range(n + 1)] for j in range(n + 1)] for i in range(1, n + 1): for j in range(1, n + 1): if (str[i - 1] == str[j - 1] and i != j): dp[i][j] = 1 + dp[i - 1][j - 1] else: dp[i][j] = ...
class Solution: def maxAreaOfIsland(self, grid: List[List[int]]) -> int: if not grid or not grid[0]: return 0 result = 0 def dfs(x, y): dx = [0, 0, 1, -1] dy = [1, -1, 0, 0] count = 1 for k in range(4): nx, ny = dx[k...
""" A trie (pronounced as 'try') or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. Implement the Trie class: - Trie() Initializes the trie object. - void insert(String...
bandera = ["N","B","B","N","A","B","B","N","B","N","N","A","N","N","B","A","A"] print(bandera) negro = [] blanco = [] azul = [] def ordenada(bandera): if len(bandera) > 0: color = bandera.pop(0) if color =="N": negro.append(color) ordenada(bandera) elif color == "B": ...
class Solution: def missingNumber(self, nums: List[int]) -> int: result = len(nums) for i in range(len(nums)): result ^= i ^ nums[i] return result
""" Default termsets for various languages """ LANGUAGES = dict() # Dutch termset dictionary nl = dict() nl_clinical = dict() nl_pseudo = [ "probleemloos", "zonder probleem", "zonder moeilijkheid", "geen verandering", "geen duidelijke verandering", "geen evidente verandering", "geen signi...
class Solution: def __init__(self): self.inorder_p = {} self.postorder_idx = None def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: self.postorder_idx = len(postorder) - 1 for i, v in enumerate(inorder): self.inorder_p[v] = i ...
#! /root/anaconda3/bin/python i = 1 while i < 11: print(i) i += 1 while True: word = input('请输入一个单词:') if not word: break print('输入的单词是:', world) for number in range(1, 4): print(number) for _ in range(1, 4): print('Hello') for number in [1, 2, 3]: print(number) for char in ...
class StopType: """ Message type that will cause an actor to exit when sent an instance of this class, even with a non-empty inbox. """ __INSTANCE = None def __new__(cls): if StopType.__INSTANCE is None: StopType.__INSTANCE = super().__new__(cls) return StopType.__...
def intAdd(x): return lambda y: x + y def intMul(x): return lambda y: x * y def numAdd(x): return lambda y: x + y def numMul(x): return lambda y: x * y
"""Deprecated suppression style.""" __revision__ = None a = 1 # pylint: disable=invalid-name b = 1 # pylint: disable-msg=invalid-name # pylint: disable=invalid-name c = 1 # pylint: enable=invalid-name # pylint: disable-msg=invalid-name d = 1 # pylint: enable-msg=invalid-name # pylint: disable-msg=C0103 e = 1 # p...
class Node: def __init__(self, data) -> None: self.data = data self.left = None self.right = None def levelOrderTraversal(root): if root is None: return queue = [] queue.append(root) while len(queue) > 0: print(queue[0].data) node = q...
def toTwoComp(n): s = bin(n & int("1"*16, 2))[2:] return ("{0:0>%s}" % (16)).format(s) def fromTwoComp(n): temp = n[:1] num = "" if int(temp): for x in n[1:]: if x == "1": num = num + "0" else: num = num + "1" ...
_.subdomain_matching _.static_folder Meta csrf csrf_class csrf_secret csrf_time_limit confirm get_user _.user catch_all bad_gateway page_not_found
''' 70-Crie um programa que leia o nome e o preço de vários produtos.O programa deverá perguntar se o usuário quer continuar.No final mostre: A)Qual o total gasto na compra. B)Quantos produtos custam mais de R$1000,00. C)Qual é o nome do produto mais barato. ''' totalcompras=contproduto=menor=contador=0 nomemaisbarato=...
l1 = ["Bhindi","Aloo","Chopsticks","Chowmein"] i = 1 # for item in l1: # if i%2 != 0: # print(f"Please buy {item}") # i+=1 for index,item in enumerate(l1): if index%2==0: # even 0 se start print(f"Please buy {item}")
""" Programa para calculo de IMC e idade. """ print('=' * 40) print() print('Caro ussuario colocar "." no lugar ","') print('-' * 40) nome = str(input('Qual é o seu nome? ')) ano_nasc = int(input('Em que ano você nasceu? ')) altura = float(input('Qual é a sua altura? ')) peso = float(input('Qual é o seu peso?(kg)')) a...
{ "targets": [ { "target_name": "trusted", "dependencies": [ "deps/wrapper/wrapper.gyp:wrapper", ], "sources": [ "src/node/main.cpp", "src/node/helper.cpp", "src/node/stdafx.cpp", ...
# Dungeon Game """ Challenge 1 It would be a 2 dimensional maze game We would put the player in a random room in the grid We would also put a monster in a random room in the grid We would out a door in a random room in the grid The player would then move around the grid to find the door Don’...
# timeout class Solution: def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]: ans = [0] * len(puzzles) words_cache = [] for word in words: word_set = set(word) if len(word_set) <= 7: words_cache.append(word_set) ...
""" Common constants for Pipeline. """ AD_FIELD_NAME = 'asof_date' ANNOUNCEMENT_FIELD_NAME = 'announcement_date' CASH_FIELD_NAME = 'cash' BUYBACK_ANNOUNCEMENT_FIELD_NAME = 'buyback_date' DAYS_SINCE_PREV = 'days_since_prev' DAYS_TO_NEXT = 'days_to_next' NEXT_ANNOUNCEMENT = 'next_announcement' PREVIOUS_ANNOUNCEMENT = 'pr...
''' urlycue's private modules ''' type(1 or 0 @ 0) # Python >= 3.5 is required
with open ("testcopy.txt", "r") as test_copy: chunk_size = 10 read_data = test_copy.read(chunk_size) while len(read_data) > 0: print(read_data) read_data = test_copy.read (chunk_size)
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Dusan Klinec, ph4r05, 2018 def collect(*args, **kwargs): pass def mem_free(*args, **kwargs): return 1000 def mem_alloc(*args, **kwargs): return 100
def part01(input, slope_right, slope_down): total = 0 pos = 0 for i in range(0, len(input), slope_down): if input[i][pos] == "#": total += 1 pos = (pos + slope_right) % len(input[i]) return total def part02(input): return part01(input, 1, 1) * part01(input, 3, 1) * part0...
def meme1(): return str( bytes( list( map( lambda i: i + 48, [ int("49"), int("3c", 16), int("60"), int(str(-16)), int("...
""" aoe2record-to-json utility functions. """ def is_record(path: str) -> bool: """ Is filename a record file? :param (str) path: User-supplied filename. :return: True if filename is valid record file; otherwise False. :rtype: bool """ return path.find("..") == -1 def record(path: str) ...
# encoding: utf-8 def lcs(maintext, comparedtext): #LCS的计算函数 #建立算法矩阵 matrix = [''] * (len(maintext) + 1) for index_MT in range(len(matrix)): matrix[index_MT] = [''] * (len(comparedtext) + 1) #若ai = bj,则LCS(i, j) = LCS(i - 1, j - 1) + 1 #若ai≠bj,则LCS(i,j)=Max(LCS(i-1,j-1),LCS(i-1...
# /app/models.py class Family: def __init__(self): pass def get_tree(self): """ Return tree of all family members """ pass def jsonify(self): pass class Person: def __init__(self): pass def get_profile(self): """ ...
# https://leetcode.com/problems/all-possible-full-binary-trees/description/ # # algorithms # Medium (64.1%) # Total Accepted: 3k # Total Submissions: 4.7k # beats 87.00% of python submissions # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # ...
""" Description : You will write a function that take a List in parameters and return a dictionary with the element of the List as Key, and the number of occurrences as value. The dictionary output must be sorted by value. Then the function will display the sum of all the items. If the list is ...
def is_valid(input_line: str) -> bool: min_max, pass_char, password = input_line.split(' ') min_count, max_count = [int(i) for i in min_max.split('-')] pass_char = pass_char.rstrip(':') min_valid = (password[min_count-1] == pass_char) max_valid = (password[max_count-1] == pass_char) ret_val =...