content
stringlengths
7
1.05M
def calculate_pi(n_terms: int) -> float: numerator: float = 4.0 denominator: float = 1.0 operation: float = 1.0 pi: float = 0.0 for _ in range(n_terms): pi += operation *(numerator/denominator) denominator += 2.0 operation *= -1.0 return pi if __name__ == "__main__": print(calculate_pi(100000)...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author: Anne Philipp (University of Vienna) @Date: March 2018 @License: (C) Copyright 2014 UIO. This software is licensed under the terms of the Apache Licence Version 2.0 which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. """
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1, l2): # create a Answer node and mark it's start node StartAns = Answer = ListNode(0) carry = 0 ...
class Node: def __init__(self, data): self.data = data self.next = None self.prev = None def deleteNode(head_ref, del_): if (head_ref == None or del_ == None): return if (head_ref == del_): head_ref = del_.next if (del_.next != None): del_.next.prev = del_.prev if (del_.prev != None): del_.prev.next...
# Windows functions with NLP data # A. Load the data # 1. Load the dataframe df = spark.read.load('sherlock_sentences.parquet') # Filter and show the first 5 rows df.where('id > 70').show(5, truncate=False) # 2. Split and explode text # Split the clause column into a column called words split_df = clauses_df.select...
# Listen # Eine Liste ist ein eingebauter Datentyp von Python # mit einer Liste kann man in einer Variablen mehrere Werte speichern und mit einem Index darauf # zugreifen # Hier legen wir uns eine leere Liste an neue_liste = [] # mit den eckigen Klammern wird eine Liste angelegt # jetzt füllen wir sie, indem wir mehre...
''' The MIT License (MIT) Copyright (c) 2016 WavyCloud 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 without limitation the rights to use, copy, modify, merge, p...
"""This problem was asked by Apple. Gray code is a binary code where each successive value differ in only one bit, as well as when wrapping around. Gray code is common in hardware so that we don't see temporary spurious values during transitions. Given a number of bits n, generate a possible gray code for it. For exa...
""" Contains code no longer used but kept for review/further reuse --- imports need to be re-added --- """ def determine_disjuct_modules_alternative(src_rep): """ Potentially get rid of determine_added_modules and get_modules_lst() """ findimports_output = subprocess.check_output(['findimports', src_rep]) findim...
class Endereco: def __init__(self, rua="", bairro="", numero="", cidade="", estado="", cep=""): self.rua = rua self.bairro = bairro self.numero = numero self.cidade = cidade self.estado = estado self.cep = cep
""" --- Day 6: Memory Reallocation --- A debugger program here is having an issue: it is trying to repair a memory reallocation routine, but it keeps getting stuck in an infinite loop. In this area, there are sixteen memory banks; each memory bank can hold any number of blocks. The goal of the reallocation routine is...
# Question Link : https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/572/week-4-december-22nd-december-28th/3581/ class Solution(object): def numDecodings(self, s): """ :type s: str :rtype: int """ n = len(s) dp = [0] * n if s[0] != '0'...
input = open('input', 'r').read().strip() input = [list(map(int, r)) for r in input.splitlines()] h, w = len(input), len(input[0]) def neighbours(x, y): return [(p, q) for u in range(-1, 2) for v in range(-1, 2) if 0 <= (p := x+u) < h and 0 <= (q := y+v) < w] def step(m): m = [[n+1 for n in r] ...
''' Automatically set `current_app` into context based on URL namespace. ''' def namespaced(request): ''' Set `current_app` to url namespace ''' request.current_app = request.resolver_match.namespace return {}
# *-* coding:utf-8 *-* """Module states Amapa""" def start(st_reg_number): """Checks the number valiaty for the Alagoas state""" divisor = 11 if len(st_reg_number) > 9: return False if len(st_reg_number) < 9: return False if st_reg_number[0:2] != "03": return False ...
#!/usr/bin/env python class AssembleError(Exception): def __init__(self, line_no, reason): message = '%d: %s' % (line_no, reason) super(AssembleError, self).__init__(message)
#Boolean is a Data Type in Python which has 2 values - True and False print (bool(0)) #Python will return False print (bool(1)) #Python will return True print (bool(1.5)) #Pyton will return True print (bool(None)) #Python will return False print (bool('')) #Python will return False
n = int(input()) count = 0 for i in range(1, n + 1): if i < 100: count += 1 else: s = str(i) if int(s[1]) - int(s[0]) == int(s[2]) - int(s[1]): count += 1 print(count)
l1 = list(range(10)) new_list = [x*x + 2*x + 1 for x in l1] print(l1) print(new_list)
class Solution: def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) if n < 2: return n dp_ = [1] * n for idx, num in enumerate(nums): for i in range(idx-1, -1, -1): if nums[i] < n...
# md5 : 2cdb8e874f0950ea17a7135427b4f07d # sha1 : 73b16f132eb0247ea124b6243ca4109f179e564c # sha256 : 099b17422e1df0235e024ff5128a60571e72af451e1c59f4d61d3cf32c1539ed ord_names = { 3: b'mciExecute', 4: b'CloseDriver', 5: b'DefDriverProc', 6: b'DriverCallback', 7: b'DrvGetModuleHandle', 8: b'Get...
""" Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. Try to do this in one pass. """ # Definition f...
dados = int(input()) pontos = input() pontos = pontos.split(' ') luisa = 0 antonio = 0 pessoa = 0 for vez in pontos: pessoa += 1 if pessoa == 3: pessoa = 1 if pessoa == 1: luisa += int(vez) elif pessoa == 2: antonio += int(vez) if int(vez) == 6 and pessoa == 1: pe...
def getCountLetterString(input): # get range space_index = input.find(" ") range = input[0:space_index] hyphen_index = input.find("-") start = range[0:hyphen_index] end = range[hyphen_index + 1:] # get letter colon_index = input.find(":") letter = input[space_index + 1:colon_index] ...
l = [0] def expChar(idx, c): global l if c == 'S': return elif c == 'D': l[idx] = l[idx]**2 return else: l[idx] = l[idx]**3 return def special(idx, c): global l if c == '*': l[idx] *= 2 l[idx-1] *= 2 else: l[idx] *= -1 def sol...
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/own_data.py', '../_base_/schedules/schedule_1x_own_data.py', '../_base_/default_runtime.py' ] # optimizer optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) load_from = 'https://download.openmmlab.com/mmdetection/...
# https://leetcode.com/problems/number-of-digit-one/ class Solution: def countDigitOne(self, n: int) -> int: result = threshold = 0 divisor = limit = 10 while n // limit > 0: limit *= 10 while divisor <= limit: div, mod = divmod(n, divisor) result...
#desafio 35: Analisando triângulo V1.0 Para construir um triângulo é necessário que # a medida de qualquer um dos lados seja menor que a soma das medidas dos outros dois # e maior que o valor absoluto da diferença entre essas medidas. # | b - c | < a < b + c # | a - c | < b < a + c # | a - b | < c < a + b print('\33[1...
height = float(input("enter your height in m: ")) weight = float(input("enter your weight in kg: ")) bmi = weight/(height**2) if bmi <= 18.5 : print(f"you bmi is {bmi}, you are underweight") elif bmi <=25 : print(f"you bmi is {bmi}you have a normal weight") elif bmi <= 30 : print(f"you bmi is {bmi...
# -*- coding: utf-8 -*- """ Created on Thu Mar 17 09:27:36 2016 @author: tih """ def Accounts(Type=None): User_Pass = { 'NASA': ['', ''], 'GLEAM': ['', ''], 'FTP_WA': ['', ''], 'MSWEP': ['', ''], 'VITO': ['', '']} Selected_Path = User_Pass[Type] return(Selected_Path)
script_create_table_tipos = lambda dados = {} : """ DROP TABLE IF EXISTS Tipos; CREATE TABLE Tipos ( id int NOT NULL PRIMARY KEY, nome text NOT NULL DEFAULT 'pokemon' ); """ script_insert_table_tipos = lambda dados = {} : """INSERT INTO Tipos (id, nome) VALUES (?, ?);""" dados_padrao_tabel...
n, k = map(int,input().split()) cnt = 0 prime = [True]*(n+1) for i in range(2,n+1,1): if prime[i] == False: continue for j in range(i,n+1,i): if prime[j] == True: prime[j] = False;cnt+=1 if cnt == k: print(j);break
class TrackData(): def __init__(self): self.trail_data = None # common dictionary, which is mutable self.camera_id = None self.trail_num = 0 self.file_name = None self.feat_list = [] self.mean_feat = None self.height = None self.map_time_stamp = []...
def sum_iter(numbers): total = 0 for n in numbers: total = total + n return total def sum_rec(numbers): if len(numbers) == 0: return 0 return numbers[0] + sum_rec(numbers[1:])
with open('data.txt') as f: data = f.readlines() data = [int(i.rstrip()) for i in data] incr = 0 for idx, val in enumerate(data): if idx == 0: print(data[0]) continue if data[idx-1] < data[idx]: incr += 1 print(f"{data[idx]} increase") else: print(f"{data[idx]}"...
#!/usr/bin/python3 def this_fails(): x = 1/0 try: this_fails() except ZeroDivisionError as err: print('Handling run-time error: ', err)
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def mergeTrees(self, t1, t2): def recurse(a1, a2): if a1 == None: return a2 if a2 == None: return a1 ...
# -*- coding: utf-8 -*- class Config(object): DEBUG = False TESTING = False DATABASE_URI = ('postgresql+psycopg2://' 'taxo:taxo@localhost:5432/taxonwiki') ASSETS_DEBUG = False ASSETS_CACHE = True ASSETS_MANIFEST = 'json' UGLIFYJS_EXTRA_ARGS = ['--compress', '--mangle'] ...
buttons_dict = {1: [r"$|a|$", "abs"], 2: [r"$\sqrt{a}$", "sqrt"], 3: [r"$\log$", "log"], 4: [r"$\ln$", "ln"], 5: [r"$a^b$", "power"], 6: [r"$()$", "brackets"], 7: [r"%", "percent"], 8: [r"$=$", "equals"], 9: [r"$\lfloor{a}\rfloor$", "floor"], 10: [r"$f(x)$", "...
default_ingredient_list = ['lentils', 'kale', 'shallots', 'swiss cheese', 'anchovies', 'Quiche', 'cashew nut', 'Waffles', 'chicken liver', 'parsley', 'babaganoosh', 'Toast', 'bouillon', 'hamburger', 'hoisin sauce', 'chaurice sausage', 'fennel', 'curry', 'clams', '...
"""type_traits.py We need to assess if a string can be converted to int or float. This module provides simple tests is_<type>. """ def is_float(val): try: return float(val) - val == 0 except: return False return False def is_int(val): try: return int(val) - val == 0 except...
# coding:utf-8 # example 04: double_linked_list.py class Node(object): def __init__(self, val=None): self.val = val self.prev = None self.next = None class DoubleLinkedList(object): def __init__(self, maxsize=None): self.maxsize = maxsize self.root = Node() sel...
def trinomial(cfg,i,j,k) : #function t=trinomial(i,j,k) #% Computes the trinomial of #% the three input arguments ...
for x in range(65,70): for y in range(65,x+1): print(chr(x),end='') print() """ # p[attern A BB CCC DDDD EEEEE """
salario = float(input('Qual o salário de contribuição? ')) if salario <= 1045.00: desc = 0.075 * salario elif salario > 1045.00 and salario <= 2089.60: desc = ((salario - 1045) * 0.09) + (1045 * 0.075) elif salario > 2089.60 and salario <= 3134.40: t = salario - 2089.60 desc = (t * 0.12) + ((2089...
# -*- coding: utf-8 -*- name = 'tbb' version = '2017.0' def commands(): appendenv('LD_LIBRARY_PATH', '{root}/lib/intel64/gcc4.7') env.TBBROOT.set('{root}') env.TBB_LIBRARIES.set('{root}/lib/intel64/gcc4.7') env.TBB_INCLUDE_DIR.set('{root}/include')
#!/usr/bin/env python3 # _*_ coding: utf-8 _*_ """ --------------------------------- @Time : 2017/12/7 15:22 @Author : yuxy @File : return_func.py @Project : PythonSyntax ---------------------------------- """ def lazy_sum(*args): def sum(): ax = 0 for n in args: ax += n ...
budget = float(input()) season = input() if budget <= 100: destination = 'Bulgaria' money_spent = budget * 0.7 info = f'Hotel - {money_spent:.2f}' if season == 'summer': money_spent = budget * 0.3 info = f'Camp - {money_spent:.2f}' elif budget <= 1000: destination = 'Balkans' mon...
# -*- coding: utf-8 -*- # ------------- Cantidad de segundos que has vivido ------------- # Definición de variables anios = 30 dias_por_anio = 365 horas_por_dia = 24 segundos_por_hora = 60 # Operación print (anios * dias_por_anio * horas_por_dia * segundos_por_hora)
"""W3C Document Object Model implementation for Python. The Python mapping of the Document Object Model is documented in <...>. This package contains the following modules: minidom -- A simple implementation of the Level 1 DOM with namespace support added (based on the Level 2 specification). """
# 1.定义类:定义静态方法 class Dog(object): @staticmethod def info_print(): print('这是一个静态方法') # 2.创建对象 wangcai = Dog() # 3.用类和实例分别调用静态方法 wangcai.info_print() Dog.info_print()
FiboList , Flag = [0,1] , True """ This Function, at first we create a array of -1's to check fibonacci data's and store them in it. Then each time we call the fibonacci function (Recursion). Flag is for understanding that we need to create a new arr or we call the function recursively. """ def fibonacci_1(n...
''' 6. 有这样一个字典d = {"chaoqian":87, “caoxu”:90, “caohuan”:98, “wuhan”:82, “zhijia”:89} 1)将以上字典按成绩排名 ''' d = {"chaoqian":87, "caoxu":90, "caohuan":98,"wuhan":82,"zhijia":89} print(sorted(d.items(),key = lambda x :x[1],reverse =True))
def solution(movements): horizontal, vertical = 0, 0 for move in movements: direction, magnitude = move.split(' ') if direction == "forward": horizontal += int(magnitude) elif direction == "down": vertical += int(magnitude) elif direction == "up": ...
stop_words = ['dey', 'awfar', 'wey', 'wan', 'shey', 'sabi', 'i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'chop', 'beta', 'molenu', 'his', 'himself', 'she', 'her', 'hers', 'herself', 'it', 'its','eni', 'duro', ...
class Solution: def combine(self, n: int, k: int) -> List[List[int]]: if k <= 0 or n < k: return [] res_lst = [] def dfs(i, curr_lst): if len(curr_lst) == k: res_lst.append(curr_lst) for value in range(i, n+1): dfs(value+1,...
# -*- coding: utf-8 -*- __version__ = "0.2.4" __title__ = "pygcgen" __summary__ = "Automatic changelog generation" __uri__ = "https://github.com/topic2k/pygcgen" __author__ = "topic2k" __email__ = "topic2k+pypi@gmail.com" __license__ = "MIT" __copyright__ = "2016-2018 %s" % __author__
""" Default status.html resource """ class StatusResource: def on_get(self, req, resp): pass
# -*- coding: utf-8 -*- """ Created on Fri Nov 13 13:02:55 2015 @author: magusverma """ def reached_limit(current, limit): for i in range(len(current)): if current[i] != limit[i]-1: return False return True def increment(current, limit): for i in range(len(current)-1,-1,-1): i...
class GraphEdgesMapping: def __init__(self, first_dual_edges_mapping, second_dual_edges_mapping): self._first = first_dual_edges_mapping self._second = second_dual_edges_mapping @property def size(self): return self._first.shape[0] @property def first(self): ret...
class Solution: def binary_find_last(self, nums, target): """ this is find the last data """ low = 0 hight = len(nums)-1 first = True while low <= hight: mid = (hight-low)//2+low if nums[mid] == target: return mid ...
#!/usr/bin/env python3 data = open("in").read().split("\n\n") data = list(map(lambda x: x.split("\n"), data)) for i in range(len(data)): # todo this is stupid data[i] = list(filter(lambda x: x != '', data[i])) tot = 0 tot2 = 0 for d in data: a = set("".join(d)) tot += len(a) tota = 0 for q in a: ...
#operate with params OP_PARAMS_PATH = "/data/params/" def save_bool_param(param_name,param_value): try: real_param_value = 1 if param_value else 0 with open(OP_PARAMS_PATH+"/"+param_name, "w") as outfile: outfile.write(f'{real_param_value}') except IOError: print("Failed t...
# Hello! World! print("Hello, World!") # Learning Strings my_string = "This is a string" ## Make string uppercase my_string_upper = my_string.upper() print(my_string_upper) # Determine data type of string print(type(my_string)) # Slicing strings [python is zero-based and starts at 0 and not 1] print(my_string[0:4]) pri...
class Solution: def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: self.ret = [] self.counts = collections.Counter(candidates) nums = [k for k in set(sorted(candidates))] self.Backtrack(nums, target, [], 0) return self.ret def Backtrack(sel...
""" Instructions: 1. Create a class named ReversedString that inherits from StringOperations class 2. Implement the function reverse 3. reverse function should be a one liner function that returns the reverse string to_be_reversed 4. Instantiate the class ReversedString 5. Print to show your function implementation res...
# Function that detects cycle in a directed graph def cycleCheck(vertices, adj): visited = set() ancestor = set() for vertex in range(vertices): if vertex not in visited: if dfs(vertex, adj, visited, ancestor)==True: return True return False # Recursive dfs funct...
def writeHigh(b, value): return (b & 0x0f) | (value << 4) def readHigh(b): return (b & 0xf0) >> 4 def writeLow(b, value): return (value) | (b & 0xf0) def readLow(b): return b & 0x0f b = 0x00 # A的位置1 b = writeLow(b, 1) while readLow(b) <= 9: b = writeHigh(b, 1) while readHigh(b) <= 9: ...
# DROP TABLES USERS_TABLE = "users" SONGS_TABLE = "songs" ARTISTS_TABLE = "artists" TIME_TABLE = "time" SONGS_PLAY_TABLE = "songplays" songplay_table_drop = f"DROP TABLE IF EXISTS {SONGS_PLAY_TABLE};" user_table_drop = f"DROP TABLE IF EXISTS {USERS_TABLE};" song_table_drop = f"DROP TABLE IF EXISTS {SONGS_TABLE};" art...
# ********************************************************************************** # # # # Project: SkinAnaliticAI # # ...
class Config(object): SECRET_KEY = "CantStopAddictedToTheShinDigChopTopHeSaysImGonnaWinBig" HOST = "0a398d5f.ngrok.io" SHOPIFY_CONFIG = { 'API_KEY': '<API KEY HERE>', 'API_SECRET': '<API SECRET HERE>', 'APP_HOME': 'http://' + HOST, 'CALLBACK_URL': 'http://' + HOST + '/insta...
#!/usr/bin/python # -*- coding: utf-8 -*- __version__ = "3.0.0" __author__ = "Amir Zeldes" __copyright__ = "Copyright 2015-2019, Amir Zeldes" __license__ = "Apache 2.0 License"
frase = str(input('Digite uma frase?').lower().strip()) print('Na Frase há: {} letra A.'.format(frase.count('a'))) print('Ela aparece pela primeira vez em {}.'.format(frase.find('a')+1)) print(' Ela aparece pela ultima vez em {}'.format(frase.rfind('a')+1))
# 对可变对象进行测试 a = 10 b = 20 c = [a] d = c a = 15 print(c) c = [10,20] print(d) print(id(c),id(d))
DEV = { "SERVER_NAME": "dev-api.materialsdatafacility.org", "API_LOG_FILE": "deva.log", "PROCESS_LOG_FILE": "devp.log", "LOG_LEVEL": "DEBUG", "FORM_URL": "https://connect.materialsdatafacility.org/", "TRANSFER_DEADLINE": 3 * 60 * 60, # 3 hours, in seconds "INGEST_URL": "https://dev-api....
inputDoc = open("input.txt") docLines = inputDoc.readlines() inputDoc.close() # PART 1 # Find two numbers that add up to 2020 and multiply them correct1 = [] for line in docLines: line = int(line.replace("\n", "")) for lineTwo in docLines: lineTwo = int(lineTwo.replace("\n", "")) if line + line...
"""Contains the class for a problem instance.""" class AgglutinatingRolls(): """Define a class for a problem instance.""" def __init__(self, instance: dict): """Initialize an object.""" self.rolls_a = instance.get('rolls_a', []) self.rolls_b = instance.get('rolls_a', []) # co...
class InvalidApiKeyError(Exception): def __init__(self): self.message = "The API key you inserted isn't valid" class InvalidCityNameError(Exception): def __init__(self): self.message = "Couldn't find any city with this name or code. Please check again."
# # PySNMP MIB module GWPAGERMIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GWPAGERMIB # Produced by pysmi-0.3.4 at Wed May 1 13:20:45 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:...
class Solution: def findErrorNums(self, nums): """ :type nums: List[int] :rtype: List[int] """ nnums = set(nums) N = len(nums) missing = N*(N+1)/2-sum(nnums) #計算缺失值 duplicated = sum(nums) - sum(nnums) #計算重複值 ...
a = input() b = input() c = input() print(a[0] + b[1] + c[2])
def evalRPN(tokens: List[str]) -> int: stack = [] #make a stack to hold the numberes and result calculation for char in tokens: #iterate through the tokens if char not in "+*-/": #if token is not an operator then it is a number so we add to stack stack.append(int(cha...
# Lv-677.PythonCore name_que = input("Hello. \nWhat is your name? \n") print ("Hello, ", name_que) age_que = input("How old are you? \n") print ("Your age is: ", age_que) live_que = input(f"Where do u live {name_que}? \n") print("You live in ", live_que)
# Royals and suits jack = 11 queen = 12 king = 13 ace = 14 spades = 's' clubs = 'c' hearts = 'h' diamonds = 'd' ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king, ace] suits = [spades, clubs, hearts, diamonds] # Hands straight_flush = 'Straight flush' quads = 'Four of a kind' full_house = 'Full house' flush = '...
s = '' while True: try: s+= input() except: break r = ['a', s.count('a')] for i in range(98, 123): n = s.count(chr(i)) if n > r[1]: r[0] = chr(i) r[1] = n elif n == r[1]: r[0] += chr(i) print(r[0])
def Run(filepath): with open(filepath) as input: measurements = list(map(int, input.read().split('\n'))) print('Day 1') Part1(measurements) Part2(measurements) def Part1(measurements): increases = 0 previousDepth = None for depth in measurements: #Increment if this isn't t...
""" O(n^min(k, n-k)) """ class Solution: def combine(self, n: int, k: int) -> List[List[int]]: result = [] self.dfs(list(range(1, n + 1)), k, [], result) return result def dfs(self, arr, k, path, result): if k < 0: return if k == 0: result.appen...
my_email = 'twitterlehigh2@gmail.com' my_password = 'kB5-LXX-T7w-TLG' # my_email = 'twitterlehigh@gmail.com' # my_password = 'Lehigh131016'
''' Given an integer, write a function that reverses the bits (in binary) and returns the integer result. Understand: 417 --> 267 167 --> 417 0 --> 0 Plan: Use bin() to convert the binary into a string. Use bracket indexing to reverse the order. Use int() to convert it into a decimal number. ''' def csReverseInte...
class Solution: def solve(self, board: List[List[str]]) -> None: m, n = len(board), len(board and board[0]) def explore(i, j): board[i][j] = "S" for x, y in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)): if 0 <= x < m and 0 <= y < n and board[x][y] == "O":...
# -*- coding: utf-8 -*- """ To-Do application """ def add(todos): """ Add a task """ pass def delete(todos, index=None): """ Delete one or all tasks """ pass def get_printable_todos(todos): """ Get formatted tasks """ pass def toggle_done(todos, index): """ ...
class SerVivo: def __init__(self): self._vivo = True def is_vivo(self): return self._vivo def morir(self): self._vivo= False #Se pone _ porque es una clase abstracta y solo se puede usar en esta clase #Se pone __ porque es una clase privada solo la usa cada clase
dias = int(input("Quantos dias alugados? ")) km = float(input("Quantos Kms rodados: ")) preco = 60 * dias + 0.15 * km print(f'O total a pagar é de R${preco:.2f}')
#!/usr/bin/env python3 with open("main.go", encoding="utf-8") as file: # FIXME usage = "\n".join(file.read().split("\n")[13:-1]) with open("tools/_README.md", mode="r", encoding="utf-8") as file: readme = file.read() readme = readme.replace("<<<<USAGE>>>>", usage) with open("README.md", mode="w", enco...
def binary_search(the_list, target): lower_bound = 0 upper_bound = len(the_list) - 1 while lower_bound <= upper_bound: pivot = (lower_bound + upper_bound) // 2 pivot_value = the_list[pivot] if pivot_value == target: return pivot if pivot_value > target...
""" User ACL ======== """ _schema = { # Medlemsnummer 'id': {'type': 'integer', 'readonly': True }, 'acl': {'type': 'dict', 'readonly': False, 'schema': {'groups': {'type': 'list',...
""" The cost of stock on each day is given in an array A[] of size N. Find all the days on which you buy and sell the stock so that in between those days your profit is maximum. """ def sellandbuy(a, n): result = [] start = 0 end = 1 while end < n: if a[start] < a[end] and a[end] > a[end-...
def solution(n): sum = 0 print(list(str(n))) for i, j in enumerate(list(str(n))): sum+=int(j) return sum print(solution(11))
""" LeetCode Problem: 108. Convert Sorted Array to Binary Search Tree Link: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ Language: Python Written by: Mostofa Adib Shakib Time Complexity: O(N) Space Complexity: O(N) """ class Solution: def sortedArrayToBST(self, nums: List[int]) -> Tre...
class Solution: def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ x = [i == '1' for i in a[::-1]] y = [i == '1' for i in b[::-1]] r = [] carry = False if len(x) > len(y): y += [False] * (len(x) - len(...