content
stringlengths
7
1.05M
class Solution(object): def firstMissingPositive(self, nums): size = len(nums) for i in range(size): v = nums[i] if v<1 or v > size: nums[i]=size+10 for i in range(size): v = abs(nums[i]) if v >0 and v<=size and nums[v-1]>0: ...
# -*- coding: utf-8 -*- class DbRouter(object): external_db_models = ['cdr', 'numbers'] def db_for_read(self, model, **hints): """ Use original asterisk Db tables for read """ if model._meta.model_name.lower() in self.external_db_models: return 'asterisk' ...
a = (2, 5, 4) b = (5, 8, 1, 2) c = a + b d = b + a print(a) print(b) print(c) print(len(c)) print(c.count(5)) #quantas vezes esta aparecendo o número 5 dentro de c. print(c.index(8)) #em que posição está o número 8. print(d)
{ "targets": [ { "target_name": "index" } ] }
def countingSort(array): size = len(array) output = [0] * size count = [0] * 10 for i in range(0, size): count[array[i]] += 1 for j in range(1,10): count[j] += count[j-1] a = size-1 while a >= 0: output[count[array[a]]-1] = array[a] count[arra...
# Uses python3 def calc_fib(n): fib_nums = [] fib_nums.append(0) fib_nums.append(1) for i in range(2, n + 1): fib_nums.append(fib_nums[i - 1] + fib_nums[i - 2]) return fib_nums[n] n = int(input()) print(calc_fib(n))
# -*- coding: utf-8 -*- """ State engine for django models. Define a state graph for a model and remember the state of each object. State transitions can be logged for objects. """ #: The version list VERSION = (2, 0, 1) #: The actual version number, used by python (and shown in sentry) __version__ = '.'.join(map(st...
#Narcissistic Number: (find all this kinds of number fromm 100~999) #example: 153 = 1**3 + 5**3 + 3**3 #................method 1............................ # for x in range(100, 1000): # digit_3 = x//100 # digit_2 = x%100//10 # digit_1 = x%10 # if x == digit_3**3 + digit_2**3 + digit_1**3: # ...
""" Copyright 2021 - Giovanni (iGio90) Rocca 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, publish, dist...
status = True print(status) print(type(status)) status = False print(status) print(type(status)) soda = 'coke' print(soda == 'coke') print(soda == 'pepsi') print(soda == 'Coke') print(soda != 'root beer') names = ['mike', 'john', 'mary'] mike_status = 'mike' in names bill_status = 'bill' in names print(mike_status) ...
def pytest_assertrepr_compare(op, left, right): # add one more line for "assert ..." return ( [''] + ['---'] + ['> ' + _.text for _ in left] + ['---'] + ['> ' + _.text for _ in right] ) def pytest_addoption(parser): parser.addoption('--int', type='int') def ...
def solution(s): answer = [] str_idx = 0 for cont in s: if cont.isalpha() == True: if str_idx % 2 == 0: answer.append(cont.upper()) else: answer.append(cont.lower()) str_idx = str_idx + 1 else: ...
MAX_ROWS_DISPLAYABLE = 60 MAX_COLS_DISPLAYABLE = 80 cmap_freq = 'viridis' cmap_grouping = 'copper' # 'Greys' grouping_text_color = 'white' grouping_text_color_background = 'grey' grouping_fontweight = 'bold'
h = int(input("请输入总头数:")) f = int(input("请输入总脚数:")) if(f % 2 != 0): f = int(input("请输入总脚数(必须是偶数):")) def fun1(h, f): rabbits = f/2-h chicken = h-rabbits if(chicken < 0 or rabbits < 0): return '无解' return chicken, rabbits def fun2(h, f): for i in range(0, h+1): if(2*i + 4*(h-i...
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ for s in [*open(0)][1:]: n,m=map(int,s.split()) print(0-(-n*m)//2)
""" Problem: Given a non-empty array, return true if there is a place to split the array so that the sum of the numbers on one side is equal to the sum of the numbers on the other side. canBalance([1, 1, 1, 2, 1]) → true canBalance([2, 1, 1, 2, 1]) → false canBalance([10, 10]) → true """ def canBalance(arr): """...
# Implement division of two positive integers without using the division, # multiplication, or modulus operators. Return the quotient as an integer, # ignoring the remainder. def division(divident, divisor): quotient = 0 if divident == 0: return 0 elif divisor == 0: raise ZeroDiv...
class AccelerationException(Exception): def __init__(self, message='This is neither acceleration nor deceleration... Go away and program Java, BooN'): self.message = message super().__init__(self.message) class NoMemberException(Exception): def __init__(self, message='This truck is not a convoy...
class InvalidValueError(Exception): pass class NotFoundError(Exception): pass
numConv = conv = 0 while(conv != 4): decimal = int(input('Digite o número decimal: ')) print(''' 1 - Converter para binário 2 - Converter para hexadecimal 3 - Converter para octal 4 - Sair ''') conv = int(input('Escolha uma opção: ')) if(conv == 1): numConv = format(decimal, "b") p...
c = get_config() c.ContentsManager.root_dir = "/root/" c.NotebookApp.allow_root = True c.NotebookApp.ip = '0.0.0.0' c.NotebookApp.open_browser = False c.NotebookApp.port = 8888 # Comment out this line or first hash your own password #c.NotebookApp.password = u'sha1:1234567abcdefghi' c.ContentsManager.allow_hidden = Tru...
r,c=map(int,input('enter number of rows and columns of matrix: ').split()) m1=[] m2=[] a=[] print('<<<<< enter element of matrix1 >>>>>') for i in range(r): l=[] for j in range(c): l.append(int(input(f"enter in m1[{i}][{j}]: "))) m1.append(l) print('<<<<< enter element of matrix2 >>>>>') for i in range(r): l=[] ...
## Find peak element in an array class Solution: def findPeakElement(self, nums: List[int]) -> int: ## Iterative Binary Search l, r = 0, len(nums)-1 while l<r: mid = (l+r)//2 if nums[mid] > nums[mid+1]: r = mid ...
class Solution: def numberOfWeeks(self, milestones: List[int]) -> int: k = sorted(milestones,reverse = True) t = sum(k) - k[0] if k[0] <= t+1: return sum(k) else: return 2*t+ 1
# from geometry_msgs.msg import PoseStamped # from geometry_msgs.msg import TwistStamped # from autoware_msgs.msg import DetectedObjectArray # from derived_object_msgs.msg import ObjectArray # from carla_msgs.msg import CarlaEgoVehicleStatus # from grid_map_msgs.msg import GridMap PERCISION = 4 """ Ego: pos: (x, y...
class FilterModule(object): ''' Ansible core jinja2 filters ''' def filters(self): return { 'infer_address' : self.infer_address } def infer_address(self, hostname, hostvars): for t in ('ansible_ssh_host', 'ansible_host', 'inventory_hostname'): if t in hos...
def check_log(recognition_log): pair = recognition_log.split(",") filename_tested = pair[0].split("/")[-1] filename_result = pair[1].split("/")[-1] no_extension_tested = filename_tested.split(".")[0] no_extension_result = filename_result.split(".")[0] check = no_extension_tested == no_extensio...
class ResponseError(Exception): """Raised when the bittrex API returns an error in the message response""" class RequestError(Exception): """Raised when the request towards the bittrex API is incorrect or fails"""
class GetTalk: def __init__(self, words): self.words = words def get_message(self, item): message = self.words[item] return message def get_talk(self, msg, *args): zero_message = False for item in self.words: if item in msg: message = self.get_message(item) zero_message = True return ...
per_cent = {'ТКБ': 5.6, 'СКБ': 5.9, 'ВТБ': 4.28, 'СБЕР': 4.0} for k, v in per_cent.items(): per_cent[k] = round(v * m) # умножаем каждое значение из словаря на вводимое число print("Сумма, которую вы можете заработать: ", list(per_cent.values())) my_max_val = 0 for k,v in per_cent.items(): if v > m...
def cw_distance(az1: float, az2: float) -> float: """ Calculates the 'clockwise' distance between two azimuths, where 0 = North and the direction of increasing angle is clockwise. :param az1: Azimuth 1. :type az1: float :param az2: Azimuth 2. :type az2: float :returns: The angular dista...
#!/usr/bin/env python3 def mod_sum(n): return sum([x for x in range(n) if (x % 3 == 0) or (x % 5 == 0)])
class Detector(object): """detection algorithm to be implemented by sub class input parameters: self and frame to be worked with Must return frame after being processed and radius""" def __init__(self): """init function""" pass def detection_algo(self, frame): """To b...
def display(summary, *args): args = list(args) usage = "" example = "" details = "" delimiter = "=" try: usage = args.pop(0) example = args.pop(0) details = args.pop(0) except IndexError: # End of arg list pass for x in range(1, len(summary)): ...
# -*- coding: utf-8 -*- ''' Created on Mar 12, 2012 @author: hathcox Copyright 2012 Root the Box 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/lice...
print(" _________ _____ ______ _________ ____ ______ ___________ ________ _________ ") print(" | | | | / \ | | | | | ") print(" | | | | /______\ | |...
def Cron_Practice_help(): helpHand = """Hey There Some useful commands - fab - To Favorite Questios for Today tasks - To see the questions that are scheduled for today compile - To compile the tasks into a CSV File""" print(helpHand) def Cron_Practice_invalid(): print("Sorry Invalid Command !") Cron_Pract...
# Write your code here n,k = [int(x) for x in input().split()] l = [] while n > 0 : a = int(input()) l.append(a) n -= 1 while(l[0] <= k) : l.pop(0) l = l[::-1] while (l[0] <= k) : l.pop(0) #print(l) print(len(l))
numero = int(input('Digite um número: ')) basedec = int(input('Qual base de conversão você deseja? \n 1 - Biário \n 2 - Octal \n 3 - Hexadecimal \n ')) if basedec == 1: print("A coversão de {} para binario é : {}".format(numero, bin(numero)[2:])) elif basedec == 2: print('A conversão de {} para octal é : {}'.f...
def find_2020th_number_spoken(starting_numbers): num_list = [] starting_numbers = [ int(num) for num in starting_numbers.split(',') ] for i in range(0, 2020): #print(f'i:{i}, num_list: {num_list}') if i < len(starting_numbers): #print(f'Still in starting numbers') num...
# -*- encoding: utf-8 -*- { "name": "合同模块", "version": "8.0.0.1", "description": """ 总包合同和分包合同 """, "author": "OSCG", "website": "http://www.wisebond.net/", "category": "YD", 'depends': [ 'base', 'product', 'purchase', 'workflow_info', 'wise_pr...
# used for template multi_assignment_list_modal class MultiVideoAssignmentData: def __init__(self, name, count, video_id, set_id): self.name = name self.count = count self.video_id = video_id self.set_id = set_id
first_number= 1 sec_number= 2 sum= 0 while (first_number < 4000000): new= first_number + sec_number first_number= sec_number sec_number= new if(first_number % 2== 0): sum= sum+first_number print(sum)
start_position = { (1, 2): "y", (1, 3): "", (1, 5): "y'", (1, 6): "y2", (2, 1): "z' y'", (2, 3): "z'", (2, 4): "z' y", (2, 6): "z' y2", (3, 1): "x y2", (3, 2): "x y", (3, 4): "x", (3, 5): "x y'", (4, 2): "z2 y'", (4, 3): "z2", (4, 5): "z2 y", (4, 6): "x2", (5, 1): "z y", (5, 3): "z", (5, 4): "z y'",...
sink_db = 'gedcom' sink_tbl = { "person": "person", "family": "family" }
# # Copyright (c) 2017-2018 Joy Diamond. All rights reserved. # @gem('Sapphire.Combine') def gem(): require_gem('Sapphire.Parse') require_gem('Sapphire.SymbolTable') variables = [ 0, # 0 = copyright ] query = variables.__getitem__ write = ...
class Solution(object): def checkPossibility(self, nums): """ :type nums: List[int] :rtype: bool """ is_modified = False for i in xrange(len(nums) - 1): if nums[i] > nums[i + 1]: if is_modified: return False ...
"""The module's version information.""" __author__ = "Tomás Farías Santana" __copyright__ = "Copyright 2021 Tomás Farías Santana" __title__ = "airflow-dbt-python" __version__ = "0.11.0"
def diag(kp): nk = [] for x in xrange(len(kp)): l = [] for y in xrange(len(kp)): l.append(kp[y][x]) nk.append("".join(l)) return tuple(nk) def parse_line(line): left, right = line.strip().split(" => ") a = tuple(left.split("/")) b = right.split("/") return a, b def parse_input(puzzle_input...
EXPECTED_RESPONSE_OF_JWKS_ENDPOINT = { 'keys': [ { 'kty': 'RSA', 'n': 'tSKfSeI0fukRIX38AHlKB1YPpX8PUYN2JdvfM-XjNmLfU1M74N0V' 'mdzIX95sneQGO9kC2xMIE-AIlt52Yf_KgBZggAlS9Y0Vx8DsSL2H' 'vOjguAdXir3vYLvAyyHin_mUisJOqccFKChHKjnk0uXy_38-1r17' ...
# # Modify `remove_html_markup` so that it actually works! # def remove_html_markup(s): tag = False quote = False quoteSign = '"' out = "" for c in s: # print c, tag, quote if c == '<' and not quote: tag = True elif c == '>' and not quote: tag = ...
features_dict = { "Name":{ "Description":"String", "Pre_Action":''' ''', "Post_Action":''' ''', "Equip":''' ''', "Unequip":''' ''' }, "Dual Wielding":{ "Description":"You can use this weapon in your Off Hand (if availab...
tiles = [ # track example in Marin Headlands, a member of Bay Area Ridge Trail, a regional network # https://www.openstreetmap.org/way/12188550 # https://www.openstreetmap.org/relation/2684235 [12, 654, 1582] ] for z, x, y in tiles: assert_has_feature( z, x, y, 'roads', {'highway': ...
""" production_settings.py ~~~~~~~~ 生产环境配置项(高优先级) 先根据配置文件需要, 设置环境变量: e.g.:: cp scripts/etc-profile.d-ffpyadmin.sh /etc/profile.d/ffpyadmin.sh chmod +x /etc/profile.d/ffpyadmin.sh source /etc/profile.d/ffpyadmin.sh :author: Fufu, 2019/9/2 """ ########## # CORE #######...
class Readfile(): def process(self, utils, logger): filenames = utils.check_input() words = [] for filename in filenames: with open(utils.indir + filename, 'r') as f: for line in f: words.append(line.strip()) return words
# -*- coding: utf-8 -*- # Copyright (C) 2009-2010, Luis Pedro Coelho <luis@luispedro.org> # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # Software Distributed under the MIT License ''' Value types: An hierarchy of value types. Hierarchy: vtype |- numeric | |-ordinal | | |- ordinalrange | | ...
"""Module entrypoint.""" def main() -> None: """Execute package entrypoint.""" print("Test") if __name__ == "__main__": main()
""" Дан список целых чисел. Требуется “сжать” его, переместив все ненулевые элементы в левую часть списка, не меняя их порядок, а все нули - в правую часть. Порядок ненулевых элементов изменять нельзя, дополнительный список использовать нельзя, задачу нужно выполнить за один проход по списку. Распечатайте полученный сп...
dis = float(input('Qual é a distância da sua viagem? ')) print('Você está prestes a começar uma viagem de {:.1f}km'.format(dis)) if dis <= 200: preço = dis * 0.50 print('E o preço da sua passagem será R${:.2f}'.format(preço)) else: preço = dis * 0.45 print('E o preço da sua passagem será de R${:.2f}'.fo...
def letter_to_number(letter): if letter == 'A': return 10 if letter == 'B': return 11 if letter == 'C': return 12 if letter == 'D': return 13 if letter == 'E': return 14 if letter == 'F': return 15 else: return int(letter) def int_to_...
def returned(reduction): if reduction is not None: return r""" Returns ------- torch.Tensor If `reduction` is left as default {} is taken and single value returned. Otherwise whatever `reduction` returns. """.format( reduction ) return r""" Returns ------- torch....
p = int(input()) total = 0 numbers = [] for i in range(p): cod, quant = input().split(' ') cod = int(cod) quant = int(quant) if(cod == 1001): total = quant*1.50 elif(cod==1002): total = quant*2.50 elif(cod==1003): total = quant*3.50 elif(cod==1004): total = q...
""" Code examples for common DevOps tasks cmd.py : Running comand line utils from python script archive.py : tar/zip archives management """ __author__ = "Oleg Merzlyakov" __license__ = "MIT" __email__ = "contact@merzlyakov.me"
ENV_NAMES = [ "coinrun", "starpilot", "caveflyer", "dodgeball", "fruitbot", "chaser", "miner", "jumper", "leaper", "maze", "bigfish", "heist", "climber", "plunder", "ninja", "bossfight", ] HARD_GAME_RANGES = { 'coinrun': [5, 10], 'starpilot': [1.5...
# Use binary search to find the key in the list def binarySearch(lst, key): low = 0 high = len(lst) - 1 while high >= low: mid = (high + low) // 2 if key < lst[mid]: high = mid - 1 elif key == lst[mid]: return mid else: low = mid + 1 ...
# https://leetcode.com/problems/partition-to-k-equal-sum-subsets/ # By Jiapeng # Partition problem using DFS # Runtime: 132 ms, faster than 47.77% of Python3 online submissions for Partition to K Equal Sum Subsets. # Memory Usage: 13.8 MB, less than 86.54% of Python3 online submissions for Partition to K Equal Sum Sub...
#Alian Colors #2 alian_color = 'green' if alian_color == 'green' or alian_color == 'yellow' or alian_color == 'red': print("You just earned 5 points.") else: print("You just earned 10 points.")
# Archivo: objetos_clases.py # Autor: Javier Garcia Algarra # Fecha: 25 de enero de 2017 # Descripción: Mini introudccion OOP en Python class Person: def __init__(self, name): self.name = name def saluda(self): print('Hola, me llamo', self.name) def cambia_nombre(self, nuevo_no...
class Solution: # @param {integer[]} nums # @return {integer} def removeDuplicates(self, nums): n = len(nums) if n <=1: return n i= 0 j = 0 while(j < n): if nums[j]!=nums[i]: nums[i+1] = nums[j] i += 1 ...
canMega = [3,6,9,15,18,65,80,94,127,130,142,150,181,208,212,214,229,248,254,257,260,282,302,303,306,308,310,319,323,334,354,359,373,376,380,381,384,428,445,448,460,475,531,719] megaForms = [6,150] def findMega(dex): if dex in canMega: if dex in megaForms: return "This Pokemon has multiple Mega Evolutions." els...
alien_color = 'green' print("alien_color = " + alien_color) if alien_color == 'green': print("You earned 5 points!") elif alien_color == 'yellow': print("You earned 10 points!") else: print("You earned 15 points!") alien_color = 'yellow' print("\nalien_color = " + alien_color) if alien_color == 'green': ...
COL_TIME = 0 COL_OPEN = 1 COL_HIGH = 2 COL_LOW = 3 COL_CLOSE = 4 def max_close(candles): c = [x[COL_CLOSE] for x in candles] return max(c)
# Author : Nekyz # Date : 29/06/2015 # Project Euler Challenge 1 def sum_of_multiple_of_3_and_5(number: int) -> int: result = 0 for num in range(0, number): if num % 3 == 0: result += num elif num % 5 == 0: result += num return result print("#################...
""" idx 0 1 2 3 4 5 6 7 n = 8 elm 1 1 2 3 0 0 0 0 i res 1 0 0 2 3 0 0 4 5 0 0 fake_len = n + zeros j """ class Solution: def duplicateZeros(self, arr: List[int]) -> None: ...
def can_build(env, platform): return True def configure(env): pass def get_doc_classes(): return [ "VoxelBuffer", "VoxelMap", "Voxel", "VoxelLibrary", "VoxelTerrain", "VoxelLodTerrain", "VoxelStream", "VoxelStreamFile", "VoxelStreamBlockFiles", "VoxelStreamRegionFile...
fields = [ ["#bEasy#k", 211042402], ["Normal", 211042400], ["#rChaos#k", 211042401] ] # Zakum door portal s = "Which difficulty of Zakum do you wish to fight? \r\n" i = 0 for entry in fields: s += "#L" + str(i) + "#" + entry[0] + "#l\r\n" i += 1 answer = sm.sendSay(s) sm.warp(fields[answer][1]) sm.dispose()
class MEAPIUrls: COLLECTION_STATS = 'https://api-mainnet.magiceden.io/rpc/getCollectionEscrowStats/' COLLECTION_INFO = 'https://api-mainnet.magiceden.io/collections/' COLLECTION_LIST = 'https://api-mainnet.magiceden.io/all_collections' COLLECTION_LIST_STATS = 'https://api-mainnet.magiceden.io/rpc/getAgg...
# http://codeforces.com/problemset/problem/318/A n, k = map(int, input().split()) if k <= (n + 1) / 2: print(k * 2 - 1) else: print(int(k - n / 2) * 2)
class Solution: def isPerfectSquare(self, num: int) -> bool: i = 1 while i * i < num: i += 1 return i * i == num
''' import math r=input(">>") s=2*r*math.sin(math.pi/5) Area=5*s*s/(4*math.tan(math.pi/5)) print(Area) ''' ''' import math x1,y1,x2,y2=input(">>") x3,y3,x4,y4=math.radians(x1),math.radians(y1),math.radians(x2),math.radians(y2) d=6371.01*math.acos(math.sin(x3)*math.sin(x4)+math.cos(x3)*math.cos(x4)*math.cos(y3-y4)) prin...
# coding: UTF-8 a = 10 b = 20 print("init value:") print("a : {} | b : {}".format(a, b)) print("Comparison Symbol:") print("a == b : {}".format(a == b)) #等于 - 比较对象是否相等 print("a != b : {}".format(a != b)) #不等于 - 比较两个对象是否不相等 #print("a <> b : {}".format(a <> b)) #不等于 - 比较两个对象是否不相等(python 3.x被取消) print("a > b : {}".forma...
# -------------- # Code starts here # creating lists class_1 = [ 'Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio' ] class_2 = [ 'Hilary Mason', 'Carla Gentry', 'Corinna Cortes' ] # concatinating lists new_class = class_1 + class_2 # looking at the resultant list print(new_class) # appending 'Pet...
class OslotsFeature(object): def __init__(self, api, metaData, data): self.api = api self.meta = metaData self.data = data[0] self.maxSlot = data[1] self.maxNode = data[2] def items(self): maxSlot = self.maxSlot data = self.data maxNode = self...
class Solution: # Function to remove 2 chars by given index of the first char def del_substr(i, s): return s[:i] + s[i+2:] def romanToInt(self, s: str) -> int: # Roman numeral mapping roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} # S...
"""Integration of psycopg2 with coroutine framework """ # Copyright (C) 2010-2020 Daniele Varrazzo <daniele.varrazzo@gmail.com> # All rights reserved. See COPYING file for details. __version__ = '1.0.2'
""" This is the "fizzbuzz" module. The module supplies one function, fizzbuzz(), which is the classic coding test looking for factors of 3 and 5. For example: >>>fizzbuzz(15) "FizzBuzz!" """ def fizzbuzz(x): assert int(x), "Must be a number" assert (x >= 0), 'Number must be greater than or equal to 0' i...
# Configuration file for jupyter-notebook. ## Whether to allow the user to run the notebook as root. c.NotebookApp.allow_root = True ## The IP address the notebook server will listen on. c.NotebookApp.ip = '*' ## Whether to open in a browser after starting. The specific browser used is # platform dependent and dete...
'''Desenvolva um programa que leia o primeiro termos e a razao de uma PA. No final, mostre os 10 primeiros termos dessa progressao. Pesquisar sobre progressao aritmetica.''' print('=' * 50) frase = '10 TERMOS DE UMA PA' print(frase.center(50,' ')) print('=' * 50) termo = int(input('Primeiro Termo: ')) razao = int(inp...
class Solution: # Built-in function ''' def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ return bin(int(a, 2) + int(b, 2))[2:] ''' # Think binary as decimal way def addBinary(self, a, b): """ :type ...
{ "targets": [ { "target_name": "node-xed", "cflags!": ["-fno-exceptions"], "cflags_cc!": ["-fno-exceptions"], "sources": [ "cpp/node-xed.cpp" ], "include_dirs": [ "<!@(node -p \"require('node-addon-api')...
# Program to Add Two Integers def isNumber(num): if(type(num) == type(1)): return True else: return False def add(num1, num2): if(isNumber(num1) & isNumber(num2)): return num1 + num2 else: return "we only accept numbers." # Test cases print(add(1, 2)) print(add("hola",...
def is_valid(r: int, c: int): global n return (-1 < r < n) and (-1 < c < n) n = int(input()) matrix = [[int(x) for x in input().split()] for _ in range(n)] tokens = input() while tokens != "END": tokens = tokens.split() cmd = tokens[0] row = int(tokens[1]) col = int(tokens[2]) val = int(...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/9/20 10:02 # @Author : Peter # @Des : # @File : Callback # @Software: PyCharm def msg(msg, *arg, **kw): print("---" * 60) print("callback -------> {}".format(msg)) print("---" * 60) if __name__ == "__main__": pass
class CounterStat: new = int @staticmethod def apply_diff(x, y): return x + y class SetStat: new = set class Diff: def __init__(self, added=set(), removed=set()): self.added = added self.removed = removed def invert(self): self.added, ...
class Solution: def heightChecker(self, heights: List[int]) -> int: new_heights = sorted(heights) count = 0 for i in range(len(heights)): if heights[i] != new_heights[i]: count += 1 return count
# -*- coding: utf-8 -*- A_INDEX = 0 B_INDEX = 1 C_INDEX = 2 D_INDEX = 3 def main(): values = input().split() a = int(values[A_INDEX]) b = int(values[B_INDEX]) c = int(values[C_INDEX]) d = int(values[D_INDEX]) if b > c and d > a and c + d > a + b and c > 0 and d > 0 and a % 2 == 0: pri...
numero1 = input('digite o primeiro numero: ') numero2 = input('digite o segundo numero: ') soma = float(numero1) + float(numero2) subtrai = float(numero1) - float(numero2) multiplica = float(numero1) * float(numero2) dividi = float(numero1) / float(numero2) print('o resultado da soma é: ' + str(soma)) print('o resul...
""" https://leetcode.com/problems/reverse-words-in-a-string-iii/ Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1: Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc" Note: In the string...
# The realm, where users are allowed to login as administrators SUPERUSER_REALM = ['super', 'administrators'] # Your database mysql://u:p@host/db SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:Pa55w0rd@localhost:5432/privacy_idea' # This is used to encrypt the auth_token SECRET_KEY = 't0p s3cr3t' # This is used to en...
class Solution(object): def canCompleteCircuit(self, gas, cost): """ :type gas: List[int] :type cost: List[int] :rtype: int """ # https://discuss.leetcode.com/topic/5088/my-ac-is-o-1-space-o-n-running-time-solution-does-anybody-have-posted-this-solution ls = l...