content stringlengths 7 1.05M |
|---|
def simple_moving_average(df, base, target, period):
"""
Function to compute Simple Moving Average (SMA)
This is a lagging indicator
df - the data frame
base - on which the indicator has to be calculated eg Close
target - column name to store output
period - period of the sma
"""
df[target] = df[base].rolling(window=period).mean().round(2)
return df
def exponential_moving_average(df, base, target, period):
"""
Function to compute Exponential Moving Average (EMA)
This is a lagging indicator
df - the data frame
base - on which the indicator has to be calculated eg Close
target - column name to store output
period - period of the ema
"""
df[target] = df[base].ewm(ignore_na=False, min_periods=period, com=period, adjust=True).mean()
return df
def moving_average_convergence_divergence(df, base, macd_target, macd_line_target, period_long=26, period_short=12,
period_signal=9):
"""
Function to compute MACD (Moving Average Convergence/Divergence)
This is a lagging indicator
df - the data frame
base - on which the indicator has to be calculated eg Close
macd_target - column name to store macd value
macd_line_target - column name to store macd line
period_long - period of the longer time frame
period_short - period of the shorter time frame
period_signal - period of the signal
"""
short_ema_target = 'ema_{}'.format(period_short)
long_ema_target = 'ema_{}'.format(period_long)
df = exponential_moving_average(df, base, long_ema_target, period_long)
df = exponential_moving_average(df, base, short_ema_target, period_short)
df[macd_target] = df[short_ema_target] - df[long_ema_target]
df[macd_line_target] = df[macd_target].ewm(ignore_na=False, min_periods=0, com=period_signal, adjust=True).mean()
df = df.drop([short_ema_target, long_ema_target], axis=1)
return df
|
class Usuario:
def __init__(self, nome) -> None:
self.nome = nome
self.id = None
|
_all__ = [
'Auto'
]
class Auto(object):
pass
|
def add(number_one, number_two):
return number_one + number_two
def multiply(number_one, number_two):
return number_one * number_two
if __name__ == "__main__":
print(add(3, 4))
print(multiply(5, 5))
|
# ElasticQuery
# File: exception.py
# Desc: ES query builder exceptions
class QueryError(ValueError):
pass
class NoQueryError(QueryError):
pass
class NoAggregateError(QueryError):
pass
class NoSuggesterError(QueryError):
pass
class MissingArgError(ValueError):
pass
|
#https://rszalski.github.io/magicmethods/
#__init__ é um metodo magico
#Um design muito utilizado é o Singleton, ou seja, somente uma instacia para o projeto todo
class A:
def __new__(cls, *args, **kwargs):
if not hasattr(cls,'_jaexiste'):
cls._jaexiste = object.__new__(cls)
return cls._jaexiste
def __call__(self, *args, **kwds):
#Faz se comportar como uma função
resultado = 1
for i in args:
resultado *= i
return resultado
def __setattr__(self, name, value):
if name == 'nome':
self.__dict__[name] = 'You are not Allowed.'
else:
self.__dict__[name] = value
def __del__(self):
#Confirmação que o Garbage Colector do Python funcionou. Não é muito recomendado.
print('Coletado a Sujeira.')
def __str__(self):
return "<class 'A'>"# Retorna informacao da Classe em Uso.
def __len__(self):
return 55
#útil para usar como contador de metodos dentro de uma classe.
def __init__(self):
print('Eu sou o INIT')
a = A()
b = A()
c = A()
variavel = a(1,2,3,4,5,6,7,8,9,10)
print(variavel)
a.nome = 'Zezão da Esquina'
print(a.nome)
print(a)
print(len(a)) |
#serie a,b,a,b,a,b....
limite = int(input("Digite las veces que se repetira: "))
interructor = True
controlador = 0
letra = ""
while controlador < limite:
controlador = controlador + 1
if interructor:
letra = "A"
interructor = False
else:
letra = "B"
interructor = True
print(letra, end=", ")
|
# Longest Common Subsequence
def lcs(X, Y, m, n):
if m == 0 or n == 0:
return 0
elif X[m - 1] == Y[n - 1]:
return 1 + lcs(X, Y, m-1, n-1)
else:
return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n))
X = 'AGGTAB'
Y = 'GXTXAYB'
print('Length of LCS is ', lcs(X, Y, len(X), len(Y)))
'''
Output:-
>>>
Length of LCS is 4
'''
|
''' bd_username = 'ruslan'
bd_password = '12345'
def auth(tries: int):
count = 0
while count < tries:
username = input('введите имя пользователя: ')
password = input('введите пароль: ')
if username == bd_username and password == bd_password:
print('добро пожаловать')
break
else:
print('ввели неверные данные! Попробуйте еще раз')
count += 1
auth(3)
'''
'''def register_to_bd(username, password, check_password):
if password == check_password:
file1 = open('database.txt', 'w')
result = username + "\n" + password
file1.write(result)
register_to_bd('ruslan', '123', '123')
'''
'''file1 = open('database.txt')
list1 = file1.readlines()
my_input = input('я хочу ')
if my_input in list1:
print('в наличии')
else:
print('нет в наличии! На складе!')
'''
'''with open('database.txt') as file1:
ban = 'ban_word' + '\n'
check_ban = ''
streamer_words = file1.readlines()
i = 0
while i < len(streamer_words):
if streamer_words[i] == ban:
check_ban = streamer_words[i]
print(streamer_words[i], streamer_words.index(streamer_words[i]) + 1)
i += 1
if check_ban in streamer_words:
print('найдено')
else:
print('ok')'''
'''spisok = [1, 2, 3, 4, 5, 6]
print(spisok[1:4:2])'''
|
#!env python
#
# ACSL Intermediate Division - Number Transformation - 2019-2020
# Solution by Arul John
# 2020-11-22
#
# Function to do the number transformations
def number_transformation(n, p):
str_n = n
n = int(n)
p = int(p)
if len(str_n) < p:
return
str_n_ans = '' # answer
# index of the Pth digit
i = len(str_n) - p
# Pth digit
pth_digit = int(str_n[i:i+1])
str_n_right = str_n[i+1:]
str_n_left = str_n[:i]
for c in str_n_left:
str_n_ans += str((int(c) + pth_digit) % 10)
str_n_ans += str(pth_digit)
for c in str_n_right:
str_n_ans += str(abs(int(c) - pth_digit))
return int(str_n_ans)
# Tests
def test_number_transformation():
test_data = [('296351 5', 193648),
('762184 3', 873173),
('45873216 7', 95322341),
('19750418 6', 86727361),
('386257914 5', 831752441)
]
for test_input, answer in test_data:
testlist = test_input.split(' ')
assert number_transformation(*testlist) == answer
# Main
if __name__ == "__main__":
test_number_transformation()
n, p = input().split()
print(number_transformation(n, p))
|
def fileNaming(names):
for i in range(1, len(names)):
temp = names[i]
counter = 1
while temp in names[0:i]:
temp = f"{names[i]}({counter})"
counter += 1
names[i] = temp
return names
print(fileNaming(["doc", "doc", "image", "doc(1)", "doc"]))
|
helpline_numbers = {
'source':'https://www.mohfw.gov.in/pdf/coronvavirushelplinenumber.pdf',
'helpline_number':'+91-11-23978046',
'toll_free':'1075',
'helpline_email':'ncov2019@gov.in',
'contact_details':[
{
'state_or_UT':'Andhra Pradesh',
'helpline_number':'0866-2410978'
},
{
'state_or_UT':'Arunachal Pradesh',
'helpline_number':'9436055743'
},
{
'state_or_UT':'Assam',
'helpline_number':'6913347770'
},
{
'state_or_UT':'Bihar',
'helpline_number':'104'
},
{
'state_or_UT':'Chhattisgarh',
'helpline_number':'104'
},
{
'state_or_UT':'Goa',
'helpline_number':'104'
},
{
'state_or_UT':'Gujarat',
'helpline_number':'104'
},
{
'state_or_UT':'Haryana',
'helpline_number':'8558893911'
},
{
'state_or_UT':'Himachal Pradesh',
'helpline_number':'104'
},
{
'state_or_UT':'Jharkhand',
'helpline_number':'104'
},
{
'state_or_UT':'Karnataka',
'helpline_number':'104'
},
{
'state_or_UT':'Kerala',
'helpline_number':'0471-2552056'
},
{
'state_or_UT':'Madhya Pradesh',
'helpline_number':'104'
},
{
'state_or_UT':'Maharashtra',
'helpline_number':'020-26127394'
},
{
'state_or_UT':'Manipur',
'helpline_number':'3852411668'
},
{
'state_or_UT':'Meghalaya',
'helpline_number':'108'
},
{
'state_or_UT':'Mizoram',
'helpline_number':'102'
},
{
'state_or_UT':'Nagaland',
'helpline_number':'7005539653'
},
{
'state_or_UT':'Odisha',
'helpline_number':'9439994859'
},
{
'state_or_UT':'Punjab',
'helpline_number':'104'
},
{
'state_or_UT':'Rajasthan',
'helpline_number':'0141-2225624'
},
{
'state_or_UT':'Sikkim',
'helpline_number':'104'
},
{
'state_or_UT':'Tamil Nadu',
'helpline_number':'044-29510500'
},
{
'state_or_UT':'Telangana',
'helpline_number':'104'
},
{
'state_or_UT':'Tripura',
'helpline_number':'0381-2315879'
},
{
'state_or_UT':'Uttarakhand',
'helpline_number':'104'
},
{
'state_or_UT':'Uttar Pradesh',
'helpline_number':'18001805145'
},
{
'state_or_UT':'West Bengal',
'helpline_number':'1800313444222 , 03323412600'
},
{
'state_or_UT':'Andaman and Nicobar Islands',
'helpline_number':'03192-232102'
},
{
'state_or_UT':'Chandigarh',
'helpline_number':'9779558282'
},
{
'state_or_UT':'Dadra and Nagar Haveli and Daman & Diu',
'helpline_number':'104'
},
{
'state_or_UT':'Delhi',
'helpline_number':'011-22307145'
},
{
'state_or_UT':'Jammu & Kashmir',
'helpline_number':'01912520982, 0194-2440283'
},
{
'state_or_UT':'Ladakh',
'helpline_number':'01982256462'
},
{
'state_or_UT':'Lakshadweep',
'helpline_number':'104'
},
{
'state_or_UT':'Puducherry',
'helpline_number':'104'
}
]
} |
"""Takes a number of miles and converts it to a feet value."""
def main() -> None:
"""Convert the user input miles value to feet and display the result."""
print('Hike Calculator')
miles: float = float(input('How many miles did you walk?: '))
print(f'You walked {to_feet(miles)} feet.')
def to_feet(miles: float) -> int:
"""Return the input miles value as feet."""
FEET_PER_MILE: int = 5280
return int(miles * FEET_PER_MILE)
if __name__ == '__main__':
main() |
#-------------------------------------------------------------------------------
#
# Project: EOxServer <http://eoxserver.org>
# Authors: Fabian Schindler <fabian.schindler@eox.at>
# Martin Paces <martin.paces@eox.at>
#
#-------------------------------------------------------------------------------
# Copyright (C) 2013 EOX IT Services GmbH
#
# 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 of this Software or works derived from this 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.
#-------------------------------------------------------------------------------
class AsyncBackendInterface(object):
""" Interface class for an asynchronous WPS back-end.
NOTE: Only one asynchronous back-end at time is allowed to be configured.
"""
@property
def supported_versions(self):
""" A list of versions of the WPS standard supported by the back-end.
"""
def execute(self, process, raw_inputs, resp_form, extra_parts=None,
job_id=None, version="1.0.0", **kwargs):
""" Execute process asynchronously.
The request is defined by the process's identifier ``process_id``,
``raw_inputs`` (before the decoding and resolution
of the references), and the ``resp_form`` (holding
the outputs' parameters). The ``version`` of the WPS standard
to be used. Optionally, the user defined ``job_id`` can be passed.
If the ``job_id`` cannot be used the execute shall fail.
The ``extra_parts`` should contain a dictionary of named request parts
should the request contain multi-part/related CID references.
On success, the method returns the ``job_id`` assigned to the
executed job.
"""
def get_response_url(self, job_id):
""" Get URL of the execute response for the given job id """
def get_status(self, job_id):
""" Get status of a job. Allowed responses and their meanings are:
ACCEPTED - job scheduled for execution
STARTED - job in progress
PAUSED - job is stopped and it can be resumed
CANCELLED - job was terminated by the user
FAILED - job ended with an error
SUCCEEDED - job ended successfully
"""
def purge(self, job_id, **kwargs):
""" Purge the job from the system by removing all the resources
occupied by the job.
"""
def cancel(self, job_id, **kwargs):
""" Cancel the job execution. """
def pause(self, job_id, **kwargs):
""" Pause the job execution. """
def resume(self, job_id, **kwargs):
""" Resume the job execution. """
class ProcessInterface(object):
""" Interface class for processes offered, described and executed by
the WPS.
"""
@property
def version(self):
""" The version of the process, if applicable. Optional.
When omitted it defaults to '1.0.0'.
"""
@property
def synchronous(self):
""" Optional boolean flag indicating whether the process can be executed
synchronously. If missing True is assumed.
"""
@property
def asynchronous(self):
""" Optional boolean flag indicating whether the process can be executed
asynchronously. If missing False is assumed.
"""
@property
def retention_period(self):
""" This optional property (`datetime.timedelta`) indicates the minimum
time the process results shall be retained after the completion.
If omitted the default server retention policy is applied.
"""
@property
def identifier(self):
""" An identifier (URI) of the process. Optional.
When omitted it defaults to the process' class-name.
"""
@property
def title(self):
""" A human-readable title of the process. Optional. When omitted it
defaults to the process identifier.
"""
@property
def description(self):
""" A human-readable detailed description of the process. Optional.
(Content of the the abstract in the WPS process description.)
"""
@property
def profiles(self):
""" A iterable of URNs of WPS application profiles this process
adheres to. Optional.
"""
@property
def metadata(self):
""" A dict of title/URL meta-data pairs associated with the process.
Optional.
"""
@property
def wsdl(self):
""" A URL of WSDL document describing this process. Optional.
"""
@property
def inputs(self):
""" A dict mapping the inputs' identifiers to their respective types.
The type can be either one of the supported native python types
(automatically converted to a ``LiteralData`` object) or an instance
of one of the data-specification classes (``LiteralData``,
``BoundingBoxData``, or ``ComplexData``). Mandatory.
"""
@property
def outputs(self):
""" A dict mapping the outputs' identifiers to their respective types.
The type can be either one of the supported native python types
(automatically converted to a ``LiteralData`` object) or an instance
of one of the data-specification classes (``LiteralData``,
``BoundingBoxData``, or ``ComplexData``). Mandatory.
"""
def execute(self, **kwargs):
""" The main execution function for the process. The ``kwargs`` are the
parsed input inputs (using the keys as defined by the ``inputs``)
and the Complex Data format requests (using the keys as defined by
the ``outputs``).
The method is expected to return a dictionary of the output values
(using the keys as defined by the ``outputs``). In case of only
one output item defined by the ``outputs``, one output value
is allowed to be returned directly.
"""
|
# Utility macros for Twister2 core files
def twister2_core_files():
return twister2_core_conf_files() + twister2_core_lib_files()
def twister2_core_conf_files():
return [
"//twister2/config/src/yaml:config-system-yaml",
"//twister2/config/src/yaml:common-conf-yaml",
]
def twister2_core_lib_files():
return twister2_core_lib_resource_scheduler_files() + \
twister2_core_lib_task_scheduler_files() + \
twister2_core_lib_communication_files()
def twister2_core_lib_resource_scheduler_files():
return [
"//twister2/resource-scheduler/src/java:resource-scheduler-java",
]
def twister2_core_lib_task_scheduler_files():
return [
"//twister2/taskscheduler/src/java:taskscheduler-java",
]
def twister2_core_lib_communication_files():
return [
"//twister2/comms/src/java:comms-java",
"//twister2/proto:proto-jobmaster-java",
]
def twister2_core_lib_connector_files():
return [
"//twister2/connectors/src/java:connector-java",
"@org_xerial_snappy_snappy_java//jar",
"@org_lz4_lz4_java//jar",
"@org_slf4j_slf4j_api//jar",
"@org_apache_kafka_kafka_clients//jar",
]
def twister2_client_lib_master_files():
return [
"//twister2/connectors/src/java:master-java",
]
def twister2_core_lib_data_files():
return [
"//twister2/data/src/main/java:data-java",
"@org_apache_hadoop_hadoop_hdfs//jar",
"@org_apache_hadoop_hadoop_common//jar",
"@org_apache_hadoop_hadoop_annotations//jar",
"@org_apache_hadoop_hadoop_auth//jar",
"@org_apache_hadoop_hadoop_mapreduce_client_core//jar",
"@com_google_code_findbugs_jsr305//jar",
"@com_fasterxml_woodstox_woodstox_core//jar",
"@org_codehaus_woodstox_stax2_api//jar",
"@commons_io_commons_io//jar",
"@commons_collections_commons_collections//jar",
"@org_apache_commons_commons_lang3//jar",
"@commons_configuration_commons_configuration//jar",
"@log4j_log4j//jar",
"@org_apache_htrace_htrace_core4//jar",
"@org_apache_hadoop_hadoop_hdfs_client//jar",
]
def twister2_core_lib_executor_files():
return [
"//twister2/executor/src/java:executor-java",
]
def twister2_core_lib_data_lmdb_files():
return [
"//twister2/data/src/main/java:data-java",
"@org_lmdbjava_lmdbjava//jar",
"@org_lmdbjava_lmdbjava_native_linux_x86_64//jar",
"@org_lmdbjava_lmdbjava_native_windows_x86_64//jar",
"@org_lmdbjava_lmdbjava_native_osx_x86_64//jar",
"@com_github_jnr_jnr_ffi//jar",
"@com_github_jnr_jnr_constants//jar",
"@com_github_jnr_jffi//jar",
"//third_party:com_github_jnr_jffi_native",
]
def twister2_harp_integration_files():
return [
"//twister2/compatibility/harp:twister2-harp",
"//third_party:harp_collective",
"@it_unimi_dsi_fastutil//jar",
]
def twister2_dashboard_files():
return [
"//dashboard/server:twister2-dash-server",
]
def twister2_core_checkpointing_files():
return [
"//twister2/checkpointing/src/java:checkpointing-java",
]
def twister2_core_tset_files():
return [
"//twister2/tset/src/java:tset-java",
"@maven//:com_google_re2j_re2j"
]
def twister2_core_restarter_files():
return [
"//twister2/checkpointing/src/java/edu/iu/dsc/tws/restarter:restarter-java",
]
def twister2_storm_files():
return [
"//twister2/compatibility/storm:twister2-storm",
]
def twister2_beam_files():
return [
"//twister2/compatibility/beam:twister2-beam",
"@org_apache_beam_beam_runners_core_java//jar",
"@org_apache_beam_beam_sdks_java_core//jar",
"@org_apache_beam_beam_model_pipeline//jar",
"@org_apache_beam_beam_runners_java_fn_execution//jar",
"@com_fasterxml_jackson_core_jackson_annotations//jar",
"@joda_time_joda_time//jar",
"@org_apache_beam_beam_runners_core_construction_java//jar",
"@com_google_guava_guava//jar",
"//third_party:vendored_grpc_1_21_0",
"//third_party:vendored_guava_26_0_jre",
"@org_apache_beam_beam_vendor_guava_20_0//jar",
"@javax_xml_bind_jaxb_api//jar",
"@org_apache_beam_beam_vendor_sdks_java_extensions_protobuf//jar",
"@org_apache_beam_beam_vendor_grpc_1_13_1//jar",
]
def twister2_python_support_files():
return [
"//twister2/python-support:python-support",
"@net_sf_py4j_py4j//jar",
"@black_ninia_jep//jar",
]
|
class Exception:
def __init__(self, message):
self.message = message
class TypeError(Exception):
pass
class AttributeError(Exception):
pass
class KeyError(Exception):
pass
class StopIteration(Exception):
pass
class NotImplementedError(Exception):
pass
class NotImplemented(Exception):
pass
class ValueError(Exception):
pass
|
__version__ = '0.15.0.dev0'
PROJECT_NAME = "pulsar"
PROJECT_OWNER = PROJECT_USERAME = "galaxyproject"
PROJECT_AUTHOR = 'Galaxy Project and Community'
PROJECT_EMAIL = 'jmchilton@gmail.com'
PROJECT_URL = "https://github.com/{}/{}".format(PROJECT_OWNER, PROJECT_NAME)
RAW_CONTENT_URL = "https://raw.github.com/{}/{}/master/".format(
PROJECT_USERAME, PROJECT_NAME
)
|
test = {
'name': 'Problem 5',
'points': 2,
'suites': [
{
'cases': [
{
'code': r"""
>>> abs_diff = lambda w1, w2, limit: abs(len(w2) - len(w1))
>>> autocorrect("cul", ["culture", "cult", "cultivate"], abs_diff, 10)
'cult'
>>> autocorrect("cul", ["culture", "cult", "cultivate"], abs_diff, 0)
'cul'
>>> autocorrect("wor", ["worry", "car", "part"], abs_diff, 10)
'car'
>>> first_diff = lambda w1, w2, limit: 1 if w1[0] != w2[0] else 0
>>> autocorrect("wrod", ["word", "rod"], first_diff, 1)
'word'
>>> autocorrect("inside", ["idea", "inside"], first_diff, 0.5)
'inside'
>>> autocorrect("inside", ["idea", "insider"], first_diff, 0.5)
'idea'
>>> autocorrect("outside", ["idea", "insider"], first_diff, 0.5)
'outside'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> matching_diff = lambda w1, w2, limit: sum([w1[i] != w2[i] for i in range(min(len(w1), len(w2)))]) # Num matching chars
>>> autocorrect("tosting", ["testing", "asking", "fasting"], matching_diff, 10)
'testing'
>>> autocorrect("tsting", ["testing", "rowing"], matching_diff, 10)
'rowing'
>>> autocorrect("bwe", ["awe", "bye"], matching_diff, 10)
'awe'
>>> autocorrect("bwe", ["bye", "awe"], matching_diff, 10)
'bye'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> words_list = sorted(lines_from_file('data/words.txt')[:10000])
>>> autocorrect("testng", words_list, lambda w1, w2, limit: 1, 10)
'a'
>>> autocorrect("testing", words_list, lambda w1, w2, limit: 1, 10)
'testing'
>>> autocorrect("gesting", words_list, lambda w1, w2, limit: sum([w1[i] != w2[i] for i in range(min(len(w1), len(w2)))]) + abs(len(w1) - len(w2)), 10)
'getting'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('statutably', ['statutably'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 5)
'statutably'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('decephalization', ['tautit', 'misorder', 'uptill', 'urostealith', 'cowy', 'sinistrodextral'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 3)
'sinistrodextral'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('hypostasis', ['tinosa'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 0)
'hypostasis'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('indeprivable', ['echeneidid', 'iridiate', 'conjugality', 'convolute', 'momentariness', 'hotelless', 'archon', 'rheotome', 'transformistic'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 6)
'conjugality'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('helena', ['ailment', 'undeclared', 'staphyloplastic', 'ag', 'sulphurless', 'ungrappler', 'ascertainer', 'dormitory', 'zoarial'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 0)
'helena'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('lictorian', ['felineness', 'deontological', 'extraterrestrial', 'experimentalist', 'incomputable'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 0)
'lictorian'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('mousehound', ['unembowelled', 'indigene', 'kersmash', 'mousehound', 'matchmark', 'proportionably', 'persons', 'suprasternal', 'agomphious'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 0)
'mousehound'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('chamfer', ['pretyrannical'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 8)
'pretyrannical'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('locksman', ['coinheritance', 'fourscore', 'naggingly', 'scutelliplantar', 'shiftful', 'prolonger'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 6)
'shiftful'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('nonextensional', ['unlivably', 'error', 'emoloa'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 0)
'nonextensional'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('incavern', ['donnert', 'incavern'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 8)
'incavern'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('disable', ['semiductile', 'microcephalic', 'coauthor', 'whorishness', 'disable'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 8)
'disable'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('antigravitational', ['brad'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 5)
'antigravitational'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('trifurcation', ['trifurcation', 'formative'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 3)
'trifurcation'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('phlogistic', ['mangue', 'lawproof', 'paginary', 'eruption', 'ambrosin', 'tubularly', 'alienee'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 9)
'tubularly'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('psychotic', ['cylinderlike', 'filipendulous'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 2)
'psychotic'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('terpodion', ['terpodion', 'wintertide'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 1)
'terpodion'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('socky', ['childed', 'peoplehood', 'foxwood', 'brachistochronic', 'dentilation', 'luteous'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 1)
'socky'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('wedding', ['mordaciously', 'quinia', 'fixer', 'wedding', 'sendable', 'ainoi'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 7)
'wedding'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('unarrestable', ['unmarring', 'cationic', 'nunhood', 'martyrdom', 'perambulation', 'gaseous'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 3)
'perambulation'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('sprightliness', ['unlimb', 'octamerism', 'antipodist', 'caprinic', 'ringbark', 'suboptimal', 'kingfish', 'amomal'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 0)
'sprightliness'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('veteraness', ['wavement', 'paradoxidian', 'hypergeometrical', 'veteraness', 'purposeful', 'irrigative', 'ultramontanism', 'epephragmal'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 6)
'veteraness'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('hyperphysics', ['thiouracil', 'cibophobia', 'katamorphism', 'trimorphism', 'norie'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 4)
'katamorphism'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('evagation', ['sensationalize', 'stamphead', 'tankmaker', 'becut', 'oenochoe', 'digoneutic', 'refinement', 'tininess', 'benedictively', 'segment'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 5)
'stamphead'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('ashine', ['nonfrustration', 'perineostomy', 'nonupholstered', 'hypocoristically', 'plushlike', 'rancorously'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 2)
'ashine'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('unshameful', ['ger', 'ahoy', 'ventriloquial'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 1)
'unshameful'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('dramatist', ['tournament', 'acclinate', 'rasion'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 8)
'acclinate'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('beewort', ['terrestrious', 'sociometry'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 0)
'beewort'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('claylike', ['houndish', 'muirfowl', 'unexplorative'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 3)
'houndish'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('columbine', ['nonupholstered', 'columbine', 'entoptical', 'spondylolisthetic'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 5)
'columbine'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('owners', ['choledochostomy', 'superobstinate', 'pagoscope'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 0)
'owners'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('tampa', ['commonness', 'incentively', 'courtezanship', 'unapproachableness', 'readvertisement', 'strumiprivous'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 2)
'tampa'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('reaffirmance', ['reaffirmance', 'nursy'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 4)
'reaffirmance'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('photonasty', ['decisively', 'uninclosed', 'chlor'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 6)
'decisively'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('intercepter', ['empiecement'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 7)
'empiecement'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('semideity', ['roundseam', 'misrule', 'cardioblast', 'semideity', 'yaply', 'anthroponomy'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 3)
'semideity'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('served', ['cecomorphic', 'ademption', 'impassibility', 'introvert', 'reintrench', 'transmigratively', 'commerge', 'hematocryal'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 3)
'commerge'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('unliterally', ['vility', 'copellidine', 'creditor', 'parvenuism', 'hindbrain', 'autantitypy', 'sailing', 'dermatoskeleton'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 5)
'copellidine'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('growth', ['assassinator'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 1)
'growth'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('thereabouts', ['quantifiable', 'exterritorial', 'believe', 'untemporal', 'thereabouts'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 0)
'thereabouts'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('goblinism', ['bobby', 'thig', 'plasterwork', 'unhyphenated', 'subessential', 'softhead', 'metrocracy', 'understem'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 5)
'understem'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('resoutive', ['hydroseparation', 'descry', 'apodosis', 'atavist'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 5)
'apodosis'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('unwebbed', ['cramble', 'pseudopopular', 'unwebbed', 'minimize', 'ricinoleate', 'arthrogastran', 'testaceography'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 1)
'unwebbed'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('emphasize', ['putchen'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 0)
'emphasize'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('whapuka', ['seambiter', 'cogman', 'polymorphistic'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 1)
'cogman'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('cubatory', ['byssaceous', 'begins', 'cubatory', 'galvanothermometer', 'appearanced', 'proavian'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 7)
'cubatory'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('singler', ['mycetous', 'singler'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 2)
'singler'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('esquirearchy', ['souper', 'ark', 'niccolite', 'reagin', 'esquirearchy', 'effeminatize'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 7)
'esquirearchy'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('evulse', ['uniocular', 'caution', 'unhoofed', 'misinterpret', 'ooscope', 'physiophilosophy', 'potteringly', 'wartyback'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 0)
'evulse'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('underpopulation', ['adenocarcinomatous', 'soliloquy', 'antispace', 'slimeman', 'cardioncus', 'bin', 'undervalve', 'sundek'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 1)
'underpopulation'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('osteology', ['transphenomenal'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 4)
'osteology'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('solenaceous', ['padding', 'pixel', 'unalimentary', 'dyschroa', 'undefinedly', 'violational', 'bisulfid', 'pralltriller', 'demonstration'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 3)
'undefinedly'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('diabolicalness', ['cronstedtite', 'precipitate', 'undertook', 'unconspicuousness'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 7)
'cronstedtite'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('airworthiness', ['sep'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 9)
'airworthiness'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('pseudomorula', ['toprope', 'doltishly', 'radiotelegraphic'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 1)
'pseudomorula'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('hauld', ['pyrenodean', 'hauld'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 2)
'hauld'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('doll', ['stylolitic', 'altigraph', 'doll', 'avowably', 'manzana', 'galloon'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 2)
'doll'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('rachilla', ['tridentated', 'bridgework', 'coif', 'hitchhike', 'rachilla', 'uptaker', 'penalty', 'commitment', 'supervisor', 'unquartered'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 4)
'rachilla'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('ventriculogram', ['luggie', 'septectomy', 'unproctored', 'volition', 'straked', 'oliver', 'telescopic', 'scarabaeoid'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 2)
'ventriculogram'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('arsonvalization', ['nondisarmament', 'arsonvalization', 'ketyl', 'tussle', 'rhabdomysarcoma'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 0)
'arsonvalization'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('photospectroscopical', ['unenclosed', 'sagacious', 'saur', 'gloveress', 'limbless', 'daresay', 'mysticize'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 8)
'photospectroscopical'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('tupara', ['unkerchiefed', 'dormant', 'triplite', 'bimuscular', 'insider', 'coadjacency', 'unslighted', 'perichordal'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 3)
'dormant'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('odontoglossate', ['odontoglossate', 'conceivableness'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 4)
'odontoglossate'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('retro', ['grayback'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 1)
'retro'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('pung', ['campoo'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 1)
'pung'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('liberal', ['owse', 'ingenerable', 'patrol', 'kenosis', 'wetted'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 6)
'kenosis'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('disclaimer', ['psiloi', 'kusti', 'vallation', 'reprehensive', 'blameworthiness', 'proteiform', 'taintless', 'incruent', 'wednesday', 'codebtor'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 4)
'proteiform'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('orthological', ['consentaneous', 'orthological'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 2)
'orthological'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('amylemia', ['chirotonsory', 'loiter', 'ulnad', 'ticklebrain'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 1)
'amylemia'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('amendableness', ['baked', 'nonpriestly', 'unfavorably', 'amendableness', 'curatorship', 'intermediacy'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 7)
'amendableness'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('gammoning', ['weariedly', 'elongation', 'xanthous', 'squatty', 'dermad', 'iamatology', 'hexachloride', 'womanize', 'favorably'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 8)
'weariedly'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('siliciferous', ['siliciferous'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 5)
'siliciferous'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('patrization', ['deuteropathy', 'pregracile'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 5)
'deuteropathy'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('royetously', ['coster', 'microbiological', 'royetously'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 8)
'royetously'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('unbewritten', ['camphane', 'unbewritten', 'meditationist', 'hydriform'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 8)
'unbewritten'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('searing', ['ultrapapist', 'shriekingly', 'scratchiness', 'searing', 'pot', 'valanche', 'subterraqueous', 'helleboraceous'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 7)
'searing'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('arara', ['synergistically', 'prerecital', 'lozengeways', 'coessentially', 'cubicontravariant', 'snootiness', 'hetaerocracy', 'acaudate', 'simperer'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 5)
'acaudate'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('uptowner', ['hopyard'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 1)
'hopyard'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('presettlement', ['previsit'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 3)
'presettlement'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('soak', ['upside', 'demirevetment', 'undelineated', 'excusative', 'engagingness'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 6)
'upside'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('reduction', ['gym'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 1)
'reduction'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('doctorship', ['peccable', 'jussive', 'doctorship', 'overgladly', 'lurdanism', 'channel', 'malpublication', 'derringer', 'amental'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 9)
'doctorship'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('wintry', ['scyllitol', 'seringhi', 'ditchdown', 'procursive', 'unwholesome', 'unholiday', 'eureka', 'feathertop'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 7)
'eureka'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('transborder', ['conciliative', 'undercoachman', 'phasogeneous', 'philobrutish'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 2)
'conciliative'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('pericycloid', ['viertelein', 'felicitation', 'aortolith', 'nonpresbyter', 'germinable', 'illegibleness', 'undercondition', 'introverted', 'noselessly', 'tramming'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 3)
'introverted'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('indissolvability', ['hotbox', 'tokay', 'palaeofauna', 'indissolvability'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 9)
'indissolvability'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('soubrettish', ['unadvisably', 'unoften', 'unsecreted', 'precessional', 'erosional'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 8)
'unadvisably'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('semiopacity', ['animotheism', 'recoupment', 'juvenescence', 'scalable', 'thai', 'semiopacity'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 1)
'semiopacity'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('penwomanship', ['pyrocondensation', 'spooler', 'archorrhea', 'penwomanship', 'acheirus', 'lieutenant', 'plumless'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 3)
'penwomanship'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('subcordiform', ['subcordiform'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 7)
'subcordiform'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('quarrelsomely', ['concert', 'canonics', 'hip', 'uncrested', 'ectoethmoid', 'supertutelary', 'ignore'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 6)
'supertutelary'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('ditchdown', ['gonapophysis', 'permeability'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 1)
'ditchdown'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('suborbiculate', ['prisonable', 'rhapsodist', 'suborbiculate'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 9)
'suborbiculate'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('quiesce', ['synedria', 'apesthesia', 'squawbush', 'devourer', 'tetany', 'quiesce'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 7)
'quiesce'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('shiv', ['unconceivableness', 'inappetence'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 6)
'shiv'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('shuttleheaded', ['uterovaginal', 'extraparochially', 'serolipase'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 0)
'shuttleheaded'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('hilarity', ['valorously', 'hilarity', 'fungilliform', 'haven', 'torsk', 'thing', 'pickerel', 'refilm'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 4)
'hilarity'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('prefunctional', ['kep'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 2)
'prefunctional'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('oxypurine', ['overpensiveness', 'overindustrialize', 'lightweight', 'provinciality', 'telestereoscope', 'vastidity'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 0)
'vastidity'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> autocorrect('forewarningly', ['foxery'], lambda x, y, lim: min(lim + 1, abs(len(x) - len(y))), 9)
'foxery'
""",
'hidden': False,
'locked': False
}
],
'scored': True,
'setup': r"""
>>> from typing import autocorrect, lines_from_file
""",
'teardown': '',
'type': 'doctest'
}
]
}
|
# puzzle3a.py
def main():
calc_slope(1, 1)
calc_slope(3, 1)
calc_slope(5, 1)
calc_slope(7, 1)
calc_slope(1, 2)
def calc_slope(horiz_step = 3, vert_step = 1):
tree_char = "#"
horiz_pos = 0
trees = 0
input_file = open("input.txt", "r")
lines = input_file.readlines()
line_len = len(lines[0]) - 1 # Subtract 1 to account for '\n'
lines = lines[vert_step::vert_step]
for line in lines:
horiz_pos = (horiz_pos + horiz_step) % line_len
if line[horiz_pos] == tree_char:
trees += 1
print("Trees encountered: " + str(trees))
return trees
if __name__ == "__main__":
main() |
"""Exceptions that pertain to Flashcards-level functionality."""
class FlashCardsError(Exception):
"""Base class for other Flashcards-level exceptions."""
def __init__(self, message: str) -> None:
super().__init__(f"Flashcards Error: {message}")
class InvalidConfiguration(FlashCardsError):
"""Something was attempted that is not possible for the current configuration."""
def __init__(self, message: str) -> None:
super().__init__(f"Invalid configuration: {message}")
class MediaPlayerError(FlashCardsError):
"""Something bad happened in / with the media player"""
|
#
# PySNMP MIB module RADLAN-AGGREGATEVLAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-AGGREGATEVLAN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:45:06 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")
ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection")
InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex")
rnd, = mibBuilder.importSymbols("RADLAN-MIB", "rnd")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
MibIdentifier, Unsigned32, Integer32, ModuleIdentity, NotificationType, Bits, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, IpAddress, iso, Counter64, TimeTicks, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Unsigned32", "Integer32", "ModuleIdentity", "NotificationType", "Bits", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "IpAddress", "iso", "Counter64", "TimeTicks", "ObjectIdentity")
RowStatus, TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TextualConvention", "DisplayString")
rlAggregateVlan = ModuleIdentity((1, 3, 6, 1, 4, 1, 89, 73))
rlAggregateVlan.setRevisions(('2007-01-02 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: rlAggregateVlan.setRevisionsDescriptions(('Initial revision.',))
if mibBuilder.loadTexts: rlAggregateVlan.setLastUpdated('200701020000Z')
if mibBuilder.loadTexts: rlAggregateVlan.setOrganization('Radlan - a MARVELL company. Marvell Semiconductor, Inc.')
if mibBuilder.loadTexts: rlAggregateVlan.setContactInfo('www.marvell.com')
if mibBuilder.loadTexts: rlAggregateVlan.setDescription('This private MIB module defines Aggregate Vlan private MIBs.')
rlAggregateVlanMibVersion = MibScalar((1, 3, 6, 1, 4, 1, 89, 73, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlAggregateVlanMibVersion.setStatus('current')
if mibBuilder.loadTexts: rlAggregateVlanMibVersion.setDescription("MIB's version, the current version is 1.")
rlAggregateVlanTable = MibTable((1, 3, 6, 1, 4, 1, 89, 73, 2), )
if mibBuilder.loadTexts: rlAggregateVlanTable.setStatus('current')
if mibBuilder.loadTexts: rlAggregateVlanTable.setDescription('The table creates an aggregateVlans, the IfIndex is from 10000')
rlAggregateVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 89, 73, 2, 1), ).setIndexNames((0, "RADLAN-AGGREGATEVLAN-MIB", "rlAggregateVlanIndex"))
if mibBuilder.loadTexts: rlAggregateVlanEntry.setStatus('current')
if mibBuilder.loadTexts: rlAggregateVlanEntry.setDescription('The row definition for this table.')
rlAggregateVlanIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 73, 2, 1, 1), InterfaceIndex())
if mibBuilder.loadTexts: rlAggregateVlanIndex.setStatus('current')
if mibBuilder.loadTexts: rlAggregateVlanIndex.setDescription('This index indicate the aggrigateVlan id, the aggregate vlan index is starting from 10000 ')
rlAggregateVlanName = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 73, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rlAggregateVlanName.setStatus('current')
if mibBuilder.loadTexts: rlAggregateVlanName.setDescription('The name of the aggregateVlan ')
rlAggregateVlanPhysAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 73, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("default", 1), ("reserve", 2))).clone('default')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rlAggregateVlanPhysAddressType.setStatus('current')
if mibBuilder.loadTexts: rlAggregateVlanPhysAddressType.setDescription(' This variable indicates whether the physical address assigned to this VLAN should be the default one or be chosen from the set of reserved physical addresses of the device.')
rlAggregateVlanStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 73, 2, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rlAggregateVlanStatus.setStatus('current')
if mibBuilder.loadTexts: rlAggregateVlanStatus.setDescription("The status of the aggregateVlan table entry. It's used to delete an entry")
rlAggregateSubVlanTable = MibTable((1, 3, 6, 1, 4, 1, 89, 73, 3), )
if mibBuilder.loadTexts: rlAggregateSubVlanTable.setStatus('current')
if mibBuilder.loadTexts: rlAggregateSubVlanTable.setDescription('The table indicates all the allocated sub-vlans to the aggregateVlans, an entry in the rlAggregateVlanTable must be exist before allocating the subVlans')
rlAggregateSubVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 89, 73, 3, 1), ).setIndexNames((0, "RADLAN-AGGREGATEVLAN-MIB", "rlAggregateVlanIndex"), (0, "RADLAN-AGGREGATEVLAN-MIB", "rlAggregateSubVlanIfIndex"))
if mibBuilder.loadTexts: rlAggregateSubVlanEntry.setStatus('current')
if mibBuilder.loadTexts: rlAggregateSubVlanEntry.setDescription('The row definition for this table.')
rlAggregateSubVlanIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 73, 3, 1, 1), InterfaceIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlAggregateSubVlanIfIndex.setStatus('current')
if mibBuilder.loadTexts: rlAggregateSubVlanIfIndex.setDescription('Indicate the subVlan that allocated to the aggregate vlan')
rlAggregateSubVlanStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 73, 3, 1, 2), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rlAggregateSubVlanStatus.setStatus('current')
if mibBuilder.loadTexts: rlAggregateSubVlanStatus.setDescription("The status of the aggregateSubVlan table entry. It's used to delete an entry")
rlAggregateVlanArpProxy = MibScalar((1, 3, 6, 1, 4, 1, 89, 73, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlAggregateVlanArpProxy.setStatus('current')
if mibBuilder.loadTexts: rlAggregateVlanArpProxy.setDescription('When ARP Proxy is enabled, the router can respond to ARP requests for nodes located on different sub-vlans, which belong to the same Super VLAN.The router responds with its own MAC address. When ARP Proxy is disabled, the router responds only to ARP requests for its own IP addresses.')
mibBuilder.exportSymbols("RADLAN-AGGREGATEVLAN-MIB", rlAggregateVlanName=rlAggregateVlanName, rlAggregateVlan=rlAggregateVlan, rlAggregateSubVlanTable=rlAggregateSubVlanTable, PYSNMP_MODULE_ID=rlAggregateVlan, rlAggregateVlanIndex=rlAggregateVlanIndex, rlAggregateSubVlanEntry=rlAggregateSubVlanEntry, rlAggregateVlanEntry=rlAggregateVlanEntry, rlAggregateVlanArpProxy=rlAggregateVlanArpProxy, rlAggregateVlanTable=rlAggregateVlanTable, rlAggregateSubVlanStatus=rlAggregateSubVlanStatus, rlAggregateSubVlanIfIndex=rlAggregateSubVlanIfIndex, rlAggregateVlanPhysAddressType=rlAggregateVlanPhysAddressType, rlAggregateVlanStatus=rlAggregateVlanStatus, rlAggregateVlanMibVersion=rlAggregateVlanMibVersion)
|
# Title : Url shortner
# Author : Kiran Raj R.
# Date : 07:11:2020
class URL_short:
url_id = 0
url_dict = {}
def url_shortner(self,orginal_url):
if orginal_url in self.url_dict:
url = self.url_dict[orginal_url]
return f"{orginal_url} already has a shorten url: my_url.com/{url}"
else:
url = str(hex(self.url_id))
# print(url)
self.url_dict[orginal_url] = url
self.url_id+=1
return f"my_url.com/{url}"
def return_site(self,short_url):
url = short_url.split('/')[1]
site = [key for key,value in self.url_dict.items() if value == url]
if site == []:
return f"{short_url} not found!!!"
else:
return site[0]
url_obj = URL_short()
site1 = url_obj.url_shortner('google.com')
site2 = url_obj.url_shortner('facebook.com')
site3 = url_obj.url_shortner('instagram.com')
site4 = url_obj.url_shortner('facebook.com')
# print(site1, site2, site3, site4)
# print(url_obj.url_dict)
print(url_obj.return_site('my_url.com/0x1'))
print(url_obj.return_site('my_url.com/0x21'))
print(site4) |
# Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra "A",
# em que posição ela aparece a primeira vez e em que posição ela aparece a última vez.
text = input('Digite uma frase:').strip().upper()
print('Quantidade de letras "A":', text.count('A'))
print('Primeira aparição:', text.find('A')+1)
print('Última aparição:', text.rfind('A')+1)
|
"""
Exceptions raised by cli-toolkit
"""
class ScriptError(Exception):
"""
Errors raise during script processing
"""
|
def snake_to_camel(s):
"""
>>> snake_to_camel('snake_to_camel')
'snakeToCamel'
"""
pass
|
# -*- coding: utf-8 -*-
__title__ = 'gym_breakout_pygame'
__description__ = 'Gym Breakout environment using Pygame'
__url__ = 'https://github.com/whitemech/gym-breakout-pygame.git'
__version__ = '0.1.1'
__author__ = 'Marco Favorito, Luca Iocchi'
__author_email__ = 'favorito@diag.uniroma1.it, iocchi@diag.uniroma1.it'
__license__ = 'Apache License 2.0'
__copyright__ = '2019 Marco Favorito, Luca Iocchi'
|
def numUniqueEmails(self, emails):
"""
:type emails: List[str]
:rtype: int
"""
email_set = set()
for i in emails:
email = i.split("@")
local = email[0].replace(".", "")
locate_plus = local.find("+")
if locate_plus != -1:
email_set.add(local[:locate_plus] + "@" + email[1])
else:
email_set.add(local + "@" + email[1])
return len(email_set)
#Less efficient
# hash_map = {}
# for i in emails:
# locate_at = i.find("@")
# local = get_rid_periods(i[:locate_at])
# locate_plus = local.find("+")
# if locate_plus != -1 and locate_plus < locate_at:
# email = local[:locate_plus] + i[locate_at:]
# if email not in hash_map:
# hash_map[email] = 0
# else:
# pass
# else:
# email = local + i[locate_at:]
# if email not in hash_map:
# hash_map[email] = 0
# else:
# pass
# return len(hash_map)
# def get_rid_periods(local_name):
# return "".join([i for i in local_name if i != "."])
Input = ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]
# Output: 2
# Explanation: "testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails |
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l = len(nums)
sum = (0 + l) * (l + 1) / 2
for n in nums:
sum -= n
return sum
|
class ContactList(list):
def search(self, name):
"""Return all contacts that contain the search value in their name"""
matching_contact = []
for contact in self:
if name in contact.name:
matching_contact.append(contact)
return matching_contact
|
# MOOC-Python Task
# takuron@github
def lcm(n1,n2) :
maxx = 0
if n1>=n2:
maxx = n1
else:
maxx = n2
i = 0
while 1 :
i = i+1
if ((maxx+i)%n1==0) and ((maxx+i)%n2==0):
return maxx+i
num1=int(input(""))
num2=int(input(""))
print(lcm(num1,num2)) |
# The marketing team is spending way too much time typing in hashtags.
# Let's help them with our own Hashtag Generator!
#
# Here's the deal:
#
# It must start with a hashtag (#).
# All words must have their first letter capitalized.
# If the final result is longer than 140 chars it must return false.
# If the input or the result is an empty string it must return false.
# Examples
# " Hello there thanks for trying my Kata" => "#HelloThereThanksForTryingMyKata"
# " Hello World " => "#HelloWorld"
# "" => false
def generate_hashtag(s):
output_str = ''
first_letter = True
if not s:
return False
output_str = output_str + "#"
for x in s:
if first_letter and x != ' ':
output_str += x.upper()
first_letter = False
elif x != ' ':
output_str += x.lower()
else:
first_letter = True
if len(output_str) > 140:
return False
else:
return output_str
|
#
# 1520. Maximum Number of Non-Overlapping Substrings
#
# Q: https://leetcode.com/problems/maximum-number-of-non-overlapping-substrings/
# A: https://leetcode.com/problems/maximum-number-of-non-overlapping-substrings/discuss/749421/Javascript-Python3-C%2B%2B-beginend-index-%2B-greedy-consumption
#
class Solution:
def maxNumOfSubstrings(self, s: str) -> List[str]:
ans = []
# 1. track the begin index and end index of each character
beg = { c: s.index(c) for c in set(s) }
end = { c: s.rindex(c) for c in set(s) }
# 2. update the min begin index and max end index for each unique character candidate
seen = set()
for cand in s:
if cand in seen:
continue
seen.add(cand)
i, j = beg[cand], end[cand]
mini, maxj = i, j
while i <= maxj:
c = s[i]
mini = min(mini, beg[c])
maxj = max(maxj, end[c])
i += 1
beg[cand], end[cand] = mini, maxj
# 3. sort the intervals by end index for greedy consumption of non-overlapping intervals
A = sorted(seen, key = lambda c: end[c])
pre = -1 # end index inclusive of previous interval
for cand in A:
i = beg[cand]
j = end[cand]
if pre < i: # non-overlapping interval
ans.append(s[i : j + 1]) # 🎯 +1 for i..j inclusive
pre = j
return ans
|
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n < 1:
return False
if n == 1:
return True
if sum(list(map(int, str(n)))) % 3 != 0:
return False
else:
while n > 1:
if n % 3 == 0:
n /= 3
else:
return False
if n != 1:
return False
else:
return True
# Alternate Approach
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n < 1:
return False
else:
return 1162261467 % n == 0
|
"""Static Token And Credential Scanner CI integrations.
SPDX-License-Identifier: BSD-3-Clause
"""
__title__ = "stacs-ci"
__summary__ = "Static Token And Credential Scanner CI Integrations."
__version__ = "0.1.6"
__author__ = "Peter Adkins"
__uri__ = "https://www.github.com/stacscan/stacs-integration/"
__license__ = "BSD-3-Clause"
|
def bubble_sort(items):
for i in range(len(items)):
for j in range(len(items)-1-i):
if items[j] > items[j+1]:
items[j], items[j+1] = items[j+1], items[j]
def f(n): #bubble sort worst case
bubble_sort(range(n,0,-1)) |
"""
Global information to be used by the module.
"""
class Question:
q_p_id: int
q_id: str
q_text: str
q_answer: str
q_a: str
q_b: str
q_c: str
q_d: str
def __init__(
self,
q_p_id,
q_id,
q_text,
q_answer,
q_a,
q_b,
q_c,
q_d,
):
self.q_p_id = q_p_id
self.q_id = q_id
self.q_text = q_text
self.q_answer = q_answer
self.q_a = q_a
self.q_b = q_b
self.q_c = q_c
self.q_d = q_d
def __str__(self):
temp = f" Pool ID: {self.q_p_id}\n"
temp = f"{temp}Question ID: {self.q_id}\n"
temp = f"{temp} Text: {self.q_text}\n"
temp = f"{temp}Answer: {self.q_answer}\n"
temp = f"{temp} A: {self.q_a}\n"
temp = f"{temp} B: {self.q_b}\n"
temp = f"{temp} C: {self.q_c}\n"
temp = f"{temp} D: {self.q_d}"
return temp
|
a = 'C:\\Users\\Jason\\Documents\\GitHub\\chesspdftofen\\data\\out\\yasser\\WhiteQueen'
l = []
for e in sorted(os.listdir(a)):
i = cv2.imread(os.path.join(a, e), 0)
h,w = i.shape
# l.append([np.sum(i[h//4:h//4*3, w//4:w//4*3]), e])
l.append([np.sum(i), e])
l.sort()
print(l)
for i, k in enumerate(l):
# aa = k[1].find('_')
# bb = k[1][aa:]
# os.rename(os.path.join(a, k[1]), os.path.join(a, str(i) + bb))
os.rename(os.path.join(a, k[1]), os.path.join(a, ('%06d_' % (i,)) + '_' + k[1])) |
'''
Created on Sep 3, 2010
@author: ilg
'''
class WriterBase(object):
'''
classdocs
'''
def __init__(self, sName):
'''
Constructor
'''
self.bVerbose = False
self.sName = sName
self.sLocalUrl = None
pass
def setVerbose(self, bVerbose):
self.bVerbose = bVerbose
def setUserUrl(self, sUrl):
self.sUserUrl = sUrl
def setLocalUrl(self, sUrl):
self.sLocalUrl = sUrl
def setOutputStream(self, oOutStream):
self.oOutStream = oOutStream
def setHierarchicalDepth(self, s):
self.sHierarchicalDepth = s
def setCollection(self, sID, sTitle, sDescription, sSmallIcon, sLargeIcon):
self.sCollectionID = sID
self.sCollectionTitle = sTitle
self.sCollectionDescription = sDescription
self.sCollectionSmallIcon = sSmallIcon
self.sCollectionLargeIcon = sLargeIcon
def setStatistics(self, nCollections, nSets, nPhotos):
self.nCollections = nCollections
self.nSets = nSets
self.nPhotos = nPhotos
def setPhotoset(self, sID, sTitle, sDescription, nPhotos, sIcon):
self.sPhotosetID = sID
self.sPhotosetTitle = sTitle
self.sPhotosetDescription = sDescription
self.nPhotosetPhotos = nPhotos
self.sPhotosetIcon = sIcon
def setDepth(self, nDepth):
self.nDepth = nDepth
self.sIndent = ''
for i in range(1, self.nDepth): #@UnusedVariable
self.sIndent += '\t'
def incDepth(self):
self.setDepth(self.nDepth+1)
def decDepth(self):
self.setDepth(self.nDepth-1)
def writeBegin(self):
return
def writeEnd(self):
return
def writeHeaderBegin(self):
return
def writeHeaderEnd(self):
return
def writeCollectionBegin(self):
return
def writeEmbeddedBegin(self):
return
def writeEmbeddedEnd(self):
return
def writeCollectionEnd(self):
return
def writePhotosetBegin(self):
return
def writePhotosetEnd(self):
return
|
def process_old_format(self, cg_resources_requirements):
"""
Old format is njs,request_cpu=1,request_memory=1,request_disk=1,request_color=blue
Regex is assumed to be true
:param cg_resources_requirements:
:return:
"""
cg_res_req_split = cg_resources_requirements.split(",") # List
# Access and remove clientgroup from the statement
client_group = cg_res_req_split.pop(0)
requirements = dict()
for item in cg_res_req_split:
(req, value) = item.split("=")
requirements[req] = value
# Set up default resources
resources = self.get_default_resources(client_group)
if client_group is None or client_group is "":
client_group = resources[self.CG]
requirements_statement = []
for key, value in requirements.items():
if key in resources:
# Overwrite the resources with catalog entries
resources[key] = value
else:
# Otherwise add it to the requirements statement
requirements_statement.append(f"{key}={value}")
# Delete special keys
print(resources)
print(requirements)
del requirements[self.REQUEST_MEMORY]
del requirements[self.REQUEST_CPUS]
del requirements[self.REQUEST_DISK]
# Set the clientgroup just in case it was blank
# Add clientgroup to resources because it is special
# Regex is enabled by default
cge = f'regexp("{client_group}",CLIENTGROUP)'
requirements_statement.append(cge)
rv = dict()
rv[self.CG] = client_group
rv["client_group_expression"] = cge
rv["requirements"] = "".join(requirements_statement)
rv["requirements_statement"] = cge
for key, value in resources.items():
rv[key] = value
return rv
def process_new_format(self, client_group_and_requirements):
"""
New format is {'client_group' : 'njs', 'request_cpu' : 1, 'request_disk' :
:param client_group_and_requirements:
:return:
"""
reqs = json.loads(client_group_and_requirements)
def generate_requirements(self, cg_resources_requirements):
print(cg_resources_requirements)
if "{" in cg_resources_requirements:
reqs = self.process_new_format(cg_resources_requirements)
else:
reqs = self.process_old_format(cg_resources_requirements)
self.check_for_missing_requirements(reqs)
return self.resource_requirements(
request_cpus=reqs["request_cpus"],
request_disk=reqs["request_disk"],
request_memory=reqs["request_memory"],
requirements_statement=reqs["requirements"],
)
return r
@staticmethod
def check_for_missing_requirements(requirements):
for item in (
"client_group_expression",
"request_cpus",
"request_disk",
"request_memory",
):
if item not in requirements:
raise MissingCondorRequirementsException(
f"{item} not found in requirements"
)
def _process_requirements_new_format(self, requirements):
requirements = dict()
cg = requirements.get("client_group", "")
if cg is "":
# requirements[
if bool(requirements.get("regex", False)) is True:
cg["client_group_requirement"] = f'regexp("{cg}",CLIENTGROUP)'
else:
cg["client_group_requirement"] = f"+CLIENTGROUP == {client_group} "
|
"""
Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email that is common to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.
Example 1:
Input:
accounts = [["John", "johnsmith@mail.com", "john00@mail.com"], ["John", "johnnybravo@mail.com"], ["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["Mary", "mary@mail.com"]]
Output: [["John", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'], ["John", "johnnybravo@mail.com"], ["Mary", "mary@mail.com"]]
Explanation:
The first and third John's are the same person as they have the common email "johnsmith@mail.com".
The second John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'],
['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.
Note:
The length of accounts will be in the range [1, 1000].
The length of accounts[i] will be in the range [1, 10].
The length of accounts[i][j] will be in the range [1, 30].
"""
class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
def get_connections(accounts):
track = {}
emails = {}
for i, acc in enumerate(accounts):
if i not in track:
track[i] = []
for j, email in enumerate(acc):
if j == 0:
continue
if email not in emails:
emails[email] = []
for k in emails[email]:
if k not in track:
track[k] = []
track[k].append(i)
track[i].append(k)
emails[email].append(i)
return track
track = get_connections(accounts)
visited = set()
parts = []
for i, acc in enumerate(accounts):
if i in visited:
continue
part = []
stack = [i]
while stack:
curr = stack.pop()
if curr in visited:
continue
visited.add(curr)
part.append(curr)
for ne in track.get(curr, []):
if ne in visited:
continue
stack.append(ne)
parts.append(part)
ret = []
for part in parts:
name = accounts[part[0]][0]
acc = set()
for pp in part:
acc = acc.union(set(accounts[pp][1:]))
ret.append([name] + sorted(acc))
return ret |
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
n = len(prices)
if n == 1:
return 0
dp = [0 for i in range(n + 1)]
tmpmin = prices[0]
for i in range(1, n + 1):
tmpmin = min(tmpmin, prices[i - 1])
tmpres = prices[i - 1] - tmpmin
dp[i] = max(tmpres, dp[i - 1])
return dp[-1]
a = Solution()
a.maxProfit([7, 1, 5, 3, 6, 4])
|
class Solution:
def calculateTime(self, keyboard: str, word: str) -> int:
positions = {key : i for i, key in enumerate(keyboard)}
n = len(word)
ans = 0
for i in range(1, n):
ans += abs(positions[word[i]] - positions[word[i - 1]])
return ans + positions[word[0]]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Utility functions.
"""
def _check_columns(df_to_check, cols) -> None:
"""Check that a list of required column names is in a data frame
Args:
df_to_check: A DataFrame to check columns on.
cols (Iterable[str]): Required columns.
Returns:
None
Raises:
ValueError: if required cols are not a subset of column names in
``df_to_check``.
Examples:
>> df = pd.DataFrame({'col_a': [1,2], 'col_b': [2,4]})
>> check_columns(df, ['col_c'])
ValueError: Missing columns: `{col_c}`
"""
if isinstance(cols, str):
cols = [cols]
if not set(cols).issubset(df_to_check.columns):
missing_cols = set(cols).difference(df_to_check.columns)
raise ValueError(f"Missing columns: `{missing_cols}`.")
return None
|
# -*- coding: utf-8 -*-
"""
neutrino_api
This file was automatically generated for NeutrinoAPI by APIMATIC v2.0 ( https://apimatic.io ).
"""
class BrowserBotResponse(object):
"""Implementation of the 'Browser Bot Response' model.
TODO: type model description here.
Attributes:
url (string): The page URL
content (string): The complete raw, decompressed and decoded page
content. Usually will be either HTML, JSON or XML
mime_type (string): The document MIME type
title (string): The document title
is_error (bool): True if an error has occurred loading the page. Check
the 'error-message' field for details
is_timeout (bool): True if a timeout occurred while loading the page.
You can set the timeout with the request parameter 'timeout'
error_message (string): Contains the error message if an error has
occurred ('is-error' will be true)
http_status_code (int): The HTTP status code the URL returned
http_status_message (string): The HTTP status message the URL
returned
is_http_ok (bool): True if the HTTP status is OK (200)
is_http_redirect (bool): True if the URL responded with an HTTP
redirect
http_redirect_url (string): The redirected URL if the URL responded
with an HTTP redirect
server_ip (string): The HTTP servers IP address
load_time (int): The number of seconds taken to load the page (from
initial request until DOM ready)
response_headers (dict<object, string>): Map containing all the HTTP
response headers the URL responded with
is_secure (bool): True if the page is secured using TLS/SSL
security_details (dict<object, string>): Map containing details of the
TLS/SSL setup
elements (list of string): Array containing all the elements matching
the supplied selector. Each element object will contain the text
content, HTML content and all current element attributes
exec_results (list of string): If you executed any JavaScript this
array holds the results as objects
"""
# Create a mapping from Model property names to API property names
_names = {
"url":'url',
"content":'content',
"mime_type":'mimeType',
"title":'title',
"is_error":'isError',
"is_timeout":'isTimeout',
"error_message":'errorMessage',
"http_status_code":'httpStatusCode',
"http_status_message":'httpStatusMessage',
"is_http_ok":'isHttpOk',
"is_http_redirect":'isHttpRedirect',
"http_redirect_url":'httpRedirectUrl',
"server_ip":'serverIp',
"load_time":'loadTime',
"response_headers":'responseHeaders',
"is_secure":'isSecure',
"security_details":'securityDetails',
"elements":'elements',
"exec_results":'execResults'
}
def __init__(self,
url=None,
content=None,
mime_type=None,
title=None,
is_error=None,
is_timeout=None,
error_message=None,
http_status_code=None,
http_status_message=None,
is_http_ok=None,
is_http_redirect=None,
http_redirect_url=None,
server_ip=None,
load_time=None,
response_headers=None,
is_secure=None,
security_details=None,
elements=None,
exec_results=None):
"""Constructor for the BrowserBotResponse class"""
# Initialize members of the class
self.url = url
self.content = content
self.mime_type = mime_type
self.title = title
self.is_error = is_error
self.is_timeout = is_timeout
self.error_message = error_message
self.http_status_code = http_status_code
self.http_status_message = http_status_message
self.is_http_ok = is_http_ok
self.is_http_redirect = is_http_redirect
self.http_redirect_url = http_redirect_url
self.server_ip = server_ip
self.load_time = load_time
self.response_headers = response_headers
self.is_secure = is_secure
self.security_details = security_details
self.elements = elements
self.exec_results = exec_results
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
url = dictionary.get('url')
content = dictionary.get('content')
mime_type = dictionary.get('mimeType')
title = dictionary.get('title')
is_error = dictionary.get('isError')
is_timeout = dictionary.get('isTimeout')
error_message = dictionary.get('errorMessage')
http_status_code = dictionary.get('httpStatusCode')
http_status_message = dictionary.get('httpStatusMessage')
is_http_ok = dictionary.get('isHttpOk')
is_http_redirect = dictionary.get('isHttpRedirect')
http_redirect_url = dictionary.get('httpRedirectUrl')
server_ip = dictionary.get('serverIp')
load_time = dictionary.get('loadTime')
response_headers = dictionary.get('responseHeaders')
is_secure = dictionary.get('isSecure')
security_details = dictionary.get('securityDetails')
elements = dictionary.get('elements')
exec_results = dictionary.get('execResults')
# Return an object of this model
return cls(url,
content,
mime_type,
title,
is_error,
is_timeout,
error_message,
http_status_code,
http_status_message,
is_http_ok,
is_http_redirect,
http_redirect_url,
server_ip,
load_time,
response_headers,
is_secure,
security_details,
elements,
exec_results)
|
# Exercício Python 056
# Leia nome, idade e sexo de quatro pessoas. Mostre:
# média de idade, qual é o nome do homem mais velho, quantas mulheres tem menos de 20 anos
maisvelho = ''
maior = 0
somaIdade = 0
somaMulheres = 0
for c in range(0,4):
nome = str(input('Nome: ')).strip
idade = int(input('Idade: '))
sexo = str(input('Sexo (F) ou (M): ')).upper().strip
somaIdade = somaIdade + idade
if sexo == 'M':
if idade > maior:
maior = idade
maisvelho = nome
if sexo == 'F':
if idade < 20:
somaMulheres = somaMulheres +1
print('A média de idade é {:.2f}.'.format(somaIdade / 4))
print('O homem mais velho é o {}.'.format(maisvelho))
print('Existe(m) {} mulher(es) com menos de 20 anos.'.format(somaMulheres)) |
'''
Nesse problema você deverá descobrir se um conjunto de diversas palavras é bom ou ruim. Por definição, um conjunto é bom quando nenhuma palavra desse conjunto é um prefixo de uma outra palavra. Caso contrário, este é considerado um conjunto ruim.
Por exemplo, {abc, dae, abcde} é um conjunto ruim, pois abc é um prefixo de abcde. Quando duas palavras são iguais, definimos como uma sendo prefixo da outra.
Entrada
A entrada contém vários casos de teste. A primeira linha de cada caso de teste terá um inteiro N (1 ≤ N ≤ 10⁵), representando a quantidade de palavras no conjunto. Segue então N linhas, cada uma tendo uma palavra de no máximo 100 letras minúsculas. A entrada termina quando N = 0 e não deve ser processada.
Saída
Para cada caso de teste, você deverá imprimir Conjunto Bom, ou Conjunto Ruim, conforme explicado acima.
'''
def teste(conjunto):
prefixos = []
prefixos = [i for i in conjunto if not i in prefixos]
for i in prefixos:
tamanho_prefixo = len(i)
conjunto.remove(i)
for c in conjunto:
if i in c[:tamanho_prefixo]:
return 'Conjunto Ruim'
conjunto.append(i)
return 'Conjunto Bom'
while True:
conjunto = []
N = int(input())
if N == 0:
break
for _ in range(N):
conjunto.append(input())
conjunto = sorted(conjunto, key = lambda i: len(i))
validador = teste(conjunto)
print(validador) |
numbers = [0, 1, 2, 3, 4]
doubled_numbers = []
for num in numbers:
doubled_numbers.append(num * 2)
print(doubled_numbers)
# -- List comprehension --
numbers = [0, 1, 2, 3, 4] # list(range(5)) is better
doubled_numbers = [num * 2 for num in numbers]
# [num * 2 for num in range(5)] would be even better.
print(doubled_numbers)
# -- You can add anything to the new list --
friend_ages = [22, 31, 35, 37]
age_strings = [f"My friend is {age} years old." for age in friend_ages]
print(age_strings)
# -- This includes things like --
names = ["Rolf", "Bob", "Jen"]
lower = [name.lower() for name in names]
# That is particularly useful for working with user input.
# By turning everything to lowercase, it's less likely we'll miss a match.
friend = input("Enter your friend name: ")
friends = ["Rolf", "Bob", "Jen", "Charlie", "Anne"]
friends_lower = [name.lower() for name in friends]
if friend.lower() in friends_lower:
print(f"I know {friend}!")
|
# É possível digitar listas dentro de lista
galera = [["João", 44], ["Ana", 18], ["Pedro", 29]]
print(galera[1][0])
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
generator用到的工具函数
"""
def get_trigger_event(s, is_delay=False):
"""
获取触发事件
"""
# 取第一个event term
for t in s.terms:
if t.left.type == 'event':
if is_delay:
new = t.left.event[:]
new[-1] = new[-1] + '_DELAY'
return new
return t.left.event
def get_dimension_from_trigger_keys(trigger_keys):
"""
从触发字段中判断维度
:param trigger_keys:
:return:
"""
if 'uid' in trigger_keys:
return 'uid'
if 'did' in trigger_keys:
return 'did'
# ip by default
return 'ip'
def get_field_from_dimension(dimension):
if dimension == 'uid':
return 'uid'
elif dimension == 'did':
return 'did'
else:
return 'c_ip'
|
# internal library
def ceil_pow2(n):
x = 0
while((1 << x) < n):
x += 1
return x
# internal library end
class segtree:
def __init__(self, op, e, n=0, ary=[]):
self.op = op
self.e = e
if n:
ary = [e()] * n
else:
n = len(ary)
self.n = n
self.log = ceil_pow2(n)
self.size = 1 << self.log
self.d = [e()] * (2 * self.size)
for i in range(n):
self.d[self.size + i] = ary[i]
for i in reversed(range(1, self.size)):
self.update(i)
def set(self, p, x):
p += self.size
self.d[p] = x
for i in range(1, self.log + 1):
self.update(p >> i)
def get(self, p):
return self.d[p + self.size]
def prod(self, l, r):
sml = self.e()
smr = self.e()
l += self.size
r += self.size
while l < r:
if l & 1:
sml = self.op(sml, self.d[l])
l += 1
if r & 1:
r -= 1
smr = self.op(self.d[r], smr)
l >>= 1
r >>= 1
return self.op(sml, smr)
def all_prod(self):
return self.d[1]
def max_right(self, l, f):
if l == self.n:
return self.n
l += self.size
sm = self.e()
while 1:
while l % 2 == 0:
l >>= 1
if f(self.op(sm, self.d[l])) == 0:
while l < self.size:
l *= 2
if f(self.op(sm, self.d[l])):
sm = self.op(sm, self.d[l])
l += 1
return l - self.size
sm = self.op(sm, self.d[l])
l += 1
if (l & -l) == l:
break
return self.n
def min_left(self, r, f):
assert(0 <= r and r < self.n)
if r == 0:
return 0
r += self.size
sm = self.e()
while 1:
r -= 1
while r > 1 and (r & 1):
r >>= 1
if not f(self.op(self.d[r], sm)):
while r < self.size:
if f(self.op(self.d[r], sm)):
sm = self.op(sm, self.d[r])
r -= 1
return r + 1 - self.size
sm = self.op(self.d[r], sm)
if (r & -r) == r:
break
return 0
def update(self, k):
self.d[k] = self.op(self.d[2 * k], self.d[2 * k + 1]) |
class CompatibilityResult(object):
def __init__(self, mergerule, incompatible_rule_class_names=[]):
"""
:param mergerule: MergeRule
:param incompatible_rule_class_names: list of strings
"""
self._mergerule = mergerule
self._incompatible_rule_class_names = incompatible_rule_class_names
def rule(self):
return self._mergerule
def rule_class_name(self):
return self._mergerule.get_rule_class_name()
def is_compatible(self):
return len(self._incompatible_rule_class_names) > 0
def incompatible_rule_class_names(self):
return set(self._incompatible_rule_class_names)
|
class User:
# Class Attribute
active_users = 0
#class Methods
@classmethod
def display_active(cls):
return f"Total Active users are {cls.active_users}"
def __init__(self,first_name,last_name,age):
# instance Attribute/Variable
self.first_name = first_name
self.last_name = last_name
self.age = age
User.active_users += 1
# Instance method
def fullName(self):
return f"{self.first_name} {self.last_name}"
def initials(self):
return f"{self.first_name[0]}.{self.last_name[0]}."
def likes(self,thing):
return f"{self.first_name} likes {thing}"
def isSenior(self):
return (self.age > 65)
print('Active Users',User.active_users)
p = User('Qaidjohar','Jawadwala',70)
q = User('Mustafa','Poona',25)
print('Active Users',User.active_users)
r = User('Qaidjohar','Jawadwala',70)
print('R Active Users',User.active_users)
s = User('Mustafa','Poona',25)
print('Active Users',User.active_users)
print('P Active Users',p.active_users)
print(User.display_active())
print(User.fullName(self))
print(s.display_active())
|
"""
█▀▀ █▀▀ █▄░█ █▀▀ █▀ █ █▀ █░░ █▀▀ █▀ █▀ █▀█ █▄░█ █▀ █░█ █▀█ █░░ ░ ▄█
█▄█ ██▄ █░▀█ ██▄ ▄█ █ ▄█ █▄▄ ██▄ ▄█ ▄█ █▄█ █░▀█ ▄█ ▀▄▀ █▄█ █▄▄ ▄ ░█
Welcome to the genesis gir lesson tutorials Volume 1! Companion Cube is a program
based on doing various tasks on guiding your companion cube to freedom and most importantly
you! escape the robotic infrastructure and save your little cube friend out of the chaos
and i have a feeling a portal gun will be needed to overcome these challenges can you escape?
is the cake a lie?
. Thanks for downloading!
⼕ㄖᗪ🝗ᗪ & 山尺讠セセ🝗𝓝 ⻏丫 Ꮆ🝗𝓝🝗丂讠丂 Ꮆ讠尺
"""
#This program is about escpaing a facility with a cube know as companion cube!
#a reference to the game portal by valve enjoy!
print('Enter your name into terminal')#prompts user to enter their name in terminal
print('(press enter)')#prompts the user to press enter
name=input()#the input() function takes input from the user to create essentially the variable
print('You hear a mysterious radio playing music and you awaken')#setting scene with print function!
print('(Press enter to continue)')#prompting to press enter!
input()#input function being used to progress to the next line of code
"""
█░█░█ █░█ ▄▀█ ▀█▀ █ █▀ █▀█ █▄█ ▀█▀ █░█ █▀█ █▄░█
▀▄▀▄▀ █▀█ █▀█ ░█░ █ ▄█ █▀▀ ░█░ ░█░ █▀█ █▄█ █░▀█
"The Python programming language has a wide range of syntactical constructions,
standard library functions, and interactive development environment features.
Fortunately, you can ignore most of that; you just need to learn enough to write
some handy little programs.
You will, however, have to learn some basic programming concepts before you can do anything.
Like a wizard in training, you might think these concepts seem arcane and tedious,
but with some knowledge and practice, you’ll be able to command your computer like a
magic wand and perform incredible feats." by Al Sweigart
Just like in chapter 1 Python basics he goes on to explain that it's a language that
uses various lines of code to create handy little programs Like this one!
This volume uses python as the language 100%.
"""
print('The room around you is still and all white with forestation growing within the walls')#setting the scene of the program with print!
print('(Press enter to continue)')#more prompts to progress
input()#input function takes input from user and progresses to next line
print('A intercom interupts the radio and a robotic sarcastic tone is heard')#introducing the character @glados
print('(press enter to continue)')#telling the user and prompting them to hit enter
input()#more input functions being used as a menu sys to continue to next line of code
print('GLADOS:Welcome to your new home , I know your not used to it. . yet but')#creating speech dialog with glados using the speech dialog
print('Im sure with some warming up youll be just fine. We are going to be great neighbors')#
print('little do you know.')#continuing from line '27' to fit into tis line of code!
print('(press enter to continue)')#prompts user to press enter on their keyboard to proceed
input()#the input function is being used again with tandem with the line '28' to create a menu sys
"""
▀█░█▀ █▀▀█ █▀▀█ ░▀░ █▀▀█ █▀▀▄ █░░ █▀▀ █▀▀
░█▄█░ █▄▄█ █▄▄▀ ▀█▀ █▄▄█ █▀▀▄ █░░ █▀▀ ▀▀█
░░▀░░ ▀░░▀ ▀░▀▀ ▀▀▀ ▀░░▀ ▀▀▀░ ▀▀▀ ▀▀▀ ▀▀▀
Variables are like little tiny safes or cardboard boxes that you can label! In them you can
insert data types from intergers, strings(stirs), floating-points and values to later use
them in your file editor and is a great way to store data.
ex.( box='a cat inside of it' ) we stored "a cat inside of it" inside box making box a variable!
"""
print('GLADOS: would you like to tell me your name?')#asking user their name
print('(Press enter)')#prompting user to continue of course
input()#input function takes the keyboard intake from user
print('GLADOS:Just kidding. I know your name already '+name+'.')#combing a variable and a string to create shock value
print('(press enter to continue)')#prompts the user to press enter using the call to print(nice way to generate strings to stream(screen)
input()#input() being used here to progress to next line after user presses enter!
print('GLADOS:Pretty dumb name if you ask me.')#glados giving a rude tone towards user with print func
print('(respond back to her rude comment)')#prompts user to reply to her rude comment uses print
input()#the input function can be used in a variety of ways but here is to progress
print('GLADOS: I dont think your opinion matters.')#uses the print function to let glados use speech
print('(press enter to read)')#asks user to proceed to next line of code with print()
input()#input function gathers the user input and waits for them to press enter
print('GLADOS:Besides.')#using print to create dialog
print('(press enter to read)')#prompts the user to press enter uses the print functionality
input()#takes input from user to progress
print('GLADOS:Your going to be here for enternity') # using the print function to give realism and print values onto stream(screen)
print('(Reply to the inhumane robot)')#asks user to reply in their own way to glados! gives variety
print()#an empty line of text uses 'print()'
response=input()#input function takes input from user rendering it the 'response' variable
print(name+':*quivers and utters the words*')#uses the print function+variable to create a snese that user is feeling emotion
print(name+':'+response)#meshes variable and another variable+print() function to make user speak
print()#empty line of code uses the print() funcionality!
print('GLADOS:I could care less. . .')#more speech dialog from glados using print functionality
print('(press enter to read)')#prompts to continue
input()#gathers users keyboard presses but in this instance
print('GLADOS:I really dont think your the brightest tool in the shed')#insulting characteristics by glados using the print function!
print('GLADOS:are you?. . .')#using the print function to add dialog to glados!
print('(respond)')#prompting user to reply using the print function
print()#empty line
response=input()#using the input function in reality to intake users reply back to glados storing it within repsonse
print(name+':*looks up at her and says*')#sense of action with user
print(name+':'+response)#combining print+variables to give the user their response
print()#empty line of code! pretty isnt it?
print('GLADOS:Well no matter what you are.')#we are using this line of instruction to make the character glados speak!
print('(press enter to read)')#prompts user to press enter using the print function!
input()#gathers user intake from keyboard press and wait form the to press enter
print('GLADOS:Where you come from. . ')#making the character glados asks for the users name but she already knows due to the variable set in line '16'
print('(press enter to read)')#more prompts that use print
""""
🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁
▀█▀ █░█ █▀▀ ▄▀█ █▀█ ▀█▀ █▀█ █▀▀ █▀ █▀▀ █░░ █▀▀ ▀█▀ ▄▀█ █░█ █▀▀ █░█ ▀█▀
░█░ █▀█ ██▄ █▀█ █▀▄ ░█░ █▄█ █▀░ ▄█ ██▄ █▄▄ █▀░ ░█░ █▀█ █▄█ █▄█ █▀█ ░█░
In the world we live in now alot of new or novice programmers will run to discord servers or
sites like stack overflow for answers. These methods seem overrated to me and i highly
suggest you branch out! Explore , Discover , Swim threw the internet and find resources other
than those two things. i have never used a discord server nor stack for learning.
you can simply dig and do things on your own and you learn quicker that way some will debate
but i could care less. programming has no rules except the functions and if you speak it correctly
Stay focused , Stay thinking outside the box! Self-taught Programmers are a thing and I
can vouch for this the artform is vast and very complex but remeber the term 'Self-taught' simply
means to teach yourself the things you want to explore. Being self-taught is looked at very
indie-modern type of approach but nonetheless very benefical. and chances are if your reading
this you are self-taught as well!
🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁
▄▀▀▀▄
█ █
███████ ▄▀▀▄
██ ▀ ██ █▀█▀▀▀▀█ █ 𝓬σɳടιട𝜏αɳ𝜏 , ⨍σ𝓬ᥙടҽԃ , αɳԃ ԃҽ𝜏ҽɾ𝓶ιɳҽԃ. ιട ƙҽყ.
███▄███ ▀ ▀ ▀▀
| ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄|
I'm Self-taught!
|___________| 𝙏𝙞𝙥: 𝙂𝙞𝙩 𝙆𝙧𝙖𝙠𝙚𝙣 𝙞𝙨 𝙫𝙚𝙧𝙮 𝙪𝙨𝙚𝙛𝙪𝙡
⠀⠀⠀⠀⠀⠀(\__/) ||
⠀⠀⠀⠀⠀⠀(•ㅅ•) || 𝙏𝙞𝙥: 𝙈𝙖𝙠𝙚 𝙖 𝙂𝙞𝙩𝙝𝙪𝙗 𝙖𝙘𝙘𝙤𝙪𝙣𝙩 𝙩𝙤 𝙨𝙖𝙫𝙚 𝙮𝙤𝙪𝙧 𝙧𝙚𝙥𝙤𝙨𝙞𝙩𝙤𝙧𝙞𝙚𝙨
⠀⠀⠀⠀⠀⠀/ づ
🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁
"""
print('-'+name+'looks up-')#arguements calling to print + a variable of users name
print()#empty line of code uses the 'print()' to create a empty line within the code
print('GLADOS:We are going to. . ')#more character speech from glados
print('(press enter to read)')#prompts the user to press enter to progress further
input()#gathers input from user to proceed to line '74'
print('GLADOS:Run some tests.')#using the print function to print the sir values onto stream(screen)
print('(press enter to read)')#prompts user to press enter
input()#waits for input from user using the 'input()'
print('GLADOS:Head over to that elevator over there.')#glados directs the user to go to the elevator using the print function
print('press enter to read')#prompts to progress to next line of code
input()#waits for input from user
print(name+' *looks around confused feeling cautious*')
print('press enter to read')#prompting the user to press enter to progress uses 'print()' function
input()#waits for input from user
print('GLADOS:Its the thing that people use to switch floor levels just in case you where')
print('wondering.')
print('(respond)')#prompting user to respond back to glados comment
response=input()#input() function and creating a variable from user
print()#an empty line that does nothing but create space between lines
print(name+':'+response)#combining variables together to make complete sentences! pretty neat
print()#used to let the code breathe 'print()'
print('GLADOS:Good so we understand eachother.')#print function being used to print glados speech to stream(screen)
print('(press enter to continue)')#prompting user to continue to next area in code using print function
input()#takes input
print()#empty line of code that skips to line '91'
print('░█████╗░░█████╗░███╗░░░███╗██████╗░░█████╗░███╗░░██╗██╗░█████╗░███╗░░██╗ ░█████╗░██╗░░░██╗██████╗░███████╗')
print('██╔══██╗██╔══██╗████╗░████║██╔══██╗██╔══██╗████╗░██║██║██╔══██╗████╗░██║ ██╔══██╗██║░░░██║██╔══██╗██╔════╝')
print('██║░░╚═╝██║░░██║██╔████╔██║██████╔╝███████║██╔██╗██║██║██║░░██║██╔██╗██║ ██║░░╚═╝██║░░░██║██████╦╝█████╗░░')
print('██║░░██╗██║░░██║██║╚██╔╝██║██╔═══╝░██╔══██║██║╚████║██║██║░░██║██║╚████║ ██║░░██╗██║░░░██║██╔══██╗██╔══╝░░')
print('╚█████╔╝╚█████╔╝██║░╚═╝░██║██║░░░░░██║░░██║██║░╚███║██║╚█████╔╝██║░╚███║ ╚█████╔╝╚██████╔╝██████╦╝███████╗')
print('░╚════╝░░╚════╝░╚═╝░░░░░╚═╝╚═╝░░░░░╚═╝░░╚═╝╚═╝░░╚══╝╚═╝░╚════╝░╚═╝░░╚══╝ ░╚════╝░░╚═════╝░╚═════╝░╚══════╝')
print(' .,-:;//;:=, ')
print(' . :H@@@MM@M#H/.,+%;, ')
print(' ,/X+ +M@@M@MM%=,-%HMMM@X/, ')
print(' -+@MM; $M@@MH+-,;XMMMM@MMMM@+- ')
print(' ;@M@@M- XM@X;. -+XXXXXHHH@M@M#@/. ')
print(' ,%MM@@MH ,@%= .---=-=:=,. ')
print(' -@#@@@MX ., -%HX$$%%%+; ')
print(' =-./@M@M$ .;@MMMM@MM: ')
print(' X@/ -$MM/ .+MM@@@M$ ')
print(' ,@M@H: :@: . -X#@@@@- ')
print(' ,@@@MMX, . Portal™ /H- ;@M@M= ')
print(' .H@@@@M@+, %MM+..%#$. ')
print(' /MMMM@MMH/. XM@MH; -; ')
print(' /%+%$XHH@$= , .H@@@@MX, ')
print(' .=--------. -%H.,@@@@@MX, ')
print(' .%MM@@@HHHXX$$$%+- .:$MMX -M@@MM%. ')
print(' =XMMM@MM@MM#H;,-+HMM@M+ /MMMX= ')
print(' =%@M@M#@$-.=$@MM@@@M; %M%= ')
print(' ,:+$+-,/H#MMMMMMM@- -, ')
print(' =++%%%%+/:- ')
print()
"""
🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁
▄▀█ █▀█ █▀▀ █▀█ ▀█▀ █░█ █▀█ █▀▀
█▀█ █▀▀ ██▄ █▀▄ ░█░ █▄█ █▀▄ ██▄
█▀ █▀▀ █ █▀▀ █▄░█ █▀▀ █▀▀
▄█ █▄▄ █ ██▄ █░▀█ █▄▄ ██▄
█ █▄░█ █▄░█ █▀█ █░█ ▄▀█ ▀█▀ █ █▀█ █▄░█ █▀
█ █░▀█ █░▀█ █▄█ ▀▄▀ █▀█ ░█░ █ █▄█ █░▀█ ▄█
=/;;/-
+: //
/; /;
-X H.
.//;;;:;;-, X= :+ .-;:=;:;%;.
M- ,=;;;#:, ,:#;;:=, ,@
:% :%.=/++++/=.$= %=
,%; %/:+/;,,/++:+/ ;+.
,+/. ,;@+, ,%H;, ,/+,
;+;;/= @. .H##X -X :///+;
;+=;;;.@, .XM@$. =X.//;=%/.
,;: :@%= =$H: .+%-
,%= %;-///==///-// =%,
;+ :%-;;;;;;;;-X- +:
@- .-;;;;M- =M/;;;-. -X
:;;::;;-. %- :+ ,-;;-;:==
,X H.
;/ %=
// +;
,////,
🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁
""" # ends multi line comment!
print('(press enter to continue')#prompts the user to press enter to progress
input()#takes input from user using the input()
print('-The elevator door opens to level 1-')#takes user threw a elevator
print('press enter to continue')#prompts using the print functionality
input()#gathers input function data and waits for user to press any key than hit enter
print('(walk out [ENTER]')#prompts the user to press enter using the print function 'print()'
input()#input function to proceed
print(name+' walks out the elevator')#user walks out of elevator this line uses the print function
print('-errie silence preset and a white room with obstacles are seen-')
print('(press enter)')#prompts the user to press enter
input()#takes input from user using the input()
print('RADIO:Here at Aperture Industies we strive to keep your limbs intact *BRRr* i mean we will')
print('try our very best to do so. if in any case you do lose any limbs during the experiment please')
print('remain calm at all times and a local nurse will come to your aid.')
print('(press enter to continue)')#using the print function to create a dialog for the radio
input()#taking more input to skip to next line of code!
print('GLADOS: Well , well , well.')#print function being used to print values onto screen
print('(press enter to read)')
input()#you can use the input function to skip lines of code or gather info on key presses from user
print('GLADOS:Look at what the cat dragged in')#some inults issued by the character glados uses print functionalities
print('(press enter to read)')
input()#input to skip to next line of code!
print('-'+name+' looks at her-')#shows that the user looks over @glados uses the rpint call functions
print('(press enter to read)')#prompts user to press enter
input()#takes input from users keyboard press and waits for enter key press
print('GLADOS:Im surpised to know that you can use an elevatoRrRrRrrrrr*Brr*')
print('(press enter to read)')#prompts using the print function using 'print'
input()#gathers keyboard presses and waits for user uses input function
print('GLADOS:Nonetheless I find you very. . .')
print('(press enter to read)')#prompts user to press enter to progress!
input()#takes the users input with the input() func and progresses them to line '187'
print('GLADOS:Dull . . .')#speech dialog that uses the print feature
print('(press enter to read)')#prompts
input()#progress to line '189'
print('*Her voice begins to get aggressive and her voice echoes off the walls')#sense of direction with print
print('(press enter to read)')
input()#using the input function to my advantage to gather users enter input key press
print('GLADOS:Boring. . .')#using the print function to generate strings to stream(screen)
print('(respond)')#asking the user to respond uses the print function to print values to stream(screen)
response=input()#creating response variable with input()
print()#create a spacial space between the lines so they can breathe
print(name+' stands up and and looks at her and says '+response)#user looks at the character uses the print function
print('(press enter to continue)')#prompts the user to press the neter key with print feature!
input()#neat another input! we use these to gather info from users!
print('-A swooshing vaccum sound is heard and a Cube falls out the vent-')#the companion cube introduces itself to setting
print('(press enter to read)')#more prompts
input()#waits for users input uses the 'input()' function to gather data!
print('GLADOS: You seem really lonely I thought it would be nice to get you a friend')
print('while testing it could benefit you. . ')
print('(press enter to read)')#asks user to press enter and they do so in line '208'
input()#takes input from user w/input()
print('GLADOS:You look agitated why dont you spend time with your new. . ')#glados speech using the print call function!
"""
█▄█ █▀█ █░█ ▄▀█ █▀█ █▀▀ █▀▀ █▀█ █▀▀ ▄▀█ ▀█▀ █ █▄░█ █▀▀ █▀█ █░░ ▄▀█ █▄░█ █▀▀ ▀█▀ █▀
░█░ █▄█ █▄█ █▀█ █▀▄ ██▄ █▄▄ █▀▄ ██▄ █▀█ ░█░ █ █░▀█ █▄█ █▀▀ █▄▄ █▀█ █░▀█ ██▄ ░█░ ▄█
..;===+.
. . .:=iiiiii=+=
.=i))=;::+)i=+,
,=i);)I)))I):=i=;
𝘾𝙧𝙚𝙖𝙩𝙚, 𝘽𝙪𝙞𝙡𝙙, 𝘾𝙤𝙙𝙚 , 𝙛𝙤𝙘𝙪𝙨 .=i==))))ii)))I:i++
+)+))iiiiiiii))I=i+:' .
.,:;;++++++;:,. )iii+:::;iii))+i='
. .:;++=iiiiiiiiii=++;. =::,,,:::=i));=+' .
. ,;+==ii)))))))))))ii==+;, ,,,:=i))+=:
,;+=ii))))))IIIIII))))ii===;. ,,:=i)=i+
;+=ii)))IIIIITIIIIII))))iiii=+, ,:=));=, . .
. ,+=i))IIIIIITTTTTITIIIIII)))I)i=+,,:+i)=i+
,+i))IIIIIITTTTTTTTTTTTI))IIII))i=::i))i=' .
,=i))IIIIITLLTTTTTTTTTTIITTTTIII)+;+i)+i`
=i))IIITTLTLTTTTTTTTTIITTLLTTTII+:i)ii:' 𝒊𝒎𝒂𝒈𝒊𝒏𝒆 , 𝒃𝒓𝒆𝒂𝒕𝒉𝒆 𝒍𝒊𝒇𝒆
+i))IITTTLLLTTTTTTTTTTTTLLLTTTT+:i)))=,
. ░██████╗░███████╗███╗░░██╗███████╗░██████╗██╗░██████╗™
██╔════╝░██╔════╝████╗░██║██╔════╝██╔════╝██║██╔════╝ .
██║░░██╗░█████╗░░██╔██╗██║█████╗░░╚█████╗░██║╚█████╗░
██║░░╚██╗██╔══╝░░██║╚████║██╔══╝░░░╚═══██╗██║░╚═══██╗
╚██████╔╝███████╗██║░╚███║███████╗██████╔╝██║██████╔╝
░╚═════╝░╚══════╝╚═╝░░╚══╝╚══════╝╚═════╝░╚═╝╚═════╝░
=))ITTTTTTTTTTTLTTTTTTLLLLLLTi:=)IIiii; .
.i)IIITTTTTTTTLTTTITLLLLLLLT);=)I)))))i;
:))IIITTTTTLTTTTTTLLHLLLLL);=)II)IIIIi=: .
. :i)IIITTTTTTTTTLLLHLLHLL)+=)II)ITTTI)i= .
. .i)IIITTTTITTLLLHHLLLL);=)II)ITTTTII)i+ .
=i)IIIIIITTLLLLLLHLL=:i)II)TTTTTTIII)i'
+i)i)))IITTLLLLLLLLT=:i)II)TTTTLTTIII)i;
+ii)i:)IITTLLTLLLLT=;+i)I)ITTTTLTTTII))i; .
=;)i=:,=)ITTTTLTTI=:i))I)TTTLLLTTTTTII)i;
+i)ii::, +)IIITI+:+i)I))TTTTLLTTTTTII))=, .
:=;)i=:,, ,i++::i))I)ITTTTTTTTTTIIII)=+'
.+ii)i=::,, ,,::=i)))iIITTTTTTTTIIIII)=+ .
,==)ii=;:,,,,:::=ii)i)iIIIITIIITIIII))i+:'
+=:))i==;:::;=iii)+)= `:i)))IIIII)ii+' .
.+=:))iiiiiiii)))+ii;
.+=;))iiiiii)));ii+
█▄▄ █▀▀ █▀▀ █▀█ █▀▀ ▄▀█ ▀█▀ █ █░█ █▀▀
█▄█ ██▄ █▄▄ █▀▄ ██▄ █▀█ ░█░ █ ▀▄▀ ██▄
.+=i:)))))))=+ii+
.;==i+::::=)i=; Use your imagination the world of coding is diverse and endless you
,+==iiiiii+, can make a program about any setting you'd like and the best developers
`+=+++;` think outside the box and use improvised decisions. There is no right
or wrong but think of your file editor as a canvas and your brain
the paint brush. Because in the end you really are creating an experience
that user must go threw and you are setting the scene. YOU are setting the
Emotion , Paths , Routes , YOU are building the earth and waterfalls that
user must overcome or deal with no matter if it's a game, Software
tool, Program. Learn the functions in this volume and make sure to refer
to the automatetheboringstuff page chapter one and study that like the
back of your hand. Over and Over and Over!
🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁
"""
print('(press enter to read)')#prompts
print('GLADOS:Friend.')#speech dialog from Glados using the function 'print'
print('(press enter to read)')#more prompts to progress using the print function
input()#users data input is recorded and gathered by input() function displayed here!
print(name+' looks over at the white hearted cube')#sense of actions with print functionality
print('GLADOS:Get acquainted with your cube.')#glados speech dialogs
print('(press enter to read)')#prompts user to press enter in the end
input()#input from user being gathered by input()
print(name+' looks over at her')#giving the audience a general idea where user looks. Uses variable+print
print('(press enter to read)')#prompts
input()#pulls in and takes input from user using the input()
print('GLADOS:Oh dont give me that look you both look great together.Just dont die together.')
print('(press enter to continue)')#prompts
input()#gathers input from user using the input() feature
print('(Pick up your Companion Cube)')#telling user to pick up his/her cube calls to print
print(' (press enter to pick up) ')#prompts with the print function
input()#uses an input calling method that gathers the info of key presses from user
print(name+' picks up Companion Cube!')#user picks up Companion Cube
print('(name your Companion Cube)')#asks user to name their cube calls to variable in line '277'
CompanionCube=input()#creating the variable for the item Companion Cube+using the input from user!
print()#empty line to give spacial depth nusing the 'print()' function
print('-'+name+' holds the cube now in their hands-')#letting the user know they now have the cube in their possesion
print('-'+name+' named their cube '+CompanionCube+'!')#lets the user know what they named their lovely cube!
print('(press enter to continue)')#prompts the user to press enter to progress to next line of code!
input()#gathers user input to progress
print('(Press enter to accept)'+' Your Cube will be named '+CompanionCube+'.')#prompts the user to accept the cube name
input()#gather data from user inputs using input()
print()#an empty line that enters the void
print(name+' picks up '+CompanionCube+' and puts them into their backpack.')#lets the user know where they put their amazing cube!
print('(press enter to read)')#more cool little prompts to progress!
input()#using the input() function to wait for enter key press
print('-Rumble-')#the cube rumbles added for sensation of gameplay!
input()#waits for user to press enter to progress
print(CompanionCube+' -Rumble-')#adds a small rumble with the print call function
print('(Press enter)')#asks user to press enter with print function
input()#gathers data from enter key press
print(CompanionCube+' -softly Rumbles-')#giving a sense of direction with print function to print values to stream(screen)
print('(Press enter to begin Level 1 Course)')#prompts user to press enter to begin course
input()#gathers input from user with the input() function
print('GLADOS: Aww how sweet.')#the character Glados speech dialog
print('(Press enter to read)')#prmopts the user to press enter using the input() in line '251'
input()#gathers the key presses from user uses the input()!
print('GLADOS:You made friends with your litle toy box. That wont help you pass this course.')
print('(press enter to read)')#character boasted and inults using the print function
input()#data collection with input()
print('GLADOS: This course was designed by the best at Aperture and someone of your. . ')
print('(press enter to read)')#prompts from user waiting to progress uses print functionality
input()#waiting for user to insert some type of input in this case we ask for enter key!
print('GLADOS:Brain power. *Her voice echoes off the beautiful white walls*')#we are using the print function to print values to screen
print('(press enter to begin!)')
input()#more data intake using the input() function
print('-Theres a Door Maybe you should go in it-')##suggesting to user to go threw door , uses the print function
print('(Go inside the door? Press enter)')#prompts user to press enter to progress to line '263'
input()#the user presses enter here to progress to line '264'
print('-A square empty socket is there-')#giving a clue to user using the print functionality
print(name+':'+' maybe i should put something there. . ')#uses the print and a variable 'name'
print('(Enter '+CompanionCube+' inside the socket)')#we use the name of the users cube by using its variable in this case 'CompanionCube'
print('(press enter to insert '+CompanionCube+')')#prompts user to insert their cube uses variable+print functions!
input()#waits for a direct input from user
print(name+':'+'Its asking me for to put a random number.')#uses the print func+the user namae variable
print('(enter any number)')#we ask the user to give us a random number!
number=input()#creating the number variable with users input uses the input() function
print('-you input the number-')#Ah! my favorite part! we use
print('(press enter to input your guess)')#telling user to input their guess uses the print function!
input()#input() being used as a menu sys
print('-The number was guessed perfectly turns out it was right!-')
print('(press enter to confirm)')#prompts user to confirm
input()#gathers input function from user and waits for the enter key press
print('-The door opens and an elevator awaits you-')#setting the scene
print('(press enter to walk in)')#asking the user to press enter to walk in elevator
input()#gathers data from user
print('GLADOS:..that was pure luck.. I think your over exceeding yourself.')#glados speech using the print feature 'print'
print('press enter to read')#propts user to continue telling them to press enter!
input()#using the input function as a menu sys uses input() fucntion
print(name+' waits in the elevator as glados talks feeling victory-')
print('- and as the floors change.The lights shine threw the elevators slits as floors')#setting scene with print functionality
print('change in a rapid manner.')#conversation continues from line '285' pretty neat
print('(press enter to read)')#prompts for user using the print feature
input()#input() taking input from user
print('-fades to black-')#sets scene with print function
print('(Press enter to see results!)')#telling the user to press enter to see their results!
input()#waiting for enter key press from user using the input( function)
print('Aperture Industries have '+name+' on log for being the first to make it out!')#results using the print+variable
print('(next [enter])')#prompts user to press enter with print
input()#waits to gather input from user using the print function
print('Aperture Industries have on log that your Cube was named '+CompanionCube+'!')#giving the user the name of their cube
print('(next [enter])')#prompting user to press enter with the print function
input()#gathers data info from key presses from user using the print function
print('Aperture Industries have on log that the number for the door was actually 504')#results+storyline driven content
print(' but somehow '+name+'s Cube hacked the mainframe and put it in for them!')#more storyline driven speech
print('(next [enter])')#prompts user to press enter
input()#gathers information such as key presses than waits user to press enter
print('Aperture Industries will be hearing from you again!')#print() function being used to print values onto stream(screen)
print('(Press enter to exit program and view credits)')#prompts user to click enter to exit)
input()
print('_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _')
(' .,-:;//;:=, ')
print(' . :H@@@MM@M#H/.,+%;, ')
print(' This was a triumph ,/X+ +M@@M@MM%=,-%HMMM@X/, Software Developer - Genesis Gir ')
print(' Im making a note here: -+@MM; $M@@MH+-,;XMMMM@MMMM@+- ')
print(' HUGE SUCCESS. ;@M@@M- XM@X;. -+XXXXXHHH@M@M#@/. Programming Lead - Genesis Gir ')
print(' Its hard to overstate ,%MM@@MH ,@%= .---=-=:=,. ')
print(' my satisfaction. -@#@@@MX ., -%HX$$%%%+; Storyline Directer Genesis Gir ')
print(' Aperture Science =-./@M@M$ .;@MMMM@MM: ')
print(' We do what we must X@/ -$MM/ .+MM@@@M$ Owners of Portal™ - Valve™ ')
print(' because we can. ,@M@H: :@: . -X#@@@@- ')
print(' For the good of all of us. ,@@@MMX, . /H- ;@M@M= Twitch:https://www.twitch.tv/genesisgir ')
print(' Execept the ones who are dead..H@@@@M@+, %MM+..%#$. ')
print(' /MMMM@MMH/. XM@MH; -; Resources:https://automatetheboringstuff.com/ ')
print(' But theres no sense crying /%+%$XHH@$= , .H@@@@MX, ')
print(' over every mistake. .=--------. -%H.,@@@@@MX, ')
print(' you just keep on trying .%MM@@@HHHXX$$$%+- .:$MMX -M@@MM%. ')
print(' till you run out of cake =XMMM@MM@MM#H;,-+HMM@M+ /MMMX= ')
print(' And the science gets done. =%@M@M#@$-.=$@MM@@@M; %M%= ')
print(' ,:+$+-,/H#MMMMMMM@- -, Special thanks to - My family and everyone @Twitch ')
print(' =++%%%%+/:- ')
print('_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _')
"""
🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁 🅶🅴🅽🅴🆂🅸🆂🅶🅸🆁
"""
print()#empty line of code to create a space between using the print() function
print('press enter to meet your savior '+CompanionCube+' the Companion Cube! Thanks for Playing!')#prompts the user if they would liek to meet their cube!
input()#waits for user to insert enter data to progress uses the input() feature
print('(https://i.pinimg.com/originals/f1/ac/72/f1ac72fb5fc76b95bc1c954740f2b1d3.gif)')#sends a link of a companion cube gif that user can click
print('Enter to exit')#prompts user to press enter to exit the program!
input()#waits for user to put final enter key press to end program and again thank you all!
"""
█▀█ █▀▀ █▀ █▀█ █░█ █▀█ █▀▀ █▀▀ █▀
█▀▄ ██▄ ▄█ █▄█ █▄█ █▀▄ █▄▄ ██▄ ▄█
link: >>> https://www.twitch.tv/genesisgir <<< Find Livestreams and more!
link: >>> https://automatetheboringstuff.com <<< Discover and learn how i did!
"""
|
class TextStats:
def _calc_symbol_freqs(self):
self.symbol_freq = {}
for c in self.text:
if c in self.symbol_freq:
self.symbol_freq[c] += 1
else:
self.symbol_freq[c] = 1
@staticmethod
def _is_valid_bigram(a, b):
""" 0nly count bigrams with 2 unique letters, as only those can
be optimiazed. Consider ' a letter, as it tends occur in common
words, such as "don't". """
return (a.isalpha() or a == "'") and \
(b.isalpha() or b == "'") and a != b
@staticmethod
def _is_valid_trigram(a, b, c):
""" 0nly count trigrams with 3 unique letters, as only those can
be optimiazed. Consider ' a letter, as it tends occur in common
words, such as "don't". """
return (a.isalpha() or a == "'") and \
(b.isalpha() or b == "'") and \
(c.isalpha() or c == "'") and \
a != b and b != c and c != a
def _calc_bigrams(self):
self.bigrams = {}
prev = ' '
for c in self.text.lower():
if self._is_valid_bigram(prev, c):
bigram = (prev, c)
if bigram in self.bigrams:
self.bigrams[bigram] += 1
else:
self.bigrams[bigram] = 1
prev = c
def _calc_trigrams(self):
self.trigrams = {}
prev2, prev1 = ' ', ' '
for c in self.text.lower():
if self._is_valid_trigram(prev2, prev1, c):
trigram = (prev2, prev1, c)
if trigram in self.trigrams:
self.trigrams[trigram] += 1
else:
self.trigrams[trigram] = 1
prev2, prev1 = prev1, c
def __init__(self, text):
self.text = text
self._calc_symbol_freqs()
self._calc_bigrams()
self._calc_trigrams()
#t = [(s[0]+s[1]+s[2], f) for s, f in self.trigrams.items() if "'" in s]
#t.sort(key=lambda a: a[1])
#print(t)
#print(len(self.bigrams))
#print(len(self.trigrams))
|
test = {
'name': 'Problem 7',
'points': 3,
'suites': [
{
'cases': [
{
'code': r"""
>>> big_limit = 10
>>> meowstake_matches("wird", "wiry", big_limit)
1
>>> meowstake_matches("wird", "bird", big_limit)
1
>>> meowstake_matches("wird", "wir", big_limit)
1
>>> meowstake_matches("wird", "bwird", big_limit)
1
>>> meowstake_matches("speling", "spelling", big_limit)
1
>>> meowstake_matches("used", "use", big_limit)
1
>>> meowstake_matches("hash", "ash", big_limit)
1
>>> meowstake_matches("ash", "hash", big_limit)
1
>>> meowstake_matches("roses", "arose", big_limit) # roses -> aroses -> arose
2
>>> meowstake_matches("tesng", "testing", big_limit) # tesng -> testng -> testing
2
>>> meowstake_matches("rlogcul", "logical", big_limit) # rlogcul -> logcul -> logicul -> logical
3
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> small_words_list = ["spell", "nest", "test", "pest", "best", "bird", "wired",
... "abstraction", "abstract", "wire", "peeling", "gestate",
... "west", "spelling", "bastion"]
>>> autocorrect("speling", small_words_list, meowstake_matches, 10)
'spelling'
>>> autocorrect("abstrction", small_words_list, meowstake_matches, 10)
'abstraction'
>>> autocorrect("wird", small_words_list, meowstake_matches, 10)
'bird'
>>> autocorrect("gest", small_words_list, meowstake_matches, 10)
'nest'
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> # ***Check that the recursion stops when the limit is reached***
>>> import trace, io
>>> from contextlib import redirect_stdout
>>> with io.StringIO() as buf, redirect_stdout(buf):
... trace.Trace(trace=True).runfunc(meowstake_matches, "someawe", "awesome", 3)
... output = buf.getvalue()
>>> len([line for line in output.split('\n') if 'funcname' in line]) < 1000
True
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('thong', 'thong', 100)
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('place', 'wreat', 100)
5
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('pray', 'okee', 100)
4
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('cloit', 'cloit', 100)
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('yond', 'snd', 100)
2
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('tb', 'tb', 100)
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('gobi', 'gobi', 100)
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('watap', 'woitap', 100)
2
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('baffy', 'btfi', k) > k for k in range(5)])
3
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('else', 'konak', k) > k for k in range(5)])
5
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('zygon', 'jzon', k) > k for k in range(5)])
3
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('lar', 'lar', 100)
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('shop', 'wopd', 100)
3
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('pc', 'pc', k) > k for k in range(2)])
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('sail', 'sail', 100)
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('fiber', 'fbk', 100)
3
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('doff', 'def', 100)
2
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('meile', 'mqeile', 100)
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('donor', 'doinor', k) > k for k in range(6)])
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('meet', 'meeu', k) > k for k in range(4)])
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('tic', 'tih', k) > k for k in range(3)])
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('taft', 'hewer', k) > k for k in range(5)])
5
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('moorn', 'toxa', k) > k for k in range(5)])
4
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('hamal', 'hamal', k) > k for k in range(5)])
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('pridy', 'dance', 100)
5
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('dekko', 'zbk', 100)
4
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('julio', 'juio', k) > k for k in range(5)])
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('boist', 'spume', k) > k for k in range(5)])
5
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('jail', 'jaila', 100)
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('cumin', 'goes', 100)
5
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('civil', 'whose', k) > k for k in range(5)])
5
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('stead', 'ny', k) > k for k in range(5)])
5
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('mikie', 'mdiye', 100)
3
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('utils', 'utils', k) > k for k in range(5)])
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('nuque', 'nuq', k) > k for k in range(5)])
2
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('chine', 'ziinx', k) > k for k in range(5)])
3
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('tour', 'erase', k) > k for k in range(5)])
5
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('ak', 'rose', 100)
4
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('sawah', 'shape', k) > k for k in range(5)])
4
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('elb', 'logia', 100)
5
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('noily', 'oibs', 100)
3
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('fluid', 'grad', 100)
4
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('titer', 'tskhteur', 100)
4
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('shood', 'shood', 100)
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('sher', 'xdhe', 100)
3
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('dayal', 'qualm', 100)
4
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('tenai', 'whata', 100)
5
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('bow', 'how', 100)
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('tony', 'togqq', k) > k for k in range(5)])
3
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('baby', 'ton', k) > k for k in range(4)])
4
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('seron', 'seron', 100)
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('tame', 'tfme', k) > k for k in range(4)])
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('kissy', 'kisdsxk', 100)
3
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('str', 'st', k) > k for k in range(3)])
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('enema', 'nemr', 100)
2
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('beden', 'beden', 100)
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('coral', 'coral', 100)
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('hack', 'rhack', 100)
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('alan', 'alan', 100)
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('aru', 'aru', 100)
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('tail', 'taiil', 100)
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('corps', 'ckcp', 100)
3
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('kazi', 'kazi', 100)
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('bone', 'bone', 100)
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('dee', 'derv', k) > k for k in range(4)])
2
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('fuder', 'fuder', 100)
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('harl', 'hhtar', 100)
3
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('def', 'df', 100)
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('moio', 'yomo', 100)
2
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('amnia', 'wna', k) > k for k in range(5)])
3
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('pair', 'pair', k) > k for k in range(4)])
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('peai', 'eabi', k) > k for k in range(4)])
2
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('pryse', 'prysvf', k) > k for k in range(6)])
2
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('amelu', 'samp', 100)
4
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('weak', 'wk', 100)
2
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('atelo', 'atelo', 100)
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('uc', 'kc', 100)
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('strew', 'jaup', k) > k for k in range(5)])
5
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('dome', 'dume', k) > k for k in range(4)])
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('braze', 'sxaze', 100)
2
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('zaman', 'zadpamn', 100)
3
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('twank', 'renne', 100)
4
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('pinky', 'opiky', k) > k for k in range(5)])
2
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('spoke', 'spoke', k) > k for k in range(5)])
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('recto', 'recto', k) > k for k in range(5)])
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('ula', 'ula', 100)
0
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('dame', 'froth', 100)
5
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('grane', 'griae', 100)
2
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('cycad', 'cqcad', 100)
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('creem', 'ashreem', 100)
3
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('alky', 'alfy', k) > k for k in range(4)])
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('finds', 'fid', k) > k for k in range(5)])
2
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('argot', 'arxgot', k) > k for k in range(6)])
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('lc', 'roost', 100)
5
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('mi', 'iran', 100)
4
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('faded', 'fabehc', k) > k for k in range(6)])
3
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('slee', 'ble', k) > k for k in range(4)])
2
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> meowstake_matches('macro', 'macr', 100)
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('bbs', 'bbj', k) > k for k in range(3)])
1
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> sum([meowstake_matches('roud', 'roud', k) > k for k in range(4)])
0
""",
'hidden': False,
'locked': False
}
],
'scored': True,
'setup': r"""
>>> from cats import meowstake_matches, autocorrect
""",
'teardown': '',
'type': 'doctest'
}
]
}
|
# Notices we don't need to worry about
ignore_notices = [
"already_banned",
"already_emote_only_off",
"already_emote_only_on",
"already_r9k_off",
"already_r9k_on",
"already_subs_off",
"already_subs_on",
"bad_ban_admin",
"bad_ban_anon",
"bad_ban_broadcaster",
"bad_ban_global_mod",
"bad_ban_mod",
"bad_ban_self",
"bad_ban_staff",
"bad_commercial_error",
"bad_delete_message_broadcaster",
"bad_delete_message_mod",
"bad_host_error",
"bad_host_hosting",
"bad_host_rate_exceeded",
"bad_host_rejected",
"bad_host_self",
"bad_marker_client",
"bad_mod_banned",
"bad_mod_mod",
"bad_slow_duration",
"bad_timeout_admin",
"bad_timeout_anon",
"bad_timeout_broadcaster",
"bad_timeout_duration",
"bad_timeout_global_mod",
"bad_timeout_mod",
"bad_timeout_self",
"bad_timeout_staff",
"bad_unban_no_ban",
"bad_unhost_error",
"bad_unmod_mod",
"ban_success",
"cmds_available",
"color_changed",
"commercial_success",
"delete_message_success",
"emote_only_off",
"emote_only_on",
"followers_off",
"followers_on",
"followers_onzero",
"host_off",
"host_on",
"host_success",
"host_success_viewers",
"host_target_went_offline",
"hosts_remaining",
"invalid_user",
"mod_success",
"no_help",
"no_mods",
"not_hosting",
"r9k_off",
"r9k_on",
"raid_error_already_raiding",
"raid_error_forbidden",
"raid_error_self",
"raid_error_too_many_viewers",
"raid_error_unexpected",
"raid_notice_mature",
"raid_notice_restricted_chat",
"room_mods",
"slow_off",
"slow_on",
"subs_off",
"subs_on",
"timeout_no_timeout",
"timeout_success",
"turbo_only_color",
"unban_success",
"unmod_success",
"unraid_error_no_active_raid",
"unraid_error_unexpected",
"unraid_success",
"untimeout_banned",
"untimeout_success",
"usage_ban",
"usage_clear",
"usage_color",
"usage_commercial",
"usage_disconnect",
"usage_emote_only_off",
"usage_emote_only_on",
"usage_followers_off",
"usage_followers_on",
"usage_help",
"usage_host",
"usage_marker",
"usage_me",
"usage_mod",
"usage_mods",
"usage_r9k_off",
"usage_r9k_on",
"usage_raid",
"usage_slow_off",
"usage_slow_on",
"usage_subs_off",
"usage_subs_on",
"usage_timeout",
"usage_unban",
"usage_unhost",
"usage_unmod",
"usage_unraid",
"usage_untimeout",
]
# Notices that indicate we're not a mod
cooldown_notices = [
"msg_duplicate",
"msg_emoteonly",
"msg_facebook",
"msg_followersonly",
"msg_followersonly_followed",
"msg_followersonly_zero",
"msg_r9k",
"msg_ratelimit",
"msg_rejected",
"msg_rejected_mandatory",
"msg_slowmode",
"msg_subsonly",
"no_permission",
]
# Notices that indicate we should probably go
leave_notices = [
"msg_banned",
"msg_channel_blocked",
"msg_room_not_found",
"msg_timedout",
"msg_verified_email",
"tos_ban",
]
|
class InvalidUsage(Exception):
status_code = 404
message = 'Instance Not Found!'
def __init__(self, message=None, status_code=None):
Exception.__init__(self)
if message is not None:
self.message = message
if status_code is not None:
self.status_code = status_code
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
NotCorrectDirection = InvalidUsage("Direction is not correct!", 418)
IdNotFound = InvalidUsage("Id not found!", 404)
CoordinatesNotEmpty = InvalidUsage("Coordinates is not empty.", 421)
CoordinatesNotValid = InvalidUsage("Coordinates not valid.", 422)
ErrorOnBoardCoding = InvalidUsage("Not matching with robot values.", 423)
ErrorBoardCreation = InvalidUsage("String size is not matching with board size", 424)
BoardIsFull = InvalidUsage("Board is full, no emtpy spot! Attack!", 425)
RobotNotFound = InvalidUsage("Robot not found on given coordinates.", 426)
SizeIsNotValid = InvalidUsage("Size should be larger than 1!", 427)
ServerError = InvalidUsage("Server Error!", 500)
ExceptionResponses = {
NotCorrectDirection.status_code: NotCorrectDirection.message,
IdNotFound.status_code: IdNotFound.message,
CoordinatesNotEmpty.status_code: CoordinatesNotEmpty.message,
CoordinatesNotValid.status_code: CoordinatesNotValid.message,
ErrorOnBoardCoding.status_code: ErrorOnBoardCoding.message,
ErrorBoardCreation.status_code: ErrorBoardCreation.message,
BoardIsFull.status_code: BoardIsFull.message,
RobotNotFound.status_code: RobotNotFound.message,
ServerError.status_code: ServerError.message
}
|
"""
Here we create template function
"""
def function_file2(value=1):
print(f"you have called function from file 2 level 1")
return value + 1
|
def build_response(parameters):
response = {}
if("success" in parameters and parameters["success"] == True):
response['success'] = True
else:
response['success'] = False
if("response" in parameters):
response["response"] = parameters["response"]
if("error" in parameters):
response['error'] = parameters["error"]
if("context" in parameters):
response['@context'] = parameters["context"]
return response
|
f = open("Q20/testinputs.txt","r")
#ques_input = [i.strip("\n") for i in f.readlines()]
a,b = f.read().split("\n\n")
b = "".join(b).split("\n")
trans = []
for i in range(-1,2,1):
for j in range(-1,2,1):
trans += [(i,j)]
# rowlength = len(b[0])
# top_row = [inf_symbol] * (rowlength+4)
inf_symbol = "."
flip_switch = True
for _ in range(50):
rowlength = len(b[0])
top_row = [inf_symbol] * (rowlength+4)
new_matrix = []
next_iter = []
for _ in range(2):
new_matrix += [top_row[:]]
next_iter += [top_row[:]]
for c in b:
new_matrix += [[inf_symbol]*2 + list(c) + [inf_symbol]*2]
next_iter += [top_row[:]]
for _ in range(2):
new_matrix += [top_row[:]]
next_iter += [top_row[:]]
b = new_matrix
k = 0
for i in range(1,len(new_matrix)-1):
for j in range(1,len(new_matrix[i])-1):
u = ""
for x,y in [(-1,-1),(-1,0),(-1,1),(0,-1),(0,0),(0,1),(1,-1),(1,0),(1,1)]:
u += b[i+x][j+y]
binnum = int(u.replace(".","0").replace("#","1"),2)
next_iter[i][j] = a[binnum]
# if j == 0:
# #print(i,j)
b = [row[1:-1] for row in next_iter[1:-1]]
if flip_switch:
if inf_symbol == "#":
inf_symbol = "."
else:
inf_symbol = "#"
# for i in b:
# print("".join(i))
# 1/0
fstr = ""
for i in b:
fstr += "".join(i)
print(fstr.count("#")) |
COMPANY_SCALE_CHOICE = [
('0-15', '少于 15 人'),
('15-50', '15 - 50 人'),
('50-150', '50 - 150 人'),
('150-500', '150 - 500 人'),
('500-2000', '500 - 2000 人'),
('2000-', '2000 人以上')
]
COMPANY_FINANCING_CHOICE = [
('none', '未融资'),
('angel', '天使轮'),
('a', 'A 轮'),
('b', 'B 轮'),
('c', 'C 轮'),
('d', 'D 轮以上'),
('d', 'D 轮以上'),
('listed', '上市公司'),
('not_need', '不需要融资')
]
JOB_SALARY_CHOICE = [
('0-2000', '2k 以下'),
('2000-5000', '2k-5k'),
('5000-10000', '5k-10k'),
('10000-15000', '10k-15k'),
('15000-25000', '15k-25k'),
('25000-50000', '25k-50k'),
('50000-', '50k 以上')
]
JOB_EXPERIENCE_CHOICE = [
('new', '在校/应届'),
('0-3', '3 年以下'),
('3-5', '3-5 年'),
('5-10', '5-10 年'),
('10-', '10 年以上'),
('none', '无要求')
] |
goal = int(input('Write a number: '))
epsilon = 0.01
low = 0.0
high = max(1.0, goal)
answer = (high + low) / 2
while abs(answer**2 - goal) >= epsilon:
if answer**2 < goal:
low = answer
else:
high = answer
answer = (high + low) / 2
print(f'The square root of {goal} is {answer}') |
class CustomListIndexException(Exception):
pass
class CustomListTypeException(Exception):
pass
class CustomListSumException(Exception):
pass
|
# len = 1001
tp_qtys = (
(0.0, 0.0, 0.0, 0.0, 1.0),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 0.0, 0.0),
(0.8, 0.0, 0.0, 0.0, 0.2),
(0.8, 0.0, 0.0, 0.1, 0.1),
(0.8, 0.0, 0.0, 0.2, 0.0),
(0.8, 0.0, 0.1, 0.0, 0.1),
(0.8, 0.0, 0.1, 0.1, 0.0),
(0.8, 0.0, 0.2, 0.0, 0.0),
(0.8, 0.1, 0.0, 0.0, 0.1),
(0.8, 0.1, 0.0, 0.1, 0.0),
(0.8, 0.1, 0.1, 0.0, 0.0),
(0.8, 0.2, 0.0, 0.0, 0.0),
(0.9, 0.0, 0.0, 0.0, 0.1),
(0.9, 0.0, 0.0, 0.1, 0.0),
(0.9, 0.0, 0.1, 0.0, 0.0),
(0.9, 0.1, 0.0, 0.0, 0.0),
(1.0, 0.0, 0.0, 0.0, 0.0)
)
|
def binary_prefix(value, binary=True):
'''Return a tuple with a scaled down version of value and it's binary prefix
Parameters:
- `value`: numeric type to trim down
- `binary`: use binary (ICE) or decimal (SI) prefix
'''
SI = 'kMGTPEZY'
unit = binary and 1024. or 1000.
for i in range(-1, len(SI)):
if abs(value) < unit:
break
value/= unit
return (value, i<0 and '' or (binary and SI[i].upper() + 'i' or SI[i]))
|
a, b, c = [int(x) for x in input().split()]
if c >= a and c <= b:
print("Yes")
else:
print("No")
|
"""
All modules contained in frontend were written to be compiled bythe transpiler (transcrypt), they were not tested
in Cpython.
"""
|
def lambda_handler(event, context):
print("event ->", event)
print("context ->", context)
return {"statusCode": "200", "body" : "hello from user profile"}
|
# is.numeric() verifica se o conteúdo da string pode ser convertido para número
num = '3'
palavra = 'Olá'
decimal = '5.2a'
print(num.isnumeric())
print(palavra.isnumeric())
print(palavra.isalpha()) |
#coding=utf-8
'''
删除设备:Dev_Del
request:
{
"user_id":"1", #设备所属的用户
"dev_id":1, #模块的id
}
return:
{
"error":"SUCCESS", #
}
'''
def main(data):
cip=data['client_ip']
par=data['params']
red=data['red']
dbconn=data['dbconn']
cur=data['dbcursor']
assert('dev_id' in par)
cur.execute('''delete from device where dev_id=%(dev_id)s'''%par)
dbconn.commit()
res=dict(error='SUCCESS')
return res
|
class SDKConfig(object):
"""
The class to configure the SDK.
"""
def __init__(self, auto_refresh_fields=False, pick_list_validation=True, read_timeout=None, connect_timeout=None):
"""
Creates an instance of SDKConfig with the following parameters
Parameters:
auto_refresh_fields(bool): A bool representing auto_refresh_fields
pick_list_validation(bool): A bool representing pick_list_validation
read_timeout(float): A Float representing read_timeout
connect_timeout(float): A Float representing connect_timeout
"""
self.__auto_refresh_fields = auto_refresh_fields
self.__pick_list_validation = pick_list_validation
self.__read_timeout = read_timeout
self.__connect_timeout = connect_timeout
def get_auto_refresh_fields(self):
"""
This is a getter method to get auto_refresh_fields.
Returns:
bool: A bool representing auto_refresh_fields
"""
return self.__auto_refresh_fields
def get_pick_list_validation(self):
"""
This is a getter method to get pick_list_validation.
Returns:
bool: A bool representing pick_list_validation
"""
return self.__pick_list_validation
def get_read_timeout(self):
"""
This is a getter method to get read_timeout.
Returns:
Float: A Float representing read_timeout
"""
return self.__read_timeout
def get_connect_timeout(self):
"""
This is a getter method to get connect_timeout.
Returns:
Float: A Float representing connect_timeout
"""
return self.__connect_timeout
|
#coding: UTF8
"""
Module description.
"""
|
# Python Classes and Objects
# Python is an Object-oriented Programming Language and almost everything in Python is an object with it properties and methods
# A Python Class is like an object constructor or a blueprint for creating objects
class Employee:
# This "Employee" class contains one variable "age"
age = 30
# Class instantiation uses function notation.
# The class object is a parameterless function that returns a new instance of the class.
# The below code creates a new instance of the class named "Employee" and assigns this object to the local variable named "employeeObject"
employeeObject = Employee()
print(employeeObject.age)
print("**********************************************************")
# _init_function of a class
# This gets executed when the class is being initiated. It can be used to assign values
# to object properties or ot other properties that are necessary when the object is
# being created
class Person:
# This "Person" class contains one public method "printAge" and a constructor
# The "self" parameter is a reference to the class itself, and is used to access variables
# that belongs to the class. It does not have to be named "self" , we can call it
# whatever we like, but it has to be the first parameter of any function in the class.
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city
# Object Methods
# Objects can also contain methods. Methods in objects are functions that belong to the object
def printAge(self):
print("Printing the age of the person and his age is: " + str(self.age))
personObject1 = Person("Sam", 30, "Pune")
print("The name of the person is: " + personObject1.name)
print("The age of the person is: " + str(personObject1.age))
print("The city where the person lives is: " + personObject1.city)
print("**********************************************************")
personObject2 = Person("Richard", 35, "Kolkata")
personObject2.printAge()
print("**********************************************************")
# We can also modify, delete the object properties like below
personObject2.age = 40
personObject2.printAge()
del personObject2.age
# personObject2.printAge() # This will throw AttributeError
print("**********************************************************")
# We can also delete objects
del personObject2
# personObject2.printAge() # This will throw NameError
print("**********************************************************")
|
def traverse_nested_dict(d):
iters = [d.iteritems()]
while iters:
it = iters.pop()
try:
k, v = it.next()
except StopIteration:
continue
iters.append(it)
if isinstance(v, dict):
iters.append(v.iteritems())
yield k, v
def transform_to_json(dot_notation_dict):
keys_dict = {}
delim = '.'
for key, val in dot_notation_dict.items():
if delim in key:
splits = key.split(delim)
if splits[0] not in keys_dict:
keys_dict[splits[0]] = {}
keys_dict[splits[0]]['.'.join(splits[1:])] = val
else:
keys_dict[key] = val
for key, val in keys_dict.items():
if isinstance(val, dict):
keys_dict[key] = transform_to_json(val)
return keys_dict
|
T = int(input())
for i in range(T):
n_A = int(input())
A = set([int(j) for j in input().split(' ')])
n_B = int(input())
B = set([int(j) for j in input().split(' ')])
if not A.difference(B):
print("True")
else:
print("False") |
bad_char = {"," , "₹"}
def Clean_price(price):
for char in bad_char:
price = price.replace(char,'')
return float(price)
|
# Принадлежит ли точка квадрату - 1
def is_point_in_square(x, y):
axis_x = -1 <= x <= 1
axis_y = -1 <= y <= 1
return axis_x and axis_y
if __name__ == '__main__':
x, y = float(input()), float(input())
if is_point_in_square(x, y):
print("YES")
else:
print("NO")
|
for _ in range(int(input())):
n=int(input())
if(n%4==0 or n%4==1):
print((n//4)**2)
else:
print(((n//4)+1) * (n//4))
|
class TSTreeNode(object):
def __init__(self, char, key, value, low, eq, high):
self.char = char
self.key = key
self.low = low
self.eq = eq
self.high = high
self.value = value
def __repr__(self):
return f"{self.key}:{self.value}<{self.low and self.low.key}={self.eq and self.eq.key}={self.high and self.high.key}>"
class TSTree(object):
def __init__(self):
self.root = None
def _get(self, node, chars):
char = chars[0]
if node == None:
return None
elif char < node.char:
return self._get(node.low, chars)
elif char == node.char:
if len(chars) > 1:
return self._get(node.eq, chars[1:])
else:
return node
else:
return self._get(node.high, chars)
def get(self, key):
chars = [ord(x) for x in key]
node = self._get(self.root, chars)
return node and node.value or None
def _set(self, node, chars, key, value):
next_char = chars[0]
if not node:
# what happens if you add the value here?
node = TSTreeNode(next_char, None, None, None, None, None)
if next_char < node.char:
node.low = self._set(node.low, chars, key, value)
elif next_char == node.char:
if len(chars) > 1:
node.eq = self._set(node.eq, chars[1:], key, value)
else:
# what happens if you DO NOT add the value here?
node.value = value
node.key = key
else:
node.high = self._set(node.high, chars, key, value)
return node
def set(self, key, value):
chars = [ord(x) for x in key]
self.root = self._set(self.root, chars, key, value)
def find_shortest(self, key):
nodes = self.find_all(key)
if nodes:
shortest = nodes[0]
for node in nodes:
if len(node.key) < len(shortest.key):
shortest = node
return shortest
else:
return None
def find_longest(self, key):
nodes = self.find_all(key)
longest = nodes[0]
for node in nodes:
if len(node.key) > len(longest.key):
longest = node
return longest
def _find_all(self, node, key, results):
if not node: return
if node.key and node.value:
# this node has something so save it
results.append(node)
# if there is a low then go low
if node.low:
self._find_all(node.low, key, results)
if node.eq:
# now follow middle
self._find_all(node.eq, key, results)
if node.high:
# if there is a high then go high
self._find_all(node.high, key, results)
def find_all(self, key):
results = []
chars = [ord(x) for x in key]
start = self._get(self.root, chars)
if start:
self._find_all(start.eq, key, results)
return results
def find_part(self, key):
"""The difference between part and shortest is this:
If you give find_part a 10 char key, and only 2 chars of the key
match 2 chars in the TSTree, then it will return that key. It is
partial on *both* search key and key/value key.
If you give a 10 char key to shortest, and only 2 chars match then
it doesn't find anything.
"""
# start by just finding the shortest key starting with the first char
found = self.find_shortest(key[:1])
if not found: return None
# now if we found something then keep increasing the key
for i in range(2, len(key)):
stem = key[:i]
node = self.find_shortest(stem)
if not node:
# didn't find something with the new key, so return what
# we've found so far
return found
else:
# found something, so update the best match so far
found = node
return found
|
BASE_URL = 'https://imdb.com'
URLS = {
'Top 250 movies': '/chart/top/',
'Most popular movies': '/chart/moviemeter/',
'Top 250 TV shows': '/chart/toptv/',
'Most popular TV shows': '/chart/tvmeter/',
'Lowest rated movies': '/chart/bottom/',
}
def get_url(url_key):
if url_key in URLS:
return BASE_URL + URLS[url_key]
return BASE_URL + url_key
|
#Array
curso = " Curso de Python "
print(curso.strip()) # remove os espaços
print("Tamanho: " +str (len(curso)))
|
"""
Useful base functionality for use internally by the operations modules
"""
class Operation(object):
"""
An abstract operation that represents some modification/action on
this operations's image. Implementation of a particular operation can be created by
subclassing this and then overidding the `run()` method (and possibly the constructor).
This abstraction allows bookkeeping/higher-level parts of the api to treat
each operation as a discrete command, for the purposes of undos, tracking, etc.
"""
def __init__(self, image, *args, **kwargs):
"""
Initializes the operation
:Parameters:
image : `Image`
An image to operate on
"""
self.image = image
self.opimage = None
def run(self):
"""
Runs the operation and returns the resulting image after applying the operation
:Rtype:
`Image`
"""
self.opimage = self.image.clone()
return self.opimage
|
while True:
try:
a = float(input('Number: '))
except ValueError:
print('Please, numbers only.')
continue
break
print('You entered a number: {}'.format(a))
|
class Solution:
def maxProduct(self, nums: List[int]) -> int:
ans , max_p, min_p = nums[0], 1, 1
for num in nums:
max_p, min_p = max(num, min_p*num, max_p* num), min(num, min_p*num, max_p*num)
ans = max(ans, max_p)
return ans
|
# Exercício Python 086: Crie um programa que declare uma matriz de dimensão 3x3 e preencha com valores lidos pelo teclado.
# No final, mostre a matriz na tela, com a formatação correta.
#Inicializando com 0's.
matrix = [[0,0,0], [0,0,0], [0,0,0]]
for i in range(0,3):
for j in range(0,3):
matrix[i][j] = int(input(f'Enter a number in the position: '))
for i in range(0,3):
for j in range(0,3):
print(f'[{matrix[i][j]:^5}]', end='')
print()
|
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
t = bin(n)[2:]
return int(((32 - len(t)) * "0" + t)[: : -1], 2) |
'''Simple parsing using mxTextTools
See the /doc subdirectory for introductory and
general documentation. See license.txt for licensing
information. (This is a BSD-licensed package).
'''
__version__="2.1.1"
|
class Stack:
def __init__(self):
self.stack = []
def push(self, el):
self.stack.append(el)
def pop(self):
return self.stack.pop()
def peek(self):
return self.stack[-1]
def is_empty(self):
return len(self.stack) == 0
|
class Student:
def __init__(self, name, phy, chem, bio):
self.name = name
self.phy = phy
self.chem = chem
self.bio = bio
def totalObtained(self):
return(self.phy + self.chem + self.bio)
def percentage(self):
return((self.totalObtained() / 300) * 100)
|
local_var = "foo"
class C:
local_var = local_var #pass
def foo(self):
print(self.local_var)
C().foo()
|
numero = int(input("\033[35mMe diga um número qualquer:\033[m "))
par = numero % 2 == 0
if par:
print("\033[36mEsse número é PAR!\033[m")
else:
print("\033[36mEsse número é ÍMPAR!\033[m")
|
n = int(input())
lista = list(map(int,input().split(" ")))
menor = lista[0]
posicao = 0
for i in range(len(lista)):
if menor > lista[i]:
menor = lista[i]
posicao = i
print("Menor valor: {}".format(menor))
print("Posicao: {}".format(posicao))
|
a = list(map(int, input().split()))
def mergesort(a):
if len(a) > 1:
mid = len(a) // 2
left = a[:mid]
right = a[mid:]
mergesort(left)
mergesort(right)
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
a[k] = left[i]
i += 1
elif right[j] < left[i]:
a[k] = right[j]
j += 1
k += 1
while i < len(left):
a[k] = left[i]
i += 1
k += 1
while j < len(right):
a[k] = right[j]
j += 1
k += 1
mergesort(a)
print(a)
|
# -*- coding: utf-8 -*-
# # Figure 14-2 from page 284
class Item(object):
def __init__(self, n, v, w):
self._name = n
self._value = v
self._weight = w
def get_name(self):
return self._name
def get_value(self):
return self._value
def get_weight(self):
return self._weight
def __str__(self):
return f'<{self._name}, {self._value}, {self._weight}>'
def value(item):
return item.get_value()
def weight_inverse(item):
return 1.0/item.get_weight()
def density(item):
return item.get_value()/item.get_weight()
# # Figure 14-3 from page 284
def greedy(items, max_weight, key_function):
"""Assumes items a list, max_weight >= 0,
key_function maps elements of items to numbers"""
items_copy = sorted(items, key=key_function, reverse = True)
result = []
total_value, total_weight = 0.0, 0.0
for i in range(len(items_copy)):
if (total_weight + items_copy[i].get_weight()) <= max_weight:
result.append(items_copy[i])
total_weight += items_copy[i].get_weight()
total_value += items_copy[i].get_value()
return (result, total_value)
# # Figure 14-4 from page 286
def build_items():
names = ['clock','painting','radio','vase','book','computer']
values = [175,90,20,50,10,200]
weights = [10,9,4,2,1,20]
Items = []
for i in range(len(values)):
Items.append(Item(names[i], values[i], weights[i]))
return Items
def test_greedy(items, max_weight, key_function):
taken, val = greedy(items, max_weight, key_function)
print('Total value of items taken is', val)
for item in taken:
print(' ', item)
def test_greedys(max_weight = 20):
items = build_items()
print('Use greedy by value to fill knapsack of size', max_weight)
test_greedy(items, max_weight, value)
print('\nUse greedy by weight to fill knapsack of size',
max_weight)
test_greedy(items, max_weight, weight_inverse)
print('\nUse greedy by density to fill knapsack of size',
max_weight)
test_greedy(items, max_weight, density)
# # Code from page 287
# test_greedys()
# # Code from Figure 11-6
def get_binary_rep(n, num_digits):
"""Assumes n and numDigits are non-negative ints
Returns a str of length numDigits that is a binary
representation of n"""
result = ''
while n > 0:
result = str(n%2) + result
n = n//2
if len(result) > num_digits:
raise ValueError('not enough digits')
for i in range(num_digits - len(result)):
result = '0' + result
return result
def gen_powerset(L):
"""Assumes L is a list
Returns a list of lists that contains all possible
combinations of the elements of L. E.g., if
L is [1, 2] it will return a list with elements
[], [1], [2], and [1,2]."""
powerset = []
for i in range(0, 2**len(L)):
bin_str = get_binary_rep(i, len(L))
subset = []
for j in range(len(L)):
if bin_str[j] == '1':
subset.append(L[j])
powerset.append(subset)
return powerset
# # Figure 14-5 on page 289
def choose_best(pset, max_weight, get_val, get_weight):
best_val = 0.0
best_set = None
for items in pset:
items_val = 0.0
items_weight = 0.0
for item in items:
items_val += get_val(item)
items_weight += get_weight(item)
if items_weight <= max_weight and items_val > best_val:
best_val = items_val
best_set = items
return (best_set, best_val)
def test_best(max_weight = 20):
items = build_items()
pset = gen_powerset(items)
taken, val = choose_best(pset, max_weight, Item.get_value,
Item.get_weight)
print('Total value of items taken is', val)
for item in taken:
print(item)
# test_best()
# # Figure 14-7 on page 294
class Node(object):
def __init__(self, name):
"""Assumes name is a string"""
self._name = name
def get_name(self):
return self._name
def __str__(self):
return self._name
class Edge(object):
def __init__(self, src, dest):
"""Assumes src and dest are nodes"""
self._src = src
self._dest = dest
def get_source(self):
return self._src
def get_destination(self):
return self._dest
def __str__(self):
return self._src.get_name() + '->' + self._dest.get_name()
class Weighted_edge(Edge):
def __init__(self, src, dest, weight = 1.0):
"""Assumes src and dest are nodes, weight a number"""
self._src = src
self._dest = dest
self._weight = weight
def get_weight(self):
return self._weight
def __str__(self):
return (f'{self._src.get_name()}->({self._weight})' +
f'{self._dest.get_name()}')
# # Figure 14-8 on page 296
class Digraph(object):
#nodes is a list of the nodes in the graph
#edges is a dict mapping each node to a list of its children
def __init__(self):
self._nodes = []
self._edges = {}
def add_node(self, node):
if node in self._nodes:
raise ValueError('Duplicate node')
else:
self._nodes.append(node)
self._edges[node] = []
def add_edge(self, edge):
src = edge.get_source()
dest = edge.get_destination()
if not (src in self._nodes and dest in self._nodes):
raise ValueError('Node not in graph')
self._edges[src].append(dest)
def children_of(self, node):
return self._edges[node]
def has_node(self, node):
return node in self._nodes
def __str__(self):
result = ''
for src in self._nodes:
for dest in self._edges[src]:
result = (result + src.get_name() + '->'
+ dest.get_name() + '\n')
return result[:-1] #omit final newline
class Graph(Digraph):
def add_edge(self, edge):
Digraph.add_edge(self, edge)
rev = Edge(edge.get_destination(), edge.get_source())
Digraph.add_edge(self, rev)
# # Figure 14-9 on page 299
def print_path(path):
"""Assumes path is a list of nodes"""
result = ''
for i in range(len(path)):
result = result + str(path[i])
if i != len(path) - 1:
result = result + '->'
return result
def DFS(graph, start, end, path, shortest, to_print = False):
"""Assumes graph is a Digraph; start and end are nodes;
path and shortest are lists of nodes
Returns a shortest path from start to end in graph"""
path = path + [start]
if to_print:
print('Current DFS path:', print_path(path))
if start == end:
return path
for node in graph.children_of(start):
if node not in path: #avoid cycles
if shortest == None or len(path) < len(shortest):
new_path = DFS(graph, node, end, path, shortest,
to_print)
if new_path != None:
shortest = new_path
return shortest
def shortest_path(graph, start, end, to_print = False):
"""Assumes graph is a Digraph; start and end are nodes
Returns a shortest path from start to end in graph"""
return DFS(graph, start, end, [], None, to_print)
# # Figure 14-10 on page 301
def test_SP():
nodes = []
for name in range(6): #Create 6 nodes
nodes.append(Node(str(name)))
g = Digraph()
for n in nodes:
g.add_node(n)
g.add_edge(Edge(nodes[0],nodes[1]))
g.add_edge(Edge(nodes[1],nodes[2]))
g.add_edge(Edge(nodes[2],nodes[3]))
g.add_edge(Edge(nodes[2],nodes[4]))
g.add_edge(Edge(nodes[3],nodes[4]))
g.add_edge(Edge(nodes[3],nodes[5]))
g.add_edge(Edge(nodes[0],nodes[2]))
g.add_edge(Edge(nodes[1],nodes[0]))
g.add_edge(Edge(nodes[3],nodes[1]))
g.add_edge(Edge(nodes[4],nodes[0]))
sp = shortest_path(g, nodes[0], nodes[5], to_print = True)
print('Shortest path found by DFS:', print_path(sp))
# test_SP()
# # Figure 14-11 on page 303
def BFS(graph, start, end, to_print = False):
"""Assumes graph is a Digraph; start and end are nodes
Returns a shortest path from start to end in graph"""
init_path = [start]
path_queue = [init_path]
while len(path_queue) != 0:
#Get and remove oldest element in path_queue
tmp_path = path_queue.pop(0)
if to_print:
print('Current BFS path:', print_path(tmp_path))
last_node = tmp_path[-1]
if last_node == end:
return tmp_path
for next_node in graph.children_of(last_node):
if next_node not in tmp_path:
new_path = tmp_path + [next_node]
path_queue.append(new_path)
return None
# # test_sp modifed as per code on page 303
def test_SP():
nodes = []
for name in range(6): #Create 6 nodes
nodes.append(Node(str(name)))
g = Digraph()
for n in nodes:
g.add_node(n)
g.add_edge(Edge(nodes[0],nodes[1]))
g.add_edge(Edge(nodes[1],nodes[2]))
g.add_edge(Edge(nodes[2],nodes[3]))
g.add_edge(Edge(nodes[2],nodes[4]))
g.add_edge(Edge(nodes[3],nodes[4]))
g.add_edge(Edge(nodes[3],nodes[5]))
g.add_edge(Edge(nodes[0],nodes[2]))
g.add_edge(Edge(nodes[1],nodes[0]))
g.add_edge(Edge(nodes[3],nodes[1]))
g.add_edge(Edge(nodes[4],nodes[0]))
sp = shortest_path(g, nodes[0], nodes[5], to_print = True)
print('Shortest path found by DFS:', print_path(sp))
sp = BFS(g, nodes[0], nodes[5], to_print = True)
print('Shortest path found by BFS:', print_path(sp))
# test_SP()
|
'''
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
A leaf is a node with no children.
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
node_stack = []
node_stack.append((root, targetSum - root.val))
while node_stack:
node, curr_sum = node_stack.pop()
if not node.left and not node.right and curr_sum == 0:
return True
if node.right:
node_stack.append((node.right, curr_sum - node.right.val))
if node.left:
node_stack.append((node.left, curr_sum - node.left.val))
return False
def hasPathSum_recur(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
targetSum = targetSum - root.val
if not root.left and not root.right:
return targetSum == 0
return self.hasPathSum_recur(root.left, targetSum) or self.hasPathSum_recur(root.right, targetSum)
|
#
# PySNMP MIB module AP64STATS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AP64STATS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:07:11 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)
#
ap64Stats, = mibBuilder.importSymbols("APENT-MIB", "ap64Stats")
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
ModuleIdentity, Unsigned32, TimeTicks, iso, Counter64, IpAddress, Integer32, Counter32, Bits, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, Gauge32, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "Unsigned32", "TimeTicks", "iso", "Counter64", "IpAddress", "Integer32", "Counter32", "Bits", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "Gauge32", "NotificationType")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
ap64StatsMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 2467, 1, 44, 1))
if mibBuilder.loadTexts: ap64StatsMib.setLastUpdated('9710092000Z')
if mibBuilder.loadTexts: ap64StatsMib.setOrganization('ArrowPoint Communications Inc.')
class PhysAddress(OctetString):
pass
class OwnerString(DisplayString):
pass
class EntryStatus(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))
namedValues = NamedValues(("valid", 1), ("createRequest", 2), ("underCreation", 3), ("invalid", 4))
ap64dot3StatsTable = MibTable((1, 3, 6, 1, 4, 1, 2467, 1, 44, 2), )
if mibBuilder.loadTexts: ap64dot3StatsTable.setStatus('current')
ap64dot3StatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2467, 1, 44, 2, 1), ).setIndexNames((0, "AP64STATS-MIB", "ap64dot3StatsIndex"))
if mibBuilder.loadTexts: ap64dot3StatsEntry.setStatus('current')
ap64dot3StatsIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64dot3StatsIndex.setStatus('current')
ap64dot3StatsAlignmentErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 2, 1, 2), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64dot3StatsAlignmentErrors.setStatus('current')
ap64dot3StatsFCSErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 2, 1, 3), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64dot3StatsFCSErrors.setStatus('current')
ap64dot3StatsSingleCollisionFrames = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 2, 1, 4), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64dot3StatsSingleCollisionFrames.setStatus('current')
ap64dot3StatsMultipleCollisionFrames = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 2, 1, 5), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64dot3StatsMultipleCollisionFrames.setStatus('current')
ap64dot3StatsSQETestErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 2, 1, 6), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64dot3StatsSQETestErrors.setStatus('current')
ap64dot3StatsDeferredTransmissions = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 2, 1, 7), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64dot3StatsDeferredTransmissions.setStatus('current')
ap64dot3StatsLateCollisions = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 2, 1, 8), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64dot3StatsLateCollisions.setStatus('current')
ap64dot3StatsExcessiveCollisions = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 2, 1, 9), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64dot3StatsExcessiveCollisions.setStatus('current')
ap64dot3StatsInternalMacTransmitErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 2, 1, 10), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64dot3StatsInternalMacTransmitErrors.setStatus('current')
ap64dot3StatsCarrierSenseErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 2, 1, 11), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64dot3StatsCarrierSenseErrors.setStatus('current')
ap64dot3StatsFrameTooLongs = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 2, 1, 13), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64dot3StatsFrameTooLongs.setStatus('current')
ap64dot3StatsInternalMacReceiveErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 2, 1, 16), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64dot3StatsInternalMacReceiveErrors.setStatus('current')
ap64ifTable = MibTable((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3), )
if mibBuilder.loadTexts: ap64ifTable.setStatus('current')
ap64ifEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1), ).setIndexNames((0, "AP64STATS-MIB", "ap64ifIndex"))
if mibBuilder.loadTexts: ap64ifEntry.setStatus('current')
ap64ifIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifIndex.setStatus('current')
ap64ifDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifDescr.setStatus('current')
ap64ifType = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32))).clone(namedValues=NamedValues(("other", 1), ("regular1822", 2), ("hdh1822", 3), ("ddn-x25", 4), ("rfc877-x25", 5), ("ethernet-csmacd", 6), ("iso88023-csmacd", 7), ("iso88024-tokenBus", 8), ("iso88025-tokenRing", 9), ("iso88026-man", 10), ("starLan", 11), ("proteon-10Mbit", 12), ("proteon-80Mbit", 13), ("hyperchannel", 14), ("fddi", 15), ("lapb", 16), ("sdlc", 17), ("ds1", 18), ("e1", 19), ("basicISDN", 20), ("primaryISDN", 21), ("propPointToPointSerial", 22), ("ppp", 23), ("softwareLoopback", 24), ("eon", 25), ("ethernet-3Mbit", 26), ("nsip", 27), ("slip", 28), ("ultra", 29), ("ds3", 30), ("sip", 31), ("frame-relay", 32)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifType.setStatus('current')
ap64ifMtu = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifMtu.setStatus('current')
ap64ifSpeed = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 5), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifSpeed.setStatus('current')
ap64ifPhysAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 6), PhysAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifPhysAddress.setStatus('current')
ap64ifAdminStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("up", 1), ("down", 2), ("testing", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifAdminStatus.setStatus('current')
ap64ifOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("up", 1), ("down", 2), ("testing", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifOperStatus.setStatus('current')
ap64ifLastChange = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 9), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifLastChange.setStatus('current')
ap64ifInOctets = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 10), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifInOctets.setStatus('current')
ap64ifInUcastPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 11), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifInUcastPkts.setStatus('current')
ap64ifInNUcastPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 12), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifInNUcastPkts.setStatus('current')
ap64ifInDiscards = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 13), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifInDiscards.setStatus('current')
ap64ifInErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 14), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifInErrors.setStatus('current')
ap64ifInUnknownProtos = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 15), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifInUnknownProtos.setStatus('current')
ap64ifOutOctets = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 16), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifOutOctets.setStatus('current')
ap64ifOutUcastPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 17), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifOutUcastPkts.setStatus('current')
ap64ifOutNUcastPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 18), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifOutNUcastPkts.setStatus('current')
ap64ifOutDiscards = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 19), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifOutDiscards.setStatus('current')
ap64ifOutErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 20), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifOutErrors.setStatus('current')
ap64ifOutQLen = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 21), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifOutQLen.setStatus('current')
ap64ifSpecific = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 3, 1, 22), ObjectIdentifier()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64ifSpecific.setStatus('current')
ap64etherStatsTable = MibTable((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4), )
if mibBuilder.loadTexts: ap64etherStatsTable.setStatus('current')
ap64etherStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1), ).setIndexNames((0, "AP64STATS-MIB", "ap64etherStatsIndex"))
if mibBuilder.loadTexts: ap64etherStatsEntry.setStatus('current')
ap64etherStatsIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsIndex.setStatus('current')
ap64etherStatsDataSource = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 2), ObjectIdentifier()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsDataSource.setStatus('current')
ap64etherStatsDropEvents = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 3), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsDropEvents.setStatus('current')
ap64etherStatsOctets = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 4), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsOctets.setStatus('current')
ap64etherStatsPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 5), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsPkts.setStatus('current')
ap64etherStatsBroadcastPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 6), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsBroadcastPkts.setStatus('current')
ap64etherStatsMulticastPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 7), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsMulticastPkts.setStatus('current')
ap64etherStatsCRCAlignErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 8), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsCRCAlignErrors.setStatus('current')
ap64etherStatsUndersizePkts = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 9), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsUndersizePkts.setStatus('current')
ap64etherStatsOversizePkts = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 10), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsOversizePkts.setStatus('current')
ap64etherStatsFragments = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 11), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsFragments.setStatus('current')
ap64etherStatsJabbers = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 12), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsJabbers.setStatus('current')
ap64etherStatsCollisions = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 13), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsCollisions.setStatus('current')
ap64etherStatsPkts64Octets = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 14), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsPkts64Octets.setStatus('current')
ap64etherStatsPkts65to127Octets = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 15), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsPkts65to127Octets.setStatus('current')
ap64etherStatsPkts128to255Octets = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 16), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsPkts128to255Octets.setStatus('current')
ap64etherStatsPkts256to511Octets = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 17), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsPkts256to511Octets.setStatus('current')
ap64etherStatsPkts512to1023Octets = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 18), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsPkts512to1023Octets.setStatus('current')
ap64etherStatsPkts1024to1518Octets = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 19), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsPkts1024to1518Octets.setStatus('current')
ap64etherStatsOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 20), OwnerString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsOwner.setStatus('current')
ap64etherStatsStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 44, 4, 1, 21), EntryStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ap64etherStatsStatus.setStatus('current')
mibBuilder.exportSymbols("AP64STATS-MIB", ap64etherStatsPkts64Octets=ap64etherStatsPkts64Octets, ap64etherStatsIndex=ap64etherStatsIndex, ap64etherStatsStatus=ap64etherStatsStatus, ap64etherStatsJabbers=ap64etherStatsJabbers, ap64ifInNUcastPkts=ap64ifInNUcastPkts, ap64etherStatsCollisions=ap64etherStatsCollisions, ap64dot3StatsInternalMacReceiveErrors=ap64dot3StatsInternalMacReceiveErrors, ap64dot3StatsExcessiveCollisions=ap64dot3StatsExcessiveCollisions, ap64ifLastChange=ap64ifLastChange, ap64ifOutDiscards=ap64ifOutDiscards, ap64ifMtu=ap64ifMtu, ap64ifInUcastPkts=ap64ifInUcastPkts, ap64ifInErrors=ap64ifInErrors, ap64dot3StatsIndex=ap64dot3StatsIndex, ap64etherStatsPkts=ap64etherStatsPkts, PYSNMP_MODULE_ID=ap64StatsMib, ap64etherStatsOwner=ap64etherStatsOwner, ap64dot3StatsSingleCollisionFrames=ap64dot3StatsSingleCollisionFrames, ap64ifInDiscards=ap64ifInDiscards, OwnerString=OwnerString, ap64etherStatsPkts128to255Octets=ap64etherStatsPkts128to255Octets, ap64ifSpecific=ap64ifSpecific, ap64etherStatsEntry=ap64etherStatsEntry, ap64ifType=ap64ifType, ap64ifOutOctets=ap64ifOutOctets, ap64etherStatsDropEvents=ap64etherStatsDropEvents, ap64etherStatsOversizePkts=ap64etherStatsOversizePkts, ap64StatsMib=ap64StatsMib, ap64ifAdminStatus=ap64ifAdminStatus, ap64ifOutErrors=ap64ifOutErrors, ap64dot3StatsLateCollisions=ap64dot3StatsLateCollisions, ap64etherStatsPkts512to1023Octets=ap64etherStatsPkts512to1023Octets, ap64dot3StatsTable=ap64dot3StatsTable, PhysAddress=PhysAddress, ap64ifOperStatus=ap64ifOperStatus, ap64dot3StatsMultipleCollisionFrames=ap64dot3StatsMultipleCollisionFrames, ap64ifEntry=ap64ifEntry, ap64dot3StatsAlignmentErrors=ap64dot3StatsAlignmentErrors, ap64ifOutNUcastPkts=ap64ifOutNUcastPkts, ap64ifSpeed=ap64ifSpeed, ap64dot3StatsFrameTooLongs=ap64dot3StatsFrameTooLongs, ap64etherStatsPkts1024to1518Octets=ap64etherStatsPkts1024to1518Octets, ap64dot3StatsSQETestErrors=ap64dot3StatsSQETestErrors, ap64dot3StatsInternalMacTransmitErrors=ap64dot3StatsInternalMacTransmitErrors, ap64etherStatsMulticastPkts=ap64etherStatsMulticastPkts, ap64etherStatsDataSource=ap64etherStatsDataSource, ap64ifDescr=ap64ifDescr, ap64etherStatsTable=ap64etherStatsTable, ap64etherStatsOctets=ap64etherStatsOctets, ap64etherStatsCRCAlignErrors=ap64etherStatsCRCAlignErrors, ap64etherStatsPkts65to127Octets=ap64etherStatsPkts65to127Octets, ap64ifOutUcastPkts=ap64ifOutUcastPkts, ap64etherStatsFragments=ap64etherStatsFragments, EntryStatus=EntryStatus, ap64dot3StatsDeferredTransmissions=ap64dot3StatsDeferredTransmissions, ap64ifInOctets=ap64ifInOctets, ap64etherStatsUndersizePkts=ap64etherStatsUndersizePkts, ap64dot3StatsFCSErrors=ap64dot3StatsFCSErrors, ap64dot3StatsCarrierSenseErrors=ap64dot3StatsCarrierSenseErrors, ap64ifTable=ap64ifTable, ap64ifOutQLen=ap64ifOutQLen, ap64etherStatsBroadcastPkts=ap64etherStatsBroadcastPkts, ap64ifPhysAddress=ap64ifPhysAddress, ap64etherStatsPkts256to511Octets=ap64etherStatsPkts256to511Octets, ap64dot3StatsEntry=ap64dot3StatsEntry, ap64ifInUnknownProtos=ap64ifInUnknownProtos, ap64ifIndex=ap64ifIndex)
|
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: jianzhi_offer_65_1.py
@time: 2019/4/25 15:29
@desc:
'''
class Solution:
def maxInWindows(self, num, size):
if not num or size <= 0:
return []
if size > len(num):
return []
if size == 1:
return num
idx = [] # queue stores index, max value in [0]
res = [] # results
# first size numbers
for i in range(size):
while idx and num[i] >= num[idx[-1]]:
idx.pop()
idx.append(i) # only store index
res.append(num[idx[0]]) # the first max value in the first sliding window
# other numbers
for i in range(size, len(num)):
if idx[0] <= i - size: # index[0] is out of the window
idx.pop(0)
while idx and num[i] >= num[idx[-1]]:
idx.pop()
idx.append(i)
res.append(num[idx[0]])
return res
if __name__ == '__main__':
num = [2,3,4,2,6,2,5,1]
res = Solution()
a = res.maxInWindows(num, 3)
print(a)
|
n=int(input("Enter the number : "))
sum=0
order=len(str(n))
copy_n=n
while(n>0):
digit=n%10
sum+=digit**order
n=n//10
if(sum==copy_n):
print(f"{copy_n} is an armstrong number")
else:
print(f"{copy_n} is not an armstrong number")
|
# Aula 15 - Interrompendo repetições while
cont = soma = 0
while True:
num = int(input('Digite um numero: '))
if num == 999:
break
soma += num
cont += 1
print('FIM!')
print(f'Os {cont} numeros somados deram = {soma}.')
|
a = True
while a:
if(not a):
a = get()
else:
execute(b)
a = execute(mogrify(a)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.