content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# 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
| def kwarget(key, default, **kwargs):
if key in kwargs:
return kwargs[key]
else:
return default |
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) | def salary_net_uah(salary_usd, currency, taxes, esv):
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):
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() | 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())
| 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 = list_with_users()
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")
| split_string = 'Hello\nWorld'
print(splitString)
another_split_string = 'Multiline\nin\nSingle\nvariable\nand i don\'t need to escape single\nor double " quote :)'
print(anotherSplitString)
print('c:\\User\\text\\notes.txt')
print('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 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_boss_percentage(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))
| 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()
| 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)
| 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 to_hex_string(n, bits):
assert bits > 0
p = (bits + (4 - 1)) // 4
assert 4 * p >= n.bit_length()
return '0x{:0{}X}'.format(n, p)
def format_hex_chunks(n, bits_per_chunk=64):
chunks = split(n, bits_per_chunk)
s = ', '.join(map(lambda x: to_hex_string(x, bits_per_chunk), reversed(chunks)))
if len(chunks) > 1:
s = '{' + s + '}'
return s
def floor_log2_pow10(e):
assert e >= -1233
assert e <= 1232
return e * 1741647 >> 19
def round_up(num, den):
assert num >= 0
assert den > 0
(p, r) = divmod(num, den)
if 2 * r >= den:
p += 1
return p
def compute_grisu_power(k, bits):
assert bits > 0
e = floor_log2_pow10(k) + 1 - bits
if k >= 0:
if e > 0:
f = round_up(10 ** k, 2 ** e)
else:
f = 10 ** k * 2 ** (-e)
else:
f = round_up(2 ** (-e), 10 ** (-k))
assert f >= 2 ** (bits - 1)
assert f < 2 ** bits
return (f, e)
def print_grisu_powers(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) = compute_grisu_power(k, bits)
print(format_hex_chunks(f, bits_per_chunk=64) + ', // e = {:5d}, k = {:4d}'.format(e, k))
def div_up(num, den):
return (num + (den - 1)) // den
def ceil_log10_pow2(e):
assert e >= -2620
assert e <= 2620
return e * 315653 + (2 ** 20 - 1) >> 20
def floor_log10_pow2(e):
assert e >= -2620
assert e <= 2620
return e * 315653 >> 20
def compute_binary_exponent_range(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 print_grisu_powers_for_exponent_range(alpha, gamma, q=64, p=53, exponent_bits=11):
assert alpha + 3 <= gamma
(e_min, e_max) = compute_binary_exponent_range(q, p, exponent_bits)
k_del = max(1, floor_log10_pow2(gamma - alpha))
assert k_del >= 1
k_min = ceil_log10_pow2(alpha - e_max - 1)
k_max = ceil_log10_pow2(alpha - e_min - 1)
num_cached = div_up(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('')
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('// 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) = compute_grisu_power(k, q)
print(' ' + format_hex_chunks(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('}')
print_grisu_powers_for_exponent_range(-50, -36, q=64, p=53, exponent_bits=11) |
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)
| 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)
| """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]))
| 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) | 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
| population_in2012 = 1000
population_in2013 = populationIn2012 * 1.1
population_in2014 = populationIn2013 * 1.1
population_in2015 = 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)
| 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)
| """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
"""
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 "
| """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))
| 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):
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):
"""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]
for card in cards:
counts[card[0] - 2] += 1
if check_flush(cards):
if check_straight(cards):
if cards[4][0] == 14:
return [10]
else:
return [9, cards[4]]
elif not (4 in counts or (3 in counts and 2 in counts)):
return [6] + cards[::-1]
if 4 in counts:
return [8] + [counts.index(4) + 2, counts.index(1) + 2]
if 3 in counts and 2 in counts:
return [7] + [counts.index(3) + 2, counts.index(2) + 2]
if check_straight(cards):
return [5, cards[4]]
if 3 in counts:
three = counts.index(3) + 2
return [4] + [three] + [x[0] for x in remove_all(cards, [three])][::-1]
if counts.count(2) == 2:
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:
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]
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]
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) | """
Created on Thu Dec 31 12:37:52 2020
@author: SethHarden
Heap Sorting a List
"""
def left(i):
return 2 * i + 1
def right(i):
return 2 * i + 2
def swap(A, i, j):
temp = A[i]
A[i] = A[j]
A[j] = temp
def heapify(A, i, size):
left = left(i)
right = right(i)
largest = i
if left < size and A[left] > A[i]:
largest = left
if right < size and A[right] > A[largest]:
largest = right
if largest != i:
swap(A, i, largest)
heapify(A, largest, size)
def pop(A, size):
if size <= 0:
return -1
top = A[0]
A[0] = A[size - 1]
heapify(A, 0, size - 1)
return top
def heap_sort(A):
n = len(A)
i = (n - 2) // 2
while i >= 0:
heapify(A, i, n)
i = i - 1
while n:
A[n - 1] = pop(A, n)
n = n - 1
if __name__ == '__main__':
a = [6, 4, 7, 1, 9, -2]
heap_sort(A)
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)
| 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 merge_trees(self, t1, t2):
if t1 is None:
return t2
elif t2 is None:
return t1
result = tree_node(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 = tree_node(1)
t1_1 = tree_node(3)
t1_2 = tree_node(2)
t1_3 = tree_node(5)
t1_1.left = t1_3
t1_0.left = t1_1
t1_0.right = t1_2
t2_0 = tree_node(2)
t2_1 = tree_node(1)
t2_2 = tree_node(3)
t2_3 = tree_node(4)
t2_4 = tree_node(7)
t2_2.right = t2_4
t2_1.right = t2_3
t2_0.left = t2_1
t2_0.right = t2_2
t3_0 = tree_node(3)
t3_1 = tree_node(4)
t3_2 = tree_node(5)
t3_3 = tree_node(5)
t3_4 = tree_node(4)
t3_5 = tree_node(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"
] | 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', 'livereload.middleware.LiveReloadScript', 'debug_toolbar.middleware.DebugToolbarMiddleware'] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@author: rainsty
@file: decorator.py
@time: 2019-12-30 13:34:29
@description: decorator
"""
| """
@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
| 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)) | def delete_duplicate(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(delete_duplicate(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]))
| 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])) |
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
| 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', 'AK_RURAL_1': 'AK_RURAL_1', 'AK_RURAL_2': 'AK_RURAL_2', '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]
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) | 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
left_ret = True
right_ret = True
if node.left is not None:
left_ret = self.filter_recursive(node.left, k)
if node.right is not None:
right_ret = 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):
solu = solution()
solu.filter_recursive(tree, k)
return tree
if __name__ == '__main__':
n5 = node(2)
n4 = node(1)
n3 = node(1, n4)
n2 = node(1, n5)
n1 = node(1, n2, n3)
print(str(filter(n1, 1))) |
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
| sector_size = 40000
def pixels2sector(x, y):
return str(int(x / SECTOR_SIZE + 0.5)) + ':' + str(int(-y / SECTOR_SIZE + 0.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 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
| def get_data():
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
| """
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_evidence_source(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 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) | def print_owing(self, amount):
self.printBanner()
print('name: ', self._name)
print('amount: ', amount)
def print_late_notice(self, amount):
self.printBanner()
self.printLateNoticeHeader()
print('name: ', self._name)
print('amount: ', amount)
def print_owing(self, amount):
self.printBanner()
self.printDetails(amount)
def print_late_notice(self, amount):
self.printBanner()
self.printLateNoticeHeader()
self.printDetails(amount)
def print_details(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")
| 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"
| 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))
| 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 | 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.
"""
name = 'rob'
gpu_count = 1
images_per_gpu = 2
num_classes = 1 + 4
train_rois_per_image = 32
steps_per_epoch = int(5561 / (GPU_COUNT * IMAGES_PER_GPU))
detection_max_instances = 5
detection_min_confidence = 0.6
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" | database = './vocabulary.db'
word_type_cutoffed = 1
word_type_cutoff = 0
word_right_yes = 1
word_right_no = 0
wrong_words_review_frequency = 3
recite_print_format = '[{}]> \x1b[1m\x1b[31m{}\x1b[0m\x1b[0m'
print_vocabulary_desc = '[Answer]\x1b[1m\x1b[32m{}\x1b[0m\x1b[0m'
details_print_format_in_database = '[Detail]ID:\x1b[1m\x1b[32m{}\x1b[0m\x1b[0m\t desc=\x1b[1m\x1b[32m{}\x1b[0m\x1b[0m\tcutoff=\x1b[1m\x1b[32m{}\x1b[0m\x1b[0m'
recite_help_information = "\nCOMMANDS OF RECITING VOCABULARIES\n`\x1b[1m\x1b[33myes\x1b[0m\x1b[0m` : i have know this vocabulary, just pass it.\n`\x1b[1m\x1b[33mno\x1b[0m\x1b[0m` : i don't know this vocabulary, tell me the meaning.\n`\x1b[1m\x1b[33msay\x1b[0m\x1b[0m` : play the audio by using system setting.\n`\x1b[1m\x1b[33mcutoff\x1b[0m\x1b[0m` : never show this vocabulary again.\n`\x1b[1m\x1b[33mrepeat\x1b[0m\x1b[0m` : repeat current word and stay in this round.\n`\x1b[1m\x1b[33mshow \x1b[0m\x1b[0m` : show details in database.\n`\x1b[1m\x1b[33mfind= \x1b[0m\x1b[0m` : find=xxx, get the meaning in database with key=xxx\n`\x1b[1m\x1b[33mstatic=N\x1b[0m\x1b[0m`: static=N, show the statics of N days ago. N=0 means current day. N <= 0\n`\x1b[1m\x1b[33mwrong=N \x1b[0m\x1b[0m`: wrong=N, show the wrong words of N days ago. N=0 means current day. N <= Zero\n`\x1b[1m\x1b[33mquit\x1b[0m\x1b[0m` : quit this recite round.\n`\x1b[1m\x1b[33mexport=N\x1b[0m\x1b[0m`: export=N, for exporting wrong words of N days ago.\n`\x1b[1m\x1b[36mhelp\x1b[0m\x1b[0m` : tip me with keywords.\n\nexample:\n>say say repeat\n>say show\n>find=hello\n"
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
| """
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 zero_division_error("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 findComplement(self, num: int) -> int:
x = bin(num)[2:]
z = ""
for i in x:
z+=str(int(i) ^ 1)
return int(z, 2) | def find_complement(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 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 add_all(self, inc: int) -> None:
if len(self.data) == 0:
return
self.add[-1] += inc
def mult_all(self, m: int) -> None:
if len(self.data) == 0:
return
self.mult[-1] *= m
self.add[-1] *= m
def get_index(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 |
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
| class Logger(object):
""" Utility class responsible for logging all interactions during the simulation. """
def __init__(self, file_name):
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.
"""
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}
"
or the other edge cases:
"{person.ID} didn't infect {random_person.ID} because {'vaccinated' or 'already sick'}
"
"""
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
" or "{person.ID} survived infection.
"
"""
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}
"
"""
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)
| """
Title - Trie Data Structure
Data structure to insert and search word efficiently
time complexity - O(n) where n=len(word)
"""
class Ll:
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 starts_with(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 |
#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
| class Logiccell:
def __init__(self, name, width):
self.width = width
self.name = name
inv1 = logic_cell('sky130_fd_sc_hvl__inv_1', 1.44)
inv4 = logic_cell('sky130_fd_sc_hvl__inv_4', 3.84)
decap_8 = logic_cell('sky130_fd_sc_hvl__decap_8', 3.84)
mux2 = logic_cell('sky130_fd_sc_hvl__mux2_1', 5.28)
or2 = logic_cell('sky130_fd_sc_hvl__or2_1', 3.36)
nor2 = logic_cell('sky130_fd_sc_hvl__nor2_1', 2.4)
nand2 = logic_cell('sky130_fd_sc_hvl__nand2_1', 2.4)
and2 = logic_cell('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]
row1 = [decap_8, and2, or2, inv1, and2, nor2, nor2]
row2 = [decap_8, decap_8, decap_8, nand2, mux2]
row3 = [decap_8, decap_8, decap_8, and2, mux2]
row4 = [decap_8, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv4]
row5 = [decap_8, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv4]
row6 = [decap_8, mux2, or2, inv1, inv4, inv4]
row7 = [decap_8, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv4]
row8 = [decap_8, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv1, inv4]
row9 = [decap_8, mux2, and2, inv1, inv4, inv4]
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:
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)
elif 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
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:
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)
elif 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()
| 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)
| 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 | class Solution(object):
def shortest_palindrome(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 |
# 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}")
| if __name__ == '__main__':
prime = False
prime_numbers = [2]
counter = 3
while counter < 2000000:
for i in range(2, counter):
if counter % i == 0:
prime = False
break
else:
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 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))
assert get_frequency([+1, +1, +1]) == 3
assert get_frequency([+1, +1, -2]) == 0
assert get_frequency([-1, -2, -3]) == -6
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)
| def prime(x):
limit = x ** 0.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) |
#
# 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)
| (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_range_constraint, single_value_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ConstraintsIntersection', 'ValueRangeConstraint', 'SingleValueConstraint', 'ValueSizeConstraint')
(fast_path,) = mibBuilder.importSymbols('EdgeSwitch-REF-MIB', 'fastPath')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(counter32, time_ticks, mib_identifier, integer32, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity, iso, bits, unsigned32, gauge32, object_identity, counter64, ip_address, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter32', 'TimeTicks', 'MibIdentifier', 'Integer32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity', 'iso', 'Bits', 'Unsigned32', 'Gauge32', 'ObjectIdentity', 'Counter64', 'IpAddress', 'NotificationType')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
fast_path_time_zone_private = module_identity((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')
agent_system_time_group = mib_identifier((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 1))
agent_time_zone_group = mib_identifier((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 2))
agent_summer_time_group = mib_identifier((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3))
agent_summer_time_recurring_group = mib_identifier((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2))
agent_summer_time_non_recurring_group = mib_identifier((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3))
agent_system_time = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 1, 1), display_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentSystemTime.setStatus('current')
agent_system_date = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 1, 2), display_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentSystemDate.setStatus('current')
agent_system_time_zone_acronym = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 1, 3), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentSystemTimeZoneAcronym.setStatus('current')
agent_system_time_source = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('none', 0), ('sntp', 1)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentSystemTimeSource.setStatus('current')
agent_system_summer_time_state = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 0))).clone(namedValues=named_values(('enabled', 1), ('disabled', 0)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentSystemSummerTimeState.setStatus('current')
agent_time_zone_hours_offset = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 2, 1), integer32().subtype(subtypeSpec=value_range_constraint(-12, 13))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentTimeZoneHoursOffset.setStatus('current')
agent_time_zone_minutes_offset = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 2, 2), integer32().subtype(subtypeSpec=value_range_constraint(0, 59))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentTimeZoneMinutesOffset.setStatus('current')
agent_time_zone_acronym = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 2, 3), display_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentTimeZoneAcronym.setStatus('current')
agent_summer_time_mode = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4))).clone(namedValues=named_values(('noSummertime', 0), ('recurring', 1), ('recurringEu', 2), ('recurringUsa', 3), ('nonrecurring', 4))).clone('noSummertime')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentSummerTimeMode.setStatus('current')
agent_st_recurring_starting_week = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4, 5))).clone(namedValues=named_values(('none', 0), ('first', 1), ('second', 2), ('third', 3), ('fourth', 4), ('last', 5))).clone('none')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentStRecurringStartingWeek.setStatus('current')
agent_st_recurring_starting_day = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=named_values(('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')
agent_st_recurring_starting_month = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=named_values(('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')
agent_st_recurring_starting_time = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 4), display_string().subtype(subtypeSpec=value_size_constraint(0, 5))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentStRecurringStartingTime.setStatus('current')
agent_st_recurring_ending_week = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4, 5))).clone(namedValues=named_values(('none', 0), ('first', 1), ('second', 2), ('third', 3), ('fourth', 4), ('last', 5))).clone('none')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentStRecurringEndingWeek.setStatus('current')
agent_st_recurring_ending_day = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=named_values(('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')
agent_st_recurring_ending_month = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=named_values(('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')
agent_st_recurring_ending_time = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 8), display_string().subtype(subtypeSpec=value_size_constraint(0, 5))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentStRecurringEndingTime.setStatus('current')
agent_st_recurring_zone_acronym = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 9), display_string().subtype(subtypeSpec=value_size_constraint(0, 4))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentStRecurringZoneAcronym.setStatus('current')
agent_st_recurring_zone_offset = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 2, 10), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(0, 0), value_range_constraint(1, 1440)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentStRecurringZoneOffset.setStatus('current')
agent_st_non_recurring_starting_day = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 1), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(0, 0), value_range_constraint(1, 31)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentStNonRecurringStartingDay.setStatus('current')
agent_st_non_recurring_starting_month = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=named_values(('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')
agent_st_non_recurring_starting_year = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 3), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(0, 0), value_range_constraint(2000, 2097)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentStNonRecurringStartingYear.setStatus('current')
agent_st_non_recurring_starting_time = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 4), display_string().subtype(subtypeSpec=value_size_constraint(0, 5))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentStNonRecurringStartingTime.setStatus('current')
agent_st_non_recurring_ending_day = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 5), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(0, 0), value_range_constraint(1, 31)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentStNonRecurringEndingDay.setStatus('current')
agent_st_non_recurring_ending_month = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=named_values(('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')
agent_st_non_recurring_ending_year = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 7), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(0, 0), value_range_constraint(2000, 2097)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentStNonRecurringEndingYear.setStatus('current')
agent_st_non_recurring_ending_time = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 8), display_string().subtype(subtypeSpec=value_size_constraint(0, 5))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentStNonRecurringEndingTime.setStatus('current')
agent_st_non_recurring_zone_offset = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 9), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(0, 0), value_range_constraint(1, 1440)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentStNonRecurringZoneOffset.setStatus('current')
agent_st_non_recurring_zone_acronym = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 42, 3, 3, 10), display_string().subtype(subtypeSpec=value_size_constraint(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
| class Solution:
def generate_matrix(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
| """
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, _):
request = event['Records'][0]['cf']['request']
old_uri = request['uri']
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 + '$>'
| __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') | """ 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."""
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]
marks = {}
pcmb_stu = {}
for i in range(len(srns)):
marks['Phys'] = p_marks[i]
marks['Chem'] = c_marks[i]
marks['Math'] = m_marks[i]
marks['Bio'] = b_marks[i]
PCMB_stu[srns[i]] = marks
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
| 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 |
# 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
| if __name__ == '__main__':
print('Welcome to hangman!!')
while True:
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
| 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)')
| 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) | 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'
| """
File type enumaration.
"""
image = 'image'
video = 'video'
file = 'file' |
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!')
#
| 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!') |
#
# 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)
| (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, single_value_constraint, value_range_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ConstraintsIntersection', 'SingleValueConstraint', 'ValueRangeConstraint', 'ValueSizeConstraint')
(elt_mes_ospf,) = mibBuilder.importSymbols('ELTEX-MES-IP', 'eltMesOspf')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(notification_type, mib_scalar, mib_table, mib_table_row, mib_table_column, counter64, bits, iso, gauge32, unsigned32, counter32, object_identity, time_ticks, mib_identifier, ip_address, integer32, module_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'NotificationType', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter64', 'Bits', 'iso', 'Gauge32', 'Unsigned32', 'Counter32', 'ObjectIdentity', 'TimeTicks', 'MibIdentifier', 'IpAddress', 'Integer32', 'ModuleIdentity')
(row_status, display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'DisplayString', 'TextualConvention')
elt_ospf_auth_table = mib_table((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.')
elt_ospf_auth_entry = mib_table_row((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.')
elt_ospf_if_ip_address = mib_table_column((1, 3, 6, 1, 4, 1, 35265, 1, 23, 91, 1, 1, 1, 1), ip_address()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
eltOspfIfIpAddress.setStatus('current')
if mibBuilder.loadTexts:
eltOspfIfIpAddress.setDescription('The IP address of this OSPF interface.')
elt_ospf_auth_key_id = mib_table_column((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).')
elt_ospf_auth_key = mib_table_column((1, 3, 6, 1, 4, 1, 35265, 1, 23, 91, 1, 1, 1, 3), octet_string().subtype(subtypeSpec=value_size_constraint(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.")
elt_ospf_auth_status = mib_table_column((1, 3, 6, 1, 4, 1, 35265, 1, 23, 91, 1, 1, 1, 4), row_status()).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()
| def outer_function(msg):
def inner_function():
print(msg)
return inner_function
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print('Wrapper executed this before {}'.format(original_function.__name__))
return original_function(*args, **kwargs)
return wrapper_function
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__))
return self.original_function(*args, **kwargs)
@decorator_function
def display():
print('display function ran')
@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() |
"""
Investigating Ulam sequences
"""
| """
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]
| """
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 = {}
for i in range(len(cluster) - 1):
for j in range(i + 1, len(cluster)):
distances[f'atom {i + 1} and atom {j + 1}'] = dist3_d(cluster[i], cluster[j])
shortest_distance = min(distances.values())
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 = {}
for i in range(len(cluster) - 1):
for j in range(i + 1, len(cluster)):
distances[f'atom {i + 1} and atom {j + 1}'] = dist3_d(cluster[i], cluster[j])
all_lennard_jones_potentials = [lennard_jones_potential(dist) for dist in distances.values()]
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 dist3_d(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)
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.
"""
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])
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] |
{
"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": [
]
}
]
}
| {'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': []}]} |
################################################################################
# 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
| def is_prime(n):
judge = 1
if n == 1:
judge = 0
else:
for i in range(1, round((n - 1) ** 0.5 + 1)):
if not n % (i + 1) and n != i + 1:
judge = 0
return bool(judge)
return True
def main():
pl = []
num = int(input('Enter a positive integer: '))
for i in range(num):
pri = is_prime(i + 1)
if pri == True:
pl.append(i + 1)
pl = ', '.join((str(i) for i in pl))
print('The primes up to', num, 'are:', pl)
if __name__ == '__main__':
main() |
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 | class Solution:
def contains_nearby_duplicate(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]
| """Google Earth Engine Developer's Guide examples for 'Images - Relational, conditional and Boolean operations'."""
image = ee.Image('COPERNICUS/S2_SR/20210114T185729_20210114T185730_T10SEG')
replacement = ee.Image('COPERNICUS/S2_SR/20210109T185751_20210109T185931_T10SEG')
replaced = image.where(image.select('MSK_CLDPRB').gt(5), replacement)
map_replaced = folium.Map(location=[37.7349, -122.3769], zoom_start=11)
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())) |
#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
| """ 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 |
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()
| 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
def check_invariant(self):
if len(self.heap) > 1:
for i in range(1, len(self.heap)):
if self.heap[(i - 1) // 2] > self.heap[i]:
raise runtime_error('Heap invariant violated')
def swap(self, i, j):
old_i = self.heap[i]
self.heap[i] = self.heap[j]
self.heap[j] = old_i
def insert(self, priority):
self.heap.append(priority)
i_new = len(self.heap) - 1
i_parent = (i_new - 1) // 2
while i_new > 0 and self.heap[i_parent] > self.heap[i_new]:
self.swap(i_new, i_parent)
i_new = i_parent
i_parent = (i_parent - 1) // 2
self.check_invariant()
def is_empty(self):
return len(self.heap) == 0
def remove_min(self):
min_priority = self.heap[0]
self.swap(0, len(self.heap) - 1)
self.heap.pop()
i_current = 0
next_swap = self.next_down(i_current)
while next_swap != None:
self.swap(i_current, next_swap)
i_current = next_swap
next_swap = self.next_down(i_current)
return min_priority
def next_down(self, i):
max_ind = len(self.heap) - 1
left = 2 * i + 1
right = left + 1
if left > max_ind:
return None
elif right > max_ind:
if self.heap[left] < self.heap[i]:
return left
else:
return None
else:
next = None
if self.heap[left] < self.heap[i]:
next = left
if self.heap[right] < self.heap[left]:
next = right
return next
def main():
pq = min_pq()
print(pq)
if __name__ == '__main__':
main() |
#! /usr/bin/env python3
""" example module: extra.good.omega """
def FunO():
return "Omega"
if __name__ == "__main__":
print("I prefer to be a module") | """ example module: extra.good.omega """
def fun_o():
return 'Omega'
if __name__ == '__main__':
print('I prefer to be a module') |
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='')
| 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'
] | consumer_key = 'FILL ME IN'
consumer_secret = 'FILL ME IN'
access_token = 'FILL ME IN'
access_token_secret = 'FILL ME IN'
twitter_screen_name = 'FILL ME IN'
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]
| class Colorcode:
def get_ohms(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, 0), 'grey': ('8', 100000000), 'white': ('9', 1000000000)}
return int(d[code[0]][0] + d[code[1]][0]) * d[code[2]][1] |
class Solution:
def XXX(self, root: TreeNode) -> List[List[int]]:
if root is None: return []
res = []
queue = [root]
while queue:
tmp = []
size = len(queue)
while size:
q = queue.pop(0)
tmp.append(q.val)
if q.left:
queue.append(q.left)
if q.right:
queue.append(q.right)
size -= 1
res.append(tmp)
return res
| class Solution:
def xxx(self, root: TreeNode) -> List[List[int]]:
if root is None:
return []
res = []
queue = [root]
while queue:
tmp = []
size = len(queue)
while size:
q = queue.pop(0)
tmp.append(q.val)
if q.left:
queue.append(q.left)
if q.right:
queue.append(q.right)
size -= 1
res.append(tmp)
return res |
"""
The different types of errors the compiler can raise.
"""
class CompilerError(Exception):
"""
A general-purpose compiler error, which contains the position of the error
as well as a formatted message.
"""
def __init__(self, filename, line, col, fmt, *args, **kwargs):
super().__init__()
self.filename = filename
self.line = line
self.column = col
if line > 0 and col > 0:
self.message = (
"At {}:{}:{}: ".format(filename, line, col) +
fmt.format(*args, **kwargs))
else:
self.message = ('In {}: '.format(filename) +
fmt.format(*args, **kwargs))
@staticmethod
def from_token(tok, fmt, *args, **kwargs):
"""
Makes a new CompilerError, taking the position from the given token.
"""
return CompilerError(tok.filename, tok.line, tok.column,
fmt, *args, **kwargs)
| """
The different types of errors the compiler can raise.
"""
class Compilererror(Exception):
"""
A general-purpose compiler error, which contains the position of the error
as well as a formatted message.
"""
def __init__(self, filename, line, col, fmt, *args, **kwargs):
super().__init__()
self.filename = filename
self.line = line
self.column = col
if line > 0 and col > 0:
self.message = 'At {}:{}:{}: '.format(filename, line, col) + fmt.format(*args, **kwargs)
else:
self.message = 'In {}: '.format(filename) + fmt.format(*args, **kwargs)
@staticmethod
def from_token(tok, fmt, *args, **kwargs):
"""
Makes a new CompilerError, taking the position from the given token.
"""
return compiler_error(tok.filename, tok.line, tok.column, fmt, *args, **kwargs) |
#!/usr/bin/env python3
def get_stream(path):
with open(path, encoding='utf-8') as infile:
return infile.read()
stream = get_stream("input.txt")
def find_in_list(list_, x, start=0):
i = None
try:
i = list_.index(x, start)
except ValueError:
pass
return i
# Stream types:
# S = Stream (main)
# < = Garbage
# { = Group
# ! = Ignored
class Stream:
def __init__(self, text, stream_type=None):
self.stream_type = stream_type or 'S'
if self.stream_type == 'S':
text = self.cancel_chars(list(text))
text = self.identify_garbage(text)
if self.stream_type in ['S', '{']:
text = self.identify_groups(text)
self.data = text
def cancel_chars(self, text):
start = find_in_list(text, '!')
while start is not None:
if (start + 1) < len(text):
text[start] = Stream(text.pop(start + 1), '!')
start = find_in_list(text, '!', start + 1)
return text
def identify_garbage(self, text):
start = find_in_list(text, '<')
while start is not None:
end = text.index('>', start)
text[start] = Stream(text[start + 1:end], '<')
del text[start + 1:end + 1]
start = find_in_list(text, '<', start + 1)
return text
def identify_groups(self, text):
count = 0
groups = []
start = None
for i in range(len(text)):
if text[i] == '{':
count += 1
if count == 1:
start = i
elif text[i] == '}':
count -= 1
if count == 0:
groups.append((start, i))
removed = 0
for group in groups:
start = group[0] - removed
end = group[1] - removed
removed += (end - start)
text[start] = Stream(text[start + 1:end], '{')
del text[start + 1:end + 1]
return text
def count_groups(self):
count = 0
for s in self.data:
if hasattr(s, 'stream_type') and s.stream_type == '{':
count += 1
count += s.count_groups()
return count
def score_groups(self, outer=0):
score = 0
if self.stream_type == '{':
score += outer + 1
outer += 1
for s in self.data:
if hasattr(s, 'stream_type') and s.stream_type == '{':
score += s.score_groups(outer)
return score
def count_garbage(self):
count = 0
for s in self.data:
if hasattr(s, 'stream_type'):
if s.stream_type == '{':
count += s.count_garbage()
elif s.stream_type == '<':
count += len(
[s for s in s.data if type(s) == str]
)
return count
def __repr__(self):
if self.stream_type == 'S':
return ''.join([str(d) for d in self.data])
elif self.stream_type == '{':
return ' {' + ''.join(str(d) for d in self.data) + '} '
elif self.stream_type == '<':
return ' <' + ''.join(str(d) for d in self.data) + '> '
else:
return ' !' + str(self.data) + ' '
s = Stream(stream)
#print('Stream:', s)
print('Num groups:', s.count_groups())
print('Score:', s.score_groups())
print('Garbage:', s.count_garbage())
| def get_stream(path):
with open(path, encoding='utf-8') as infile:
return infile.read()
stream = get_stream('input.txt')
def find_in_list(list_, x, start=0):
i = None
try:
i = list_.index(x, start)
except ValueError:
pass
return i
class Stream:
def __init__(self, text, stream_type=None):
self.stream_type = stream_type or 'S'
if self.stream_type == 'S':
text = self.cancel_chars(list(text))
text = self.identify_garbage(text)
if self.stream_type in ['S', '{']:
text = self.identify_groups(text)
self.data = text
def cancel_chars(self, text):
start = find_in_list(text, '!')
while start is not None:
if start + 1 < len(text):
text[start] = stream(text.pop(start + 1), '!')
start = find_in_list(text, '!', start + 1)
return text
def identify_garbage(self, text):
start = find_in_list(text, '<')
while start is not None:
end = text.index('>', start)
text[start] = stream(text[start + 1:end], '<')
del text[start + 1:end + 1]
start = find_in_list(text, '<', start + 1)
return text
def identify_groups(self, text):
count = 0
groups = []
start = None
for i in range(len(text)):
if text[i] == '{':
count += 1
if count == 1:
start = i
elif text[i] == '}':
count -= 1
if count == 0:
groups.append((start, i))
removed = 0
for group in groups:
start = group[0] - removed
end = group[1] - removed
removed += end - start
text[start] = stream(text[start + 1:end], '{')
del text[start + 1:end + 1]
return text
def count_groups(self):
count = 0
for s in self.data:
if hasattr(s, 'stream_type') and s.stream_type == '{':
count += 1
count += s.count_groups()
return count
def score_groups(self, outer=0):
score = 0
if self.stream_type == '{':
score += outer + 1
outer += 1
for s in self.data:
if hasattr(s, 'stream_type') and s.stream_type == '{':
score += s.score_groups(outer)
return score
def count_garbage(self):
count = 0
for s in self.data:
if hasattr(s, 'stream_type'):
if s.stream_type == '{':
count += s.count_garbage()
elif s.stream_type == '<':
count += len([s for s in s.data if type(s) == str])
return count
def __repr__(self):
if self.stream_type == 'S':
return ''.join([str(d) for d in self.data])
elif self.stream_type == '{':
return ' {' + ''.join((str(d) for d in self.data)) + '} '
elif self.stream_type == '<':
return ' <' + ''.join((str(d) for d in self.data)) + '> '
else:
return ' !' + str(self.data) + ' '
s = stream(stream)
print('Num groups:', s.count_groups())
print('Score:', s.score_groups())
print('Garbage:', s.count_garbage()) |
sum = 0
for i in range(1, 101):
sum += i
print(sum)
| sum = 0
for i in range(1, 101):
sum += i
print(sum) |
interest = [
(0, "Hadoop"), (0, "Big Data"), (0, "HBase"), (0, "Java"),
(0, "Spark"), (0, "Storm"), (0, "Cassandra"),
(1, "NoSQL"), (1, "MongDB"), (1, "Cassandra"), (1, "HBase"),
(1, "Postgres"), (2, "Python"), (2, "scikit-learn"), (2, "scipy"),
(2, "numpy"), (2, "statsmodels"), (2, "pandas"), (3, "R"), (3, "Python"),
(3, "statistics"), (3, "regression"), (3, "probability"),
(4, "machine learning"), (4, "regression"), (4, "decision trees"),
(4, "libsvm"), (5, "Python"), (5, "R"), (5, "Java"), (5, "C++"),
(5, "Haskell"), (5, "programming languages"), (6, "statistics"),
(6, "probability"), (6, "mathematics"), (6, "theory"),
(7, "machine learning"), (7, "scikit-learn"), (7, "Mahout"),
(7, "neural networks"), (8, "neural networks"), (8, "deep learning"),
(8, "Big data"), (8, "artificial intelligence"), (9, "Hadoop"),
(9, "Java"), (9, "MapReduce"), (9, "Big data")
]
| interest = [(0, 'Hadoop'), (0, 'Big Data'), (0, 'HBase'), (0, 'Java'), (0, 'Spark'), (0, 'Storm'), (0, 'Cassandra'), (1, 'NoSQL'), (1, 'MongDB'), (1, 'Cassandra'), (1, 'HBase'), (1, 'Postgres'), (2, 'Python'), (2, 'scikit-learn'), (2, 'scipy'), (2, 'numpy'), (2, 'statsmodels'), (2, 'pandas'), (3, 'R'), (3, 'Python'), (3, 'statistics'), (3, 'regression'), (3, 'probability'), (4, 'machine learning'), (4, 'regression'), (4, 'decision trees'), (4, 'libsvm'), (5, 'Python'), (5, 'R'), (5, 'Java'), (5, 'C++'), (5, 'Haskell'), (5, 'programming languages'), (6, 'statistics'), (6, 'probability'), (6, 'mathematics'), (6, 'theory'), (7, 'machine learning'), (7, 'scikit-learn'), (7, 'Mahout'), (7, 'neural networks'), (8, 'neural networks'), (8, 'deep learning'), (8, 'Big data'), (8, 'artificial intelligence'), (9, 'Hadoop'), (9, 'Java'), (9, 'MapReduce'), (9, 'Big data')] |
#!python
def is_sorted(items):
#TODO: write code to implement the selection sort algorithm
for i in range(len(items)):
#moving the boundary of the sorted section forward
min_location = i
for j in range(i + 1, len(items)):
#finding the min value location in the unsorted section
if items[j] < items[min_location]:
min_location = j
temp = items[i]
items[i] = items[min_location]
items[min_location] = temp
items = [3,1,7,0]
#i i j->
is_sorted(items)
#print(items) #should print [0, 1, 3, 7]
def bubble_sort(list_a):
'''
Sort given items by swapping adjacent items that are out of order, and
repeating until all items are in sorted order.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?
# TODO: Repeat until all items are in sorted order
# TODO: Swap adjacent items that are out of order
'''
indexing_length = len(list_a) - 1 #SCan not apply comparision starting with last item of list (No item to right)
sorted = False #Create variable of sorted and set it equal to false
while not sorted: #Repeat until sorted = True
sorted = True # Break the while loop whenever we have gone through all the values
for i in range(0, indexing_length): # For every value in the list
if list_a[i] > list_a[i+1]: #if value in list is greater than value directly to the right of it,
sorted = False # These values are unsorted
list_a[i], list_a[i+1] = list_a[i+1], list_a[i] #Switch these values
return list_a # Return our list "unsorted_list" which is not sorted.
# print(bubble_sort([4,8,1,14,8,2,9,5,7,6,6]))
def selection_sort(items):
"""Sort given items by finding minimum item, swapping it with first
unsorted item, and repeating until all items are in sorted order.
Running time: O(n^2) because as the numbers of items grow the so does the outter and inner loop, also the function increases in a quadratic way
Memory usage: O(1) because as items grow no additional spaces are created and everything done in place"""
# pseudo seperates list into 2 sections, sorted and unsorted, goes through the unsorted section and finds the index with lowest value among all and swaps it with the sorted section
## can use while or for outter loop
# i = 0
# this is 'sorted' section
# while i < len(items) - 1:
for i in range(len(items)-1):
lowest_index = i
lowest_value = items[lowest_index]
# this is 'unsorted' section
for j in range(lowest_index + 1, len(items)):
if items[j] < lowest_value:
# lowest_index gets updated and settles with the lowest index of lowest value
lowest_index = j
lowest_value = items[j]
# performs the swap
items[i], items[lowest_index] = items[lowest_index], items[i]
# moves pointer up
# i += 1
return items
def insertion_sort(items):
"""Sort given items by taking first unsorted item, inserting it in sorted
order in front of items, and repeating until all items are in order.
Running time: O(n^2) because as items grow outter and inner loop both increases, also the function increases in a quadratic way
Memory usage: O(1) because everything is done in place """
# similar to selection sort where list is pseudo broken into 'sorted' and 'unsorted' sections
# an item is selected from 'unsorted' and checks against the 'sorted' section to see where to add
# this is our selection section of the list
for i in range(1, len(items)):
# range is non inclusive so i is never reached only i-1
# loop through our 'sorted' section
for j in range(0, i):
# the moment it finds an item in this part of the list which is greater or equal 'unsorted' selected item, it is removed from the 'unsorted' section and inserted into the 'sorted' section
if items[j] >= items[i]:
removed_item = items.pop(i)
items.insert(j, removed_item)
continue
return items
| def is_sorted(items):
for i in range(len(items)):
min_location = i
for j in range(i + 1, len(items)):
if items[j] < items[min_location]:
min_location = j
temp = items[i]
items[i] = items[min_location]
items[min_location] = temp
items = [3, 1, 7, 0]
is_sorted(items)
def bubble_sort(list_a):
"""
Sort given items by swapping adjacent items that are out of order, and
repeating until all items are in sorted order.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?
# TODO: Repeat until all items are in sorted order
# TODO: Swap adjacent items that are out of order
"""
indexing_length = len(list_a) - 1
sorted = False
while not sorted:
sorted = True
for i in range(0, indexing_length):
if list_a[i] > list_a[i + 1]:
sorted = False
(list_a[i], list_a[i + 1]) = (list_a[i + 1], list_a[i])
return list_a
def selection_sort(items):
"""Sort given items by finding minimum item, swapping it with first
unsorted item, and repeating until all items are in sorted order.
Running time: O(n^2) because as the numbers of items grow the so does the outter and inner loop, also the function increases in a quadratic way
Memory usage: O(1) because as items grow no additional spaces are created and everything done in place"""
for i in range(len(items) - 1):
lowest_index = i
lowest_value = items[lowest_index]
for j in range(lowest_index + 1, len(items)):
if items[j] < lowest_value:
lowest_index = j
lowest_value = items[j]
(items[i], items[lowest_index]) = (items[lowest_index], items[i])
return items
def insertion_sort(items):
"""Sort given items by taking first unsorted item, inserting it in sorted
order in front of items, and repeating until all items are in order.
Running time: O(n^2) because as items grow outter and inner loop both increases, also the function increases in a quadratic way
Memory usage: O(1) because everything is done in place """
for i in range(1, len(items)):
for j in range(0, i):
if items[j] >= items[i]:
removed_item = items.pop(i)
items.insert(j, removed_item)
continue
return items |
#$ID$
class Participant:
"""This class is used to create object for participant."""
def __init__(self):
"""Initialize parameters for participant object."""
self.participant_id = ""
self.participant_person = ""
def set_participant_id(self, participant_id):
"""Set participant id.
Args:
participant_id(str): Participant id.
"""
self.participant_id = participant_id
def get_participant_id(self):
"""Get participant id.
Returns:
str: Participant id.
"""
return self.participant_id
def set_participant_person(self, participant_person):
"""Set participant person.
Args:
participant_person(str): Participant person.
"""
self.participant_person = participant_person
def get_participant_person(self):
"""Get participant person.
Returns:
str: Participant person.
"""
return self.participant_person
| class Participant:
"""This class is used to create object for participant."""
def __init__(self):
"""Initialize parameters for participant object."""
self.participant_id = ''
self.participant_person = ''
def set_participant_id(self, participant_id):
"""Set participant id.
Args:
participant_id(str): Participant id.
"""
self.participant_id = participant_id
def get_participant_id(self):
"""Get participant id.
Returns:
str: Participant id.
"""
return self.participant_id
def set_participant_person(self, participant_person):
"""Set participant person.
Args:
participant_person(str): Participant person.
"""
self.participant_person = participant_person
def get_participant_person(self):
"""Get participant person.
Returns:
str: Participant person.
"""
return self.participant_person |
def count_neigbors_on(lights, i, j):
return (lights[i-1][j-1] if i > 0 and j > 0 else 0) \
+ (lights[i-1][j] if i > 0 else 0) \
+ (lights[i-1][j+1] if i > 0 and j < len(lights) - 1 else 0) \
+ (lights[i][j-1] if j > 0 else 0) \
+ (lights[i][j+1] if j < len(lights) - 1 else 0) \
+ (lights[i+1][j-1] if i < len(lights) - 1 and j > 0 else 0) \
+ (lights[i+1][j] if i < len(lights) - 1 else 0) \
+ (lights[i+1][j+1] if i < len(lights) - 1 and j < len(lights) - 1 else 0)
def get_next_state(curr_state):
next_state = []
for i in range(0, len(curr_state)):
row = [0] * len(curr_state[0])
for j in range(0, len(row)):
on_stays_on = curr_state[i][j] == 1 and count_neigbors_on(curr_state, i, j) in [2, 3]
off_turns_on = curr_state[i][j] == 0 and count_neigbors_on(curr_state, i, j) == 3
if on_stays_on or off_turns_on:
row[j] = 1
next_state.append(row)
return next_state
def solve(lights):
curr_state = lights
for turn in range(0, 100):
curr_state = get_next_state(curr_state)
return sum([sum(line) for line in curr_state])
def parse(file_name):
with open(file_name, "r") as f:
lights = []
lines = [line.strip() for line in f.readlines()]
for i in range(0, len(lines)):
row = [0] * len(lines[0])
for j in range(0, len(row)):
if lines[i][j] == "#":
row[j] = 1
lights.append(row)
return lights
if __name__ == '__main__':
print(solve(parse("data.txt")))
| def count_neigbors_on(lights, i, j):
return (lights[i - 1][j - 1] if i > 0 and j > 0 else 0) + (lights[i - 1][j] if i > 0 else 0) + (lights[i - 1][j + 1] if i > 0 and j < len(lights) - 1 else 0) + (lights[i][j - 1] if j > 0 else 0) + (lights[i][j + 1] if j < len(lights) - 1 else 0) + (lights[i + 1][j - 1] if i < len(lights) - 1 and j > 0 else 0) + (lights[i + 1][j] if i < len(lights) - 1 else 0) + (lights[i + 1][j + 1] if i < len(lights) - 1 and j < len(lights) - 1 else 0)
def get_next_state(curr_state):
next_state = []
for i in range(0, len(curr_state)):
row = [0] * len(curr_state[0])
for j in range(0, len(row)):
on_stays_on = curr_state[i][j] == 1 and count_neigbors_on(curr_state, i, j) in [2, 3]
off_turns_on = curr_state[i][j] == 0 and count_neigbors_on(curr_state, i, j) == 3
if on_stays_on or off_turns_on:
row[j] = 1
next_state.append(row)
return next_state
def solve(lights):
curr_state = lights
for turn in range(0, 100):
curr_state = get_next_state(curr_state)
return sum([sum(line) for line in curr_state])
def parse(file_name):
with open(file_name, 'r') as f:
lights = []
lines = [line.strip() for line in f.readlines()]
for i in range(0, len(lines)):
row = [0] * len(lines[0])
for j in range(0, len(row)):
if lines[i][j] == '#':
row[j] = 1
lights.append(row)
return lights
if __name__ == '__main__':
print(solve(parse('data.txt'))) |
'''Publisher form
Provides a form for publisher creation
'''
__version__ = '0.1'
| """Publisher form
Provides a form for publisher creation
"""
__version__ = '0.1' |
class Item():
def __init__(self, id_, value):
self.id_ = id_
self.value = value
class Stack():
def __init__(self):
self.size = 0
self._items = []
def push(self, item):
self._items.append(item)
self.size += 1
def pop(self):
item = None
if self.size > 0:
item = self._items.pop()
self.size -= 1
return item
| class Item:
def __init__(self, id_, value):
self.id_ = id_
self.value = value
class Stack:
def __init__(self):
self.size = 0
self._items = []
def push(self, item):
self._items.append(item)
self.size += 1
def pop(self):
item = None
if self.size > 0:
item = self._items.pop()
self.size -= 1
return item |
NON_TERMINALS = [
"S",
"SBAR",
"SQ",
"SBARQ",
"SINV",
"ADJP",
"ADVP",
"CONJP",
"FRAG",
"INTJ",
"LST",
"NAC",
"NP",
"NX",
"PP",
"PRN",
"QP",
"RRC",
"UCP",
"VP",
"WHADJP",
"WHAVP",
"WHNP",
"WHPP",
"WHADVP",
"X",
"ROOT",
"NP-TMP",
"PRT",
]
class Token(object):
def __init__(self, word, idx):
self.word = word
self.idx = idx
def __repr__(self):
return repr(self.word)
class Node(object):
def __init__(self):
self.root = False
self.children = []
self.label = None
self.parent = None
self.phrase = ""
self.terminal = False
self.start_idx = 0
self.end_idx = 0
class Sentence(object):
def __init__(self, parse_string):
self.num_nodes = 0
self.tree = self.get_tree(parse_string)
self.sent = self.tree.phrase
tokens = {}
for idx, tok in enumerate(self.tree.phrase.split(" ")):
tokens[idx] = Token(tok, idx)
self.tokens = tokens
self.num_tokens = len(tokens)
def get_tree(self, parse_string):
tree = self.contruct_tree_from_parse(parse_string, None)
tree = self.reduce_tree(tree)
phrase_whole = self.assign_phrases(tree, 0)
tree.phrase = phrase_whole
tree.start_idx = 0
tree.end_idx = len(phrase_whole.split(" "))
tree.parent_idx = -1
self.assign_ids(tree)
return tree
def assign_ids(self, tree):
tree.idx = self.num_nodes
self.num_nodes += 1
for child in tree.children:
child.parent_idx = tree.idx
self.assign_ids(child)
@staticmethod
def get_subtrees(parse_txt_partial):
parse_txt_partial = parse_txt_partial[1:-1]
if "(" in parse_txt_partial:
idx_first_lb = parse_txt_partial.index("(")
name_const = parse_txt_partial[:idx_first_lb].strip()
parse_txt_partial = parse_txt_partial[idx_first_lb:]
count = 0
partition_indices = []
for idx in range(len(parse_txt_partial)):
if parse_txt_partial[idx] == "(":
count += 1
elif parse_txt_partial[idx] == ")":
count -= 1
if count == 0:
partition_indices.append(idx + 1)
partitions = []
part_idx_prev = 0
for i, part_idx in enumerate(partition_indices):
partitions.append(parse_txt_partial[part_idx_prev:part_idx])
part_idx_prev = part_idx
else:
temp = parse_txt_partial.split(" ")
name_const = temp[0]
partitions = [temp[1]]
return name_const, partitions
# constructs constituency tree from the parse string
@staticmethod
def contruct_tree_from_parse(parse_txt, node):
if parse_txt.startswith("("):
phrase_name, divisions = Sentence.get_subtrees(parse_txt)
if node is None:
node = Node()
node.root = True
node.label = phrase_name
if phrase_name in NON_TERMINALS:
for phrase in divisions:
if phrase.strip() == "":
continue
node_temp = Node()
node_temp.parent = node
node.children.append(
Sentence.contruct_tree_from_parse(phrase, node_temp)
)
else:
node.terminal = True
node.phrase = divisions[0]
return node
# only used for debugging
@staticmethod
def print_tree(tree):
print(tree.label)
print(tree.phrase)
print(tree.start_idx)
print(tree.end_idx)
for child in tree.children:
Sentence.print_tree(child)
# remove single child nodes
@staticmethod
def reduce_tree(tree):
while len(tree.children) == 1:
tree = tree.children[0]
children = []
for child in tree.children:
child = Sentence.reduce_tree(child)
children.append(child)
tree.children = children
return tree
@staticmethod
def assign_phrases(tree, phrase_start_idx):
if tree.terminal:
tree.start_idx = phrase_start_idx
tree.end_idx = phrase_start_idx + len(
tree.phrase.strip().split(" ")
)
return tree.phrase
else:
phrase = ""
phrase_idx_add = 0
for child in tree.children:
child_phrase = Sentence.assign_phrases(
child, phrase_start_idx + phrase_idx_add
).strip()
child.start_idx = phrase_start_idx + phrase_idx_add
phrase_idx_add += len(child_phrase.strip().split(" "))
child.end_idx = phrase_start_idx + phrase_idx_add
child.phrase = child_phrase
phrase += " " + child_phrase
phrase = phrase.strip()
return phrase
| non_terminals = ['S', 'SBAR', 'SQ', 'SBARQ', 'SINV', 'ADJP', 'ADVP', 'CONJP', 'FRAG', 'INTJ', 'LST', 'NAC', 'NP', 'NX', 'PP', 'PRN', 'QP', 'RRC', 'UCP', 'VP', 'WHADJP', 'WHAVP', 'WHNP', 'WHPP', 'WHADVP', 'X', 'ROOT', 'NP-TMP', 'PRT']
class Token(object):
def __init__(self, word, idx):
self.word = word
self.idx = idx
def __repr__(self):
return repr(self.word)
class Node(object):
def __init__(self):
self.root = False
self.children = []
self.label = None
self.parent = None
self.phrase = ''
self.terminal = False
self.start_idx = 0
self.end_idx = 0
class Sentence(object):
def __init__(self, parse_string):
self.num_nodes = 0
self.tree = self.get_tree(parse_string)
self.sent = self.tree.phrase
tokens = {}
for (idx, tok) in enumerate(self.tree.phrase.split(' ')):
tokens[idx] = token(tok, idx)
self.tokens = tokens
self.num_tokens = len(tokens)
def get_tree(self, parse_string):
tree = self.contruct_tree_from_parse(parse_string, None)
tree = self.reduce_tree(tree)
phrase_whole = self.assign_phrases(tree, 0)
tree.phrase = phrase_whole
tree.start_idx = 0
tree.end_idx = len(phrase_whole.split(' '))
tree.parent_idx = -1
self.assign_ids(tree)
return tree
def assign_ids(self, tree):
tree.idx = self.num_nodes
self.num_nodes += 1
for child in tree.children:
child.parent_idx = tree.idx
self.assign_ids(child)
@staticmethod
def get_subtrees(parse_txt_partial):
parse_txt_partial = parse_txt_partial[1:-1]
if '(' in parse_txt_partial:
idx_first_lb = parse_txt_partial.index('(')
name_const = parse_txt_partial[:idx_first_lb].strip()
parse_txt_partial = parse_txt_partial[idx_first_lb:]
count = 0
partition_indices = []
for idx in range(len(parse_txt_partial)):
if parse_txt_partial[idx] == '(':
count += 1
elif parse_txt_partial[idx] == ')':
count -= 1
if count == 0:
partition_indices.append(idx + 1)
partitions = []
part_idx_prev = 0
for (i, part_idx) in enumerate(partition_indices):
partitions.append(parse_txt_partial[part_idx_prev:part_idx])
part_idx_prev = part_idx
else:
temp = parse_txt_partial.split(' ')
name_const = temp[0]
partitions = [temp[1]]
return (name_const, partitions)
@staticmethod
def contruct_tree_from_parse(parse_txt, node):
if parse_txt.startswith('('):
(phrase_name, divisions) = Sentence.get_subtrees(parse_txt)
if node is None:
node = node()
node.root = True
node.label = phrase_name
if phrase_name in NON_TERMINALS:
for phrase in divisions:
if phrase.strip() == '':
continue
node_temp = node()
node_temp.parent = node
node.children.append(Sentence.contruct_tree_from_parse(phrase, node_temp))
else:
node.terminal = True
node.phrase = divisions[0]
return node
@staticmethod
def print_tree(tree):
print(tree.label)
print(tree.phrase)
print(tree.start_idx)
print(tree.end_idx)
for child in tree.children:
Sentence.print_tree(child)
@staticmethod
def reduce_tree(tree):
while len(tree.children) == 1:
tree = tree.children[0]
children = []
for child in tree.children:
child = Sentence.reduce_tree(child)
children.append(child)
tree.children = children
return tree
@staticmethod
def assign_phrases(tree, phrase_start_idx):
if tree.terminal:
tree.start_idx = phrase_start_idx
tree.end_idx = phrase_start_idx + len(tree.phrase.strip().split(' '))
return tree.phrase
else:
phrase = ''
phrase_idx_add = 0
for child in tree.children:
child_phrase = Sentence.assign_phrases(child, phrase_start_idx + phrase_idx_add).strip()
child.start_idx = phrase_start_idx + phrase_idx_add
phrase_idx_add += len(child_phrase.strip().split(' '))
child.end_idx = phrase_start_idx + phrase_idx_add
child.phrase = child_phrase
phrase += ' ' + child_phrase
phrase = phrase.strip()
return phrase |
# Error handling
def fatal_error(error):
"""Print out the error message that gets passed, then quit the program.
Inputs:
error = error message text
:param error: str
:return:
"""
raise RuntimeError(error)
| def fatal_error(error):
"""Print out the error message that gets passed, then quit the program.
Inputs:
error = error message text
:param error: str
:return:
"""
raise runtime_error(error) |
# Problem:
# In one cinema hall, the chairs are arranged in rectangular shape in r row and c columns.
# There are three types of projections with Tickets at different rates:
# -> Premiere - Premiere, at a price of 12.00 BGN.
# -> Normal - standard screening, at a price of 7.50 leva.
# -> Discount - screening for children, students and students at a reduced price of 5.00 BGN.
# Write a program that introduces a screen type, number of rows, and number of columns in the room
# numbers) and calculates total ticket revenue in a full room.
# Print the result in a format such as the examples below, with 2 decimal places.
projections_Type = input()
row = int(input())
cow = int(input())
tickets_Price = 0
total_Price = 0
if projections_Type == "Premiere":
tickets_Price = 12
elif projections_Type == "Normal":
tickets_Price = 7.5
elif projections_Type == "Discount":
tickets_Price = 5
total_Price = tickets_Price * (row * cow)
print("{0:.2f} leva".format(total_Price))
| projections__type = input()
row = int(input())
cow = int(input())
tickets__price = 0
total__price = 0
if projections_Type == 'Premiere':
tickets__price = 12
elif projections_Type == 'Normal':
tickets__price = 7.5
elif projections_Type == 'Discount':
tickets__price = 5
total__price = tickets_Price * (row * cow)
print('{0:.2f} leva'.format(total_Price)) |
# Title : TODO
# Objective : TODO
# Created by: Wenzurk
# Created on: 2018/2/19
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets) | pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets) |
class NotInServer(Exception): # The whole point of this is to do nothing
def __init__(self):
pass
class NotWhitelisted(Exception):
def __init__(self):
pass
| class Notinserver(Exception):
def __init__(self):
pass
class Notwhitelisted(Exception):
def __init__(self):
pass |
class Pagination(object):
count = None
def paginate_queryset(self, request, queryset, handler):
raise NotImplementedError
def get_paginated_response(self, request, data):
raise NotImplementedError
| class Pagination(object):
count = None
def paginate_queryset(self, request, queryset, handler):
raise NotImplementedError
def get_paginated_response(self, request, data):
raise NotImplementedError |
# hello world
def print_lol(the_list, indent=false, level=0):
for each_item in the_list:
if isinstance(each_item, list):
print_lol(each_item, indent, level+1)
else:
if indent:
for tab_stop in range(level):
print("\t", end=' ')
print(each_item)
| def print_lol(the_list, indent=false, level=0):
for each_item in the_list:
if isinstance(each_item, list):
print_lol(each_item, indent, level + 1)
else:
if indent:
for tab_stop in range(level):
print('\t', end=' ')
print(each_item) |
def read_samplesCSV(spls):
# reads in samples.csv file, format: Batch,Lane,Barcode,Sample,Alignments,ProviderName,Patient
hdr_check = ['Batch', 'Lane', 'Barcode', 'Sample', 'Alignments', 'ProviderName', 'Patient']
switch = "on"
file = open(spls, 'r')
list_path = []
list_splID = []
list_providerNames = []
list_refG = []
list_patient = []
for line in file:
line = line.strip('\n').split(',')
# Test Header. Note: Even when header wrong code continues (w/ warning), but first line not read.
if switch == "on":
if (line == hdr_check):
print("Passed CSV header check")
else:
Warning("CSV did NOT pass header check! Code continues, but first line ignored")
switch = "off"
continue
# build lists
list_path.append(line[0])
list_splID.append(line[3])
list_refG.append(line[4])
list_providerNames.append(line[5])
list_patient.append(line[6])
return [list_path,list_splID,list_refG,list_providerNames,set(list_patient)] # set(list_patient) provides only unique subject IDs
def read_samples_caseCSV(spls):
# reads in samples_case.csv file, format: Path,Sample,ReferenceGenome,Outgroup
hdr_check = ['Path','Sample','ReferenceGenome','Outgroup']
switch = "on"
file = open(spls, 'r')
list_path = []
list_splID = []
list_refG = []
list_outgroup = []
for line in file:
line = line.strip('\n').split(',')
# Test Header. Note: Even when header wrong code continues (w/ warning), but first line not read.
if switch == "on":
if (line == hdr_check):
print("Passed CSV header check")
else:
Warning("CSV did NOT pass header check! Code continues, but first line ignored")
switch = "off"
continue
# build lists
list_path.append(line[0])
list_splID.append(line[1])
list_refG.append(line[2])
list_outgroup.append(line[3])
return [list_path,list_splID,list_refG,list_outgroup]
| def read_samples_csv(spls):
hdr_check = ['Batch', 'Lane', 'Barcode', 'Sample', 'Alignments', 'ProviderName', 'Patient']
switch = 'on'
file = open(spls, 'r')
list_path = []
list_spl_id = []
list_provider_names = []
list_ref_g = []
list_patient = []
for line in file:
line = line.strip('\n').split(',')
if switch == 'on':
if line == hdr_check:
print('Passed CSV header check')
else:
warning('CSV did NOT pass header check! Code continues, but first line ignored')
switch = 'off'
continue
list_path.append(line[0])
list_splID.append(line[3])
list_refG.append(line[4])
list_providerNames.append(line[5])
list_patient.append(line[6])
return [list_path, list_splID, list_refG, list_providerNames, set(list_patient)]
def read_samples_case_csv(spls):
hdr_check = ['Path', 'Sample', 'ReferenceGenome', 'Outgroup']
switch = 'on'
file = open(spls, 'r')
list_path = []
list_spl_id = []
list_ref_g = []
list_outgroup = []
for line in file:
line = line.strip('\n').split(',')
if switch == 'on':
if line == hdr_check:
print('Passed CSV header check')
else:
warning('CSV did NOT pass header check! Code continues, but first line ignored')
switch = 'off'
continue
list_path.append(line[0])
list_splID.append(line[1])
list_refG.append(line[2])
list_outgroup.append(line[3])
return [list_path, list_splID, list_refG, list_outgroup] |
while True:
n_peer = int(input())
counter = 1
for i in range(2, n_peer):
if n_peer%i == 1:
print(i, end=' ')
counter += 1
print()
print(counter) | while True:
n_peer = int(input())
counter = 1
for i in range(2, n_peer):
if n_peer % i == 1:
print(i, end=' ')
counter += 1
print()
print(counter) |
def read_next(*args):
for el in args:
for i in el:
yield i
for item in read_next('string', (2,), {'d': 1, 'i': 2, 'c': 3, 't': 4}):
print(item, end='')
| def read_next(*args):
for el in args:
for i in el:
yield i
for item in read_next('string', (2,), {'d': 1, 'i': 2, 'c': 3, 't': 4}):
print(item, end='') |
# ---------------------------------------------------------- #
# Title: Listing 07
# Description: A module of multiple processing classes
# ChangeLog (Who,When,What):
# RRoot,1.1.2030,Created started script
# ---------------------------------------------------------- #
if __name__ == "__main__":
raise Exception("This file is not meant to ran by itself")
class FileProcessor:
"""Processes data to and from a file and a list of objects:
methods:
save_data_to_file(file_name,list_of_objects):
read_data_from_file(file_name): -> (a list of objects)
changelog: (When,Who,What)
RRoot,1.1.2030,Created Class
"""
@staticmethod
def save_data_to_file(file_name: str, list_of_objects: list):
""" Write data to a file from a list of object rows
:param file_name: (string) with name of file
:param list_of_objects: (list) of objects data saved to file
:return: (bool) with status of success status
"""
success_status = False
try:
file = open(file_name, "w")
for row in list_of_objects:
file.write(row.__str__() + "\n")
file.close()
success_status = True
except Exception as e:
print("There was a general error!")
print(e, e.__doc__, type(e), sep='\n')
return success_status
@staticmethod
def read_data_from_file(file_name: str):
""" Reads data from a file into a list of object rows
:param file_name: (string) with name of file
:return: (list) of object rows
"""
list_of_rows = []
try:
file = open(file_name, "r")
for line in file:
row = line.split(",")
list_of_rows.append(row)
file.close()
except Exception as e:
print("There was a general error!")
print(e, e.__doc__, type(e), sep='\n')
return list_of_rows
class DatabaseProcessor:
pass
# TODO: Add code to process to and from a database
| if __name__ == '__main__':
raise exception('This file is not meant to ran by itself')
class Fileprocessor:
"""Processes data to and from a file and a list of objects:
methods:
save_data_to_file(file_name,list_of_objects):
read_data_from_file(file_name): -> (a list of objects)
changelog: (When,Who,What)
RRoot,1.1.2030,Created Class
"""
@staticmethod
def save_data_to_file(file_name: str, list_of_objects: list):
""" Write data to a file from a list of object rows
:param file_name: (string) with name of file
:param list_of_objects: (list) of objects data saved to file
:return: (bool) with status of success status
"""
success_status = False
try:
file = open(file_name, 'w')
for row in list_of_objects:
file.write(row.__str__() + '\n')
file.close()
success_status = True
except Exception as e:
print('There was a general error!')
print(e, e.__doc__, type(e), sep='\n')
return success_status
@staticmethod
def read_data_from_file(file_name: str):
""" Reads data from a file into a list of object rows
:param file_name: (string) with name of file
:return: (list) of object rows
"""
list_of_rows = []
try:
file = open(file_name, 'r')
for line in file:
row = line.split(',')
list_of_rows.append(row)
file.close()
except Exception as e:
print('There was a general error!')
print(e, e.__doc__, type(e), sep='\n')
return list_of_rows
class Databaseprocessor:
pass |
califications = {
'anartz': 9.99,
'mikel': 5.01,
'aitor': 1.22,
'maite': 10,
'miren': 7.8,
'olatz': 9.89
}
pass_students = []
# Obtener clave, valor elemento a elemento
for key, value in califications.items():
if (value >= 5): pass_students.append(key)
print("Notas del curso:")
print(califications)
print("Aprobados:")
print(pass_students)
| califications = {'anartz': 9.99, 'mikel': 5.01, 'aitor': 1.22, 'maite': 10, 'miren': 7.8, 'olatz': 9.89}
pass_students = []
for (key, value) in califications.items():
if value >= 5:
pass_students.append(key)
print('Notas del curso:')
print(califications)
print('Aprobados:')
print(pass_students) |
def qsort(arr):
if len(arr) <= 1:
return arr
pivot = arr.pop()
greater, lesser = [], []
for item in arr:
if item > pivot:
greater.append(item)
else:
lesser.append(item)
return qsort(lesser) + [pivot] + qsort(greater)
| def qsort(arr):
if len(arr) <= 1:
return arr
pivot = arr.pop()
(greater, lesser) = ([], [])
for item in arr:
if item > pivot:
greater.append(item)
else:
lesser.append(item)
return qsort(lesser) + [pivot] + qsort(greater) |
class A():
def load_data(self):
return [1,2,3,4,5]
def __getitem__(self, item):
a = self.load_data()
return a[item]
class B(A):
def load_data(self):
return ['a','b','c']
a = B()
print(a[1]) | class A:
def load_data(self):
return [1, 2, 3, 4, 5]
def __getitem__(self, item):
a = self.load_data()
return a[item]
class B(A):
def load_data(self):
return ['a', 'b', 'c']
a = b()
print(a[1]) |
"""
Fixes the extra commas in some of the regions in the Russian data.
"""
file = open("data/2018-Russia-election-data.csv", "r", encoding="utf-8")
TEXT = ""
for line in file:
if len(line.split(",")) == 5:
last_char_index = line.rfind(",")
new_line = line[:last_char_index] + "" + line[last_char_index + 1:]
TEXT += new_line
else:
TEXT += line
file.close()
x = open("data/2018-Russia-election-data.csv", "w", encoding="utf-8")
x.writelines(TEXT)
x.close()
| """
Fixes the extra commas in some of the regions in the Russian data.
"""
file = open('data/2018-Russia-election-data.csv', 'r', encoding='utf-8')
text = ''
for line in file:
if len(line.split(',')) == 5:
last_char_index = line.rfind(',')
new_line = line[:last_char_index] + '' + line[last_char_index + 1:]
text += new_line
else:
text += line
file.close()
x = open('data/2018-Russia-election-data.csv', 'w', encoding='utf-8')
x.writelines(TEXT)
x.close() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.