content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
pass
def insert(self):
pass
def level_order_traversal(self):
pass
def delete(self):
pass
| class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class Binarysearchtree:
def __init__(self):
pass
def insert(self):
pass
def level_order_traversal(self):
pass
def delete(self):
pass |
'''
Assignment 1
'''
#Observing the output of the following commands
emp_number = 1233
print("Employee Number",emp_number)
emp_salary = 16745.50
emp_name = "Jerry Squaris"
print("Employee Salary and Name:",emp_salary, emp_name)
emp_salary = 23450.34
print("Updated Employee Salary:",emp_salary)
| """
Assignment 1
"""
emp_number = 1233
print('Employee Number', emp_number)
emp_salary = 16745.5
emp_name = 'Jerry Squaris'
print('Employee Salary and Name:', emp_salary, emp_name)
emp_salary = 23450.34
print('Updated Employee Salary:', emp_salary) |
with open("output.txt") as output:
data = output.read()
produced = {}
is_producing = set()
consumed = {}
readies = 0
for line in data.splitlines():
if ("JMSBasedValueInput" in line and "produced" in line) or "to low" in line:
for robot in (part.split("]")[0][6:] for part in line.split("[")[2:]):
if robot in produced:
produced[robot] += 1
else:
produced[robot] = 1
if "JMSBasedRobot" in line and "Received value" in line:
robot = line.split(":")[3].strip()
if robot in consumed:
consumed[robot] += 1
else:
consumed[robot] = 1
if "JMSBasedRobot" in line and "to low" in line:
robot = line.split(":")[3].strip()
is_producing.add(robot)
if "JMSBasedRobot" in line and "Done" in line:
robot = line.split(":")[3].strip()
is_producing.remove(robot)
if "Ready to" in line:
readies += 1
print(produced)
print(consumed)
print([(k,v) for k,v in produced.items() if v < 2])
print([(k,v) for k,v in consumed.items() if v < 2])
print(is_producing)
print(readies) | with open('output.txt') as output:
data = output.read()
produced = {}
is_producing = set()
consumed = {}
readies = 0
for line in data.splitlines():
if 'JMSBasedValueInput' in line and 'produced' in line or 'to low' in line:
for robot in (part.split(']')[0][6:] for part in line.split('[')[2:]):
if robot in produced:
produced[robot] += 1
else:
produced[robot] = 1
if 'JMSBasedRobot' in line and 'Received value' in line:
robot = line.split(':')[3].strip()
if robot in consumed:
consumed[robot] += 1
else:
consumed[robot] = 1
if 'JMSBasedRobot' in line and 'to low' in line:
robot = line.split(':')[3].strip()
is_producing.add(robot)
if 'JMSBasedRobot' in line and 'Done' in line:
robot = line.split(':')[3].strip()
is_producing.remove(robot)
if 'Ready to' in line:
readies += 1
print(produced)
print(consumed)
print([(k, v) for (k, v) in produced.items() if v < 2])
print([(k, v) for (k, v) in consumed.items() if v < 2])
print(is_producing)
print(readies) |
H, W, Y, X = map(int, input().split())
X -= 1
Y -= 1
field = []
for i in range(H):
field.append(input())
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
ans = 1
for i in range(4):
nx = X + dx[i]
ny = Y + dy[i]
while 0 <= nx < W and 0 <= ny < H and field[ny][nx] == '.':
nx += dx[i]
ny += dy[i]
ans += 1
print(ans) | (h, w, y, x) = map(int, input().split())
x -= 1
y -= 1
field = []
for i in range(H):
field.append(input())
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
ans = 1
for i in range(4):
nx = X + dx[i]
ny = Y + dy[i]
while 0 <= nx < W and 0 <= ny < H and (field[ny][nx] == '.'):
nx += dx[i]
ny += dy[i]
ans += 1
print(ans) |
#!/usr/bin/env python
def func1():
print("Hello World")
class Bogus:
my_var1 = ""
my_var2 = ""
my_var3 = ""
def hello(self):
print("Hello " + self.my_var1 + ", " + self.my_var2 + " and " + self.my_var3)
def not_hello(self):
print("Bye " + self.my_var1 + ", " + self.my_var2 + " and " + self.my_var3)
def __init__(self, var1, var2, var3):
self.my_var1 = var1
self.my_var2 = var2
self.my_var3 = var3
class BogusNew(Bogus):
def hello(self):
print("Welcome " + self.my_var1 + ", " + self.my_var2 + " and " + self.my_var3)
def __init__(self, var1, var2, var3):
print("Doing something more here...")
Bogus.__init__(self, var1, var2, var3)
if __name__ == "__main__":
print("I'm the module 'world'")
| def func1():
print('Hello World')
class Bogus:
my_var1 = ''
my_var2 = ''
my_var3 = ''
def hello(self):
print('Hello ' + self.my_var1 + ', ' + self.my_var2 + ' and ' + self.my_var3)
def not_hello(self):
print('Bye ' + self.my_var1 + ', ' + self.my_var2 + ' and ' + self.my_var3)
def __init__(self, var1, var2, var3):
self.my_var1 = var1
self.my_var2 = var2
self.my_var3 = var3
class Bogusnew(Bogus):
def hello(self):
print('Welcome ' + self.my_var1 + ', ' + self.my_var2 + ' and ' + self.my_var3)
def __init__(self, var1, var2, var3):
print('Doing something more here...')
Bogus.__init__(self, var1, var2, var3)
if __name__ == '__main__':
print("I'm the module 'world'") |
def foo():
return bbb
aaa = foo() and ccc | def foo():
return bbb
aaa = foo() and ccc |
#Print 1 to 100 ussing a loop
num = 0
while (num < 100):
num += 1
print(num)
| num = 0
while num < 100:
num += 1
print(num) |
def generate_table():
alphabet = 'ABCDEFGHIKLMNOPQRSTUVWXYZ'
tabel = [[0] * 5 for row in range(5)]
pos = 0
for x in range(5):
for y in range(5):
tabel[x][y] = alphabet[pos]
pos += 1
return tabel
def getStr(x, format='%02s'):
return ''.join(format % i for i in x)
def print_table(table):
print(' ' + getStr(range(1, 6)))
for row in range(0, len(table)):
print(str(row + 1) + getStr(table[row]))
def encrypt(table, words):
string = table
cipher = ''
for ch in words.upper():
if ch == "J": ch = "I"
for row in range(len(table)):
if ch in table[row]:
x = str((table[row].index(ch) + 1))
y = str(row + 1)
cipher += y + x
return cipher
def decrypt(table, numbers):
text = ''
for index in range(0, len(numbers), 2):
y = int(numbers[index]) - 1
x = int(numbers[index + 1]) - 1
if table[y][x] == "I":
table[y][x] = "(I/J)"
text += table[y][x]
return text
if __name__ == '__main__':
table = generate_table()
print_table(table)
cyp = input("Masukkan Plain Text: ")
ciphertext = encrypt(table, cyp)
print(ciphertext)
print(decrypt(table, ciphertext))
| def generate_table():
alphabet = 'ABCDEFGHIKLMNOPQRSTUVWXYZ'
tabel = [[0] * 5 for row in range(5)]
pos = 0
for x in range(5):
for y in range(5):
tabel[x][y] = alphabet[pos]
pos += 1
return tabel
def get_str(x, format='%02s'):
return ''.join((format % i for i in x))
def print_table(table):
print(' ' + get_str(range(1, 6)))
for row in range(0, len(table)):
print(str(row + 1) + get_str(table[row]))
def encrypt(table, words):
string = table
cipher = ''
for ch in words.upper():
if ch == 'J':
ch = 'I'
for row in range(len(table)):
if ch in table[row]:
x = str(table[row].index(ch) + 1)
y = str(row + 1)
cipher += y + x
return cipher
def decrypt(table, numbers):
text = ''
for index in range(0, len(numbers), 2):
y = int(numbers[index]) - 1
x = int(numbers[index + 1]) - 1
if table[y][x] == 'I':
table[y][x] = '(I/J)'
text += table[y][x]
return text
if __name__ == '__main__':
table = generate_table()
print_table(table)
cyp = input('Masukkan Plain Text: ')
ciphertext = encrypt(table, cyp)
print(ciphertext)
print(decrypt(table, ciphertext)) |
async def calc_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, localization, numexpr, prefix, embed_color):
args = message.content.split();
err = ""
no_args = discord.Embed(title=localization[1][9][0], description=str(localization[1][9][4]).format(prefix), color=botconfig['accent1'])
no_args.add_field(name=localization[1][9][6], value=localization[1][9][7], inline=False)
if " ".join(args[1:]) == "" or " ".join(args[1:]) == " " or " ".join(args[1:]) == None:
return await message.channel.send(embed=no_args)
calc_content = discord.Embed(title=localization[1][9][0], color=embed_color)
calc_content.add_field(name=localization[1][9][1], value="```py\n" + " ".join(args[1:]) + "```", inline=False)
try:
result = str(numexpr.evaluate(" ".join(args[1:])))
except Exception as e:
if str(e) == 'division by zero':
result = localization[1][9][8]
elif str(e) == "Python int too large to convert to C long":
result = localization[1][9][9]
elif str(e).startswith("'VariableNode' object has no attribute"):
result = localization[1][9][10]
else:
result = localization[1][9][3] + str(e)
finally:
calc_content.add_field(name=localization[1][9][2], value="```" + result + "```", inline=False)
calc_content.add_field(name=localization[1][9][6], value=localization[1][9][7], inline=False)
await message.channel.send(embed=calc_content)
| async def calc_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, localization, numexpr, prefix, embed_color):
args = message.content.split()
err = ''
no_args = discord.Embed(title=localization[1][9][0], description=str(localization[1][9][4]).format(prefix), color=botconfig['accent1'])
no_args.add_field(name=localization[1][9][6], value=localization[1][9][7], inline=False)
if ' '.join(args[1:]) == '' or ' '.join(args[1:]) == ' ' or ' '.join(args[1:]) == None:
return await message.channel.send(embed=no_args)
calc_content = discord.Embed(title=localization[1][9][0], color=embed_color)
calc_content.add_field(name=localization[1][9][1], value='```py\n' + ' '.join(args[1:]) + '```', inline=False)
try:
result = str(numexpr.evaluate(' '.join(args[1:])))
except Exception as e:
if str(e) == 'division by zero':
result = localization[1][9][8]
elif str(e) == 'Python int too large to convert to C long':
result = localization[1][9][9]
elif str(e).startswith("'VariableNode' object has no attribute"):
result = localization[1][9][10]
else:
result = localization[1][9][3] + str(e)
finally:
calc_content.add_field(name=localization[1][9][2], value='```' + result + '```', inline=False)
calc_content.add_field(name=localization[1][9][6], value=localization[1][9][7], inline=False)
await message.channel.send(embed=calc_content) |
def f():
(some_global): int
print(some_global)
| def f():
(some_global): int
print(some_global) |
#!/usr/bin/env python3
n = int(input())
power = 7
i = 0
while i < n:
print(power)
power = power + 7
i = i + 1
| n = int(input())
power = 7
i = 0
while i < n:
print(power)
power = power + 7
i = i + 1 |
ANNOTATION_NAME = "service-meta-Name"
ANNOTATION_DESCRIPTION = "service-meta-Description"
ANNOTATION_DOCS_LINK = "service-meta-DocsLink"
ANNOTATION_ENVIRONMENT = "service-meta-Environment"
ANNOTATION_FRIENDLY_NAME = "service-meta-FriendlyName"
ANNOTATION_ICON_URL = "service-meta-IconURL"
ANNOTATION_MAJOR_VERSION = "service-meta-MajorVersion"
ANNOTATION_MINOR_VERSION = "service-meta-MinorVersion"
ANNOTATION_PATCH_VERSION = "service-meta-PatchVersion"
ANNOTATION_PROJECTS = "service-meta-Projects"
ANNOTATION_SERVICE_TYPE = "service-meta-ServiceType"
ANNOTATION_SOURCE_LINK = "service-meta-SourceLink"
| annotation_name = 'service-meta-Name'
annotation_description = 'service-meta-Description'
annotation_docs_link = 'service-meta-DocsLink'
annotation_environment = 'service-meta-Environment'
annotation_friendly_name = 'service-meta-FriendlyName'
annotation_icon_url = 'service-meta-IconURL'
annotation_major_version = 'service-meta-MajorVersion'
annotation_minor_version = 'service-meta-MinorVersion'
annotation_patch_version = 'service-meta-PatchVersion'
annotation_projects = 'service-meta-Projects'
annotation_service_type = 'service-meta-ServiceType'
annotation_source_link = 'service-meta-SourceLink' |
try:
fname = open("a.txt","r")
fname.write("hello world")
except:
print("Cannot write the contents to the file")
finally:
f.close()
print("File closed")
| try:
fname = open('a.txt', 'r')
fname.write('hello world')
except:
print('Cannot write the contents to the file')
finally:
f.close()
print('File closed') |
#
# PySNMP MIB module CISCO-SWITCH-RATE-LIMITER-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-SWITCH-RATE-LIMITER-CAPABILITY
# Produced by pysmi-0.3.4 at Wed May 1 12:13:38 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint")
ciscoAgentCapability, = mibBuilder.importSymbols("CISCO-SMI", "ciscoAgentCapability")
NotificationGroup, AgentCapabilities, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "AgentCapabilities", "ModuleCompliance")
MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, Integer32, iso, IpAddress, TimeTicks, MibIdentifier, Counter64, ModuleIdentity, NotificationType, ObjectIdentity, Unsigned32, Bits, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "Integer32", "iso", "IpAddress", "TimeTicks", "MibIdentifier", "Counter64", "ModuleIdentity", "NotificationType", "ObjectIdentity", "Unsigned32", "Bits", "Counter32")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
ciscoSwitchRateLimiterCapability = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 7, 606))
ciscoSwitchRateLimiterCapability.setRevisions(('2011-07-27 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: ciscoSwitchRateLimiterCapability.setRevisionsDescriptions(('Initial version of this MIB module.',))
if mibBuilder.loadTexts: ciscoSwitchRateLimiterCapability.setLastUpdated('201107270000Z')
if mibBuilder.loadTexts: ciscoSwitchRateLimiterCapability.setOrganization('Cisco Systems, Inc.')
if mibBuilder.loadTexts: ciscoSwitchRateLimiterCapability.setContactInfo('Cisco Systems Customer Service Postal: 170 West Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: cs-lan-switch-snmp@cisco.com')
if mibBuilder.loadTexts: ciscoSwitchRateLimiterCapability.setDescription('The capabilities description of CISCO-SWITCH-RATE-LIMITER-MIB.')
ciscoRateLimiterCapNxOSV05R0201PN7k = AgentCapabilities((1, 3, 6, 1, 4, 1, 9, 7, 606, 1))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoRateLimiterCapNxOSV05R0201PN7k = ciscoRateLimiterCapNxOSV05R0201PN7k.setProductRelease('Cisco NX-OS 5.2(1) on Nexus 7000\n series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoRateLimiterCapNxOSV05R0201PN7k = ciscoRateLimiterCapNxOSV05R0201PN7k.setStatus('current')
if mibBuilder.loadTexts: ciscoRateLimiterCapNxOSV05R0201PN7k.setDescription('CISCO-SWITCH-RATE-LIMITER-MIB capabilities.')
mibBuilder.exportSymbols("CISCO-SWITCH-RATE-LIMITER-CAPABILITY", PYSNMP_MODULE_ID=ciscoSwitchRateLimiterCapability, ciscoSwitchRateLimiterCapability=ciscoSwitchRateLimiterCapability, ciscoRateLimiterCapNxOSV05R0201PN7k=ciscoRateLimiterCapNxOSV05R0201PN7k)
| (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_range_constraint, constraints_union, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'SingleValueConstraint', 'ValueRangeConstraint', 'ConstraintsUnion', 'ValueSizeConstraint')
(cisco_agent_capability,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoAgentCapability')
(notification_group, agent_capabilities, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'AgentCapabilities', 'ModuleCompliance')
(mib_scalar, mib_table, mib_table_row, mib_table_column, gauge32, integer32, iso, ip_address, time_ticks, mib_identifier, counter64, module_identity, notification_type, object_identity, unsigned32, bits, counter32) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Gauge32', 'Integer32', 'iso', 'IpAddress', 'TimeTicks', 'MibIdentifier', 'Counter64', 'ModuleIdentity', 'NotificationType', 'ObjectIdentity', 'Unsigned32', 'Bits', 'Counter32')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
cisco_switch_rate_limiter_capability = module_identity((1, 3, 6, 1, 4, 1, 9, 7, 606))
ciscoSwitchRateLimiterCapability.setRevisions(('2011-07-27 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
ciscoSwitchRateLimiterCapability.setRevisionsDescriptions(('Initial version of this MIB module.',))
if mibBuilder.loadTexts:
ciscoSwitchRateLimiterCapability.setLastUpdated('201107270000Z')
if mibBuilder.loadTexts:
ciscoSwitchRateLimiterCapability.setOrganization('Cisco Systems, Inc.')
if mibBuilder.loadTexts:
ciscoSwitchRateLimiterCapability.setContactInfo('Cisco Systems Customer Service Postal: 170 West Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: cs-lan-switch-snmp@cisco.com')
if mibBuilder.loadTexts:
ciscoSwitchRateLimiterCapability.setDescription('The capabilities description of CISCO-SWITCH-RATE-LIMITER-MIB.')
cisco_rate_limiter_cap_nx_osv05_r0201_pn7k = agent_capabilities((1, 3, 6, 1, 4, 1, 9, 7, 606, 1))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_rate_limiter_cap_nx_osv05_r0201_pn7k = ciscoRateLimiterCapNxOSV05R0201PN7k.setProductRelease('Cisco NX-OS 5.2(1) on Nexus 7000\n series devices.')
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_rate_limiter_cap_nx_osv05_r0201_pn7k = ciscoRateLimiterCapNxOSV05R0201PN7k.setStatus('current')
if mibBuilder.loadTexts:
ciscoRateLimiterCapNxOSV05R0201PN7k.setDescription('CISCO-SWITCH-RATE-LIMITER-MIB capabilities.')
mibBuilder.exportSymbols('CISCO-SWITCH-RATE-LIMITER-CAPABILITY', PYSNMP_MODULE_ID=ciscoSwitchRateLimiterCapability, ciscoSwitchRateLimiterCapability=ciscoSwitchRateLimiterCapability, ciscoRateLimiterCapNxOSV05R0201PN7k=ciscoRateLimiterCapNxOSV05R0201PN7k) |
'''
520. Detect Capital
Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in this word is capital, like "Google".
Otherwise, we define that this word doesn't use capitals in a right way.
Example 1:
Input: "USA"
Output: True
Example 2:
Input: "FlaG"
Output: False
Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
'''
def detectCapitalUse(word):
# check if all caps
if word.isupper():
return True
# check if all lower
if word.islower():
return True
# if at least one character in the word
if len(word)>=1:
# if first character is upper
if word[0].isupper():
# check if the rest is lower
for i in range(1, len(word)):
if word[i].isupper():
return False
# if all is lower return true
else:
return True
# if first is not upper return false because all upper and all lower cheked above
else:
return False
print(detectCapitalUse("USA"))
print("USA*"*8)
print(detectCapitalUse("some words"))
print("some words*"*8)
print(detectCapitalUse("Right"))
print("Right*"*8)
print(detectCapitalUse("wrOng"))
print("wrOng*"*8)
print(detectCapitalUse("A"))
print("A*"*8)
print(detectCapitalUse("b"))
print("b*"*8)
print(detectCapitalUse(""))
| """
520. Detect Capital
Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in this word is capital, like "Google".
Otherwise, we define that this word doesn't use capitals in a right way.
Example 1:
Input: "USA"
Output: True
Example 2:
Input: "FlaG"
Output: False
Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
"""
def detect_capital_use(word):
if word.isupper():
return True
if word.islower():
return True
if len(word) >= 1:
if word[0].isupper():
for i in range(1, len(word)):
if word[i].isupper():
return False
else:
return True
else:
return False
print(detect_capital_use('USA'))
print('USA*' * 8)
print(detect_capital_use('some words'))
print('some words*' * 8)
print(detect_capital_use('Right'))
print('Right*' * 8)
print(detect_capital_use('wrOng'))
print('wrOng*' * 8)
print(detect_capital_use('A'))
print('A*' * 8)
print(detect_capital_use('b'))
print('b*' * 8)
print(detect_capital_use('')) |
#!/usr/bin/python3
# 2019-1-30
# Daniel Nicolas Gisolfi
lexemes = {
'TYPE': {
'priority': 0,
'pattern': r'^(int|string|boolean)$',
},
'BOOLEAN': {
'priority': 0,
'pattern':r'^(true|false)$',
},
'BOOL_OP':{
'priority': 2,
'pattern':r'^(!=|==)$',
},
'ADDITION_OP': {
'priority': 2,
'pattern': r'^\+$'
},
'WHILE': {
'priority': 0,
'pattern': r'^while$'
},
'PRINT': {
'priority': 0,
'pattern': r'^print$'
},
'ASSIGN_OP': {
'priority': 2,
'pattern': r'^=$'
},
'LEFT_PAREN': {
'priority': 2,
'pattern': r'^\($'
},
'RIGHT_PAREN': {
'priority': 2,
'pattern': r'^\)$'
},
'LEFT_BRACE': {
'priority': 2,
'pattern': r'^{$'
},
'RIGHT_BRACE': {
'priority': 2,
'pattern': r'^}$'
},
'DIGIT': {
'priority': 3,
'pattern': r'^\d$'
},
'CHAR': {
'priority': 4,
'pattern': r'^[a-z]{1}$'
},
'QUOTE': {
'priority': 2,
'pattern': r'^"$'
},
'ID': {
'priority': 1,
'pattern': r'^[a-z]$'
},
'EOP': {
'priority': 2,
'pattern': r'^\$$'
},
'IF': {
'priority': 0,
'pattern': r'^if$'
}
}
# Lexemes that will occur in the buffer rather than as a single char.
# They are sorted by length in descending order and seperate from
# the default lexeme list for effiecincy
buffer_lexemes = {
'ID': {
'pattern': r'^[a-z]',
'token': 'ID'
},
'DIGIT': {
'pattern': r'^\d',
'token': 'DIGIT'
},
'IF': {
'pattern': r'^if',
'token': 'IF',
'value': 'if'
},
'INT': {
'pattern': r'^int',
'token': 'TYPE',
'value': 'int'
},
'TRUE': {
'pattern': r'^true',
'token': 'BOOLEAN',
'value': 'true'
},
'FALSE': {
'pattern': r'^false',
'token': 'BOOLEAN',
'value': 'false'
},
'STRING': {
'pattern': r'^string',
'token': 'TYPE',
'value': 'string'
},
'WHILE': {
'pattern': r'^while',
'token': 'WHILE',
'value': 'while'
},
'PRINT': {
'pattern': r'^print',
'token': 'PRINT',
'value': 'print'
},
'BOOLEAN': {
'pattern': r'^boolean',
'token': 'TYPE',
'value': 'boolean'
}
} | lexemes = {'TYPE': {'priority': 0, 'pattern': '^(int|string|boolean)$'}, 'BOOLEAN': {'priority': 0, 'pattern': '^(true|false)$'}, 'BOOL_OP': {'priority': 2, 'pattern': '^(!=|==)$'}, 'ADDITION_OP': {'priority': 2, 'pattern': '^\\+$'}, 'WHILE': {'priority': 0, 'pattern': '^while$'}, 'PRINT': {'priority': 0, 'pattern': '^print$'}, 'ASSIGN_OP': {'priority': 2, 'pattern': '^=$'}, 'LEFT_PAREN': {'priority': 2, 'pattern': '^\\($'}, 'RIGHT_PAREN': {'priority': 2, 'pattern': '^\\)$'}, 'LEFT_BRACE': {'priority': 2, 'pattern': '^{$'}, 'RIGHT_BRACE': {'priority': 2, 'pattern': '^}$'}, 'DIGIT': {'priority': 3, 'pattern': '^\\d$'}, 'CHAR': {'priority': 4, 'pattern': '^[a-z]{1}$'}, 'QUOTE': {'priority': 2, 'pattern': '^"$'}, 'ID': {'priority': 1, 'pattern': '^[a-z]$'}, 'EOP': {'priority': 2, 'pattern': '^\\$$'}, 'IF': {'priority': 0, 'pattern': '^if$'}}
buffer_lexemes = {'ID': {'pattern': '^[a-z]', 'token': 'ID'}, 'DIGIT': {'pattern': '^\\d', 'token': 'DIGIT'}, 'IF': {'pattern': '^if', 'token': 'IF', 'value': 'if'}, 'INT': {'pattern': '^int', 'token': 'TYPE', 'value': 'int'}, 'TRUE': {'pattern': '^true', 'token': 'BOOLEAN', 'value': 'true'}, 'FALSE': {'pattern': '^false', 'token': 'BOOLEAN', 'value': 'false'}, 'STRING': {'pattern': '^string', 'token': 'TYPE', 'value': 'string'}, 'WHILE': {'pattern': '^while', 'token': 'WHILE', 'value': 'while'}, 'PRINT': {'pattern': '^print', 'token': 'PRINT', 'value': 'print'}, 'BOOLEAN': {'pattern': '^boolean', 'token': 'TYPE', 'value': 'boolean'}} |
# -*- coding: utf-8 -*-
def main():
low, high = list(map(int, input().split()))
n = int(input())
a = [int(input()) for _ in range(n)]
for ai in a:
if ai > high:
print(-1)
else:
print(max(0, low - ai))
if __name__ == '__main__':
main()
| def main():
(low, high) = list(map(int, input().split()))
n = int(input())
a = [int(input()) for _ in range(n)]
for ai in a:
if ai > high:
print(-1)
else:
print(max(0, low - ai))
if __name__ == '__main__':
main() |
'''A program to find the sum of all values in a dictionary!!'''
print("Program to find sum of all items in dictionary!!")
def toFindSum(myD):
s = 0
for i in myD.values():
s= s + i
print('Sum:{}'.format(s))
d = dict()
length = int(input('Enter the number of {key:value} pairs\n'))
for i in range(length):
Input = input('\nEnter the {key:value} pair\nThe input should be of the format key:value\n')
t = Input.split(':')
d[t[0]] = int(t[1])
toFindSum(d)
| """A program to find the sum of all values in a dictionary!!"""
print('Program to find sum of all items in dictionary!!')
def to_find_sum(myD):
s = 0
for i in myD.values():
s = s + i
print('Sum:{}'.format(s))
d = dict()
length = int(input('Enter the number of {key:value} pairs\n'))
for i in range(length):
input = input('\nEnter the {key:value} pair\nThe input should be of the format key:value\n')
t = Input.split(':')
d[t[0]] = int(t[1])
to_find_sum(d) |
class Node:
def __init__(self, id, neighbours):
self.id = id
self.neighbours = neighbours
self.visited = False
class Path:
def __init__(self, neighbours):
self.neighbours = neighbours
def dfs_recursive(node):
print('Node ', node.id)
node.visited = True
for next in node.neighbours:
dfs_recursive(next)
def dfs_open_list(start):
open_list = [start]
while open_list != []:
first, rest = open_list[0], open_list[1:]
if first.visited == True:
open_list = rest
else:
print('Node ', first.id)
first.visited = True
open_list = first.neighbours + rest
def bfs_open_list(start):
open_list = [start]
while open_list != []:
first, rest = open_list[0], open_list[1:]
if first.visited:
open_list = rest
else:
print('Node ', first.id)
first.visited = True
open_list = rest + first.neighbours
def dfs_stack(start):
stack = [None] * 10
stack[0] = start
stack_pointer = 0
while stack_pointer >= 0:
current = stack[stack_pointer]
stack_pointer -= 1
if not current.visited:
print('Node ', current.id)
current.visited = True
if current.neighbours != []:
for n in reversed(current.neighbours):
stack_pointer += 1
stack[stack_pointer] = n
def reset_tree():
global tree
tree = Node(1,
[Node(2,
[Node(3, []),
Node(4, [])]),
Node(5,
[Node(6, [])])])
print("Recursive Depth First Search")
reset_tree()
dfs_recursive(tree)
print("Iterative Depth First Search")
reset_tree()
dfs_open_list(tree)
print("Breadth First Search")
reset_tree()
bfs_open_list(tree)
print("Depth First Search with Stack")
reset_tree()
dfs_stack(tree)
| class Node:
def __init__(self, id, neighbours):
self.id = id
self.neighbours = neighbours
self.visited = False
class Path:
def __init__(self, neighbours):
self.neighbours = neighbours
def dfs_recursive(node):
print('Node ', node.id)
node.visited = True
for next in node.neighbours:
dfs_recursive(next)
def dfs_open_list(start):
open_list = [start]
while open_list != []:
(first, rest) = (open_list[0], open_list[1:])
if first.visited == True:
open_list = rest
else:
print('Node ', first.id)
first.visited = True
open_list = first.neighbours + rest
def bfs_open_list(start):
open_list = [start]
while open_list != []:
(first, rest) = (open_list[0], open_list[1:])
if first.visited:
open_list = rest
else:
print('Node ', first.id)
first.visited = True
open_list = rest + first.neighbours
def dfs_stack(start):
stack = [None] * 10
stack[0] = start
stack_pointer = 0
while stack_pointer >= 0:
current = stack[stack_pointer]
stack_pointer -= 1
if not current.visited:
print('Node ', current.id)
current.visited = True
if current.neighbours != []:
for n in reversed(current.neighbours):
stack_pointer += 1
stack[stack_pointer] = n
def reset_tree():
global tree
tree = node(1, [node(2, [node(3, []), node(4, [])]), node(5, [node(6, [])])])
print('Recursive Depth First Search')
reset_tree()
dfs_recursive(tree)
print('Iterative Depth First Search')
reset_tree()
dfs_open_list(tree)
print('Breadth First Search')
reset_tree()
bfs_open_list(tree)
print('Depth First Search with Stack')
reset_tree()
dfs_stack(tree) |
# 7. Lists
freinds = ["Pythobit","Boy"]
print(freinds[0]) # Output - Pythobit
print(len(freinds)) # Output - 2
freinds = [["Pythobit",20],["Boy",21]]
print(freinds[0][0]) # Output - Pythobit
print(freinds[1][1]) # Output - 21
freinds = ["Pythobit","Boy"]
freinds.append("Pythobit boy")
print(freinds) # Output - ["Pythobit", "Boy", "Pythobit boy"]
freinds = ["Pythobit","Boy","Pythobit boy"]
freinds.remove("Pythobit")
print(freinds) # Output - ['Boy', 'Pythobit boy']
| freinds = ['Pythobit', 'Boy']
print(freinds[0])
print(len(freinds))
freinds = [['Pythobit', 20], ['Boy', 21]]
print(freinds[0][0])
print(freinds[1][1])
freinds = ['Pythobit', 'Boy']
freinds.append('Pythobit boy')
print(freinds)
freinds = ['Pythobit', 'Boy', 'Pythobit boy']
freinds.remove('Pythobit')
print(freinds) |
filename = '/Users/andrew.meyers/Documents/andy/AdventOfCode2021/Day10/input.txt'
def parseInput(filename):
lines = []
with open(filename) as f:
for line in f:
lines.append(line)
return lines
def getPoints(line):
map = {')': 3, ']': 57, '}': 1197, '>': 25137}
stack = []
for c in line:
if c == '{' or c == '(' or c == '<' or c == '[':
stack.append(c)
else:
if len(stack) == 0:
return 0
l = stack.pop()
if (c == ')' and l != '(') or \
(c == '}' and l != '{') or \
(c == ']' and l != '[') or \
(c == '>' and l != '<'):
return map[c]
return 0
def getPointsForCorruptedLines(lines):
pts = 0
count = 0
for line in lines:
pt = getPoints(line)
if pt > 0:
count += 1
pts += pt
print(count)
return pts
def getAutoCompleteScore(line):
stack = []
for c in line:
if c == '\n':
continue
if c == '{' or c == '(' or c == '<' or c == '[':
stack.append(c)
else:
if len(stack) == 0:
return 0
l = stack.pop()
if (c == ')' and l != '(') or \
(c == '}' and l != '{') or \
(c == ']' and l != '[') or \
(c == '>' and l != '<'):
return 0
missingVal = {
'<': 4,
'{': 3,
'[': 2,
'(': 1
}
currentScore = 0
# we have leftovers
while len(stack) > 0:
l = stack.pop()
currentScore *= 5
currentScore += missingVal[l]
return currentScore
def getMiddleScoreForAutocomplete(lines):
scores = []
for line in lines:
score = getAutoCompleteScore(line)
if score > 0:
scores.append(score)
scores = sorted(scores)
print(len(scores))
idx = (len(scores) // 2)
print(idx)
return scores[idx]
test_lines = ['[({(<(())[]>[[{[]{<()<>>',
'[(()[<>])]({[<{<<[]>>(',
'{([(<{}[<>[]}>{[]{[(<()>',
'(((({<>}<{<{<>}{[]{[]{}',
'[[<[([]))<([[{}[[()]]]',
'[{[{({}]{}}([{[{{{}}([]',
'{<[[]]>}<{[{[{[]{()[[[]',
'[<(<(<(<{}))><([]([]()',
'<{([([[(<>()){}]>(<<{{',
'<{([{{}}[<[[[<>{}]]]>[]]']
if __name__ == '__main__':
isPart1 = False
lines = parseInput(filename)
if isPart1:
total = getPointsForCorruptedLines(lines)
print('The answer is:', total)
else:
total = getMiddleScoreForAutocomplete(lines)
print('The answer is:', total)
| filename = '/Users/andrew.meyers/Documents/andy/AdventOfCode2021/Day10/input.txt'
def parse_input(filename):
lines = []
with open(filename) as f:
for line in f:
lines.append(line)
return lines
def get_points(line):
map = {')': 3, ']': 57, '}': 1197, '>': 25137}
stack = []
for c in line:
if c == '{' or c == '(' or c == '<' or (c == '['):
stack.append(c)
else:
if len(stack) == 0:
return 0
l = stack.pop()
if c == ')' and l != '(' or (c == '}' and l != '{') or (c == ']' and l != '[') or (c == '>' and l != '<'):
return map[c]
return 0
def get_points_for_corrupted_lines(lines):
pts = 0
count = 0
for line in lines:
pt = get_points(line)
if pt > 0:
count += 1
pts += pt
print(count)
return pts
def get_auto_complete_score(line):
stack = []
for c in line:
if c == '\n':
continue
if c == '{' or c == '(' or c == '<' or (c == '['):
stack.append(c)
else:
if len(stack) == 0:
return 0
l = stack.pop()
if c == ')' and l != '(' or (c == '}' and l != '{') or (c == ']' and l != '[') or (c == '>' and l != '<'):
return 0
missing_val = {'<': 4, '{': 3, '[': 2, '(': 1}
current_score = 0
while len(stack) > 0:
l = stack.pop()
current_score *= 5
current_score += missingVal[l]
return currentScore
def get_middle_score_for_autocomplete(lines):
scores = []
for line in lines:
score = get_auto_complete_score(line)
if score > 0:
scores.append(score)
scores = sorted(scores)
print(len(scores))
idx = len(scores) // 2
print(idx)
return scores[idx]
test_lines = ['[({(<(())[]>[[{[]{<()<>>', '[(()[<>])]({[<{<<[]>>(', '{([(<{}[<>[]}>{[]{[(<()>', '(((({<>}<{<{<>}{[]{[]{}', '[[<[([]))<([[{}[[()]]]', '[{[{({}]{}}([{[{{{}}([]', '{<[[]]>}<{[{[{[]{()[[[]', '[<(<(<(<{}))><([]([]()', '<{([([[(<>()){}]>(<<{{', '<{([{{}}[<[[[<>{}]]]>[]]']
if __name__ == '__main__':
is_part1 = False
lines = parse_input(filename)
if isPart1:
total = get_points_for_corrupted_lines(lines)
print('The answer is:', total)
else:
total = get_middle_score_for_autocomplete(lines)
print('The answer is:', total) |
# =============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 11052.py
# Description: UVa Online Judge - 11052
# =============================================================================
while True:
N = int(input())
if N == 0:
break
A = []
year = []
dp = []
for i in range(N):
tt, num, keep = input().split()
time_tuple = list(map(int, tt.split(":")))
A.append((time_tuple, keep))
year.append(-1)
dp.append(-1)
year[-1] = 0
for i in range(N - 2, -1, -1):
next_t = A[i + 1][0]
curr_t = A[i][0]
if curr_t < next_t:
year[i] = year[i + 1]
else:
year[i] = year[i + 1] - 1
# initialization
last = -1
earliest = -1
for i in range(N - 1, -1, -1):
if last == -1 and year[i] == 0:
dp[i] = 1
else:
dp[i] = N - i
if last == -1 and (A[i][1] == "+" or year[i] != 0):
last = i
if A[i][1] == "+":
earliest = i
for i in range(last, earliest - 1, -1):
for j in range(i + 1, N):
if year[i] == year[j]:
dp[i] = min(dp[i], dp[j] + 1)
elif A[i][0] >= A[j][0] and year[i] + 1 == year[j]:
dp[i] = min(dp[i], dp[j] + 1)
else:
break
if A[j][1] == "+":
break
print(dp[earliest])
| while True:
n = int(input())
if N == 0:
break
a = []
year = []
dp = []
for i in range(N):
(tt, num, keep) = input().split()
time_tuple = list(map(int, tt.split(':')))
A.append((time_tuple, keep))
year.append(-1)
dp.append(-1)
year[-1] = 0
for i in range(N - 2, -1, -1):
next_t = A[i + 1][0]
curr_t = A[i][0]
if curr_t < next_t:
year[i] = year[i + 1]
else:
year[i] = year[i + 1] - 1
last = -1
earliest = -1
for i in range(N - 1, -1, -1):
if last == -1 and year[i] == 0:
dp[i] = 1
else:
dp[i] = N - i
if last == -1 and (A[i][1] == '+' or year[i] != 0):
last = i
if A[i][1] == '+':
earliest = i
for i in range(last, earliest - 1, -1):
for j in range(i + 1, N):
if year[i] == year[j]:
dp[i] = min(dp[i], dp[j] + 1)
elif A[i][0] >= A[j][0] and year[i] + 1 == year[j]:
dp[i] = min(dp[i], dp[j] + 1)
else:
break
if A[j][1] == '+':
break
print(dp[earliest]) |
def largest_exponential(file):
text_file = open(file, "r")
lines = text_file.read().splitlines()
greatest = 0
count = 0
split_list = []
for elem in lines:
seperated = elem.split(',')
split_list.append(seperated)
for i in range(0, len(split_list)):
count += 1
base = int(split_list[i][0])
exp = float(split_list[i][1][:-len(split_list[i][1]) + 1] + "." + split_list[i][1][-len(split_list[i][1]) + 1:])
result = base ** exp
if result > greatest:
greatest = result
new_list = [base, exp, count]
return new_list
print(largest_exponential("Additional Files/p099_base_exp.txt"))
| def largest_exponential(file):
text_file = open(file, 'r')
lines = text_file.read().splitlines()
greatest = 0
count = 0
split_list = []
for elem in lines:
seperated = elem.split(',')
split_list.append(seperated)
for i in range(0, len(split_list)):
count += 1
base = int(split_list[i][0])
exp = float(split_list[i][1][:-len(split_list[i][1]) + 1] + '.' + split_list[i][1][-len(split_list[i][1]) + 1:])
result = base ** exp
if result > greatest:
greatest = result
new_list = [base, exp, count]
return new_list
print(largest_exponential('Additional Files/p099_base_exp.txt')) |
items = ["Clothes", "phones", "laptops", "Chocolates"]
if __name__ == "__main__":
while True:
try:
for index in range(0,len(items)):
print(f"{index} ")
option = int(input("Enter the number of your choice to get gift: "))
print(f"You have choosen {items[option]}")
except ValueError as ve:
print("Enter the choice of getting gift in numbers")
print(ve)
except IndexError as ie:
print(f"Enter valid number choice ranging from 0 to {len(items)-1}")
except Exception as e:
print(f"Unknown Error occured {e}")
else:
print("Thank god no errors")
finally:
choice = input('Do you want to Continue Enter y for yes and n for no: ')
if choice == 'n':
break
| items = ['Clothes', 'phones', 'laptops', 'Chocolates']
if __name__ == '__main__':
while True:
try:
for index in range(0, len(items)):
print(f'{index} ')
option = int(input('Enter the number of your choice to get gift: '))
print(f'You have choosen {items[option]}')
except ValueError as ve:
print('Enter the choice of getting gift in numbers')
print(ve)
except IndexError as ie:
print(f'Enter valid number choice ranging from 0 to {len(items) - 1}')
except Exception as e:
print(f'Unknown Error occured {e}')
else:
print('Thank god no errors')
finally:
choice = input('Do you want to Continue Enter y for yes and n for no: ')
if choice == 'n':
break |
# accept an integer and print the digits in reverse
n = int(input("Enter a positive integer: "))
print()
while (n!=0):
digit = n % 10 # extract the last digit
print(digit) # print the last digit
n = n // 10 # remove the last digit
'''
123 / 10
q = 12
r = 3
456 / 10
q = 45
r = 6
q = dividend // divisor
r = dividend % divisor
In case of quotient calculation, where the divisor is 10, the quotient is the number formed by removing the last digit.
In case of remainder calculation, where the divisor is 10, the remainder is the last digit.
'''
'''
In our above example, the loop is executed for every digit in the number. That means that the loop is not fixed, and depends on the input from the user. In such cases, where the loop is not fixed, we can use a while loop.
''' | n = int(input('Enter a positive integer: '))
print()
while n != 0:
digit = n % 10
print(digit)
n = n // 10
'\n\n123 / 10\n\nq = 12\nr = 3\n\n456 / 10\n\nq = 45\nr = 6\n\nq = dividend // divisor\nr = dividend % divisor\n\nIn case of quotient calculation, where the divisor is 10, the quotient is the number formed by removing the last digit.\nIn case of remainder calculation, where the divisor is 10, the remainder is the last digit.\n'
'\nIn our above example, the loop is executed for every digit in the number. That means that the loop is not fixed, and depends on the input from the user. In such cases, where the loop is not fixed, we can use a while loop.\n' |
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2016, 2017
class DataAlreadyExistsError(RuntimeError):
def __init__(self, label):
self.message = str("Data with label '%s' already exists and cannot be added" % (label))
def get_patient_id(d):
return d['patient']['identifier']
def get_index_by_label(d, label):
for idx in range(len(d['data'])):
if d['data'][idx]['label'] == label:
return idx
return None
def get_sampled_data_values(d, label):
idx = get_index_by_label(d, label)
return d['data'][idx]['valueSampledData']['values']
def get_coordinate_data_values(d, label):
idx = get_index_by_label(d, label)
return d['data'][idx]['valueCoordinateData']['values']
def get_period_value(d, label):
idx = get_index_by_label(d, label)
return d['data'][idx]['valueSampledData']['period']['value']
def get_sampled_data_unit(d, label):
idx = get_index_by_label(d, label)
return d['data'][idx]['valueSampledData']['unit']
def get_period_unit(d, label):
idx = get_index_by_label(d, label)
return d['data'][idx]['valueSampledData']['period']['unit']
def get_gain(d, label):
idx = get_index_by_label(d, label)
return d['data'][idx]['valueSampledData']['gain']
def get_initValue(d, label):
idx = get_index_by_label(d, label)
return d['data'][idx]['valueSampledData']['initVal']
def get_patient_ID(d):
return d['patient']['identifier']
def add_sampled_data(d, label, sampled_data, period_value, period_unit, update_if_exists=False):
# check if label already exists
data_idx = get_index_by_label(d, label)
if data_idx is not None:
if update_if_exists == True:
v = {'valuesSampledData' : { 'values' : sampled_data, 'period' : { 'value' : period_value, 'unit' : period_unit }}}
d['data'][data_idx] = v
else:
raise DataAlreadyExistsError(label=label)
else:
v = {'label' : label, 'valuesSampledData' : { 'values' : sampled_data, 'period' : { 'value' : period_value, 'unit' : period_unit }}}
d['data'].append(v)
def add_coordinate_data(d, label, coords, replace_if_exists=False):
data_idx = get_index_by_label(d, label)
if data_idx is not None:
if replace_if_exists == True:
v = {'valueCoordinateData' : {'values' : coords}}
d['data'][data_idx] = v
else:
raise DataAlreadyExistsError(label=label)
else:
v = {'label' : label, 'valueCoordinateData' : {'values' : coords}}
d['data'].append(v)
| class Dataalreadyexistserror(RuntimeError):
def __init__(self, label):
self.message = str("Data with label '%s' already exists and cannot be added" % label)
def get_patient_id(d):
return d['patient']['identifier']
def get_index_by_label(d, label):
for idx in range(len(d['data'])):
if d['data'][idx]['label'] == label:
return idx
return None
def get_sampled_data_values(d, label):
idx = get_index_by_label(d, label)
return d['data'][idx]['valueSampledData']['values']
def get_coordinate_data_values(d, label):
idx = get_index_by_label(d, label)
return d['data'][idx]['valueCoordinateData']['values']
def get_period_value(d, label):
idx = get_index_by_label(d, label)
return d['data'][idx]['valueSampledData']['period']['value']
def get_sampled_data_unit(d, label):
idx = get_index_by_label(d, label)
return d['data'][idx]['valueSampledData']['unit']
def get_period_unit(d, label):
idx = get_index_by_label(d, label)
return d['data'][idx]['valueSampledData']['period']['unit']
def get_gain(d, label):
idx = get_index_by_label(d, label)
return d['data'][idx]['valueSampledData']['gain']
def get_init_value(d, label):
idx = get_index_by_label(d, label)
return d['data'][idx]['valueSampledData']['initVal']
def get_patient_id(d):
return d['patient']['identifier']
def add_sampled_data(d, label, sampled_data, period_value, period_unit, update_if_exists=False):
data_idx = get_index_by_label(d, label)
if data_idx is not None:
if update_if_exists == True:
v = {'valuesSampledData': {'values': sampled_data, 'period': {'value': period_value, 'unit': period_unit}}}
d['data'][data_idx] = v
else:
raise data_already_exists_error(label=label)
else:
v = {'label': label, 'valuesSampledData': {'values': sampled_data, 'period': {'value': period_value, 'unit': period_unit}}}
d['data'].append(v)
def add_coordinate_data(d, label, coords, replace_if_exists=False):
data_idx = get_index_by_label(d, label)
if data_idx is not None:
if replace_if_exists == True:
v = {'valueCoordinateData': {'values': coords}}
d['data'][data_idx] = v
else:
raise data_already_exists_error(label=label)
else:
v = {'label': label, 'valueCoordinateData': {'values': coords}}
d['data'].append(v) |
#
# @lc app=leetcode id=202 lang=python3
#
# [202] Happy Number
#
# @lc code=start
# class Solution:
# def isHappy(self, n: int):
# appeared = {}
# while True:
# s = 0
# while n > 0:
# s += (n % 10) * (n % 10)
# n = n//10
# if s == 1:
# return True
# else:
# if s not in appeared:
# appeared[s] = True
# n = s
# else:
# return False
class Solution:
def isHappy(self, n):
visited = set()
re = self.helper(n, visited)
return re
def helper(self, n, visited):
s = 0
while n > 0:
s = s + (n%10) ** 2
n = n//10
if s == 1:
return True
elif s in visited:
return False
else:
visited.add(s)
return self.helper(s, visited)
if __name__ == '__main__':
a = Solution()
b = a.isHappy(68)
print(b)
# @lc code=end
| class Solution:
def is_happy(self, n):
visited = set()
re = self.helper(n, visited)
return re
def helper(self, n, visited):
s = 0
while n > 0:
s = s + (n % 10) ** 2
n = n // 10
if s == 1:
return True
elif s in visited:
return False
else:
visited.add(s)
return self.helper(s, visited)
if __name__ == '__main__':
a = solution()
b = a.isHappy(68)
print(b) |
# capture discord_id to validate
@bot.command(pass_context=True)
async def example(ctx):
get_discord_id = ctx.message.author.id
user = await bot.get_user_info(get_discord_id)
print(get_discord_id)
# get username and unique ID from discord user that uses the command
@bot.command(pass_context=True)
async def getinfo(ctx, vote):
getMemberID = ctx.message.author.id
getMemberName = ctx.message.author.name
print (getMemberID)
print (getMemberName)
| @bot.command(pass_context=True)
async def example(ctx):
get_discord_id = ctx.message.author.id
user = await bot.get_user_info(get_discord_id)
print(get_discord_id)
@bot.command(pass_context=True)
async def getinfo(ctx, vote):
get_member_id = ctx.message.author.id
get_member_name = ctx.message.author.name
print(getMemberID)
print(getMemberName) |
values = [23,52,59,37,48]
sum = 0
length = 10
for value in values:
sum+=value
length+=1
print("Total sum:"+str(sum)+"-Average: " + str(sum/length))
| values = [23, 52, 59, 37, 48]
sum = 0
length = 10
for value in values:
sum += value
length += 1
print('Total sum:' + str(sum) + '-Average: ' + str(sum / length)) |
class Solution:
# kind of dynamic programming?
def fib(self, N):
prepared_numbers = [0, 1, 1, 2, 3, 5, 8, 13]
if N <= len(prepared_numbers) - 1:
return prepared_numbers[N]
else:
for i in range(N - len(prepared_numbers) + 1):
prepared_numbers.append(prepared_numbers[-2] + prepared_numbers[-1])
return prepared_numbers[-1]
| class Solution:
def fib(self, N):
prepared_numbers = [0, 1, 1, 2, 3, 5, 8, 13]
if N <= len(prepared_numbers) - 1:
return prepared_numbers[N]
else:
for i in range(N - len(prepared_numbers) + 1):
prepared_numbers.append(prepared_numbers[-2] + prepared_numbers[-1])
return prepared_numbers[-1] |
try:
num = int(input('Enter a number: '))
except Exception:
print('Some input error')
def convert_to_binary(num):
if num > 1:
convert_to_binary(num // 2)
print(num % 2, end = '')
print('Binary: ', end = '')
convert_to_binary(num) | try:
num = int(input('Enter a number: '))
except Exception:
print('Some input error')
def convert_to_binary(num):
if num > 1:
convert_to_binary(num // 2)
print(num % 2, end='')
print('Binary: ', end='')
convert_to_binary(num) |
# from .disalexi import Image
# from .landsat import Landsat
__version__ = "0.0.3"
| __version__ = '0.0.3' |
# Definir excepciones en Python
class Err(Exception):
def __init__(self,valor):
print("Fue el error por",valor)
try:
raise Err(4)
except Err:
print("Error escrito:")
| class Err(Exception):
def __init__(self, valor):
print('Fue el error por', valor)
try:
raise err(4)
except Err:
print('Error escrito:') |
# Define the class as author
class Author:
# The function is in it and the __ is a special function in python. properties in the brackets are what
# is being passed in the function
def __init__(self, name, firstName, nationality):
# Define the attributes in the class
self.name = name
self.firstName = firstName
self.nationality = nationality
| class Author:
def __init__(self, name, firstName, nationality):
self.name = name
self.firstName = firstName
self.nationality = nationality |
db = {
"users": [
{
"id": 2,
"username": "marceline",
"name": "Marceline Abadeer",
"bio": "1000 year old vampire queen, musician"
}
],
"threads": [
{
"id": 2,
"title": "What's up with the Lich?",
"createdBy": 2
}
],
"posts": [
{
"thread": 2,
"text": "Has anyone checked on the lich recently?",
"user": 2
}
]
}
db_more = {
"users": [
{
"id": 1,
"username": "marceline",
"name": "Marceline Abadeer",
"bio": "1000 year old vampire queen, musician"
},
{
"id": 2,
"username": "finn",
"name": "Finn 'the Human' Mertens",
"bio": "Adventurer and hero, last human, defender of good"
},
{
"id": 3,
"username": "pb",
"name": "Bonnibel Bubblegum",
"bio": "Scientist, bearer of candy power, ruler of the candy kingdom"
}
],
"threads": [
{
"id": 1,
"title": "What's up with the Lich?",
"createdBy": 4
},
{
"id": 2,
"title": "Party at the candy kingdom tomorrow",
"createdBy": 3
},
{
"id": 3,
"title": "In search of a new guitar",
"createdBy": 1
}
],
"posts": [
{
"thread": 1,
"text": "Has anyone checked on the lich recently?",
"user": 4
},
{
"thread": 1,
"text": "I'll stop by and see how he's doing tomorrow!",
"user": 2
},
{
"thread": 2,
"text": "Come party with the candy people tomorrow!",
"user": 3
}
]
}
| db = {'users': [{'id': 2, 'username': 'marceline', 'name': 'Marceline Abadeer', 'bio': '1000 year old vampire queen, musician'}], 'threads': [{'id': 2, 'title': "What's up with the Lich?", 'createdBy': 2}], 'posts': [{'thread': 2, 'text': 'Has anyone checked on the lich recently?', 'user': 2}]}
db_more = {'users': [{'id': 1, 'username': 'marceline', 'name': 'Marceline Abadeer', 'bio': '1000 year old vampire queen, musician'}, {'id': 2, 'username': 'finn', 'name': "Finn 'the Human' Mertens", 'bio': 'Adventurer and hero, last human, defender of good'}, {'id': 3, 'username': 'pb', 'name': 'Bonnibel Bubblegum', 'bio': 'Scientist, bearer of candy power, ruler of the candy kingdom'}], 'threads': [{'id': 1, 'title': "What's up with the Lich?", 'createdBy': 4}, {'id': 2, 'title': 'Party at the candy kingdom tomorrow', 'createdBy': 3}, {'id': 3, 'title': 'In search of a new guitar', 'createdBy': 1}], 'posts': [{'thread': 1, 'text': 'Has anyone checked on the lich recently?', 'user': 4}, {'thread': 1, 'text': "I'll stop by and see how he's doing tomorrow!", 'user': 2}, {'thread': 2, 'text': 'Come party with the candy people tomorrow!', 'user': 3}]} |
class Node:
def __init__(self, data=None):
self.val = data
self.next = None
class LinkedList:
def __init__(self):
self.head=None
def push(self,val):
new_node=Node(val)
#case 1
if self.head is None:
self.head=new_node
self.head.next=None
return
temp=self.head
while temp.next is not None:
temp=temp.next
temp.next=new_node
new_node.next=None
LinkedList.push=push
def __str__(self):
re_str="["
temp=self.head
while temp is not None:
re_str+=" "+str(temp.val) + " ,"
temp=temp.next
re_str=re_str.rstrip(",")
re_str+="]"
return re_str
LinkedList.__str__=__str__
def pop(self):
#case 1
if self.head is None:
raise IndexError("list cannot be pop, : because list is empty")
#case 2
if self.head.next is None:
val=self.head.val
self.head=None
return val
temp=self.head
while temp.next is not None:
pre=temp
temp=temp.next
val=temp.val
pre.next=None
return val
LinkedList.pop=pop
def insert(self,index,val):
new_node=Node(val)
if index==0:
new_node.next=self.head
self.head=new_node
return
count=0
temp=self.head
while temp is not None and count<index:
pre=temp
temp=temp.next
count+=1
pre.next=new_node
new_node.next=temp
LinkedList.insert=insert
def remove_at(self,index):
if index>self.len():
raise IndexError("list index out of Range ")
if index==0:
self.head=self.head.next
return
if self.head is None:
raise IndexError("Cannot be remove because list is empty")
count=0
temp=self.head
# remove funtion must be temp not the temp.next remember!!!!
while temp is not None and count<index:
pre=temp
temp=temp.next
count+=1
pre.next=temp.next
LinkedList.remove_at=remove_at
def len(self):
if self.head is None:
return 0
temp=self.head
count=0
while temp is not None:
temp=temp.next
count+=1
return count
LinkedList.len=len
def remove(self,val):
if self.head is None:
raise IndexError(" Cannot be removed becaus list is empty ")
if self.head.val ==val:
self.head=self.head.next
return
if self.head.next is None:
if self.head.val==val:
self.head=None
return
temp=self.head
while temp.next is not None:
pre=temp
temp=temp.next
if temp.val==val:
break
else:
return
pre.next=temp.next
return
LinkedList.remove=remove
def reverse_list(self):
pre = None
current = self.head
while current is not None:
next = current.next
current.next = pre
pre = current
current = next
self.head = pre
LinkedList.reverse_list=reverse_list
if __name__ == '__main__':
l = LinkedList()
l.push(1)
l.push(2)
l.push(3)
print(l)
l.reverse_list()
print(l)
| class Node:
def __init__(self, data=None):
self.val = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def push(self, val):
new_node = node(val)
if self.head is None:
self.head = new_node
self.head.next = None
return
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = new_node
new_node.next = None
LinkedList.push = push
def __str__(self):
re_str = '['
temp = self.head
while temp is not None:
re_str += ' ' + str(temp.val) + ' ,'
temp = temp.next
re_str = re_str.rstrip(',')
re_str += ']'
return re_str
LinkedList.__str__ = __str__
def pop(self):
if self.head is None:
raise index_error('list cannot be pop, : because list is empty')
if self.head.next is None:
val = self.head.val
self.head = None
return val
temp = self.head
while temp.next is not None:
pre = temp
temp = temp.next
val = temp.val
pre.next = None
return val
LinkedList.pop = pop
def insert(self, index, val):
new_node = node(val)
if index == 0:
new_node.next = self.head
self.head = new_node
return
count = 0
temp = self.head
while temp is not None and count < index:
pre = temp
temp = temp.next
count += 1
pre.next = new_node
new_node.next = temp
LinkedList.insert = insert
def remove_at(self, index):
if index > self.len():
raise index_error('list index out of Range ')
if index == 0:
self.head = self.head.next
return
if self.head is None:
raise index_error('Cannot be remove because list is empty')
count = 0
temp = self.head
while temp is not None and count < index:
pre = temp
temp = temp.next
count += 1
pre.next = temp.next
LinkedList.remove_at = remove_at
def len(self):
if self.head is None:
return 0
temp = self.head
count = 0
while temp is not None:
temp = temp.next
count += 1
return count
LinkedList.len = len
def remove(self, val):
if self.head is None:
raise index_error(' Cannot be removed becaus list is empty ')
if self.head.val == val:
self.head = self.head.next
return
if self.head.next is None:
if self.head.val == val:
self.head = None
return
temp = self.head
while temp.next is not None:
pre = temp
temp = temp.next
if temp.val == val:
break
else:
return
pre.next = temp.next
return
LinkedList.remove = remove
def reverse_list(self):
pre = None
current = self.head
while current is not None:
next = current.next
current.next = pre
pre = current
current = next
self.head = pre
LinkedList.reverse_list = reverse_list
if __name__ == '__main__':
l = linked_list()
l.push(1)
l.push(2)
l.push(3)
print(l)
l.reverse_list()
print(l) |
def crossingSum(matrix, a, b):
return sum(matrix[a]) + sum([x[b] for i, x in enumerate(matrix) if i != a])
if __name__ == '__main__':
input0 = [[[1,1,1,1], [2,2,2,2], [3,3,3,3]], [[1,1], [1,1]], [[1,1], [3,3], [1,1], [2,2]], [[100]], [[1,2], [3,4]], [[1,2,3,4]], [[1,2,3,4,5], [1,2,2,2,2], [1,2,2,2,2], [1,2,2,2,2], [1,2,2,2,2], [1,2,2,2,2], [1,2,2,2,2]]]
input1 = [1, 0, 3, 0, 1, 0, 1]
input2 = [3, 0, 0, 0, 1, 3, 1]
expectedOutput = [12, 3, 9, 100, 9, 10, 21]
assert len(input0) == len(expectedOutput), '# input0 = {}, # expectedOutput = {}'.format(len(input0), len(expectedOutput))
assert len(input1) == len(expectedOutput), '# input1 = {}, # expectedOutput = {}'.format(len(input1), len(expectedOutput))
assert len(input2) == len(expectedOutput), '# input2 = {}, # expectedOutput = {}'.format(len(input2), len(expectedOutput))
for i, expected in enumerate(expectedOutput):
actual = crossingSum(input0[i], input1[i], input2[i])
assert actual == expected, 'crossingSum({}, {}, {}) returned {}, but expected {}'.format(input0[i], input1[i], input2[i], actual, expected)
print('PASSES {} out of {} tests'.format(len(expectedOutput), len(expectedOutput))) | def crossing_sum(matrix, a, b):
return sum(matrix[a]) + sum([x[b] for (i, x) in enumerate(matrix) if i != a])
if __name__ == '__main__':
input0 = [[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]], [[1, 1], [1, 1]], [[1, 1], [3, 3], [1, 1], [2, 2]], [[100]], [[1, 2], [3, 4]], [[1, 2, 3, 4]], [[1, 2, 3, 4, 5], [1, 2, 2, 2, 2], [1, 2, 2, 2, 2], [1, 2, 2, 2, 2], [1, 2, 2, 2, 2], [1, 2, 2, 2, 2], [1, 2, 2, 2, 2]]]
input1 = [1, 0, 3, 0, 1, 0, 1]
input2 = [3, 0, 0, 0, 1, 3, 1]
expected_output = [12, 3, 9, 100, 9, 10, 21]
assert len(input0) == len(expectedOutput), '# input0 = {}, # expectedOutput = {}'.format(len(input0), len(expectedOutput))
assert len(input1) == len(expectedOutput), '# input1 = {}, # expectedOutput = {}'.format(len(input1), len(expectedOutput))
assert len(input2) == len(expectedOutput), '# input2 = {}, # expectedOutput = {}'.format(len(input2), len(expectedOutput))
for (i, expected) in enumerate(expectedOutput):
actual = crossing_sum(input0[i], input1[i], input2[i])
assert actual == expected, 'crossingSum({}, {}, {}) returned {}, but expected {}'.format(input0[i], input1[i], input2[i], actual, expected)
print('PASSES {} out of {} tests'.format(len(expectedOutput), len(expectedOutput))) |
r,x,y,z=open("ads\\1Plumber\\Ad.txt").read().split("\n", 3)
print(y)
| (r, x, y, z) = open('ads\\1Plumber\\Ad.txt').read().split('\n', 3)
print(y) |
# 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()) |
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) |
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) |
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 -*-
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'] |
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 |
## 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)) |
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 |
#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) |
# 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 |
__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 |
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) |
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() |
{
"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 |
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() |
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 |
#!/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')] |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.