content
stringlengths 7
1.05M
|
---|
v_carro = float(input("Informe o valor: "))
total_mes_carro = (0.004 * v_carro) +v_carro
p_inicial = 10000
renda_total = (0.007 * p_inicial) + p_inicial
mes = -1
while True:
mes += 1
total_mes_carro = (0.004 * total_mes_carro) + total_mes_carro
if renda_total < total_mes_carro:
renda_total = (0.007 * renda_total) + renda_total
else:
break
print(f'Você so podera comprar um carro com {mes} meses!') |
_kirciuotos_raides = {
"a" : ["a`","a~","a^"],
"ą" : ["ą~","ą^"],
"e" : ["e`","e~","e^"],
"ę" : ["ę~","ę^"],
"ė" : ["ė~","ė^"],
"i" : ["i`","i~","i^"],
"į" : ["į~","į^"],
"y" : ["y~","y^"],
"o" : ["o`","o~","o^"],
"u" : ["u`","u~","u^"],
"ų" : ["ų~","ų^"],
"ū" : ["ū~","ū^"],
"l" : ["l~"],
"m" : ["m~"],
"n" : ["n~"],
"r" : ["r~"]
}
_fonemos = {
'regular' :['į', 'ų', 'c', 'č'],
'accent' : ['ą~','ą^','ę~','ę^','i^','į','į~','į^','u^','ų','ų~','ų^','c','č'],
'add' : ['ch']
}
def get_valid_symbol_ids(cleaners):
_simboliai = ' ?!.'
_balsiai = 'AaĄąEeĘęĖėIiĮįYyOoUuŲųŪū'
_priebalsiai_sprogstamieji = 'BbDdGgPpTtKk'
_priebalsiai_snypsciantieji = 'CcČčSsŠšZzŽžFfHh'
_priebalsiai_kiti = 'JjLlMmNnRrVv'
_kirciai = '~^`'
_raidynas = _balsiai + _priebalsiai_sprogstamieji + _priebalsiai_snypsciantieji + _priebalsiai_kiti
if "lowercase" in cleaners:
_raidynas = ''.join([x[0] for x in zip(_raidynas, _raidynas.upper()) if x[0] != x[1]])
if "accent_chars" in cleaners:
_raidynas += _kirciai
_raidynas = list(_raidynas) + list(_simboliai)
if "accent_letters" in cleaners:
for raide in _raidynas:
if raide in _kirciuotos_raides:
insert_index = _raidynas.index(raide) + 1
if "lowercase" not in cleaners:
kirciuotos_su_didz = []
for kirciuota_raide in _kirciuotos_raides[raide]:
kirciuotos_su_didz.append(kirciuota_raide.upper())
kirciuotos_su_didz.append(kirciuota_raide)
_raidynas[insert_index:insert_index] = kirciuotos_su_didz
else:
_raidynas[insert_index:insert_index] = _kirciuotos_raides[raide]
if "phonemes" in cleaners:
if "accent_letters" in cleaners:
_raidynas = [x for x in _raidynas if x.lower() not in _fonemos['accent']]
else:
_raidynas = [x for x in _raidynas if x.lower() not in _fonemos['regular']]
insert_index = _raidynas.index('h') + 1
_raidynas[insert_index:insert_index] = _fonemos['add']
return _raidynas
def get_symbol_len(cleaners):
return len(get_valid_symbol_ids(cleaners))
|
def exception_test(assert_check_fn):
try:
def exception_wrapper(*arg, **kwarg):
assert_check_fn(*arg, **kwarg)
except Exception as e:
pytest.failed(e) |
#########################
# 生成器
#########################
# 创建一个生成器
L = (x * 2 for x in range(5))
print(type(L))
print(L)
for value in L:
print(value, end=' ')
print()
# 创建一个函数生成器
def fib(times):
n = 0
a, b = 0, 1
while n < times:
"""
在循环过程中不断调用 yield ,就会不断中断。当然要给循环设置一个条件来退出循环,不然就会产生一个无限数列出来。
同样的,把函数改成generator后,我们基本上从来不会用 next() 来获取下一个返回值,而是直接使用 for 循环来迭代
"""
yield b
a, b = b, a + b
n += 1
return 'done'
for value in fib(10):
print(value, end=' ')
print()
# 如果想要拿到返回值,必须捕获StopIteration错误,返回值包含在StopIteration的value中
try:
fibSqu = fib(10)
while True:
print(next(fibSqu), end=' ')
except StopIteration as e:
print("生成器返回值:%s" % e.value, end='')
print()
# 使用send
def gen():
i = 0
while i < 5:
# temp为外部调用send函数时发送的值
temp = yield i
print('gen ', temp, end=' ')
i += 1
f = gen()
print(f.__next__()) # 必须先调用 __next__或 send(None)
print('send ', f.send('a'))
print('send ', f.send('b'))
print('send ', f.send('c'))
|
"""
Queries of issue queries
"""
def gql_issues(fragment):
"""
Return the GraphQL issues query
"""
return f'''
query ($where: IssueWhere!, $first: PageSize!, $skip: Int!) {{
data: issues(where: $where, first: $first, skip: $skip) {{
{fragment}
}}
}}
'''
GQL_ISSUES_COUNT = '''
query($where: IssueWhere!) {
data: countIssues(where: $where)
}
'''
|
"""
@desc Prints informations about the candidate : his/her profile and messages sent
@params candidate: instance of Candidate
"""
def show_candidate_informations(candidate):
print("## CANDIDATE PROFILE ##", end="\n\n")
print("Firstname: {}".format(candidate.firstname))
print("Lastname: {}".format(candidate.lastname))
print("Email address: {}".format(candidate.email))
print("Job: {}".format(candidate.job), end="\n\n")
print("## MESSAGE SENT ##", end="\n\n")
for message in candidate.messages:
print("{0} sent : {1}, {2} days ago".format(
message["name"],
message["ts_str"],
message["diff_to_today"])
)
def show_candidates(candidates):
for candidate in candidates:
print("\nFirstname: {0}, Lastname: {1}, Email address: {2}, Job: {3}".format(candidate.firstname, candidate.lastname, candidate.email, candidate.job))
for message in candidate.messages:
print("\t{0} sent : {1}, {2} days ago".format(
message["name"],
message["ts_str"],
message["diff_to_today"])
)
|
class Korean:
"""Korean speaker"""
def __init__(self):
self.name = "Korean"
def speak_korean(self):
return "An-neyong?"
class British:
"""English speaker"""
def __init__(self):
self.name = "British"
#Note the different method name here!
def speak_english(self):
return "Hello!"
class Adapter:
"""This changes the generic method name to individualized method names"""
def __init__(self, object, **adapted_method):
"""Change the name of the method"""
self._object = object
#Add a new dictionary item that establishes the mapping between the generic method name: speak() and the concrete method
#For example, speak() will be translated to speak_korean() if the mapping says so
self.__dict__.update(adapted_method)
def __getattr__(self, attr):
"""Simply return the rest of attributes!"""
return getattr(self._object, attr)
def main():
#List to store speaker objects
objects = []
#Create a Korean object
korean = Korean()
#Create a British object
british =British()
#Append the objects to the objects list
objects.append(Adapter(korean, speak=korean.speak_korean))
objects.append(Adapter(british, speak=british.speak_english))
for obj in objects:
print("{} says '{}'\n".format(obj.name, obj.speak()))
if __name__ == '__main__':
main()
|
def green(text):
return f"\033[92m{text}\033[0m"
def yellow(text):
return f"\033[93m{text}\033[0m"
|
# rainfall_mi is a string that contains the average number of inches of rainfall in Michigan for every month (in inches)
# with every month separated by a comma. Write code to compute the number of months that have more than 3 inches of
# rainfall. Store the result in the variable num_rainy_months. In other words, count the number of items with values > 3.0.
rainfall_mi = "1.65, 1.46, 2.05, 3.03, 3.35, 3.46, 2.83, 3.23, 3.5, 2.52, 2.8, 1.85"
rain_list = rainfall_mi.split(", ")
num_rainy_months = 0
for i in rain_list:
if float(i) > 3.0:
num_rainy_months += 1
# The variable sentence stores a string. Write code to determine how many words in sentence start and end with the same letter,
# including one-letter words. Store the result in the variable same_letter_count.
sentence = "students flock to the arb for a variety of outdoor activities such as jogging and picnicking"
same_letter_count = 0
sent_list = sentence.split()
for i in sent_list:
if i[0] == i[-1]:
same_letter_count += 1
# Write code to count the number of strings in list items that have the character w in it. Assign that number to the variable
# acc_num.
items = ["whirring", "wow!", "calendar", "wry", "glass", "", "llama","tumultuous","owing"]
acc_num = 0
for i in items:
if "w" in i:
acc_num += 1
# Write code that counts the number of words in sentence that contain either an “a” or an “e”. Store the result in the variable
# num_a_or_e.
sentence = "python is a high level general purpose programming language that can be applied to many different classes of problems."
sent_list = sentence.split()
num_a_or_e = 0
for i in sent_list:
if "a" in i or "e" in i:
num_a_or_e += 1
# Write code that will count the number of vowels in the sentence s and assign the result to the variable num_vowels. For this problem,
# vowels are only a, e, i, o, and u.
s = "singing in the rain and playing in the rain are two entirely different situations but both can be fun"
vowels = ['a','e','i','o','u']
num_vowels = 0
for i in s:
if i in vowels:
num_vowels += 1
|
MORSE_CODE_DICT = { 'A':'.-', 'B':'-...',
'C':'-.-.', 'D':'-..', 'E':'.',
'F':'..-.', 'G':'--.', 'H':'....',
'I':'..', 'J':'.---', 'K':'-.-',
'L':'.-..', 'M':'--', 'N':'-.',
'O':'---', 'P':'.--.', 'Q':'--.-',
'R':'.-.', 'S':'...', 'T':'-',
'U':'..-', 'V':'...-', 'W':'.--',
'X':'-..-', 'Y':'-.--', 'Z':'--..',
'1':'.----', '2':'..---', '3':'...--',
'4':'....-', '5':'.....', '6':'-....',
'7':'--...', '8':'---..', '9':'----.',
'0':'-----', ', ':'--..--', '.':'.-.-.-',
'?':'..--..', '/':'-..-.', '-':'-....-',
'(':'-.--.', ')':'-.--.-'}
# Function to encrypt the string
# according to the morse code chart
def encrypt(message):
cipher = ''
for letter in message:
if letter != ' ':
# Looks up the dictionary and adds the
# correspponding morse code
# along with a space to separate
# morse codes for different characters
cipher += MORSE_CODE_DICT[letter] + ' '
else:
# 1 space indicates different characters
# and 2 indicates different words
cipher += ' '
return cipher
# Hard-coded driver function to run the program
def main():
message = input("Enter a Word or Phrase")
result = encrypt(message.upper())
print (result)
# Executes the main function
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
class MyClass:
# The __init__ method doesn't return anything, so it gets return
# type None just like any other method that doesn't return anything.
def __init__(self) -> None:
...
# For instance methods, omit `self`.
def my_class_method(self, num: int, str1: str) -> str:
return num * str1
# User-defined classes are written with just their own names.
x = MyClass() # type: MyClass
|
expected_output = {
"bridge_group": {
"D": {
"bridge_domain": {
"D-w": {
"ac": {
"num_ac": 1,
"num_ac_up": 1
},
"id": 0,
"pbb": {
"num_pbb": 0,
"num_pbb_up": 0
},
"pw": {
"num_pw": 1,
"num_pw_up": 1
},
"state": "up",
"vni": {
"num_vni": 0,
"num_vni_up": 0
}
}
}
},
"GO-LEAFS": {
"bridge_domain": {
"GO": {
"ac": {
"num_ac": 3,
"num_ac_up": 2
},
"id": 9,
"pbb": {
"num_pbb": 0,
"num_pbb_up": 0
},
"pw": {
"num_pw": 7,
"num_pw_up": 5
},
"state": "up",
"vni": {
"num_vni": 0,
"num_vni_up": 0
}
}
}
},
"MGMT": {
"bridge_domain": {
"DSL-MGMT": {
"ac": {
"num_ac": 1,
"num_ac_up": 0
},
"id": 2,
"pbb": {
"num_pbb": 0,
"num_pbb_up": 0
},
"pw": {
"num_pw": 0,
"num_pw_up": 0
},
"state": "up",
"vni": {
"num_vni": 0,
"num_vni_up": 0
}
}
}
},
"WOrd": {
"bridge_domain": {
"CODE-123-4567": {
"ac": {
"num_ac": 1,
"num_ac_up": 0
},
"id": 3,
"pbb": {
"num_pbb": 0,
"num_pbb_up": 0
},
"pw": {
"num_pw": 1,
"num_pw_up": 0
},
"state": "up",
"vni": {
"num_vni": 0,
"num_vni_up": 0
}
}
}
},
"admin1": {
"bridge_domain": {
"domain1": {
"ac": {
"num_ac": 1,
"num_ac_up": 0
},
"id": 6,
"pbb": {
"num_pbb": 0,
"num_pbb_up": 0
},
"pw": {
"num_pw": 1,
"num_pw_up": 0
},
"state": "admin down",
"vni": {
"num_vni": 0,
"num_vni_up": 0
}
}
}
},
"d": {
"bridge_domain": {
"s-VLAN_20": {
"ac": {
"num_ac": 2,
"num_ac_up": 2
},
"id": 1,
"pbb": {
"num_pbb": 0,
"num_pbb_up": 0
},
"pw": {
"num_pw": 1,
"num_pw_up": 1
},
"state": "up",
"vni": {
"num_vni": 0,
"num_vni_up": 0
}
}
}
},
"g1": {
"bridge_domain": {
"bd1": {
"ac": {
"num_ac": 1,
"num_ac_up": 1
},
"id": 0,
"pw": {
"num_pw": 1,
"num_pw_up": 1
},
"state": "up"
}
}
},
"woRD": {
"bridge_domain": {
"THING_PLACE_DIA-765_4321": {
"ac": {
"num_ac": 1,
"num_ac_up": 1
},
"id": 4,
"pbb": {
"num_pbb": 0,
"num_pbb_up": 0
},
"pw": {
"num_pw": 1,
"num_pw_up": 1
},
"state": "up",
"vni": {
"num_vni": 0,
"num_vni_up": 0
}
}
}
}
}
} |
INPUT_TO_DWI_CONVERSION_EDGES = [("dwi_file", "in_file")]
INPUT_TO_FMAP_CONVERSION_EDGES = [("fmap_file", "in_file")]
LOCATE_ASSOCIATED_TO_COVERSION_EDGES = [
("json_file", "json_import"),
("bvec_file", "in_bvec"),
("bval_file", "in_bval"),
]
DWI_CONVERSION_TO_OUTPUT_EDGES = [("out_file", "dwi_file")]
FMAP_CONVERSION_TO_OUTPUT_EDGES = [("out_file", "fmap_file")]
|
almacen_api_config = {
'debug': {
'name': 'almacen_api',
'database': 'stage_01',
'debug': True,
'app': {
'DEBUG': True,
'UPLOAD_FOLDER': '/tmp',
},
'run': {
# 'ssl_context': ('ssl/cert.pem', 'ssl/key.pem'),
'port': 8000,
},
'app_tokens': {
'TOKEN': {
'app': 'development',
'roles': ['super', 'tagger'],
},
'TOKEN': {
'app': 'longcat_api',
'roles': ['tagger'],
},
},
},
'development': {
'name': 'almacen_api',
'database': 'stage_01',
'run': {
'port': 8000,
},
'app_tokens': {
'TOKEN': {
'app': 'development',
'roles': ['super', 'tagger'],
},
'TOKEN': {
'app': 'longcat_api',
'roles': ['tagger'],
},
'TOKEN': {
'app': 'longcat_api',
'roles': ['reader'],
},
},
's3_query_results_bucket': {
'access_key_id': 'ACCESSKEY',
'secret_access_key': 'SECRET',
'bucket_name': 'almacen-entrega',
'bucket_region': 'us-east-2',
'bucket_directory': 'almacen_api/stage/query_results',
},
},
'production': {
'name': 'almacen_api',
'database': 'prod_01',
'app_tokens': {
'TOKEN': {
'app': 'longcat_api',
'roles': ['tagger'],
},
},
},
'testing': {
'name': 'almacen_api_test',
'database': 'stage_01',
'app_tokens': {
'TOKEN': {
'app': 'development',
'roles': ['super', 'tagger'],
},
},
},
} |
# Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo.
print('Suas retas formam um triângulo?')
r1 = float(input('Digite a primeira reta: '))
r2 = float(input('Digite a segunda reta: '))
r3 = float(input('Digite a terceira reta: '))
if r1 < (r2+r3) and r2 < (r1 + r3) and r3 < (r2 + r1):
print('Essas retas formam um triângulo!')
else:
print('Essas retas NÃO formam um triângulo!')
|
a=1
def change_integer(a):
a = a+1
return a
print (change_integer(a))
print (a)
b=[1,2,3]
def change_list(b):
b[0]=b[0]+1
return b
print (change_list(b))
print (b)
|
number_1 = int(input())
number_2 = int(input())
if number_1 >= number_2:
print(number_1)
print(number_2)
else:
print(number_2)
print(number_1)
|
def main(input):
myDict = {}
myDict['ก']='k'
for key in ['ข','ค', 'ฆ']:
myDict[key] = 'k'
myDict['ง']='ng'
myDict['จ']='t'
for key in ['ฉ','ฌ', 'ช']:
myDict[key] = 't'
for key in ['ซ','ศ', 'ษ','ส']:
myDict[key] = 't'
for key in ['ย']:
myDict[key] = 'j'
for key in ['ฎ', 'ด']:
myDict[key] = 't'
for key in ['ฏ', 'ต']:
myDict[key] = 't'
for key in ['ฐ','ฑ', 'ฒ','ถ','ท','ธ']:
myDict[key] = 't'
for key in ['ณ', 'น','ญ']:
myDict[key] = 'n'
myDict['บ']='p'
myDict['ป']='p'
for key in ['ผ', 'พ','ภ']:
myDict[key] = 'p'
for key in ['ฝ', 'ฟ']:
myDict[key] = 'p'
myDict['ม']='m'
myDict['ร']='n'
for key in ['ล', 'ฬ']:
myDict[key] = 'n'
myDict['ว']='w'
for key in ['ฤ', 'ฦ']:
myDict[key] = 'r'
for key in ['ห', 'ฮ']:
myDict[key] = ''
myDict['อ']=''
x=myDict.get(input)
return x;
|
'''
Gas Station
Asked in: Bloomberg, Google, DE Shaw, Amazon, Flipkart
Given two integer arrays A and B of size N.
There are N gas stations along a circular route, where the amount of gas at station i is A[i].
You have a car with an unlimited gas tank and it costs B[i] of gas to travel from station i
to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the minimum starting gas station’s index if you can travel around the circuit once, otherwise return -1.
You can only travel in one direction. i to i+1, i+2, … n-1, 0, 1, 2.. Completing the circuit means starting at i and
ending up at i again.
Input Format
The first argument given is the integer array A.
The second argument given is the integer array B.
Output Format
Return the minimum starting gas station's index if you can travel around the circuit once, otherwise return -1.
For Example
Input 1:
A = [1, 2]
B = [2, 1]
Output 1:
1
Explanation 1:
If you start from index 0, you can fill in A[0] = 1 amount of gas. Now your tank has 1 unit of gas. But you need B[0] = 2 gas to travel to station 1.
If you start from index 1, you can fill in A[1] = 2 amount of gas. Now your tank has 2 units of gas. You need B[1] = 1 gas to get to station 0. So, you travel to station 0 and still have 1 unit of gas left over. You fill in A[0] = 1 unit of additional gas, making your current gas = 2. It costs you B[0] = 2 to get to station 1, which you do and complete the circuit.
Solution by interviewbit.com
'''
# @param A : tuple of integers
# @param B : tuple of integers
# @return an integer
def canCompleteCircuit(gas, cost):
sumo=0
fuel=0
start=0
for i in range(len(gas)):
sumo = sumo + (gas[i] - cost[i])
fuel = fuel + (gas[i] - cost[i])
if fuel<0:
fuel=0
start=i+1
if sumo>=0:
return (start%len(gas))
else:
return -1
if __name__ == "__main__":
data = [
] |
#!/usr/bin/env python3
# CHECKED
A = [[4.5, -1, -1, 1], [-1, 4.5, 1, -1], [-1, 2, 4.5, -1], [2, -1, -1, 4.5]]
b = [1, -1, -1, 0]
x = [0.25, 0.25, 0.25, 0.25]
x_new = [0, 0, 0, 0]
for k in range(2):
for i in range(4):
x_new[i] = b[i]
for j in range(4):
if j != i:
x_new[i] -= A[i][j] * x[j]
x_new[i] *= (1 / A[i][i])
print("Ans", k, "\n", x_new)
x = x_new.copy()
|
class Solution:
# @param num : a list of integer
# @return : a list of integer
def nextPermutation(self, num):
# write your code here
# Version 1
bp = -1
for i in range(len(num) - 1):
if (num[i] < num[i + 1]):
bp = i
if (bp == -1):
num.reverse()
return num
rest = num[bp:]
local_max = None
for i in rest:
if (i > rest[0] and (local_max is None or i < local_max)):
local_max = i
rest.pop(rest.index(local_max))
rest = sorted(rest)
return num[:bp] + [local_max] + rest
# Version 2
# i = len(num) - 1
# target_index = None
# second_index = None
# while (i > 0):
# if (num[i] > num[i - 1]):
# target_index = i - 1
# break
# i -= 1
# if (target_index is None):
# return sorted(num)
# i = len(num) - 1
# while (i > target_index):
# if (num[i] > num[target_index]):
# second_index = i
# break
# i -= 1
# temp = num[target_index]
# num[target_index] = num[second_index]
# num[second_index] = temp
# return num[:target_index] + [num[target_index]] + sorted(num[target_index + 1:])
|
X = int(input())
a_list = []
for s in range(1, 32):
for i in range(2, 10):
a = s ** i
if a > 1000:
break
a_list.append(a)
a2 = sorted(list(set(a_list)), reverse=True)
for n in a2:
if n <= X:
print(n)
break |
def presentacion_inicial():
print("*"*20)
print("Que accion desea realizar : ")
print("1) Insertar Persona : ")
print("2) Insertar Empleado : ")
print("3) Consultar las personas : ")
print("4) Consultar por empleados : ")
return int(input("Opcion necesitas : "))
|
class SEHException(ExternalException):
"""
Represents structured exception handling (SEH) errors.
SEHException()
SEHException(message: str)
SEHException(message: str,inner: Exception)
"""
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return SEHException()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
def CanResume(self):
"""
CanResume(self: SEHException) -> bool
Indicates whether the exception can be recovered from,and whether the code can continue from the point at which the exception was thrown.
Returns: Always false,because resumable exceptions are not implemented.
"""
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,message=None,inner=None):
"""
__new__(cls: type)
__new__(cls: type,message: str)
__new__(cls: type,message: str,inner: Exception)
__new__(cls: type,info: SerializationInfo,context: StreamingContext)
"""
pass
def __reduce_ex__(self,*args):
pass
def __str__(self,*args):
pass
SerializeObjectState=None
|
# encoding: utf-8
# module Revit.References calls itself References
# from RevitNodes,Version=1.2.1.3083,Culture=neutral,PublicKeyToken=null
# by generator 1.145
# no doc
# no imports
# no functions
# classes
class RayBounce(object):
# no doc
@staticmethod
def ByOriginDirection(origin, direction, maxBounces, view):
"""
ByOriginDirection(origin: Point,direction: Vector,maxBounces: int,view: View3D) -> Dictionary[str,object]
Returns positions and elements hit by ray bounce from the specified origin
point and direction
"""
pass
__all__ = [
"ByOriginDirection",
]
|
load("@io_bazel_rules_docker//go:image.bzl", go_image_repositories="repositories")
load("@io_bazel_rules_docker//container:container.bzl", container_repositories = "repositories")
def initialize_rules_docker():
container_repositories()
go_image_repositories()
load("@distroless//package_manager:package_manager.bzl", "package_manager_repositories",)
def initialize_rules_package_manager():
package_manager_repositories()
|
a = 15
b = 15
exp = a == b
if a < b:
print(f'{a} e menor que {b}')
elif a > b :
print(f'{a} e maior que {b}')
else:
print('Os valores são iguais')
letra = 'l'
nome = 'Djonatan l'
if letra in nome:
print(f'Contem {letra} no nome')
else:
print(f'Não Contem {letra} no nome')
valor = '2'
valores = '82718939289172'
if valor in valores:
print(f'Contem o valor {valor} em {valores}')
i = 0
for valor in valores:
if valor in valores[i]:
i += 1
print(i)
#idade = int(input("Sua idade? "))
#if idade < 20 or idade > 30:
# print('Você não pode pegar emprestimos')
#else:
# print('Voce pode pegar emprestimos')
|
"""
1. Problem Summary / Clarifications / TDD:
output("abcd", "abecd") = "e"
2. Inuition: xor operator
3. Tests:
output("abcd", "abecd") = "e": The added character is in the middle of t
output("abcd", "abcde") = "e": The added character is at the end of t
output("abcd", "eabcd") = "e": The added character is at the beginning of t
Specific case
output("aaa", "aaaa") = "a"
Edge case: s is empty
output("", "a") = "a"
3. Complexity Analysis:
Time Complexity: O(|t|)
Space Complexity: O(1)
"""
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
xor_result = 0
for i in range(len(s)):
xor_result ^= ord(s[i])
xor_result ^= ord(t[i])
xor_result ^= ord(t[-1])
return chr(xor_result)
|
# urls.py
# urls for dash app
url_paths = {
"index": '/',
"home": '/home',
"scatter": '/apps/scatter-test',
"combo": '/apps/combo-test'
}
|
scoreboard_display = [['0', '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'],
['51', '50', '49', '48', '47', '46', '45', '44', '43', '42', '41', '40', '39', '38', '37', '36', '35', '34', '33', '32', '31', '30', '29', '28', '27', '26'],
['52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77'],
['103', '102', '101', '100', '99', '98', '97', '96', '95', '94', '93', '92', '91', '90', '89', '88', '87', '86', '85', '84', '83', '82', '81', '80', '79', '78'],
['104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129'],
['155', '154', '153', '152', '151', '150', '149', '148', '147', '146', '145', '144', '143', '142', '141', '140', '139', '138', '137', '136', '135', '134', '133', '132', '131', '130'],
['156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181'],
['207', '206', '205', '204', '203', '202', '201', '200', '199', '198', '197', '196', '195', '194', '193', '192', '191', '190', '189', '188', '187', '186', '185', '184', '183', '182'],
['208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233'],
['259', '258', '257', '256', '255', '254', '253', '252', '251', '250', '249', '248', '247', '246', '245', '244', '243', '242', '241', '240', '239', '238', '237', '236', '235', '234'],
['260', '261', '262', '263', '264', '265', '266', '267', '268', '269', '270', '271', '272', '273', '274', '275', '276', '277', '278', '279', '280', '281', '282', '283', '284', '285'],
['311', '310', '309', '308', '307', '306', '305', '304', '303', '302', '301', '300', '299', '298', '297', '296', '295', '294', '293', '292', '291', '290', '289', '288', '287', '286'],
['312', '313', '314', '315', '316', '317', '318', '319', '320', '321', '322', '323', '324', '325', '326', '327', '328', '329', '330', '331', '332', '333', '334', '335', '336', '337'],
['363', '362', '361', '360', '359', '358', '357', '356', '355', '354', '353', '352', '351', '350', '349', '348', '347', '346', '345', '344', '343', '342', '341', '340', '339', '338'],
['364', '365', '366', '367', '368', '369', '370', '371', '372', '373', '374', '375', '376', '377', '378', '379', '380', '381', '382', '383', '384', '385', '386', '387', '388', '389'],
['415', '414', '413', '412', '411', '410', '409', '408', '407', '406', '405', '404', '403', '402', '401', '400', '399', '398', '397', '396', '395', '394', '393', '392', '391', '390'],
['416', '417', '418', '419', '420', '421', '422', '423', '424', '425', '426', '427', '428', '429', '430', '431', '432', '433', '434', '435', '436', '437', '438', '439', '440', '441']]
|
# flake8: noqa
# in legacy datasets we need to put our sample data within the data dir
legacy_datasets = ["cmu_small_region.svs"]
# Registry of datafiles that can be downloaded along with their SHA256 hashes
# To generate the SHA256 hash, use the command
# openssl sha256 filename
registry = {
"histolab/broken.svs": "b1325916876afa17ad5e02d2e7298ee883e758ed25369470d85bc0990e928e11",
"histolab/kidney.png": "5c6dc1b9ae10a2865302d9c8eda360362ec47732cb3e9766c38ed90cb9f4c371",
"data/cmu_small_region.svs": "ed92d5a9f2e86df67640d6f92ce3e231419ce127131697fbbce42ad5e002c8a7",
"aperio/JP2K-33003-1.svs": "6205ccf75a8fa6c32df7c5c04b7377398971a490fb6b320d50d91f7ba6a0e6fd",
"aperio/JP2K-33003-2.svs": "1a13cef86b55b51127cebd94a1f6069f7de494c98e3e708640d1ce7181d9e3fd",
"tcga/breast/TCGA-A8-A082-01A-01-TS1.3cad4a77-47a6-4658-becf-d8cffa161d3a.svs": "e955f47b83c8a5ae382ff8559493548f90f85c17c86315dd03134c041f44df70",
"tcga/breast/TCGA-A1-A0SH-01Z-00-DX1.90E71B08-E1D9-4FC2-85AC-062E56DDF17C.svs": "6de90fe92400e592839ab7f87c15d9924bc539c61ee3b3bc8ef044f98d16031b",
"tcga/breast/TCGA-E9-A24A-01Z-00-DX1.F0342837-5750-4172-B60D-5F902E2A02FD.svs": "55c694262c4d44b342e08eb3ef2082eeb9e9deeb3cb445e4776419bb9fa7dc21",
"tcga/breast/TCGA-BH-A201-01Z-00-DX1.6D6E3224-50A0-45A2-B231-EEF27CA7EFD2.svs": "e1ccf3360078844abbec4b96c5da59a029a441c1ab6d7f694ec80d9d79bd3837",
"tcga/prostate/TCGA-CH-5753-01A-01-BS1.4311c533-f9c1-4c6f-8b10-922daa3c2e3e.svs": "93ed7aa906c9e127c8241bc5da197902ebb71ccda4db280aefbe0ecd952b9089",
"tcga/ovarian/TCGA-13-1404-01A-01-TS1.cecf7044-1d29-4d14-b137-821f8d48881e.svs": "6796e23af7cd219b9ff2274c087759912529fec9f49e2772a868ba9d85d389d6",
"9798433/?format=tif": "7db49ff9fc3f6022ae334cf019e94ef4450f7d4cf0d71783e0f6ea82965d3a52",
"9798554/?format=tif": "8a4318ac713b4cf50c3314760da41ab7653e10e90531ecd0c787f1386857a4ef",
}
APERIO_REPO_URL = "http://openslide.cs.cmu.edu/download/openslide-testdata/Aperio"
TCGA_REPO_URL = "https://api.gdc.cancer.gov/data"
IDR_REPO_URL = "https://idr.openmicroscopy.org/webclient/render_image_download"
registry_urls = {
"histolab/broken.svs": "https://raw.githubusercontent.com/histolab/histolab/master/tests/fixtures/svs-images/broken.svs",
"histolab/kidney.png": "https://user-images.githubusercontent.com/4196091/100275351-132cc880-2f60-11eb-8cc8-7a3bf3723260.png",
"aperio/JP2K-33003-1.svs": f"{APERIO_REPO_URL}/JP2K-33003-1.svs",
"aperio/JP2K-33003-2.svs": f"{APERIO_REPO_URL}/JP2K-33003-2.svs",
"tcga/breast/TCGA-A8-A082-01A-01-TS1.3cad4a77-47a6-4658-becf-d8cffa161d3a.svs": f"{TCGA_REPO_URL}/ad9ed74a-2725-49e6-bf7a-ef100e299989",
"tcga/breast/TCGA-A1-A0SH-01Z-00-DX1.90E71B08-E1D9-4FC2-85AC-062E56DDF17C.svs": f"{TCGA_REPO_URL}/3845b8bd-cbe0-49cf-a418-a8120f6c23db",
"tcga/breast/TCGA-E9-A24A-01Z-00-DX1.F0342837-5750-4172-B60D-5F902E2A02FD.svs": f"{TCGA_REPO_URL}/682e4d74-2200-4f34-9e96-8dee968b1568",
"tcga/breast/TCGA-BH-A201-01Z-00-DX1.6D6E3224-50A0-45A2-B231-EEF27CA7EFD2.svs": f"{TCGA_REPO_URL}/e70c89a5-1c2f-43f8-b6be-589beea55338",
"tcga/prostate/TCGA-CH-5753-01A-01-BS1.4311c533-f9c1-4c6f-8b10-922daa3c2e3e.svs": f"{TCGA_REPO_URL}/5a8ce04a-0178-49e2-904c-30e21fb4e41e",
"tcga/ovarian/TCGA-13-1404-01A-01-TS1.cecf7044-1d29-4d14-b137-821f8d48881e.svs": f"{TCGA_REPO_URL}/e968375e-ef58-4607-b457-e6818b2e8431",
"9798433/?format=tif": f"{IDR_REPO_URL}/9798433/?format=tif",
"9798554/?format=tif": f"{IDR_REPO_URL}/9798554/?format=tif",
}
legacy_registry = {
("data/" + filename): registry["data/" + filename] for filename in legacy_datasets
}
|
print('=' * 15, '\033[1;35mAULA 18 - Listas[Part #2]\033[m', '=' * 15)
# --------------------------------------------------------------------
dados = []
pessoas = []
galera = [['Miguel', 25], ['Berta', 59], ['Joaquim', 20]]
# --------------------------------------------------------------------
dados.append('Joaquim')
dados.append(20)
dados.append('Fernando')
dados.append(23)
dados.append('Maria')
dados.append(19)
pessoas.append(dados[:])
# galera.append(pessoas[:])
print(galera[0][0]) # Miguel
print(galera[1][1]) # 59
print(galera[2][0]) # Joaquim
print(galera[1]) # Berta + 59
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 22/4/2016 10:57 AM
Author: Qu Dong
"""
class QuikFindUF():
def __init__(self, N):
self.count = N
self.parent = list(range(N))
def count(self):
return self.count
def find(self, p):
self._validate(p)
return self.parent[p]
def _validate(self, p):
N = len(self.parent)
if p < 0 or p >= N:
raise IndexError('Index {} is not between 0 and {}'.format(p, N - 1))
def connected(self, p, q):
return self.find(p) == self.find(q)
def union(self, p, q):
p_par = self.parent[p]
q_par = self.parent[q]
if p_par == q_par:
return
for i, par in enumerate(self.parent):
if par == p_par: # 如果这个数的爸爸和P的爸爸相等,那么Q的爸爸就变成了这个数的爸爸
self.parent[i] = q_par
self.count -= 1
class QuickUnionUF():
def __init__(self, N):
self.count = N
self.parent = list(range(N))
def count(self):
return self.count
def find(self, p): # return the root of p
self._validate(p)
while p != self.parent[p]:
p = self.parent[p]
return p
def _validate(self, p):
N = len(self.parent)
if p < 0 or p >= N:
raise IndexError('Index {} is not between 0 and {}'.format(p, N - 1))
def connected(self, p, q):
return self.find(p) == self.find(q)
def union(self, p, q):
p_root = self.find(p)
q_root = self.find(q)
if p_root == q_root:
return
self.parent[p_root] = q_root
self.count -= 1
class WeightedQuickUnionUF():
def __init__(self, N):
self.count = N
self.parent = list(range(N))
self.size = [1] * N
def count(self):
return self.count
def find(self, p):
self._validate(p)
while p != self.parent[p]:
p = self.parent[p]
return p
def _validate(self, p):
N = len(self.parent)
if p < 0 or p >= N:
raise IndexError('Index {} is not between 0 and {}'.format(p, N - 1))
def connected(self, p, q):
return self.find(p) == self.find(q)
def union(self, p, q):
p_root = self.find(p)
q_root = self.find(q)
if p_root == q_root:
return
if self.size[p_root] < self.size[q_root]:
self.parent[p_root] = q_root
self.size[q_root] += self.size[p_root]
else:
self.parent[q_root] = p_root
self.size[p_root] += self.size[q_root]
self.count -= 1
if __name__ == "__main__":
# uf = WeightedQuickUnionUF(10)
# uf = QuickUnionUF(10)
uf = QuikFindUF(10)
uf.union(6, 9)
print(' '.join([str(i) for i in uf.parent]))
uf.union(8, 2)
print(' '.join([str(i) for i in uf.parent]))
uf.union(5, 9)
print(' '.join([str(i) for i in uf.parent]))
uf.union(0, 6)
print(' '.join([str(i) for i in uf.parent]))
uf.union(9, 1)
print(' '.join([str(i) for i in uf.parent]))
uf.union(5, 4)
print(' '.join([str(i) for i in uf.parent]))
uf.union(3, 7)
print(' '.join([str(i) for i in uf.parent]))
uf.union(8, 7)
print(' '.join([str(i) for i in uf.parent]))
uf.union(4, 3)
print(' '.join([str(i) for i in uf.parent]))
print(uf.count, "Components")
print(' '.join([str(i) for i in uf.parent]))
|
#AUTH Kaio Guilherme
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
root = Node(0)
root.left = Node(1)
root.right = Node(0)
root.right.left = Node(1)
root.right.right = Node(0)
root.right.left.right = Node(1)
root.right.left.left = Node(1)
def sum_uni(root):
univais = 0
if root is None:
return 0
else:
if((root.left is None and root.right is None) or root.left.key == root.right.key):
univais = 1
return sum_uni(root.right) + sum_uni(root.left) + univais
print("Esta árvore possui {} subárvores Univais ".format(sum_uni(root)))
|
P, D = list(map(int, input().split(' ')))
totA, totB = 0, 0
dis = [[0,0,0,0] for i in range(D)]
for i in range(P):
a, b, c = map(int, input().split(' '))
k = (b+c)//2 + 1
dis[a-1][0] += b
dis[a-1][1] += c
for i, (ta, tb, _, _) in enumerate(dis):
k = (ta + tb)//2 + 1
if ta > tb:
wA = ta-k
wB = tb
else:
wA = ta
wB = tb-k
dis[i][2] = wA
dis[i][3] = wB
print('A' if ta > tb else 'B', f"{wA} {wB}")
tot = sum(a[0] + a[1] for a in dis)
wA = sum(a[2] for a in dis)
wB = sum(a[3] for a in dis)
print(abs(wA - wB) / tot)
|
# -*- coding: utf-8 -*-
def _data_from_bar(ax, bar_label):
"""Given a matplotlib Axes object and a bar label,
returns (x,y,w,h) data underlying the bar plot.
Args:
ax: The Axes object the data will be extracted from.
bar_label: The bar label from which you want to extract the data.
Returns:
A list of (x,y,w,h) for this bar.
"""
data = []
# each bar is made of several rectangles (matplotlib "artists")
# here we extract their coordinates from the bar label
handles = ax.get_legend_handles_labels()
# handles[0] is a list of list of artists (one per bar)
# handles[1] is a list of bar labels
bar_artists = handles[0][handles[1].index(bar_label)]
# each artist of the bar is a rectangle
for rectangle in bar_artists:
data.append([
rectangle.get_x(),
rectangle.get_y(),
rectangle.get_width(),
rectangle.get_height()
])
return data
|
baklava_price = float(input())
muffin_price = float(input())
shtolen_kg = float(input())
candy_kg = float(input())
bisquits_kg = int(input())
shtolen_price = baklava_price + baklava_price * 0.6
candy_price = muffin_price + muffin_price * 0.8
busquits_price = 7.50
shtolen_sum = shtolen_kg * shtolen_price
candy_sum = candy_kg * candy_price
bisquits_sum = bisquits_kg * busquits_price
all_sum = shtolen_sum + candy_sum + bisquits_sum
print(f'{all_sum:.2f}') |
"""
Generic utilities
"""
def any(seq):
for i in seq:
if i:
return True
return False
|
x=int(input('Enter the number to convert: '))
print('Select the convertion')
print('''
[ 1 ] Binary
[ 1 ] Octal
[ 3 ] HexaDeicmal
''')
y=int(input('1 - Binary 2 - Octal 3 - Hexadecimal'))
if y==1:
bin(x)[2:]
print('{}'.format(x))
elif y==2:
oct(x)
print('{}'.format(x))
elif y==3:
hex(x)
print(x)
else:
print('Invalid') |
"""
给定一个整数n,返回从1到n的数字中1个出现的个数.
例如:
n=5,1~n为1,2,3,4,5.那么1出现了1次,所以返回1.
n=11,1~n为1,2,3,4,5,6,7,8,9,10,11.那么1出现的次数为1(出现
1次),10(出现1次),11(有两个1,所以出现了2次),所以返回4
"""
class OneCounter:
@classmethod
def get_nums_of_one(cls, n):
if n == 0:
return 0
n = abs(n)
high_pos = 1
cur = 9
while cur/n < 1:
cur = 9 * pow(10, high_pos) + cur
high_pos += 1
return cls.process(n, high_pos)
@classmethod
def process(cls, n, pos):
if n < 10:
return 1
left = int(n % pow(10, pos-1))
num = int(n/pow(10, pos-1))
if num > 1:
first_one_num = pow(10, pos-1)
else:
first_one_num = n - num * pow(10, pos-1) + 1
other_one_num = num * (pos-1) * (pow(10, pos-1)/10)
return int(first_one_num + other_one_num + cls.process(left, pos-1))
if __name__ == '__main__':
print(OneCounter.get_nums_of_one(9991))
|
# -*- coding: utf-8 -*-
"""
meetup.py
~~~~~~~~~
a mock for the Meetup APi client
"""
class MockMeetupGroup:
def __init__(self, *args, **kwargs):
self.name = "Mock Meetup Group"
self.link = "https://www.meetup.com/MeetupGroup/"
self.next_event = {
"id": 0,
"name": "Monthly Meetup",
"venue": "Galvanize",
"yes_rsvp_count": 9,
"time": 1518571800000, # February 13, 2018 6:30PM
"utc_offset": -25200000,
}
class MockMeetupEvents:
def __init__(self, *args, **kwargs):
self.results = [MockMeetupGroup().next_event] + [self.events(_) for _ in range(1, 6)]
def events(self, idx):
return {k: idx for k in ["id", "venue", "time", "utc_offset"]}
class MockMeetup:
api_key = ""
def __init__(self, *args, **kwargs):
return
def GetGroup(self, *args, **kwargs):
return MockMeetupGroup()
def GetEvents(self, *args, **kwargs):
return MockMeetupEvents()
|
# TASK:
# Given an integer, n, perform the following conditional actions:
# If n is odd, print Weird
# If n is even and in the inclusive range of 2 to 5, print Not Weird
# If n is even and in the inclusive range of 6 to 20, print Weird
# If n is even and greater than 20, print Not Weird
if __name__ == '__main__':
n = int(input().strip())
if n % 2 == 1:
print('Weird')
elif 2 <= n <= 5:
print('Not Weird')
elif 6 <= n <= 20:
print('Weird')
else:
print('Not Weird')
# input(): Read a string from standard input. The trailing newline is
# stripped. If you include the optional <prompt> argument, input()
# displays it as a prompt to the user before pausing to read input.
# >>> name = input('What is your name? ')
# input() always returns a string. If you want a numeric type, then
# you need to convert the string to the appropriate type with the int()
# as we did in above code.
# Frequently, a program needs to skip over some statements, execute a
# series of statements repetitively, or choose between alternate sets
# of statements to execute.
# That is where control structures come in. A control structure directs
# the order of execution of the statements in a program (referred to as
# the program’s control flow).
# In a Python program, the if statement is how we perform this sort of
# decision-making. It allows for conditional execution of a statement or
# group of statements based on the value of an expression. Syntax:
# if <expr>: #<expr> is an expression evaluated in boolean
# <statements> #these are valid Python statements, which must be indented.
# Sometimes, you want to evaluate a condition and take one path if it
# is true but specify an alternative path if it is not. This is accomplished
# with an else
# clause:
# if <expr>:
# <statement(s)>
# else:
# <statement(s)>
# If <expr> is true, the first suite is executed, and the second is skipped.
# If <expr> is false, the first suite is skipped and the second is executed.
# There is also syntax for branching execution based on several alternatives.
# For this, use one or more elif (short for else if) clauses. Python evaluates
# each <expr> in turn and executes the suite corresponding to the first that is
# true. If none of the expressions
# are true, and an else clause is specified, then its suite is executed:
# if <expr>:
# <statement(s)>
# elif <expr>:
# <statement(s)>
# elif <expr>:
# <statement(s)>
# ...
# else:
# <statement(s)>
# At most, one of the code blocks specified will be executed. If an else clause
# isn’t included, and all the conditions are false, then none of the blocks will
# be executed.
|
#!/usr/bin/python3
def safe_print_list_integers(my_list=[], x=0):
i = 0
for index in range(x):
try:
print("{:d}".format(my_list[index]), end="")
i += 1
except (ValueError, TypeError):
pass
print()
return i
|
class PlacementRuleUtil:
def __init__(self, game_data, placement_data):
self.rule = int(game_data.rule[int(placement_data.obj_number)-1]["placementRule"])
self.placement = placement_data.placement
self.type = game_data.rule[int(placement_data.obj_number)-1]["type"]
self.placement_type = placement_data.placement_type
self.board = placement_data.board
self.curr_x = placement_data.curr_x
self.curr_y = placement_data.curr_y
self.next_x = placement_data.next_x
self.next_y = placement_data.next_y
self.obj_number = placement_data.obj_number
self.placement_rule_option = {1: self.block_move, 2: self.remove}
# add option
# if self.rule[2]:
# self.obj_option = self.rule[2]
def check_type(self): # type -> 0: add, 1: move, 2: add&move
if self.placement_type == 'add' and self.type == "move":
raise Exception(f'stone{self.obj_number}{self.next_x, self.next_y} cant move')
elif self.placement_type == 'move' and self.type == "add":
raise Exception(f'stone{self.obj_number}{self.next_x, self.next_y} can only move')
def check_base_rule(self):
stone = int(self.obj_number)
if stone < 0:
raise Exception(f'It is not your stone : {self.placement}')
elif stone == 0:
raise Exception(f'There is no stone : {self.placement}')
elif self.board[self.next_x][self.next_y] > 0:
raise Exception(f'There is already your stone: {self.placement}')
elif self.board[self.next_x][self.next_y] < 0: # catch enemy stone
pass
# if self.obj_option:
# if 2 not in self.obj_option:
# raise Exception(f'There is already enemy stone: {self.placement}')
# else:
# raise Exception(f'There is already enemy stone: {self.placement}')
def check_in_range(self, num, min=0, max=None):
if max is None:
max = len(self.board)
return num in range(min, max)
def add_rule_option(self):
if self.obj_option is not None:
for option in self.obj_option:
self.rules.append(self.placement_rule_option[option])
# 인접한 곳에 돌 추가
def add_adjacent(self, direction):
if direction == "CROSS":
dir = [(0, 1), (1, 0), (0, -1), (-1, 0)]
elif direction == "DIAGONAL":
dir = [(-1, 1), (1, 1), (1, -1), (-1, -1)]
elif direction == "EIGHT":
dir = [(0, 1), (1, 0), (0, -1), (-1, 0), (-1, 1), (1, 1), (1, -1), (-1, -1)]
for d in dir:
x = self.next_x + d[0]
y = self.next_y + d[1]
if self.check_in_range(x) is False or \
self.check_in_range(y) is False:
continue
if self.board[x][y] > 0:
return True
return False
# 이동
def move(self, direction, distance):
min_distance = distance[0]
max_distance = distance[1]
x_inc = abs(self.next_x - self.curr_x)
y_inc = abs(self.next_y - self.curr_y)
if max_distance == 0:
max_distance = 999
if direction == 'CROSS' or 'EIGHT':
if (x_inc == 0 and self.check_in_range(y_inc, min=min_distance, max=max_distance+1)) or \
(y_inc == 0 and self.check_in_range(x_inc, min=min_distance, max=max_distance+1)):
return True
if direction == 'DIAGONAL' or 'EIGHT':
if x_inc == y_inc and \
self.check_in_range(x_inc, min=min_distance, max=max_distance+1) and \
self.check_in_range(y_inc, min=min_distance, max=max_distance+1):
return True
if direction == 'CUSTOM':
x_custom = distance[0]
y_custom = distance[1]
if x_inc == x_custom and y_inc == y_custom:
return True
return False
def update_board(self):
if self.placement_type == 'move':
self.board[self.curr_x][self.curr_y] = 0
self.board[self.next_x][self.next_y] = self.obj_number
else:
self.board[self.next_x][self.next_y] = self.obj_number
def block_move(self): # 이동시 충돌 무시 여부
pass
def remove(self): # 상대방 돌이 존재할 시 없애고 추가
pass
|
N = int(input())
A, B = (
zip(*(map(int, input().split()) for _ in range(N))) if N else
((), ())
)
ans = len({(min(a, b), max(a, b)) for a, b in zip(A, B)})
print(ans)
|
URLS = [
"url1"
]
STATUSPAGE_API_KEY = ""
STATUSPAGE_PAGE_ID = ""
STATUSPAGE_METRICS = {
"url": "metric_id"
}
STATUSPAGE_COMPONENTS = {
"url": "component_id"
}
PING_WEBHOOKS = []
STATUS_WEBHOOKS = []
ESCALATION_IDS = []
POLL_TIME = 60
OUTAGE_CHANGE_AFTER = 10
DRY_MODE = False
DEGRADED_PERFORMANCE_TARGET_PING = 500
TIMEOUT_PING = 30000
|
d = {'a': 1, 'c': 3}
match d:
case {'a': chave_a, 'b': _}:
print(f'chave A {chave_a=} + chave B')
case {'a': _} | {'c': _}:
print('chave A ou C')
case {}:
print('vazio')
case _:
print('Não sei')
|
{ 'application':{ 'type':'Application',
'name':'MulticolumnExample',
'backgrounds':
[
{ 'type':'Background',
'name':'bgMulticolumnExample',
'title':'Multicolumn Example PythonCard Application',
'size':( 620, 500 ),
'menubar':
{
'type':'MenuBar',
'menus':
[
{ 'type':'Menu',
'name':'menuFile',
'label':'&File',
'items': [
{ 'type':'MenuItem',
'name':'menuFileExit',
'label':'E&xit\tAlt+X',
'command':'exit' } ] }
]
},
'components':
[
{'type':'Button',
'name':'demoButton',
'position':(510, 5),
'size':(85, 25),
'label':'Load Demo',
},
{'type':'Button',
'name':'clearButton',
'position':(510, 30),
'size':(85, 25),
'label':'Clear',
},
{'type':'Button',
'name':'loadButton',
'position':(510, 55),
'size':(85, 25),
'label':'Load CSV',
},
{'type':'Button',
'name':'appendButton',
'position':(510, 80),
'size':(85, 25),
'label':'Append CSV',
},
{'type':'Button',
'name':'swapButton',
'position':(510, 105),
'size':(85, 25),
'label':'Swap Lists',
},
{'type':'Button',
'name':'prevButton',
'position':(510, 130),
'size':(85, 25),
'label':'Prev',
},
{'type':'Button',
'name':'nextButton',
'position':(510, 155),
'size':(85, 25),
'label':'Next',
},
{'type':'Button',
'name':'exitButton',
'position':(510, 180),
'size':(85, 25),
'label':'Exit',
},
{'type':'MultiColumnList',
'name':'theList',
'position':(3, 3), #10, 305
'size':(500, 390),
'columnHeadings': ['Example List'],
'items':['Example 1','Example 2','Example 3'],
},
{'type':'TextArea',
'name':'displayArea',
'position':(3, 398),
'size':(500, 40),
'font':{'family': 'monospace', 'size': 12},
},
{'type':'TextArea',
'name':'countArea',
'position':(507, 398),
'size':(85, 40),
'font':{'family': 'monospace', 'size': 12},
},
]
}
]
}
}
|
# Refaça o desafio 035, acrescentando o recurso de mostrar que
# tipo de triângulo será formado:
# - Equilátero: todos os lados iguais;
# - Isósceles: dois lados iguais;
# - Escaleno: todos os lados diferentes.
n1 = float(input('\033[34mMedida 1:\033[m '))
n2 = float(input('\033[31mMedida 2:\033[m '))
n3 = float(input('\033[36mMedida 3:\033[m '))
if n1 < n2 + n3 and n2 < n1 + n3 and n3 < n1 + n2:
print('\033[30mCom essas medidas É POSSÍVEL montarmos um triângulo!\033[m')
if n1 == n2 and n2 == n3:
print('Esse triângulo será EQUILÁTERO.')
elif n1 == n2 or n1 == n3:
print('Esse triângulo será ISÓSCELES.')
elif n1 != n2 and n2 != n3:
print('Esse triângulo será ESCALENO.')
else:
print('\033[30mCom essas medidas NÃO É POSSÍVEL montarmos um triângulo!\033[m')
# Forma mais complexa e desnecessária que acabei fazendo
''' if n1 == n2 and n2 == n3 and n1 < n2 + n3 and n2 < n1 + n3 and n3 < n1 + n2:
print('\033[35mEsse triângulo será EQUILÁTERO!\033[m')
elif n1 == n2 or n1 == n3 and n1 < n2 + n3 and n2 < n1 + n3 and n3 < n1 + n2:
print('\033[35mEsse triângulo será ISÓSCELES!\033[m')
elif n1 != n2 and n2 != n3 and n1 < n2 + n3 and n2 < n1 + n3 and n3 < n1 + n2:
print('\033[35mEsse triângulo será ESCALENO!\033[m') '''
|
#!/usr/bin/env python3
"""
Models that maps to Cloudformation functions.
"""
def replace_fn(node):
"""Iteratively replace all Fn/Ref in the node"""
if isinstance(node, list):
return [replace_fn(item) for item in node]
if isinstance(node, dict):
return {name: replace_fn(value) for name, value in node.items()}
if isinstance(node, (str, int, float)):
return node
if isinstance(node, Ref):
return node.render()
if hasattr(Fn, node.__class__.__name__):
return node.render()
raise ValueError(f"Invalid value specified in the code: {node}")
class Ref:
"""Represents a ref function in Cloudformation."""
# This is our DSL, it's a very thin wrapper around dictionary.
# pylint: disable=R0903
def __init__(self, target):
"""Creates a Ref node with a target."""
self.target = target
def render(self):
"""Render the node as a dictionary."""
return {"Ref": self.target}
class Base64:
"""Fn::Base64 function."""
# pylint: disable=R0903
def __init__(self, value):
self.value = value
def render(self):
"""Render the node with Fn::Base64."""
return {"Fn::Base64": replace_fn(self.value)}
class Cidr:
"""Fn::Cidr function."""
# pylint: disable=R0903
def __init__(self, ipblock, count, cidr_bits):
self.ipblock = ipblock
self.count = count
self.cidr_bits = cidr_bits
def render(self):
"""Render the node with Fn::Cidr."""
return {
"Fn::Cidr": [
replace_fn(self.ipblock),
replace_fn(self.count),
replace_fn(self.cidr_bits),
]
}
class And:
"""Fn::And function."""
# pylint: disable=R0903
def __init__(self, *args):
self.conditions = list(args)
def render(self):
"""Render the node with Fn::And."""
return {"Fn::And": replace_fn(self.conditions)}
class Equals:
"""Fn::Equals function."""
# pylint: disable=R0903
def __init__(self, lhs, rhs):
self.lhs = lhs
self.rhs = rhs
def render(self):
"""Render the node with Fn::Equals."""
return {"Fn::Equals": [replace_fn(self.lhs), replace_fn(self.rhs)]}
class If:
"""Fn::If function."""
# pylint: disable=R0903
def __init__(self, condition, true_value, false_value):
self.condition = condition
self.true_value = true_value
self.false_value = false_value
def render(self):
"""Render the node with Fn::If."""
return {
"Fn::If": [
replace_fn(self.condition),
replace_fn(self.true_value),
replace_fn(self.false_value),
]
}
class Not:
"""Fn::Not function."""
# pylint: disable=R0903
def __init__(self, condition):
self.condition = condition
def render(self):
"""Render the node with Fn::Not."""
return {"Fn::Not": [replace_fn(self.condition)]}
class Or:
"""Fn::Or function."""
# pylint: disable=R0903
def __init__(self, *args):
self.conditions = list(args)
def render(self):
"""Render the node with Fn::Or."""
return {"Fn::Or": replace_fn(self.conditions)}
class FindInMap:
"""Fn::FindInMap function."""
# pylint: disable=R0903
def __init__(self, map_name, l1key, l2key):
self.map_name = map_name
self.l1key = l1key
self.l2key = l2key
def render(self):
"""Render the node with Fn::FindInMap."""
return {
"Fn::FindInMap": [
replace_fn(self.map_name),
replace_fn(self.l1key),
replace_fn(self.l2key),
]
}
class GetAtt:
"""Fn::GetAtt function."""
# pylint: disable=R0903
def __init__(self, logical_name, attr):
self.logical_name = logical_name
self.attr = attr
def render(self):
"""Render the node with Fn::GetAtt."""
return {"Fn::GetAtt": [replace_fn(self.logical_name), replace_fn(self.attr)]}
class GetAZs:
"""Fn::GetAZs function."""
# pylint: disable=R0903
def __init__(self, region):
self.region = region
def render(self):
"""Render the node with Fn::GetAZs."""
return {"Fn::GetAZs": replace_fn(self.region)}
class ImportValue:
"""Fn::ImportValue function."""
# pylint: disable=R0903
def __init__(self, export):
self.export = export
def render(self):
"""Render the node with Fn::ImportValue."""
return {"Fn::ImportValue": replace_fn(self.export)}
class Join:
"""Fn::Join function."""
# pylint: disable=R0903
def __init__(self, delimiter, elements):
self.delimiter = delimiter
self.elements = elements
def render(self):
"""Render the node with Fn::Join."""
return {"Fn::Join": [replace_fn(self.delimiter), replace_fn(self.elements)]}
class Select:
"""Fn::Select function."""
# pylint: disable=R0903
def __init__(self, index, elements):
self.index = index
self.elements = elements
def render(self):
"""Render the node with Fn::Select."""
return {"Fn::Select": [replace_fn(self.index), replace_fn(self.elements)]}
class Split:
"""Fn::Split function."""
# pylint: disable=R0903
def __init__(self, delimiter, target):
self.delimiter = delimiter
self.target = target
def render(self):
"""Render the node with Fn::Split."""
return {"Fn::Split": [replace_fn(self.delimiter), replace_fn(self.target)]}
class Sub:
"""Fn::Sub function."""
# pylint: disable=R0903
def __init__(self, target, mapping=None):
if not isinstance(target, str):
raise ValueError(
f"The first argument of Fn::Sub must be string: `{target}`"
)
if mapping is None:
self.mapping = {}
self.target = target
self.mapping = mapping
def render(self):
"""Render the node with Fn::Sub."""
if self.mapping:
return {"Fn::Sub": [replace_fn(self.target), replace_fn(self.mapping)]}
return {"Fn::Sub": replace_fn(self.target)}
class Transform:
"""Fn::Transform function."""
# pylint: disable=R0903
def __init__(self, construct):
is_dict = isinstance(construct, dict)
match_keys = set(construct.keys()) == {"Name", "Parameters"}
if not is_dict or not match_keys:
raise ValueError("Invalid Transform construct")
self.construct = construct
def render(self):
"""Render the node with Fn::Transform."""
return {
"Fn::Transform": {
"Name": replace_fn(self.construct["Name"]),
"Parameters": replace_fn(self.construct["Parameters"]),
}
}
class Fn:
"""
This is a container for all functions.
Rationale is instead of having to import all the functions,
we just import Fn and use any function as Fn.FuncName
"""
# pylint: disable=R0903
Base64 = Base64
Cidr = Cidr
And = And
Equals = Equals
If = If
Not = Not
Or = Or
FindInMap = FindInMap
GetAtt = GetAtt
GetAZs = GetAZs
ImportValue = ImportValue
Join = Join
Select = Select
Split = Split
Sub = Sub
Transform = Transform
|
"""Rule and corresponding provider that joins a label pointing to a TreeArtifact
with a path nested within that directory
"""
load("//lib:utils.bzl", _to_label = "to_label")
DirectoryPathInfo = provider(
doc = "Joins a label pointing to a TreeArtifact with a path nested within that directory.",
fields = {
"directory": "a TreeArtifact (ctx.actions.declare_directory)",
"path": "path relative to the directory",
},
)
def _directory_path(ctx):
if not ctx.file.directory.is_directory:
fail("directory attribute must be created with Bazel declare_directory (TreeArtifact)")
return [DirectoryPathInfo(path = ctx.attr.path, directory = ctx.file.directory)]
directory_path = rule(
doc = """Provide DirectoryPathInfo to reference some path within a directory.
Otherwise there is no way to give a Bazel label for it.""",
implementation = _directory_path,
attrs = {
"directory": attr.label(
doc = "a TreeArtifact (ctx.actions.declare_directory)",
mandatory = True,
allow_single_file = True,
),
"path": attr.string(
doc = "path relative to the directory",
mandatory = True,
),
},
provides = [DirectoryPathInfo],
)
def make_directory_path(name, directory, path, **kwargs):
"""Helper function to generate a directory_path target and return its label.
Args:
name: unique name for the generated `directory_path` target
directory: `directory` attribute passed to generated `directory_path` target
path: `path` attribute passed to generated `directory_path` target
**kwargs: parameters to pass to generated `output_files` target
Returns:
The label `name`
"""
directory_path(
name = name,
directory = directory,
path = path,
**kwargs
)
return _to_label(name)
def make_directory_paths(name, dict, **kwargs):
"""Helper function to convert a dict of directory to path mappings to directory_path targets and labels.
For example,
```
make_directory_paths("my_name", {
"//directory/artifact:target_1": "file/path",
"//directory/artifact:target_2": ["file/path1", "file/path2"],
})
```
generates the targets,
```
directory_path(
name = "my_name_0",
directory = "//directory/artifact:target_1",
path = "file/path"
)
directory_path(
name = "my_name_1",
directory = "//directory/artifact:target_2",
path = "file/path1"
)
directory_path(
name = "my_name_2",
directory = "//directory/artifact:target_2",
path = "file/path2"
)
```
and the list of targets is returned,
```
[
"my_name_0",
"my_name_1",
"my_name_2",
]
```
Args:
name: The target name to use for the generated targets & labels.
The names are generated as zero-indexed `name + "_" + i`
dict: The dictionary of directory keys to path or path list values.
**kwargs: additional parameters to pass to each generated target
Returns:
The label of the generated `directory_path` targets named `name + "_" + i`
"""
labels = []
pairs = []
for directory, val in dict.items():
if type(val) == "list":
for path in val:
pairs.append((directory, path))
elif type(val) == "string":
pairs.append((directory, val))
else:
fail("Value must be a list or string")
for i, pair in enumerate(pairs):
directory, path = pair
labels.append(make_directory_path(
"%s_%d" % (name, i),
directory,
path,
**kwargs
))
return labels
|
# Programa Simulador de Caixa Eletrônico
# O caixa possui cédulas de 50, 20, 10 e 1
# Forma 1 = MINHA FORMA, COMPLICADA, MEIO NO CHUTE
print('=' * 50)
print('{:^50}'.format(' BANCO SIMÕES '))
print('=' * 50)
valor = int(input('Qual valor você quer sacar: R$'))
while True:
if valor % 50 != 1:
if valor // 50 > 0:
print(f'Total de {valor//50} cédulas de R$50,00')
valor = valor - (valor // 50) * 50
if (valor // 50) * 50 - valor == 0:
break
if valor % 20 != 1:
if valor // 20 > 0:
print(f'Total de {valor//20} cédulas de R$20,00')
valor = valor - (valor // 20) * 20
if (valor // 20) * 20 - valor == 0:
break
if valor % 10 != 1:
if valor // 10 > 0:
print(f'Total de {valor//10} cédulas de R$10,00')
valor = valor - (valor//10) * 10
if (valor // 10) * 10 - valor == 0:
break
if valor % 1 == 0:
if valor // 1 > 0:
print(f'Total de {valor//1} cédulas de R$1,00')
valor = (valor // 1) * 1 - valor == 0
if (valor // 1) * 1 - valor == 0:
break
print('=' * 50)
print('Obrigado, volte sempre ao BANCO SIMÕES!')
#FORMA 2: Curso em Vídeo, SIMPLES
print('=' * 50)
print('{:^50}'.format(' BANCO SIMÕES '))
print('=' * 50)
valor = int(input('Qual valor você quer sacar: R$'))
total = valor # Total do montante a ser sacado, que começa valendo o valor digitado pelo usuário
cedula = 50 # A primeira cédula a ser verificada é 50
totalCedulas = 0 # Contagem de cédulas
while True:
if total >= cedula: # Se o total for maior que o valor da cédula, retiro do total uma cédula e o totalCédulas é +1
total -= cedula
totalCedulas += 1
else: # Se não conseguir retirar o do total uma cédula
if totalCedulas > 0:
print(f'Total de {totalCedulas} cédulas de R${cedula},00')
if cedula == 50:
cedula = 20
elif cedula == 20: # Tem que ser elif, se não, o programa entra em conflito com os valores e vai a R$1 direto
cedula = 10
elif cedula == 10: # Tem que ser elif, se não, o programa entra em conflito com os valores e vai a R$1 direto
cedula = 1
totalCedulas = 0 # Sempre que o valor da cédula for trocado, o total de cédulas volta a 0
if total == 0:
break
print('=' * 50)
print('Obrigado, volte sempre ao BANCO SIMÕES!')
|
# Find algorithm that sorts the stack of size n in O(log(n)) time. It is allowed to use operations
# provided only by the stack interface: push(), pop(), top(), isEmpty() and additional stacks.
class Stack:
def __init__(self):
self.stack = []
def push(self, value):
self.stack.append(value)
def pop(self):
return self.stack.pop()
def top(self):
return self.stack[-1]
def isEmpty(self):
if self.stack == []:
return True
else:
return False
def sort_stack(stack):
temporary_stack = Stack()
while not stack.isEmpty():
value = stack.pop()
while not temporary_stack.isEmpty() and temporary_stack.top() > value:
stack.push(temporary_stack.pop())
temporary_stack.push(value)
while not temporary_stack.isEmpty():
stack.push(temporary_stack.pop())
result = []
while not stack.isEmpty():
result.append(stack.pop())
return result
def create_stack(T):
stack = Stack()
for i in range(len(T)):
stack.push(T[i])
return stack
T = [7, 10, 7, 87, 5, 53, 10, 15, 49, 1, 73, 14, 8, 68, 2, 32, 23, 41, 35, 98, 26]
stack = create_stack(T)
print(sort_stack(stack))
|
#!/usr/bin/python3
'''
Pegando todos os parametros
Um argumento pocisional sempre deve estar antes de parametros nomeados
def todos_params(*args, **kwargs):
Significa que quer pegar os argumentos de uma forma genérica
tanto pocisionais quanto os nomeados
'''
def todos_params(*args, **kwargs):
print(f'args: {args}')
print(f'kwargs: {kwargs}')
if __name__ == '__main__':
# 3 parametros posicionais
todos_params('a', 'b', 'c')
# 3 parametros pocisinais + 2 nomeados
todos_params(1, 2, 3, legal=True, valor=12.99)
# 3 parametros posicionais + 2 nomeados
todos_params('Ana', False, [1, 2, 3], tamanho='M', fragil=False)
# 2 parametros nomeados
todos_params(primeiro='João', segundo='Maria')
# 1 parametro pociaional + 1 nomeados
todos_params('Maria', primeiro='João')
# Forma incorreto, passando parametro pocional depois do nomeado
# todos_params(primeiro='João', 'Maria')
# Fontes:
# Curso Python 3 - Curso Completo do Básico ao Avançado Udemy Aula 124
# https://github.com/cod3rcursos/curso-python/tree/master/funcoes
|
N = int(input())
MAX, VAR, FIX = range(3)
# latest=9 r=3 b=4
# max_variable_fixed_values = [
# 3 4 5
# 2 3 3
# 2 1 5
# 2 4 2
# 2 2 4
# 2 5 1
# ]
def try_to_beat(latest_score, r, b, max_var_fixed):
our_score = 0
while b > 0:
if not r:
return -1
best_c_max_b, best_max_b = 0, 0
for max_b, variable, fixed in max_var_fixed:
this_c_max = min(
max_b,
b,
(latest_score - fixed - 1)//variable
)
if this_c_max > best_max_b: # and this_c_max > 0
best_c_max_b, best_max_b = ([max_b, variable, fixed], this_c_max)
if not best_max_b:
return -1
max_var_fixed.remove(best_c_max_b)
b -= best_max_b
r -= 1
our_score = max(
our_score,
best_c_max_b[FIX] + best_max_b*best_c_max_b[VAR]
)
return our_score
def initial_total_time(b, max_var_fixed):
initial_best_time = 0
for max_b, variable, fixed in max_var_fixed:
passed_bits = min(b, max_b)
b -= passed_bits
initial_best_time = max(
initial_best_time,
fixed + variable*passed_bits
)
if not b:
return initial_best_time
for case_id in range(1, N + 1):
r, b, c = map(int, input().split())
max_variable_fixed_values = sorted([
[*map(int, input().split())]
for _ in range(c)
], key=lambda item: item[MAX], reverse=True)
total_time = initial_total_time(b, max_variable_fixed_values)
print(total_time)
while True:
new_attempt = try_to_beat(total_time, r, b, max_variable_fixed_values.copy())
print(new_attempt)
if new_attempt == -1:
break
else:
total_time = new_attempt
print('Case #{}: {}'.format(case_id, total_time))
|
#
# PySNMP MIB module CTRON-CHASSIS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-CHASSIS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:44:24 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)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint")
ctronChassis, = mibBuilder.importSymbols("CTRON-MIB-NAMES", "ctronChassis")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, TimeTicks, Integer32, Counter32, Counter64, NotificationType, ObjectIdentity, iso, MibIdentifier, ModuleIdentity, Unsigned32, Bits, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "TimeTicks", "Integer32", "Counter32", "Counter64", "NotificationType", "ObjectIdentity", "iso", "MibIdentifier", "ModuleIdentity", "Unsigned32", "Bits", "Gauge32")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
ctChas = MibIdentifier((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 1))
ctEnviron = MibIdentifier((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2))
ctFanModule = MibIdentifier((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 3))
ctChasFNB = MibScalar((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("absent", 1), ("present", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ctChasFNB.setStatus('mandatory')
if mibBuilder.loadTexts: ctChasFNB.setDescription('Denotes the presence or absence of the FNB.')
ctChasAlarmEna = MibScalar((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("disable", 1), ("enable", 2), ("notSupported", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ctChasAlarmEna.setStatus('mandatory')
if mibBuilder.loadTexts: ctChasAlarmEna.setDescription('Allow an audible alarm to be either enabled or dis- abled. Setting this object to disable(1) will prevent an audible alarm from being heard and will also stop the sound from a current audible alarm. Setting this object to enable(2) will allow an audible alarm to be heard and will also enable the sound from a current audible alarm, if it has previously been disabled. This object will read with the current setting.')
chassisAlarmState = MibScalar((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("chassisNoFaultCondition", 1), ("chassisFaultCondition", 2), ("notSupported", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisAlarmState.setStatus('mandatory')
if mibBuilder.loadTexts: chassisAlarmState.setDescription('Denotes the current condition of the power supply fault detection circuit. This object will read with the value of chassisNoFaultCondition(1) when the chassis is currently operating with no power faults detected. This object will read with the value of chassisFaultCondition(2) when the chassis is currently in a power fault condition.')
ctChasPowerTable = MibTable((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2, 1), )
if mibBuilder.loadTexts: ctChasPowerTable.setStatus('mandatory')
if mibBuilder.loadTexts: ctChasPowerTable.setDescription('A list of power supply entries.')
ctChasPowerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2, 1, 1), ).setIndexNames((0, "CTRON-CHASSIS-MIB", "ctChasPowerSupplyNum"))
if mibBuilder.loadTexts: ctChasPowerEntry.setStatus('mandatory')
if mibBuilder.loadTexts: ctChasPowerEntry.setDescription('An entry in the powerTable providing objects for a power supply.')
ctChasPowerSupplyNum = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ctChasPowerSupplyNum.setStatus('mandatory')
if mibBuilder.loadTexts: ctChasPowerSupplyNum.setDescription('Denotes the power supply.')
ctChasPowerSupplyState = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("infoNotAvailable", 1), ("notInstalled", 2), ("installedAndOperating", 3), ("installedAndNotOperating", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ctChasPowerSupplyState.setStatus('mandatory')
if mibBuilder.loadTexts: ctChasPowerSupplyState.setDescription("Denotes the power supply's state.")
ctChasPowerSupplyType = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("ac-dc", 1), ("dc-dc", 2), ("notSupported", 3), ("highOutput", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ctChasPowerSupplyType.setStatus('mandatory')
if mibBuilder.loadTexts: ctChasPowerSupplyType.setDescription('Denotes the power supply type.')
ctChasPowerSupplyRedundancy = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("redundant", 1), ("notRedundant", 2), ("notSupported", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ctChasPowerSupplyRedundancy.setStatus('mandatory')
if mibBuilder.loadTexts: ctChasPowerSupplyRedundancy.setDescription('Denotes whether or not the power supply is redundant.')
ctChasFanModuleTable = MibTable((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 3, 1), )
if mibBuilder.loadTexts: ctChasFanModuleTable.setStatus('mandatory')
if mibBuilder.loadTexts: ctChasFanModuleTable.setDescription('A list of fan module entries.')
ctChasFanModuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 3, 1, 1), ).setIndexNames((0, "CTRON-CHASSIS-MIB", "ctChasFanModuleNum"))
if mibBuilder.loadTexts: ctChasFanModuleEntry.setStatus('mandatory')
if mibBuilder.loadTexts: ctChasFanModuleEntry.setDescription('An entry in the fan module Table providing objects for a fan module.')
ctChasFanModuleNum = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 3, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ctChasFanModuleNum.setStatus('mandatory')
if mibBuilder.loadTexts: ctChasFanModuleNum.setDescription('Denotes the Fan module that may have failed.')
ctChasFanModuleState = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("infoNotAvailable", 1), ("notInstalled", 2), ("installedAndOperating", 3), ("installedAndNotOperating", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ctChasFanModuleState.setStatus('mandatory')
if mibBuilder.loadTexts: ctChasFanModuleState.setDescription('Denotes the fan modules state.')
mibBuilder.exportSymbols("CTRON-CHASSIS-MIB", ctEnviron=ctEnviron, ctChasPowerSupplyNum=ctChasPowerSupplyNum, ctChasFanModuleState=ctChasFanModuleState, ctChasPowerEntry=ctChasPowerEntry, ctChasPowerSupplyState=ctChasPowerSupplyState, chassisAlarmState=chassisAlarmState, ctChasPowerSupplyType=ctChasPowerSupplyType, ctChas=ctChas, ctChasFanModuleEntry=ctChasFanModuleEntry, ctChasFanModuleTable=ctChasFanModuleTable, ctChasFNB=ctChasFNB, ctChasPowerTable=ctChasPowerTable, ctChasPowerSupplyRedundancy=ctChasPowerSupplyRedundancy, ctChasAlarmEna=ctChasAlarmEna, ctChasFanModuleNum=ctChasFanModuleNum, ctFanModule=ctFanModule)
|
class BaseDataset:
def __init__(self, data=list()):
self.data = data
def __getitem__(self, idx):
return self.data[idx]
def __len__(self):
return len(self.data)
|
"""Calculators for different values.
In order to approximate the emissions for a single kWh of produced
energy, per power source we look at the following 2016 data sets.
* Detailed EIA-923 emissions survey data
(https://www.eia.gov/electricity/data/state/emission_annual.xls)
* Net Generation by State by Type of Producer by Energy Source
(EIA-906, EIA-920, and EIA-923)
(https://www.eia.gov/electricity/data/state/annual_generation_state.xls)
The NY Numbers for 2016 on power generation are (power in MWh)
2016 NY Total Electric Power Industry Total 134,417,107
2016 NY Total Electric Power Industry Coal 1,770,238
2016 NY Total Electric Power Industry Pumped Storage -470,932
2016 NY Total Electric Power Industry Hydroelectric Conventional 26,888,234
2016 NY Total Electric Power Industry Natural Gas 56,793,336
2016 NY Total Electric Power Industry Nuclear 41,570,990
2016 NY Total Electric Power Industry Other Gases 0
2016 NY Total Electric Power Industry Other 898,989
2016 NY Total Electric Power Industry Petroleum 642,952
2016 NY Total Electric Power Industry Solar Thermal and Photovoltaic 139,611
2016 NY Total Electric Power Industry Other Biomass 1,604,650
2016 NY Total Electric Power Industry Wind 3,940,180
2016 NY Total Electric Power Industry Wood and Wood Derived Fuels 638,859
The NY Numbers on Emissions are (metric tons of CO2, SO2, NOx)
2016 NY Total Electric Power Industry All Sources 31,295,191 18,372 32,161
2016 NY Total Electric Power Industry Coal 2,145,561 10,744 2,635
2016 NY Total Electric Power Industry Natural Gas 26,865,277 122 14,538
2016 NY Total Electric Power Industry Other Biomass 0 1 8,966
2016 NY Total Electric Power Industry Other 1,660,517 960 3,991
2016 NY Total Electric Power Industry Petroleum 623,836 1,688 930
2016 NY Total Electric Power Industry Wood and Wood Derived Fuels 0 4,857 1,101
Duel Fuel systems are interesting, they are designed to burn either
Natural Gas, or Petroleum when access to NG is limited by price or
capacity. (Under extreme cold conditions NG supply is prioritized for
heating)
We then make the following simplifying assumptions (given access to the data):
* All natural gas generation is the same from emissions perspective
* The duel fuel systems burned 30% of the total NG in the state, and
all of the Petroleum. Based on eyeballing the Duel Fuel systems,
they tend to be running slightly less than straight NG systems.
* The mix of NG / Oil burned in duel fuel plants is constant
throughout the year. This is clearly not true, but there is no
better time resolution information available.
* All other fossil fuels means Coal. All Coal is equivalent from
emissions perspective.
"""
# PWR in MWh
# CO2 in Metric Tons
#
# TODO(sdague): add in
FUEL_2016 = {
"Petroleum": {
"Power": 642952,
"CO2": 623836
},
"Natural Gas": {
"Power": 56793336,
"CO2": 26865277
},
"Other Fossil Fuels": {
"Power": 1770238,
"CO2": 2145561
}
}
# assume Dual Fuel systems consume 30% of state NG. That's probably low.
FUEL_2016["Dual Fuel"] = {
"Power": (FUEL_2016["Petroleum"]["Power"] +
(FUEL_2016["Natural Gas"]["Power"] * .3)),
"CO2": (FUEL_2016["Petroleum"]["CO2"] +
(FUEL_2016["Natural Gas"]["CO2"] * .3)),
}
# Calculate CO2 per kWh usage
def co2_for_fuel(fuel):
"Returns metric tons per / MWh, or kg / kWh"
if fuel in FUEL_2016:
hpow = FUEL_2016[fuel]["Power"]
hco2 = FUEL_2016[fuel]["CO2"]
co2per = float(hco2) / float(hpow)
return co2per
else:
return 0.0
def co2_rollup(rows):
total_kW = 0
total_co2 = 0
for row in rows:
fuel_name = row[2]
kW = int(float(row[3]))
total_kW += kW
total_co2 += kW * co2_for_fuel(fuel_name)
co2_per_kW = total_co2 / total_kW
return co2_per_kW
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/2/11 14:23
# @Author : Baimohan/PH
# @Site : https://github.com/BaiMoHan
# @File : comment_test.py
# @Software: PyCharm
print("hello world")
# 这是一行注释
'''
多行注释
单引号形式
'''
"""
双引号多注释 三个双引号
"""
print("测试")
a = 5
print(a)
a += 3
print(a)
|
def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the message will be displayed
assert 'DecisionTreeClassifier' in __solution__, "Make sure you are specifying a 'DecisionTreeClassifier'."
assert model.get_params()['random_state'] == 1, "Make sure you are settting the model's 'random_state' to 1."
assert 'model.fit' in __solution__, "Make sure you are using the '.fit()' function to fit 'X' and 'y'."
assert 'model.predict(X)' in __solution__, "Make sure you are using the model to predict on 'X'."
assert list(predicted).count('Canada') == 6, "Your predicted values are incorrect. Are you fitting the model properly?"
assert list(predicted).count('Both') == 8, "Your predicted values are incorrect. Are you fitting the model properly?"
assert list(predicted).count('America') == 11, "Your predicted values are incorrect. Are you fitting the model properly?"
__msg__.good("Nice work, well done!") |
"""EXCEPTIONS
Exceptions used on the project
"""
__all__ = ("VigoBusAPIException", "StopNotExist", "StopNotFound")
class VigoBusAPIException(Exception):
"""Base exception for the project custom exceptions"""
pass
class StopNotExist(VigoBusAPIException):
"""The Stop does not physically exist (as reported by an external trusted API/data source)"""
pass
class StopNotFound(VigoBusAPIException):
"""The Stop was not found on a local data source, but might physically exist"""
pass
|
def foo():
'''
>>> from mod import CamelCase as CONST
'''
pass
|
#! python3
###############################################################################
# Copyright (c) 2021, PulseRain Technology LLC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (LGPL) as
# published by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
###############################################################################
# References:
# https://en.wikipedia.org/wiki/Pseudorandom_binary_sequence
###############################################################################
class PRBS:
def reset(self, prbs_length, start_value):
if (prbs_length == 7):
self.poly = 0xC1 >> 1
elif (prbs_length == 9):
self.poly = 0x221 >> 1
elif (prbs_length == 11):
self.poly = 0xA01 >> 1
elif (prbs_length == 15):
self.poly = 0xC001 >> 1
elif (prbs_length == 20):
self.poly = 0x80005 >> 1
elif (prbs_length == 23):
self.poly = 0x840001 >> 1
else:
assert (prbs_length == 31)
self.poly = 0xA0000001 >> 1
self.state = start_value
self.prbs_length = prbs_length
def __init__ (self, prbs_length, start_value):
self.reset (prbs_length, start_value)
def get_next (self):
next_bit = 0
for i in range(self.prbs_length):
if ((self.poly >> i) & 1):
next_bit = next_bit ^ ((self.state >> i) & 1)
self.state = ((self.state << 1) | next_bit) & ((2**(self.prbs_length + 1)) - 1)
return self.state
def main():
init = 2
p = PRBS (15, init)
i = 0
while(1):
x = p.get_next()
print ("%d 0x%x" % (i, x))
if (x == init):
print ("period = %d" % (i + 1))
break
i = i + 1
if __name__ == "__main__":
main()
|
class AVLNode:
def __init__(self, key):
self.key = key
self.parent = None
self.left = None
self.right = None
self.balance = 0
def has_left(self): return self.left is not None
def has_right(self): return self.right is not None
def has_no_children(self): return not (self.has_left() or self.has_right())
def is_root(self): return isinstance(self.parent, AVLTree)
def is_left(self): return self is self.parent.left
def is_right(self): return self is self.parent.right
def is_unbalanced(self): return abs(self.balance) > 1
def set_left(self, key):
self.left = AVLNode(key)
self.left.parent = self
self.left.update_balance()
def set_right(self, key):
self.right = AVLNode(key)
self.right.parent = self
self.right.update_balance()
def update_balance(self):
if self.is_unbalanced():
return self.new_balance()
if not self.is_root():
parent = self.parent
if self.is_left():
parent.balance += 1
elif self.is_right():
parent.balance -= 1
if parent.balance != 0:
parent.update_balance()
def new_balance(self):
if self.balance < 0:
if self.right.balance > 0:
self.right.rotate_right()
self.rotate_left()
else:
self.rotate_left()
elif self.balance > 0:
if self.left.balance < 0:
self.left.rotate_left()
self.rotate_right()
else:
self.rotate_right()
def rotate_left(self):
parent = self.parent
if self.is_root():
parent.root = self.__rotate_left()
elif self.is_left():
parent.left = self.__rotate_left()
elif self.is_right():
parent.right = self.__rotate_left()
def __rotate_left(self):
pivot = self.right
self.right = pivot.left
if pivot.has_left():
pivot.left.parent = self
pivot.left = self
parent = self.parent
self.parent = pivot
pivot.parent = parent
self.balance = self.balance + 1 - min(0, pivot.balance)
pivot.balance = pivot.balance + 1 + max(0, self.balance)
return pivot
def rotate_right(self):
parent = self.parent
if self.is_root():
parent.root = self.__rotate_right()
elif self.is_left():
parent.left = self.__rotate_right()
elif self.is_right():
parent.right = self.__rotate_right()
def __rotate_right(self):
pivot = self.left
self.left = pivot.right
if pivot.has_right():
pivot.right.parent = self
pivot.right = self
parent = self.parent
self.parent = pivot
pivot.parent = parent
self.balance = self.balance - 1 - max(0, pivot.balance)
pivot.balance = pivot.balance - 1 + min(0, self.balance)
return pivot
def search(self, key):
node = self
while True:
if key == node.key:
return node
elif key < node.key:
if node.has_left():
node = node.left
else:
break
else:
if node.has_right():
node = node.right
else:
break
def search_max(self):
node = self
while node.has_right():
node = node.right
return node
def update_balance_on_delete(self, came_from_left):
if came_from_left:
self.balance -= 1
else:
self.balance += 1
if self.is_unbalanced():
self.new_balance()
if not self.is_root():
if self.parent.balance == 0 and not self.parent.is_root():
self.parent.parent.update_balance_on_delete(self.parent.is_left())
elif self.balance == 0 and not self.is_root():
self.parent.update_balance_on_delete(self.is_left())
def delete(self, node_or_key):
if isinstance(node_or_key, AVLNode):
node = node_or_key
else:
node = self.search(node_or_key)
if node is None:
return
parent = node.parent
if node.has_no_children():
if node.is_root():
parent.root = None
elif node.is_left():
parent.left = None
parent.update_balance_on_delete(True)
elif node.is_right():
parent.right = None
parent.update_balance_on_delete(False)
elif node.has_left() and not node.has_right():
if node.is_root():
parent.root = node.left
node.left.parent = parent
elif node.is_left():
parent.left = node.left
node.left.parent = parent
parent.update_balance_on_delete(True)
elif node.is_right():
parent.right = node.left
node.left.parent = parent
parent.update_balance_on_delete(False)
elif node.has_right() and not node.has_left():
if node.is_root():
parent.root = node.right
node.right.parent = parent
elif node.is_left():
parent.left = node.right
node.right.parent = parent
parent.update_balance_on_delete(True)
elif node.is_right():
parent.right = node.right
node.right.parent = parent
parent.update_balance_on_delete(False)
else:
left_max = node.left.search_max()
node.key = left_max.key
node.left.delete(left_max)
def exists(self, key):
return bool(self.search(key))
def insert(self, key):
tmp_node = self
while True:
if key == tmp_node.key: break
elif key < tmp_node.key:
if tmp_node.has_left(): tmp_node = tmp_node.left
else:
tmp_node.set_left(key)
break
else:
if tmp_node.has_right(): tmp_node = tmp_node.right
else:
tmp_node.set_right(key)
break
@staticmethod
def next(tree, x):
if tree is None or (tree.key == x and not tree.has_right()): return 'none'
elif tree.key > x:
k = AVLNode.next(tree.left, x)
if k == 'none': return tree.key
else: return k
elif tree.key < x: return AVLNode.next(tree.right, x)
elif tree.key == x: return AVLNode.next(tree.right, x)
@staticmethod
def prev(tree, x):
if tree is None or (tree.key == x and not tree.has_left()): return 'none'
elif tree.key < x:
k = AVLNode.prev(tree.right, x)
if k == 'none': return tree.key
else: return k
elif tree.key > x: return AVLNode.prev(tree.left, x)
elif tree.key == x: return AVLNode.prev(tree.left, x)
@staticmethod
def kth(tree, ind, nodes_lst):
if tree is None or nodes_lst[0] >= ind: return 'none'
left = AVLNode.kth(tree.left, ind, nodes_lst)
if left != 'none': return left
nodes_lst[0] += 1
if nodes_lst[0] == ind: return tree.key
return AVLNode.kth(tree.right, ind, nodes_lst)
class AVLTree:
def __init__(self): self.root = None
def is_empty(self): return self.root is None
def insert(self, key):
if self.is_empty():
self.root = AVLNode(key)
self.root.parent = self
else:
self.root.insert(key)
def exists(self, key):
if self.is_empty(): return 'false'
else: return 'true' if self.root.exists(key) else 'false'
def delete(self, key):
if not self.is_empty(): self.root.delete(key)
def next(self, x):
if not self.is_empty(): return AVLNode.next(self.root, x)
else: return 'none'
def prev(self, x):
if not self.is_empty(): return AVLNode.prev(self.root, x)
else: return 'none'
def kth(self, i):
if not self.is_empty(): return AVLNode.kth(self.root, i, [0])
else: return 'none'
if __name__ == "__main__":
root = AVLTree()
while True:
try: cmd, arg = input().split()
except: break
if cmd == 'insert': root.insert(int(arg))
elif cmd == 'delete': root.delete(int(arg))
elif cmd == 'exists': print(root.exists(int(arg)))
elif cmd == 'next': print(root.next(int(arg)))
elif cmd == 'prev': print(root.prev(int(arg)))
elif cmd == 'kth': print(root.kth(int(arg))) |
# Project Euler Problem 11
# Created on: 2012-06-14
# Created by: William McDonald
# Return the minimum number that can be present in
# a solution set of four numbers
def getMin(cap, min):
k = 99 * 99 * 99
for i in range(min, 99):
if i * k > cap:
return i
def importGrid():
f = open("problem11.txt")
grid = []
for line in f:
str = line
lon = str.split(" ")
i = 0
for n in lon:
lon[i] = int(n)
i += 1
grid.append(lon)
f.close()
return grid
def transpose(g):
return map(list, zip(*g))
def makeDiagGrid(g):
n = []
for i in range(3, len(g)):
temp = []
for j in range(i, -1, -1):
temp.append(g[j][i - j])
n.append(temp)
for i in range(1, len(g) - 3):
temp = []
for j in range(0, len(g) - i):
temp.append(g[i + j][len(g) - 1 - j])
n.append(temp)
return n
def getAns():
# Cursory examination: 94 * 99 * 71 * 61
max = 94 * 99 * 71 * 61
min = getMin(max, 0)
udg = importGrid()
lrg = transpose(udg)
dg1 = makeDiagGrid(lrg)
lrg.reverse()
dg2 = makeDiagGrid(lrg)
grids = [udg, lrg, dg1, dg2]
for g in grids:
prod = 1
i = 0
while i < len(g):
j = 0
lst = g[i]
while j < (len(lst) - 3):
for k in range(4):
if lst[j + k] < min:
j += k
break
else:
prod *= lst[j + k]
else:
if prod > max:
max = prod
min = getMin(max, min)
j += 1
prod = 1
i += 1
return max
ans = getAns()
print(ans)
|
def get_final_line(
filepath: str
) -> str:
with open(filepath) as fs_r:
for line in fs_r:
pass
return line
def get_final_line__readlines(
filepath: str
) -> str:
with open(filepath) as fs_r:
return fs_r.readlines()[-1]
def main():
filepath = 'file.txt'
final_line_content = get_final_line(filepath)
print(f'Final line content: [{final_line_content}]')
if __name__ == '__main__':
main()
|
price = float(input("Digite o preco do produto: "))
discount = (5/100) * price
total = price - discount
print("O valor com desconto eh: {:.2f}".format(total)) |
def soma(n1, n2):
return n1 + n2
def subtracao(n1,n2):
return n1 - n2
def multiplicacao(n1, n2):
return n1 * n2
def divisao(n1, n2):
return n1 / n2
|
"""
________ ___ __ ________ ________ ___ ___ ________ _______ ________
|\ ____\|\ \ |\ \|\ __ \|\ __ \ |\ \|\ \|\ ____\|\ ___ \ |\ __ \
\ \ \___|\ \ \ \ \ \ \ \|\ \ \ \|\ \ \ \ \\\ \ \ \___|\ \ __/|\ \ \|\ \
\ \_____ \ \ \ __\ \ \ \ __ \ \ ____\ \ \ \\\ \ \_____ \ \ \_|/_\ \ _ _\
\|____|\ \ \ \|\__\_\ \ \ \ \ \ \ \___| \ \ \\\ \|____|\ \ \ \_|\ \ \ \\ \|
____\_\ \ \____________\ \__\ \__\ \__\ \ \_______\____\_\ \ \_______\ \__\\ _\
|\_________\|____________|\|__|\|__|\|__| \|_______|\_________\|_______|\|__|\|__|
\|_________| \|_________|
"""
__title__ = "Django Swap User"
__version__ = "0.9.8"
__author__ = "Artem Innokentiev"
__license__ = "MIT"
__copyright__ = "Copyright 2022 © Artem Innokentiev"
VERSION = __version__
default_app_config = "swap_user.apps.DjangoSwapUser"
|
# noinspection PyUnusedLocal
# skus = unicode string
price_table = { 'A': {'Price': 50, 'Offers': ['3A', 130]},
'B': {'Price': 30, 'Offers': ['2b', 45]},
'C': {'Price': 20, 'Offers': []},
'D': {'Price': 15, 'Offers': []}
}
def checkout(skus):
if ((skus.isalpha() and skus.isupper()) or skus == ''):
order_dict = build_orders(skus)
running_total = 0
for order in order_dict:
cur_total = get_price(order, order_dict[order])
running_total += cur_total
return running_total
else:
return -1
def get_price(stock, units):
try:
item = price_table.get(stock)
running_total = 0
offers = item.get('Offers', [])
if item.get('Offers', []) != []:
offer = int(offers[0][0])
if units >= offer:
offer_quantity = int(units / int(offer))
running_total += (offers[1] * offer_quantity)
units -= int(offer_quantity * offer)
amount = units * item['Price']
running_total += amount
return running_total
except Exception as e:
return 0
def build_orders(orders):
order_dict = {}
for order in orders:
quantity = order_dict.get(order.upper(), 0)
quantity += 1
order_dict.update({order.upper(): quantity})
return order_dict |
"""
Add `Django Filebrowser`_ to your project so you can use a centralized interface to manage the uploaded files to be used with other components (`cms`_, `zinnia`_, etc.).
The version used is a special version called *no grappelli* that can be used outside of the *django-grapelli* environment.
Filebrowser manage files with a nice interface to centralize them and also manage image resizing versions (original, small, medium, etc..), you can edit these versions or add new ones in the settings.
.. note::
Don't try to use other resizing app like sorl-thumbnails or easy-thumbnails, they will not work with Image fields managed with Filebrowser.
""" |
def first_non_consecutive(arr: list) -> int:
''' This function returns the first element of an array that is not consecutive. '''
if len(arr) < 2:
return None
non_consecutive = []
for i in range(len(arr) - 1):
if arr[i+1] - arr[i] != 1:
non_consecutive.append(arr[i+1])
if len(non_consecutive) == 0:
return None
return int(''.join(map(str, non_consecutive[:1]))) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Jared
"""
# LATTICE VARIATION
lattice_mul = 20 #how many lattice variations to perform
lattice_variation_percent = 10
keep_aspect = False
# COMPOSITION VARIATION
# upper limit to sim num
lattice_comp_num = 500 #how many crystals to generate (random mixing)
lattice_init = [11.7, 5.4, 11.7]
#lattice_init = [12.5, 6.19, 12.5]
# ATOMIC VARIATION
fnum = 20 # how many atomic randomizations for a given crystal
atomic_position_variation_percent = 3
resolution = [1, 1, 2] #cannot change to [4, 4, 12] due to itertools overflow
# possible elements
# Asite = ['Rb', 'Cs', 'K', 'Na']
# Bsite = ['Sn', 'Ge']
# Xsite = ['Cl', 'Br', 'I']
#test compound trend
Asite = ['Cs', 'Rb', 'K', 'Na']
Bsite = ['Sn', 'Ge']
Xsite = ['I', 'Cl', 'Br']
#fname = 'builderOutput.csv'
#path = './bin/'
|
try:
print('enter try statement')
raise Exception()
print('exit try statement')
except Exception as inst:
print(inst.__class__.__name__)
|
def solution(M, A):
# write your code in Python 3.6
seen = [0] * (M + 1)
count = 0
i,j = 0,0
while(i < len(A) and j < len(A)):
if seen[A[j]]:
seen[A[i]] = 0
i += 1
else:
seen[A[j]] = 1
count += j - i + 1
j += 1
if count > 1e9:
return int(1e9)
return count |
# Time: O(n)
# Space: O(1)
# 978
# A subarray A[i], A[i+1], ..., A[j] of A is said to be turbulent if and only if:
# - For i <= k < j, A[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even;
# - OR, for i <= k < j, A[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is odd.
# That is, the subarray is turbulent if the comparison sign flips between each adjacent
# pair of elements in the subarray.
#
# Return the length of a maximum size turbulent subarray of A.
#
# Example 1:
# Input: [9,4,2,10,7,8,8,1,9]
# Output: 5
# Explanation: (A[1] > A[2] < A[3] > A[4] < A[5])
class Solution(object):
# Solution: sliding window
# If we are at the end of a window (last elements OR it stopped alternating), then we
# record the length of that window as our candidate answer, and set the start of a new window.
def maxTurbulenceSize(self, A):
"""
:type A: List[int]
:rtype: int
"""
ans = 1
start = 0
for i in xrange(1, len(A)):
c = cmp(A[i-1], A[i])
if c == 0:
start = i
elif i == len(A)-1 or c * cmp(A[i], A[i+1]) != -1:
ans = max(ans, i-start+1)
start = i
return ans
# Dynamic programming. Time O(n), Space O(n). Many values stored in dp array are not needed.
# E.g up/down values followed by a comma is not useful.
# A = [9, 4,2,10,7,8,8,1,9]
# up= 1 1 1,3 1,5 1 1,3
# down= 1, 2 2 1, 4 1,1,2 1,
def maxTurbulenceSize_dp(self, A):
N = len(A)
up, down, ans = [1]*N, [1]*N, 1
for i in xrange(1, len(A)):
if A[i] > A[i-1]:
up[i] = down[i-1] + 1
elif A[i] < A[i-1]:
down[i] = up[i-1] + 1
ans = max(ans, up[i], down[i])
return ans
print(Solution().maxTurbulenceSize([1,1,1,1,1])) |
# 类装饰器,使用类装饰已有函数
class MyDecorator(object):
def __init__(self, func):
self.__func = func
# 实现__call__方法,让实例对象变为像函数一样的可调用对象
def __call__(self, *args, **kwds):
# 对已有函数进行封装
print("课已经讲完了")
self.__func()
@MyDecorator # MyDecorator => show = MyDecorator(show)
def show():
print("可以放学了!")
# 执行show 就等于执行MyDecorator创建的实例对象
show() |
sql_1 = """INSERT INTO `pt_exam`.`user_order` (`id`, `exam_id`, `user_id`, `order_number`, `pre_pay_number`, `entry_fee`, `actual_pay_fee`, `status`, `pay_url`, `pay_time`, `create_time`) VALUES (NULL, {exam_id}, {user_id}, 'zsyl20210811103413909170a3{user_id}{exam_id}', NULL, 1, 1, 1, 'weixin://wxpay/bizpayurl?pr=hDqke8nzz', '2021-08-11 12:00:00.000000', '2021-08-11 12:00:00');"""
sql_2 = """INSERT INTO `pt_exam`.`user_exam` (`id`, `exam_id`, `user_id`, `room_id`, `step`, `id_photo_url`, `ticket_no`, `ticket_url`, `level`, `flag`, `certificate_url`, `certificate_no`, `create_time`, `resit_flag`) VALUES (null, {exam_id}, {user_id}, NULL, 1, NULL, NULL, NULL, NULL, 0, NULL, NULL, '2021-08-11 12:00:00', 0);"""
# 配置
exam_id = 34
# 初级认证的人
# user_ids = [873, 1152, 1153, 1154, 1155, 1156, 1157, 1159, 264, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168, 1169, 1170, 1171, 1172, 1173, 1174, 1175, 1176, 1177, 1178, 535, 1180, 925, 1182, 1183, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 543, 297, 1194, 171, 1196, 1197, 1198, 1201, 1202, 1203, 1205, 1206, 1181, 1207, 1208, 574, 459, 1160, 849, 478, 873, 1005, 622, 249, 762, 252, 1149, 1150, 1151]
# 中级认证
# user_ids = [480, 292, 581, 305, 819, 189, 537, 475, 348, 349, 1196, 1183, 1005]
user_ids = [1211]
# 陈默 1196
# 周源苠 1183
# 廖敏 1208
# 刁青青 1005
# 冯丹 1207
user_ids = list(set(user_ids))
# user_order表
for user_id in user_ids:
print(sql_1.format(exam_id=exam_id, user_id=user_id))
# user_exam表
for user_id in user_ids:
print(sql_2.format(exam_id=exam_id, user_id=user_id))
# print(user_ids)
|
class TitleItem:
def __init__(self, title='', title_type='', genre='', directors='', actors='', run_time='', release_date='',
cover_url=''):
"""
:param title: String. The title of the movie/tv show.
:param title_type: String. Options: feature or tv_series.
:param genre: String. A list of genres the title belongs to.
:param directors: String. A list of director(s).
:param actors: String. A list of actor(s).
:param run_time: String. The runtime of the movie.
:param release_date: String. The release date of the movie.
:param cover_url: String. The URL of the media cover.
"""
self.title = title
self.title_type = title_type
self.genre = genre
self.directors = directors
self.actors = actors
self.run_time = run_time
self.release_date = release_date
self.cover_url = cover_url
|
class Earth:
"""
Class used to represent Earth. Values are defined using EGM96 geopotential
model. Constant naming convention is intentionally not used since the
values defined here may be updated in the future by introducing other
geopotential models
"""
mu = 3.986004415e5 #km^3/s^2
equatorial_radius = 6378.1363 #km |
#
# PySNMP MIB module Wellfleet-DS1-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-DS1-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:39:54 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)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
iso, Gauge32, Counter64, MibIdentifier, Unsigned32, Integer32, ModuleIdentity, NotificationType, ObjectIdentity, Counter32, mgmt, MibScalar, MibTable, MibTableRow, MibTableColumn, mib_2, NotificationType, IpAddress, Bits, enterprises, Opaque, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Gauge32", "Counter64", "MibIdentifier", "Unsigned32", "Integer32", "ModuleIdentity", "NotificationType", "ObjectIdentity", "Counter32", "mgmt", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "mib-2", "NotificationType", "IpAddress", "Bits", "enterprises", "Opaque", "TimeTicks")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
wfDs1Group, = mibBuilder.importSymbols("Wellfleet-COMMON-MIB", "wfDs1Group")
wfDs1Config = MibTable((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1), )
if mibBuilder.loadTexts: wfDs1Config.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1Config.setDescription('The DS1 Configuration table')
wfDs1ConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1), ).setIndexNames((0, "Wellfleet-DS1-MIB", "wfDs1LineIndex"))
if mibBuilder.loadTexts: wfDs1ConfigEntry.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1ConfigEntry.setDescription('per circuit DS1 configuration objects; wfDs1LineIndex corresponds to Wellfleet circuit number')
wfDs1LineIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024))).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1LineIndex.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1LineIndex.setDescription('this corresponds to the Wellfleet circuit number')
wfDs1TimeElapsed = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1TimeElapsed.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1TimeElapsed.setDescription('1..900 seconds within the current 15-minute interval')
wfDs1ValidIntervals = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1ValidIntervals.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1ValidIntervals.setDescription('0..96 previous intervals that valid data were collected. This is 96 unless the CSU device was brought on line within the last 24 hours.')
wfDs1LineType = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(4))).clone(namedValues=NamedValues(("ds1ansi-esf", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1LineType.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1LineType.setDescription('the variety of DS1 implementing this circuit')
wfDs1ZeroCoding = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2, 5))).clone(namedValues=NamedValues(("ds1b8zs", 2), ("ds1zbtsi", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1ZeroCoding.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1ZeroCoding.setDescription('the variety of Zero Code Suppression used on the link')
wfDs1SendCode = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2))).clone(namedValues=NamedValues(("ds1sendnocode", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1SendCode.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1SendCode.setDescription('the type of code being sent across the DS1 circuit by the CSU')
wfDs1CircuitIdentifier = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 7), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1CircuitIdentifier.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1CircuitIdentifier.setDescription("the transmission vendor's circuit identifier")
wfDs1LoopbackConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("ds1noloop", 1), ("ds1mgrpayloadloop", 2), ("ds1mgrlineloop", 3), ("ds1netreqpayloadloop", 4), ("ds1netreqlineloop", 5), ("ds1otherloop", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1LoopbackConfig.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1LoopbackConfig.setDescription('the loopback state of the CSU')
wfDs1LineStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 4, 8, 16, 32))).clone(namedValues=NamedValues(("ds1noalarm", 1), ("ds1farendalarm", 2), ("ds1alarmindicationsignal", 4), ("ds1lossofframe", 8), ("ds1lossofsignal", 16), ("ds1loopbackstate", 32)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1LineStatus.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1LineStatus.setDescription('the state of the DS1 line')
wfDs1Current = MibTable((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2), )
if mibBuilder.loadTexts: wfDs1Current.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1Current.setDescription('The DS1 Current table')
wfDs1CurrentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1), ).setIndexNames((0, "Wellfleet-DS1-MIB", "wfDs1CurrentIndex"))
if mibBuilder.loadTexts: wfDs1CurrentEntry.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1CurrentEntry.setDescription('per circuit DS1 current objects - wfDs1CurrentIndex corresponds to Wellfleet circuit number')
wfDs1CurrentIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024))).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1CurrentIndex.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1CurrentIndex.setDescription('this corresponds to the Wellfleet circuit number')
wfDs1CurrentESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1CurrentESs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1CurrentESs.setDescription('the count of errored seconds in the current interval')
wfDs1CurrentSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1CurrentSESs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1CurrentSESs.setDescription('the count of severely errored seconds in the current interval')
wfDs1CurrentSEFs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1CurrentSEFs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1CurrentSEFs.setDescription('the count of severely errored framing seconds in the current interval')
wfDs1CurrentUASs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1CurrentUASs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1CurrentUASs.setDescription('the number of unavailable seconds in the current interval')
wfDs1CurrentBPVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1CurrentBPVs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1CurrentBPVs.setDescription('the count of bipolar violations in the current interval')
wfDs1CurrentCVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1CurrentCVs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1CurrentCVs.setDescription('the count of code violation error events in the current interval')
wfDs1Interval = MibTable((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3), )
if mibBuilder.loadTexts: wfDs1Interval.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1Interval.setDescription('The DS1 Interval table')
wfDs1IntervalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1), ).setIndexNames((0, "Wellfleet-DS1-MIB", "wfDs1IntervalIndex"), (0, "Wellfleet-DS1-MIB", "wfDs1IntervalNumber"))
if mibBuilder.loadTexts: wfDs1IntervalEntry.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1IntervalEntry.setDescription('per circuit DS1 interval objects - wfDs1IntervalIndex corresponds to Wellfleet circuit number, wfDs1IntervalNumber is the numbered previous 15-minute interval')
wfDs1IntervalIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024))).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1IntervalIndex.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1IntervalIndex.setDescription('this corresponds to the Wellfleet circuit number')
wfDs1IntervalNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 96))).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1IntervalNumber.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1IntervalNumber.setDescription('1..96 where 1 is the most recent 15-minute interval and 96 is the least')
wfDs1IntervalESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 3), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1IntervalESs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1IntervalESs.setDescription('the count of errored seconds in the specified interval')
wfDs1IntervalSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 4), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1IntervalSESs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1IntervalSESs.setDescription('the count of severely errored seconds in the specified interval')
wfDs1IntervalSEFs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 5), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1IntervalSEFs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1IntervalSEFs.setDescription('the count of severely errored framing seconds in the specified interval')
wfDs1IntervalUASs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 6), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1IntervalUASs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1IntervalUASs.setDescription('the number of unavailable seconds in the specified interval')
wfDs1IntervalBPVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 7), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1IntervalBPVs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1IntervalBPVs.setDescription('the count of bipolar violations in the specified interval')
wfDs1IntervalCVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 8), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1IntervalCVs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1IntervalCVs.setDescription('the count of code violation error events in the specified interval')
wfDs1Total = MibTable((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4), )
if mibBuilder.loadTexts: wfDs1Total.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1Total.setDescription('The DS1 Total table')
wfDs1TotalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1), ).setIndexNames((0, "Wellfleet-DS1-MIB", "wfDs1TotalIndex"))
if mibBuilder.loadTexts: wfDs1TotalEntry.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1TotalEntry.setDescription('per circuit DS1 total objects - wfDs1TotalIndex corresponds to Wellfleet circuit number')
wfDs1TotalIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024))).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1TotalIndex.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1TotalIndex.setDescription('this corresponds to the Wellfleet circuit number')
wfDs1TotalESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 2), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1TotalESs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1TotalESs.setDescription('total count of errored seconds')
wfDs1TotalSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 3), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1TotalSESs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1TotalSESs.setDescription('total count of severely errored seconds')
wfDs1TotalSEFs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 4), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1TotalSEFs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1TotalSEFs.setDescription('total count of severely errored framing seconds')
wfDs1TotalUASs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 5), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1TotalUASs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1TotalUASs.setDescription('total number of unavailable seconds')
wfDs1TotalBPVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 6), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1TotalBPVs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1TotalBPVs.setDescription('total count of bipolar violations')
wfDs1TotalCVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 7), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1TotalCVs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1TotalCVs.setDescription('total count of code violation error events')
wfDs1FeCurrent = MibTable((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5), )
if mibBuilder.loadTexts: wfDs1FeCurrent.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeCurrent.setDescription('The DS1 Far End Current table')
wfDs1FeCurrentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1), ).setIndexNames((0, "Wellfleet-DS1-MIB", "wfDs1FeCurrentIndex"))
if mibBuilder.loadTexts: wfDs1FeCurrentEntry.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeCurrentEntry.setDescription('per circuit DS1 far end current objects wfDs1CurrentIndex corresponds to Wellfleet circuit number')
wfDs1FeCurrentIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024))).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeCurrentIndex.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeCurrentIndex.setDescription('this corresponds to the Wellfleet circuit number')
wfDs1FeCurrentESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeCurrentESs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeCurrentESs.setDescription('the count of errored seconds in the current interval')
wfDs1FeCurrentSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeCurrentSESs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeCurrentSESs.setDescription('the count of severely errored seconds in the current interval')
wfDs1FeCurrentSEFs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeCurrentSEFs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeCurrentSEFs.setDescription('the count of severely errored framing seconds in the current interval')
wfDs1FeCurrentBPVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeCurrentBPVs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeCurrentBPVs.setDescription('the count of bipolar violations in the current interval')
wfDs1FeCurrentCVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeCurrentCVs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeCurrentCVs.setDescription('the count of code violation error events in the current interval')
wfDs1FeInterval = MibTable((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6), )
if mibBuilder.loadTexts: wfDs1FeInterval.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeInterval.setDescription('The DS1 Far End Interval table')
wfDs1FeIntervalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1), ).setIndexNames((0, "Wellfleet-DS1-MIB", "wfDs1FeIntervalIndex"), (0, "Wellfleet-DS1-MIB", "wfDs1FeIntervalNumber"))
if mibBuilder.loadTexts: wfDs1FeIntervalEntry.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeIntervalEntry.setDescription('per circuit DS1 far end interval objects - wfDs1FeIntervalIndex corresponds to Wellfleet circuit number, wfDs1FeIntervalNumber is the numbered previous 15-minute interval')
wfDs1FeIntervalIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024))).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeIntervalIndex.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeIntervalIndex.setDescription('this corresponds to the Wellfleet circuit number')
wfDs1FeIntervalNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 96))).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeIntervalNumber.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeIntervalNumber.setDescription('1..96 where 1 is the most recent 15-minute interval and 96 is the least')
wfDs1FeIntervalESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 3), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeIntervalESs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeIntervalESs.setDescription('the count of errored seconds in the specified interval')
wfDs1FeIntervalSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 4), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeIntervalSESs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeIntervalSESs.setDescription('the count of severely errored seconds in the specified interval')
wfDs1FeIntervalSEFs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 5), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeIntervalSEFs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeIntervalSEFs.setDescription('the count of severely errored framing seconds in the specified interval')
wfDs1FeIntervalBPVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 6), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeIntervalBPVs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeIntervalBPVs.setDescription('the count of bipolar violations in the specified interval')
wfDs1FeIntervalCVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 7), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeIntervalCVs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeIntervalCVs.setDescription('the count of code violation error events in the specified interval')
wfDs1FeTotal = MibTable((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7), )
if mibBuilder.loadTexts: wfDs1FeTotal.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeTotal.setDescription('The DS1 Far End Total table')
wfDs1FeTotalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1), ).setIndexNames((0, "Wellfleet-DS1-MIB", "wfDs1FeTotalIndex"))
if mibBuilder.loadTexts: wfDs1FeTotalEntry.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeTotalEntry.setDescription('per circuit DS1 far end total objects - wfDs1FeTotalIndex corresponds to Wellfleet circuit number')
wfDs1FeTotalIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024))).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeTotalIndex.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeTotalIndex.setDescription('this corresponds to the Wellfleet circuit number')
wfDs1FeTotalESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1, 2), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeTotalESs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeTotalESs.setDescription('total count of errored seconds')
wfDs1FeTotalSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1, 3), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeTotalSESs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeTotalSESs.setDescription('total count of severely errored seconds')
wfDs1FeTotalSEFs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1, 4), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeTotalSEFs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeTotalSEFs.setDescription('total count of severely errored framing seconds')
wfDs1FeTotalBPVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1, 5), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeTotalBPVs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeTotalBPVs.setDescription('total count of bipolar violations')
wfDs1FeTotalCVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1, 6), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: wfDs1FeTotalCVs.setStatus('mandatory')
if mibBuilder.loadTexts: wfDs1FeTotalCVs.setDescription('total count of code violation error events')
mibBuilder.exportSymbols("Wellfleet-DS1-MIB", wfDs1FeIntervalNumber=wfDs1FeIntervalNumber, wfDs1Config=wfDs1Config, wfDs1CurrentIndex=wfDs1CurrentIndex, wfDs1TotalSESs=wfDs1TotalSESs, wfDs1FeIntervalIndex=wfDs1FeIntervalIndex, wfDs1IntervalUASs=wfDs1IntervalUASs, wfDs1FeTotalIndex=wfDs1FeTotalIndex, wfDs1FeTotalEntry=wfDs1FeTotalEntry, wfDs1IntervalESs=wfDs1IntervalESs, wfDs1CurrentEntry=wfDs1CurrentEntry, wfDs1CurrentCVs=wfDs1CurrentCVs, wfDs1FeTotalESs=wfDs1FeTotalESs, wfDs1LineStatus=wfDs1LineStatus, wfDs1CurrentBPVs=wfDs1CurrentBPVs, wfDs1FeIntervalSEFs=wfDs1FeIntervalSEFs, wfDs1TotalEntry=wfDs1TotalEntry, wfDs1ValidIntervals=wfDs1ValidIntervals, wfDs1IntervalCVs=wfDs1IntervalCVs, wfDs1FeCurrentEntry=wfDs1FeCurrentEntry, wfDs1IntervalNumber=wfDs1IntervalNumber, wfDs1Interval=wfDs1Interval, wfDs1TotalCVs=wfDs1TotalCVs, wfDs1FeTotal=wfDs1FeTotal, wfDs1CurrentSEFs=wfDs1CurrentSEFs, wfDs1TotalSEFs=wfDs1TotalSEFs, wfDs1CurrentESs=wfDs1CurrentESs, wfDs1LineIndex=wfDs1LineIndex, wfDs1SendCode=wfDs1SendCode, wfDs1IntervalIndex=wfDs1IntervalIndex, wfDs1ZeroCoding=wfDs1ZeroCoding, wfDs1IntervalSESs=wfDs1IntervalSESs, wfDs1CircuitIdentifier=wfDs1CircuitIdentifier, wfDs1FeTotalCVs=wfDs1FeTotalCVs, wfDs1Total=wfDs1Total, wfDs1FeCurrentESs=wfDs1FeCurrentESs, wfDs1FeInterval=wfDs1FeInterval, wfDs1FeTotalSESs=wfDs1FeTotalSESs, wfDs1FeCurrent=wfDs1FeCurrent, wfDs1FeCurrentBPVs=wfDs1FeCurrentBPVs, wfDs1FeTotalSEFs=wfDs1FeTotalSEFs, wfDs1CurrentSESs=wfDs1CurrentSESs, wfDs1IntervalBPVs=wfDs1IntervalBPVs, wfDs1FeIntervalSESs=wfDs1FeIntervalSESs, wfDs1FeIntervalBPVs=wfDs1FeIntervalBPVs, wfDs1FeIntervalCVs=wfDs1FeIntervalCVs, wfDs1FeIntervalEntry=wfDs1FeIntervalEntry, wfDs1ConfigEntry=wfDs1ConfigEntry, wfDs1TimeElapsed=wfDs1TimeElapsed, wfDs1FeTotalBPVs=wfDs1FeTotalBPVs, wfDs1FeCurrentIndex=wfDs1FeCurrentIndex, wfDs1Current=wfDs1Current, wfDs1TotalESs=wfDs1TotalESs, wfDs1CurrentUASs=wfDs1CurrentUASs, wfDs1FeIntervalESs=wfDs1FeIntervalESs, wfDs1FeCurrentSESs=wfDs1FeCurrentSESs, wfDs1LineType=wfDs1LineType, wfDs1TotalUASs=wfDs1TotalUASs, wfDs1TotalIndex=wfDs1TotalIndex, wfDs1IntervalSEFs=wfDs1IntervalSEFs, wfDs1IntervalEntry=wfDs1IntervalEntry, wfDs1FeCurrentSEFs=wfDs1FeCurrentSEFs, wfDs1FeCurrentCVs=wfDs1FeCurrentCVs, wfDs1LoopbackConfig=wfDs1LoopbackConfig, wfDs1TotalBPVs=wfDs1TotalBPVs)
|
#import numpy as np
"""
#moving avg
#Parameters
array of ts value
#Returns moving avg
"""
#def moving_average(series, n):
# return np.average(series[-n:])
|
# *args - arguments - it returns tuple
# **kwargs - keyword arguments - it returns dictionary
def myfunc(*args):
print(args)
myfunc(1,2,3,4,5,6,7,8,9,0)
def myfunc1(**kwargs):
print(kwargs)
if 'fruit' in kwargs:
print('my fruit of choice is {}'.format(kwargs['fruit']))
else:
print('I did not find any fruit here')
myfunc1(fruit='apple',veggie='lettuce')
|
"""
Write a program that reads a value in meters and displays it converted to centimeters and millimeters
"""
m = float(input('Uma distância em metros: '))
"""Kilometre --> Divide the length value by 1000"""
km = m / 1000
"""Hectometre --> Divide the length value by 100"""
hm = m / 100
"""Decametre --> Divide the length value by 10"""
dam = m / 10
"""Decimetre --> Multiply the length value by 10"""
dm = m * 10
"""Centimetre --> Multiply the length value by 100"""
cm = m * 100
"""Millimetre --> Multiply the length value by 1000"""
mm = m * 1000
print('A medida de {}m corresponde a\n{}km\n{}hm\n{}dam\n{}dm\n{}cm\n{}mm'.format(m, km, hm, dam, dm, cm, mm))
|
class AppConstants:
ADDRESS = {
"서울": [
"강남구",
"강동구",
"강북구",
"강서구",
"관악구",
"광진구",
"구로구",
"금천구",
"노원구",
"도봉구",
"동대문구",
"동작구",
"마포구",
"서대문구",
"서초구",
"성동구",
"성북구",
"송파구",
"양천구",
"영등포구",
"용산구",
"은평구",
"종로구",
"중구",
"중랑구",
],
"부산": [
"강서구",
"금정구",
"기장군",
"남구",
"동구",
"동래구",
"부산진구",
"북구",
"사상구",
"사하구",
"서구",
"수영구",
"연제구",
"영도구",
"중구",
"해운대구",
],
"대구": ["남구", "달서구", "달성군", "동구", "북구", "서구", "수성구", "중구"],
"인천": ["강화군", "계양구", "남동구", "동구", "미추홀구", "부평구", "서구", "연수구", "옹진군", "중구"],
"광주": ["광산구", "남구", "동구", "북구", "서구"],
"대전": ["대덕구", "동구", "서구", "유성구", "중구"],
"울산": ["남구", "동구", "북구", "울주군", "중구"],
"세종": [],
"경기": [
"가평군",
"고양시 덕양구",
"고양시 일산동구",
"고양시 일산서구",
"과천시",
"광명시",
"광주시",
"구리시",
"군포시",
"김포시",
"남양주시",
"동두천시",
"부천시",
"성남시 분당구",
"성남시 수정구",
"성남시 중원구",
"수원시 권선구",
"수원시 영통구",
"수원시 장안구",
"수원시 팔달구",
"시흥시",
"안산시 단원구",
"안산시 상록구",
"안성시",
"안양시 동안구",
"안양시 만안구",
"양주시",
"양평군",
"여주시",
"연천군",
"오산시",
"용인시 기흥구",
"용인시 수지구",
"용인시 처인구",
"의왕시",
"의정부시",
"이천시",
"파주시",
"평택시",
"포천시",
"하남시",
"화성시",
],
"강원": [
"강릉시",
"고성군",
"동해시",
"삼척시",
"속초시",
"양구군",
"양양군",
"영월군",
"원주시",
"인제군",
"정선군",
"철원군",
"춘천시",
"태백시",
"평창군",
"홍천군",
"화천군",
"횡성군",
],
"충북": [
"괴산군",
"단양군",
"보은군",
"영동군",
"옥천군",
"음성군",
"제천시",
"증평군",
"진천군",
"청주시 상당구",
"청주시 서원구",
"청주시 청원구",
"청주시 흥덕구",
"충주시",
],
"충남": [
"계룡시",
"공주시",
"금산군",
"논산시",
"당진시",
"보령시",
"부여군",
"서산시",
"서천군",
"아산시",
"예산군",
"천안시 동남구",
"천안시 서북구",
"청양군",
"태안군",
"홍성군",
],
"전북": [
"고창군",
"군산시",
"김제시",
"남원시",
"무주군",
"부안군",
"순창군",
"완주군",
"익산시",
"임실군",
"장수군",
"전주시 덕진구",
"전주시 완산구",
"정읍시",
"진안군",
],
"전남": [
"강진군",
"고흥군",
"곡성군",
"광양시",
"구례군",
"나주시",
"담양군",
"목포시",
"무안군",
"보성군",
"순천시",
"신안군",
"여수시",
"영광군",
"영암군",
"완도군",
"장성군",
"장흥군",
"진도군",
"함평군",
"해남군",
"화순군",
],
"경북": [
"경산시",
"경주시",
"고령군",
"구미시",
"군위군",
"김천시",
"문경시",
"봉화군",
"상주시",
"성주군",
"안동시",
"영덕군",
"영양군",
"영주시",
"영천시",
"예천군",
"울릉군",
"울진군",
"의성군",
"청도군",
"청송군",
"칠곡군",
"포항시 남구",
"포항시 북구",
],
"경남": [
"거제시",
"거창군",
"고성군",
"김해시",
"남해군",
"밀양시",
"사천시",
"산청군",
"양산시",
"의령군",
"진주시",
"창녕군",
"창원시 마산합포구",
"창원시 마산회원구",
"창원시 성산구",
"창원시 의창구",
"창원시 진해구",
"통영시",
"하동군",
"함안군",
"함양군",
"합천군",
],
"제주": ["서귀포시", "제주시"],
}
|
def test_get_topics(client):
response = client.get("/topics/")
contents = response.get_json()
assert contents["status"] == "OK"
assert type(contents["payload"]) is dict
assert type(contents["payload"]["topics"]) is list
assert type(contents["payload"]["subtopics"]) is dict
assert response.status_code == 200
|
"""
Find an efficient algorithm to find the smallest distance
(measured in number of words) between any two given words in a string.
For example, given words "hello", and "world" and a text content of
"dog cat hello cat dog dog hello cat world", return 1 because there's only one word "cat" in between the two words.
"""
def find_distance(string:str, key_word_1, key_word_2):
"""
This works as follows:
eg. key_word_1 = hello; key_word_1 = world
"dog cat hello cat dog dog hello cat world"
-------------------------------------------------------------------------------
count| 0 0 0 1 2 3 0 1 0
ending_key_word | None None world world world world world world hello
min_count | inf inf inf inf inf inf inf inf 1
Args:
string:
key_word_1:
key_word_2:
Returns:
"""
min_count = float('inf')
count = 0
ending_key_word = None # initially we don't know which keyword we are looking to end the count
for word in string.split():
if ending_key_word is None and word == key_word_1: # check if we should start counting
ending_key_word = key_word_2 # look for key_word_2 to stop count
elif ending_key_word is None and word == key_word_2:
ending_key_word = key_word_1 # look for key_word_1 to stop the count
elif ending_key_word == word: # when the ending keyword has been found
min_count = min(count, min_count) # store the min count
# now we if the the ending_key_word was:
# a - key_word_1 we will now set ending_key_word=key_word_2
# b - key_word_2 we will now set ending_key_word=key_word_1
ending_key_word = key_word_2 if key_word_1 == word else key_word_1
count = 0 # reset count
elif word == key_word_1 or word == key_word_2:
count = 0 # reset count found a word that is possibly closer
elif ending_key_word:
count += 1 # while we are looking for end_key_word keep counting words
return min_count
if __name__ == '__main__':
test_string = "dog cat hello cat dog dog hello cat world"
print(find_distance(test_string, 'hello', 'world')) # ans 1
test_string = "dog cat hello cat dog dog dog cat world cat world dog dog hello"
print(find_distance(test_string, 'hello', 'world')) # ans 2 |
# https://practice.geeksforgeeks.org/problems/number-of-palindromic-paths-in-a-matrix0819/1#
# at each node recursively call itself and at bottom,left cornet determine it its a palindrome
class Solution:
def rec(self, matrix, it, jt, ib, jb, cache):
if it > ib or jt > jb:
cache[(it, jt, ib, jb)] = 0
return 0
if matrix[it][jt] != matrix[ib][jb]:
cache[(it, jt, ib, jb)] = 0
return 0
if abs(it - ib) + abs(jt - jb) < 2:
cache[(it, jt, ib, jb)] = 1
return 1
coun1, count2, count3, count4 = 0,0,0,0
if cache.__contains__((it+1, jt, ib-1, jb)):
count1 = cache[(it+1, jt, ib-1, jb)]
else:
count1 = self.rec(matrix, it+1, jt, ib-1, jb, cache)
if cache.__contains__((it+1, jt, ib, jb-1)):
count2 = cache[(it+1, jt, ib, jb-1)]
else:
count2 = self.rec(matrix, it+1, jt, ib, jb-1, cache)
if cache.__contains__((it, jt+1, ib-1, jb)):
count3 = cache[(it, jt+1, ib-1, jb)]
else:
count3 = self.rec(matrix, it, jt+1, ib-1, jb, cache)
if cache.__contains__((it, jt+1, ib, jb-1)):
count4 = cache[(it, jt+1, ib, jb-1)]
else:
count4 = self.rec(matrix, it, jt+1, ib, jb-1, cache)
count = count1+count2+count3+count4
cache[(it, jt, ib, jb)] = count
return count
def countOfPalindromicPaths(self, matrix):
return self.rec(matrix, 0, 0, len(matrix)-1, len(matrix[0])-1, {})
if __name__ == '__main__':
T = int(input())
for i in range(T):
n, m = input().split()
n = int(n);
m = int(m);
matrix = []
for _ in range(n):
cur = input()
temp = []
for __ in cur:
temp.append(__)
matrix.append(temp)
obj = Solution()
ans = obj.countOfPalindromicPaths(matrix)
print(ans)
|
# Numbers 0 to 10
print(list(range(0,11)))
print()
# Even numbers 0 to 10
print(list(range(0,11,2)))
print()
# Odd numbers 0 to 10
print(list(range(1,11,2)))
print()
# Numbers 20 to 10
print(list(range(20,9,-1)))
print()
# Numbers 45 to 75 divisable by 5
print(list(range(45, 76, 5)))
|
# https://leetcode.com/problems/monotonic-array/description/
#
# algorithms
# Medium (42.6%)
# Total Accepted: 4.8k
# Total Submissions: 11.2k
# beats 77.52% of python submissions
class Solution(object):
def largestOverlap(self, A, B):
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: int
"""
length = len(A)
A_1_arr, B_1_arr = [], []
for i in xrange(length):
for j in xrange(length):
if A[i][j] == 1:
A_1_arr.append((i, j))
if B[i][j] == 1:
B_1_arr.append((i, j))
res = 0
for i in xrange(length):
for j in xrange(length):
cnt_sum_A, cnt_sum_B = 0, 0
for x, y in A_1_arr:
if x + i < length and y + j < length and B[x + i][y + j] == 1:
cnt_sum_A += 1
for x, y in B_1_arr:
if x + i < length and y + j < length and A[x + i][y + j] == 1:
cnt_sum_B += 1
res = max(res, cnt_sum_A, cnt_sum_B)
return res
|
term_mappings = {
'Cell': 'csvw:Cell',
'Column': 'csvw:Column',
'Datatype': 'csvw:Datatype',
'Dialect': 'csvw:Dialect',
'Direction': 'csvw:Direction',
'ForeignKey': 'csvw:ForeignKey',
'JSON': 'csvw:JSON',
'NCName': 'xsd:NCName',
'NMTOKEN': 'xsd:NMTOKEN',
'Name': 'xsd:Name',
'NumericFormat': 'csvw:NumericFormat',
'QName': 'xsd:QName',
'Row': 'csvw:Row',
'Schema': 'csvw:Schema',
'Table': 'csvw:Table',
'TableGroup': 'csvw:TableGroup',
'TableReference': 'csvw:TableReference',
'Transformation': 'csvw:Transformation',
'aboutUrl': 'csvw:aboutUrl',
'any': 'xsd:anyAtomicType',
'anyAtomicType': 'xsd:anyAtomicType',
'anyURI': 'xsd:anyURI',
'as': 'https://www.w3.org/ns/activitystreams#',
'base': 'csvw:base',
'base64Binary': 'xsd:base64Binary',
'binary': 'xsd:base64Binary',
'boolean': 'xsd:boolean',
'byte': 'xsd:byte',
'cc': 'http://creativecommons.org/ns#',
'columnReference': 'csvw:columnReference',
'columns': 'csvw:column',
'commentPrefix': 'csvw:commentPrefix',
'csvw': 'http://www.w3.org/ns/csvw#',
'ctag': 'http://commontag.org/ns#',
'datatype': 'csvw:datatype',
'date': 'xsd:date',
'dateTime': 'xsd:dateTime',
'dateTimeStamp': 'xsd:dateTimeStamp',
'datetime': 'xsd:dateTime',
'dayTimeDuration': 'xsd:dayTimeDuration',
'dc': 'http://purl.org/dc/terms/',
'dc11': 'http://purl.org/dc/elements/1.1/',
'dcat': 'http://www.w3.org/ns/dcat#',
'dcterms': 'http://purl.org/dc/terms/',
'dctypes': 'http://purl.org/dc/dcmitype/',
'decimal': 'xsd:decimal',
'decimalChar': 'csvw:decimalChar',
'default': 'csvw:default',
'delimiter': 'csvw:delimiter',
'describedby': 'wrds:describedby',
'describes': 'csvw:describes',
'dialect': 'csvw:dialect',
'double': 'xsd:double',
'doubleQuote': 'csvw:doubleQuote',
'dqv': 'http://www.w3.org/ns/dqv#',
'duration': 'xsd:duration',
'duv': 'https://www.w3.org/TR/vocab-duv#',
'encoding': 'csvw:encoding',
'float': 'xsd:float',
'foaf': 'http://xmlns.com/foaf/0.1/',
'foreignKeys': 'csvw:foreignKey',
'format': 'csvw:format',
'gDay': 'xsd:gDay',
'gMonth': 'xsd:gMonth',
'gMonthDay': 'xsd:gMonthDay',
'gYear': 'xsd:gYear',
'gYearMonth': 'xsd:gYearMonth',
'gr': 'http://purl.org/goodrelations/v1#',
'grddl': 'http://www.w3.org/2003/g/data-view#',
'groupChar': 'csvw:groupChar',
'header': 'csvw:header',
'headerRowCount': 'csvw:headerRowCount',
'hexBinary': 'xsd:hexBinary',
'html': 'rdf:HTML',
'ical': 'http://www.w3.org/2002/12/cal/icaltzd#',
'int': 'xsd:int',
'integer': 'xsd:integer',
'json': 'csvw:JSON',
'lang': 'csvw:lang',
'language': 'xsd:language',
'ldp': 'http://www.w3.org/ns/ldp#',
'length': 'csvw:length',
'license': 'xhv:license',
'lineTerminators': 'csvw:lineTerminators',
'long': 'xsd:long',
'ma': 'http://www.w3.org/ns/ma-ont#',
'maxExclusive': 'csvw:maxExclusive',
'maxInclusive': 'csvw:maxInclusive',
'maxLength': 'csvw:maxLength',
'maximum': 'csvw:maxInclusive',
'minExclusive': 'csvw:minExclusive',
'minInclusive': 'csvw:minInclusive',
'minLength': 'csvw:minLength',
'minimum': 'csvw:minInclusive',
'name': 'csvw:name',
'negativeInteger': 'xsd:negativeInteger',
'nonNegativeInteger': 'xsd:nonNegativeInteger',
'nonPositiveInteger': 'xsd:nonPositiveInteger',
'normalizedString': 'xsd:normalizedString',
'notes': 'csvw:note',
'null': 'csvw:null',
'number': 'xsd:double',
'oa': 'http://www.w3.org/ns/oa#',
'og': 'http://ogp.me/ns#',
'ordered': 'csvw:ordered',
'org': 'http://www.w3.org/ns/org#',
'owl': 'http://www.w3.org/2002/07/owl#',
'pattern': 'csvw:pattern',
'positiveInteger': 'xsd:positiveInteger',
'primaryKey': 'csvw:primaryKey',
'propertyUrl': 'csvw:propertyUrl',
'prov': 'http://www.w3.org/ns/prov#',
'qb': 'http://purl.org/linked-data/cube#',
'quoteChar': 'csvw:quoteChar',
'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'rdfa': 'http://www.w3.org/ns/rdfa#',
'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
'reference': 'csvw:reference',
'referencedRows': 'csvw:referencedRow',
'required': 'csvw:required',
'resource': 'csvw:resource',
'rev': 'http://purl.org/stuff/rev#',
'rif': 'http://www.w3.org/2007/rif#',
'role': 'xhv:role',
'row': 'csvw:row',
'rowTitles': 'csvw:rowTitle',
'rownum': 'csvw:rownum',
'rr': 'http://www.w3.org/ns/r2rml#',
'schema': 'http://schema.org/',
'schemaReference': 'csvw:schemaReference',
'scriptFormat': 'csvw:scriptFormat',
'sd': 'http://www.w3.org/ns/sparql-service-description#',
'separator': 'csvw:separator',
'short': 'xsd:short',
'sioc': 'http://rdfs.org/sioc/ns#',
'skipBlankRows': 'csvw:skipBlankRows',
'skipColumns': 'csvw:skipColumns',
'skipInitialSpace': 'csvw:skipInitialSpace',
'skipRows': 'csvw:skipRows',
'skos': 'http://www.w3.org/2004/02/skos/core#',
'skosxl': 'http://www.w3.org/2008/05/skos-xl#',
'source': 'csvw:source',
'string': 'xsd:string',
'suppressOutput': 'csvw:suppressOutput',
'tableDirection': 'csvw:tableDirection',
'tableSchema': 'csvw:tableSchema',
'tables': 'csvw:table',
'targetFormat': 'csvw:targetFormat',
'textDirection': 'csvw:textDirection',
'time': 'xsd:time',
'titles': 'csvw:title',
'token': 'xsd:token',
'transformations': 'csvw:transformations',
'trim': 'csvw:trim',
'unsignedByte': 'xsd:unsignedByte',
'unsignedInt': 'xsd:unsignedInt',
'unsignedLong': 'xsd:unsignedLong',
'unsignedShort': 'xsd:unsignedShort',
'uriTemplate': 'csvw:uriTemplate',
'url': 'csvw:url',
'v': 'http://rdf.data-vocabulary.org/#',
'valueUrl': 'csvw:valueUrl',
'vcard': 'http://www.w3.org/2006/vcard/ns#',
'virtual': 'csvw:virtual',
'void': 'http://rdfs.org/ns/void#',
'wdr': 'http://www.w3.org/2007/05/powder#',
'wrds': 'http://www.w3.org/2007/05/powder-s#',
'xhv': 'http://www.w3.org/1999/xhtml/vocab#',
'xml': 'rdf:XMLLiteral',
'xsd': 'http://www.w3.org/2001/XMLSchema#',
'yearMonthDuration': 'xsd:yearMonthDuration',
}
core_group_of_tables_annotations = ['id', 'notes', 'tables']
core_table_annotations = ['columns', 'tableDirection', 'foreignKeys', 'id', 'notes', 'rows', 'schema',
'suppressOutput', 'transformations', 'url']
core_column_annotations = ['aboutUrl', 'cells', 'datatype', 'default', 'lang', 'name', 'null', 'number', 'ordered',
'propertyUrl', 'required', 'separator', 'sourceNumber', 'suppressOutput', 'table',
'textDirection', 'titles', 'valueUrl', 'virtual']
core_row_annotations = ['cells', 'number', 'primaryKey', 'titles', 'referencedRows', 'sourceNumber', 'table']
schema_description = ['columns', 'foreignKeys', 'primaryKey', 'rowTitles', '@type', '@id']
def is_non_core_annotation(name):
return name not in core_group_of_tables_annotations \
and name not in core_table_annotations \
and name not in core_column_annotations \
and name not in core_row_annotations \
and name not in schema_description
CONST_STANDARD_MODE = 'standard'
CONST_MINIMAL_MODE = 'minimal'
core_group_of_tables_properties = ['tables', 'dialect', 'notes', 'tableDirection', 'tableSchema', 'transformations',
'@id', '@type', '@context']
core_table_properties = ['url', 'dialect', 'notes', 'suppressOutput', 'tableDirection', 'tableSchema',
'transformations', '@id', '@type']
inherited_properties = ['aboutUrl', 'datatype', 'default', 'lang', 'null', 'ordered', 'propertyUrl', 'required',
'separator', 'textDirection', 'valueUrl']
array_properties = ['tables', 'transformations', '@context', 'notes', 'foreignKeys',
'columns', 'lineTerminators']
array_property_item_types = {
'columns': dict,
'foreignKeys': dict,
'lineTerminators': str,
'notes': dict,
'transformations': dict,
'tables': dict,
}
number_datatypes = ['decimal', 'integer', 'integer', 'long', 'int', 'short', 'byte', 'nonNegativeInteger',
'positiveInteger', 'unsignedLong', 'unsignedInt', 'unsignedShort', 'unsignedByte',
'nonPositiveInteger', 'negativeInteger', 'double', 'number', 'duration', 'dayTimeDuration',
'yearMonthDuration', 'float']
date_datatypes = ['date', 'dateTime', 'datetime', 'dateTimeStamp']
fields_properties = {
'transformations': {'url': True, 'scriptFormat': True, 'targetFormat': True, 'source': False, 'titles': False,
'@id': False, '@type': True},
'tableGroup': {'tables': True, 'dialect': False, 'notes': False, 'tableDirection': False, 'tableSchema': False,
'transformations': False, '@id': False, '@type': False, '@context': True},
'tables': {'url': True, 'dialect': False, 'notes': False, 'suppressOutput': False, 'tableDirection': False,
'transformations': False, 'tableSchema': False, '@id': False, '@type': False},
'columns': {'name': False, 'suppressOutput': False, 'titles': False, 'virtual': False, '@id': False,
'@type': False, }
}
|
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2021 Oleksandr Moskalenko <om@rc.ufl.edu>
#
# Distributed under terms of the MIT license.
"""
Visualize fragments and events in a terminal
"""
def print_region(data):
"""
Print a scaled region to screen with labels and dashes for visualization.
"""
label = ""
region = ""
r_end = 0
for i in (sorted(data.keys())):
start = i
name = data[start][0]
end = data[start][1]
ilen = end - start - 1
if ilen < 0:
ilen = 0
gap = start - r_end - 1
if gap <= 0:
gap = 0
region += gap * " " + '|'
label += (gap + 1) * " "
region += (ilen * "-") + '|'
r_end = end + 1
l_pad = round((end - start) / 2 - len(name) / 2) - 1
if l_pad < 0:
l_pad = 0
label += l_pad * " "
label += name
# print(f"ER: {name}, {start}, {end}, {ilen}, {r_end}, {gap}, {l_pad}")
# print(label)
# print(region)
l_fill = len(region) - len(label)
label += l_fill * " "
print(label)
print(region)
def plot_ers(ers, tx1, tx2):
"""
Plot ERs visually when debugging.
"""
start, end, er_dict, tx1_dict, tx2_dict = [], [], {}, {}, {}
for er in ers:
start.append(er.start)
end.append(er.end)
g_start = min(start)
g_end = max(end)
er_range = g_end - g_start + 1
scale = 200.0 / er_range
print(tx1_dict)
for i in ers:
i_name = i.name.split(':')[1]
er_dict[round((i.start - g_start) * scale)] = [i_name, round((i.end - g_start) * scale)]
for i in tx1:
tx1_name = i.name.split("_")[0]
i_name = "E" + i.name.split('_')[-1]
tx1_dict[round((i.start - g_start) * scale)] = [i_name, round((i.end - g_start) * scale)]
for i in tx2:
tx2_name = i.name.split("_")[0]
i_name = "E" + i.name.split('_')[-1]
tx2_dict[round((i.start - g_start) * scale)] = [i_name, round((i.end - g_start) * scale)]
gene_name = next(iter(er_dict.values()))[0].split(':')[0]
print(f"Exonic Regions for {gene_name} gene")
print('|' + '-' * 198 + '|')
print_region(er_dict)
print('|' + '-' * 98 + '|')
print(f"Transcript 1: {tx1_name}")
print_region(tx1_dict)
print('|' + '-' * 98 + '|')
print(f"Transcript 2: {tx2_name}")
print_region(tx2_dict)
print('|' + '-' * 98 + '|')
|
expected_number_of_transactions = [
2650, 2543, 1395, 2751, 2398, 2827, 2737, 3084, 1998, 2997, 976,
1929, 3268, 1904, 1772, 776, 2553, 2547, 2581, 2226, 2307, 2812,
2618, 177, 1538, 1990, 2323, 2613, 2503, 2140, 2542, 2291, 2782,
1994, 2513, 2773, 1359, 1744, 868, 896, 2228, 2300, 2349, 2440,
2562, 2123, 3150, 2564, 1590, 349, 2049, 1978, 2687, 2330, 1492,
1968, 2610, 2228, 1581, 2204, 1837, 2565, 2375, 2422, 1808, 2662,
2760, 1507, 2753, 2067, 2786, 1677, 2622, 2319, 17, 2144, 922, 2123,
2379, 2798, 2197, 2060, 2081, 2257, 2728, 2689, 2103, 2218, 960,
1397, 479, 913, 87, 1682, 2032, 2307, 2579, 229, 817, 1457, 1822,
1353, 907, 912, 1413, 2469, 2293, 2396, 1087, 970, 1363, 2305,
2319, 2192, 2320, 2804, 2936, 2627, 2242, 2068, 2630, 2366, 2494,
2191, 2598, 1933, 1236, 1380, 985, 2507, 2003, 586, 1223, 1120,
2119, 2401, 1706, 739, 1378, 960, 1751, 2553, 2312, 2392
]
expected_block_sizes = [
1340282.0, 1171564.8, 1290236.0, 1374338.4, 1306336.8333333333,
1114189.7272727273, 1334556.3333333333, 1072760.4, 1190087.0,
1316951.0, 1258290.5, 1263454.6666666667, 1261141.25, 1350125.8,
1387607.0, 1215300.1666666667, 828290.3333333334, 1227950.5,
1287358.3333333333, 925557.1666666666, 1215318.111111111,
1523156.4444444445, 1278528.75, 1411428.0, 1315790.6666666667,
1019578.3, 990839.5
]
expected_hourly_transactions = [
2650, 11914, 7819, 11074, 12455,
23563, 7067, 9257, 18048, 2564,
10983, 6070, 7850, 11832, 2760,
13412, 4480, 12479, 14076, 5518,
13503, 15208, 19508, 7490, 6722,
15560, 13791
]
expected_times_between_blocks = [
1612, 93, 242, 1294, 1704, 586, 789, 1969, 403, 228, 116, 23, 2398, 850,
864, 340, 185, 24, 1802, 812, 203, 887, 677, 45, 194, 73, 366, 125, 76,
456, 1035, 236, 1450, 1123, 872, 1669, 110, 725, 186, 10, 85, 291, 252,
279, 1380, 180, 3919, 1201, 218, 102, 791, 257, 233, 1721, 773, 433, 2865,
343, 410, 2042, 285, 121, 1515, 851, 135, 977, 4108, 43, 1585, 177, 249,
759, 1361, 2200, 2, 530, 23, 496, 626, 459, 1125, 1305, 639, 45, 884, 47,
1069, 813, 158, 1963, 122, 239, 21, 443, 158, 1002, 807, 65, 66, 525, 461,
284, 170, 63, 172, 714, 1043, 815, 259, 184, 98, 521, 582, 922, 40, 430, 181,
431, 526, 1225, 829, 1015, 1220, 2161, 175, 1224, 347, 372, 253, 224, 699,
152, 388, 204, 162, 1277, 483, 178, 337, 68, 452, 75, 701
]
expected_transaction_values = [
11383.94878785999, 17308.05367398, 3622.7728769900023, 9633.670801730033,
14826.62779696996, 7259.995884540011, 11203.150786679953, 29506.748038190017,
16576.26348286996, 13175.761536749957, 8641.552318090005, 4003.4319120199984,
25662.060170189954, 10444.260513739988, 7554.059845370009, 4268.25902016,
2472.864963509989, 4077.0395888499947, 12750.97627863001, 12355.883847110006,
2393.240527540009, 8622.960466979994, 5447.26763365, 87.38996292999992,
2605.2993410000067, 1471.356488039999, 3053.277851210003, 2625.0749443800064,
1072.1113604599975, 5041.109816149992, 9713.188765789986, 3266.108440949993,
11768.000924819953, 13569.830664560017, 7538.576938960003, 13569.767463059985,
844.6543596399998, 5331.023938179994, 848.165141919999, 967.1358015199999,
1010.1064013400085, 5567.299901390007, 1625.9675534700016, 2253.125553860004,
7658.386822249995, 8384.54668757001, 19206.147882259953, 4469.351264000007,
1315.0544174199972, 432.19316666, 6127.310503930018, 2066.3867831300004,
1872.9193954999962, 8815.472050029986, 2843.420696440003, 4687.6417044999835,
16042.92928003998, 1382.5175280100018, 8815.100493969989, 14234.330114909988,
1557.5183457699975, 685.3837385100013, 8590.53198090003, 4053.731241960002,
4720.6605097500005, 9639.943570420017, 11608.579181260073, 988.918982430001,
6871.058338240004, 989.8308203200012, 1580.3052625199962, 10245.606500710022,
5184.384621690003, 11088.598342719983, 8.966610300000001, 3152.560446030012,
194.15356827999992, 1916.1249402400003, 2332.781637169996, 1904.5502168199978,
4478.237747329994, 3766.84221378, 2647.122554909998, 1194.9242250000002,
3695.6209336000006, 1154.9818379700005, 9400.906267190016, 6496.324190000008,
1501.6140470199998, 19201.642837140032, 1197.2633540199993, 1833.1202640199983,
78.32123893999999, 1376.2240791900024, 976.7801730400008, 3321.5335948599977,
3486.9283997099947, 129.03544430000005, 1922.221544139999, 2939.189555250006,
5593.631477060008, 2429.757580759996, 2298.759065579999, 703.1883488999998,
1117.6024098399996, 5161.379796689989, 5459.422803130007, 4495.1067846999795,
4045.725931109999, 1516.9282807899995, 854.3813730699983, 1992.721841120003,
4143.047950169987, 5249.556289420004, 1518.8253502700004, 4252.785797819985,
1540.4489411699933, 3430.193032909998, 4144.407905429995, 6595.714538640011,
6396.9363644500345, 9235.605561159991, 8098.343213619993, 11370.341906110016,
1631.5964133900047, 7494.17682190998, 1991.0408088299973, 1646.4867985599997,
5561.463178049983, 1584.26847222, 4428.548573870004, 510.3291968700005,
1558.24513197, 2942.867825329997, 1391.3934453300005, 7026.66253513999,
3573.887328660006, 1833.9685547500019, 4669.513988809994, 587.4164939700005,
2331.6464144200054, 1765.9344505200047, 6876.602656040003, 11012.55110367002
]
|
files_c=[
'C/Threads.c',
]
files_cpp=[
'CPP/7zip/UI/P7ZIP/wxP7ZIP.cpp',
'CPP/Common/IntToString.cpp',
'CPP/Common/MyString.cpp',
'CPP/Common/MyVector.cpp',
'CPP/Common/StringConvert.cpp',
'CPP/Windows/FileDir.cpp',
'CPP/Windows/FileFind.cpp',
'CPP/Windows/FileIO.cpp',
'CPP/Windows/FileName.cpp',
'CPP/Common/MyWindows.cpp',
'CPP/myWindows/wine_date_and_time.cpp',
]
|
# Medium
# https://leetcode.com/problems/spiral-matrix/
# Time Complexity: O(N)
# Space Complexity: 0(1)
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
return Solution.spiralsol(matrix, [])
@staticmethod
def spiralsol(matrix, res):
m = len(matrix)
if m == 0:
return res
n = len(matrix[0])
if n == 0:
return res
res += matrix[0]
if m > 1:
res += [matrix[i][n - 1] for i in range(1, m - 1)]
res += matrix[m - 1][::-1]
if n > 1:
res += [matrix[i][0] for i in range(m - 2, 0, -1)]
matrix = matrix[1:m - 1]
for index, row in enumerate(matrix):
matrix[index] = row[1:n-1]
Solution.spiralsol(matrix, res)
return res |
a = 5
b = 10
my_variable = 56
any_variable_name = 100
string_variable = "hello"
single_quotes = 'strings can have single quotes'
print(string_variable)
print(my_variable)
# print is a method with one parameter—what we want to print
def my_print_method(my_parameter):
print(my_parameter)
my_print_method(string_variable)
def my_multiplication_method(number_one, number_two):
return number_one * number_two
result = my_multiplication_method(a, b)
print(result)
print(my_multiplication_method(56, 75))
my_print_method(my_multiplication_method('b', 5)) # What would this do?
|
# https://www.reddit.com/wiki/bottiquette omit /r/suicidewatch and /r/depression
# note: lowercase for case insensitive match
blacklist = [
# https://www.reddit.com/r/Bottiquette/wiki/robots_txt_json
"anime",
"asianamerican",
"askhistorians",
"askscience",
"askreddit",
"aww",
"chicagosuburbs",
"cosplay",
"cumberbitches",
"d3gf",
"deer",
"depression",
"depthhub",
"drinkingdollars",
"forwardsfromgrandma",
"geckos",
"giraffes",
"grindsmygears",
"indianfetish",
"me_irl",
"misc",
"movies",
"mixedbreeds",
"news",
"newtotf2",
"omaha",
"petstacking",
"pics",
"pigs",
"politicaldiscussion",
"politics",
"programmingcirclejerk",
"raerthdev",
"rants",
"runningcirclejerk",
"salvia",
"science",
"seiko",
"shoplifting",
"sketches",
"sociopath",
"suicidewatch",
"talesfromtechsupport",
"torrent",
"torrents",
"trackers",
"tr4shbros",
"unitedkingdom",
"crucibleplaybook",
"cassetteculture",
"italy_SS",
"DimmiOuija",
# no bots allowed but not on bottiquette
"todayilearned",
# non-english speaking
"hololive",
"internetbrasil",
"puebla",
"chile",
"saintrampalji",
# needs more karma
"centrist",
"conspiracy",
# handle timestamp in youtube title
"dauntless",
# timestamps usually not a skip point
"speedrun",
]
min_karma_dict = {"superstonk": 1200}
|
# The major optimization is to do arithmetic in base 10 in the main loop, avoiding division and modulo
def problem206():
"""
Find the unique positive integer whose square has the form
1_2_3_4_5_6_7_8_9_0,
where each “_” is a single digit.
"""
# Initialize
n = 1000000000 # The pattern is greater than 10^18, so start searching at 10^9
ndigits = [0] * 10 # In base 10, little-endian
temp = n
for i in range(len(ndigits)):
ndigits[i] = temp % 10
temp //= 10
n2digits = [0] * 19 # Based on length of pattern
temp = n * n
for i in range(len(n2digits)):
n2digits[i] = temp % 10
temp //= 10
# Increment and search
while not is_concealed_square(n2digits):
# Add 20n + 100 so that n2digits = (n + 10)^2
add_20n(ndigits, n2digits)
add_10pow(n2digits, 2)
# Since n^2 ends with 0, n must end with 0
n += 10
add_10pow(ndigits, 1)
# Now n2digits = n^2
return n
def is_concealed_square(n):
for i in range(1, 10): # Scan for 1 to 9
if n[20 - i * 2] != i:
return False
return n[0] == 0 # Special case for 0
def add_10pow(n, i):
while n[i] == 9:
n[i] = 0
i += 1
n[i] += 1
def add_20n(n, n2):
carry = 0
i = 0
while i < len(n):
sum = n[i] * 2 + n2[i + 1] + carry
n2[i + 1] = sum % 10
carry = sum // 10
i += 1
i += 1
while carry > 0:
sum = n2[i] + carry
n2[i] = sum % 10
carry = sum // 10
i += 1
if __name__ == "__main__":
print(problem206())
|
load("//bazel/rules/cpp:object.bzl", "cpp_object")
load("//bazel/rules/hcp:hcp.bzl", "hcp")
load("//bazel/rules/hcp:hcp_hdrs_derive.bzl", "hcp_hdrs_derive")
def string_tree_to_static_tree_parser(name):
#the file names to use
target_name = name + "_string_tree_parser_dat"
in_file = name + ".dat"
outfile = name + "_string_tree_parser.hcp"
#converting hcp to hpp/cpp
native.genrule(
name = target_name,
srcs = [in_file],
outs = [outfile],
tools = ["//code/programs/transcompilers/tree_hcp/string_tree_to_static_tree_parser:string_tree_to_static_tree_parser"],
cmd = "$(location //code/programs/transcompilers/tree_hcp/string_tree_to_static_tree_parser:string_tree_to_static_tree_parser) -i $(SRCS) -o $@",
)
#compile hcp file
#unique dep (TODO: dynamically decide)
static_struct_dep = "//code/utilities/code:concept_static_tree_structs"
deps = [
"//code/utilities/data_structures/tree/generic:string_tree",
"//code/utilities/data_structures/tree/generic:string_to_string_tree",
"//code/utilities/types/strings/transformers/appending:lib",
"//code/utilities/data_structures/tree/generic/tokens:tree_token",
"//code/utilities/types/vectors/observers:lib",
static_struct_dep,
]
hcp(name + "_string_tree_parser", deps)
|
class BaseServerException(Exception):
def __init__(self, detail, status_code, message):
super().__init__(message)
self.detail = detail
self.status_code = status_code
class SearchFieldRequiered(BaseServerException):
def __init__(self):
super().__init__(detail='entity', status_code=404, message='Search field required')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.