content stringlengths 7 1.05M |
|---|
def m2f_e(s, st):
return [[st.index(ch), st.insert(0, st.pop(st.index(ch)))][0] for ch in s]
def m2f_d(sq, st):
return ''.join([st[i], st.insert(0, st.pop(i))][0] for i in sq)
ST = list('abcdefghijklmnopqrstuvwxyz')
for s in ['broood', 'bananaaa', 'hiphophiphop']:
encode = m2f_e(s, ST[::])
print('%14r encodes to %r' % (s, encode), end=', ')
decode = m2f_d(encode, ST[::])
print('decodes back to %r' % decode)
assert s == decode, 'Whoops!'
|
'''
堆是特殊空间的有顺序的完全二叉树,root是最大值的是大顶堆,其他未小顶堆
堆:数据流中的第K大(小)问题
'''
|
def get_pyenv_root():
return "/usr/local/pyenv"
def get_user():
return "root"
def get_group():
return "root"
def get_rc_file():
return "/etc/profile.d/pyenv.sh"
def get_python_test_case():
return "3.9.0", True
def get_venv_test_case():
return "neovim", True
|
# https://www.hackerrank.com/challenges/30-testing/forum/comments/138775
print("5")
print("5 3\n-1 90 999 100 0")
print("4 2\n0 -1 2 1")
print("3 3\n-1 0 1")
print("6 1\n-1 0 1 -1 2 3")
print("7 3\n-1 0 1 2 3 4 5")
|
def inorde_tree_walk(self, vertice = None):
if(self.raiz == None): #arvore vazia
return
if(verice == None): #Por padrao comeca pela raiz
vertice = self.raiz
if(vertice.left != None): #Decomposicao
self.inorde_tree_walk(vertice = vertice.left)
print(vertice)
if(vertice.right != None): #Decomposicao
self.inorde_tree_walk(vertice = vertice.right) |
#
# PySNMP MIB module HM2-DHCPS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HM2-DHCPS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:31:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint")
HmEnabledStatus, hm2ConfigurationMibs = mibBuilder.importSymbols("HM2-TC-MIB", "HmEnabledStatus", "hm2ConfigurationMibs")
InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Counter32, Bits, Unsigned32, ModuleIdentity, ObjectIdentity, Counter64, Integer32, iso, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, IpAddress, Gauge32, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "Bits", "Unsigned32", "ModuleIdentity", "ObjectIdentity", "Counter64", "Integer32", "iso", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "IpAddress", "Gauge32", "NotificationType")
TextualConvention, RowStatus, DisplayString, MacAddress = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "RowStatus", "DisplayString", "MacAddress")
hm2DhcpsMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 248, 11, 91))
hm2DhcpsMib.setRevisions(('2012-03-16 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: hm2DhcpsMib.setRevisionsDescriptions(('Initial version.',))
if mibBuilder.loadTexts: hm2DhcpsMib.setLastUpdated('201203160000Z')
if mibBuilder.loadTexts: hm2DhcpsMib.setOrganization('Hirschmann Automation and Control GmbH')
if mibBuilder.loadTexts: hm2DhcpsMib.setContactInfo('Postal: Stuttgarter Str. 45-51 72654 Neckartenzlingen Germany Phone: +49 7127 140 E-mail: hac.support@belden.com')
if mibBuilder.loadTexts: hm2DhcpsMib.setDescription('Hirschmann DHCP server MIB. Copyright (C) 2012. All Rights Reserved.')
hm2DHCPServerMibNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 91, 0))
hm2DHCPServerMibObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 91, 1))
hm2DHCPServerSNMPExtensionGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 91, 3))
hm2DHCPServerGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1))
hm2DHCPServerConfigGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1))
hm2DHCPServerLeaseGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 2))
hm2DHCPServerInterfaceGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 3))
hm2DHCPServerCounterGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4))
hm2DHCPServerMode = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 1), HmEnabledStatus().clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2DHCPServerMode.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerMode.setDescription('Enable or disable DHCP server global.')
hm2DHCPServerMaxPoolEntries = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 2), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerMaxPoolEntries.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerMaxPoolEntries.setDescription('Maximum possible entries in hm2DHCPServerPoolTable.')
hm2DHCPServerMaxLeaseEntries = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 3), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerMaxLeaseEntries.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerMaxLeaseEntries.setDescription('Maximum possible entries in hm2DHCPServerLeaseTable.')
hm2DHCPServerPoolTable = MibTable((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5), )
if mibBuilder.loadTexts: hm2DHCPServerPoolTable.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolTable.setDescription('A table containing the DHCP server pools.')
hm2DHCPServerPoolEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1), ).setIndexNames((0, "HM2-DHCPS-MIB", "hm2DHCPServerPoolIndex"))
if mibBuilder.loadTexts: hm2DHCPServerPoolEntry.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolEntry.setDescription('A logical row in the hm2DHCPServerPoolTable.')
hm2DHCPServerPoolIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerPoolIndex.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolIndex.setDescription('The index of hm2DHCPServerPoolTable.')
hm2DHCPServerPoolStartIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 2), IpAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolStartIpAddress.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolStartIpAddress.setDescription('The IPv4 address of the first address in the range. The value of hm2DHCPServerPoolStartIpAddress MUST be less than or equal to the value of hm2DHCPServerPoolEndIpAddress.')
hm2DHCPServerPoolEndIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 3), IpAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolEndIpAddress.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolEndIpAddress.setDescription('The IPv4 address of the last address in the range. The value of hm2DHCPServerPoolEndIpAddress MUST be greater than or equal to the value of hm2DHCPServerPoolStartIpAddress.')
hm2DHCPServerPoolLeaseTime = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 4), Unsigned32().clone(86400)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolLeaseTime.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolLeaseTime.setDescription("The pools lease time in number of seconds. A value of 4294967295 SHOULD be used for leases that have a lease time which is 'infinite' and for BOOTP leases.")
hm2DHCPServerPoolFlags = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 5), Bits().clone(namedValues=NamedValues(("interface", 0), ("mac", 1), ("gateway", 2), ("clientid", 3), ("remoteid", 4), ("circuitid", 5), ("dynamic", 6), ("vlanid", 7)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolFlags.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolFlags.setDescription('This object shows the parameters that are used to lease the IP Address.')
hm2DHCPServerPoolIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 6), Integer32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolIfIndex.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolIfIndex.setDescription('The index of the interface.')
hm2DHCPServerPoolMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 7), MacAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolMacAddress.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolMacAddress.setDescription('The MAC Address of the entry that is used to lease the IP Address.')
hm2DHCPServerPoolGateway = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 8), IpAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolGateway.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolGateway.setDescription('The IPv4 address of the Gatewayinterface that is used to lease the IP Address.')
hm2DHCPServerPoolClientId = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 9), OctetString()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolClientId.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolClientId.setDescription('The Client Identifier of the entry that is used to lease the IP Address.')
hm2DHCPServerPoolRemoteId = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 10), OctetString()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolRemoteId.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolRemoteId.setDescription('The Remote Identifier of the entry that is used to lease the IP Address. The Remote Identifier must be send in Option 82 as defined in RFC 3046.')
hm2DHCPServerPoolCircuitId = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 11), OctetString()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolCircuitId.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolCircuitId.setDescription('The Cicuit Identifier of the entry that is used to lease the IP Address. The Circuit Identifier must be send in Option 82 as defined in RFC 3046.')
hm2DHCPServerPoolHirschmannClient = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 12), HmEnabledStatus().clone('disable')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolHirschmannClient.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolHirschmannClient.setDescription('Enable or disable Hirschmann Multicast.')
hm2DHCPServerPoolVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 13), Integer32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolVlanId.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolVlanId.setDescription('The Vlan ID of the entry that is used to lease the IP Address. A value of -1 corresponds to management vlan (the default), any other value (1-4042) represents a specific VLAN')
hm2DHCPServerPoolOptionConfFileName = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 30), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 70))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolOptionConfFileName.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolOptionConfFileName.setDescription('Full specified name of the configuration file e.g. tftp://192.9.200.1/cfg/config1.sav. An empty string zeros the SNAME and the FILE field in the DHCP header.')
hm2DHCPServerPoolOptionGateway = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 31), IpAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolOptionGateway.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolOptionGateway.setDescription('The IPv4 address of the Gateway. A value of 0 disables the attachment of the option field in the DHCP message.')
hm2DHCPServerPoolOptionNetmask = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 32), IpAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolOptionNetmask.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolOptionNetmask.setDescription('The subnet mask. A value of 0 disables the attachment of the option field in the DHCP message.')
hm2DHCPServerPoolOptionWINS = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 33), IpAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolOptionWINS.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolOptionWINS.setDescription('The IPv4 address of the WINS Server. A value of 0 disables the attachment of the option field in the DHCP message.')
hm2DHCPServerPoolOptionDNS = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 34), IpAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolOptionDNS.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolOptionDNS.setDescription('The IPv4 address of the DNS Server. A value of 0 disables the attachment of the option field in the DHCP message.')
hm2DHCPServerPoolOptionHostname = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 35), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolOptionHostname.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolOptionHostname.setDescription('The name of the client (Option 12). An empty string disables the attachment of the option field in the DHCP message.')
hm2DHCPServerPoolMethod = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 36), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("config", 2), ("ttdp", 3))).clone('none')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2DHCPServerPoolMethod.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolMethod.setDescription('The source of the DHCP Server Pool. User can set the object to none(1), config(2), ttdp(3).')
hm2DHCPServerPoolErrorStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 99), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerPoolErrorStatus.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolErrorStatus.setDescription('The error Code by create a new Pool.')
hm2DHCPServerPoolRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 1, 5, 1, 100), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DHCPServerPoolRowStatus.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerPoolRowStatus.setDescription('This object indicates the status of this entry.')
hm2DHCPServerLeaseTable = MibTable((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 2, 1), )
if mibBuilder.loadTexts: hm2DHCPServerLeaseTable.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerLeaseTable.setDescription('A table containing the DHCP server leases.')
hm2DHCPServerLeaseEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 2, 1, 1), ).setIndexNames((0, "HM2-DHCPS-MIB", "hm2DHCPServerLeasePoolIndex"), (0, "HM2-DHCPS-MIB", "hm2DHCPServerLeaseIpAddress"))
if mibBuilder.loadTexts: hm2DHCPServerLeaseEntry.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerLeaseEntry.setDescription('A logical row in the hm2DHCPServerLeaseTable.')
hm2DHCPServerLeasePoolIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 2, 1, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerLeasePoolIndex.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerLeasePoolIndex.setDescription('The index of the hm2DHCPServerPoolTable above.')
hm2DHCPServerLeaseIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 2, 1, 1, 2), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerLeaseIpAddress.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerLeaseIpAddress.setDescription('This is an IP address from the pool with index hm2DHCPServerLeasePoolIndex.')
hm2DHCPServerLeaseState = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("bootp", 1), ("offering", 2), ("requesting", 3), ("bound", 4), ("renewing", 5), ("rebinding", 6), ("declined", 7), ("released", 8)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerLeaseState.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerLeaseState.setDescription('The state of the lease.')
hm2DHCPServerLeaseTimeRemaining = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 2, 1, 1, 4), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerLeaseTimeRemaining.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerLeaseTimeRemaining.setDescription('The remaining time of the lease configured in hm2DHCPServerPoolLeaseTime.')
hm2DHCPServerLeaseIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 2, 1, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerLeaseIfIndex.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerLeaseIfIndex.setDescription('The interface index where the lease is currently active.')
hm2DHCPServerLeaseClientMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 2, 1, 1, 6), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerLeaseClientMacAddress.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerLeaseClientMacAddress.setDescription('The MAC Address of the entry that has leased the IP Address.')
hm2DHCPServerLeaseGateway = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 2, 1, 1, 7), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerLeaseGateway.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerLeaseGateway.setDescription('The IPv4 address of the Gatewayinterface that was used to lease the IP Address.')
hm2DHCPServerLeaseClientId = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 2, 1, 1, 8), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerLeaseClientId.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerLeaseClientId.setDescription('The Client Identifier of the entry that was used to lease the IP Address.')
hm2DHCPServerLeaseRemoteId = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 2, 1, 1, 9), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerLeaseRemoteId.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerLeaseRemoteId.setDescription('The Remote Identifier of the entry that was used to lease the IP Address.')
hm2DHCPServerLeaseCircuitId = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 2, 1, 1, 10), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerLeaseCircuitId.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerLeaseCircuitId.setDescription('The Cicuit Identifier of the entry that was used to lease the IP Address.')
hm2DHCPServerLeaseStartTime = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 2, 1, 1, 11), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerLeaseStartTime.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerLeaseStartTime.setDescription('Lease start Time.')
hm2DHCPServerLeaseAction = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 2, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("release", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2DHCPServerLeaseAction.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerLeaseAction.setDescription('Manually release this ip address for new assignment.')
hm2DHCPServerLeaseVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 2, 1, 1, 13), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerLeaseVlanId.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerLeaseVlanId.setDescription('The Vlan ID of the entry that is used to lease the IP Address. A value of -1 corresponds to management vlan (the default), any other value (1-4042) represents a specific VLAN')
hm2DHCPServerIfConfigTable = MibTable((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 3, 1), )
if mibBuilder.loadTexts: hm2DHCPServerIfConfigTable.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerIfConfigTable.setDescription('A table containing current configuration information for each interface.')
hm2DHCPServerIfConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 3, 1, 1), ).setIndexNames((0, "HM2-DHCPS-MIB", "hm2DHCPServerIfConfigIndex"))
if mibBuilder.loadTexts: hm2DHCPServerIfConfigEntry.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerIfConfigEntry.setDescription('A logical row in the hm2DHCPServerIfConfigTable.')
hm2DHCPServerIfConfigIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 3, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerIfConfigIndex.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerIfConfigIndex.setDescription('The index of the interface.')
hm2DHCPServerIfConfigMode = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 3, 1, 1, 2), HmEnabledStatus().clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2DHCPServerIfConfigMode.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerIfConfigMode.setDescription('Enable or disable DHCP server on this interface.')
hm2DHCPServerCounterIfTable = MibTable((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2), )
if mibBuilder.loadTexts: hm2DHCPServerCounterIfTable.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterIfTable.setDescription('A table containing current configuration information for each interface.')
hm2DHCPServerCounterIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1), ).setIndexNames((0, "HM2-DHCPS-MIB", "hm2DHCPServerCounterIfIndex"))
if mibBuilder.loadTexts: hm2DHCPServerCounterIfEntry.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterIfEntry.setDescription('A logical row in the hm2DHCPServerCounterIfTable.')
hm2DHCPServerCounterIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 1), InterfaceIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterIfIndex.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterIfIndex.setDescription('The index of the interface.')
hm2DHCPServerCounterBootpRequests = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterBootpRequests.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterBootpRequests.setDescription('The number of packets received that contain a Message Type of 1 (BOOTREQUEST) in the first octet and do not contain option number 53 (DHCP Message Type) in the options.')
hm2DHCPServerCounterBootpInvalids = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterBootpInvalids.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterBootpInvalids.setDescription('The number of packets received that do not contain a Message Type of 1 (BOOTREQUEST) in the first octet or are not valid BOOTP packets (e.g., too short, invalid field in packet header).')
hm2DHCPServerCounterBootpReplies = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterBootpReplies.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterBootpReplies.setDescription('The number of packets sent that contain a Message Type of 2 (BOOTREPLY) in the first octet and do not contain option number 53 (DHCP Message Type) in the options.')
hm2DHCPServerCounterBootpDroppedUnknownClients = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterBootpDroppedUnknownClients.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterBootpDroppedUnknownClients.setDescription('The number of BOOTP packets dropped due to the server not recognizing or not providing service to the hardware address received in the incoming packet.')
hm2DHCPServerCounterBootpDroppedNotServingSubnet = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterBootpDroppedNotServingSubnet.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterBootpDroppedNotServingSubnet.setDescription('The number of BOOTP packets dropped due to the server not being configured or not otherwise able to serve addresses on the subnet from which this message was received.')
hm2DHCPServerCounterDhcpv4Discovers = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 20), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4Discovers.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4Discovers.setDescription('The number of DHCPDISCOVER (option 53 with value 1) packets received.')
hm2DHCPServerCounterDhcpv4Offers = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 21), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4Offers.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4Offers.setDescription('The number of DHCPOFFER (option 53 with value 2) packets sent.')
hm2DHCPServerCounterDhcpv4Requests = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 22), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4Requests.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4Requests.setDescription('The number of DHCPREQUEST (option 53 with value 3) packets received.')
hm2DHCPServerCounterDhcpv4Declines = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 23), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4Declines.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4Declines.setDescription('The number of DHCPDECLINE (option 53 with value 4) packets received.')
hm2DHCPServerCounterDhcpv4Acks = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 24), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4Acks.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4Acks.setDescription('The number of DHCPACK (option 53 with value 5) packets sent.')
hm2DHCPServerCounterDhcpv4Naks = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 25), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4Naks.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4Naks.setDescription('The number of DHCPNACK (option 53 with value 6) packets sent.')
hm2DHCPServerCounterDhcpv4Releases = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 26), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4Releases.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4Releases.setDescription('The number of DHCPRELEASE (option 53 with value 7) packets received.')
hm2DHCPServerCounterDhcpv4Informs = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 27), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4Informs.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4Informs.setDescription('The number of DHCPINFORM (option 53 with value 8) packets received.')
hm2DHCPServerCounterDhcpv4ForcedRenews = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 28), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4ForcedRenews.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4ForcedRenews.setDescription('The number of DHCPFORCERENEW (option 53 with value 9) packets sent.')
hm2DHCPServerCounterDhcpv4Invalids = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 29), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4Invalids.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4Invalids.setDescription('The number of DHCP packets received whose DHCP message type (i.e., option number 53) is not understood or handled by the server.')
hm2DHCPServerCounterDhcpv4DroppedUnknownClient = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 30), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4DroppedUnknownClient.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4DroppedUnknownClient.setDescription('The number of DHCP packets dropped due to the server not recognizing or not providing service to the client-id and/or hardware address received in the incoming packet.')
hm2DHCPServerCounterDhcpv4DroppedNotServingSubnet = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 31), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4DroppedNotServingSubnet.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterDhcpv4DroppedNotServingSubnet.setDescription('The number of DHCP packets dropped due to the server not being configured or not otherwise able to serve addresses on the subnet from which this message was received.')
hm2DHCPServerCounterMiscOtherDhcpServer = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 91, 1, 1, 4, 2, 1, 40), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DHCPServerCounterMiscOtherDhcpServer.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerCounterMiscOtherDhcpServer.setDescription('The number of BOOTP and DHCP packets from another DHCP server seen on this interface.')
hm2DHCPServerRowStatusInvalidConfigurationErrorReturn = ObjectIdentity((1, 3, 6, 1, 4, 1, 248, 11, 91, 3, 1))
if mibBuilder.loadTexts: hm2DHCPServerRowStatusInvalidConfigurationErrorReturn.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerRowStatusInvalidConfigurationErrorReturn.setDescription('DHCP Server pool with index {0} cannot be enabled, errors in data entry.')
hm2DHCPServerConflictDHCPRrelayErrorReturn = ObjectIdentity((1, 3, 6, 1, 4, 1, 248, 11, 91, 3, 2))
if mibBuilder.loadTexts: hm2DHCPServerConflictDHCPRrelayErrorReturn.setStatus('current')
if mibBuilder.loadTexts: hm2DHCPServerConflictDHCPRrelayErrorReturn.setDescription('{0} and {1} cannot be active at the same time.')
mibBuilder.exportSymbols("HM2-DHCPS-MIB", hm2DHCPServerPoolMacAddress=hm2DHCPServerPoolMacAddress, hm2DHCPServerLeaseAction=hm2DHCPServerLeaseAction, hm2DHCPServerIfConfigIndex=hm2DHCPServerIfConfigIndex, hm2DHCPServerMibNotifications=hm2DHCPServerMibNotifications, hm2DHCPServerConfigGroup=hm2DHCPServerConfigGroup, hm2DHCPServerCounterMiscOtherDhcpServer=hm2DHCPServerCounterMiscOtherDhcpServer, hm2DHCPServerCounterDhcpv4Discovers=hm2DHCPServerCounterDhcpv4Discovers, hm2DHCPServerLeaseStartTime=hm2DHCPServerLeaseStartTime, hm2DHCPServerPoolLeaseTime=hm2DHCPServerPoolLeaseTime, hm2DHCPServerPoolErrorStatus=hm2DHCPServerPoolErrorStatus, hm2DHCPServerCounterIfTable=hm2DHCPServerCounterIfTable, hm2DHCPServerLeaseEntry=hm2DHCPServerLeaseEntry, hm2DHCPServerCounterBootpDroppedUnknownClients=hm2DHCPServerCounterBootpDroppedUnknownClients, hm2DHCPServerPoolEntry=hm2DHCPServerPoolEntry, hm2DHCPServerIfConfigMode=hm2DHCPServerIfConfigMode, hm2DHCPServerCounterBootpReplies=hm2DHCPServerCounterBootpReplies, hm2DHCPServerLeaseGroup=hm2DHCPServerLeaseGroup, hm2DHCPServerLeaseClientId=hm2DHCPServerLeaseClientId, hm2DHCPServerCounterIfIndex=hm2DHCPServerCounterIfIndex, hm2DHCPServerCounterDhcpv4Naks=hm2DHCPServerCounterDhcpv4Naks, hm2DHCPServerPoolVlanId=hm2DHCPServerPoolVlanId, hm2DHCPServerIfConfigEntry=hm2DHCPServerIfConfigEntry, hm2DHCPServerCounterDhcpv4ForcedRenews=hm2DHCPServerCounterDhcpv4ForcedRenews, hm2DHCPServerPoolOptionWINS=hm2DHCPServerPoolOptionWINS, hm2DHCPServerInterfaceGroup=hm2DHCPServerInterfaceGroup, hm2DHCPServerPoolOptionNetmask=hm2DHCPServerPoolOptionNetmask, hm2DHCPServerCounterDhcpv4Acks=hm2DHCPServerCounterDhcpv4Acks, hm2DHCPServerCounterDhcpv4Releases=hm2DHCPServerCounterDhcpv4Releases, PYSNMP_MODULE_ID=hm2DhcpsMib, hm2DHCPServerPoolRemoteId=hm2DHCPServerPoolRemoteId, hm2DHCPServerPoolTable=hm2DHCPServerPoolTable, hm2DHCPServerSNMPExtensionGroup=hm2DHCPServerSNMPExtensionGroup, hm2DHCPServerPoolEndIpAddress=hm2DHCPServerPoolEndIpAddress, hm2DHCPServerLeaseTable=hm2DHCPServerLeaseTable, hm2DHCPServerLeaseState=hm2DHCPServerLeaseState, hm2DHCPServerMibObjects=hm2DHCPServerMibObjects, hm2DHCPServerPoolRowStatus=hm2DHCPServerPoolRowStatus, hm2DHCPServerCounterDhcpv4Declines=hm2DHCPServerCounterDhcpv4Declines, hm2DHCPServerCounterDhcpv4DroppedNotServingSubnet=hm2DHCPServerCounterDhcpv4DroppedNotServingSubnet, hm2DHCPServerLeasePoolIndex=hm2DHCPServerLeasePoolIndex, hm2DHCPServerPoolMethod=hm2DHCPServerPoolMethod, hm2DHCPServerIfConfigTable=hm2DHCPServerIfConfigTable, hm2DHCPServerCounterDhcpv4Requests=hm2DHCPServerCounterDhcpv4Requests, hm2DhcpsMib=hm2DhcpsMib, hm2DHCPServerRowStatusInvalidConfigurationErrorReturn=hm2DHCPServerRowStatusInvalidConfigurationErrorReturn, hm2DHCPServerCounterIfEntry=hm2DHCPServerCounterIfEntry, hm2DHCPServerCounterBootpDroppedNotServingSubnet=hm2DHCPServerCounterBootpDroppedNotServingSubnet, hm2DHCPServerMaxLeaseEntries=hm2DHCPServerMaxLeaseEntries, hm2DHCPServerLeaseIfIndex=hm2DHCPServerLeaseIfIndex, hm2DHCPServerPoolIndex=hm2DHCPServerPoolIndex, hm2DHCPServerCounterBootpInvalids=hm2DHCPServerCounterBootpInvalids, hm2DHCPServerPoolStartIpAddress=hm2DHCPServerPoolStartIpAddress, hm2DHCPServerPoolFlags=hm2DHCPServerPoolFlags, hm2DHCPServerCounterDhcpv4Informs=hm2DHCPServerCounterDhcpv4Informs, hm2DHCPServerGroup=hm2DHCPServerGroup, hm2DHCPServerCounterGroup=hm2DHCPServerCounterGroup, hm2DHCPServerPoolOptionGateway=hm2DHCPServerPoolOptionGateway, hm2DHCPServerLeaseGateway=hm2DHCPServerLeaseGateway, hm2DHCPServerPoolHirschmannClient=hm2DHCPServerPoolHirschmannClient, hm2DHCPServerLeaseClientMacAddress=hm2DHCPServerLeaseClientMacAddress, hm2DHCPServerCounterDhcpv4Invalids=hm2DHCPServerCounterDhcpv4Invalids, hm2DHCPServerMode=hm2DHCPServerMode, hm2DHCPServerPoolClientId=hm2DHCPServerPoolClientId, hm2DHCPServerLeaseIpAddress=hm2DHCPServerLeaseIpAddress, hm2DHCPServerCounterDhcpv4DroppedUnknownClient=hm2DHCPServerCounterDhcpv4DroppedUnknownClient, hm2DHCPServerPoolIfIndex=hm2DHCPServerPoolIfIndex, hm2DHCPServerLeaseRemoteId=hm2DHCPServerLeaseRemoteId, hm2DHCPServerConflictDHCPRrelayErrorReturn=hm2DHCPServerConflictDHCPRrelayErrorReturn, hm2DHCPServerLeaseTimeRemaining=hm2DHCPServerLeaseTimeRemaining, hm2DHCPServerPoolOptionDNS=hm2DHCPServerPoolOptionDNS, hm2DHCPServerCounterBootpRequests=hm2DHCPServerCounterBootpRequests, hm2DHCPServerLeaseVlanId=hm2DHCPServerLeaseVlanId, hm2DHCPServerPoolCircuitId=hm2DHCPServerPoolCircuitId, hm2DHCPServerPoolGateway=hm2DHCPServerPoolGateway, hm2DHCPServerPoolOptionHostname=hm2DHCPServerPoolOptionHostname, hm2DHCPServerLeaseCircuitId=hm2DHCPServerLeaseCircuitId, hm2DHCPServerCounterDhcpv4Offers=hm2DHCPServerCounterDhcpv4Offers, hm2DHCPServerMaxPoolEntries=hm2DHCPServerMaxPoolEntries, hm2DHCPServerPoolOptionConfFileName=hm2DHCPServerPoolOptionConfFileName)
|
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(root, value):
"""
For a binary search tree
"""
if root is None:
return Node(value)
node = root
parent = None
new = Node(value)
while True:
parent = node
if value < parent.data:
node = parent.left
if node is None:
parent.left = new
break
else:
node = parent.right
if node is None:
parent.right = new
break
def search(node, value):
if node is None:
return None
while node is not None:
if value == node.data:
return node
if value < node.data:
node = node.left
else:
node = node.right
return None
def deepest_level(node):
if node is None:
return -1
left_level = deepest_level(node.left) + 1
right_level = deepest_level(node.right) + 1
if left_level > right_level:
return left_level
else:
return right_level
def deepest_level2(node):
if node is None:
return 0
left_level = deepest_level(node.left)
right_level = deepest_level(node.right)
return max(left_level, right_level) + 1
def inOrderTraversal(node, level = 0):
if node is not None:
inOrderTraversal(node.left, level + 1)
visit(node, level)
inOrderTraversal(node.right, level + 1)
def preOrderTraversal(node, level = 0):
if node is not None:
visit(node, level)
preOrderTraversal(node.left, level + 1)
preOrderTraversal(node.right, level + 1)
def postOrderTraversal(node, level = 0):
if node is not None:
postOrderTraversal(node.left, level + 1)
postOrderTraversal(node.right, level + 1)
visit(node, level)
def visit(node, level, left = True):
print(' ' * level, node.data)
if __name__ == "__main__":
root = Node(10)
root.left = Node(5)
root.right = Node(15)
root.left.left = Node(2)
root.right.left = Node(12)
root.right.right = Node(18)
inOrderTraversal(root)
print('-' * 50)
preOrderTraversal(root)
print('-' * 50)
postOrderTraversal(root)
print('-' * 50)
bst = insert(None, 10)
inOrderTraversal(bst)
print('.' * 50)
insert(bst, 5)
inOrderTraversal(bst)
print('.' * 50)
insert(bst, 15)
inOrderTraversal(bst)
print('.' * 50)
insert(bst, 3)
insert(bst, 8)
inOrderTraversal(bst)
print('.' * 50)
print('-' * 50, "Search")
print('Should be none: ', search(None, 10))
print('Should be none: ', search(bst, 10).data)
print('Should be none: ', search(bst, 5).data)
insert(bst, 30)
insert(bst, 50)
inOrderTraversal(bst)
print('Should be none: ', search(bst, 30).data)
print('-' * 50, "Deepest level")
print('Level: ', deepest_level(None))
print('Level: ', deepest_level(Node(1)))
print('Level: ', deepest_level(root))
print('Level: ', deepest_level(bst)) |
table_pkeys_map = {
"account": [
"account_id"
],
"account_assignd_cert": [
"account_id",
"x509_cert_id",
"x509_key_usg"
],
"account_auth_log": [
"account_id",
"account_auth_ts",
"auth_resource",
"account_auth_seq"
],
"account_coll_type_relation": [
"account_collection_type",
"account_collection_relation"
],
"account_collection": [
"account_collection_id"
],
"account_collection_account": [
"account_id",
"account_collection_id"
],
"account_collection_hier": [
"account_collection_id",
"child_account_collection_id"
],
"account_password": [
"account_id",
"account_realm_id",
"password_type"
],
"account_realm": [
"account_realm_id"
],
"account_realm_acct_coll_type": [
"account_realm_id",
"account_collection_type"
],
"account_realm_company": [
"account_realm_id",
"company_id"
],
"account_realm_password_type": [
"password_type",
"account_realm_id"
],
"account_ssh_key": [
"account_id",
"ssh_key_id"
],
"account_token": [
"account_token_id"
],
"account_unix_info": [
"account_id"
],
"appaal": [
"appaal_id"
],
"appaal_instance": [
"appaal_instance_id"
],
"appaal_instance_device_coll": [
"appaal_instance_id",
"device_collection_id"
],
"appaal_instance_property": [
"app_key",
"appaal_group_name",
"appaal_group_rank",
"appaal_instance_id"
],
"approval_instance": [
"approval_instance_id"
],
"approval_instance_item": [
"approval_instance_item_id"
],
"approval_instance_link": [
"approval_instance_link_id"
],
"approval_instance_step": [
"approval_instance_step_id"
],
"approval_instance_step_notify": [
"approv_instance_step_notify_id"
],
"approval_process": [
"approval_process_id"
],
"approval_process_chain": [
"approval_process_chain_id"
],
"asset": [
"asset_id"
],
"badge": [
"card_number"
],
"badge_type": [
"badge_type_id"
],
"certificate_signing_request": [
"certificate_signing_request_id"
],
"chassis_location": [
"chassis_location_id"
],
"circuit": [
"circuit_id"
],
"company": [
"company_id"
],
"company_collection": [
"company_collection_id"
],
"company_collection_company": [
"company_id",
"company_collection_id"
],
"company_collection_hier": [
"child_company_collection_id",
"company_collection_id"
],
"company_type": [
"company_type",
"company_id"
],
"component": [
"component_id"
],
"component_property": [
"component_property_id"
],
"component_type": [
"component_type_id"
],
"component_type_component_func": [
"component_function",
"component_type_id"
],
"component_type_slot_tmplt": [
"component_type_slot_tmplt_id"
],
"contract": [
"contract_id"
],
"contract_type": [
"contract_id",
"contract_type"
],
"department": [
"account_collection_id"
],
"device": [
"device_id"
],
"device_collection": [
"device_collection_id"
],
"device_collection_assignd_cert": [
"device_collection_id",
"x509_cert_id",
"x509_key_usg"
],
"device_collection_device": [
"device_id",
"device_collection_id"
],
"device_collection_hier": [
"device_collection_id",
"child_device_collection_id"
],
"device_collection_ssh_key": [
"device_collection_id",
"ssh_key_id",
"account_collection_id"
],
"device_encapsulation_domain": [
"device_id",
"encapsulation_type"
],
"device_layer2_network": [
"layer2_network_id",
"device_id"
],
"device_management_controller": [
"manager_device_id",
"device_id"
],
"device_note": [
"note_id"
],
"device_ssh_key": [
"ssh_key_id",
"device_id"
],
"device_ticket": [
"ticketing_system_id",
"device_id",
"ticket_number"
],
"device_type": [
"device_type_id"
],
"device_type_module": [
"device_type_module_name",
"device_type_id"
],
"device_type_module_device_type": [
"device_type_module_name",
"device_type_id",
"module_device_type_id"
],
"dns_change_record": [
"dns_change_record_id"
],
"dns_domain": [
"dns_domain_id"
],
"dns_domain_collection": [
"dns_domain_collection_id"
],
"dns_domain_collection_dns_dom": [
"dns_domain_collection_id",
"dns_domain_id"
],
"dns_domain_collection_hier": [
"child_dns_domain_collection_id",
"dns_domain_collection_id"
],
"dns_domain_ip_universe": [
"dns_domain_id",
"ip_universe_id"
],
"dns_record": [
"dns_record_id"
],
"dns_record_relation": [
"dns_record_id",
"related_dns_record_id",
"dns_record_relation_type"
],
"encapsulation_domain": [
"encapsulation_type",
"encapsulation_domain"
],
"encapsulation_range": [
"encapsulation_range_id"
],
"encryption_key": [
"encryption_key_id"
],
"inter_component_connection": [
"inter_component_connection_id"
],
"ip_universe": [
"ip_universe_id"
],
"ip_universe_visibility": [
"visible_ip_universe_id",
"ip_universe_id"
],
"kerberos_realm": [
"krb_realm_id"
],
"klogin": [
"klogin_id"
],
"klogin_mclass": [
"device_collection_id",
"klogin_id"
],
"l2_network_coll_l2_network": [
"layer2_network_collection_id",
"layer2_network_id"
],
"l3_network_coll_l3_network": [
"layer3_network_id",
"layer3_network_collection_id"
],
"layer2_connection": [
"layer2_connection_id"
],
"layer2_connection_l2_network": [
"layer2_connection_id",
"layer2_network_id"
],
"layer2_network": [
"layer2_network_id"
],
"layer2_network_collection": [
"layer2_network_collection_id"
],
"layer2_network_collection_hier": [
"child_l2_network_coll_id",
"layer2_network_collection_id"
],
"layer3_network": [
"layer3_network_id"
],
"layer3_network_collection": [
"layer3_network_collection_id"
],
"layer3_network_collection_hier": [
"layer3_network_collection_id",
"child_l3_network_coll_id"
],
"logical_port": [
"logical_port_id"
],
"logical_port_slot": [
"logical_port_id",
"slot_id"
],
"logical_volume": [
"logical_volume_id"
],
"logical_volume_property": [
"logical_volume_property_id"
],
"logical_volume_purpose": [
"logical_volume_purpose",
"logical_volume_id"
],
"mlag_peering": [
"mlag_peering_id"
],
"netblock": [
"netblock_id"
],
"netblock_collection": [
"netblock_collection_id"
],
"netblock_collection_hier": [
"netblock_collection_id",
"child_netblock_collection_id"
],
"netblock_collection_netblock": [
"netblock_collection_id",
"netblock_id"
],
"network_interface": [
"network_interface_id"
],
"network_interface_netblock": [
"network_interface_id",
"device_id",
"netblock_id"
],
"network_interface_purpose": [
"network_interface_purpose",
"device_id"
],
"network_range": [
"network_range_id"
],
"network_service": [
"network_service_id"
],
"operating_system": [
"operating_system_id"
],
"operating_system_snapshot": [
"operating_system_snapshot_id"
],
"person": [
"person_id"
],
"person_account_realm_company": [
"account_realm_id",
"person_id",
"company_id"
],
"person_auth_question": [
"person_id",
"auth_question_id"
],
"person_company": [
"company_id",
"person_id"
],
"person_company_attr": [
"person_company_attr_name",
"company_id",
"person_id"
],
"person_company_badge": [
"company_id",
"person_id",
"badge_id"
],
"person_contact": [
"person_contact_id"
],
"person_image": [
"person_image_id"
],
"person_image_usage": [
"person_image_usage",
"person_image_id"
],
"person_location": [
"person_location_id"
],
"person_note": [
"note_id"
],
"person_parking_pass": [
"person_id",
"person_parking_pass_id"
],
"person_vehicle": [
"person_vehicle_id"
],
"physical_address": [
"physical_address_id"
],
"physical_connection": [
"physical_connection_id"
],
"physicalish_volume": [
"physicalish_volume_id"
],
"private_key": [
"private_key_id"
],
"property": [
"property_id"
],
"property_collection": [
"property_collection_id"
],
"property_collection_hier": [
"property_collection_id",
"child_property_collection_id"
],
"property_collection_property": [
"property_collection_id",
"property_type",
"property_name"
],
"pseudo_klogin": [
"pseudo_klogin_id"
],
"rack": [
"rack_id"
],
"rack_location": [
"rack_location_id"
],
"service_environment": [
"service_environment_id"
],
"service_environment_coll_hier": [
"child_service_env_coll_id",
"service_env_collection_id"
],
"service_environment_collection": [
"service_env_collection_id"
],
"shared_netblock": [
"shared_netblock_id"
],
"shared_netblock_network_int": [
"shared_netblock_id",
"network_interface_id"
],
"site": [
"site_code"
],
"slot": [
"slot_id"
],
"slot_type": [
"slot_type_id"
],
"slot_type_prmt_comp_slot_type": [
"slot_type_id",
"component_slot_type_id"
],
"slot_type_prmt_rem_slot_type": [
"slot_type_id",
"remote_slot_type_id"
],
"snmp_commstr": [
"snmp_commstr_id"
],
"ssh_key": [
"ssh_key_id"
],
"static_route": [
"static_route_id"
],
"static_route_template": [
"static_route_template_id"
],
"sudo_acct_col_device_collectio": [
"sudo_alias_name",
"account_collection_id",
"device_collection_id"
],
"sudo_alias": [
"sudo_alias_name"
],
"svc_environment_coll_svc_env": [
"service_environment_id",
"service_env_collection_id"
],
"sw_package": [
"sw_package_id"
],
"ticketing_system": [
"ticketing_system_id"
],
"token": [
"token_id"
],
"token_collection": [
"token_collection_id"
],
"token_collection_hier": [
"token_collection_id",
"child_token_collection_id"
],
"token_collection_token": [
"token_collection_id",
"token_id"
],
"token_sequence": [
"token_id"
],
"unix_group": [
"account_collection_id"
],
"val_account_collection_relatio": [
"account_collection_relation"
],
"val_account_collection_type": [
"account_collection_type"
],
"val_account_role": [
"account_role"
],
"val_account_type": [
"account_type"
],
"val_app_key": [
"appaal_group_name",
"app_key"
],
"val_app_key_values": [
"app_value",
"app_key",
"appaal_group_name"
],
"val_appaal_group_name": [
"appaal_group_name"
],
"val_approval_chain_resp_prd": [
"approval_chain_response_period"
],
"val_approval_expiration_action": [
"approval_expiration_action"
],
"val_approval_notifty_type": [
"approval_notify_type"
],
"val_approval_process_type": [
"approval_process_type"
],
"val_approval_type": [
"approval_type"
],
"val_attestation_frequency": [
"attestation_frequency"
],
"val_auth_question": [
"auth_question_id"
],
"val_auth_resource": [
"auth_resource"
],
"val_badge_status": [
"badge_status"
],
"val_cable_type": [
"cable_type"
],
"val_company_collection_type": [
"company_collection_type"
],
"val_company_type": [
"company_type"
],
"val_company_type_purpose": [
"company_type_purpose"
],
"val_component_function": [
"component_function"
],
"val_component_property": [
"component_property_name",
"component_property_type"
],
"val_component_property_type": [
"component_property_type"
],
"val_component_property_value": [
"component_property_name",
"valid_property_value",
"component_property_type"
],
"val_contract_type": [
"contract_type"
],
"val_country_code": [
"iso_country_code"
],
"val_device_auto_mgmt_protocol": [
"auto_mgmt_protocol"
],
"val_device_collection_type": [
"device_collection_type"
],
"val_device_mgmt_ctrl_type": [
"device_mgmt_control_type"
],
"val_device_status": [
"device_status"
],
"val_diet": [
"diet"
],
"val_dns_class": [
"dns_class"
],
"val_dns_domain_collection_type": [
"dns_domain_collection_type"
],
"val_dns_domain_type": [
"dns_domain_type"
],
"val_dns_record_relation_type": [
"dns_record_relation_type"
],
"val_dns_srv_service": [
"dns_srv_service"
],
"val_dns_type": [
"dns_type"
],
"val_encapsulation_mode": [
"encapsulation_type",
"encapsulation_mode"
],
"val_encapsulation_type": [
"encapsulation_type"
],
"val_encryption_key_purpose": [
"encryption_key_purpose",
"encryption_key_purpose_version"
],
"val_encryption_method": [
"encryption_method"
],
"val_filesystem_type": [
"filesystem_type"
],
"val_image_type": [
"image_type"
],
"val_ip_namespace": [
"ip_namespace"
],
"val_iso_currency_code": [
"iso_currency_code"
],
"val_key_usg_reason_for_assgn": [
"key_usage_reason_for_assign"
],
"val_layer2_network_coll_type": [
"layer2_network_collection_type"
],
"val_layer3_network_coll_type": [
"layer3_network_collection_type"
],
"val_logical_port_type": [
"logical_port_type"
],
"val_logical_volume_property": [
"filesystem_type",
"logical_volume_property_name"
],
"val_logical_volume_purpose": [
"logical_volume_purpose"
],
"val_logical_volume_type": [
"logical_volume_type"
],
"val_netblock_collection_type": [
"netblock_collection_type"
],
"val_netblock_status": [
"netblock_status"
],
"val_netblock_type": [
"netblock_type"
],
"val_network_interface_purpose": [
"network_interface_purpose"
],
"val_network_interface_type": [
"network_interface_type"
],
"val_network_range_type": [
"network_range_type"
],
"val_network_service_type": [
"network_service_type"
],
"val_operating_system_family": [
"operating_system_family"
],
"val_os_snapshot_type": [
"operating_system_snapshot_type"
],
"val_ownership_status": [
"ownership_status"
],
"val_package_relation_type": [
"package_relation_type"
],
"val_password_type": [
"password_type"
],
"val_person_company_attr_dtype": [
"person_company_attr_data_type"
],
"val_person_company_attr_name": [
"person_company_attr_name"
],
"val_person_company_attr_value": [
"person_company_attr_value",
"person_company_attr_name"
],
"val_person_company_relation": [
"person_company_relation"
],
"val_person_contact_loc_type": [
"person_contact_location_type"
],
"val_person_contact_technology": [
"person_contact_technology",
"person_contact_type"
],
"val_person_contact_type": [
"person_contact_type"
],
"val_person_image_usage": [
"person_image_usage"
],
"val_person_location_type": [
"person_location_type"
],
"val_person_status": [
"person_status"
],
"val_physical_address_type": [
"physical_address_type"
],
"val_physicalish_volume_type": [
"physicalish_volume_type"
],
"val_processor_architecture": [
"processor_architecture"
],
"val_production_state": [
"production_state"
],
"val_property": [
"property_type",
"property_name"
],
"val_property_collection_type": [
"property_collection_type"
],
"val_property_data_type": [
"property_data_type"
],
"val_property_type": [
"property_type"
],
"val_property_value": [
"valid_property_value",
"property_name",
"property_type"
],
"val_pvt_key_encryption_type": [
"private_key_encryption_type"
],
"val_rack_type": [
"rack_type"
],
"val_raid_type": [
"raid_type"
],
"val_service_env_coll_type": [
"service_env_collection_type"
],
"val_shared_netblock_protocol": [
"shared_netblock_protocol"
],
"val_slot_function": [
"slot_function"
],
"val_slot_physical_interface": [
"slot_function",
"slot_physical_interface_type"
],
"val_snmp_commstr_type": [
"snmp_commstr_type"
],
"val_ssh_key_type": [
"ssh_key_type"
],
"val_sw_package_type": [
"sw_package_type"
],
"val_token_collection_type": [
"token_collection_type"
],
"val_token_status": [
"token_status"
],
"val_token_type": [
"token_type"
],
"val_volume_group_purpose": [
"volume_group_purpose"
],
"val_volume_group_relation": [
"volume_group_relation"
],
"val_volume_group_type": [
"volume_group_type"
],
"val_x509_certificate_file_fmt": [
"x509_file_format"
],
"val_x509_certificate_type": [
"x509_certificate_type"
],
"val_x509_key_usage": [
"x509_key_usg"
],
"val_x509_key_usage_category": [
"x509_key_usg_cat"
],
"val_x509_revocation_reason": [
"x509_revocation_reason"
],
"volume_group": [
"volume_group_id"
],
"volume_group_physicalish_vol": [
"volume_group_id",
"physicalish_volume_id"
],
"volume_group_purpose": [
"volume_group_id",
"volume_group_purpose"
],
"x509_key_usage_attribute": [
"x509_cert_id",
"x509_key_usg"
],
"x509_key_usage_categorization": [
"x509_key_usg_cat",
"x509_key_usg"
],
"x509_key_usage_default": [
"x509_key_usg",
"x509_signed_certificate_id"
],
"x509_signed_certificate": [
"x509_signed_certificate_id"
]
} |
""" Largest element in the array. """
class Solution:
""" Naive Solution.
Time complexity: O(n^2)
"""
def largestElementInArray(self, arr):
i = 0
while i <len(arr):
j =i+1
while j< len(arr):
if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]
j += 1
i += 1
return arr[i-1]
class Solution_2:
""" Improved version
2. Largest element
3. Also find second largest element.
"""
def largestElementInArray(self, arr):
largest = []
i = 0
while i <len(arr):
if len(largest):
if arr[largest[0]] < arr[i]:
largest[1] = largest[0] if len(largest) > 1 else largest.append(largest[0])
largest[0] = i
elif len(largest) > 1 and arr[largest[1]] < arr[i]:
largest[1] = i
else:
largest.append(i)
i += 1
return largest[0], largest[1] if len(largest) > 1 else None
if __name__ == "__main__":
s = Solution()
res = s.largestElementInArray([8, 9, 10, 1, 2, 20, 30, -1, -50])
print("The largest element from the given array is ", res)
s_1 = Solution_2()
res = s_1.largestElementInArray([8, 9, 10, 1, 2, 20, 30, -1, -50])
print("The largest element from the given array is ", res)
res = s_1.largestElementInArray([10, 10, 10])
print("The largest element from the given array is ", res)
|
# LANGUAGE: Python
# AUTHOR: randy
# GITHUB: https://github.com/randy1369
print('Hello, python!') |
convidados = []
for _ in range(int(input())):
convidados.append(input())
if 'André' in convidados:
print('Cuidado!')
else:
print('Seguro!')
|
def test_opendota_api_type(heroes):
# Ensure data returned by fetch_hero_stats() is a list
assert isinstance(heroes, list)
def test_opendota_api_count(heroes, N_HEROES):
# Ensure all heroes are included
assert len(heroes) == N_HEROES
def test_opendota_api_contents(heroes, N_HEROES):
# Verify that all elements in heroes list are dicts
assert all(isinstance(hero, dict) for hero in heroes)
|
class ParserException(Exception):
"""
Base exception for the email parser.
"""
pass
class ParseEmailException(ParserException):
"""
Raised when the parser can't create a email.message.Message object of the raw string or bytes.
"""
pass
class MessageIDNotExistException(ParserException):
"""
Raised when a message not contain a message-id
"""
pass
class DefectMessageException(ParserException):
"""
Raised when the recieved message is defect.
"""
pass
|
# -*- coding:utf-8 -*-
"""
@author:SiriYang
@file: AppModel.py
@time: 2019.12.23 00:25
"""
class App (object):
#记录id
mId=None
#应用id
mAppId=None
#应用链接
mURL=None
#图标链接
mImgURL=None
#应用名称
mName=None
#应用类型
mApplicationCategory=None
#应用作者
mAuthor=None
#用户备注
mNote=None
#愿望单top
mStar=None
#自动更新
mAutoUpdate=None
#创建时间
mCreateTime=None
#更新时间
mUpdateTime=None
def __init__(self,url=""):
self.mId=-1
i=url.rfind("id")
if(i==-1):
self.mAppId=""
else:
self.mAppId=url[i:]
self.mURL=url
self.mImgURL=""
self.mName=""
self.mApplicationCategory=""
self.mAuthor=""
self.mNote=""
self.mStar=0
self.mAutoUpdate=0
def setId(self,id):
self.mId=id
def getId(self):
return self.mId
def setAppId(self,appid):
self.mAppId=appid
def getAppId(self):
return self.mAppId
def setURL(self,url):
self.mURL=url
def getURL(self):
return self.mURL
def setImgURL(self,url):
self.mImgURL=url
def getImgURL(self):
return self.mImgURL
def setName(self,name):
self.mName=name
def getName(self):
return self.mName
def setApplicationCategory(self,category):
self.mApplicationCategory=category
def getApplicationCategory(self):
return self.mApplicationCategory
def setAuthor(self,author):
self.mAuthor=author
def getAuthor(self):
return self.mAuthor
def setNote(self,note):
self.mNote=note
def getNote(self):
return self.mNote
def setStar(self,star):
self.mStar=star
def getStar(self):
return self.mStar
def setAutoUpdate(self,arg):
self.mAutoUpdate=arg
def getAutoUpdate(self):
return self.mAutoUpdate
def getCreateTime(self):
return self.mCreateTime
def getUpdateTime(self):
return self.mUpdateTime
def initByJson(self, json):
self.mName=json["name"]
self.mImgURL=json["image"]
self.mApplicationCategory=json["applicationCategory"]
self.mAuthor=json["author"]["name"]
def updateByJson(self, json):
self.mName=json["name"]
self.mImgURL=json["image"]
self.mAuthor=json["author"]["name"]
def initByTuple(self,t):
self.mId=t[0]
self.mAppId=t[1]
self.mURL=t[2]
self.mImgURL=t[3]
self.mName=t[4]
self.mApplicationCategory=t[5]
self.mAuthor=t[6]
self.mNote=t[7]
self.mStar=t[8]
self.mAutoUpdate=t[9]
self.mCreateTime=t[10]
self.mUpdateTime=t[11]
def toString(self):
return 'Id:\t'+str(self.mId)+'\nAppId:\t'+self.mAppId+'\nURL:\t'+self.mURL+'\nName:\t'+self.mName+'\nApplicationCategory:\t'+self.mApplicationCategory+'\nAuthor:\t'+self.mAuthor+'\nNote:\t'+str(self.mNote)+'\nStar:\t'+str(self.mStar)+'\nAutoUpdate:\t'+str(self.mAutoUpdate)
if __name__ == "__main__":
app=App("https://apps.apple.com/cn/app/playdeads-inside/id1201642309")
app.setId(1)
#app.setAppId("id123")
app.setName("test")
app.setApplicationCategory("game")
#app.setURL("siriyang.cn")
app.setAuthor("siriyang")
print(app.toString())
|
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
# Runtime: 12 ms
# Memory: 13.5 MB
pascal = []
for r in range(1, numRows + 1):
row = []
for c in range(r):
if c == 0 or c == r - 1:
row.append(1)
else:
last_row = pascal[-1]
row.append(last_row[c - 1] + last_row[c])
pascal.append(row)
return pascal
|
"""
백준 17626번 : Four Squares
Dynamic Programming + pypy3
메모이제이션
"""
n = int(input())
dp = [0, 1]
for i in range(2, n + 1):
dp.append(dp[i - 1])
j = 1
while j ** 2 <= i:
dp[i] = min(dp[i], dp[i - j ** 2])
j += 1
dp[i] += 1
print(dp[n]) |
data=input();
A = (data[0:2]); # dia
B = (data[3:5]); # mês
C = (data[6:8]); # ano
print(B,A,C,sep="/"); # MM/DD/AA
print(C,B,A,sep="/"); # AA/MM/DD
print(A,B,C,sep="-"); # DD-MM-AA |
filename = 'programming.txt'
with open(filename, 'w') as file_obj:
file_obj.write("I love programming.\n")
file_obj.write("I love creating new games.\n")
# 附加到文件
with open(filename, 'a') as file_obj:
file_obj.write("I also love finding meaning in large datasets.\n") |
class Solution:
def lastRemaining(self, n):
"""
:type n: int
:rtype: int
"""
def helper(n,i):
if n == 1:
return 1
if i:
return 2 * helper(n//2,0)
elif n % 2 == 1:
return 2 * helper(n//2,1)
else:
return 2 * helper(n//2,1) - 1
return helper(n,1)
a = Solution()
print(a.lastRemaining(100000000)) |
'''
From: LeetCode - 141. Linked List Cycle
Level: Easy
Source: https://leetcode.com/problems/linked-list-cycle/description/
Status: AC
Solution: Using Hash Table
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head is None:
return False
p = head.next
m = {head}
while p is not None:
if p in m:
return True
m.add(p)
p = p.next
return False
# times o(n)
# space o(n)
'''
Most Optimal Answer: Two Pointers
def hasCycle(self, head):
try:
normalSpeed = head
x2Speed = head.next
while normalSpeed is not x2Speed:
normalSpeed = normalSpeed.next
x2Speed = x2Speed.next.next
print('normal: {}, x2Speed: {}'.format(normalSpeed.val, x2Speed.val))
return True
except:
return False
# times o(n)
# space o(1)
''' |
"""
Journals module of Spire library and API version.
"""
SPIRE_JOURNALS_VERSION = "0.1.1"
|
class Structure(object):
_fields = ()
def __init__(self, *args):
if len(_fields) != len(args):
raise TypeError(f"Expected {len(_fields)} arguments.")
for name, value in zip(self._fields, args):
setattr(self, name, value)
if __name__ == '__main__':
class Shares(Structure):
_fields = ('name', 'share', 'price')
class Point(Structure):
_fields = ('x', 'y')
class Circle(Structure):
_fields = ('radius')
|
#!/usr/bin/env python
#-*- coding: utf-8 -*-
ID = 'ID'
TOKEN = 'TOKEN'
SUB_DOMAIN = 'xsy'
DOMAIN = 'admxj.pw'
|
'''
this program translates any integer base to decimal.
examples for testing:
assert checkio("101", 2) == 5, "Binary"
assert checkio("111112", 3) == 365, "Ternary"
assert checkio("200", 4) == 32, "Quaternary"
assert checkio("101", 5) == 26, "5 base"
assert checkio("25", 6) == 17, "Heximal/Senary"
assert checkio("112", 8) == 74, "Octal
assert checkio("AB", 10) == -1, "B > A > 10"
assert checkio("10000", 12) == 20736, "duodecimal"
assert checkio("AF", 16) == 175, "Hex"
assert checkio("20", 20) == 40, "Vigesimal"
assert checkio("D0", 20) == 260, "Vigesimal"
assert checkio("100", 20) == 400, "Vigesimal"
assert checkio("Z", 36) == 35, "Hexatrigesimal"
'''
def checkio(str_number, radix):
myList = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
# initialise first digit
letter = str_number[0].lower();
faktor = myList.index(letter);
# digit cannot be greater than base
if faktor >= radix:
return -1
# only one digit
if len(str_number) == 1:
return faktor;
# only two digits
if len(str_number) == 2:
letter = str_number[0].lower();
faktor = myList.index(letter);
if faktor > radix:
return -1
result = faktor * radix;
letter = str_number[1].lower();
faktor = myList.index(letter);
if faktor > radix:
return -1
result += faktor;
return result
# all other cases
result = faktor;
for elem in range(1, len(str_number)):
letter = str_number[elem].lower();
faktor = myList.index(letter);
# check that digit is not greater than base
if faktor > radix:
return -1
result *= radix;
result += faktor;
return result;
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio("AF", 16) == 175, "Hex"
assert checkio("101", 2) == 5, "Bin"
assert checkio("101", 5) == 26, "5 base"
assert checkio("Z", 36) == 35, "Z base"
assert checkio("AB", 10) == -1, "B > A > 10"
|
classes = [
{
'name': 'science-1',
'subjects': [
{
'name': 'Math',
'taughtBy': 'Turing',
'duration': 60
},
{
'name': 'English',
'taughtBy': 'Adele',
'duration': 60
},
{
'name': 'Sports',
'taughtBy': 'Dinho',
'duration': 60
},
{
'name': 'Science',
'taughtBy': 'Harish',
'duration': 60
}
],
},
{
'name': 'science-2',
'subjects': [
{
'name': 'Math',
'taughtBy': 'Harish',
'duration': 60
},
{
'name': 'English',
'taughtBy': 'Freddie',
'duration': 60
},
{
'name': 'Music',
'taughtBy': 'Freddie',
'duration': 60
},
{
'name': 'Science',
'taughtBy': 'Harish',
'duration': 60
}
]
},
{
'name': 'biology',
'subjects': [
{
'name': 'Botany',
'taughtBy': 'Dalton',
'duration': 60
},
{
'name': 'Zoology',
'taughtBy': 'Dalton',
'duration': 60
}
]
},
{
'name': 'politics',
'subjects': [
{
'name': 'Political Administration',
'taughtBy': 'Trump',
'duration': 60
},
{
'name': 'Business Administration',
'taughtBy': 'Trump',
'duration': 60
},
{
'name': 'Foreign Affairs',
'taughtBy': 'Trump',
'duration': 60
}
]
},
{
'name': 'politics-2',
'subjects': [
{
'name': 'Foreign Affairs',
'taughtBy': 'Swaraj',
'duration': 60
}
]
},
{
'name': 'philosophy',
'subjects': [
{
'name': 'Philosophy',
'taughtBy': 'Socrates',
'duration': 60
},
{
'name': 'Moral Science',
'taughtBy': 'Socrates',
'duration': 60
}
]
},
]
|
"""
snek.tests Package: Unit & integration tests for Snek.
"""
#-------------------------------------------------------------------------------
# Constants
#-------------------------------------------------------------------------------
MOCKS_FOLDER = './tests/mocks'
|
cont = 0
lista = []
while cont < 20:
x = input()
lista.append(x)
cont += 1
cont2 = 0
valor = -1
while cont2 < 20:
print("N[" + str(cont2) + "] = " + str(lista[valor]))
valor -= 1
cont2 += 1 |
class Solution:
def isRobotBounded(self, instructions: str) -> bool:
x, y, dx, dy = 0, 0, 0, 1
for it in instructions:
if it == 'L':
dx, dy = -dy, dx
elif it == 'R':
dx, dy = dy, -dx
else:
x = x + dx
y = y + dy
return (x, y) == (0, 0) or (dx, dy) != (0, 1)
|
### TODO use the details of your database connection
REGION = 'eu-west-2'
DBPORT = 1433
DBUSERNAME = 'admin' # the name of the database user you created in step 2
DBNAME = 'EventDatabase' # the name of the database your database user is granted access to
DBENDPOINT = 'eventdatabase.cu9s0xzhp0zw.eu-west-2.rds.amazonaws.com' #
DBPASSWORD = 'Eventpassword'
#config file containing credentials for RDS MySQL instance
db_username = "admin"
db_password = "Eventpassword"
db_name = "event_shema"
|
MAILBOX_MOVIE_CLEAR = 2
MAILBOX_MOVIE_EMPTY = 3
MAILBOX_MOVIE_WAITING = 4
MAILBOX_MOVIE_READY = 5
MAILBOX_MOVIE_NOT_OWNER = 6
MAILBOX_MOVIE_EXIT = 7
|
def parse(data):
return [
[int(x) if x.replace("-", "").isdigit() else x for x in l.split()]
for l in data.split("\n")
]
def calc(data):
# ¯\_(ツ)_/¯ Just use the values that mater, automating decompile was too hard
stack = []
for i in range(len(data) // 18):
if data[i * 18 + 5][2] > 0:
stack.append((i, data[i * 18 + 15][2]))
else:
ii, offset = stack.pop()
yield i, ii, offset + data[i * 18 + 5][2]
def aoc(data):
digits = [9] * 14
for i, ii, offset in calc(parse(data)):
if offset > 0:
digits[ii] -= offset
else:
digits[i] += offset
return "".join(str(d) for d in digits)
|
# Copyright (c) 2013 by pytest_pyramid authors and contributors
#
# This module is part of pytest_pyramid and is released under
# the MIT License (MIT): http://opensource.org/licenses/MIT
"""pytest_pyramid main module."""
__version__ = "1.0.1" # pragma: no cover
|
answer = int(input("How many times do you want to play? "))
for i in range(0,answer):
person1 = input("What is the first name? ")
person2 = input("What is the second name? ")
if person1 > person2:
print(person1)
print("has won")
elif person1 == person2:
print("friendship")
print("has won")
else:
print(person2)
print("has won")
|
__all__ = ['strip_comments']
def strip_comments(contents):
"""Strips the comments from coq code in contents.
The strings in contents are only preserved if there are no
comment-like tokens inside of strings. Stripping should be
successful and correct, regardless of whether or not there are
comment-like tokens in strings.
The behavior of this method is undefined if there are any
notations which change the meaning of '(*', '*)', or '"'.
Note that we take some extra care to leave *) untouched when it
does not terminate a comment.
"""
contents = contents.replace('(*', ' (* ').replace('*)', ' *) ')
tokens = contents.split(' ')
rtn = []
is_string = False
comment_level = 0
for token in tokens:
do_append = (comment_level == 0)
if is_string:
if token.count('"') % 2 == 1: # there are an odd number of '"' characters, indicating that we've ended the string
is_string = False
elif token.count('"') % 2 == 1: # there are an odd number of '"' characters, so we're starting a string
is_string = True
elif token == '(*':
comment_level += 1
do_append = False
elif comment_level > 0 and token == '*)':
comment_level -= 1
if do_append:
rtn.append(token)
return ' '.join(rtn).replace(' (* ', '(*').replace(' *) ', '*)').strip('\n\t ')
|
"""This file contains macros to be called during WORKSPACE evaluation.
For historic reasons, pip_repositories() is defined in //python:pip.bzl.
"""
def py_repositories():
"""Pull in dependencies needed to use the core Python rules."""
# At the moment this is a placeholder hook, in that it does not actually
# pull in any dependencies. Users should still call this function to make
# it less likely that they need to update their WORKSPACE files, in case
# this function is changed in the future.
pass
|
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( X , Y , m , n ) :
LCSuff = [ [ 0 for k in range ( n + 1 ) ] for l in range ( m + 1 ) ]
result = 0
for i in range ( m + 1 ) :
for j in range ( n + 1 ) :
if ( i == 0 or j == 0 ) :
LCSuff [ i ] [ j ] = 0
elif ( X [ i - 1 ] == Y [ j - 1 ] ) :
LCSuff [ i ] [ j ] = LCSuff [ i - 1 ] [ j - 1 ] + 1
result = max ( result , LCSuff [ i ] [ j ] )
else :
LCSuff [ i ] [ j ] = 0
return result
#TOFILL
if __name__ == '__main__':
param = [
(['A', 'D', 'E', 'E', 'L', 'L', 'T', 'r', 'x'],['D', 'F', 'H', 'O', 'g', 'o', 'u', 'v', 'w'],4,4,),
(['9', '3', '4', '8', '7', '6', '3', '8', '3', '3', '5', '3', '5', '4', '2', '5', '5', '3', '6', '2', '1', '7', '4', '2', '7', '3', '2', '1', '3', '7', '6', '5', '0', '6', '3', '8', '5', '1', '7', '9', '2', '7'],['5', '5', '3', '7', '8', '0', '9', '8', '5', '8', '5', '1', '4', '4', '0', '2', '9', '2', '3', '1', '1', '3', '6', '1', '2', '0', '5', '4', '3', '7', '5', '5', '8', '1', '1', '4', '8', '1', '7', '5', '5', '4'],41,37,),
(['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],35,29,),
(['W', 'X', 'P', 'u', 's', 'k', 'O', 'y', 'Q', 'i', 't', 'z', 'F', 'f', 's', 'N', 'K', 'm', 'I', 'M', 'g', 'e', 'E', 'P', 'b', 'Y', 'c', 'O', ' ', 'G', 'F', 'x'],['e', 'R', 'P', 'W', 'd', 'a', 'A', 'j', 'H', 'v', 'T', 'w', 'x', 'I', 'd', 'o', 'z', 'K', 'B', 'M', 'J', 'L', 'a', ' ', 'T', 'L', 'V', 't', 'M', 'U', 'z', 'R'],31,18,),
(['0', '1', '2', '4', '5', '7', '7', '7', '8', '8', '9', '9', '9'],['0', '0', '2', '2', '2', '3', '4', '6', '6', '7', '8', '9', '9'],12,8,),
(['0', '0', '1'],['0', '0', '1'],1,1,),
(['A', 'C', 'F', 'G', 'G', 'H', 'I', 'K', 'K', 'N', 'O', 'Q', 'R', 'V', 'V', 'W', 'Y', 'a', 'a', 'c', 'd', 'k', 'k', 'm', 'o', 'p', 't', 'u', 'y', 'y', 'y', 'z'],[' ', ' ', 'B', 'C', 'C', 'C', 'D', 'E', 'I', 'J', 'M', 'N', 'P', 'T', 'U', 'U', 'V', 'V', 'W', 'W', 'Y', 'b', 'c', 'e', 'i', 'o', 'p', 'r', 't', 'y', 'y', 'z'],21,23,),
(['0', '0', '0', '2', '8', '3', '5', '1', '0', '7', '7', '9', '9', '4', '8', '9', '5'],['8', '5', '8', '7', '1', '4', '0', '2', '2', '7', '2', '4', '0', '8', '3', '8', '7'],13,12,),
(['0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1'],['0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1'],9,9,),
(['B', 'o', 'R', 'k', 'Y', 'M', 'g', 'b', 'h', 'A', 'i', 'X', 'p', 'i', 'j', 'f', 'V', 'n', 'd', 'P', 'T', 'U', 'f', 'G', 'M', 'W', 'g', 'a', 'C', 'E', 'v', 'C', ' '],['F', 'h', 'G', 'H', 'Q', 'Q', 'K', 'g', 'k', 'u', 'l', 'c', 'c', 'o', 'n', 'G', 'i', 'Z', 'd', 'b', 'c', 'b', 'v', 't', 'S', 't', 'P', 'A', 'K', 'g', 'G', 'i', 'm'],19,32,)
]
n_success = 0
for i, parameters_set in enumerate(param):
if f_filled(*parameters_set) == f_gold(*parameters_set):
n_success+=1
print("#Results: %i, %i" % (n_success, len(param))) |
#Simple declaration of Funtion
'''def say_hello():
print('hello')
say_hello()
'''
def greeting(name):
print(f'Hello {name}')
greeting('raj') |
def for_hyphen():
for row in range(3):
for col in range(3):
if row==1:
print("*",end=" ")
else:
print(" ",end=" ")
print()
def while_hyphen():
row=0
while row<3:
col=0
while col<3:
if row==1:
print("*",end=" ")
else:
print(" ",end=" ")
col+=1
row+=1
print()
|
# 세트; 셋(set)
# 수학에서의 `집합`과 동일한 의미를 가집니다.
# 중복된 값을 가지지 않으며 순서를 갖지 않는 컨테이너 타입입니다.
# 리터럴 선언 방식
# 세트의 리터럴 선언은 `{}` 기호를 사용합니다.
# 단, 안에 값이 있어야 합니다.
# 값이 들어있지 않으면 `dict` 타입의 리터럴로 간주됩니다.
s = {0, }
# <class 'set'>
print(type(s))
# {0}
print(s)
s = {1, 2, 2, 3, 4, 5, 5}
# {1, 2, 3, 4, 5}
print(s)
# 생성자 선언 방식
s = set()
# <class 'set'>
print(type(s))
# set()
print(s)
s = {1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 5, 5}
# add
# 세트에 요소를 추가시킵니다.
# 리스트의 `append`와 동일한 역할을 하지만, 세트는 순서를 가지지 않으므로 요소 추가 시 매핑하여 정렬합니다.
s.add(6)
# {1, 2, 3, 4, 5, 6}
print(s)
# update
# 세트에 여러 요소를 한번에 추가합니다.
# 리스트의 `extend`와 동일합니다.
s.update({7, 8, 9})
# {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(s)
# pop
# 세트의 마지막 요소를 제거합니다.
# 리스트의 `pop`과 동일합니다.
item = s.pop()
# 1
print(item)
# {2, 3, 4, 5, 6}
print(s)
# remove
# 리스트의 `remove`와 동일합니다.
# 해당하는 요소를 제거합니다.
s.remove(3)
# {2, 4, 5, 6}
print(s)
# discard
# `remove`와 동일하지만, `remove`는 사용 시 해당하는 요소가 없으면 `KeyError`를 발생하는 반면,
# `discard`는 해당 요소가 없어도 에러를 발생시키지 않는다는 차이가 있습니다.
s.discard(2)
# {4, 5, 6, 7, 8, 9}
print(s)
s.discard(2)
# {4, 5, 6, 7, 8, 9}
print(s)
# clear
# 리스트의 `clear`와 동일합니다.
# 세트의 요소를 모두 제거합니다.
s.clear()
# set()
print(s)
s = {1, 2, 2, 3, 3, 3, 4, 4, 5, 6}
# copy
# 리스트의 `copy`와 동일합니다.
# 세트 객체를 복제시킵니다.
s2 = s.copy()
# {1, 2, 3, 4, 5, 6}
print(s2)
s1 = {1, 2, 3, 4, 5}
s2 = {4, 5, 6, 7, 8}
# union
# 수학에서의 합집합과 동일합니다.
# 해당 이터러블(Iterable; 순회 가능한) 객체의 요소와 합쳐진 새로운 이터러블 객체를 반환합니다.
# 이터러블 객체 중에서는 리스트, 튜플, 세트 등이 있습니다.
uni = s2.union(s1)
# {1, 2, 3, 4, 5, 6, 7, 8}
print(uni)
l = [10, 20, 3, 4, 5, 60]
uni = s2.union(l)
# {3, 4, 5, 6, 7, 8, 10, 20, 60}
print(uni)
t = (10, 11, 12)
uni = s2.union(t)
# {4, 5, 6, 7, 8, 10, 11, 12}
print(uni)
# intersection
# 수학에서의 교집합과 동일합니다.
# 해당 이터러블 객체와 비교하여 같은 요소만 포함된 새로운 이터러블 객체를 반환합니다.
inter = s1.intersection(s2)
# {4, 5}
print(inter)
# difference
# 수학에서의 차집합과 동일합니다.
# 해당 이터러블 객체와 비교하여 다른 요소가 포함된 새로운 이터러블 객체를 반환합니다.
diff = s2.difference(s1)
# {8, 6, 7}
print(diff)
# symmetric_difference
# 수학에서의 대칭차집합(합집합 - 교집합) 연산자와 동일합니다.
# 해당 이터러블 객체와 비교하여 서로 대칭되는 요소들을 포함한 새로운 이터러블 객체를 반환합니다.
sym_diff = s1.symmetric_difference(s2)
# {1, 2, 3, 6, 7, 8}
print(sym_diff)
# (차집합 or 교집합 or 대칭차집합)_update
# 각 기능에 `_update`가 붙은 함수는 모두 기능을 수행함과 동시에 해당 객체에 요소를 추가 `update` 시킵니다.
s2.difference_update(s1)
# {6, 7, 8}
print(s2)
s2.intersection_update(s1)
# set()
print(s2)
s2.symmetric_difference_update(s1)
# {1, 2, 3, 4, 5}
print(s2)
# 세트 연산자
# 위에 방식대로 할 수 있지만, 세트는 세트만의 고유한 연산자를 가지고 있습니다.
# - 합집합: `|` 기호
# - 차집합: `-` 기호
# - 교집합: `&` 기호
# - 대칭차집합: `^` 기호
uni = s1 | s2
diff = s1 - s2
inter = s1 & s2
sym_diff = s1 ^ s2
# {1, 2, 3, 4, 5}
print(uni)
# set()
print(diff)
# {1, 2, 3, 4, 5}
print(inter)
# set()
print(sym_diff)
s1 = {1, 2, 3, 4, 5}
s2 = {1, 2, 3}
# issubset
# 해당 이터러블에 대한 부분집합(subset)인지 여부를 확인합니다.
# 즉, 해당 이터러블 객체의 부분집합이라면 참, 아니면 거짓을 나타냅니다.
result = s1.issubset(s2)
# False
print(result)
result = s2.issubset(s1)
# True
print(result)
# issuperset
# `issubset`과 반대입니다.
# 해당 이터러블에 대한 상위집합(superset)인지 여부를 확인합니다.
# 즉, 해당 이터러블 객체의 상위집합이라면 참, 아니면 거짓을 나타냅니다.
result = s1.issuperset(s2)
# True
print(result)
result = s2.issuperset(s1)
# False
print(result)
# isdisjoint
# 해당 이터러블에 대한 교집합이 없으면 참, 있다면 거짓을 나타냅니다.
result = s1.isdisjoint(s2)
# False
print(result)
s3 = {6, 7, 8}
result = s1.isdisjoint(s3)
# True
print(result)
# 세트 컴프리헨션
s = {x for x in [1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6]}
# {1, 2, 3, 4, 5, 6}
print(s)
|
class EmptyGraphHelper(object):
@staticmethod
def get_help_message():
return f"""
We are deeply sorry but unfortunately the result graph is empty.
Please try the following steps to fix the problem -
\t1. Try running again with other / no filters
\t2. Make sure to run 'edr lineage generate' command first
\t3. Join our slack channel here - https://bit.ly/slack-elementary, we promise to help and be nice!
"""
|
def tabuada(numero):
for i in range(1, 11):
print(f'{i} x {numero} = {i * numero}')
tabuada(int(input()))
|
#usar operador de incremento e atribuição
#count = 0
#while count != 5:
#count+=1 #é o mesmo que count = count + 1
#print(count)
#incrementar a contagem em 3
#count = 0
#while count <= 20:
#count+=3
#print(count)
#diminui a contagem em 3
count = 20
while count>=0:
count -= 3
print(count) |
class RadarSensor:
angle = None
axis = None
distance = None
property = None
|
# 838. Push Dominoes
# There are N dominoes in a line, and we place each domino vertically upright.
# In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
# After each second, each domino that is falling to the left pushes the adjacent domino on the left.
# Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.
# When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.
# For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.
# Given a string "S" representing the initial state. S[i] = 'L', if the i-th domino has been pushed to the left; S[i] = 'R', if the i-th domino has been pushed to the right; S[i] = '.', if the i-th domino has not been pushed.
# Return a string representing the final state.
# Example 1:
# Input: ".L.R...LR..L.."
# Output: "LL.RR.LLRRLL.."
# Example 2:
# Input: "RR.L"
# Output: "RR.L"
# Explanation: The first domino expends no additional force on the second domino.
# Note:
# 0 <= N <= 10^5
# String dominoes contains only 'L', 'R' and '.'
class Solution(object):
def pushDominoes(self, dominoes):
"""
:type dominoes: str
:rtype: str
"""
# sol 1:
# use DP
# time O(n) space O(n)
# runtime: 553ms
dp = [0]*len(dominoes) # distance from current index to L/R.
lst = list(dominoes)
n = len(lst)
leftDist, rightDist = None, None
for i, val in enumerate(dominoes): # right
if val == 'R':
rightDist = 0
elif val == 'L':
rightDist = None
elif rightDist != None:
rightDist += 1
lst[i] = 'R'
dp[i] = rightDist
for i in range(n-1, -1, -1):
if dominoes[i] == 'L':
leftDist = 0
elif dominoes[i] == 'R':
leftDist = None
elif leftDist != None:
leftDist += 1
if leftDist < dp[i] or lst[i]=='.': lst[i] = 'L'
elif leftDist == dp[i]: lst[i] = '.'
return ''.join(lst)
|
result = []
def PrimeFactor(n):
for i in range(2,int(n/2+1)):
if n % i == 0:
result.append(i)
return PrimeFactor(n/i)
result.append(int(n))
if __name__ == '__main__':
PrimeFactor(90)
print("90的质因数:",result)
|
#!/usr/bin/env python3
class Course:
'''Course superclass for any course'''
def __init__(self, dept, num, name='',
units=4, prereq=set(), restr=set(), coclass=None):
self.dept, self.num, self.name = dept, num, name
self.units = units
self.prereq, self.restr = prereq, restr
if coclass:
self.coclass = coclass
else:
self.coclass = 'No co-classes required'
def __repr__(self):
return self.dept+' '+self.num
def get_info(self):
return self.__repr__()+': '+self.name\
+'\nPrerequisites: '+', '.join(self.prereq)\
+ '\nCoclasses: '+self.coclass
class GE(Course):
'''GE class'''
def __init__(self, dept, num, name='',
units=4, prereq=set(), restr=set(), coclass=None, section=set()):
self.section = section
super.__init__(dept, num, name, units, prereq, restr, coclass) |
"""Ecosystem exception."""
class QiskitEcosystemException(Exception):
"""Exceptions for qiskit ecosystem."""
|
# LIS2DW12 3-axis motion seneor micropython drive
# ver: 1.0
# License: MIT
# Author: shaoziyang (shaoziyang@micropython.org.cn)
# v1.0 2019.7
LIS2DW12_CTRL1 = const(0x20)
LIS2DW12_CTRL2 = const(0x21)
LIS2DW12_CTRL3 = const(0x22)
LIS2DW12_CTRL6 = const(0x25)
LIS2DW12_STATUS = const(0x27)
LIS2DW12_OUT_T_L = const(0x0D)
LIS2DW12_OUT_X_L = const(0x28)
LIS2DW12_OUT_Y_L = const(0x2A)
LIS2DW12_OUT_Z_L = const(0x2C)
LIS2DW12_SCALE = ('2g', '4g', '8g', '16g')
class LIS2DW12():
def __init__(self, i2c, addr = 0x19):
self.i2c = i2c
self.addr = addr
self.tb = bytearray(1)
self.rb = bytearray(1)
self.oneshot = False
self.irq_v = [0, 0, 0]
self._power = 0x20
# ODR=5 MODE=0 LP=1
self.setreg(LIS2DW12_CTRL1, 0x51)
# BDU=1
self.setreg(LIS2DW12_CTRL2, 0x0C)
# SLP_MODE_SEL=1
self.setreg(LIS2DW12_CTRL3, 0x02)
# scale=2G
self._scale = 0
self.scale(self._scale)
self.oneshot_mode(False)
def int16(self, d):
return d if d < 0x8000 else d - 0x10000
def setreg(self, reg, dat):
self.tb[0] = dat
self.i2c.writeto_mem(self.addr, reg, self.tb)
def getreg(self, reg):
self.i2c.readfrom_mem_into(self.addr, reg, self.rb)
return self.rb[0]
def get2reg(self, reg):
return self.getreg(reg) + self.getreg(reg+1) * 256
def r_w_reg(self, reg, dat, mask):
self.getreg(reg)
self.rb[0] = (self.rb[0] & mask) | dat
self.setreg(reg, self.rb[0])
def oneshot_mode(self, oneshot=None):
if oneshot is None:
return self.oneshot
else:
self.oneshot = oneshot
d = 8 if oneshot else 0
self.r_w_reg(LIS2DW12_CTRL1, d, 0xF3)
def ONE_SHOT(self):
if self.oneshot:
self.r_w_reg(LIS2DW12_CTRL3, 1, 0xFE)
while 1:
if (self.getreg(LIS2DW12_CTRL3) & 0x01) == 0:
return
def x_raw(self):
self.ONE_SHOT()
return self.int16(self.get2reg(LIS2DW12_OUT_X_L))>>2
def y_raw(self):
self.ONE_SHOT()
return self.int16(self.get2reg(LIS2DW12_OUT_Y_L))>>2
def z_raw(self):
self.ONE_SHOT()
return self.int16(self.get2reg(LIS2DW12_OUT_Z_L))>>2
def get_raw(self):
self.ONE_SHOT()
self.irq_v[0] = self.int16(self.get2reg(LIS2DW12_OUT_X_L))>>2
self.irq_v[1] = self.int16(self.get2reg(LIS2DW12_OUT_Y_L))>>2
self.irq_v[2] = self.int16(self.get2reg(LIS2DW12_OUT_Z_L))>>2
return self.irq_v
def mg(self, reg):
return round(self.int16(self.get2reg(reg)) * 0.061 * (1 << self._scale))
def x(self):
self.ONE_SHOT()
return self.mg(LIS2DW12_OUT_X_L)
def y(self):
self.ONE_SHOT()
return self.mg(LIS2DW12_OUT_Y_L)
def z(self):
self.ONE_SHOT()
return self.mg(LIS2DW12_OUT_Z_L)
def get(self):
self.ONE_SHOT()
self.irq_v[0] = self.mg(LIS2DW12_OUT_X_L)
self.irq_v[1] = self.mg(LIS2DW12_OUT_Y_L)
self.irq_v[2] = self.mg(LIS2DW12_OUT_Z_L)
return self.irq_v
def temperature(self):
try:
return self.int16(self.get2reg(LIS2DW12_OUT_T_L))/256 + 25
except MemoryError:
return self.temperature_irq()
def temperature_irq(self):
self.getreg(LIS2DW12_OUT_T_L+1)
if self.rb[0] & 0x80: self.rb[0] -= 256
return self.rb[0] + 25
def scale(self, dat=None):
if dat is None:
return LIS2DW12_SCALE[self._scale]
else:
if type(dat) is str:
if not dat in LIS2DW12_SCALE: return
self._scale = LIS2DW12_SCALE.index(dat)
else: return
self.r_w_reg(LIS2DW12_CTRL6, self._scale<<4, 0xCF)
def power(self, on=None):
if on is None:
return self._power > 0
else:
if on:
self.r_w_reg(LIS2DW12_CTRL1, self._power, 0x0F)
self._power = 0
else:
self._power = self.getreg(LIS2DW12_CTRL1) & 0xF0
self.r_w_reg(LIS2DW12_CTRL1, 0, 0x0F)
|
recomputation_vm_memory = 2048
haskell_vm_memory = 4096
recomputation_vm_cpus = 2
vagrantfile_templates_dict = {
"python": "python/python.vagrantfile",
"node_js": "nodejs/nodejs.vagrantfile",
"cpp": "cpp/cpp.vagrantfile",
"c++": "cpp/cpp.vagrantfile",
"c": "cpp/cpp.vagrantfile",
"haskell": "haskell/haskell.vagrantfile",
"go": "go/go.vagrantfile"
}
languages_version_dict = {
"python": "2.7",
"node_js": "0.10"
}
languages_install_dict = {
"python": ["pip install -r requirements.txt"],
"node_js": ["npm install"],
"cpp": ["chmod +x configure", "./configure", "make", "sudo make install"],
"c++": ["chmod +x configure", "./configure", "make", "sudo make install"],
"c": ["chmod +x configure", "./configure", "make", "sudo make install"],
"haskell": ["$VAGRANT_USER 'cabal configure'", "$VAGRANT_USER 'cabal install'"]
}
boxes_install_scripts = {
"gecode": ["echo \"export LD_LIBRARY_PATH=/home/vagrant/gecode\" >> /home/vagrant/.bashrc", "source /home/vagrant/.bashrc"],
"Idris-dev": ["$VAGRANT_USER 'sudo cabal configure'", "$VAGRANT_USER 'sudo cabal install'"]
}
ignore_test_scripts = ["Idris-dev"]
|
def pay(hours,rate) :
return hours * rate
hours = float(input('Enter Hours:'))
rate = float(input('Enter Rate:'))
print(pay(hours,rate)) |
{
"targets": [
{
"target_name": "mynanojs",
"sources": [ "./src/mynanojs.c", "./src/utility.c", "./src/mybitcoinjs.c" ],
"include_dirs":[ "./include", "./include/sodium" ],
"libraries": [
"../lib/libnanocrypto1.a", "../lib/libsodium.a"
],
}
]
}
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
def add(x, y):
"""Add two numbers together and return the result"""
return x + y
def subtract(x, y):
"""Subtract x from y and return result"""
return y - x
|
input00 = open("input/input00.txt", "r")
input01 = open("input/input01.txt", "r")
input00_list = input00.read().splitlines()
input01_list = input01.read().splitlines()
count_elements = int(input00_list[0])
dictionary = {}
for i in range(count_elements):
str_elements = input00_list[i+1].split()
dictionary[str_elements[0]] = [str_elements[1], str_elements[2], str_elements[3]]
average = sum(map(int, dictionary[input00_list[count_elements + 1]])) / len(input00_list)
print(average)
# query_scores = student_marks[query_name]
# print("{0:.2f}".format(sum(query_scores) / len(query_scores)))
|
met = int(input('Digite o valor em metros:'))
cm = met*100
ml = met*1000
print('o valor de {}m em centimetros é: {}cm. E o mesmo em milimetros é {}ml'.format(met, cm, ml))
|
# In this program we'll be implementing variousthings using map()
# map() function applies some transformer function to every part
# of the list
def double_stuff (things) :
""" Returns a new list with doubl ethe values than the previous list """
# accum list
new_list = []
# iterate over each item in the prev list
for thing in things :
# double each item
new_elem = thing * 2
# add to the new list
new_list.append(new_elem)
return new_list
# define list
things = [2, 3, 5]
# print
print(things)
# print by calling the defined function
print(double_stuff(things))
#print(list(map(lambda v: v * 4, things))
####################### map() ##################################
# map takes two arguments, a function and a sequence.
# The function is the mapper that transforms items.
# It is automatically applied to each item in the sequence.
# You don’t have to initialize an accumulator or iterate with a for loop at all.
states = ['hp','mp','up','tn','ap','asm','pb','mh']
def f (st) :
return st.upper()
# Technically, in a proper Python 3 interpreter, the map function produces
# an “iterator”, which is like a list but produces the items as they are needed.
# Most places in Python where you can use a list (e.g., in a for loop) you can use
# an “iterator” as if it was actually a list. So you probably won’t ever notice the difference.
# If you ever really need a list, you can explicitly turn the output of map into
# a list: list(map(...)).
u_states = list(map(f, states))
# u_states = map (lambda st: st.upper(), states)
print(u_states) |
'''
Autor: Pedro Sousa
Data: 17/03/2021
Numero da questao: Questão 08
Descriçao do problema:
Nome na vertical. Faça um programa que solicite o nome do usuário
e imprima-o na vertical, em formato de escada, conforme exemplo
abaixo (para a entrada "JOSE"):
Descricao da solucao:
* Criei uma classe para usar testes unitários apenas chamando um método solv()
com a classe instanciada.
* Criei um construtor para testar com outros valores de quantidade de pessoas
O método solv() chama métodos auxiliares e resolve item a item
Versão do Python: 3.9.2
Versão do Pytest: 6.2.2
'''
class Numero:
def solv(self):
"""
Método que soluciona o problema
"""
try:
nome = input('Nome: ')
for i in range(1, len(nome) + 1):
print(nome[:i])
except ValueError as e:
print(e)
if __name__ == '__main__':
Numero().solv()
|
primeiro = int(input('Termo: '))
razao = int(input('Razão: '))
termo = primeiro
cont = 1
total = 0
mais = 10
while mais != 0:
total += mais
while cont <= total:
print(f'{termo} →', end='')
termo += razao
cont += 1
print(' PAUSA...')
mais = int(input('Deseja que monstre mais, quantos? [0 STOP]'))
print('FIM...')
print(total)
|
{
"variables": {
"library%": "shared_library",
"mikmod_dir%": "../libmikmod"
},
"target_defaults": {
"include_dirs": [
"include",
"<(mikmod_dir)/include"
],
"defines": [
"HAVE_CONFIG_H"
],
"cflags": [
"-Wall",
"-finline-functions",
"-funroll-loops",
"-ffast-math"
],
"target_conditions": [
["OS == 'win'", {
"defines": [ "WIN32" ]
}],
["OS != 'win'", {
"defines": [ "unix" ]
}],
["_type == 'shared_library' and OS == 'win'", {
"defines": [ "DLL_EXPORTS" ]
}],
["_type == 'shared_library' and OS == 'linux'", {
"cflags": [ "-fPIC" ]
}]
],
"default_configuration": "Release",
"configurations": {
"Debug": {
"defines": [ "MIKMOD_DEBUG" ],
"cflags": [ "-g3", "-Werror" ],
"msvs_settings": {
"VCCLCompilerTool": {
"RuntimeLibrary": 3
}
}
},
"Release": {
"cflags": [ "-g", "-O2" ],
"msvs_settings": {
"VCCLCompilerTool": {
"RuntimeLibrary": 2
}
}
}
}
},
"targets": [
{
"target_name": "mikmod",
"type": "<(library)",
"product_dir": "../../System",
"sources": [
"<(mikmod_dir)/drivers/drv_nos.c",
"<(mikmod_dir)/drivers/drv_raw.c",
"<(mikmod_dir)/drivers/drv_stdout.c",
"<(mikmod_dir)/drivers/drv_wav.c",
"<(mikmod_dir)/loaders/load_669.c",
"<(mikmod_dir)/loaders/load_amf.c",
"<(mikmod_dir)/loaders/load_asy.c",
"<(mikmod_dir)/loaders/load_dsm.c",
"<(mikmod_dir)/loaders/load_far.c",
"<(mikmod_dir)/loaders/load_gdm.c",
"<(mikmod_dir)/loaders/load_gt2.c",
"<(mikmod_dir)/loaders/load_it.c",
"<(mikmod_dir)/loaders/load_imf.c",
"<(mikmod_dir)/loaders/load_m15.c",
"<(mikmod_dir)/loaders/load_med.c",
"<(mikmod_dir)/loaders/load_mod.c",
"<(mikmod_dir)/loaders/load_mtm.c",
"<(mikmod_dir)/loaders/load_okt.c",
"<(mikmod_dir)/loaders/load_s3m.c",
"<(mikmod_dir)/loaders/load_stm.c",
"<(mikmod_dir)/loaders/load_stx.c",
"<(mikmod_dir)/loaders/load_ult.c",
"<(mikmod_dir)/loaders/load_uni.c",
"<(mikmod_dir)/loaders/load_xm.c",
"<(mikmod_dir)/mmio/mmalloc.c",
"<(mikmod_dir)/mmio/mmerror.c",
"<(mikmod_dir)/mmio/mmio.c",
"<(mikmod_dir)/playercode/mdriver.c",
"<(mikmod_dir)/playercode/mdreg.c",
"<(mikmod_dir)/playercode/mdulaw.c",
"<(mikmod_dir)/playercode/mloader.c",
"<(mikmod_dir)/playercode/mlreg.c",
"<(mikmod_dir)/playercode/mlutil.c",
"<(mikmod_dir)/playercode/mplayer.c",
"<(mikmod_dir)/playercode/munitrk.c",
"<(mikmod_dir)/playercode/mwav.c",
"<(mikmod_dir)/playercode/npertab.c",
"<(mikmod_dir)/playercode/sloader.c",
"<(mikmod_dir)/playercode/virtch.c",
"<(mikmod_dir)/playercode/virtch2.c",
"<(mikmod_dir)/playercode/virtch_common.c"
],
"all_dependent_settings": {
"include_dirs": [
"include",
"<(mikmod_dir)/include"
]
},
"conditions": [
["OS != 'win'", {
"libraries": [ "-lm" ]
}]
]
}
]
}
|
##
# Copyright (c) 2006-2016 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
def parsetoken(text, delimiters=" \t"):
if not text:
return "", ""
if text[0] == '"':
return parsequoted(text, delimiters)
else:
for pos, c in enumerate(text):
if c in delimiters:
token = text[0:pos]
break
else:
return text, ""
return token, lstripdelimiters(text[pos:], delimiters)
def parsequoted(text, delimiters=" \t"):
assert(text)
assert(text[0] == '"')
pos = 1
while True:
next_pos = text.find('"', pos)
if next_pos == -1:
return text[1:].replace("\\\\", "\\").replace("\\\"", "\""), ""
if text[next_pos - 1] == '\\':
pos = next_pos + 1
else:
return (
text[1:next_pos].replace("\\\\", "\\").replace("\\\"", "\""),
lstripdelimiters(text[next_pos + 1:], delimiters)
)
def lstripdelimiters(text, delimiters):
for pos, c in enumerate(text):
if c not in delimiters:
return text[pos:]
else:
return ""
def parseStatusLine(status):
status = status.strip()
# Must have 'HTTP/1.1' version at start
if status[0:9] != "HTTP/1.1 ":
return 0
# Must have three digits followed by nothing or one space
if not status[9:12].isdigit() or (len(status) > 12 and status[12] != " "):
return 0
# Read in the status code
return int(status[9:12])
|
units=int(input("Enter the number of units you used: "))
if(units>=0 and units <= 50):
amount = units * 0.50
elif(units <= 150):
amount = units * 0.75
elif(units <= 250):
amount = units * 1.25
else:
amount = units * 1.50
surcharge = amount * 17/100
ebill = amount + surcharge
print("Electricity Bill = Rs.",ebill)
|
class matching_matrix_proportion():
def __init__(self, sol, n, * args, **kwargs):
self.rows = {i : {int(j):1} for i, j in enumerate(sol)}
self.n = n
self.k = len(Counter(sol))
self.update_A = {}
self.maximums = np.zeros(self.k)
self.where = np.zeros(self.k)
def merge_rows(self, i_1, i_2, k):
if i_1 >= self.n:
i_1 = self.update_A.pop(i_1)
if i_2 >= self.n:
i_2 = self.update_A.pop(i_2)
if (len(self.rows[i_1]) >= len(self.rows[i_2]) and
i_1 >= self.n and i_2 >= self.n):
i_1 , i_2 = i_2, i_1
self.update_A[k + self.n] = i_2
r1, r2 = self.rows.pop(i_1), self.rows[i_2]
# If the maximum is moving then update it's location
if i_1 in self.where:
self.where[np.where(self.where == i_1)] = i_2
for elem in r1:
if elem not in r2:
r2[elem] = r1[elem]
else:
value_1 = r1[elem]
value_2 = r2[elem]
value_new = value_1 + value_2
r2[elem] = value_new
if value_new > self.maximums[elem]:
self.maximums[elem] = value_new
self.where[elem] = i_2
self.rows[i_2] = r2
def to_dense(self):
m = len(self.rows)
n = self.k
M = np.zeros((m, n))
for i, row in enumerate(self.rows):
for j, col in self.rows[row].items():
M[i, j] = self.rows[row][j]
return(M) |
class Solution:
def findNumbers(self, nums: List[int]) -> int:
ans = 0
if(len(nums) == 0):
return 0
for i in nums:
if(len(str(i))%2 == 0):
ans+=1;
return ans
|
"""
This file contains all the biological constants of Chlamy CCM.
--------------------------------------------------------------
"""
# ============================================================= #
# + Define relevant length scale, time scale, and conc. scale
Lnth = 3.14 * pow(10, -6) # Typical length scale; same as the chloroplast radius
Time = Lnth * Lnth / pow(10, -9) # Characteristic time for small molecules to diffuse over the
# chloroplast assuming diffusion constant ~ 1E-9 m^2/s
Conc = 0.001 # Typical concentration 1 mM
# ============================================================= #
# ============================================================= #
# + Passive transport: permeability of different species
k_h2co3 = 3 * pow(10, -5) / (Lnth / Time) # permeability of membrane to H2CO3, m/s
k_hco3 = 5 * pow(10, -8) / (Lnth / Time) # permeability of membrane to HCO3-, m/s
# ============================================================= #
# ============================================================= #
# + pH and pKa [o]
pKa1 = 3.4 # 1st pKa of H2CO3
pH_tub = 6.0 # tubule pH
pH_cyt = 7.1 # cytosolic pH
pH_chlor = 8.0 # stromal pH
pK_eff = 6.1 # effective pKa of CO2 <--> HCO3- conversion
# + pH dependent partition factors
# The fraction of HCO3- is f / (1+f), and
# the fraction of H2CO3 is 1 / (1+f) in a given compartment
f_cyt = pow(10, -pKa1 + pH_cyt)
f_chlor = pow(10, -pKa1 + pH_chlor)
f_tub = pow(10, -pKa1 + pH_tub)
# ============================================================= #
# ============================================================= #
# + Diffusion constant
D_c = 1.88 * pow(10, -9) / (Lnth * Lnth / Time) # diffusion constant of CO2 in water, m^2/s
D_h = 1.15 * pow(10, -9) / (Lnth * Lnth / Time) # diffusion constant of HCO3- in water, m^2/s
D_h2co3 = 1.15 * pow(10, -9) / (Lnth * Lnth / Time) # diffusion constant of H2CO3 in water, m^2/s (UPDATE)
# for the sum of HCO3- + H2CO3 in each compartment
D_h_chlor = f_chlor / (1 + f_chlor) * D_h + 1 / (1 + f_chlor) * D_h2co3
D_h_tub = f_tub / (1 + f_tub) * D_h + 1 / (1 + f_tub) * D_h2co3
# ============================================================= #
# ============================================================= #
# + Geometry factors
R_chlor = 3.14 * pow(10, -6) / Lnth # radius of Chlamy chloroplast
R_pyr = 0.3 * R_chlor # radius of Chlamy pyrenoid
N_tub = 40 # number of thylkaoid tubules
rin = 0.4 * pow(10, -6) / Lnth # radius of the tubule meshwork
a_tub = 0.05 * pow(10, -6) / Lnth # cylindrical radius of the thylakoid tubules
fv_in = N_tub / 4 * (a_tub / rin)**2 # volume fraction
# for plant thylakoid geometry (!)
# (optional, assuming a meshwork structure of thylakoids
# throughout the chloroplast)
fv_plant = 0.35
a_plant = 0.25 * pow(10, -6) / Lnth
# ============================================================= #
# ============================================================= #
# + Rubsico reaction kinetics
C_rub = 0.005 # conc. of Rubisco active sites, M
kcat = 3.0 # kcat(turnover number) of Rubisco, s^-1
Km_c = 3.0 * pow(10, -5) / Conc # concentration of CO2 that half-maximizes rate of Rubisco
Km_o = 15.0 * pow(10, -5) / Conc # concentration of O2 that half-maximizes rate of Rubisco
O = 0.00023 / Conc # concentration of O2 in the pyrenoid
Vmax = (kcat * C_rub) / (Conc / Time) # maximum velocity of Rubisco carboxylation
Km_eff = Km_c * (1 + O / Km_o) # effective Km of Rubisco for CO2
# ============================================================= #
# ============================================================= #
# + Carbonic anhydrase kinetics
v_sp = 0.036 / (1 / Time) # velocity of spontaneous interconversion
#kmax_C = 1E4 / (1 / Time)
#kmax_H_tub = kmax_C * pow(10, pK_eff - pH_tub)
#kmax_H_chlor = kmax_C_lcib * pow(10, pK_eff - pH_chlor)
Km_CO2 = 0.005 / Conc # estimates of Km for carbonic anhydrases
Km_HCO3 = 0.005 / Conc
# ============================================================= #
#Km_active_chlor = 0.005 / Conc
#Km_active_tub = 0.005 / Conc
|
#! /usr/bin/env python
"""
RASPA file format and default parameters.
"""
GENERIC_PSEUDO_ATOMS_HEADER = [
['# of pseudo atoms'],
['29'],
['#type ', 'print ', 'as ', 'chem ', 'oxidation ', 'mass ', 'charge ', 'polarization ', 'B-factor radii ', 'connectivity ', 'anisotropic ', 'anisotropic-type ', 'tinker-type ']
]
GENERIC_PSEUDO_ATOMS = [
['He ' ,'yes' ,'He' ,'He' ,'0' ,'4.002602' ,' 0.0 ' ,'0.0' ,'1.0' ,'1.0 ' ,'0' ,'0' ,'relative' ,'0'],
['CH4_sp3' ,'yes' ,'C ' ,'C ' ,'0' ,'16.04246' ,' 0.0 ' ,'0.0' ,'1.0' ,'1.00 ' ,'0' ,'0' ,'relative' ,'0'],
['CH3_sp3' ,'yes' ,'C ' ,'C ' ,'0' ,'15.03452' ,' 0.0 ' ,'0.0' ,'1.0' ,'1.00 ' ,'0' ,'0' ,'relative' ,'0'],
['CH2_sp3' ,'yes' ,'C ' ,'C ' ,'0' ,'14.02658' ,' 0.0 ' ,'0.0' ,'1.0' ,'1.00 ' ,'0' ,'0' ,'relative' ,'0'],
['CH_sp3 ' ,'yes' ,'C ' ,'C ' ,'0' ,'13.01864' ,' 0.0 ' ,'0.0' ,'1.0' ,'1.00 ' ,'0' ,'0' ,'relative' ,'0'],
['C_sp3 ' ,'yes' ,'C ' ,'C ' ,'0' ,'12.0 ' ,' 0.0 ' ,'0.0' ,'1.0' ,'1.00 ' ,'0' ,'0' ,'relative' ,'0'],
['H_h2 ' ,'yes' ,'H ' ,'H ' ,'0' ,'1.00794 ' ,' 0.468 ' ,'0.0' ,'1.0' ,'0.7 ' ,'0' ,'0' ,'relative' ,'0'],
['H_com ' ,'no ' ,'H ' ,'H ' ,'0' ,'0.0 ' ,'-0.936 ' ,'0.0' ,'1.0' ,'0.7 ' ,'0' ,'0' ,'relative' ,'0'],
['C_co2 ' ,'yes' ,'C ' ,'C ' ,'0' ,'12.0 ' ,' 0.70 ' ,'0.0' ,'1.0' ,'0.720' ,'0' ,'0' ,'relative' ,'0'],
['O_co2 ' ,'yes' ,'O ' ,'O ' ,'0' ,'15.9994 ' ,'-0.35 ' ,'0.0' ,'1.0' ,'0.68 ' ,'0' ,'0' ,'relative' ,'0'],
['O_o2 ' ,'yes' ,'O ' ,'O ' ,'0' ,'15.9994 ' ,'-0.112 ' ,'0.0' ,'1.0' ,'0.7 ' ,'0' ,'0' ,'relative' ,'0'],
['O_com ' ,'no ' ,'O ' ,'- ' ,'0' ,'0.0 ' ,' 0.224 ' ,'0.0' ,'1.0' ,'0.7 ' ,'0' ,'0' ,'relative' ,'0'],
['N_n2 ' ,'yes' ,'N ' ,'N ' ,'0' ,'14.00674' ,'-0.4048' ,'0.0' ,'1.0' ,'0.7 ' ,'0' ,'0' ,'relative' ,'0'],
['N_com ' ,'no ' ,'N ' ,'- ' ,'0' ,'0.0 ' ,' 0.8096' ,'0.0' ,'1.0' ,'0.7 ' ,'0' ,'0' ,'relative' ,'0'],
['Ar ' ,'yes' ,'Ar' ,'Ar' ,'0' ,'39.948 ' ,' 0.0 ' ,'0.0' ,'1.0' ,'0.7 ' ,'0' ,'0' ,'relative' ,'0'],
['Ow ' ,'yes' ,'O ' ,'O ' ,'0' ,'15.9994 ' ,' 0.0 ' ,'0.0' ,'1.0' ,'0.5 ' ,'2' ,'0' ,'relative' ,'0'],
['Hw ' ,'yes' ,'H ' ,'H ' ,'0' ,'1.00794 ' ,' 0.241 ' ,'0.0' ,'1.0' ,'1.00 ' ,'1' ,'0' ,'relative' ,'0'],
['Lw ' ,'no ' ,'L ' ,'H ' ,'0' ,'0.0 ' ,'-0.241 ' ,'0.0' ,'1.0' ,'1.00 ' ,'1' ,'0' ,'relative' ,'0'],
['C_benz ' ,'yes' ,'C ' ,'C ' ,'0' ,'12.0 ' ,'-0.095 ' ,'0.0' ,'1.0' ,'0.70 ' ,'0' ,'0' ,'relative' ,'0'],
['H_benz ' ,'yes' ,'H ' ,'H ' ,'0' ,'1.00794 ' ,' 0.095 ' ,'0.0' ,'1.0' ,'0.320' ,'0' ,'0' ,'relative' ,'0'],
['N_dmf ' ,'yes' ,'N ' ,'N ' ,'0' ,'14.00674' ,'-0.57 ' ,'0.0' ,'1.0' ,'0.50 ' ,'0' ,'0' ,'relative' ,'0'],
['Co_dmf ' ,'yes' ,'C ' ,'C ' ,'0' ,'12.0 ' ,' 0.45 ' ,'0.0' ,'1.0' ,'0.52 ' ,'0' ,'0' ,'relative' ,'0'],
['Cm_dmf ' ,'yes' ,'C ' ,'C ' ,'0' ,'12.0 ' ,' 0.28 ' ,'0.0' ,'1.0' ,'0.52 ' ,'0' ,'0' ,'relative' ,'0'],
['O_dmf ' ,'yes' ,'O ' ,'O ' ,'0' ,'15.9994 ' ,'-0.50 ' ,'0.0' ,'1.0' ,'0.78 ' ,'0' ,'0' ,'relative' ,'0'],
['H_dmf ' ,'yes' ,'H ' ,'H ' ,'0' ,'1.00794 ' ,' 0.06 ' ,'0.0' ,'1.0' ,'0.22 ' ,'0' ,'0' ,'relative' ,'0'],
['Na ' ,'yes' ,'Na' ,'Na' ,'0' ,'22.98977' ,' 1.0 ' ,'0.0' ,'1.0' ,'1.00 ' ,'0' ,'0' ,'relative' ,'0'],
['Cl ' ,'yes' ,'Cl' ,'Cl' ,'0' ,'35.453 ' ,'-1.0 ' ,'0.0' ,'1.0' ,'1.00 ' ,'0' ,'0' ,'relative' ,'0'],
['Kr ' ,'yes' ,'Kr' ,'Kr' ,'0' ,'83.798 ' ,' 0.0 ' ,'0.0' ,'1.0' ,'1.00 ' ,'0' ,'0' ,'relative' ,'0'],
['Xe ' ,'yes' ,'Xe' ,'Xe' ,'0' ,'131.293 ' ,' 0.0 ' ,'0.0' ,'1.0' ,'1.00 ' ,'0' ,'0' ,'relative' ,'0'],
]
GENERIC_FF_MIXING_HEADER = [
['# general rule for shifted vs truncated '],
['shifted '],
['# general rule tailcorrections '],
['no '],
['# number of defined interactions '],
['55 '],
['# type interaction, parameters. IMPORTANT: define shortest matches first, so that more specific ones overwrites these '],
]
GENERIC_FF_MIXING = [
['He ' , 'lennard-jones' ,'10.9 ' ,'2.64 '],
['CH4_sp3 ' , 'lennard-jones' ,'158.5 ' ,'3.72 '],
['CH3_sp3 ' , 'lennard-jones' ,'108.0 ' ,'3.76 '],
['CH2_sp3 ' , 'lennard-jones' ,'56.0 ' ,'3.96 '],
['CH_sp3 ' , 'lennard-jones' ,'17.0 ' ,'4.67 '],
['C_sp3 ' , 'lennard-jones' ,' 0.8 ' ,'6.38 '],
['H_com ' , 'lennard-jones' ,'36.7 ' ,'2.958 '],
['H_h2 ' , 'none ' ,' ' ,' '],
['O_co2 ' , 'lennard-jones' ,'79.0 ' ,'3.05 '],
['C_co2 ' , 'lennard-jones' ,'27.0 ' ,'2.80 '],
['C_benz ' , 'lennard-jones' ,'30.70 ' ,'3.60 '],
['H_benz ' , 'lennard-jones' ,'25.45 ' ,'2.36 '],
['N_n2 ' , 'lennard-jones' ,'36.0 ' ,'3.31 '],
['N_com ' , 'none ' ,' ' ,' '],
['Ow ' , 'lennard-jones' ,'89.633' ,'3.097 '],
['N_dmf ' , 'lennard-jones' ,'80.0 ' ,'3.2 '],
['Co_dmf ' , 'lennard-jones' ,'50.0 ' ,'3.7 '],
['Cm_dmf ' , 'lennard-jones' ,'80.0 ' ,'3.8 '],
['O_dmf ' , 'lennard-jones' ,'100.0 ' ,'2.96 '],
['H_dmf ' , 'lennard-jones' ,'8.0 ' ,'2.2 '],
['Ar ' , 'lennard-jones' ,'119.8 ' ,'3.34 '],
['Kr ' , 'lennard-jones' ,'166.4 ' ,'3.636 '],
['Xe ' , 'lennard-jones' ,'221.0 ' ,'4.1 '],
]
GENERIC_FF_MIXING_FOOTER = [
['# general mixing rule for Lennard-Jones '],
['Lorentz-Berthelot '],
]
|
class Store:
def __init__(self):
self.store_item = []
def __str__(self):
if self.store_item == []:
return 'No items'
return '\n'.join(map(str,self.store_item))
def add_item(self,item):
self.store_item.append(item)
def count(self):
return len(self.store_item)
def filter(self, q_object):
store_obj = Store()
for items in self.store_item:
field_name = q_object.field
if q_object.operation == 'EQ' and getattr(items,field_name) == q_object.value:
store_obj.add_item(items)
elif q_object.operation == 'GT' and getattr(items,field_name) > q_object.value:
store_obj.add_item(items)
elif q_object.operation == 'GTE' and getattr(items,field_name) >= q_object.value:
store_obj.add_item(items)
elif q_object.operation == 'LT' and getattr(items,field_name) < q_object.value:
store_obj.add_item(items)
elif q_object.operation == 'LTE' and getattr(items,field_name) <= q_object.value:
store_obj.add_item(items)
elif (q_object.operation == 'CONTAINS' or q_object.operation == 'STARTS_WITH' or q_object.operation== 'ENDS_WITH') and q_object.value in getattr(items,field_name):
store_obj.add_item(items)
elif q_object.operation == 'IN' and getattr(items,field_name) in q_object.value:
store_obj.add_item(items)
return store_obj
def exclude(self, q_object):
exclude_obj = Store()
include_obj = self.filter(q_object)
for items in self.store_item:
if items not in include_obj.store_item:
exclude_obj.add_item(items)
return exclude_obj
class Item:
def __init__(self, name=None, price=0, category=None):
self._name = name
self._price = price
self._category = category
#raise error for value
if price <= 0:
raise ValueError('Invalid value for price, got {}'.format(price))
@property
def name(self):
return self._name
@property
def price(self):
return self._price
@property
def category(self):
return self._category
def __str__(self):
return f'{self._name}@{self._price}-{self._category}'
class Query:
valid_op = ['IN','EQ','GT','GTE','LT','LTE','STARTS_WITH','ENDS_WITH','CONTAINS']
def __init__(self, field=None, operation=None, value=None):
self.field = field
self.operation = operation
self.value = value
if operation not in Query.valid_op:
raise ValueError('Invalid value for operation, got {}'.format(operation))
def __str__(self):
return f"{self.field} {self.operation} {self.value}"
|
def add(x, y):
"""Sum two numbers"""
return x + y
def subtract(x, y):
"""Subtract two numbers"""
return x - y
|
# -*-coding:Utf-8 -*
# Programme testant si une année, saisie par l'utilisateur, est bissextile ou non
annee = input("Saisissez une année : ") # On attend que l'utilisateur saisisse l'année qu'il désire tester
annee = int(annee) # Risque d'erreur si l'utilisateur n'a pas saisi un nombre
if annee % 400 == 0 or (annee % 4 == 0 and annee % 100 != 0):
print("L'année saisie est bissextile.")
else:
print("L'année saisie n'est pas bissextile.")
|
"""
# Why we use for else condition ?
# For checking the specific number or checking the condition is true
# if the condition is false we just print single line in else condition.
"""
# To check whether the given number is divisible by 5 then print the number
# if it's not then print "Given is not divisible by 5"
nums = [34, 53, 32, 20, 39]
for num in nums:
if num % 5 == 0:
print(num)
break # If condition is True it's break the loop
# print else part, after the condition is false
else:
print("Given number is not divisible by 5")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 22 10:26:43 2018
@author: francisco
"""
#1)
if 6 > 7:
print("Yep")
# Answer: Blank
# Since 6 is not greater than 7, it doesn't print anything and it doesn't have any
# more conditionals to evalutate.
#2)
if 6 > 7:
print("Yep")
else:
print("Nope")
#Answer: Nope
#Same as previous exercise, only this time we have an else statement. So the else statement gets executed.
#3)
var = 'Panda'
if var == "panda":
print("Cute!")
elif var == "Panda":
print("Regal!")
else:
print("Ugly...")
#Answer: Regal!
# Strings in Python are case sensitive, the first condition compares 'Panda' with
# 'panda', thus they're not the same, so we pass on to the next conditional
# this one compares 'Panda' with 'Panda' and they're the same so the code inside
# is executed
#4)
temp = 120
if temp > 85:
print("Hot")
elif temp > 100:
print("REALLY HOT!")
elif temp > 60:
print("Comfortable")
else:
print("Cold")
#Answer: Hot
# Conditionals are evaluated in order, in this case the first conditions says
# if temp is greater than 85, since it is the conditional ends and the rest
# isn't evaluated. That's why it prints hot and not REALLY HOT!
#5)
temp = 50
if temp > 85:
print("Hot")
elif temp > 100:
print("REALLY HOT!")
elif temp > 60:
print("Comfortable")
else:
print("Cold")
# The value of temp is 50 and the 3 conditions compares if temp is greater than
# 85, 100 and 60, 50 is not greater than any of them so each condition returns
# false so the code inside the else statement is the one that gets executed
|
'''Faça um Programa que verifique se uma letra digitada é "F" ou "M". Conforme a
letra escrever: F - Feminino, M - Masculino, Sexo Inválido.'''
letra = str(input("Digite m para masculino e f para feminino: "))
if letra == "m":
print(f"Você é do sexo Masculino {letra}")
elif letra == "f":
print(f"Você é do sexo Feminino {letra}")
else:
print("Digite uma letra válida")
|
#!/usr/bin/python3.6
# created by cicek on 07.09.2018 09:44
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector2D(self.x + other.x, self.y + other.y)
first = Vector2D(5, 7)
second = Vector2D(3, 9)
result = first + second
print(result.x) # 8
print(result.y) # 16
'''
Therefore, the "result = first + second" line of code gets interpreted as follows:
result = first + second
result = first.__add__(second)
'''
'''
More magic methods for common operators:
__sub__ for -
__mul__ for *
__truediv__ for /
__floordiv__ for //
__mod__ for %
__pow__ for **
__and__ for &
__xor__ for ^
__or__ for |
The expression x + y is translated into x.__add__(y).
However, if x hasn't implemented __add__, and x and y are of different types, then y.__radd__(x) is called.
There are equivalent r methods for all magic methods just mentioned.
R in magic methods means reflected./yansıtılmış, geri dönmüş
'''
class SpecialString:
def __init__(self, cont):
self.cont = cont
def __truediv__(self, other):
line = "=" * len(other.cont)
return "\n".join([self.cont, line, other.cont])
spam = SpecialString("spam")
hello = SpecialString("Hello world!")
print(spam / hello)
# spam
# ============
# Hello world!
print(6/2) # 3.0
print("------------------------------")
'''Here's some code that shows how Python works with magic methods.'''
# only 1 magic method implemented
class A:
def __or__(self, other):
return ("A or")
# several magic methods
class B:
def __or__(self, other):
return ("B or")
def __ror__(self, other):
return ("B ror")
def __xor__(self, other):
return ("B xor")
def __rxor__(self, other):
return ("B rxor")
# compare classes directly
print(str(A() ^ B())) # B rxor # xor is not implemented for A
print(str(B() ^ A())) # B xor
# create instances and compare
a=A()
b=B()
print(str(a | b)) # A or
print(str(b | a)) # B or
print(str(a ^ b)) # B rxor - xor is not implemented for A
print(str(b ^ a)) # B xor
# print(str(a & b)) # TypeError: unsupported operand type(s) for &: 'A' and 'B'
|
class A:
def __init__(self, *, kw_only, optional_kw_only=None):
pass
class B(A):
def __init__(self, *, kw_only):
super().__init__(kw_only=kw_only) |
'''
Problem description:
Given an array of unsorted integers, find the smallest positive integer not in the array.
'''
def find_smallest_missing_pos_int_sort(array):
'''
runtime: O(nlogn)
space : O(1) - this depends on the sort but python's list.sort() performs an in-place sort
This sort-based solution is slow but requires no additional space, given the right sorting
algorithm.
'''
array.sort()
n = len(array)
# move to index of first positive integer; if none exist, return 1
index_of_first_pos = 0
for index_of_first_pos in xrange(n):
if array[index_of_first_pos] > 0:
break
current_pos_int = 1
for i in xrange(index_of_first_pos, n):
if array[i] != current_pos_int:
return current_pos_int
current_pos_int += 1
return current_pos_int
def find_smallest_missing_pos_int_set(array):
'''
runtime: O(n)
space : O(n)
This set-based solution is fast and readable but requires linear additional space.
'''
as_set = set(array)
n = len(array)
for x in xrange(1, n + 1):
if x not in as_set:
return x
return n + 1
def find_smallest_missing_pos_int_optimal(array):
'''
runtime: O(n)
space : O(1)
This in-place swap solution runs in linear time and requires constant space. Aside from some
constant-factor performance optimizations, this is the optimal solution.
'''
n = len(array)
def in_bounds(value):
return 1 <= value <= n
# swap integers within 1 to n into their respective cells
# all other values (x < 1, x > n, and repeats) end up in the remaining empty cells
for i in xrange(n):
while in_bounds(array[i]) and array[i] != i + 1 and array[array[i] - 1] != array[i]:
swap_cell = array[i] - 1
array[i], array[swap_cell] = array[swap_cell], array[i]
for i in xrange(n):
if array[i] != i + 1:
return i + 1
return n + 1
|
class Crawler:
def __init__(self, root):
self._root = root
def crawl(self):
pass
def crawl_into(self):
pass
|
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
def buildbuddy_deps():
maybe(
http_archive,
name = "rules_cc",
sha256 = "b6f34b3261ec02f85dbc5a8bdc9414ce548e1f5f67e000d7069571799cb88b25",
strip_prefix = "rules_cc-726dd8157557f1456b3656e26ab21a1646653405",
urls = ["https://github.com/bazelbuild/rules_cc/archive/726dd8157557f1456b3656e26ab21a1646653405.tar.gz"],
)
|
def TP(target, prediction):
"""
True positives.
:param target: target value
:param prediction: prediction value
:return:
"""
return (target.float() * prediction.float().round()).sum()
def TN(target, prediction):
"""
True negatives.
:param target: target value
:param prediction: prediction value
:return:
"""
return ((target == 0).float() * (prediction.float().round() == 0).float()).sum()
def FP(target, prediction):
"""
False positives.
:param target: target value
:param prediction: prediction value
:return:
"""
return ((target == 0).float() * prediction.float().round()).sum()
def FN(target, prediction):
"""
False negatives.
:param target: target value
:param prediction: prediction value
:return:
"""
return (target.float() * (prediction.float().round() == 0).float()).sum()
def TPR(target, prediction, eps=1e-7):
"""
True positive rate metric.
:param target: target value
:param prediction: prediction value
:param eps: epsilon to avoid zero division
:return:
"""
tp = TP(target, prediction)
fn = FN(target, prediction)
s = tp + fn + eps
return tp / s
def TNR(target, prediction, eps=1e-7):
"""
True negative rate metric.
:param target: target value
:param prediction: prediction value
:param eps: epsilon to avoid zero division
:return:
"""
tn = TN(target, prediction)
fp = FP(target, prediction)
s = (tn + fp + eps)
assert (s > 0)
return tn / s
def FPR(target, prediction, eps=1e-7):
"""
False positive rate metric.
:param target: target value
:param prediction: prediction value
:param eps: epsilon to avoid zero division
:return:
"""
fp = FP(target, prediction)
tn = TN(target, prediction)
s = fp + tn + eps
assert (s > 0)
return fp / s
def FNR(target, prediction, eps=1e-7):
"""
False negative rate metric.
:param target: target value
:param prediction: prediction value
:param eps: epsilon to avoid zero division
:return:
"""
fn = FN(target, prediction)
tp = TP(target, prediction)
s = fn + tp + eps
assert (s > 0)
return fn / s
def ACC(target, prediction, eps=1e-7):
"""
Accuracy metric.
:param target: target value
:param prediction: prediction value
:param eps: epsilon to avoid zero division
:return:
"""
tp = TP(target, prediction)
tn = TN(target, prediction)
p = target.sum().float()
n = (target == 0).sum().float()
s = p + n + eps
assert (s > 0)
return (tp + tn) / s
def BACC(target, prediction, eps=1e-7):
"""
Balanced accuracy metric.
:param target: target value
:param prediction: prediction value
:param eps: epsilon to avoid zero division
:return:
"""
tp = TP(target, prediction)
tn = TN(target, prediction)
p = target.sum().float()
n = (target == 0).sum().float()
s = (p + eps) + tn / (n + eps)
assert (s > 0)
return 0.5 * (tp / s)
def precision(target, prediction, eps=1e-7):
"""
Precision metric.
:param target: target value
:param prediction: prediction value
:param eps: epsilon to avoid zero division
:return:
"""
tp = TP(target, prediction)
fp = FP(target, prediction)
s = (tp + fp + eps)
assert (s > 0)
return tp / s
def recall(target, prediction, eps=1e-7):
"""
Recall metric.
:param target: target value
:param prediction: prediction value
:param eps: epsilon to avoid zero division
:return:
"""
tp = TP(target, prediction)
fn = FN(target, prediction)
s = (tp + fn + eps)
assert (s > 0)
return tp / s
def f1_score(target, prediction, eps=1e-7):
"""
F1-score metric.
:param target: target value
:param prediction: prediction value
:param eps: epsilon to avoid zero division
:return:
"""
precision_ = precision(target, prediction)
recall_ = recall(target, prediction)
n = (precision_ * recall_)
s = (precision_ + recall_ + eps)
assert (s > 0)
return 2 * (n / s)
|
# The @npm packages at the root node_modules are used by integration tests
# with `file:../../node_modules/foobar` references
NPM_PACKAGE_ARCHIVES = [
"@angular/animations-12",
"@angular/common-12",
"@angular/core-12",
"@angular/forms-12",
"@angular/platform-browser-12",
"@angular/platform-browser-dynamic-12",
"@angular/platform-server-12",
"@angular/router-12",
"@babel/core",
"@rollup/plugin-babel",
"@rollup/plugin-node-resolve",
"@rollup/plugin-commonjs",
"check-side-effects",
"core-js",
"google-closure-compiler",
"jasmine",
"typescript",
"rxjs",
"systemjs",
"tsickle",
"tslib",
"protractor",
"terser",
"rollup",
"rollup-plugin-sourcemaps",
"@angular/cli",
"@angular-devkit/build-angular",
"@bazel/bazelisk",
"@types/jasmine",
"@types/jasminewd2",
"@types/node",
]
def npm_package_archive_label(package_name):
return package_name.replace("/", "_").replace("@", "") + "_archive"
def npm_package_archives():
"""Function to generate pkg_tar definitions for WORKSPACE yarn_install manual_build_file_contents"""
npm_packages_to_archive = NPM_PACKAGE_ARCHIVES
result = """load("@rules_pkg//:pkg.bzl", "pkg_tar")
"""
for name in npm_packages_to_archive:
label_name = npm_package_archive_label(name)
last_segment_name = name.split("/")[-1]
result += """pkg_tar(
name = "{label_name}",
srcs = ["//{name}:{last_segment_name}__all_files"],
extension = "tar.gz",
strip_prefix = "/external/npm/node_modules/{name}",
# should not be built unless it is a dependency of another rule
tags = ["manual"],
)
""".format(name = name, label_name = label_name, last_segment_name = last_segment_name)
return result
|
# Copyright (C) 2016 Benoit Myard <myardbenoit@gmail.com>
# Released under the terms of the BSD license.
class BaseRemoteStorage(object):
def __init__(self, config, root):
self.config = config
self.root = root
def __enter__(self):
raise NotImplementedError
def __exit__(self, *args):
pass
def push(self, filename):
raise NotImplementedError
def pull(self, path):
raise NotImplementedError
|
get_f = float(input("Enter temperature in Fahrenheit: "))
convert_c = (get_f - 32) * 5/9
print(f"{get_f} in Fahrenheit is equal to {convert_c} in Celsius")
|
#!/usr/bin/env python
# coding: utf-8
# # Exercise 1. Regex and Parsing challenges :
# ### writer : Faranak Alikhah 1954128
# ### 14.Regex Substitution :
# In[ ]:
for _ in range(int(input())):
line = input()
while '&&'in line or '||'in line:
line = line.replace("&&", "and").replace("||", "or")
print(line)
#
#
|
def is_valid_story_or_comment(form_data):
parent = form_data.get('parent')
title = bool(form_data.get('title'))
url = bool(form_data.get('url'))
text = bool(form_data.get('text'))
if parent:
if title or url:
return (False, 'Invalid fields for a comment')
if not text:
return (False, 'Comment field is missing')
else:
if not title:
return (False, 'Missing title field')
if text and url:
return (False, 'Please enter either URL or text, but not both')
return (True, 'success')
|
# метод трапеций s = (f(x[i]) + f(x[i+1])/2*h
def f(x):
return x
def integral(a, b, n, f):
total = 0
h = (b-a)/n
for i in range(n):
total += (f(a) + f(a + h))
a += h
total *= h/2
return total
a, b = map(float, input('Введите границы интегрирования: ').split())
n = int(input('Введите количество участков разбиения для интегрирования: '))
I = integral(a, b, n, f)
print('Интеграл равен: {:.4f}'.format(I))
print(I)
|
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self, values = []):
self.head = None
for value in values:
self.append(value)
def append(self, value):
if self.head is None:
self.head = Node(value)
return
node = self.head
while node.next:
node = node.next
node.next = Node(value)
def search(self, value):
if self.head is None:
return False
node = self.head
while node:
if node.value == value:
return True
node = node.next
return False
def delete(self, value):
if self.head is None:
return
if self.head.value == value:
self.head = self.head.next
return
node = self.head
while node.next:
if node.next.value == value:
node.next = node.next.next
return
node = node.next
def pop(self):
if self.head is None:
return None
node = self.head
self.head = self.head.next
return node.value
def to_list(self):
out = []
node = self.head
while node is not None:
out.append(node.value)
node = node.next
return out
# Test Case
linked_list = LinkedList([5, 7, -1, 0.9, 71])
print("Linked List tests:")
print (" Initialization: " + "Pass" if (linked_list.to_list() == [5, 7, -1, 0.9, 71]) else "Fail")
linked_list.delete(-1)
print (" Delete: " + "Pass" if (linked_list.to_list() == [5, 7, 0.9, 71]) else "Fail")
print (" Search: " + "Pass" if (linked_list.search(0.9)) else "Fail")
print (" Search: " + "Pass" if (not linked_list.search(55)) else "Fail")
linked_list.append(91)
print (" Append: " + "Pass" if (linked_list.to_list() == [5, 7, 0.9, 71, 91]) else "Fail")
print (" Pop: " + "Pass" if (linked_list.pop() == 5) else "Fail")
|
""" A Symbol in a pushdown automaton """
class Symbol:
""" A Symbol in a pushdown automaton
Parameters
----------
value : any
The value of the state
"""
def __init__(self, value):
self._value = value
def __hash__(self):
return hash(str(self._value))
@property
def value(self):
""" Returns the value of the symbol
Returns
----------
value: The value
any
"""
return self._value
def __eq__(self, other):
if isinstance(other, Symbol):
return self._value == other.value
return False
def __repr__(self):
return "Symbol(" + str(self._value) + ")"
|
loss_fns = ['retrain_regu_mas', 'retrain_regu_mine', 'retrain_regu_minen', 'retrain_regu_fisher', 'retrain_regu_fishern',\
'retrain', 'retrain_regu', 'retrain_regu_selfless']#'retrain_regu_mine3', 'cnn'
model_log_map = {'fishern': 'EWCN', 'mine': 'Arms', 'minen': 'ArmsN', 'regu': 'RetrainRegu', \
'fisher': 'EWC', 'mas': 'MAS', 'selfless': 'Selfless', 'retrain':'Retrain'} |
def digit_to_text(digit):
if digit == 1:
return "one"
elif digit == 2:
return "two"
elif digit == 3:
return "three"
elif digit == 4:
return "four"
elif digit == 5:
return "five"
elif digit == 6:
return "six"
elif digit == 7:
return "seven"
elif digit == 8:
return "eight"
elif digit == 9:
return "nine"
else:
return None
def teen_to_text(digit):
if digit == 1:
return "ten"
elif digit == 11:
return "eleven"
elif digit == 12:
return "twelve"
elif digit == 13:
return "thirteen"
elif digit == 14:
return "fourteen"
elif digit == 15:
return "fifteen"
elif digit == 16:
return "sixteen"
elif digit == 17:
return "seventeen"
elif digit == 18:
return "eighteen"
elif digit == 19:
return "nineteen"
else:
return None
def convert_to_text(num):
text = ""
hundreds = num // 100
tens = num // 10
if hundreds:
text += digit_to_text(hundreds) + " hundred"
if tens:
if tens == 1:
if num > 100:
real_ten = real_ten - (hundreds * 100)
else:
real_ten = num
text += teen_to_text(real_ten)
return text
print(convert_to_text(1))
print(convert_to_text(11))
print(convert_to_text(16))
print(convert_to_text(22))
|
def get_schema():
return {
'type': 'object',
'properties':
{
'aftale_id': {'type': 'string'},
'state': {'type': 'string'},
'gateway_fejlkode': {'type': 'string'}
},
'required': ['aftale_id', 'gateway_fejlkode']
}
|
w = h = 600
s = 40
off = s/4
shift = 3
x = y = 0
newPage(w, h)
strokeWidth(2)
stroke(.5)
while (y * s) < h:
while (x *s) < w:
fill(0) if x % 2 == 0 else fill(1)
rect(off + x * s, y * s, s, s)
x += 1
if y % 3 == 0: off *= -1
off += s/4
x = 0
y += 1
saveImage('imgs/cafe_wall.png') |
"""
Caesar Cipher Encryptor:
Given a non-empty string of lowercase letters and a non-negative integer representing a key,
write a function that returns a new string obtained by shifting every letter in the input string by k positions in the alphabet,
where k is the key.
Note that letters should "wrap" around the alphabet;
in other words, the letter z shifted by one returns the letter a.
https://www.algoexpert.io/questions/Caesar%20Cipher%20Encryptor
"""
# O(n) time | O(n) space
def caesarCipherEncryptor(string, key):
characters = list(string)
# Calculate where to move the character
for idx, char in enumerate(characters):
char_unicode = ord(char) + key
# make sure key is < ord('z') else subtract 26
while char_unicode > ord('z'):
char_unicode -= 26
# replace moved character in our characters
characters[idx] = chr(char_unicode)
return "".join(characters)
# O(n) time | O(n) space
def caesarCipherEncryptor1(string, key):
newLetters = []
newKey = key % 26 # handle large numbers
for letter in string:
newLetters.append(getNewLetter(letter, newKey))
return "".join(newLetters)
def getNewLetter(letter, key):
newLetterCode = ord(letter) + key
# # return within alphabet
return chr(newLetterCode) if newLetterCode <= 122 else chr(96 + newLetterCode % 122)
"""
For each character in the string calculate where to move it
# convert characters/string into array for better runtime
1. Iterate through each character
2. Calculate where to move the character
- get it's unicode value: ord(char)
- add/move it by the key: ord(char) + key
- make sure key is < ord('z') else subtract 26 - to return it withoin the alphabet
- convert back to char chr(result from above)
3. replace character in our characters
4. convert characters to string and return
"""
print(caesarCipherEncryptor("abcxyz", 1))
print(caesarCipherEncryptor("abcxyz", 100))
|
class Pile:
"""Classe modélisant une Pile"""
# Constructeur
def __init__(self, iterable=None):
if iterable is None:
iterable = []
self.__elements = list(iterable)
def est_vide(self):
return len(self.__elements) == 0
def sommet(self):
return self.__elements[-1]
def empiler(self, e):
self.__elements.append(e)
def depiler(self):
return self.__elements.pop()
def afficher(self):
print(self.__elements)
def __str__(self):
return f'{self.__elements}' |
class Solution:
def recoverTree(self, root):
def inorder(node):
if node.left:
yield from inorder(node.left)
yield node
if node.right:
yield from inorder(node.right)
swap1 = swap2 = smaller = None
for node in inorder(root):
if smaller and smaller.val > node.val:
if not swap1:
swap1 = smaller
swap2 = node
smaller = node
if swap1:
swap1.val, swap2.val = swap2.val, swap1.val |
'''
80. Remove Duplicates from Sorted Array II
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
'''
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# TODO
pass
class Solution2:
def removeDuplicates(self, nums):
'''
Incredible solution from https://leetcode.com/stefanpochmann
'''
i = 0
AT_MOST = 2
for num in nums:
if i<AT_MOST or num > nums[i-AT_MOST]:
nums[i]=num
i+=1
print(nums)
return i
if __name__ == "__main__":
s = Solution()
t1 = [1,1,1,2,2,3]
assert s.removeDuplicates(t1)==5
t2 = [0,0,1,1,1,1,2,3,3]
assert s.removeDuplicates(t2)==7
t3 = [1,1,2,3,4,5,5,5,5,5,5,5,5]
assert s.removeDuplicates(t3)==7 |
expected_output = {
"dhcp_guard_policy_config":{
"policy_name":"pol1",
"trusted_port":True,
"device_role":"dhcp server",
"max_preference":255,
"min_preference":0,
"access_list":"acl2",
"prefix_list":"abc",
"targets":{
"vlan 2":{
"target":"vlan 2",
"type":"VLAN",
"feature":"DHCP Guard",
"target_range":"vlan all"
},
"vlan 3":{
"target":"vlan 3",
"type":"VLAN",
"feature":"DHCP Guard",
"target_range":"vlan all"
},
"vlan 4":{
"target":"vlan 4",
"type":"VLAN",
"feature":"DHCP Guard",
"target_range":"vlan all"
},
"vlan 5":{
"target":"vlan 5",
"type":"VLAN",
"feature":"DHCP Guard",
"target_range":"vlan all"
},
"vlan 6":{
"target":"vlan 6",
"type":"VLAN",
"feature":"DHCP Guard",
"target_range":"vlan all"
},
"vlan 7":{
"target":"vlan 7",
"type":"VLAN",
"feature":"DHCP Guard",
"target_range":"vlan all"
},
"vlan 8":{
"target":"vlan 8",
"type":"VLAN",
"feature":"DHCP Guard",
"target_range":"vlan all"
},
"vlan 9":{
"target":"vlan 9",
"type":"VLAN",
"feature":"DHCP Guard",
"target_range":"vlan all"
},
"vlan 10":{
"target":"vlan 10",
"type":"VLAN",
"feature":"DHCP Guard",
"target_range":"vlan all"
}
}
}
} |
class Person:
Y = "You are young."
T = "You are a teenager."
O = "You are old."
age = int(0)
def __init__(self, initialAge):
if initialAge < 0:
print('Age is not valid, setting age to 0.')
else:
self.age = initialAge
def amIOld(self):
if self.age < 13:
print(self.Y)
elif self.age < 18:
print(self.T)
else:
print(self.O)
def yearPasses(self):
self.age += 1
|
"""
Stuff
"""
class Sequence(object):
def __init__(self, *_seq):
self.seq = tuple(_seq)
pass; |
# -*- coding: utf-8 -*-
# py_ornery.py
"""
This type of object gets along with nobody!
or·ner·y
ˈôrn(ə)rē/
adjective North American informal
adjective: ornery
bad-tempered and combative.
"some hogs are just mean and ornery"
synonyms: grouchy, grumpy, cranky, crotchety, cantankerous,
bad-tempered, ill-tempered, dyspeptic, irascible, waspish
自 = self in Chinese, disregard errors
Using this character in place of self to prove self is
not a keyword, just a placeholder. Any legal name will
work, just "self" is universally accepted by convention.
Make sure you keep the utf-8 directive at the top,
especially on Windows.
"""
class Ornery:
def __init__(自, name="Fred"):
自.name = name
print("A sourpuss is born!")
def __getitem__(自, key):
return "How dare you touch me with those brackets!"
def __call__(自, *args, **kwargs):
return "Don't call me at home!"
def __getattr__(自, attr):
return "I'm insulted you'd suppose I'd have '{}'".format(attr)
def __repr__(自):
return "Don't bother me! Go away."
def __invert__(自):
return "I can't invert, are you kidding?"
def main():
obj = Ornery() # __init__
print(obj) # __repr__
print(obj.mood) # __getattr__
print(obj("Hello?")) # __call__
print(~obj) # __invert__
if __name__ == "__main__":
main() |
# Improved Position Calculation
# objectposncalc.py (improved)
print("This program calculates an object's final position.")
do_calculation = True
while(do_calculation):
# Get information about the object from the user
while (True):
try:
initial_position = float(input("\nEnter the object's initial position: "))
except ValueError:
print("The value you entered is invalid. Only numerical values are valid.");
else:
break
while (True):
try:
initial_velocity = float(input("Enter the object's initial velocity: "))
except ValueError:
print("The value you entered is invalid. Only numerical values are valid.");
else:
break
while (True):
try:
acceleration = float(input("Enter the object's acceleration: "))
except ValueError:
print("The value you entered is invalid. Only numerical values are valid.");
else:
break
while (True):
try:
time_elapsed = float(input("Enter the time that has elapsed: "))
if (time_elapsed < 0):
print("Negative times are not allowed.")
continue
except ValueError:
print("The value you entered is invalid. Only numerical values are valid.");
else:
break
# Calculate the final position
final_position = initial_position + initial_velocity * time_elapsed + 0.5 * acceleration * time_elapsed ** 2
# Output final position
print("\nThe object's final position is", final_position)
# Check if the user wants to perform another calculation
another_calculation = input("\nDo you want to perform another calculation? (y/n): ")
if (another_calculation != "y"):
do_calculation = False
|
CELL_DIM = 46
NEXT_CELL_DISTANCE = 66
NEXT_ROW_DISTANCE_V = 57
NEXT_ROW_DISTANCE_H = 33
INITIAL_V = 44
INITIAL_H = 230
|
# (01-Gabarito/043.py)) Desenvolva uma lógica que leia o peso e a altura de uma pessoa,
# calcule seu IMC e mostre seu status, de acordo com a tabela abaixo:
# - Abaixo de 18.5: Abaixo do Peso
# - Entre 18.5 e 25: Peso ideal
# - 25 até 30: Sobrepeso
# - 30 até 40: Obesidade
# - Acima de 40: Obesidade mórbida
peso = float(input('Digite seu peso em Kg\t: '))
altura = float(input('Digite seu peso em M\t: '))
imc = round((peso / (altura * altura)),2)
print('')
if imc < 18.5:
print('Seu IMC é {}. Você está abaixo do peso! Vai cuidar, homem!!!'.format(imc))
elif imc >= 18.5 and imc <= 25:
print('Seu IMC é {}. Você está no peso ideal! Parabéns!!!'.format(imc))
elif imc > 25 and imc <= 30:
print('Seu IMC é {}. Você está com sobrebeso. Se oriente!!!'.format(imc))
elif imc > 30 and imc <= 40:
print('Seu IMC é {}. Você está obeso. Cuide não que vc morre!!!'.format(imc))
else:
print('Seu IMC é {}. Você está com obesidade mórbida. Você já morreu. Tá faltando só ser enterrado!!!'.format(imc))
|
#ex035: Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo.
print('\033[1;32mANALISANDO TRIÂNGULOS\033[m')
r1 = float(input('Primeiro segmento: '))
r2 = float(input('Segundo segmento: '))
r3 = float(input('Terceiro segmento: '))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
print('Os segmentos podem formar triângulo.')
else:
print('Os segmentos não podem formar triângulo.')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.