content stringlengths 7 1.05M |
|---|
class Utilities:
@staticmethod
def swap(a, b, arr):
arr[a], arr[b] = arr[b], arr[a]
return arr
|
class Solution:
def kidsWithCandies(self, candies: list[int], extraCandies: int) -> list[bool]:
result = list(map(lambda x: True if x+extraCandies >=
max(candies) else False, candies))
return result
# Time Complexity = O(1) |
# AC 26/08/2019 17:58:21 IST #
n = int(input())
print(n)
|
def Range(first, second=None, step=1):
if second is None:
current = 0
end = first
else:
current = first
end = second
while not (current >= end and step > 0
or current <= end and step < 0):
yield current
current += step
def print_space(str):
print("{}".format(str), end=' ')
for i in Range(10):
prin... |
class Info:
"""
Represents more of the metadata associated with the API
output
"""
def __init__(self, **kwargs):
self.seed = kwargs['seed']
self.results = kwargs['results'] # will represent an integer (500 in this case)
self.page = kwargs['page']
self.version... |
#from baconsarnie.io.window import Window
#__all__ = ["io", "Window"]
__all__ = ["io"] |
{
'target_defaults': {
'default_configuration': 'Release',
'configurations': {
'Debug': {
'cflags': ['-g3', '-O0'],
'msvs_settings': {
'VCLinkerTool': {
'GenerateDebugInformation': 'true',
'LinkIncremental': 2
}
}
},
'Releas... |
class Board():
# Initialize Board
def __init__(self):
'''Initialize the tiles with private attributes'''
self.__tiles = list(map(str, range(9)))
# Get tile value
def get_tile(self, index:int):
'''Getter for the tile'''
if self.__tiles[index] not in list(map(str, rang... |
# -*- coding: utf-8 -*-
# if Statements
x = int(input("Please enter an integer: "))
if x < 0:
print('Negative number')
elif x > 0:
print('Positive number')
else:
print('Zero')
# for Statement
words = ['cat', 'window', 'door']
for w in words:
print(w, len(w))
# range(begin=0, end, step) Function
fo... |
# Parsing file using list comprehension
file1 = open("test.txt", "r")
output = [i for i in file1 if "All" in i]
print(output) |
def check_palindrome(strings):
for i in range(int(len(strings)/2)):
if strings[i] != strings[len(strings)-i-1]:
return False
return True
strings = input("Nhap vào chuoi: ")
if(check_palindrome(strings)):
print("Chuoi doi xung")
else:
print("khong la chuoi doi xung")
|
'''
Description : Use Of Forloop With Hardcoded Value
Function Date : 15 Feb 2021
Function Author : Prasad Dangare
Input : Int
Output : str
'''
def display():
print("Output of For loop")
icnt = 0
for icnt in range(10, 1, -1):
print(icnt)
else:
... |
class AuthError(Exception):
"""Authentication error"""
def __init__(self, msg):
super(AuthError, self).__init__(msg)
class DocumentNotFound(Exception):
"""Could not found a requested document"""
def __init__(self, msg):
super(DocumentNotFound, self).__init__(msg)
class UnsupportedTyp... |
# Grocery list class
class GroceryList:
def __init__(self, initial_items=[]):
# Use a set, so that we don't get duplicates
self.grocery_list = set(initial_items)
def add(self, item):
# Use the lower case of the item so we don't get duplicates
self.grocery_list.add(item.lower()... |
{
'includes': [
'common.gypi',
],
'target_defaults': {
'conditions': [
['skia_os != "win"', {
'sources/': [ ['exclude', '_win.(h|cpp)$'],
],
}],
['skia_os != "mac"', {
'sources/': [ ['exclude', '_mac.(h|cpp)$'],
],
}],
['skia_os != "linux"', {
... |
#Escreva um programa que leia um número inteiro maior do
#que zero e devolva, na tela, a soma de todos os seus
#algarismos. Por exemplo, ao número 251 corresponderá
#o valor (2+5+1). Se o número lido não for maior do
#que zero, o programa terminará com a mensagem
#“Número inválido”.
num=int(input("Informe um nume... |
def pares(num):
valores_pares = 0
for n in num:
if n % 2 == 0:
valores_pares += 1
return print(f'{valores_pares} valor(es) par(es)')
def impares(num):
valores_impares = 0
for n in num:
if n % 2 != 0:
valores_impares += 1
return print(f'{valores_impares} ... |
def insertShiftArray(list,val):
list[int(len(list)/2):int(len(list)/2)] = [val]
return list
|
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
c = 0
res = 0
dic = {0:-1}
for i in range(len(nums)):
n = nums[i]
if n == 1 : c += 1
else: c -= 1
if c in dic... |
# No Bugs in Production (NBP) Library
# https://github.com/aenachescu/nbplib
#
# Licensed under the MIT License <http://opensource.org/licenses/MIT>.
# SPDX-License-Identifier: MIT
# Copyright (c) 2019-2020 Alin Enachescu <https://github.com/aenachescu>
#
# Permission is hereby granted, free of charge, to any person ob... |
# This sample tests annotated types on global variables.
# This should generate an error because the declared
# type below does not match the assigned type.
glob_var1 = 4
# This should generate an error because the declared
# type doesn't match the later declared type.
glob_var1 = Exception() # type: str
... |
numbers = [5, 5, 5, 6, 7, 4, 6, 10]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
print(uniques) |
technologies = {}
while True:
line = input()
if "end" == line:
break
technology, courses_tokens = line.split(" - ")
if technology not in technologies:
technologies[technology] = {}
courses_tokens = [(course, int(participants)) for course, participants in
[to... |
def edad(numedades):
edades = []
edades20 = []
n = 0
while n <= (numedades-1):
edades.append(int(input ("Dame una edad: ")))
if edades[n] > 20:
edades20.append(edades[n])
n += 1
edades = tuple(edades)
print ("Tus edades: ", edades)
print ("Las edades mayores a 20 años, son: ", edades20)
nume... |
variavel = 'valor'
def func():
print(variavel)
def func2():
variavel = 'Outro valor'
print(variavel)
func()
func2()
print(variavel)
|
class Solution:
def moveRobot(self, matrix, current_position):
"""
Handles following cases:
if moving results in 0 no result
otherwise returns positions.
"""
# move robot to the right
# or down
down_move = current_position[0] + \
1, curren... |
# Faça um Programa que peça um número e então mostre a mensagem O número informado foi [número].
# Ivo Dias
# Recebe o numero
numero = input("Informe um numero: ")
# Mostra na tela
print("O numero informado foi %s" % numero) |
unicode_type = type(u"")
def ensure_unicode(data, encoding="utf8"):
"""
Ensures that the given string is return as type ``unicode``.
:type data: str or bytes
:param data: String to convert if needed.
:param str encoding: [opt] The encoding to use if needed..
:returns: The given string as type ``... |
# Time: O(h)
# Space: O(1)
# 998
# We are given the root node of a maximum tree: a tree where every node has a value greater than
# any other value in its subtree.
#
# Just as in the previous problem, the given tree was constructed from an list A (root = Construct(A))
# recursively with the following Construct(A) rou... |
"""Collect modules for import."""
__author__ = "David Longo (longodj@gmail.com)"
#from .data import JTNNCollator # noqa: F401 |
#
# PySNMP MIB module ROOMALERT4E-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ROOMALERT4E-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:58:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
dist = 0
speed = 0
lastTime = 0
while(True):
try:
inp = input()
if not inp:
raise ValueError
except ValueError:
break
except EOFError:
break
arr = inp.split(' ')
if (len(arr) == 1):
outp = True
else:
outp = False
time = arr[0].split(':')
currtime = int(time[0])*3600 + in... |
class Solution:
# 1st solution
# O(1) time | O(1) space
def isPowerOfTwo(self, n: int) -> bool:
x = 1
while x < n:
x *= 2
return x == n
# 2nd solution
# O(1) time | O(1) space
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and not (n & n-1) |
'''Crie um programa que leia e mostre
na tela todos os números de 1 até 50
e mostre os números pares'''
print('Contagem de números Pares!!')
for n in range(0, 51, 2):
print(n, end=' ')
|
# coding=utf-8
"""
Tests for gym-acnportal.
TODO: This module copies data from acnportal. Should this instead be
accessed directly from acnportal?
"""
|
'''
# Pass command
for i in range (0,9):
if i == 3:
pass
print (" Pass Here", end = '')
else:
print (f" {i}", end = '')
'''
# String Commands
myString = "India is my country"
myString2 = "I love my India"
print (myString.index("is"))
print (myString.find("is"))
print (myString.isalph... |
# Issue #38 in Python 2.7
# Problem is distinguishing 'continue' from 'jump_back'
# in assembly instructions.
# Here, we hack looking for two jump backs
# followed by the end of the except. This
# is a big hack.
for a in [__name__]:
try:len(a)
except:continue
# The above has JUMP_ABSOLUTE in it.
# This has ... |
App.open("java -jar C:/JabRef-4.2-fat.jar")
wait(30)
click("1529632189350.png")
wait(2)
click("1529632296782.png")
wait(2)
click("1529632312432.png")
wait(2)
click("1529632554435.png")
wait(2)
click("1529632574104.png")
wait(2)
click("1529632589427.png")
wait(2)
click("1529632601277.png")
wait(2)
click("1529632757740.p... |
class Solution:
def makeLargestSpecial(self, S):
"""
:type S: str
:rtype: str
"""
count = i = 0
res = []
for j, ch in enumerate(S):
count += 1 if ch == '1' else -1
if count == 0:
res.append('1' + self.makeLargestSpecial(... |
class Solution:
@staticmethod
def jewels_and_stones(jewels: str, stones: str) -> int:
count = 0
for i in stones:
if i in jewels:
count += 1
continue
return count
J = "z"
S = "ZZ"
solution = Solution()
print(solution.jewels_and_stones(J, S))
|
# -*- coding: utf-8 -*-
# author:lyh
# datetime:2020/7/12 9:55
"""
1513. 仅含 1 的子串数
给你一个二进制字符串 s(仅由 '0' 和 '1' 组成的字符串)。
返回所有字符都为 1 的子字符串的数目。
由于答案可能很大,请你将它对 10^9 + 7 取模后返回。
示例 1:
输入:s = "0110111"
输出:9
解释:共有 9 个子字符串仅由 '1' 组成
"1" -> 5 次
"11" -> 3 次
"111" -> 1 次
示例 2:
输入:s = "101"
输出:2
解释:子字符串 "1" 在 s 中共出现 2 次
示例 3... |
#------------------------SKLEP---------------------------#
#-----------------Spis przedmiotów w sklepie-------------#
#### nazwa # cena # ilość #####
sklep = {1: ['Arbuz', 3.50, 10],
2: ["Banan", 2.99, 2],
3: ["Cebula", 9.99, 1],
4: ["Wisnia", 0.5, 100],
5: ["More... |
'''A simple calculator using a dictionary to look up functions for operators'''
def add(n1, n2): return n1 + n2
def mult(n1, n2): return n1 * n2
opers = {
'+': add,
'*': mult
}
print("Enter expressions like 23 * 10 or 2 - 5")
while True:
expr = input('> ')
if expr:
try:
(op1, op,... |
#read the input test cases into a list (of lists)
test_file = open("input_test_case", "r")
test_file = [element.strip() for element in test_file]
test_case_count = int(test_file[0])
test_cases = [[] for col in range(test_case_count)]; test_case_count = 0
test_file = test_file[2:]
for idx, element in enumerate(test_fi... |
#
# Copyright 2022 Erwan Mahe (github.com/erwanM974)
# 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 agre... |
'''
Bifurcaciones
Estructura.-
if CONDICION:
INSTRUCCIONES
[elif CONDICION:
INSTRUCCIONES
else:
INSTRUCCIONES
]
**Las palabras en mayusculas indican estatutos variables (no siempre son los mismos)
y lo que esta en corchetes es opcional. Puede haber mas de un elif.
'''
#Ejemplos
matricula=... |
# Python program to display the Fibonacci sequence
def fibonacci(n):
if n <= 1:
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
N = input()
if N <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(N):
print(fibonacci(i)) |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 13 06:01:48 2020
@author: azmanrafee
"""
X=[8]
NX=[800]
x0=0
xn=0
azim_div=64
energy_group=1
nu=1
def sigma_scatter(x):
return 0.8
def sigma_trans(x):
return 1.0
def sigma_fis(x):
return 1.0
|
"""Stop words for Cantonese."""
_STOP_WORDS = """
一啲
一定
不如
不過
之後
乜
乜嘢
人哋
但係
你
你哋
佢
佢哋
係
個
其他
冇
再
到
即
即係
原來
去
又
可以
可能
同
同埋
吖
呀
呢
咁
咗
咩
咪
哦
哩
哩個
哩啲
哩度
哩樣
唔
唔使
唔係
啊
啲
喎
喺
喺度
嗯
嗰
嗰個
嗰啲
嗰度
嘅
嘢
噉
噉樣
因為
多
太
好
如果
就
已經
幾
幾多
得
想
應該
成日
我
我哋
或者
所以
最
會
有
有冇
有啲
未
梗係
然之後
由
真係
睇
知
而
而家
自己
要
覺得
話
諗
講
譬如
跟住
返
過
邊個
都
點
點樣
點解
""".strip()... |
__author__ = '''
Dawson Reid (dreid93@gmail.com)
'''
VALID_CURRENCY = ['CAD', 'BTC', 'LTC']
VALID_CURRENCY_PAIRS = ['BTCCAD', 'LTCCAD', 'BTCLTC']
DATE_FORMAT = '%Y-%m-%d'
VALID_WITHDRAW_CURRENCY = ['BTC', 'LTC']
|
"""
Stores information for each dimension of parallelism
"""
class parallelism():
def __init__(self, pp: int, dp: int, mp: int, pp_parts: list, rank_map: dict):
self.pp = pp
self.dp = dp
self.mp = mp
"""
The order of axis is (pp, dp, mp). For example, if dp... |
"""
constants.py
Constants.py é responsável por armazenar qualquer varia´vel fixa utilizada no projeto.
"""
WITAI_KEY = 'ZBH7LRPZAISA7VIM7CNZDG3HJJPRTVTA'
PYOWM_KEY = '48250140b550af15b1537f212d815013'
NEWS_KEY = '281513d9cf5f444da3c010c87cccdd62'
|
''' 5.9 Escreva um programa que leia dois números. Imprima a divisão inteira do
primeiro pelo segundo, assi m como o resto da divisão. Utilize apenas os operadores
de soma e subtração para calcular o resultado. Lembre-se de que podemos entender o
quociente da divisão de dois números como a quantidade de vezes que p... |
# https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square
'''
Time Complexity: O(N)
Space Complexity: O(N)
'''
def count_good_rectangles(rectangles):
max_len, all_max_lens = 0, []
for rec in rectangles:
square_len = min(rec[0], rec[1])
max_len = max(max_len, sq... |
"""Author: Brandon Trabucco
String values for use in the caption machine.
"""
WELCOME_STRING = """
I'm ready to caption images for you.
Please tell me a command, or say help.
"""
HELP_STRING = """
Ask me to navigate,
learn a place,
tell where I am,
look around,
or tell what I see
I currently know {0} places.
Th... |
class UnionFind:
def __init__(self):
self.parent = {}
self.name = {}
def find(self, a):
path = []
while self.parent[a] != a:
path.append(a)
a = self.parent[a]
for p in path:
self.parent[p] = a
return a
def connect(self... |
num_to_word = {
0: '',
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: ... |
# 1.2 Check Permutation:
# Given two strings, write a method to decide if one is a permutation of the other.
# https://github.com/joaomh/Cracking-the-Code-Interview-Python
# My solution
def Permutation(str1, str2):
str1 = str1.lower()
str2 = str2.lower()
for character in str1:
if character is... |
n = int(input())
data = []
for _ in range(n):
x, y = map(str, input().split())
data.append([int(x), y])
sorted_data = sorted(data, key=lambda item : item[0])
for x, y in sorted_data:
print('{0} {1}'.format(x, y)) |
# Função que descobre o maior
def maior (*valor):
print("-=-" * 15)
print("Analisando os valores passados...")
print(f"{valor} Foram informados {len(valor)} ao todo ")
print(f"O maior valor informado foi {max(valor)} ")
print("-=-" * 15)
maior(1, 2, 3, 5) |
# subtracting type dp with sort
class Solution(object):
def combinationSum(self, candidates, target):
candidates.sort()
dp = [[[]]] + [[] for i in xrange(target)]
for i in xrange(1, target + 1):
for number in candidates:
if number > i:
break
... |
"""A list of structured message templates supported by the platform. For unstructured content see content_types"""
class Template(object):
pass
|
def dict_path(d, path):
if not isinstance(path, (list, tuple)):
raise ValueError()
for keys in path:
if type(keys) is not list:
keys = [keys]
value = None
for key in keys:
if key not in d:
continue
value = d[key]
if... |
dias = int(input('Digite a quantidade de dias: '))
horas = int(input('Digite a quantidade de horas: '))
minutos = int(input('Digite a quantidade de minutos: '))
segundos = int(input('Digite a quantidade de segundos: '))
total = segundos + (minutos * 60) + ((horas * 60) * 60) + (((dias * 24) * 60) * 60)
print ('Isso equ... |
# Each line gives the password policy and then the password. The password policy indicates the lowest and highest number of times a given letter must appear for the password to be valid. For example, 1-3 a means that the password must contain a at least 1 time and at most 3 times.
# How many passwords are valid accordi... |
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
result = [[0 for _ in range(len(word2)+1)] for _ in range(len(word1) + 1)]
# update top row
for j in range(1,len(word2)+1):
result[0][j] = 1+ result[0][j-1]
# update first column
for i in rang... |
n = int(input()) # 1
k = int(input()) # 2
x = int(input()) # 3
y = int(input()) # 4
arr = list(map(int, input().split())) # 5
# s = sum(arr[:k+1])
w = 50
if k != 1:
for i in range(n):
... |
print('Calcularemos a seguir a sequencia de Fibonacci') #soma o último e penúltimos termos para criar o prox.
n = int(input('Quantos termos quer ver?'))
T1 = 0 #por padrão começa com 0 e 1!
T2 = 1
print('{} - {}'.format(T1, T2), end='')
cont = 3 #começa no 3 pq o 1º e 2º termo já foram mostrados
while cont <= n:
T3... |
# This is a file which does actually have a variable called 'answers'.
# This file is used in the test_check.py file which tests the check module
answers = 1
|
#1.Introduce boolean type
sunny = True #注意首字母大写
print(1, type(sunny), sunny)
#2.Compare I
number1 = 3
number2 = 5
print(2, number1 < number2) #'number1 < number2' 是一个布尔表达式
#3.Compare II
number1 = 3
number2 = 3
print(3, number1 >= number2)
#4.Compare III
number = 30
boolean = number == 30 #区别'='和'=='
... |
#encoding:utf-8
subreddit = 'MoviePosterPorn'
t_channel = '@MoviePosterTG'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
#
# PySNMP MIB module Juniper-ATM-1483-Profile-CONF (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-ATM-1483-Profile-CONF
# Produced by pysmi-0.3.4 at Wed May 1 14:01:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ve... |
class parent:
def parentmethod(self):
print("Calling Parent Method")
def parentmethod2(self):
print("Calling the second parent method")
class child(parent):
def childmethod(self):
print("Calling the Child Method")
def parentmethod2(self):
print("Modified parent method ... |
# Flip the keys to the values, and the values to the keys
namesAndNumbers = {"Ellis": 123456789, "Roy": 987654321, "Blake": 753159842}
numbersAndNames = {}
for k in namesAndNumbers:
numbersAndNames[namesAndNumbers[k]] = k
print(numbersAndNames) |
# directories path
BASIC_DIR = "~/ECG_Analysis/ECG_data"
ECG_eHEALTH_DATA_DIR = BASIC_DIR + '/eHealth_ECG'
ECG_ID_DATA_DIR = BASIC_DIR + '/ECG-ID/resampled'
ECG_eHEALTH_DATA_DIR = BASIC_DIR + '/eHealth_ECG'
ECG_eHEALTH_TRAIN_DATA_DIR = BASIC_DIR + '/trainECG'
ECG_eHEALTH_TEST_DATA_DIR = BASIC_DIR + '/testECG'
SEGMEN... |
N = int(input())
for i in range(1, 10):
if N % i == 0 and (N // i) < 10:
print("Yes")
break
else:
print("No")
|
# --------------
##File path for the file
file_path
def read_file(path):
file = open (path,'r')
sentence = file.readline()
file.close ()
return sentence
sample_message = read_file (file_path)
print (sample_message)
#Code starts here
# --------------
#Code starts here
message_1 = rea... |
def split_list(big_list , max_split: int):
for i in range(0, len(big_list), max_split):
yield big_list[i: i+max_split]
|
def remove_repetidos(lista):
lista_b = []
for i in lista:
if i not in lista_b:
lista_b.append(i)
lista_b.sort()
return lista_b
def soma_elementos(lista):
return sum(lista)
#print(sum(lista))
def maior_elemento(lista):
#max(lista)
print(max(lista))
lista = [1, 1,... |
def Posicao(a, b, c, d,u, pos):
posicao =""
if pos != 0:
pos = "transversal"
else:
if (a*u[0] + b*u[1] + c*u[2] + d) == 0:
pos = "contida"
else:
pos = "paralela"
return pos |
class JsonObject:
@staticmethod
def decode(json, agent):
return json
@staticmethod
def encode(obj):
return obj
|
#113
# Time: O(n)
# Space: O(h), h is height of binary tree
# Given a binary tree and a sum, find all root-to-leaf paths
# where each path's sum equals the given sum.
#
# For example:
# Given the below binary tree and sum = 22,
# 5
# / \
# 4 8
# / / \
# ... |
#!/usr/bin/python3
qaly = 0
for x in range(int(input())):
a, b = map(float, input().split())
qaly += a*b
print("{0:.3f}".format(qaly))
|
# @Title: 买卖股票的最佳时机 (Best Time to Buy and Sell Stock)
# @Author: 18015528893
# @Date: 2021-02-01 22:11:17
# @Runtime: 792 ms
# @Memory: 29.5 MB
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
dp = [[0, 1] for _ in range(n+1)]
dp[0][0] = 0
dp[0][1] = f... |
class BreakOpportunity:
"""A `GraphicObject` mixin which indicates a break can be performed here.
Some notational constructs are well suited to be placed at line
or page breaks, for example bar lines or grand pauses. Such classes
should subclass this mixin so the flowable container can know this.
... |
#
# PySNMP MIB module IPV6-TUNNEL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IPV6-TUNNEL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:56:52 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
BASEURL = "https://fnbr.co/api"
VALID_IMAGE_TYPES = ['emote','glider','emoji','loading','outfit','pickaxe','skydive','umbrella','misc']
VALID_IMAGE_LIMIT_MIN = 1
VALID_IMAGE_LIMIT_MAX = 15
NONE_TYPE = "none"
ERROR_TYPE = "error"
STATS_TYPE = "stats"
IMAGE_TYPE = "image"
SHOP_TYPE = "shop"
|
# Title: Validate Binary Search Tree
# Runtime: 52 ms
# Memory: 16.6 MB
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Time Complexity: O(n)
# Space Complexity: O(n)
class Solution:
def postOrderTr... |
# RUN: test-output.sh %s
x = 1
def adder():
y = 2
def inner(z):
return x + y + z
return inner(10)
print("Start") # OUTPUT-LABEL: Start
print(adder()) # OUTPUT-NEXT: 13
print("End") # OUTPUT-LABEL: End
|
parameter_lists_copy = [bar for bar in parameter_lists]
for bar in parameter_lists_copy:
if param_index >= len(bar.GetParameters()):
parameter_lists.remove(bar)
|
# example of definitions of names part 3
#global name
X = 11
# access to global name from function
def f():
if __name__ == '__main__':
print(X)
# changing global name X in module
def g():
global X
X = 22
if __name__ == '__main__':
print(X)
def h1():
X = 33 # locale name in functi... |
def gcdRecur(a,b):
'''
a,b:positive integers
returns a positive integer, the GCD of a and b
'''
if b==0:
return a
else:
return gcdRecur(b,a%b)
|
def query_tekst(source, target):
postgreSQL_select_Query = f"SELECT MIN(r.seq) AS seq, " \
f"e.old_id AS id, " \
f"sum(e.distance) AS distance, " \
f"ST_Collect(e.the_geom) AS geom " \
f"FROM pgr_... |
{
"targets": [
{
"target_name": "ledcontrol",
"sources": [ "led-control.cpp", "include/gpio-driver.cpp",
"include/spi-driver.cpp", "include/ws2801-driver.cpp" ],
},
{
"target_name": "spectrum",
"sources": [ "i2c_spectrum.cc" ],
"include_dirs": [
"/usr/include/glib-2.... |
double_qoute_string = "This is a string with double qoute";
single_qoute_string = 'This is a string with single qoute';
three_qoute_string = '''
This is a string with single qoute.
'''
three_double_qoute_string = """
This is a string with three double qoute.
"""
print(double_qoute_string);
print(single_qoute_string... |
def bubble_sort(input_list):
last_position = len(input_list) - 1
made_changes = True
while made_changes:
made_changes = False
for i in range(0, last_position):
if input_list[i] > input_list[i + 1]:
input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i... |
# @Title: 两数相除 (Divide Two Integers)
# @Author: KivenC
# @Date: 2019-01-28 16:51:37
# @Runtime: 64 ms
# @Memory: 6.6 MB
class Solution:
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
sign = dividend >> 31 == divisor >... |
class Solution:
def trap(self, height: List[int]) -> int:
box = 0
left_max = 0
right_max = 0
left = 0
right = len(height)-1
while left<right:
if height[left]<height[right]:
if height[left]>left_max:
left_max = height[lef... |
'''
70. Climbing Stairs
https://leetcode.com/problems/climbing-stairs/
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the to... |
#Exercício 52 – Números primos
#Exercício Python 52: Faça um programa que leia um número inteiro e diga se ele é ou não um número primo.
while True:
num = int(input('Digite um número: '))
p = True
for i in range(2, num + 1, 1):
resto = num % i
if resto == 0:
if i != num:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.