content
stringlengths 7
1.05M
|
---|
n = int(input())
if n%2!=0:
print('Weird')
elif 2<n<=5 and n%2==0:
print('Not Weird')
elif 6<n<=20 and n%2==0:
print('Weird')
elif n>20 and n%2==0:
print('Not Weird')
|
expected_output = {
"interface": {
"FastEthernet2/1/1.2": {
"ethernet_vlan": {2: {"status": "up"}},
"status": "up",
"destination_address": {
"10.2.2.2": {
"default_path": "active",
"imposed_label_stack": "{16}",
"next_hop": "point2point",
"output_interface": "Serial2/0/2",
"tunnel_label": "imp-null",
"vc_id": {"1002": {"vc_status": "up"}},
"preferred_path": "not configured",
}
},
"last_status_change_time": "1d00h",
"line_protocol_status": "up",
"signaling_protocol": {
"LDP": {
"peer_id": "10.2.2.2:0",
"remote_interface_description": "xconnect to PE2",
"group_id": {"local": "0", "remote": "0"},
"peer_state": "up",
"mtu": {"local": "1500", "remote": "1500"},
"mpls_vc_labels": {"local": "21", "remote": "16"},
}
},
"create_time": "1d00h",
"statistics": {
"bytes": {"received": 4322368, "sent": 5040220},
"packets": {"received": 3466, "sent": 12286},
"packets_drop": {"received": 0, "sent": 0},
},
"sequencing": {"received": "disabled", "sent": "disabled"},
}
}
}
|
class merfishParams:
"""
An object that contains input variables.
"""
def __init__(self, **arguments):
for (arg, val) in arguments.items():
setattr(self, arg, val)
def to_string(self):
return ("\n".join(["%s = %s" % (str(key), str(val)) \
for (key, val) in self.__dict__.items() ]))
|
class InvalidResponseException(Exception):
def __init__(self, message):
self.message = f'Request was not success: {message}'
super()
|
# Contents:
# Ahoy! (or Should I Say Ahoyay!)
# Input!
# Check Yourself!
# Check Yourself... Some More
# Ay B C
# Word Up
# Move it on Back
# Ending Up
# Testing, Testing, is This Thing On?
print("### Ahoy! (or Should I Say Ahoyay!) ###")
print("Pig Latin")
print("### Input! ###")
original = input("Enter a word: ")
print("### Check Yourself! ###")
# if len(original) > 0:
# print(original)
# else:
# print("empty")
print("### Check Yourself... Some More ###")
# if len(original) > 0 and original.isalpha():
# print(original)
# else:
# print("empty")
print("### Ay B C ###")
pyg = 'ay'
print("### Word Up ###")
# if len(original) > 0 and original.isalpha():
# word = original.lower()
# first = word[0]
# else:
# print('empty')
print("### Move it on Back ###")
# if len(original) > 0 and original.isalpha():
# word = original.lower()
# first = word[0]
# new_word = word + first + pyg
# else:
# print('empty')
print("### Ending Up ###")
# if len(original) > 0 and original.isalpha():
# word = original.lower()
# first = word[0]
# new_word = word + first + pyg
# new_word = new_word[1:len(new_word)]
# else:
# print('empty')
print("### Testing, Testing, is This Thing On? ###")
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
new_word = word + first + pyg
new_word = new_word[1:len(new_word)]
print(new_word)
else:
print('empty')
|
# Exercício Python 51: Desenvolva um programa que leia o primeiro termo e a razão de uma PA.
# No final, mostre os 10 primeiros termos dessa progressão.
print('=' * 30)
print(' 10 TERMOS DE UMA PA')
print('=' * 30)
termo = int(input('Primeiro termo: '))
razao = int(input('Razão: '))
print(termo, ' -> ', end=' ')
for n in range(9): # o range será 9 pois o usuário já passa o 1o termo, assim fazem 10 no total
termo = termo + razao
print(termo, ' -> ', end=' ')
print('ACABOU')
|
class ContactList():
def __init__(self, names):
"""
names is a list of strings.
"""
self.names = names
def __hash__(self):
"""Conceptually we want to hash the set of names. Since set
type is mutable it cannot be hashed so we use a frozenset
"""
return hash(frozenset(self.names))
def __eq__(self, other):
"""
In practice we'd store the underlying set and hash code
remembering to void these values on updates.
"""
return set(self.names) == set(other.names)
def merge_contact_lists(self):
"""
Contacts is a list of ContactList.
"""
return list(set(self.names))
names = ['joe', 'amir', 'mary', 'ana', 'vannessa', 'joe', 'mary', 'mary']
contacts = ContactList(names)
print(contacts.merge_contact_lists())
|
# Write a programme to find sum of cubes of first n natural numbers.
n = int(input('Input : '))
sumofcubes = sum([x*x*x for x in [*range(1, n+1)]])
print('Output: ', sumofcubes)
|
Bin_Base=['0','1']
Oct_Base=['0', '1', '2', '3', '4', '5', '6', '7']
Hex_Base=['0', '1', '2', '3', '4', '5', '6', '7','8','9','A','B','C','D','E','F']
def BinTesting(n):
n=str(n)
for digit in n:
if digit in Bin_Base:
continue
else:
return False
return True
def OctTesting(n):
n=str(n)
for digit in n:
if digit in Oct_Base:
continue
else:
return False
return True
def HexTesting(n):
n=str(n)
for digit in n:
if digit in Hex_Base:
continue
else:
return False
return True
def DecToBin(n):
n=int(n)
if n==0:
return 0
else:
result=[]
while n!=0:
result.append(str(n%2))
n = n//2
result.reverse()
return "".join(result)
def BinToDec(n):
if BinTesting(n) == False:
return "Base error"
n=str(n)
x=len(n)-1
result =0
for digit in n:
result += int(digit)*2**x
x -= 1
return result
def DecToHex(n):
n=int(n)
if n==0:
return 0
else:
sys={10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'}
result=[]
while n!=0:
a=n%16
if a in sys:
result.append(sys[a])
else:
result.append(str(a))
n=n//16
result.reverse()
return "".join(result)
def HexToDec(n):
n=str(n)
if HexTesting(n) == False:
return "Wrong Base"
sys={'A':10,'B':11,'C':12,'D':13,'E':14,'F':15}
x=len(n)-1
result =0
for digit in n:
if digit in sys:
a=sys[digit]
else:
a=digit
result += int(a)*16**x
x -= 1
return result
def DecToOct(n):
n=int(n)
if n==0:
return 0
else:
result=[]
while n!=0:
result.append(str(n%8))
n = n//8
result.reverse()
return "".join(result)
def OctToDec(n):
n=str(n)
if OctTesting(n) == False:
return "Base error"
x=len(n)-1
result =0
for digit in n:
result += int(digit)*8**x
x -= 1
return result
def Filter(result):
while result[0]=='0':
result = result[1:]
return result
def HexToBin(n):
n=str(n)
if HexTesting(n) == False:
return "Base error"
if n=='0':
return 0
else:
sys={'A':10,'B':11,'C':12,'D':13,'E':14,'F':15}
result=[]
for digit in n:
if digit in sys:
a=DecToBin(sys[digit])
result.append(a)
else:
a=DecToBin(digit)
while len(str(a))<4:
a='0'+a
result.append(a)
return Filter("".join(result))
def BinToHex(n):
n=str(n)
if BinTesting(n) == False:
return "Base error"
if n=='0':
return 0
else:
sys={10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'}
while len(n)%4 != 0:
n='0'+n
value=n
result=[]
for i in range((len(n)//4)):
if i== len(n)//4:
num = value
else:
num=value[0:4]
value=value[4:]
a=BinToDec(num)
if a in sys:
result.append(sys[a])
else:
result.append(str(a))
return "".join(result)
def OctToBin(n):
n=str(n)
if OctTesting(n) == False:
return "Base error"
if n =='0':
return 0
else:
result=[]
for digit in n:
a=DecToBin(digit)
while len(str(a))<3:
a='0'+str(a)
result.append(a)
return Filter("".join(result))
def BinToOct(n):
n=str(n)
if BinTesting(n) == False:
return "Base error"
if n=='0':
return 0
else:
sys={10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'}
while len(n)%3 != 0:
n='0'+n
value=n
result=[]
for i in range((len(n)//3)):
if i== len(n)//3:
num = value
else:
num=value[0:3]
value=value[3:]
a=BinToDec(num)
result.append(str(a))
return "".join(result)
def OctToHex(n):
a=OctToBin(n)
b=BinToHex(a)
return b
def HexToOct(n):
a=HexToBin(n)
b=BinToOct(a)
return b
Operations=[DecToBin,BinToDec,DecToHex,HexToDec,DecToOct,OctToDec,HexToBin,BinToHex,OctToBin,BinToOct,OctToHex,HexToOct]
Operations_names=["From decimal to binary is:","From binary to decimal is:",
"From decimal to hexadecimal is:","From hexadecimal to decimal is:",
"From decimal to octal is:","From octal to decimal is:",
"From hexadecimal to binary is:",
"From binary to hexadecimal is:","From octal to binary is:",
"From binary to octal is:"
,"From octal to hexadecimal is:","From hexadecimal to octal is:"]
def opt():
print("Number Systems Conversion")
print("Select the operation by enetering its number from the list below then enter the starting number")
print("0 From Decimal system to Binary system")
print("1 From Binary system to Decimal system")
print("2 From Decimal system to Hexadecimal system")
print("3 From Hexadecimal system to Deicmal system")
print("4 From Decimal system to Octal system")
print("5 From Octal system to Decimal system")
print("6 From Hexadecimal system to Binary system")
print("7 From Binary system to Hexadecimal system")
print("8 From Octal system to Binary system")
print("9 From Binary system to Octal system")
print("10 From Octal system to Hexadecimal system")
print("11 From Hexadecimal system to Octal system")
opt_ord=int(input("Enter the number of the selected operation: "))
number=input("Enter the number: ")
try:
print("The Conversion of",number,Operations_names[opt_ord],Operations[opt_ord](number))
except:
print("Wrong operation number")
count=int(input("Number of operations: "))
for i in range(count):
opt()
|
class Payment:
"""
Payment class
"""
def __init__(self,date, perceptions:dict=None, deductions:dict=None):
self._date = date
self.perceptions = perceptions
self.deductions = deductions
def __str__(self):
ret = f"""
Date: {self.date}
Total Perceptions: ${self.total_perceptions():,.2f}
Total Deductions: ${self.total_deductions():,.2f}
------------------------
Total: ${self.total():,.2f}"""
# format(self.date,
# self.total_perceptions(),
# self.total_deductions(),
# self.total())
return ret
def total(self):
return self.total_perceptions() - self.total_deductions()
def total_perceptions(self):
return sum(self.perceptions.values())
def total_deductions(self):
return sum(self.deductions.values())
@property
def date(self):
return self._date
|
def minmax_decision(state):
def max_value(state):
if is_terminal(state):
return utility_of(state)
v = -infinity
for (a, s) in successors_of(state):
v = max(v, min_value(s))
print('V: ' + str(v))
return v
def min_value(state):
if is_terminal(state):
return utility_of(state)
v = infinity
for (a, s) in successors_of(state):
v = min(v, max_value(s))
return v
infinity = float('inf')
action, state = argmax(successors_of(state), lambda a: min_value(a[1]))
return action
def is_terminal(state):
board_is_full = True
for i in range(len(state)):
if state[i] != 'O' and state[i] != 'X':
board_is_full = False
break
if board_is_full:
return True
utility = utility_of(state)
if utility == 1 or utility == -1:
return True
else:
return False
def utility_of(state):
"""
returns +1 if winner is X (MAX player), -1 if winner is O (MIN player), or 0 otherwise
:param state: State of the checkerboard. Ex: [0; 1; 2; 3; X; 5; 6; 7; 8]
:return:
"""
if state[0] == state[1] == state[2]:
if state[0] == 'X':
return 1
else:
return -1
if state[0] == state[4] == state[8]:
if state[0] == 'X':
return 1
else:
return -1
if state[0] == state[3] == state[6]:
if state[0] == 'X':
return 1
else:
return -1
if state[3] == state[4] == state[5]:
if state[3] == 'X':
return 1
else:
return -1
if state[6] == state[7] == state[8]:
if state[6] == 'X':
return 1
else:
return -1
if state[2] == state[4] == state[6]:
if state[2] == 'X':
return 1
else:
return -1
if state[1] == state[4] == state[7]:
if state[1] == 'X':
return 1
else:
return -1
if state[2] == state[5] == state[8]:
if state[2] == 'X':
return 1
else:
return -1
return 0
def check_players_turn(state):
count = 0
for board_entry in state:
if board_entry == 'O' or board_entry == 'X':
continue
count += 1
if count % 2 == 1:
return True
def successors_of(state):
"""
returns a list of tuples (move, state) as shown in the exercise slides
:param state: State of the checkerboard. Ex: [0; 1; 2; 3; X; 5; 6; 7; 8]
:return:
"""
# Generate valid moves:
max_turn = check_players_turn(state)
valid_moves = []
for state_index in range(len(state)):
if state[state_index] == 'O' or state[state_index] == 'X':
continue
new_state = state.copy()
new_state[state_index] = 'X' if max_turn else 'O'
valid_moves.append((state_index, new_state))
return valid_moves
def display(state):
print("-----")
for c in [0, 3, 6]:
print(state[c + 0], state[c + 1], state[c + 2])
def main():
board = [0, 1, 2, 3, 4, 5, 6, 7, 8]
while not is_terminal(board):
board[minmax_decision(board)] = 'X'
if not is_terminal(board):
display(board)
board[int(input('Your move? '))] = 'O'
display(board)
def argmax(iterable, func):
return max(iterable, key=func)
if __name__ == '__main__':
main()
|
### tutorzzz
tutorzzzURL = 'https://tutorzzz.com/tutorzzz/orders/assignList'
tutorzzzCookie = 'SESSION_TUTOR=581fb89c-88c6-4942-a735-d082bf1a29db'
tutorzzzReqBody = {"pageNumber":1,"pageSize":20,"sortField":"id","order":"desc"}
openIDList = ['ouZ_Ys2FvyLlOk9o-B8oZOnme5n4', 'ouZ_Ys2uzq8fijTerZziXI69jVVY']
appID = 'wxe7b878e46bcf3e24'
appsecret = 'a275853a41bdd2b0518befaab24cb545'
getAccessTokenURL = 'https://api.weixin.qq.com/cgi-bin/token'
templateID = 'ZTtP2eWz4XkEVtmDBsB8JpwapYfv5mCCKkG5ekx1pDE'
templateSendURL = 'https://api.weixin.qq.com/cgi-bin/message/template/send'
|
"""
Exceptions for psz.
You can stringify these exceptions to get a message about the error type and
whatver extra string arguments that were passed in when the object was created.
"""
class PszError(Exception):
_msg = ''
def __str__(self):
s = []
if self._msg:
s.append(self._msg)
s.extend(self.args)
return '\n'.join(s)
class PszConfigError(PszError):
_msg = 'There was a problem with your configuration. Check the following:\n'
class PszKeygenError(PszError):
_msg = 'Keygen error: '
class PszDnsError(PszError):
_meg = 'Dns Error: '
class PszDnsCountError(PszDnsError):
pass
class PszDnsUpdateServfail(PszDnsError):
_msg = 'Dns SERVFAIL Error'
|
# -*- python -*-
load("@drake//tools/workspace:execute.bzl", "path", "which")
def _impl(repository_ctx):
command = repository_ctx.attr.command
additional_paths = repository_ctx.attr.additional_search_paths
found_command = which(repository_ctx, command, additional_paths)
if found_command:
repository_ctx.symlink(found_command, command)
else:
error_message = "Could not find {} on PATH={}".format(
command,
path(repository_ctx, additional_paths),
)
if repository_ctx.attr.allow_missing:
repository_ctx.file(command, "\n".join([
"#!/bin/sh",
"echo 'ERROR: {}' 1>&2".format(error_message),
"false",
]), executable = True)
else:
fail(error_message)
build_file_content = """# -*- python -*-
# DO NOT EDIT: generated by which_repository()
# A symlink to {}.
exports_files(["{}"])
{}
""".format(found_command, command, repository_ctx.attr.build_epilog)
repository_ctx.file(
"BUILD.bazel",
content = build_file_content,
executable = False,
)
which_repository = repository_rule(
attrs = {
"command": attr.string(mandatory = True),
"additional_search_paths": attr.string_list(),
"allow_missing": attr.bool(default = False),
"build_epilog": attr.string(),
},
local = True,
configure = True,
implementation = _impl,
)
"""Alias the result of $(which $command) into a label @$name//:$command (or
@$command if name and command match). The PATH is set according to the path()
function in execute.bzl. The value of the user's PATH environment variable is
ignored.
Changes to any WORKSPACE or BUILD.bazel file will cause this rule to be
re-evaluated because it sets its local attribute. However, note that if neither
WORKSPACE nor **/BUILD.bazel change, then this rule will not be re-evaluated.
This means that adding or removing the presence of `command` on some entry in
the PATH (as defined above) will not be accounted for until something else
changes.
Args:
command (:obj:`str`): Short name of command, e.g., "cat".
additional_search_paths (:obj:`list` of :obj:`str`): List of additional
search paths.
allow_missing (:obj:`bool`): When True, errors will end up deferred to
build time instead of fetch time -- a failure to find the command will
still result in a BUILD.bazel target that provides the command, but
the target will be missing.
build_epilog: (Optional) Extra text to add to the generated BUILD.bazel.
"""
|
def loadfile(name):
numbers = []
f = open(name, "r")
for x in f:
for number in x.split(","):
number = int(number)
numbers.append(number)
return numbers
def caculateTravelLinear(numbers, endpoint):
travel = 0
for number in numbers:
distance = endpoint - number if (endpoint - number) > 0 else (endpoint - number) * -1
travel = travel + distance
return travel
def caculateTravelFuel(numbers, endpoint):
travel = 0
for number in numbers:
distance = endpoint - number if (endpoint - number) > 0 else (endpoint - number) * -1
rangeOfNumber = range(0, distance + 1)
fuel = sum(rangeOfNumber)
travel = travel + fuel
return travel
def findLowestTravel(function, numbers):
median = int(numbers[int(len(numbers) / 2)] if len(numbers) % 2 == 0 else (numbers[int(len(numbers) / 2 - 1)] + (numbers[int(len(numbers) / 2 + 1)])/2))
average = round(sum(numbers)/len(numbers))
print("Median: " + str(median))
print("Average: " + str(average))
lowestTravel = 99999999999999999999999999999999999999999999999999999999999999999999999999999
rangeOfLoop = range(median, average + 1) if median < average + 1 else range(average - 1, median + 1)
for endpoint in rangeOfLoop:
travel = function(numbers, endpoint)
print("Endpoint: ", str(endpoint) + "Travel: ", str(travel) + "-")
if travel < lowestTravel:
lowestTravel = travel
print("Lowest: ", travel)
return lowestTravel
numbers = sorted(loadfile("data.txt"))
lowestTravelA = findLowestTravel(caculateTravelLinear, numbers)
lowestTravelB = findLowestTravel(caculateTravelFuel, numbers)
print("solution day7a: " + str(lowestTravelA))
print("solution day7b: " + str(lowestTravelB))
|
#!/usr/bin/env python3
def import_input(path):
with open(path, encoding='utf-8') as infile:
return [int(n) for n in infile.read().split()]
banks = import_input("input.txt")
class Redistributor:
def __init__(self, banks):
self._banks = banks
def redistribute(self, i):
blocks = self._banks[i]
self._banks[i] = 0
while blocks > 0:
i += 1
i = i % len(self._banks)
self._banks[i] += 1
blocks -= 1
def find_biggest_bank(self):
return self._banks.index(max(self._banks))
def solve(self):
count = 0
records = []
while self._banks not in records:
records.append(self._banks.copy())
i = self.find_biggest_bank()
self.redistribute(i)
count += 1
return count
def solve2(self):
count = 0
target = self._banks.copy()
current = None
while current != target:
i = self.find_biggest_bank()
self.redistribute(i)
count += 1
current = self._banks.copy()
return count
r = Redistributor(banks)
print(r.solve())
print(r.solve2())
|
"""
Tracebacks: <<< __traceback__ >>>
-> Attribute on an exception object that holds a reference to the traceback object
-> traceback: Standard library module containing functions for working with traceback objects.
"""
"""
More Traceback Functions
-> There are many more functions in the traceback module
-> format_tb() can render a traceback to a string
"""
"""
Storing Tracebacks:
-> Rendering: Try to render a traceback within the scope of the except block
-> Stack frames: Tracebacks contain references to their stack frames and, thus, to all of the locals in
those frames.
-> Memory usage: The transitive closure over the stack frames can use a lot of memory, and it won't be garbage
collected until the traceback is released.
-> Transform: For longer term storage, render tracebacks into a different, more concise form suited to your needs.
"""
|
def test():
assert (
"if token.like_num" in __solution__
), "¿Estás revisando el atributo del token like_num?"
assert (
'next_token.text == "%"' in __solution__
), "¿Estás revisando si el texto del siguiente token es un símbolo de porcentaje?"
assert (
next_token.text == "%"
), "¿Estás revisando si el texto del siguiente token es un símbolo de porcentaje?"
__msg__.good(
"¡Bien hecho! Como puedes ver hay muchos análisis poderosos que puedes hacer usando los tokens y sus atributos."
)
|
prompt= "Enter a sentence which may be terminated by either’.’, ‘?’or’!’ only."
prompt += "The words may be separated by more than one blank space and are in UPPER CASE"
vowel=['A','E','I','O','U']
sentence = (input(prompt + "\n>"))
new_sentence = []
new_s = ""
new = ""
while True:
if sentence == sentence.upper():
if sentence[-1] == "." or sentence[-1] == "?" or sentence[-1] == "!":
break
else:
print("INVALID INPUT")
exit()
sentence = sentence.split()
last = sentence.pop()
last = list(last)
last.pop()
for i in last:
new = new + i
sentence.append(new)
for word in sentence:
if word[0] in vowel:
if word[-1] in vowel:
new_sentence.append(word)
sentence.remove(word)
print("NUMBER OF WORDS BEGINNIG AND ENDING WITH A VOWEL = " + str(len(new_sentence)))
for word in sentence:
new_sentence.append(word)
for word in new_sentence:
new_s = new_s + word + " "
print(new_s)
|
WordDic = {
# 形容词大类
'a': 'n2', # 形容词
'ad': 'n2', # 副行词
'ag': 'n2', # 形语素
'an': 'n2', # 名形词
'c': 'n16', # 连词
'b': 'n8', # 区别词
#副词大类
'd':'n11', #副词
'dg':'n11', #副语素
'e':'n18', #叹词
'f':'n4', #方位词
'i':'n23', #成语
'm':'n5', #数词
#名词大类
'n':'n0', #名词
'ng':'n0', #名语素
'nr':'n0', #人名
'ns':'n0', #地名
'nt':'n0', #机构团体
'nx':'n0', #字母专名
'nz':'n0', #其他专名
'o':'n13',#拟声词
'p':'n15',#介词
'r':'n6',#代词
's':'n7',#处所词
't':'n3',#时间词
'tg':'n3',#时语素
#助词大类
'u':'n17', #助词
'ud':'n17', #结构助词
'ug':'n17', #时态助词
'uj':'n17', #结构助词的
'ul': 'n17', # 时态助词了
'uv': 'n17', # 结构助词地
'uz': 'n17', # 结构助词着
#动词大类
'v':'n1', #动词
'vd': 'n1', #副动词
'vg': 'n1', # 动语素
'vn':'n1', #名动词
'w':'n19', #标点符号
'y':'n12', #语气词
'z': 'n9' #状态词
}
if __name__ == '__main__':
print(WordDic.setdefault('dy','n22'))
|
class ClientData:
"""
Class contains user info
"""
data = {}
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
counter = 1
curnode = head
while curnode.next is not None:
counter = counter + 1
curnode = curnode.next
counter = counter // 2
retnode = head
while counter > 0:
counter = counter - 1
retnode = retnode.next
return retnode
|
# https://leetcode.com/problems/search-a-2d-matrix
'''
Runtime Complexity: O(logNM)
Space Complexity: O(1)
'''
def search_matrix(matrix, target):
rows, columns = len(matrix), len(matrix[0])
start, end = 0, rows * columns - 1
while start <= end:
middle = (start + end) // 2
number = matrix[middle // columns][middle % columns]
if number == target:
return True
if target < number:
end = middle - 1
else:
start = middle + 1
return False
|
class PaginatorFactory(object):
def __init__(self, http_client):
self.http_client = http_client
def make(self, uri, data=None, union_key=None):
return Paginator(self.http_client, uri, data, union_key)
class Paginator(object):
def __init__(self, http_client, uri, data=None, union_key=None):
self.http_client = http_client
self.union_key = union_key
self.uri = uri
# Copy dictionary, defaulting to empty.
self.data = dict(data or {})
def page(self, page=0):
# Add page_index to the dictionary passed in request.
data = dict(self.data)
data['page_index'] = page - 1
return self.http_client.request(self.uri, data)
def all(self):
if not self.union_key:
raise ValueError("Union key parameter is missing")
union_result = []
data = dict(self.data)
page_num = 1
page_index = 0
while page_index < page_num:
data['page_index'] = page_index
page_result = self.http_client.request(self.uri, data)
page_num = page_result.get('page_num')
if page_num is None:
return page_result.get(self.union_key, [])
page_index = page_result.get('page_index') + 1
page_result = page_result.get(self.union_key, [])
union_result.extend(page_result)
return union_result
def __iter__(self):
if not self.union_key:
raise ValueError("Union key parameter is missing")
page_index = 0
data = dict(self.data)
while True:
data['page_index'] = page_index
whole_page_result = self.http_client.request(self.uri, data)
interesting_data = whole_page_result.get(self.union_key, [])
for entry in interesting_data:
yield entry
page_num = whole_page_result.get('page_num')
# Check if that was the last page.
if not page_num or page_index >= page_num - 1:
break
page_index += 1
|
def suppress_value(valuein: int, rc: str = "*", upper: int = 100000000) -> str:
"""
Suppress values less than or equal to 7, round all non-national values.
This function suppresses value if it is less than or equal to 7.
If value is 0 then it will remain as 0.
If value is at national level it will remain unsuppressed.
All other values will be rounded to the nearest 5.
Parameters
----------
valuein : int
Metric value
rc : str
Replacement character if value needs suppressing
upper : int
Upper limit for suppression of numbers
Returns
-------
out : str
Suppressed value (*), 0 or valuein if greater than 7 or national
Examples
--------
>>> suppress_value(3)
'*'
>>> suppress_value(24)
'25'
>>> suppress_value(0)
'0'
"""
base = 5
if not isinstance(valuein, int):
raise ValueError("The input: {} is not an integer.".format(valuein))
if valuein < 0:
raise ValueError("The input: {} is less than 0.".format(valuein))
elif valuein == 0:
valueout = str(valuein)
elif valuein >= 1 and valuein <= 7:
valueout = rc
elif valuein > 7 and valuein <= upper:
valueout = str(base * round(valuein / base))
else:
raise ValueError("The input: {} is greater than: {}.".format(valuein, upper))
return valueout
|
# Time: 93 ms
# Memory: 12 KB
n = int(input())
apy = list(map(int, input().split()))
apx = list(map(int, input().split()))
apset = set(apy[1:] + apx[1:])
# n*(n+1)//2 is 1 + 2 + 3... n
# https://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF
if sum(apset) == n*(n+1)//2:
print('I become the guy.')
else:
print('Oh, my keyboard!')
|
"""
znajdz największy palindrom utworzony poprzez przemnożenie przez siebie dwóch liczby 3-cyfrowych
odp:906609
"""
print("906609")
|
class Solution(object):
def isBadVersion(self, num):
return True
def firstBadVersion(self, n):
left, right = 1, n
while left <= right:
mid = left + (right - left)/2
if self.isBadVersion(mid):
right = mid - 1
else:
left = mid + 1
return left
|
#mengubah atau konversi tipe data
data = 20
print(data)
#konversi ke float
dataFloat = float(data)
print(dataFloat)
print(type(dataFloat))
#konversi sting
dataStr = str(data)
print(dataStr)
print(type(dataStr))
|
"""Object Oriented Programming Examples - Sprint 1, Module 2"""
# import pandas as pd
#
# class MyDataFrame(pd.DataFrame):
# def num_cells(self):
# return self.shape[0] * self.shape[1] # num cells of df
class BareMinimumClass:
pass
class Complex:
def __init__(self, real, imaginary):
"""
Constructor for Complex Numbers.
Complex numbers have a real part, and imaginary part
"""
self.r = real
self.i = imaginary
def add(self, other_complex):
self.r += other_complex.r
self.i += other_complex.i
def __repr__(self):
return "({}, {})".format(self.r, self.i)
class SocialMediaUser:
def __init__(self, name, location, upvotes=0):
self.name = str(name)
self.location = location
self.upvotes = int(upvotes)
def receive_upvotes(self, num_upvotes = 1):
self.upvotes += num_upvotes
def is_popular(self):
return self.upvotes > 100
class Animal:
""" General Representation of Animals"""
def __init__(self, name, weight, diet_type):
self.name = str(name)
self.weight = float(weight)
self.diet_type = diet_type
def run(self):
return "I am flying right now"
def eat(self, food):
return "I love eating " + food
class Sloth(Animal):
def __init__(self, name, weight, diet_type, num_naps=104):
super().__init__(name, weight, diet_type)
self.num_naps = float(num_naps)
def eat(self, food):
return "I really love eating"
if __name__ == "__main__":
num1 = Complex(3, -5) # num1.r =3, num1.i = -5
num2 = Complex(2, 6) # num2.r = 2, num2.i = 6
num1.add(num2)
print("num1.r: {}, num1.i: {}".format(num1.r, num1.i))
user1 = SocialMediaUser("Mena", "Boston", 300)
user2 = SocialMediaUser("John", "New York", 88)
user3 = SocialMediaUser("Alex", "Cambridge", 2000)
user4 = SocialMediaUser("Carl", "lagos", 99)
print(user1.is_popular())
print(user2.is_popular())
user2.receive_upvotes(25)
print(user2.is_popular())
print("Received {} upvotes".format(user2.upvotes))
print(user2.is_popular())
|
#Solution 1
def search_and_insert(nums, target):
for i in range(0, len(nums)):
if target == nums[i]:
return i
elif target <nums[i]:
return i
return i+1
#Solution 2
def search_and_insert2(nums, target):
start_index = 0
half_index = len(nums)//2
end_index = len(nums)
while True:
if target < nums[half_index]:
end_index = half_index
half_index = (start_index + half_index)//2
elif target > nums[half_index]:
start_index = half_index
half_index = (half_index + end_index)//2
if target == nums[half_index]:
return half_index
if (half_index == end_index or half_index == start_index) and target>nums[half_index]:
return half_index +1
if (half_index == end_index or half_index == start_index) and target<nums[half_index]:
return half_index
#Tests
def search_and_insert2_test():
input_nums = [1,3,5,6]
input_target1 = 5
input_target2 = 2
input_target3 = 7
input_target4 = 0
actual_output_k1 = search_and_insert2(input_nums, input_target1)
actual_output_k2 = search_and_insert2(input_nums, input_target2)
actual_output_k3 = search_and_insert2(input_nums, input_target3)
actual_output_k4 = search_and_insert2(input_nums, input_target4)
return actual_output_k1==2, actual_output_k2 ==1, actual_output_k3==4, actual_output_k4 == 0
print(search_and_insert2_test())
print(search_and_insert2([1,3,5,6], 5))
print(search_and_insert2([1,3,5,6], 2))
print(search_and_insert2([1,3,5,6], 7))
print(search_and_insert2([1,3,5,6], 0))
# #For leetcode
#Solution 1
class Solution(object):
def removeElement(self, nums, val):
holding_pointer = 0
for i in range(0, len(nums)):
if nums[i] != val:
nums[holding_pointer] = nums[i]
holding_pointer = holding_pointer +1
return holding_pointer
#Solution 2
class Solution(object):
def searchInsert(self, nums, target):
start_index = 0
half_index = len(nums)//2
end_index = len(nums)
while True:
if target < nums[half_index]:
end_index = half_index
half_index = (start_index + half_index)//2
elif target > nums[half_index]:
start_index = half_index
half_index = (half_index + end_index)//2
if target == nums[half_index]:
return half_index
if (half_index == end_index or half_index == start_index) and target>nums[half_index]:
return half_index +1
if (half_index == end_index or half_index == start_index) and target<nums[half_index]:
return half_index
|
# MIT License
# (C) Copyright 2021 Hewlett Packard Enterprise Development LP.
#
# regions : Set or get regions and region appliance associations
def get_all_regions(self) -> dict:
"""Get all regions
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - regions
- GET
- /regions
:return: Returns dictionary of configured regions
:rtype: dict
"""
return self._get("/regions")
def create_region(
self,
region: str,
) -> bool:
"""Create a new region
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - regions
- POST
- /regions
:param region: Name of the new region to be created
:type region: str
:return: Returns True/False based on successful call
:rtype: bool
"""
data = {"regionName": region}
return self._post(
"/regions",
data=data,
return_type="bool",
)
def get_region(
self,
region_id: int,
) -> dict:
"""Get region by ID
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - regions
- GET
- /regions/{regionId}
:param region_id: Numeric ID of region
:type region_id: int
:return: Returns dictionary of region
:rtype: dict
"""
return self._get("/regions/{}".format(region_id))
def update_region_name(
self,
region_id: int,
region_name: str,
) -> bool:
"""Update the name of an existing region
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - regions
- PUT
- /regions/{regionId}
:param region_id: Numeric ID of region
:type region_id: int
:param region_name: New name of the region
:type region_name: str
:return: Returns True/False based on successful call
:rtype: bool
"""
return self._put(
"/regions/{}".format(region_id),
expected_status=[204],
return_type="bool",
)
def delete_region(
self,
region_id: int,
) -> bool:
"""Delete a region by region ID
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - regions
- DELETE
- /regions/{regionId}
:param region_id: Numeric ID of region
:type region_id: int
:return: Returns True/False based on successful call
:rtype: bool
"""
return self._delete(
"/regions/{}".format(region_id),
expected_status=[204],
return_type="bool",
)
def get_region_appliance_association(self) -> dict:
"""Get all appliance/region associations
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - regions
- GET
- /regions/appliances
:return: Returns dictionary of appliance associations to regions
:rtype: dict
"""
return self._get("/regions/appliances")
def set_region_appliance_association(
self,
appliance_region_map: dict,
) -> bool:
"""Set association between appliances and regions. Can set one or
many associations.
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - regions
- POST
- /regions/appliances
:param appliance_region_map: Dictionary where each key/value pair is
an appliance nePk (e.g. ``3.NE``) and region_id.
e.g. {"3.NE":"1", "10.NE","2",...}
:type appliance_region_map: dict
:return: Returns True/False based on successful call
:rtype: bool
"""
return self._post(
"/regions",
data=appliance_region_map,
expected_status=[204],
return_type="bool",
)
def update_region_appliance_association(
self,
ne_pk: str,
region_id: int,
) -> bool:
"""Update association between appliance and regions.
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - regions
- PUT
- /regions/appliances/{nePk}
:param ne_pk: Network Primary Key (nePk) of existing appliance,
e.g. ``3.NE``
:type ne_pk: str
:param region_id: Numeric ID of region
:type region_id: int
:return: Returns True/False based on successful call
:rtype: bool
"""
data = {"regionId": region_id}
return self._put(
"/regions/appliances/{}".format(ne_pk),
data=data,
expected_status=[204],
return_type="bool",
)
def get_region_appliance_association_by_nepk(
self,
ne_pk: str,
) -> dict:
"""Get appliance/region association by nePk of appliance
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - regions
- GET
- /regions/appliances/nePk/{nePk}
:param ne_pk: Network Primary Key (nePk) of existing appliance,
e.g. ``3.NE``
:type ne_pk: str
:return: Returns dictionary of appliance association to region \n
* keyword **nePk** (`str`): Appliance NePK, e.g. ``3.NE``
* keyword **regionId** (`int`): Region ID, ``0`` is default
* keyword **regionName** (`str`): Region name
:rtype: dict
"""
return self._get("/regions/appliances/nePk/{}".format(ne_pk))
def get_region_appliance_association_by_region_id(
self,
region_id: int,
) -> dict:
"""Get all appliances associated with region
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - regions
- GET
- /regions/appliances/regionId/{regionId}
:param region_id: Numeric ID of region
:type region_id: int
:return: Returns dictionary of appliances associated to region
:rtype: dict
"""
return self._get("/regions/appliances/regionId/{}".format(region_id))
|
t = int(input())
answer = []
for a in range(t):
n = int(input())
if(n%4 == 0):
answer.append("YES")
else:
answer.append("NO")
for b in answer:
print(b)
|
#Faça um programa que leia três números e mostre qual é
# o maior e qual é o menor.
n1 = int(input('Primeiro valor: '))
n2 = int(input('Segundo valor: '))
n3 = int(input('Terceiro valor: '))
#MAIOR
'''if n1 > n2:
if n1 > n3:
ma = n1
if n2 > n1:
if n2 > n3:
ma = n2
if n3 > n1:
if n3 > n2:
ma = n3
#MENOR
if n1 < n2:
if n1 < n3:
me = n1
if n2 < n1:
if n2 < n3:
me = n2
if n3 < n1:
if n3 < n2:
me = n3'''
#Verificando qual é o menor
me = n1
if n2 < n1 and n2 < n3:
me = n2
if n3 < n1 and n3 < n2:
me = n3
#Verificando qual é o maior
ma = n1
if n2 > n1 and n2 > n3:
ma = n2
if n3 > n1 and n3 > n2:
ma = n3
print('O {} é o maior valor.'.format(ma))
print('O {} é o menor valor.'.format(me))
|
"""
Copyright (C) 2014 Maruf Maniruzzaman
Website: http://cosmosframework.com
Author: Maruf Maniruzzaman
License :: OSI Approved :: MIT License
"""
PASSWORD_HMAC_SIGNATURE = "hmac:"
PASSWORD_COLUMN_NAME = "password"
USERNAME_COLUMN_NAME = "username"
USER_COOKIE_NAME = "usersecret"
USER_PLAINTEXT_COOKIE_NAME = "user"
IDENTITY_TYPE_FB_GRAPH = 'fb_graph'
IDENTITY_TYPE_GOOGLE_OAUTH2 = "google_oauth2"
IDENTITY_TYPE_GITHUB_OAUTH2 = "github_oauth2"
IDENTITY_TYPE_OPEN_ID = "openid"
|
class Params:
"""
Validating input parameters and building jsons for chart init
-----
Attributes:
obj: a Chart object whose attributes will be checked and built by BuilderParams.
"""
def __init__(self,
obj):
"""
"""
self.obj = obj
def valid(self):
"""
Checks if the values for the given entries are valid.
"""
msg = 'width must be an int (number of pixels) or a string'
assert (isinstance(self.obj.width_in, int)
or isinstance(self.obj.width_in, str)), msg
msg = 'height must be an int (number of pixels)'
assert isinstance(self.obj.height_in, int), msg
li_theme = ['dark-unica',
'grid-light',
'sand-signika',
'']
# Empty string is a valid theme
msg = 'theme must be one of {}'.format(li_theme)
assert self.obj.theme in li_theme, msg
def build(self):
"""
Builds parameters of the chart
"""
# Convert width to string
if isinstance(self.obj.width_in, int):
self.obj.width = str(self.obj.width_in) + 'px'
else:
self.obj.width = self.obj.width_in
# Height
if self.obj.height_in == 0:
self.obj.height_in = 350
self.obj.height = str(self.obj.height_in) + 'px'
|
# when creating a function it can return nothing or it can return a value like so
# the return value can be any data type you wish including custom class you've made (see Object-oriented-programming file 1)
#main return nothing
def main():
result = sum(1, 5)
print(result)
# sum returns a inter or float depening on the arguments passed
def sum(*argv):
total = 0
for arg in argv:
total += arg
return total
if __name__ == "__main__":
main()
|
"""
Find the total area covered by two rectilinear rectangles in a 2D plane.
Each rectangle is defined by its bottom left corner and top right corner as
shown in the figure.
![Example layout]
(https://leetcode.com/static/images/problemset/rectangle_area.png)
Assume that the total area is never beyond the maximum possible value of int.
Credits:
Special thanks to @mithmatt for adding this problem, creating the above
image and all test cases.
"""
class Solution(object):
def computeArea(self, A, B, C, D, E, F, G, H):
"""
:type A: int
:type B: int
:type C: int
:type D: int
:type E: int
:type F: int
:type G: int
:type H: int
:rtype: int
"""
areaA=(C-A)*(D-B)
areaB=(G-E)*(H-F)
if (G-A)*(E-C)>=0 or (H-B)*(F-D)>=0:
areaO=0
else:
overlapX=min(abs(G-A),abs(C-E),abs(C-A),abs(G-E))
overlapY=min(abs(H-B),abs(D-F),abs(D-B),abs(H-F))
areaO=overlapX*overlapY
return areaA+areaB-areaO
|
"""
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of
every node never differ by more than 1.
"""
__author__ = 'Danyang'
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isBalanced(self, root):
"""
pre-order traversal
:param root: TreeNode
:return: boolean
"""
if not root:
return True
if abs(self.fathom(root.left, 0)-self.fathom(root.right, 0))>1:
return False
if self.isBalanced(root.left) and self.isBalanced(root.right):
return True
else:
return False
def fathom(self, root, depth):
"""
DFS
"""
if not root:
return depth-1 # test cases
return max(self.fathom(root.left, depth + 1), self.fathom(root.right, depth + 1))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def recursion(n):
if n == 1:
return 1
return n + recursion(n - 1)
def main():
n = int(input("Введите n = "))
summa = 0
for i in range(1, n + 1):
summa += i
print(f"Сумма посчитаная без рекурсии = {summa}")
print(f"Сумма посчитанная с помощью рекурсии = {recursion(n)}")
if __name__ == '__main__':
main()
|
class Airport:
def __init__(self, code, lat, lng, airportName):
self.code = code
self.lat = lat
self.lng = lng
self.name = airportName
self.flightCategory = None
self.isCalculated = False
|
def gcd(a,b = None):
if b != None:
if a % b == 0:
return b
else:
return gcd( b, a % b)
else:
for i in range(len(a)):
a[0] = gcd(a[0],a[i])
return a[0]
print(gcd([18,12, 6]))
print(gcd(9, 12))
|
#!/usr/bin/env python3
# Copyright 20
# Python provides the open() function for opening file
# open() opens the file in read-only default mode.
def main():
# open the file - open() returns a file object. It takes the file name and opens that file and returns
# a file object. The file object itself is a iterator, and so we can use a for loop and get one line at a time
# without having to buffer the entire file in memory
f = open('lines.txt', 'w') # opens it in write mode. a: append mode, r: read -only, r+ allows to read and write.
# read each line by line, stripping the new lines off the end of each line and display them
# rstrip() - each of the line is returned as a string and the string class has an R-strip method
# which will strip any white space, incl. new lines from the end of the line.
for line in f:
print(line.rstrip())
if __name__ == '__main__':
main()
|
#{
#Driver Code Starts
#Initial Template for Python 3
# } Driver Code Ends
#User function Template for python3
# Function to count even and odd
# c_e : variable to store even count
# c_o : variable to store odd count
def count_even_odd(n, arr):
c_e = 0
c_o = 0
pair = list()
# your code here
for i in range(0,n):
if(arr[i]%2==0):
c_e +=1
else:
c_o +=1
pair.append(c_e)
pair.append(c_o)
return pair
#{
#Driver Code Starts.
# Driver Code
def main():
# Testcase input
testcases = int(input())
# Looping through testcases
while(testcases > 0):
# size of array
size_array = int(input())
# array elements input
array = input().split()
# print (array)
arr = list()
for i in array:
arr.append(int(i))
# print (arr)
# calling function to count even odd
a = count_even_odd(size_array, arr)
print (a[0], a[1])
testcases -= 1
if __name__ == '__main__':
main()
#} Driver Code Ends
|
print('''
Exponent code
Exponent code
''')
print('''
def answer2(number, power):
result=1
for index in range(power):
result=result * number
return result
print(answer2(3,2))
''')
print('''
''')
def answer2(number, power):
result=1
for index in range(power):
result=result * number
return result
print(answer2(3,2))
|
"""
Part and parcel of daily life?
lol why the fuck only got 2 spaces per indent
"""
def projector():
"""9 per cohort class"""
switch_on = "Nope. Please call tech support"
raise Exception(switch_on)
def fire_alarm():
'''random'''
for _ in range(10):
print("Ladies and gentlemen, it was a false alarm. I repeat, it was a false alarm. Sorry for the inconvenience caused.")
def air_con(temp):
'''singapore so hot'''
if temp > 25:
print("TURN IT DOWN AND SAVE POWER")
else:
print("Please note it is centrally controlled and it will be set at 21 degrees")
|
def intersect(nums1, nums2):
"""
Given two arrays, write a function to compute their intersection.
:param nums1: list
:param nums2: list
:return: list
"""
nums1, nums2 = sorted(nums1), sorted(nums2)
pt1 = pt2 = 0
res = []
while True:
try:
if nums1[pt1] > nums2[pt2]:
pt2 += 1
elif nums1[pt1] < nums2[pt2]:
pt1 += 1
else:
res.append(nums1[pt1])
pt1 += 1
pt2 += 1
except IndexError:
break
return res
|
# test output stream only
print('begin')
for i in range(1, 5): # CHANGED FROM 20 TO 1,5
print('Spam!' * i)
print('end')
|
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def glm_repository():
maybe(
http_archive,
name = "glm",
urls = [
"https://github.com/g-truc/glm/archive/6ad79aae3eb5bf809c30bf1168171e9e55857e45.zip",
],
sha256 = "9a147a2b58df9fc30ec494468f6b974489a72aecbaa9062dd1d375379e011b70",
strip_prefix = "glm-6ad79aae3eb5bf809c30bf1168171e9e55857e45/",
build_file = "@third_party//glm:package.BUILD",
patches = [
"@third_party//glm:0001-Works-around-Visual-Studio-compiler-issue-with-std-c.patch",
],
patch_args = ["-p1"],
)
|
## -*- encoding: utf-8 -*-
"""
This file (./sol/nonlinear_doctest.sage) was *autogenerated* from ./sol/nonlinear.tex,
with sagetex.sty version 2011/05/27 v2.3.1.
It contains the contents of all the sageexample environments from this file.
You should be able to doctest this file with:
sage -t ./sol/nonlinear_doctest.sage
It is always safe to delete this file; it is not used in typesetting your
document.
Sage example in ./sol/nonlinear.tex, line 17::
sage: def intervalgen(f, phi, s, t):
....: assert (f(s) * f(t) < 0), \
....: 'Wrong arguments: f(%s) * f(%s) >= 0)'%(s, t)
....: yield s
....: yield t
....: while 1:
....: u = phi(s, t)
....: yield u
....: fu = f(u)
....: if fu == 0:
....: return
....: if fu * f(s) < 0:
....: t = u
....: else:
....: s = u
Sage example in ./sol/nonlinear.tex, line 40::
sage: f(x) = 4 * x - 1
sage: a, b = 0, 1
sage: phi(s, t) = (s + t) / 2
sage: list(intervalgen(f, phi, a, b))
[0, 1, 1/2, 1/4]
Sage example in ./sol/nonlinear.tex, line 49::
sage: from types import GeneratorType, FunctionType
sage: def checklength(u, v, w, prec):
....: return abs(v - u) < 2 * prec
sage: def iterate(series,check=checklength,prec=10^-5,maxit=100):
....: assert isinstance(series, GeneratorType)
....: assert isinstance(check, FunctionType)
....: niter = 2
....: v, w = next(series), next(series)
....: while (niter <= maxit):
....: niter += 1
....: u, v, w = v, w, next(series)
....: if check(u, v, w, prec):
....: print('After {0} iterations: {1}'.format(niter, w))
....: return
....: print('Failed after {0} iterations'.format(maxit))
Sage example in ./sol/nonlinear.tex, line 76::
sage: f(x) = 4 * sin(x) - exp(x) / 2 + 1
sage: a, b = RR(-pi), RR(pi)
sage: def phi(s, t): return RR.random_element(s, t)
sage: random = intervalgen(f, phi, a, b)
sage: iterate(random, maxit=10000) # random
After 19 iterations: 2.15848379485564
Sage example in ./sol/nonlinear.tex, line 93::
sage: basering.<x> = PolynomialRing(SR, 'x')
sage: p = x^2 + x
sage: p.roots(multiplicities=False)
[-1, 0]
Sage example in ./sol/nonlinear.tex, line 101::
sage: from collections import deque
sage: basering = PolynomialRing(SR, 'x')
sage: q, method = None, None
sage: def quadraticgen(f, r, s):
....: global q, method
....: t = r - f(r) / f.derivative()(r)
....: method = 'newton'
....: yield t
....: pts = deque([(p, f(p)) for p in (r, s, t)], maxlen=3)
....: while True:
....: q = basering.lagrange_polynomial(pts)
....: roots = [r for r in q.roots(multiplicities=False) \
....: if CC(r).is_real()]
....: approx = None
....: for root in roots:
....: if (root - pts[2][0]) * (root - pts[1][0]) < 0:
....: approx = root
....: break
....: elif (root - pts[0][0]) * (root - pts[1][0]) < 0:
....: pts.pop()
....: approx = root
....: break
....: if approx:
....: method = 'quadratic'
....: else:
....: method = 'dichotomy'
....: approx = (pts[1][0] + pts[2][0]) / 2
....: pts.append((approx, f(approx)))
....: yield pts[2][0]
Sage example in ./sol/nonlinear.tex, line 141::
sage: basering = PolynomialRing(SR, 'x')
sage: a, b = pi/2, pi
sage: f(x) = 4 * sin(x) - exp(x) / 2 + 1
sage: generator = quadraticgen(f, a, b)
sage: next(generator)
1/2*pi - (e^(1/2*pi) - 10)*e^(-1/2*pi)
"""
|
#Faça um Programa que leia um número inteiro menor que 1000 e imprima a quantidade de
#centenas, dezenas e unidades do mesmo.
#o Observando os termos no plural a colocação do "e", da vírgula entre outros. Exemplo:
#o 326 = 3 centenas, 2 dezenas e 6 unidades
#o 12 = 1 dezena e 2 unidades Testar com: 326, 300, 100, 320, 310,305, 301, 101, 311,
#111, 25, 20, 10, 21, 11, 1, 7 e 16
numb = int(input("Informe um numero(menor que 1000): "))
n = str(numb)
if(numb<1000):
if(n[0]==0):
if(n[1]==0):
if(n[2]==1):
print(" %.0f = %s unidade"%(numb,n[2]))
else:
print(" %.0f = %s unidades"%(numb,n[2]))
else:
if(n[1]==1):
if(n[2]==1):
print(" %.0f = %s dezena e %s unidade"%(numb,n[1],n[2]))
else:
print(" %.0f = %s dezena e %s unidades"%(numb,n[1],n[2]))
else:
if(n[2]==1):
print(" %.0f = %s dezenas e %s unidade"%(numb,n[1],n[2]))
else:
print(" %.0f = %s dezenas e %s unidades"%(numb,n[1],n[2]))
else:
if(n[0]==1):
if(n[1]==1):
if(n[2]==1):
print(" %.0f = %s centena, %s dezena e %s unidade"%(numb,n[0],n[1],n[2]))
else:
print(" %.0f = %s centena, %s dezena e %s unidades"%(numb,n[0],n[1],n[2]))
else:
if(n[2]==1):
print(" %.0f = %s centena, %s dezenas e %s unidade"%(numb,n[0],n[1],n[2]))
else:
print(" %.0f = %s centena, %s dezenas e %s unidades"%(numb,n[0],n[1],n[2]))
else:
if(n[1]==1):
if(n[2]==1):
print(" %.0f = %s centenas, %s dezena e %s unidade"%(numb,n[0],n[1],n[2]))
else:
print(" %.0f = %s centenas, %s dezena e %s unidades"%(numb,n[0],n[1],n[2]))
else:
if(n[2]==1):
print(" %.0f = %s centenas, %s dezenas e %s unidade"%(numb,n[0],n[1],n[2]))
else:
print(" %.0f = %s centenas, %s dezenas e %s unidades"%(numb,n[0],n[1],n[2]))
else:
print("Numero invalido")
|
min_computer_fish_size = 0.25
max_computer_fish_size = 3.7
min_computer_fish_speed = 100
max_computer_fish_speed = 500
player_fish_speed = 400
player_start_size = min_computer_fish_size*1.2
player_win_size = max_computer_fish_size*1.2
player_start_size_acceleration_time_constant = 0.13
player_final_size_acceleration_time_constant = 0.3
|
#
# PySNMP MIB module CISCO-COMMON-ROLES-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-COMMON-ROLES-EXT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:36: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)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint")
ccrmConfigurationExtGroup, = mibBuilder.importSymbols("CISCO-COMMON-ROLES-MIB", "ccrmConfigurationExtGroup")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
ModuleIdentity, iso, ObjectIdentity, MibIdentifier, Counter64, TimeTicks, Integer32, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Unsigned32, Bits, NotificationType, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "iso", "ObjectIdentity", "MibIdentifier", "Counter64", "TimeTicks", "Integer32", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Unsigned32", "Bits", "NotificationType", "Gauge32")
DisplayString, TextualConvention, RowStatus, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "RowStatus", "TruthValue")
ciscoCommonRolesExtMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 651))
ciscoCommonRolesExtMIB.setRevisions(('2008-02-15 00:00',))
if mibBuilder.loadTexts: ciscoCommonRolesExtMIB.setLastUpdated('200802150000Z')
if mibBuilder.loadTexts: ciscoCommonRolesExtMIB.setOrganization('Cisco Systems Inc.')
ciscoCommonRolesExtNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 0))
ciscoCommonRolesExtMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 1))
ciscoCommonRolesExtMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 2))
ccreInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1))
ccreRoleConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2))
ccreRuleConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3))
class CcreOperation(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("read", 1), ("readWrite", 2))
class CcreResourceAccess(TextualConvention, Bits):
status = 'current'
namedValues = NamedValues(("vsan", 0), ("vlan", 1), ("interface", 2))
ccreFeatureElementTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1), )
if mibBuilder.loadTexts: ccreFeatureElementTable.setStatus('current')
ccreFeatureElementEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-COMMON-ROLES-EXT-MIB", "ccreFeatureName"), (0, "CISCO-COMMON-ROLES-EXT-MIB", "ccreFeatureElementIndex"))
if mibBuilder.loadTexts: ccreFeatureElementEntry.setStatus('current')
ccreFeatureName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32)))
if mibBuilder.loadTexts: ccreFeatureName.setStatus('current')
ccreFeatureElementIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1, 1, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295)))
if mibBuilder.loadTexts: ccreFeatureElementIndex.setStatus('current')
ccreFeatureElementName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ccreFeatureElementName.setStatus('current')
ccreFeatureElementType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("command", 1), ("feature", 2), ("none", 3)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ccreFeatureElementType.setStatus('current')
ccreFeatureRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ccreFeatureRowStatus.setStatus('current')
ccreRoleTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 2), )
if mibBuilder.loadTexts: ccreRoleTable.setStatus('current')
ccreRoleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 2, 1), ).setIndexNames((0, "CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleName"))
if mibBuilder.loadTexts: ccreRoleEntry.setStatus('current')
ccreRoleName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 16)))
if mibBuilder.loadTexts: ccreRoleName.setStatus('current')
ccreRoleDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 2, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ccreRoleDescription.setStatus('current')
ccreRoleResourceAccess = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 2, 1, 3), CcreResourceAccess()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ccreRoleResourceAccess.setStatus('current')
ccreRoleRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 2, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ccreRoleRowStatus.setStatus('current')
ccreRoleScopeTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 3), )
if mibBuilder.loadTexts: ccreRoleScopeTable.setStatus('current')
ccreRoleScopeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 3, 1), ).setIndexNames((0, "CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleName"), (0, "CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleScopeIndex"))
if mibBuilder.loadTexts: ccreRoleScopeEntry.setStatus('current')
ccreRoleScopeIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 3, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295)))
if mibBuilder.loadTexts: ccreRoleScopeIndex.setStatus('current')
ccreRoleScopeRestriction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("vsan", 1), ("vlan", 2), ("interface", 3)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ccreRoleScopeRestriction.setStatus('current')
ccreRoleScopeValue = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ccreRoleScopeValue.setStatus('current')
ccreRoleScopeRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 3, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ccreRoleScopeRowStatus.setStatus('current')
ccreRuleTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2), )
if mibBuilder.loadTexts: ccreRuleTable.setStatus('current')
ccreRuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1), ).setIndexNames((0, "CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleName"), (0, "CISCO-COMMON-ROLES-EXT-MIB", "ccreRuleNumber"))
if mibBuilder.loadTexts: ccreRuleEntry.setStatus('current')
ccreRuleNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 256)))
if mibBuilder.loadTexts: ccreRuleNumber.setStatus('current')
ccreRuleFeatureElementName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32)).clone(hexValue="")).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ccreRuleFeatureElementName.setStatus('current')
ccreRuleFeatureElementType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("command", 1), ("feature", 2), ("featureGroup", 3), ("all", 4)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ccreRuleFeatureElementType.setStatus('current')
ccreRuleOperation = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1, 4), CcreOperation()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ccreRuleOperation.setStatus('current')
ccreRuleOperationPermitted = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1, 5), TruthValue().clone('true')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ccreRuleOperationPermitted.setStatus('current')
ccreRuleRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1, 6), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ccreRuleRowStatus.setStatus('current')
ccreMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 2, 1))
ccreMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 2, 2))
ccreMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 651, 2, 1, 1)).setObjects(("CISCO-COMMON-ROLES-EXT-MIB", "ccreConfigurationGroup"), ("CISCO-COMMON-ROLES-MIB", "ccrmConfigurationExtGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ccreMIBCompliance = ccreMIBCompliance.setStatus('current')
ccreConfigurationGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 651, 2, 2, 1)).setObjects(("CISCO-COMMON-ROLES-EXT-MIB", "ccreFeatureElementName"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreFeatureElementType"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreFeatureRowStatus"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleDescription"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleResourceAccess"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleRowStatus"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleScopeRestriction"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleScopeValue"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleScopeRowStatus"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRuleFeatureElementName"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRuleFeatureElementType"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRuleOperation"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRuleOperationPermitted"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRuleRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ccreConfigurationGroup = ccreConfigurationGroup.setStatus('current')
mibBuilder.exportSymbols("CISCO-COMMON-ROLES-EXT-MIB", ccreRoleName=ccreRoleName, ccreMIBCompliance=ccreMIBCompliance, ccreRoleTable=ccreRoleTable, ccreRuleEntry=ccreRuleEntry, ciscoCommonRolesExtNotifications=ciscoCommonRolesExtNotifications, ccreRoleEntry=ccreRoleEntry, ccreRuleTable=ccreRuleTable, ccreFeatureElementIndex=ccreFeatureElementIndex, ccreRoleConfig=ccreRoleConfig, ccreRuleOperation=ccreRuleOperation, PYSNMP_MODULE_ID=ciscoCommonRolesExtMIB, ccreFeatureElementName=ccreFeatureElementName, ccreFeatureRowStatus=ccreFeatureRowStatus, ccreFeatureElementTable=ccreFeatureElementTable, ccreRuleFeatureElementName=ccreRuleFeatureElementName, ccreRuleRowStatus=ccreRuleRowStatus, ccreInfo=ccreInfo, ccreRuleNumber=ccreRuleNumber, ccreConfigurationGroup=ccreConfigurationGroup, ccreRoleScopeValue=ccreRoleScopeValue, ccreRuleOperationPermitted=ccreRuleOperationPermitted, ccreRoleScopeIndex=ccreRoleScopeIndex, ccreRuleFeatureElementType=ccreRuleFeatureElementType, ccreRoleScopeRestriction=ccreRoleScopeRestriction, ccreRoleScopeTable=ccreRoleScopeTable, ciscoCommonRolesExtMIB=ciscoCommonRolesExtMIB, CcreOperation=CcreOperation, ccreRoleScopeEntry=ccreRoleScopeEntry, ccreRoleDescription=ccreRoleDescription, CcreResourceAccess=CcreResourceAccess, ccreMIBGroups=ccreMIBGroups, ccreFeatureElementType=ccreFeatureElementType, ciscoCommonRolesExtMIBObjects=ciscoCommonRolesExtMIBObjects, ccreMIBCompliances=ccreMIBCompliances, ccreRuleConfig=ccreRuleConfig, ciscoCommonRolesExtMIBConformance=ciscoCommonRolesExtMIBConformance, ccreRoleScopeRowStatus=ccreRoleScopeRowStatus, ccreRoleResourceAccess=ccreRoleResourceAccess, ccreRoleRowStatus=ccreRoleRowStatus, ccreFeatureName=ccreFeatureName, ccreFeatureElementEntry=ccreFeatureElementEntry)
|
#!/usr/bin/env python3
# coding:utf-8
def get_num(num_lst):
global count # count 是循环的重点
if len(num_lst) == 1: # num_lst=1 的时候,剩下的是答案
print("\nThe lucky number is:", num_lst[0])
else:
length = len(num_lst)
for i in range(length):
if count == 3: # 数到 3 出场
num_lst[i] = 0
count = 1
else:
count += 1
for j in range(length-1, -1, -1):
if num_lst[j] == 0: # 删除退出的值;把非零值加到新列表也行
del num_lst[j]
get_num(num_lst) # 数组已经改变,重新调用一次函数,此时 count 不变
def run():
n = int(input("Please enter a number of people: "))
num_lst = list( range(1, n+1))
get_num(num_lst)
if __name__ == '__main__':
count = 1
run()
|
# coding=utf-8
# python3
# https://leetcode.com/problems/combination-sum/
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
candidates.sort()
self.dfs(candidates, target, 0, res, [])
return res
def dfs(self, nums, target, index, res, path):
if target < 0:
return
elif target == 0:
res.append(path)
return
for i in xrange(index, len(nums)):
if nums[index] > target:
return
self.dfs(nums, target - nums[i], i, res, path + [nums[i]])
|
# x_2_6
#
# 問題を準備中です
first_name = '山田'
last_name = '太郎'
members = ['桃太郎', 'いぬ', 'さる', 'きじ']
fruits = {'apple': 'りんご', 'banana': 'バナナ'}
def change_first_name():
global first_name
first_name = '山村'
def change_last_name():
last_name = '四郎'
def change_list():
members[2] = 'ゴリラ'
def change_dict():
fruits['grape'] = 'ぶどう'
change_first_name()
change_last_name()
change_list()
change_dict()
def print_global_variables():
print(first_name + last_name)
print(members)
print(fruits)
print_global_variables()
|
class ServerCommands(dict):
def __init__(self):
super().__init__()
self.update({
'!connect': 'on_client_connect',
'!disconnect': 'on_client_disconnect'
})
def register_command(self, command, callback_name):
self[command] = callback_name
def remove_command(self, command):
try:
del self[command]
return True
except KeyError:
return False
def get_command(self, get_command):
try:
self[get_command]
except KeyError:
return None
|
# _*_ coding: utf-8 _*_
__author__ = "吴飞鸿"
__date__ = "2019/11/26 0:54"
# 吴川一中2014届
URL_1 = 'https://weibo.com/p/1005052698466184/follow?relate=fans'
# 吴川一中
URL_2 = 'https://weibo.com/p/1005051916867493/follow?relate=fans'
|
# Get input
N, M = map(int, input().split()) # N - the number of restaurants, M - the number of pho restaurants
pho = list(map(int, input().split())) # A list of the pho restaurants
phos = [False for x in range(N)]
leaves = [True for x in range(N)]
paths = [[] for x in range(N)]
nodes = [False for x in range(N)]
total = 0 # The total of the tree
ind = [x for x in range(N)]
dists = [1 for x in range(N)]
maxdist = 0 # The longest distance in the tree
def mark(curr, prev): # goes through each of the nodes recursively, setting it to true if it is a pho restaurant
if phos[curr] and not nodes[curr]: # If the current node is a pho restaurant
nodes[curr] = True # The current node is included in the subtree
global total
total += 2
for i in paths[curr]: # For all of the connections of this node
if i != prev: # If it was not the previous one
mark(i, curr) # We go through the connections of that node as well
if nodes[i] and not nodes[curr]: # If it is a pho restaurant and the current one is not
nodes[curr] = True # This one must also be included in the subtree
global total
total += 2
def depthFirstSearch(curr, prev, dist):
for i in paths[curr]:
if i != prev and nodes[i]:
depthFirstSearch(i, curr, dist+1)
if dists[i]+1 > dists[curr]:
dists[curr] = dists[i]+1
ind[curr] = ind[i]
def depthFirstSearch2(curr, prev, dist):
global maxdist
if dist > maxdist:
maxdist = dist
for i in paths[curr]:
if i != prev and nodes[i]:
depthFirstSearch2(i, curr, dist+1)
for i in range(M):
phos[pho[i]] = True
for i in range(N-1):
a, b = map(int, input().split())
paths[a].append(b)
paths[b].append(a)
mark(pho[0], -1)
depthFirstSearch(pho[0], -1, 0)
depthFirstSearch2(ind[pho[0]], -1, 0)
total -= 2
print(total - maxdist)
|
#entrada
while True:
n = int(input())
if n == 0:
break
for i in range(0, n):
planeta, anoRecebida, tempo = str(input()).split()
anoRecebida = int(anoRecebida)
tempo = int(tempo)
#processamento
if i == 0:
primeira = anoRecebida - tempo
firstPlanet = planeta
if anoRecebida - tempo < primeira:
primeira = anoRecebida - tempo
firstPlanet = planeta
#saida
print(firstPlanet)
|
#
# PySNMP MIB module CISCO-WAN-CES-PORT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WAN-CES-PORT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:20:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "SingleValueConstraint")
circuitEmulation, = mibBuilder.importSymbols("BASIS-MIB", "circuitEmulation")
ciscoWan, = mibBuilder.importSymbols("CISCOWAN-SMI", "ciscoWan")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
NotificationType, ObjectIdentity, Integer32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, TimeTicks, Counter64, iso, Counter32, Unsigned32, Gauge32, Bits, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "ObjectIdentity", "Integer32", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "TimeTicks", "Counter64", "iso", "Counter32", "Unsigned32", "Gauge32", "Bits", "IpAddress")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
ciscoWanCesPortMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 351, 150, 40))
ciscoWanCesPortMIB.setRevisions(('2002-11-13 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: ciscoWanCesPortMIB.setRevisionsDescriptions(('Initial version of the MIB. The content of this MIB was originally available in CISCO-WAN-AXIPOP-MIB defined using SMIv1. The applicable objects from CISCO-WAN-AXIPOP-MIB are defined using SMIv2 in this MIB. Also the descriptions of some of the objects have been modified.',))
if mibBuilder.loadTexts: ciscoWanCesPortMIB.setLastUpdated('200211130000Z')
if mibBuilder.loadTexts: ciscoWanCesPortMIB.setOrganization('Cisco Systems, Inc.')
if mibBuilder.loadTexts: ciscoWanCesPortMIB.setContactInfo(' Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: [email protected]')
if mibBuilder.loadTexts: ciscoWanCesPortMIB.setDescription('The MIB module to configure the Circuit Emulation Service(CES) ports.')
cesmPort = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1))
cesmPortCnfGrp = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1))
cesmPortCnfGrpTable = MibTable((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1), )
if mibBuilder.loadTexts: cesmPortCnfGrpTable.setStatus('current')
if mibBuilder.loadTexts: cesmPortCnfGrpTable.setDescription('The config table is for CES logical port. This is used for configuring the port type and number of DS0s and number of Subcircuits in DS0 on the CES port.')
cesmPortCnfGrpEntry = MibTableRow((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-WAN-CES-PORT-MIB", "cesPortNum"))
if mibBuilder.loadTexts: cesmPortCnfGrpEntry.setStatus('current')
if mibBuilder.loadTexts: cesmPortCnfGrpEntry.setDescription('An entry for each logical port. Each entry contains information on the port type, DS0s configured and number of DS0 subcircuits.')
cesPortNum = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2048))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cesPortNum.setStatus('current')
if mibBuilder.loadTexts: cesPortNum.setDescription('This object identifies the logical port number. The range support depends upon the type of the service module(Card). - 8 port T1 Card, range is 1..192. - 8 port E1 Card, range is 1..248. - 1 port T3 Card, range is 1..1. Range is caclulated as follows. This can be used for calculating the range for other type of cards. For T1 Card: (24 * Number of T1 Ports) For E1 Card: (31 * Number of E1 Ports).')
cesPortRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("add", 1), ("del", 2), ("mod", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cesPortRowStatus.setStatus('current')
if mibBuilder.loadTexts: cesPortRowStatus.setDescription('This variable enables or modifies the port 1 - add : Add a logical port 2 - del : Delete a logical port 3 - mod : Modify a logical port.')
cesPortLineNum = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 128))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cesPortLineNum.setStatus('current')
if mibBuilder.loadTexts: cesPortLineNum.setDescription('This object represents the line number to which this port is associated. The supported range depends upon the type of service module(card).')
cesPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("structured", 1), ("unstructured", 2), ("framingOnVcDisconnect", 3), ("strau", 4)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cesPortType.setStatus('current')
if mibBuilder.loadTexts: cesPortType.setDescription('This object represents port type whether it is carrying subrate circuits. structured : This is for SDT(Structured Data Transfer). This type of port supports following features: * intended to emulate point-to-point fractional DS1 or E1 circuit. * Synchronous timing * Fractional(Nx64 Kbps)DS1/E1 service (Contiguous timeslots only).You can map an Nx64 Kbps channel to any Virtual Channel(VC). unstructured : This is for unstructured data transfer(UDT) All the DS0 time slots are allocated. This type of port supports following features: * intended to emulate point-to-point DS1 or E1 circuit. * Synchronous and Asynchronous timing framingOnVcDisconnect : similar to unstructured during normal operation. In case of channel failure line data will be looped back towards line. strau : only one DS0 time slot is allocated. The value strau(4) value is not supported in CESM-8T1/E1 or CESM-T3E3. CESM-T3E3 card supports value unstructured(2) only.')
cesPortDs0ConfigBitMap = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cesPortDs0ConfigBitMap.setStatus('current')
if mibBuilder.loadTexts: cesPortDs0ConfigBitMap.setDescription('This represents bit map of DS0s for a line which are used to form this logical port. Bit 0 represents DS0-1.')
cesPortNumOfDs0Slot = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 32))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cesPortNumOfDs0Slot.setStatus('current')
if mibBuilder.loadTexts: cesPortNumOfDs0Slot.setDescription('This represents number of DS0 time slots configured to this Port. If the cesPortType is strau(4), then this can not have more than 1 DS0 time slot.')
cesPortNumOfSCIPerDS0 = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8)).clone(4)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cesPortNumOfSCIPerDS0.setStatus('current')
if mibBuilder.loadTexts: cesPortNumOfSCIPerDS0.setDescription('This object represents number of subcircuit in the DS0 time slot. This is applicable only when cesPortType is strau(4). 8 = there are 8 no .of 8kbps links (1 bit) 4 = there are 4 no .of 16kbps links (2 bit) 2 = there are 2 no .of 32kbps links (4 bit) Currently not supported in CESM-8.')
cesPortSpeed = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 44736))).setUnits('kbps').setMaxAccess("readonly")
if mibBuilder.loadTexts: cesPortSpeed.setStatus('current')
if mibBuilder.loadTexts: cesPortSpeed.setDescription('This object identifies the configured speed of port. Max speed for T1 = 1544 Max speed for E1 = 2038 Max speed for T3 = 44736 Max speed for E3 = 34368.')
cesPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("notConfigured", 1), ("active", 2), ("remoteLoopback", 3), ("failedDueToLine", 4), ("failedDueToSignalling", 5), ("inactive", 6), ("inBert", 7), ("farEndRemoteLoopback", 8))).clone('notConfigured')).setMaxAccess("readonly")
if mibBuilder.loadTexts: cesPortState.setStatus('current')
if mibBuilder.loadTexts: cesPortState.setDescription('This variable indicates the state of the logical port. The possible values are : notConfigured (1) : Port is not configured active (2) : Port is in active state remoteLoopback (3) : Remote Loopback is set failedDueToLine(4) : Port failed due to some failure in physical line failedDueToSignalling(5) : Port failed due to some Signalling issues. inactive (6) : Port is not active inBert (7) : Bit Error Rate Test(BERT) in progress. farEndRemoteLoopback(8): Far End is in loopback.')
cesPortBERTEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disable", 1), ("enable", 2))).clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cesPortBERTEnable.setStatus('current')
if mibBuilder.loadTexts: cesPortBERTEnable.setDescription('This variable enables/disables BERT. This object is not supported in CESM-T3E3.')
cesPortNextAvailable = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2048))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cesPortNextAvailable.setStatus('current')
if mibBuilder.loadTexts: cesPortNextAvailable.setDescription("This variable contains the next UNUSED logical port number of the possible 32 DS0s * n ports. This number can be used in channel config table, the cesportNextAvailable gets updated if the number gets used to create a logical port. A '0' indicates that no more ports are available.")
cesPortsUsedLine1 = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cesPortsUsedLine1.setStatus('current')
if mibBuilder.loadTexts: cesPortsUsedLine1.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 1')
cesPortsUsedLine2 = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cesPortsUsedLine2.setStatus('current')
if mibBuilder.loadTexts: cesPortsUsedLine2.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 2.')
cesPortsUsedLine3 = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cesPortsUsedLine3.setStatus('current')
if mibBuilder.loadTexts: cesPortsUsedLine3.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 3')
cesPortsUsedLine4 = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cesPortsUsedLine4.setStatus('current')
if mibBuilder.loadTexts: cesPortsUsedLine4.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1. This is for line 4')
cesPortsUsedLine5 = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cesPortsUsedLine5.setStatus('current')
if mibBuilder.loadTexts: cesPortsUsedLine5.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 5')
cesPortsUsedLine6 = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cesPortsUsedLine6.setStatus('current')
if mibBuilder.loadTexts: cesPortsUsedLine6.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 6')
cesPortsUsedLine7 = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cesPortsUsedLine7.setStatus('current')
if mibBuilder.loadTexts: cesPortsUsedLine7.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 7')
cesPortsUsedLine8 = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cesPortsUsedLine8.setStatus('current')
if mibBuilder.loadTexts: cesPortsUsedLine8.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 8')
ciscoWanCesPortMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 40, 2))
ciscoWanCesPortMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 40, 2, 1))
ciscoWanCesPortMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 40, 2, 2))
ciscoWanCesPortCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 351, 150, 40, 2, 2, 1)).setObjects(("CISCO-WAN-CES-PORT-MIB", "ciscoWanCesPortConfGroup"), ("CISCO-WAN-CES-PORT-MIB", "ciscoWanCesPortDs0InDs1Group"), ("CISCO-WAN-CES-PORT-MIB", "ciscoWanCesPortsUsedGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoWanCesPortCompliance = ciscoWanCesPortCompliance.setStatus('current')
if mibBuilder.loadTexts: ciscoWanCesPortCompliance.setDescription('The compliance statement for objects related to CES Logical Ports.')
ciscoWanCesPortsUsedGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 351, 150, 40, 2, 1, 1)).setObjects(("CISCO-WAN-CES-PORT-MIB", "cesPortNextAvailable"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoWanCesPortsUsedGroup = ciscoWanCesPortsUsedGroup.setStatus('current')
if mibBuilder.loadTexts: ciscoWanCesPortsUsedGroup.setDescription('The collection of objects which are applicable for general information about logical ports.')
ciscoWanCesPortConfGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 351, 150, 40, 2, 1, 2)).setObjects(("CISCO-WAN-CES-PORT-MIB", "cesPortNum"), ("CISCO-WAN-CES-PORT-MIB", "cesPortRowStatus"), ("CISCO-WAN-CES-PORT-MIB", "cesPortLineNum"), ("CISCO-WAN-CES-PORT-MIB", "cesPortType"), ("CISCO-WAN-CES-PORT-MIB", "cesPortDs0ConfigBitMap"), ("CISCO-WAN-CES-PORT-MIB", "cesPortNumOfDs0Slot"), ("CISCO-WAN-CES-PORT-MIB", "cesPortNumOfSCIPerDS0"), ("CISCO-WAN-CES-PORT-MIB", "cesPortSpeed"), ("CISCO-WAN-CES-PORT-MIB", "cesPortState"), ("CISCO-WAN-CES-PORT-MIB", "cesPortBERTEnable"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoWanCesPortConfGroup = ciscoWanCesPortConfGroup.setStatus('current')
if mibBuilder.loadTexts: ciscoWanCesPortConfGroup.setDescription('The collection of objects which are used to represent Circuit Emulation Service Port information.')
ciscoWanCesPortDs0InDs1Group = ObjectGroup((1, 3, 6, 1, 4, 1, 351, 150, 40, 2, 1, 3)).setObjects(("CISCO-WAN-CES-PORT-MIB", "cesPortsUsedLine1"), ("CISCO-WAN-CES-PORT-MIB", "cesPortsUsedLine2"), ("CISCO-WAN-CES-PORT-MIB", "cesPortsUsedLine3"), ("CISCO-WAN-CES-PORT-MIB", "cesPortsUsedLine4"), ("CISCO-WAN-CES-PORT-MIB", "cesPortsUsedLine5"), ("CISCO-WAN-CES-PORT-MIB", "cesPortsUsedLine6"), ("CISCO-WAN-CES-PORT-MIB", "cesPortsUsedLine7"), ("CISCO-WAN-CES-PORT-MIB", "cesPortsUsedLine8"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoWanCesPortDs0InDs1Group = ciscoWanCesPortDs0InDs1Group.setStatus('current')
if mibBuilder.loadTexts: ciscoWanCesPortDs0InDs1Group.setDescription('The collection of objects related to information on DS0 time slots used in each DS1 line.')
mibBuilder.exportSymbols("CISCO-WAN-CES-PORT-MIB", cesPortNum=cesPortNum, ciscoWanCesPortCompliance=ciscoWanCesPortCompliance, PYSNMP_MODULE_ID=ciscoWanCesPortMIB, cesPortDs0ConfigBitMap=cesPortDs0ConfigBitMap, cesmPort=cesmPort, cesPortsUsedLine8=cesPortsUsedLine8, ciscoWanCesPortsUsedGroup=ciscoWanCesPortsUsedGroup, cesmPortCnfGrpTable=cesmPortCnfGrpTable, cesmPortCnfGrp=cesmPortCnfGrp, cesPortNextAvailable=cesPortNextAvailable, cesPortsUsedLine5=cesPortsUsedLine5, ciscoWanCesPortMIBConformance=ciscoWanCesPortMIBConformance, ciscoWanCesPortConfGroup=ciscoWanCesPortConfGroup, cesPortsUsedLine6=cesPortsUsedLine6, ciscoWanCesPortMIBGroups=ciscoWanCesPortMIBGroups, cesPortState=cesPortState, cesPortsUsedLine3=cesPortsUsedLine3, cesPortBERTEnable=cesPortBERTEnable, cesPortSpeed=cesPortSpeed, cesmPortCnfGrpEntry=cesmPortCnfGrpEntry, cesPortsUsedLine4=cesPortsUsedLine4, cesPortsUsedLine7=cesPortsUsedLine7, cesPortType=cesPortType, cesPortNumOfDs0Slot=cesPortNumOfDs0Slot, cesPortLineNum=cesPortLineNum, cesPortRowStatus=cesPortRowStatus, cesPortsUsedLine1=cesPortsUsedLine1, ciscoWanCesPortMIBCompliances=ciscoWanCesPortMIBCompliances, ciscoWanCesPortDs0InDs1Group=ciscoWanCesPortDs0InDs1Group, ciscoWanCesPortMIB=ciscoWanCesPortMIB, cesPortsUsedLine2=cesPortsUsedLine2, cesPortNumOfSCIPerDS0=cesPortNumOfSCIPerDS0)
|
class ScopeError(Exception):
pass
class ScopeFormatError(ScopeError):
pass
class PendingExperimentsError(ValueError):
pass
class MissingArchivePathError(FileNotFoundError):
pass
class AsymmetricCorrelationError(ValueError):
"""Two conflicting values are given for correlation of two parameters."""
class DistributionTypeError(TypeError):
"""The distribution is expected to be continuous but it is actually discrete, or vice versa."""
class DistributionFreezeError(Exception):
"""An error is thrown when creating an rv_frozen object."""
|
class Frame:
def __init__(self, resume: int, store: int, locals_: list, arguments: list):
self.stack = []
self.locals = []
for i in range(len(locals_)):
self.locals.append(locals_[i])
if len(arguments) > i:
self.locals[i] == arguments[i]
self.arg_count = len(arguments)
self.resume = resume
self.store = store
def empty(self):
self.stack = []
self.locals = []
self.arg_count = 0
self.resume = 0
self.store = None
@classmethod
def from_bytes(cls, bytes_: bytearray) -> cls:
resume = 0
resume += (bytes_[0] << 16)
resume += (bytes_[1] << 8)
resume += bytes_[2]
flags = bytes_[3]
has_store = (flags & 0b0001_0000) == 0
num_locals = flags & 0b0000_1111
store = bytes_[4] if has_store else None
mask = bytes_[5]
arg_count = 0
for bit in range(7):
if (mask & (1 << bit)) != 0:
arg_count += 1
stack_length = 0
stack_length += bytes_[6] << 8
stack_length += bytes_[7]
locals_ = []
stack = []
index = 8
for offset in range(num_locals):
word = 0
word += bytes_[index + offset * 2] << 8
word += bytes_[index + offset * 2 + 1]
locals_.append(word)
index += num_locals * 2
for offset in range(stack_length):
word = 0
word += bytes_[index + offset * 2] << 8
word += bytes_[index + offset * 2 + 1]
stack.append(word)
new_frame = cls(resume, store, locals_, [])
new_frame.arg_count = arg_count
return new_frame
def read_local(self, index: int) -> int:
return self.locals[index]
def write_local(self, index: int, value: int):
self.locals[index] = value
def stack_push(self, value: int):
self.stack.append(value)
def stack_pop(self) -> int:
return self.stack.pop()
def stack_peek(self) -> int:
return self.stack[-1]
def to_string(self) -> str:
return "--- to do ---"
def to_list(self) -> list:
bytes_ = []
bytes_.append((self.resume & 0xFF_0000) >> 16)
bytes_.append((self.resume & 0x00_FF00) >> 8)
bytes_.append(self.resume & 0x00_00FF)
flags = len(self.locals)
if self.store:
flags += 0b0001_0000
args_supplied = 0
for bit in range(self.arg_count):
args_supplied |= 1 << bit
bytes_.append(flags)
bytes_.append(self.store or 0)
bytes_.append(args_supplied)
stack_length = len(self.stack)
bytes_.append((stack_length & 0xFF00) >> 8)
bytes_.append(stack_length & 0x00FF)
for local in self.locals:
bytes_.append((local & 0xFF00) >> 8)
bytes_.append(local & 0x00FF)
for var in self.stack:
bytes_.append((var & 0xFF00) >> 8)
bytes_.append(var & 0x00FF)
return bytes_
|
#will ask the user for their age and then it will
#tell them how many months that age equals to
user_age = input("Enter your age : ")
years = int(user_age)
months = years * 12
print(f"Your age, {years}, equals to {months} months.")
|
a = [_.split('\t') for _ in open('a.txt', 'r').read().split('\n')]
b = [_.split('\t') for _ in open('b.txt', 'r').read().split('\n')]
for _ in range(len(a)):
for a_, b_ in zip(a[_], b[_]):
print(a_, b_, end='\t', sep='\t')
print('')
|
# 불량 사용자
def solution(user_id, banned_id):
visited = set()
state_arr = []
backtrack(0, len(banned_id), visited, state_arr, user_id, banned_id)
return len(state_arr)
def backtrack(idx: int, max_cnt: int, visited: set, state_arr: list, user_id: list, banned_id: list):
if idx == max_cnt:
if visited not in state_arr:
state_arr.append(visited.copy())
return
for i in range(len(user_id)):
if i in visited:
continue
if len(user_id[i]) != len(banned_id[idx]):
continue
banned = list(banned_id[idx])
for j in range(len(banned)):
if banned[j] == "*":
banned[j] = user_id[i][j]
if banned == list(user_id[i]):
visited.add(i)
backtrack(idx + 1, max_cnt, visited, state_arr, user_id, banned_id)
visited.remove(i)
if __name__ == "__main__":
user_id = ["frodo", "fradi", "crodo", "abc123", "frodoc"]
banned_id = ["fr*d*", "*rodo", "******", "******"]
print(solution(user_id, banned_id))
|
#function -->mehgiclude sebuah nilai didalam fungsi
def input_barang(nama,harga):
print("Nama Barang:", nama)
print("Harga Barang", harga)
a=input("masukan nama barang:")
b=input("masukan harga barang")
input_barang(a,b)
|
#!/usr/bin/python3
class Bash_DB:
def __init(self, Parent):
self.Controller = Parent
def Create_DB(self, DB_Type):
if DB_Type.DB_Stack == "LAMP":
self.Controller.Bash_Script.subprocess.call("./Sensor_Database/LAMP_Server/LAMP_Setup.sh")
|
# @desc This is a code that determines whether a number is positive, negative, or just 0
# @desc by Merrick '23
def positive_negative(x):
if x > 0:
return "pos"
elif x == 0:
return "0"
else:
return "neg"
def main():
print(positive_negative(5))
print(positive_negative(-1))
print(positive_negative(0))
print(positive_negative(21))
print(positive_negative(-100))
if __name__ == '__main__':
main()
|
__all__ = [
'resp',
'user'
]
|
# ------------------------------------------------ EASTER EGG ------------------------------------------------
# Congratulations on finding this file! Please use the following methods below to decrypt the given cipher.
def decrypt(cipher, multiple):
text = ""
for idx, ch in enumerate(cipher):
if ch.isalpha():
shift = multiple * idx % 26
newChar = ord(ch) + shift
if newChar > ord('z'):
newChar -= 26
text += chr(newChar)
return text
def encrypt(text, multiple):
cipher = ""
for idx, ch in enumerate(text):
if ch.isalpha():
shift = multiple * idx % 26
newChar = ord(ch) - shift
if newChar < ord('a'):
newChar += 26
cipher += chr(newChar)
return cipher
|
ueberweisungslimit = 50_000
kontostand = 3_500
ungueltiger_betrag = True
# Funktionsdefinition
def trenner(anzahl):
for zaehler in range(anzahl):
print("-", end="")
print()
# Funktionsaufruf
trenner(50)
print("Willkommen beim Online-Banking der DKB")
print("Ihr Überweisungslimit beträgt", ueberweisungslimit, "€")
print("Ihr aktueller Kontostand beträgt", kontostand, "€")
trenner(50)
while ungueltiger_betrag:
try:
betrag = round(float(input("Bitte geben Sie einen Überweisungbetrag in € ein: ")),2)
if betrag > ueberweisungslimit:
print("Ihr Betrag liegt über den Überweisungslimit von", ueberweisungslimit, "€.")
elif betrag < 0:
print("Bitte geben Sie nur positive Zahle für eine Überweisung ein.")
elif betrag > kontostand:
print("Leider reicht Ihr Kontostand i.H.v.", kontostand,"€ nicht für die Überweisung i.H.v.", betrag,"€ aus.")
entscheidung = input("Wollen Sie einen niedrigeren Betrag überweisen (ja/nein): ")
if entscheidung.lower() == "nein":
ungueltiger_betrag = False
else:
print("Ihre Überweisung i.H.v.", betrag,"€ wurde durchgeführt.")
kontostand -= betrag
print("Ihr neuer Kontostand beträgt:", kontostand, "€.")
ungueltiger_betrag = False
except:
print("Bitte geben Sie nur Zahlen ein.")
|
while True:
n = int(input())
if n == -1:
break
s = 0
last = 0
for i in range(n):
a,b=map(int,input().split())
s += a*(b-last)
last = b
print(s,"miles")
|
no_of_adults = float(input())
no_of_childrens = float(input())
total_passenger_cost = 0
service_tax = 7/100
discount = 10/100
rate_per_adult = no_of_adults * 37550.0 + service_tax
rate_per_children = no_of_childrens * (37550.0/3.0) + service_tax
total_passenger_cost = (rate_per_adult + rate_per_children) - discount
print(round(total_passenger_cost, 2))
|
class Status(object):
SHUTTING_DOWN = 'Shutting Down'
RUNNING = 'Running'
class __State(object):
def __init__(self):
self._shutting_down = False
def set_to_shutting_down(self):
self._shutting_down = True
def is_shutting_down(self):
return self._shutting_down
@property
def status(self):
return Status.SHUTTING_DOWN if self.is_shutting_down() else Status.RUNNING
runtime_state = __State()
|
"""Python Wavelet Imaging
PyWI is an image filtering library aimed at removing additive background noise
from raster graphics images.
* Input: a FITS file containing the raster graphics to clean (i.e. an image
defined as a classic rectangular lattice of square pixels).
* Output: a FITS file containing the cleaned raster graphics.
The image filter relies on multiresolution analysis methods (Wavelet
transforms) that remove some scales (frequencies) locally in space. These
methods are particularly efficient when signal and noise are located at
different scales (or frequencies). Optional features improve the SNR ratio when
the (clean) signal constitute a single cluster of pixels on the image (e.g.
electromagnetic showers produced with Imaging Atmospheric Cherenkov
Telescopes). This library is written in Python and is based on the existing
Cosmostat tools iSAp (Interactive Sparse Astronomical data analysis Packages
http://www.cosmostat.org/software/isap/).
The PyWI library also contains a dedicated package to optimize the image filter
parameters for a given set of images (i.e. to adapt the filter to a specific
problem). From a given training set of images (containing pairs of noised and
clean images) and a given performance estimator (a function that assess the
image filter parameters comparing the cleaned image to the actual clean image),
the optimizer can determine the optimal filtering level for each scale.
The PyWI library contains:
* wavelet transform and wavelet filtering functions for image multiresolution
analysis and filtering;
* additional filter to remove some image components (non-significant pixels
clusters);
* a set of generic filtering performance estimators (MSE, NRMSE, SSIM, PSNR,
image moment's difference), some relying on the scikit-image Python library
(supplementary estimators can be easily added to meet particular needs);
* a graphical user interface to visualize the filtering process in the wavelet
transformed space;
* an Evolution Strategies (ES) algorithm known in the mathematical optimization
community for its good convergence rate on generic derivative-free continuous
global optimization problems (Beyer, H. G. (2013) "The theory of evolution
strategies", Springer Science & Business Media);
* additional tools to manage and monitor the parameter optimization.
Note:
This project is in beta stage.
Viewing documentation using IPython
-----------------------------------
To see which functions are available in `pywi`, type ``pywi.<TAB>`` (where
``<TAB>`` refers to the TAB key), or use ``pywi.*transform*?<ENTER>`` (where
``<ENTER>`` refers to the ENTER key) to narrow down the list. To view the
docstring for a function, use ``pywi.transform?<ENTER>`` (to view the
docstring) and ``pywi.transform??<ENTER>`` (to view the source code).
"""
# PEP0440 compatible formatted version, see:
# https://www.python.org/dev/peps/pep-0440/
#
# Generic release markers:
# X.Y
# X.Y.Z # For bugfix releases
#
# Admissible pre-release markers:
# X.YaN # Alpha release
# X.YbN # Beta release
# X.YrcN # Release Candidate
# X.Y # Final release
#
# Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer.
# 'X.Y.dev0' is the canonical version of 'X.Y.dev'
__version__ = '0.3.dev12'
def get_version():
return __version__
# The following lines are temporary commented to avoid BUG#2 (c.f. BUGS.md)
#from . import benchmark
#from . import data
#from . import io
#from . import optimization
#from . import processing
#from . import ui
|
class DynGraph():
def node_presence(self, nbunch=None):
raise NotImplementedError("Not implemented")
def add_interaction(self,u_of_edge,v_of_edge,time):
raise NotImplementedError("Not implemented")
def add_interactions_from(self, nodePairs, times):
raise NotImplementedError("Not implemented")
def add_node_presence(self,node,time):
raise NotImplementedError("Not implemented")
def add_nodes_presence_from(self, nodes, times):
raise NotImplementedError("Not implemented")
def remove_node_presence(self,node,time):
raise NotImplementedError("Not implemented")
def graph_at_time(self,t):
raise NotImplementedError("Not implemented")
def remove_interaction(self,u_of_edge,v_of_edge,time):
raise NotImplementedError("Not implemented")
def remove_interactions_from(self, nodePairs, periods):
raise NotImplementedError("Not implemented")
def cumulated_graph(self,times=None):
raise NotImplementedError("Not implemented")
|
def smallest(max_factor, min_factor):
return is_palindrome(min_factor, max_factor)
def largest(max_factor, min_factor):
return is_palindrome(min_factor, max_factor, low=False)
def is_palindrome(mn, mx, low=True):
"""
Throughout the method all ranges' upper bound is extended because in python it's exclusive
and we need to include it.
:param mn: min value
:param mx: max value
:param low: True means we need smallest palindrome, False - largest one
:return:
"""
if mn > mx:
raise ValueError("min shouldn't be bigger than max")
# iterate over range of squares to avoid nested loops
args = (mn ** 2, mx ** 2 + 1) if low else (mx ** 2, mn ** 2 - 1, -1)
for r in range(*args):
s = str(r)
palindrome = s == s[::-1]
if palindrome:
# Since we're iterating through range created using smallest and largest squares as its bounds,
# it'll contain numbers which aren't products of the min-max range.
# So we need to check if there's a factor of a palindrome in the initial range
# mn <= r // j <= mx is here because we extended our ranges by 1
factor_in_range = any(mn <= r // j <= mx for j in range(mn, mx + 1) if r % j == 0)
if factor_in_range:
# Similar to the above we need to find the factors of a palindrome in the initial range
return r, ((i, r // i) for i in range(mn, mx + 1)
if r % i == 0 and mn <= i <= r // i <= mx)
else:
return None, []
|
def get_sql(company, conn, gl_code, start_date, end_date, step):
# start_date = '2018-02-28'
# end_date = '2018-03-01'
# step = 1
sql = (
"WITH RECURSIVE dates AS "
f"(SELECT CAST('{start_date}' AS {conn.constants.date_cast}) AS op_date, "
f"{conn.constants.func_prefix}date_add('{start_date}', {step-1}) AS cl_date "
f"UNION ALL SELECT {conn.constants.func_prefix}date_add(cl_date, 1) AS op_date, "
f"{conn.constants.func_prefix}date_add(cl_date, {step}) AS cl_date "
f"FROM dates WHERE {conn.constants.func_prefix}date_add(cl_date, {step}) <= '{end_date}') "
"SELECT "
# "a.op_row_id, a.cl_row_id"
# ", a.op_date, a.cl_date"
"a.op_date AS \"[DATE]\", a.cl_date AS \"[DATE]\""
# ", c.location_row_id, c.function_row_id, c.source_code_id"
", SUM(COALESCE(b.tran_tot, 0)) AS \"[REAL2]\""
", SUM(COALESCE(c.tran_tot, 0) - COALESCE(b.tran_tot, 0)) AS \"[REAL2]\""
", SUM(COALESCE(c.tran_tot, 0)) AS \"[REAL2]\""
# ", COALESCE(c.tran_tot, 0) AS \"[REAL2]\", COALESCE(b.tran_tot, 0) AS \"[REAL2]\""
" FROM "
"(SELECT dates.op_date, dates.cl_date, ("
"SELECT c.row_id FROM {0}.gl_totals c "
"JOIN {0}.gl_codes f on f.row_id = c.gl_code_id "
"WHERE c.tran_date < dates.op_date "
"AND c.location_row_id = d.row_id "
"AND c.function_row_id = e.row_id "
"AND c.source_code_id = g.row_id "
f"AND f.gl_code = '{gl_code}' "
"ORDER BY c.tran_date DESC LIMIT 1"
") AS op_row_id, ("
"SELECT c.row_id FROM {0}.gl_totals c "
"JOIN {0}.gl_codes f on f.row_id = c.gl_code_id "
"WHERE c.tran_date <= dates.cl_date "
"AND c.location_row_id = d.row_id "
"AND c.function_row_id = e.row_id "
"AND c.source_code_id = g.row_id "
f"AND f.gl_code = '{gl_code}' "
"ORDER BY c.tran_date DESC LIMIT 1"
") AS cl_row_id "
"FROM dates, {0}.adm_locations d, {0}.adm_functions e, {0}.gl_source_codes g "
"WHERE d.location_type = 'location' "
"AND e.function_type = 'function' "
") AS a "
"LEFT JOIN {0}.gl_totals b on b.row_id = a.op_row_id "
"LEFT JOIN {0}.gl_totals c on c.row_id = a.cl_row_id "
"GROUP BY a.op_date, a.cl_date "
# "WHERE c.location_row_id IS NOT NULL "
.format(company)
)
params = ()
fmt = '{:%d-%m} - {:%d-%m} : {:>12}{:>12}{:>12}'
return sql, params, fmt
# cur = await conn.exec_sql(sql)
# async for row in cur:
# print(fmt.format(*row))
# # print(row)
|
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
curr = self
vals = []
while curr:
vals.append(curr.val)
curr = curr.next
return str(vals)
@classmethod
def from_list(cls, vals):
head = None
curr = None
for i in vals:
node = ListNode(i)
if not head:
head = node
curr = node
else:
curr.next = node
curr = node
return head
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
def __str__(self):
queue = [self]
s = ''
while len(queue) > 0:
next_queue = []
for node in queue:
s += node.val.__str__() + '\t'
if node.left:
next_queue.append(node.left)
if node.right:
next_queue.append(node.right)
s += '\n'
queue = next_queue
return s
@classmethod
def from_list(cls, vals):
n = len(vals)
if n == 0:
return None
head = TreeNode(vals[0])
level = [head]
i = 1
while i < n:
next_level = []
for node in level:
v = vals[i]
if v != '#':
left = TreeNode(v)
node.left = left
next_level.append(left)
i += 1
if i >= n:
break
v = vals[i]
if v != '#':
right = TreeNode(v)
node.right = right
next_level.append(right)
i += 1
if i >= n:
break
level = next_level
return head
|
num1 = int(input())
num2 = int(input())
num3 = int(input())
if num1 == num2 and num2 == num3:
print("yes")
else:
print("no")
print("let's see", end="")
print("?")
|
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the COPYING file.
def test_simple(qipy_action, record_messages):
qipy_action.add_test_project("a_lib")
qipy_action.add_test_project("big_project")
qipy_action.add_test_project("foomodules")
qipy_action("list")
assert record_messages.find(r"\*\s+a")
assert record_messages.find(r"\*\s+big_project")
|
# Copyright Alexander Baranin 2016
Logging = None
EngineCore = None
def onLoad(core):
global EngineCore
EngineCore = core
global Logging
Logging = EngineCore.loaded_modules['engine.Logging']
Logging.logMessage('TestFIFOModule1.onLoad()')
EngineCore.schedule_FIFO(run1, 10)
EngineCore.schedule_FIFO(run2, 30)
def onUnload():
Logging.logMessage('TestFIFOModule1.onUnload()')
EngineCore.unschedule_FIFO(10)
EngineCore.unschedule_FIFO(30)
def run1():
Logging.logMessage('dummy print from Module1')
def run2():
Logging.logMessage('another dummy print from Module1')
raise ArithmeticError()
|
'''
Find the greatest product of five consecutive digits in the 1000-digit number.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
'''
number = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'
maxResultArrayLength = 5
resultProduct = 0
resultArrayLength = 0
resultArray = []
loopIndex = 0
digitsCount = len(number)
tempDigit = 0
while loopIndex < digitsCount:
tempDigit = int(number[loopIndex])
if tempDigit == 0:
loopIndex = loopIndex + maxResultArrayLength
resultArray = []
resultArrayLength = 0
continue
else :
if resultArrayLength < maxResultArrayLength:
resultArray.append(tempDigit)
resultArrayLength = resultArrayLength + 1
if resultArrayLength == maxResultArrayLength:
tempResultProduct = 1
for x in resultArray:
tempResultProduct = tempResultProduct * x
if tempResultProduct > resultProduct:
resultProduct = tempResultProduct
resultArray.pop(0)
resultArrayLength = resultArrayLength - 1
loopIndex = loopIndex + 1
print(resultProduct)
|
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
# Copyright (C) 2020 Daniel Rodriguez
# Use of this source code is governed by the MIT License
###############################################################################
__all__ = []
def _generate(cls, bases, dct, **kwargs):
# Try to find a group definition in the directory of the class and it not
# possible, get the attribute which will have been inherited from the class
# Add the final attribute in tuple form, to support many
grps = dct.get('group', ()) or getattr(cls, 'group', ())
if isinstance(grps, str):
grps = (grps,) # if only str, simulate iterable
cls.group = grps # set it in the instance, let others process
|
#! /usr/bin/python3
# product.py -- This script prints out a product and it's price.
# Author -- Prince Oppong Boamah<[email protected]>
# Date -- 10th September, 2015
class Product:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
# The program starts running here.
p = Product("Lenovo")
p.price = "2000gh cedis or 400 pounds or 600 dollars to be precise."
print("p is a %s" % (p.__class__))
print("This is a Laptop called %s and the price is %s" % (p.name, p.price))
|
# constantly ask the user for new names and phone numbers
# to add to the phone book, then save them
phone_book = {}
|
key_words = ["Trending", "Fact", "Reason", "Side Effect", "Index", "Stock", "ETF"]
knowledge_graph_dict = {
"Value Investing": {},
"Risk Management": {},
"Joe Biden": {
"Tax Increase Policy": {
"Tech Company": {
"Trending": "Negative",
},
"Corporate Tax": {
"Trending": "Negative",
},
"Capital Gain Tax": {
"Trending": "Negative",
},
},
"Economic Stimulus Package": {
"Trending": "Positive",
"Reason": "buy the rumor sell the news.",
"Fact": "Negative",
"Side Effect": {
"Consumption Discretionary Sector": {
"ETF": [
"PEJ Leisure & entertainment etf",
"XLY Consumer discretionary select sector SPDR fund",
],
"Trending": "Positive",
"Reason": "Covid recover and stimulus package delivered.",
},
},
},
},
"New Type of Inflation": {
"Phenomenon": "Fed release money -> core CPI not increasing fast, but asset bull",
"Result": "New Type of Inflation, fool people and rich richest all the time",
"Reason": "This is so call new type of inflation. "
"Traditional CPI index already out of style, because the necessity in the modern world is not food but asset."
"Fed blindly or intend to blindly use old world index as CPI to fool people."
"Then, the asset increase fast, and the gap between rich and poor split more."
"The side effect would show the result sooner or later.",
},
}
investment_principle = {
"principle1": {
"Principle": "Other investors haven't go into the underlying but will plan to.",
"Trending": "Positive",
"Reason": "Newly long position crowd would push the price to go high and squeeze short."
},
"principle2": {
"Principle": "Does all the potential investors go into the trading? Yes, then leave it",
"Trending": "Negative",
"Reason": "Picked like leek",
},
"principle3": {
"Principle": "Find the frontier and the edger of the world who being laughed at.",
"Trending": "Positive",
"Reason": "Margin cost lowest but margin reward highest in the uncultivated land to lead the world."
"Being laughed at by the crowd means less people realize the real value and underestimated but already obtain attention."
"Truth is in the hands of a few",
},
"principle4": {
"Principle": "The highest risk is not long the position but is sell then buy again risk.",
"Reason": "long time experience",
}
}
target_assets = [
{
"Name": "Asana",
"Symbol": "ASAN",
"Type": "Equity",
"Positive": [],
"Negative": [],
},
{
"Name": "Nano Dimension",
"Symbol": "NNDM",
"Type": "Equity",
"Positive": [],
"Negative": [],
},
{
"Name": "Lockheed",
"Symbol": "LMT",
"Type": "Equity",
"Positive": [],
"Negative": [],
},
{
"Name": "Lockheed",
"Symbol": "LMT",
"Type": "Equity",
"Positive": [],
"Negative": [],
},
{
"Name": "Bitcoin",
"Symbol": "BTC",
"Type": "Cryptocurrencies",
"Positive": [],
"Negative": [],
},
{
"Name": "Uber",
"Symbol": "Uber",
"Type": "Equity",
"Positive": [
"SP500 target stock",
],
"Negative": [],
}
]
todo_list = ["https://en.wikipedia.org/wiki/Ronald_S._Baron"]
class Investment2021:
def __init__(self):
self.knowledge_graph_dict = knowledge_graph_dict
if __name__ == "__main__":
print("Investment Jan. Plan")
|
# encoding: utf-8
'''
@author: developer
@software: python
@file: run8.py
@time: 2021/7/28 22:35
@desc:
'''
str1 = input()
str2 = input()
output_str1 = str2[0:2] + str1[2:]
output_str2 = str1[0:2] + str2[2:]
print(output_str1)
print(output_str2)
|
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def tomlplusplus_repository():
maybe(
http_archive,
name = "tomlplusplus",
urls = [
"https://github.com/marzer/tomlplusplus/archive/v2.5.0.zip",
],
sha256 = "887dfb7025d532a3485e1269ce5102d9e628ddce8dd055af1020c7b10ee14248",
strip_prefix = "tomlplusplus-2.5.0/",
build_file = "@third_party//tomlplusplus:package.BUILD",
)
|
#! /usr/bin/env python3
# hjjs.py - write some HJ J-sequences
EXTENSION = ".hjjs.txt"
MODE = "w"
J_MAX = 2 ** 32 - 1
def i22a(f, m):
n = 0
js = []
while True:
j = 2 ** (2 * n + m) - 2 ** n
if j > J_MAX:
break
js.append(j)
n += 1
print(*js, file = f)
for m in range(10):
with open("i22a" + str(m) + EXTENSION, MODE) as f:
i22a(f, m)
|
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
"""Stack.
Running time: O(n) where n == len(s).
"""
d = {c: i for i, c in enumerate(s)}
st = []
seen = set()
for i, c in enumerate(s):
if c in seen:
continue
while st and st[-1] > c and d[st[-1]] > i:
v = st.pop()
seen.remove(v)
st.append(c)
seen.add(c)
return ''.join(st)
|
# This should be subclassed within each
# class that gets registered with the API
class BaseContext:
def __init__(self, instance=None, serial=None):
pass
def serialized(self):
return ()
def instance(self, global_context):
return None
# This is actually very different from a context.
# Meh. It just holds the things we need it to.
class GlobalContext:
def __init__(self, universes, network):
self.universes = universes
self.network = network
# ** Function Decorator **
def expose(func, label=None):
if not label:
label = func.__name__
setattr(func, "__api_exposed__", True)
setattr(func, "__api_label__", label)
return func
def readable(*attrs):
def decorator(cls):
if not hasattr(cls, "__api_readable__"):
setattr(cls, "__api_readable__", [])
cls.__api_readable__.extend([attr for attr in attrs if attr not in cls.__api_readable__])
return cls
return decorator
def writable(*attrs):
def decorator(cls):
if not hasattr(cls, "__api_readable__"):
setattr(cls, "__api_readable__", [])
if not hasattr(cls, "__api_writable__"):
setattr(cls, "__api_writable__", [])
cls.__api_readable__.extend(attrs)
cls.__api_writable__.extend(attrs)
return cls
return decorator
# There are two parts to this:
#
# One is a decorator which, applied to a function,
# marks it as registerable through the Client API.
#
# The other is a method in the ClientAPI, which gets
# passed a Class Name and searches through it for any
# applicable classes, as well as a Context class. If
# the class does not have a context, then the call
# will fail.
#
# Also, each Context will have a constructor that
# accepts a global context and either its object, or
# a tuple which represents its serialized value. It
# should also have an 'object' method which returns
# the object to which the context refers. And finally
# there should be a 'serialized' method which returns
# a tuple that uniquely identifies the context within
# the global context.
class ClientAPI:
def __init__(self, globalContext):
self.classes = {}
self.globalContext = globalContext
def onGet(self, name, ctx):
cls, attr = name.split(".")
classInfo = self.classes[cls]
if attr not in classInfo["readable"]:
raise AttributeError("Attribute {} is not readable -- did you @readable it?".format(attr))
context = classInfo["context"]
instance = context(serial=ctx).instance(self.globalContext)
result = getattr(instance, attr, None)
if hasattr(result, 'Context'):
return {"result": result, "context": result.Context(instance=result)}
return {"result": result}
def onSet(self, name, ctx, value):
cls, attr = name.split(".")
classInfo = self.classes[cls]
if attr not in classInfo["writable"]:
raise AttributeError("Attribute {} is not writable -- did you @writable it?".format(attr))
context = classInfo["context"]
instance = context(serial=ctx).instance(self.globalContext)
setattr(instance, attr, value)
if attr in classInfo["readable"]:
result = getattr(instance, attr)
else:
result = None
if hasattr(result, 'Context'):
return {"result": result, "context": result.Context(instance=result)}
return {"result": result}
def onCall(self, name, ctx, *args, **kwargs):
cls, func = name.split(".")
classInfo = self.classes[cls]
if func not in classInfo["methods"]:
raise AttributeError("Method {} is not available -- did you @expose it?".format(func))
context = classInfo["context"]
instance = context(serial=ctx).instance(self.globalContext)
method = classInfo["methods"][func]["callable"]
result = method(instance, *args, **kwargs)
if hasattr(result, 'Context'):
return {"result": result, "context": result.Context(instance=result)}
return {"result": result}
def getTable(self):
return self.classes
def register(self, cls):
if not hasattr(cls, "Context"):
raise AttributeError("Cannot register class {}; must have Context.".format(cls.__name__))
if not issubclass(cls.Context, BaseContext):
raise AttributeError("Cannot register class {}; Invalid Context.".format(cls.__name__))
methods = {}
for methname in dir(cls):
method = getattr(cls, methname)
if hasattr(method, "__api_exposed__") and hasattr(method, "__api_label__"):
methods[method.__api_label__] = {"callable": method}
readable = []
writable = []
if hasattr(cls, "__api_readable__"):
for attrName in cls.__api_readable__:
readable.append(attrName)
if hasattr(cls, "__api_writable__"):
for attrName in cls.__api_writable__:
writable.append(attrName)
if attrName not in readable:
readable.append(attrName)
self.classes[cls.__name__] = {
"class": cls,
"context": cls.Context,
"methods": methods,
"readable": readable,
"writable": writable
}
|
def pageCount(n, p):
print(min(p//2,n//2-p//2))
if __name__ == '__main__':
n = int(input())
p = int(input())
pageCount(n, p)
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pseudoPalindromicPaths (self, root: TreeNode) -> int:
self.a = [0] * 10
self.count = 0
self.dfs(root, [])
return self.count;
def dfs(self, root, path):
if root is None:
return
self.a[root.val]+=1
if root.left is None and root.right is None:
md = 0
for i in range(10):
if self.a[i] % 2 != 0 and self.a[i] != 0:
md +=1
print(self.a)
if md < 2:
self.count +=1
if root.left:
self.dfs(root.left, path)
if root.right:
self.dfs(root.right, path)
self.a[root.val] -=1
|
"""
Programming for linguists
Implementation of the class Circle
"""
class Circle:
"""
A class for circles
"""
def __init__(self, uid: int, radius: int):
pass
def get_area(self):
"""
Returns the area of a circle
:return int: the area of a circle
"""
pass
def get_perimeter(self):
"""
Returns the perimeter of a circle
:return int: the perimeter of a circle
"""
pass
def get_diameter(self):
"""
Returns the diameter of a circle
:return int: the diameter of a circle
"""
pass
|
class FLAGS:
data_url = ""
data_dir = None
background_volume = 0.1
background_frequency = 0
silence_percentage = 10.0
unknown_percentage = 10.0
time_shift_ms = 0
use_custom_augs = False
testing_percentage = 10
validation_percentage = 10
sample_rate = 16000
clip_duration_ms = 1000
window_size_ms = 30
window_stride_ms = 10
dct_coefficient_count = 40
model_architecture = "ds_cnn"
model_size_info = [128, 128, 128]
start_checkpoint = ""
eval_step_interval = 400
how_many_training_steps = [5000, 5000]
learning_rate = [0.001, 0.0001]
batch_size = 100
wanted_words = ""
excluded_words = ""
summaries_dir = None
train_dir = None
save_step_interval = 100
check_nans = False
|
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
returnList = [0] * len(nums)
temp = 0
for i in range(0,n):
returnList[temp] = nums[i]
returnList[temp+1] = nums[n]
n+=1
temp+=2
return returnList
|
'''
选择排序, 平均时间O(n^2), 最好O(n^2), 最坏O(n^2), 空间O(1), in-place, 不稳定
步骤:
1未排序序列中找最小(大)值,放到起始位置
2剩余的未排序序列中继续找最小(大)值,放到已排序序列的末尾
3重复步骤2
不管什么数据规模都是O(n^2),所以使用时数据规模越小越好
需要进行n*(n-1)/2次交换,比较冒泡排序,其交换次数更少
冒泡排序每次遍历后前者>后者就会交换,但是前者可能不是最小的,还会发生交换,需要多次才能确定,比较耗时
'''
def selectionSort(lst):
countCompare = 0
countSwap = 0
length = len(lst)
print("选择排序")
print("数据:{0}".format(lst))
for i in range(0, length-1):
minIndex = i
for j in range(i+1, length):
countCompare += 1
if lst[j] < lst[minIndex]:
minIndex = j
countCompare += 1
if minIndex != i:
countSwap += 1
lst[i], lst[minIndex] = lst[minIndex], lst[i]
print("统计:{0}次比较, {1}次交换, {2}".format(countCompare, countSwap, lst))
return lst
# 选择排序优化,每次循环确定最小最大值
def selectionSortOpt(lst):
countCompare = 0
countSwap = 0
length = len(lst)
mid = length >> 1
print("选择排序优化")
print("数据:{0}".format(lst))
for i in range(0, mid):
minIndex = i
maxIndex = i
for j in range(i+1, length-i):
countCompare += 2
if lst[j] < lst[minIndex]:
minIndex = j
elif lst[j] > lst[maxIndex]:
maxIndex = j
countCompare += 2
if minIndex != i:
countSwap += 1
lst[i], lst[minIndex] = lst[minIndex], lst[i]
countCompare += 1
if maxIndex == i:
maxIndex = minIndex
if maxIndex != length-1-i:
countSwap += 1
lst[length-1-i], lst[maxIndex] = lst[maxIndex], lst[length-1-i]
print("统计:{0}次比较, {1}次交换, {2}".format(countCompare, countSwap, lst))
return lst
|
def get_player_score():
score = []
for i in range(0, 5):
while True:
try:
s = float(input('Enter golf scores between 78 and 100: '))
if 78 <= s <= 100:
score.append(s)
break
raise ValueError
except ValueError:
print("Invalid Input!")
return score
print(get_player_score())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.