content stringlengths 7 1.05M |
|---|
async def m001_initial(db):
await db.execute(
f"""
CREATE TABLE IF NOT EXISTS tipjar.TipJars (
id {db.serial_primary_key},
name TEXT NOT NULL,
wallet TEXT NOT NULL,
onchain TEXT,
webhook TEXT
);
"""
)
await db.exec... |
# -*- coding: utf8 -*-
# Copyright 2017-2019 NLCI (http://www.nlci.in/fonts/)
# Apache License v2.0
class Charset:
common_name = 'NLCI: Tamil script'
native_name = 'Tamil script'
abbreviation = 'Taml'
key = 0x0B95
glyphs = [
0x0B82, # TAMIL SIGN ANUSVARA
0x0B83, # TAMIL SIGN VISA... |
def run_length_encoding(string: str) -> str:
counter = 0
current_character = None
output = []
for character in string:
if current_character == character:
counter += 1
else:
if current_character:
output.append(current_character + str(counter if c... |
###***********************************###
'''
Grade Notifier
File: refresh_result.py
Author: Ehud Adler
Core Maintainers: Ehud Adler, Akiva Sherman,
Yehuda Moskovits
Copyright: Copyright 2019, Ehud Adler
License: MIT
'''
###***********************************###
class RefreshResult():
def __init__(self, classes, g... |
# try:
# from fake_useragent import UserAgent
#
# ua =UserAgent(verify_ssl=False,use_cache_server=False,cache=False) #禁用ssl
# print(ua.chrome)
#
# except Exception as e:
# print(e)
#
#
# re=[]
#
# count =0
#
# while count!=300:
# re.append(ua.random)
# count+=1
#
# print(re)
user_agents=['Mozi... |
homem = maiores = mulher20 = cont = 0
sexo = escolha = ' '
while True:
cont += 1
print(f'==CADASTRANDO A {cont}ª PESSOA==')
idade = int(input('Quantos anos você tem? '))
if idade >= 18:
maiores += 1
sexo = ' '
while sexo not in 'FM':
sexo = str(input('Qual o seu sexo? [F/M] ')).s... |
#1.SORU
satisMik=500
birimSatisF=20
ciro=5000
i=0
while(ciro<=500000):
ciro=ciro+(satisMik*birimSatisF)
satisMik=satisMik+200
birimSatisF=birimSatisF+10
i=i+1
print("500000 den fazla kar",i,"ayda tamamlanmıştır,")
#2.SORU
sm=10000
satılanurun=500
alınanurun=100
i=0
while True:
... |
'''
key -> value store
any types -> any type
'''
english = {
'apple': 'fruit blah blah',
'apetite': 'desire for something, usually food',
'pluto': 'a gray planet'
}
print(english['apple'])
#print(english['banana']) fails with KeyError
print(english.get('banana')) #handles KeyError and return Non... |
def __is_integer(some_string):
try:
int(some_string)
return True
except:
return False
def compute(expression: str = None) -> int:
stack = []
for element in expression.split():
if __is_integer(element):
stack.append(int(element))
continue
... |
# encoding=utf-8
class Player(object):
'''A basic player with a name and a Bot.
bot may be a subclass of LightCycleBaseBot or a string with its Python
source code.
'''
def __init__(self, name, bot, **kwargs):
for attr, value in kwargs.items():
if not hasattr(self, attr):
... |
"""
Estruturas de decisao: IF e Else (se nao ou caso contrario)
':' no python, substitui o then
a condicao if so depende de resposta True ou Fale, exeplo case 2
"""
#Case 1
idade = int(input('Quantos Anos voce tem?'))
resp = idade >= 18
if resp == True:
print('Voce pode beber a vontade')
if resp == False:
... |
RATE_1MBIT = 0
RATE_250KBIT = 2
RATE_2MBIT = 1
def config():
pass
def off():
pass
def on():
pass
def receive():
pass
def receive_bytes():
pass
def receive_bytes_into():
pass
def receive_full():
pass
def reset():
pass
def send():
pass
def send_bytes():
pass
|
price = 49
txt = "The price is {} dollars"
print(txt.format(price))
txt = "The price is {:.2f} dollars"
print(txt.format(price))
quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))
quantity = 3
itemno = 567
price = 49
... |
# 8 kyu
def reverse_words(s):
return " ".join(reversed(s.split()))
|
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 找到最优子序列的起点就可以了
max_sum = 0
sum = 0
n = len(nums)
val = max(nums)
if val <= 0:
return val
for i in range(n):
sum +... |
class Programa:
def __init__(self,nome,ano):
self._nome = nome.title()
self.ano = ano
self._likes = 0
@property
def likes(self):
return self._likes
def dar_likes(self):
self._likes += 1
@property
def nome(self):
return self._nome
@nome.sett... |
def tower_builder(n_floors):
tower = []
d = '*'
for i in range(1, 2 * n_floors + 1 , 2):
tower.append((d * i).center(2 * i - 1))
return tower
print(tower_builder(3))
|
#
# PySNMP MIB module Netrake-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Netrake-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:16:34 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, 0... |
numbers = [1,2,3,4,5]
numbers_again = [n for n in numbers]
even_numbers = [n for n in numbers if n%2 == 0]
odd_squares = [n**2 for n in numbers if n%2 == 1]
matrix = [[1,2,3], [4,5,6], [7,8,9]]
flattened_matrix = [n for row in x for n in row]
|
'''
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
'''
class Solution(object):
def minPathSum(self, grid):
"""
:type gr... |
# -*- coding: utf-8 -*-
class BaseProcessor(object):
def __init__(self, exporter, generator_info):
super(BaseProcessor, self).__init__()
self.exporter = exporter
self.generator_info = generator_info
def run(self):
pass
|
n = int(input())
dic = {}
for i in range(n):
c = input()
if c == "Q":
n = input()
if n in dic.keys():
print(dic[n])
else:
print("NONE")
elif c == "A":
n, p = input().split(" ")
dic[n] = p
|
class Solution:
def nextBeautifulNumber(self, n: int) -> int:
def isBalance(num: int) -> bool:
count = [0] * 10
while num:
if num % 10 == 0:
return False
count[num % 10] += 1
num //= 10
return all(c == i for i, c in enumerate(count) if c)
n += 1
while n... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim :set ft=py:
# blosc args
DEFAULT_TYPESIZE = 8
DEFAULT_CLEVEL = 7
DEFAULT_SHUFFLE = True
DEFAULT_CNAME = 'blosclz'
# bloscpack args
DEFAULT_OFFSETS = True
DEFAULT_CHECKSUM = 'adler32'
DEFAULT_MAX_APP_CHUNKS = lambda x: 10 * x
DEFAULT_CHUNK_SIZE = '1M'
# metadata ar... |
class Heroes:
ana = 1
bastion = 2
dva = 3
genji = 4
hanzo = 5
junkrat = 6
lucio = 7
mccree = 8
mei = 9
mercy = 10
pharah = 11
reaper = 12
reinhardt = 13
roadhog = 14
soldier76 = 15
symmetra = 16
torbjorn = 17
tracer = 18
widowmaker = 19
win... |
#-------------------#
# Measures
#-------------------#
json_save = False
measures = {
"z":"[i * pF.dz for i in range(pN.n_z)]",
"phi":"getDryProfile('phiPart')",
"vx":"getVxPartProfile()",
"dirs":"getOrientationHist(5.0, 0.0)",
"mdirs":"getVectorMeanOrientation()",
"ori":"getOrientationProfiles(pM.z_ground,... |
# encoding: utf-8
##################################################
# This script shows an example of a header section. This sections is a group of commented lines (lines starting with
# the "#" character) that describes general features of the script such as the type of licence (defined by the
# developer), authors,... |
def consecutive_pairalign(reversed_part, identical_part):
count = 0
lrev = len(reversed_part)
no_iter = min(len(reversed_part), len(identical_part))
i = 0
for i in range(0, no_iter):
if (reversed_part[lrev - i - 1] + identical_part[i]) in [
"au",
"ua",
"gc... |
myconfig = {
"name": "Your Name",
"email": None,
"password": None,
"categories": ["physics:cond-mat"]
}
|
fin = open('sum.in', 'r')
fout = open('sum.out', 'w')
while True:
True
result = sum(map(int, fin.readline().strip().split()))
fout.write(str(result)+'\n')
|
#读入用户输入的一个字符串,判断字符串中有多少个大写字母,多少个数字,多少个小写字母
intCount = 0
smallCount = 0
bigCount = 0
mystr = input("请输入一个字符串:")
for i in mystr:
if i.isupper():
bigCount += 1
elif i.isdigit():
intCount += 1
else:
smallCount += 1
print("大写字母%d个小写字母%d个数字%d个"%(bigCount,smallCount,intCount))
|
# -*- coding: utf-8 -*-
__author__ = 'Hugo Martiniano'
__email__ = 'hugomartiniano@gmail.com'
__version__ = '0.1.7'
__url__ = 'https://github.com/hmartiniano/faz'
|
word = input()
length = len(word)
def firstLine():
for i in range(0, length):
if (i == 0):
print(".", end='')
if (i % 3 == 2):
print(".*..", end='')
else:
print(".#..", end='')
print()
def secondLine():
for i in range(0, length):
if (i... |
# Here will be implemented the runtime stats calculators
class statsCalculator:
# Average of file sizes that were opened, written or read. (Before write operation)
avgFileSizes_open = 0
open_counter = 0
avgFileSizes_read = 0
read_counter = 0
avgFileSizes_write = 0
write_counter = 0
def... |
class Point(object):
__slots__ = ('x', 'y')
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __getitem__(self, index):
if isinstance(index, slice):
if index.start is None an... |
class Person:
eyes = 2
def __init__(self, *children, name=None, age=20):
#Atributo = parâmetro
self.name = name
self.age = age
self.children = list(children)
def greet(self):
return f'Hey {id(self)}'
if __name__ == '__main__':
felipe = Person(name='Felipe')
... |
def power(x, y):
if(y == 0):
return 1
if(y < 0):
n = (1/x) * power(x, (y+1)/2)
return n*n
if(y%2 == 0):
m = power(x, y/2)
return m*m
else:
return x * power(x, y-1)
def main():
print("To calculate x^y ...\n")
x = float(input("Please e... |
"""
https://leetcode.com/problems/wiggle-subsequence/
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is tri... |
# -*- coding: UTF8 -*-
"""
NAME
visualize
DESCRIPTION
Module that implements methods to plot ground_truth trajectories
and estimated for 6D poses.
METHODS
get_xy(pose)
Function that extracts (x,y) positions from
a list of 6D poses.
get_seq_star... |
print('Accumulated value of a scheduled savings account')
p = float(input('Type the value of the monthly application constant: '))
i = float(input('The tax: '))
n = int(input('How many months: '))
accumulated_value = p*((1 + i)**n - 1) / i
print(f'The accumulated value is $${accumulated_value}.')
|
# -*- coding: utf-8 -*-
model = {
'yn ': 0,
'dd ': 1,
' yn': 2,
' y ': 3,
'ydd': 4,
'eth': 5,
'th ': 6,
' i ': 7,
'aet': 8,
'd y': 9,
'ch ': 10,
'od ': 11,
'ol ': 12,
'edd': 13,
' ga': 14,
' gw': 15,
"'r ": 16,
'au ': 17,
'ddi': 18,
'ad ': 19,
' cy': 20,
' gy': 21,
' ei': 22,
' o ': 23,
'iad': ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'dracarysX'
class APIError(Exception):
"""
"""
def __init__(self, code, message):
self.code = code
self.message = message
class APIError404(APIError):
"""
"""
def __init__(self, message='Not Found'):
super... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class SharedMemoryException(Exception):
"""
Exception raised when using shared memory.
"""
def __init__(self, msg: str) -> None:
super().__init__(msg)
|
def ngram(s, num):
res = []
slen = len(s) - num + 1
for i in range(slen):
ss = s[i:i + num]
res.append(ss)
return res
def diff_ngram(sa, sb, num):
a = ngram(sa, num)
b = ngram(sb, num)
r = []
cnt = 0
for i in a:
for j in b:
if i == j:
cnt += 1
r.append(i)
return cn... |
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
"""Hash table.
"""
st = {}
ts = {}
for i in range(len(s)):
if s[i] not in st:
st[s[i]] = t[i]
elif st[s[i]] != t[i]:
return False
if t[i] not in... |
def some_function():
for i in range(4):
yield i
for i in some_function():
print(i) |
[
{
'date': '2021-01-01',
'description': 'Novo leto',
'locale': 'sl-SI',
'notes': '',
'region': '',
'type': 'NF'
},
{
'date': '2021-01-02',
'description': 'Novo leto',
'locale': 'sl-SI',
'notes': '',
'region': '',
... |
def spiralCopy(inputMatrix):
numRows = len(inputMatrix)
numCols = len(inputMatrix[0])
# keep track of where we are along each
# of the four sides of the matrix
topRow = 0
bottomRow = numRows - 1
leftCol = 0
rightCol = numCols - 1
result = []
# iterate throughout the entire matr... |
class Config(object):
JOOX_API_DOMAIN = "https://api-jooxtt.sanook.com/web-fcgi-bin"
JOOX_AUTH_PATH = "/web_wmauth"
JOOX_GETFAV_PATH = "/web_getfav"
JOOX_ADD_DIR_PATH = "/web_fav_add_dir"
JOOX_DEL_DIR_PATH = "/web_fav_del_dir"
JOOX_ADD_SONG_PATH = "/web_fav_add_song"
JOOX_DEL_SONG_PATH = "/... |
n=int(input())
squareMatrix=[]
k=0; i=0
while k<n:
row=input()
squareMatrix.append([])
for j in range(0,len(row)):
squareMatrix[i].append(row[j])
k+=1; i+=1
symbolToFind=input()
rowFound=0; colFound=0; symbolFound=False
for k in range(0,len(squareMatrix)):
if symbolFound=... |
"""
410. Split Array Largest Sum
Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.
Note:
If n is the length of array, assume the following constraints are satisf... |
# Given an array nums, write a function to move all 0's to the end of it
# while maintaining the relative order of the non-zero elements.
# EXAMPLE
# Input: [0,1,0,3,12]
# Output: [1,3,12,0,0]
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
'''
Time: O(N), worst case no 0s have to i... |
def solution(new_id):
answer = ''
for ele in new_id:
if 65 <= ord(ele) <= 90:
answer += chr(ord(ele) + 32) # 대문자 to 소문자
elif 48 <= ord(ele) <= 57 or 45 <= ord(ele) <= 46 or ord(ele) == 95 or 97 <= ord(ele) <= 122:
answer += ele
else:
continu... |
def czy_pal(tekst):
for x in range(len(tekst)):
if tekst[x] != tekst[len(tekst)-1-x]:
return False
return True
def nowy_pal(tekst):
odp = tekst
for x in range(len(tekst)):
odp += tekst[len(tekst)-1-x]
return odp
tekst = input()
results = czy_pal(tekst)
if result... |
class Ts2xlException(Exception):
'''
Used for expected errors, where the command-line tool
shouldn't show a full stack trace.
'''
pass
|
#!/usr/bin/python
# Word and some similarity (float).
class WordSim:
"""Word and some similarity"""
# name of the dictionary article
word = ''
# size of synset kernel |IntS|, i.e. number of synonyms, which always make subsets more nearer
sim = 0.0;
#def f(self):
# ret... |
class DataGridViewColumn(DataGridViewBand, ICloneable, IDisposable, IComponent):
"""
Represents a column in a System.Windows.Forms.DataGridView control.
DataGridViewColumn()
DataGridViewColumn(cellTemplate: DataGridViewCell)
"""
def Clone(self):
"""
Clone(self: DataGridViewColum... |
class Example1:
def __init__(self):
self.field1 = 1
class Example2(Example1):
def __init__(self): # Some valuable comment here
Example1.__init__(self) |
A, B, C = map(int, input().split())
K = int(input())
for _ in range(K):
if A >= B:
B *= 2
elif B >= C:
C *= 2
if A < B < C:
print('Yes')
else:
print('No')
|
"""This module defines custom exceptions
"""
class InvalidItemException(Exception):
"""Exception for when the pipeline tries to process an non-supported item."""
pass
|
# about.py
#
# Information for presentation in a Help:About dialog.
#
# Some items can be used elsewhere, e.g in __init__.py
# or in setup.cfg
NAME = 'BookMaker'
VERSION = '0.26b3'
COPYRIGHT = 'Copyright © 2021 Chris Brown and Marcris Software'
DESCRIPTION = 'A Book Authoring Application in Python - inspired by Gitboo... |
class TestResult:
def __init__(self):
self.runCount = 0
self.errorCount = 0
def testStarted(self):
self.runCount = self.runCount + 1
def testFailed(self):
self.errorCount = self.errorCount + 1
def summary(self):
return "%d run, %d failed" % (self.runCount, self.er... |
"""
a set of very basic queries - simply ensure the counts of label
"""
EXPECTED_COUNTS = {
'Case': 35577,
'Sample': 76883,
'Project': 172,
'Aliquot': 849801,
'DrugResponse': 641610,
'G2PAssociation': 50099,
'Gene': 63677,
'GenomicFeature': 5941,
'Allele': 4023292,
'Phenotype'... |
# Liste
names = ["Ben", "Jan", "Peter", "Melissa"]
noten = [1, 2, 1, 4]
# dict {(key, value)}
names_and_noten = {"Ben": 1, "Jan": 2, "Peter": 1, "Melissa": 4}
# Wert hinzufügen
names_and_noten.update({"Pia": 3})
# oder
names_and_noten["Julia"] = 1
# Wert entfernen
names_and_noten.pop("Julia")
# Keys
for k in names_a... |
"""terrainbento **UniformPrecipitator**."""
class UniformPrecipitator(object):
"""Generate uniform precipitation.
UniformPrecipitator populates the at-node field "rainfall__flux" with a
value provided by the keyword argument ``rainfall_flux``.
To make discharge proprortional to drainage area, use th... |
#Topic Class for handling msg from device
#Jon Durrant
#17-Sep-2021
#Topic handler superclass. Respond to a message on a particular topic channel
class Topic:
# handle a topic message
# @param topicName - string name of the topic
# @param data - string data
# @param twin - twin interface... |
# capitlize certain letters in plain text
# how to decide which letters to capitalize ?
# => Idea1: bool array with same length as plain_text
# -> set the required letters (positions) to True
# specify letters -> use range (start, end) position
class FormattedText:
def __init__(self, plain_text):
... |
class Solution:
"""
@param S: a string
@return: return a list of strings
"""
def letterCasePermutation(self, S):
return self.dfs(S, 0, {})
def dfs(self, S, idx, records):
if idx == len(S):
return [""]
if idx in records:
return records[idx]
... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
_multi_phase = False
def enable_multi_phase():
global _multi_phase
_multi_phase = True
def multi_phase_enabled():
return _multi_phase
|
def numbers_divisible_by_5_and_7_between_values(start_value, end_value):
result = []
for e in range(start_value, end_value + 1, 5):
if e % 7 == 0:
result.append(e)
return result
def numbers_divisible_by_5_and_13_between_values(start_value, end_value):
result = []
for e in range... |
class Constants:
def __init__(self):
self.version = "0.1a"
self.paste_url = "https://pastebin.com/api/api_post.php"
self.user_url = "https://pastebin.com/api/api_login.php"
self.raw_paste_url = "https://pastebin.com/api/api_raw.php"
self.headers = {
"X-Li... |
#declaração função aumento
def aumento():
#recebimento do salario atual
salario = float(input("Digite seu salario:\n"))
#verificação sobre qual taxa de aumento será utilizada
if(salario > 1250.00):
#aumento de 10%
salario *= 1.10
else:
#aumento de 15%
salario *= 1.15
... |
#!/usr/bin/python
# -*- coding: iso8859-1 -*-
# This should be not uploaded to repo, but since we're using test credentials is ok
# Should use env variables, local_settings not uploaded to repo or pass protect this
BASE_URL = 'http://22566bf6.ngrok.io/' # This might change with ngrok everytime...need to set it each tim... |
"""A macro that wraps a script to generate an object that maps routes to their entry data"""
load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_binary", "npm_package_bin")
def generate_route_manifest(name, routes):
"""Generates a json file that is a representation of all routes.
Args:
name: name o... |
# avax-python : Python tools for the exploration of the Avalanche AVAX network.
#
# Find tutorials and use cases at https://crypto.bi
"""
Copyright (C) 2021 - crypto.bi
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), t... |
class Superman:
def __init__(self):
self.superpowers = ['flight']
def print_superpowers(self):
print(f"Superpowers {self.superpowers}")
sm = Superman()
sm.print_superpowers()
class Megaman(Superman):
def __init__(self, megaman_powers=[]):
super().__init__()
self.superpowe... |
# List Comprehension is sort of like Map + Filter
numbers_list = range(10)
# Basic list comprehension (map)
doubled = [x * 2 for x in numbers_list]
print(doubled)
# Basic list comprehension (filter)
evens = [x for x in numbers_list if x % 2 == 0]
print(evens)
# list comprehension (map + filter)
doubled_evens = [x *... |
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
# Version 1: Inorder traverse, Time: O(n)
class Solution:
"""
@param root: the given BST
@param p: the given node
@return: the in-order predecessor of the give... |
# Python Week4 Day-23
# القواميس )المعاجم( في لغة البايثون
# Python Dictionaries 2
# Check if Key Exists
# To determine if a specified key is present in a dictionary use the in keyword.
print("-------Check if Key Exists-----------\n")
mydict = {
"brand":"Toyota",
"model":"Camry",
"year":2020
}
if "model"... |
#looping in Tuples
#tuple with one element
#tuple unpacking
#list inside tuple
#some function that you can use with tuple
Mixed = (1,2,3,4.0)
#for loop and tuple
for i in Mixed:
print(i)
#you can use while loop too
#tuple with one element
num1 = (1) #that is the class of integer
num2 = (1,) #that is the class of ... |
class classonlymethod(classmethod):
'''
Descriptor for making class only methods.
A `classonly` method is a class method, which can be called only from the
class itself and not from instances. If called from an instance will
raise ``AttributeError``.
'''
def __get__(self, instance, owner):... |
ACTIVATED_MSG = (200, "Successfully_activated")
DEACTIVATED_MSG = (200, "Successfully_deactivated")
DELETE_IMG = (204, "image_deleted")
SENT_SMS_MSG = (403, 'Message_Didnt_send')
NOT_SENT_SMS_MSG = (200, 'Message_sent')
NOT_VALID_CODE = (422, 'Code_is_not_valid')
STILL_HAS_VALID_CODE = (403, 'Phone_already_has_valid_co... |
"""Classes to organize the ouput of GLSL shader parsing"""
class Identifier:
def __init__(self, name, index, swizzle):
self.name = name
self.index = None
self.swizzle = None
def __repr__(self):
r = ["Ident(name=", self.name]
if self.index != None:
r.append(", index={}".format(self.index))
if self.swi... |
inutil = input()
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
temp = True
temp2 = True
for index,i in enumerate(b):
if i not in a:
temp = False
for n in b[0:index]:
for m in b[0:index]:
if m+n == i:
temp = True
if not temp:
print(i)
temp2 = False
break
if temp2:
p... |
class RenderMethod:
def __init__(self, image):
self.image = image
def to_string(self):
raise NotImplementedError('Renderer::to_string() should be implemented!')
|
"""
Given an array of distinct integers,
find length of the longest subarray which contains numbers that can be arranged in a continuous sequence.
Examples:
Input: arr[] = {10, 12, 11};
Output: Length of the longest contiguous subarray is 3
Input: arr[] = {14, 12, 11, 20};
Output: Length of the longest contiguou... |
#Imprima o valor da soma dos quadrados de 3 numeros inteiras
a = int(input('Digite o valor de a: '))
b = int(input('Digite o valor de b: '))
c = int(input('Digite o valor de c: '))
d = (a**2) + (b**2) + (c**2)
print(f'Resultado: {d}') |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( S , n ) :
found = False
S.sort ( )
for i in range ( n - 1 , - 1 , - 1 ) :
for j in range ( 0 , ... |
"""Module initialization."""
__version__ = "0.29.0"
__name__ = "gt4sd"
|
# -*- coding: utf-8 -*-
class NumMatrix(object):
''' https://leetcode.com/problems/range-sum-query-2d-immutable/
'''
def __init__(self, matrix):
"""
initialize your data structure here.
:type matrix: List[List[int]]
"""
self.matrix_sum = []
if not matrix:
... |
# Super Spooky Damage Skin
success = sm.addDamageSkin(2433183)
if success:
sm.chat("The Super Spooky Damage Skin has been added to your account's damage skin collection.")
|
# 2 - Dimmensional array
# Is implemented as array of array or list of list in python
# initialize an 2D array
array_2D = [[1, 2, 3, 4],
["a", "b", "c", "d"]]
# or
array_2d = [[5,6,7,8],
[3,5,2,9]]
# print the second item in the first row
print(array_2d[0][1])
print(array_2D[0][1])
# print ... |
# MIN HEIGHT BST
# O(NlogN) time and O(N) space
def minHeightBst(array):
return minHeightHelper(array, None, 0, len(array) - 1)
def minHeightHelper(array, nodeBST, start, end):
if start > end:
return
mid = (start + end) // 2
if not nodeBST:
nodeBST = BST(array[mid])
else:
nodeBST.insert(array[mid])
m... |
#!/usr/bin/python3
#str = input("Please give me an integer: ")
#num = int(str)
num = 20
# I'm guessing we can optionally exception catch.
# Perhaps this alone makes people recommend Python over Java.
# Optional error handling was a feature of BASIC.
if num < 0:
#print(num = 0, "");
# Among other reasons, Python can... |
STORAGE_ACCOUNT_NAME = " aibootcamp2019sa "
STORAGE_ACCOUNT_KEY = ""
BATCH_ACCOUNT_NAME = "aibootcamp2019ba"
BATCH_ACCOUNT_KEY = ""
BATCH_ACCOUNT_URL = "https://aibootcamp2019ba.westeurope.batch.azure.com"
ACR_LOGINSERVER = "athensaibootcampdemo.azurecr.io"
ACR_USERNAME = "athensaibootcampdemo"
ACR_PASSWORD = "" |
buf = b""
buf += b"\x48\x31\xc9\x48\x81\xe9\xb1\xff\xff\xff\x48\x8d\x05"
buf += b"\xef\xff\xff\xff\x48\xbb\xf8\x3d\x59\x54\x46\x6d\x59"
buf += b"\x99\x48\x31\x58\x27\x48\x2d\xf8\xff\xff\xff\xe2\xf4"
buf += b"\x04\x75\xda\xb0\xb6\x85\x95\x99\xf8\x3d\x18\x05\x07"
buf += b"\x3d\x0b\xc8\xae\x75\x68\x86\x23\x25\xd2\xcb\x98... |
class Utils(object):
# From https://gist.github.com/miohtama/5389146
@staticmethod
def get_decoded_email_body(msg, html_needed):
""" Decode email body.
Detect character set if the header is not set.
We try to get text/plain, but if there is not one then fallback to text/html.
... |
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval... |
def separate_speaker(speaker_npz_obj):
all_speaker = sorted(list(set(map(str, speaker_npz_obj.values()))))
all_keys = sorted(list(speaker_npz_obj.keys()))
speaker_individual_keys = [
[
key
for key in all_keys if speaker_npz_obj[key] == speaker
]
for speaker in all_sp... |
# Problem: Reshape the Matrix
# Difficulty: Easy
# Category: Array
# Leetcode 566: https://leetcode.com/problems/reshape-the-matrix/#/description
# Description:
"""
In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix
into a new one with different size but keep its original da... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.