content stringlengths 7 1.05M |
|---|
class Utilities:
@staticmethod
def swap(a, b, arr):
arr[a], arr[b] = arr[b], arr[a]
return arr
|
class Solution:
def kidsWithCandies(self, candies: list[int], extraCandies: int) -> list[bool]:
result = list(map(lambda x: True if x+extraCandies >=
max(candies) else False, candies))
return result
# Time Complexity = O(1) |
# AC 26/08/2019 17:58:21 IST #
n = int(input())
print(n)
|
def Range(first, second=None, step=1):
if second is None:
current = 0
end = first
else:
current = first
end = second
while not (current >= end and step > 0
or current <= end and step < 0):
yield current
current += step
def print_space(str):
print("{}".format(str), end=' ')
for i in Range(10):
print_space(i)
print()
for i in Range(3, 18):
print_space(i)
print()
for i in Range(2, 15, 2):
print_space(i)
print()
for i in Range(10, 0, -1):
print_space(i)
|
class Info:
"""
Represents more of the metadata associated with the API
output
"""
def __init__(self, **kwargs):
self.seed = kwargs['seed']
self.results = kwargs['results'] # will represent an integer (500 in this case)
self.page = kwargs['page']
self.version = kwargs['version']
class User:
"""
Represents a top level result entry from the API output
"""
def __init__(self, **kwargs):
self.gender = kwargs['gender']
self.name = kwargs['name']
self.location = kwargs['email']
self.email = kwargs['email']
self.login = kwargs['gender']
self.dob = kwargs['dob']
self.registered = kwargs['registered']
self.phone = kwargs['phone']
self.cell = kwargs['cell']
self.id = kwargs['id']
self.picture = kwargs['picture']
self.nat = kwargs['nat']
class Name:
def __init__(self, **kwargs):
self.title = kwargs['title']
self.first = kwargs['first']
self.last = kwargs['last']
class Location:
def __init__(self, **kwargs):
self.street = kwargs['street']
self.city = kwargs['city']
self.state = kwargs['state']
self.country = kwargs['country']
self.postcode = kwargs['postcode']
self.coordinates = kwargs['coordinates']
self.timezone = kwargs['coordinates']
class Street:
def __init__(self, **kwargs):
self.number = kwargs['number']
self.name = kwargs['name']
class Coordinates:
def __init__(self, **kwargs):
self.latitude = kwargs['latitude']
self.longitude = kwargs['longitude']
class Timezone:
def __init__(self, **kwargs):
self.offset = kwargs['offset']
self.description = kwargs['description']
class Login:
def __init__(self, **kwargs):
self.uuid = kwargs['uuid']
self.username = kwargs['username']
self.password = kwargs['password']
self.salt = kwargs['salt']
self.md5 = kwargs['md5']
self.sha1 = kwargs['sha1']
self.sha256 = kwargs['sha256']
class Dob:
def __init__(self, **kwargs):
self.date = kwargs['date']
self.age = kwargs['age']
class Registered:
def __init__(self, **kwargs):
self.date = kwargs['date']
self.age = kwargs['age']
class Id:
def __init__(self, **kwargs):
self.name = kwargs['name']
self.value = kwargs['value']
class Picture:
def __init__(self, **kwargs):
self.large = kwargs['large']
self.medium = kwargs['medium']
self.thumbnail = kwargs['thumbnail']
|
#from baconsarnie.io.window import Window
#__all__ = ["io", "Window"]
__all__ = ["io"] |
{
'target_defaults': {
'default_configuration': 'Release',
'configurations': {
'Debug': {
'cflags': ['-g3', '-O0'],
'msvs_settings': {
'VCLinkerTool': {
'GenerateDebugInformation': 'true',
'LinkIncremental': 2
}
}
},
'Release': {
'cflags': ['-O2', '-W', '-Wall', '-Wextra', '-ansi', '-pedantic'],
'msvs_settings': {
'VCCLCompilerTool': {
'Optimization': 3, # -O3
'FavorSizeOrSpeed': 1, # favor speed
},
'VCLinkerTool': {
'OptimizeReferences': 2, # /OPT:REF
}
}
},
},
},
"targets": [
{
"target_name": "<(module_name)",
'lflags': ['-lm'],
"include_dirs": [
"zopfli/src/zopfli",
"zopfli/src/zopflipng",
"<!(node -e \"require('nan')\")"
],
"sources": [
"src/zopfli-binding.cc",
"src/png/zopflipng.cc",
"zopfli/src/zopfli/blocksplitter.c",
"zopfli/src/zopfli/cache.c",
"zopfli/src/zopfli/deflate.c",
"zopfli/src/zopfli/gzip_container.c",
"zopfli/src/zopfli/hash.c",
"zopfli/src/zopfli/katajainen.c",
"zopfli/src/zopfli/lz77.c",
"zopfli/src/zopfli/squeeze.c",
"zopfli/src/zopfli/tree.c",
"zopfli/src/zopfli/util.c",
"zopfli/src/zopfli/zlib_container.c",
"zopfli/src/zopfli/zopfli_lib.c",
"zopfli/src/zopflipng/zopflipng_lib.cc",
"zopfli/src/zopflipng/lodepng/lodepng.cpp",
"zopfli/src/zopflipng/lodepng/lodepng_util.cpp"
],
"cflags": [
"-Wall",
"-O3"
]
},
{
"target_name": "action_after_build",
"type": "none",
"dependencies": [ "<(module_name)" ],
"copies": [
{
"files": [ "<(PRODUCT_DIR)/<(module_name).node" ],
"destination": "<(module_path)"
}
]
}
]
}
|
class Board():
# Initialize Board
def __init__(self):
'''Initialize the tiles with private attributes'''
self.__tiles = list(map(str, range(9)))
# Get tile value
def get_tile(self, index:int):
'''Getter for the tile'''
if self.__tiles[index] not in list(map(str, range(9))):
return self.__tiles[index]
else:
return str(int(self.__tiles[index])+1)
# Add symbol
def set_tile(self, symbol, coordinate:int):
'''Setter for the tile'''
if self.__tiles[coordinate] not in list(map(str, range(9))):
return False
self.__tiles[coordinate] = symbol
return True
# Print board
def possible_moves(self):
'''Returns a list of unoccupied tiles in the board'''
return [ index+1 for index in range(len(self.__tiles)) if self.__tiles[index] in list(map(str, range(9)))]
# Win condition
def check_board(self, symbol):
'''Check if the player won, cause a draw, or doesn't cause either'''
possible_combination = [
self.__tiles[:3], self.__tiles[3:6], self.__tiles[6:],
self.__tiles[::3],self.__tiles[1::3], self.__tiles[2::3],
self.__tiles[0::4], self.__tiles[2:8:2]
]
if len(list(filter(lambda x: x==[symbol]*3, possible_combination)))>0:
return symbol
elif not len(list(filter(lambda x: x in list(map(str, range(9))),self.__tiles))):
return 'DRAW'
else:
return False |
# -*- coding: utf-8 -*-
# if Statements
x = int(input("Please enter an integer: "))
if x < 0:
print('Negative number')
elif x > 0:
print('Positive number')
else:
print('Zero')
# for Statement
words = ['cat', 'window', 'door']
for w in words:
print(w, len(w))
# range(begin=0, end, step) Function
for i in range(5):
print(i) # 0 1 2 3 4
range(10) # -> an iterator
list(range(10)) # -> a list
# stay away from else Clauses on loops, anti-pattern
for n in range(10):
pass
else:
pass
# functions
def fib(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
print('fib of 10', fib(10))
# default argument values
def ask_ok(prompt, retries=4, remider='Please try again'):
while True:
ok = input(prompt)
if ok in ('y', 'yes'):
return True
if ok in ('n', 'no'):
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user')
print(remider)
# the scope of default argument values
i = 100
def foo(bar=i):
print(bar)
i = 6
foo() # 5
# default arguments caution
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
f(1) # [1]
f(2) # [2]
f(3) # [3]
# keyword arguments
def foo(a, b='b', c='c'):
pass
foo(1)
foo(1, c=3)
foo(b=2)
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
keys = sorted(keywords.keys())
for kw in keys:
print(kw, ":", keywords[kw])
cheeseshop(
"Limburger",
*[
"It's very runny, sir.",
"It's really very, VERY runny, sir.",
],
**{
"shopkeeper": "Michael Palin",
"client": "John Cleese",
"sketch": "Cheese Shop Sketch",
}
)
# -- Do you have any Limburger ?
# -- I'm sorry, we're all out of Limburger
# It's very runny, sir.
# It's really very, VERY runny, sir.
# ----------------------------------------
# client : John Cleese
# shopkeeper : Michael Palin
# sketch : Cheese Shop Sketch
# lambda expression
f = lambda x: x + n
# documentation strings
def func():
"""
it's func
"""
pass
print(func.__doc__)
# function annotations, but you can still pass other typed values
def f(ham: str, eggs: str = 'eggs') -> str:
print("Annotations:", f.__annotations__)
print("Arguments:", ham, eggs)
return ham + ' and ' + eggs
|
# Parsing file using list comprehension
file1 = open("test.txt", "r")
output = [i for i in file1 if "All" in i]
print(output) |
def check_palindrome(strings):
for i in range(int(len(strings)/2)):
if strings[i] != strings[len(strings)-i-1]:
return False
return True
strings = input("Nhap vào chuoi: ")
if(check_palindrome(strings)):
print("Chuoi doi xung")
else:
print("khong la chuoi doi xung")
|
'''
Description : Use Of Forloop With Hardcoded Value
Function Date : 15 Feb 2021
Function Author : Prasad Dangare
Input : Int
Output : str
'''
def display():
print("Output of For loop")
icnt = 0
for icnt in range(10, 1, -1):
print(icnt)
else:
print("End of For loop")
def main():
display()
if __name__ == "__main__":
main() |
class AuthError(Exception):
"""Authentication error"""
def __init__(self, msg):
super(AuthError, self).__init__(msg)
class DocumentNotFound(Exception):
"""Could not found a requested document"""
def __init__(self, msg):
super(DocumentNotFound, self).__init__(msg)
class UnsupportedTypeError(Exception):
"""Not the expected type"""
def __init__(self, msg):
super(UnsupportedTypeError, self).__init__(msg)
class FolderNotFound(Exception):
"""Could not found a requested folder"""
def __init__(self, msg):
super(FolderNotFound, self).__init__(msg)
class ApiError(Exception):
"""Could not found a requested document"""
def __init__(self, msg, response=None):
self.response = response
super(ApiError, self).__init__(msg)
|
# Grocery list class
class GroceryList:
def __init__(self, initial_items=[]):
# Use a set, so that we don't get duplicates
self.grocery_list = set(initial_items)
def add(self, item):
# Use the lower case of the item so we don't get duplicates
self.grocery_list.add(item.lower())
def remove(self, item):
self.grocery_list.remove(item.lower())
def contains(self, item):
return item.lower() in self.grocery_list
def items(self):
return list(self.grocery_list)
#################
# Example usage
my_list = GroceryList()
my_list.add("strawberries")
my_list.add("wine")
my_list.add("gouda cheese")
if not my_list.contains("Crackers"):
my_list.add("crackers")
my_list.add("beer")
my_list.remove("beer")
print("My list has: ")
for item in my_list.items():
print ("\t",item) |
{
'includes': [
'common.gypi',
],
'target_defaults': {
'conditions': [
['skia_os != "win"', {
'sources/': [ ['exclude', '_win.(h|cpp)$'],
],
}],
['skia_os != "mac"', {
'sources/': [ ['exclude', '_mac.(h|cpp)$'],
],
}],
['skia_os != "linux"', {
'sources/': [ ['exclude', '_unix.(h|cpp)$'],
],
}],
['skia_os != "ios"', {
'sources/': [ ['exclude', '_iOS.(h|cpp)$'],
],
}],
['skia_os != "android"', {
'sources/': [ ['exclude', '_android.(h|cpp)$'],
],
}],
[ 'skia_os == "android"', {
'defines': [
'GR_ANDROID_BUILD=1',
],
}],
[ 'skia_os == "mac"', {
'defines': [
'GR_MAC_BUILD=1',
],
}],
[ 'skia_os == "linux"', {
'defines': [
'GR_LINUX_BUILD=1',
],
}],
[ 'skia_os == "ios"', {
'defines': [
'GR_IOS_BUILD=1',
],
}],
[ 'skia_os == "win"', {
'defines': [
'GR_WIN32_BUILD=1',
],
}],
# nullify the targets in this gyp file if skia_gpu is 0
[ 'skia_gpu == 0', {
'sources/': [
['exclude', '.*'],
],
'defines/': [
['exclude', '.*'],
],
'include_dirs/': [
['exclude', '.*'],
],
'link_settings': {
'libraries/': [
['exclude', '.*'],
],
},
'direct_dependent_settings': {
'defines/': [
['exclude', '.*'],
],
'include_dirs/': [
['exclude', '.*'],
],
},
}],
],
'direct_dependent_settings': {
'conditions': [
[ 'skia_os == "android"', {
'defines': [
'GR_ANDROID_BUILD=1',
],
}],
[ 'skia_os == "mac"', {
'defines': [
'GR_MAC_BUILD=1',
],
}],
[ 'skia_os == "linux"', {
'defines': [
'GR_LINUX_BUILD=1',
],
}],
[ 'skia_os == "ios"', {
'defines': [
'GR_IOS_BUILD=1',
],
}],
[ 'skia_os == "win"', {
'defines': [
'GR_WIN32_BUILD=1',
'GR_GL_FUNCTION_TYPE=__stdcall',
],
}],
],
'include_dirs': [
'../deps/skia/include/gpu',
],
},
},
'targets': [
{
'target_name': 'skgr',
'type': 'static_library',
'include_dirs': [
'../deps/skia/include/config',
'../deps/skia/include/core',
'../deps/skia/src/core',
'../deps/skia/include/gpu',
'../deps/skia/src/gpu',
],
'dependencies': [
'angle.gyp:*',
],
'export_dependent_settings': [
'angle.gyp:*',
],
'sources': [
'../deps/skia/include/gpu/SkGpuCanvas.h',
'../deps/skia/include/gpu/SkGpuDevice.h',
'../deps/skia/include/gpu/SkGr.h',
'../deps/skia/include/gpu/SkGrPixelRef.h',
'../deps/skia/include/gpu/SkGrTexturePixelRef.h',
'../deps/skia/include/gpu/gl/SkGLContext.h',
'../deps/skia/include/gpu/gl/SkMesaGLContext.h',
'../deps/skia/include/gpu/gl/SkANGLEGLContext.h',
'../deps/skia/include/gpu/gl/SkNativeGLContext.h',
'../deps/skia/include/gpu/gl/SkNullGLContext.h',
'../deps/skia/include/gpu/gl/SkDebugGLContext.h',
'../deps/skia/src/gpu/SkGpuCanvas.cpp',
'../deps/skia/src/gpu/SkGpuDevice.cpp',
'../deps/skia/src/gpu/SkGr.cpp',
'../deps/skia/src/gpu/SkGrFontScaler.cpp',
'../deps/skia/src/gpu/SkGrPixelRef.cpp',
'../deps/skia/src/gpu/SkGrTexturePixelRef.cpp',
'../deps/skia/src/gpu/gl/SkGLContext.cpp',
'../deps/skia/src/gpu/gl/SkNullGLContext.cpp',
'../deps/skia/src/gpu/gl/debug/SkDebugGLContext.cpp',
'../deps/skia/src/gpu/gl/mac/SkNativeGLContext_mac.cpp',
'../deps/skia/src/gpu/gl/win/SkNativeGLContext_win.cpp',
'../deps/skia/src/gpu/gl/unix/SkNativeGLContext_unix.cpp',
'../deps/skia/src/gpu/gl/mesa/SkMesaGLContext.cpp',
'../deps/skia/src/gpu/gl/angle/SkANGLEGLContext.cpp',
'../deps/skia/src/gpu/gl/angle/GrGLCreateANGLEInterface.cpp',
'../deps/skia/src/gpu/android/SkNativeGLContext_android.cpp',
],
'conditions': [
[ 'not skia_mesa', {
'sources!': [
'../deps/skia/src/gpu/gl/mesa/SkMesaGLContext.cpp',
],
}],
[ 'skia_mesa and skia_os == "mac"', {
'include_dirs': [
'$(SDKROOT)/usr/X11/include/',
],
}],
[ 'not skia_angle', {
'sources!': [
'../deps/skia/include/gpu/gl/SkANGLEGLContext.h',
'../deps/skia/src/gpu/gl/angle/SkANGLEGLContext.cpp',
'../deps/skia/src/gpu/gl/angle/GrGLCreateANGLEInterface.cpp',
],
}],
],
},
{
'target_name': 'gr',
'type': 'static_library',
'include_dirs': [
'../deps/skia/include/core',
'../deps/skia/include/config',
'../deps/skia/include/gpu',
'../deps/skia/src/core', # SkRasterClip.h
'../deps/skia/src/gpu'
],
'dependencies': [
'angle.gyp:*',
],
'export_dependent_settings': [
'angle.gyp:*',
],
'sources': [
'../deps/skia/include/gpu/GrAARectRenderer.h',
'../deps/skia/include/gpu/GrClipData.h',
'../deps/skia/include/gpu/GrColor.h',
'../deps/skia/include/gpu/GrConfig.h',
'../deps/skia/include/gpu/GrContext.h',
'../deps/skia/include/gpu/GrContextFactory.h',
'../deps/skia/include/gpu/GrCustomStage.h',
'../deps/skia/include/gpu/GrCustomStageUnitTest.h',
'../deps/skia/include/gpu/GrFontScaler.h',
'../deps/skia/include/gpu/GrGlyph.h',
'../deps/skia/include/gpu/GrInstanceCounter.h',
'../deps/skia/include/gpu/GrKey.h',
'../deps/skia/include/gpu/GrMatrix.h',
'../deps/skia/include/gpu/GrNoncopyable.h',
'../deps/skia/include/gpu/GrPaint.h',
'../deps/skia/include/gpu/GrPoint.h',
'../deps/skia/include/gpu/GrProgramStageFactory.h',
'../deps/skia/include/gpu/GrRect.h',
'../deps/skia/include/gpu/GrRefCnt.h',
'../deps/skia/include/gpu/GrRenderTarget.h',
'../deps/skia/include/gpu/GrResource.h',
'../deps/skia/include/gpu/GrSamplerState.h',
'../deps/skia/include/gpu/GrScalar.h',
'../deps/skia/include/gpu/GrSurface.h',
'../deps/skia/include/gpu/GrTextContext.h',
'../deps/skia/include/gpu/GrTexture.h',
'../deps/skia/include/gpu/GrTypes.h',
'../deps/skia/include/gpu/GrUserConfig.h',
'../deps/skia/include/gpu/gl/GrGLConfig.h',
'../deps/skia/include/gpu/gl/GrGLConfig_chrome.h',
'../deps/skia/include/gpu/gl/GrGLFunctions.h',
'../deps/skia/include/gpu/gl/GrGLInterface.h',
'../deps/skia/src/gpu/GrAAHairLinePathRenderer.cpp',
'../deps/skia/src/gpu/GrAAHairLinePathRenderer.h',
'../deps/skia/src/gpu/GrAAConvexPathRenderer.cpp',
'../deps/skia/src/gpu/GrAAConvexPathRenderer.h',
'../deps/skia/src/gpu/GrAARectRenderer.cpp',
'../deps/skia/src/gpu/GrAddPathRenderers_default.cpp',
'../deps/skia/src/gpu/GrAllocator.h',
'../deps/skia/src/gpu/GrAllocPool.h',
'../deps/skia/src/gpu/GrAllocPool.cpp',
'../deps/skia/src/gpu/GrAtlas.cpp',
'../deps/skia/src/gpu/GrAtlas.h',
'../deps/skia/src/gpu/GrBinHashKey.h',
'../deps/skia/src/gpu/GrBufferAllocPool.cpp',
'../deps/skia/src/gpu/GrBufferAllocPool.h',
'../deps/skia/src/gpu/GrClipData.cpp',
'../deps/skia/src/gpu/GrContext.cpp',
'../deps/skia/src/gpu/GrCustomStage.cpp',
'../deps/skia/src/gpu/GrDefaultPathRenderer.cpp',
'../deps/skia/src/gpu/GrDefaultPathRenderer.h',
'../deps/skia/src/gpu/GrDrawState.h',
'../deps/skia/src/gpu/GrDrawTarget.cpp',
'../deps/skia/src/gpu/GrDrawTarget.h',
'../deps/skia/src/gpu/GrGeometryBuffer.h',
'../deps/skia/src/gpu/GrClipMaskManager.h',
'../deps/skia/src/gpu/GrClipMaskManager.cpp',
'../deps/skia/src/gpu/GrGpu.cpp',
'../deps/skia/src/gpu/GrGpu.h',
'../deps/skia/src/gpu/GrGpuFactory.cpp',
'../deps/skia/src/gpu/GrGpuVertex.h',
'../deps/skia/src/gpu/GrIndexBuffer.h',
'../deps/skia/src/gpu/GrInOrderDrawBuffer.cpp',
'../deps/skia/src/gpu/GrInOrderDrawBuffer.h',
'../deps/skia/src/gpu/GrMatrix.cpp',
'../deps/skia/src/gpu/GrMemory.cpp',
'../deps/skia/src/gpu/GrMemoryPool.cpp',
'../deps/skia/src/gpu/GrMemoryPool.h',
'../deps/skia/src/gpu/GrPath.h',
'../deps/skia/src/gpu/GrPathRendererChain.cpp',
'../deps/skia/src/gpu/GrPathRendererChain.h',
'../deps/skia/src/gpu/GrPathRenderer.cpp',
'../deps/skia/src/gpu/GrPathRenderer.h',
'../deps/skia/src/gpu/GrPathUtils.cpp',
'../deps/skia/src/gpu/GrPathUtils.h',
'../deps/skia/src/gpu/GrPlotMgr.h',
'../deps/skia/src/gpu/GrRandom.h',
'../deps/skia/src/gpu/GrRectanizer.cpp',
'../deps/skia/src/gpu/GrRectanizer.h',
'../deps/skia/src/gpu/GrRedBlackTree.h',
'../deps/skia/src/gpu/GrRenderTarget.cpp',
'../deps/skia/src/gpu/GrResource.cpp',
'../deps/skia/src/gpu/GrResourceCache.cpp',
'../deps/skia/src/gpu/GrResourceCache.h',
'../deps/skia/src/gpu/GrStencil.cpp',
'../deps/skia/src/gpu/GrStencil.h',
'../deps/skia/src/gpu/GrStencilAndCoverPathRenderer.cpp',
'../deps/skia/src/gpu/GrStencilAndCoverPathRenderer.h',
'../deps/skia/src/gpu/GrStencilBuffer.cpp',
'../deps/skia/src/gpu/GrStencilBuffer.h',
'../deps/skia/src/gpu/GrTBSearch.h',
'../deps/skia/src/gpu/GrTDArray.h',
'../deps/skia/src/gpu/GrSWMaskHelper.cpp',
'../deps/skia/src/gpu/GrSWMaskHelper.h',
'../deps/skia/src/gpu/GrSoftwarePathRenderer.cpp',
'../deps/skia/src/gpu/GrSoftwarePathRenderer.h',
'../deps/skia/src/gpu/GrSurface.cpp',
'../deps/skia/src/gpu/GrTemplates.h',
'../deps/skia/src/gpu/GrTextContext.cpp',
'../deps/skia/src/gpu/GrTextStrike.cpp',
'../deps/skia/src/gpu/GrTextStrike.h',
'../deps/skia/src/gpu/GrTextStrike_impl.h',
'../deps/skia/src/gpu/GrTexture.cpp',
'../deps/skia/src/gpu/GrTHashCache.h',
'../deps/skia/src/gpu/GrTLList.h',
'../deps/skia/src/gpu/GrVertexBuffer.h',
'../deps/skia/src/gpu/gr_unittests.cpp',
'../deps/skia/src/gpu/effects/Gr1DKernelEffect.h',
'../deps/skia/src/gpu/effects/GrColorTableEffect.cpp',
'../deps/skia/src/gpu/effects/GrColorTableEffect.h',
'../deps/skia/src/gpu/effects/GrConvolutionEffect.cpp',
'../deps/skia/src/gpu/effects/GrConvolutionEffect.h',
'../deps/skia/src/gpu/effects/GrMorphologyEffect.cpp',
'../deps/skia/src/gpu/effects/GrMorphologyEffect.h',
'../deps/skia/src/gpu/effects/GrSingleTextureEffect.cpp',
'../deps/skia/src/gpu/effects/GrSingleTextureEffect.h',
'../deps/skia/src/gpu/effects/GrTextureDomainEffect.cpp',
'../deps/skia/src/gpu/effects/GrTextureDomainEffect.h',
'../deps/skia/src/gpu/gl/GrGLCaps.cpp',
'../deps/skia/src/gpu/gl/GrGLCaps.h',
'../deps/skia/src/gpu/gl/GrGLContextInfo.cpp',
'../deps/skia/src/gpu/gl/GrGLContextInfo.h',
'../deps/skia/src/gpu/gl/GrGLCreateNativeInterface_none.cpp',
'../deps/skia/src/gpu/gl/GrGLCreateNullInterface.cpp',
'../deps/skia/src/gpu/gl/GrGLDefaultInterface_none.cpp',
'../deps/skia/src/gpu/gl/GrGLDefaultInterface_native.cpp',
'../deps/skia/src/gpu/gl/GrGLDefines.h',
'../deps/skia/src/gpu/gl/GrGLIndexBuffer.cpp',
'../deps/skia/src/gpu/gl/GrGLIndexBuffer.h',
'../deps/skia/src/gpu/gl/GrGLInterface.cpp',
'../deps/skia/src/gpu/gl/GrGLIRect.h',
'../deps/skia/src/gpu/gl/GrGLPath.cpp',
'../deps/skia/src/gpu/gl/GrGLPath.h',
'../deps/skia/src/gpu/gl/GrGLProgram.cpp',
'../deps/skia/src/gpu/gl/GrGLProgram.h',
'../deps/skia/src/gpu/gl/GrGLProgramStage.cpp',
'../deps/skia/src/gpu/gl/GrGLProgramStage.h',
'../deps/skia/src/gpu/gl/GrGLRenderTarget.cpp',
'../deps/skia/src/gpu/gl/GrGLRenderTarget.h',
'../deps/skia/src/gpu/gl/GrGLShaderBuilder.cpp',
'../deps/skia/src/gpu/gl/GrGLShaderBuilder.h',
'../deps/skia/src/gpu/gl/GrGLShaderVar.h',
'../deps/skia/src/gpu/gl/GrGLSL.cpp',
'../deps/skia/src/gpu/gl/GrGLSL.h',
'../deps/skia/src/gpu/gl/GrGLStencilBuffer.cpp',
'../deps/skia/src/gpu/gl/GrGLStencilBuffer.h',
'../deps/skia/src/gpu/gl/GrGLTexture.cpp',
'../deps/skia/src/gpu/gl/GrGLTexture.h',
'../deps/skia/src/gpu/gl/GrGLUtil.cpp',
'../deps/skia/src/gpu/gl/GrGLUtil.h',
'../deps/skia/src/gpu/gl/GrGLUniformManager.cpp',
'../deps/skia/src/gpu/gl/GrGLUniformManager.h',
'../deps/skia/src/gpu/gl/GrGLUniformHandle.h',
'../deps/skia/src/gpu/gl/GrGLVertexBuffer.cpp',
'../deps/skia/src/gpu/gl/GrGLVertexBuffer.h',
'../deps/skia/src/gpu/gl/GrGpuGL.cpp',
'../deps/skia/src/gpu/gl/GrGpuGL.h',
'../deps/skia/src/gpu/gl/GrGpuGL_program.cpp',
'../deps/skia/src/gpu/gl/debug/GrGLCreateDebugInterface.cpp',
'../deps/skia/src/gpu/gl/debug/GrFakeRefObj.h',
'../deps/skia/src/gpu/gl/debug/GrBufferObj.h',
'../deps/skia/src/gpu/gl/debug/GrBufferObj.cpp',
'../deps/skia/src/gpu/gl/debug/GrFBBindableObj.h',
'../deps/skia/src/gpu/gl/debug/GrRenderBufferObj.h',
'../deps/skia/src/gpu/gl/debug/GrTextureObj.h',
'../deps/skia/src/gpu/gl/debug/GrTextureObj.cpp',
'../deps/skia/src/gpu/gl/debug/GrTextureUnitObj.h',
'../deps/skia/src/gpu/gl/debug/GrTextureUnitObj.cpp',
'../deps/skia/src/gpu/gl/debug/GrFrameBufferObj.h',
'../deps/skia/src/gpu/gl/debug/GrFrameBufferObj.cpp',
'../deps/skia/src/gpu/gl/debug/GrShaderObj.h',
'../deps/skia/src/gpu/gl/debug/GrShaderObj.cpp',
'../deps/skia/src/gpu/gl/debug/GrProgramObj.h',
'../deps/skia/src/gpu/gl/debug/GrProgramObj.cpp',
'../deps/skia/src/gpu/gl/debug/GrDebugGL.h',
'../deps/skia/src/gpu/gl/debug/GrDebugGL.cpp',
'../deps/skia/src/gpu/gl/mac/GrGLCreateNativeInterface_mac.cpp',
'../deps/skia/src/gpu/gl/win/GrGLCreateNativeInterface_win.cpp',
'../deps/skia/src/gpu/gl/unix/GrGLCreateNativeInterface_unix.cpp',
'../deps/skia/src/gpu/gl/mesa/GrGLCreateMesaInterface.cpp',
'../deps/skia/src/gpu/gl/angle/GrGLCreateANGLEInterface.cpp',
'../deps/skia/src/gpu/android/GrGLCreateNativeInterface_android.cpp',
],
'defines': [
'GR_IMPLEMENTATION=1',
],
'conditions': [
[ 'skia_nv_path_rendering', {
'defines': [
'GR_GL_USE_NV_PATH_RENDERING=1',
],
}],
[ 'skia_os == "linux"', {
'sources!': [
'../deps/skia/src/gpu/gl/GrGLDefaultInterface_none.cpp',
'../deps/skia/src/gpu/gl/GrGLCreateNativeInterface_none.cpp',
],
'link_settings': {
'libraries': [
'-lGL',
'-lX11',
],
},
}],
[ 'skia_mesa and skia_os == "linux"', {
'link_settings': {
'libraries': [
'-lOSMesa',
],
},
}],
[ 'skia_os == "mac"', {
'link_settings': {
'libraries': [
'$(SDKROOT)/System/Library/Frameworks/OpenGL.framework',
],
},
'sources!': [
'../deps/skia/src/gpu/gl/GrGLDefaultInterface_none.cpp',
'../deps/skia/src/gpu/gl/GrGLCreateNativeInterface_none.cpp',
],
}],
[ 'skia_mesa and skia_os == "mac"', {
'link_settings': {
'libraries': [
'$(SDKROOT)/usr/X11/lib/libOSMesa.dylib',
],
},
'include_dirs': [
'$(SDKROOT)/usr/X11/include/',
],
}],
[ 'not skia_mesa', {
'sources!': [
'../deps/skia/src/gpu/gl/mesa/GrGLCreateMesaInterface.cpp',
],
}],
[ 'skia_os == "win"', {
'sources!': [
'../deps/skia/src/gpu/gl/GrGLDefaultInterface_none.cpp',
'../deps/skia/src/gpu/gl/GrGLCreateNativeInterface_none.cpp',
],
}],
[ 'not skia_angle', {
'sources!': [
'../deps/skia/include/gpu/gl/SkANGLEGLContext.h',
'../deps/skia/src/gpu/gl/angle/GrGLCreateANGLEInterface.cpp',
'../deps/skia/src/gpu/gl/angle/SkANGLEGLContext.cpp',
],
}],
[ 'skia_os == "android"', {
'sources!': [
'../deps/skia/src/gpu/gl/GrGLDefaultInterface_none.cpp',
'../deps/skia/src/gpu/gl/GrGLCreateNativeInterface_none.cpp',
],
'link_settings': {
'libraries': [
'-lGLESv2',
'-lEGL',
],
},
}],
],
},
],
}
# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
|
#Escreva um programa que leia um número inteiro maior do
#que zero e devolva, na tela, a soma de todos os seus
#algarismos. Por exemplo, ao número 251 corresponderá
#o valor (2+5+1). Se o número lido não for maior do
#que zero, o programa terminará com a mensagem
#“Número inválido”.
num=int(input("Informe um numero inteiro: "))
txt_compl=[]
if(num>0):
algoritmo=str(num)
txt=f"{algoritmo[0]} "
txt_compl.append(txt)
for c in range(1,len(algoritmo)):
txt=f"+ {algoritmo[c]} "
txt_compl.append(txt)
print(f"O valor {num} corresponde a {txt_compl}") |
def pares(num):
valores_pares = 0
for n in num:
if n % 2 == 0:
valores_pares += 1
return print(f'{valores_pares} valor(es) par(es)')
def impares(num):
valores_impares = 0
for n in num:
if n % 2 != 0:
valores_impares += 1
return print(f'{valores_impares} valor(es) impar(es)')
def positivos(num):
valores_positivos = 0
for n in num:
if n > 0:
valores_positivos += 1
return print(f'{valores_positivos} valor(es) positivo(s)')
def negativos(num):
valores_negativos = 0
for n in num:
if n < 0:
valores_negativos += 1
return print(f'{valores_negativos} valor(es) negativo(s)')
def entrada():
numeros = list()
for i in range(5):
numeros.append(int(input()))
return numeros
numbers = entrada()
pares(numbers)
impares(numbers)
positivos(numbers)
negativos(numbers)
|
def insertShiftArray(list,val):
list[int(len(list)/2):int(len(list)/2)] = [val]
return list
|
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
c = 0
res = 0
dic = {0:-1}
for i in range(len(nums)):
n = nums[i]
if n == 1 : c += 1
else: c -= 1
if c in dic : res = max(res, i - dic[c])
else:dic[c] = i
return res |
# No Bugs in Production (NBP) Library
# https://github.com/aenachescu/nbplib
#
# Licensed under the MIT License <http://opensource.org/licenses/MIT>.
# SPDX-License-Identifier: MIT
# Copyright (c) 2019-2020 Alin Enachescu <https://github.com/aenachescu>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
supportedCompilersDict = {
"gcc-5": {
"standards": [ "-std=c99", "-std=c11" ],
"platforms": [ "-m32", "-m64"],
"gcov_tool": "gcov-5"
},
"gcc-6": {
"standards": [ "-std=c99", "-std=c11" ],
"platforms": [ "-m32", "-m64"],
"gcov_tool": "gcov-6"
},
"gcc-7": {
"standards": [ "-std=c99", "-std=c11" ],
"platforms": [ "-m32", "-m64"],
"gcov_tool": "gcov-7"
},
"gcc-8": {
"standards": [ "-std=c99", "-std=c11" ],
"platforms": [ "-m32", "-m64"],
"gcov_tool": "gcov-8"
},
"gcc-9": {
"standards": [ "-std=c99", "-std=c11" ],
"platforms": [ "-m32", "-m64"],
"gcov_tool": "gcov-9"
},
"g++-5": {
"standards": [ "-std=c++03", "-std=c++11", "-std=c++14", "-std=c++17" ],
"platforms": [ "-m32", "-m64"],
"gcov_tool": "gcov-5"
},
"g++-6": {
"standards": [ "-std=c++03", "-std=c++11", "-std=c++14", "-std=c++17" ],
"platforms": [ "-m32", "-m64"],
"gcov_tool": "gcov-6"
},
"g++-7": {
"standards": [ "-std=c++03", "-std=c++11", "-std=c++14", "-std=c++17" ],
"platforms": [ "-m32", "-m64"],
"gcov_tool": "gcov-7"
},
"g++-8": {
"standards": [ "-std=c++03", "-std=c++11", "-std=c++14", "-std=c++17" ],
"platforms": [ "-m32", "-m64"],
"gcov_tool": "gcov-8"
},
"g++-9": {
"standards": [ "-std=c++03", "-std=c++11", "-std=c++14", "-std=c++17" ],
"platforms": [ "-m32", "-m64"],
"gcov_tool": "gcov-9"
},
"clang-5.0": {
"standards": [ "-std=c99", "-std=c11" ],
"platforms": [ "-m32", "-m64" ],
"gcov_tool": "scripts/clang_cov/clang_cov_5.sh",
"gcov_tool_absolute_path": True
},
"clang-6.0": {
"standards": [ "-std=c99", "-std=c11" ],
"platforms": [ "-m32", "-m64" ],
"gcov_tool": "scripts/clang_cov/clang_cov_6.sh",
"gcov_tool_absolute_path": True
},
"clang-7": {
"standards": [ "-std=c99", "-std=c11" ],
"platforms": [ "-m32", "-m64" ],
"gcov_tool": "scripts/clang_cov/clang_cov_7.sh",
"gcov_tool_absolute_path": True
},
"clang-8": {
"standards": [ "-std=c99", "-std=c11" ],
"platforms": [ "-m32", "-m64" ],
"gcov_tool": "scripts/clang_cov/clang_cov_8.sh",
"gcov_tool_absolute_path": True
},
"clang-9": {
"standards": [ "-std=c99", "-std=c11" ],
"platforms": [ "-m32", "-m64" ],
"gcov_tool": "scripts/clang_cov/clang_cov_9.sh",
"gcov_tool_absolute_path": True
},
}
|
# This sample tests annotated types on global variables.
# This should generate an error because the declared
# type below does not match the assigned type.
glob_var1 = 4
# This should generate an error because the declared
# type doesn't match the later declared type.
glob_var1 = Exception() # type: str
glob_var1 = Exception() # type: Exception
# This should generate an error because the assigned
# type doesn't match the declared type.
glob_var1 = "hello" # type: Exception
# This should generate an error.
glob_var2 = 5
def func1():
global glob_var1
global glob_var2
# This should generate an error.
glob_var1 = 3
glob_var2 = "hello" # type: str
|
numbers = [5, 5, 5, 6, 7, 4, 6, 10]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
print(uniques) |
technologies = {}
while True:
line = input()
if "end" == line:
break
technology, courses_tokens = line.split(" - ")
if technology not in technologies:
technologies[technology] = {}
courses_tokens = [(course, int(participants)) for course, participants in
[token.split(':') for token in courses_tokens.split(", ")]]
for course, participants in courses_tokens:
technologies[technology].setdefault(course, 0)
technologies[technology][course] += participants
def get_total_participants(tech):
return sum(tech.values())
technologies = sorted(technologies.items(), key=lambda key: -get_total_participants(key[1]))
print(f"Most popular: {technologies[0][0]} ({get_total_participants(technologies[0][1])} participants)")
print(f"Least popular: {technologies[-1][0]} ({get_total_participants(technologies[-1][1])} participants)")
for technology, courses in technologies:
print(f"{technology} ({get_total_participants(courses)} participants):")
for course, participants in sorted(courses.items(), key=lambda x: -x[1]):
print(f"--{course} -> {participants}")
|
def edad(numedades):
edades = []
edades20 = []
n = 0
while n <= (numedades-1):
edades.append(int(input ("Dame una edad: ")))
if edades[n] > 20:
edades20.append(edades[n])
n += 1
edades = tuple(edades)
print ("Tus edades: ", edades)
print ("Las edades mayores a 20 años, son: ", edades20)
numedades = int(input("Dame el numero de edades: "))
edad(numedades) |
variavel = 'valor'
def func():
print(variavel)
def func2():
variavel = 'Outro valor'
print(variavel)
func()
func2()
print(variavel)
|
class Solution:
def moveRobot(self, matrix, current_position):
"""
Handles following cases:
if moving results in 0 no result
otherwise returns positions.
"""
# move robot to the right
# or down
down_move = current_position[0] + \
1, current_position[1], current_position[2] + 1
right_move = current_position[0], current_position[1] + \
1, current_position[2] + 1
if not down_move[0] < len(matrix):
# invalid down move
down_move = current_position
if not right_move[1] < len(matrix[0]):
# invalid right move
right_move = current_position
# check if 0 pos...
moves = [down_move, right_move]
answers = []
for move in moves:
if(matrix[move[0]][move[1]] != 0 and move != current_position):
answers.append(move)
return answers
def demolitionRobot(self, matrix):
# robot can only make right moves
# or down moves.
positions = [(0, 0, 0)]
while len(positions) > 0:
current_position = positions.pop()
new_pos = self.moveRobot(matrix, current_position)
# check if there is 9 in new positions.
for pos in new_pos:
if(matrix[pos[0]][pos[1]] == 9):
return pos[2]
# add new positions to the list.
positions.append(pos)
return -1
matrix = [[1, 0, 0], [1, 0, 0], [1, 1, 9]]
print(Solution().demolitionRobot(matrix))
|
# Faça um Programa que peça um número e então mostre a mensagem O número informado foi [número].
# Ivo Dias
# Recebe o numero
numero = input("Informe um numero: ")
# Mostra na tela
print("O numero informado foi %s" % numero) |
unicode_type = type(u"")
def ensure_unicode(data, encoding="utf8"):
"""
Ensures that the given string is return as type ``unicode``.
:type data: str or bytes
:param data: String to convert if needed.
:param str encoding: [opt] The encoding to use if needed..
:returns: The given string as type ``unicode``.
:rtype: str
"""
return data.decode(encoding) if isinstance(data, bytes) else unicode_type(data)
class Property():
def __init__(self):
self.raw_dict={}
def __setitem__(self, key, value): # type: (str, str) -> None
if value:
self.raw_dict[key] = ensure_unicode(value)
else:
logger.debug("Ignoring empty property: '%s'", key)
def _close(self, listitem): # type: (xbmcgui.ListItem) -> None
for key, value in self.raw_dict.items():
listitem.setProperty(key, value)
class Listitem(object):
"""
The “listitem” control is used for the creating "folder" or "video" items within Kodi.
:param str content_type: [opt] Type of content been listed. e.g. "video", "music", "pictures".
"""
def __getstate__(self):
state = self.__dict__.copy()
state["label"] = self.label
del state["listitem"]
return state
def __setstate__(self, state):
label = state.pop("label")
self.__dict__.update(state)
self.listitem = xbmcgui.ListItem()
self.label = label
def __init__(self, content_type="video"):
self._content_type = content_type
self._is_playable = False
self._is_folder = False
self._args = None
self._path = ""
#: List of paths to subtitle files.
self.subtitles = []
self.property = Property()
"""
Dictionary like object that allows you to add "listitem properties". e.g. "StartOffset".
Some of these are processed internally by Kodi, such as the "StartOffset" property,
which is the offset in seconds at which to start playback of an item. Others may be used
in the skin to add extra information, such as "WatchedCount" for tvshow items.
:examples:
>>> item = Listitem()
>>> item.property['StartOffset'] = '256.4'
"""
@property
def label(self): # type: () -> str
"""
The listitem label property.
:example:
>>> item = Listitem()
>>> item.label = "Video Title"
"""
label = self.listitem.getLabel()
return label.decode("utf8") if isinstance(label, bytes) else label
@label.setter
def label(self, label): # type: (str) -> None
self.listitem.setLabel(label)
unformatted_label = strip_formatting("", label)
self.params["_title_"] = unformatted_label
self.info["title"] = unformatted_label
@property
def path(self):
return self._path
@path.setter
def path(self, value):
# For backwards compatibility
self._path = value
self._is_playable = True
def set_path(self, path, is_folder=False, is_playable=True):
"""
Set the listitem's path.
The path can be any of the following:
* Any kodi path, e.g. "plugin://" or "script://"
* Directly playable URL or filepath.
.. note::
When specifying a external 'plugin' or 'script' as the path, Kodi will treat it as a playable item.
To override this behavior, you can set the ``is_playable`` and ``is_folder`` parameters.
:param path: A playable URL or plugin/script path.
:param is_folder: Tells kodi if path is a folder (default -> ``False``).
:param is_playable: Tells kodi if path is a playable item (default -> ``True``).
"""
self._path = path
self._is_folder = is_folder
self._is_playable = False if path.startswith("script://") else is_playable
def set_callback(self, callback, *args, **kwargs):
"""
Set the "callback" function for this listitem.
The "callback" parameter can be any of the following:
* :class:`codequick.Script<codequick.script.Script>` callback.
* :class:`codequick.Route<codequick.route.Route>` callback.
* :class:`codequick.Resolver<codequick.resolver.Resolver>` callback.
* A callback reference object :func:`Script.ref<codequick.script.Script.ref>`.
:param callback: The "callback" function or reference object.
:param args: "Positional" arguments that will be passed to the callback.
:param kwargs: "Keyword" arguments that will be passed to the callback.
"""
if hasattr(callback, "route"):
callback = callback.route
elif not isinstance(callback, CallbackRef):
# We don't have a plugin / http path,
# So we should then have a callback path
if "://" not in callback:
msg = "passing callback path to 'set_callback' is deprecated, " \
"use callback reference 'Route.ref' instead"
logger.warning("DeprecationWarning: " + msg)
callback = dispatcher.get_route(callback)
else:
msg = "passing a playable / plugin path to 'set_callback' is deprecated, use 'set_path' instead"
logger.warning("DeprecationWarning: " + msg)
is_folder = kwargs.pop("is_folder", False)
is_playable = kwargs.pop("is_playable", not is_folder)
self.set_path(callback, is_folder, is_playable)
return
self.params.update(kwargs)
self._is_playable = callback.is_playable
self._is_folder = callback.is_folder
self._path = callback
self._args = args
# noinspection PyProtectedMember
def build(self):
listitem = self.listitem
isfolder = self._is_folder
listitem.setProperty("folder", str(isfolder).lower())
listitem.setProperty("isplayable", str(self._is_playable).lower())
if isinstance(self._path, CallbackRef):
path = build_path(self._path, self._args, self.params.raw_dict)
else:
path = self._path
if not isfolder:
# Add mediatype if not already set
if "mediatype" not in self.info.raw_dict and self._content_type in ("video", "music"): # pragma: no branch
self.info.raw_dict["mediatype"] = self._content_type
# Set the listitem subtitles
if self.subtitles:
self.listitem.setSubtitles(self.subtitles)
# Add Video Specific Context menu items
self.context.append(("$LOCALIZE[13347]", "Action(Queue)"))
self.context.append(("$LOCALIZE[13350]", "ActivateWindow(videoplaylist)"))
# Close video related datasets
self.stream._close(listitem)
# Set label to UNKNOWN if unset
if not self.label: # pragma: no branch
self.label = u"UNKNOWN"
# Close common datasets
listitem.setPath(path)
self.property._close(listitem)
self.context._close(listitem)
self.info._close(listitem, self._content_type)
self.art._close(listitem, isfolder)
# Return a tuple compatible with 'xbmcplugin.addDirectoryItems'
return path, listitem, isfolder
@classmethod
def from_dict(
cls,
callback,
label,
art=None,
info=None,
stream=None,
context=None,
properties=None,
params=None,
subtitles=None
):
"""
Constructor to create a "listitem".
This method will create and populate a listitem from a set of given values.
:param Callback callback: The "callback" function or playable URL.
:param str label: The listitem's label.
:param dict art: Dictionary of listitem art.
:param dict info: Dictionary of infoLabels.
:param dict stream: Dictionary of stream details.
:param list context: List of "context menu" item(s) containing "tuples" of ("label", "command") pairs.
:param dict properties: Dictionary of listitem properties.
:param dict params: Dictionary of parameters that will be passed to the "callback" function.
:param list subtitles: List of paths to subtitle files.
:return: A listitem object.
:rtype: Listitem
:example:
>>> params = {"url": "http://example.com"}
>>> item = {"label": "Video Title", "art": {"thumb": "http://example.com/image.jpg"}, "params": params}
>>> listitem = Listitem.from_dict(**item)
"""
item = cls()
item.label = label
if isinstance(callback, str) and "://" in callback:
item.set_path(callback)
else:
item.set_callback(callback)
if params: # pragma: no branch
item.params.update(params)
if info: # pragma: no branch
item.info.update(info)
if art: # pragma: no branch
item.art.update(art)
if stream: # pragma: no branch
item.stream.update(stream)
if properties: # pragma: no branch
item.property.update(properties)
if context: # pragma: no branch
item.context.extend(context)
if subtitles: # pragma: no branch
item.subtitles.extend(subtitles)
return item
@classmethod
def next_page(cls, *args, **kwargs):
"""
Constructor for adding link to "Next Page" of content.
By default the current running "callback" will be called with all of the parameters that are given here.
You can specify which "callback" will be called by setting a keyword only argument called 'callback'.
:param args: "Positional" arguments that will be passed to the callback.
:param kwargs: "Keyword" arguments that will be passed to the callback.
:example:
>>> item = Listitem()
>>> item.next_page(url="http://example.com/videos?page2")
"""
# Current running callback
callback = kwargs.pop("callback") if "callback" in kwargs else dispatcher.get_route().callback
# Add support params to callback params
kwargs["_updatelisting_"] = True if u"_nextpagecount_" in dispatcher.params else False
kwargs["_title_"] = dispatcher.params.get(u"_title_", u"")
kwargs["_nextpagecount_"] = dispatcher.params.get(u"_nextpagecount_", 1) + 1
# Create listitem instance
item = cls()
label = u"%s %i" % (Script.localize(localized.NEXT_PAGE), kwargs["_nextpagecount_"])
item.info["plot"] = Script.localize(localized.NEXT_PAGE_PLOT)
item.label = bold(label)
item.art.global_thumb("next.png")
item.set_callback(callback, *args, **kwargs)
return item
@classmethod
def recent(cls, callback, *args, **kwargs):
"""
Constructor for adding "Recent Videos" folder.
This is a convenience method that creates the listitem with "name", "thumbnail" and "plot", already preset.
:param Callback callback: The "callback" function.
:param args: "Positional" arguments that will be passed to the callback.
:param kwargs: "Keyword" arguments that will be passed to the callback.
"""
# Create listitem instance
item = cls()
item.label = bold(Script.localize(localized.RECENT_VIDEOS))
item.info["plot"] = Script.localize(localized.RECENT_VIDEOS_PLOT)
item.art.global_thumb("recent.png")
item.set_callback(callback, *args, **kwargs)
return item
@classmethod
def search(cls, callback, *args, **kwargs):
"""
Constructor to add "saved search" support to add-on.
This will first link to a "sub" folder that lists all saved "search terms". From here,
"search terms" can be created or removed. When a selection is made, the "callback" function
that was given will be executed with all parameters forwarded on. Except with one extra
parameter, ``search_query``, which is the "search term" that was selected.
:param Callback callback: Function that will be called when the "listitem" is activated.
:param args: "Positional" arguments that will be passed to the callback.
:param kwargs: "Keyword" arguments that will be passed to the callback.
"""
if hasattr(callback, "route"):
route = callback.route
elif isinstance(callback, CallbackRef):
route = callback
else:
route = dispatcher.get_route(callback)
kwargs["first_load"] = True
kwargs["_route"] = route.path
item = cls()
item.label = bold(Script.localize(localized.SEARCH))
item.art.global_thumb("search.png")
item.info["plot"] = Script.localize(localized.SEARCH_PLOT)
item.set_callback(Route.ref("/codequick/search:saved_searches"), *args, **kwargs)
return item
@classmethod
def youtube(cls, content_id, label=None, enable_playlists=True):
"""
Constructor to add a "YouTube channel" to add-on.
This listitem will list all videos from a "YouTube", channel or playlist. All videos will have a
"Related Videos" option via the context menu. If ``content_id`` is a channel ID and ``enable_playlists``
is ``True``, then a link to the "channel playlists" will also be added to the list of videos.
:param str content_id: Channel ID or playlist ID, of video content.
:param str label: [opt] Listitem Label. (default => "All Videos").
:param bool enable_playlists: [opt] Set to ``False`` to disable linking to channel playlists.
(default => ``True``)
:example:
>>> item = Listitem()
>>> item.youtube("UC4QZ_LsYcvcq7qOsOhpAX4A")
"""
# Youtube exists, Creating listitem link
item = cls()
item.label = label if label else bold(Script.localize(localized.ALLVIDEOS))
item.art.global_thumb("videos.png")
item.params["contentid"] = content_id
item.params["enable_playlists"] = False if content_id.startswith("PL") else enable_playlists
item.set_callback(Route.ref("/codequick/youtube:playlist"))
return item
def __repr__(self):
"""Returns representation of the object."""
return "{}('{}')".format(self.__class__.__name__, ensure_native_str(self.label)) |
# Time: O(h)
# Space: O(1)
# 998
# We are given the root node of a maximum tree: a tree where every node has a value greater than
# any other value in its subtree.
#
# Just as in the previous problem, the given tree was constructed from an list A (root = Construct(A))
# recursively with the following Construct(A) routine:
#
# If A is empty, return null.
# Otherwise, let A[i] be the largest element of A. Create a root node with value A[i].
# The left child of root will be Construct([A[0], A[1], ..., A[i-1]])
# The right child of root will be Construct([A[i+1], A[i+2], ..., A[A.length - 1]])
# Return root.
# Note that we were not given A directly, only a root node root = Construct(A).
#
# Suppose B is a copy of A with the value val appended to it. It is guaranteed that B has unique values.
#
# Return Construct(B).
# Input: root = [4,1,3,null,null,2], val = 5
# Output: [5,4,null,1,3,null,null,2]
# Explanation: A = [1,4,2,3], B = [1,4,2,3,5]
# Input: root = [5,2,4,null,1], val = 3
# Output: [5,2,4,null,1,null,3]
# Explanation: A = [2,1,5,4], B = [2,1,5,4,3]
# Input: root = [5,2,3,null,1], val = 4
# Output: [5,2,4,null,1,3]
# Explanation: A = [2,1,5,3], B = [2,1,5,3,4]
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# 扫描右子树的所有根节点,找到插入位置
# Search on the right, find the node that cur.val > val > cur.right.val
# put old cur.right as node.left, put node as new cur.right.
# use only 1 pointer curr, use dummy node for edge case
def insertIntoMaxTree(self, root, val): # USE THIS
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
dummy = TreeNode(float('inf'))
dummy.right = root
curr = dummy
while curr.right and curr.right.val > val:
curr = curr.right
node = TreeNode(val)
node.left = curr.right
curr.right = node
return dummy.right
# use 2 pointers cur, par; but don't need special handle edge case
def insertIntoMaxTree2(self, root, val):
node = TreeNode(val)
cur, par = root, None
while cur and cur.val > val:
par = cur
cur = cur.right
node.left = cur
if par:
par.right = node
return root
else:
return node
# recursion: Time O(h), Space O(h)
# If root.val > val, recusion on the right.
# Else, put right subtree on the left of new node TreeNode(val)
def insertIntoMaxTree_recursion(self, root, val):
if root and root.val > val:
root.right = self.insertIntoMaxTree(root.right, val)
return root
node = TreeNode(val)
node.left = root
return node |
"""Collect modules for import."""
__author__ = "David Longo (longodj@gmail.com)"
#from .data import JTNNCollator # noqa: F401 |
#
# PySNMP MIB module ROOMALERT4E-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ROOMALERT4E-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:58:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, IpAddress, Bits, Counter32, Gauge32, Unsigned32, enterprises, TimeTicks, MibIdentifier, iso, NotificationType, Integer32, ObjectIdentity, ModuleIdentity, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "IpAddress", "Bits", "Counter32", "Gauge32", "Unsigned32", "enterprises", "TimeTicks", "MibIdentifier", "iso", "NotificationType", "Integer32", "ObjectIdentity", "ModuleIdentity", "Counter64")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
avtech = MibIdentifier((1, 3, 6, 1, 4, 1, 20916))
products = MibIdentifier((1, 3, 6, 1, 4, 1, 20916, 1))
ROOMALERT4E = MibIdentifier((1, 3, 6, 1, 4, 1, 20916, 1, 6))
sensors = MibIdentifier((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1))
signaltower = MibIdentifier((1, 3, 6, 1, 4, 1, 20916, 1, 6, 2))
traps = MibIdentifier((1, 3, 6, 1, 4, 1, 20916, 1, 6, 3))
internal = MibIdentifier((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 1))
temperature = MibIdentifier((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 1, 1))
humidity = MibIdentifier((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 1, 2))
heat_index = MibIdentifier((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 1, 3)).setLabel("heat-index")
digital = MibIdentifier((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 2))
digital_sen1 = MibIdentifier((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 2, 1)).setLabel("digital-sen1")
digital_sen2 = MibIdentifier((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 2, 2)).setLabel("digital-sen2")
switch = MibIdentifier((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 3))
internal_tempf = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setLabel("internal-tempf").setMaxAccess("readonly")
if mibBuilder.loadTexts: internal_tempf.setStatus('mandatory')
if mibBuilder.loadTexts: internal_tempf.setDescription('The internal temperature reading in Fahrenheit. Because the SNMP Protocol does not support floating point numbers, values are scaled by 100 and should be divided by 100 to get the actual value.')
internal_tempc = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setLabel("internal-tempc").setMaxAccess("readonly")
if mibBuilder.loadTexts: internal_tempc.setStatus('mandatory')
if mibBuilder.loadTexts: internal_tempc.setDescription('The internal temperature reading in Celsius. Because the SNMP Protocol does not support floating point numbers, values are scaled by 100 and should be divided by 100 to get the actual value.')
internal_humidity = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 1, 2, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setLabel("internal-humidity").setMaxAccess("readonly")
if mibBuilder.loadTexts: internal_humidity.setStatus('mandatory')
if mibBuilder.loadTexts: internal_humidity.setDescription('The internal relative humidity reading in %RH. Because the SNMP Protocol does not support floating point numbers, values are scaled by 100 and should be divided by 100 to get the actual value.')
internal_heat_index = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 1, 3, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setLabel("internal-heat-index").setMaxAccess("readonly")
if mibBuilder.loadTexts: internal_heat_index.setStatus('mandatory')
if mibBuilder.loadTexts: internal_heat_index.setDescription('The internal heat index reading in Fahrenheit. Because the SNMP Protocol does not support floating point numbers, values are scaled by 100 and should be divided by 100 to get the actual value.')
digital_sen1_1 = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setLabel("digital-sen1-1").setMaxAccess("readonly")
if mibBuilder.loadTexts: digital_sen1_1.setStatus('mandatory')
if mibBuilder.loadTexts: digital_sen1_1.setDescription('If this sensor is a Temperature or Temp/Humidity sensor, this value represents the current temperature in Celsius. If this sensor is a Digital Power Sensor, this value represents the Current reading in Amperage.')
digital_sen1_2 = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setLabel("digital-sen1-2").setMaxAccess("readonly")
if mibBuilder.loadTexts: digital_sen1_2.setStatus('mandatory')
if mibBuilder.loadTexts: digital_sen1_2.setDescription('If this sensor is a Temperature or Temp/Humidity sensor, this value represents the current temperature in Fahrenheit. If this sensor is a Digital Power Sensor, this value represents the Power reading in Watts.')
digital_sen1_3 = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setLabel("digital-sen1-3").setMaxAccess("readonly")
if mibBuilder.loadTexts: digital_sen1_3.setStatus('mandatory')
if mibBuilder.loadTexts: digital_sen1_3.setDescription('If this sensor is a Temp/Humidity sensor, this value represents the current relative humidity in % Relative Humidity. If this sensor is a Digital Power Sensor, this value represents the Voltage reading in Volts.')
digital_sen1_4 = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setLabel("digital-sen1-4").setMaxAccess("readonly")
if mibBuilder.loadTexts: digital_sen1_4.setStatus('mandatory')
if mibBuilder.loadTexts: digital_sen1_4.setDescription('If this sensor is a Temperature or Temp/Humidity sensor, this value represents the current heat index in Fahrenheit. If this sensor is a Digital Power Sensor, this value represents the Reference reading in Volts.')
digital_sen2_1 = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 2, 2, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setLabel("digital-sen2-1").setMaxAccess("readonly")
if mibBuilder.loadTexts: digital_sen2_1.setStatus('mandatory')
if mibBuilder.loadTexts: digital_sen2_1.setDescription('If this sensor is a Temperature or Temp/Humidity sensor, this value represents the current temperature in Celsius. If this sensor is a Digital Power Sensor, this value represents the Current reading in Amperage.')
digital_sen2_2 = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 2, 2, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setLabel("digital-sen2-2").setMaxAccess("readonly")
if mibBuilder.loadTexts: digital_sen2_2.setStatus('mandatory')
if mibBuilder.loadTexts: digital_sen2_2.setDescription('If this sensor is a Temperature or Temp/Humidity sensor, this value represents the current temperature in Fahrenheit. If this sensor is a Digital Power Sensor, this value represents the Power reading in Watts.')
digital_sen2_3 = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 2, 2, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setLabel("digital-sen2-3").setMaxAccess("readonly")
if mibBuilder.loadTexts: digital_sen2_3.setStatus('mandatory')
if mibBuilder.loadTexts: digital_sen2_3.setDescription('If this sensor is a Temp/Humidity sensor, this value represents the current relative humidity in % Relative Humidity. If this sensor is a Digital Power Sensor, this value represents the Voltage reading in Volts.')
digital_sen2_4 = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 2, 2, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setLabel("digital-sen2-4").setMaxAccess("readonly")
if mibBuilder.loadTexts: digital_sen2_4.setStatus('mandatory')
if mibBuilder.loadTexts: digital_sen2_4.setDescription('If this sensor is a Temperature or Temp/Humidity sensor, this value represents the current heat index in Fahrenheit. If this sensor is a Digital Power Sensor, this value represents the Reference reading in Volts.')
switch_sen1 = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 1, 3, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1))).setLabel("switch-sen1").setMaxAccess("readonly")
if mibBuilder.loadTexts: switch_sen1.setStatus('mandatory')
if mibBuilder.loadTexts: switch_sen1.setDescription('The reading for switch sensor 1 (0 = OPEN, 1 = CLOSED).')
red_led = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 2, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1))).setLabel("red-led").setMaxAccess("readwrite")
if mibBuilder.loadTexts: red_led.setStatus('current')
if mibBuilder.loadTexts: red_led.setDescription('The status of this Signal Tower element (0 = OFF, 1 = ON).')
amber_led = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 2, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1))).setLabel("amber-led").setMaxAccess("readwrite")
if mibBuilder.loadTexts: amber_led.setStatus('current')
if mibBuilder.loadTexts: amber_led.setDescription('The status of this Signal Tower element (0 = OFF, 1 = ON).')
green_led = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 2, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1))).setLabel("green-led").setMaxAccess("readwrite")
if mibBuilder.loadTexts: green_led.setStatus('current')
if mibBuilder.loadTexts: green_led.setDescription('The status of this Signal Tower element (0 = OFF, 1 = ON).')
blue_led = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 2, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1))).setLabel("blue-led").setMaxAccess("readwrite")
if mibBuilder.loadTexts: blue_led.setStatus('current')
if mibBuilder.loadTexts: blue_led.setDescription('The status of this Signal Tower element (0 = OFF, 1 = ON).')
white_led = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 2, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1))).setLabel("white-led").setMaxAccess("readwrite")
if mibBuilder.loadTexts: white_led.setStatus('current')
if mibBuilder.loadTexts: white_led.setDescription('The status of this Signal Tower element (0 = OFF, 1 = ON).')
alarm1 = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 2, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: alarm1.setStatus('current')
if mibBuilder.loadTexts: alarm1.setDescription('The status of this Signal Tower element (0 = OFF, 1 = ON).')
alarm2 = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 2, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: alarm2.setStatus('current')
if mibBuilder.loadTexts: alarm2.setDescription('The status of this Signal Tower element (0 = OFF, 1 = ON).')
alarmmessage = MibScalar((1, 3, 6, 1, 4, 1, 20916, 1, 6, 3, 1), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: alarmmessage.setStatus('mandatory')
if mibBuilder.loadTexts: alarmmessage.setDescription('Last Alarm Message')
room_alert_4e_snmp_trap = NotificationType((1, 3, 6, 1, 4, 1, 20916, 1, 6) + (0,2)).setLabel("room-alert-4e-snmp-trap").setObjects(("ROOMALERT4E-MIB", "alarmmessage"))
if mibBuilder.loadTexts: room_alert_4e_snmp_trap.setDescription('A room-alert-4e-snmp-trap indicates that an alarm condition has occurred on the sensor indicated by the alarmmessage variable.')
mibBuilder.exportSymbols("ROOMALERT4E-MIB", digital_sen2_4=digital_sen2_4, alarm2=alarm2, digital_sen1_3=digital_sen1_3, internal=internal, green_led=green_led, digital_sen1_4=digital_sen1_4, red_led=red_led, blue_led=blue_led, digital=digital, temperature=temperature, white_led=white_led, signaltower=signaltower, digital_sen1_1=digital_sen1_1, digital_sen1_2=digital_sen1_2, sensors=sensors, ROOMALERT4E=ROOMALERT4E, internal_tempf=internal_tempf, internal_humidity=internal_humidity, internal_heat_index=internal_heat_index, room_alert_4e_snmp_trap=room_alert_4e_snmp_trap, digital_sen2_1=digital_sen2_1, traps=traps, products=products, digital_sen2_3=digital_sen2_3, alarm1=alarm1, switch_sen1=switch_sen1, heat_index=heat_index, humidity=humidity, switch=switch, avtech=avtech, alarmmessage=alarmmessage, digital_sen2=digital_sen2, digital_sen2_2=digital_sen2_2, digital_sen1=digital_sen1, amber_led=amber_led, internal_tempc=internal_tempc)
|
dist = 0
speed = 0
lastTime = 0
while(True):
try:
inp = input()
if not inp:
raise ValueError
except ValueError:
break
except EOFError:
break
arr = inp.split(' ')
if (len(arr) == 1):
outp = True
else:
outp = False
time = arr[0].split(':')
currtime = int(time[0])*3600 + int(time[1])*60 + int(time[2]) - 1
diff = currtime - lastTime
dist += speed * (diff / 3600)
# print(time)
# print(currtime)
if outp:
# print(diff * 60)
print(arr[0] + ' ' + '%.2f' % dist + ' km')
else:
speed = int(arr[1])
lastTime = currtime
|
class Solution:
# 1st solution
# O(1) time | O(1) space
def isPowerOfTwo(self, n: int) -> bool:
x = 1
while x < n:
x *= 2
return x == n
# 2nd solution
# O(1) time | O(1) space
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and not (n & n-1) |
'''Crie um programa que leia e mostre
na tela todos os números de 1 até 50
e mostre os números pares'''
print('Contagem de números Pares!!')
for n in range(0, 51, 2):
print(n, end=' ')
|
# coding=utf-8
"""
Tests for gym-acnportal.
TODO: This module copies data from acnportal. Should this instead be
accessed directly from acnportal?
"""
|
'''
# Pass command
for i in range (0,9):
if i == 3:
pass
print (" Pass Here", end = '')
else:
print (f" {i}", end = '')
'''
# String Commands
myString = "India is my country"
myString2 = "I love my India"
print (myString.index("is"))
print (myString.find("is"))
print (myString.isalpha())
print (myString.isalnum())
print (myString.isdecimal())
print (myString.islower())
print (myString.isupper())
print (myString.isdigit())
print (myString.isspace())
print (myString.isidentifier())
print (myString.isnumeric())
print (myString.istitle())
print (myString.join(myString2))
S1 = "Kerivada Makkale"
S2 = "Anjooran"
print(S1.join(S2))
print (len(S1))
print (S1.lower())
print (S1.upper())
print (S1.replace("Kerivada","Odivada"))
print (S1.strip())
print (S1.split())
print (S1.startswith("Kerivada"))
print (S1.swapcase())
|
# Issue #38 in Python 2.7
# Problem is distinguishing 'continue' from 'jump_back'
# in assembly instructions.
# Here, we hack looking for two jump backs
# followed by the end of the except. This
# is a big hack.
for a in [__name__]:
try:len(a)
except:continue
# The above has JUMP_ABSOLUTE in it.
# This has JUMP_FORWARD instead.
for a in [__name__]:
try:len(a)
except:continue
y = 2
|
App.open("java -jar C:/JabRef-4.2-fat.jar")
wait(30)
click("1529632189350.png")
wait(2)
click("1529632296782.png")
wait(2)
click("1529632312432.png")
wait(2)
click("1529632554435.png")
wait(2)
click("1529632574104.png")
wait(2)
click("1529632589427.png")
wait(2)
click("1529632601277.png")
wait(2)
click("1529632757740.png")
|
class Solution:
def makeLargestSpecial(self, S):
"""
:type S: str
:rtype: str
"""
count = i = 0
res = []
for j, ch in enumerate(S):
count += 1 if ch == '1' else -1
if count == 0:
res.append('1' + self.makeLargestSpecial(S[i + 1:j]) + '0')
i = j + 1
return ''.join(sorted(res, reverse=True)) |
class Solution:
@staticmethod
def jewels_and_stones(jewels: str, stones: str) -> int:
count = 0
for i in stones:
if i in jewels:
count += 1
continue
return count
J = "z"
S = "ZZ"
solution = Solution()
print(solution.jewels_and_stones(J, S))
|
# -*- coding: utf-8 -*-
# author:lyh
# datetime:2020/7/12 9:55
"""
1513. 仅含 1 的子串数
给你一个二进制字符串 s(仅由 '0' 和 '1' 组成的字符串)。
返回所有字符都为 1 的子字符串的数目。
由于答案可能很大,请你将它对 10^9 + 7 取模后返回。
示例 1:
输入:s = "0110111"
输出:9
解释:共有 9 个子字符串仅由 '1' 组成
"1" -> 5 次
"11" -> 3 次
"111" -> 1 次
示例 2:
输入:s = "101"
输出:2
解释:子字符串 "1" 在 s 中共出现 2 次
示例 3:
输入:s = "111111"
输出:21
解释:每个子字符串都仅由 '1' 组成
示例 4:
输入:s = "000"
输出:0
提示:
s[i] == '0' 或 s[i] == '1'
1 <= s.length <= 10^5
"""
class Solution:
def numSub(self, s: str) -> int:
res = 0
pre = 0
mod = int(1e9 + 7)
for c in s:
if c == '1':
pre += 1
res += pre
res %= mod
else:
pre = 0
return res
if __name__ == '__main__':
print(
Solution().numSub(nums=[5, 3, 2, 4]),
)
|
#------------------------SKLEP---------------------------#
#-----------------Spis przedmiotów w sklepie-------------#
#### nazwa # cena # ilość #####
sklep = {1: ['Arbuz', 3.50, 10],
2: ["Banan", 2.99, 2],
3: ["Cebula", 9.99, 1],
4: ["Wisnia", 0.5, 100],
5: ["Morela", 5.45, 15],
6: ["Jablko", 1.51, 8]}
#-----------------Tablica zamowienia---------------------#
zamowienie = []
def exit_function():
print("Do następnego razu...\nZegnaj")
exit()
def sprawdzenie_ilosci_produktu(numer_produktu, zamowiona_ilosc):
sprawdz_ilosc = sklep[numer_produktu][2]
if sprawdz_ilosc >= zamowiona_ilosc:
print("Ok, mamy tyle w magazynie, laduje...")
return zamowiona_ilosc
elif sprawdz_ilosc < zamowiona_ilosc:
print("Przykro mi, nie mamy takiej ilości wybranego produktu, Moze zechcesz kupic cos innego?")
return twoj_wybor()
def cena_produktu(id, ilosc_produktu):
cenaxilosc = ilosc_produktu * sklep[id][1]
print("%s w ilosci zamówionej kosztuje: %d" % (sklep[id][0], cenaxilosc), "PLN")
return sklep[id][0], ilosc_produktu, cenaxilosc
def dodaj_do_zamowienia(nazwa_produktu, zamowiona_ilosc, cena_calkowita):
zamowienie.append([nazwa_produktu, zamowiona_ilosc, cena_calkowita])
return zamowienie
def rachunek(zamowienie):
pieniadze = 0
for powtorz in range(0, len(zamowienie)):
pieniadze += zamowienie[powtorz][2]
return pieniadze
def aktualne_zamowienie(zamowienie):
print("--------------------------")
print("| RACHUNEK |")
print("--------------------------")
print("| Produkt |Ilość| Cena |")
print("--------------------------")
for powtorz in range(0, len(zamowienie)):
print("|%10s" % zamowienie[powtorz][0], "|%4s" % zamowienie[powtorz][1], "|%5.2f" % zamowienie[powtorz][2], "|")
print("--------------------------")
def twoj_wybor():
print("Zatem wybierz proszę przedmiot ktory cie interesuje podając numer ID oraz ilość która chcesz kupic")
pokaz_liste()
try:
i_d = int(input("Wybierz przedmiot z listy podając numer ID: "))
ilosc = int(input("Wybierz ile chcesz kupić produktów typu %s " % sklep[i_d][0]))
zamowiona_ilosc = sprawdzenie_ilosci_produktu(i_d, ilosc)
[nazwa_produktu, zamowiona_ilosc, cena_calkowita] = cena_produktu(i_d, zamowiona_ilosc)
zamowienie = dodaj_do_zamowienia(nazwa_produktu, zamowiona_ilosc, cena_calkowita)
aktualne_zamowienie(zamowienie)
except KeyError:
print("Nie ma takiej liczby w menu zaprezentowanym")
except ValueError:
print("Należało podać liczbę a inny znak")
finally:
while True:
decyzja2 = input("Czy chcesz dodatkowo cos kupic? (t/n)")
if decyzja2 == "t":
twoj_wybor()
elif decyzja2 == "n":
try:
pieniadze = rachunek(zamowienie)
print("W sumie musisz zaplacic za wszystkie produkty %6.2f" % pieniadze, "PLN")
except UnboundLocalError:
print("Prawdopodobnie nic nie kupiles dlatego tez")
exit_function()
else:
print("Proszę wpisać literę \"t\" lub \"n\" ")
def pokaz_liste():
print("------------------")
print("|ID |", " Produkt |")
print("------------------")
for lista_w_sklepie in sklep:
print("|", lista_w_sklepie, "|", "%10s" % sklep[lista_w_sklepie][0], "|")
print("------------------")
def main():
print("Witaj w sklepie!\n" + "Oto lista dostepnych produktow w sklepie:")
pokaz_liste()
while True:
decyzja = input("Czy chcesz cos kupic? (t/n): ")
if decyzja == "t":
twoj_wybor()
elif decyzja == "n":
return exit_function()
else:
print("Zła litera, Proszę wpisać literę \"t\" lub \"n\" ")
main()
|
'''A simple calculator using a dictionary to look up functions for operators'''
def add(n1, n2): return n1 + n2
def mult(n1, n2): return n1 * n2
opers = {
'+': add,
'*': mult
}
print("Enter expressions like 23 * 10 or 2 - 5")
while True:
expr = input('> ')
if expr:
try:
(op1, op, op2) = expr.split(' ')
print(opers[op](int(op1), int(op2)))
except Exception:
print("Sorry, I couldn't make sense of that")
else:
break
|
#read the input test cases into a list (of lists)
test_file = open("input_test_case", "r")
test_file = [element.strip() for element in test_file]
test_case_count = int(test_file[0])
test_cases = [[] for col in range(test_case_count)]; test_case_count = 0
test_file = test_file[2:]
for idx, element in enumerate(test_file):
if (len(element)):
test_cases[test_case_count].append(element)
else:
test_case_count += 1
#process each case individually
for case in test_cases:
#calculate length of the file
file_len = 0
for fragment in case:
file_len += len(fragment)
file_len //= (len(case)//2)
#create an array of dicts. for all possible fragments
dict_array = [ {} for frag_size in range(file_len) ]
for fragment in case:
if (fragment in dict_array[len(fragment)]):
dict_array[len(fragment)-1][fragment] += 1
else:
dict_array[len(fragment)-1][fragment] = 1
dict_array = [ list(element) for element in dict_array ]
#go through each of the sizes, and create all possible combinations of a file
comb_array = [ set() for case_count in range(file_len//2) ]
for idx in range(file_len//2):
word_size = idx + 1;
if ( word_size == file_len//2 and (not file_len%2) ):
if (len(dict_array[word_size-1]) == 1):
comb_array[idx].add(2*dict_array[word_size-1][0])
else:
for rep in range(0, 1+1):
comb_array[idx].add("".join(dict_array[word_size-1]))
dict_array[word_size-1].reverse()
else:
for idx_1, element_1 in enumerate(dict_array[word_size-1]):
for idx_2, element_2 in enumerate(dict_array[file_len-word_size-1]):
comb_array[idx].add(element_1 + element_2); comb_array[idx].add(element_2 + element_1)
#we find the only combination that's common across ALL the words
final_set = set();
for comb_set in comb_array:
if (comb_set):
#check if 'final' set is empty
if (not final_set):
final_set = final_set.union(comb_set)
else:
final_set.intersection_update(comb_set)
#break out of loop if only one selection remains
if (len(final_set) == 1):
break
#we print all possibilities (in case there are multiple)
print(list(final_set)[0])
print("");
#NOTE: there can be MULTIPLE solutions (and we need to print only ONE of them), and that might NOT neccesarily
#match uDebug's solution(s), but this solutino IS correct
|
#
# Copyright 2022 Erwan Mahe (github.com/erwanM974)
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
timeout_in_seconds = 10
#
multi_trace_number_per_loop_height = 5
#
multitrace_outer_loop_ns = [x for x in range(1,41)]
#
multi_trace_obs = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
#
hsfs = ["hid_wtloc","hid_noloc","sim_wtloc","sim_noloc"]
#
sensor_example_lifelines = ["CSI","CI","SM","LSM","CSM","CR","CA","SOS"]
|
'''
Bifurcaciones
Estructura.-
if CONDICION:
INSTRUCCIONES
[elif CONDICION:
INSTRUCCIONES
else:
INSTRUCCIONES
]
**Las palabras en mayusculas indican estatutos variables (no siempre son los mismos)
y lo que esta en corchetes es opcional. Puede haber mas de un elif.
'''
#Ejemplos
matricula=20
temperatura=40
if matricula%2==0:
print('La matricula es par')
else:
print('La matricula es impar')
if temperatura<15:
print('Tengo frio')
elif temperatura>=15 and temperatura<26:
print('Esta agradable')
elif temperatura>=26 and temperatura<35:
print('Tengo calor')
else:
print('Tengo mucho calor')
|
# Python program to display the Fibonacci sequence
def fibonacci(n):
if n <= 1:
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
N = input()
if N <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(N):
print(fibonacci(i)) |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 13 06:01:48 2020
@author: azmanrafee
"""
X=[8]
NX=[800]
x0=0
xn=0
azim_div=64
energy_group=1
nu=1
def sigma_scatter(x):
return 0.8
def sigma_trans(x):
return 1.0
def sigma_fis(x):
return 1.0
|
"""Stop words for Cantonese."""
_STOP_WORDS = """
一啲
一定
不如
不過
之後
乜
乜嘢
人哋
但係
你
你哋
佢
佢哋
係
個
其他
冇
再
到
即
即係
原來
去
又
可以
可能
同
同埋
吖
呀
呢
咁
咗
咩
咪
哦
哩
哩個
哩啲
哩度
哩樣
唔
唔使
唔係
啊
啲
喎
喺
喺度
嗯
嗰
嗰個
嗰啲
嗰度
嘅
嘢
噉
噉樣
因為
多
太
好
如果
就
已經
幾
幾多
得
想
應該
成日
我
我哋
或者
所以
最
會
有
有冇
有啲
未
梗係
然之後
由
真係
睇
知
而
而家
自己
要
覺得
話
諗
講
譬如
跟住
返
過
邊個
都
點
點樣
點解
""".strip().split()
def stop_words(add=None, remove=None):
"""Return Cantonese stop words.
.. versionadded:: 2.2.0
Parameters
----------
add : iterable[str], optional
Stop words to add.
remove : iterable[str], optional
Stop words to remove.
Returns
-------
set[str]
Examples
--------
>>> stop_words_1 = stop_words()
>>> len(stop_words_1)
104
>>> '香港' in stop_words_1
False
>>> stop_words_1 # doctest: +SKIP
{'一啲', '一定', '不如', '不過', ...}
>>>
>>> stop_words_2 = stop_words(add='香港')
>>> len(stop_words_2)
105
>>> '香港' in stop_words_2
True
"""
_stop_words = set(_STOP_WORDS)
if add:
if isinstance(add, str):
_stop_words.add(add)
else:
# assume "add" is an iterable of strings
_stop_words |= set(add)
if remove:
if isinstance(remove, str):
_stop_words.remove(remove)
else:
# assume "remove" is an iterable of strings
_stop_words -= set(remove)
return _stop_words
|
__author__ = '''
Dawson Reid (dreid93@gmail.com)
'''
VALID_CURRENCY = ['CAD', 'BTC', 'LTC']
VALID_CURRENCY_PAIRS = ['BTCCAD', 'LTCCAD', 'BTCLTC']
DATE_FORMAT = '%Y-%m-%d'
VALID_WITHDRAW_CURRENCY = ['BTC', 'LTC']
|
"""
Stores information for each dimension of parallelism
"""
class parallelism():
def __init__(self, pp: int, dp: int, mp: int, pp_parts: list, rank_map: dict):
self.pp = pp
self.dp = dp
self.mp = mp
"""
The order of axis is (pp, dp, mp). For example, if dp=2,mp=3,pp=4,
the numbe gpu at number 5 stands for (pp=0, dp=1, mp=2).
An example pp_parts for pp = 2 is [0, 14, 30] for a load-balanced
GPT2 model with num_layer = 24.
"""
self._check_valid_rank(rank_map)
self.rank_map = rank_map
self.pp_parts = pp_parts
"""
Check whether the rank_map is a valid permutation from 0 to num(gpu)-1.
"""
def _check_valid_rank(self, rank_map):
base = []
for k, v in rank_map.items():
base.extend(v)
bijection = (len(rank_map) == self.pp * self.dp * self.mp)
validity = (sorted(base) == list(range(len(base))))
assert validity and bijection, "rank map is not a permutation from 0 to num_gpus-1."
"""
Returns this as (rank_map, pp, dp, mp, pp_config)
"""
def get_repr(self):
return (self.rank_map, self.pp, self.dp, self.mp, self.pp_parts)
"""
Returns the rank to axis. If pp=dp=mp=2, rank 3 gives (0,1,1)
"""
def rank2axis(self, rank):
pp = rank // (self.mp * self.dp)
remainder = rank % (self.mp * self.dp)
dp = remainder // (self.mp)
remainder = remainder % self.mp
mp = remainder
returns (pp, dp, mp)
"""
Returns the axis to rank. If pp=dp=mp=2, (0,1,1) gives 3
"""
def axis2rank(self, axis):
pp, dp, mp = axis
return mp + self.mp * dp + (self.mp * self.dp) * pp
|
"""
constants.py
Constants.py é responsável por armazenar qualquer varia´vel fixa utilizada no projeto.
"""
WITAI_KEY = 'ZBH7LRPZAISA7VIM7CNZDG3HJJPRTVTA'
PYOWM_KEY = '48250140b550af15b1537f212d815013'
NEWS_KEY = '281513d9cf5f444da3c010c87cccdd62'
|
''' 5.9 Escreva um programa que leia dois números. Imprima a divisão inteira do
primeiro pelo segundo, assi m como o resto da divisão. Utilize apenas os operadores
de soma e subtração para calcular o resultado. Lembre-se de que podemos entender o
quociente da divisão de dois números como a quantidade de vezes que podemos retirar
o divisor do dividendo. Logo, 20 ÷ 4 = 5, uma vez que podemos subtrair 4 cinco vezes
de 20. ''' |
# https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square
'''
Time Complexity: O(N)
Space Complexity: O(N)
'''
def count_good_rectangles(rectangles):
max_len, all_max_lens = 0, []
for rec in rectangles:
square_len = min(rec[0], rec[1])
max_len = max(max_len, square_len)
all_max_lens.append(square_len)
counter = 0
for length in all_max_lens:
if length == max_len:
counter += 1
return counter
def count_good_rectangles_optimized(rectangles):
max_len, counter = 0, 0
for rec in rectangles:
square_len = min(rec[0], rec[1])
if square_len > max_len:
max_len = square_len
counter = 0
if square_len == max_len:
counter += 1
return counter |
"""Author: Brandon Trabucco
String values for use in the caption machine.
"""
WELCOME_STRING = """
I'm ready to caption images for you.
Please tell me a command, or say help.
"""
HELP_STRING = """
Ask me to navigate,
learn a place,
tell where I am,
look around,
or tell what I see
I currently know {0} places.
These are {1}.
"""
UNK_STRING = """
I'm sorry, I do not recognize the {0}.
I currently know {1} places.
These are {2}.
"""
LOST_STRING = """
I'm sorry, I cannot determine my position.
"""
WHERE_STRING = """
I am closest to the {0},
which is about {1:.2f} units away.
"""
NAV_STRING = """
I am navigating to the {0},
which is about {1:.2f} units away.
"""
STOP_STRING = """
Thanks for talking with me, have a nice day.
"""
ERROR_STRING = """
There was an error with your request.
"""
THINK_STRING = """
Okay, I am thinking of a caption.
"""
STILL_THINK_STRING = """
Still thinking of a caption.
"""
KNOWN_STRING = """
I already know where the {0} is located.
"""
LEARN_STRING = """
I have added {0} to my memory.
"""
|
class UnionFind:
def __init__(self):
self.parent = {}
self.name = {}
def find(self, a):
path = []
while self.parent[a] != a:
path.append(a)
a = self.parent[a]
for p in path:
self.parent[p] = a
return a
def connect(self, a, b):
root_a = self.find(a)
root_b = self.find(b)
if root_a != root_b:
self.parent[root_b] = root_a
def add(self, a, name):
self.parent[a] = a
self.name[a] = name
def exist(self, a):
return a in self.parent
class Solution:
"""
@param accounts: List[List[str]]
@return: return a List[List[str]]
"""
def accountsMerge(self, accounts):
union = UnionFind()
for mails in accounts:
if len(mails) < 2:
continue
for i in range(1, len(mails)):
if not union.exist(mails[i]):
union.add(mails[i], mails[0])
for i in range(1, len(mails) - 1):
union.connect(mails[i], mails[i + 1])
mail_group = {}
for mail in union.parent.keys():
root = union.find(mail)
if root not in mail_group:
mail_group[root] = set([root])
mail_group[root].add(mail)
results = []
for mail, mail_list in mail_group.items():
mail_list = list(mail_list)
mail_list.sort()
mail_list.insert(0, union.name[mail])
results.append(mail_list)
return results |
num_to_word = {
0: '',
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
20: 'twenty',
30: 'thirty',
40: 'forty',
50: 'fifty',
60: 'sixty',
70: 'seventy',
80: 'eighty',
90: 'ninety',
100: 'hundred',
1000: 'thousand'
}
def number_to_word(n):
if 20 >= n > 0:
return num_to_word[n]
# 21 - 99
if n < 100:
n_ten = n // 10
n_one = n - (n_ten * 10)
return f'{num_to_word[n_ten * 10]} {num_to_word[n_one]}'
# 101 - 999
if n < 1000:
n_hundred = n // 100
n_ten = (n // 10) - (n_hundred * 10)
n_one = n - (n_hundred * 100) - (n_ten * 10)
word = f'{num_to_word[n_hundred]} hundred'
if n_ten == 0 and n_one == 0:
return word
elif n_ten == 0 and n_one > 0:
word += f' and {num_to_word[n_one]}'
elif n_ten == 1 and n_one > 0:
word += f' and {num_to_word[10 * n_ten + n_one]}'
else:
word += f' and {num_to_word[n_ten * 10]} {num_to_word[n_one]}'
return word
# 1000
if n == 100 or n == 1000:
return f'one {num_to_word[n]}'
# We don't support anything else :\
return None
def count_number_chars(n):
word = number_to_word(n)
return len(word.replace(' ', ''))
def compute():
total = 0
for i in range(1, 1001):
print(number_to_word(i))
total += count_number_chars(i)
return total
if __name__ == '__main__':
print(compute())
|
# 1.2 Check Permutation:
# Given two strings, write a method to decide if one is a permutation of the other.
# https://github.com/joaomh/Cracking-the-Code-Interview-Python
# My solution
def Permutation(str1, str2):
str1 = str1.lower()
str2 = str2.lower()
for character in str1:
if character is ' ':
pass
elif character in str2:
str2 = str2.replace(character, '', 1)
else:
return False
if len(str2.replace(' ','')) == 0:
return True
else:
return False
# Test
print("Pass" if Permutation('he llo','elhlo') else "Fail")
print("Pass" if Permutation('he was there','theresaweh') else "Fail")
|
n = int(input())
data = []
for _ in range(n):
x, y = map(str, input().split())
data.append([int(x), y])
sorted_data = sorted(data, key=lambda item : item[0])
for x, y in sorted_data:
print('{0} {1}'.format(x, y)) |
# Função que descobre o maior
def maior (*valor):
print("-=-" * 15)
print("Analisando os valores passados...")
print(f"{valor} Foram informados {len(valor)} ao todo ")
print(f"O maior valor informado foi {max(valor)} ")
print("-=-" * 15)
maior(1, 2, 3, 5) |
# subtracting type dp with sort
class Solution(object):
def combinationSum(self, candidates, target):
candidates.sort()
dp = [[[]]] + [[] for i in xrange(target)]
for i in xrange(1, target + 1):
for number in candidates:
if number > i:
break
for L in dp[i - number]:
if not L or number >= L[-1]:
dp[i] += L + [number],
return dp[target]
|
"""A list of structured message templates supported by the platform. For unstructured content see content_types"""
class Template(object):
pass
|
def dict_path(d, path):
if not isinstance(path, (list, tuple)):
raise ValueError()
for keys in path:
if type(keys) is not list:
keys = [keys]
value = None
for key in keys:
if key not in d:
continue
value = d[key]
if value is None:
value = {}
for key in keys:
d[key] = value
d = value
return d
|
dias = int(input('Digite a quantidade de dias: '))
horas = int(input('Digite a quantidade de horas: '))
minutos = int(input('Digite a quantidade de minutos: '))
segundos = int(input('Digite a quantidade de segundos: '))
total = segundos + (minutos * 60) + ((horas * 60) * 60) + (((dias * 24) * 60) * 60)
print ('Isso equivale a %d segundos' %total)
|
# Each line gives the password policy and then the password. The password policy indicates the lowest and highest number of times a given letter must appear for the password to be valid. For example, 1-3 a means that the password must contain a at least 1 time and at most 3 times.
# How many passwords are valid according to their policies?
# Part 2
# Each policy actually describes two positions in the password, where 1 means the first character, 2 means the second character, and so on. (Be careful; Toboggan Corporate Policies have no concept of "index zero"!) Exactly one of these positions must contain the given letter. Other occurrences of the letter are irrelevant for the purposes of policy enforcement.
problemInput = ["2-5 z: zzztvz",
"2-8 d: pddzddkdvqgxndd",
"4-14 r: rrrjrrrrrrbrrccrr",
"2-7 r: zrgsnrr",
"9-10 z: zzzxwzznpd",
"8-13 g: gggggggxgggghggg",
"1-6 c: xcccxcccccz",
"3-4 b: bxbt",
"8-11 d: dddddddzddv",
"4-14 m: kxdmmmdmfwmmmdfr",
"16-17 g: ggggggggggggggggg",
"2-3 f: ddvdlff",
"9-11 g: ggggpfgggggg",
"7-8 c: fdhctccc",
"3-6 c: tmcdcncqcvccg",
"2-3 l: clllll",
"1-9 b: bbbbbbbbbb",
"10-15 w: wglmwwwrnnzgwhhwvvd",
"10-14 g: ggggggxsgggqggg",
"9-19 q: fjlqbvtdngwvtbnsgfm",
"1-2 k: kgbkkv",
"4-10 m: mmmmtmmmmgm",
"3-4 h: hplh",
"5-7 q: qqqqrqk",
"3-12 v: zbvlbpxcrnvvwjpwl",
"1-4 r: crrr",
"4-5 h: hhhrj",
"2-4 r: mhrr",
"9-10 c: pccccsccbk",
"10-16 n: drnhqnnnnqnnpxmh",
"5-6 v: vvvnvvg",
"11-12 c: ccccgcccccpc",
"5-10 b: bdbjbbfmfbb",
"9-13 w: zwbwwzhwwkwsxdfwglx",
"5-19 v: vvvvvqrvvfvgvvvvmvv",
"3-9 d: dddgztdljb",
"12-13 s: swssssrsssshx",
"5-6 l: dllkljq",
"4-5 q: qqqsdqq",
"2-4 w: tmwg",
"10-12 l: llllsldflllllljjlxl",
"3-11 s: sjtsssssksbs",
"1-5 v: hvvtmvgvv",
"3-12 g: ggvgkgfgggghgg",
"3-4 p: ccpp",
"3-9 v: vfvvvvvvvvvvvr",
"8-16 k: kkkkkkkkkkkkkwkkkk",
"8-9 x: wxbrxfdrw",
"7-9 n: nnnfnnnnn",
"7-11 w: wwwwxwwwwwzxw",
"6-9 n: nknnhnnnnlnnn",
"10-12 l: qllllllllqbl",
"17-19 p: pppppppppppppwppkpp",
"4-5 q: qqqqqq",
"7-15 v: vvvbmbjvjznzdhfvtn",
"3-12 w: wwwwwdwwwwwwtwwwww",
"7-10 x: mmgmknpvdbxdl",
"9-10 v: jljttxpvvv",
"11-15 d: dshddnddqdhddvm",
"1-3 r: vrqrrr",
"6-7 c: ltcbpccw",
"5-13 q: qqqqcqqqxqrqg",
"3-7 l: lhlmhzl",
"2-3 l: lxntjnttkllll",
"3-4 b: bbnsb",
"5-6 j: rjppzvjdjj",
"4-10 g: fgggjgvfggggggsggm",
"11-12 z: ztzzzkzzzzsvzzzzt",
"2-3 h: hcvbf",
"7-13 s: sswkwhsdqsdcs",
"3-10 j: mghjglnbdhjp",
"6-8 x: dfxrxxsxpsxxxxmc",
"11-12 f: fffmfcdpffmpflfffdw",
"4-7 n: nnnknncnn",
"2-6 k: tzqlzqhrncvktfwvswt",
"2-4 h: pqplh",
"8-13 h: zhlwqvmnkjhhtkf",
"2-3 l: llll",
"19-20 j: jjjjjjjjjjjjjjjjjrjj",
"3-14 n: crnnrgpmxxlrfljk",
"2-4 t: stpr",
"11-13 c: cctcccccccccccc",
"5-6 q: fqqqqqdwtwqjq",
"6-7 z: zzzzzzg",
"8-16 j: njjgsjjljktjcbjvjc",
"3-6 c: swjccc",
"5-7 h: ghvwjmzm",
"9-12 s: sssssmvtdckmfs",
"3-4 r: bsrm",
"6-7 c: ccctcccc",
"6-10 t: swndrtcvtl",
"13-19 v: vjvxvvvdvvvvvvdvblv",
"5-7 w: hnwwwtwp",
"8-9 k: kkkkkktzxkkv",
"4-6 g: xpsxgs",
"2-3 r: xrrdxm",
"2-9 f: ffvqxxvsf",
"7-10 t: tttttttttt",
"4-6 q: bbqqqqqqbq",
"7-9 q: xjcwqhprgh",
"3-6 j: jjjjjjjxjjj",
"1-3 l: blll",
"2-5 p: phbppp",
"3-4 p: phpb",
"2-15 r: mwgnrkxrrbmgpzrdrr",
"8-13 x: jsrlvxmxwglkh",
"4-11 b: ctcbsjgjplbthhrskfnb",
"6-7 q: qqqqqfvcq",
"10-11 d: ddddddjdbndddd",
"8-9 p: pppppppkf",
"10-14 q: qqqqqqnqzgqsqv",
"12-13 b: bbbbbbbbbbbbb",
"6-11 h: khnkthfhhdhrhh",
"5-6 g: gzggwcgq",
"2-4 f: fbfg",
"6-9 f: ffvfsfvffxff",
"6-7 t: tsfdltt",
"14-17 t: tttttttttttxtcttp",
"3-4 v: vwtv",
"7-10 x: pxmldqqxmw",
"1-2 s: pdssssssss",
"5-6 n: snwnml",
"3-8 t: tjnpjqzxbj",
"5-7 n: mxkqfnjb",
"4-12 q: qqqkqqqqqqqkqqq",
"4-5 d: pjhnsfdgddjsddvpxxd",
"14-15 t: trttdtxwtdmtttt",
"3-4 j: jjvz",
"1-2 p: xqpppp",
"11-15 d: dddpdddddddddddq",
"15-16 b: bnbbbbbbbbbtbbdbb",
"9-11 w: wwwnwwmwbghw",
"15-18 g: tjwqbgwmvpvghxgzkgj",
"3-4 j: jjps",
"9-12 f: ffflfffmfnffvff",
"1-3 g: gbgstndgggqrdbtpdqdr",
"4-6 f: fflxfqffff",
"10-14 t: ttttttttttttttttt",
"1-7 v: vvsqlvvvvkj",
"3-7 b: wvbxlwbjtbbbvh",
"3-7 p: hqvsvpn",
"2-6 f: fkwfhf",
"3-11 d: dzrwnffrdvs",
"8-9 s: sssdssztlssqksx",
"12-15 t: tttttttttthtttt",
"5-6 m: mmmmmmmm",
"2-3 n: dnnl",
"12-16 w: wrwwtvwwwwwwwwww",
"2-4 j: jjjjsj",
"7-11 x: xxxxxtcxxxlxxx",
"8-17 n: nbngnnnsnjnbhnntzwxt",
"5-6 b: tmbdgn",
"15-16 x: xqlpjxbbxnrbxxxxqmkf",
"1-3 c: ccclf",
"12-14 m: zhmmmzltwhrmfmx",
"15-17 c: ccvcxcmccgccccbcccc",
"10-13 k: mkgkljkkkjkkg",
"1-4 b: ckdr",
"10-12 b: bvfbgbbbbbbb",
"2-4 v: jfvcv",
"2-7 p: jswmqpmc",
"11-16 b: bbbncbpmbjbbvgrb",
"1-6 n: ktjcwr",
"2-9 l: lllrwljlnlwllln",
"17-18 h: hhhhhhhhhhhhhhhhzfh",
"9-14 b: bbbsbqbbjjbbkb",
"7-12 j: jjjjjwwjjjjcj",
"10-13 w: wfwwwwwwwjwww",
"2-6 j: bjghpj",
"13-16 z: zzzzzzzzbzzzzzvg",
"10-11 f: ffffkfffcfxff",
"3-4 m: mmmmkjvzmkp",
"2-5 k: kkkkk",
"5-6 r: rrbrrs",
"1-2 c: ccqjmc",
"13-14 r: rrrrrrrrrrrrztr",
"8-12 z: zrzzzzzqbzvdz",
"4-9 m: hlgmtvvqs",
"9-10 t: tthttrtbrnt",
"2-4 k: snpkzhck",
"12-13 x: wlxwwxxxhgxxx",
"11-16 h: ncmfhhvgghhhhhjhd",
"13-15 g: sgxgfntgjnxkgbgm",
"4-13 s: vqkslldmgmfrd",
"3-14 z: zzzzzzzzzzzzzzzz",
"14-15 c: ccccvccccccsmlpcfccx",
"4-5 p: pppppp",
"9-10 z: kgblzrqbzz",
"13-15 p: pppppptpmppbpppqpp",
"7-8 b: dntbbcmswb",
"16-17 d: dddddddddddddddgd",
"10-11 r: rrrsrmrrrqtr",
"2-3 q: qtqgz",
"6-8 c: xztzfkcch",
"14-15 l: lllflllllllllzsl",
"1-6 s: zssssss",
"5-8 d: hdddwddvdpd",
"10-12 j: jjjjjjjjjpjbj",
"1-9 q: tqqqqqqqqnqqwqk",
"2-4 t: shpwwttwqb",
"8-9 s: xrssssssz",
"3-4 c: cjcfc",
"3-10 v: rfvzsncmfv",
"4-7 t: lshczltjfqkmkt",
"13-16 x: xxxxxxxfxxxxzxxrxx",
"1-3 z: pzkzlzmzz",
"4-5 d: ddkbfdtdd",
"9-10 r: rrrrrrrrlfkj",
"3-7 s: svtbsssjsldts",
"10-13 c: ccccgxzqtctrc",
"1-7 q: zgwqgrx",
"6-8 f: ffnffrfg",
"4-5 f: kffcffp",
"1-2 m: ggcm",
"5-6 z: zzzdgz",
"9-14 j: jjjnjjjjjjjjjjjj",
"2-17 d: xttgzggnfhsrjqdbppps",
"5-6 f: xrcfff",
"1-3 z: wzzg",
"1-2 h: hhhvl",
"13-17 q: qqqqqqqqqqmqqqqqqq",
"2-3 q: bjqq",
"1-5 w: zwwwgww",
"5-7 s: jnvpmgj",
"9-10 q: zctgztwpqq",
"16-20 j: jkjjkjnjwqqjjjzgjjpk",
"16-20 k: kkkkkkkkkkkkkkkkkkkk",
"17-18 d: dddddddddddddddddbd",
"3-5 d: dngrhxb",
"10-12 t: tmttttttttrttwh",
"7-9 q: nqqqkqcqqqqq",
"7-9 z: zqzzzzwctng",
"10-13 d: dddjldsddkddjpddd",
"3-7 g: lgglgggggphx",
"6-7 b: llkbcdxwtzrblp",
"1-5 s: dssdscpzwcn",
"2-6 h: hhphhhhhh",
"4-13 z: smkzzpzjfzzbzqzxzjz",
"2-5 j: jjjjjj",
"8-11 p: lgmppspppppk",
"9-10 c: ccccccccdnkc",
"3-9 m: mmfmmmmpkmsmmm",
"13-15 m: mmmmkmmmmmmmgmhmmm",
"5-6 x: xxxxxxx",
"10-14 b: bbbjbqbbwcbbbb",
"3-12 f: ffmfffffffnzfffff",
"11-12 m: mmmnmmmmmmmmm",
"8-12 v: jptmbccvmvsxchfvv",
"4-5 s: ssssns",
"12-14 j: jjjjjjdjjjjvjhjjj",
"11-13 j: wjjjljjjcjjjjqjjp",
"1-7 g: ggggggggdg",
"2-3 v: bkjqv",
"4-13 q: qzhldwthbwgtr",
"12-13 p: ppplppdgpppppp",
"11-12 f: flffxfpffprgfff",
"8-14 b: mbbbbbtbwbhstbbbbbbb",
"6-7 m: bqmsmmm",
"1-3 w: qxlggmxtwj",
"3-17 c: dwbkjcwqcrccbcxcnvxc",
"11-13 p: ppxppppdppxpzpppp",
"4-10 v: vfvvfvzvqv",
"1-7 m: mmmxmmmmmbmmrmmmmmm",
"2-12 x: xrdxwxzwfxpxtqxxxgxp",
"6-11 w: swzwwkddmsrxwzfg",
"6-8 g: ggggggggggg",
"3-4 h: tzshs",
"7-8 t: zjtzpclm",
"5-6 k: brzkzk",
"14-15 c: cccccccccjccccc",
"2-3 h: hhfh",
"15-19 w: wwwwwwwkzxwwwwwwwwh",
"8-10 f: mjmwqnlnhf",
"3-8 l: ksllllplllc",
"1-3 q: gjmhq",
"2-9 l: lwklcxllf",
"5-7 p: ppcclscppgdxmg",
"3-6 z: fpxmpz",
"8-11 r: vrrrrrrrrrrrrrs",
"1-7 q: cqqqqqgq",
"13-14 t: tttztttttttttt",
"4-6 q: qzkqsqzmhhq",
"8-14 l: llllfllplllgzll",
"5-9 m: mmmtmmmmm",
"9-14 l: llllllllrllllltl",
"3-4 r: czrr",
"2-5 s: lssslssnmfqss",
"14-17 h: hhhhhhhhhhhhhhhhhh",
"3-4 x: xxxx",
"7-8 x: zdjbxxsl",
"10-13 n: ffrnphpzhnfxnncptmn",
"7-11 m: mmmmmmdmmmmmf",
"1-2 j: jjjjjjjjjtj",
"2-6 g: kglgsq",
"3-8 x: csvxxxxxztxdxpw",
"3-9 m: qbqwfmfpjmbnbcccgfgk",
"2-14 v: rmqhqlrvcjdhpw",
"8-9 p: pppppppvwpm",
"8-12 f: zvfjxbdgzjbplm",
"2-3 f: frff",
"7-9 f: htkxffclfr",
"4-7 v: cvqjctzvzvvv",
"6-7 f: fjffflj",
"1-4 b: tbnpb",
"8-10 t: tjpbtfzhtfsdjtlttttt",
"8-12 h: hhhhhhhhhhhrh",
"3-5 n: hxbwgjchklnplnb",
"1-2 z: jzvz",
"4-7 z: vzzzvcz",
"11-12 f: fffffvcfskcfcfftqf",
"2-5 p: cxktpckkqkgjpptvgp",
"9-16 b: bbbbbbbbkbbbbbbbbbbb",
"10-11 p: jcpnpppxpppb",
"7-9 n: sncnrzncnzdnngn",
"10-11 n: ttqrrkbspnn",
"11-19 c: ccczncccccsccpccccjc",
"1-2 h: hhhbwhhknzf",
"5-8 q: zxbtktkf",
"2-6 x: trxhzl",
"1-5 d: dskddkqdgqkhcz",
"7-12 c: ccccccccccccc",
"7-9 t: kskrrhtxtvsqzt",
"5-12 v: vvvjvwrdfscv",
"6-10 z: pzznznzczkwzzzmzz",
"15-18 t: tttttntttttttttttttt",
"4-6 m: bxmmmm",
"2-8 k: tkkhqwkkkpk",
"6-11 p: pppppgmpppppp",
"7-10 b: bkbcbbrrbr",
"6-11 c: cctccccbnbcvccc",
"2-5 t: ccpxgwzqktxwjf",
"4-11 s: sssssscsssssg",
"3-4 d: ndpk",
"3-4 z: gjzzzkbhzzs",
"8-9 t: ttttttttt",
"5-10 l: lllldmmlln",
"9-15 j: njzjgjjjjjjjprjjj",
"5-7 p: zppppppgkp",
"2-6 r: rvdrrrgdnrrrlrr",
"6-7 k: kkkkkkkk",
"3-4 x: nxxxmtmljgldjx",
"2-6 f: qfxxxftf",
"1-9 z: zzdlqgzwzzjw",
"6-8 n: rnjnstwm",
"4-6 w: vhfhwckw",
"3-7 k: kkpkkfpk",
"5-7 k: kkkfzkhkk",
"1-11 j: jjjtjjjjmjs",
"2-17 w: wlwdkkwmkwskpstxvrwr",
"5-11 g: kgpgjspqlwnx",
"2-6 l: lpllld",
"1-6 d: xwkvgvkdxlljpdqwmhs",
"5-6 z: llrzzsz",
"4-5 l: lllll",
"18-19 g: gggggggngggggggggggg",
"1-10 x: kkdxwkrtfh",
"3-4 t: ttrqzttbsrt",
"14-16 s: ssshsssssssssnsss",
"2-6 k: kjzkxkkhkp",
"2-10 b: bbbbbbbbbbbbbb",
"1-9 v: vvvvvvvvvvv",
"11-12 m: mqmmmmmmmmhsl",
"5-6 s: sssmsss",
"14-20 s: srssssssdsssskssksvs",
"1-3 r: rrrr",
"4-7 d: zddkdptdfdw",
"6-7 g: rggglggtgkgg",
"3-5 c: bcctcvpcprcccqccpcrc",
"8-9 r: rrrxzrrlmrd",
"12-17 c: hcctccccbqcctscsscv",
"15-16 d: dkddddjdddddsdhwdddj",
"13-14 b: blbbbbqbhbbbmz",
"2-10 p: hvxqpjqstv",
"1-4 p: plxp",
"3-6 z: zzdlzqjzzz",
"1-14 s: qsssssssslshswsjh",
"3-5 r: grrrnrrrsvrrrdrrrjrr",
"1-4 d: dfdjdxbpdddf",
"2-3 p: pppppp",
"16-18 c: cmcccjxfclcgmchswq",
"9-11 x: xxrxxxxxvxrxx",
"13-14 p: dpppppsppspftpppwp",
"15-19 h: hhhhhhhhhhhhhhhhhhhh",
"6-12 q: qqqxqqqqgqqpqqqqqqqv",
"10-12 g: gqgdgzhgghjgdd",
"2-6 p: pnppppp",
"3-14 l: lllllllllllllllll",
"12-19 h: hhdhhhhvxrfhcshhwxh",
"16-18 m: mmrmmmmlmmgmmmmmmmmm",
"8-11 t: tntmlpgfttv",
"8-11 f: mffffffffff",
"15-18 t: tftttttttjwtttjttjt",
"5-12 d: pzdrdqxzqzwgzwcgsv",
"4-9 d: cdwdmhksdzgd",
"9-17 l: mlsllmgdlhlgmfglr",
"1-5 r: rrcnr",
"3-4 c: ccccccc",
"1-2 g: cskvbgnlgnpfrh",
"5-10 n: tfnnvnnqbbn",
"1-15 g: fxpdggmtrqggdglh",
"3-4 t: ftttppdtdbxzqw",
"5-6 p: qpxsjt",
"8-14 r: bkltjzprkhrhmrg",
"1-11 f: gffkkmpflxlqfsf",
"1-4 d: vddknn",
"5-7 l: llllllvlllll",
"2-11 b: bbbbbbbbbbbbb",
"1-3 h: hhhh",
"13-14 q: jqqqcckhdqkqqj",
"4-14 p: mfwcbqxpdkhtdfj",
"3-4 g: ggggg",
"6-14 v: vvvvvvvvvvvvvvv",
"16-18 v: vvvvvvvsvvvsvvvvvv",
"9-13 l: llllllllllllllllllll",
"3-4 r: zjrr",
"6-8 x: xxxxxxxxx",
"2-6 p: zlgpps",
"3-8 t: ttjtbttjt",
"18-19 k: kkkkkkkkkkkklkkkkkk",
"8-13 q: hcvnkpnqfzqmqscwf",
"15-16 p: ppppppppppppdpmr",
"7-12 c: cqccccdcccwsccc",
"8-12 d: ddhddddgdddgdddd",
"3-4 x: xxxx",
"6-8 w: wwwrlzcbwhwlqwwwv",
"1-5 h: hhhhdwhhlhph",
"4-5 f: fffvz",
"3-8 c: ccqqcccc",
"3-5 k: xkwkdkh",
"2-3 s: ssssshhsss",
"4-6 x: gxxxcx",
"8-12 l: vsnlqbjltbtlphjtf",
"3-6 n: tgpnqxnntkmntvl",
"9-12 f: cjzkldhmvclk",
"4-7 b: zgpdznb",
"1-12 s: ssssnrssssscnssssq",
"14-16 p: pppppppppppppwpjp",
"4-14 b: xpbbvcbbbspgbbqbw",
"5-6 s: smssrb",
"5-16 b: tzbdqxgkbxbvzwvt",
"2-14 f: vzplvvftrcdmgs",
"13-15 t: tttttkthhtzttdt",
"2-3 s: vpwss",
"9-14 s: sssssssfssssss",
"7-13 s: tsnwzxwzjzsjkchlg",
"12-15 q: qlqbbfqqvqmcqhvq",
"12-13 g: gggggggggggggggggg",
"1-3 g: jjdqzgwgggggg",
"5-6 n: nlnxnnnwv",
"15-16 m: mmmmmmmmmmmmmmmjmmm",
"2-6 m: vmrqrmz",
"4-5 n: nvnnwb",
"13-15 x: xgblxvxmpskqwvlx",
"6-7 v: vvvvvvvv",
"8-10 r: fsrrdprbrfxhrdv",
"4-5 j: jsjjf",
"4-6 k: kkkjkkk",
"5-9 j: cflfvjjtjljjhbhnj",
"9-11 t: xswktxtqrbm",
"4-16 r: drrrrrrrrrrrrfwnr",
"13-18 p: bbkplmplqmppppspmp",
"9-15 r: kgnwvxmcrmltpcgwvrb",
"4-5 c: jcwcccnc",
"2-4 f: ffff",
"8-12 d: rvsdddvdtdcd",
"3-10 v: qvdzjhcvsz",
"10-11 x: qcmvlvgxkxx",
"6-9 s: sxsspsksjssfsnssrvs",
"3-7 x: zbxxxxxwrpxgr",
"9-17 j: hrppktjsqhzqwxhdz",
"5-7 z: nzzzvzswz",
"6-7 p: ppppsbpp",
"10-13 f: fffffffffhffmfcxffpf",
"9-12 f: ffffffffsffmf",
"14-15 r: rrrrrrmrrrrmrrzr",
"3-6 w: whwwwwwwwwwwm",
"7-8 b: btqbbbbbbbz",
"13-16 z: zznbbdmbzhjzzzzzmngd",
"6-7 q: fqmqltdqqqdwqss",
"3-4 h: hphhhhh",
"1-3 r: rdgktrmrmdztrkmn",
"17-18 w: wwslwwsmwswwfxwwwww",
"6-8 p: ppprpppp",
"8-10 z: zzzzzdzrztzzzz",
"8-11 m: tmldmmwxmjmrmtrmm",
"12-16 s: phpprsdvkmsssmssnqwm",
"3-4 h: qplnhkhh",
"14-19 w: wvxvqzqzdnjjwwtdbwc",
"2-4 p: fpnp",
"3-5 c: ccccpcccccccc",
"3-12 g: ggwggbgfggrxggg",
"4-8 r: rrszrgdbrw",
"2-4 n: vnmgjtps",
"8-10 j: mjjjxjjgjc",
"2-6 m: vmmhmm",
"3-4 w: vwww",
"10-18 v: mvnbqbvcpkvnhqvvbvzv",
"15-19 g: ggtggggggbggggxggglg",
"7-13 m: mmmmmmjmmmmmmm",
"5-11 d: ddxhdndtfdddndxzdqk",
"3-11 f: ffnfbfffffgrff",
"7-14 w: fflfpgklzlxfwwt",
"15-17 d: zxllzgbjrrddnmdhdwp",
"1-5 n: nnnnknnn",
"15-16 j: ffkjjljgndljjnjscs",
"2-3 v: nvvxvntqcrqq",
"5-6 c: rcccgpcc",
"2-3 j: qjjfrhwljgczj",
"5-8 k: kkkkkkkkkk",
"1-2 r: rrrrxrcrrr",
"1-15 t: ltttttttttttttttt",
"4-13 q: prlqzqvgpqslqqcqqjq",
"3-12 q: gfbpbdrwrbqt",
"2-5 q: qsxccx",
"4-9 t: slglllcdkjzdmxt",
"2-3 r: rlvrrr",
"2-13 w: wwmkwwwjcwbcwzwwcg",
"3-4 t: ndkvx",
"6-13 b: qflzbbbcfzkbmtx",
"6-10 j: pdckwfhkjxqljnjjw",
"1-5 j: jjjjjqmj",
"2-10 x: xlxxxxxxxfxx",
"1-5 r: rvcnr",
"4-10 c: cnchrcsgcvncpq",
"3-5 j: fjxbj",
"4-11 c: ccdlcsxckcx",
"12-16 m: mmmmlmvmpcmnmmdbmms",
"3-4 q: qqwlqqqq",
"2-6 f: kvcfdv",
"8-10 m: mmmmmmmmmm",
"7-8 j: jjjjjjjj",
"5-7 c: ccccncsjc",
"7-9 f: fffffrpfplhzfff",
"1-6 c: sbcccscccccccccccc",
"5-7 j: njpjqxjrljnqjwjgchtj",
"11-18 b: gktmxhjwbmbpjrbqkb",
"1-4 f: lffbfffffw",
"5-6 c: ccccsc",
"10-14 v: mkbxvxvgvvvvbv",
"5-6 x: jxxxxxx",
"4-6 c: qccmhcccw",
"3-7 s: qwmtwprsxd",
"10-19 d: rkdwbrndmxdsknddddl",
"2-5 p: pppppppppppp",
"6-7 w: wwffxwc",
"2-7 z: pkzcnxr",
"5-10 b: bbqbkbtdbbbbb",
"10-13 j: qmqgvhzkjmfjhjjm",
"5-6 n: nnnnrn",
"7-14 n: qgmlsvnjnrdzcdbstxv",
"9-16 q: qpllvqpmqlqvkhwqqrsm",
"2-4 s: sqpnqsgsssq",
"13-15 z: zzzzmzzzzzzzzzzzzg",
"10-15 b: bbbdbmqbkjbbtbd",
"2-5 h: qrhhhhp",
"11-12 x: xxcxhmxxxxxx",
"13-18 c: ccccccccccccdccccccc",
"12-13 h: knktllrdtgjhhhxpd",
"9-13 g: tdpfvzcqgbslgnbxkgpq",
"8-15 g: gggggggsggggggxggggg",
"1-3 v: wvfvvdvvvvv",
"10-11 b: bbbbbbbbbhzb",
"15-17 b: bbbbbbbbbbbbbbpttv",
"1-7 m: bmmmmmdm",
"2-3 h: rhksbfgh",
"6-7 w: wwwwwgf",
"3-12 h: hkhzhhhhhhhlhhmh",
"3-5 x: xxcxpx",
"7-9 m: mmdmtmjdxmm",
"1-4 n: lnnlnnnnn",
"4-9 k: kkkmkkkkbk",
"3-4 t: tttt",
"5-12 k: tkgwkrwwzcwkhkmk",
"4-5 f: fhfvfgwfff",
"3-5 h: fmbgjrxgh",
"5-6 j: xtwnjj",
"11-15 r: rrrrrrrrprqrrrfrr",
"13-14 f: fdffffflfffvfff",
"1-6 b: krsbnd",
"6-7 b: bbbbvxqbl",
"1-2 v: vvcvvvv",
"7-9 t: ctfcmttht",
"2-7 v: bcxhtdwbfqvv",
"14-15 n: nnsnlnvkqztnxnn",
"2-6 g: rknndvrhbg",
"2-6 z: mzzzdzzzz",
"11-14 q: qqqqqqvrqqzlqkqqq",
"3-4 t: ttcrttjtknjpvwhzm",
"8-10 j: jjjjjjjjjjjj",
"2-7 c: ccnhcccc",
"3-14 m: mmmmmmmmmmmmzmm",
"10-16 w: swsmwwwwwrnwmwwk",
"4-5 m: bmdjm",
"6-11 l: cmlllxllllkrllf",
"14-18 t: tttttttttttttvtltt",
"11-13 f: ffffffffffhfzfff",
"3-6 g: wkzxtrkgr",
"7-10 c: cccpcccccvccc",
"3-13 m: mmbmmzbcmlwmmfnmmq",
"2-3 p: pdszp",
"13-14 r: rqrrfrdrrrwvrrrrrwrr",
"9-11 g: gggwggggfcpg",
"3-9 p: pnppppdpppp",
"17-19 k: gzkktkxkkskkkmkkkpk",
"4-11 x: bmqhtxzqmvx",
"11-14 v: cvsvssqghzjqxm",
"1-14 z: zwxczzszzdmkztl",
"8-9 t: jkpptwctt",
"3-8 z: vqmzzpjj",
"6-10 s: msdrxssssswssjz",
"1-7 z: zhpzzzz",
"13-17 m: mmmmmmmmmlmmgmmmgm",
"9-10 n: qgtcnnnnnkcnnn",
"2-4 v: vrcvv",
"4-5 h: hhhdwh",
"8-9 c: zcccccccc",
"13-14 p: pjxcpmdpppmgwt",
"2-6 c: gskmcc",
"6-7 q: qqqqqqqq",
"3-13 b: gfbxqtnxnqxbb",
"8-10 l: lhrlqlrqlsllll",
"5-8 z: jlzgzzzq",
"10-13 z: zzzzzzzpzkzzgz",
"6-7 d: wddnddd",
"10-11 h: vbhhbhhhhbz",
"7-10 s: sxssksskqs",
"1-12 b: vdgxvsxpgbbpd",
"5-6 n: npnvckn",
"3-4 v: vvjvv",
"9-15 r: njhhqlmcmncjrpx",
"2-8 h: bghrdhhrjbhhhbjz",
"5-7 q: qqqqlflrq",
"9-12 f: qfhfffffffffffff",
"2-3 m: mmmblxmbpz",
"13-16 v: vvvvvvvqvvvvlvvw",
"6-12 b: wbfgbghzbmvf",
"12-15 r: rbrrrrthrrrrrrrr",
"4-8 k: pkprqkkkpsphwnhp",
"8-9 h: hhhhhhhsl",
"1-3 b: bsbn",
"15-16 j: ktjjjxjfjjrjjcjk",
"4-8 z: smzzmzzszzr",
"3-4 m: qmmmzqzlrpt",
"11-12 n: nnnnngnnnnwgnnnn",
"5-10 x: slpbxqfxxxx",
"12-19 q: qqqqgqqqsqqqqqqqsqqq",
"4-10 s: ssstssssss",
"6-11 g: gggggvggggzggggggg",
"12-14 c: cckccccdccxnngccc",
"3-5 j: jnrjvj",
"2-6 t: vtdtms",
"13-15 p: ppppppppppppjpq",
"1-9 j: jjjjjjjjjjj",
"8-9 d: wfdddddkddxd",
"3-7 p: pwpcpvp",
"3-4 h: hhzl",
"9-10 n: lnkjxnsbnn",
"7-11 z: zzzzfznzbzbzbzd",
"1-2 m: mmzlmkm",
"6-7 t: jbmpztx",
"5-6 v: vvbvvtn",
"7-17 q: lvdfpbqxbxdnwqzjlfs",
"3-5 z: zdzzzxczbzzz",
"10-14 f: fpffffffffffff",
"3-8 x: wxxchxjx",
"1-6 x: xxxxxx",
"14-15 x: zmxtcbjxtvxxxxg",
"4-5 f: qfffghf",
"2-3 p: pppp",
"10-12 n: nnngnxnnnhnsbntln",
"1-2 w: ftwwww",
"10-11 f: fffffffffpkf",
"4-5 n: nnnnnn",
"10-11 r: rrrrtrrlrrrr",
"5-6 h: hjhxhhnbhlbxvhs",
"1-4 q: qqqq",
"7-11 p: dkpfppwzpxqqx",
"11-17 l: lzknllnllkgvllllh",
"1-3 z: zzzzz",
"16-17 b: bbbbbbbbbbbbbbbbbb",
"2-4 n: qcpwnhn",
"1-4 v: svvhvvv",
"10-12 l: llllllllllljl",
"1-2 l: xzlllllll",
"1-3 l: plklll",
"4-8 x: xxxxfxbxcxxqxfxpx",
"3-8 b: xgbbwncxclbv",
"5-6 m: mmmmmmm",
"4-5 p: pptppfnpl",
"14-16 x: gwjfkzwrldzxpdxgk",
"10-11 z: zzzzvzzzzzzz",
"3-12 k: kkxkblkkkkkgkkkmkk",
"4-6 p: pppfpx",
"2-7 r: rrmrrrrrrrrrr",
"7-9 p: pbpfpppppp",
"2-3 v: tvvbbjnvv",
"5-8 j: jjjjjjjjj",
"2-5 c: xcwcczjkvgccccvpkd",
"5-7 f: ffffpfqfffff",
"11-13 m: qmmmmmmmlwkmmmmmm",
"14-15 d: dddddddpmddddszdd",
"6-15 b: kptphpbxxqsbxlhxplml",
"16-18 x: xxkzfxgqxdcvzdxlzn",
"10-12 m: clrmmmmksmmm",
"1-3 w: wwpww",
"8-15 g: ggggggnlgggggggggng",
"3-6 h: tnhhxh",
"4-5 l: lllrdllxlnllqll",
"1-2 m: lmjhvl",
"1-4 k: dkkhkkk",
"6-7 x: wncxcxf",
"4-5 w: wwwhfww",
"4-8 b: bshnbbdbmfxbbrc",
"4-7 t: tbdtztm",
"7-8 n: zntlhccn",
"10-14 f: frgffffffflfzlf",
"3-4 b: nzbbbnfbdg",
"2-6 m: srmwsmtp",
"5-6 z: zzpvsrz",
"2-13 m: msmmmhmmmmmmtm",
"3-4 c: ccvcc",
"1-4 n: nnnnnn",
"2-3 j: zdvsj",
"4-6 c: ccctccc",
"4-5 z: zzpdztnrzl",
"4-6 z: hzdzpz",
"2-6 x: gxjxcxxjqcb",
"4-9 j: jjjvjcgzl",
"5-8 z: dmppvjqfzzzzn",
"5-7 v: vvvvvvr",
"2-5 l: lvkkft",
"2-11 n: nnhnqnnvnsn",
"1-3 d: dhndddjfd",
"8-9 x: xxxxxxxxxxxxxxxxxxxx",
"4-9 p: fntpgcwtwv",
"4-12 q: qbrlqzqcnwtjq",
"2-3 f: ftcjvnfkzx",
"1-2 d: dddd",
"7-10 g: gggggghggzgg",
"4-6 g: zhgbgphggtm",
"2-4 l: lblq",
"14-17 n: bnnngnnnnnnznnnnn",
"5-6 f: fxxffffhmswq",
"6-10 p: pppppppppp",
"2-4 q: lsxgqkqsblqqq",
"11-19 x: xxnrgxxxxxxxxxfwmxx",
"4-7 j: jjjtjjljjjjjjj",
"6-7 l: llllllll",
"1-4 f: pfftffffnffff",
"11-13 r: xrrlrrrrrqrrzrr",
"1-3 p: pvpqp",
"9-13 d: ddddxrnddddfdscsd",
"1-2 f: lbbr",
"3-7 t: mpttsgwb",
"2-10 c: jccchctshcpchwx",
"2-4 p: lmpd",
"1-2 n: zlnxnnf",
"2-3 w: fwwtqw",
"9-16 s: sssssssssssssssssssj",
"1-5 s: hssrm",
"15-17 b: ghpvwjbzpksvhsjbj",
"8-9 h: hzrvxhhdz",
"3-4 j: mkjjpvkfhprr",
"1-8 n: cnnnnnnmnn",
"1-4 x: lxxxx",
"3-5 m: pjttcvvcmfvzffcfmmv",
"3-10 r: rsxtvwjrfrqrrbzzr",
"2-7 h: hhckhhr",
"7-8 r: srrrmprrrhkzsndrrkr",
"4-13 m: pdsmlsnxcmhmmsvc",
"3-12 d: ddsdddddddddddddd",
"14-16 s: sssssssssssssjsds",
"3-4 m: djfp",
"2-5 w: bgwpc",
"4-5 r: zffrrqrs",
"4-9 r: rrrgrrrrqrrrrrrr",
"4-6 w: wxwwvw",
"7-8 d: tvddddwtdddldd",
"6-7 g: tgdggggfzrgqggggmggg",
"2-6 t: tgtfdtttttttttqxd",
"14-18 f: fffsffgfffffskfkff",
"1-12 b: qbvbbbbmbsqbcbgbbbcp",
"5-7 d: ddbqhdddsdm",
"6-9 n: tqwnckjsn",
"1-3 n: nnnn",
"5-10 w: wwwwwwwlwwqwwwp",
"3-4 r: rrrr",
"2-12 m: mmchtqmhfdpm",
"6-9 d: dzgzdbddwgdwldb",
"10-14 k: kkkkkkkkkkkkkzkkkkk",
"13-14 v: vvvvvvvvvvvvvvvv",
"2-12 f: btqtbrvkmfzhz",
"1-5 b: bbbbbb",
"7-10 j: jhjnjjwnjbj",
"2-16 h: kjszvtwrjgrvzrqlzcb",
"6-8 t: nxzftvtnrtxg",
"3-6 h: cvhhnhnhhcgst",
"5-8 f: fxgfjnjzz",
"11-12 b: bbbbbnbbbzbqbbbq",
"1-6 h: hjzhhw",
"18-19 m: xrvmftmpkpmrlkqmxvm",
"6-7 v: cvxbdsr",
"5-6 v: vjvvvvf",
"2-3 m: mmzpm",
"3-4 k: mkghkxc",
"1-6 s: sjsmjsstsss",
"2-10 s: wndvkxbmffh",
"9-15 q: qqqqqqqqqqqqqqqqq",
"4-5 f: rffffpc",
"10-11 v: vvvvvvrvvlmv",
"6-7 n: tnnnnlq",
"16-18 g: gggggdgdgggggggggggg",
"5-11 l: lwlfvzlsjll",
"11-14 v: vvvvvvvrvwvvvv",
"12-16 j: jjjjjjjjjjjpjjjx",
"4-6 w: wwwwwr",
"2-4 d: ncdd",
"15-17 c: nccccctccwccccqcqcc",
"3-5 m: mnlmqtsvn",
"7-8 w: swwwwwnl",
"6-12 l: zlplklqldllxlpvb",
"7-9 h: fhkhqnfhhzrhqhhh",
"11-14 v: vvvvvvvvvvvvvv",
"16-18 v: vnvvsllmvswcvzqvvxjl",
"7-9 k: kkkzkkkkskkkzkkkjlk",
"5-17 w: wckwxwlrlwrncxwwb",
"2-4 v: vqvvqgx",
"2-3 b: bbbbbbmbbbbqb",
"4-5 p: ptphbprpv",
"3-6 q: kqqkpqbnt",
"15-20 n: nnnnnnngnnnnnnnnnnnw",
"10-12 p: pppppxpppmpnjp",
"5-10 x: bhwlxkrdxxqvkphvmfgn",
"2-3 l: lllhql",
"4-11 l: wllvwfccllk",
"7-11 d: dmvmmzlngpw",
"2-6 v: rskbvv",
"7-9 k: kwtckkkkx",
"11-12 j: jnjjfzjjjjjjjj",
"2-5 v: rvvnnjjxjnnt",
"2-6 j: ljcqpjmhgmmcxjkgd",
"1-3 k: lklbx",
"14-15 c: ccccccccccccckc",
"2-6 x: xxxxxxxxxxxx",
"1-7 t: btrtxtjgtt",
"2-3 t: sttt",
"5-7 k: kkkkzksxgb",
"3-4 q: mnnxqwtnw",
"8-10 t: vwzmnxjdzx",
"4-10 f: svglffffpzw",
"1-5 s: dsfjsv",
"8-10 m: vmwpmmmjmv",
"6-7 h: hhhhhwxhhhhhhhhhhhhh",
"7-19 n: ktlblznjctnnrzwrknt",
"3-6 n: nzxclnvc",
"2-5 t: wtrttkx",
"9-10 j: jjjjjjxjjj",
"12-13 r: rrrrrjrrrrrwx",
"11-16 c: plvcnjcpnkvcpcmcpbc",
"2-3 c: gccclcslqdmsg",
"10-13 d: dddddddddhddd",
"8-9 w: kklwmwqmwwtwqw",
"2-5 q: qsqqwx",
"3-4 c: hcqvfbccccctcc",
"6-7 k: kkkwqgv",
"13-15 h: qhhmhkjvhhhhngnhhhhs",
"4-5 d: msjdd",
"6-7 g: ggggggg",
"5-8 r: cqrdrfxnrrjrsr",
"9-15 r: lprrqrrrrrrrrrrbr",
"6-7 h: hhrqhrlhhh",
"2-3 g: glgg",
"1-11 n: nnnnnnnnlnnjzwnnnn",
"3-6 l: bwllrl",
"2-6 p: nptphqv",
"3-8 l: lrlknvlpcm",
"2-8 g: wjbgpjrlfsgg",
"5-6 w: swwfww",
"1-8 p: pptpxppppppwpppfx",
"3-4 d: wlddg",
"15-17 c: sccccccgccccccccc",
"4-6 n: nnnhnp",
"8-9 r: prvrxmprlzxs",
"9-12 t: ttttttttttttkrtt",
"5-6 h: hhhhkfh",
"1-10 q: psqpzpkqtcq",
"4-7 f: ffflnfzkf",
"10-11 j: jjjvjjxfjjj",
"4-11 p: wlhgrxlclnt",
"1-14 t: wfntvttxmldhqg",
"14-19 c: ccpczqrccfhtcvljlvc",
"11-12 w: wwwwwwwwwwwww",
"2-8 z: lzsdqxzz",
"17-18 p: pppppppppppqphppprpp",
"2-4 j: wjjq",
"4-6 f: ffkfffgff",
"8-20 x: phxxxxxnwxxdqzxxxxxx",
"9-10 d: xvddddsldd",
"3-10 l: rglllxlnfl",
"6-15 d: ddddddgddpddddwd",
"6-7 w: kwwwwhs",
"8-10 r: rrrfmrrrrd",
"2-11 x: xcjcgtkzkhtmrxqjxxx",
"4-5 v: wvmdr",
"7-8 d: dddddddd",
"7-13 l: lllllldlxllln",
"13-14 z: zzdrzzzffzzzzzznzz",
"3-4 j: zjjj",
"8-9 s: sssssssbss",
"6-15 f: pfsfvfxqpffqfqf",
"9-11 p: pjpppprzpcphvppwp",
"3-4 c: ccrd",
"9-10 c: qcwbccccjhwvtwcccnc",
"3-4 x: xgxx",
"5-6 x: xgxzxxxxxxx",
"5-10 l: kxdgnqrkpqgcmcmnk",
"4-7 v: vvvpvvvv",
"1-4 n: nqnnnnnn",
"5-6 p: pprgpst",
"14-20 q: wlxrjczhxwdctvpcgxqc",
"5-8 g: gcggbggggggzgg",
"10-11 g: ggggtggggggg",
"14-18 h: hhchhhmhhbwhhlhsvrh",
"3-6 f: ffmfffffffff",
"1-12 n: rnnnnjwnnnnv",
"7-12 l: bpxlhthjplljwxvvvjm",
"4-5 j: jhjjjjj",
"9-12 q: qvqqqqqvqsqq",
"3-4 d: ddnvdddddgddd",
"1-7 h: xhhhhhkh",
"1-4 f: fffff",
"3-4 q: qfrq",
"5-8 k: kkkkgkkqkk",
"14-18 k: nkkkkkkfkkwkkkkkqk",
"1-4 q: qqdc",
"17-18 f: ffffffffhffffffffff",
"16-17 b: bbbbbbbbbbbbbbbdm",
"17-18 z: zzzzzzzzzznzzzvzmwzz",
"3-4 g: tggd",
"4-6 t: mlttlqqz",
"11-18 f: fgffgwlffffftfzfrt",
"7-9 h: hmmhhhpljjn",
"16-17 m: mmrsnmmzfhtmrjwmmjm",
"2-3 l: cllcbm",
"3-4 k: fkkkqbpbmmcd",
"9-10 f: kfmchwkwzfh",
"5-6 j: jjmjjjjjj",
"3-5 v: vsvbfvvh",
"3-4 k: tgkk",
"2-8 k: lscvjjnhpxl",
"7-8 v: vvlvvfkqqv",
"8-9 q: qcqqtqqhqvqqtq",
"12-14 z: zzzhzwzzqzzzzwzzlz",
"5-8 k: kzknkkkkkp",
"5-6 s: spsssw",
"2-3 k: kmkh",
"9-10 f: vnlxmstqbsg",
"1-2 k: kkkk",
"6-15 r: rcrrrsrrrrrrrrzrrqrr",
"3-8 c: cfczjwkcxbc",
"15-16 k: kkkkgkkkkkkkkkkh",
"5-18 c: ccdcxtccccccpcfccv",
"6-11 w: qdwnfhzlwwwwxwwgwhwk",
"1-6 d: fddddddhddw",
"7-10 p: wpbppvpzwc",
"12-14 k: kkkkkkkkkkhhkslsk",
"4-7 r: hdrrfhrqrdmcbnlrrjbr",
"7-10 b: bbbbbjbbbbbb",
"4-7 p: pzppzppsp",
"11-12 h: qhhhhhhqhrlwlhhthh",
"6-9 s: sbssxsskswvp",
"17-18 b: bbmpbbhhbnsbbbbbbb",
"8-9 g: wgggktggg",
"1-12 s: vsssssfssssrqk",
"2-5 s: bsgssxc",
"3-4 c: ccccccc",
"2-3 d: dddd",
"5-7 r: ldlcjrrlrngr",
"5-10 m: msmjqmmmmm",
"3-7 c: ccccccccc",
"13-14 p: pppxpppppppppcpppp",
"2-3 r: jrfrvrk",
"11-12 g: gggggggggggg",
"6-18 t: ctvqgcrgnxdvbzjfrrbt",
"6-11 f: rnjptfnwgxfp",
"5-8 w: wwwtwwwwww",
"14-15 r: rkrbrvrrrgrczrz",
"12-13 t: trtjtttlnxnxx",
"5-8 l: qnwllfsl",
"2-15 g: xgtcjftlqqfwkggpf",
"11-16 j: jjjjjjjjjljjjjjjj",
"8-9 b: bbzbkbbvgcbb",
"5-6 r: dvkxrrsvrrksszsdr",
"12-13 j: jjjjjjjjjjjhdjjj",
"16-17 z: mzzzrxfzzzzczzgzz",
"2-15 p: lpjxcdzjmnghfppr",
"9-15 s: ssssssssnsssssss",
"1-11 t: tfvtqvlbtld",
"4-5 k: kkkczkkkvkkk",
"2-7 p: ptphppvppppp"]
def ParsePasswordAndPolicy(line: str):
password = line[line.find(':') + 2:len(line)]
character = line[line.find(':') - 1]
minNum = int(line[:line.find('-')])
maxNum = int(line[line.find('-') + 1:line.find(' ')])
return {
"password": password,
"character": character,
"min": minNum,
"max": maxNum}
def VerifyPasswordSecondPolicy(passworddata):
parsedData = ParsePasswordAndPolicy(passworddata)
pword = parsedData["password"]
firstIndex = pword[parsedData["min"] - 1] == parsedData["character"]
secondIndex = pword[parsedData["max"] - 1] == parsedData["character"]
return firstIndex != secondIndex
def VerifyPasswordFirstPolicy(passworddata):
parsedData = ParsePasswordAndPolicy(passworddata)
characterCount = 0
for character in parsedData["password"]:
if (character == parsedData["character"]):
characterCount += 1
return(characterCount >= parsedData["min"] and characterCount <= parsedData["max"])
def CheckPasswordsPartTwo(input):
validPasswords = 0
for line in input:
if (VerifyPasswordFirstPolicy(line)):
validPasswords += 1
return validPasswords
def CheckPasswordsPartOne(input):
validPasswords = 0
for line in input:
if (VerifyPasswordSecondPolicy(line)):
validPasswords += 1
return validPasswords
print(CheckPasswordsPartOne(problemInput))
print(CheckPasswordsPartTwo(problemInput)) |
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
result = [[0 for _ in range(len(word2)+1)] for _ in range(len(word1) + 1)]
# update top row
for j in range(1,len(word2)+1):
result[0][j] = 1+ result[0][j-1]
# update first column
for i in range(1,len(word1) +1):
result[i][0] = 1 + result[i-1][0]
for i in range(1,len(word1) +1):
for j in range(1,len(word2)+1):
if word1[i-1] == word2[j-1]:
result[i][j] = result[i-1][j-1]
else:
result[i][j] = 1 + min(result[i-1][j-1], result[i][j-1], result[i-1][j])
return result[len(word1)][len(word2)]
word1 = "intention"
word2 = "execution"
ob = Solution()
print(ob.minDistance(word2, word1)) |
n = int(input()) # 1
k = int(input()) # 2
x = int(input()) # 3
y = int(input()) # 4
arr = list(map(int, input().split())) # 5
# s = sum(arr[:k+1])
w = 50
if k != 1:
for i in range(n):
arr[i] = sum(arr[i:i+k])
arr = arr[:-1]
# print(arr, len(arr))
for i in arr:
# print(i)
if i in range(x, y + 1): w = w
elif i < x: w -= 1
elif i > y: w += 1
print(w-50) |
print('Calcularemos a seguir a sequencia de Fibonacci') #soma o último e penúltimos termos para criar o prox.
n = int(input('Quantos termos quer ver?'))
T1 = 0 #por padrão começa com 0 e 1!
T2 = 1
print('{} - {}'.format(T1, T2), end='')
cont = 3 #começa no 3 pq o 1º e 2º termo já foram mostrados
while cont <= n:
T3 = T1 + T2 #essa substituição fará que a contagem caminhe, sendo possível fazer o T2 e T3 mudarem
#conforme a quantia de termos.
print(' - {}'.format(T3), end='') #só vai o T3 pq os dois primeiros já estão fixos
T1 = T2
T2 = T3
cont = cont + 1 # se faz isso para que cada termo seja adicionado, se n o while não poderá fazer a contagem se
# segue sendo menor que o 'n'
print(' - Fim')
|
# This is a file which does actually have a variable called 'answers'.
# This file is used in the test_check.py file which tests the check module
answers = 1
|
#1.Introduce boolean type
sunny = True #注意首字母大写
print(1, type(sunny), sunny)
#2.Compare I
number1 = 3
number2 = 5
print(2, number1 < number2) #'number1 < number2' 是一个布尔表达式
#3.Compare II
number1 = 3
number2 = 3
print(3, number1 >= number2)
#4.Compare III
number = 30
boolean = number == 30 #区别'='和'=='
print(4, boolean)
#5.Compare IV
number = 30
boolean = number != 30 #'!='不等于
print(5, boolean)
#6.String compare
pw = "123456"
boolean = pw == "password"
print(6, boolean)
#7.Logical operator -- not
boolean = 3.14159265359 == 3
opposite = not boolean
print(7, opposite)
#8.Logical operator -- and
boolean1 = True
boolean2 = False
print(8, boolean1 and not boolean2) #not 优先级大于 and
#9.Logical operator -- or
boolean1 = False
boolean2 = True
print(9, boolean1 or boolean2)
#10.Mix
rainy = False
sunny = not rainy
print(10.1, rainy and sunny)
print(10.2, len("password") >= 8) |
#encoding:utf-8
subreddit = 'MoviePosterPorn'
t_channel = '@MoviePosterTG'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
#
# PySNMP MIB module Juniper-ATM-1483-Profile-CONF (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-ATM-1483-Profile-CONF
# Produced by pysmi-0.3.4 at Wed May 1 14:01:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection")
juniProfileAgents, = mibBuilder.importSymbols("Juniper-Agents", "juniProfileAgents")
AgentCapabilities, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "AgentCapabilities", "NotificationGroup", "ModuleCompliance")
Bits, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, ModuleIdentity, Counter32, Counter64, NotificationType, ObjectIdentity, IpAddress, MibIdentifier, Unsigned32, Integer32, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "ModuleIdentity", "Counter32", "Counter64", "NotificationType", "ObjectIdentity", "IpAddress", "MibIdentifier", "Unsigned32", "Integer32", "TimeTicks")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
juniAtm1483ProfileAgent = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 5, 2, 34, 6))
juniAtm1483ProfileAgent.setRevisions(('2004-07-26 19:54', '2004-11-02 21:07', '2004-11-02 21:07',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: juniAtm1483ProfileAgent.setRevisionsDescriptions(('Added Encapsulation Type Lockout objects.', 'Added ifALias support to profile entries.', 'The initial release of this management information module. Added support for OAM admin status and loopback frequency.',))
if mibBuilder.loadTexts: juniAtm1483ProfileAgent.setLastUpdated('200407261954Z')
if mibBuilder.loadTexts: juniAtm1483ProfileAgent.setOrganization('Juniper Networks, Inc.')
if mibBuilder.loadTexts: juniAtm1483ProfileAgent.setContactInfo(' Juniper Networks, Inc. Postal: 10 Technology Park Drive Westford, MA 01886-3146 USA Tel: +1 978 589 5800 E-mail: mib@Juniper.net')
if mibBuilder.loadTexts: juniAtm1483ProfileAgent.setDescription('The agent capabilities definitions for the ATM 1483 Profile component of the SNMP agent in the Juniper E-series family of products.')
juniAtm1483ProfileAgentV1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 34, 6, 1))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniAtm1483ProfileAgentV1 = juniAtm1483ProfileAgentV1.setProductRelease('Version 1 of the ATM 1483 Profile component of the JUNOSe SNMP agent.\n This version of the ATM 1483 Profile component was supported in Juniper\n JUNOSe 5.1 and 5.2 system releases.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniAtm1483ProfileAgentV1 = juniAtm1483ProfileAgentV1.setStatus('obsolete')
if mibBuilder.loadTexts: juniAtm1483ProfileAgentV1.setDescription('The MIB supported by the SNMP agent for the ATM 1483 Profile application in JUNOSe. These capabilities became obsolete when ifALias support was added to profile entries.')
juniAtm1483ProfileAgentV2 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 34, 6, 2))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniAtm1483ProfileAgentV2 = juniAtm1483ProfileAgentV2.setProductRelease('Version 2 of the ATM 1483 Profile component of the JUNOSe SNMP agent.\n This version of the ATM 1483 Profile component was supported in Juniper\n JUNOSe 5.3 system releases.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniAtm1483ProfileAgentV2 = juniAtm1483ProfileAgentV2.setStatus('obsolete')
if mibBuilder.loadTexts: juniAtm1483ProfileAgentV2.setDescription('The MIB supported by the SNMP agent for the ATM 1483 Profile application in JUNOSe. These capabilities became obsolete when OAM support was added to profile entries.')
juniAtm1483ProfileAgentV3 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 34, 6, 3))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniAtm1483ProfileAgentV3 = juniAtm1483ProfileAgentV3.setProductRelease('Version 3 of the ATM 1483 Profile component of the JUNOSe SNMP agent.\n This version of the ATM 1483 Profile component was supported in Juniper\n JUNOSe 5.1 and 5.2 system releases.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniAtm1483ProfileAgentV3 = juniAtm1483ProfileAgentV3.setStatus('obsolete')
if mibBuilder.loadTexts: juniAtm1483ProfileAgentV3.setDescription('The MIB supported by the SNMP agent for the ATM 1483 Profile application in JUNOSe. These capabilities became obsolete when ifALias support was added to profile entries.')
juniAtm1483ProfileAgentV4 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 34, 6, 4))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniAtm1483ProfileAgentV4 = juniAtm1483ProfileAgentV4.setProductRelease('Version 4 of the ATM 1483 Profile component of the JUNOSe SNMP agent.\n This version of the ATM 1483 Profile component was supported in Juniper\n JUNOSe 5.3, 6.0, and 6.1 system releases.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniAtm1483ProfileAgentV4 = juniAtm1483ProfileAgentV4.setStatus('current')
if mibBuilder.loadTexts: juniAtm1483ProfileAgentV4.setDescription('')
juniAtm1483ProfileAgentV5 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 34, 6, 5))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniAtm1483ProfileAgentV5 = juniAtm1483ProfileAgentV5.setProductRelease('Version 5 of the ATM 1483 Profile component of the JUNOSe SNMP agent.\n This version of the ATM 1483 Profile component is supported in Juniper\n JUNOSe 7.0 and subsequent system releases.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniAtm1483ProfileAgentV5 = juniAtm1483ProfileAgentV5.setStatus('current')
if mibBuilder.loadTexts: juniAtm1483ProfileAgentV5.setDescription('')
mibBuilder.exportSymbols("Juniper-ATM-1483-Profile-CONF", juniAtm1483ProfileAgentV4=juniAtm1483ProfileAgentV4, juniAtm1483ProfileAgentV1=juniAtm1483ProfileAgentV1, juniAtm1483ProfileAgentV2=juniAtm1483ProfileAgentV2, juniAtm1483ProfileAgent=juniAtm1483ProfileAgent, juniAtm1483ProfileAgentV5=juniAtm1483ProfileAgentV5, juniAtm1483ProfileAgentV3=juniAtm1483ProfileAgentV3, PYSNMP_MODULE_ID=juniAtm1483ProfileAgent)
|
class parent:
def parentmethod(self):
print("Calling Parent Method")
def parentmethod2(self):
print("Calling the second parent method")
class child(parent):
def childmethod(self):
print("Calling the Child Method")
def parentmethod2(self):
print("Modified parent method 2")
p = parent()
c = child()
p.parentmethod() # Accessing Parent Method
c.childmethod() # Accessing Child Method
c.parentmethod() # Accessing the inherited parent method from child class.
p.parentmethod2() # Accessing the 2nd parent method from parent class
c.parentmethod2() # Accessing the 2nd parent method from the child class after modification
print("\nView code and read comments for better understanding.")
# Parent class cannot access child class. However, the child class can access the parent class.
|
# Flip the keys to the values, and the values to the keys
namesAndNumbers = {"Ellis": 123456789, "Roy": 987654321, "Blake": 753159842}
numbersAndNames = {}
for k in namesAndNumbers:
numbersAndNames[namesAndNumbers[k]] = k
print(numbersAndNames) |
# directories path
BASIC_DIR = "~/ECG_Analysis/ECG_data"
ECG_eHEALTH_DATA_DIR = BASIC_DIR + '/eHealth_ECG'
ECG_ID_DATA_DIR = BASIC_DIR + '/ECG-ID/resampled'
ECG_eHEALTH_DATA_DIR = BASIC_DIR + '/eHealth_ECG'
ECG_eHEALTH_TRAIN_DATA_DIR = BASIC_DIR + '/trainECG'
ECG_eHEALTH_TEST_DATA_DIR = BASIC_DIR + '/testECG'
SEGMENTATOR_DIR = BASIC_DIR + '/ECG_segmentator'
COMBINATOR_DIR = BASIC_DIR + '/ECG_combinator' |
N = int(input())
for i in range(1, 10):
if N % i == 0 and (N // i) < 10:
print("Yes")
break
else:
print("No")
|
# --------------
##File path for the file
file_path
def read_file(path):
file = open (path,'r')
sentence = file.readline()
file.close ()
return sentence
sample_message = read_file (file_path)
print (sample_message)
#Code starts here
# --------------
#Code starts here
message_1 = read_file (file_path_1)
print (message_1)
message_2 = read_file (file_path_2)
print (str(message_2))
def fuse_msg (message_a, message_b):
quotient = int(message_a)//int(message_b)
return str(quotient)
secret_msg_1 = fuse_msg (message_2,message_1)
print (secret_msg_1)
# --------------
#Code starts here
message_3 = read_file (file_path_3)
print (message_3)
def substitute_msg (message_c):
if (message_c == 'Red'):
sub = "Army General"
elif (message_c == 'Green'):
sub = "Data Scientist"
elif (message_c == 'Blue'):
sub = "Marine Biologist"
return sub
secret_msg_2 = substitute_msg(message_3)
print (secret_msg_2)
# --------------
# File path for message 4 and message 5
file_path_4
file_path_5
#Code starts here
message_4 = read_file (file_path_4)
print (message_4)
message_5 = read_file (file_path_5)
print (message_5)
def compare_msg(message_d, message_e):
a_list =[]
b_list = []
c_list = []
a_list = message_d.split ()
print (a_list)
b_list = message_e.split ()
print (b_list)
c_list = [x for x in a_list if x not in b_list]
final_msg = " ".join(c_list)
return str(final_msg)
secret_msg_3 = compare_msg(message_4,message_5)
print (str(secret_msg_3))
# --------------
#Code starts here
message_6 = read_file (file_path_6)
print (message_6)
def extract_msg (message_f):
a_list = []
a_list = message_f.split()
print (a_list)
even_word = lambda x: True if (len(x)%2 ==0) else False
b_list = filter (even_word, a_list)
final_msg = " ".join(b_list)
return final_msg
secret_msg_4 = extract_msg (message_6)
print (str(secret_msg_4))
# --------------
#Secret message parts in the correct order
message_parts=[secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2]
final_path= user_data_dir + '/secret_message.txt'
#Code starts here
secret_msg = " ".join (message_parts)
def write_file (secret_msg, path):
f = open (path, 'a+')
f.write (str(secret_msg))
f.close ()
print (secret_msg)
write_file (message_parts, final_path)
|
def split_list(big_list , max_split: int):
for i in range(0, len(big_list), max_split):
yield big_list[i: i+max_split]
|
def remove_repetidos(lista):
lista_b = []
for i in lista:
if i not in lista_b:
lista_b.append(i)
lista_b.sort()
return lista_b
def soma_elementos(lista):
return sum(lista)
#print(sum(lista))
def maior_elemento(lista):
#max(lista)
print(max(lista))
lista = [1, 1, 2, 1, 3, 4, 3, 6, 7, 6, 7, 8, 10 ,9]
lista = remove_repetidos(lista)
print(lista)
soma_elementos(lista)
maior_elemento(lista) |
def Posicao(a, b, c, d,u, pos):
posicao =""
if pos != 0:
pos = "transversal"
else:
if (a*u[0] + b*u[1] + c*u[2] + d) == 0:
pos = "contida"
else:
pos = "paralela"
return pos |
class JsonObject:
@staticmethod
def decode(json, agent):
return json
@staticmethod
def encode(obj):
return obj
|
#113
# Time: O(n)
# Space: O(h), h is height of binary tree
# Given a binary tree and a sum, find all root-to-leaf paths
# where each path's sum equals the given sum.
#
# For example:
# Given the below binary tree and sum = 22,
# 5
# / \
# 4 8
# / / \
# 11 13 4
# / \ / \
# 7 2 5 1
# return
# [
# [5,4,11,2],
# [5,8,4,5]
# ]
class TreeNode():
def __init__(self,val):
self.val=val;
self.right=None
self.left=None
class DFSSol():
def pathSumBTII(self,root,target_sum):
return self.pathSumBTIIRec(root,target_sum,[],[])
def pathSumBTIIRec(self,root,target_sum,cur_path,result):
if not root:
return result
if not root.left and not root.right and root.val==target_sum:
result.append(cur_path+[root.val])
return result
cur_path.append(root.val)
self.pathSumBTIIRec(root.left,target_sum-root.val,cur_path,result)
self.pathSumBTIIRec(root.right,target_sum-root.val,cur_path,result)
cur_path.pop()
return result
|
#!/usr/bin/python3
qaly = 0
for x in range(int(input())):
a, b = map(float, input().split())
qaly += a*b
print("{0:.3f}".format(qaly))
|
# @Title: 买卖股票的最佳时机 (Best Time to Buy and Sell Stock)
# @Author: 18015528893
# @Date: 2021-02-01 22:11:17
# @Runtime: 792 ms
# @Memory: 29.5 MB
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
dp = [[0, 1] for _ in range(n+1)]
dp[0][0] = 0
dp[0][1] = float('-inf')
for i in range(1, n+1):
dp[i][0] = max(dp[i-1][0], dp[i-1][1]+prices[i-1])
dp[i][1] = max(dp[i-1][1], -prices[i-1])
return dp[-1][0]
|
class BreakOpportunity:
"""A `GraphicObject` mixin which indicates a break can be performed here.
Some notational constructs are well suited to be placed at line
or page breaks, for example bar lines or grand pauses. Such classes
should subclass this mixin so the flowable container can know this.
This mixin is only useful when used inside a `Flowable`.
"""
pass
|
#
# PySNMP MIB module IPV6-TUNNEL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IPV6-TUNNEL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:56:52 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint")
InetAddressPrefixLength, InetAddressIPv4 = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressPrefixLength", "InetAddressIPv4")
Ipv6AddressPrefix, Ipv6IfIndex, Ipv6Address = mibBuilder.importSymbols("IPV6-TC", "Ipv6AddressPrefix", "Ipv6IfIndex", "Ipv6Address")
switch, = mibBuilder.importSymbols("QUANTA-SWITCH-MIB", "switch")
ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup")
MibScalar, MibTable, MibTableRow, MibTableColumn, mib_2, NotificationType, MibIdentifier, Counter32, Counter64, Unsigned32, ModuleIdentity, Integer32, TimeTicks, ObjectIdentity, iso, Gauge32, Bits, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "mib-2", "NotificationType", "MibIdentifier", "Counter32", "Counter64", "Unsigned32", "ModuleIdentity", "Integer32", "TimeTicks", "ObjectIdentity", "iso", "Gauge32", "Bits", "IpAddress")
RowStatus, TextualConvention, PhysAddress, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TextualConvention", "PhysAddress", "DisplayString")
ipv6Tunnel = ModuleIdentity((1, 3, 6, 1, 4, 1, 7244, 2, 27))
if mibBuilder.loadTexts: ipv6Tunnel.setLastUpdated('201108310000Z')
if mibBuilder.loadTexts: ipv6Tunnel.setOrganization('QCI')
if mibBuilder.loadTexts: ipv6Tunnel.setContactInfo(' Customer Support Postal: Quanta Computer Inc. 4, Wen Ming 1 St., Kuei Shan Hsiang, Tao Yuan Shien, Taiwan, R.O.C. Tel: +886 3 328 0050 E-Mail: strong.chen@quantatw.com')
if mibBuilder.loadTexts: ipv6Tunnel.setDescription('The Quanta Private MIB for IPV6 Tunnel')
agentTunnelIPV6Group = MibIdentifier((1, 3, 6, 1, 4, 1, 7244, 2, 27, 1))
agentTunnelIPV6Table = MibTable((1, 3, 6, 1, 4, 1, 7244, 2, 27, 1, 1), )
if mibBuilder.loadTexts: agentTunnelIPV6Table.setStatus('current')
if mibBuilder.loadTexts: agentTunnelIPV6Table.setDescription('A summary table of the IPV6 tunnel instances')
agentTunnelIPV6Entry = MibTableRow((1, 3, 6, 1, 4, 1, 7244, 2, 27, 1, 1, 1), ).setIndexNames((0, "IPV6-TUNNEL-MIB", "agentTunnelID"))
if mibBuilder.loadTexts: agentTunnelIPV6Entry.setStatus('current')
if mibBuilder.loadTexts: agentTunnelIPV6Entry.setDescription('')
agentTunnelID = MibTableColumn((1, 3, 6, 1, 4, 1, 7244, 2, 27, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647)))
if mibBuilder.loadTexts: agentTunnelID.setStatus('current')
if mibBuilder.loadTexts: agentTunnelID.setDescription('The tunnel ID is associated with Internal Interface number which is generated when we create a tunnel, and is used to configure the tunnel.')
agentTunnelIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 7244, 2, 27, 1, 1, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentTunnelIfIndex.setStatus('current')
if mibBuilder.loadTexts: agentTunnelIfIndex.setDescription('The external interface of the tunnel is associted with internal interface. The tunnel ID associated with Internal Interface number is generated when we create a tunnel, which is used to configure the tunnel.')
agentTunnelMode = MibTableColumn((1, 3, 6, 1, 4, 1, 7244, 2, 27, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("undefined", 1), ("ip6over4", 2), ("ip6to4", 3))).clone('undefined')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: agentTunnelMode.setStatus('current')
if mibBuilder.loadTexts: agentTunnelMode.setDescription('Specifies the type of Tunnel either undefined, 6over4 or 6to4. The default value is undefined. It supports 6over4 which supports an assigned IPV6 address, an IPV4 address is not allowed. For this mode, the tunnel source and tunnel destination must be IPV4 address. For 6to4 tunnel, the tunnel source must be IPv4 address. Tunnel destination should not be set. The first 48-bits of the IPv4 address assigned to the 6to4 tunnel should be of the format 2002:sourceIpv4address.')
agentTunnelLocalIP4Addr = MibTableColumn((1, 3, 6, 1, 4, 1, 7244, 2, 27, 1, 1, 1, 4), InetAddressIPv4()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentTunnelLocalIP4Addr.setStatus('current')
if mibBuilder.loadTexts: agentTunnelLocalIP4Addr.setDescription('The address of the Local endpoint of the tunnel i.e. the source address used in the outer IP header. It is 0.0.0.0 if unknown or the tunnel is over IPv6.')
agentTunnelRemoteIP4Addr = MibTableColumn((1, 3, 6, 1, 4, 1, 7244, 2, 27, 1, 1, 1, 5), InetAddressIPv4()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentTunnelRemoteIP4Addr.setStatus('current')
if mibBuilder.loadTexts: agentTunnelRemoteIP4Addr.setDescription('The address of the Remote endpoint of the tunnel i.e. the destination address used in the outer IP header. It is 0.0.0.0 if the tunnel is unknown or IPv6 address, or not a point to point link')
agentTunnelLocalIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 7244, 2, 27, 1, 1, 1, 6), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentTunnelLocalIfIndex.setStatus('current')
if mibBuilder.loadTexts: agentTunnelLocalIfIndex.setDescription('Specifies the interface for IPv6 Tunnel Source')
agentTunnelStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 7244, 2, 27, 1, 1, 1, 7), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: agentTunnelStatus.setStatus('current')
if mibBuilder.loadTexts: agentTunnelStatus.setDescription('Status of this instance.Row can be added or deleted by setting the value to createAndGo/destroy active(1) - this Tunnel instance is active createAndGo(4) - set to this value to create an instance destroy(6) - set to this value to delete an instance')
agentTunnelIcmpUnreachableMode = MibTableColumn((1, 3, 6, 1, 4, 1, 7244, 2, 27, 1, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: agentTunnelIcmpUnreachableMode.setStatus('current')
if mibBuilder.loadTexts: agentTunnelIcmpUnreachableMode.setDescription('Specifies the Mode of Sending ICMPv6 Unreachable messages on this tunnel interface.')
agentTunnelIPV6PrefixTable = MibTable((1, 3, 6, 1, 4, 1, 7244, 2, 27, 1, 2), )
if mibBuilder.loadTexts: agentTunnelIPV6PrefixTable.setStatus('current')
if mibBuilder.loadTexts: agentTunnelIPV6PrefixTable.setDescription('A table of the IPV6 prefixes associated with tunnel instances')
agentTunnelIPV6PrefixEntry = MibTableRow((1, 3, 6, 1, 4, 1, 7244, 2, 27, 1, 2, 1), ).setIndexNames((0, "IPV6-TUNNEL-MIB", "agentTunnelID"), (0, "IPV6-TUNNEL-MIB", "agentTunnelIPV6PrefixPrefix"), (0, "IPV6-TUNNEL-MIB", "agentTunnelIPV6PrefixPrefixLen"))
if mibBuilder.loadTexts: agentTunnelIPV6PrefixEntry.setStatus('current')
if mibBuilder.loadTexts: agentTunnelIPV6PrefixEntry.setDescription('')
agentTunnelIPV6PrefixPrefix = MibTableColumn((1, 3, 6, 1, 4, 1, 7244, 2, 27, 1, 2, 1, 1), Ipv6AddressPrefix())
if mibBuilder.loadTexts: agentTunnelIPV6PrefixPrefix.setStatus('current')
if mibBuilder.loadTexts: agentTunnelIPV6PrefixPrefix.setDescription('The prefix associated with the tunnel interface. The data type is used to model the IPV6 address. It is a binary string of 16 octects in network byte-order. It specifies the IP address of tunnel which will be in IPV6 Format, generated using internal interface number.')
agentTunnelIPV6PrefixPrefixLen = MibTableColumn((1, 3, 6, 1, 4, 1, 7244, 2, 27, 1, 2, 1, 2), InetAddressPrefixLength())
if mibBuilder.loadTexts: agentTunnelIPV6PrefixPrefixLen.setStatus('current')
if mibBuilder.loadTexts: agentTunnelIPV6PrefixPrefixLen.setDescription('The length of the prefix (in bits).')
agentTunnelIPV6PrefixStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 7244, 2, 27, 1, 2, 1, 3), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: agentTunnelIPV6PrefixStatus.setStatus('current')
if mibBuilder.loadTexts: agentTunnelIPV6PrefixStatus.setDescription('Status of this instance.Row can be added or deleted by setting the value to createAndGo/destroy active(1) - this Tunnel instance is active createAndGo(4) - set to this value to create an instance destroy(6) - set to this value to delete an instance')
mibBuilder.exportSymbols("IPV6-TUNNEL-MIB", agentTunnelStatus=agentTunnelStatus, PYSNMP_MODULE_ID=ipv6Tunnel, agentTunnelIcmpUnreachableMode=agentTunnelIcmpUnreachableMode, agentTunnelIPV6PrefixEntry=agentTunnelIPV6PrefixEntry, agentTunnelIPV6Group=agentTunnelIPV6Group, agentTunnelMode=agentTunnelMode, agentTunnelLocalIfIndex=agentTunnelLocalIfIndex, agentTunnelIPV6Table=agentTunnelIPV6Table, agentTunnelIPV6PrefixStatus=agentTunnelIPV6PrefixStatus, agentTunnelLocalIP4Addr=agentTunnelLocalIP4Addr, agentTunnelIPV6PrefixTable=agentTunnelIPV6PrefixTable, ipv6Tunnel=ipv6Tunnel, agentTunnelIPV6PrefixPrefix=agentTunnelIPV6PrefixPrefix, agentTunnelIPV6PrefixPrefixLen=agentTunnelIPV6PrefixPrefixLen, agentTunnelIPV6Entry=agentTunnelIPV6Entry, agentTunnelID=agentTunnelID, agentTunnelRemoteIP4Addr=agentTunnelRemoteIP4Addr, agentTunnelIfIndex=agentTunnelIfIndex)
|
BASEURL = "https://fnbr.co/api"
VALID_IMAGE_TYPES = ['emote','glider','emoji','loading','outfit','pickaxe','skydive','umbrella','misc']
VALID_IMAGE_LIMIT_MIN = 1
VALID_IMAGE_LIMIT_MAX = 15
NONE_TYPE = "none"
ERROR_TYPE = "error"
STATS_TYPE = "stats"
IMAGE_TYPE = "image"
SHOP_TYPE = "shop"
|
# Title: Validate Binary Search Tree
# Runtime: 52 ms
# Memory: 16.6 MB
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Time Complexity: O(n)
# Space Complexity: O(n)
class Solution:
def postOrderTraverse(self, root: TreeNode, lst: List):
if not root:
return
self.postOrderTraverse(root.left, lst)
lst.append(root.val)
self.postOrderTraverse(root.right, lst)
def isSorted(self, lst: List) -> bool:
for i in range(len(lst) - 1):
if lst[i] >= lst[i + 1]:
return False
return True
def isValidBST(self, root: TreeNode) -> bool:
lst = []
self.postOrderTraverse(root, lst)
return self.isSorted(lst)
|
# RUN: test-output.sh %s
x = 1
def adder():
y = 2
def inner(z):
return x + y + z
return inner(10)
print("Start") # OUTPUT-LABEL: Start
print(adder()) # OUTPUT-NEXT: 13
print("End") # OUTPUT-LABEL: End
|
parameter_lists_copy = [bar for bar in parameter_lists]
for bar in parameter_lists_copy:
if param_index >= len(bar.GetParameters()):
parameter_lists.remove(bar)
|
# example of definitions of names part 3
#global name
X = 11
# access to global name from function
def f():
if __name__ == '__main__':
print(X)
# changing global name X in module
def g():
global X
X = 22
if __name__ == '__main__':
print(X)
def h1():
X = 33 # locale name in function
def nested():
print(X) # link to local name
if __name__ == '__main__':
nested()
def h2():
X = 33 # locale name in function
def nested():
nonlocal X
X = 44
print(X)
if __name__ == '__main__':
nested()
print(X)
if __name__ == '__main__':
print(X) # 11
f() # 11
g() # 22
print(X) # 22 - X in function is global
h1() # 33 - X in h1 is local
h2() # 44 - X is nonlocal and seen from h2() function
|
def gcdRecur(a,b):
'''
a,b:positive integers
returns a positive integer, the GCD of a and b
'''
if b==0:
return a
else:
return gcdRecur(b,a%b)
|
def query_tekst(source, target):
postgreSQL_select_Query = f"SELECT MIN(r.seq) AS seq, " \
f"e.old_id AS id, " \
f"sum(e.distance) AS distance, " \
f"ST_Collect(e.the_geom) AS geom " \
f"FROM pgr_dijkstra('SELECT id, source, target, distance as cost FROM public.\"00DrogiINTER_noded\"', {source}, {target}, false ) AS r, " \
f"public.\"00DrogiINTER_noded\" AS e " \
f"WHERE r.edge=e.id " \
f"GROUP BY e.old_id"
# print(postgreSQL_select_Query)
return postgreSQL_select_Query
def sum_length_from_scratch(tablica):
# print(tablica)
dlugosc_drogi = 0
for row in tablica:
dlugosc_drogi = dlugosc_drogi + float(row[2])
return dlugosc_drogi
|
{
"targets": [
{
"target_name": "ledcontrol",
"sources": [ "led-control.cpp", "include/gpio-driver.cpp",
"include/spi-driver.cpp", "include/ws2801-driver.cpp" ],
},
{
"target_name": "spectrum",
"sources": [ "i2c_spectrum.cc" ],
"include_dirs": [
"/usr/include/glib-2.0",
"/usr/lib/glib-2.0/include",
"/usr/include/gtk-2.0",
"/usr/lib/gtk-2.0/include",
"/usr/include/atk-1.0",
"/usr/include/cairo",
"/usr/include/gdk-pixbuf-2.0",
"/usr/include/pango-1.0",
"/usr/include/pixman-1",
"/usr/include/freetype2",
"/usr/include/libpng12",
],
}
]
}
|
double_qoute_string = "This is a string with double qoute";
single_qoute_string = 'This is a string with single qoute';
three_qoute_string = '''
This is a string with single qoute.
'''
three_double_qoute_string = """
This is a string with three double qoute.
"""
print(double_qoute_string);
print(single_qoute_string);
print(three_qoute_string);
print(three_double_qoute_string); |
def bubble_sort(input_list):
last_position = len(input_list) - 1
made_changes = True
while made_changes:
made_changes = False
for i in range(0, last_position):
if input_list[i] > input_list[i + 1]:
input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i]
made_changes = True
last_position -= 1
return input_list
|
# @Title: 两数相除 (Divide Two Integers)
# @Author: KivenC
# @Date: 2019-01-28 16:51:37
# @Runtime: 64 ms
# @Memory: 6.6 MB
class Solution:
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
sign = dividend >> 31 == divisor >> 31
dividend = self.positive(dividend)
divisor = self.positive(divisor)
cnt, minus = 0, divisor
while dividend >= minus:
minus <<= 1
cnt += 1
if cnt == 0:
return 0
r = self.negpos(sign, 2**(cnt-1) +
self.divide(dividend-(minus >> 1), divisor))
if r < -2**31 or r > 2**31 - 1:
return 2**31 - 1
return r
def negative(self, n):
return ~n+1
def positive(self, n):
t = n >> 31
return (n + t) ^ t
def negpos(self, sign, n):
return self.positive(n) if sign else self.negative(n)
|
class Solution:
def trap(self, height: List[int]) -> int:
box = 0
left_max = 0
right_max = 0
left = 0
right = len(height)-1
while left<right:
if height[left]<height[right]:
if height[left]>left_max:
left_max = height[left]
else:
box += left_max - height[left]
left+=1
else:
if height[right]>right_max:
right_max = height[right]
else:
box += right_max - height[right]
right-=1
return box
|
'''
70. Climbing Stairs
https://leetcode.com/problems/climbing-stairs/
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
'''
class Solution:
def climbStairs(self, n: int) -> int:
if n > 2:
ai, an_2, an_1 = 0, 2, 1
for _ in range(n-3, -1, -1):
ai = an_1 + an_2
an_2, an_1 = ai, an_2
# print(ai, an_2, an_1)
return ai
elif n == 2:
return 2
else: # n == 1, 0:
return 1
|
#Exercício 52 – Números primos
#Exercício Python 52: Faça um programa que leia um número inteiro e diga se ele é ou não um número primo.
while True:
num = int(input('Digite um número: '))
p = True
for i in range(2, num + 1, 1):
resto = num % i
if resto == 0:
if i != num:
print(num, 'não é primo!')
p = False
break
if p == True:
print(num, 'é primo!')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.