content
stringlengths 7
1.05M
|
---|
class Solution:
def largestBSTSubtree(self, root: TreeNode) -> int:
return self._post_order(root)[0]
def _post_order(self, root):
if not root:
return 0, True, None, None
if not root.left and not root.right:
return 1, True, root.val, root.val
ln, lbst, lmin, lmax = self._post_order(root.left)
rn, rbst, rmin, rmax = self._post_order(root.right)
if not lbst or not rbst or (lmax and root.val <= lmax) or (rmin and root.val >= rmin):
return max(ln, rn), False, None, None
return ln + rn + 1, True, lmin if lmin else root.val, rmax if rmax else root.val
|
# print function range value
for value in range(1, 5):
print(value)
numbers = list(range(1, 6))
print(numbers)
even_numbers = list(range(2, 11))
print(even_numbers)
|
def is_odd(n):
return n % 2 == 1
def is_weird(n):
if is_odd(n):
return True
else:
# n is even
if 2 <= n <= 5:
return False
elif 6 <= n <= 20:
return True
elif 20 < n:
return False
n = int(input())
if (is_weird(n)):
print("Weird")
else:
print("Not Weird")
|
class calculos():
def __init__(self):
self.funcoes = {
"soma": self.soma,
"subtracao": self.subtracao,
"multiplicacao": self.multiplicacao,
"divisao": self.divisao,
"quadrado": self.quadrado,
"raiz_quadrada": self.raiz_quadrada,
"porcentagem": self.porcentagem
}
def soma(self, x, y):
return x + y
def subtracao(self, x, y):
return x - y
def multiplicacao(self, x, y):
return x * y
def divisao(self, x, y):
return x / y
def quadrado(self, x):
return x ** 2
def raiz_quadrada(self, x):
return x ** (1/2)
def porcentagem(self, x, y):
return (x * y) / 100
if __name__ == '__main__':
calculos = calculos()
resultado = calculos.funcoes['soma'](1, 4)
print(resultado)
|
# Print the list created by using list comprehension
names = ['George', 'Harry', 'Weasely', 'Ron', 'Potter', 'Hermione']
best_list = [name for name in names if len(name) >= 6]
print(best_list)
# Range Objects
# Create a range object that goes from 0 to 5
nums = range(6)
print(type(nums))
# Convert nums to a list
nums_list = list(nums)
print(nums_list)
# Create a new list of odd numbers from 1 to 11 by unpacking a range object
nums_list2 = [*range(1,12,2)]
# This unpacks the range object to a list
print(nums_list2)
# Enumerate Objects
names = ['Jerry', 'Kramer', 'Elaine', 'George', 'Newman']
# Rewrite the for loop to use enumerate
indexed_names = []
for i,name in enumerate(names):
index_name = (i,name)
indexed_names.append(index_name)
print(indexed_names)
# Rewrite the above for loop using list comprehension
indexed_names_comp = [(i,name) for i,name in enumerate(names)]
print(indexed_names_comp)
# Unpack an enumerate object with a starting index of one
indexed_names_unpack = [*enumerate(names, start=1)]
print(indexed_names_unpack)
# Map Objects
# Use map to apply str.upper to each element in names
names_map = map(str.upper, names)
# Print the type of the names_map
print(type(names_map))
# Unpack names_map into a list
names_uppercase = [*names_map]
# Print the list created above
print(names_uppercase)
|
# -*- coding:utf-8 -*-
def read_files(path):
file = open(path, 'r+')
str_ = file.read()
print(str_)
file.close()
|
#!/usr/bin/python3
""" 4-main """
MRUCache = __import__('4-mru_cache').MRUCache
my_cache = MRUCache()
my_cache.put("A", "Hello")
my_cache.put("B", "World")
my_cache.put("C", "Holberton")
my_cache.put("D", "School")
my_cache.print_cache()
print(my_cache.get("B"))
my_cache.put("E", "Battery")
my_cache.print_cache()
my_cache.put("C", "Street")
my_cache.print_cache()
print(my_cache.get("A"))
print(my_cache.get("B"))
print(my_cache.get("C"))
my_cache.put("F", "Mission")
my_cache.print_cache()
my_cache.put("G", "San Francisco")
my_cache.print_cache()
my_cache.put("H", "H")
my_cache.print_cache()
my_cache.put("I", "I")
my_cache.print_cache()
my_cache.put("J", "J")
my_cache.print_cache()
my_cache.put("K", "K")
my_cache.print_cache()
|
class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
def change(i):
if i == '0':
return '1'
return '0'
l = ''
print(bin(num)[2:])
for i in bin(num)[2:]:
l += change(i)
return int(l, 2)
|
print("Em que ano você nasceu?")
nascimento = input()
nascimento = int(nascimento)
print("Para qual ano você quer saber sua idade?")
idadequalquer = input()
idadequalquer = int(idadequalquer)
idadefinal = idadequalquer - nascimento
print( "No ano ", idadequalquer , "você terá", idadefinal, "anos!")
|
nome = input('Digite seu nome completo: ')
print('Nome em letras maiúsculas: {}' .format(nome.upper().strip()))
print('Nome em letras minúsculas: {}' .format(nome.lower().strip()))
print('Total de letras: {}' .format(len((nome.replace(" ", "")))))
nome_s = nome.split()
print('O primeiro nome tem {} letras.' .format(len(nome_s[0])))
|
for a in range (2,21):
if a > 1:
for i in range(2,a):
if (a % i) == 0:
break
else:
print(a)
|
#!/usr/bin/env python3
# Simple data processing, extraction of GPGGA and GPRMC entries
# Source filename
FILENAME = "../data/GNSS_34_2020-02-23_16-20-44.txt"
# Output filename
OUTFILE = "../output/track.nmea"
if __name__ == "__main__":
outfile = open(OUTFILE, 'w')
with open(FILENAME, 'r') as f:
for line in f.readlines():
try:
data = line.split(';')[1].strip()
if data.startswith("$GPGGA") or data.startswith("$GPRMC"):
print(data)
outfile.write(data + '\n')
except:
pass
outfile.close()
f.close()
|
# 60
# Faça um programa que leia um número qualquer e mostre o seu fatorial.
# Exemplo: 5! = 5 x 4 x 3 x 2 x 1 = 120
num = int(input('Digite um número para calcular seu Fatorial: '))
c = num
fat = 1
# # Form 1 - using Math
# from math import factorial
# f = factorial(num)
# print("O fatorial de {} é {}".format(num, f))
# Form 2 - using While
print('Calculando {}! = '.format(num), end='')
while c > 0:
print('{}'.format(c), end='')
print(' x ' if c > 1 else ' = ', end='')
fat = fat * c
c -= 1
print(fat)
print('\nO fatorial de {}! é \33[32m{}\33[m'.format(num, fat))
# # Form 3 - using For
# for i in range(num, 0):
# print("{}".format(c), end='')
# print(' x ' if c > 1 else ' = ', end='')
# fat = fat * c
# c -= 1
# print("\nO fatorial de {}! é \33[32m{}\33[m".format(num, fat))
|
registry = {}
def unmarshal(typestr, x):
try:
unmarshaller = registry[typestr]
except KeyError:
raise TypeError("No unmarshaller registered for '{}'".format(typestr))
return unmarshaller(x)
def register(typestr, unmarshaller):
if typestr in registry:
raise NameError(
"An unmarshaller is already registered for '{}'".format(typestr)
)
registry[typestr] = unmarshaller
def identity(x):
return x
def astype(typ):
"Unmarshal by casting into ``typ``, if not already an instance of ``typ``"
def unmarshaller(x):
return typ(x) if not isinstance(x, typ) else x
return unmarshaller
def unpack_into(typ):
"Unmarshal by unpacking a dict into the constructor for ``typ``"
def unmarshaller(x):
return typ(**x)
return unmarshaller
__all__ = ["unmarshal", "register", "identity", "unpack_into"]
|
"""
1201_pull_up_method.py
范例 有两个子类,它们之中各有一个函数做了相同的事情。这个例子在 12.3 和 12.8 也有引用。
"""
class Party:
"""契约或争论的)当事人,一方"""
@property
def annual_cost(self):
return self.monthly_cost * 12
@property
def monthly_cost(self):
raise RuntimeError("SubclassResponsibilityError")
class Employee(Party):
@property
def monthly_cost(self):
return self._monthly_cost
class Department(Party):
"""total_annual_cost() 改名为 annual_cost()"""
@property
def monthly_cost(self):
return self._monthly_cost
|
def play(n=None):
if n is None:
while True:
try:
n = int(input('Input the grid size: '))
except ValueError:
print('Invalid input')
continue
if n <= 0:
print('Invalid input')
continue
break
grids = [[0]*n for _ in range(n)]
user = 1
print('Current board:')
print(*grids, sep='\n')
while True:
user_input = get_input(user, grids, n)
place_piece(user_input, user, grids)
print('Current board:')
print(*grids, sep='\n')
if check_won(user_input, user, n, grids):
print('Player', user, 'has won')
return
if not any(0 in grid for grid in grids):
return
user = 2 if user == 1 else 1
def get_input(user, grids, n):
instr = 'Input a slot player {0} from 1 to {1}: '.format(user, n)
while True:
try:
user_input = int(input(instr))
except ValueError:
print('invalid input:', user_input)
continue
if 0 > user_input or user_input > n+1:
print('invalid input:', user_input)
elif grids[0][user_input-1] != 0:
print('slot', user_input, 'is full try again')
else:
return user_input-1
def place_piece(user_input, user, grids):
for grid in grids[::-1]:
if not grid[user_input]:
grid[user_input] = user
return
# def check_won(user_input, user, n, grids):
# column = [i[user_input] for i in grids]
# print("column")
# print(column)
# if grids[user_input].count(user) == 4:
# print("aaaa"+ grids[user_input])
# return True
# index = 0
# for i in column:
# if i == 0:
# index += 1
# print(index)
# print("index: "+str(index))
# if column.count(user) == 4:
# return True
#play()
|
def get_rate(numbers,
is_o2):
nb_bits = len(numbers[0])
assert all([len(n) == nb_bits for n in numbers])
current_numbers = [n for n in numbers]
i = 0
while len(current_numbers) > 1:
nb_ones = sum([elem[i] == '1' for elem in current_numbers])
nb_zeros = sum([elem[i] == '0' for elem in current_numbers])
bit_o2 = '1' if nb_ones >= nb_zeros else '0'
bit_co2 = '0' if nb_zeros <= nb_ones else '1'
bit = bit_o2 if is_o2 else bit_co2
current_numbers = [n for n in current_numbers if n[i] == bit]
i += 1
assert(1 == len(current_numbers))
result = int(current_numbers[0], base=2)
return result
def get_life_support(numbers):
o2_rate = get_rate(numbers, is_o2=True)
co2_rate = get_rate(numbers, is_o2=False)
result = o2_rate * co2_rate
return result
if __name__ == '__main__':
input_filename = 'input.txt'
# input_filename = 'sample-input.txt'
with open(input_filename, 'r') as input_file:
fc = input_file.read()
split = fc.split()
print(get_life_support(split))
|
# Returns the sum of all multipliers of x for numbers from 1 to end.
def sumOfMultipliers(end, x):
n = end / x
return (n * (n + 1) / 2) * x
end = 999 # below 1000
x = 3
y = 5
# We have to subtract one sum of the multipliers of x * y because these multipliers take part in both of the sums of the multipliers of x and y and hence contribute twice in the final sum.
sum = sumOfMultipliers(end, x) + sumOfMultipliers(end, y) - sumOfMultipliers(end, x * y)
print(sum)
|
def cmdissue(toissue, activesession):
ssh_stdin, ssh_stdout, ssh_stderr = activesession.exec_command(toissue)
return ssh_stdout.read().decode('UTF-8')
def commands_list(sshsession, commands):
for x in commands:
## call our imported function and save the value returned
resp = cmdissue(x, sshsession)
## if returned response is not null, print it out
if resp != "":
print(resp)
|
List1 = []
List2 = []
List3 = []
List4 = []
List5 = [13,31,2,19,96]
statusList1 = 0
while statusList1 < 13:
inputList1 = str(input("Masukkan hewan bersayap : "))
statusList1 += 1
List1.append(inputList1)
print()
statusList2 = 0
while statusList2 < 5:
inputList2 = str(input("Masukkan hewan berkaki 2 : "))
statusList2 += 1
List2.append(inputList2)
print()
statusList3 = 0
while statusList3 < 5:
inputList3 = str(input("Masukkan nama teman terdekat anda : "))
statusList3 += 1
List3.append(inputList3)
print()
statusList4 = 0
while statusList4 < 5:
inputList4 = int(input("Masukkan tanggal lahir teman tersebut : "))
statusList4 += 1
List4.append(inputList4)
print(List1[0:5]+List4,'\n')
List3[4] = 'Rio'
print(List3,'\n')
tempList5 = List5.copy()
del tempList5[4]
del tempList5[2]
print(tempList5,'\n')
print(List4 + List5)
print("Nilai Max dari List 4 dan List 5 adalah",max(List4 + List5))
print("Nilai Min dari List 4 dan List 5 adalah",min(List4 + List5))
|
"""curso = "Curso de Python"
res = "Python" not in curso #imprime <FALSE> se existir o valor dentro da variável
print(res)"""
texto="Curso de Python"
palavra ="python"
res =palavra.upper()in texto.upper()#deixa a procura por palavras grande e texto grande resposta <True>
print(res)
|
class dataStore:
dataList=[]
symbolList=[]
optionList=[]
def __init__(self):
self.dataList=[]
self.symbolList=[]
self.optionList=[]
def reset(self):
self.dataList=[]
self.symbolList=[]
self.optionList=[]
|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @author jsbxyyx
# @since 1.0
class MessageType(object):
TYPE_GLOBAL_BEGIN = 1
TYPE_GLOBAL_BEGIN_RESULT = 2
TYPE_GLOBAL_COMMIT = 7
TYPE_GLOBAL_COMMIT_RESULT = 8
TYPE_GLOBAL_ROLLBACK = 9
TYPE_GLOBAL_ROLLBACK_RESULT = 10
TYPE_GLOBAL_STATUS = 15
TYPE_GLOBAL_STATUS_RESULT = 16
TYPE_GLOBAL_REPORT = 17
TYPE_GLOBAL_REPORT_RESULT = 18
TYPE_GLOBAL_LOCK_QUERY = 21
TYPE_GLOBAL_LOCK_QUERY_RESULT = 22
TYPE_BRANCH_COMMIT = 3
TYPE_BRANCH_COMMIT_RESULT = 4
TYPE_BRANCH_ROLLBACK = 5
TYPE_BRANCH_ROLLBACK_RESULT = 6
TYPE_BRANCH_REGISTER = 11
TYPE_BRANCH_REGISTER_RESULT = 12
TYPE_BRANCH_STATUS_REPORT = 13
TYPE_BRANCH_STATUS_REPORT_RESULT = 14
TYPE_SEATA_MERGE = 59
TYPE_SEATA_MERGE_RESULT = 60
TYPE_REG_CLT = 101
TYPE_REG_CLT_RESULT = 102
TYPE_REG_RM = 103
TYPE_REG_RM_RESULT = 104
TYPE_RM_DELETE_UNDOLOG = 111
TYPE_HEARTBEAT_MSG = 120
def __init__(self):
pass
|
def scoreOfParentheses(S):
total = 0
cur = 0
for i in range(len(S)):
if S[i] == "(":
cur += 1
elif S[i] == ")":
cur -= 1
if S[i-1] == "(":
total += 2**cur
return total
print(scoreOfParentheses("()")) # 1
print(scoreOfParentheses("()()")) # 2
print(scoreOfParentheses("((()))")) # 4
print(scoreOfParentheses("(()(()))")) # 6
print(scoreOfParentheses("(((()))()())")) # 12
|
c = input().split()
W, H, x, y, r = int(c[0]), int(c[1]), int(c[2]), int(c[3]), int(c[4])
if r <= x <= W - r and r <= y <= H - r:
print("Yes")
else:
print("No")
|
# -*- coding: utf-8 -*-
numeros = []
for x in range(100):
numeros.append(int(input()))
print(max(numeros))
print(numeros.index(max(numeros))+1)
|
# Python Program to Differentiate Between type() and isinstance()
class Polygon:
def sides_no(self):
pass
class Triangle(Polygon):
def area(self):
pass
obj_polygon = Polygon()
obj_triangle = Triangle()
print(type(obj_triangle) == Triangle) # true
print(type(obj_triangle) == Polygon) # false
print(isinstance(obj_polygon, Polygon)) # true
print(isinstance(obj_triangle, Polygon)) # true
|
preço = float(input('O produto custava: R$'))
novo = preço - (preço * 15 / 100)
print('o produto custava {:.2f} na promoção com desconto de 5% ele custará: {:.2f}'.format(preço, novo))
#Para calcular a porcetagem é preciso motiplicar o valor do produto x o valor do desconto e dividir por 100.#
#O resultado dubtrair pelo preço#
|
s1 = (2, 1.3, 'love', 5.6, 9, 12, False)
s2 = [True, 5, 'smile']
print('s1=',s1)
print('s1[:5]=',s1[:5])
print('s1[2:]=',s1[2:])
print('s1[0:5:2]=',s1[0:5:2])
print('s1[2:0:-1]=',s1[2:0:-1])
print('s1[-1]=',s1[-1])
print('s1[-3]=',s1[-3])
|
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code # -> 200
r.headers['content-type']
# -> 'application/json; charset=utf8'
r.encoding # -> 'utf-8'
r.text # -> u'{"type":"User"...'
r.json()
# -> {u'private_gists': 419, u'total_private_repos': 77, ...}
|
class AttachedFile:
def __init__(self, original_name: str, tmp_file_path: str, need_content_analysis: bool, uid: str) -> None:
"""
Holds information about attached files.
:param original_name: Name of the file from which the attachments are extracted
:param tmp_file_path: path to the attachment file.
"""
self.original_name = original_name
self.tmp_file_path = tmp_file_path
self.need_content_analysis = need_content_analysis
self.uid = uid
def get_filename_in_path(self) -> str:
return self.tmp_file_path
def get_original_filename(self) -> str:
return self.original_name
|
class Joint:
def __init__(self, name, min_angle: float, max_angle: float):
self.name = name
self.min_angle = min_angle
self.max_angle = max_angle
|
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
wordSet = set(wordDict) # Converted to set for O(1)
# table to map a string to its corresponding words break
# {string: [['word1', 'word2'...], ['word3', 'word4', ...]]}
mem = defaultdict(list)
def _wordBreak_topdown(s):
""" return list of word lists """
# Because word is empty
if not s:
return [[]] # list of empty list
# return cached solution
if s in mem:
return mem[s]
# Start top-down hunt
for endIndex in range(1, len(s)+1):
# Prefix word (all prefix words)
word = s[:endIndex]
if word in wordSet:
# Like subsentence would be ("cat" + _wordBreak_topdown("sanddog")
for subsentence in _wordBreak_topdown(s[endIndex:]):
mem[s].append([word] + subsentence)
return mem[s]
# break the input string into lists of words list
_wordBreak_topdown(s)
# print(mem)
# chain up the lists of words into sentences.
return [" ".join(words) for words in mem[s]]
|
#
# PySNMP MIB module SONOMASYSTEMS-SONOMA-ATM-E3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SONOMASYSTEMS-SONOMA-ATM-E3-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:09:18 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")
SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
iso, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, NotificationType, ObjectIdentity, Bits, Counter32, Integer32, ModuleIdentity, IpAddress, Counter64, MibIdentifier, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "NotificationType", "ObjectIdentity", "Bits", "Counter32", "Integer32", "ModuleIdentity", "IpAddress", "Counter64", "MibIdentifier", "Unsigned32")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
sonomaATM, = mibBuilder.importSymbols("SONOMASYSTEMS-SONOMA-MIB", "sonomaATM")
sonomaE3ATMAdapterGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3))
atmE3ConfGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1))
atmE3StatsGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2))
atmE3ConfPhyTable = MibTable((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1), )
if mibBuilder.loadTexts: atmE3ConfPhyTable.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfPhyTable.setDescription('A table of physical layer configuration for the E3 interface')
atmE3ConfPhyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1), ).setIndexNames((0, "SONOMASYSTEMS-SONOMA-ATM-E3-MIB", "atmE3ConfPhysIndex"))
if mibBuilder.loadTexts: atmE3ConfPhyEntry.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfPhyEntry.setDescription('A entry in the table, containing information about the physical layer of a E3 interface')
atmE3ConfPhysIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3ConfPhysIndex.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfPhysIndex.setDescription('The physical interface index.')
atmE3ConfFraming = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2))).clone(namedValues=NamedValues(("framingE3", 2))).clone('framingE3')).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3ConfFraming.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfFraming.setDescription('Indicates the type of framing supported.')
atmE3ConfInsGFCBits = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfInsGFCBits.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfInsGFCBits.setDescription('Enable/disable the insertion of GFC bits.')
atmE3ConfSerBipolarIO = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('enabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfSerBipolarIO.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfSerBipolarIO.setDescription('Enable/disable bipolar serial I/O.')
atmE3ConfPayloadScrambling = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('enabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfPayloadScrambling.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfPayloadScrambling.setDescription('Enable/disable payload scrambling.')
atmE3ConfOverheadProcessing = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('enabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfOverheadProcessing.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfOverheadProcessing.setDescription('Enable/disable Overhead processing.')
atmE3ConfHDB3Encoding = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('enabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfHDB3Encoding.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfHDB3Encoding.setDescription('Enable/disable HDB3 (High Density Bipolar 3) Encoding.')
atmE3ConfLoopback = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("disabled", 1), ("internal", 2), ("external", 3))).clone('disabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfLoopback.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfLoopback.setDescription('This object is used to modify the state of internal loopback....')
atmE3ConfCableLength = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("notGreaterThan225Feet", 1), ("greaterThan225Feet", 2))).clone('notGreaterThan225Feet')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfCableLength.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfCableLength.setDescription('Configure for the length of the cable.')
atmE3ConfInternalEqualizer = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("use", 1), ("bypass", 2))).clone('use')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfInternalEqualizer.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfInternalEqualizer.setDescription('Configure to use or bypass the internal equalizer.')
atmE3ConfFillerCells = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("unassigned", 1), ("idle", 2))).clone('unassigned')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfFillerCells.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfFillerCells.setDescription('This parameter indicates the type of filler cells to send when there are no data cells.')
atmE3ConfGenerateClock = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfGenerateClock.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfGenerateClock.setDescription('Enable/disable clock generation.')
atmE3StatsTable = MibTable((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1), )
if mibBuilder.loadTexts: atmE3StatsTable.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsTable.setDescription('A table of physical layer statistics information for the E3 interface')
atmE3StatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1), ).setIndexNames((0, "SONOMASYSTEMS-SONOMA-ATM-E3-MIB", "atmE3StatsPhysIndex"))
if mibBuilder.loadTexts: atmE3StatsEntry.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsEntry.setDescription('A entry in the table, containing information about the physical layer of a E3 interface')
atmE3StatsPhysIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsPhysIndex.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsPhysIndex.setDescription('The physical interface index.')
atmE3StatsNoSignals = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsNoSignals.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsNoSignals.setDescription('No signal error counter.')
atmE3StatsNoE3Frames = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsNoE3Frames.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsNoE3Frames.setDescription('No E3 frames error counter.')
atmE3StatsFrameErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsFrameErrors.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsFrameErrors.setDescription('A count of the number of Frames in error.')
atmE3StatsHECErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsHECErrors.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsHECErrors.setDescription('HEC (Header Error Check) error counter.')
atmE3StatsEMErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsEMErrors.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsEMErrors.setDescription('EM (error monitoring) error counter.')
atmE3StatsFeBlockErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsFeBlockErrors.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsFeBlockErrors.setDescription('Far End Block error counter.')
atmE3StatsBpvErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsBpvErrors.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsBpvErrors.setDescription('Bipolar Violation error counter.')
atmE3StatsPayloadTypeMismatches = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsPayloadTypeMismatches.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsPayloadTypeMismatches.setDescription('Payload Type Mismatches error counter.')
atmE3StatsTimingMarkers = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsTimingMarkers.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsTimingMarkers.setDescription('Timing Markers error counter.')
atmE3StatsAISDetects = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsAISDetects.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsAISDetects.setDescription('AIS (Alarm Indication Signal) detect counter.')
atmE3StatsRDIDetects = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsRDIDetects.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsRDIDetects.setDescription('RDI (Remote Defect Indication) error counter.')
atmE3StatsSignalLoss = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsSignalLoss.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsSignalLoss.setDescription('Signal loss indication.')
atmE3StatsFrameLoss = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsFrameLoss.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsFrameLoss.setDescription('Frame loss indication.')
atmE3StatsSyncLoss = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsSyncLoss.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsSyncLoss.setDescription('Synchronization loss counter.')
atmE3StatsOutOfCell = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsOutOfCell.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsOutOfCell.setDescription('ATM out-of-cell delineation.')
atmE3StatsFIFOOverflow = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsFIFOOverflow.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsFIFOOverflow.setDescription('ATM FIFO overflow.')
atmE3StatsPayloadTypeMismatch = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsPayloadTypeMismatch.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsPayloadTypeMismatch.setDescription('The Payload Type Mismatch state.')
atmE3StatsTimingMarker = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsTimingMarker.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsTimingMarker.setDescription('The Timing Marker state.')
atmE3StatsAISDetect = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsAISDetect.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsAISDetect.setDescription('The AIS (Alarm Indication Signal) state.')
atmE3StatsRDIDetect = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsRDIDetect.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsRDIDetect.setDescription('RDI (Remote Defect Indication) state.')
atmE3StatsClearCounters = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2))).clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3StatsClearCounters.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsClearCounters.setDescription('Clear all counters in this group ONLY.')
mibBuilder.exportSymbols("SONOMASYSTEMS-SONOMA-ATM-E3-MIB", atmE3ConfLoopback=atmE3ConfLoopback, atmE3StatsRDIDetect=atmE3StatsRDIDetect, atmE3StatsOutOfCell=atmE3StatsOutOfCell, atmE3ConfPhyTable=atmE3ConfPhyTable, atmE3ConfInternalEqualizer=atmE3ConfInternalEqualizer, atmE3StatsNoE3Frames=atmE3StatsNoE3Frames, atmE3StatsHECErrors=atmE3StatsHECErrors, atmE3ConfSerBipolarIO=atmE3ConfSerBipolarIO, atmE3ConfOverheadProcessing=atmE3ConfOverheadProcessing, atmE3ConfHDB3Encoding=atmE3ConfHDB3Encoding, atmE3StatsFeBlockErrors=atmE3StatsFeBlockErrors, atmE3StatsSignalLoss=atmE3StatsSignalLoss, atmE3ConfPhysIndex=atmE3ConfPhysIndex, atmE3ConfPhyEntry=atmE3ConfPhyEntry, atmE3StatsFrameLoss=atmE3StatsFrameLoss, atmE3ConfPayloadScrambling=atmE3ConfPayloadScrambling, atmE3StatsNoSignals=atmE3StatsNoSignals, atmE3StatsTimingMarker=atmE3StatsTimingMarker, atmE3StatsEMErrors=atmE3StatsEMErrors, atmE3StatsClearCounters=atmE3StatsClearCounters, atmE3ConfGenerateClock=atmE3ConfGenerateClock, atmE3StatsTable=atmE3StatsTable, sonomaE3ATMAdapterGroup=sonomaE3ATMAdapterGroup, atmE3StatsPayloadTypeMismatch=atmE3StatsPayloadTypeMismatch, atmE3ConfInsGFCBits=atmE3ConfInsGFCBits, atmE3ConfFraming=atmE3ConfFraming, atmE3StatsRDIDetects=atmE3StatsRDIDetects, atmE3StatsEntry=atmE3StatsEntry, atmE3ConfFillerCells=atmE3ConfFillerCells, atmE3StatsPhysIndex=atmE3StatsPhysIndex, atmE3ConfCableLength=atmE3ConfCableLength, atmE3StatsBpvErrors=atmE3StatsBpvErrors, atmE3StatsTimingMarkers=atmE3StatsTimingMarkers, atmE3StatsAISDetect=atmE3StatsAISDetect, atmE3ConfGroup=atmE3ConfGroup, atmE3StatsFrameErrors=atmE3StatsFrameErrors, atmE3StatsPayloadTypeMismatches=atmE3StatsPayloadTypeMismatches, atmE3StatsSyncLoss=atmE3StatsSyncLoss, atmE3StatsGroup=atmE3StatsGroup, atmE3StatsAISDetects=atmE3StatsAISDetects, atmE3StatsFIFOOverflow=atmE3StatsFIFOOverflow)
|
def shift(a):
last = a[-1]
a.insert(0, last)
a.pop()
return a
def f(a,b):
a = list(a)
b = list(b)
for i in range(len(a)):
a = shift(a)
if a == b:
return True
return False
f('abcde', 'abced')
|
def extractBinggoCorp(item):
"""
# Binggo & Corp Translations
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'Jiang Ye' in item['title'] and 'Chapter' in item['title']:
return buildReleaseMessageWithType(item, 'Jiang Ye', vol, chp, frag=frag, postfix=postfix)
if 'Ze Tian Ji' in item['title'] and 'Chapter' in item['title']:
return buildReleaseMessageWithType(item, 'Ze Tian Ji', vol, chp, frag=frag, postfix=postfix)
return False
|
class BaloneyInterpreter(object):
def __init__(self, prog):
self.prog = prog
def run(self):
self.vars = {} # All variables
self.lists = {} # List variables
self.error = 0 # Indicates program error
self.stat = list(self.prog) # Ordered list of all line numbers
self.stat.sort()
print(self.stat)
|
#!/bin/python3
def plus_minus(array):
ratio_positive = round(sum(i > 0 for i in array) / len(array), 6)
ratio_negative = round(sum(i < 0 for i in array) / len(array), 6)
ratio_zero = round(sum(i == 0 for i in array) / len(array), 6)
return ratio_positive, ratio_negative, ratio_zero
def test_plus_minus():
"""Test for plus_minus function."""
assert plus_minus(array=[1, 1, 0, -1, -1]) == (
0.400000,
0.400000,
0.200000,
)
assert plus_minus(array=[-4, 3, -9, 0, 4, 1]) == (
0.500000,
0.333333,
0.166667,
)
test_plus_minus()
n = int(input())
array = list(map(int, input().rstrip().split()))
for ratio in plus_minus(array):
print(ratio)
|
"""
Dictionary examples.
The intention is that you would use the code in the functions rather
than the functions themselves.
"""
def create_dict():
"""
Create a new dictionary.
Example from: https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
"""
return dict()
def copy_dict(other_dict):
"""
Returns a copy of the dictionary, separate from the original.
This separation is only at the top-level keys.
If you delete a key in the original, it will not change the copy.
>>> d1 = dict(a=1, b=2)
>>> d2 = dict(**d1)
>>> del d1['a']
>>> 'a' in d1
False
>>> 'a' in d2
True
If any of the top-level values are mutable (list, dict) then changes
to the original will appear in the copy.
>>> d1 = dict(a=[1, 2], b=[3, 4])
>>> d2 = dict(**d1)
>>> d1['a'].pop()
2
>>> d1['a']
[1]
>>> d1['a'] == d2['a']
True
Tested in Python 3.4.
"""
new_dict = dict(**other_dict)
return new_dict
def update_dict(original, other):
"""
Update the original dict with values from the other.
If you delete a key in the other, it will not change the original.
>>> d1 = dict(a=1)
>>> d2 = dict(b=2)
>>> d1
{'a': 1}
>>> d2
{'b': 2}
>>> d1.update(d2)
>>> d1
{'a': 1, 'b': 2}
>>> d2
{'b': 2}
Tested in Python 3.4.
"""
original.update(other)
return original
|
# Heap
# CLRS Chapter 6 Page 152, 154, 157, 163, 164
# For CPython's implementation see:
# https://hg.python.org/cpython/file/2.7/Lib/heapq.py
def max_heapify(heap, node):
left = _left(node)
right = _right(node)
largest = node
if left < size(heap) and heap[largest] < heap[left]:
largest = left
if right < size(heap) and heap[largest] < heap[right]:
largest = right
if largest != node:
_swap(heap, node, largest)
max_heapify(heap, largest)
def build_max_heap(heap):
# Run max_heapify buttom-up.
for node in reversed(range((len(heap) - 1) // 2 + 1)):
max_heapify(heap, node)
return heap
def remove_last(heap):
return heap.pop()
def remove(heap, node):
if node >= size(heap):
raise Exception("Node does not exist in the heap.")
# Swap the item with the last item if needed.
last = size(heap) - 1
if node != last:
_swap(heap, node, last)
# Remove the last item.
item = remove_last(heap)
# Fix the heap property.
max_heapify(heap, node)
return item
def remove_top(heap):
return remove(heap, _root())
def decrease_key(heap, node, item):
if heap[node] < item:
raise Exception("The new key is lsrger than the current key.")
heap[node] = item
_move_down(heap, node)
def increase_key(heap, node, item):
if item < heap[node]:
raise Exception("The new key is smaller than the current key.")
heap[node] = item
_move_up(heap, node)
def insert(heap, item):
# Put the item at the end.
node = size(heap)
heap.append(item)
_move_up(heap, node)
def top(heap):
"""Returns the top item in the heap."""
return heap[_root()]
def size(heap):
"""The number of items in the heap."""
return len(heap)
def empty(heap):
"""Check if the heap is empty."""
return size(heap) == 0
def _swap(heap, i, j):
"""Swaps nodes i and j in heap."""
heap[i], heap[j] = heap[j], heap[i]
def _parent(node):
"""Parent of a node. The root points to itself."""
if node == _root():
return _root()
return (node + 1) // 2 - 1
def _left(node):
"""The _left child of a node."""
return 2 * node + 1
def _right(node):
"""The right child of a node."""
return 2 * node + 2
def _root():
"""Returns the root node."""
return 0
def _move_down(heap, node):
# Move down the item as long as needed.
# This is an iterative version of max_heapify.
while node < size(heap):
left = _left(node)
right = _right(node)
largest = node
if left < size(heap) and heap[largest] < heap[left]:
largest = left
if right < size(heap) and heap[largest] < heap[right]:
largest = right
if largest == node:
break
_swap(heap, node, largest)
node = largest
def _move_up(heap, node):
# Move up the item as long as needed.
while node != _root() and heap[_parent(node)] < item:
_swap(heap, node, _parent(node))
node = _parent(node)
|
def ascii(arg): pass
def filter(pred, iterable): pass
def hex(arg): pass
def map(func, *iterables): pass
def oct(arg): pass
|
n = int(input('Escreva um numero inteiro: '))
resto = n % 2
if resto == 0:
print('O seu numero é par!')
else:
print('O seu numero é impar!')
|
galera = [['João', 19], ['Ana', 33], ['Joaquim', 13], ['Maria', 45]]
print(galera[0])
print(galera[0][0])
print(galera[2][1])
for p in galera:
print(p)
for p in galera:
print(p[0])
for p in galera:
print(p[1])
for p in galera:
print(f'{p[0]} tem {p[1]} anos de idade!')
|
#!/usr/bin/python3
'''General Class which is used for all the class
'''
class GeneralSeller:
def __init__(self,mechant_i):
pass
def start_product(self):
pass
class WishSeller(GeneralSeller):
'''
'''
class AmazonSeller(GeneralSeller):
pass
class AlibabaSeller(GeneralSeller):
pass
class EbaySeller(GeneralSeller):
pass
class DhgateSeller(GeneralSeller):
pass
|
# Python使用被称为异常的特殊对象来管理程序执行期间发生的错误.
# 每当发生让Python不知所措的错误时, 它都会创建一个异常对象.
# 如果你编写了处理该异常的代码, 程序将继续运行;
# 如果你未对异常进行处理, 程序将停止, 并显示一个traceback, 其中包含有关异常的报告.
# 处理ZeroDivisionError异常
try:
print(5 / 0)
except ZeroDivisionError:
print('除数不能为零.')
# else代码块
# try-except后包含else代码块, 依赖于try代码块成功执行的代码都应放到else代码块中
print('\n')
print('请输入两个数, 我们将对它们进行除法操作: ')
print("输入'q'退出. ")
while True:
first_number = input('\n请输入第一个数: ')
if first_number == 'q':
break
second_number = input('请输入第二个数: ')
if second_number == 'q':
break
try: # 包含可能会发生错误的程序代码
answer = int(first_number) / int (second_number)
except ZeroDivisionError: # 捕捉有可能出现的程序异常
print('第二个数(除数)不能为0.')
else: # 如果程序没有发生异常, 则else包含所有正常执行的代码
print(first_number + ' / ' + second_number + ' = ' + str(answer))
# 处理FileNotFoundError异常
print('\n')
filename = 'alice.txt'
try:
with open(filename) as file_content: # 这个as之后的变量名并非固定为file_object
contents = file_content.read()
except FileNotFoundError:
print('对不起, 文件' + filename + '不存在!')
else:
words = contents.split() # contents在这里也可以被使用, 说明contents的作用域不止try-except范围
words_num = len(words)
print('文件' + filename + '中总共包含' + str(words_num) + '个单词.')
# 使用多个文件
def count_words(filename): # 先定义一个计算文件含多少个单词的函数
"""计算一个文件中包含多少个单词"""
try:
with open(filename) as file_content: # 这个as之后的变量名并非固定为file_object
contents = file_content.read()
except FileNotFoundError:
print('对不起, 文件' + filename + '不存在!')
# pass # pass表示程序发现错误之后, 什么都不做
else:
words = contents.split() # contents在这里也可以被使用, 说明contents的作用域不止try-except范围
words_num = len(words)
print('文件' + filename + '中总共包含' + str(words_num) + '个单词.')
print('\n')
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames: # 处理异常的好处: siddhartha.txt文件不存在, 但是不影响其他后续其他文件的计算
count_words(filename)
# 失败时一声不吭
# 并非每次捕获到异常时都需要告诉用户, 有时候你希望程序在发生异常时一声不吭,
# 就像什么都没有发生一样继续运行.
# 要让程序在失败时一声不吭, 可像通常那样编写try代码块,
# 但在except代码块中明确地告诉Python什么都不要做.
# Python有一个pass语句, 可在代码块中使用它来让Python什么都不要做.
# pass语句还充当了占位符, 它提醒你在程序的某个地方什么都没有做, 并且以后也许要在这里做些什么
# 有点像Java里的TODO标识
# Python有没有像Java中的Exception和Throwable这样的顶级异常?
|
upTo = int(input())
res = 0
for i in range(upTo):
res += i
print(res)
|
class Solution(object):
def intersect(self, nums1, nums2):
nums1_counter = collections.Counter(nums1)
nums2_counter = collections.Counter(nums2)
result = []
for k in nums1_counter.keys():
if k in nums2_counter:
result.extend([k] * min(nums1_counter[k], nums2_counter[k]))
return result
|
class CandidateViewer:
def __init__(self, df):
self.df = df
def show_candidates(self):
best_players_selections = ['2 players', '3 players', '4 players', '5 or more players']
weight_selections = [(1, 1.4), (1.5, 1.9), (1.9, 2.5), (2.5, 3.1), (3.1, 4)]
cols = ['title', 'year', 'weight', 'best_for', 'final_score', 'category-cluster',
'mechanics-cluster', 'url']
for n_players in best_players_selections:
for weight_range in weight_selections:
selection = (self.df['best_for'] == n_players) & (self.df['weight'] >= weight_range[0]) & \
(self.df['weight'] <= weight_range[1]) & (self.df['year'] >= 2000) & (self.df['weight_votes'] >= 10) & \
(self.df['final_score'] >= 15)
print('Weight: {} to {} - Best for {}'.format(weight_range[0], weight_range[1], n_players))
print('-'*80)
selected = self.df[selection][cols].sort_values('final_score', ascending=False).head(10)
for idx, row in selected.iterrows():
print('{:<35} ({}) - {:.2f}, {}, {:.1f}, Cat: {}, Mech: {}\n\t\t{}'\
.format(row['title'][:35], row['year'], row['weight'], row['best_for'], row['final_score'],
row['category-cluster'][0], row['mechanics-cluster'][0], row['url']))
print('\n\n')
|
def main():
q = int(input())
pre = [
3, 5, 13, 37, 61, 73, 157, 193, 277, 313, 397, 421, 457, 541, 613, 661, 673, 733, 757, 877, 997, 1093, 1153, 1201, 1213, 1237, 1321, 1381, 1453, 1621, 1657, 1753, 1873, 1933, 1993, 2017, 2137, 2341, 2473, 2557, 2593, 2797, 2857, 2917,
3061, 3217, 3253, 3313, 3517, 3733, 4021, 4057, 4177, 4261, 4273, 4357, 4441, 4561, 4621, 4933, 5077, 5101, 5113, 5233, 5413, 5437, 5581, 5701, 6037, 6073, 6121, 6133, 6217, 6337, 6361, 6373, 6637, 6661, 6781, 6997, 7057, 7213, 7393, 7417, 7477, 7537, 7753, 7933, 8053, 8101, 8221, 8317, 8353, 8461, 8521, 8677, 8713, 8893, 9013, 9133, 9181, 9241, 9277,
9601, 9661, 9721, 9817, 9901, 9973, 10333, 10357, 10453, 10837, 10861, 10957, 11113, 11161, 11317, 11497, 11677, 11701, 12073, 12157, 12241, 12301, 12421, 12433, 12457, 12541, 12553, 12601, 12721, 12757, 12841, 12853, 13093, 13381, 13417, 13681, 13921, 13933, 14437, 14593, 14737, 14821, 15013, 15073, 15121, 15241, 15277, 15361, 15373, 15733, 15901, 16033, 16333, 16381, 16417, 16573, 16633, 16657, 16921, 17041, 17053, 17077, 17257, 17293, 17377, 17881, 18013, 18097, 18133, 18181, 18217, 18253, 18301, 18313, 18397, 18481, 18553, 18637, 18793, 19237, 19441, 19477, 19717, 19801, 19813, 19861, 20353, 20533, 20641, 20857, 21001, 21061, 21193, 21277, 21313, 21577, 21661, 21673, 21817, 22093, 22501, 22573,
22621, 22993, 23053, 23173, 23557, 23677, 23773, 23917, 24097, 24421, 24481, 24781, 24841, 25033, 25153, 25237, 25561, 25657, 25933, 26017, 26293, 26317, 26437, 26497, 26821, 26833, 26881, 26953, 27073, 27253, 27337, 27361, 27457, 27997, 28057, 28297, 28393, 28813, 28837, 28921, 29101, 29473, 29641, 30181, 30241, 30517, 30553, 30577, 30637, 30661, 30697, 30781, 30853, 31081, 31237, 31321, 31333, 31357, 31477, 31573, 31873, 31981, 32173, 32377, 32497, 32533, 32833, 33037, 33301, 33457, 33493, 33757, 33961, 34057, 34213, 34273, 34381, 34513, 34897, 34981, 35317, 35521, 35677, 35977, 36097, 36241, 36433, 36457, 36793, 36877, 36901, 36913, 37273, 37321, 37357, 37573, 37717, 37957, 38281, 38461, 38833, 38953, 38977, 39217, 39373, 39397, 39733, 40093, 40177, 40213, 40693, 40813, 41017, 41221, 41281, 41413, 41617, 41893,
42061, 42337, 42373, 42793, 42961, 43117, 43177, 43201, 43321, 43573, 43597, 43633, 43717, 44053, 44101, 44221, 44257, 44293, 44893, 45061, 45337, 45433, 45481, 45553, 45613, 45841, 46021, 46141, 46261, 46861, 46993, 47017, 47161, 47353, 47521, 47533, 47653, 47713, 47737, 47797, 47857, 48121, 48193, 48337, 48673, 48757, 48781, 49033, 49261, 49393, 49417, 49597, 49681, 49957, 50221, 50341, 50377, 50821, 50893, 51157, 51217, 51241, 51481, 51517, 51637, 52057, 52081, 52237, 52321, 52453, 52501, 52813, 52861, 52957, 53077, 53113, 53281, 53401, 53917, 54121, 54133, 54181, 54217, 54421, 54517, 54541, 54673, 54721, 54973, 55057, 55381, 55501, 55633, 55837, 55921, 55933, 56053, 56101, 56113, 56197, 56401, 56437, 56701, 56773, 56821, 56857, 56893, 57073, 57097, 57193, 57241, 57373, 57457, 57853, 58153, 58417, 58441, 58537,
58573, 58693, 59053, 59197, 59221, 59281, 59341, 59833, 60217, 60337, 60373, 60637, 60733, 60937, 61057, 61153, 61261, 61297, 61561, 61657, 61681, 61717, 61861, 62137, 62473, 62497, 62533, 62653, 62773, 63313, 63397, 63541, 63697, 63781, 63913, 64153, 64237, 64381, 64513, 64717, 65173, 65293, 65413, 65437, 65497, 65557, 65677, 65881, 66301, 66361, 66601, 66697, 66853, 66973, 67057, 67153, 67273, 67477, 67537, 67741, 67777, 67933, 67993, 68113, 68281, 68521, 68737, 69001, 69073, 69457, 69493, 69697, 69877, 70117, 70177, 70297, 70501, 70621, 70921, 70981, 71233, 71341, 71353, 71593, 71821, 72073, 72481, 72613, 72901, 72937, 73141, 73417, 73477, 73561, 73693, 74077, 74317, 74377, 74713, 75013, 75133, 75181, 75721, 75793, 75913, 76333, 76561, 76597, 76753, 77137, 77641, 78157, 78193, 78277, 78877, 78901, 79333, 79357,
79537, 79657, 79693, 79801, 79873, 80077, 80173, 80221, 80473, 80701, 80713, 80917, 81013, 81181, 81517, 81637, 81853, 82021, 82153, 82261, 82561, 82981, 83077, 83221, 83233, 83437, 83617, 83701, 83773, 84121, 84313, 84673, 84697, 84793, 84913, 85297, 85333, 85453, 85717, 85933, 86353, 86413, 87181, 87253, 87337, 87421, 87433, 87517, 87553, 87973, 88117, 88177, 88237, 88261, 88513, 88741, 88897, 88993, 89293, 89833, 89917, 90121, 91081, 91381, 91393, 91513, 91957, 92041, 92557, 92761, 92821, 92893, 92941, 93097, 93133, 93493, 93637, 93913, 94033, 94117, 94273, 94321, 94441, 94573, 94777, 94837, 94993, 95257, 95317, 95401, 95581, 95617, 95713, 95737, 96097, 96157, 96181, 96493, 96517, 96973, 97081, 97177, 97501, 97561, 97777, 97813, 98017, 98737, 98953, 99277, 99577, 99661, 99877
]
for _ in range(q):
l,r = map(int,input().split())
ans = 0
for e in pre:
if e > r:
break
if e >= l:
ans += 1
print(ans)
if __name__ == "__main__":
main()
|
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
#
# @AUTHOR: Rabbir
# @FILE: /root/GitHub/rab_steam_packages/module/info.py
# @DATE: 2021/05/21 Fri
# @TIME: 16:46:52
#
# @DESCRIPTION: Steam 账户信息模块
"""
@description: Steam 账户信息类
-------
@param:
-------
@return:
"""
class r_steam_info():
pass
|
# pkg.mod
# descr
#
# Author: Benjamin Bengfort <[email protected]>
# Created: timestamp
#
# Copyright (C) 2013 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: __init__.py [] [email protected] $
"""
"""
##########################################################################
## Imports
##########################################################################
|
class FileListing:
dictionary: dict
def __init__(self, dictionary: dict):
self.dictionary = dictionary
def __eq__(self, other):
return self.dictionary == other.dictionary
def __repr__(self):
return {'dictionary': self.dictionary}
@property
def tenant(self):
return self.dictionary.get("tenant")
@property
def file_path(self):
return self.dictionary.get("filePath")
@property
def last_modified(self):
return self.dictionary.get("lastModified")
@property
def size(self):
return self.dictionary.get("size")
|
# Builds
#T# Table of contents
#C# Compiling to bytecode
#C# Building a project to binary
#T# Beginning of content
#C# Compiling to bytecode
# |-------------------------------------------------------------
#T# Python code is compiled from .py source code files, to .pyc bytecode files
#T# in the operating system shell, the py_compile script can be run to compile a .py file into .pyc
# SYNTAX python3 -m py_compile script1.py
#T# the script1.py is compiled, python3 is the Python executable, -m is a Python option to run py_compile (see the file titled Interpreter)
#T# the output file is stored in a directory named __pycache__/ under the directory of script1.py, named something like __pycache__/script1.cpython-38.pyc, the cpython-38 part of the name stands for the Python version, in this case version 3.8
#T# in the operating system shell, a compiled .pyc file can be executed like a source code script
# SYNTAX python3 __pycache__/script1.cpython-38.pyc
#T# python3 is the Python executable, this syntax executes script1.cpython-38.pyc which gives the same output as executing script1.py
# |-------------------------------------------------------------
#C# Building a project to binary
# |-------------------------------------------------------------
#T# a Python project is formed by several related Python files whose execution starts at a main file, a project can be built into a binary executable so that the whole project resides in a single file, which doesn't depend on the Python interpreter to be executed
#T# in the operating system shell, the PyInstaller module can be executed to build a Python project (it can be installed with pip)
# SYNTAX pyinstaller --onefile main1.py dir1/module1.py dir1/dir1_1/script1.py
#T# this creates an executable file named main1 in a directory under the working directory named dist/, so the executable file is dist/main1, the --onefile option makes it so that dist/ only contains one file
print("Built")
# |-------------------------------------------------------------
|
def get_profile(name, age: int, *sports, **awards):
if type(age) != int:
raise ValueError
if len(sports) > 5:
raise ValueError
if sports and not awards:
sports = sorted(list(sports))
return {'name': name, 'age': age, 'sports': sports}
if not sports and awards:
return {'name': name, 'age': age, 'awards': awards}
if not sports and not awards:
return {'name': name, 'age': age}
sports = sorted(list(sports))
return {'name': name, 'age': age, 'sports': sports, 'awards': awards}
pass
|
a = int(input("a= "))
b = int(input("b= "))
c = int(input("c= "))
if a == 0:
if b != 0:
print("La solution est", -c / b)
else:
if c == 0:
print("INF")
else:
print("Aucune solution")
else:
delta = (b ** 2) - 4 * a * c
if delta > 0:
print(
"Les deux solutions sont ",
(- b - (delta ** 0.5)) / (2 * a),
"et",
(- b + (delta ** 0.5)) / (2 * a),
)
elif delta == 0:
print("La solution est", -b / (2 * a))
else:
print("Pas de solutions reelles")
|
# -*- coding: utf-8 -*-
"""
Solution to Project Euler problem 6
Author: Jaime Liew
https://github.com/jaimeliew1/Project_Euler_Solutions
"""
def run():
N = 100
return sum(i for i in range(N+1))**2 - sum(i**2 for i in range(N+1))
if __name__ == "__main__":
print(run())
|
# --
# Copyright (c) 2008-2021 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
# --
class SessionError(LookupError):
def name(self):
return self.__class__.__name__
# =================================================================================
class CriticalSessionError(SessionError):
pass
class LockError(CriticalSessionError):
"""Raised when an exclusive lock on a session can't be acquired
"""
pass
class StateError(CriticalSessionError):
"""Raise when a state can't be deserialized
'"""
pass
class StorageError(CriticalSessionError):
"""Raised when the serialized session can't be stored / retreived
"""
pass
# =================================================================================
class InvalidSessionError(SessionError):
pass
class ExpirationError(InvalidSessionError):
"""Raised when a session or a state id is no longer valid
"""
pass
class SessionSecurityError(InvalidSessionError):
"""Raised when the secure id of a session is not valid
"""
pass
|
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
s = set()
for v in arr:
if v * 2 in s or (v % 2 == 0 and v / 2 in s): return True
s.add(v)
return False
|
n = int(input("Dame un numero entero: "))
def factorial( n ):
if n == 1:
return n
else:
#llamada recursiva
return n * factorial( n - 1 )
print("El factorial de: ",n,"es", factorial(n))
|
#!/bin/python3
rd = open("06.input", "r")
fullSum = 0
validLetters = {"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" }
while True:
letters = {}
count = 0
while True:
line = rd.readline().strip()
if not line or line == "":
break
count += 1
for c in line:
if c in validLetters:
if c in letters:
letters[c] += 1
else:
letters[c] = 1
if len(letters) == 0:
break
for key in letters.keys():
if letters[key] == count:
fullSum += 1
print(fullSum)
|
'''
done
'''
ipAddress = '127.0.0.1'
port = 21
name = "Pustakalupi"
pi = 3.14 #tidak ada constant dalam Python 3
print("ipAddress bertipe :", type(ipAddress))
print("port bertipe :", type(port))
print("name bertipe :", type(name))
print("pi bertipe :", type(pi))
print(pi)
del pi
print(pi)
|
class Originator:
_state = None
class Memento:
def __init__(self, state):
self._state = state
def setState(self, state):
self._state = state
def getState(self):
return self._state
def __init__(self, state = None):
self._state = state
def set(self, state):
if state != None:
self._state = state
def createMemento(self):
return self.Memento(self._state)
def restore(self, memento):
self._state = memento.getState()
return self._state
class Caretaker:
pointer = 0
savedStates = []
def saveMemento(self, element):
self.pointer += 1
self.savedStates.append(element)
def getMemento(self, index):
return self.savedStates[index-1]
def undo(self):
if self.pointer > 0:
self.pointer -= 1
return self.getMemento(self.pointer)
else:
return None
def redo(self):
if self.pointer < len(self.savedStates):
self.pointer += 1
return self.getMemento(self.pointer)
else:
return None
caretaker = Caretaker()
originator = Originator()
#Testing code
originator.set("Message")
caretaker.saveMemento(originator.createMemento())
print(originator.restore(caretaker.getMemento(caretaker.pointer)))
originator.set("Typo")
caretaker.saveMemento(originator.createMemento())
print(originator.restore(caretaker.getMemento(caretaker.pointer)))
originator.set(caretaker.undo())
print(originator.restore(caretaker.getMemento(caretaker.pointer)))
originator.set(caretaker.redo())
print(originator.restore(caretaker.getMemento(caretaker.pointer)))
|
# please excuse me, I'm a C# and Rust developer with only minor Python experience :D
# let's give it a go though!
MAP = {
'a': "100000", 'n': "101110",
'b': "110000", 'o': "101010",
'c': "100100", 'p': "111100",
'd': "100110", 'q': "111110",
'e': "100010", 'r': "111010",
'f': "110100", 's': "011100",
'g': "110110", 't': "011110",
'h': "110010", 'u': "101001",
'i': "010100", 'v': "111001",
'j': "010110", 'w': "010111",
'k': "101000", 'x': "101101",
'l': "111000", 'y': "101111",
'm': "101100", 'z': "101011",
' ': "000000"
}
def solution(s):
mapped = []
for c in s:
if c.isupper():
# upper-case escape string
mapped.append("000001")
mapped.append(MAP[c.lower()])
return "".join(mapped)
if __name__ == "__main__":
assert solution("The quick brown fox jumps over the lazy dog") == "000001011110110010100010000000111110101001010100100100101000000000110000111010101010010111101110000000110100101010101101000000010110101001101100111100011100000000101010111001100010111010000000011110110010100010000000111000100000101011101111000000100110101010110110"
|
class _Node:
"""Private class to create a nodes for the tree"""
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.next = None
class Queue:
"""class Queue which implements Queue data structure with its common methods"""
def __init__(self):
"""Initiate class"""
self.front = None
self.rear = None
def is_empty(self):
"""method to check if Queue is empty"""
if self.front == None:
return True
return False
def enqueue(self, node):
"""Method that takes any value as an argument and adds a new node with that value to the back of the queue """
new_node = node
if self.is_empty():
self.front = new_node
self.rear = new_node
else:
self.rear.next = new_node
self.rear = new_node
def dequeue(self):
"""Method that removes the node from the front of the queue, and returns the node’s value."""
if not self.is_empty():
temp = self.front
self.front = self.front.next
temp.next = None
return temp
else:
return None
def peek(self):
"""Method that returns the value of the node located in the front of the queue, without removing it from the queue."""
if not self.is_empty():
return self.front.value
return None
class BinaryTree:
"""Class to create a binary tree"""
def __init__(self):
self._root = None
def pre_order(self, node=None, arr = None):
"""Method to return an array of trre values in "pre-order" order"""
if arr is None:
arr = []
node = node or self._root
arr.append(node.value)
if node.left:
self.pre_order(node.left, arr)
if node.right:
self.pre_order(node.right, arr)
return arr
def in_order(self, node=None, arr = None):
"""Method to return an array of tree values "in-order" """
if arr is None:
arr = []
node = node or self._root
if node.left:
self.in_order(node.left, arr)
arr.append(node.value)
if node.right:
self.in_order(node.right, arr)
return arr
def post_order(self, node=None, arr = []):
"""Method to return an array of tree values "post-order" """
node = node or self._root
if node.left:
self.post_order(node.left, arr)
if node.right:
self.post_order(node.right, arr)
arr.append(node.value)
return arr
@staticmethod
def breadth_first(tree, node = None, array = None):
""" A static method which takes a Binary Tree as its unique input, traversing the input tree using a Breadth-first approach, and returns a list of the values in the tree in the order they were encountered."""
q = Queue()
if array is None:
array = []
if tree._root:
q.enqueue(tree._root)
while q.peek():
node_front = q.dequeue()
array.append(node_front.value)
if node_front.left:
q.enqueue(node_front.left)
if node_front.right:
q.enqueue(node_front.right)
return array
def find_maximum_value(self):
""" An instance method that returns the maximum value stored in the tree"""
q = Queue()
if not self._root:
return None
max_ = self._root.value
q.enqueue(self._root)
while not q.is_empty():
node_front = q.dequeue()
max_ = max(max_, node_front.value)
if node_front.left:
q.enqueue(node_front.left)
if node_front.right:
q.enqueue(node_front.right)
return max_
class myException(Exception):
pass
|
"""
252. Meeting Rooms
Easy
Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings.
Example 1:
Input: intervals = [[0,30],[5,10],[15,20]]
Output: false
Example 2:
Input: intervals = [[7,10],[2,4]]
Output: true
Constraints:
0 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti < endi <= 106
"""
# Time: O(nlogn)
# Space: O(n)
#
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
# V0
class Solution:
def canAttendMeetings(self, intervals):
"""
NOTE this
"""
intervals.sort(key=lambda x: x[0])
for i in range(1, len(intervals)):
"""
NOTE this :
-> we compare ntervals[i][0] and ntervals[i-1][1]
"""
if intervals[i][0] < intervals[i-1][1]:
return False
return True
# V0'
# IDEA : SORT
class Solution(object):
def canAttendMeetings(self, intervals):
# edge case
if not intervals or len(intervals) == 1:
return True
intervals.sort(key = lambda x : [x[0], -x[1]])
if len(intervals) == 2:
return intervals[0][0] < intervals[1][0] and intervals[0][1] < intervals[1][1]
last = intervals[0]
for i in range(1, len(intervals)):
# CASE 1 : last and intervals[i] overlap (3 situations)
if (last[1] > intervals[i][0] and intervals[i][0] < last[1]) or\
(last[0] == intervals[i][0] and last[1] == intervals[i][1]) or\
(last[0] < intervals[i][1] and last[1] > intervals[i][1]):
return False
# CASE 2 : last and intervals[i] NOT overlap
else:
last = intervals[i]
return True
# V1
class Solution:
# @param {Interval[]} intervals
# @return {boolean}
def canAttendMeetings(self, intervals):
intervals.sort(key=lambda x: x[0])
for i in range(len(intervals)-1):
if intervals[i][1] > intervals[i+1][0]:
return False
return True
# V1'
# IDEA : BRUTE FORCE
# https://leetcode.com/problems/meeting-rooms/solution/
# JAVA
# public static boolean overlap(int[] interval1, int[] interval2) {
# return (Math.min(interval1[1], interval2[1]) >
# Math.max(interval1[0], interval2[0]));
# }
# V1''
# IDEA : SORTING
# https://leetcode.com/problems/meeting-rooms/solution/
class Solution:
def canAttendMeetings(self, intervals):
intervals.sort()
for i in range(len(intervals) - 1):
if intervals[i][1] > intervals[i + 1][0]:
return False
return True
# V1''''
# https://blog.csdn.net/qq508618087/article/details/50750465
class Solution(object):
def canAttendMeetings(self, v):
"""
:type intervals: List[Interval]
:rtype: bool
"""
v.sort(key = lambda val: val.start)
return not any(v[i].start < v[i-1].end for i in range(1,len(v)))
# V1''''
# https://www.jiuzhang.com/solution/meeting-rooms/
# JAVA
# public class Solution {
# public boolean canAttendMeetings(Interval[] intervals) {
# if(intervals == null || intervals.length == 0) return true;
# Arrays.sort(intervals, new Comparator<Interval>(){
# public int compare(Interval i1, Interval i2){
# return i1.start - i2.start;
# }
# });
# int end = intervals[0].end;
# for(int i = 1; i < intervals.length; i++){
# if(intervals[i].start < end) {
# return false;
# }
# end = Math.max(end, intervals[i].end);
# }
# return true;
# }
# }
# V2
class Solution:
# @param {Interval[]} intervals
# @return {boolean}
def canAttendMeetings(self, intervals):
intervals.sort(key=lambda x: x.start)
for i in range(1, len(intervals)):
if intervals[i].start < intervals[i-1].end:
return False
return True
|
# Desafio066: Desafio criar um programa que leia varios numeros de o valor total digitado e pare quando digitado 999.
nu = int (0)
controle = int(0)
print('Se precisar sair digite 999')
while True:
nu = int(input('Digite um numero '))
if nu == 999:
break
controle = controle + nu
print(controle)
|
__author__ = 'tony petrov'
DEFAULT_SOCIAL_MEDIA_CYCLE = 3600 # 1 hour since most social media websites have a 1 hour timeout
# tasks
TASK_EXPLORE = 0
TASK_BULK_RETRIEVE = 1
TASK_FETCH_LISTS = 2
TASK_FETCH_USER = 3
TASK_UPDATE_WALL = 4
TASK_FETCH_STREAM = 5
TASK_GET_DASHBOARD = 6
TASK_GET_TAGGED = 7
TASK_GET_BLOG_POSTS = 8
TASK_GET_FACEBOOK_WALL = 9
TASK_FETCH_FACEBOOK_USERS = 10
TASK_TWITTER_SEARCH = 11
TOTAL_TASKS = 12
# twitter control constants
POLITENESS_VALUE = 0.5 # how long the worker should sleep for used to prevent twitter from getting overloaded
TWITTER_MAX_LIST_SIZE = 5000
TWITTER_MAX_NUMBER_OF_LISTS = 900 #can be changed to 1000 but retrieval of tweets from all lists not guaranteed
TWITTER_MAX_NUMBER_OF_NON_FOLLOWED_USERS = 900
TWITTER_BULK_LIST_SIZE = 100
TWITTER_MAX_NUM_OF_BULK_LISTS_PER_REQUEST_CYCLE = 900
TWITTER_MAX_NUM_OF_REQUESTS_PER_CYCLE = 180
TWITTER_MAX_FOLLOW_REQUESTS = 10
TWITTER_ADD_TO_LIST_LIMIT = 100
MAX_TWITTER_TRENDS_REQUESTS = 15
TWITTER_CYCLES_PER_HOUR = 4
TWITTER_CYCLE_DURATION = 15
RUNNING_CYCLE = 900 # 15*60seconds
MAX_TWEETS_PER_CYCLE = 25
MAX_TRACKABLE_TOPICS = 400
MAX_FOLLOWABLE_USERS = 5000
# tumblr control
TUMBLR_MAX_REQUESTS_PER_DAY = 5000
TUMBLR_MAX_REQUESTS_PER_HOUR = 250
# facebook control
FACEBOOK_MAX_REQUESTS_PER_HOUR = 200
# storage locations
TWITTER_BULK_LIST_STORAGE = 'data/twitter/bulk_lists'
TWITTER_LIST_STORAGE = 'data/twitter/lists'
TWITTER_USER_STORAGE = 'data/twitter/users'
TWITTER_WALL_STORAGE = 'data/twitter/home'
TWITTER_CANDIDATES_STORAGE = 'data/twitter/remaining'
TWITTER_CREDENTIALS = 'data/twitter/login'
PROXY_LOCATION = 'data/proxies'
RANKING_FILTER_CLASSIFIER = 'data/classifier'
RANKING_FILTER_TOPIC_CLASSIFIER = 'data/topic_classifier'
# Model names
TWITTER_STREAMING_BUCKET_MODEL = 'stream'
TWITTER_CYCLE_HARVESTER = 'harvester'
TWITTER_HYBRID_MODEL = 'hybrid'
TWITTER_STREAMING_HARVESTER_NON_HYBRID = 'both'
# Service plugins
CRAWLER_PLUGIN_SERVICE = 1 # redirect all outputs to the plugin
TWITTER_PLUGIN_SERVICE = 100 # redirect output from all twitter crawler models to the plugin
TWITTER_HARVESTER_PLUGIN_SERVICE = 101 # redirect output from the twitter model to the plugin
TWITTER_STREAMING_PLUGIN_SERVICE = 102 # redirect output from the twitter stream api to the plugin
TUMBLR_PLUGIN_SERVICE = 103 # redirect tumblr output to plugin
FACEBOOK_PLUGIN_SERVICE = 104 # redirect facebook output to plugin
# Ranking Classifiers
PERCEPTRON_CLASSIFIER = 201
DEEP_NEURAL_NETWORK_CLASSIFIER = 202
K_MEANS_CLASSIFIER = 203
# other control constants and variables
TESTING = False
EXPLORING = False
COLLECTING_DATA_ONLY = False
RANK_RESET_TIME = 600 # every 10 mins
TIME_TO_UPDATE_TRENDS = 0
FILTER_STREAM = False
FRESH_TWEETS_ONLY = False # set to true to reduce the number of overlapping tweets
PARTITION_FACTOR = 0.5
TWITTER_ACCOUNTS_COUNT = 1
MIN_TWITTER_STATUSES_COUNT = 150
|
class Professor:
def __init__(self, nome):
self.__nome = nome #conceito de encapusulamento
self.__salaDeAula = None
def nome(self):
return self.__nome
def salaDeAula(self, sala):
self.__salaDeAula = sala
def EmAula(self):
return 'Em aula'
class Sala:
def __init__(self, numero):
self.__numero = numero
def numero(self):
return self.__numero
def FecharSala(self):
return 'Porta foi fechada!'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def init():
pass
def servers():
return {}
|
def processArray(l2):
loss=[];mloss=0
for i in range(0,len(l2)):
loss.append(l2[i][0]-l2[i][len(l2[i])-1])
if(len(loss)>0):
mloss=loss.index(max(loss))
print(len(l2[mloss]))
l=[]
while True:
a=int(input())
if(a<0):
break
l.append(a)
ans=[]
i=0
while(i<len(l)):
k=l[i]
tmp=[]
tmp.append(l[i])
for j in range(i+1,len(l)):
if(l[j]>k):
break
else:
tmp.append(l[j])
k=l[j]
i=j+1
print(tmp)
if(len(tmp)>1):
ans.append(tmp)
processArray(ans)
|
class Solution:
def hammingWeight(self, n: int) -> int:
n = bin(n)[2:]
str_n = str(n)
return str_n.count("1")
|
print('{:=^40}'.format(' lojas guanabara '))
p=float(input(' preço do produto'))
print(p)
print('escolha a opção de pagamento')
pag=int(input('''[1] á vista com cheque/dinheiro;
[2] á vista no cartão;
[3] 2x no cartão;
[4] 3x ou mais no cartão; '''))
print(pag)
if pag == 1:
print('valor á pagar R$ {} com 10% de desconto'.format(p-(p*10)/100))
elif pag == 2:
print('o valor a pagar é R$ {} com 5% de desconto'.format(p-(p*5/100)))
elif pag == 3:
print('ovalor a ser pago é R$ {}'.format( p))
elif pag == 4:
p=p+(p*20/100)
totpar=int(input('quantas parcelas?'))
parcela=p/totpar
print('sua compra sera parcelada em {}x de R$ {}'.format(totpar,parcela))
print('o valor final a ser pago é R$ {} com 20% de juros'.format(p))
else:
pag >= 5
print('opção invalida!')
|
def coordinate_input():
x, y = input("X, Y Coordinates ==> ").strip().split(",")
return float(x), float(y)
def main():
coordinates = []
print("Type the coordinates in order; it means A,B,C...")
while True:
try:
point = coordinate_input()
coordinates.append(point)
except:
break
sumatory = 0
for index, point in enumerate(coordinates):
if index == len(coordinates) - 1:
sumatory += point[0] * coordinates[0][1] - point[1] * coordinates[0][0]
else:
sumatory += point[0] * coordinates[index+1][1] - point[1] * coordinates[index+1][0]
print("Area:", abs(sumatory / 2))
if __name__ == '__main__':
main()
|
''' Exemplo 1
c = 1
while c < 11:
print(c)
c += 1
print('Fim')
'''
'''eXEMPLO 2
n = 1
while n!= 0:
n = int(input('Digite um valor: '))
print('Fim') '''
''' Exemplo 3
r = 'S'
while r == 'S':
n = int(input('Digite um valor: '))
r = str(input('Quer continuar? [S/N] ')).upper()
print('Fim')'''
''' Exemplo 4
n = 1
par = impar = 0
while n != 0:
n = int(input('Digite um numero: '))
if n != 0:
if n % 2 == 0:
par +=1
else:
impar += 1
print('Voce digitou {} numeros pares e {} numeros impares!'.format(par, impar))'''
'''Exemplo 5
from random import randint
computador = randint(1, 10)
print('Sou seu computador... Acabei de pensar em um numero entre 0 e 10.')
acertou = False
palpites = 0
while not acertou:
jogador = int(input('Qual o seu palpite: '))
palpites += 1
if jogador == computador:
acertou = True
else:
if jogador < computador:
print('Mais... tente mais uma vez.')
elif jogador > computador:
print('Menos... tente mais uma vez')
print('Acertou com {} tentativas. Parabens!!'.format(palpites))'''
n = int(input('digite um numero:'))
c = 0
while c < 5:
c += 1
print('Menor ' if n < 3 else 'Maior')
|
#!/home/user/code/Django-Sample/django_venv/bin/python2.7
# EASY-INSTALL-SCRIPT: 'Django==1.11.3','django-admin.py'
__requires__ = 'Django==1.11.3'
__import__('pkg_resources').run_script('Django==1.11.3', 'django-admin.py')
|
def LB2idx(lev, band, nlevs, nbands):
''' convert level and band to dictionary index '''
# reset band to match matlab version
band += (nbands-1)
if band > nbands-1:
band = band - nbands
if lev == 0:
idx = 0
elif lev == nlevs-1:
# (Nlevels - ends)*Nbands + ends -1 (because zero indexed)
idx = (((nlevs-2)*nbands)+2)-1
else:
# (level-first level) * nbands + first level + current band
idx = (nbands*lev)-band - 1
return idx
|
print("+="*10, "TABUADA", "+="*10)
while True:
n = int(input("Você quer ver a tabuada de que número? 0 (zero) encerra o programa: "))
print("--"*5)
if n == 0:
break
for c in range(1, 11):
print(f"{n} x {c} = {n*c}")
print("--"*5)
print("Programa encerrado.")
|
# https://www.hackerrank.com/challenges/s10-standard-deviation/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input().strip())
all1 = [int(i) for i in input().strip().split()]
u = sum(all1) / n
v = sum(((i - u) ** 2) for i in all1)/n
sd = v ** 0.5
print("{0:0.1f}".format(sd))
|
context_mapping = {
"schema": "http://www.w3.org/2001/XMLSchema#",
"brick": "http://brickschema.org/schema/1.0.3/Brick#",
"brickFrame": "http://brickschema.org/schema/1.0.3/BrickFrame#",
"BUDO-M": "https://git.rwth-aachen.de/EBC/Team_BA/misc/Machine-Learning/tree/MA_fst-bll/building_ml_platform/BUDO-M/Platform_Application_AI_Buildings_MA_Llopis/OntologyToModelica/CoTeTo/ebc_jsonld#",
"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
"Equipment": {"@id": "brick: Equipment"},
"Point": {"@id": "brick: Point"},
"BUDOSystem": {"@id": "BUDO-M: BUDOSystem"},
"ModelicaModel": {"@id": "BUDO-M: ModelicaModel"},
"portHeatflow": {"@id": "BUDO-M: portHeatflow"},
"EquipmentPointParameter": {"@id": "BUDO-M: EquipmentPointParameter"},
"EquipmentPointUnits": {"@id": "BUDO-M: EquipmentPointUnits"},
"EquipmentPointExplanation": {"@id": "BUDO-M: EquipmentPointExplanation"},
"portParameter": {"@id": "BUDO-M: portParameter"},
"portUnits": {"@id": "BUDO-M: portUnits"},
"portExplanation": {"@id": "BUDO-M: portExplanation"},
"Pump": {"@id":"brick:Pump"},
"Boiler": {"@id":"brick:Boiler"},
"Valve": {"@id":"brick:Valve"},
"Temperature_Sensor": {"@id":"brick:Temperature_Sensor"},
"Heat_Pump": {"@id":"brick:Heat_Pump"},
"Combined_Heat_Power": {"@id":"brick:Combined_Heat_Power"},
"Heat_Exchanger": {"@id":"brick:Heat_Exchanger"},
"ItemList": {"@id":"schema:ItemList"},
"itemListElement": {"@id":"schema:itemListElement"},
"T_Piece": {"@id":"BUDO-M:T_Piece"}
}
doc_mapping_brick={
"@context": context_mapping,
"@type": "ItemList",
"itemListElement": [{
"Pump":{
"Point":"Hot_Water_Pump/Chilled_Water_Pump",
"BUDOSystem":"PU", "ModelicaModel": "1",
"portHeatflow": "1",
"EquipmentPointParameter":"signalpath.massflow",
"EquipmentPointUnits":"kg/s",
"EquipmentPointExplanation":"mat file directory for input signal: prescribed mass flow rate for pump",
"portParameter":"massFlow.nominal/massFlow.nominal.Pipe.out/pressureDifference.nominal.Pipe.out/medium",
"portUnits":"kg/s,kg/s,pa,-",
"portExplanation":"-/nominal mass flow rate in the pipe connected to this port /nominal pressure drop in the pipe connected to this port /medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity"
} },
{
"Boiler": {
"Point":"Boiler",
"BUDOSystem":"BOI",
"ModelicaModel": "5",
"portHeatflow": "1",
"EquipmentPointParameter": "signalpath.status/signalpath.mode/signalpath.temperature",
"EquipmentPointUnits":"-,-,K",
"EquipmentPointExplanation": "mat file directory for input signal: boiler on off status , boolean value required/mat file directory for input signal: boiler switch to night mode, boolean value required/mat file directory for input signal: ambient temperature",
"portParameter":"massFlow.nominal/massFlow.nominal.Pipe.out/pressureDifference.nominal.Pipe.out/medium",
"portUnits":"kg/s,kg/s,pa,-",
"portExplanation":"-/nominal mass flow rate in the pipe connected to this port /nominal pressure drop in the pipe connected to this port /medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity"
}
},
{
"Valve": {
"Point":"Heating_Valve",
"BUDOSystem":"VAL",
"ModelicaModel": "1",
"portHeatflow": "2",
"EquipmentPointParameter":"signalpath.position",
"EquipmentPointUnits":"-",
"EquipmentPointExplanation":"mat file directory for input signal: actuator position, value in range [0,1] required (0: closed, 1: open)",
"portParameter":"massFlow.nominal/pressureDifference.nominal/massFlow.nominal.Pipe.out/pressureDifference.nominal.Pipe.out/medium",
"portUnits":"kg/s,pa,kg/s,pa,-",
"portExplanation":"-/-/nominal mass flow rate in the pipe connected to this port /nominal pressure drop in the pipe connected to this port /medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity"
}
},
{
"Temperature_Sensor": {
"Point":"Hot_Water_Supply_Temperature_Sensor/Hot_Water_Return_Temperature_Sensor/Chilled_Water_Supply_Temperature_Sensor/Chilled_Water_Return_Temperature_Sensor",
"BUDOSystem":"MEA.T",
"ModelicaModel": "0",
"portHeatflow": "0",
"EquipmentPointParameter": "massFlow.nominal/medium",
"EquipmentPointUnits": "kg/s,-",
"EquipmentPointExplanation":"- /medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity",
"portParameter":"",
"portUnits":"",
"portExplanation":""
}
},
{
"Heat_Pump": {
"Point":"Heat_Pump",
"BUDOSystem":"HP",
"ModelicaModel": "1",
"portHeatflow": "2",
"EquipmentPointParameter":"CoefficientOfPerformance/compressorPower.nominal/signalpath.loadratio",
"EquipmentPointUnits":"-,W,-",
"EquipmentPointExplanation":"-/-/mat file directory for input signal: part load ratio of compressor in heat pump, value in range [0,1] required",
"portParameter":"massFlow.nominal/pressureDifference.nominal/massFlow.nominal.Pipe.out/pressureDifference.nominal.Pipe.out/temperatureDifference.nominal/temperature.average.nominal/medium",
"portUnits":"kg/s,pa,kg/s,pa,K,K,-",
"portExplanation":"-/-/nominal mass flow rate in the pipe connected to this port /nominal pressure drop in the pipe connected to this port /temperature difference outlet-inlet in condenser for portHeatflow.prim, in evaporator for portHeatflow .sec/nominal average temperature in condenser for portHeatflow.prim, in evaporator for portHeatflow .sec/medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity"
}
},
{
"Combined_Heat_Power": {
"Point":"Combined_Heat_Power",
"BUDOSystem":"CHP",
"ModelicaModel": "3",
"portHeatflow":"1",
"EquipmentPointParameter":"signalpath.status/signalpath.temperature",
"EquipmentPointUnits":"-,K",
"EquipmentPointExplanation":"mat file directory for input signal: CHP on off status, boolean value required/mat file directory for input signal: CHP temperature setpoint, boolean value required",
"portParameter":"massFlow.nominal/medium",
"portUnits":"kg/s,-",
"portExplanation":"-/medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity"
}
},
{
"Heat_Exchanger": {
"Point":"Heat_Exchanger",
"BUDOSystem":"HX",
"ModelicaModel":"0",
"portHeatflow":"2",
"EquipmentPointParameter":"",
"EquipmentPointUnits":"",
"EquipmentPointExplanation":"",
"portParameter":"massFlow.nominal/pressureDifference.nominal/massFlow.nominal.Pipe.out/pressureDifference.nominal.Pipe.out/medium",
"portUnits":"kg/s,pa,kg/s,pa,K,K,-",
"portExplanation":"-/-/nominal mass flow rate in the pipe connected to this port /nominal pressure drop in the pipe connected to this port /-/-/medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity "
}
}]
}
doc_mapping_BUDO={
"@context": context_mapping,
"@type": "ItemList",
"itemListElement": [
{
"T_Piece": {
"Point":"T_Piece",
"BUDOSystem":"TP",
"ModelicaModel": "0",
"portHeatflow": "2",
"EquipmentPointParameter": "0",
"EquipmentPointUnits": "0",
"EquipmentPointExplanation": "0",
"portParameter": "medium",
"portUnits":"-",
"portExplanation":"medium in modelica model"
}
}
]
}
|
peso = float(input('Qual é o seu peso (KG) ? '))
altura = float(input('Qual e sua altura (M) ? '))
imc = peso / (altura ** 2)
print('O IMC dessa pessoa é de {:.2f} '.format(imc))
if imc < 18.5:
print('você está abaixo do peso normal')
elif imc > 18.5 and imc <= 25:
print('Você está no peso odeal ')
elif imc > 25 and imc <= 30:
print('Você está com sobrepeso ')
elif imc > 30 and imc <= 40:
print('Você está em em quadro de obesidade ')
else:
print('Você está em um quadro de obesidade morbida ')
|
"""Relaydomains app constants."""
PERMISSIONS = {
"Resellers": [
("relaydomains", "relaydomain", "add_relaydomain"),
("relaydomains", "relaydomain", "change_relaydomain"),
("relaydomains", "relaydomain", "delete_relaydomain"),
("relaydomains", "service", "add_service"),
("relaydomains", "service", "change_service"),
("relaydomains", "service", "delete_service")
]
}
|
"""Defines error messages and functions."""
_BAD_NAME = "Bad name '{name}'."
_BAD_LITERAL = "Bad literal '{literal}'."
_NOT_IMPLEMENTED = "Not implemented:"
class CheckError(Exception):
def __init__(self, message):
self.message = message
def bad_name(name):
_error(_BAD_NAME, name=name)
def bad_literal(literal):
_error(_BAD_LITERAL, literal=literal)
def not_implemented(message):
_error(" ".join([_NOT_IMPLEMENTED, "".join([message, "."])]))
def _error(message, **keywords):
raise CheckError(message.format_map(keywords))
|
OBJECT( 'VALUE',
attributes = [
A( 'ANY', 'value' ),
]
)
|
# Reading Error Messages
# Read the Python code and the resulting traceback below,
# and answer the following questions:
# How many levels does the traceback have?
# What is the function name where the error occurred?
# On which line number in this function did the error occur?
# What is the type of error?
# What is the error message?
# This code has an intentional error. Do not type it directly;
# use it for reference to understand the error message below.
def print_message(day):
messages = {
"monday": "Hello, world!",
"tuesday": "Today is Tuesday!",
"wednesday": "It is the middle of the week.",
"thursday": "Today is Donnerstag in German!",
"friday": "Last day of the week!",
"saturday": "Hooray for the weekend!",
"sunday": "Aw, the weekend is almost over."
}
print(messages[day])
def print_friday_message():
print_message("Friday")
print_friday_message()
|
"""
This is a config file that will be used to generate the .piwall file
"""
# Network information
master_ip = "0.0.0.0"
# Wall.py for PiWall
configs = {
'walls': {
'wall_name': {
'name': 'wall_name',
'height': '270',
'width': '1080',
'master_ip': '0.0.0.0'
}
},
'num_of_tiles': 4,
'tiles': [
{
'name': 'tile_name',
'wall': 'wall_name',
'width': '270',
'height': '270',
'x': '0',
'y': '0',
'ip': '0.0.0.0',
'id': 'tile1'
},
{
'name': 'tile_name',
'wall': 'wall_name',
'width': '270',
'height': '270',
'x': '270',
'y': '0',
'ip': '0.0.0.0',
'id': 'tile2'
},
{
'name': 'tile_name',
'wall': 'wall_name',
'width': '270',
'height': '270',
'x': '540',
'y': '0',
'ip': '0.0.0.0',
'id': 'tile3'
},
{
'name': 'tile_name',
'wall': 'wall_name',
'width': '270',
'height': '270',
'x': '810',
'y': '0',
'ip': '0.0.0.0',
'id': 'tile4'
}
],
'config': [
{
'name': 'wall_config',
'tile': [
{
'id': 'tile1'
},
{
'id': 'tile2'
},
{
'id': 'tile3'
},
{
'id': 'tile4'
}
]
}
]
}
# String new /etc/network/interfaces
replace_str = """auto lo
iface lo inet loopback
iface eth0 inet static
address {0}
netmask 255.255.255.0
up route add -net 224.0.0.0 netmask 240.0.0.0 eth0
"""
|
def cons(a, b):
def pair(f):
return f(a, b)
return pair
def car(pair):
return pair((lambda a, b: a))
def cdr(pair):
return pair((lambda a, b: a))
|
"""Sub-module of the package."""
def hello_world():
"""Print "Hello World"."""
print("Hello World")
|
# Testing site
base_url = 'http://localhost:80/demo'
# Login account
admin_auth_data = {'name': 'admin', 'password': 'admin'}
login_url = base_url + '/api/auth'
header = dict()
|
def add(x,y):
'''Add two nos'''
return x+y
def subtract(x,y):
'''Subtract two nos'''
return y-x
|
"""
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the
shortest palindrome you can find by performing this transformation.
For example:
Given "aacecaaa", return "aaacecaaa".
Given "abcd", return "dcbabcd".
"""
__author__ = 'Daniel'
class Solution:
def shortestPalindrome(self, s):
"""
KMP
:type s: str
:rtype: str
"""
s_r = s[::-1]
l = len(s)
if l < 2:
return s
# construct T
T = [0 for _ in xrange(l+1)]
T[0] = -1
pos = 2
cnd = 0
while pos <= l:
if s[pos-1] == s[cnd]:
T[pos] = cnd+1
cnd += 1
pos += 1
elif T[cnd] != -1:
cnd = T[cnd]
else:
T[pos] = 0
cnd = 0
pos += 1
# search
i = 0
b = 0
while i+b < l:
if s[i] == s_r[i+b]:
i += 1
if i == l:
return s
elif T[i] != -1:
b = b+i-T[i]
i = T[i]
else:
b += 1
i = 0
# where it falls off
return s_r+s[i:]
if __name__ == "__main__":
assert Solution().shortestPalindrome("abcd") == "dcbabcd"
|
def word2features(sent, i):
word = sent[i][0]
postag = sent[i][1]
features = [
'bias',
'word.lower=' + word.lower(),
'word[-3:]=' + word[-3:],
'word[-2:]=' + word[-2:],
'word.isupper=%s' % word.isupper(),
'word.istitle=%s' % word.istitle(),
'word.isdigit=%s' % word.isdigit(),
'postag=' + postag,
'postag[:2]=' + postag[:2],
]
if i > 0:
word1 = sent[i-1][0]
postag1 = sent[i-1][1]
features.extend([
'-1:word.lower=' + word1.lower(),
'-1:word.istitle=%s' % word1.istitle(),
'-1:word.isupper=%s' % word1.isupper(),
'-1:postag=' + postag1,
'-1:postag[:2]=' + postag1[:2],
])
else:
features.append('BOS')
if i < len(sent)-1:
word1 = sent[i+1][0]
postag1 = sent[i+1][1]
features.extend([
'+1:word.lower=' + word1.lower(),
'+1:word.istitle=%s' % word1.istitle(),
'+1:word.isupper=%s' % word1.isupper(),
'+1:postag=' + postag1,
'+1:postag[:2]=' + postag1[:2],
])
else:
features.append('EOS')
return features
def sent2features(sent):
return [word2features(sent, i) for i in range(len(sent))]
def sent2labels(sent):
return [label for token, postag, label in sent]
def sent2tokens(sent):
return [token for token, postag, label in sent]
|
words_single = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
words_teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
words_tens = ['','ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
hudred = 'hundred'
def spell_out(num):
if num > 1000 or num < 0:
raise Exception('no man')
if num == 1000:
return 'one thousand'
if num < 10:
return words_single[num]
if num < 20:
return words_teens[num-10]
if num < 100:
return words_tens[int(num/10)] + (spell_out(num%10) if num%10 > 0 else '')
return words_single[int(num/100)] + ' hundred ' + (('and ' + spell_out(num%100)) if num%100 > 0 else '')
def count(words):
return len(words.translate(str.maketrans('', '', ' ')))
total = 0
for i in range(1,1001):
print(spell_out(i))
spelled = spell_out(i)
total += count(spelled)
print(total)
|
#!/usr/bin/env python3
"""
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
we can see that the 6th prime is 13.
What is the 10,001st prime number?
https://projecteuler.net/problem=7
"""
|
def ping():
"""Always returns 'pong'."""
return 'pong'
def cowsay():
return r"""
___________________
< Hello Resource Hub! >
===================
\
\
^__^
(oo)\_______
(__)\ )\/\
||----w |
|| ||
"""
|
def same_wind(history, **kwargs):
"""Set the tropopause wind at their previous values for the new state
:param history: Current history of state
:type history: :class:`History` object
"""
assert history.size > 1
previous_state = history.state_list[-2]
current_state = history.state_list[-1]
update_var = ['ut','vt','us','vs']
for var in update_var:
current_state.vrs[var] = previous_state.vrs[var]
|
def test_Compare():
a: bool
a = 5 > 4
a = 5 <= 4
a = 5 < 4
a = 5.6 >= 5.59999
a = 3.3 == 3.3
a = 3.3 != 3.4
a = complex(3, 4) == complex(3., 4.)
|
def spaces(n, i):
countSpace= n-i
spaces = " "*countSpace
return spaces
def staircase(n):
for i in range(1, n+1):
cadena = spaces(n,i)
steps = "#"*i
cadena = cadena+steps
print(cadena)
if __name__ == "__main__":
tamanio = int(input("Ingresa el numero de escalones: "))
staircase(tamanio)
|
#!/usr/bin/python2.4
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""AppEngine Datastore/GQL related Utilities module.
This common util provides helper functionality to extend/support
various GQL related queries.
"""
def FetchEntities(query_obj, limit):
"""Fetches number of Entities up to limit using query object.
Args:
query_obj: AppEngine Datastore Query Object.
limit: Fetch limit on number of records you want to fetch.
Returns:
Fetched Entities.
"""
entities = []
# If Limit is more than 1000 than let's fetch more records using cursor.
if limit > 1000:
results = query_obj.fetch(1000)
entities.extend(results)
cursor = query_obj.cursor()
while results and limit > len(entities):
query_obj.with_cursor(cursor)
results = query_obj.fetch(1000)
entities.extend(results)
cursor = query_obj.cursor()
else:
entities = query_obj.fetch(limit)
return entities
|
'''
QUESTION:
344. Reverse String
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
'''
class Solution(object):
def reverseString(self, s):
leftindex = 0
rightindex = len(s) - 1
while (leftindex < rightindex):
s[leftindex], s[rightindex] = s[rightindex], s[leftindex]
leftindex += 1
rightindex -= 1
'''
Ideas/thoughts:
As need to modify in place, without creating new array.
As python can do pair value assign,
assign left to right, right value to left until leftindex is less than right.
No need to return anything
'''
|
{
"targets":[
{
"target_name":"stp",
"sources":["calc_grid.cc"]
}
]
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.