content stringlengths 7 1.05M |
|---|
N,K=map(int,input().split())
t=[int(input()) for i in range(N)]
count=0
for i in range(N-2):
if sum(t[i:i+3])<K:
print(i+3)
break
else:
print(-1) |
s="(a)"
charac=["+","-","*","/"]
stack=[]
for i in s:
if i=="(":
stack.append(False)
elif i in charac:
if not stack:
continue
stack[-1]=True
elif i==")":
if stack[-1]:
stack.pop()
else:
print(1)
print(0) ... |
# Linear search program to search an element, return the index position of the #array
def searching(search_arr, x):
for i in range(len(search_arr)):
if search_arr[i] == x:
return i
return -1
search_arr = [3, 4, 1, 6, 14]
x=4
print("Index position for the element x i... |
#Method find() searches a substring, passed as an argument, inside the string on which it's called.
# The function returns the index of the first occurrence of the substring.
# If the substring is not found, the method returns -1.
s = 'Hello'
print(s.find('e'))
print(s.find('ll'))
print(s.find("L"))
|
def isValidSubsequence(array, sequence):
"""
Takes one array and a sequence(another array) and checks if the sequence is the subsequence of the array.
solution complexity : O(n) time complexity and O(1) space complexity
args:
-----------
array : an array of numbers
sequence : an array of numbers
output... |
__author__ = 'Thierry Schellenbach'
__copyright__ = 'Copyright 2010, Thierry Schellenbach'
__credits__ = ['Thierry Schellenbach, mellowmorning.com, @tschellenbach']
__license__ = 'BSD'
__version__ = '2.3.2'
__maintainer__ = 'Thierry Schellenbach'
__email__ = 'thierryschellenbach@gmail.com'
__status__ = 'Production'
... |
"""
面向对象
1. 字面意思:
考虑问题从对象的角度出发
谁?干嘛?
2. 三个特征
封装(分):分而治之,变则疏之
例如,人类 汽车类 飞机类 轮船类 ...
继承(隔):抽象/统一多个变化点的共性,从而隔离变化
例如, 使用交通工具隔离人与具体交通工具的变化
多态(做):展示多个变化点的个性(调用父/子重写/创建子)
例如,具体交通工具重写交通工具的运输方法
... |
# Embedded file name: D:\Users\Akiva\Competition\cyber-pirates\admin-tools\simulator\bots\python\Demo3.py
""" Demo 3 sends two pirates to go get islands """
pirates = [0, 1]
islands = [3, 2]
def do_turn(game):
global islands
global pirates
if len(game.not_my_islands()) < 2:
return
for index, p ... |
valid = set('+-* |')
def countMines(x, y, board):
xmin, xmax = (max(0, x - 1), min(x + 2, len(board[y])))
ymin, ymax = (max(0, y - 1), min(y + 2, len(board)))
result = [c for r in board[ymin:ymax]
for c in r[xmin:xmax]
if c == '*']
return len(result) if len(result)... |
# coding: utf-8
class DialogMessage(object):
def __init__(self, msg):
if type(msg) is not dict or 'type' not in msg or 'content' not in msg:
raise ValueError('Invalid message format: {}'.format(msg))
self.type = msg['type']
self.content = msg['content']
|
"""
Project Euler Problem 7: 10,001st prime
"""
# What is the 10,001st prime number?
# NOTE: this solution implements the pseudocode explained in the posted solutions on projecteuler.net
# url: (https://projecteuler.net/overview=007)
def is_prime(n):
if ... |
class Solution:
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
if not root:
return False
seen = set()
stack = [root]
for node in stack:
if k - node.val in seen:
retu... |
# Se desea eliminar todos los numeros duplicados de una lista o vector
# Por ejemplo si toma los valores [4,7,11,4,9,5,11,7,3,5]
# Ha de cambiarse a [4,7,11,9,5,3]
def eliminar(numArray: list) -> list:
largo = len(numArray)
unicos = list()
for i in range ((largo - 1), -1, -1):
if (numArray[i] not in ... |
post = 'div._1poyrkZ7g36PawDueRza-J._11R7M_VOgKO1RJyRSRErT3 > div.STit0dLageRsa2yR4te_b > div > div._3JgI-GOrkmyIeDeyzXdyUD._2CSlKHjH7lsjx0IpjORx14 > div > a'
image_link = 'div > div._1NSbknF8ucHV2abfCZw2Z1 > div > a'
image_name = 'div.y8HYJ-y_lTUHkQIc1mdCq._2INHSNB8V5eaWp4P0rY_mE > div > h1'
|
# In Windows, Control+Z is the typical keyboard shortcut to mean "end of file",
# in Linux and Unix it's typically Control+D.
try:
text=input('Enter something -->')
except EOFError:
print('Why did you do an EOF on me?')
except KeyboardInterrupt:
print('You cancelled the opration.')
else:
print('You en... |
"""
File: part1b.py
Created by Andrew Ingson (aings1@umbc.edu)
Date: 4/26/2020
CMSC 441 (Design and Analysis of Algorithms)
"""
# size is 312 bits (supposedly)
n = 6207034496804283879630919311406969504330524655944955079581115322595987746105035112739268374117
print("Modulus is", n)
|
INPUT = [
1036,
1897,
1256,
1080,
1909,
1817,
1759,
1883,
1088,
1841,
1780,
1907,
1874,
1831,
1932,
1999,
1989,
1840,
1973,
1102,
1906,
1277,
1089,
1275,
1228,
1917,
1075,
1060,
1964,
1942,
2001,
... |
__author__ = "jes3cu"
# Name: Jake Shankman
# CompID: jes3cu
# Date: 9/28/15
# Assignment: Lab 5
# Language: python3
if __name__ == "__main__":
print("1 + 1 = 2") |
class GraphDataStructureException(Exception):
def __init__(self, message):
super().__init__(message)
class UninitializedGraph(GraphDataStructureException):
def __init__(self, message='Graph object is not initialized'):
super().__init__(message)
|
__version__ = '0.0'
__all__ = ['seed','inspect','cross','trans','reel','sieve','refine']
# sown the seed, inspect the crop,
# crossbreed to improve, transplant to adapt,
# reel them in, sieve for good, and refine for the best.
# ---- qharv maxim
|
"""
Data storage class
TODO: Add ability to analyse bar type
"""
class OHLCData:
def __init__(self, open, high, low, close):
self.open = float(open)
self.high = float(high)
self.low = float(low)
self.close = float(close)
def linearize(self):
return self.open, self.hig... |
class Solution:
"""
@param num: Given the candidate numbers
@param target: Given the target number
@return: All the combinations that sum to target
"""
def combinationSum2(self, num, target):
used = [False for i in range(len(num))]
num.sort()
result = []
self.back... |
def get_order_amount(order_string, price_list):
'''
This function returns the order amount, based on the items in the
order string, and the price of each item in the price list.
'''
# write your answer between #start and #end
#start
if len(order_string) == 0:
return 0
... |
def solution(info, query):
answer = []
# idx 정보 저장
idxs={'cpp': [], 'java': [], 'python': [], 'backend': [], 'frontend': [],
'junior': [], 'senior': [], 'chicken': [], 'pizza': []}
for i in range(len(info)):
for ele in info[i].split()[:-1]:
idxs[ele].append(i)
#... |
# -*- coding: utf-8 -*-
__author__ = 'Daniel Williams'
__email__ = 'd.williams.2@research.gla.ac.uk'
__version__ = '0.2.1'
|
# Two Sum
# Given an array of integers, return indices of the two numbers such that they add up to a specific target.
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
# Example:
# Given nums = [2, 7, 11, 15], target = 9,
# Because nums[0] + nums[1] = 2 + ... |
def stdout_handler(config):
def handle(event):
print('>', event._formatted)
print(event.message.strip())
return handle
|
# Created from VeraMono.ttf with freetype-generator.
# freetype-generator created by Meurisse D ( MCHobby.be ).
VeraMono_14 = {
'width' : 0x9,
'height' : 0xf,
32:(),
33:( 0xe7e0,),
34:( 0xf800, 0x8000, 0xf800),
35:( 0x8800, 0xe900, 0x9f00, 0x89e0, 0xf900, 0x8f80, 0x89e0, 0x8100),
36:( 0x88e0, 0x9190, 0x9110, 0xfffc,... |
# Zapytaj użytkownika o ceny trzech produktów i wypisz wyniki ich porównania
computer_price = float(input("Ile średnio kosztuje komputer? "))
car_price = float(input("Ile kosztuje typowy samochód? "))
bike_price = float(input("Ile kosztuje typowy rower? "))
print(f"Czy komputer jest droższy od samochodu? {computer_p... |
def main():
f1, f2, limit, s = 1, 2, 4000000, 2
while True:
f = f1 + f2
if f > limit:
break
if not f & 1:
s += f
f1 = f2
f2 = f
return s
if __name__ == '__main__':
print(main())
|
##Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês.
pre=float(input('Quanto ganha por hora? '))
hrs=float(input('Quantas horas que você trabalhou ao mês? '))
salario= pre*hrs
print('O preço da sua hora é {} \n O n... |
tot = soma = 0
while True:
num = int(input('Digite um numero [999 para parar]: '))
if num == 999:
break
tot += 1
soma += num
print(f'A soma dos valores foi {soma} e voce digitou {tot} numeros')
|
TARGET_PAGE = {
'CONFIG_PATH': 'system files/config',
'NUMBER_OF_PAGES' : 2, ### update number of pages
'TITLE' : 'Job Listings - ML',
'URL' : '' ## add URL
}
TARGET_URL = TARGET_PAGE['URL']
CONFIG_FILE = TARGET_PAGE['CONFIG_PATH']
EXCEL_TITLE = TARGET_PAGE['TITLE']
NUM_PAGES = TARGET_PAGE['NUMBER_OF_PAGES'... |
#Aufbau eines Dictionarys aus einer Liste
#ordnet den Schlüsselwörtern A, B und C die Elemente mit gleichem Anfangsbuchstaben zu
liste=["Auto","Apfel","Cello","Banane","Berg"]
d={}
for key in "ABC":
d[key]=[w for w in liste if w[0]==key]
print(d)
|
class Solution(object):
def maxCoins(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
nums.insert(0, 1)
nums.append(1)
memo = dict()
def burst(left, right):
if left + 1 >= right:
... |
gsCP437 = (
"\u0000"
"\u263A"
"\u263B"
"\u2665"
"\u2666"
"\u2663"
"\u2660"
"\u2022"
"\u25D8"
"\u25CB"
"\u25D9"
"\u2642"
"\u2640"
"\u266A"
"\u266B"
"\u263C"
"\u25BA"
"\u25C4"
"\u2195"
"\u203C"
"\u00B6"
"\u00A7"
"\u25AC"
"\u21A8"
"\u2191"
"\u2193"
"\u2192"
"\u2190"
... |
class Cyclist:
def __init__(self, name, nationality, nickname):
self._name = name
self._nationality = nationality
self._nickname = nickname
@property
def name(self):
return self._name
@name.setter
def name(self, new_name):
self._name = new_name
@property
def nationality(self):
... |
def add(x,y):
"""Add Function
"""
return x + y
def subtract(x,y):
"""Subtract Function
"""
return x - y
def multiply(x,y):
"""Multiply Function
"""
return x * y
def divide(x,y):
"""Divide Function
"""
return x / y
|
class Ala:
def __init__(self):
print('a')
class Bob(Ala):
def __init__(self, var):
Ala.__init__(self)
self.var = var
print('b')
class Cecylia(Bob):
def __init__(self, vara, var2):
Bob.__init__(self, vara)
self.var = var2
print('c')
c = Cecylia(3, 5... |
value = 10.00
# print("将指定类型转化为int类型的数值", int(value))
string = "这是一个字符串"
# print("将目标转化为字符串:", str(value))
# print(type(string))
data = tuple(string)
# print("这是一个list转型后的", data)
pick = set(string)
# print("将目标转化为可变集合", pick)
introduce = [1, "大", 3, 'c', 5, 6]
# print(dict(pick=introduce))
# 结束位置插入元素
# introduce.appe... |
# -*- coding: utf-8 -*-
DESC = "redis-2018-04-12"
INFO = {
"UpgradeInstance": {
"params": [
{
"name": "InstanceId",
"desc": "实例Id"
},
{
"name": "MemSize",
"desc": "分片大小 单位 MB"
},
{
"name": "RedisShardNum",
"desc": "分片数量,Redis2.8主从版、CKV主... |
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
C = float(input("Enter degree Celsius:"))
F = (C * 9 / 5) + 32
K = C + 273.15
print("Your degree Celsius is... |
"""
Default static settings for the controlled_vocabulary app
All settings variables can be overridden in your django project settings.py
See controlled_vocabulary/settings.py for dynamic settings.
"""
# List of import paths to vocabularies lookup classes
CONTROLLED_VOCABULARY_VOCABULARIES = [
"controlled_vocabul... |
def quadrado_de_pares(numero):
for num in range(2, numero + 1, 2):
print(f'{num}^2 = {num ** 2}')
n = int(input())
quadrado_de_pares(n)
|
x = input('Digite algo: ')
print('"{}" é do tipo {}'.format(x, type(x)))
# Confere quantos caracteres
print('"{}" possui {} caracteres'.format(x, len(x)))
# Confere se é numérico, alfabético ou alfanumérico
if x.isnumeric():
print('"{}" é do tipo numérico'.format(x))
elif x.isalpha():
print('"{}" é do tipo alp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Doubly linked list. The main purpose is torepresent incidence at each node.
It is used to manage an ordered list of elements for:
- dynamic insertion and deletion of elements at specific point in O(|1|).
- iteration in both forwards and backwards.
- desctuctive iterati... |
def uppercase(func):
def wrapper():
originalResult = func()
modifiedResult = originalResult.upper()
return modifiedResult
return wrapper
@uppercase
def greet():
return 'Hello World!'
print(greet())
# OUTPUT
# HELLO WORLD! |
# coding=utf-8
"""OSM Reporter exceptions.
:copyright: (c) 2016 by Etienne Trimaille
:license: GPLv3, see LICENSE for more details.
"""
class OverpassTimeoutException(Exception):
pass
class OverpassBadRequestException(Exception):
pass
class OverpassConcurrentRequestException(Exception):
pass
class O... |
LongName = raw_input("Enter Class Name... ")
ShortName = raw_input("Enter Short Name... ")
hcontents = """#pragma once
#include "./Component.h"
namespace audio
{
class %s : public Component
{
public:
%s();
virtual void CalcSample(double& dSample) override;
};
}
""" % (LongName, LongName)
f=open("../src/Com... |
panel = pm.getPanel(wf=True)
qtpanel = panel.asQtObject()
sew = qtpanel.children()[-1]
sewl = sew.layout()
seww = sewl.itemAt(1).widget()
sewww = seww.children()[-1]
splitter = sewww.children()[1]
splitter.setOrientation(QtCore.Qt.Orientation.Horizontal)
sc = splitter.widget(0)
se = splitter.widget(1)
splitter.in... |
#
# PySNMP MIB module P-BRIDGE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/P-BRIDGE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:05:00 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,... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def not_null(self, head: ListNode) -> bool:
return head is not None
def hasCycle(self, head: ListNode) -> bool:
if head is None:
return Fal... |
#coding=utf-8
#访客名单P172 2017.4.21
filename = 'guestBook.txt'
def writeIt():
active = True
while active:
guestName = input("Please input your name.(input 'quit' to exit)\n")
if guestName == 'quit':
active = False
continue
else:
print("Welcome join in ! " + guestName + '\n')
with open(filename,'a') as... |
input = """
x(X) :- X > 1, X < 3.%, #int(X).
"""
output = """
x(X) :- X > 1, X < 3.%, #int(X).
"""
|
def setup():
size(800, 400)
desenha_retangulos(0, 0, 399, 10)
def desenha_retangulos(x, y, tam, level):
rect(x, y, tam, tam)
if level > 1:
level = level -1
desenha_retangulos(x, y, tam/2, level)
desenha_retangulos(x + tam, y, tam/2, level)
|
class Calculadora:
def soma(self, num1, num2):
return num1 + num2
def subtracao(self, num1, num2):
return num1 - num2
def multiplicacao(self, num1, num2):
return num1 * num2
def divisao(self, num1, num2):
return num1 / num2
calculadora = Calculadora()
print(calcula... |
#!/usr/bin/python
#
# Locates SEH try blocks, exception filters and handlers for x64 Windows files.
#
# Author: Satoshi Tanda
#
################################################################################
# The MIT License (MIT)
#
# Copyright (c) 2015 tandasat
#
# Permission is hereby granted, free of charge, to an... |
class Node:
def __init__(self, data):
self.data = data
self.left = self.right = None
def leafTraversal(node, lst):
if node is None:
return
if node is not None:
leafTraversal(node.left, lst)
if node.left is not None and node.right is not None:
lst.append(... |
# In this challenge, we'll work with lists
# Remember to make sure the tests pass
# count the number of 1s in the given list
def list_count_ones():
a = [1, 8, 6, 7, 5, 3, 0, 9, 1]
# we have not covered the list method with this functionality
return None
# calculate the average value of the given list
def... |
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
def main():
game = [ 'Rock', 'Paper', 'Scissors', 'Lizard', 'Spock' ] #List
print(game[1:3]) #pode se usar o metodo de 3 parametros
i= game.index('Paper')
#game.append("João")
#game.insert(0, "Corea")
print(', '.join(game)) # coloc... |
def partition(a,l,h):
p = h
i = l-1
for j in range(l,h):
if a[j] <= a[p]:
i+=1
a[i],a[j]=a[j],a[i]
a[i+1],a[h]=a[h],a[i+1]
return i+1
def quickSort(a,l,h):
if l<h:
x=partition(a,l,h)
quickSort(a,l,x-1)
quickSort(a,x+1,h)
a = [97, 42, 1, 24, 63, 94, 2]
quickSort(a,0,len(a)-1)
print(a)
|
def mergesort(array, byfunc=None):
pass
class Stack:
pass
class EvaluateExpression:
pass
def get_smallest_three(challenge):
records = challenge.records
times = [r for r in records]
mergesort(times, lambda x: x.elapsed_time)
return times[:3]
|
authType = {
"access_token": str,
"token_type": str,
}
|
# 8. Print an array - Given an array of integers prints all the elements one per line. This
# is a little bit dierent as there is no need for a 'return' statement just to print and recurse.
# Define the function
def print_array(array):
# Set the base case, in this case, when the length of the array is 0.
... |
# Copyright (c) 2018 European Organization for Nuclear Research.
# All Rights Reserved.
#
# 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/LIC... |
#
# @lc app=leetcode.cn id=1190 lang=python3
#
# [1190] 反转每对括号间的子串
#
# https://leetcode-cn.com/problems/reverse-substrings-between-each-pair-of-parentheses/description/
#
# algorithms
# Medium (58.98%)
# Likes: 144
# Dislikes: 0
# Total Accepted: 27.8K
# Total Submissions: 43.5K
# Testcase Example: '"(abcd)"'
#
... |
user_password = 's3cr3t!P@ssw0rd'
input_password = input()
if input_password == user_password:
print('Welcome')
else:
print('Wrong password!')
|
def sum_fucntion(arr, i, N):
if i > N - 1:
return 0
return int(arr[i]) + sum_fucntion(arr, i + 1, N)
def main():
N = int(input())
arr = input()
print(sum_fucntion(arr, 0, N))
if __name__ == "__main__":
main()
|
# to convert list to dictionary
x="SecondName FirstName Intials "
y= x.split(" ") #this will create list "y"
print("Type yourname with Firstname Secondname Intials")
a=input()
b = a.split(" ") #this will create input to list
resultdict = {}
for index in y:
for value in b:
resultdict[index] = value
b... |
# Given a set of non-overlapping intervals, insert a new interval into the
# intervals (merge if necessary).
# You may assume that the intervals were initially sorted according to their
# start times.
# Example 1:
# Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
# Output: [[1,5],[6,9]]
# Example 2:
# Input: in... |
def succeed(*cmds):
"""Returns the concatenated output of all cmds"""
return machine.succeed(*cmds)
def assert_matches(cmd, regexp):
out = succeed(cmd)
if not re.search(regexp, out):
raise Exception(f"Pattern '{regexp}' not found in '{out}'")
def assert_matches_exactly(cmd, regexp):
out ... |
# Interview Question 3.3
class SetOfStacks(object):
def __init__(self, threshold):
if threshold <= 0:
raise ValueError('Invalid threshold value')
self._threshold = threshold
self._stacks = []
def __len__(self):
return len(self._stacks)
def push(self, item):
... |
#!/usr/bin/python3.5
# import time
def kosaraju_strongly_connected_components():
# input_file_name = 'kosaraju_SCC_test_result_is_3_3_3_0_0.txt'
# input_file_name = 'kosaraju_SCC_test_result_is_6_3_2_1_0.txt'
input_file_name = 'kosaraju_SCC_input.txt'
print('Creating adjacency lists')
adjacency_list = []
... |
"""MCAS Exceptions."""
class FormatCEFError(Exception):
"""CEF Format Error class."""
pass
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class CEFValueError(FormatCEFError, ValueError):
"""Exception raised for invalid value mappings.
:attribute: message --... |
def debug_input_output(function):
def wrapper(*args, **kwargs):
print(f"[INPUT] ARGS: {args}")
print(f"[INPUT] KWARGS: {kwargs}")
output = function(*args, **kwargs)
print(f"[OUTPUT]: {output}")
return output
return wrapper
@debug_input_output
de... |
class Solution:
def stoneGame(self, piles: List[int]) -> bool:
# dp = [[0]*len(piles) for _ in range(len(piles))]
# for i in range(len(piles)-2,-1,-1):
# for j in range(i,len((piles))):
# dp[i][j] = max(piles[i]-dp[i+1][j],piles[j]-dp[i][j-1])
# return dp[0][len(p... |
# k_configfile = "configFileName"
# dev keys
packageName = "infobot"
socialModule = "social."
storageModule = "storage."
# storage keys
dataDirectoryKey = "directory"
counterKey = "counterfile"
indexFileFormatKey = "indexformat"
pickleFileKey = "picklefile"
downloadUrlKey = "downloadurl"
# index related keys
startKe... |
#generar tuplas
tupla1=(1,2,3)
tupla2_=(1,) #sirve para crear una tupla con un solo componente
|
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'conditions': [
# In component mode (shared_lib), we build all of skia as a single DLL.
# However, in the static mode, we need to build skia ... |
RAW_PATH="./data/PeMS_04/PeMS04.npz"
SCAL_PATH='./scal/standard_scal.pkl'
HISTORY_WINDOW=50
PROCESS_PATH='./processed/process_data.csv'
LSTM_RE_PATH='./re/LSTM_re.csv'
GRU_RE_PATH='./re/GRU_re.csv'
GRU_ATTENTION_RE_PATH='./re/GRU_attention_re.csv'
GRU_DUAL_STAGE_ATTENTION_RE_PATH='./re/gru_dual_stage_attention_re.c... |
# This script is dynamically added as a subclass in tool_dock_examples.py
def main():
print("This is a script that prints when evaluated")
if __name__ == "__main__":
main()
|
myList = [16, 1, 10, 31, 15, 11, 47, 23, 47, 3, 29, 23, 44, 27, 10, 14, 17, 15, 1, 38, 7, 7, 25, 1, 8, 15, 16, 20, 12,
14, 6, 10, 39, 42, 33, 26, 30, 27, 25, 13, 11, 26, 39, 19, 15, 21, 22]
starting_index = int(input("Please enter the starting index: "))
if 0 <= starting_index <= len(myList):
stopping... |
class PresentationException(Exception):
"""Exception raised when you try to create a Presentation Link for an asset
that already has one.
"""
def __init__(
self, message="Your asset already has a presentation link associated with it."
):
self.message = message
super().__init... |
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
n1 = len(word1)
n2 = len(word2)
dp = []
for i in range(n1+1):
dp.append([0]*(n2+1))
for i in range(1, n1+1):
for j in range(1, n2+1):
if(word1[i-1] == word2[j-1]):
... |
"Install toolchain dependencies"
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@build_bazel_rules_nodejs//:index.bzl", "yarn_install")
load(":mock_io_bazel_rules_closure.bzl", "mock_io_bazel_rules_closure")
def npm_bazel_labs_dependencies():
"""
Fetch our transitive dependencies.
... |
def solution(n):
largest = 1
div = 2
while n > 1:
while n % div == 0:
if div > largest: largest = div;
n /= div
div += 1
if div * div > n:
if n > 1 and n > largest: largest = n
break
return largest
def test_LargestPrimeFactor():
... |
class Pile:
def __init__(self, *args):
self.__valeur = list(args)
def __str__(self):
return str(self.__valeur)
def __repr__(self):
return self.__str__()
def empiler(self, valeur):
self.__valeur.append(valeur)
def depiler(self):
return self.__... |
text = input("Text to translate to Roachanese: ")
words = text.split(" ")
special_chars = ['.', ',', ';', ':', '-', '_', '\'', '\"', '?', '!', '$', '%', '&', '*', '(', ')', '/', '\\']
translated = []
for word in words:
if "brother" in word:
translated.append(word)
else:
newWord = word
... |
# Author: Kirill Leontyev (DC)
# These exceptions can be raised by frt_bootstrap.boot_starter.boot.
class Boot_attempt_failure(Exception):
pass
class System_corruption(Exception):
pass
class Localization_loss(Exception):
pass
class CodePage_loss(Exception):
pass
|
#!/usr/bin/python
#
# Copyright 2018-2022 Polyaxon, 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 ... |
class Scheduler:
"""
Class to represent to Traffic Scheduler that manages the traffic signal
at a particular intersection.
"""
def __init__(self, n_roads, n_lanes, k_c, k_a, k_w, thresh=10, current=-1):
"""
Constructs the Traffic Scheduler object.
:param n_roads: Number of independent roads at this interse... |
#!/usr/bin/env python3
#
# # Copyright (c) 2021 Facebook, inc. and its affiliates. All Rights Reserved
#
#
if __name__ == '__main__':
pass
|
'''
Wifi Facade.
=============
The :class:`Wifi` is to provide access to the wifi of your mobile/ desktop
devices.
It currently supports `connecting`, `disconnecting`, `scanning`, `getting
available wifi network list` and `getting network information`.
Simple examples
---------------
To enable/ turn on wifi scannin... |
# [기초-산술연산] 정수 1개 입력받아 부호 바꿔 출력하기(설명)
# minso.jeong@daum.net
'''
문제링크 : https://www.codeup.kr/problem.php?id=1040
'''
n = int(input())
print(-1 * n) |
def get_encoder_decoder_hp(model='gin', decoder=None):
if model == 'gin':
model_hp = {
# hp from model
"num_layers": 5,
"hidden": [64,64,64,64],
"dropout": 0.5,
"act": "relu",
"eps": "False",
"mlp_layers": 2
}
i... |
Experiment(description='Trying latest code on classic data sets',
data_dir='../data/tsdlr-renamed/',
max_depth=10,
random_order=False,
k=1,
debug=False,
local_computation=False,
n_rand=9,
sd=2,
jitter_sd=0.1,
... |
#!/usr/bin/env python3
total_sum = 0
def calculate_fuel(mass: int) -> int:
part = int((mass/3)-2)
if part <= 0:
return 0
print(part)
return part + calculate_fuel(part)
with open("input.txt", "r") as f:
for line in f.readlines():
value = int(line.strip())
total_sum += calcul... |
# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## Customize your APP title, subtitle and menus here
#########################################################################
response.logo... |
with open('day08.input') as f:
data = [int(x) for x in f.read().split()]
class Node:
def __init__(self):
self.metadata = []
self.children = []
def add_child(self, obj):
self.children.append(obj)
def set_metadata(self, obj):
self.metadata = obj
def build_node(current... |
__all__ = ['MAJOR_VERSION', 'MINOR_VERSION', 'PATCH', 'TAG', \
'VERSION', 'TEXT_VERSION',
'JSONSCHEMA_SPECIFICATION']
JSONSCHEMA_SPECIFICATION = 'draft-07'
MAJOR_VERSION = 2
MINOR_VERSION = 2
PATCH = 0
TAG = 'master'
VERSION = (MAJOR_VERSION,
MINOR_VERSION,
PATCH,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.