content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#punto 1
#entradas
n=int(input("Escriba el primer digito "))
k=int(input("Escriba el primer digito "))
#caja negra y salidas
while True:
n=0
if(k<n):
n=n-1
print(n)
elif(n==k):
print(k)
break | n = int(input('Escriba el primer digito '))
k = int(input('Escriba el primer digito '))
while True:
n = 0
if k < n:
n = n - 1
print(n)
elif n == k:
print(k)
break |
class CandeError(Exception):
pass
class CandeSerializationError(CandeError):
pass
class CandeDeserializationError(CandeError):
pass
class CandeReadError(CandeError):
pass
class CandePartError(CandeError):
pass
class CandeFormatError(CandePartError):
pass
| class Candeerror(Exception):
pass
class Candeserializationerror(CandeError):
pass
class Candedeserializationerror(CandeError):
pass
class Candereaderror(CandeError):
pass
class Candeparterror(CandeError):
pass
class Candeformaterror(CandePartError):
pass |
items = ['T-Shirt','Sweater']
print("*** Note: If you want to quit this program, simply type 'quit' or 'QUIT'.")
print("*" * 20)
while True:
action = (input("Welcome to our shop, what do you want (C, R, U, D)? ")).upper()
if action == "R":
print("Our items: ", end='')
print(*items,sep=', ')
... | items = ['T-Shirt', 'Sweater']
print("*** Note: If you want to quit this program, simply type 'quit' or 'QUIT'.")
print('*' * 20)
while True:
action = input('Welcome to our shop, what do you want (C, R, U, D)? ').upper()
if action == 'R':
print('Our items: ', end='')
print(*items, sep=', ')
... |
'''
Catalan numbers (Cn) are a sequence of natural numbers that
occur in many places. The most important ones being that Cn
gives the number of Binary Search Trees possible with n values.
Cn is the number of full Binary Trees with n + 1 leaves.
Cn is the number of different ways n + 1 factors can be... | """
Catalan numbers (Cn) are a sequence of natural numbers that
occur in many places. The most important ones being that Cn
gives the number of Binary Search Trees possible with n values.
Cn is the number of full Binary Trees with n + 1 leaves.
Cn is the number of different ways n + 1 factors can be... |
# operador logico
print("Ingrese el valor de a")
a = float(input())
print("Ingrese el valor de b")
b = float(input())
print("b es mayor que a")
print(b > a)
print(type(b > a))
print("b es menor que a")
print(b < a)
print("b es mayor o igual que a")
print(b >= a)
print("b es menor o igual que a")
print(b <= a)
print("b ... | print('Ingrese el valor de a')
a = float(input())
print('Ingrese el valor de b')
b = float(input())
print('b es mayor que a')
print(b > a)
print(type(b > a))
print('b es menor que a')
print(b < a)
print('b es mayor o igual que a')
print(b >= a)
print('b es menor o igual que a')
print(b <= a)
print('b es diferente de a'... |
def similar_users_query(user):
# Pass user object, return query to get users who starred same things as them
query = """
select subq.user_id
, sum(1/log(subq.stargazers_count+1)) `score`
, count(*) `count`
from
(select others.user_id
, others.starred_re... | def similar_users_query(user):
query = '\n select subq.user_id\n , sum(1/log(subq.stargazers_count+1)) `score`\n , count(*) `count`\n from\n (select others.user_id\n , others.starred_repo_id\n , repo.repo_name\n , repo.description\n ... |
# Copyright (c) 2017 Cisco and/or its affiliates.
# 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 ag... | """This file defines the constants variables for the TLDK test."""
class Tldkconstants(object):
"""Define the directory path for the TLDK test."""
remote_fw_dir = '/tmp/TLDK-testing'
tldk_scripts = 'tests/tldk/tldk_scripts'
tldk_deplibs = 'tests/tldk/tldk_deplibs'
tldk_testconfig = 'tests/tldk/tldk... |
class d_linked_node:
def __init__(self, initData, initNext, initPrevious):
# constructs a new node and initializes it to contain
# the given object (initData) and links to the given next
# and previous nodes.
self.__data = initData
self.__next = initNext
... | class D_Linked_Node:
def __init__(self, initData, initNext, initPrevious):
self.__data = initData
self.__next = initNext
self.__previous = initPrevious
if initPrevious != None:
initPrevious.__next = self
if initNext != None:
initNext.__previous = self... |
#python program to subtract two numbers using function
def subtraction(x,y): #function definifion for subtraction
sub=x-y
return sub
num1=int(input("please enter first number: "))#input from user to num1
num2=int(input("please enter second number: "))#input from user to num2
print("Subtraction is: ",subtract... | def subtraction(x, y):
sub = x - y
return sub
num1 = int(input('please enter first number: '))
num2 = int(input('please enter second number: '))
print('Subtraction is: ', subtraction(num1, num2)) |
'''
Package to read and process material export data.
To use, initiate an endomaterial object and start exploring!
---------
Examples:
## Init
from ukw_intelli_store import EndoMaterial
em = EndoMaterial(path, path)
## To explore all used materials:
em.mat_info
## To explore specific material id
em.get_mat_info_f... | """
Package to read and process material export data.
To use, initiate an endomaterial object and start exploring!
---------
Examples:
## Init
from ukw_intelli_store import EndoMaterial
em = EndoMaterial(path, path)
## To explore all used materials:
em.mat_info
## To explore specific material id
em.get_mat_info_f... |
# Source: https://www.geeksforgeeks.org/sets-in-python/
# Python program to
# demonstrate intersection
# of two sets
set1 = [0,1,2,3,4,5]
set2 = [3,4,5,6,7,8,9]
set3 = set1 + set2
unique_set3 = []
for i in set3:
if i not in unique_set3:
unique_set3.append(i)
print("Intersection using intersecti... | set1 = [0, 1, 2, 3, 4, 5]
set2 = [3, 4, 5, 6, 7, 8, 9]
set3 = set1 + set2
unique_set3 = []
for i in set3:
if i not in unique_set3:
unique_set3.append(i)
print('Intersection using intersection() function')
print(set3)
print(unique_set3) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" ib.ext.cfg.EWrapperMsgGenerator -> config module for EWrapperMsgGenerator.java.
"""
modulePreamble = [
'from ib.ext.AnyWrapperMsgGenerator import AnyWrapperMsgGenerator',
'from ib.ext.Util import Util',
]
| """ ib.ext.cfg.EWrapperMsgGenerator -> config module for EWrapperMsgGenerator.java.
"""
module_preamble = ['from ib.ext.AnyWrapperMsgGenerator import AnyWrapperMsgGenerator', 'from ib.ext.Util import Util'] |
class Validator:
PLUS_CHAR = 43
AT_CHAR = 64
def __init__(self):
self.validation_results = None
self.sequence_symbols = list()
for symbol in "ACTGN.":
self.sequence_symbols.append(ord(symbol))
self.quality_score_symbols = list()
for symbol in "!\"#$%&'()*... | class Validator:
plus_char = 43
at_char = 64
def __init__(self):
self.validation_results = None
self.sequence_symbols = list()
for symbol in 'ACTGN.':
self.sequence_symbols.append(ord(symbol))
self.quality_score_symbols = list()
for symbol in '!"#$%&\'()*... |
#work in prgress - This creates a skelatal mods file for the givne set of files
templateFile = "C:\\python-scripts\\xml-file-output\\aids_skeletalmods.xml"
def createXmlFiles(idList):
print("create xml file list")
for id in idList:
#print("processing id " + id )
tree = ElementTree()
t... | template_file = 'C:\\python-scripts\\xml-file-output\\aids_skeletalmods.xml'
def create_xml_files(idList):
print('create xml file list')
for id in idList:
tree = element_tree()
tree.parse(templateFile)
root = tree.getroot()
name_element = tree.find('titleInfo/title')
nam... |
j,i=65,-2
for I in range (1,14):
J= j-5
I=i+3
print('I=%d J=%d' %(I,J))
j=J
i=I | (j, i) = (65, -2)
for i in range(1, 14):
j = j - 5
i = i + 3
print('I=%d J=%d' % (I, J))
j = J
i = I |
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isMirror(self, left: TreeNode, right: TreeNode) -> bool:
if left is None and right is None:
return True
elif left is not ... | class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def is_mirror(self, left: TreeNode, right: TreeNode) -> bool:
if left is None and right is None:
return True
elif left is no... |
class Solution(object):
def maxRotateFunction(self, A):
"""
:type A: List[int]
:rtype: int
"""
totalSum = sum(A)
Al = len(A)
F = {0:0}
for i in range(Al):
F[0] += i * A[i]
maxNum = F[0]
... | class Solution(object):
def max_rotate_function(self, A):
"""
:type A: List[int]
:rtype: int
"""
total_sum = sum(A)
al = len(A)
f = {0: 0}
for i in range(Al):
F[0] += i * A[i]
max_num = F[0]
for i in range(Al - 1, 0, -1):
... |
class Config:
# image size
image_min_dims = 512
image_max_dims = 512
steps_per_epoch = 50
validation_steps = 20
batch_size = 16
epochs = 10
shuffle = True
num_classes = 21
| class Config:
image_min_dims = 512
image_max_dims = 512
steps_per_epoch = 50
validation_steps = 20
batch_size = 16
epochs = 10
shuffle = True
num_classes = 21 |
'''https://leetcode.com/problems/course-schedule/
207. Course Schedule
Medium
7445
303
Add to List
Share
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if ... | """https://leetcode.com/problems/course-schedule/
207. Course Schedule
Medium
7445
303
Add to List
Share
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if ... |
# SPDX-FileCopyrightText: Copyright (C) 2019-2021 Ryan Finnie
# SPDX-License-Identifier: MIT
class SMWRand:
"""Super Mario World random number generator
Based on deconstruction by Retro Game Mechanics Explained
https://www.youtube.com/watch?v=q15yNrJHOak
"""
# SPDX-SnippetComment: Originally fro... | class Smwrand:
"""Super Mario World random number generator
Based on deconstruction by Retro Game Mechanics Explained
https://www.youtube.com/watch?v=q15yNrJHOak
"""
seed_1 = 0
seed_2 = 0
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
... |
#===================================================================================================================================================================================
# Author: Shlomo Stept
# ccvaliditycheck.py will open up a window and determine if any credit card number; entered by the user, is valid.
#... | user_input = input('Enter Your Credit Card Number as a long integer: ')
total_even = 0
total_odd = 0
numberof_variables = len(userInput)
count_even = numberofVariables - 2
count_odd = numberofVariables - 1
if numberofVariables > 12 and numberofVariables < 20:
for loopcounter in range(numberofVariables, 0, -2):
... |
# Time complexity: O(n)
# Approach: Manacher's Algorithm. Please watch this vide for explanation https://youtu.be/V-sEwsca1ak
class Solution:
def longestPalindrome(self, s: str) -> str:
newS = ""
n = 2 * len(s) + 1
ind = 0
for j in range(n):
if j % 2 == 1:
... | class Solution:
def longest_palindrome(self, s: str) -> str:
new_s = ''
n = 2 * len(s) + 1
ind = 0
for j in range(n):
if j % 2 == 1:
new_s += s[ind]
ind += 1
else:
new_s += '$'
lps = [0] * n
(sta... |
def is_index_valid(i, length):
return 0 <= i < length
initial_loot = input().split('|')
while True:
line = input()
if line == 'Yohoho!':
break
command = line.split(' ', maxsplit=1)
if command[0] == 'Loot':
items = command[1].split()
for item in items:
... | def is_index_valid(i, length):
return 0 <= i < length
initial_loot = input().split('|')
while True:
line = input()
if line == 'Yohoho!':
break
command = line.split(' ', maxsplit=1)
if command[0] == 'Loot':
items = command[1].split()
for item in items:
if item not ... |
__author__ = 'Administrator'
# class Foo(object):
# instance = None
#
# def __init__(self):
# self.name = 'alex'
# @classmethod
# def get_instance(cls):
# if Foo.instance:
# return Foo.instance
# else:
# Foo.instance = Foo()
# return Foo.insta... | __author__ = 'Administrator'
class Foo(object):
instance = None
def __init__(self):
self.name = 'alex'
def __new__(cls, *args, **kwargs):
if Foo.instance:
return Foo.instance
else:
Foo.instance = object.__new__(cls, *args, **kwargs)
return Foo.i... |
# Requer atributo e atributo_comp = {"atributo": int (id_atributo), "atributo_comp" : int (id_atributo)}
select_efetividades = lambda : """
Select fator
FROM efetividades
WHERE atributo = :atributo
AND atributo_comp = :atributo_comp
""" | select_efetividades = lambda : '\n Select fator \n FROM efetividades \n WHERE atributo = :atributo \n AND atributo_comp = :atributo_comp\n' |
inputfile = open('primes.txt')
lista = inputfile.read().split(',')
inputfile.close()
lista = sorted([int(i) for i in lista])
outputfile = open('primes_sorted.txt', 'w')
for i in lista:
outputfile.write(str(i)+',')
| inputfile = open('primes.txt')
lista = inputfile.read().split(',')
inputfile.close()
lista = sorted([int(i) for i in lista])
outputfile = open('primes_sorted.txt', 'w')
for i in lista:
outputfile.write(str(i) + ',') |
inp = input("Input roman numerals: ").upper() + " "
tot = 0
numeralDict = {
"I":1,
"V":5,
"X":10,
"L":50,
"C":100,
"D":500,
"M":1000
}
inp = list(inp)
for charNum in range(len(inp)):
char = inp[charNum]
if(char == "I"):
if(inp[charNum + 1] != "I" and inp[charNum + 1] != " "... | inp = input('Input roman numerals: ').upper() + ' '
tot = 0
numeral_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
inp = list(inp)
for char_num in range(len(inp)):
char = inp[charNum]
if char == 'I':
if inp[charNum + 1] != 'I' and inp[charNum + 1] != ' ':
tot -= 1
... |
f=open('countlines.txt','rt')
n=0
for i in f:
n+=1
print(n)
f.close()
| f = open('countlines.txt', 'rt')
n = 0
for i in f:
n += 1
print(n)
f.close() |
our_method_top50_dict = {
2: {
'is_hired_1mo': 0.98,
'is_unemployed': 0.98,
'lost_job_1mo': 0.74,
'job_search': 0.12,
'job_offer': 1.0},
0: {
'is_hired_1mo': 0.92,
'is_unemployed': 0.06,
'lost_job_1mo': 0.3,
'job_search': 1.0,
'job_... | our_method_top50_dict = {2: {'is_hired_1mo': 0.98, 'is_unemployed': 0.98, 'lost_job_1mo': 0.74, 'job_search': 0.12, 'job_offer': 1.0}, 0: {'is_hired_1mo': 0.92, 'is_unemployed': 0.06, 'lost_job_1mo': 0.3, 'job_search': 1.0, 'job_offer': 1.0}, 1: {'is_hired_1mo': 1.0, 'is_unemployed': 0.72, 'lost_job_1mo': 0.88, 'job_se... |
def solve() -> int:
n, a, b, x, y, z = map(int, input().split())
y = min(y, a * x)
z = min(z, b * x)
if y * b > z * a:
a, b = b, a
y, z = z, y
mn_cost = 1 << 60
if n // a <= a - 1:
for i in range(n // a + 1):
j, k = divmod(n - i * a, b)
... | def solve() -> int:
(n, a, b, x, y, z) = map(int, input().split())
y = min(y, a * x)
z = min(z, b * x)
if y * b > z * a:
(a, b) = (b, a)
(y, z) = (z, y)
mn_cost = 1 << 60
if n // a <= a - 1:
for i in range(n // a + 1):
(j, k) = divmod(n - i * a, b)
... |
# Problem Statement: https://leetcode.com/problems/climbing-stairs/
class Solution:
def climbStairs(self, n: int) -> int:
# Base Cases
if n==1:
return 1
if n==2:
return 2
# Memoization
memo_table = [1]*(n+1)
# Initializati... | class Solution:
def climb_stairs(self, n: int) -> int:
if n == 1:
return 1
if n == 2:
return 2
memo_table = [1] * (n + 1)
memo_table[1] = 1
memo_table[2] = 2
for i in range(3, n + 1):
memo_table[i] = memo_table[i - 1] + memo_table[... |
#concatenation
# youtuber = " varun verma" #some string concatenation
# print("subscribe to "+ youtuber)
# print("subscribe to {}" .format(youtuber))
# print(f"subscriber to {youtuber}")
adj= input("Adjective: ")
verb1 = input("Verb: ")
verb2 = input("Verb: ")
famous_person = input("Famous Person: ")
madlib = f"Comput... | adj = input('Adjective: ')
verb1 = input('Verb: ')
verb2 = input('Verb: ')
famous_person = input('Famous Person: ')
madlib = f'Computer is so {adj}! it makes me so excited all the time because I like to {verb1}. Stay hydrated and {verb2} like you are {famous_person}'
print(madlib) |
class Solution:
def XXX(self, nums: List[int]) -> bool:
l = len(nums)
start = l-1
end = 1
for index in range(1,l):
val = nums[start - index]
if val >= end:
end = 1
else:
end += 1
return end == 1
| class Solution:
def xxx(self, nums: List[int]) -> bool:
l = len(nums)
start = l - 1
end = 1
for index in range(1, l):
val = nums[start - index]
if val >= end:
end = 1
else:
end += 1
return end == 1 |
# Sage version information for Python scripts
# This file is auto-generated by the sage-update-version script, do not edit!
version = '9.5.beta2'
date = '2021-09-26'
banner = 'SageMath version 9.5.beta2, Release Date: 2021-09-26'
| version = '9.5.beta2'
date = '2021-09-26'
banner = 'SageMath version 9.5.beta2, Release Date: 2021-09-26' |
def createTree(self, root, *elements):
root = None
for element in elements:
root = self.insert(root, element)
return root | def create_tree(self, root, *elements):
root = None
for element in elements:
root = self.insert(root, element)
return root |
class ClassList(list):
def __init__(self):
self.OnClassListChange = lambda *args,**kwargs:0
def AddClass(self,Cls, notify = True):
if Cls not in self:
self.append(Cls)
if notify:self.OnClassListChange(added = self[-1])
def RemoveClass(self, Cls, notify = True):
... | class Classlist(list):
def __init__(self):
self.OnClassListChange = lambda *args, **kwargs: 0
def add_class(self, Cls, notify=True):
if Cls not in self:
self.append(Cls)
if notify:
self.OnClassListChange(added=self[-1])
def remove_class(self, Cls, n... |
'''
Defines `Error`, the base class for all exceptions generated in this package.
'''
class Error(Exception):
pass
| """
Defines `Error`, the base class for all exceptions generated in this package.
"""
class Error(Exception):
pass |
def can_build(env, platform):
return True
def configure(env):
pass
def get_doc_classes():
return [
"WorldArea",
"VoxelLight",
"VoxelmanLight",
"VoxelmanLevelGenerator",
"VoxelmanLevelGeneratorFlat",
"VoxelSurfaceMerger",
"VoxelSurfaceSimple",
... | def can_build(env, platform):
return True
def configure(env):
pass
def get_doc_classes():
return ['WorldArea', 'VoxelLight', 'VoxelmanLight', 'VoxelmanLevelGenerator', 'VoxelmanLevelGeneratorFlat', 'VoxelSurfaceMerger', 'VoxelSurfaceSimple', 'VoxelSurface', 'VoxelmanLibraryMerger', 'VoxelmanLibrarySimple'... |
#
# PySNMP MIB module Fore-J2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Fore-J2-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:17:14 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... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, constraints_union, value_range_constraint, constraints_intersection) ... |
n = int(input())
lado = 2
for i in range(n):
lado = 2*lado-1
print(lado*lado)
| n = int(input())
lado = 2
for i in range(n):
lado = 2 * lado - 1
print(lado * lado) |
class SequentialSearchST():
first = None
class Node():
def __init__(self, key, val, next):
self.key = key
self.val = val
self.next = next
def get(self, key):
x = self.first
while x is not None:
if key == x.key:
return x.val
x = x.next
return None
def ... | class Sequentialsearchst:
first = None
class Node:
def __init__(self, key, val, next):
self.key = key
self.val = val
self.next = next
def get(self, key):
x = self.first
while x is not None:
if key == x.key:
return x.v... |
class Solution:
def findNumberIn2DArray(self, matrix, target: int) -> bool:
if not matrix:
return False
n,m=len(matrix),len(matrix[0])
if m==0:
return False
row,col=0,m-1
while 1:
print(row,col)
cur=matrix[row][col]
... | class Solution:
def find_number_in2_d_array(self, matrix, target: int) -> bool:
if not matrix:
return False
(n, m) = (len(matrix), len(matrix[0]))
if m == 0:
return False
(row, col) = (0, m - 1)
while 1:
print(row, col)
cur = m... |
class StackCollection:
def __init__(self, client=None, data=None):
super(StackCollection, self).__init__()
if data is None:
paginator = client.get_paginator('describe_stacks')
results = paginator.paginate()
self.list = list()
for result in results:
... | class Stackcollection:
def __init__(self, client=None, data=None):
super(StackCollection, self).__init__()
if data is None:
paginator = client.get_paginator('describe_stacks')
results = paginator.paginate()
self.list = list()
for result in results:
... |
"""
import a
import a.b
import a.B (and is the cross thing)
import a.*
import a.b as c
from a import b, c
import a, b
from _ import *
"""
# objects see their own vars
# function args are seen ((x)->x)(2)
# import bogus
# errors
# bogus -> NameError
"""
del list[index]
del x
del dict[key]
delete o... | """
import a
import a.b
import a.B (and is the cross thing)
import a.*
import a.b as c
from a import b, c
import a, b
from _ import *
"""
'\ndel list[index]\ndel x\ndel dict[key]\n\ndelete object.member, which removes member as a key from object\n\nonly related to:\ndynamics\ndicts\nreloading modules\ngc or c++ memory ... |
# author: Allyson Vasquez
# version: May.14.2020
# Practice using functions & lists
# https://www.w3resource.com/python-exercises/python-functions-exercises.php
# Find the max of three numbers
def max(x,y,z):
if x > y or x == y:
num1 = x
else:
num1 = y
if num1 > z or num1 == z:
ma... | def max(x, y, z):
if x > y or x == y:
num1 = x
else:
num1 = y
if num1 > z or num1 == z:
max_num = num1
else:
max_num = z
return max_num
def sum(x):
total = 0
for i in range(len(x)):
total += x[i]
return total
def factorial(x):
fac = 1
if ... |
# pylint: disable=missing-docstring
__title__ = "estraven"
__summary__ = "An opinionated YAML formatter for Ansible playbooks"
__version__ = "0.0.0"
__url__ = "https://github.com/enpaul/estraven/"
__license__ = "MIT"
__authors__ = ["Ethan Paul <24588726+enpaul@users.noreply.github.com>"]
| __title__ = 'estraven'
__summary__ = 'An opinionated YAML formatter for Ansible playbooks'
__version__ = '0.0.0'
__url__ = 'https://github.com/enpaul/estraven/'
__license__ = 'MIT'
__authors__ = ['Ethan Paul <24588726+enpaul@users.noreply.github.com>'] |
"""
0034. Find First and Last Position of Element in Sorted Array
Medium
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
Follow up: Could you write an algorithm with O(log n) runtime comple... | """
0034. Find First and Last Position of Element in Sorted Array
Medium
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
Follow up: Could you write an algorithm with O(log n) runtime comple... |
def parallel_generator(generators, functors):
"""
:param generators: A list of k generators (initialized) repersenting files,
file are sorted with respect to the functors.
:param functors: A list of k functors (must be the same size as the generators),
... | def parallel_generator(generators, functors):
"""
:param generators: A list of k generators (initialized) repersenting files,
file are sorted with respect to the functors.
:param functors: A list of k functors (must be the same size as the generators),
... |
concept_detector_cfg = dict(
quantile_threshold=0.99,
with_bboxes=True,
count_disjoint=True,
)
target_layer = 'layer3.5'
| concept_detector_cfg = dict(quantile_threshold=0.99, with_bboxes=True, count_disjoint=True)
target_layer = 'layer3.5' |
method1 = []
method2 = []
with open("out.raw", "rb") as file:
byteValue = file.read(2)
while byteValue != b"":
intValueOne = int.from_bytes(byteValue, "big", signed=True)
intValueTwo = int.from_bytes(byteValue, "little", signed=True)
method1.append(intValueOne)
method2.append... | method1 = []
method2 = []
with open('out.raw', 'rb') as file:
byte_value = file.read(2)
while byteValue != b'':
int_value_one = int.from_bytes(byteValue, 'big', signed=True)
int_value_two = int.from_bytes(byteValue, 'little', signed=True)
method1.append(intValueOne)
method2.appen... |
#
# PySNMP MIB module CISCO-TELEPRESENCE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-TELEPRESENCE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:14:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, constraints_intersection, single_value_constraint, value_size_constraint) ... |
class SearchModule:
def __init__(self):
pass
def search_for_competition_by_name(self, competitions, query):
m, answer = self.search(competitions, attribute_name="caption", query=query)
if m == 0:
return False
return answer
def search_for_competition_by_code(self... | class Searchmodule:
def __init__(self):
pass
def search_for_competition_by_name(self, competitions, query):
(m, answer) = self.search(competitions, attribute_name='caption', query=query)
if m == 0:
return False
return answer
def search_for_competition_by_code(s... |
""" Write a program to display values of variables in Python. """
message = "Keep Smiling!"
print(message)
userNo = 101
print("User No is ", userNo)
gender = 'M'
print("Gender: ",gender)
| """ Write a program to display values of variables in Python. """
message = 'Keep Smiling!'
print(message)
user_no = 101
print('User No is ', userNo)
gender = 'M'
print('Gender: ', gender) |
load("@io_bazel_rules_dotnet//dotnet:defs.bzl", "core_library", "core_resource")
filegroup(
name = "core_common",
srcs = [
":src/common/ExceptionExtensions.cs",
":src/common/Guard.cs",
":src/common/TestMethodDisplay.cs",
":src/common/TestMethodDisplayOptions.cs",
] + ["@xuni... | load('@io_bazel_rules_dotnet//dotnet:defs.bzl', 'core_library', 'core_resource')
filegroup(name='core_common', srcs=[':src/common/ExceptionExtensions.cs', ':src/common/Guard.cs', ':src/common/TestMethodDisplay.cs', ':src/common/TestMethodDisplayOptions.cs'] + ['@xunit_assert//:common_files'])
core_resource(name='xunit_... |
res = []
with open('test.txt', mode='r', encoding="utf-8") as f:
for line in f:
arr = line.split()
print(arr)
res.append(arr[1])
r = '\t'.join(res)
with open('res.txt', mode='w', encoding="utf-8") as f:
# print(r)
f.write(r) | res = []
with open('test.txt', mode='r', encoding='utf-8') as f:
for line in f:
arr = line.split()
print(arr)
res.append(arr[1])
r = '\t'.join(res)
with open('res.txt', mode='w', encoding='utf-8') as f:
f.write(r) |
class GuildConfig:
def __init__(self, data):
self._data = data
self.prefix = self.settings['prefix']
self.offset = self.settings['offset']
self.regional_pkmn = self.settings['regional']
self.has_configured = self.settings['done']
@property
def settings(self):
... | class Guildconfig:
def __init__(self, data):
self._data = data
self.prefix = self.settings['prefix']
self.offset = self.settings['offset']
self.regional_pkmn = self.settings['regional']
self.has_configured = self.settings['done']
@property
def settings(self):
... |
# -*- coding: utf-8 -*-
"""Top-level package for Elejandria Libros chef."""
__author__ = """Learning Equality"""
__email__ = 'benjamin@learningequality.org'
__version__ = '0.1.0'
| """Top-level package for Elejandria Libros chef."""
__author__ = 'Learning Equality'
__email__ = 'benjamin@learningequality.org'
__version__ = '0.1.0' |
"""
# Definition for a Node.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
"""
class Solution:
def treeToDoublyList(self, root: 'Node') -> 'Node':
if not root: return None
nodes = []
def inorder(roo... | """
# Definition for a Node.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
"""
class Solution:
def tree_to_doubly_list(self, root: 'Node') -> 'Node':
if not root:
return None
nodes = []
... |
def solution(salaries: list[int]) -> int:
return sorted(salaries)[1]
if __name__ == '__main__':
user_input = input()
param = [int(x) for x in user_input.split()]
print(solution(salaries=param))
| def solution(salaries: list[int]) -> int:
return sorted(salaries)[1]
if __name__ == '__main__':
user_input = input()
param = [int(x) for x in user_input.split()]
print(solution(salaries=param)) |
#adding two numbers
num1 = 2
num2 = 3
sum = num1 + num2
print("The sum is:", sum) | num1 = 2
num2 = 3
sum = num1 + num2
print('The sum is:', sum) |
""" Cube class contains the logic for maintaining the current
state of the container, or Bedlam Cube, and methods for
checking, inserting, and removing individual Shape objects
from the cube space. """
""" Each Cube is made up of X * Y * Z Cuboids, Each of which
for simplicities sakes contain all the... | """ Cube class contains the logic for maintaining the current
state of the container, or Bedlam Cube, and methods for
checking, inserting, and removing individual Shape objects
from the cube space. """
' Each Cube is made up of X * Y * Z Cuboids, Each of which\n for simplicities sakes contain all the in... |
def validate_positive_integer(param):
if isinstance(param,int) and (param > 0):
return(None)
else:
raise ValueError("Invalid value, expected positive integer, got {0}".format(param))
| def validate_positive_integer(param):
if isinstance(param, int) and param > 0:
return None
else:
raise value_error('Invalid value, expected positive integer, got {0}'.format(param)) |
class Node:
"""
This Node class has been created for you.
It contains the necessary properties for the solution, which are:
- text
- next
"""
def __init__(self, data, value):
self.data = data
self.value = value
self.__left = None
self.__right = None
def ... | class Node:
"""
This Node class has been created for you.
It contains the necessary properties for the solution, which are:
- text
- next
"""
def __init__(self, data, value):
self.data = data
self.value = value
self.__left = None
self.__right = None
def ... |
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
n = len(gas)
total_tank, curr_tank = 0, 0
start = 0
for i in range(n):
total_tank += gas[i] - cost[i]
curr_tank += gas[i] - cost[i]
# If one cou... | class Solution:
def can_complete_circuit(self, gas: List[int], cost: List[int]) -> int:
n = len(gas)
(total_tank, curr_tank) = (0, 0)
start = 0
for i in range(n):
total_tank += gas[i] - cost[i]
curr_tank += gas[i] - cost[i]
if curr_tank < 0:
... |
def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the messag... | def test():
assert set(bs_column.values) == {'strong', 'weak'}, "Have you selected the 'base_score' column?"
assert set(score_freq) == set([573, 228]), "You count values are incorrect. Are you using the 'count' function?"
assert 'plot.bar' in __solution__, "Are you using the 'plot.bar' function?"
assert... |
# New tokens can be found at https://archive.org/account/s3.php
IA_ACCESS_KEY = 'change to valid token'
IA_SECRET_KEY = 'change to valid token'
DOI_FORMAT = '10.70102/fk2osf.io/{guid}'
OSF_BEARER_TOKEN = ''
DATACITE_USERNAME = None
DATACITE_PASSWORD = None
DATACITE_URL = None
DATACITE_PREFIX = '10.70102' # Datacite... | ia_access_key = 'change to valid token'
ia_secret_key = 'change to valid token'
doi_format = '10.70102/fk2osf.io/{guid}'
osf_bearer_token = ''
datacite_username = None
datacite_password = None
datacite_url = None
datacite_prefix = '10.70102' |
test = { 'name': 'q5',
'points': 3,
'suites': [ { 'cases': [ {'code': ">>> big_tippers(['suraj', 15, 'isaac', 9, 'angela', 19]) == ['suraj', 'angela']\nTrue", 'hidden': False, 'locked': False},
{ 'code': ">>> big_tippers(['suraj', 15, 'isaac', 25, 'angela', 19, 'anna... | test = {'name': 'q5', 'points': 3, 'suites': [{'cases': [{'code': ">>> big_tippers(['suraj', 15, 'isaac', 9, 'angela', 19]) == ['suraj', 'angela']\nTrue", 'hidden': False, 'locked': False}, {'code': ">>> big_tippers(['suraj', 15, 'isaac', 25, 'angela', 19, 'anna', 21, 'aayush', 14, 'sukrit', 8]) == ['isaac', 'angela', ... |
#statsFunctions2.py
def total(list_obj):
total = 0
n = len(list_obj)
for i in range(n):
total += list_obj[i]
return total
def mean(list_obj):
n = len(list_obj)
mean = total(list_obj) / n
return mean
list1 = [3, 6, 9, 12, 15]
total_list1 = total(list1)
print(total_list1)
mean_list1... | def total(list_obj):
total = 0
n = len(list_obj)
for i in range(n):
total += list_obj[i]
return total
def mean(list_obj):
n = len(list_obj)
mean = total(list_obj) / n
return mean
list1 = [3, 6, 9, 12, 15]
total_list1 = total(list1)
print(total_list1)
mean_list1 = mean(list1)
print('... |
ble_address_type = {
'gap_address_type_public': 0,
'gap_address_type_random': 1
}
gap_discoverable_mode = {
'non_discoverable': 0x00,
'limited_discoverable': 0x01,
'general_discoverable': 0x02,
'broadcast': 0x03,
'user_data': 0x04,
'enhanced_broadcasting': 0x80
}
gap_connectable_mode = {... | ble_address_type = {'gap_address_type_public': 0, 'gap_address_type_random': 1}
gap_discoverable_mode = {'non_discoverable': 0, 'limited_discoverable': 1, 'general_discoverable': 2, 'broadcast': 3, 'user_data': 4, 'enhanced_broadcasting': 128}
gap_connectable_mode = {'non_connectable': 0, 'directed_connectable': 1, 'un... |
#-------------------------------------------------------------------------------
# mrna
#-------------------------------------------------------------------------------
def runFib(inputFile):
fi = open(inputFile, 'r') #reads in the file that list the before/after file names
inputData = fi.readline().split() #r... | def run_fib(inputFile):
fi = open(inputFile, 'r')
input_data = fi.readline().split()
(n, m) = (int(inputData[0]), int(inputData[1]))
(mature, immature) = (0, 1)
for i in range(n - 1):
babies = mature * m
mature = immature + mature
immature = babies
total = mature + im... |
#!/usr/bin/python
CONFIG = {
"BUCKET": "sd_s3_testbucket",
"EXEC_FMT": "/usr/bin/python -m syndicate.rg.gateway",
"DRIVER": "syndicate.rg.drivers.s3"
}
| config = {'BUCKET': 'sd_s3_testbucket', 'EXEC_FMT': '/usr/bin/python -m syndicate.rg.gateway', 'DRIVER': 'syndicate.rg.drivers.s3'} |
expected_output = {
'lsps': {
'mlx8.1_to_ces.2': {
'destination': '1.1.1.1',
'admin': 'UP',
'operational': 'UP',
'flap_count': 1,
'retry_count': 0,
'tunnel_interface': 'tunnel0'
},
'mlx8.1_to_ces.1': {
'desti... | expected_output = {'lsps': {'mlx8.1_to_ces.2': {'destination': '1.1.1.1', 'admin': 'UP', 'operational': 'UP', 'flap_count': 1, 'retry_count': 0, 'tunnel_interface': 'tunnel0'}, 'mlx8.1_to_ces.1': {'destination': '2.2.2.2', 'admin': 'UP', 'operational': 'UP', 'flap_count': 1, 'retry_count': 0, 'tunnel_interface': 'tunne... |
"""
Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must... | """
Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must... |
{
'targets': [
{
'target_name': 'modemmanager-dbus-proxies',
'type': 'none',
'variables': {
'xml2cpp_type': 'proxy',
'xml2cpp_in_dir': '<(sysroot)/usr/share/dbus-1/interfaces/',
'xml2cpp_out_dir': 'include/dbus_proxies',
},
'sources': [
'<(xml2cpp_in_d... | {'targets': [{'target_name': 'modemmanager-dbus-proxies', 'type': 'none', 'variables': {'xml2cpp_type': 'proxy', 'xml2cpp_in_dir': '<(sysroot)/usr/share/dbus-1/interfaces/', 'xml2cpp_out_dir': 'include/dbus_proxies'}, 'sources': ['<(xml2cpp_in_dir)/mm-mobile-error.xml', '<(xml2cpp_in_dir)/mm-serial-error.xml', '<(xml2c... |
class Queue:
def __init__(self):
self.in_stack = []
self.out_stack = []
# Transfer values in stack1 to stack2
def stack_transfer(self, stack1, stack2):
while stack1:
stack2.append(stack1.pop())
def enqueue(self, value):
self.in_stack.append(value)
def d... | class Queue:
def __init__(self):
self.in_stack = []
self.out_stack = []
def stack_transfer(self, stack1, stack2):
while stack1:
stack2.append(stack1.pop())
def enqueue(self, value):
self.in_stack.append(value)
def dequeue(self):
if not self.in_stac... |
l = iface.activeLayer()
iter = l.getFeatures()
geoms = []
for feature in iter:
geom = feature.geometry()
if not(geom.isMultipart()):
l.boundingBox(feature.id())
geoms.append(geom)
| l = iface.activeLayer()
iter = l.getFeatures()
geoms = []
for feature in iter:
geom = feature.geometry()
if not geom.isMultipart():
l.boundingBox(feature.id())
geoms.append(geom) |
def is_in_interval(n):
return (-15 < n <= 12) or (14 < n < 17) or (19 <= n)
print(is_in_interval(int(input())))
| def is_in_interval(n):
return -15 < n <= 12 or 14 < n < 17 or 19 <= n
print(is_in_interval(int(input()))) |
class UniBrokerMessageManager:
def reject(self) -> None:
raise NotImplementedError(f'method reject must be specified for class "{type(self).__name__}"')
def ack(self) -> None:
raise NotImplementedError(f'method acknowledge must be specified for class "{type(self).__name__}"')
| class Unibrokermessagemanager:
def reject(self) -> None:
raise not_implemented_error(f'method reject must be specified for class "{type(self).__name__}"')
def ack(self) -> None:
raise not_implemented_error(f'method acknowledge must be specified for class "{type(self).__name__}"') |
__all__ = (
"Node",
"DefinitionNode",
"ExecutableDefinitionNode",
"TypeSystemDefinitionNode",
"TypeSystemExtensionNode",
"TypeDefinitionNode",
"TypeExtensionNode",
"SelectionNode",
"ValueNode",
"TypeNode",
)
class Node:
__slots__ = ()
class DefinitionNode(Node):
__slo... | __all__ = ('Node', 'DefinitionNode', 'ExecutableDefinitionNode', 'TypeSystemDefinitionNode', 'TypeSystemExtensionNode', 'TypeDefinitionNode', 'TypeExtensionNode', 'SelectionNode', 'ValueNode', 'TypeNode')
class Node:
__slots__ = ()
class Definitionnode(Node):
__slots__ = ()
class Executabledefinitionnode(Def... |
class Sort:
col_id: str
sort: str
def __init__(self, col_id, sort):
self.col_id = col_id
self.sort = sort
@staticmethod
def from_json(json: dict):
if not json:
raise Exception('Error. Sort was not defined but should be.')
sort = Sort()
# colId... | class Sort:
col_id: str
sort: str
def __init__(self, col_id, sort):
self.col_id = col_id
self.sort = sort
@staticmethod
def from_json(json: dict):
if not json:
raise exception('Error. Sort was not defined but should be.')
sort = sort()
if 'colId'... |
ANIMALS = [
"aardvark",
"aardwolf",
"albatross",
"alligator",
"alpaca",
"amphibian",
"anaconda",
"angelfish",
"anglerfish",
"ant",
"anteater",
"antelope",
"antlion",
"ape",
"aphid",
"armadillo",
"asp",
"baboon",
"badger",
"bandicoot",
"... | animals = ['aardvark', 'aardwolf', 'albatross', 'alligator', 'alpaca', 'amphibian', 'anaconda', 'angelfish', 'anglerfish', 'ant', 'anteater', 'antelope', 'antlion', 'ape', 'aphid', 'armadillo', 'asp', 'baboon', 'badger', 'bandicoot', 'barnacle', 'barracuda', 'basilisk', 'bass', 'bat', 'bear', 'beaver', 'bedbug', 'bee',... |
# Name of the campaign
CampaignName = 'iview-campaign'
# Name of the parser module. The parser module must be
# in the chromosome/parsers directory.
Parser = 'PNG'
# The path of the initial corpus
InitialPopulation = 'C:\\tmp\\png'
# The fitness algorithms that will be used by Chronzon
# and the weight of each one. ... | campaign_name = 'iview-campaign'
parser = 'PNG'
initial_population = 'C:\\tmp\\png'
fitness_algorithms = {'BasicBlockCoverage': 0.5, 'CodeCommonality': 0.3}
recombinators = ('AdditiveSimilarGeneCrossOver', 'DuplicateGeneRecombinator', 'RemoveGeneRecombinator', 'RemoveGeneRecombinator', 'ShuffleSiblings', 'ParentChildre... |
# https://www.acmicpc.net/problem/10872
def n_fac(n):
if n==1:
return 1
else:
return n * n_fac(n-1)
n = int(input())
if n == 0:
print(1)
else:
print(n_fac(n)) | def n_fac(n):
if n == 1:
return 1
else:
return n * n_fac(n - 1)
n = int(input())
if n == 0:
print(1)
else:
print(n_fac(n)) |
class TestRequest_certs():
def test_request_certs(self):
return
| class Testrequest_Certs:
def test_request_certs(self):
return |
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
dic = {}
for char in s:
dic[char] = dic.get(char,0)+1
res = []
for char in s:
dic[char] -= 1
if char not in res:
while res and char<res[-1] and dic[res[-1]]>0:
... | class Solution:
def remove_duplicate_letters(self, s: str) -> str:
dic = {}
for char in s:
dic[char] = dic.get(char, 0) + 1
res = []
for char in s:
dic[char] -= 1
if char not in res:
while res and char < res[-1] and (dic[res[-1]] >... |
VERSION_NAME = "tmtccmd"
VERSION_MAJOR = 1
VERSION_MINOR = 10
VERSION_REVISION = 2
# I think this needs to be in string representation to be parsed so we can't
# use a formatted string here.
__version__ = "1.10.2"
| version_name = 'tmtccmd'
version_major = 1
version_minor = 10
version_revision = 2
__version__ = '1.10.2' |
def caesar_encrypt(word,n):
c = ''
for i in word:
if (not i.isalpha()):
c += i
elif (i.isupper()):
c += chr((ord(i) + n-65) % 26 + 65)
else:
c += chr((ord(i) + n - 97) % 26 + 97)
return c
def caesar_decrypt(word,n):
c = ''
for i in word:
... | def caesar_encrypt(word, n):
c = ''
for i in word:
if not i.isalpha():
c += i
elif i.isupper():
c += chr((ord(i) + n - 65) % 26 + 65)
else:
c += chr((ord(i) + n - 97) % 26 + 97)
return c
def caesar_decrypt(word, n):
c = ''
for i in word:
... |
def parOuImpar(n=0):
if n % 2 ==0:
return True
else:
return False
num = int(input("Digite um numero: "))
if parOuImpar(num):
print("E par!")
else:
print("Nao e par!")
| def par_ou_impar(n=0):
if n % 2 == 0:
return True
else:
return False
num = int(input('Digite um numero: '))
if par_ou_impar(num):
print('E par!')
else:
print('Nao e par!') |
# Subtract numbers module
class Calculate:
def sub(a, b):
"""Substract two numbers"""
return a - b
def add(a, b):
"""Add two numbers"""
return a + b
def mult(a, b):
"""Product of two numbers"""
return a * b
def div(a, b):
"""Divide two numbers"""
return a / b
| class Calculate:
def sub(a, b):
"""Substract two numbers"""
return a - b
def add(a, b):
"""Add two numbers"""
return a + b
def mult(a, b):
"""Product of two numbers"""
return a * b
def div(a, b):
"""Divide two numbers"""
return a / b |
inputs = [1, 2, 3, 2.5]
weights1 = [0.2, 0.8, -0.5, 1.0]
weights2 = [0.5, -0.91, 0.26, -0.5]
weights3 = [-0.26, -0.27, 0.17, 0.87]
bias1 = 2
bias2 = 3
bias3 = 0.5
output = [ inputs[0]*weights1[0] + inputs[1]*weights1[1] + inputs[2]*weights1[2] + inputs[3]*weights1[3] + bias1,
inputs[0]*weights... | inputs = [1, 2, 3, 2.5]
weights1 = [0.2, 0.8, -0.5, 1.0]
weights2 = [0.5, -0.91, 0.26, -0.5]
weights3 = [-0.26, -0.27, 0.17, 0.87]
bias1 = 2
bias2 = 3
bias3 = 0.5
output = [inputs[0] * weights1[0] + inputs[1] * weights1[1] + inputs[2] * weights1[2] + inputs[3] * weights1[3] + bias1, inputs[0] * weights2[0] + inputs[1] ... |
x=[]
for i in range(4):
x.append(int(input()))
x.sort()
ans=sum(x[1:])
x=[]
for i in range(2):
x.append(int(input()))
ans+=max(x)
print(ans) | x = []
for i in range(4):
x.append(int(input()))
x.sort()
ans = sum(x[1:])
x = []
for i in range(2):
x.append(int(input()))
ans += max(x)
print(ans) |
#https://codeforces.com/problemset/problem/588/A
n = int(input())
a, p = map(int, input().split(" "))
mm = a * p # minimum money
mp = p # minimum price
for i in range(n - 1):
a, p = map(int, input().split(" "))
if p < mp:
mp = p
mm += a * mp
print(mm)
| n = int(input())
(a, p) = map(int, input().split(' '))
mm = a * p
mp = p
for i in range(n - 1):
(a, p) = map(int, input().split(' '))
if p < mp:
mp = p
mm += a * mp
print(mm) |
#42) Coded triangle numbers
#The nth term of the sequence of triangle numbers is given by, tn = (1/2)*n*(n+1); so the first ten triangle numbers are:
#1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
#By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a wo... | def triangle_nums(x):
n = 1
while int(1 / 2 * n * (n + 1)) <= x:
yield int(1 / 2 * n * (n + 1))
n += 1
with open('p042_words.txt', mode='r') as doc:
list_words = doc.read().replace('"', '').split(',')
list_values = [sum([ord(x) - 64 for x in word]) for word in list_words]
list_triangle = [x ... |
class Solution:
def bagOfTokensScore(self, tokens: List[int], P: int) -> int:
tokens.sort()
tokens, maxScore, currentScore = deque(tokens), 0, 0
while tokens and (P >= tokens[0] or currentScore):
while tokens and P >= tokens[0]:
P -= tokens.popleft()
... | class Solution:
def bag_of_tokens_score(self, tokens: List[int], P: int) -> int:
tokens.sort()
(tokens, max_score, current_score) = (deque(tokens), 0, 0)
while tokens and (P >= tokens[0] or currentScore):
while tokens and P >= tokens[0]:
p -= tokens.popleft()
... |
#
# PySNMP MIB module CISCO-STACKWISE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-STACKWISE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:13:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, single_value_constraint, constraints_intersection, value_size_constraint) ... |
# _*_ coding: utf-8 _*_
#
# Package: src.core.repository.file
__all__ = [
"car_repository",
"customer_repository",
"employee_repository",
"file_db",
"file_repository",
"rental_repository"
]
| __all__ = ['car_repository', 'customer_repository', 'employee_repository', 'file_db', 'file_repository', 'rental_repository'] |
# Write a function to find the longest common prefix string amongst an array of strings.
class Solution:
# @param {string[]} strs
# @return {string}
def longestCommonPrefix(self, strs):
if not strs:
return ""
lcp = ""
base = strs[0]
for i in range(len(base)):
... | class Solution:
def longest_common_prefix(self, strs):
if not strs:
return ''
lcp = ''
base = strs[0]
for i in range(len(base)):
for s in strs[1:]:
if i > len(s) - 1:
return lcp
if base[i] != s[i]:
... |
#
# @lc app=leetcode id=32 lang=python3
#
# [32] Longest Valid Parentheses
#
# @lc code=start
class Solution:
def longestValidParentheses(self, s):
if not s:
return 0
l = 0
r = len(s)
while s[r - 1] == '(' and r > 0:
r -= 1
while s[l] == ')' and l < r... | class Solution:
def longest_valid_parentheses(self, s):
if not s:
return 0
l = 0
r = len(s)
while s[r - 1] == '(' and r > 0:
r -= 1
while s[l] == ')' and l < r - 2:
l += 1
s = s[l:r]
if len(s) < 2:
return 0
... |
'''
Longest Consecutive Sequence
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
'''
class Solu... | """
Longest Consecutive Sequence
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
"""
class Solu... |
"""
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
Solution:
1. Recursion (in place)
Flatten the left subtree ... | """
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ 2 5
/ \\ 3 4 6
The flattened tree should look like:
1
2
3
4
5
6
Solution:
1. Recursion (in place)
Flatten the left subtree of root, then... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.