content stringlengths 7 1.05M |
|---|
A = []
B = []
for i in range (10):
A.append(int(input()))
U = int(input())
for j in range (len(A)):
if A[j] == U:
B.append(j)
print(B)
|
def differentSymbolsNaive(s):
diffArray = []
for i in range(len(list(s))):
if list(s)[i] not in diffArray:
diffArray.append(list(s)[i])
return len(diffArray) |
# coding=utf8
# Entrada
num = int (input("Informe um número entre 1 e 10 para ver a tabuada: "))
# Processamento
while num < 1 or num > 10:
num = int (input("Informe um número entre 1 e 10 para ver a tabuada: "))
print("Tabuada de {0}".format(num))
for i in range (0, 11):
print("{0} X {1} = {2}".format(num, i,... |
s = input()
s = s.upper()
c = 0
for i in ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
for j in s:
if(i!=j):
c = 0
else:
c = 1
break
if(c==0):
break
if c==1:
print("Pangram exists")
else:
print("Pangram doesn't exists")
|
string_variable = "Nicolas"
int_variable = 24
print(string_variable)
print(int_variable)
|
name = input("Please enter your name: ")
print("{0}, Please guess a number between 0 and 10: ".format(name))
guess = int(input())
if guess != 5:
if guess < 5 :
print("Please guess higher")
else:
print("Please guess lower")
guess = int(input())
if guess == 5:
print("Well done, {0... |
"""
time: c*26 + p
space: 26 + 26 (1)
"""
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
cntP = collections.Counter(p)
cntS = collections.Counter()
P = len(p)
S = len(s)
if P > S:
return []
ans = []
for i, c in enumerate(s):
... |
def do_the_thing():
with open("input.txt", "r") as f:
nums = list(map(int, f.readlines()))
if len(nums) < 3:
return 0
count = 0
for i in range(len(nums)-3):
if nums[i] < nums[i+3]:
count += 1
return count
#
# windo... |
_base_ = [
'../_base_/models/mask_rcnn_red50_neck_fpn_head.py',
'../_base_/datasets/coco_instance.py',
'../_base_/schedules/schedule_1x_warmup.py', '../_base_/default_runtime.py'
]
optimizer_config = dict(grad_clip(dict(_delete_=True, max_norm=5, norm_type=2)))
|
def maxSumUsingMid(a, first, last, mid):
max_left = -99999
sum1 = 0
for i in range(mid, first - 1, -1):
sum1 += a[i]
if sum1 > max_left:
max_left = sum1
max_right = -99999
sum1 = 0
for i in range(mid + 1, last + 1):
sum1 += a[i]
if sum1 > max_right:
... |
print ('\n')
print ('_-_'*15)
print (' '*15 + 'LOJAS DIAS' + ' '*15)
print ('_-_'*15)
v = float (input ('\nDigite o valor da sua compra RS:\n'))
print ('\n [ 1 ] à vista dinheiro/cheque')
print (' [ 2 ] à vista no cartão')
print (' [ 3 ] 2x no cartão')
print (' [ 4 ] 3x ou mais')
p = int(input('\nQual será a forma de... |
'''
This module exists purely to check how to import test cases in the test suite
'''
def ex_function():
return True
|
## Command format
COMMAND_SIZE_TOTAL = 14 ## Cammand size total
COMMAND_SIZE_HEADER = 4 ## Cammand header size
COMMAND_SIZE_CHECKSUM = 4 ## Cammand checksum size
COMMAND_SIZE_OVERHEAD = 8 ... |
class SessionEncryption:
"""Session Encryption types."""
NONE = 'none'
TLS = 'tls'
|
# Faça um programa que solicite o preço de uma mercadoria e o percentual de desconto
# Exiba o valor do desconto e o preço a pagar
currentPrice = float(input('\nInforme o preço do produto: R$ '))
discountPercentage = float(input('Digite o percentual de desconto: '))
discount = currentPrice * discountPercentage / 100
... |
def MinNumberInsertionAndDel(a, b, x, y):
dp = [[None for _ in range(y + 1)] for _ in range(x + 1)]
for i in range(x + 1):
for j in range(y + 1):
if i == 0 or j == 0:
dp[i][j] = 0
elif a[i - 1] == b[j - 1]:
dp[i][j] = 1 + dp[i - 1][j - 1]
... |
def ajuda(c):
titulo('Acessando o PyHelp',2)
print(help(c))
def titulo(msg,cor=0):
# 0=reset,1=preto, 2=vermelho, 3=verde, 4=amarelo, 5=azul, 6=magenta, 7=ciano
cores = ['\033[0;0m','\033[1;40m','\033[1;41m','\033[1;42m','\033[1;43m','\033[1;44m','\033[1;45m','\033[1;46m']
print(cores[cor])
pr... |
"""
Fill in the gaps in the initials function so that it returns the initials of the words contained in the phrase received, in upper case. For example:
"Universal Serial Bus" should return "USB"; "local area network" should return "LAN”
"""
def initials(phrase):
words = phrase.split(' ')
result = ""
... |
'''
WRITTEN BY Ramon Rossi
PURPOSE
Two strings are anagrams if you can make one from the other
by rearranging the letters. The function named is_anagram takes
two strings as its parameters, returning True if the strings are
anagrams and False otherwise.
EXAMPLE
The call is_anagram("typhoon", "opyt... |
class VSBaseModel:
IGNORED_DICT_PROPS = [
'ignored_dict_props',
'plugin',
'plugins',
'host',
'hosts',
'finding',
'findings',
'service',
'services',
'vulnerability',
'vulnerabilities'
]
def __init__(self):
self... |
program = []
with open("input.txt", "r") as file:
for line in file.readlines():
program.append(line.split())
def execute(op, arg, ic, acc):
# return ic change, acc change
if op == "nop":
return ic+1, acc
if op == "jmp":
return ic+int(arg), acc
if op == "acc":
retur... |
"""
[Weekly #19] Looking forward into 2015 - Predictions.
https://www.reddit.com/r/dailyprogrammer/comments/2rfexe/weekly_19_looking_forward_into_2015_predictions/
As we enter the new year - What are some trends/predictions you see in computer science, software engineering,
programming or related fields forth coming ... |
# https://leetcode.com/problems/diameter-of-binary-tree/
# Given the root of a binary tree, return the length of the diameter of the tree.
# The diameter of a binary tree is the length of the longest path between any two
# nodes in a tree. This path may or may not pass through the root.
# The length of a path betwee... |
class Group:
def __init__(self, group_name, group_level, protocols=None):
if protocols is None:
protocols = {}
self.name = group_name
self.level = group_level
self.protocols = protocols
self.group_contains = set()
def __contains__(self, protocol):
fl... |
"""Calculate correlation coefficient."""
def find_corr_x_y(x, y):
"""Calculate the correlation between x and y."""
n = len(x)
prod = []
for xi, yi in zip(x, y):
prod.append(xi * yi)
sum_prod_x_y = sum(prod)
sum_x = sum(x)
sum_y = sum(y)
squared_sum_x = sum_x**2
squared_sum... |
VARS = {
'CLIENT_SECRET_PATH': 'res/client_secret.json',
'SCOPES': 'https://www.googleapis.com/auth/spreadsheets',
'APPLICATION_NAME': 'Google Sheets API Python Quickstart',
'DISCOVERY_URL': 'https://sheets.googleapis.com/$discovery/rest?version=v4'
}
CONSTANTS = {
'CREDENTIALS_FILENAME': 'sheets.go... |
def sanitize_pg_array(pg_array):
"""
convert a array-string to a python list
PG <9.0 used comma-aperated strings as array datatype. this function
will convert those to list. if pg_array is not a tring, it will not
be modified
"""
if not type(pg_array) in (str,unicode):
return pg_a... |
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
row = [1]
for i in range(1, rowIndex+1):
row = list(map(lambda x,y: x+y, [0]+row, row + [0]))
return row
'''
Say we have the current ... |
def expandX1(m):
c = [1]
for i in range(m):
c.append(c[-1] * -(m-i) / (i+1))
return c[::-1]
def isPrime(m):
if m < 2: return False
c = expandX1(m)
c[0] += 1
return not any(mul % m for mul in c[0:-1])
#----DRIVER PROGRAM----
print('\n# [for small primes]AKS TEST GAVE THE FOLLOWING ... |
class NodeofList(object):
def __init__(self, value):
self.value = value
self.next = None
def setElement(self, value):
self.value = value
def getElement(self):
return self.value
def setNext(self, next):
self.next = next
def g... |
# V0
# V1
# https://zhuanlan.zhihu.com/p/50564246
# IDEA : TWO POINTER
class Solution:
def isLongPressedName(self, name, typed):
"""
:type name: str
:type typed: str
:rtype: bool
"""
# name's index : idx
# typed's index : i
idx = 0
for i... |
class writeDataClass():
def writeData(self,dataFiles):
fileData=open("plt.dat","w")
for f in range(0,len(dataFiles)):
fileData.write("%s\n" % dataFiles[f])
fileData.close()
|
"""
Write a function that takes in an array of integers and returns a sorted array of the three largest integers
in the input array. Note that the function should return duplicate integers if necessary;
for example, it should return [10, 10, 12] for an input array of [10, 5, 9, 10, 12].
Sample input: [141, 1, 17, -7, ... |
discounts = [1.0, 1.0, 0.95, 0.90, 0.80, 0.75]
def add(list, element, index):
if len(list) < index + 1:
list.append([])
if element not in list[index]:
list[index].append(element)
else:
add(list, element, index + 1)
def price(l):
a = []
total_price = 0
for book in l:
... |
# print("Please insert a number")
# a = int(input("> "))
# print("Please insert another number")
# b = int(input("> "))
# print("Please insert yet another number")
# c = int(input("> "))
a = 4
b = 5
c = 10
if a > b:
if a > c:
print(a)
else:
print(c)
else:
if b > c:
print(b)
... |
# raider.io api configuration
RIO_MAX_PAGE = 5
# need to update in templates/stats_table.html
# need to update in templates/compositions.html
# need to update in templates/navbar.html
RIO_SEASON = "season-sl-2"
WCL_SEASON = 2
WCL_PARTITION = 1
# config
RAID_NAME = "Sanctum of Domination"
# late in the season, se... |
def cipher(text, shift, encrypt=True):
"""
1. Description:
The Caesar cipher is one of the simplest and most widely known encryption techniques. In short, each letter is replaced by a letter some fixed number of positions down the alphabet. Apparently, Julius Caesar used it in his private correspondence.
... |
################################################################################
#
#
#
#===============================================================================
class CustomDict( dict ):
#---------------------------------------------------------------------------
defaultValue = 'THIS ITEM NOT AVAILABLE'... |
"""
Grocery List
Create a program that prompts the
user to continuously enter items for a grocery
list. Stop asking them for items
when the user enters 'quit'.
Print the grocery list in a numbered format.
Ask the user to enter prices for each
item in the grocery list in order.
Finally, ask the user how many of
each... |
MIDDLEWARES = (
'middlewares.middle_a',
'middlewares.middle_b',
'middlewares.middle_c',
'middlewares.middle_d'
) |
y=200
deadtime=0
def setup():
global xs
xs=[]
size(400,400)
stroke(0)
def draw():
global xs, deadtime, y
strokeWeight(5)
background(169)
if keyPressed and key == " " and deadtime <=0:
xs.append(0)
deadtime=10
deadtime -= 1
... |
def checkcolor():
return [255, 240, 255]
def newcolor(a, b):
return 255 |
roles = [
{
'name': 'GK',
'description': 'Goalkeeper'
},
{
'name': 'LD',
'description': 'Left Defender'
},
{
'name': 'CD',
'description': 'Central Defender'
},
{
'name': 'RD',
'description': 'Right Defender'
},
{
... |
class A:
pass
var = object()
if isinstance(var, A) and var:
pass |
count = int(input())
for i in range(1, count + 1):
for j in range(1, i + 1):
print(j, end="")
print() # print("\n", end="") - по умолчанию print() выводит в консоль только '\n' |
# cifar10 #####################
ci7 = {'stages': 3, 'depth': 22, 'branch': 3, 'rock': 'U', 'kldloss': False,
'layers': (3, 3, 3), 'blocks': ('D', 'D', 'S'), 'slink': ('A', 'A', 'A'),
'growth': (0, 0, 0), 'classify': (0, 0, 0), 'expand': (1 * 22, 2 * 22),
'dfunc': ('O', 'O'), 'dstyle': 'maxpool', '... |
# -*- coding: utf-8 -*-
# XEP-0072: Server Version
class Version:
"""
process and format a version query
"""
def __init__(self):
# init all necessary variables
self.software_version = None
self.target, self.opt_arg = None, None
def format_result(self):
# list of all possible opt_arg
possible_opt_args ... |
# https://adventofcode.com/2020/day/9
infile = open('input.txt', 'r')
lines = infile.readlines()
infile.close()
def is_valid(a: list[int], n: int):
"""
Check if given list has any 2 numbers which add up to the given number
:param a: the list of numbers
:param n: the number we search for
:return: ... |
#!/usr/bin/env python
__version__ = '0.0.1'
__author__ = 'Fernandes Macedo'
__email__ = 'masedos@gmail.com'
fruits = ["Apple", "Peach", "Pear"]
for fruit in fruits:
print(fruit)
print(fruit + " Pie")
print(fruits) |
wt5_3_7 = {'192.168.122.110': [5.7199, 8.4411, 8.0381, 7.3759, 7.1777, 6.9974, 6.816, 6.7848, 6.811, 6.8666, 6.7605, 7.1659, 7.1058, 7.117, 7.4091, 7.3653, 7.602, 7.5046, 7.5051, 7.4195, 7.3659, 7.2974, 7.2932, 7.4615, 7.6061, 7.7395, 7.7409, 7.699, 7.6546, 7.631, 7.5707, 7.562, 7.5218, 7.4742, 7.6148, 7.5669, 7.5131,... |
insert_sensor_schema = {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "insert-sensor-schema",
"description": "Schema for inserting new sensor readings",
"type": "object",
"properties": {
"temperature": {
"$id": "/properties/temperature",
"type": "num... |
# Copyright (C) 2022 Google Inc.
#
# 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 agreed to in writing, ... |
# @time: 2021/12/10 4:00 下午
# Author: pan
# @File: ATM.py
# @Software: PyCharm
# 选做题:编写ATM程序实现下述功能,数据来源于文件db.txt
# 1、充值功能:用户输入充值钱数,db.txt中该账号钱数完成修改
# 2、转账功能:用户A向用户B转账1000元,db.txt中完成用户A账号减钱,用户B账号加钱
# 3、提现功能:用户输入提现金额,db.txt中该账号钱数减少
# 4、查询余额功能:输入账号查询余额
db_data = {}
def update_db_data():
"""更新数据"""
with open("db... |
with open("zad3.txt", "w") as plik:
for i in range(0,11,1):
plik.write(str(i)+'\n')
with open("zad3.txt", "r") as plik:
for i in plik:
print(i, end="") |
'''
Problem 019
You are given the following information, but you may prefer to do some research
for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A... |
a = 2 ** 62
b = 2 ** 63
c = 0 ** 0
d = 0 ** 1
e = 1 ** 999999999
f = 1 ** 999999999999999999999999999
g = 1 ** (-1)
h = 0 ** (-1)
i = 999999999999999 ** 99999999999999999999999999999
j = 2 ** 10
k = 10 ** 10
l = 13 ** 3
m = (-3) ** 3
n = (-3) ** 4
|
class State:
'Defined state of cell in grid world'
def __init__(self, pos=[0,0], reward= -1, movable=True, absorbing=False, agent_present=False):
self.pos = pos
self.reward = reward
self.movable = movable
self.absorbing = absorbing
self.v_pi = []
self.v_pi_mean = ... |
##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2020
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Terce... |
# File: minemeld_consts.py
#
# Copyright (c) 2021 Splunk Inc.
#
# 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 applica... |
PRIVILEGE_CHOICES = [
('Users.manageUser', 'Manage Users'),
('Sales.manage', 'Manage Sales'),
('Sales.docs', 'Manage Documents'),
]
|
__all__ = [
'q1_words_score',
'q2_default_arguments'
]
|
# This example shows one of the possibilities of the canvas:
# the ability to access all existing objects on it.
size(550, 300)
fill(1, 0.8)
strokewidth(1.5)
# First, generate some rectangles all over the canvas, rotated randomly.
for i in range(3000):
grob = rect(random(WIDTH)-25, random(HEIGHT)-25,50, 50)
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Created by Ross on 19-1-8
def solve(n: int):
if n <= 0:
return -1
table = [0, 1]
if n < 2:
return table[n]
fib1 = table[0]
fib2 = table[1]
fib_n = 0
for i in range(2, n + 1):
fib_n = fib1 + fib2
fib1 = fib2
... |
numbe = 1125
strnumbe = str(numbe)
sumOfDigit = 0
productOfDigit = 1
listdigits = list(map(int, strnumbe))
for elemen in listdigits:
sumOfDigit = sumOfDigit+elemen
productOfDigit = productOfDigit*elemen
if(sumOfDigit == productOfDigit):
print('The given number', strnumbe, 'is spy number')
else:
... |
number = int(input())
if number == 1:
print("Monday")
elif number == 2:
print("Tuesday")
elif number == 3:
print("Wednesday")
elif number == 4:
print("Thursday")
elif number == 5:
print("Friday")
elif number == 6:
print("Saturday")
elif number == 7:
print("Sunday")
else:
... |
#nu = []
#i = n0 = n1 = n2 = n3 = n4 = 0
#for c in range(0, 5):
# n = int(input('Digite um valor: '))
# if c == 0:
# n0 = n1 = n2 = n3 = n4 = n
# i = 0
# elif n < n0:
# i = 0
# n0 = n
# elif n < n1:
# i = 1
# n1 = n
# elif n < n2:
# i = 2
# n2 = n
# ... |
def to_role_name(feature_name):
return feature_name.replace("-", "_")
def to_feature_name(role_name):
return role_name.replace("_", "-")
def resource_name(prefix, cluster_name, resource_type, component=None):
name = ''
if (not prefix) or (prefix == 'default'):
if component is None:
... |
"""
Faça um programa que leia o nome de uma pessoa e mostre uma mensagem de boas-
vindas
"""
nome = input('Digite seu nome: ') # perguntando ao usuário
# usando format:
print('É um prazer te conhecer, {}{}{}!'.format('\033[4;34m', nome, '\033[m'))
# usando f strings:
print(f'É um prazer te conhecer, \033[4;34m{nome}... |
number_of_wagons = int(input())
train = [0 for x in range(number_of_wagons)]
command = input()
while command != 'End':
current_task = command.split(' ')
task = current_task[0]
if task == 'add':
num_of_people = int(current_task[1])
train[-1] += num_of_people
if task == 'insert':
... |
class Comentarios:
def __init__(self, videojuego, usuario, comentario):
self.videojuego = videojuego
self.usuario = usuario
self.comentario = comentario
#MÉTODOS GET
def getVideojuego(self):
return self.videojuego
def getUsuario(self):
return self.usuario
def getComentario(self):
return self.come... |
class UwsgiconfException(Exception):
"""Base for exceptions."""
class ConfigurationError(UwsgiconfException):
"""Configuration related error."""
class RuntimeConfigurationError(ConfigurationError):
"""Runtime configuration related error."""
|
#Si existe la posibilidad de que más de una excepción se salte a un apartado "except:",
# puedes tener problemas para descubrir lo que realmente sucedió.
try:
x = int(input("Ingresa un numero: "))
y = 1 / x
print("1 /",x,"=",y)
except:
#El mensaje: "Oh cielos, algo salio mal..." que aparece en la consola no... |
# constants
PERCENTAGE_BUILTIN_SLOTS = 0.20
# Time
FOUNTAIN_MONTH = 'FOUNTAIN:MONTH'
FOUNTAIN_WEEKDAY = 'FOUNTAIN:WEEKDAY'
FOUNTAIN_HOLIDAYS = 'FOUNTAIN:HOLIDAYS'
FOUNTAIN_MONTH_DAY = 'FOUNTAIN:MONTH_DAY'
FOUNTAIN_TIME = 'FOUNTAIN:TIME'
FOUNTAIN_NUMBER = 'FOUNTAIN:NUMBER'
FOUNTAIN_DATE = 'FOUNTAIN:DATE'
# Location
F... |
"""
给定一个矩阵`A` 返回`A`的转置矩阵
矩阵的转置是指将主对角线翻转,交换矩阵的行索引和列索引。
**test case**
>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> transpose(array=matrix)
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
>>> matrix = [[1, 2, 3], [4, 5, 6]]
>>> transpose(array=matrix)
[[1, 4], [2, 5], [3, 6]]
# Solution
shape 为 R x C 的矩阵A 转置后会得到shape 为 `C x R... |
# 246. Strobogrammatic Number
# ttungl@gmail.com
# A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
# Write a function to determine if a number is strobogrammatic. The number is represented as a string.
# For example, the numbers "69", "88", and "818" are all... |
# https://leetcode.com/problems/multiply-strings/
# Given two non-negative integers num1 and num2 represented as strings, return the
# product of num1 and num2, also represented as a string.
# Note: You must not use any built-in BigInteger library or convert the inputs to
# integer directly.
########################... |
# -*- coding: utf-8 -*-
"""
the common functionalities
"""
def get_value_from_dict_safe(d, key, default=None):
"""
get the value from dict
args:
d: {dict}
key: {a hashable key, or a list of hashable key}
if key is a list, then it can be assumed the d is a nested dict
d... |
# Handling negation: "not good", "not worth it"
def hack(rev):
for i in range(0, len(rev)):
line = rev[i].split()
for it in range(0, len(line)):
if line[it] == 'no' or line[it] == 'not' or line[it] == 'nope' or line[it] == 'never' or line[it] == "isn't" or line[it] == "don't" or line[it] == "dont" or line[... |
print("Kinjal Raykarmakar\nSec: CSE2H\tRoll: 29\n")
num = int(input("Enter a number: "))
if num % 2 == 0:
print("{} is an even number".format(num))
else:
print("{} is an odd number".format(num)) |
_input = [int(num) for num in input().split(" ")]
river_width = _input[0]
max_jump_length = _input[1]
stones = [int(stone) for stone in input().split(" ")]
|
n1 = int(input('Um valor: '))
n2 = int(input('Outro valor:'))
s = n1+n2
m = n1*n2
d = n1/n2
di = n1//n2
e = n1 ** n2
print(f'A soma é {s}, o produto é {m} e a divisão é {d}')
print(f'Dovosão inteira {di} e potência {e}') |
#Compute the max depth of a binary tree
class Tree:
def __init__(self, val,left = None, right = None):
self.val = val
self.left = left
self.right = right
root = Tree(4, left = Tree(3), right=Tree(5, left= Tree(4)))
def maxDepth(root):
if root is None:
return 0
ret... |
odpremo = open(r'C:\Users\jureb\OneDrive\Desktop\Euler\names.txt', 'r')
string = odpremo.read()
odpremo.close
string = string[1:-1]
sez = string.split('","')
sez.sort()
#do te točke samo importamo seznam, nič se ne zgodi
sample = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'
rezultat = 0
i = 1
for el in sez:
score = i
vsota... |
lst=list(map(int, input().split()))
if sum(lst)==180 and 0 not in lst:
print('YES')
else:
print('NO')
|
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
current_max=nums[0]
global_max=nums[0]
for i in range(1,len(nums)):
current_max=max(nums[i],current_max+nums[i])
global_max=max(current_max,global_max)
return global_max |
'''
BITONIC POINT
Given an array. The task is to find the bitonic point of the array.
The bitonic point in an array is the index before which all the numbers
are in increasing order and after which, all are in decreasing order.
'''
def bitonic(a, n):
l = 1
r = n - 2
while(l <= r):
m = (l + r) // 2... |
class Solution:
def nthUglyNumber(self, n):
dp = [0] * n
dp[0] = 1
p2 = 0
p3 = 0
p5 = 0
for i in range(1, n):
dp[i] = min(2 * dp[p2], 3 * dp[p3], 5 * dp[p5])
if dp[i] >= 2 * dp[p2]:
p2 += 1
if dp[i] >= 3 * dp[p3]:
... |
"""
Check that `yield from`-statement takes an iterable.
"""
# pylint: disable=missing-docstring
def to_ten():
yield from 10 # [not-an-iterable]
|
class SpatialExtent:
def __init__(self):
self.bbox = ""
class TemporalExtent:
def __init__(self):
self.interval = ""
|
ascii_brand = """
[49m[K[0m[12C[48;5;102m [3C [49m
[11C[48;5;102m [17C [49m
[10C[48;5;102m [7C[48;5;209m [7C[48;5;102m [49m
[9C[48;5;102m [21C [49m
[7C[48;5;102m [8C[48;5;209m [48;5;203m [12C[48;5;102m [49m
[7C[48;5;102m [9C[48;5;209m [14C[48... |
#!/usr/bin/python
# ==============================================================================
# Author: Tao Li (taoli@ucsd.edu)
# Date: May 6, 2015
# Question: 001-Two-Sum
# Link: https://leetcode.com/problems/two-sum/
# ==============================================================================
# Giv... |
class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
if not intervals:
return 0
result, curr = 0, 0
for i, val in sorted(
x for interval in intervals for x in [(interval[0], 1), (interval[1], -1)]
):
curr += val
... |
dados = list()
pessoas = list()
pesados = list()
leves = list()
maior = menor = 0
while True:
dados.append(str(input('Nome: ')))
dados.append(float(input('Peso: ')))
pessoas.append(dados[:])
dados.clear()
continuar = ' '
while continuar not in 'SN':
continuar = str(input('Deseja continua... |
# Futu Algo: Algorithmic High-Frequency Trading Framework
# Copyright (c) billpwchan - All Rights Reserved
# Unauthorized copying of this file, via any medium is strictly prohibited
# Proprietary and confidential
# Written by Bill Chan <billpwchan@hotmail.com>, 2021
class Settings:
# APP SETTINGS
ENABLE_... |
# search for the 1000th prime number and print it
# author Zhou Fang Version: 1.0
# Problem 1.
# Write a program that computes and prints the 1000th prime number.
number_prime = 1
i = 3
while number_prime < 1000:
divider = 3
status = 1
while status:
if i % divider != 0 and divider < i/2:
... |
"""
Basic implementation of a binary tree.
Author: Xavier Cucurull Salamero <xavier.cucurull@estudiantat.upc.edu>
"""
class Node:
""" Implementation of a binary tree to use with CART.
"""
def __init__(self, predicted_class, gini, data_idx=None):
self.predicted_class = predicted_class
self.... |
class Components(object):
"""Represents an OpenAPI Components in a service."""
def __init__(
self, schemas=None, responses=None, parameters=None,
request_bodies=None):
self.schemas = schemas and dict(schemas) or {}
self.responses = responses and dict(responses) or {}
... |
class Mixin(object):
def _send_neuron(self, *args):
return self._send_entity('Neuron', *args)
def _send_synapse(self, *args):
return self._send_entity('Synapse', *args)
def send_synapse(self, source_neuron_id, target_neuron_id, weight):
"""Send a synapse to the simulator to connec... |
print("welcome to SBI bank ATM")
restart=('y')
chances = 3
balance = 1000
while chances>0:
restart=('y')
pin = int(input("please enter your secret number"))
if pin == 1234:
print('you entered your pin correctly\n')
while restart not in ('n','N','no','NO'):
print('press ... |
# encoding: utf-8
"""Basic token types for use by parsers."""
class Token(object):
def __lt__(self, other):
return self.length < len(other)
def __len__(self):
return self.length
class InlineToken(Token):
"""Inline token definition."""
__slots__ = ('annotation', 'match')
def __init__(self, annotation,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.