content
stringlengths
7
1.05M
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # def getIntersectionNode(self, A, B): # myset = set() # tmp = A # while tmp.next is not None: # myset.add(tmp) # tmp = tmp....
""" This folder contains Python functions that check the data type and format of input variables. """ __credits__ = "ICOS Carbon Portal" __license__ = "GPL-3.0" __version__ = "0.1.0" __maintainer__ = "ICOS Carbon Portal, elaborated products team" __email__ = ['info@icos-cp.eu', 'karoli...
# https://practice.geeksforgeeks.org/problems/count-possible-triangles-1587115620/1 #User function Template for python3 class Solution: #Function to count the number of possible triangles. def findNumberOfTriangles(self, arr, n): #code here # Sort array and initialize count as 0 ...
class Solution: def shiftingLetters(self, s: str, shifts: List[int]) -> str: ans = [] for i in reversed(range(len(shifts) - 1)): shifts[i] += shifts[i + 1] for c, shift in zip(s, shifts): ans.append(chr((ord(c) - ord('a') + shift) % 26 + ord('a'))) return ''.join(ans)
# -*- coding:utf-8 -*- # class RandomListNode: # def __init__(self, x): # self.label = x # self.next = None # self.random = None class Solution: # 返回 RandomListNode def Clone(self, pHead): # write code here if pHead is None: return None hashset = d...
#!/usr/bin/env python3 with open("facts.txt", "r") as dead_language1: latin_1 = dead_language1.read() print("Following was read from the file:", latin_1)
################################################### # header_dialogs.py # This file contains declarations for dialogs # DO NOT EDIT THIS FILE! ################################################### speaker_pos = 0 ipt_token_pos = 1 sentence_conditions_pos = 2 text_pos = 3 opt_token_pos = 4 sentence_consequences_pos = 5 ...
n = int(input()) l = [] for _ in range(n): e = list(map(int, input().split())) l.append(e) c = 1 l = sorted(l) for i in range(n-1): if l[i][0] != l[i+1][0]: c = c+1 print(c)
# # PySNMP MIB module Juniper-ISIS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-ISIS-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:03:15 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
env = None pg = None # __pragma__ ('opov') def init(environ): global env, pg env = environ pg = env['pg'] tests = [test_sprite, test_sprite_group] return tests def test_sprite(): Sprite = pg.sprite.Sprite Group = pg.sprite.Group g = [Group() for i in range(20)] sx,...
# -*- coding: utf-8 -*- def func(comp_list, cr_list): ord_list = sorted(cr_list) return comp_list.count('+'), comp_list.count('-'), ord_list n = int(input()) comp_list = [] cr_list = [] for _ in range(n): comp, cr = map(str, input().split()) comp_list.append(comp) cr_list.append(cr) p_comp,...
a = [] a.append(2) a.append(4) a.append(6) print(a[0:4]) #print(a)
class Piece(object): ''' two type of players: black and white ''' def __init__(self, player): self.player = player class Grid(object): ''' each grid has one color: W - white / B - black a grid may point to a piece object ''' def __init__(self, color, piece = None): self.color = color self.piece = piece ...
sıfır = "\033[0m" # Öntanımlı hale getir kalin = "\033[1m" # Kalın yazı egik = "\033[2m" # Eğik yazı aCizili = "\033[4m" # Altı Çizili tRenk = "\033[7m" # Ters renkler gYazi = "\033[8m" # Gizli yazı uCizili = "\033[9m" # Üstü çizili # Renkli yazı siyah = "\033[;30m" # Siyah kirmizi = "\033[;31m" # Kırmızı yesil = "...
#List items are indexed and you can access them by referring to the index number: #Example #Print the second item of the list: thislist = ["apple", "banana", "cherry"] print(thislist[1])
# 所有型号包括的要素打乱重组 # 品牌父类分为两大类 电机 和 驱动器 # 孙类才是品牌 # 所有电机型号四要素 # 1.系列 # 2.电压-编码器位数-转速-减速机? # 3.功率 # 4.键槽刹车-定制款尾缀? class brand: """docstring for YASKAWA""" def __init__(self,model): super(brand, self).__init__() self.model = model yaskawa_I = ['SGM','SGMP','SGMCS','SGMM','SGME','SGML'] yaskaw...
# # PySNMP MIB module EMPIRE-APACHEMOD (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EMPIRE-APACHEMOD # Produced by pysmi-0.3.4 at Mon Apr 29 18:48:20 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
#Operadores Aritméticos soma = 1 + 1 subtracao = 1 - 1 multiplicacao = 1 * 1 divisao = 1 / 1 divisao_inteira = 1 // 1 expoente = 1**1 #Operadores de Comparação comparacao = 4 > 5 #Isso vai ser FALSE outra_comparacao = 6 == 6 #Isso vai ser TRUE #Veremos os outros em exercicios mais para frente
for number in range(4): print(f"The for loop has run for {number} time(s)") print("\n") for number in range(10, 15): print(f"The for loop has run for {number} time(s)") print("\n") for number in range(20, 30, 2): print(f"The for loop has run for {number} time(s)") print("\n") status = False for number...
""" A sliding window is an abstract concept commonly used in array/string problems. A window is a range of elements in the array/string which usually defined by the start and end indices, i.e. [i, j)[i,j) (left-closed, right-open). A sliding window is a window "slides" its two boundaries to the certain direction. "...
def up(config, database): database.execute('ALTER TABLE ONLY mapped_courses ALTER COLUMN registration_section SET DATA TYPE character varying(255) USING registration_section::varchar(255)') database.execute('ALTER TABLE ONLY mapped_courses ALTER COLUMN mapped_section SET DATA TYPE character varying(255) USING m...
# Write a function that always returns 5 # Sounds easy right? # Just bear in mind that you can't use # any of the following characters: 0123456789*+-/ def unusual_five(): return len('trump')
# code -> {"name": "creaturename", # "desc": "description",} CREATURES = {} SOLO_CREATURES = {} GROUP_CREATURES = {} with open("creatures.csv") as f: lines = f.readlines() for line in lines: if line.strip() == "": continue parts = line.strip().split(",") c...
# Copyright 2020 VMware, Inc. # SPDX-License-Identifier: Apache-2.0 PATH = "path" DESCRIPTOR = "descriptor" BEFORE = "@before" AFTER = "@after" DESCRIPTORS = "@descriptors" PARAMS = "@params" POINTER_SEPARATOR = "/" WS_CURRENT_POINTER = "__crp" WS_ENV = "__env" WS_OUTPUT = "_output"
kazu = [3, 7, 0, 1, 2, 2] shin_kazu = 1 for ex in range(1, len(kazu), 2): shin_kazu *= kazu[ex] print(shin_kazu)
def group(list): groups = [] curr = [] for elem in list: if elem in curr: curr.append(elem) elif len(curr) != 0: groups.append(curr) curr = [] curr.append(elem) elif len(curr) == 0: curr.append(elem) if curr != []: groups.append(curr) return groups def main(): print(group([1, 1, 1...
# -*- coding: utf-8 -*- """ Created on Thu Sep 23 14:04:41 2021 @author: Experiment4K """ class Euro2404(object): def __init__(self,inst): self.inst = inst self.inst.serial.timeout = 2 self.inst.serial.baudrate = 9600 def data_info(self,devicenumber):#returns ...
# python3 class Query: def __init__(self, query): self.type = query[0] if self.type == 'check': self.ind = int(query[1]) else: self.s = query[1] class QueryProcessor: _multiplier = 263 _prime = 1000000007 def __init__(self, bucket_count): self...
class Solution: def solve(self, s): s = s.replace('(',' ( ').replace(')',' ) ') tokens = s.split() stack = [] for token in tokens: if token == 'true': if stack and stack[-1] in ['or','and']: if stack[-1] == 'or': ...
""" Algorithmic intervensions for satisfying fairness criteria. There are three families of techniques: 1. **Pre-processing** - Adjust features in the dataset. 2. **In-processing** - Adjust the learning algorithm. 3. **Post-processing** - Adjust the learned classifier. """
print('Descubra o antecessor e o sucessor!') n1 = int(input('Insira o Número: ')) soma = n1 + 1 sub = n1 - 1 print('Antecessor: {} \n Sucessor: {}'.format( sub, soma)) #ou criar uma varial dentro do .format pra deixa-lo mais leve
checkpoint_config = dict(interval=20) # yapf:disable log_config = dict( interval=5, hooks=[ dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook') ]) # yapf:enable custom_hooks = [dict(type='NumClassCheckHook')] dist_params = dict(backend='nccl') log_level = 'INFO' load_from = None...
#!/usr/bin/python3 # suggested time: 10 mins # INSTRUCTIONS: # # Give this class a constructor that prints "hi". # # Give this class a destructor that prints "bye". class Spinner: """ Defining a constructor""" def __init__(self): print("Hi") def __del__(self): print("Bye") Spinner()
######################## #### Initialisation #### ######################## input_ex1 = [] with open("inputs/day6_1.txt") as inputfile: input_ex1 = [int(i) for i in inputfile.readline().strip().split()] ######################## #### Part one #### ######################## def redistribute(memblock): mem...
''' Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. The same repeated number may be chosen from candidates unlimited number of times. Note: All numbers (including target) will b...
class Solution: def thousandSeparator(self, n: int) -> str: s = str(n)[::-1] return ".".join(s[i : i + 3] for i in range(0, len(s), 3))[::-1]
class Solution: def titleToNumber(self, s: str) -> int: length = len(s) num = 0 for i in range(0, length): num += (ord(s[length-i-1]) - ord('A') + 1) * (26 ** i) return num
""" Problem 3. Suppose we rewrite the FancyDivide function to use a helper function. def FancyDivide(list_of_numbers, index): denom = list_of_numbers[index] return [SimpleDivide(item, denom) for item in list_of_numbers] def SimpleDivide(item, denom): return item / denom This c...
""" private public protected """ ################################# # class A: # def __init__(self,yetki): # self.yetki = yetki # self.__gizli = 2 # # __gizli gizli # # __gizli_ gizli # # __gizli__ gizli degil # # _yari_gizli # obj1 = A(1) # print(obj1.yetki) # print(obj1.__gizli) ##################...
def get(event, context): return {"body": "GET OK", "statusCode": 200} def put(event, context): return {"body": "PUT OK", "statusCode": 200}
a=input('Enter a srting: ') i=0 for letters in a: if letters=='a' or letters=='e' or letters=='i' or letters=='o' or letters=='u': i+=1 print("Number of vowels:",i)
class Solution: def lemonadeChange(self, bills: List[int]) -> bool: m5 = 0 m10 = 0 m20 = 0 for b in bills: if b == 5: m5 += 1 elif b == 10: m10 += 1 if m5 >= 1: m5 -= 1 else: ...
t = input() lines = int(input()) columns = int(input()) result = 0 if t == 'Premiere': result = columns * lines * 12 elif t == 'Normal': result = columns * lines * 7.5 elif t == 'Discount': result = columns * lines * 5 print('{0:.2f} leva'.format(result))
def main_pot_winner(hand_txt: str) -> str: """ Extracts the name of the main pot winner Parameters: hand_txt (int): a hand history Returns: winner (str): name of main pot winner or '**[CHOP-CHOP]**' when it's a chop """ ...
""" Number to string map 0 => None 1 => None 2 => A,B,C 3 => D,E,F 4 => G,H,I 5 => J,K,L 6 => M,N,O 7 => P,Q,R,S 8 => T,U,V 9 => W,X,Y,Z Map the number to corresponding character. Example: 23 => AD,AE,AF,BD,BE,BF,CD,CE,CF """ num_letter_map = { "0":None, "1":None, "2":"ABC", "3":"DEF", "4":"GHI", ...
''' https://www.codingame.com/training/easy/prefix-code ''' def find_unique_lengths(inputs: dict) -> set: """ Given a dictionary, return a set of integers representing the unique lengths of the input strings """ return set([len(str(s)) for s in inputs]) n = int(input()) tokens = {} for i in ra...
# Ugg, dummy file to make Github not think this site is written in PHP # that's an insult foo = 'bar' foo = 'bar' foo = 'bar' foo = 'bar' foo = 'bar' foo = 'bar' foo = 'bar' foo = 'bar' foo = 'bar' foo = 'bar' foo = 'bar' foo = 'bar' foo = 'bar' foo = 'bar' foo = 'bar' foo = 'bar' foo = 'bar' foo = 'bar' foo = 'bar' f...
""" @author: David Lei @since: 6/11/2017 https://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-lists/problem Given two lists guaranteed to converge (have same value) find when this occurs. Return the data at the node where this occurs. Both pass :) """ def FindMergeNodeBetter(headA, headB):...
# -*- coding: utf-8 -*- def check_tuple(values): x1,x2,x3 = values try: assert (2*x1 - 4*x2 -x3) == 1 assert (x1 - 3 * x2 + x3) == 1 assert (3*x1 - 5*x2 - 3*x3) == 1 except: return False return True a = (3,1,1,) b = (3,-1,1) c = (13,5,2) d = (13/2,5/2,2) e...
'''Escreva um programa que leia um número inteiro qualquer e pela para o usuárui escolher qual será a base de conversão: - 1 para binário; - 2 para octal; - 3 para hexadecimal''' num = int(input('Digite um número inteiro: ')) print('''Escolha uma das bases para conversão: [1] para Binário [2] para Octal [3] para Hexad...
''' Given a 2D board of characters and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. For example, given the following bo...
#Encrypt Function def encrypt(password): password_li = list(password) encrypted_password = "" for i in password_li: ascii_password_li = chr(ord(i) + 5) encrypted_password = encrypted_password + ascii_password_li print("Your encrypted password is: ") print(encrypted_password) #de...
film_budget = float(input()) statists = int(input()) dress = float(input()) decor_price = 0.1*film_budget if statists > 150: dress_price = (statists*dress) - 0.1*(statists*dress) else: dress_price = statists*dress if decor_price + dress_price > film_budget: print('Not enough money!') print(f'Wingard ne...
class UserQueryError(Exception): def __init__(self, msg): Exception.__init__(self, None) self.msg = msg def __str__(self): return 'User query error: %s' % self.msg
while True: try: n = int(input()) while n != 0: n -= 1 s = int(input()) array1 = list(map(int, input().split()))[:s] array2 = list(input()) count = 0 for i in range(s): if array2[i] == "J" and array1[i]...
class Image: def __init__(self): self.id = 0 self.name = "" self.thumbnail = "" self.url = "" self.upload_time = "" self.upload_user = "" @classmethod def convert_to_images(cls, entity_images): images = [] for entity_image in entity_images: ...
# v. 1.0 # 10.01.2018 # Sergii Mamedov summa = 0 for i in range(3, 1000): if (i % 3 == 0) or (i % 5 == 0): summa += i print(summa)
# https://www.hackerrank.com/challenges/circular-array-rotation/problem # Complete the circularArrayRotation function below. def circularArrayRotation(a, k, queries): return [a[(q-k)%len(a)] for q in queries]
#!/usr/bin/env python """ 6. Parse the following 'show ip bgp summary' output (see link below). From this output, extract the following fields: Neighbor, Remote AS, Up_Down, and State_PrefixRcvd. Also include the Local AS and the BGP Router ID in each row of the tabular output (hint: use filldown for this). Note, i...
frase = 'Curso em Video Python' print(frase[3]) print(frase[3:12]) print(frase[:12]) print(frase[13:]) print(frase[:15]) print(frase[1:15:2]) print(frase[::2]) print(len(frase)) print(frase.count('o')) print(frase.count('o', 0, 13)) print(frase.find('deo')) print(frase.find('Android')) # valor -1 significa que a string...
word = input("Enter a simple word : ") if word[::-1].upper() == word.upper(): print("This word is a palindrome") elif word[::-1].upper() != word.upper(): print("This word is not a palindrome... It prints", word[::-1].upper(), "when reversed.")
""" Retorne true se "talking" for true e "hour" for menor que 7 ou maior que 20. "hour" está em um range 0..23 que será determinado pelo horário da hora atual. """ def parrot_trouble(talking, hour): return talking and (hour < 7 or hour > 20) print(parrot_trouble(True, 6))
#!/usr/bin/python3 def VennSet(mini_answer, ix, big_string): frags = [] clues = [] center_blanks_l = ["_" for c in mini_answer] center_blanks_l[ix-1] = "◯" center_blanks_html = "&puncsp;".join(center_blanks_l) for line in big_string.splitlines(): if not "\t" in line: continue st...
def get_cheapest_cost(rootNode): result = float("inf") stack = [] stack.append((rootNode, rootNode.cost)) seen = set() seen.add(rootNode) while stack: current_node, path_sum = stack.pop() if len(current_node.children) == 0: if path_sum < result: result = path_sum else: ...
"""Quick sort function.""" def quicksort(arr): """.""" if type(arr) is not list: raise TypeError('Input must be a list type.') for i in range(0, len(arr)): if not isinstance(arr[i], (int, str)): raise TypeError('All elements must be either an \ integer or string.')...
# -*- coding: utf-8 -*- class SessionHelper(): def __init__(self, app): self.app = app @property def logged_user_name(self): return self.app.wd.find_element_by_css_selector(".user-info") def open_homepage(self): wd = self.app.wd if wd.current_url.endswith("/mantisbt/m...
''' URL: https://leetcode.com/problems/non-decreasing-array/ Difficulty: Medium Description: Non-decreasing Array Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element. We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for ever...
''' Instructions Write a program in main.py that prints the same notes from the previous lesson using what you have learnt about the Python print function. Warning: The output in your program should match the example output shown below exactly, character for character, even spaces and symbols should be identical, oth...
class Solution: def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]: m = len(nums) n = len(nums[0]) if m * n != r * c: return nums ori = [nums[i][j] for i in range(m) for j in range(n)] ans = [] for i in range(0, len(ori), c): ans.append(ori[i:i+c]) ...
class Solution: def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool: while sx <= tx and sy <= ty: if tx < ty: if sx == tx: return (ty - sy) % sx == 0 else: ty %= tx else: if sy ==...
datasetFile = open("datasets/rosalind_ba1f.txt", "r") genome = datasetFile.readline().strip() print("Find a Position in a Genome Minimizing the Skew") def minSkew(genome): indices = [0] skew = 0 min = 0 for i in range(len(genome)): if genome[i] == 'G': skew += 1 elif genome...
""" Exercício 03 Peça ao usuário para digitar 3 valores inteiros e imprima a soma deles. """ print('Digite três números inteiros para somá-los:\n') num1 = int(float(input('Primeiro número: ').replace(',', '.'))) num2 = int(float(input('Segundo número: ').replace(',', '.'))) num3 = int(float(input('Terceiro número: ')....
def double_pole_fitness_func(target_len, cart, net): def fitness_func(genes): net.init_weight(genes) return net.evaluate(cart, target_len) return fitness_func
""" More simple if Statements Problem # 2 Write a program that inputs two numbers and find whether whether they are equal """ # num1 = input("Enter the first number: ") # 4 # num1 = int(num1) # num2 = input("Enter the second number: ") # 4 # num2 = int(num2) # if num1 == num2: # print("bo...
corpus = open('corpuslimpio.txt','r',encoding='utf8') pos = open('pos.txt','w',encoding='utf8') neg = open('neg.txt','w',encoding='utf8') for line in corpus.readlines(): if line[0] == 'P': pos.write(line[2:]) elif line[0] == 'N': neg.write(line[2:]) corpus.close() pos.close() neg...
class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, value): if self.root is None: self.root = Node(value) else: se...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def tree2str(self, root: TreeNode) -> str: if not root: return '' s = f'{root.va...
""" You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls...
cust="customer1" my_age=int(input("Hello {}, Please confirm your age:".format(cust))) if my_age<18: print("you are minor, you have no entry") if my_age<18:print("you are minor, you have no entry")
p = int(input()) q = int(input()) result=[] for i in range(p,q+1,1): k = i**2 r = k % (10 ** len(str(i))) l = k // (10 ** len(str(i))) if i == int(r)+int(l): result.append(i) result= list(set(result)) result.sort() if len(result) == 0: print ('INVALID RANGE') else: print (' '.join...
C_ANY = 0 # Any length C_ONE = 2 # Only one C_DEF = 4 # Up to 5 C_SAR = 8 # Up to 7 (shifts and rotates) END = 0x60 LDA = 0xA9 LDX = 0xA2 LDY = 0xA0 BIT = 0x24 CMP = 0xC9 CPX = 0xE0 CPY = 0xC0 OPCODES = { 0x00: (1, C_ANY, 0x00, 'BRK'), 0x01: (2, C_ANY, 0x01, 'ORA (nn,X)'), 0x05: (2, C_ANY, 0x02, 'ORA nn')...
# # import calendar # # print(calendar.calendar(2019,w=2,l=1,c=6)) # def showInfo(): # print("1.添加学生\n2.删除学生\n3.修改学生\n4.显示所有学生信息\n5.退出系统\n") # students=[] # while True: # showInfo() # key = int(input("请选择功能(序号):")) # if key == 1: # print("您选择了添加学生信息功能") # stuName = input("请输入学生姓名:") # ...
""" Variables that never change """ __version__ = '0.0.1a' __author__ = 'Seniatical & Daftscientist' __license__ = 'MIT License' USER_AGENT = 'PyPtero <https://github.com/Rapi-Dev/PyPtero> [Version {}]'.format(__version__) USE_SSL = {True: 'https', False: 'http'} REQUEST_TYPES = ('DELETE', 'GET', 'POST', 'PAT...
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
class NonogramError(Exception): """Base class for exceptions in this module.""" pass class LengthError(NonogramError): """Exception raised for unexpected list lengths.""" pass class AxisError(NonogramError): """Exception raised for unexpected axis.""" pass class ClueError(NonogramError): ...
# TODO This is probably the wrong place to put it. class GameContext(object): """ This object will hold the instances required to be passed around. Avoiding the need to pass 40 arguments just in case something down the line needs it. """ def __init__(self): self.player = None self.fa...
class MissingEnvError(Exception): """ An exception raised when looking up a missing environment variable without a default. """ pass
""" constants.py Nicholas Boucher 2020 Contains the constant values utilized in the ElectionGuard protocol. """ # Large prime p P: int = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF93C467E37DB0C7A4D1BE3F810152CB56A1CECC3AF65CC0190C03DF34709AFFBD8E4B59FA03A9F0EED0649CCB621057D11056AE91321...
# TOKENS BOT_TOKEN = "" API_KEY = "" GCS_ENGINE_ID = "" SPOTIFY_ID = "" SPOTIFY_SECRET = "" # PREFIXO PARA USAR COMANDOS BOT_PREFIX = "!" # CORES (você pode mudá-las colocando o código decímal após o "0x") EMBED_COLOR = 0x7DCE82 # ciano EMBED_COLOR_OK = 0x9BE89B # verde EMBED_COLOR_ERROR = 0xFF9494 # vermelho MAX_SO...
''' Merge sort ''' def merge ( lst1 , lst2 ): ''' This function merges 2 lists. :param lst1: :param lst2: :return list 1 merged with list 2: >>> merge ([1, 2, 4, 6] ,[3, 5, 7, 8]) [1, 2, 3, 4, 5, 6, 7, 8] ''' res = [] n1 , n2 = len( lst1 ) , len( lst2 ) i , j = 0 , 0 wh...
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ for _ in [0]*int(input()): a,b,c,d,k=map(int,input().split()) x,y=(a+c-1)//c,(b+d-1)//d print(-1) if x+y>k else print(x,y)
# Runtime: 32 ms # Beats 99.87% of Python submissions # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def middleNode(self, head): """ :type head: ListNode :rtype: ListNode """ ...
# @Rexhino_Kovaci # hash tables we use dictionaries as it is an array whose indexes are obtained using a hash function on the keys # we use 3 collision handling problems: linear, quadratic, double hashing # we are obliged to use ASCII values and divide it by the element of our array/dictionary # declare a dictionary ...
heroes = {hero: [] for hero in input().split(", ")} command = input() while command != "End": hero, item, price = command.split("-") if item not in heroes[hero]: heroes[hero] += [item, price] command = input() for hero, items in heroes.items(): price = [int(item) for item in items if item.isde...
""" Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. Example 1: Input: s = "aa" p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: ...
print('======= DESAFIO 05 =======') n = int(input('Digite um número: ')) print('O antecessor de {} é {}, e seu sucessor é {}.'.format(n, (n-1), (n+1))) # (ou) RESOLUÇÃO: # n = int(input('Digite um número: )) # a = n - 1 # s = n + 1
# -*- coding: utf-8 -*- ''' Para completar os números é necessário obter a soma que as linhas, colunas e diagonais deveriam gerar. Assim a variável "n" irá armazenar este número. Primeiramente é obtida a matriz e feita a soma total dos elementos. Para cada linha, coluna e diagonal é checado se a mesma não possui zero...
def fib(n): if n <= 1: return 1 return fib(n-1) + fib(n-2) def fib2(n,cache={}): if n <= 1: return 1 if n not in cache: cache[n] = fib2(n-1,cache) + fib2(n-2,cache) return cache[n] sum=0 for i in range(1,100): if fib2(i) >= 4000000: break if fib2(i) % 2 == 0: sum+= fib2(i) print(sum)
pw = ph = 500 s = 5 amount = int(pw / s + 4) newPage(pw, ph) translate(pw/2, ph/2) rect(-s, 0, s, s) for i in range(amount): rect(0, 0, s*i, s) rotate(-90) translate(0, s * (i-1)) # saveImage('spiral.jpg')
class Square: def __init__(self, id, x, y, data): self.id = id self.x = x self.y = y self.data = data