content
stringlengths
7
1.05M
# To Find The Total Number Of Digits In A Number N = int(input("Enter The number")) count = 0 while(N!=0): N = (N-N%10)/10 count+=1 print(count)
# Napisz funkcję, która obliczy pole powierzchni prostokąta na podstawie długości jego boków. def rectangle_area(long, width): return long * width print(f"Pole prostokąta o bokach 5 i 18 to {rectangle_area(5, 18)}")
class DummyObject: # When we try to access any attribute of the # dummy object, it will return himself. def __getattr__(self, item): return self # And if dummy object is called, nothing is being done, # and error created if the function did not exist. def __call__(self, *args, **kwargs): pass dummy_object = DummyObject()
#Calculate Value of PI using the Neelkantha method to nth digit using upto 50 trailing digits j = 3.0 k=1 for i in range(2, 4000000, 2): #Change the Desired End Step to get a better nth value k = k+1 if k % 2 ==0: j = j+ 4/(i*(i+1)*(i+2)) else: j = j- 4/(i*(i+1)*(i+2)) kaggle = input('Enter value of n upto which you want to display the value of PI:') a = '%.'+kaggle+'f' print (a%(j))
class Solution: # bottom up def minimumTotal(self, triangle: 'List[List[int]]') -> 'int': if not triangle: return rst = triangle[-1] for level in range(len(triangle)-2,-1,-1): for i in range(0,len(triangle[level]),1): rst[i] = triangle[level][i] + min(rst[i], rst[i+1]) return rst[0]
# -*- coding: utf-8 -*- """ Exceptions ========== Specific application exceptions. """ class PyCssStyleguideException(Exception): """ Exception base. You should never use it directly except for test purpose. Instead make or use a dedicated exception related to the error context. """ pass class SerializerError(PyCssStyleguideException): """ Exception to raise when there is a syntax issue during serialization. """ pass class StyleguideValidationError(PyCssStyleguideException): """ Exception to raise when there is invalid naming in reference rules and properties. """ pass
def digit_sum(): a=int(input('Enter an integer ')) sum=0 for i in range(1,a+1): sum+=i if(i!=a): print(i,end='+') else: print(a,'=',sum) digit_sum()
""" map applies a function to all values in one or more iterables filter runs each value through a function and creates an iterable with all truthy values """ # map a_list = list(range(10)) b_list = list(range(10, 30)) c_list = list(range(30, 60)) def add(value1, value2): return value1 + value2 added = [] for value1, value2 in zip(a_list, b_list): added.append(add(value1, value2)) added_comp = [add(value1, value2) for value1, value2 in zip(a_list, b_list)] added_map = list(map(add, a_list, b_list)) added_lambda = list(map(lambda x, y: x + y, a_list, b_list)) # filter def div_by_3(value): return not value % 3 by_3 = [] for value in a_list: if div_by_3(value): by_3.append(value) by_3_filter = list(filter(div_by_3, a_list)) by_3_lambda = list(filter(lambda value: not value % 3, a_list)) by_3_map = list(map(div_by_3, a_list)) # map and filter def to_point(x, y=None, z=None): _x = f"x: {x}" _y = f"y: {y}" if y else y _z = f"z: {z}" if z else z return ", ".join(filter(None, [_x, _y, _z])) x_points = list(map(to_point, a_list)) xy_points = list(map(to_point, a_list, b_list)) xyz_points = list(map(to_point, a_list, b_list, c_list))
with open("Crime.csv",'r') as file: mainlist=[] list2=[] count=[] i=0 j=1 k=2 countvalue=0 for line in file: line.strip() line.split(",") print(line) """ if line[2] in mainlist: mainlist.index(line[7]) count[index]+=1 list2[k]=count[index] else: list1.append(line[7]) list2[i]=list[8] list2[j]=list[7] count.append(1) list2[k]=count[index1] i+=3 j+=3 k+=3 """
""" Sams Teach Yourself Python in 24 Hours by Katie Cunningham Hour 3: Logic in Programming Exercise: 1. a) Given a number, write a snippet of code that will print "You have money" if the number is positive, "You're out" if the number is zero, "You seem to be in debt" if less than zero" Your code should have an if statement, an elif statement, and an else. """ #Hour 3: Logic in Programming balance = float(input("Insert Money Amount: $")) if balance > 0: print ("You have money") elif balance == 0: print ("You're out") else: print ("You seem to be in debt")
"""init py module tells python this folder contains a package. You don't particularly need this file for python 3.6. """
# commaCode script # Chapter 4 - Lists def func(arg): text = "" for i in range(len(arg)): text = text + arg[i] + ". " if i == len(arg) - 2: text += "and " return text spam = ['apples', 'bananas', 'tofu', 'cats'] print(func(spam))
# https://leetcode.com/problems/is-subsequence/ class Solution: def isSubsequence(self, s: str, t: str) -> bool: if not s: return True if len(t) < len(s): return False s_idx = 0 for t_idx in range(len(t)): if s[s_idx] == t[t_idx]: s_idx += 1 if s_idx == len(s): return True return False
class Validator(object): def __init__(self): self.isValid = False def validate(self, number): try: if number is None: return self.isValid if isinstance(number, str) and number.find(' ') >= 0: number = number.replace(' ', '') self.isValid = number.isdigit() and len(number) == 10 if self.isValid: multiplier = 10 n = 0 numArray = list(number) for value in numArray: if multiplier == 1: break n = n + (int(value) * multiplier) multiplier = multiplier - 1 n = 11 - (n % 11) if n == 11: n = 0 if n == 10: self.isValid = False return self.isValid self.isValid = int(numArray[9]) == n return self.isValid except Exception: self.isValid = False return self.isValid
def loss_disc(disc, x_real, x_fake): """Compute the discriminator loss for `x_real` and `x_fake` given `disc` Args: disc: The discriminator x_real (ndarray): An array of shape (N,) that contains the real samples x_fake (ndarray): An array of shape (N,) that contains the fake samples Returns: ndarray: The discriminator loss """ # Loss for real data label_real = 1 loss_real = label_real * torch.log(disc.classify(x_real)) # Loss for fake data label_fake = 0 loss_fake = (1 - label_fake) * torch.log(1 - disc.classify(x_fake)) return torch.cat([loss_real, loss_fake]) # add event to airtable atform.add_event('Coding Exercise 2.1: Implement Discriminator Loss') disc = DummyDisc() gen = DummyGen() x_real = get_data() x_fake = gen.sample() ## Uncomment to check your function ld = loss_disc(disc, x_real, x_fake) with plt.xkcd(): plotting_ld(ld)
message = input().split() for word in message: number = "" letters = "" for char in word: if char.isdigit(): number += char else: letters += char first_letter = chr(int(number)) current_word = first_letter + letters current_word = list(current_word) current_word[1], current_word[-1] = current_word[-1], current_word[1] current_word = "".join(current_word) print(current_word, end=" ") # data input # 72olle 103doo 100ya
def prog(l, noun=12, verb=2): res = list(map(int, l.split(','))) res[1] = noun res[2] = verb for i in range(0, len(l), 4): if res[i] == 1: res[res[i+3]] = res[res[i+1]] + res[res[i+2]] elif res[i] == 2: res[res[i+3]] = res[res[i+1]] * res[res[i+2]] elif res[i] == 99: return res else: raise ValueError(i) input = '1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,10,19,2,6,19,23,1,23,5,27,1,27,13,31,2,6,31,35,1,5,35,39,1,39,10,43,2,6,43,47,1,47,5,51,1,51,9,55,2,55,6,59,1,59,10,63,2,63,9,67,1,67,5,71,1,71,5,75,2,75,6,79,1,5,79,83,1,10,83,87,2,13,87,91,1,10,91,95,2,13,95,99,1,99,9,103,1,5,103,107,1,107,10,111,1,111,5,115,1,115,6,119,1,119,10,123,1,123,10,127,2,127,13,131,1,13,131,135,1,135,10,139,2,139,6,143,1,143,9,147,2,147,6,151,1,5,151,155,1,9,155,159,2,159,6,163,1,163,2,167,1,10,167,0,99,2,14,0,0' if __name__ == '__main__': print(prog(input)[0])
# # PySNMP MIB module CISCO-LWAPP-AAA-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LWAPP-AAA-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:47:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint") CLSecKeyFormat, = mibBuilder.importSymbols("CISCO-LWAPP-TC-MIB", "CLSecKeyFormat") cLWlanIndex, = mibBuilder.importSymbols("CISCO-LWAPP-WLAN-MIB", "cLWlanIndex") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") InetAddressType, InetPortNumber, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetPortNumber", "InetAddress") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") Integer32, TimeTicks, iso, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, Counter64, ObjectIdentity, NotificationType, IpAddress, Bits, Gauge32, ModuleIdentity, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "TimeTicks", "iso", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "Counter64", "ObjectIdentity", "NotificationType", "IpAddress", "Bits", "Gauge32", "ModuleIdentity", "MibIdentifier") MacAddress, TimeInterval, DisplayString, TruthValue, RowStatus, TextualConvention, StorageType = mibBuilder.importSymbols("SNMPv2-TC", "MacAddress", "TimeInterval", "DisplayString", "TruthValue", "RowStatus", "TextualConvention", "StorageType") ciscoLwappAAAMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 598)) ciscoLwappAAAMIB.setRevisions(('2010-07-25 00:00', '2006-11-21 00:00',)) if mibBuilder.loadTexts: ciscoLwappAAAMIB.setLastUpdated('201007250000Z') if mibBuilder.loadTexts: ciscoLwappAAAMIB.setOrganization('Cisco Systems Inc.') ciscoLwappAAAMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 598, 0)) ciscoLwappAAAMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 598, 1)) ciscoLwappAAAMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 598, 2)) claConfigObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1)) claStatusObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 2)) claPriorityTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 1), ) if mibBuilder.loadTexts: claPriorityTable.setStatus('current') claPriorityEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-LWAPP-AAA-MIB", "claPriorityAuth")) if mibBuilder.loadTexts: claPriorityEntry.setStatus('current') claPriorityAuth = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("local", 1), ("radius", 2), ("tacacsplus", 3)))) if mibBuilder.loadTexts: claPriorityAuth.setStatus('current') claPriorityOrder = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 1, 1, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 10))).setMaxAccess("readwrite") if mibBuilder.loadTexts: claPriorityOrder.setStatus('current') claTacacsServerTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 2), ) if mibBuilder.loadTexts: claTacacsServerTable.setStatus('current') claTacacsServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 2, 1), ).setIndexNames((0, "CISCO-LWAPP-AAA-MIB", "claTacacsServerType"), (0, "CISCO-LWAPP-AAA-MIB", "claTacacsServerPriority")) if mibBuilder.loadTexts: claTacacsServerEntry.setStatus('current') claTacacsServerType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("authentication", 1), ("authorization", 2), ("accounting", 3)))) if mibBuilder.loadTexts: claTacacsServerType.setStatus('current') claTacacsServerPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 2, 1, 2), Unsigned32()) if mibBuilder.loadTexts: claTacacsServerPriority.setStatus('current') claTacacsServerAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 2, 1, 3), InetAddressType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: claTacacsServerAddressType.setStatus('current') claTacacsServerAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 2, 1, 4), InetAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: claTacacsServerAddress.setStatus('current') claTacacsServerPortNum = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 2, 1, 5), InetPortNumber()).setMaxAccess("readcreate") if mibBuilder.loadTexts: claTacacsServerPortNum.setStatus('current') claTacacsServerEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 2, 1, 6), TruthValue().clone('true')).setMaxAccess("readcreate") if mibBuilder.loadTexts: claTacacsServerEnabled.setStatus('current') claTacacsServerSecretType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 2, 1, 7), CLSecKeyFormat()).setMaxAccess("readcreate") if mibBuilder.loadTexts: claTacacsServerSecretType.setStatus('current') claTacacsServerSecret = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 2, 1, 8), DisplayString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: claTacacsServerSecret.setStatus('current') claTacacsServerTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 2, 1, 9), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(5, 30)).clone(5)).setUnits('seconds').setMaxAccess("readcreate") if mibBuilder.loadTexts: claTacacsServerTimeout.setStatus('current') claTacacsServerStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 2, 1, 10), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: claTacacsServerStorageType.setStatus('current') claTacacsServerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 2, 1, 11), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: claTacacsServerRowStatus.setStatus('current') claWlanTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 3), ) if mibBuilder.loadTexts: claWlanTable.setStatus('current') claWlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 3, 1), ).setIndexNames((0, "CISCO-LWAPP-WLAN-MIB", "cLWlanIndex")) if mibBuilder.loadTexts: claWlanEntry.setStatus('current') claWlanAcctServerEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 3, 1, 1), TruthValue().clone('true')).setMaxAccess("readwrite") if mibBuilder.loadTexts: claWlanAcctServerEnabled.setStatus('current') claWlanAuthServerEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 3, 1, 2), TruthValue().clone('true')).setMaxAccess("readwrite") if mibBuilder.loadTexts: claWlanAuthServerEnabled.setStatus('current') claSaveUserData = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 9), TruthValue().clone('true')).setMaxAccess("readwrite") if mibBuilder.loadTexts: claSaveUserData.setStatus('current') claWebRadiusAuthentication = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("pap", 1), ("chap", 2), ("md5-chap", 3))).clone('pap')).setMaxAccess("readwrite") if mibBuilder.loadTexts: claWebRadiusAuthentication.setStatus('current') claRadiusFallbackMode = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("off", 1), ("passive", 2), ("active", 3))).clone('off')).setMaxAccess("readwrite") if mibBuilder.loadTexts: claRadiusFallbackMode.setStatus('current') claRadiusFallbackUsername = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 12), SnmpAdminString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: claRadiusFallbackUsername.setStatus('current') claRadiusFallbackInterval = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 13), TimeInterval().subtype(subtypeSpec=ValueRangeConstraint(180, 3600)).clone(300)).setUnits('seconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: claRadiusFallbackInterval.setStatus('current') claRadiusAuthMacDelimiter = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("noDelimiter", 1), ("colon", 2), ("hyphen", 3), ("singleHyphen", 4))).clone('hyphen')).setMaxAccess("readwrite") if mibBuilder.loadTexts: claRadiusAuthMacDelimiter.setStatus('current') claRadiusAcctMacDelimiter = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("noDelimiter", 1), ("colon", 2), ("hyphen", 3), ("singleHyphen", 4))).clone('hyphen')).setMaxAccess("readwrite") if mibBuilder.loadTexts: claRadiusAcctMacDelimiter.setStatus('current') claAcceptMICertificate = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 16), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: claAcceptMICertificate.setStatus('current') claAcceptLSCertificate = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 17), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: claAcceptLSCertificate.setStatus('current') claAllowAuthorizeLscApAgainstAAA = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 18), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: claAllowAuthorizeLscApAgainstAAA.setStatus('current') claRadiusServerTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 2, 1), ) if mibBuilder.loadTexts: claRadiusServerTable.setStatus('current') claRadiusServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 2, 1, 1), ).setIndexNames((0, "CISCO-LWAPP-AAA-MIB", "claRadiusReqId")) if mibBuilder.loadTexts: claRadiusServerEntry.setStatus('current') claRadiusReqId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 2, 1, 1, 1), Unsigned32()) if mibBuilder.loadTexts: claRadiusReqId.setStatus('current') claRadiusAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 2, 1, 1, 2), InetAddressType()).setMaxAccess("readonly") if mibBuilder.loadTexts: claRadiusAddressType.setStatus('current') claRadiusAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 2, 1, 1, 3), InetAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: claRadiusAddress.setStatus('current') claRadiusPortNum = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 2, 1, 1, 4), InetPortNumber()).setMaxAccess("readonly") if mibBuilder.loadTexts: claRadiusPortNum.setStatus('current') claRadiusWlanIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 2, 1, 1, 5), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 17))).setMaxAccess("readonly") if mibBuilder.loadTexts: claRadiusWlanIdx.setStatus('current') claRadiusClientMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 2, 1, 1, 6), MacAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: claRadiusClientMacAddress.setStatus('current') claRadiusUserName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 2, 1, 1, 7), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: claRadiusUserName.setStatus('current') claDBCurrentUsedEntries = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 2, 2), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: claDBCurrentUsedEntries.setStatus('current') claRadiusServerGlobalActivatedEnabled = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 4), TruthValue().clone('true')).setMaxAccess("readwrite") if mibBuilder.loadTexts: claRadiusServerGlobalActivatedEnabled.setStatus('current') claRadiusServerGlobalDeactivatedEnabled = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 5), TruthValue().clone('true')).setMaxAccess("readwrite") if mibBuilder.loadTexts: claRadiusServerGlobalDeactivatedEnabled.setStatus('current') claRadiusServerWlanActivatedEnabled = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 6), TruthValue().clone('true')).setMaxAccess("readwrite") if mibBuilder.loadTexts: claRadiusServerWlanActivatedEnabled.setStatus('current') claRadiusServerWlanDeactivatedEnabled = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 7), TruthValue().clone('true')).setMaxAccess("readwrite") if mibBuilder.loadTexts: claRadiusServerWlanDeactivatedEnabled.setStatus('current') claRadiusReqTimedOutEnabled = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 598, 1, 1, 8), TruthValue().clone('true')).setMaxAccess("readwrite") if mibBuilder.loadTexts: claRadiusReqTimedOutEnabled.setStatus('current') ciscoLwappAAARadiusServerGlobalActivated = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 598, 0, 1)).setObjects(("CISCO-LWAPP-AAA-MIB", "claRadiusAddressType"), ("CISCO-LWAPP-AAA-MIB", "claRadiusAddress"), ("CISCO-LWAPP-AAA-MIB", "claRadiusPortNum")) if mibBuilder.loadTexts: ciscoLwappAAARadiusServerGlobalActivated.setStatus('current') ciscoLwappAAARadiusServerGlobalDeactivated = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 598, 0, 2)).setObjects(("CISCO-LWAPP-AAA-MIB", "claRadiusAddressType"), ("CISCO-LWAPP-AAA-MIB", "claRadiusAddress"), ("CISCO-LWAPP-AAA-MIB", "claRadiusPortNum")) if mibBuilder.loadTexts: ciscoLwappAAARadiusServerGlobalDeactivated.setStatus('current') ciscoLwappAAARadiusServerWlanActivated = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 598, 0, 3)).setObjects(("CISCO-LWAPP-AAA-MIB", "claRadiusAddressType"), ("CISCO-LWAPP-AAA-MIB", "claRadiusAddress"), ("CISCO-LWAPP-AAA-MIB", "claRadiusPortNum"), ("CISCO-LWAPP-AAA-MIB", "claRadiusWlanIdx")) if mibBuilder.loadTexts: ciscoLwappAAARadiusServerWlanActivated.setStatus('current') ciscoLwappAAARadiusServerWlanDeactivated = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 598, 0, 4)).setObjects(("CISCO-LWAPP-AAA-MIB", "claRadiusAddressType"), ("CISCO-LWAPP-AAA-MIB", "claRadiusAddress"), ("CISCO-LWAPP-AAA-MIB", "claRadiusPortNum"), ("CISCO-LWAPP-AAA-MIB", "claRadiusWlanIdx")) if mibBuilder.loadTexts: ciscoLwappAAARadiusServerWlanDeactivated.setStatus('current') ciscoLwappAAARadiusReqTimedOut = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 598, 0, 5)).setObjects(("CISCO-LWAPP-AAA-MIB", "claRadiusAddressType"), ("CISCO-LWAPP-AAA-MIB", "claRadiusAddress"), ("CISCO-LWAPP-AAA-MIB", "claRadiusPortNum"), ("CISCO-LWAPP-AAA-MIB", "claRadiusClientMacAddress"), ("CISCO-LWAPP-AAA-MIB", "claRadiusUserName")) if mibBuilder.loadTexts: ciscoLwappAAARadiusReqTimedOut.setStatus('current') ciscoLwappAAAMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 598, 2, 1)) ciscoLwappAAAMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 598, 2, 2)) ciscoLwappAAAMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 598, 2, 1, 1)).setObjects(("CISCO-LWAPP-AAA-MIB", "ciscoLwappAAAMIBConfigGroup"), ("CISCO-LWAPP-AAA-MIB", "ciscoLwappAAAMIBNotifsGroup"), ("CISCO-LWAPP-AAA-MIB", "ciscoLwappAAAMIBStatusObjsGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappAAAMIBCompliance = ciscoLwappAAAMIBCompliance.setStatus('deprecated') ciscoLwappAAAMIBComplianceRev1 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 598, 2, 1, 2)).setObjects(("CISCO-LWAPP-AAA-MIB", "ciscoLwappAAAMIBConfigGroup"), ("CISCO-LWAPP-AAA-MIB", "ciscoLwappAAAMIBSaveUserConfigGroup"), ("CISCO-LWAPP-AAA-MIB", "ciscoLwappAAAMIBRadiusConfigGroup"), ("CISCO-LWAPP-AAA-MIB", "ciscoLwappAAAMIBAPPolicyConfigGroup"), ("CISCO-LWAPP-AAA-MIB", "ciscoLwappAAAMIBWlanAuthAccServerConfigGroup"), ("CISCO-LWAPP-AAA-MIB", "ciscoLwappAAAMIBNotifsGroup"), ("CISCO-LWAPP-AAA-MIB", "ciscoLwappAAAMIBStatusObjsGroup"), ("CISCO-LWAPP-AAA-MIB", "ciscoLwappAAAMIBDBEntriesGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappAAAMIBComplianceRev1 = ciscoLwappAAAMIBComplianceRev1.setStatus('current') ciscoLwappAAAMIBConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 598, 2, 2, 1)).setObjects(("CISCO-LWAPP-AAA-MIB", "claPriorityOrder"), ("CISCO-LWAPP-AAA-MIB", "claTacacsServerAddressType"), ("CISCO-LWAPP-AAA-MIB", "claTacacsServerAddress"), ("CISCO-LWAPP-AAA-MIB", "claTacacsServerPortNum"), ("CISCO-LWAPP-AAA-MIB", "claTacacsServerEnabled"), ("CISCO-LWAPP-AAA-MIB", "claTacacsServerSecretType"), ("CISCO-LWAPP-AAA-MIB", "claTacacsServerSecret"), ("CISCO-LWAPP-AAA-MIB", "claTacacsServerTimeout"), ("CISCO-LWAPP-AAA-MIB", "claTacacsServerStorageType"), ("CISCO-LWAPP-AAA-MIB", "claTacacsServerRowStatus"), ("CISCO-LWAPP-AAA-MIB", "claRadiusServerGlobalActivatedEnabled"), ("CISCO-LWAPP-AAA-MIB", "claRadiusServerGlobalDeactivatedEnabled"), ("CISCO-LWAPP-AAA-MIB", "claRadiusServerWlanActivatedEnabled"), ("CISCO-LWAPP-AAA-MIB", "claRadiusServerWlanDeactivatedEnabled"), ("CISCO-LWAPP-AAA-MIB", "claRadiusReqTimedOutEnabled")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappAAAMIBConfigGroup = ciscoLwappAAAMIBConfigGroup.setStatus('current') ciscoLwappAAAMIBSaveUserConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 598, 2, 2, 2)).setObjects(("CISCO-LWAPP-AAA-MIB", "claSaveUserData")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappAAAMIBSaveUserConfigGroup = ciscoLwappAAAMIBSaveUserConfigGroup.setStatus('current') ciscoLwappAAAMIBNotifsGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 9, 598, 2, 2, 3)).setObjects(("CISCO-LWAPP-AAA-MIB", "ciscoLwappAAARadiusServerGlobalActivated"), ("CISCO-LWAPP-AAA-MIB", "ciscoLwappAAARadiusServerGlobalDeactivated"), ("CISCO-LWAPP-AAA-MIB", "ciscoLwappAAARadiusServerWlanActivated"), ("CISCO-LWAPP-AAA-MIB", "ciscoLwappAAARadiusServerWlanDeactivated"), ("CISCO-LWAPP-AAA-MIB", "ciscoLwappAAARadiusReqTimedOut")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappAAAMIBNotifsGroup = ciscoLwappAAAMIBNotifsGroup.setStatus('current') ciscoLwappAAAMIBStatusObjsGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 598, 2, 2, 4)).setObjects(("CISCO-LWAPP-AAA-MIB", "claRadiusAddressType"), ("CISCO-LWAPP-AAA-MIB", "claRadiusAddress"), ("CISCO-LWAPP-AAA-MIB", "claRadiusPortNum"), ("CISCO-LWAPP-AAA-MIB", "claRadiusWlanIdx"), ("CISCO-LWAPP-AAA-MIB", "claRadiusClientMacAddress"), ("CISCO-LWAPP-AAA-MIB", "claRadiusUserName")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappAAAMIBStatusObjsGroup = ciscoLwappAAAMIBStatusObjsGroup.setStatus('current') ciscoLwappAAAMIBDBEntriesGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 598, 2, 2, 5)).setObjects(("CISCO-LWAPP-AAA-MIB", "claDBCurrentUsedEntries")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappAAAMIBDBEntriesGroup = ciscoLwappAAAMIBDBEntriesGroup.setStatus('current') ciscoLwappAAAMIBRadiusConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 598, 2, 2, 6)).setObjects(("CISCO-LWAPP-AAA-MIB", "claWebRadiusAuthentication"), ("CISCO-LWAPP-AAA-MIB", "claRadiusFallbackMode"), ("CISCO-LWAPP-AAA-MIB", "claRadiusFallbackUsername"), ("CISCO-LWAPP-AAA-MIB", "claRadiusFallbackInterval"), ("CISCO-LWAPP-AAA-MIB", "claRadiusAuthMacDelimiter"), ("CISCO-LWAPP-AAA-MIB", "claRadiusAcctMacDelimiter")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappAAAMIBRadiusConfigGroup = ciscoLwappAAAMIBRadiusConfigGroup.setStatus('current') ciscoLwappAAAMIBAPPolicyConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 598, 2, 2, 7)).setObjects(("CISCO-LWAPP-AAA-MIB", "claAcceptMICertificate"), ("CISCO-LWAPP-AAA-MIB", "claAcceptLSCertificate"), ("CISCO-LWAPP-AAA-MIB", "claAllowAuthorizeLscApAgainstAAA")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappAAAMIBAPPolicyConfigGroup = ciscoLwappAAAMIBAPPolicyConfigGroup.setStatus('current') ciscoLwappAAAMIBWlanAuthAccServerConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 598, 2, 2, 8)).setObjects(("CISCO-LWAPP-AAA-MIB", "claWlanAuthServerEnabled"), ("CISCO-LWAPP-AAA-MIB", "claWlanAcctServerEnabled")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappAAAMIBWlanAuthAccServerConfigGroup = ciscoLwappAAAMIBWlanAuthAccServerConfigGroup.setStatus('current') mibBuilder.exportSymbols("CISCO-LWAPP-AAA-MIB", claRadiusReqTimedOutEnabled=claRadiusReqTimedOutEnabled, ciscoLwappAAAMIBCompliances=ciscoLwappAAAMIBCompliances, claConfigObjects=claConfigObjects, claAllowAuthorizeLscApAgainstAAA=claAllowAuthorizeLscApAgainstAAA, claRadiusUserName=claRadiusUserName, ciscoLwappAAAMIBNotifs=ciscoLwappAAAMIBNotifs, ciscoLwappAAAMIBConform=ciscoLwappAAAMIBConform, claRadiusFallbackUsername=claRadiusFallbackUsername, claStatusObjects=claStatusObjects, claTacacsServerRowStatus=claTacacsServerRowStatus, claRadiusServerEntry=claRadiusServerEntry, claSaveUserData=claSaveUserData, claWebRadiusAuthentication=claWebRadiusAuthentication, claWlanEntry=claWlanEntry, claRadiusWlanIdx=claRadiusWlanIdx, ciscoLwappAAAMIBGroups=ciscoLwappAAAMIBGroups, ciscoLwappAAAMIBCompliance=ciscoLwappAAAMIBCompliance, claTacacsServerSecretType=claTacacsServerSecretType, claRadiusFallbackMode=claRadiusFallbackMode, claRadiusAuthMacDelimiter=claRadiusAuthMacDelimiter, claRadiusServerTable=claRadiusServerTable, ciscoLwappAAAMIBSaveUserConfigGroup=ciscoLwappAAAMIBSaveUserConfigGroup, ciscoLwappAAAMIBComplianceRev1=ciscoLwappAAAMIBComplianceRev1, ciscoLwappAAAMIBStatusObjsGroup=ciscoLwappAAAMIBStatusObjsGroup, claRadiusPortNum=claRadiusPortNum, claRadiusServerGlobalDeactivatedEnabled=claRadiusServerGlobalDeactivatedEnabled, claWlanTable=claWlanTable, PYSNMP_MODULE_ID=ciscoLwappAAAMIB, ciscoLwappAAAMIB=ciscoLwappAAAMIB, claPriorityEntry=claPriorityEntry, ciscoLwappAAAMIBConfigGroup=ciscoLwappAAAMIBConfigGroup, claDBCurrentUsedEntries=claDBCurrentUsedEntries, claTacacsServerType=claTacacsServerType, claTacacsServerTimeout=claTacacsServerTimeout, claRadiusServerWlanActivatedEnabled=claRadiusServerWlanActivatedEnabled, claRadiusFallbackInterval=claRadiusFallbackInterval, ciscoLwappAAARadiusServerWlanDeactivated=ciscoLwappAAARadiusServerWlanDeactivated, claTacacsServerTable=claTacacsServerTable, claTacacsServerStorageType=claTacacsServerStorageType, claPriorityTable=claPriorityTable, claTacacsServerAddressType=claTacacsServerAddressType, ciscoLwappAAARadiusServerGlobalDeactivated=ciscoLwappAAARadiusServerGlobalDeactivated, claRadiusServerWlanDeactivatedEnabled=claRadiusServerWlanDeactivatedEnabled, claRadiusClientMacAddress=claRadiusClientMacAddress, ciscoLwappAAAMIBNotifsGroup=ciscoLwappAAAMIBNotifsGroup, claRadiusAcctMacDelimiter=claRadiusAcctMacDelimiter, claRadiusReqId=claRadiusReqId, claTacacsServerPriority=claTacacsServerPriority, claAcceptMICertificate=claAcceptMICertificate, claRadiusServerGlobalActivatedEnabled=claRadiusServerGlobalActivatedEnabled, ciscoLwappAAARadiusReqTimedOut=ciscoLwappAAARadiusReqTimedOut, ciscoLwappAAAMIBObjects=ciscoLwappAAAMIBObjects, claTacacsServerEnabled=claTacacsServerEnabled, ciscoLwappAAARadiusServerWlanActivated=ciscoLwappAAARadiusServerWlanActivated, claTacacsServerSecret=claTacacsServerSecret, claWlanAuthServerEnabled=claWlanAuthServerEnabled, claTacacsServerEntry=claTacacsServerEntry, claTacacsServerAddress=claTacacsServerAddress, claRadiusAddressType=claRadiusAddressType, claRadiusAddress=claRadiusAddress, claWlanAcctServerEnabled=claWlanAcctServerEnabled, ciscoLwappAAAMIBRadiusConfigGroup=ciscoLwappAAAMIBRadiusConfigGroup, ciscoLwappAAAMIBAPPolicyConfigGroup=ciscoLwappAAAMIBAPPolicyConfigGroup, claPriorityOrder=claPriorityOrder, ciscoLwappAAAMIBWlanAuthAccServerConfigGroup=ciscoLwappAAAMIBWlanAuthAccServerConfigGroup, ciscoLwappAAAMIBDBEntriesGroup=ciscoLwappAAAMIBDBEntriesGroup, claAcceptLSCertificate=claAcceptLSCertificate, ciscoLwappAAARadiusServerGlobalActivated=ciscoLwappAAARadiusServerGlobalActivated, claTacacsServerPortNum=claTacacsServerPortNum, claPriorityAuth=claPriorityAuth)
class Solution: def gcdOfStrings(self, str1, str2): if len(str1)<=len(str2): temp = str1 else: temp = str2 m = len(temp) x = 1 res=[""] while x<=m: if m%x==0 and temp[:x] * (len(str1)//x) == str1 and temp[:x] * (len(str2)//x) == str2: res.append(temp[:x]) x+=1 return res[-1] ob1 = Solution() print(ob1.gcdOfStrings("ABABAB","ABAB"))
#!/usr/bin/python3 # https://practice.geeksforgeeks.org/problems/extract-maximum/0 def sol(s, n): """ If the character is a number and l is not set set it to that index, if it is set the r. If character is not a number set both l and r as None """ l = None r = None mx = 0 for i in range(n): if 48 <= ord(s[i]) <= 57: if l == None: # Be careful when saying "not X" keeping in mind 0 is False l = i r = i mx = max(mx, int(s[l:r+1])) else: l = None return mx
# Magatia (261000000) / NLC Town Center (600000000) => Free Market sm.setReturnField() sm.setReturnPortal() sm.warp(910000000, 36)
class KeywordError(Exception): pass class SingletonError(Exception): pass class StepNotFoundError(Exception): pass class EmptyFeatureError(Exception): pass
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def buildTree(self, preorder, inorder): """ :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode """ return self.__buildTree(preorder,inorder,0,len(preorder),0,len(inorder)) def __buildTree(self,preorder,inorder,preS,preE,inS,inE): if preS >= preE: return None root = TreeNode(preorder[preS]) leftInS , leftInE = inS , inorder.index(root.val) rightInS , rightInE = inorder.index(root.val)+1, inE leftPreS, leftPreE = preS+1, preS+leftInE-leftInS+1 rightPreS, rightPreE = preS+leftInE-leftInS+1, preE root.left = self.__buildTree(preorder, inorder, leftPreS, leftPreE, leftInS, leftInE) root.right = self.__buildTree(preorder, inorder, rightPreS, rightPreE, rightInS, rightInE) return root sol = Solution() preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] print(sol.buildTree(preorder,inorder))
# Number of motors NUM_MOTORS = 12 # Number of legs NUM_LEGS = 4 # ////// # Legs # ////// LEG_NAMES = ["FR", # Front Right "FL", # Front Left "RR", # Rear Right "RL"] # Rear Left # ////////////// # Joint Types: # ////////////// JOINT_TYPES = [0, # Hip 1, # Thigh 2] # Knee # /////////////// # JOINT_MAPPING # /////////////// # Joint names are given by concatenation of # LEG_NAME + JOINT_TYPE as in following table # # ______| Front Right | Front Left | Rear Right | Rear Left # Hip | FR_0 = 0 | FL_0 = 3 | RR_0 = 6 | RL_0 = 9 # Thigh | FR_1 = 1 | FL_1 = 4 | RR_1 = 7 | RL_1 = 10 # Knee | FR_2 = 2 | FL_2 = 5 | RR_2 = 8 | RL_2 = 11 GAINS = {0: {'P': 100, 'D': 1}, 1: {'P': 100, 'D': 2}, 2: {'P': 100, 'D': 2}} # Define the joint limits in rad LEG_JOINT_LIMITS = {0: {'MIN': -0.802, 'MAX': 0.802}, 1: {'MIN': -1.05, 'MAX': 4.19}, 2: {'MIN': -2.7, 'MAX': -0.916}} # Define torque limits in Nm LEG_TORQUE_LIMITS = {0: {'MIN': -10, 'MAX': 10}, 1: {'MIN': -10, 'MAX': 10}, 2: {'MIN': -10, 'MAX': 10}} LEG_JOINT_INITS = {0: 0, 1: 0, 2: 0} LEG_JOINT_OFFSETS = {0: 0, 1: 0, 2: 0} # TODO: Do it more concisely # stand_angles = 4*[0.0, 0.77, -1.82] # init_angles = [-0.25, 1.14, -2.72, # 0.25, 1.14, -2.72, # -0.25, 1.14, -2.72, # 0.25, 1.14, -2.72] # //////////////////////////////////////////////////////////////////////// JOINT_CONSTANTS = { 'OFFSETS': [], 'INITS': [], 'POS_LIMITS': {'MIN': [], 'MAX': []}, 'TORQUE_LIMITS': {'MIN': [], 'MAX': []}, 'GAINS': {'P': [], 'D': []}} for JOINT in range(NUM_MOTORS): JOINT_ID = JOINT % 3 JOINT_CONSTANTS['OFFSETS'].append(LEG_JOINT_INITS[JOINT_ID]) JOINT_CONSTANTS['INITS'].append(LEG_JOINT_OFFSETS[JOINT_ID]) for BOUND in {'MIN', 'MAX'}: POS_LIMIT = LEG_JOINT_LIMITS[JOINT_ID][BOUND] JOINT_CONSTANTS['TORQUE_LIMITS'][BOUND].append(POS_LIMIT) JOINT_CONSTANTS['POS_LIMITS'][BOUND].append(POS_LIMIT) for GAIN_TYPE in {'P', 'D'}: GAIN = GAINS[JOINT_ID][GAIN_TYPE] JOINT_CONSTANTS['GAINS'][GAIN_TYPE].append(GAIN) JOINT_LIMITS = JOINT_CONSTANTS['POS_LIMITS'] JOINT_LIMITS_MIN = JOINT_LIMITS['MIN'] JOINT_LIMITS_MAX = JOINT_LIMITS['MAX'] TORQUE_LIMITS = JOINT_CONSTANTS['TORQUE_LIMITS'] TORQUE_LIMITS_MIN = TORQUE_LIMITS['MIN'] TORQUE_LIMITS_MAX = TORQUE_LIMITS['MAX'] JOINT_OFFSETS = JOINT_CONSTANTS['OFFSETS'] JOINT_INITS = JOINT_CONSTANTS['INITS'] POSITION_GAINS = JOINT_CONSTANTS['GAINS']['P'] DAMPING_GAINS = JOINT_CONSTANTS['GAINS']['D'] # //////////////////////////////////////////////////////////////////////// # TODO: Add high level commands scaling factors # KINEMATIC_PARAMETERS LEG_KINEMATICS = [0.0838, 0.2, 0.2] TRUNK_LENGTH = 0.1805 * 2 TRUNK_WIDTH = 0.047 * 2 LEGS_BASES = [[TRUNK_LENGTH/2, -TRUNK_WIDTH/2], [TRUNK_LENGTH/2, TRUNK_WIDTH/2], [-TRUNK_LENGTH/2, -TRUNK_WIDTH/2], [-TRUNK_LENGTH/2, TRUNK_WIDTH/2]] # LEG_DYNAMICS = # BODY_DYNAMICS =
# draw a playing board def DrawBoard(rows,cols): dash = " ---" hline = "| " for i in range(0,rows): print (dash * (cols)) print (hline * (cols +1)) DrawBoard(3, 3)
# # 给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。 # # 示例 1: # # 输入: [10,2] # 输出: 210 # 示例 2: # # 输入: [3,30,34,5,9] # 输出: 9534330 # 说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。 def bi(i): if i == 0: return 0 s = 0 k = i while i >= 1 : i=i/ 10 s+=1 return k /( 10 **s) class Solution(object): def largestNumber(self, nums): nums = sorted(nums,key = bi,reverse=True) if nums[0] == 0: return "0" print(nums) return "".join([str(i) for i in nums]) S = Solution() print(S.largestNumber([10,2,34,345,3456]))
def read_file(test = True): if test: filename = '../tests/day3.txt' else: filename = '../input/day3.txt' with open(filename) as file: temp = list() for line in file: temp.append(line.strip()) return temp def puzzle1(): temp = read_file(False) houses = set() for line in temp: pos = [0,0] for move in line: if move == "^": pos[0] += 1 houses.add(tuple(pos)) elif move == 'v': pos[0] -= 1 houses.add(tuple(pos)) elif move == ">": pos[1] += 1 houses.add(tuple(pos)) elif move == '<': pos[1] -= 1 houses.add(tuple(pos)) print(len(houses)) def puzzle2(): temp = read_file(False) houses = set() pos1 = [0,0] pos2 = [0,0] houses.add(tuple(pos1)) for line in temp: pos1 = [0,0] pos2 = [0,0] for i, move in enumerate(line): if i % 2 == 0: if move == "^": pos1[0] += 1 houses.add(tuple(pos1)) elif move == 'v': pos1[0] -= 1 houses.add(tuple(pos1)) elif move == ">": pos1[1] += 1 houses.add(tuple(pos1)) elif move == '<': pos1[1] -= 1 houses.add(tuple(pos1)) else: if move == "^": pos2[0] += 1 houses.add(tuple(pos2)) elif move == 'v': pos2[0] -= 1 houses.add(tuple(pos2)) elif move == ">": pos2[1] += 1 houses.add(tuple(pos2)) elif move == '<': pos2[1] -= 1 houses.add(tuple(pos2)) print(len(houses)) puzzle1() puzzle2()
data = open("input.txt", "r").readlines() score_map = { ")": 3, "]": 57, "}": 1197, ">": 25137 } def get_opening_bracket(bracket): if bracket == ")": return "(" if bracket == "]": return "[" if bracket == "}": return "{" if bracket == ">": return "<" score = 0 def parse(line: str): stack = [] for bracket in line.strip(): if bracket in ["{", "(", "<", "["]: stack.append(bracket) else: last = stack.pop() expected = get_opening_bracket(bracket) if last != expected: print("corrupt expected", expected, " found ", bracket) return score_map[bracket] return 0 for line in data: score += parse(line) print(f"The answer to part 1 is ", score)
#write a program to check whether the given number is Disarium or not? n = int(input("Enter number:")) i= 1 sum = 0 num = n while(num!=0): rem = num%10 sum = sum*10+rem num = num//10 num = sum sum = 0 while(num!= 0): rem = num % 10 sum = sum + pow(rem,i) num = num//10 i+=1 if sum == n: print(n,"is a 'Disarium Number'.") else: print(n,"is not a 'Disarium Number'.")
''' Created by Vedant Christian Created on 18 / 08 / 2020 ''' terms = int(input("How many terms? ")) base = int(input("What is the base? ")) result = list(map(lambda x: base ** x, range(terms+1))) print("The total terms is: ", terms) print("The base is ", base) for i in range(terms+1): print(base, "raied to the power", i, "is", result[i])
x=10; print(x); #输出10 str="I am a student"; print(str); #输出I am a student #print(y); #y没有定义,所以这里必定会报错 num=1; print(num); #输出1 Num=2.8; NUM=1+2j; #python中的复数形式:m+nj(其中m,n分别为实数部和虚数部) print(num,Num,NUM); #输出1 2.8 (1+2j) print(type(num)); #输出<class 'int'> print(type(Num)); #输出<class 'float'> print(type(NUM)); #输出<class 'complex'> st="我是一个字符串"; #print(st+6); #数据类型不同不可相加,所以这里会报错; a=5;b=6; print("a=",a,"b=",b) a,b=b,a; print("a=",a,"b=",b);
class TryNode(object): def __init__(self, line, start, end, handler): self.buf = "" self.exception = "" self.start = None self.end = None self.handler = None self.__parse(line, start, end, handler) def __repr__(self): return "Try: %s {%s .. %s} %s" % \ (self.exception, start.index, end.index, handler.index) def __parse(self, line, start, end, handler): self.buf = line self.start = start self.end = end end.tries.append(self) self.handler = handler segs = self.buf.split() self.exception = segs[1] def reload(self): pass
class Solution: def maxProfit(self, prices: List[int]) -> int: first_buy, first_sell = inf, 0 second_buy, second_sell = inf, 0 for price in prices: first_buy = min(first_buy, price) first_sell = max(first_sell, price - first_buy) second_buy = min(second_buy, price - first_sell) second_sell = max(second_sell, price - second_buy) return second_sell
# Copyright (c) 2007-2010 Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.internet.application}. """
n, k = input().split(' ') n, k = int(n), int(k) c = sorted(list(map(int, input().split(' ')))) count = [0] * k count_i, min_sum = 0, 0 for i in reversed(range(n)): min_sum += (count[count_i]+1) * c[i] count[count_i] += 1 count_i += 1 if count_i >= k: count_i = 0 #print (count) print (min_sum)
def split(word): return [int(char) for char in word] data = '222221202212222122222211222222222222222222222202222022222222222002221222222222220222202222202122222020222222021020220022122222222220222222202222222222222221202202222122222222222222222222222222222202222022222222222022220222222222220222212222212222222220222222221121222022022222222222222222212222222222222220202202222122222210222222222222222222222202222122222222222212222222222022222222212022212122222020222222122021221222122222222221222222222222222222222221202202222022222221222222222222222222222212222022222222222022220222222122222222202122222022222021222222220220220022222222222220222222202222222222222221202222222122222220222212222222222222222202222222222222222022222212222022220222202022202022222120222222121020222122222222222221222222202222222222222221202212222022222221222222222222222222222202222022222222222212220222202022220222202222202022222121222222020021222122022222222220222222212222222220222220212222222122222211222212222222222222222222222122222222222102222202222022222222202222202022222021222222120221220222122222222020222222212222222222222222202212222022222222222222222222222222222212222122222222222012222222202022222222212222222222222120222222122021222122222222222120222222202222222221222121202222222222222201222202222222222222222222222222222222222112221212202222222222202122212122222121222222122020221122122222222220222222212222222222222120212212222222222210222212222222222222222212222122222222222102221212202022222222212022222022222122222222221221222222022222222021222222222222222221222222222212222022222211222202222222222222222212202222222222222112221202222022220222202222202021222121222222220022220122022222222222222222212022222220222020202202222122222211222202222222202222222222222022222222222022222202222222222222202222222120222121222222222120222122122222222221222222202222222222222122202222222122222211220222222222212222022212202122222222222212222222222122222222212022212020222022222222021022221222222222222220222222202022222222222120222222222022222222222222222222202222022202202122222222222012222202212022221222202122212220222120222222222022222022222222222021222221222122222220022220212202222122222200220202222222222222022202200122222222222002221212202122221222202122212222222121222222221120222222122222222221222222212222222220222020222212222022222222220212222222202222122202221122222222222202222222222122222022222122212022222120222222222121220222022222222021222222212022222220122022212202222122222212220212222222212222122222212022222222222222220202212122220122202022212122222022222222021122221122122222222021222221202222222220122100222202122122222200221202222222202222122212201022222222222122220202122022222122212122212020222120222222120121220122222222222220222222212122222220122122222202122022222201222202222222222222022212201122222222222102220212202122222122222022222020222022222222221021222022022222222022222222222122222220222011202222122222222200221222222222212212222202220222222222222002221212022122221022222222212021222220222222122220221222022222222122222221222222222220022201222202122222222212221212222222212002022222201122222222222112222212022022221122222222202120222221222222220020222022122222222122222222212022222220222001202212122122222222222212222222212222022222222222022222222212222222212122221122212122202122222222222222222021220222122222222022222222202222222222222101212212222122222201222222222222212202122212210122122222222002222202202122220222202022212221222122212222020220221022222222222101222220202022222220122110222212122222222222220202222222202122122212202022122222222102221212022222222222202122202022222122222222020221221122022222222122222221202022222221022202202222022122222221220222222222222022222202202222221222222222222202202122220222202122222220222020212222021122220122222222222121222220222022222221122120212222122122222222221202222222202122222222211022222222222222222222102122220122202222212120222122222222122222221022122222222022222222202122222222022021222222222122222210221212222222202022122222202022222222222112222222122222222022222222212220222120202222220021221122022222222121222220202222222221022200212212222022222220221202222222212212022222221122022222222222220222022022221122212222212022222221222222122122221022222222222001222221202022222222022001222212222122222200220212222222212212022222200122220222222212221202022222221222222022222122222020222222020022222222222222222010222222202122222222222122202222022022122221222202222222212012022212200122120222222022220202102222221022212122222122222220212222220222222222022222222001222222202122222222022202222212222022222220221202222222202202222222221022222222222212222212122022222122202122222020222222222222121222222022122222222121222222212022222220222212222202222122022212222202222222212102022202221022222222022222220202002022221022202222202120222020212222220121221222122222222002222220222022222220222021222221222222022200222222222222202002022212220022222222222112221202212222222022212022212222222221212222120220221022222222222201222222221222222222122200202200222222122211221212222222222222222222220222222222122112221202112122221022212022212120222220212222121020222222122222222021222222222022222221222121212210222222122222221202222222202102012212221022022222122002220212122222221222222222202221222021202222121221220022222222222211222221221022222220022021202212022122122220220222222222212022112212220022220222222102220212122222220022222222202020222021222222020221221022222222222102222221200222222221022212202210222022122200220202222222222002222222212122222222222022220212112222220222212222202121222121212222221021222122122222222121222220211222222221222120222210022222222220220202222222212122102202202022020222022212220222002022222222202022202221222222212222121021020222022222222102222220210022222222222010202222122022222212221212222222222202122202201222120222002022220202022222221022222122222120222021222222222121122022222222222022222220211202222200022221212212120022022201220202222222222002102222212222121222102112220222102222220122202022212120222222202222121120120022022222222210222221220212222202222202212200220222222200222212222222202022022222212222221222012102220212102022222022012222212021222121222222021120120122022222222202222221222022222202022012222222122022122220221212222222212122002212220221021222002222222222002022222222202122212221222021222222120020221122022222222202222221212222222202222022212200021122222221220202222222202212202222201020120222222012222202202122221222002122112220222021212222120122021122122222222122222222200102222202022212012221022122122212222212222222012012122222212022022222122012221212002122222122112222102022222022212222222220121022022222222011222221200202222220122021002200022022022201222222222222122212002202212120022222012212222202002122222022002222212021222022202221221020022022122222222120222220212112222222222210102222120222022200220202222222102112012222221222120222002112220212112122220222202122212220222121222220020101022122222222222110222220202202222201122011122200220222222222220222222222122102202222212120120222212002221212112022222022002022002120222020222220121112221122222222222210222221200202222212022112222220022222122220221212222222112212022222222020020222012022221212112122221022202022202221222120212200220021221022222222222221222220221022222220022010222212020022222222220202222222102112102202210020221022022112222202102122222222112222012222222120212221121001020222222222222221222221211222222212122122122200220222122211221202222022002222212222000221121022122012220202122122221022122222012221222120212210221110022022222222222022222222220012222221222200212202120222122220220212222122212002202222021222122222102212121212112022222022102002102020222020212211220001022022222222222121222222222112222202022121002202121122222221220202122222002022022222110222222222222222020212222122220122002222022022222022212211020122121122022222222221222221210002222212022101122200020222122221220222122122112122002222020022222122202012021212222122222222002002122220222021212222121202122022222222222210222221211022222221122122022212220122222200222202122122022012112212112021122022112202222212022022221122222102222122222022222222020210220222122222222122222220211002222201122202022221222122022202220222122122222022222222221120020222222212121212102122222022022212122120222122222221120210122222222022222100222221210122222202122112222211222022222201222202220122102002222222111221201222101212020222122222221222022002222220222022202221120011022122022122222202222220221202222002122011122201120122022220222202021022012112102202000121201222210212020212122022221222112112112020222222222222220211110122022122222012222222202202222202022022222211122022122201220212221122002002112212221120121022000212220202102122222222112122022220222021202220220020010022122122222210222220221112222200122201012200122222122200222212122220121212222202000120110122101212220212202122220122222022022020222120222220122201112022122122222010222220220012222001222211112222022122122202220222121220110222202222001220101122100112122212002122221122122212202020222020212210022212111022022222222121222222221112222112222202102222222222122200222222120222012102122202221220102022100022120222122222220122122120102122222222212212020200201122022022222221222221220002222211022111012212221222222220221212120120112222012202120121101222101002220202120120122222222111112221222121202210221001000222122022222000222222211222222001222110202212022222222212221212221120100012102202210020211022101122021212122222022122112221102120222022212201022120111222022222222210222222211112222120122100012201020122022212221222220120200012122202200222121122101112221221211022120222122222022221222021222210120211112022122222222112222221210112222022222000212201020222222211221210221121000102102212020121120022102022120202201220220222222010012222222121202202000002222222022022222010222222202202222020222002122212122222022222221010121221212112202212111021111222022022020221000120122222202012212120222012222210012221102022222022222021222220201102222110022110002220020222122212220021222120002212202202121222200022200112021202110020221122122222122220222110222211211022111222022122222011222221210012222210022100212212222222002122220202222222102222222112110022111222020022221211110121221022112020012220222011212210220101100222122122222000222221210112222100122001222222120222202021222000120221221122102112121020210222010222122210212120122222012211102122222021212201211202220222022122222221222220201202222221222222212200220122202110222202120020122022222112010021000222210122022220011122022222222022222021220002222020011212102122122222222002222222221112222112222011002212122222112002201200022120221002102012220022000122220002222200010021121122002002122221222121202101121101012022222222222121222222200002222112022020102202122022112210200101021221100222202212021021111022120222020200110222220222122220222222220000222110211022120122222222222000222221210112222020122012202212122222002001210210120122220212202002100021220022212122121200102021021222202120122021222220202220001001221022122122222122222220212122222112022210122212121022012011201010020220222022112112211222011122212112022212022221022022002012112221221221202022022200210122222222222222222221212112222002222122102222020222102222222020220220120212112202111020212222012102122221222122121222212222212222221210022021222212101222022122222211122222201021222121002112202210220122022020221212121122110222212102222020210022122022022222102021122222212002012122200000022102111201200222122022222000122222220000222110102200012220022222122022221220220221011122102212102220002022101102222220121120022122212200102122200102022102200202122022122022222122122221222200222120222002122202022022112220211122021022111222002022120121220022122022222211211021122022122102022222220201112112112002002122122022222020222222200111220102222020122221221222202122202210221220121122022212220120011022011002121211212121022222022022212221212221102212022022101122122222222110222222220021220202202100012212221122202022220211021222012112222002100120010022022212221201121222221222212001122020200212002202110101121122022122222002022222120011222001002210112202022222002022212121121120021102012202002221120022221002022002211021120222222201020221220110012120201202111022222222222202022220212020221002022202002202020022112222221022121020221102212022121221220022121012122000101020020222212111202020210200102121101001210122022022222021122221002222222111112002012221220022102201220012122222101022212122200220021122220112120220202020020222022120002122210121002121001211222022122022222101122221211121220202022120112212021222022100201100020120112002212002001022021222121102222101001120220222212200121122210112122011211010220022022022222100122222010200222222212100222222020122022202211121020122002102222112020022200222122022222002001121120222102001001020221220222220021121202022222022222011022221120212222111222100122202222222211220210211020120212102112212021020020022112012122202110220120122102221011121211000012112201221211012122022222120222222000021222212222211012220022222102021201222022220022022222002201122100022201212022011000021000222002200100222220212022212111002222012122122222201222220020100221120022102212200120222102002201101221120001122022022010121121222220222222210202120101022122121011020020121022222102012010202122122222212022221002101222101012100222220120022202111211202221221201002202222022121110222200202022021100020010122012102011222220122022201212020200222022022222010122222021222021001122210002221120122111220221121220220110002002112001122000022012122121000212022212122212121100122122201110221211112102002122022222020022220001112221112202020102221022022022012201221120221111022212112112121111122022202221110101021122122222210111020111221200011001021020002222122222201222220202101121201112010122211122222011112201102221022200122022012121121200122010212021111022021112122122000021122210100000021000220122222022122222121122220020012222020202112122220122022122112202211220222202212202000120022200222201012022201220020200122112022010221011022120220102201222202022122222220020222201010022010122222012222022222102100212200221121221022102110021220010222201211120121120120020022212110002120220112122111220111221202022222222211121220110021020102012100102220222222211202220222021021002202212110222120012022121222121212202122220022222112020022122112121112111202212122022122222101221221001210122220202102222202220022012222210021120221211012212022222021011122012021222022110220020022112000022022200122012220212102100022122022222000121120211020120100212200012200122022112211210212122021212202022121011022000120022012221220220020121122122222120120201000121220210002210002122222220201121121101101022110122010112202021222122120222021020020001022102120202021212121210011121110021021012122012111212021121201200021010001200012122222220201021120000011020212002210222201220022220222211122022120111012022101201221220212002122120112112221001122101021212121020100202201020202020012222222222010021222201002121221201202010111012000000120021022102012211120100001100000220102221021011011002200112010111012101102112201021120220001010120200100111202002112122101210121' wide, tall = 25, 6 img = split(data) bm = wide * tall it = int(len(img) / bm) layer_zeros = {} for i in range(it): layer = img[(bm*i):(bm*(i+1))] print((bm*i),(bm*(i+1))) zeros = 0 for num in layer: if num == 0: zeros += 1 layer_zeros[i] = zeros min_layer = 0 minl = layer_zeros[0] for k, v in layer_zeros.items(): if minl > v: min_layer = k minl = v layer = img[(bm*min_layer):(bm*(min_layer+1))] num_1 = 0 num_2 = 0 for num in layer: if num == 1: num_1 += 1 elif num == 2: num_2 += 1 print(num_1 * num_2)
def find_short(s): l = len(s) #conta a quantidade caracteres apenas para ter um número alto o suficiente para comparação. a = s.split() #separa as palavras for x in a: if l > len(x): #se l for maior que a quantidade de letras na palavra x, desse jeito l vai receber o valor menor sempre l = len(x) return l # l: shortest word length
name, age = "Aromal S", 20 username = "aromalsanthosh" print ('Hello!') print("Name: {}\nAge: {}\nUsername: {}".format(name, age, username))
""" document.py Contains a simple class that represents a Twitter-esque comment, with hashtags. """ class Document: """ This class essentially takes in a list of tokenized words and stores two lists, one containing the words in the order that they appear and a set containing any hashtags in the comment. """ def __init__(self, words, tags, raw): """ words is expected to be a parameter of tokenized words in the comment They can be processed further. """ self.words = words self.tags = tags self.raw = raw @classmethod def create_from_raw_list(cls, words, raw): d = Document([], set(), raw) for w in words: if w.startswith('#'): d.tags.add(w) else: d.words.append(w) return d def export(self): """ Convert this object into a database model """ pass
# -*- coding: utf-8 -*- """ ジェネレーターの利用例 """ def tuggle(): """ >>> g = tuggle() >>> next(g) True >>> next(g) False >>> next(g) True """ r = False while True: r = not r yield r def file_read(file_name): with open(file_name) as f: for line in f: yield line.strip('\n') def modern_style_file_read_with_block(file_name, n): with open(file_name) as f: for block in iter(lambda: f.read(n), ''): yield block def old_style_file_read_with_block(file_name, n): with open(file_name) as f: while True: block = f.read(n) yield block if block == '': break
class Solution(object): # dutch partitioning problem def sortColors(self, nums): low, mid, high = 0, 0, len(nums)-1 while(mid <= high): if(nums[mid] == 0): nums[low],nums[mid] = nums[mid], nums[low] low +=1 mid += 1 elif(nums[mid] == 1): mid += 1 else: nums[mid], nums[high] = nums[high], nums[mid] high -= 1 sol = Solution() arr = [2,0,2,1,1,0] sol.sortColors(arr) print(arr)
def definition(): view = f""" -- Exists just as a reference, to check the categorisation of accounts to super-sections. Built 'right to left' SELECT e.super_section_id, e.description as Super, d.section_id, d.description as Section, c.sub_section_id, c.description as SubSection, b.summary_code, b.description as Summary, a.account, a.description as AccountName FROM fs_account a LEFT OUTER JOIN fs_summary_code b ON b.summary_code = a.summary_code LEFT OUTER JOIN fs_sub_section c ON c.sub_section_id = b.sub_section_id LEFT OUTER JOIN fs_section d ON d.section_id = c.section_id LEFT OUTER JOIN fs_super_section e ON e.super_section_id = d.super_section_id """ return view
# name this file 'solutions.py'. """Volume II Lab 15: Line Search Algorithms <name> <class> <date> """ # Problem 1 def newton1d(f, df, ddf, x, niter=10): """ Perform Newton's method to minimize a function from R to R. Parameters: f (function): The twice-differentiable objective function. df (function): The first derivative of 'f'. ddf (function): The second derivative of 'f'. x (float): The initial guess. niter (int): The number of iterations. Defaults to 10. Returns: (float) The approximated minimizer. """ raise NotImplementedError("Problem 1 Incomplete") def test_newton(): """Use the newton1d() function to minimixe f(x) = x^2 + sin(5x) with an initial guess of x_0 = 0. Also try other guesses farther away from the true minimizer, and note when the method fails to obtain the correct answer. Returns: (float) The true minimizer with an initial guess x_0 = 0. (float) The result of newton1d() with a bad initial guess. """ raise NotImplementedError("Problem 1 Incomplete") # Problem 2 def backtracking(f, slope, x, p, a=1, rho=.9, c=10e-4): """Perform a backtracking line search to satisfy the Armijo Conditions. Parameters: f (function): the twice-differentiable objective function. slope (float): The value of grad(f)^T p. x (ndarray of shape (n,)): The current iterate. p (ndarray of shape (n,)): The current search direction. a (float): The intial step length. (set to 1 in Newton and quasi-Newton methods) rho (float): A number in (0,1). c (float): A number in (0,1). Returns: (float) The computed step size satisfying the Armijo condition. """ raise NotImplementedError("Problem 2 Incomplete") # Problem 3 def gradientDescent(f, df, x, niter=10): """Minimize a function using gradient descent. Parameters: f (function): The twice-differentiable objective function. df (function): The gradient of the function. x (ndarray of shape (n,)): The initial point. niter (int): The number of iterations to run. Returns: (list of ndarrays) The sequence of points generated. """ raise NotImplementedError("Problem 3 Incomplete") def newtonsMethod(f, df, ddf, x, niter=10): """Minimize a function using Newton's method. Parameters: f (function): The twice-differentiable objective function. df (function): The gradient of the function. ddf (function): The Hessian of the function. x (ndarray of shape (n,)): The initial point. niter (int): The number of iterations. Returns: (list of ndarrays) The sequence of points generated. """ raise NotImplementedError("Problem 3 Incomplete") # Problem 4 def gaussNewton(f, df, jac, r, x, niter=10): """Solve a nonlinear least squares problem with Gauss-Newton method. Parameters: f (function): The objective function. df (function): The gradient of f. jac (function): The jacobian of the residual vector. r (function): The residual vector. x (ndarray of shape (n,)): The initial point. niter (int): The number of iterations. Returns: (ndarray of shape (n,)) The minimizer. """ raise NotImplementedError("Problem 4 Incomplete") # Problem 5 def census(): """Generate two plots: one that considers the first 8 decades of the US Census data (with the exponential model), and one that considers all 16 decades of data (with the logistic model). """ # Start with the first 8 decades of data. years1 = np.arange(8) pop1 = np.array([3.929, 5.308, 7.240, 9.638, 12.866, 17.069, 23.192, 31.443]) # Now consider the first 16 decades. years2 = np.arange(16) pop2 = np.array([3.929, 5.308, 7.240, 9.638, 12.866, 17.069, 23.192, 31.443, 38.558, 50.156, 62.948, 75.996, 91.972, 105.711, 122.775, 131.669]) raise NotImplementedError("Problem 5 Incomplete")
vocales ='aeiou' while True: palabra = input("Escriba una palabra: ") letras = palabra.split() if len(letras) == 1: break else: print("Eso no es solo una palabra") pass posicion = -1 puntos_kevin = 0 puntos_stuart = 0 for letras in palabra: if vocales.__contains__(letras): if palabra.count(letras) > 1: posicion = palabra.index(letras, posicion + 1) puntos_kevin = puntos_kevin + len(palabra) - palabra.index(letras, posicion) else: puntos_kevin = puntos_kevin + len(palabra) - palabra.index(letras) else: if palabra.count(letras) > 1: posicion = palabra.index(letras, posicion + 1) puntos_stuart = puntos_stuart + len(palabra) - palabra.index(letras, posicion) else: puntos_stuart = puntos_stuart + len(palabra) - palabra.index(letras) if puntos_stuart > puntos_kevin: print("El ganador es Stuart, ha obtenido ", puntos_stuart, " puntos") elif puntos_kevin > puntos_stuart: print("El ganador es Kevin, ha obtenido ", puntos_kevin, " puntos") else: print("Draw")
kheader = ''' <head> <style> <!-- body {font-size:12px; font-family:verdana,arial,helvetica,sans-serif; background-color:#ffffff} .text {font-size:12px; font-family:verdana,arial,helvetica,sans-serif} h1 {font-size:24px; font-weight:bold; font-family:verdana,arial,helvetica,sans-serif; color:#005050} h2 {font-size:18px; font-weight:bold; font-family:verdana,arial,helvetica,sans-serif; color:#005050} h3 {font-size:16px; font-weight:bold; font-family:verdana,arial,helvetica,sans-serif} h4 {font-size:14px; font-weight:bold; font-family:verdana,arial,helvetica,sans-serif} h5 {font-size:12px; font-weight:bold; font-family:verdana,arial,helvetica,sans-serif; color:#444444} b {font-size:12px; font-weight:bold; font-family:verdana,arial,helvetica,sans-serif} th {font-size:12px; font-weight:bold; font-family:verdana,arial,helvetica,sans-serif} td {font-size:12px; font-family:verdana,arial,helvetica,sans-serif} input {font-size:12px; font-family:verdana,arial,helvetica,sans-serif} select {font-size:12px; font-family:verdana,arial,helvetica,sans-serif} pre {font-size:12px; font-family:courier,monospace} a {text-decoration:none} a:link {color:#003399} a:visited {color:#003399} a:hover {color:#33cc99} font.title3 {color: #005050; font-size:14px; font-weight:bold; font-family:verdana,arial,helvetica,sans-serif} hr.frame0 {border: 1px solid #f5e05f; color: #f5e05f} div.poplay { position: absolute; padding: 2px; background-color: #ffff99; border-top: solid 1px #c0c0c0; border-left: solid 1px #c0c0c0; border-bottom: solid 1px #808080; border-right: solid 1px #808080; visibility: hidden; } span.popup { font-weight: bold; color: #ffffff; white-space: nowrap; } form { margin: 0px; } --> </style> <script language="JavaScript"> var MSIE, Netscape, Opera, Safari, Firefox; if(window.navigator.appName.indexOf("Internet Explorer") >= 0){ MSIE = true; }else if(window.navigator.appName == "Opera"){ Opera = true; }else if(window.navigator.userAgent.indexOf("Safari") >= 0){ Safari = true; }else if(window.navigator.userAgent.indexOf("Firefox") >= 0){ Firefox = true; Netscape = true; }else{ Netscape = true; } function Component(id) { this._component = document.getElementById(id); this._opacity_change_interval = 1; var opc = this._component.style.opacity; if(opc == "") { opc = 1; } this._opacity = opc * 100; } function _Component_ID() { return this._component.id; } Component.prototype.id = _Component_ID; function _Component_FontSize(size) { if(_defined(size)) { this._component.style.fontSize = size + "px"; } else { return this._component.style.fontSize; } } Component.prototype.fontSize = _Component_FontSize; function _Component_OpacityChangeInterval(interval) { if(typeof(interval) == "undefined") { return this._opacity_change_interval; } else { this._opacity_change_interval = interval; } } Component.prototype.opacityChangeInterval = _Component_OpacityChangeInterval function _Component_HTML(html) { var component = this._component; if(typeof(html) == "undefined") { return component.innerHTML; } else { component.innerHTML = html; } } Component.prototype.HTML = _Component_HTML; function _Component_BackgroundColor(color) { this._component.style.backgroundColor = color; } Component.prototype.backgroundColor = _Component_BackgroundColor; function _Component_BorderTop(border) { if(_defined(border)){ var comp = this._component; if(MSIE) { //comp.style.borderTop = border.color(); //comp.style.border-top-style = border.style(); //comp.style.border-top-width = border.width(); } else { comp.style.borderTopColor = border.color(); comp.style.borderTopStyle = border.style(); comp.style.borderTopWidth = border.width() + "px"; } } } Component.prototype.borderTop = _Component_BorderTop; function _Component_BorderBottom(border) { if(_defined(border)){ var comp = this._component; if(MSIE) { } else { comp.style.borderBottomColor = border.color(); comp.style.borderBottomStyle = border.style(); comp.style.borderBottomWidth = border.width() + "px"; } } } Component.prototype.borderBottom = _Component_BorderBottom; function _Component_BorderLeft(border) { if(_defined(border)){ var comp = this._component; if(MSIE) { } else { comp.style.borderLeftColor = border.color(); comp.style.borderLeftStyle = border.style(); comp.style.borderLeftWidth = border.width() + "px"; } } } Component.prototype.borderLeft = _Component_BorderLeft; function _Component_BorderRight(border) { if(_defined(border)){ var comp = this._component; if(MSIE) { } else { comp.style.borderRightColor = border.color(); comp.style.borderRightStyle = border.style(); comp.style.borderRightWidth = border.width() + "px"; } } } Component.prototype.borderRight = _Component_BorderRight; function _Component_Border() { var arg = _Component_Border.arguments; if(arg.length == 1) { this.borderTop(arg[0]); this.borderBottom(arg[0]); this.borderLeft(arg[0]); this.borderRight(arg[0]); } else if(arg.length == 2) { this.borderTop(arg[0]); this.borderBottom(arg[0]); this.borderLeft(arg[1]); this.borderRight(arg[1]); }else if(arg.length == 3) { this.borderTop(arg[0]); this.borderLeft(arg[1]); this.borderRight(arg[1]); this.borderBottom(arg[2]); } else if(arg.length == 4) { this.borderTop(arg[0]); this.borderRight(arg[1]); this.borderBottom(arg[2]); this.borderLeft(arg[3]); } } Component.prototype.border = _Component_Border; function _Component_X(x) { var component = this._component; if(typeof(x) == "undefined") { var ret = (MSIE) ? component.style.pixelLeft : parseInt(component.style.left); return ret; } else { if(MSIE) { component.style.pixelLeft = x; } else if(Opera) { component.style.left = x; } else { component.style.left = x + "px"; } } } Component.prototype.x = _Component_X; function _Component_Y(y) { var component = this._component; if(typeof(y) == "undefined") { var ret = (MSIE) ? component.style.pixelTop : parseInt(component.style.top); return ret; }else { if(MSIE) { component.style.pixelTop = y; } else if(Opera) { component.style.top = y; } else { component.style.top = y + "px"; } } } Component.prototype.y = _Component_Y; function _Component_Move(x, y) { this.x(x); this.y(y); } Component.prototype.move = _Component_Move; function _Component_Width(width) { var component = this._component; if(typeof(width) == "undefined") { var ret = (MSIE) ? component.style.pixelWidth : parseInt(component.style.width); return ret; } else { if(MSIE) { component.style.pixelWidth = width; } else if(Opera) { component.style.width = width; } else { component.style.width = width + "px"; } } } Component.prototype.width = _Component_Width; function _Component_Height(height) { var component = this._component; if(typeof(height) == "undefined") { var ret = (MSIE) ? component.style.pixelWidth : parseInt(component.style.width); return ret; } else { if(MSIE) { component.style.pixelHeight = height; } else if(Opera) { component.style.height = height; } else { component.style.height = height + "px"; } } } Component.prototype.height = _Component_Height; function _Component_Size(width, height) { this.width(width); this.height(height); } Component.prototype.size = _Component_Size; function _Component_Visible(visible) { var component = this._component; if(typeof(visible) == "undefined") { return (component.style.visibility == "visible") ? true : false; } else { if(MSIE || Safari || Firefox || Opera) { if(visible) { component.style.visibility = "visible"; this._opacityStep = 10; this._opacity = 0; } else { this._opacityStep = -10; this._opacity = this.opacity(); } _addComponent(this); this.changeOpacity(); } else { component.style.visibility = (visible) ? "visible" : "hidden"; } } } Component.prototype.visible = _Component_Visible; function _Component_ChangeOpacity() { var opacity = this._opacity + this._opacityStep; this.opacity(opacity); if(opacity >= 100) { return; } else if(opacity <= 0) { this._component.style.visibility = "hidden"; return } else { var interval = this._opacity_change_interval; setTimeout("_triggerChangeOpacity('" + this.id() + "')", interval); } } Component.prototype.changeOpacity = _Component_ChangeOpacity; function _Component_Opacity(opacity) { if(typeof(opacity) == "undefined") { return this._opacity; } else { this._opacity = opacity; var component = this._component; component.style.opacity = opacity / 100; component.style.mozOpacity = opacity / 100; component.style.filter = "alpha(opacity=" + opacity + ")"; } } Component.prototype.opacity = _Component_Opacity; var _component_list = new Array(); function _addComponent(component) { var id = component.id(); _component_list[id] = component; } function _triggerChangeOpacity(id) { var component = _component_list[id]; component.changeOpacity(); } function _defined(val) { return (typeof(val) != "undefined") ? true : false; } function Border() { this._width = 1; this._style = "solid"; this._color = "#000000"; } function _Border_Color(color) { if(!_defined(color)){ return this._color; }else{ this._color = color; } } Border.prototype.color = _Border_Color; function _Border_Style(style) { if(!_defined(style)){ return this._style; }else{ this._style = style; } } Border.prototype.style = _Border_Style; function _Border_Width(width) { if(!_defined(width)){ return this._width; }else{ this._width = width; } } Border.prototype.width = _Border_Width; document.onmousemove = _documentMouseMove; var _mousePosX = 0; var _mousePosY = 0; function _documentMouseMove(evt) { _mousePosX = _getEventX(evt); _mousePosY = _getEventY(evt); } function _getEventX(evt) { var ret; if(Netscape){ ret = evt.pageX; }else if(MSIE){ ret = event.x + getPageXOffset(); }else if(Safari){ ret = event.x + getPageXOffset(); }else{ ret = evt.x; } return ret; } function _getEventY(evt) { var ret; if(Netscape){ ret = evt.pageY; }else if(MSIE){ ret = event.y + getPageYOffset(); }else if(Safari){ ret = event.y + getPageYOffset(); }else{ ret = event.y; } return ret; } function getCurrentMouseX() { return _mousePosX; } function getCurrentMouseY() { return _mousePosY } function getPageXOffset() { var ret; if(Safari || Opera){ ret = document.body.scrollLeft; }else{ if(document.body.scrollLeft > 0){ ret = document.body.scrollLeft; }else{ ret = document.documentElement.scrollLeft; } } return ret; } function getPageYOffset() { var ret; if(Safari || Opera){ ret = document.body.scrollTop; }else{ if(document.body.scrollTop > 0){ ret = document.body.scrollTop; }else{ ret = document.documentElement.scrollTop; } } return ret; } var timer = 0; var p_entry, p_title, p_bgcolor; function popupTimer(entry, title, bgcolor) { p_entry = entry; p_title = title; p_bgcolor = bgcolor; if(timer == 0){ var func = "showThumbnail()"; timer = setTimeout(func, 1200); } } function showThumbnail() { var url = ""; if(p_entry.match(/^[A-Z]+\d+$/)) { url = "http://www.genome.jp/kegg/misc/thumbnail/" + p_entry + ".gif"; } else if(p_entry.match(/(\d+)$/)) { url = "http://www.genome.jp/kegg/misc/thumbnail/map" + RegExp.$1 + ".gif"; } var html = ""; html += '<img src="' + url + '" alt="Loading...">'; var x = getCurrentMouseX(); var y = getCurrentMouseY(); var layer = new Component("poplay"); layer.backgroundColor(p_bgcolor); layer.HTML(html); layer.move(x, y+40); layer.visible(true); timer = 0; } function hideMapTn(){ var layer = new Component("poplay"); layer.visible(false); if(timer != 0){ clearTimeout(timer); timer = 0; } } </script> </head> '''
def linear_search(list, target): result = False if not target: return "Error: target is None" if not list: return "Error: list is None" for n in list: if n == target: result = True return result return result list = [1,5,2,3,6,10,2] target = 1 print("original: " + str(list)) print("result : " + str(linear_search(list, target))) # O(N)
# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'chromium_code': 1, # Use higher warning level. }, 'includes': [ 'content_browser.gypi', 'content_common.gypi', 'content_gpu.gypi', 'content_plugin.gypi', 'content_ppapi_plugin.gypi', 'content_renderer.gypi', 'content_worker.gypi', ], }
par = [] impar = [] for i in range(0, 10): num = int(input("escreva um número: ")) if num % 2 == 0: par.append(num) else: impar.append(num) print(f"Essa lista tem {len(par)} números pares e {len(impar)} impares")
cx = 250 cy = 250 cRadius = 200 i=0 def setup(): size(500, 500) smooth() background(50) strokeWeight(5) stroke(250) noLoop() def draw(): global i while i <2*PI : x1 = cos(i)*cRadius + cx y1 = sin(i)*cRadius + cy line(x1 , y1 , x1 , y1) line(cx , cy , cx , cy) i += 2*PI/12 def keyPressed(): if (key== "s"): saveFrame(" myProcessing .png")
#desenvolva um pograma que mostre as duas notas de um aluno calcule, e mostre a sua média np1 = float(input('Me diga sua nota da np1:')) np2 = float(input('Me diga a sua notada np2:')) print('Sua média é ', float((np1+np2)/2 )) #outra forma '''resultado = (np1+np2)/2 print('Sua média é {}'.format(resultado)''' #essa linha de baixo não esta na aula eu ja sabia if (np1+np2)/2 >=6: print('Parabéns você passou!') if (np1+np2)/2 ==5: print('Encima em!') if (np1+np2)/2 <=4: print('Estude mais um pouco') if (np1+np2)/2 == 0: print('orra! o trem ta fei')
def m(a,n,b,c,d): if n<0: return(abs(b-c)) k = str(n)+'|'+str(b) try: return d[k] except: inc = m(a,n-1,b+a[n],c,d) exc = m(a,n-1,b,c+a[n],d) d[k] = min(inc,exc) return d[k] for i in range(int(input())): d = {} n = int(input()) a = [int(j) for j in input().split()] if len(set(a))-n!=0: print(0) else: print(m(a,n-1,0,0,d))
class DocumentFileContentToolsViewsTestMixin: def _request_document_parsing_error_list_view(self): return self.get(viewname='document_parsing:error_list') def _request_document_type_parsing_view(self): return self.post( viewname='document_parsing:document_type_submit', data={ 'document_type': self.test_document_type.pk } ) class DocumentFileContentViewTestMixin: def _request_test_document_file_content_delete_view(self): return self.post( viewname='document_parsing:document_file_content_delete', kwargs={ 'document_file_id': self.test_document_file.pk } ) def _request_test_document_file_content_download_view(self): return self.get( viewname='document_parsing:document_file_content_download', kwargs={ 'document_file_id': self.test_document_file.pk } ) def _request_test_document_file_content_view(self): return self.get( 'document_parsing:document_file_content_view', kwargs={ 'document_file_id': self.test_document_file.pk } ) def _request_test_document_file_page_content_view(self): return self.get( viewname='document_parsing:document_file_page_content_view', kwargs={ 'document_file_page_id': self.test_document_file.pages.first().pk, } ) def _request_test_document_file_parsing_error_list_view(self): return self.get( viewname='document_parsing:document_file_parsing_error_list', kwargs={ 'document_file_id': self.test_document_file.pk, } ) def _request_test_document_file_parsing_submit_view(self): return self.post( viewname='document_parsing:document_file_submit', kwargs={ 'document_file_id': self.test_document_file.pk } ) def _request_test_document_parsing_submit_view(self): return self.post( viewname='document_parsing:document_submit', kwargs={ 'document_id': self.test_document.pk } ) class DocumentParsingAPITestMixin: def _request_document_file_page_content_api_view(self): return self.get( viewname='rest_api:document-file-page-content-view', kwargs={ 'document_id': self.test_document.pk, 'document_file_id': self.test_document_file.pk, 'document_file_page_id': self.test_document_file.pages.first().pk } ) class DocumentTypeContentViewsTestMixin: def _request_test_document_type_parsing_settings_view(self): return self.get( viewname='document_parsing:document_type_parsing_settings', kwargs={'document_type_id': self.test_document_type.pk} ) class DocumentTypeParsingSettingsAPIViewTestMixin(): def _request_document_type_parsing_settings_details_api_view(self): return self.get( viewname='rest_api:document-type-parsing-settings-view', kwargs={'document_type_id': self.test_document_type.pk} ) def _request_document_type_parsing_settings_patch_api_view(self): return self.patch( viewname='rest_api:document-type-parsing-settings-view', kwargs={'document_type_id': self.test_document_type.pk}, data={'auto_parsing': True} ) def _request_document_type_parsing_settings_put_api_view(self): return self.put( viewname='rest_api:document-type-parsing-settings-view', kwargs={'document_type_id': self.test_document_type.pk}, data={'auto_parsing': True} )
class SqlQueries: create_staging_events = (""" CREATE TABLE IF NOT EXISTS public.events_stage ( index integer, concert varchar(256), artist varchar(256), location varchar(256), start_date date ); """) create_staging_songs = (""" CREATE TABLE IF NOT EXISTS public.songs_stage ( index integer, artist varchar(256), artist_listeners integer, song varchar(256), song_playcount integer, song_listeners integer ); """) create_dwh_songs = (""" CREATE TABLE IF NOT EXISTS public.songs_dwh ( song varchar(256), song_playcount integer, song_listeners integer, artist varchar(256) ); """) create_dwh_artists = (""" CREATE TABLE IF NOT EXISTS public.artists_dwh ( artists varchar(256), artist_listeners integer ); """) create_dwh_concerts = (""" CREATE TABLE IF NOT EXISTS public.concerts_dwh ( name varchar(256), location varchar(256), start_date date, artist varchar(256) ); """) songs_insert = (""" INSERT INTO public.songs_dwh (song, song_playcount, song_listeners, artist) SELECT song, song_playcount, song_listeners, artist FROM public.songs_stage WHERE artist IS NOT NULL """) artists_insert = (""" INSERT INTO public.artists_dwh (artists, artist_listeners) SELECT DISTINCT ss.artist, ss.artist_listeners FROM public.songs_stage ss FULL JOIN public.events_stage es ON ss.artist = es.artist WHERE ss.artist IS NOT NULL AND es.artist IS NOT NULL """) concerts_insert = (""" INSERT INTO public.concerts_dwh (name, location, start_date, artist) SELECT concert, location, start_date, artist FROM public.events_stage WHERE artist IS NOT NULL """) delete_staging_events = "DROP TABLE IF EXISTS public.events_stage;" delete_staging_songs = "DROP TABLE IF EXISTS public.songs_stage;" delete_dwh_songs = "DROP TABLE IF EXISTS public.songs_dwh;" delete_dwh_artists = "DROP TABLE IF EXISTS public.artists_dwh;" delete_dwh_concerts = "DROP TABLE IF EXISTS public.concerts_dwh;" create_staging_table_queries = [create_staging_events, create_staging_songs] delete_staging_table_queries = [delete_staging_events, delete_staging_songs] create_dwh_table_queries = [create_dwh_songs, create_dwh_artists, create_dwh_concerts] delete_dwh_table_queries = [delete_dwh_songs, delete_dwh_artists, delete_dwh_concerts]
# Excel Sheet Column Number ''' Given a column title as appear in an Excel sheet, return its corresponding column number. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... Example 1: Input: "A" Output: 1 Example 2: Input: "AB" Output: 28 Example 3: Input: "ZY" Output: 701 Constraints: 1 <= s.length <= 7 s consists only of uppercase English letters. s is between "A" and "FXSHRXW". ''' class Solution: def titleToNumber(self, s: str) -> int: s = s[::-1] ans = 0 for i, ch in enumerate(s): ans = ans + (ord(ch)-64)*(26**i) return ans
''' Add two numbers ''' def add(a, b): return a + b ''' Concatenate two lists ''' def concat(L1, L2, L3): return L1 + L2 + L3 ''' Get length of a list ''' def length(L): # We will make this one wrong to test failed tests return len(L) - 1
#Lo que se busca es, dependiendo de la posición Y del peón en el tablero, los peones decidan poner una pared vertical en frente de su oponente posPeon1Y = 0 posPeon1X = 4 posPeon2Y = 8 posPeon2X = 4 peonWall1 = 10 peonWall2 = 10 coolDown1 = 2 coolDown2 = 2 while(posPeon1Y != 8 or posPeon2Y != 0): if(posPeon1Y == 3 and coolDown2 == 2 and peonWall2 != 0 or posPeon1Y == posPeon2Y and coolDown2 == 2 and peonWall2 != 0): print("Pawn 2 added a wall in " ,posPeon1Y + 1) peonWall2-= 1 coolDown2 = 0 else: print("El peon 2 se mueve") coolDown2+= 1 if(posPeon2Y == 6 and coolDown1 == 2 and peonWall1 != 0 or posPeon1Y == posPeon2Y and coolDown1 == 2 and peonWall1 != 0): print("Pawn 1 added a wall in", posPeon2Y - 1) peonWall1-= 1 coolDown1 = 0 else: print("El peon 1 se mueve") coolDown1+= 1
# -*- coding: utf-8 -*- def __reversed__(self): """Built-in to implement reverse iteration""" return self._statements.__reversed__()
# -*- coding:utf-8 -*- """ @author: SiriYang @file: __init__.py @createTime: 2021-01-23 13:51:53 @updateTime: 2021-01-23 13:51:53 @codeLines: 0 """
""" home.ts.__init__ ================ Nothing to see here! """
'''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.''' # Bitcoin Cash (BCH) qpz32c4lg7x7lnk9jg6qg7s4uavdce89myax5v5nuk # Ether (ETH) - 0x843d3DEC2A4705BD4f45F674F641cE2D0022c9FB # Litecoin (LTC) - Lfk5y4F7KZa9oRxpazETwjQnHszEPvqPvu # Bitcoin (BTC) - 34L8qWiQyKr8k4TnHDacfjbaSqQASbBtTd # contact :- github@jamessawyer.co.uk """ Wiggle Sort. Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... For example: if input numbers = [3, 5, 2, 1, 6, 4] one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4]. """ def wiggle_sort(nums): """Perform Wiggle Sort.""" for i in range(len(nums)): if (i % 2 == 1) == (nums[i - 1] > nums[i]): nums[i - 1], nums[i] = nums[i], nums[i - 1] if __name__ == "__main__": print("Enter the array elements:\n") array = list(map(int, input().split())) print("The unsorted array is:\n") print(array) wiggle_sort(array) print("Array after Wiggle sort:\n") print(array)
def mul(x, y): return x * y % 1337 class Solution(object): def superPow(self, a, b): """ :type a: int :type b: List[int] :rtype: int """ if a >= 1337: return self.superPow(a % 1337, b) if a == 0 or a == 1: return a n = len(b) res = 1 for i in range(0, n): if b[n - 1 - i]: res = mul(res, pow(a, b[n - 1 - i], 1337)) a = pow(a, 10, 1337) return res
Terrain = [ {"stop": 0.00, "color": {'r': 0x00, 'g': 0x9a, 'b': 0x24}}, {"stop": 0.45, "color": {'r': 0xff, 'g': 0xff, 'b': 0x00}}, {"stop": 0.90, "color": {'r': 0xff, 'g': 0x00, 'b': 0x00}}, {"stop": 1.00, "color": {'r': 0xff, 'g': 0xe0, 'b': 0xe0}} ] Water = [ {"stop": 0.00, "color": {'r': 0x34, 'g': 0x40, 'b': 0x44}}, {"stop": 1.00, "color": {'r': 0x15, 'g': 0x54, 'b': 0xd1}} ] WaterDepth = [ {"stop": 0.00, "color": {'r': 0x15, 'g': 0x54, 'b': 0xd1}}, {"stop": 1.00, "color": {'r': 0x34, 'g': 0x40, 'b': 0x44}} ] GrayScale = [ {"stop": 0.00, "color": {'r': 0x00, 'g': 0x00, 'b': 0x00}}, {"stop": 1.00, "color": {'r': 0xff, 'g': 0xff, 'b': 0xff}} ]
def load(h): return ({'abbr': 0, 'code': 0, 'title': 'Unknown'}, {'abbr': 'fg', 'code': 1, 'title': 'First guess'}, {'abbr': 'an', 'code': 2, 'title': 'Analysis'}, {'abbr': 'ia', 'code': 3, 'title': 'Initialised analysis'}, {'abbr': 'oi', 'code': 4, 'title': 'Oi analysis'}, {'abbr': '3v', 'code': 5, 'title': '3d variational analysis'}, {'abbr': '4v', 'code': 6, 'title': '4d variational analysis'}, {'abbr': '3g', 'code': 7, 'title': '3d variational gradients'}, {'abbr': '4g', 'code': 8, 'title': '4d variational gradients'}, {'abbr': 'fc', 'code': 9, 'title': 'Forecast'}, {'abbr': 'cf', 'code': 10, 'title': 'Control forecast'}, {'abbr': 'pf', 'code': 11, 'title': 'Perturbed forecast'}, {'abbr': 'ef', 'code': 12, 'title': 'Errors in first guess'}, {'abbr': 'ea', 'code': 13, 'title': 'Errors in analysis'}, {'abbr': 'cm', 'code': 14, 'title': 'Cluster means'}, {'abbr': 'cs', 'code': 15, 'title': 'Cluster std deviations'}, {'abbr': 'fp', 'code': 16, 'title': 'Forecast probability'}, {'abbr': 'em', 'code': 17, 'title': 'Ensemble mean'}, {'abbr': 'es', 'code': 18, 'title': 'Ensemble standard deviation'}, {'abbr': 'fa', 'code': 19, 'title': 'Forecast accumulation'}, {'abbr': 'cl', 'code': 20, 'title': 'Climatology'}, {'abbr': 'si', 'code': 21, 'title': 'Climate simulation'}, {'abbr': 's3', 'code': 22, 'title': 'Climate 30 days simulation'}, {'abbr': 'ed', 'code': 23, 'title': 'Empirical distribution'}, {'abbr': 'tu', 'code': 24, 'title': 'Tubes'}, {'abbr': 'ff', 'code': 25, 'title': 'Flux forcing realtime'}, {'abbr': 'of', 'code': 26, 'title': 'Ocean forward'}, {'abbr': 'efi', 'code': 27, 'title': 'Extreme forecast index'}, {'abbr': 'efic', 'code': 28, 'title': 'Extreme forecast index control'}, {'abbr': 'pb', 'code': 29, 'title': 'Probability boundaries'}, {'abbr': 'ep', 'code': 30, 'title': 'Event probability'}, {'abbr': 'bf', 'code': 31, 'title': 'Bias-corrected forecast'}, {'abbr': 'cd', 'code': 32, 'title': 'Climate distribution'}, {'abbr': '4i', 'code': 33, 'title': '4D analysis increments'}, {'abbr': 'go', 'code': 34, 'title': 'Gridded observations'}, {'abbr': 'me', 'code': 35, 'title': 'Model errors'}, {'abbr': 'pd', 'code': 36, 'title': 'Probability distribution'}, {'abbr': 'ci', 'code': 37, 'title': 'Cluster information'}, {'abbr': 'sot', 'code': 38, 'title': 'Shift of Tail'}, {'abbr': 'eme', 'code': 39, 'title': 'Ensemble data assimilation model errors'}, {'abbr': 'im', 'code': 40, 'title': 'Images'}, {'abbr': 'sim', 'code': 42, 'title': 'Simulated images'}, {'abbr': 'wem', 'code': 43, 'title': 'Weighted ensemble mean'}, {'abbr': 'wes', 'code': 44, 'title': 'Weighted ensemble standard deviation'}, {'abbr': 'cr', 'code': 45, 'title': 'Cluster representative'}, {'abbr': 'ses', 'code': 46, 'title': 'Scaled ensemble standard deviation'}, {'abbr': 'taem', 'code': 47, 'title': 'Time average ensemble mean'}, {'abbr': 'taes', 'code': 48, 'title': 'Time average ensemble standard deviation'}, {'abbr': 'sg', 'code': 50, 'title': 'Sensitivity gradient'}, {'abbr': 'sf', 'code': 52, 'title': 'Sensitivity forecast'}, {'abbr': 'pa', 'code': 60, 'title': 'Perturbed analysis'}, {'abbr': 'icp', 'code': 61, 'title': 'Initial condition perturbation'}, {'abbr': 'sv', 'code': 62, 'title': 'Singular vector'}, {'abbr': 'as', 'code': 63, 'title': 'Adjoint singular vector'}, {'abbr': 'svar', 'code': 64, 'title': 'Signal variance'}, {'abbr': 'cv', 'code': 65, 'title': 'Calibration/Validation forecast'}, {'abbr': 'or', 'code': 70, 'title': 'Ocean reanalysis'}, {'abbr': 'fx', 'code': 71, 'title': 'Flux forcing'}, {'abbr': 'fu', 'code': 72, 'title': 'Fill-up'}, {'abbr': 'sfo', 'code': 73, 'title': 'Simulations with forcing'}, {'abbr': 'fcmean', 'code': 80, 'title': 'Forecast mean'}, {'abbr': 'fcmax', 'code': 81, 'title': 'Forecast maximum'}, {'abbr': 'fcmin', 'code': 82, 'title': 'Forecast minimum'}, {'abbr': 'fcstdev', 'code': 83, 'title': 'Forecast standard deviation'}, {'abbr': 'emtm', 'code': 84, 'title': 'Ensemble mean of temporal mean'}, {'abbr': 'estdtm', 'code': 85, 'title': 'Ensemble standard deviation of temporal mean'}, {'abbr': 'hcmean', 'code': 86, 'title': 'Hindcast climate mean'}, {'abbr': 'ssd', 'code': 87, 'title': 'Simulated satellite data'}, {'abbr': 'gsd', 'code': 88, 'title': 'Gridded satellite data'}, {'abbr': 'ga', 'code': 89, 'title': 'GFAS analysis'}, {'abbr': 'gai', 'code': 90, 'title': 'Gridded analysis input'})
class Solution: def maxSubArray(self, nums: [int]) -> int: tmp = nums[0] maxv = tmp for i in range(1, len(nums)): if tmp + nums[i] > nums[i]: maxv = max(maxv, tmp + nums[i]) tmp = tmp + nums[i] else: maxv = max(maxv, tmp, nums[i]) tmp = nums[i] return maxv
class SimulationParameters: start_time = 0. # start time for simulation end_time = 50000. # end time for simulation dt_video = 0.1 dt_simulation = 0.03 # smallest time step for simulation dt_plotting = 0.3 # refresh rate for plots dt_controller = dt_simulation # sample rate for the controller dt_observer = dt_simulation # sample rate for the observer
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ result = ListNode(0) head = result carry = 0 while (l1 or l2): addition = 0 if l1: addition = addition + l1.val if l2: addition = addition + l2.val addition = addition + carry val = addition % 10 carry = addition / 10 result.next = ListNode(val) result = result.next if l1: l1 = l1.next if l2: l2 = l2.next if carry: result.next = ListNode(carry) return head.next
__all__ = [ 'FeatureEncoder' ] class FeatureEncoder(): r"""Class for implementing feature encoders. Date: 2020 Author: Luka Pečnik License: MIT Attributes: Name (str): Name of the feature encoder. """ Name = None def __init__(self, **kwargs): r"""Initialize feature encoder. """ return None def fit(self, feature): r"""Fit feature encoder. Arguments: feature (pandas.core.frame.DataFrame): A column (categorical) from DataFrame of features. """ return None def transform(self, feature): r"""Transform feature's values. Arguments: feature (pandas.core.frame.DataFrame): A column (categorical) from DataFrame of features. Returns: pandas.core.frame.DataFrame: A transformed column. """ return None def to_string(self): r"""User friendly representation of the object. Returns: str: User friendly representation of the object. """ return '{name}'
class CyclesCurveSettings: radius_scale = None root_width = None shape = None tip_width = None use_closetip = None
#from .atributo import Atributo class TablaDestino: nombre = " " atributos = [] datos=[] funcion=False atributo='' proceso='' def __init__(self,nombre,atributos,funcion=False,atributo=None,proceso=None): self.nombre=nombre self.atributos=atributos self.funcion=funcion self.atributo=atributo self.proceso=proceso def setDato(self,datos): #print (datos) self.datos.append(datos)
#ordena a lista em ordem crescente sem o SORT/SORTED numeros = list() for n in range(0,5): numero = int(input("Digite um numero: ")) for chave, valor in enumerate(numeros): if numero < valor: numeros.insert(chave, numero) break else: numeros.append(numero) print(numeros)
# # Copyright (c) 2021 salesforce.com, inc. # All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause # """ Contains all anomaly detection models. Forecaster-based anomaly detection models may be found in :py:mod:`merlion.models.anomaly.forecast_based`. Change-point detection models may be found in :py:mod:`merlion.models.anomaly.change_point`. For anomaly detection, we define an abstract `DetectorBase` class which inherits from `ModelBase` and supports the following interface, in addition to ``model.save`` and ``DetectorClass.load`` defined for `ModelBase`: 1. ``model = DetectorClass(config)`` - initialization with a model-specific config - configs contain: - a (potentially trainable) data pre-processing transform from :py:mod:`merlion.transform`; note that ``model.transform`` is a property which refers to ``model.config.transform`` - **a (potentially trainable) post-processing rule** from :py:mod:`merlion.post_process`; note that ``model.post_rule`` is a property which refers to ``model.config.post_rule``. In general, this post-rule will have two stages: :py:mod:`calibration <merlion.post_process.calibrate>` and :py:mod:`thresholding <merlion.post_process.threshold>`. - booleans ``enable_calibrator`` and ``enable_threshold`` (both defaulting to ``True``) indicating whether to enable calibration and thresholding in the post-rule. - model-specific hyperparameters 2. ``model.get_anomaly_score(time_series, time_series_prev=None)`` - returns a time series of anomaly scores for each timestamp in ``time_series`` - ``time_series_prev`` (optional): the most recent context, only used for some models. If not provided, the training data is used as the context instead. 3. ``model.get_anomaly_label(time_series, time_series_prev=None)`` - returns a time series of post-processed anomaly scores for each timestamp in ``time_series``. These scores are calibrated to correspond to z-scores if ``enable_calibrator`` is ``True``, and they have also been filtered by a thresholding rule (``model.threshold``) if ``enable_threshold`` is ``True``. ``threshold`` is specified manually in the config (though it may be modified by `DetectorBase.train`), . - ``time_series_prev`` (optional): the most recent context, only used for some models. If not provided, the training data is used as the context instead. 4. ``model.train(train_data, anomaly_labels=None, train_config=None, post_rule_train_config=None)`` - trains the model on the time series ``train_data`` - ``anomaly_labels`` (optional): a time series aligned with ``train_data``, which indicates whether each time stamp is anomalous - ``train_config`` (optional): extra configuration describing how the model should be trained (e.g. learning rate for the `LSTMDetector`). Not used for all models. Class-level default provided for models which do use it. - ``post_rule_train_config``: extra configuration describing how to train the model's post-rule. Class-level default is provided for all models. - returns a time series of anomaly scores produced by the model on ``train_data``. """
# -*-coding:utf-8 -*- # Reference:********************************************** # @Time    : 2019-12-31 19:53 # @Author  : Fabrice LI # @File    : 20191231_106_convert_sorted_list_to_binary_search_tree.py # @User    : liyihao # @Software : PyCharm # @Description: Given a singly linked list where elements are sorted in ascending order, # convert it to a height balanced BST. # Reference:********************************************** """ Example 1: Input: array = 1->2->3 Output: 2 / \ 1 3 Example 2: Input: 2->3->6->7 Output: 3 / \ 2 6 \ 7 Explanation: There may be multi answers, and you could return any of them. """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def sortedListToBST(self, head: ListNode) -> TreeNode: if not head: return None if not head.next: return TreeNode(head.val) def find_mid(head): slow = fast = head pre = None while fast and fast.next: pre = slow slow = slow.next fast = fast.next.next pre.next =None return slow mid = find_mid(head) root = TreeNode(mid.val) root.left = self.sortedListToBST(head) root.right = self.sortedListToBST(mid.next) return root
valid_address_types = [ ['ant', 'antenna'], ['mbth', 'marine berth'], ['allotment', 'allotment'], ['atm', 'auto teller machine'], ['bbox', 'bathing box'], ['bbq', 'barbeque'], ['berths', 'berths'], ['berth', 'berth'], ['bldgs', 'buildings'], ['bldg', 'building'], ['bld', 'building'], ['bngws', 'bungalows'], ['bngw', 'bungalow'], ['cages', 'cages'], ['cage', 'cage'], ['carps', 'carparks'], ['carp', 'carpark'], ['cars', 'carspace'], ['carw', 'carwash'], ['cool', 'coolroom'], ['ctges', 'cottages'], ['ctge', 'cottage'], ['ctyds', 'courtyards'], ['ctyd', 'courtyard'], ['dupl', 'duplex'], ['fctys', 'factories'], ['fcty', 'factory'], ['flats', 'flats'], ['grges', 'garages'], ['flat', 'flat'], ['grge', 'garage'], ['heli', 'heliport'], ['hngrs', 'hangers'], ['hngr', 'hanger'], ['host', 'hostel'], ['hses', 'houses'], ['hse', 'house'], ['ksk', 'kiosk'], ['lbby', 'lobby'], ['loft', 'loft'], ['lots', 'lots'], ['lot', 'lot'], ['lse', 'lease'], ['str', 'strata unit'], ['msnt', 'maisonette'], ['offcs', 'offices'], ['offc', 'office'], ['pswy', 'passageway'], ['pths', 'penthouse'], ['rest', 'restaraunt'], ['room', 'room'], ['rptn', 'reception'], ['sapt', 'studio apartment'], ['suites', 'suites'], ['suite', 'suite'], ['shcs', 'showcase'], ['sheds', 'sheds'], ['shed', 'shed'], ['shops', 'shops'], ['shp', 'shop'], ['shop', 'shop'], ['shrms', 'showrooms'], ['shrm', 'showroom'], ['sign', 'sign'], ['sites', 'sites'], ['site', 'site'], ['stlls', 'stalls'], ['stll', 'stall'], ['stors', 'stores'], ['stor', 'store'], ['studios', 'studios'], ['stu', 'studio'], ['subs', 'substation'], ['tncys', 'tenancies'], ['tncy', 'tenancy'], ['townhouses', 'townhouses'], ['tnhs', 'townhouse'], ['twrs', 'towers'], ['twr', 'tower'], ['units', 'units'], ['unit', 'unit'], ['u', 'unit'], ['vllas', 'villas'], ['vlla', 'villa'], ['vlt', 'vault'], ['wards', 'wards'], ['ward', 'ward'], ['wc', 'toilet'], ['whses', 'warehouses'], ['whse', 'warehouse'], ['wkshs', 'workshops'], ['wksh', 'workshop'], ['apts', 'apartments'], ['apt', 'apartment'] ]
def get_oauth(): pass def get_repo(owner, name): pass
def decompress(nums): keep = [] for i in range (0,len(nums),2): x = nums[i] while x > 0: keep.append(nums[i+1]) x-=1 return keep #nums = [1,2,3,4] nums = [1,1,2,3] print(decompress(nums))
def weekday(n): 'returns the name of the nth day of the week' days = ['Monday', 'Tuesday', 'Wednesday'] if 1 <= n and n <= 7: return days[n-1]
''' Write and test a program that computes the area of a circle. Request a number representing a radius as input from the user. Use the formula 3.14 × radius^2 to compute the area. Output this result with a suitable label. An example of the program input and output is shown below: Enter the radius: 5 The area is 78.5 square units. ''' radius = float(input("Enter the radius: ")) pi = 3.14 area = pi * (radius * radius) print(f'The area is {area} square units.')
while True: enemy = hero.findNearestEnemy() friend = hero.findNearestFriend() hero.moveXY((friend.pos.x + enemy.pos.x) / 2, (friend.pos.y + enemy.pos.y) / 2);
''' Faça um Programa que leia 10 números inteiros e armazene-os num vetor. Armazene os números pares no vetor PAR e os números IMPARES no vetor impar. Imprima os três vetores. ''' # Resposta: num = [] par = [] imp = [] for n in range(10): num.append(int(input('Digite um número: '))) for n in num: if n % 2 == 0: if n not in par: par.append(n) else: if n not in imp: imp.append(n) print(f'\nNúmeros pares inseridos: {par}\nNúmeros ímpares inseridos: {imp}')
r_fib = {} LIMIT = 100 + 1 fib = [1,2] for i in range(LIMIT): fib.append(fib[-1] + fib[-2]) for i in range(LIMIT): r_fib[fib[i]] = i num_cases = int(input()) for c in range(num_cases): input() code = list(map(int, input().split())) cipher = input().strip() out_text = [' '] * 100 i = 0 str_len = 0 for ch in cipher: if i >= len(code): break if ch.isupper(): out_index = r_fib[code[i]] out_text[out_index] = ch str_len = max(str_len, out_index+1) i += 1 print("".join(out_text[:str_len]))
""" Exception for use in the telemetry agent Copyright (C) 2017-2022 Intel Corporation SPDX-License-Identifier: Apache-2.0 """ class TelemetryException(Exception): pass
# O(N * logN) # https://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/ class Solution(object): def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ res = [] for n in nums: index = self.binary_search(res, n) # use bisect.bisect_left to reduce more runtime if index == -1: res.append(n) else: res[index] = n return len(res) def binary_search(self, nums, target): #find element no less than target if len(nums) == 0: return -1 start = 0 end = len(nums) - 1 while(start + 1 < end): mid = start + (end - start) / 2 if nums[mid] < target: start = mid else: end = mid if nums[start] >= target: return start if nums[end] >= target: return end return -1 # f(i) = max(1, f(j) + 1 if j < i and nums[j] < nums[i]) # O(N ^ 2) class Solution2(object): def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ if nums is None or len(nums) == 0: return 0 m = len(nums) table = [0 for _ in range(m)] table[0] = 1 for i in range(1, m): value = 1 for j in range(i): if nums[j] < nums[i]: value = max(value, table[j] + 1) table[i] = value return max(table)
g = 85 h = 85 if g < h: print("g is less than h") else: if g == h: print("g is equal to h") else: print("g is greater than h")
# -*- coding:utf-8 -*- # Copyright 2019 TEEX # # 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. class Response: def __init__(self, type, response_method, result, request_id, chain_name, gas_price, gas_limit, tora_addr, user_addr, params): self.type = type # builtin 0, collector 1, swap verify 2, cross chain info 3, executor 4 self.response_method = response_method self.result = result self.request_id = request_id self.chain_name = chain_name self.gas_price = gas_price self.gas_limit = gas_limit self.tora_addr = tora_addr self.user_addr = user_addr self.params = params
def soma_imposto(custo,taxa_imposto): preco = custo +(custo * taxa_imposto/100) return preco x = float(input("Digite o valor de custo:")) y = float(input("Digite o valor de porcentagem de imposto:")) result = soma_imposto(x,y) print("O preço final do produto é:",result)
""" # SEARCH IN ROTATED ARRAY You are given an integer array nums sorted in ascending order, and an integer target. Suppose that nums is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). If target is found in the array return its index, otherwise, return -1. Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2: Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 Example 3: Input: nums = [1], target = 0 Output: -1 Constraints: 1 <= nums.length <= 5000 -10^4 <= nums[i] <= 10^4 All values of nums are unique. nums is guranteed to be rotated at some pivot. -10^4 <= target <= 10^4 """ def search(nums, target): l = 0 r = len(nums) - 1 while l <= r: mid = (l + r) // 2 if nums[mid] == target: return mid else: if nums[l] <= nums[mid]: if nums[l] <= target < nums[mid]: r = mid - 1 else: l = mid + 1 else: if nums[mid] < target <= nums[r]: l = mid + 1 else: r = mid - 1 return -1
class Solution: def lengthOfLastWord(self, s: str) -> int: length = 0 for s_i in reversed(s): if(s_i != ' '): length += 1 elif (length != 0): break return length # input = "Hello World" input = "a " output = Solution().lengthOfLastWord(input) print(output)
# -*- coding: utf-8 -*- moves = { 0x01: "POUND", 0x02: "KARATE_CHOP", 0x03: "DOUBLESLAP", 0x04: "COMET_PUNCH", 0x05: "MEGA_PUNCH", 0x06: "PAY_DAY", 0x07: "FIRE_PUNCH", 0x08: "ICE_PUNCH", 0x09: "THUNDERPUNCH", 0x0A: "SCRATCH", 0x0B: "VICEGRIP", 0x0C: "GUILLOTINE", 0x0D: "RAZOR_WIND", 0x0E: "SWORDS_DANCE", 0x0F: "CUT", 0x10: "GUST", 0x11: "WING_ATTACK", 0x12: "WHIRLWIND", 0x13: "FLY", 0x14: "BIND", 0x15: "SLAM", 0x16: "VINE_WHIP", 0x17: "STOMP", 0x18: "DOUBLE_KICK", 0x19: "MEGA_KICK", 0x1A: "JUMP_KICK", 0x1B: "ROLLING_KICK", 0x1C: "SAND_ATTACK", 0x1D: "HEADBUTT", 0x1E: "HORN_ATTACK", 0x1F: "FURY_ATTACK", 0x20: "HORN_DRILL", 0x21: "TACKLE", 0x22: "BODY_SLAM", 0x23: "WRAP", 0x24: "TAKE_DOWN", 0x25: "THRASH", 0x26: "DOUBLE_EDGE", 0x27: "TAIL_WHIP", 0x28: "POISON_STING", 0x29: "TWINEEDLE", 0x2A: "PIN_MISSILE", 0x2B: "LEER", 0x2C: "BITE", 0x2D: "GROWL", 0x2E: "ROAR", 0x2F: "SING", 0x30: "SUPERSONIC", 0x31: "SONICBOOM", 0x32: "DISABLE", 0x33: "ACID", 0x34: "EMBER", 0x35: "FLAMETHROWER", 0x36: "MIST", 0x37: "WATER_GUN", 0x38: "HYDRO_PUMP", 0x39: "SURF", 0x3A: "ICE_BEAM", 0x3B: "BLIZZARD", 0x3C: "PSYBEAM", 0x3D: "BUBBLEBEAM", 0x3E: "AURORA_BEAM", 0x3F: "HYPER_BEAM", 0x40: "PECK", 0x41: "DRILL_PECK", 0x42: "SUBMISSION", 0x43: "LOW_KICK", 0x44: "COUNTER", 0x45: "SEISMIC_TOSS", 0x46: "STRENGTH", 0x47: "ABSORB", 0x48: "MEGA_DRAIN", 0x49: "LEECH_SEED", 0x4A: "GROWTH", 0x4B: "RAZOR_LEAF", 0x4C: "SOLARBEAM", 0x4D: "POISONPOWDER", 0x4E: "STUN_SPORE", 0x4F: "SLEEP_POWDER", 0x50: "PETAL_DANCE", 0x51: "STRING_SHOT", 0x52: "DRAGON_RAGE", 0x53: "FIRE_SPIN", 0x54: "THUNDERSHOCK", 0x55: "THUNDERBOLT", 0x56: "THUNDER_WAVE", 0x57: "THUNDER", 0x58: "ROCK_THROW", 0x59: "EARTHQUAKE", 0x5A: "FISSURE", 0x5B: "DIG", 0x5C: "TOXIC", 0x5D: "CONFUSION", 0x5E: "PSYCHIC_M", 0x5F: "HYPNOSIS", 0x60: "MEDITATE", 0x61: "AGILITY", 0x62: "QUICK_ATTACK", 0x63: "RAGE", 0x64: "TELEPORT", 0x65: "NIGHT_SHADE", 0x66: "MIMIC", 0x67: "SCREECH", 0x68: "DOUBLE_TEAM", 0x69: "RECOVER", 0x6A: "HARDEN", 0x6B: "MINIMIZE", 0x6C: "SMOKESCREEN", 0x6D: "CONFUSE_RAY", 0x6E: "WITHDRAW", 0x6F: "DEFENSE_CURL", 0x70: "BARRIER", 0x71: "LIGHT_SCREEN", 0x72: "HAZE", 0x73: "REFLECT", 0x74: "FOCUS_ENERGY", 0x75: "BIDE", 0x76: "METRONOME", 0x77: "MIRROR_MOVE", 0x78: "SELFDESTRUCT", 0x79: "EGG_BOMB", 0x7A: "LICK", 0x7B: "SMOG", 0x7C: "SLUDGE", 0x7D: "BONE_CLUB", 0x7E: "FIRE_BLAST", 0x7F: "WATERFALL", 0x80: "CLAMP", 0x81: "SWIFT", 0x82: "SKULL_BASH", 0x83: "SPIKE_CANNON", 0x84: "CONSTRICT", 0x85: "AMNESIA", 0x86: "KINESIS", 0x87: "SOFTBOILED", 0x88: "HI_JUMP_KICK", 0x89: "GLARE", 0x8A: "DREAM_EATER", 0x8B: "POISON_GAS", 0x8C: "BARRAGE", 0x8D: "LEECH_LIFE", 0x8E: "LOVELY_KISS", 0x8F: "SKY_ATTACK", 0x90: "TRANSFORM", 0x91: "BUBBLE", 0x92: "DIZZY_PUNCH", 0x93: "SPORE", 0x94: "FLASH", 0x95: "PSYWAVE", 0x96: "SPLASH", 0x97: "ACID_ARMOR", 0x98: "CRABHAMMER", 0x99: "EXPLOSION", 0x9A: "FURY_SWIPES", 0x9B: "BONEMERANG", 0x9C: "REST", 0x9D: "ROCK_SLIDE", 0x9E: "HYPER_FANG", 0x9F: "SHARPEN", 0xA0: "CONVERSION", 0xA1: "TRI_ATTACK", 0xA2: "SUPER_FANG", 0xA3: "SLASH", 0xA4: "SUBSTITUTE", 0xA5: "STRUGGLE", 0xA6: "SKETCH", 0xA7: "TRIPLE_KICK", 0xA8: "THIEF", 0xA9: "SPIDER_WEB", 0xAA: "MIND_READER", 0xAB: "NIGHTMARE", 0xAC: "FLAME_WHEEL", 0xAD: "SNORE", 0xAE: "CURSE", 0xAF: "FLAIL", 0xB0: "CONVERSION2", 0xB1: "AEROBLAST", 0xB2: "COTTON_SPORE", 0xB3: "REVERSAL", 0xB4: "SPITE", 0xB5: "POWDER_SNOW", 0xB6: "PROTECT", 0xB7: "MACH_PUNCH", 0xB8: "SCARY_FACE", 0xB9: "FAINT_ATTACK", 0xBA: "SWEET_KISS", 0xBB: "BELLY_DRUM", 0xBC: "SLUDGE_BOMB", 0xBD: "MUD_SLAP", 0xBE: "OCTAZOOKA", 0xBF: "SPIKES", 0xC0: "ZAP_CANNON", 0xC1: "FORESIGHT", 0xC2: "DESTINY_BOND", 0xC3: "PERISH_SONG", 0xC4: "ICY_WIND", 0xC5: "DETECT", 0xC6: "BONE_RUSH", 0xC7: "LOCK_ON", 0xC8: "OUTRAGE", 0xC9: "SANDSTORM", 0xCA: "GIGA_DRAIN", 0xCB: "ENDURE", 0xCC: "CHARM", 0xCD: "ROLLOUT", 0xCE: "FALSE_SWIPE", 0xCF: "SWAGGER", 0xD0: "MILK_DRINK", 0xD1: "SPARK", 0xD2: "FURY_CUTTER", 0xD3: "STEEL_WING", 0xD4: "MEAN_LOOK", 0xD5: "ATTRACT", 0xD6: "SLEEP_TALK", 0xD7: "HEAL_BELL", 0xD8: "RETURN", 0xD9: "PRESENT", 0xDA: "FRUSTRATION", 0xDB: "SAFEGUARD", 0xDC: "PAIN_SPLIT", 0xDD: "SACRED_FIRE", 0xDE: "MAGNITUDE", 0xDF: "DYNAMICPUNCH", 0xE0: "MEGAHORN", 0xE1: "DRAGONBREATH", 0xE2: "BATON_PASS", 0xE3: "ENCORE", 0xE4: "PURSUIT", 0xE5: "RAPID_SPIN", 0xE6: "SWEET_SCENT", 0xE7: "IRON_TAIL", 0xE8: "METAL_CLAW", 0xE9: "VITAL_THROW", 0xEA: "MORNING_SUN", 0xEB: "SYNTHESIS", 0xEC: "MOONLIGHT", 0xED: "HIDDEN_POWER", 0xEE: "CROSS_CHOP", 0xEF: "TWISTER", 0xF0: "RAIN_DANCE", 0xF1: "SUNNY_DAY", 0xF2: "CRUNCH", 0xF3: "MIRROR_COAT", 0xF4: "PSYCH_UP", 0xF5: "EXTREMESPEED", 0xF6: "ANCIENTPOWER", 0xF7: "SHADOW_BALL", 0xF8: "FUTURE_SIGHT", 0xF9: "ROCK_SMASH", 0xFA: "WHIRLPOOL", 0xFB: "BEAT_UP", }
# Configs # Just Monika. # MongoDB数据库链接 ## Example: mongodb://root:password@192.168.1.9:3821 MONGO_DB_URL = "MONGO_DB_ADDR" # 历史记录最多显示条数 MAX_HISTORY_DISPLAY = 5 # 白名单用户最多显示条数 MAX_WHITELIST_DIAPLAY = 10 # 签到最多尝试次数 TRY_TIME = 5 # 签到失败后延时 LATER_TIME = 60 # 程序启动广播 START_BROADCAST_STR = \ '''Hello World! QQ机器人程序启动成功 软件版本@PSM20200430b 正式版 更新内容@用户登录信息持久化 此版本为GitHub开源分支版本'''
x,y,z = 32,31,23; list = ['Apple','Benana','Mango']; a,b,c = list; print(">>> x y z <<<"); print("> x : " + str(x)); print("> y : " + str(y)); print("> z : " + str(z)); print("\n>>> a b c <<<"); print("> a : " + a); print("> b : " + b); print("> c : " + c);
def addr(regs, a, b, c): result = regs[:] result[c] = regs[a] + regs[b] return result def addi(regs, a, b, c): result = regs[:] result[c] = regs[a] + b return result def mulr(regs, a, b, c): result = regs[:] result[c] = regs[a] * regs[b] return result def muli(regs, a, b, c): result = regs[:] result[c] = regs[a] * b return result def banr(regs, a, b, c): result = regs[:] result[c] = regs[a] & regs[b] return result def bani(regs, a, b, c): result = regs[:] result[c] = regs[a] & b return result def borr(regs, a, b, c): result = regs[:] result[c] = regs[a] | regs[b] return result def bori(regs, a, b, c): result = regs[:] result[c] = regs[a] | b return result def setr(regs, a, b, c): result = regs[:] result[c] = regs[a] return result def seti(regs, a, b, c): result = regs[:] result[c] = a return result def gtir(regs, a, b, c): result = regs[:] if a > regs[b]: result[c] = 1 else: result[c] = 0 return result def gtri(regs, a, b, c): result = regs[:] if regs[a] > b: result[c] = 1 else: result[c] = 0 return result def gtrr(regs, a, b, c): result = regs[:] if regs[a] > regs[b]: result[c] = 1 else: result[c] = 0 return result def eqir(regs, a, b, c): result = regs[:] if a == regs[b]: result[c] = 1 else: result[c] = 0 return result def eqri(regs, a, b, c): result = regs[:] if regs[a] == b: result[c] = 1 else: result[c] = 0 return result def eqrr(regs, a, b, c): result = regs[:] if regs[a] == regs[b]: result[c] = 1 else: result[c] = 0 return result ops = [ addr, addi, mulr, muli, banr, bani, borr, bori, setr, seti, gtir, gtri, gtrr, eqir, eqri, eqrr, ] def registers(line): return list(map(int,line[9:-1].split(', '))) def solve(input): i = 0 total = 0 while i <= len(input): before = registers(input[i]) after = registers(input[i+2]) op = list(map(int, input[i+1].split())) count = 0 for o in ops: # print( o(before, *op[1:]), after) if o(before, *op[1:]) == after: count += 1 if count >= 3: total +=1 i += 4 print(total) # with open('test.txt', 'r') as f: # input = f.read().splitlines() # solve(input) with open('input.txt', 'r') as f: input = f.read().splitlines() solve(input)
class Solution(object): def freqAlphabets(self, s): """ :type s: str :rtype: str """ res = [] n = len(s) - 1 while n >= 0: if s[n] == '#': res.append(s[n - 2:n]) n -= 3 else: res.append(s[n]) n -= 1 res.reverse() return "".join([chr(int(c) + 96)for c in res]) def test_freq_alphabets(): s = Solution() assert "jkab" == s.freqAlphabets("10#11#12") assert "acz" == s.freqAlphabets("1326#") assert "y" == s.freqAlphabets("25#") assert "abcdefghijklmnopqrstuvwxyz" == s.freqAlphabets( "12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#")
languages = [ "afrikaans", "albanian", "amharic", "arabic", "armenian", "assamese", "azerbaijani", "basque", "belarusian", "bengali", "bengali romanize", "bosnian", "breton", "bulgarian", "burmese", "burmese zawgyi font", "catalan", "chinese (simplified)", "chinese (traditional)", "croatian", "czech", "danish", "dutch", "english", "esperanto", "estonian", "filipino", "finnish", "french", "galician", "georgian", "german", "greek", "gujarati", "hausa", "hebrew", "hindi", "hindi romanize", "hungarian", "icelandic", "indonesian", "irish", "italian", "japanese", "javanese", "kannada", "kazakh", "khmer", "korean", "kurdish (kurmanji)", "kyrgyz", "lao", "latin", "latvian", "lithuanian", "macedonian", "malagasy", "malay", "malayalam", "marathi", "mongolian", "nepali", "norwegian", "oriya", "oromo", "pashto", "persian", "polish", "portuguese", "punjabi", "romanian", "russian", "sanskrit", "scottish gaelic", "serbian", "sindhi", "sinhala", "slovak", "slovenian", "somali", "spanish", "sundanese", "swahili", "swedish", "tamil", "tamil romanize", "telugu", "telugu romanize", "thai", "turkish", "ukrainian", "urdu", "urdu romanize", "uyghur", "uzbek", "vietnamese", "welsh", "western frisian", "xhosa", "yiddish", ]
{ "name": "PerUDT", "version": "1.0.0", "task": "Treebank", "splits": ["train", "test", "dev"], "description": "The Persian Universal Dependency Treebank (PerUDT) is the result of automatic coversion of Persian Dependency Treebank (PerDT) with extensive manual corrections", "size": {"train": 26196, "test": 1455, "dev": 1456}, "filenames": ["fa_perdt-ud-train.conllu", "fa_perdt-ud-dev.conllu", "fa_perdt-ud-test.conllu"] }
class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ target = int(a, 2)+ int(b, 2) ans = "" while target//2: ans = str(target%2) + ans target = target//2 ans = str(target) + ans return ans
# # PySNMP MIB module BNET-ATM-TOPOLOGY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BNET-ATM-TOPOLOGY-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:22:58 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection") VpiInteger, = mibBuilder.importSymbols("LAN-EMULATION-CLIENT-MIB", "VpiInteger") s5AtmTop, = mibBuilder.importSymbols("S5-ROOT-MIB", "s5AtmTop") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Counter64, Counter32, ModuleIdentity, Integer32, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, TimeTicks, ObjectIdentity, Unsigned32, iso, Gauge32, IpAddress, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "Counter32", "ModuleIdentity", "Integer32", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "TimeTicks", "ObjectIdentity", "Unsigned32", "iso", "Gauge32", "IpAddress", "Bits") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") bnetAtmTopGbl = MibIdentifier((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 1)) bnetAtmTopLinks = MibIdentifier((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 2)) bnetAtmTopGblStatus = MibScalar((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("topOn", 1), ("topOff", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: bnetAtmTopGblStatus.setStatus('mandatory') bnetAtmTopGblLstChg = MibScalar((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 1, 2), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: bnetAtmTopGblLstChg.setStatus('mandatory') bnetAtmTopGblCurNum = MibScalar((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: bnetAtmTopGblCurNum.setStatus('mandatory') bnetAtmTopGblCurMibVer = MibScalar((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bnetAtmTopGblCurMibVer.setStatus('mandatory') bnetAtmTopGblOperStatus = MibScalar((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("topOn", 1), ("topOff", 2), ("topUnavailable", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: bnetAtmTopGblOperStatus.setStatus('mandatory') bnetAtmTopLinksTable = MibTable((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 2, 1), ) if mibBuilder.loadTexts: bnetAtmTopLinksTable.setStatus('mandatory') bnetAtmTopLinksEntry = MibTableRow((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 2, 1, 1), ).setIndexNames((0, "BNET-ATM-TOPOLOGY-MIB", "bnetAtmTopLinksSlotNumIndx"), (0, "BNET-ATM-TOPOLOGY-MIB", "bnetAtmTopLinksPortNumIndx"), (0, "BNET-ATM-TOPOLOGY-MIB", "bnetAtmTopLinksLcnIndx")) if mibBuilder.loadTexts: bnetAtmTopLinksEntry.setStatus('mandatory') bnetAtmTopLinksSlotNumIndx = MibTableColumn((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: bnetAtmTopLinksSlotNumIndx.setStatus('mandatory') bnetAtmTopLinksPortNumIndx = MibTableColumn((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: bnetAtmTopLinksPortNumIndx.setStatus('mandatory') bnetAtmTopLinksLcnIndx = MibTableColumn((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 2, 1, 1, 3), VpiInteger()).setMaxAccess("readonly") if mibBuilder.loadTexts: bnetAtmTopLinksLcnIndx.setStatus('mandatory') bnetAtmTopLinksTopoState = MibTableColumn((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("unavailable", 1), ("notParticipating", 2), ("participating", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: bnetAtmTopLinksTopoState.setStatus('mandatory') bnetAtmTopLinksPeerSlotNum = MibTableColumn((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: bnetAtmTopLinksPeerSlotNum.setStatus('mandatory') bnetAtmTopLinksPeerPortNum = MibTableColumn((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: bnetAtmTopLinksPeerPortNum.setStatus('mandatory') bnetAtmTopLinksPeerIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 2, 1, 1, 7), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: bnetAtmTopLinksPeerIpAddr.setStatus('mandatory') bnetAtmTopLinksPeerChassisType = MibTableColumn((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 2, 1, 1, 8), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bnetAtmTopLinksPeerChassisType.setStatus('mandatory') bnetAtmTopLinksPeerChassisSubType = MibTableColumn((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 2, 1, 1, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bnetAtmTopLinksPeerChassisSubType.setStatus('mandatory') bnetAtmTopLinksEosSize = MibScalar((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 2, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1440))).setMaxAccess("readonly") if mibBuilder.loadTexts: bnetAtmTopLinksEosSize.setStatus('mandatory') bnetAtmTopLinksEosTable = MibTable((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 2, 3), ) if mibBuilder.loadTexts: bnetAtmTopLinksEosTable.setStatus('mandatory') bnetAtmTopLinksEosEntry = MibTableRow((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 2, 3, 1), ).setIndexNames((0, "BNET-ATM-TOPOLOGY-MIB", "bnetAtmTopLinksSlotNumIndx"), (0, "BNET-ATM-TOPOLOGY-MIB", "bnetAtmTopLinksPortNumIndx"), (0, "BNET-ATM-TOPOLOGY-MIB", "bnetAtmTopLinksLcnIndx")) if mibBuilder.loadTexts: bnetAtmTopLinksEosEntry.setStatus('mandatory') bnetAtmTopLinksEos = MibTableColumn((1, 3, 6, 1, 4, 1, 45, 1, 6, 14, 2, 3, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 1400))).setMaxAccess("readonly") if mibBuilder.loadTexts: bnetAtmTopLinksEos.setStatus('mandatory') mibBuilder.exportSymbols("BNET-ATM-TOPOLOGY-MIB", bnetAtmTopLinksPortNumIndx=bnetAtmTopLinksPortNumIndx, bnetAtmTopLinksLcnIndx=bnetAtmTopLinksLcnIndx, bnetAtmTopLinksEosSize=bnetAtmTopLinksEosSize, bnetAtmTopGblCurNum=bnetAtmTopGblCurNum, bnetAtmTopLinksEntry=bnetAtmTopLinksEntry, bnetAtmTopLinksEosTable=bnetAtmTopLinksEosTable, bnetAtmTopLinksPeerChassisSubType=bnetAtmTopLinksPeerChassisSubType, bnetAtmTopGblLstChg=bnetAtmTopGblLstChg, bnetAtmTopGblStatus=bnetAtmTopGblStatus, bnetAtmTopGblOperStatus=bnetAtmTopGblOperStatus, bnetAtmTopLinks=bnetAtmTopLinks, bnetAtmTopLinksTopoState=bnetAtmTopLinksTopoState, bnetAtmTopLinksEos=bnetAtmTopLinksEos, bnetAtmTopGblCurMibVer=bnetAtmTopGblCurMibVer, bnetAtmTopLinksTable=bnetAtmTopLinksTable, bnetAtmTopLinksPeerPortNum=bnetAtmTopLinksPeerPortNum, bnetAtmTopLinksPeerChassisType=bnetAtmTopLinksPeerChassisType, bnetAtmTopLinksPeerIpAddr=bnetAtmTopLinksPeerIpAddr, bnetAtmTopLinksEosEntry=bnetAtmTopLinksEosEntry, bnetAtmTopGbl=bnetAtmTopGbl, bnetAtmTopLinksSlotNumIndx=bnetAtmTopLinksSlotNumIndx, bnetAtmTopLinksPeerSlotNum=bnetAtmTopLinksPeerSlotNum)
# sorting algorithm # insertion sorting def insertion_sort(a): for i in range(1, len(a)): print("In the i {%s} A : {%s}" % (i, a)) key = a[i] j = i - 1 print('Before entering in the while j : {%s} , i : {%s} , key : {%s}' % (j, i, key)) while j >= 0 and a[j] > key: print("In the j {%s} A : {%s}" % (j, a)) a[j + 1] = a[j] j = j - 1 a[j + 1] = key # for j in range(i-1, 0): # print('j for loop', j) # if a[j] > a[i]: # print("In the j {%s} i {%s} A : {%s}" % (j, i, a)) # temp = a[j] # a[j] = a[j+1] # a[j+1] = temp # print("In the j {%s} i {%s} A : {%s}" % (j, i, a)) return a # A = [8.01203212, 7, 6.2, 4.123122, 3-3, 43, 432, -2, 43, 42, 224, 2432, -432.0102, -42.4, -242342, -242342, 24234232, # 4, 0, 20, 0.0001, 00.2, 00.32, -0.41, 2, 432, 2, -224223423] # A = [4, 3, 8, 7, 6, 5, 4, 3, 2] A = [5, 4, 6, 8, 1] # A = ['KA', 'CB', 'EC', 'EF', 'ALPHA', 'ZOOM', 'D', 'J'] print("UnSorted list : ", A) insertion_sort(A) print("Sorted list : ", A) j = range(len(A), 0) print(j) j = range(len(A)) print(j)
""" Global exception registry """ class APIException(Exception): """ Generic Exception wrapper """ status_code = 500 def __init__(self, message, user_details=None, internal_details=None): """ Create a new APIException :param message: General exception message :param user_details: Message to be shown to user :param internal_details: Additional details provided by the system """ self.message = message self.internal_details = internal_details if user_details is not None: self.user_details = user_details else: self.user_details = self.message super(APIException, self).__init__(self, message) def __str__(self): exception_str = super(APIException, self).__str__() dict_str = str(self.__dict__) return '{0} {1}'.format(exception_str, dict_str) def __unicode__(self): exception_str = super(APIException, self).__unicode__() dict_str = unicode(self.__dict__) return u'{0} {1}'.format(exception_str, dict_str) def to_dict(self): """ Convert this exception to a dict for serialization. """ return { 'error': self.user_details } class TokenException(APIException): """ Raised when a token fails to be decoded because it is either tampered with or expired. """ status_code = 400 def __init__(self, message, user_details=None, internal_details=None): super(TokenException, self).__init__( message, user_details=user_details, internal_details=internal_details) class ValidationException(APIException): """ Indicates an exception when validating input data. """ status_code = 400 def __init__(self, message, user_details=None, internal_details=None): super(ValidationException, self).__init__( message, user_details=user_details, internal_details=internal_details) class UnprocessableEntityException(APIException): """ Indicates an exception when valid input is semantically incorrect. """ status_code = 422 def __init__(self, message, user_details=None, internal_details=None): super(UnprocessableEntityException, self).__init__( message, user_details=user_details, internal_details=internal_details) class IntegrityException(APIException): """ Raised when database constraints are not met on updates. """ status_code = 409 def __init__(self, message, user_details=None, internal_details=None): super(IntegrityException, self).__init__( message, user_details=user_details, internal_details=internal_details) class ResourceDoesNotExistException(APIException): """ Raised when retrieving a resource and it cannot be found in the database. """ status_code = 404 def __init__(self, user_details=None, internal_details=None, *args): if len(args) > 0: message = args[0] else: message = 'Resource does not exist.' super(ResourceDoesNotExistException, self).__init__( message, user_details=user_details, internal_details=internal_details) class AuthenticationException(APIException): """ Raised when authentication fails for any reason. """ status_code = 401 def __init__(self, message, user_details=None, internal_details=None): super(AuthenticationException, self).__init__( message, user_details=user_details, internal_details=internal_details) class AuthorizationException(APIException): """ Raised when a user tries to access something without proper permissions. """ status_code = 401 def __init__(self, message, user_details=None, internal_details=None): super(AuthorizationException, self).__init__( message, user_details=user_details, internal_details=internal_details)
expected_output = { "lldp-global-status": "Disabled", "lldp-advertisement-interval": "30", "lldp-transmit-delay-interval": "0", "lldp-hold-time-interval": "120", "lldp-notification-interval": "5", "ptopo-configuration-trap-interval": "0", "ptopo-maximum-hold-time": "300", "lldp-med-global-status": "Disabled", "lldp-port-id-subtype": "locally-assigned", "lldp-port-description-type": "interface-alias (ifAlias)", }
""" Least Recently Used Cache We have briefly discussed caching as part of a practice problem while studying hash maps. The lookup operation (i.e., get()) and put() / set() is supposed to be fast for a cache memory. While doing the get() operation, if the entry is found in the cache, it is known as a cache hit. If, however, the entry is not found, it is known as a cache miss. When designing a cache, we also place an upper bound on the size of the cache. If the cache is full and we want to add a new entry to the cache, we use some criteria to remove an element. After removing an element, we use the put() operation to insert the new element. The remove operation should also be fast. For our first problem, the goal will be to design a data structure known as a Least Recently Used (LRU) cache. An LRU cache is a type of cache in which we remove the least recently used entry when the cache memory reaches its limit. For the current problem, consider both get and set operations as an use operation. Your job is to use an appropriate data structure(s) to implement the cache. In case of a cache hit, your get() operation should return the appropriate value. In case of a cache miss, your get() should return -1. While putting an element in the cache, your put() / set() operation must insert the element. If the cache is full, you must write code that removes the least recently used entry first and then insert the element. All operations must take O(1) time. For the current problem, you can consider the size of cache = 5. Here is some boiler plate code and some example test cases to get you started on this problem: """ class DoubleNode: def __init__(self, key, value): self.key = key self.value = value self.next = None self.previous = None class DoublyLinkedList: def __init__(self): self.head = None self.tail = None def preappend(self, key, value, node=None): head = self.head if node == head and node is not None and head is not None: return if node is None: node = DoubleNode(key, value) else: self.remove(node) node.next = head node.previous = None self.head = node if self.tail is None: self.tail = self.head if head is not None: head.previous = self.head return self.head def remove(self, node): if self.head is None: return if node == self.tail: node.previous.next = None self.tail = node.previous elif node == self.head: node.next.previous = None self.head = node.next else: node.previous.next = node.next node.next.previous = node.previous def to_list(self): out = [] node = self.head while node: out.append(node.value) node = node.next return out class LRU_Cache(object): def __init__(self, capacity=5): # Initialize class variables self.list = DoublyLinkedList() self.bucket = dict({}) self.num_entries = 0 self.capacity = capacity def get(self, key): # Retrieve item from provided key. Return -1 if nonexistent. try: if self.bucket[key] is not None: self.list.preappend(key, None, self.bucket[key]) return self.bucket[key].value except KeyError: return -1 def set(self, key, value): # Set the value if the key is not present in the cache. If the cache is at capacity remove the oldest item. if self.capacity == 0: return if self.list.head is None or self.num_entries < self.capacity: self.bucket[key] = self.list.preappend(key, value) self.num_entries += 1 else: del self.bucket[self.list.tail.key] self.list.remove(self.list.tail) self.bucket[key] = self.list.preappend(key, value) our_cache = LRU_Cache(5) our_cache.set(1, 1) our_cache.set(2, 2) our_cache.set(3, 3) our_cache.set(4, 4) print(our_cache.get(1)) # returns 1 print(our_cache.get(2)) # returns 2 print(our_cache.get(9)) # returns -1 because 9 is not present in the cache our_cache.set(5, 5) our_cache.set(6, 6) print(our_cache.get(3)) # returns -1 because the cache reached it's capacity and 3 was the least recently used entry #Edge cases #Capacity 0 our_cache = LRU_Cache(0) our_cache.set(1, 1) result = our_cache.get(1) # returns -1 because the cache has no capacity print(result) #Capacity 10 High Capacity our_cache = LRU_Cache(10) our_cache.set(1, 1) our_cache.set(2, 2) our_cache.set(3, 3) our_cache.set(4, 4) our_cache.set(5, 5) our_cache.set(6, 6) print(our_cache.get(1)) # returns 1 print(our_cache.get(2)) # returns 2 print(our_cache.get(3)) # returns 3 print(our_cache.get(4)) # returns 4 our_cache.set(7, 7) print(our_cache.get(5)) # returns 5 result = our_cache.get(6) # returns 6 print(result)