content stringlengths 7 1.05M |
|---|
# Define the class as author
class Author:
# The function is in it and the __ is a special function in python. properties in the brackets are what
# is being passed in the function
def __init__(self, name, firstName, nationality):
# Define the attributes in the class
self.name = name
self.firstName = firstName
self.nationality = nationality
|
db = {
"users": [
{
"id": 2,
"username": "marceline",
"name": "Marceline Abadeer",
"bio": "1000 year old vampire queen, musician"
}
],
"threads": [
{
"id": 2,
"title": "What's up with the Lich?",
"createdBy": 2
}
],
"posts": [
{
"thread": 2,
"text": "Has anyone checked on the lich recently?",
"user": 2
}
]
}
db_more = {
"users": [
{
"id": 1,
"username": "marceline",
"name": "Marceline Abadeer",
"bio": "1000 year old vampire queen, musician"
},
{
"id": 2,
"username": "finn",
"name": "Finn 'the Human' Mertens",
"bio": "Adventurer and hero, last human, defender of good"
},
{
"id": 3,
"username": "pb",
"name": "Bonnibel Bubblegum",
"bio": "Scientist, bearer of candy power, ruler of the candy kingdom"
}
],
"threads": [
{
"id": 1,
"title": "What's up with the Lich?",
"createdBy": 4
},
{
"id": 2,
"title": "Party at the candy kingdom tomorrow",
"createdBy": 3
},
{
"id": 3,
"title": "In search of a new guitar",
"createdBy": 1
}
],
"posts": [
{
"thread": 1,
"text": "Has anyone checked on the lich recently?",
"user": 4
},
{
"thread": 1,
"text": "I'll stop by and see how he's doing tomorrow!",
"user": 2
},
{
"thread": 2,
"text": "Come party with the candy people tomorrow!",
"user": 3
}
]
}
|
class LogEntry(dict):
"""
Log message and info for jobs and services
Fields:
- ``id``: Unique ID for the log, string, REQUIRED
- ``code``: Error code, string, optional
- ``level``: Severity level, string (error, warning, info or debug), REQUIRED
- ``message``: Error message, string, REQUIRED
- ``time``: Date and time of the error event as RFC3339 date-time, string, available since API 1.1.0
- ``path``: A "stack trace" for the process, array of dicts
- ``links``: Related links, array of dicts
- ``usage``: Usage metrics available as property 'usage', dict, available since API 1.1.0
May contain the following metrics: cpu, memory, duration, network, disk, storage and other custom ones
Each of the metrics is also a dict with the following parts: value (numeric) and unit (string)
- ``data``: Arbitrary data the user wants to "log" for debugging purposes.
Please note that this property may not exist as there's a difference
between None and non-existing. None for example refers to no-data in
many cases while the absence of the property means that the user did
not provide any data for debugging.
"""
_required = {"id", "level", "message"}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Check required fields
missing = self._required.difference(self.keys())
if missing:
raise ValueError("Missing required fields: {m}".format(m=sorted(missing)))
@property
def id(self):
return self["id"]
# Legacy alias
log_id = id
@property
def message(self):
return self["message"]
@property
def level(self):
return self["level"]
# TODO: add properties for "code", "time", "path", "links" and "data" with sensible defaults?
|
"""
from django import forms
from .models import Item
class AddForm(forms.ModelForm):
class Meta:
model = Item
fields = ('created_by',
'title', 'image', 'description', 'price', 'pieces', 'instructions', 'labels', 'label_colour', 'slug')
"""
|
'''
http://pythontutor.ru/lessons/for_loop/problems/sum_of_n_numbers/
Дано несколько чисел. Вычислите их сумму. Сначала вводите количество чисел N,
затем вводится ровно N целых чисел. Какое наименьшее число переменных нужно для решения этой задачи?
'''
inp = int(input())
s = 0
for _ in range(inp):
s += int(input())
print(s)
|
# "Strange Number"
# Alec Dewulf
# April Long 2020
# Difficulty: Easy
# Prerequisities: Number Theory
"""
OVERVIEW
This solution is based on the idea that the number of prime factors (k) must be less
than the total prime factors (max_k). The number of factors can be calculated by
adding one to each exponent in a number's prime factorization and then multiplying
those exponents.
HELPER FUNCTIONS
Is_prime returns True if none of the numbers less than the square root of n
divide it and False otherwise.
get_prime factors takes in n and k and returns the length of the list of n's prime
factorization.
Example:
get_prime_factors(100, 2)
returns: 4 --> len([2, 2, 5, 5])
k is used as a limit. If at any time the length of prime factors reaches k, then that k is
valid and there is no need to collect more of the prime factors.
MAIN SOLUTION
After getting inputs, max_k is assigned to the value of the function call get_prime_factors(x, k).
This is the max value k can take on because there need to be at least k things that multiply to be x.
The most amount of things you can multiply to get x is all the numbers of its prime factorization.
Example:
x = 100
k = 4
100 = 5x5x2x2
Therefore you can have a k up to four and have 100 work as a value of x.
For example the number: 2^4 x 3^4 x 5^1 x 7^1 will have 100 factors
((4+1)*(4+1)*(1+1)*(1+1)) and 4 prime factors (2, 3, 5, 7).
No greater amount of prime factors are possible because there are no five
things that multiply to be 100 (You can't use 1 or break down the prime
factorization any more)
"""
def is_prime(n):
if n < 2:
return False
return all(n % i for i in range(2, int(math.sqrt(n)) + 1))
def get_prime_factors(n, k):
prime_factors = []
d = 2
while d * d <= n:
while n % d == 0:
n //= d
prime_factors.append(d)
if len(prime_factors) == k:
return k
d += 1
# avoid 1 as a factor
if n > 1:
assert d <= n
prime_factors.append(n)
if len(prime_factors) == k:
return k
return len(prime_factors)
test_cases = int(input())
answers = []
for n in range(test_cases):
x, k = map(int, input().split())
max_k = get_prime_factors(x, k)
# no number with 1 factor
if x == 1:
answers.append(0)
elif k <= max_k:
answers.append(1)
else:
answers.append(0)
# return results
for a in answers:
print(a)
|
class Node:
def __init__(self, data=None):
self.val = data
self.next = None
class LinkedList:
def __init__(self):
self.head=None
def push(self,val):
new_node=Node(val)
#case 1
if self.head is None:
self.head=new_node
self.head.next=None
return
temp=self.head
while temp.next is not None:
temp=temp.next
temp.next=new_node
new_node.next=None
LinkedList.push=push
def __str__(self):
re_str="["
temp=self.head
while temp is not None:
re_str+=" "+str(temp.val) + " ,"
temp=temp.next
re_str=re_str.rstrip(",")
re_str+="]"
return re_str
LinkedList.__str__=__str__
def pop(self):
#case 1
if self.head is None:
raise IndexError("list cannot be pop, : because list is empty")
#case 2
if self.head.next is None:
val=self.head.val
self.head=None
return val
temp=self.head
while temp.next is not None:
pre=temp
temp=temp.next
val=temp.val
pre.next=None
return val
LinkedList.pop=pop
def insert(self,index,val):
new_node=Node(val)
if index==0:
new_node.next=self.head
self.head=new_node
return
count=0
temp=self.head
while temp is not None and count<index:
pre=temp
temp=temp.next
count+=1
pre.next=new_node
new_node.next=temp
LinkedList.insert=insert
def remove_at(self,index):
if index>self.len():
raise IndexError("list index out of Range ")
if index==0:
self.head=self.head.next
return
if self.head is None:
raise IndexError("Cannot be remove because list is empty")
count=0
temp=self.head
# remove funtion must be temp not the temp.next remember!!!!
while temp is not None and count<index:
pre=temp
temp=temp.next
count+=1
pre.next=temp.next
LinkedList.remove_at=remove_at
def len(self):
if self.head is None:
return 0
temp=self.head
count=0
while temp is not None:
temp=temp.next
count+=1
return count
LinkedList.len=len
def remove(self,val):
if self.head is None:
raise IndexError(" Cannot be removed becaus list is empty ")
if self.head.val ==val:
self.head=self.head.next
return
if self.head.next is None:
if self.head.val==val:
self.head=None
return
temp=self.head
while temp.next is not None:
pre=temp
temp=temp.next
if temp.val==val:
break
else:
return
pre.next=temp.next
return
LinkedList.remove=remove
def reverse_list(self):
pre = None
current = self.head
while current is not None:
next = current.next
current.next = pre
pre = current
current = next
self.head = pre
LinkedList.reverse_list=reverse_list
if __name__ == '__main__':
l = LinkedList()
l.push(1)
l.push(2)
l.push(3)
print(l)
l.reverse_list()
print(l)
|
def crossingSum(matrix, a, b):
return sum(matrix[a]) + sum([x[b] for i, x in enumerate(matrix) if i != a])
if __name__ == '__main__':
input0 = [[[1,1,1,1], [2,2,2,2], [3,3,3,3]], [[1,1], [1,1]], [[1,1], [3,3], [1,1], [2,2]], [[100]], [[1,2], [3,4]], [[1,2,3,4]], [[1,2,3,4,5], [1,2,2,2,2], [1,2,2,2,2], [1,2,2,2,2], [1,2,2,2,2], [1,2,2,2,2], [1,2,2,2,2]]]
input1 = [1, 0, 3, 0, 1, 0, 1]
input2 = [3, 0, 0, 0, 1, 3, 1]
expectedOutput = [12, 3, 9, 100, 9, 10, 21]
assert len(input0) == len(expectedOutput), '# input0 = {}, # expectedOutput = {}'.format(len(input0), len(expectedOutput))
assert len(input1) == len(expectedOutput), '# input1 = {}, # expectedOutput = {}'.format(len(input1), len(expectedOutput))
assert len(input2) == len(expectedOutput), '# input2 = {}, # expectedOutput = {}'.format(len(input2), len(expectedOutput))
for i, expected in enumerate(expectedOutput):
actual = crossingSum(input0[i], input1[i], input2[i])
assert actual == expected, 'crossingSum({}, {}, {}) returned {}, but expected {}'.format(input0[i], input1[i], input2[i], actual, expected)
print('PASSES {} out of {} tests'.format(len(expectedOutput), len(expectedOutput))) |
r,x,y,z=open("ads\\1Plumber\\Ad.txt").read().split("\n", 3)
print(y)
|
"""
MAD LIBS
Objetivo:
Completar as frases com palavras.
"""
### 1
print("""1-
Rosas são _______(1)
_______ são azuis(2)
Eu amo _______(3)
Quais seriam as palavras?""")
pri=input("1: ")
seg=input("2: ")
ter=input("3: ")
print(f"Então ficaria assim!\n\nRosas são {pri}\n{seg} são azuis\nEu amo {ter}")
### 2
print("""2-
Quer ver a _______(1)
Bater ______(2)?
É dar a _______(3)
Uma ________(4)
""")
print("Quais seriam as palavras?")
pri=input("1: ")
seg=input("2: ")
ter=input("3: ")
quar=input("4: ")
print(f"""Então ficaria assim!
Quer ver a {pri}
Bater {seg}?
É dar a {ter}
Uma {quar}""")
### 3
print("""3-
Onde vais _______(1)
_______(2) pelo caminho
Assim tão desconsolado
Andas _______(3), bichinho
Espetaste o pé no ________(4)
Que sentes, pobre coitado
Estou com um _______(5) danado
Encotrei um _______(6)
""")
print("Quais seriam as palavras?")
pri=input("1: ")
seg=input("2: ")
ter=input("3: ")
quar=input("4: ")
quin=input("5: ")
sex=input("6: ")
print(f"""Então ficaria assim!
Onde vais {pri}
{seg} pelo caminho
Assim tão desconsolado
Andas {ter}, bichinho
Espetaste o pé no {quar}
Que sentes, pobre coitado
Estou com um {quin} danado
Encotrei um {sex}""")
### 4
print("""4-
Brancas
______(1)
______(2)
E pretas
Brincam
Na luz
As belas
________(3)
________(4) brancas
São alegres e francas
Borboletas azuis
Gostam muito de ______(5)
As ______(6)
São tão _______(7)
E as pretas, então
Oh, que _______(8)
""")
print("Quais seriam as palavras?")
pri=input("1: ")
seg=input("2: ")
ter=input("3: ")
quar=input("4: ")
quin=input("5: ")
sex=input("6: ")
setm=input("7: ")
oit=input("8: ")
print(f"""Então ficaria assim!
Brancas
{pri}
{seg}
E pretas
Brincam
Na luz
As belas
{ter}
{quar} brancas
São alegres e francas
Borboletas azuis
Gostam muito de {quin}
As {sex}
São tão {setm}
E as pretas, então
Oh, que {oit}""") |
ENTRY_POINT = 'circular_shift'
#[PROMPT]
def circular_shift(x, shift):
"""Circular shift the digits of the integer x, shift the digits right by shift
and return the result as a string.
If shift > number of digits, return digits reversed.
>>> circular_shift(12, 1)
"21"
>>> circular_shift(12, 2)
"12"
"""
#[SOLUTION]
s = str(x)
if shift > len(s):
return s[::-1]
else:
return s[len(s) - shift:] + s[:len(s) - shift]
#[CHECK]
def check(candidate):
# Check some simple cases
assert candidate(100, 2) == "001"
assert candidate(12, 2) == "12"
assert candidate(97, 8) == "79"
assert candidate(12, 1) == "21", "This prints if this assert fails 1 (good for debugging!)"
# Check some edge cases that are easy to work out by hand.
assert candidate(11, 101) == "11", "This prints if this assert fails 2 (also good for debugging!)"
|
#Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues.
#OBS: considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1.
totalCedula = 0
cedula = 50
print('='*50)
print('{:^55}'.format('\33[34mBANCO GEEK\33[m'))
print('='*50)
valor = int(input('Qual o valor do saque: '))
total = valor
while True:
if total >= cedula:
total = total - cedula
totalCedula += 1
else:
if totalCedula > 0:
print(f'Total de \33[32m{totalCedula}\33[m cédulas de R$\33[32m{cedula}\33[m')
if cedula == 50:
cedula = 20
elif cedula == 20:
cedula = 10
elif cedula == 10:
cedula = 1
totalCedula = 0
if total == 0:
break
print('='*50)
print('Volte sempre ao Banco Geek! Tenha um bom dia!') |
# A collection of quality of life functions that may be used in many places
# A silly function to set a defatul value if not in kwargs
def kwarget(key, default, **kwargs):
if key in kwargs:
return kwargs[key]
else:
return default
|
nome = str(input('\033[33;44mDigite o nome de uma cidade:\033[m ')).strip().capitalize().split()
print('O nome da cidade começa com a palavras "Santo"?: {}'.format(nome[0] == 'Santo'))
# Forma como o Gustavo Guanabara resolveu, mas tem uma falha, se digitar "santos" ele considera True, pois
# o programa só está lendo os 5 primeiros caracteres
#name = str(input('Digite o nome da cidade que você nasceu: ')).strip()
#print('O nome da cidade começa com a palavra "Santo"?', name[:5].lower() == 'santo') |
def salary_net_uah(salary_usd, currency, taxes, esv):
# What salary in UAH after paying taxes
salary_uah = salary_usd*currency
salary_minus_taxes = salary_uah - salary_uah*taxes/100
result_uah = salary_minus_taxes - esv
return result_uah
def salary_net_usd(salary_usd, currency, taxes, esv):
# What salary in USD after paying taxes
esv_usd = esv/currency
salary_minus_esv = salary_usd - salary_usd*taxes/100
result_usd = salary_minus_esv - esv_usd
return result_usd
def print_salary(salary_usd, currency, taxes, esv):
result_usd = str(round(salary_net_usd(salary_usd, currency, taxes, esv), 2))
result_uah = str(round(salary_net_uah(salary_usd, currency, taxes, esv), 2))
print("Your salary after paying taxes is " + result_usd + " USD " + "(" + result_uah + " UAH)")
print_salary(salary_usd=2100, currency=27, taxes=5, esv=1039.06) |
n = int(input("Enter Height : "))
if(n%2==0):
print("Invalid Input")
else:
half = n//2
for i in range(half+1):
for j in range(i+1):
print("*",end="")
print()
for i in range(half):
for j in range(half-i):
print("*",end="")
print() |
class User:
def __init__(self, username):
self.username = username
def __repr__(self):
return self.username
class ListWithUsers:
def __init__(self):
self.users = []
def add_user(self, user: User):
self.users.append(user)
def remove_user(self, username: str):
tem_users = self.find_user(username)
try:
self.users.remove(tem_users[0])
except IndexError:
return "User %s not found" % username
def find_user(self, username):
user = [x for x in self.users if x.username == username]
return user
def show_users(self):
result = "\n".join([u.__repr__() for u in self.users])
return result
if __name__ == '__main__':
u1 = User('borko')
u2 = User('george')
users = ListWithUsers()
users.add_user(u1)
users.add_user(u2)
users.remove_user('borko')
print(users.show_users())
|
splitString = 'Hello\nWorld'
print(splitString)
# While writing """ or ''' python interpreter waits for next three " or ' to end vars
anotherSplitString = '''Multiline
in
Single
variable
and i don't need to escape single
or double " quote :)'''
print(anotherSplitString)
# Escaping \ from string
# escape \ with another \
print("c:\\User\\text\\notes.txt")
# use raw string, this is typically used in regular expression
print(r"c:\User\text\notes.txt")
|
class Fight:
"""
Parameters
-----------
id: `int`
ID of the fight number (including trash packs)
boss: `int`
ID of the boss
start_time: `int`
Start time of the figth in milliseconds
end_time: `int`
End time of the fight in milliseconds
duration: `int`
Duration of the fight in milliseconds
name: `str`
Name of the boss
zoneName: `str`
Name of the zone
difficulty: `int`
Fight difficulty (Mythic = 5)
bossPercentage: `str`
Boss health in % or an information that the boss died
others: `dict`
Other parameters like:
- kill (is boss dead or not `bool`)
"""
def __init__(self, id: int, boss: int, start_time: int, end_time: int, name: str, zoneName: str, difficulty: int, bossPercentage: int, **others: dict):
self.id = id
self.boss = boss
self.start_time = start_time
self.end_time = end_time
self.duration = self.set_duration()
self.name = name
self.zoneName = zoneName
self.others = others
self.difficulty = self.set_difficulty(difficulty)
self.bossPercentage = self.set_bossPercentage(bossPercentage)
def set_bossPercentage(self, bossPercentage: int):
if self.others["kill"] == True:
return "Dead!"
else:
return str(bossPercentage / 100) + "%"
def set_difficulty(self, difficulty: int):
"""
1 = LFR
3 = Normal
4 = Heroic
5 = Mythic
10 = Mythic+
20 = Torghast
"""
if difficulty == 20:
return "Torghast"
elif difficulty == 10:
return "Mythic+"
elif difficulty == 5:
return "Mythic"
elif difficulty == 4:
return "Heroic"
elif difficulty == 3:
return "Normal"
elif difficulty == 1:
return "LFR"
def set_duration(self):
return abs(self.start_time - self.end_time)
def __str__(self):
return f"{self.id} - {self.name} {self.duration} {self.difficulty} {self.bossPercentage}"
|
class NoTargetFoundError(Exception):
def __init__(self):
super().__init__("Received attack action without target set. Check correctness")
class IllegalTargetError(Exception):
def __init__(self, agent):
super().__init__(
"The chosen target with id {0} can not be attacked/healed by agent with id {1}."
.format(agent.target_id, agent.id))
class OverhealError(Exception):
def __init__(self, agent):
super().__init__(
"The chosen target with id {0} can not be overhealed by agent with id {1}."
.format(agent.target_id, agent.id))
|
mod = 10**9+7
def extgcd(a, b):
r = [1,0,a]
w = [0,1,b]
while w[2] != 1:
q = r[2]//w[2]
r2 = w
w2 = [r[0]-q*w[0], r[1]-q*w[1], r[2]-q*w[2]]
r = r2
w = w2
return [w[0], w[1]]
def mod_inv(a,m):
x = extgcd(a,m)[0]
return ( m + x%m ) % m
def main():
n,k = map(int,input().split())
z = list(map(int,input().split()))
z.sort()
ans = 0
res = 1
a = n-k
b = k-1
for i in range(1,b+1):
res = res*mod_inv(i,mod) % mod
for i in range(1,b+1):
res = res*i % mod
for i in range(1,a+2):
ans = (ans + z[k-2+i]*res) % mod
ans = (ans - z[n-k+1-i]*res) % mod
res = res*(i+b) % mod
res = res*mod_inv(i,mod) % mod
print(ans)
if __name__ == "__main__":
main()
|
#===============================================================================
#
#===============================================================================
# def Sum(chunks, bits_per_chunk):
# assert bits_per_chunk > 0
# return sum( map(lambda (i, c): c * (2**bits_per_chunk)**i, enumerate(chunks)) )
def Split(n, bits_per_chunk):
assert n >= 0
assert bits_per_chunk > 0
chunks = []
while True:
n, r = divmod(n, 2**bits_per_chunk)
chunks.append(r)
if n == 0:
break
return chunks
def ToHexString(n, bits):
assert bits > 0
p = (bits + (4 - 1)) // 4 # Round up to four bits per hexit
# p = 2**((p - 1).bit_length()) # Round up to next power-of-2
assert 4*p >= n.bit_length()
return('0x{:0{}X}'.format(n, p))
def FormatHexChunks(n, bits_per_chunk = 64):
chunks = Split(n, bits_per_chunk)
s = ', '.join(map(lambda x: ToHexString(x, bits_per_chunk), reversed(chunks)))
if len(chunks) > 1:
s = '{' + s + '}'
return s
#===============================================================================
# Grisu
#===============================================================================
def FloorLog2Pow10(e):
assert e >= -1233
assert e <= 1232
return (e * 1741647) >> 19
def RoundUp(num, den):
assert num >= 0
assert den > 0
p, r = divmod(num, den)
if 2 * r >= den:
p += 1
return p
def ComputeGrisuPower(k, bits):
assert bits > 0
e = FloorLog2Pow10(k) + 1 - bits
if k >= 0:
if e > 0:
f = RoundUp(10**k, 2**e)
else:
f = 10**k * 2**(-e)
else:
f = RoundUp(2**(-e), 10**(-k))
assert f >= 2**(bits - 1)
assert f < 2**bits
return f, e
def PrintGrisuPowers(bits, min_exponent, max_exponent, step = 1):
print('// Let e = FloorLog2Pow10(k) + 1 - {}'.format(bits))
print('// For k >= 0, stores 10^k in the form: round_up(10^k / 2^e )')
print('// For k <= 0, stores 10^k in the form: round_up(2^-e / 10^-k)')
for k in range(min_exponent, max_exponent + 1, step):
f, e = ComputeGrisuPower(k, bits)
print(FormatHexChunks(f, bits_per_chunk=64) + ', // e = {:5d}, k = {:4d}'.format(e, k))
# For double-precision:
# PrintGrisuPowers(bits=64, min_exponent=-300, max_exponent=324, step=8)
# For single-precision:
# PrintGrisuPowers(bits=32, min_exponent=-37, max_exponent=46, step=1)
def DivUp(num, den):
return (num + (den - 1)) // den
def CeilLog10Pow2(e):
assert e >= -2620
assert e <= 2620
return (e * 315653 + (2**20 - 1)) >> 20;
def FloorLog10Pow2(e):
assert e >= -2620
assert e <= 2620
return (e * 315653) >> 20
def ComputeBinaryExponentRange(q, p, exponent_bits):
assert 0 <= p and p + 3 <= q
bias = 2**(exponent_bits - 1) - 1
min_exp = (1 - bias) - (p - 1) - (p - 1) - (q - p)
max_exp = (2**exponent_bits - 2 - bias) - (p - 1) - (q - p)
return min_exp, max_exp
def PrintGrisuPowersForExponentRange(alpha, gamma, q = 64, p = 53, exponent_bits = 11):
assert alpha + 3 <= gamma
# DiyFp precision q = 64
# For IEEE double-precision p = 53, exponent_bits = 11
# e_min, e_max = ComputeBinaryExponentRange(q=64, p=53, exponent_bits=11)
# e_min, e_max = ComputeBinaryExponentRange(q=32, p=24, exponent_bits=8)
e_min, e_max = ComputeBinaryExponentRange(q, p, exponent_bits)
k_del = max(1, FloorLog10Pow2(gamma - alpha))
# k_del = 1
assert k_del >= 1
k_min = CeilLog10Pow2(alpha - e_max - 1)
# k_min += 7
k_max = CeilLog10Pow2(alpha - e_min - 1)
num_cached = DivUp(k_max - k_min, k_del) + 1
k_min_cached = k_min;
k_max_cached = k_min + k_del * (num_cached - 1)
print('constexpr int kAlpha = {:3d};'.format(alpha))
print('constexpr int kGamma = {:3d};'.format(gamma))
print('// k_min = {:4d}'.format(k_min))
print('// k_max = {:4d}'.format(k_max))
# print('// k_del = {:4d}'.format(k_del))
# print('// k_min (max) = {}'.format(k_min + (k_del - 1)))
print('')
print('constexpr int kCachedPowersSize = {:>4d};'.format(num_cached))
print('constexpr int kCachedPowersMinDecExp = {:>4d};'.format(k_min_cached))
print('constexpr int kCachedPowersMaxDecExp = {:>4d};'.format(k_max_cached))
print('constexpr int kCachedPowersDecExpStep = {:>4d};'.format(k_del))
print('')
# print('inline CachedPower GetCachedPower(int index)')
# print('{')
# print(' static constexpr uint{}_t kSignificands[] = {{'.format(q))
# for k in range(k_min_cached, k_max_cached + 1, k_del):
# f, e = ComputeGrisuPower(k, q)
# print(' ' + FormatHexChunks(f, q) + ', // e = {:5d}, k = {:4d}'.format(e, k))
# print(' };')
# print('')
# print(' GRISU_ASSERT(index >= 0);')
# print(' GRISU_ASSERT(index < kCachedPowersSize);')
# print('')
# print(' const int k = kCachedPowersMinDecExp + index * kCachedPowersDecExpStep;')
# print(' const int e = FloorLog2Pow10(k) + 1 - {};'.format(q))
# print('')
# print(' return {kSignificands[index], e, k};')
# print('}')
print('// For a normalized DiyFp w = f * 2^e, this function returns a (normalized)')
print('// cached power-of-ten c = f_c * 2^e_c, such that the exponent of the product')
print('// w * c satisfies')
print('//')
print('// kAlpha <= e_c + e + q <= kGamma.')
print('//')
print('inline CachedPower GetCachedPowerForBinaryExponent(int e)')
print('{')
print(' static constexpr uint{}_t kSignificands[] = {{'.format(q))
for k in range(k_min_cached, k_max_cached + 1, k_del):
f, e = ComputeGrisuPower(k, q)
print(' ' + FormatHexChunks(f, q) + ', // e = {:5d}, k = {:4d}'.format(e, k))
print(' };')
print('')
print(' GRISU_ASSERT(e >= {:>5d});'.format(e_min))
print(' GRISU_ASSERT(e <= {:>5d});'.format(e_max))
print('')
print(' const int k = CeilLog10Pow2(kAlpha - e - 1);')
print(' GRISU_ASSERT(k >= kCachedPowersMinDecExp - (kCachedPowersDecExpStep - 1));')
print(' GRISU_ASSERT(k <= kCachedPowersMaxDecExp);')
print('')
print(' const unsigned index = static_cast<unsigned>(k - (kCachedPowersMinDecExp - (kCachedPowersDecExpStep - 1))) / kCachedPowersDecExpStep;')
print(' GRISU_ASSERT(index < kCachedPowersSize);')
print('')
print(' const int k_cached = kCachedPowersMinDecExp + static_cast<int>(index) * kCachedPowersDecExpStep;')
print(' const int e_cached = FloorLog2Pow10(k_cached) + 1 - {};'.format(q))
print('')
print(' const CachedPower cached = {kSignificands[index], e_cached, k_cached};')
print(' GRISU_ASSERT(kAlpha <= cached.e + e + {});'.format(q))
print(' GRISU_ASSERT(kGamma >= cached.e + e + {});'.format(q))
print('')
print(' return cached;')
print('}')
# PrintGrisuPowersForExponentRange(-60, -32, q=64, p=53, exponent_bits=11)
# PrintGrisuPowersForExponentRange(-59, -32, q=64, p=53, exponent_bits=11)
# PrintGrisuPowersForExponentRange(-56, -42, q=64, p=53, exponent_bits=11)
# PrintGrisuPowersForExponentRange(-3, 0, q=64, p=53, exponent_bits=11)
# PrintGrisuPowersForExponentRange(-28, 0, q=64, p=53, exponent_bits=11)
# PrintGrisuPowersForExponentRange(-53, -46, q=64, p=53, exponent_bits=11)
PrintGrisuPowersForExponentRange(-50, -36, q=64, p=53, exponent_bits=11)
# PrintGrisuPowersForExponentRange(-50, -41, q=64, p=53, exponent_bits=11)
# PrintGrisuPowersForExponentRange(-50, -44, q=64, p=53, exponent_bits=11)
# PrintGrisuPowersForExponentRange(-50, -47, q=64, p=53, exponent_bits=11)
# PrintGrisuPowersForExponentRange(-50, -36, q=64, p=53, exponent_bits=11)
# PrintGrisuPowersForExponentRange(-50, -41, q=64, p=53, exponent_bits=11)
# PrintGrisuPowersForExponentRange(0, 3, q=32, p=24, exponent_bits= 8)
# PrintGrisuPowersForExponentRange(0, 3, q=64, p=53, exponent_bits=11)
# PrintGrisuPowersForExponentRange(-25, -18, q=32, p=24, exponent_bits= 8)
|
class Material():
def __init__(self, E, v, gamma):
self.E = E
self.v = v
self.gamma = gamma
self.G = self.E/2/(1+self.v)
|
"""Kata url: https://www.codewars.com/kata/57a5c31ce298a7e6b7000334."""
def bin_to_decimal(inp: str) -> int:
return int(inp, 2)
|
number = str(input('Digite um numero de 4 digitos: '))
print('Analisando {}....'.format(number))
number.split(" ")
print(number)
print('Tem {} Milhar'.format(number[0]))
print('Tem {} Centenas'.format(number[1]))
print('Tem {} Dezenas'.format(number[2]))
print('Tem {} Unidades'.format(number[3]))
|
class GanException(Exception):
def __init__(self, error_type, error_message, *args, **kwargs):
self.error_type = error_type
self.error_message = error_message
def __str__(self):
return u'({error_type}) {error_message}'.format(error_type=self.error_type,
error_message=self.error_message) |
populationIn2012 = 1000
populationIn2013 = populationIn2012 * 1.1
populationIn2014 = populationIn2013 * 1.1
populationIn2015 = populationIn2014 * 1.1
|
# If you want your function to accept more than one parameter
def f(x, y, z):
return x + y + z
result = f(1, 2, 3)
print(result)
|
'''input
100 99 9
SSSEEECCC
96
94
3 2 3
SEC
1
1
2 4 6
SSSEEE
0
1
0 3 6
SEECEE
0
0
'''
# -*- coding: utf-8 -*-
# bitflyer2018 qual
# Problem B
if __name__ == '__main__':
a, b, n = list(map(int, input().split()))
x = input()
for xi in x:
if xi == 'S' and a > 0:
a -= 1
elif xi == 'C' and b > 0:
b -= 1
elif xi == 'E':
if a >= b and a > 0:
a -= 1
elif a < b and b > 0:
b -= 1
print(a)
print(b)
|
"""This problem was asked by LinkedIn.
Given a string, return whether it represents a number. Here are the different kinds of numbers:
- "10", a positive integer
- "-10", a negative integer
- "10.1", a positive real number
- "-10.1", a negative real number
- "1e5", a number in scientific notation
And here are examples of non-numbers:
- "a"
- "x 1"
- "a -2"
- "-"
"""
def number(data):
first = data[0]
real = False
positive = True
if first == '-':
positive = False
for i in data[1:]:
if i not in [1,2,3,4,5,6,7,8,9,0]:
return "not a number"
if i == ".":
real = True
if positive :
yield "a Positive"
else:
yield "a Negative"
if real:
return " Real Number"
else :
return " Integer "
|
print("hello world")
def get_array(file_name: str):
with open(file_name) as f:
array = [[x for x in line.split()] for line in f]
return(array)
def card_to_tuple(card: str):
faces = {
"A" : 14,
"K" : 13,
"Q" : 12,
"J" : 11,
"T" : 10,
"9" : 9,
"8" : 8,
"7" : 7,
"6" : 6,
"5" : 5,
"4" : 4,
"3" : 3,
"2" : 2,
}
return (faces[card[0]],card[1])
def check_flush(cards:list):
for i in range(1,5): #checks all suits are the same as cards[1]
if cards[i][1] != cards[1][1]:
return False
return True
def check_straight(cards:list):
for i in range(1,5):
if cards[i][0] != cards[i-1][0] + 1:
return False
return True
def sort_cards(cards): #NEED TO TEST ------------------------------------------------
'''selection sort. Smallest to largest'''
for i in range(len(cards)):
for j in range(i+1, len(cards)):
if cards[i][0] > cards[j][0]:
cards[j],cards[i] = cards[i],cards[j]
return cards
def remove_all(cards, removes: list):
new = cards[:]
for i in cards:
if i[0] in removes:
new.remove(i)
return new
def pokerhand(cards:list):
'''Returns the rating a list: [pokerhand rating, level of hand, highcard1, ...]'''
for i in range(5):
cards[i] = card_to_tuple(cards[i])
cards = sort_cards(cards)
counts = [0,0,0,0,0,0,0,0,0,0,0,0,0] # number of each card
for card in cards:
counts[card[0]-2] += 1
if check_flush(cards):
if check_straight(cards):
if cards[4][0] == 14: #royal flush
return [10]
else:
return [9, cards[4]] #straight flush
elif not (4 in counts or 3 in counts and 2 in counts): #Not a 4 of a kind or full house
return [6] + cards[::-1] # flush
if 4 in counts: #4 of a kind
return [8] + [counts.index(4)+2, counts.index(1)+2]
if 3 in counts and 2 in counts: # full house
return[7] + [counts.index(3)+2, counts.index(2)+2]
if check_straight(cards):
return [5, cards[4]]
if 3 in counts: #3 of a kind
three = counts.index(3)+2
return [4] + [three] + [x[0] for x in remove_all(cards, [three])][::-1]
if counts.count(2) == 2: #two pair
twos = []
for i in range(len(counts)):
if counts[i] == 2:
twos.append(i + 2)
return [3] + twos[::-1] + [x[0] for x in remove_all(cards, twos)][::-1]
elif counts.count(2) == 1: # pair
two = counts.index(2)+2
return [2] + [two] + [x[0] for x in remove_all(cards, [two])][::-1]
return [1] + [x[0] for x in cards][::-1] #high cards
def poker_win(arr:list):
'''find the maximum base exponent pair in array
array is a list of lists
'''
count = 1
for hand in arr:
p1 = hand[:5]#splits into players
p2 = hand[5:]
score1 = pokerhand(p1)
score2 = pokerhand(p2)
for i in range(5):
if score1[i] > score2[i]:
count += 1
break
if score1[i] < score2[i]:
break
return count
if __name__ == "__main__":
hands = get_array('p054_poker.txt')
print(poker_win(hands))
|
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 31 12:37:52 2020
@author: SethHarden
Heap Sorting a List
"""
# Data structure for Max Heap
# return left child of A[i]
def LEFT(i):
return 2 * i + 1
# return right child of A[i]
def RIGHT(i):
return 2 * i + 2
# Utility function to swap two indices in the list
def swap(A, i, j):
temp = A[i]
A[i] = A[j]
A[j] = temp
# Recursive Heapify-down algorithm. The node at index i and
# its two direct children violates the heap property
def Heapify(A, i, size):
# get left and right child of node at index i
left = LEFT(i)
right = RIGHT(i)
largest = i
# compare A[i] with its left and right child
# and find largest value
if left < size and A[left] > A[i]:
largest = left
if right < size and A[right] > A[largest]:
largest = right
# swap with child having greater value and
# call heapify-down on the child
if largest != i:
swap(A, i, largest)
Heapify(A, largest, size)
# function to remove element with highest priority (present at root)
def pop(A, size):
# if heap has no elements
if size <= 0:
return -1
top = A[0]
# replace the root of the heap with the last element
# of the list
A[0] = A[size - 1]
# call heapify-down on root node
Heapify(A, 0, size - 1)
return top
# Function to perform heapsort on list A of size n
def heapSort(A):
# build a priority queue and initialize it by given list
n = len(A)
# Build-heap: Call heapify starting from last internal
# node all the way upto the root node
i = (n - 2) // 2
while i >= 0:
Heapify(A, i, n)
i = i - 1
# pop repeatedly from the heap till it becomes empty
while n:
A[n - 1] = pop(A, n)
n = n - 1
if __name__ == '__main__':
A = [6, 4, 7, 1, 9, -2]
# perform heapsort on the list
heapSort(A)
# print the sorted list
print(A) |
# -*- coding: utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __eq__(self, other):
return (
other is not None and
self.val == other.val and
self.left == other.left and
self.right == other.right
)
class Solution:
def mergeTrees(self, t1, t2):
if t1 is None:
return t2
elif t2 is None:
return t1
result = TreeNode(t1.val + t2.val)
result.left = self.mergeTrees(t1.left, t2.left)
result.right = self.mergeTrees(t1.right, t2.right)
return result
if __name__ == '__main__':
solution = Solution()
t1_0 = TreeNode(1)
t1_1 = TreeNode(3)
t1_2 = TreeNode(2)
t1_3 = TreeNode(5)
t1_1.left = t1_3
t1_0.left = t1_1
t1_0.right = t1_2
t2_0 = TreeNode(2)
t2_1 = TreeNode(1)
t2_2 = TreeNode(3)
t2_3 = TreeNode(4)
t2_4 = TreeNode(7)
t2_2.right = t2_4
t2_1.right = t2_3
t2_0.left = t2_1
t2_0.right = t2_2
t3_0 = TreeNode(3)
t3_1 = TreeNode(4)
t3_2 = TreeNode(5)
t3_3 = TreeNode(5)
t3_4 = TreeNode(4)
t3_5 = TreeNode(7)
t3_2.right = t3_5
t3_1.left = t3_3
t3_1.right = t3_4
t3_0.left = t3_1
t3_0.right = t3_2
assert t3_0 == solution.mergeTrees(t1_0, t2_0)
|
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
# from django-livereload server
'livereload.middleware.LiveReloadScript',
# from django-debug-toolbar
"debug_toolbar.middleware.DebugToolbarMiddleware"
] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@author: rainsty
@file: decorator.py
@time: 2019-12-30 13:34:29
@description: decorator
"""
|
class DeviceConsent:
def __init__(
self,
id: int,
location_capture: bool,
location_granular: bool,
camera: bool,
calendar: bool,
photo_sharing: bool,
push_notification: bool,
created_at,
updated_at
):
self.id = id
self.location_capture = location_capture
self.location_granular = location_granular
self.camera = camera
self.calendar = calendar
self.photo_sharing = photo_sharing
self.push_notification = push_notification
self.created_at = created_at
self.updated_at = updated_at
|
def deleteDuplicate(elements):
del_duplicates = set(elements)
return list(del_duplicates)
if __name__ == '__main__':
list_with_Duplicate = [1,2,34,2,3,1,5,6,3,1,2,6,5,4,3]
print(deleteDuplicate(list_with_Duplicate)) |
# Challenge 8 : Create a function named max_num() that takes a list of numbers named nums as a parameter.
# The function should return the largest number in nums
# Date : Sun 07 Jun 2020 09:19:45 AM IST
def max_num(nums):
maximum = nums[0]
for i in range(len(nums)):
if maximum < nums[i]:
maximum = nums[i]
return maximum
print(max_num([50, -10, 0, 75, 20]))
print(max_num([-50, -20]))
|
#!/usr/bin/env python
# encoding:utf-8
# file: homework1.py
# 列表中找元素
# TODO 用哈希表实现元素查找
def find1(lst, elem):
"""方法1:遍历
"""
for i in lst:
if elem == i:
return 1
else:
return 0
def find2(lst, elem):
"""方法2:内置方法
"""
return 1 if elem in lst else 0
if __name__ == '__main__':
x = '123'
a_list = [1, 2, 'a', '123', 2.2]
b_list = [1, 2, 'a', '1234', 2.2]
print(find1(a_list, x))
print(find1(b_list, x))
print(find2(a_list, x))
print(find2(b_list, x))
|
class FetchMinAllotments:
'''
Uses a state or territory and a household size to fetch the min allotment,
returning None if the household is not eligible for a minimum allotment.
In 2020, only one- and two- person households are eligible for a minimum
allotment amount.
'''
def __init__(self, state_or_territory, household_size, min_allotments):
self.state_or_territory = state_or_territory
self.household_size = household_size
self.min_allotments = min_allotments
def state_lookup_key(self):
return {
'AK_URBAN': 'AK_URBAN', # TODO (ARS): Figure this out.
'AK_RURAL_1': 'AK_RURAL_1', # TODO (ARS): Figure this out.
'AK_RURAL_2': 'AK_RURAL_2', # TODO (ARS): Figure this out.
'HI': 'HI',
'GUAM': 'GUAM',
'VIRGIN_ISLANDS': 'VIRGIN_ISLANDS'
}.get(self.state_or_territory, 'DEFAULT')
def calculate(self):
scale = self.min_allotments[self.state_lookup_key()][2020]
# Minimum SNAP allotments are only defined for one- or two- person
# households. A return value of None means no minimum, so the household
# might receive zero SNAP benefit despite being eligible.
if (0 < self.household_size < 3):
return scale[self.household_size]
else:
return None
|
#Hi, here's your problem today. This problem was recently asked by Twitter:
#Given a binary tree and an integer k, filter the binary tree such that its leaves don't contain the value k. Here are the rules:
#- If a leaf node has a value of k, remove it.
#- If a parent node has a value of k, and all of its children are removed, remove it.
#Here's an example and some starter code:
#Analysis
#dfs to the leaf with recursive function: func(node) -> boolean
# if leaf value is k, return true else false
# if non leaf node
# check return value of recursive function.... if yes, remove that child
# if all children removed, and its value is k,
# return true to its caller
# else return false
# Time complexity O(N) Space complexity O(N) --- memory stack usage when doing recursion
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __repr__(self):
return f"value: {self.value}, left: ({self.left.__repr__()}), right: ({self.right.__repr__()})"
class Solution():
def filter_recursive(self, node:Node,k:int)->bool:
if node.left is None and node.right is None:
return node.value == k
leftRet = True
rightRet = True
if node.left is not None:
leftRet = self.filter_recursive(node.left, k)
if node.right is not None:
rightRet = self.filter_recursive(node.right, k)
if leftRet:
node.left = None
if rightRet:
node.right = None
return leftRet and rightRet and node.value==k
def filter(tree, k):
# Fill this in.
solu = Solution()
solu.filter_recursive(tree, k)
return tree
if __name__ == "__main__":
# 1
# / \
# 1 1
# / /
# 2 1
n5 = Node(2)
n4 = Node(1)
n3 = Node(1, n4)
n2 = Node(1, n5)
n1 = Node(1, n2, n3)
print(str(filter(n1, 1)))
# 1
# /
# 1
# /
# 2
# value: 1, left: (value: 1, left: (value: 2, left: (None), right: (None)), right: (None)), right: (None) |
SECTOR_SIZE = 40000
def pixels2sector(x, y):
return str(int(x/SECTOR_SIZE+.5)) + ":" + str(int(-y/SECTOR_SIZE+.5))
def sector2pixels(sec):
x, y = sec.split(":")
return int(x)*SECTOR_SIZE, -int(y)*SECTOR_SIZE
|
# returns unparenthesized character string
def balanced_parens(s):
open_parens = len(s) - len(s.replace("(", ""))
closed_parens = len(s) - len(s.replace(")", ""))
if (open_parens == closed_parens):
return True
else:
return False
|
def get_data():
# get raw data for modeling
print('Get data..')
return
|
"""
Definition for classes used to represent models generated by Swagger.
"""
class Error:
def __init__(self):
self.code = 200
self.message = "OK"
def __str__(self):
return self.code+ " : " +self.message
class Evidence:
def __init__(self):
self.evidenceSource = []
self.evidenceCode = ""
def add_evidenceSource(self, evidenceSource):
self.evidenceSource.append(evidenceSource)
def __str__(self):
return self.evidenceSource+ " : "+self.evidenceCode
class SearchParameter:
def __init__(self):
self.searchField = "AllFields"
self.searchValue = ""
self.showAltID = True
self.showPROName = True
self.showPRONamespace = True
self.showPROTermDefinition = True
self.showCategory = True
self.showParent = True
self.showAncestor = False
self.showAnnotation = False
self.showAnyRelationship = False
self.showChild = False
self.showDescendant = False
self.showComment = False
self.showEcoCycID = False
self.showGeneName = False
self.showHGNCID = False
self.showMGIID = False
self.showOrthoIsoform = False
self.showOrthoModform = False
self.showPANTHERID = False
self.showPIRSFID = False
self.showPMID = False
self.showReactomeID = False
self.showSynonym = False
self.showTaxonID = False
self.showUniProtKBID = False
self.offset = "0"
self.limit = "50"
def __str__(self):
return "searchField: "+self.searchField+"\nsearchValue: " + self.searchValue+\
"\nshowPROName: " + str(self.showPROName) + "\nshowPROTermDefinition: "+ str(self.showPROTermDefinition)+\
"\nshowCategory: "+ str(self.showCategory) + "\nshowParent: "+str(self.showParent) + \
"\nshowAncestor: " + str(self.showAncestor) + "\nshowAnnotation: " + str(self.showAnnotation) + \
"\nshowAnyRelationship: " + str(self.showAnyRelationship) + "\nshowChild: " + str(self.showChild)
class Annotation:
def __init__(self):
self.modifier = ""
self.relation = ""
self.ontologyID = ""
self.ontologyTerm = ""
self.relativeTo = ""
self.interactionWith = ""
self.evidence = None
self.ncbiTaxonId = ""
self.inferredFrom = []
# class PAF:
#
# def __init__(self):
# self.proID = ""
# self.objectTerm = ""
# self.objectSyny = ""
# self.modifier = ""
# self.relation = ""
# self.ontologyID = ""
# self.ontologyTerm = ""
# self.relativeTo = ""
# self.interactionWith = ""
# self.evidenceSource = ""
# self.evidenceCode = ""
# self.taxon = ""
# self.inferredFrom = ""
# self.dbID = ""
# self.date = ""
# self.assignedBy = ""
# self.comment = ""
class Parent:
def __init__(self):
self.pro = ""
self.parent = ""
class Ancestor:
def __init__(self):
self.pro = ""
self.ancestor = ""
class Children:
def __init__(self):
self.pro = ""
self.children = ""
class Decendant:
def __init__(self):
self.pro = ""
self.decendant = ""
class PAF:
def __init__(self):
self.PRO_ID = ""
self.Object_term = ""
self.Object_syny = ""
self.Modifier = ""
self.Relation = ""
self.Ontology_ID = ""
self.Ontology_term = ""
self.Relative_to = ""
self.Interaction_with = ""
self.Evidence_source = ""
self.Evidence_code = ""
self.Taxon = ""
self.Inferred_from = ""
self.DB_ID = ""
self.Date = ""
self.Assigned_by = ""
self.Comment = ""
class PROTerm:
def __init__(self):
self.id = ""
self.alt_id = ""
self.name = ""
self.namespace = ""
self.termDef = ""
self.category = ""
self.anyRelationship = ""
self.annotation = []
self.child = []
self.descendant = []
self.comment = ""
self.ecoCycID = ""
self.geneName = ""
self.hgncID = []
self.mgiID = []
self.orthoIsoform = []
self.orthoModform = []
self.pantherID = ""
self.parent = []
self.ancestor = []
self.pirsfID = ""
self.pmID = []
self.reactomeID = []
self.synonym = []
self.taxonID = "";
self.uniprotKBID = []
def __str__(self):
return "alt_id: "+self.alt_id
|
## Problem: Print details
def printOwing(self, amount):
self.printBanner()
# print details
print("name: ", self._name)
print("amount: ", amount)
def printLateNotice(self, amount):
self.printBanner()
self.printLateNoticeHeader()
# print details
print("name: ", self._name)
print("amount: ", amount)
## Solution
def printOwing(self, amount):
self.printBanner()
self.printDetails(amount)
def printLateNotice(self, amount):
self.printBanner()
self.printLateNoticeHeader()
self.printDetails(amount)
def printDetails(self, amount):
print("name: ", self._name)
print("amount: ", amount) |
lower = list(range(3,21,1))
upper = list(range(21,39,1))
output = ""
count = 0
for i in range(len(lower)):
for j in range(len(lower)):
if j != i and j != i-1 and j != i+1:
count += 1
output += "\t" + str(lower[i]) + "\t" + str(lower[j]) + "\n"
for i in range(len(upper)):
for j in range(len(upper)):
if j != i and j != i-1 and j != i+1:
count += 1
output += "\t" + str(upper[i]) + "\t" + str(upper[j]) + "\n"
print("Disconnect" + "\n\t" + str(count) + "\n" + output)
for i in range(len(lower)):
if i != 0:
print("intergace_force_coef_" + str(lower[i]) + "_" + str(lower[i-1]))
print("\t1.0")
print("intergace_strength_coef_" + str(lower[i]) + "_" + str(lower[i-1]))
print("\t1.0")
print("intergace_force_coef_" + str(lower[i]) + "_1" )
print("\t1.0")
print("intergace_strength_coef_" + str(lower[i]) + "_1" )
print("\t1.0")
print("intergace_force_coef_" + str(lower[i]) + "_2")
print("\t1.0")
print("intergace_strength_coef_" + str(lower[i]) + "_2")
print("\t1.0")
for i in range(len(upper)):
if i != 0:
print("intergace_force_coef_" + str(upper[i]) + "_" + str(upper[i-1]))
print("\t1.0")
print("intergace_strength_coef_" + str(upper[i]) + "_" + str(upper[i-1]))
print("\t1.0")
print("intergace_force_coef_" + str(upper[i]) + "_1" )
print("\t1.0")
print("intergace_strength_coef_" + str(upper[i]) + "_1" )
print("\t1.0")
print("intergace_force_coef_" + str(upper[i]) + "_2")
print("\t1.0")
print("intergace_strength_coef_" + str(upper[i]) + "_2")
print("\t1.0")
|
extensions = ["sphinx.ext.autodoc", "sphinx_markdown_builder"]
master_doc = "index"
project = "numbers-parser"
copyright = "Jon Connell"
|
#Ex1072 Intervalo 2
entrada = int(input())
cont = 1
intervalo = 0
fora = 0
while cont <= entrada:
numeros = int(input())
if numeros >= 10 and numeros <= 20:
intervalo = intervalo + 1
else:
fora = fora + 1
cont = cont + 1
print('{} in\n{} out'.format(intervalo, fora))
|
class ROBConfig(Config):
"""Configuration for training on the toy shapes dataset.
Derives from the base Config class and overrides values specific
to the toy shapes dataset.
"""
# Give the configuration a recognizable name
NAME = "rob"
# Train on 1 GPU and 8 images per GPU. We can put multiple images on each
# GPU because the images are small. Batch size is 8 (GPUs * images/GPU).
GPU_COUNT = 1
# IMAGES_PER_GPU = 8
# Default is 2
IMAGES_PER_GPU = 2
# Number of classes (including background)
NUM_CLASSES = 1 + 4 # background + 4 class labels
# Use small images for faster training. Set the limits of the small side
# the large side, and that determines the image shape.
# IMAGE_MIN_DIM = 128
# IMAGE_MAX_DIM = 128
# Default is 800 x 1024
# Use smaller anchors because our image and objects are small
# RPN_ANCHOR_SCALES = (8, 16, 32, 64, 128) # anchor side in pixels
# DEFAULT: RPN_ANCHOR_SCALES = (32, 64, 128, 256, 512)
# Reduce training ROIs per image because the images are small and have
# few objects. Aim to allow ROI sampling to pick 33% positive ROIs.
TRAIN_ROIS_PER_IMAGE = 32
# Default is 200
# Use a small epoch since the data is simple
# STEPS_PER_EPOCH = 100
# Default is 1000
STEPS_PER_EPOCH = int(5561/(GPU_COUNT*IMAGES_PER_GPU))
# use small validation steps since the epoch is small
# VALIDATION_STEPS = 5
# Max number of final detections
DETECTION_MAX_INSTANCES = 5
# Minimum probability value to accept a detected instance
# ROIs below this threshold are skipped
DETECTION_MIN_CONFIDENCE = 0.6
# Run these lines in the co-lab cell where this is imported:
# config = ROBConfig()
# config.display()
class InferenceConfig(ROBConfig):
GPU_COUNT = 1
IMAGES_PER_GPU = 1 |
#!/usr/bin/python3
DATABASE = "./vocabulary.db"
WORD_TYPE_CUTOFFED = 1
WORD_TYPE_CUTOFF = 0
WORD_RIGHT_YES = 1
WORD_RIGHT_NO = 0
# wrong words review frequency, N means wrong words will occur each N times.
WRONG_WORDS_REVIEW_FREQUENCY = 3
# highlight and with font color red.
RECITE_PRINT_FORMAT = "[{}]> \33[1m\33[31m{}\33[0m\33[0m"
# answer with font color green
PRINT_VOCABULARY_DESC = "[Answer]\33[1m\33[32m{}\33[0m\33[0m"
# details in database
DETAILS_PRINT_FORMAT_IN_DATABASE = "[Detail]ID:\33[1m\33[32m{}\33[0m\33[0m\t desc=\33[1m\33[32m{}\33[0m\33[0m\tcutoff=\33[1m\33[32m{}\33[0m\33[0m"
# help information
RECITE_HELP_INFORMATION = """
COMMANDS OF RECITING VOCABULARIES
`\33[1m\33[33myes\33[0m\33[0m` : i have know this vocabulary, just pass it.
`\33[1m\33[33mno\33[0m\33[0m` : i don't know this vocabulary, tell me the meaning.
`\33[1m\33[33msay\33[0m\33[0m` : play the audio by using system setting.
`\33[1m\33[33mcutoff\33[0m\33[0m` : never show this vocabulary again.
`\33[1m\33[33mrepeat\33[0m\33[0m` : repeat current word and stay in this round.
`\33[1m\33[33mshow \33[0m\33[0m` : show details in database.
`\33[1m\33[33mfind= \33[0m\33[0m` : find=xxx, get the meaning in database with key=xxx
`\33[1m\33[33mstatic=N\33[0m\33[0m`: static=N, show the statics of N days ago. N=0 means current day. N <= 0
`\33[1m\33[33mwrong=N \33[0m\33[0m`: wrong=N, show the wrong words of N days ago. N=0 means current day. N <= Zero
`\33[1m\33[33mquit\33[0m\33[0m` : quit this recite round.
`\33[1m\33[33mexport=N\33[0m\33[0m`: export=N, for exporting wrong words of N days ago.
`\33[1m\33[36mhelp\33[0m\33[0m` : tip me with keywords.
example:
>say say repeat
>say show
>find=hello
"""
# sub commands to act for reciting words.
COMMANDS_HELP = "help"
COMMANDS_SAY = "say"
COMMANDS_CUTOFF = "cutoff"
COMMANDS_REPEAT = "repeat"
COMMANDS_SHOW = "show"
COMMANDS_FIND = "find="
COMMANDS_STATIC = "static="
COMMANDS_WRONG = "wrong="
COMMANDS_EXPORT = "export="
COMMANDS_YES = "yes"
COMMANDS_NO = "no"
COMMANDS_QUIT = "quit" |
# -*- coding: utf-8 -*-
#
"""
Partie arithmetique du module lycee.
"""
def pgcd(a, b):
"""Renvoie le Plus Grand Diviseur Communs des entiers ``a`` et ``b``.
Arguments:
a (int) : un nombre entier
b (int) : un nombre entier
"""
if a < 0 or b < 0:
return pgcd(abs(a), abs(b))
if b == 0:
if a == 0:
raise ZeroDivisionError(
"Le PGCD de deux nombres nuls n'existe pas")
return a
return pgcd(b, a % b)
def reste(a, b):
"""Renvoie le reste de la division de ``a`` par ``b``.
Arguments:
a (int): Un nombre entier.
b (int): Un nombre entier non nul.
"""
r = a % b
if r < 0:
r = r + abs(b)
return r
def quotient(a, b):
"""Le quotient de la division de ``a`` par ``b``.
Arguments:
a (int): Un nombre entier.
b (int): Un nombre entier non nul.
"""
return a // b
|
def is_number_tryexcept(s):
""" Returns True is string is a number. """
try:
int(s)
return True
except ValueError:
return False
def get_valid_k_input(list_length):
while True:
k = input('podaj k: ')
if not is_number_tryexcept(k):
print('podana wartość nie jest liczbą')
continue
k_int = int(k)
if k_int <= 0 or k_int > list_length:
print('podany indeks jest spoza dozwolonego zakresu')
continue
return k_int
def get_kth_element_reversed(lst):
k = get_valid_k_input(len(lst))
return lst[-k]
print(get_kth_element_reversed([1, 2, 3, 4, 5, 6, 7, 8, 9]))
|
def findComplement(self, num: int) -> int:
x = bin(num)[2:]
z = ""
for i in x:
z+=str(int(i) ^ 1)
return int(z, 2) |
class Fancy:
def __init__(self):
self.data=[]
self.add=[]
self.mult=[]
def append(self, val: int) -> None:
self.data.append(val)
if len(self.mult)==0:
self.mult.append(1)
self.add.append(0)
self.mult.append(self.mult[-1])
self.add.append(self.add[-1])
def addAll(self, inc: int) -> None:
if len(self.data)==0:
return
self.add[-1]+=inc
def multAll(self, m: int) -> None:
if len(self.data)==0:
return
self.mult[-1]*=m
self.add[-1]*=m
def getIndex(self, idx: int) -> int:
if idx>=len(self.data):
return -1
m=self.mult[-1]//self.mult[idx]
inc=self.add[-1]-self.add[idx]*m
return (self.data[idx]*m+inc)%1000000007
# Your Fancy object will be instantiated and called as such:
# obj = Fancy()
# obj.append(val)
# obj.addAll(inc)
# obj.multAll(m)
# param_4 = obj.getIndex(idx)
# Ref: https://leetcode.com/problems/fancy-sequence/discuss/898753/Python-Time-O(1)-for-each |
class Logger(object):
''' Utility class responsible for logging all interactions during the simulation. '''
# TODO: Write a test suite for this class to make sure each method is working
# as expected.
# PROTIP: Write your tests before you solve each function, that way you can
# test them one by one as you write your class.
def __init__(self, file_name):
# TODO: Finish this initialization method. The file_name passed should be the
# full file name of the file that the logs will be written to.
self.file_name = None
def write_metadata(self, pop_size, vacc_percentage, virus_name, mortality_rate,
basic_repro_num):
'''
The simulation class should use this method immediately to log the specific
parameters of the simulation as the first line of the file.
'''
# TODO: Finish this method. This line of metadata should be tab-delimited
# it should create the text file that we will store all logs in.
# TIP: Use 'w' mode when you open the file. For all other methods, use
# the 'a' mode to append a new log to the end, since 'w' overwrites the file.
# NOTE: Make sure to end every line with a '/n' character to ensure that each
# event logged ends up on a separate line!
pass
def log_interaction(self, person, random_person, random_person_sick=None,
random_person_vacc=None, did_infect=None):
'''
The Simulation object should use this method to log every interaction
a sick person has during each time step.
The format of the log should be: "{person.ID} infects {random_person.ID} \n"
or the other edge cases:
"{person.ID} didn't infect {random_person.ID} because {'vaccinated' or 'already sick'} \n"
'''
# TODO: Finish this method. Think about how the booleans passed (or not passed)
# represent all the possible edge cases. Use the values passed along with each person,
# along with whether they are sick or vaccinated when they interact to determine
# exactly what happened in the interaction and create a String, and write to your logfile.
pass
def log_infection_survival(self, person, did_die_from_infection):
''' The Simulation object uses this method to log the results of every
call of a Person object's .resolve_infection() method.
The format of the log should be:
"{person.ID} died from infection\n" or "{person.ID} survived infection.\n"
'''
# TODO: Finish this method. If the person survives, did_die_from_infection
# should be False. Otherwise, did_die_from_infection should be True.
# Append the results of the infection to the logfile
pass
def log_time_step(self, time_step_number):
''' STRETCH CHALLENGE DETAILS:
If you choose to extend this method, the format of the summary statistics logged
are up to you.
At minimum, it should contain:
The number of people that were infected during this specific time step.
The number of people that died on this specific time step.
The total number of people infected in the population, including the newly infected
The total number of dead, including those that died during this time step.
The format of this log should be:
"Time step {time_step_number} ended, beginning {time_step_number + 1}\n"
'''
# TODO: Finish this method. This method should log when a time step ends, and a
# new one begins.
# NOTE: Here is an opportunity for a stretch challenge!
pass
|
"""
Title - Trie Data Structure
Data structure to insert and search word efficiently
time complexity - O(n) where n=len(word)
"""
class LL: # Linked List Data structure to store level wise nodes of Trie
def __init__(self, val):
self.val = val
self.next = {}
self.completed = False
class Trie:
"""
Trie is also called as prefix tree
"""
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = LL(None)
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node = self.root
for i in word:
if i not in node.next:
node.next[i] = LL(i)
node = node.next[i]
node.completed = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
node = self.root
for i in word:
if i not in node.next:
return False
node = node.next[i]
return node.completed
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
node = self.root
for i in prefix:
if i not in node.next:
return False
node = node.next[i]
return True
# obj = Trie()
# obj.insert("python")
# param_2 = obj.search("python")
# param_3 = obj.startsWith("pyt")
# print(param_2)
# print(param_3)
|
#layout notes:
# min M1 trace width for M1-M2 via: 0.26um
# min M2 trace width for Li -M2 via: 0.23um trace with 0.17um x 0.17um contact
class LogicCell:
def __init__(self, name, width):
self.width = width
self.name = name
inv1 = LogicCell("sky130_fd_sc_hvl__inv_1", 1.44)
inv4 = LogicCell("sky130_fd_sc_hvl__inv_4", 3.84)
decap_8 = LogicCell("sky130_fd_sc_hvl__decap_8", 3.84)
mux2 = LogicCell("sky130_fd_sc_hvl__mux2_1", 5.28)
or2 = LogicCell("sky130_fd_sc_hvl__or2_1", 3.36)
nor2 = LogicCell("sky130_fd_sc_hvl__nor2_1", 2.4)
nand2 = LogicCell("sky130_fd_sc_hvl__nand2_1", 2.4)
and2 = LogicCell("sky130_fd_sc_hvl__and2_1", 3.36)
flipped_cells = [mux2]
fout = open("switch_control_build.tcl", "w")
cmd_str = "load switch_control\n"
fout.write(cmd_str)
vertical_pitch = 4.07
row0 = [decap_8, mux2, inv1, inv4] #timeout select
row1 = [decap_8, and2, or2, inv1, and2, nor2, nor2] #input and SR latch
row2 = [decap_8, decap_8, decap_8, nand2, mux2] # PMOS switch control
row3 = [decap_8, decap_8, decap_8, and2, mux2] #nmos switch control
row4 = [decap_8, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv4] #PMOS delay chain
row5 = [decap_8, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv4] #PMOS delay chain
row6 = [decap_8, mux2, or2, inv1, inv4, inv4] #pmos out
row7 = [decap_8, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv4] #NMOS delay chain
row8 = [decap_8, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv4] #NMOS delay chain
row9 = [decap_8, mux2, and2, inv1, inv4, inv4] #nmos out
ending_decap_loc = 0
rows = [row0, row1, row2, row3, row4, row5, row6, row7, row8, row9]
x_start = 0
y_start = 0
y_val = y_start
index = 0
ending_decap_loc = 0
for row in rows:
total_width = 0
for cell in row:
total_width = total_width + cell.width
if total_width > ending_decap_loc:
ending_decap_loc = total_width
for row in rows:
x_val = x_start
y_val = y_val + vertical_pitch
for cell in row:
cmd_str = "box %gum %gum %gum %gum\n" % (x_val, y_val, x_val, y_val)
fout.write(cmd_str)
if (index%2 == 0): #normal orientation
if cell in flipped_cells:
cmd_str = "getcell %s h child ll \n" % (cell.name)
fout.write(cmd_str)
else:
cmd_str = "getcell %s child ll \n" % (cell.name)
fout.write(cmd_str)
else: #odd cells are vertically flipped so power stripes align
if cell in flipped_cells:
cmd_str = "getcell %s 180 child ll \n" % (cell.name)
fout.write(cmd_str)
else:
cmd_str = "getcell %s v child ll \n" % (cell.name)
fout.write(cmd_str)
x_val = x_val + cell.width
#ending decap
x_val = ending_decap_loc
cell = decap_8
cmd_str = "box %gum %gum %gum %gum\n" % (x_val, y_val, x_val, y_val)
fout.write(cmd_str)
if (index%2 == 0): #normal orientation
if cell in flipped_cells:
cmd_str = "getcell %s h child ll \n" % (cell.name)
fout.write(cmd_str)
else:
cmd_str = "getcell %s child ll \n" % (cell.name)
fout.write(cmd_str)
else: #odd cells are vertically flipped so power stripes align
if cell in flipped_cells:
cmd_str = "getcell %s 180 child ll \n" % (cell.name)
fout.write(cmd_str)
else:
cmd_str = "getcell %s v child ll \n" % (cell.name)
fout.write(cmd_str)
index = index + 1
|
num1 = 5
num2 = 25
print('num1 is: ', str(num1))
print('num2 is: ', str(num2))
for i in range(num1, num2 + 1, 5):
print('i is currently: ', str(i))
print(str(i) + ' ', end='')
print()
print()
|
# -*- coding: utf-8 -*-
for i in range(1,3):
print(i)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Zeyuan Shang
# @Date: 2015-11-19 20:43:07
# @Last Modified by: Zeyuan Shang
# @Last Modified time: 2015-11-19 20:43:21
class Solution(object):
def shortestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
ss = s + '#' + s[::-1]
n = len(ss)
p = [0] * n
for i in xrange(1, n):
j = p[i - 1]
while j > 0 and ss[i] != ss[j]:
j = p[j - 1]
p[i] = j + (ss[i] == s[j])
return s[p[-1]:][::-1] + s |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class QLTecnica(object):
u"""Técnica para Q-Learning"""
def __init__(self, parametro=None, paso_decremento=0, intervalo_decremento=0):
super(QLTecnica, self).__init__()
self._paso_decremento = paso_decremento
self._intervalo_decremento = intervalo_decremento
self._val_param_general = parametro
self._val_param_parcial = parametro
self._name = "QLTecnica"
def obtener_accion(self, acciones):
u"""
Devuelve un sólo estado vecino de una lista de estados acciones.
:param matriz_q: Matriz Q a utilizar.
:param acciones: Acciones del estado actual.
"""
pass
def decrementar_parametro(self):
u"""
Decrementar parámetro en un valor dado.
"""
pass
def get_paso_decremento(self):
return self._paso_decremento
def set_paso_decremento(self, paso):
self._paso_decremento = paso
def get_intervalo_decremento(self):
return self._intervalo_decremento
def set_intervalo_decremento(self, valor):
u"""
Establecer cada cuantos episodios se decrementará el episodio.
:param valor: Número flotante que se descontará al parámetro.
"""
self._intervalo_decremento = valor
def get_valor_param_general(self):
return self._val_param_general
def set_valor_param_general(self, valor):
self._val_param_general = valor
self._val_param_parcial = valor
def _get_valor_param_parcial(self):
return self._val_param_parcial
def restaurar_val_parametro(self):
self._val_param_parcial = self._val_param_general
def get_name(self):
return self._name
def set_name(self, nombre):
self._name = nombre
def __repr__(self, *args, **kwargs):
return self.__class__.__name__
def __str__(self, *args, **kwargs):
return self.__class__.__name__
paso_decremento = property(get_paso_decremento,
set_paso_decremento,
None,
"Valor de decremento")
intervalo_decremento = property(get_intervalo_decremento,
set_intervalo_decremento,
None,
u"Número entero indicando cada cuantas \
iteraciones decrementar el parámetro \
utilizando un \
valor de paso dado")
valor_param_general = property(get_valor_param_general,
set_valor_param_general,
None,
u"Número indicando el valor del \
parámetro general")
valor_param_parcial = property(_get_valor_param_parcial,
None,
None,
u"Número indicando el valor del \
parámetro parcial")
nombre = property(get_name, set_name, None, "Nombre de la técnica")
|
# Summation of primes
# The Sum of the primes below 10 is 2 + 3+ 5 +7 = 17.
#
# Find the sum of all the primes below two million.
if __name__ == "__main__":
prime = False
prime_numbers = [2]
counter = 3
while (counter < 2000000):
for i in range(2,counter):
if counter % i == 0:
# print(f"Not Prime - counter: {counter}, range: {i}")
prime = False
break
else:
# print(f"Prime - counter: {counter}, range: {i}")
prime = True
if prime == True:
prime_numbers.append(counter)
print(f"Prime: {counter}")
counter += 1
prime = False
print("Calculating the sum of the primes")
prime_sum = sum(prime_numbers)
print(f"Counter: {counter}")
print(f"Sum of the primes: {prime_sum}")
|
def get_frequency(numbers):
return sum(numbers)
def get_dejavu(numbers):
frequencies = {0}
frequency = 0
while True:
for n in numbers:
frequency += n
if frequency in frequencies:
return frequency
frequencies.add(frequency)
if __name__ == "__main__":
data = [int(line.strip()) for line in open("day01.txt", "r")]
print('resulting frequency:', get_frequency(data))
print('dejavu frequency:', get_dejavu(data))
# part 1
assert get_frequency([+1, +1, +1]) == 3
assert get_frequency([+1, +1, -2]) == 0
assert get_frequency([-1, -2, -3]) == -6
# part 2
assert get_dejavu([+1, -1]) == 0
assert get_dejavu([+3, +3, +4, -2, -4]) == 10
assert get_dejavu([-6, +3, +8, +5, -6]) == 5
assert get_dejavu([+7, +7, -2, -7, -4]) == 14
|
def prime(x):
limit=x**.5
limit=int(limit)
for i in range(2,limit+1):
if x%i==0:
return False
return True
print("Not prime")
a=int(input("N="))
result=prime(a)
print(result)
|
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2021/9/29
# @Author : MashiroF
# @File : HT_account.py
# @Software: PyCharm
## 账号管理样本
# {
# 'user':'', # 备注,必要
# 'CK':'', # Cookie,必要(建议全部粘贴)
# 'UA':'' # User-Agent,必要
# },
## 账号管理
accounts = [
{
'user':'',
'CK':'',
'UA':''
},
{
'user':'',
'CK':'',
'UA':''
},
] |
#
# PySNMP MIB module EdgeSwitch-TIMEZONE-PRIVATE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EdgeSwitch-TIMEZONE-PRIVATE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:57:00 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, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint")
fastPath, = mibBuilder.importSymbols("EdgeSwitch-REF-MIB", "fastPath")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Counter32, TimeTicks, MibIdentifier, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, iso, Bits, Unsigned32, Gauge32, ObjectIdentity, Counter64, IpAddress, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "TimeTicks", "MibIdentifier", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "iso", "Bits", "Unsigned32", "Gauge32", "ObjectIdentity", "Counter64", "IpAddress", "NotificationType")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
fastPathTimeZonePrivate = ModuleIdentity((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42))
fastPathTimeZonePrivate.setRevisions(('2011-01-26 00:00', '2007-02-28 05:00',))
if mibBuilder.loadTexts: fastPathTimeZonePrivate.setLastUpdated('201101260000Z')
if mibBuilder.loadTexts: fastPathTimeZonePrivate.setOrganization('Broadcom Inc')
agentSystemTimeGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 1))
agentTimeZoneGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 2))
agentSummerTimeGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3))
agentSummerTimeRecurringGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2))
agentSummerTimeNonRecurringGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3))
agentSystemTime = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 1, 1), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentSystemTime.setStatus('current')
agentSystemDate = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 1, 2), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentSystemDate.setStatus('current')
agentSystemTimeZoneAcronym = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentSystemTimeZoneAcronym.setStatus('current')
agentSystemTimeSource = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("none", 0), ("sntp", 1)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentSystemTimeSource.setStatus('current')
agentSystemSummerTimeState = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 0))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 0)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentSystemSummerTimeState.setStatus('current')
agentTimeZoneHoursOffset = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 2, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-12, 13))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentTimeZoneHoursOffset.setStatus('current')
agentTimeZoneMinutesOffset = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 2, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 59))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentTimeZoneMinutesOffset.setStatus('current')
agentTimeZoneAcronym = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 2, 3), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentTimeZoneAcronym.setStatus('current')
agentSummerTimeMode = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("noSummertime", 0), ("recurring", 1), ("recurringEu", 2), ("recurringUsa", 3), ("nonrecurring", 4))).clone('noSummertime')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentSummerTimeMode.setStatus('current')
agentStRecurringStartingWeek = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("none", 0), ("first", 1), ("second", 2), ("third", 3), ("fourth", 4), ("last", 5))).clone('none')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStRecurringStartingWeek.setStatus('current')
agentStRecurringStartingDay = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("none", 0), ("sun", 1), ("mon", 2), ("tue", 3), ("wed", 4), ("thu", 5), ("fri", 6), ("sat", 7))).clone('none')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStRecurringStartingDay.setStatus('current')
agentStRecurringStartingMonth = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=NamedValues(("none", 0), ("jan", 1), ("feb", 2), ("mar", 3), ("apr", 4), ("may", 5), ("jun", 6), ("jul", 7), ("aug", 8), ("sep", 9), ("oct", 10), ("nov", 11), ("dec", 12))).clone('none')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStRecurringStartingMonth.setStatus('current')
agentStRecurringStartingTime = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 5))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStRecurringStartingTime.setStatus('current')
agentStRecurringEndingWeek = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("none", 0), ("first", 1), ("second", 2), ("third", 3), ("fourth", 4), ("last", 5))).clone('none')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStRecurringEndingWeek.setStatus('current')
agentStRecurringEndingDay = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("none", 0), ("sun", 1), ("mon", 2), ("tue", 3), ("wed", 4), ("thu", 5), ("fri", 6), ("sat", 7))).clone('none')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStRecurringEndingDay.setStatus('current')
agentStRecurringEndingMonth = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=NamedValues(("none", 0), ("jan", 1), ("feb", 2), ("mar", 3), ("apr", 4), ("may", 5), ("jun", 6), ("jul", 7), ("aug", 8), ("sep", 9), ("oct", 10), ("nov", 11), ("dec", 12))).clone('none')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStRecurringEndingMonth.setStatus('current')
agentStRecurringEndingTime = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 5))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStRecurringEndingTime.setStatus('current')
agentStRecurringZoneAcronym = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 4))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStRecurringZoneAcronym.setStatus('current')
agentStRecurringZoneOffset = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 1440), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStRecurringZoneOffset.setStatus('current')
agentStNonRecurringStartingDay = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 31), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStNonRecurringStartingDay.setStatus('current')
agentStNonRecurringStartingMonth = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=NamedValues(("none", 0), ("jan", 1), ("feb", 2), ("mar", 3), ("apr", 4), ("may", 5), ("jun", 6), ("jul", 7), ("aug", 8), ("sep", 9), ("oct", 10), ("nov", 11), ("dec", 12))).clone('none')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStNonRecurringStartingMonth.setStatus('current')
agentStNonRecurringStartingYear = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(2000, 2097), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStNonRecurringStartingYear.setStatus('current')
agentStNonRecurringStartingTime = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 5))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStNonRecurringStartingTime.setStatus('current')
agentStNonRecurringEndingDay = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 31), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStNonRecurringEndingDay.setStatus('current')
agentStNonRecurringEndingMonth = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=NamedValues(("none", 0), ("jan", 1), ("feb", 2), ("mar", 3), ("apr", 4), ("may", 5), ("jun", 6), ("jul", 7), ("aug", 8), ("sep", 9), ("oct", 10), ("nov", 11), ("dec", 12))).clone('none')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStNonRecurringEndingMonth.setStatus('current')
agentStNonRecurringEndingYear = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(2000, 2097), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStNonRecurringEndingYear.setStatus('current')
agentStNonRecurringEndingTime = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 5))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStNonRecurringEndingTime.setStatus('current')
agentStNonRecurringZoneOffset = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 1440), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStNonRecurringZoneOffset.setStatus('current')
agentStNonRecurringZoneAcronym = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 10), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 4))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentStNonRecurringZoneAcronym.setStatus('current')
mibBuilder.exportSymbols("EdgeSwitch-TIMEZONE-PRIVATE-MIB", agentSummerTimeRecurringGroup=agentSummerTimeRecurringGroup, agentTimeZoneGroup=agentTimeZoneGroup, agentStRecurringStartingDay=agentStRecurringStartingDay, agentStRecurringZoneAcronym=agentStRecurringZoneAcronym, agentStRecurringZoneOffset=agentStRecurringZoneOffset, agentStRecurringEndingWeek=agentStRecurringEndingWeek, agentSystemTimeZoneAcronym=agentSystemTimeZoneAcronym, agentStRecurringEndingMonth=agentStRecurringEndingMonth, agentStNonRecurringStartingDay=agentStNonRecurringStartingDay, agentTimeZoneHoursOffset=agentTimeZoneHoursOffset, agentSystemDate=agentSystemDate, agentSystemTimeGroup=agentSystemTimeGroup, agentStNonRecurringEndingYear=agentStNonRecurringEndingYear, agentStNonRecurringStartingYear=agentStNonRecurringStartingYear, agentTimeZoneMinutesOffset=agentTimeZoneMinutesOffset, agentStNonRecurringEndingDay=agentStNonRecurringEndingDay, agentStNonRecurringZoneAcronym=agentStNonRecurringZoneAcronym, agentStRecurringEndingDay=agentStRecurringEndingDay, agentSummerTimeMode=agentSummerTimeMode, agentTimeZoneAcronym=agentTimeZoneAcronym, agentStNonRecurringStartingTime=agentStNonRecurringStartingTime, agentSystemTime=agentSystemTime, agentStRecurringStartingWeek=agentStRecurringStartingWeek, agentSummerTimeNonRecurringGroup=agentSummerTimeNonRecurringGroup, PYSNMP_MODULE_ID=fastPathTimeZonePrivate, agentStNonRecurringStartingMonth=agentStNonRecurringStartingMonth, fastPathTimeZonePrivate=fastPathTimeZonePrivate, agentStNonRecurringEndingTime=agentStNonRecurringEndingTime, agentStNonRecurringEndingMonth=agentStNonRecurringEndingMonth, agentSummerTimeGroup=agentSummerTimeGroup, agentStRecurringStartingMonth=agentStRecurringStartingMonth, agentSystemSummerTimeState=agentSystemSummerTimeState, agentStRecurringStartingTime=agentStRecurringStartingTime, agentSystemTimeSource=agentSystemTimeSource, agentStRecurringEndingTime=agentStRecurringEndingTime, agentStNonRecurringZoneOffset=agentStNonRecurringZoneOffset)
|
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
res = [[0]*n for i in range(n)]
left,right,top,bot = 0,n,0,n
num = 1
while left < right and top < bot:
for i in range(left, right):
res[top][i] = num
num+=1
top+=1
for i in range(top,bot):
res[i][right-1] = num
num+=1
right -=1
for i in range(right-1,left-1,-1):
res[bot-1][i] = num
num+=1
bot-=1
for i in range(bot-1,top-1,-1):
res[i][left] = num
num+=1
left+=1
return res
|
"""
This function appends index.html to all request URIs with a trailing
slash. Intended to work around the S3 Origins for Cloudfront, that use
Origin Access Identity.
"""
def lambda_handler(event, _): # pylint: disable=C0116
request = event["Records"][0]["cf"]["request"]
old_uri = request["uri"]
# If URI has a trailing slash, append index.html
if old_uri.endswith("/"):
new_uri = old_uri + "index.html"
print("Modified URI from: " + old_uri + " to: " + new_uri)
request["uri"] = new_uri
return request
|
__all__ = ['mpstr']
def mpstr(s):
return '$<$fff' + s + '$>'
|
''' PROGRAM TO
FOR A GIVEN LIST OF STUDENTS, MARKS FOR PHY, CHEM, MATHS AND BIOLOGY FORM A DICTIONARY
WHERE KEY IS SRN AND VALUES ARE DICTIONARY CONTAINING PCMB MARKS OF RESPECTIVE STUDENT.'''
#Given lists
srns = ["PECS001","PECS015","PECS065","PECS035","PECS038"]
p_marks = [98,99,85,92,79]
c_marks = [91,90,84,98,99]
m_marks = [78,39,60,50,84]
b_marks = [95,59,78,80,89]
#Creating the dictionary
marks = {}
PCMB_stu = {}
for i in range(len(srns)):
#Creating a dictionary with key as subject and value as marks
marks['Phys'] = p_marks[i]
marks['Chem'] = c_marks[i]
marks['Math'] = m_marks[i]
marks['Bio'] = b_marks[i]
#Creating a dictionary with key as SRN and value as marks dictionary
PCMB_stu[srns[i]] = marks
#Displaying the dictionary
print('\nThe dictionary is:')
print(PCMB_stu,'\n') |
# change_stmt() accepts the number of bills/coins you want to return and
# creates the appropriate string
def change_stmt(twenties, tens, fives, ones, quarters, dimes, nickels, pennies):
if twenties == 0 and tens == 0 and fives == 0 and ones == 0 and quarters == 0 and dimes == 0 and nickels == 0 and pennies == 0:
return "No change returned."
prefix = "Your change will be:"
s = prefix
if twenties > 0:
s += " {} $20".format(twenties)
if tens > 0:
if s != prefix:
s += ","
s += " {} $10".format(tens)
if fives > 0:
if s != prefix:
s += ","
s += " {} $5".format(fives)
if ones > 0:
if s != prefix:
s += ","
s += " {} $1".format(ones)
if quarters > 0:
if s != prefix:
s += ","
s += " {} $.25".format(quarters)
if dimes > 0:
if s != prefix:
s += ","
s += " {} $.10".format(dimes)
if nickels > 0:
if s != prefix:
s += ","
s += " {} $.05".format(nickels)
if pennies > 0:
if s != prefix:
s += ","
s += " {} $.01".format(pennies)
return s
|
# 🚨 Don't change the code below 👇
height = input("enter your height in m: ")
weight = input("enter your weight in kg: ")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
heightNum= float(height)
weightNum=float(weight)
print(str(int(weightNum/heightNum**2))) |
# Write an implementation of the classic game hangman
# fill in the implementation in this program bones
if __name__ == '__main__':
print("Welcome to hangman!!")
#to-do: choos the hidden word: it can be a constant or random choosed from a list or dowloaded from an api
#to-do: choose how many tries are possible
while True:
#to-do: show how many letters there are
#to-do: let the user input a letter and look for a match into the hidden word
#to-do: decide when the user loose or won
break
|
class GoCardlessError(Exception):
pass
class ClientError(GoCardlessError):
"""Thrown when there was an error processing the request"""
def __init__(self, message, errors=None):
self.message = message
if errors is not None:
self.message += self._stringify_errors(errors)
super(ClientError, self).__init__(self.message)
def _stringify_errors(self, errors):
msgs = []
if isinstance(errors, list):
msgs += errors
elif isinstance(errors, dict):
for field in errors:
msgs += ['{} {}'.format(field, msg) for msg in errors[field]]
else:
msgs = [str(errors)]
return ", ".join(msgs)
class SignatureError(GoCardlessError):
pass
|
dia1 = int(input().split()[1])
h1, m1, s1 = map(int, input().split(' : '))
dia2 = int(input().split()[1])
h2, m2, s2 = map(int, input().split(' : '))
segs = (s2+(86400*dia2)+(3600*h2)+(60*m2))-(s1+(86400*dia1)+(3600*h1)+(60*m1))
print(segs//86400, 'dia(s)')
print(segs%86400//3600, 'hora(s)')
print(segs%86400%3600//60, 'minuto(s)')
print(segs%86400%3600%60, 'segundo(s)')
|
######################################################
# Interpreter | CLCInterpreter
#-----------------------------------------------------
# Interpreting AST (Abstract Syntax Tree)
######################################################
class CLCInterpreter:
def __init__(self,ast,storage):
self.r = 0
self.storage = storage
self.visit(ast)
def visit(self,ast):
if ast[0] == "MAT_ADD":
return self.add(ast)
if ast[0] == "DIVISION" :
return self.div(ast)
if ast[0] == "MAT_MULT" :
return self.mult(ast)
if ast[0] == "MIN" :
return self.minus(ast)
if ast[0] == "var_assignment":
return self.assign(ast)
if ast[0] == "PRINT":
return self.program_print(ast)
def program_print(self,node):
val = node[1]
if type(val) is str and val[0] != '\"' :
val = self.var_access(val)
if type(val) is tuple:
val = self.visit(val)
print("PRINT OUT : ",val)
def assign(self,node):
identifier = node[1]
value = node[2]
if type(value) is tuple:
value = self.visit(value)
self.storage.setVar(identifier,value)
return value
def var_access(self,identifier):
return self.storage.getVar(identifier)
def add(self,node):
left = node[1]
right = node[2]
if type(left) is tuple:
left = self.visit(left)
if type(right) is tuple:
right = self.visit(right)
if type(left) is str:
left = self.var_access(left)
if type(right) is str:
right = self.var_access(right)
self.r = left+right
return left+right
def div(self,node):
left = node[1]
right = node[2]
if type(left) is tuple:
left = self.visit(left)
if type(right) is tuple:
right = self.visit(right)
if type(left) is str:
left = self.var_access(left)
if type(right) is str:
right = self.var_access(right)
self.r = left/right
return left/right
def mult(self,node):
left = node[1]
right = node[2]
if type(left) is tuple:
left = self.visit(left)
if type(right) is tuple:
right = self.visit(right)
if type(left) is str:
left = self.var_access(left)
if type(right) is str:
right = self.var_access(right)
self.r = left*right
return left*right
def minus(self,node):
left = node[1]
right = node[2]
if type(left) is tuple:
left = self.visit(left)
if type(right) is tuple:
right = self.visit(right)
if type(left) is str:
left = self.var_access(left)
if type(right) is str:
right = self.var_access(right)
self.r = left-right
return left-right
def __repr__(self):
return str(self.r) |
"""
File type enumaration.
"""
IMAGE = 'image'
VIDEO = 'video'
FILE = 'file'
|
def separa(texto, sep):
''' Recebe uma string e a separa de acordo com o caracter separador recebido '''
lista = texto.split(sep)
return lista
def maior_palavra():
texto = input("Digite palavras separadas por vírgula: ")
list_words = separa(texto, ",")
length_word = 0
bigger_word = ""
for word in list_words:
if len(word) > length_word :
bigger_word = word
length_word = len(word)
print(bigger_word)
maior_palavra() |
def capture(matrix, r, c, size):
possible_moves = [(x, y) for x in range(-1, 2) for y in range(-1, 2)]
for move in possible_moves:
first_step_row = r + move[0]
first_step_col = c + move[1]
next_row = first_step_row
next_col = first_step_col
while 0 <= next_row < size and 0 <= next_col < size:
if matrix[next_row][next_col] == "K":
return True, [r, c]
elif matrix[next_row][next_col] == "Q":
break
next_row += move[0]
next_col += move[1]
return False, [r, c]
board_size = 8
board = [input().split() for row in range(board_size)]
queens = []
for row in range(board_size):
for col in range(board_size):
if board[row][col] == "Q":
captured_king, position = capture(board, row, col, board_size)
if captured_king:
queens.append(position)
if queens:
[print(pos) for pos in queens]
else:
print("The king is safe!")
# def check_to_kill_king_on_row(matrix, row):
# row_to_check = matrix[row]
# if 'K' not in row_to_check:
# return False
# king_position = row_to_check.index('K')
# if col < king_position:
# if 'Q' in row_to_check[col+1:king_position]:
# return False
# else:
# if 'Q' in row_to_check[king_position+1:col]:
# return False
# return True
#
#
# def check_to_kill_king_on_col(matrix, row, col):
# column_to_check = [row[col] for row in matrix]
# if 'K' not in column_to_check:
# return False
# king_position = column_to_check.index('K')
# if row < king_position:
# if 'Q' in column_to_check[row+1:king_position]:
# return False
# else:
# if 'Q' in column_to_check[king_position+1:row]:
# return False
# return True
#
#
# def check_to_kill_king_on_first_diagonal(matrix, row, col):
# current_queen = matrix[row][col]
# first_diagonal_to_check = [current_queen]
#
# current_row = row
# current_col = col
# while current_row in range(1, 8) and current_col in range(1, 8):
# current_row -= 1
# current_col -= 1
# try:
# first_diagonal_to_check.insert(0, matrix[current_row][current_col])
# except IndexError:
# pass
#
# current_row = row
# current_col = col
# while current_row in range(0, 7) and current_row in range(0, 7):
# current_row += 1
# current_col += 1
# try:
# first_diagonal_to_check.append(matrix[current_row][current_col])
# except IndexError:
# pass
#
# if 'K' not in first_diagonal_to_check:
# return False
#
# king_position = first_diagonal_to_check.index('K')
# if col < king_position:
# if 'Q' in first_diagonal_to_check[col+1:king_position]:
# return False
# else:
# if 'Q' in first_diagonal_to_check[king_position+1:col]:
# return False
# return True
#
#
# def check_to_kill_king_on_second_diagonal(matrix, row, col):
# current_queen = matrix[row][col]
# second_diagonal_to_check = [current_queen]
#
# current_row = row
# current_col = col
# while current_row in range(0, 7) and current_col in range(1, 8):
# current_row += 1
# current_col -= 1
# try:
# second_diagonal_to_check.insert(0, matrix[current_row][current_col])
# except IndexError:
# pass
#
# current_row = row
# current_col = col
# while current_row in range(1, 8) and current_col in range(0, 7):
# current_row -= 1
# current_col += 1
# try:
# second_diagonal_to_check.append(matrix[current_row][current_col])
# except IndexError:
# pass
# if 'K' not in second_diagonal_to_check:
# return False
#
# king_position = second_diagonal_to_check.index('K')
# if col < king_position:
# if 'Q' in second_diagonal_to_check[col+1:king_position]:
# return False
# else:
# if 'Q' in second_diagonal_to_check[king_position+1:col]:
# return False
# return True
#
# rows = 8
# cols = rows
#
# matrix = []
#
# [matrix.append(input().split()) for _ in range(rows)]
#
# killer_queens_positions = []
#
# for row in range(rows):
# for col in range(cols):
# try:
# if matrix[row][col] == 'Q':
# if check_to_kill_king_on_row(matrix, row):
# killer_queens_positions.append([row, col])
# if check_to_kill_king_on_col(matrix, row, col):
# killer_queens_positions.append([row, col])
# if check_to_kill_king_on_first_diagonal(matrix, row, col):
# killer_queens_positions.append([row, col])
# if check_to_kill_king_on_second_diagonal(matrix, row, col):
# killer_queens_positions.append([row, col])
# except IndexError:
# pass
#
# if killer_queens_positions:
# print(*killer_queens_positions, sep='\n')
# else:
# print('The king is safe!')
#
|
#
# PySNMP MIB module ELTEX-MES-IpRouter (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-MES-IpRouter
# Produced by pysmi-0.3.4 at Wed May 1 13:01:34 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, ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint")
eltMesOspf, = mibBuilder.importSymbols("ELTEX-MES-IP", "eltMesOspf")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, Bits, iso, Gauge32, Unsigned32, Counter32, ObjectIdentity, TimeTicks, MibIdentifier, IpAddress, Integer32, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "Bits", "iso", "Gauge32", "Unsigned32", "Counter32", "ObjectIdentity", "TimeTicks", "MibIdentifier", "IpAddress", "Integer32", "ModuleIdentity")
RowStatus, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "DisplayString", "TextualConvention")
eltOspfAuthTable = MibTable((1, 3, 6, 1, 4, 1, 35265, 1, 23, 91, 1, 1), )
if mibBuilder.loadTexts: eltOspfAuthTable.setReference('OSPF Version 2, Appendix C.3 Router interface parameters')
if mibBuilder.loadTexts: eltOspfAuthTable.setStatus('current')
if mibBuilder.loadTexts: eltOspfAuthTable.setDescription('The OSPF Interface Table describes the inter- faces from the viewpoint of OSPF.')
eltOspfAuthEntry = MibTableRow((1, 3, 6, 1, 4, 1, 35265, 1, 23, 91, 1, 1, 1), ).setIndexNames((0, "ELTEX-MES-IpRouter", "eltOspfIfIpAddress"), (0, "ELTEX-MES-IpRouter", "eltOspfAuthKeyId"))
if mibBuilder.loadTexts: eltOspfAuthEntry.setStatus('current')
if mibBuilder.loadTexts: eltOspfAuthEntry.setDescription('The OSPF Interface Entry describes one inter- face from the viewpoint of OSPF.')
eltOspfIfIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 1, 23, 91, 1, 1, 1, 1), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltOspfIfIpAddress.setStatus('current')
if mibBuilder.loadTexts: eltOspfIfIpAddress.setDescription('The IP address of this OSPF interface.')
eltOspfAuthKeyId = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 1, 23, 91, 1, 1, 1, 2), Unsigned32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltOspfAuthKeyId.setStatus('current')
if mibBuilder.loadTexts: eltOspfAuthKeyId.setDescription('The md5 authentication key ID. The value must be (1 to 255). This field identifies the algorithm and secret key used to create the message digest appended to the OSPF packet. Key Identifiers are unique per-interface (or equivalently, per-subnet).')
eltOspfAuthKey = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 1, 23, 91, 1, 1, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltOspfAuthKey.setStatus('current')
if mibBuilder.loadTexts: eltOspfAuthKey.setDescription("The MD5 Authentication Key. If the Area's Authorization Type is md5, and the key length is shorter than 16 octets, the agent will left adjust and zero fill to 16 octets. When read, snOspfIfMd5AuthKey always returns an Octet String of length zero.")
eltOspfAuthStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 1, 23, 91, 1, 1, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: eltOspfAuthStatus.setStatus('current')
if mibBuilder.loadTexts: eltOspfAuthStatus.setDescription('This variable displays the status of the en- try.')
mibBuilder.exportSymbols("ELTEX-MES-IpRouter", eltOspfIfIpAddress=eltOspfIfIpAddress, eltOspfAuthStatus=eltOspfAuthStatus, eltOspfAuthKeyId=eltOspfAuthKeyId, eltOspfAuthTable=eltOspfAuthTable, eltOspfAuthKey=eltOspfAuthKey, eltOspfAuthEntry=eltOspfAuthEntry)
|
#!/usr/bin/env python3
# Closure
def outer_function(msg):
def inner_function():
print(msg)
return inner_function
# Decorator Function
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print('Wrapper executed this before {}'.format(original_function.__name__)) # noqa
return original_function(*args, **kwargs)
return wrapper_function
# Decorator Class
class decorator_class(object):
def __init__(self, original_function):
self.original_function = original_function
def __call__(self, *args, **kwargs):
print('call method executed this before {}'.format(self.original_function.__name__)) # noqa
return self.original_function(*args, **kwargs)
# display = decorator_function(display)
@decorator_function
def display():
print('display function ran')
# display_info = decorator_function(display_info)
@decorator_function
def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))
@decorator_class
def test():
print('test function ran')
display()
display_info('John', 25)
test()
|
# Corrigido
# Usando a formatação no bloco de saída
nome = 'Guanabara'
print()
print('Muito prazer em te conhecer, {}{}{}!'.format(
'\033[4;34m', nome, '\033[m'))
print()
|
"""
Investigating Ulam sequences
"""
|
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 27 11:31:56 2019
@author: Kieran
"""
def shortest_distance_of_cluster(cluster):
"""
given an input NumpyArray cluster, it computes the shortest distance between any pair of atoms.
It returns the shortest_distance and the closest atoms.
shortest_distance is a float.
closest atoms is a formatted string : f"atom n and atom q" where n and q are integers.
"""
distances = {} # Will have {atom n and atom q: distance value}
for i in range(len(cluster)-1): # Loop through first till 2nd from last vectors in cluster
for j in range(i+1, len(cluster)): # Loop through from i till last vectors in cluster
distances[f"atom {i+1} and atom {j+1}"] = dist3D(cluster[i],cluster[j])
# Assign the shortest value in distances dictionary to var shortest_distance
shortest_distance = min(distances.values())
# Loops through the keys and values (as atoms and distance) and if distance is the shortest distance
# it assigns the atoms (key) to closest_atoms. This way we know which atoms are the closest.
for atoms, distance in distances.items():
if distance == shortest_distance:
closest_atoms = atoms
return shortest_distance, closest_atoms
def total_lennard_jones_potential(cluster):
"""
Takes a NumpyArray cluster as input for a cluster of atoms, calculates the total lennard_jones_potential of the cluster
"""
distances = {} # Will have {atom n and atom q: distance value}
for i in range(len(cluster)-1): # Loop through first till 2nd from last vectors in cluster
for j in range(i+1, len(cluster)): # Loop through from i till last vectors in cluster
distances[f"atom {i+1} and atom {j+1}"] = dist3D(cluster[i],cluster[j])
# Creates a List which contains all the lennard jones potentials for each distance of pair of atoms in the cluster
all_lennard_jones_potentials = [lennard_jones_potential(dist) for dist in distances.values()]
# Computes the total of all the lennard jones potentials in the cluster of atoms
total_potential = sum(all_lennard_jones_potentials)
return total_potential
def lennard_jones_potential(x):
"""
calculates the lennard-jones-potential of a given value x
"""
return 4 * ((x ** -12) - (x ** -6))
def dist3D(start, final):
"""
calculates the distance between two given vectors.
Vectors must be given as two 3-dimensional lists, with the aim of representing
2 3d position vectors.
"""
(x1, y1, z1) = (start[0], start[1], start[2])
(x2, y2, z2) = (final[0], final[1], final[2])
(xdiff,ydiff,zdiff) = (x2-x1,y2-y1,z2-z1)
# Calculate the hypotenuse between the x difference, y difference and the z difference
# This should give the distance between the two points
distance = (xdiff **2 + ydiff ** 2 + zdiff ** 2) ** (1/2)
return distance
def centre_of_mass(mass, numpy_array):
"""
takes the mass of the atoms as first argument, then takes a number of vectors as
arguments and computes the centre of mass of all the atoms.
"""
# assigns all the x positions, y positions and z position values from all the vectors to three individual lists.
x_values = []
y_values = []
z_values = []
for vector in numpy_array:
x_values.append(vector[0])
y_values.append(vector[1])
z_values.append(vector[2])
# Calculate the centre of mass for the x, y and z direction and return these as a vector.
centre_x = mass * sum(x_values)/(mass * len(numpy_array))
centre_y = mass * sum(y_values)/(mass * len(numpy_array))
centre_z = mass * sum(z_values)/(mass * len(numpy_array))
return [centre_x, centre_y, centre_z]
|
# 词汇表
dist = {'python': 'lift is bab,I use python.', 'php': 'php is the best language in the world.'}
for k, v in dist.items():
print(k + ':' + v)
|
{
"targets": [
{
"target_name": "jspmdk",
"sources": [
"jspmdk.cc",
"persistentobjectpool.cc",
"persistentobject.cc",
"persistentarraybuffer.cc",
"internal/memorymanager.cc",
"internal/pmdict.cc",
"internal/pmarray.cc",
"internal/pmobjectpool.cc",
"internal/pmobject.cc",
"internal/pmarraybuffer.cc",
],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")"
],
"dependencies": [
"<!(node -p \"require('node-addon-api').gyp\")"
],
"libraries": [
"-lpmem",
"-lpmemobj",
"-lpthread",
"-lgcov"
],
"cflags_cc": [
"-Wno-return-type",
"-fexceptions",
"-O3",
"-fdata-sections",
"-ffunction-sections",
"-fno-strict-overflow",
"-fno-delete-null-pointer-checks",
"-fwrapv"
],
'link_settings': {
'ldflags': [
'-Wl,--gc-sections',
]
},
"defines": [
]
}
]
}
|
"""
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
Example:
For num = 5 you should return [0,1,1,2,1,2].
Follow up:
It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
Credits:
Special thanks to @ syedee for adding this problem and creating all test cases.
"""
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
"""
Method 1:
Your runtime beats 53.63 % of python submissions.
"""
# return [bin(ele).count('1') for ele in range(num+1)]
"""
Method 2: Dynamic Programming
[0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5]
DP Pattern: dp[index] = dp[index - offset] + 1
Your runtime beats 99.29 % of python submissions.
"""
dp = [0] * (num + 1)
offset = 1
for i in range(1, num + 1):
if offset * 2 == i:
offset = offset * 2
dp[i] = dp[i - offset] + 1
return dp |
################################################################################
# Author: Fanyang Cheng
# Date: 2/26/2021
# This program asks user for a number and send back all the prime numbers from 2
# to that number.
################################################################################
def is_prime(n): #define function is_prime.
#use a loop to test all of the reserves devided by the number less than
#the input.
judge = 1 #give a judgement parameter.
if n == 1: #give 1 a specific case as range would not be applicable to it.
judge = 0
else:
for i in range(1,round((n-1)**0.5+1)):
if not(n%(i+1)) and n != i+1: #if in this turn it has a remain of 0 and it is not the number itself.
judge = 0 #then change the judgement to "not prime".
return bool(judge) #well, we can directly return judge but it is a boolean function so return the boolean value.
# 1 for Ture, it is a prime number. 0 for false, it is not a prime number.
return True # If only 1 and n meet the need, then it is a prime number.
def main(): #def the main function
pl = [] #create a list
num = int(input("Enter a positive integer: ")) #ask for input.
for i in range(num): #give the judge for each numbers
pri = is_prime(i+1) #have the judgement
if pri == True:
pl.append(i+1) #if it is prime, append to the pl list.
pl = ", ".join(str(i) for i in pl) #change the list to string so that won't print brackets.
print("The primes up to",num,"are:",pl) #output
if __name__ == "__main__":
main() #run
|
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
if not nums or k < 1:
return False
used = {}
flag = False
for i, v in enumerate(nums):
if v in used and not flag:
flag = (i - used[v] <= k)
used[v] = i
return flag |
# Copyright 2020 The Google Earth Engine Community Authors
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Google Earth Engine Developer's Guide examples for 'Images - Relational, conditional and Boolean operations'."""
# [START earthengine__images09__where_operator]
# Load a cloudy Sentinel-2 image.
image = ee.Image(
'COPERNICUS/S2_SR/20210114T185729_20210114T185730_T10SEG')
# Load another image to replace the cloudy pixels.
replacement = ee.Image(
'COPERNICUS/S2_SR/20210109T185751_20210109T185931_T10SEG')
# Set cloudy pixels (greater than 5% probability) to the other image.
replaced = image.where(image.select('MSK_CLDPRB').gt(5), replacement)
# Define a map centered on San Francisco Bay.
map_replaced = folium.Map(location=[37.7349, -122.3769], zoom_start=11)
# Display the images on a map.
vis_params = {'bands': ['B4', 'B3', 'B2'], 'min': 0, 'max': 2000}
map_replaced.add_ee_layer(image, vis_params, 'original image')
map_replaced.add_ee_layer(replaced, vis_params, 'clouds replaced')
display(map_replaced.add_child(folium.LayerControl()))
# [END earthengine__images09__where_operator]
|
#MIT License
#Copyright (c) 2017 Tim Wentzlau
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
""" Named lists are lists that are located by name """
class NamedLists(object):
def __init__(self):
self.data = {}
def add(self, list_name, obj):
if list_name in self.data:
self.data[list_name] += [obj]
else:
self.data[list_name] = [obj]
def remove(self, list_name, obj):
if list_name in self.data:
self.data[list_name].remove(obj)
def get_list_names(self):
result = []
for key in self.data:
result += [key]
return result
def get_list_data(self, list_name):
if list_name in self.data:
return self.data[list_name]
return None
def get_list_data_with_partial_key(self, list_name):
items = any(key.startswith(list_name) for key in self.data)
result = {}
for item in items:
result[item] = self.data[item]
return result
|
"""
给定一个字符串 S 和一个字符串 T,计算在 S 的子序列中 T 出现的个数。
一个字符串的一个子序列是指,通过删除一些(也可以不删除)字符且不干扰剩余字符相对位置所组成的新字符串。(例如,"ACE" 是 "ABCDE" 的一个子序列,而 "AEC" 不是)
示例 1:
输入: S = "rabbbit", T = "rabbit"
输出: 3
解释:
如下图所示, 有 3 种可以从 S 中得到 "rabbit" 的方案。
(上箭头符号 ^ 表示选取的字母)
rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^
示例 2:
输入: S = "babgbag", T = "bag"
输出: 5
解释:
如下图所示, 有 5 种可以从 S 中得到 "bag" 的方案。
(上箭头符号 ^ 表示选取的字母)
babgbag
^^ ^
babgbag
^^ ^
babgbag
^ ^^
babgbag
^ ^^
babgbag
^^^
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/distinct-subsequences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def numDistinct(self, s: str, t: str) -> int:
pass |
class min_PQ(object):
def __init__(self):
self.heap = []
def __repr__(self):
heap_string = ''
for i in range(len(self.heap)):
heap_string += str(self.heap[i]) + ' '
return heap_string
# check each non-root node is >= its parent
def check_invariant(self):
#emtpy and 1-size heaps cannot violate heap property
if len(self.heap)>1:
for i in range(1, len(self.heap)):
if self.heap[(i-1) // 2] > self.heap[i]:
raise RuntimeError('Heap invariant violated')
# utility function to swap two indices in the heap (not tested)
def swap(self, i, j):
old_i = self.heap[i] # store old value at index i
self.heap[i] = self.heap[j]
self.heap[j] = old_i
# inserts given priority into end of heap then "bubbles up" until
# invariant is preserved
def insert(self, priority):
self.heap.append(priority)
i_new = len(self.heap)-1 # get location of just-inserted priority
i_parent = (i_new-1) // 2 # get location of its parent
# "bubble up" step
while (i_new > 0) and (self.heap[i_parent] > self.heap[i_new]):
self.swap(i_new, i_parent)
i_new = i_parent # after swap: newly inserted priority gets loc of parent
i_parent = (i_parent-1) // 2
self.check_invariant() #check invariant after bubbling up
def is_empty(self):
return len(self.heap) == 0
# summary: returns item with minimum priority and removes it from PQ
# requires: is_empty to be checked before calling
# effects: IndexError if called on an empty PQ. Otherwise, removes minimum
# item and returns it, replacing it with last item in PQ. "bubbles down"
# if needed.
def remove_min(self):
min_priority = self.heap[0]
self.swap(0, len(self.heap)-1) #bring last element to front
self.heap.pop() #remove last element, which was the min
#bubble down
i_current = 0
next_swap = self.next_down(i_current)
while (next_swap != None): #while we should swap
self.swap(i_current, next_swap) #swap the elements
i_current = next_swap #i_current is now in the place of one of its children
next_swap = self.next_down(i_current)
return min_priority
# summary: given an index representing a priority we are bubbling down,
# returns index of node it should be swapped with.
# requires: index of item of interest
# effects: if node has no children (leaf) or the minimum of its children
# is strictly greater than it, then return None. Otherwise, return
# the index of the minimum-priority child
def next_down(self, i):
max_ind = len(self.heap)-1 #get max index of current heap
left = (2*i) + 1 #calculate where left and right child would be
right = left + 1
if left > max_ind: #if this is true, node is a leaf
return None
elif right > max_ind: #node has left child but not right
if self.heap[left] < self.heap[i]:
return left
else:
return None
else: #both children exist
next = None #default if we cannot find a suitable node to swap with
if self.heap[left] < self.heap[i]: #left child might need to be swapped
next = left
if self.heap[right] < self.heap[left]: #overwrite if right is actually smaller
next = right
return next
def main():
pq = min_PQ()
print(pq)
if __name__ == '__main__':
main()
|
dados = dict()
totg = list()
cont = gol = 0
dados['nome'] = (str(input('Informe o nome do jogador: '))).strip().title()
part = (int(input('Informe a quantidade de partidas do jogador: ')))
for c in range(1, part + 1):
gols = (int(input(f'Quantos gols foram marcados no {c}ª partidada? ')))
totg.append(gols)
dados['gols'] = totg.copy()
print('=' * 50)
print(f'O jogador {dados["nome"]} jogou {part} partidas no total: ')
for t in range(1, part + 1):
print(' =>', f'Na {t}ª partida {dados["nome"]} fez {dados["gols"][cont]} gols')
cont = cont + 1
for c in dados['gols']:
gol = gol + c
print(f'Foi um total de {gol} gols !')
|
#! /usr/bin/env python3
""" example module: extra.good.omega """
def FunO():
return "Omega"
if __name__ == "__main__":
print("I prefer to be a module") |
"""练习 1:遍历商品控制器"""
class Graphiciterator:
def __init__(self, date):
self.date = date
self.index = -1
def __next__(self):
self.index += 1
if self.index > len(self.date) - 1:
raise StopIteration
return self.date[self.index]
class GraphicController:
def __init__(self):
self.__list_graphic = []
def add_graphic(self, graphic):
self.__list_graphic.append(graphic)
def __iter__(self):
return Graphiciterator(self.__list_graphic)
controller = GraphicController()
controller.add_graphic("圆形")
controller.add_graphic("矩形")
controller.add_graphic("三角形")
iterator = controller.__iter__()
while True:
try:
item = iterator.__next__()
print(item)
except StopIteration:
break
|
c=2;r=''
while True:
s=__import__('sys').stdin.readline().strip()
if s=='Was it a cat I saw?': break
l=len(s)
for i in range(0, l, c):
r+=s[i]
c+=1;r+='\n'
print(r, end='')
|
# Go to http://apps.twitter.com and create an app.
# The consumer key and secret will be generated for you after
CONSUMER_KEY="FILL ME IN"
CONSUMER_SECRET="FILL ME IN"
# After the step above, you will be redirected to your app's page.
# Create an access token under the the "Your access token" section
ACCESS_TOKEN="FILL ME IN"
ACCESS_TOKEN_SECRET="FILL ME IN"
# Name of the twitter account
TWITTER_SCREEN_NAME = "FILL ME IN" # Ex: "MikaSoftware"
# This array controls what hashtags we are to re-tweet. Change these to whatever
# hashtags you would like to retweet with this Python script.
HASHTAGS = [
'#LndOnt',
'#lndont',
'#LndOntTech',
'#lndonttech',
'#LndOntDowntown',
'#lndontdowntown'
'#LdnOnt',
'#ldnont',
'#LdnOntTech',
'#ldnonttech',
'#LdnOntDowntown',
'#ldnontdowntown'
] |
class ColorCode:
def getOhms(self, code):
d = {
'black': ('0', 1),
'brown': ('1', 10),
'red': ('2', 100),
'orange': ('3', 1000),
'yellow': ('4', 10000),
'green': ('5', 100000),
'blue': ('6', 1000000),
'violet': ('7', 10000,000),
'grey': ('8', 100000000),
'white': ('9', 1000000000)
}
return int(d[code[0]][0] + d[code[1]][0]) * d[code[2]][1]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.