content
stringlengths
7
1.05M
EXCHANGE_MAX_NAME_LENGTH = 100 EXCHANGE_MAX_DESCRIPTION_LENGTH = 1000 FOLDER_FORBIDDEN_CHARS = {'/', '\\', ':', '*', '"', '<', '>', '?', '|'} FOLDER_MAX_NAME_LENGTH = 60 def validate_folder(folder): if 'name' not in folder: raise Exception('No name') for c in VALIDATE_FOLDER_FORBIDDEN_CHARS: if c in folder['name']: raise Exception('Not allowed in name: {}'.format(c)) if len(folder['name']) > VALIDATE_FOLDER_MAX_NAME_LENGTH: raise Exception('Exceed 60 characters: {}'.format(len(folder['name']))) GROUP_MAX_NAME_LENGTH = 49 GROUP_MAX_NOTE_LENGTH = 200 GROUP_MAX_ENTITY_COUNT_DELETE = 100
class OperationStaResult(object): def __init__(self): self.total = None self.wait = None self.processing = None self.success = None self.fail = None self.stop = None self.timeout = None def getTotal(self): return self.total def setTotal(self, total): self.total = total def getWait(self): return self.wait def setWait(self, wait): self.wait = wait def getProcessing(self): return self.processing def setProcessing(self, processing): self.processing = processing def getSuccess(self): return self.success def setSuccess(self, success): self.success = success def getFail(self): return self.fail def setFail(self, fail): self.fail = fail def getStop(self): return self.stop def setStop(self, stop): self.stop = stop def getTimeout(self): return self.timeout def setTimeout(self, timeout): self.timeout = timeout
CHEESES = { "brie": ( "Brie", "France", "Brie is a soft cow's-milk cheese named after Brie, the French region from which it originated.", ), "valdeon": ( "Valdeón", "Spain", " A Spanish blue cheese from León. It is wrapped in sycamore leaves before being sent to market.", ), "monterey-jack": ( "Monterey Jack", "USA", "An American white, semi-hard cheese made using cow's milk. It's noted for a mild flavor and slight sweetness.", ), "brillat-savarin": ( "Brillat-Savarin", "France", "A soft-ripened triple cream cow's milk cheese with at least 72% fat. Made in the province of Normandy.", ), }
""" This very high-level module determines/implements the specific behavior of the "standard" Necrobot running on the Crypt of the Necrobot server. Package Requirements -------------------- botbase util daily race stats user Dependencies ------------ mainchannel botbase/ cmd_admin daily/ cmd_daily racebot/ cmd_seedgen cmd_color cmd_role race/ cmd_racemake cmd_racestats user/ cmd_user pmbotchannel botbase/ cmd_admin daily/ cmd_daily racebot/ cmd_seedgen race/ cmd_racemake cmd_racestats user/ cmd_user """
def yield_test(n): for j in range(n): yield call(j) print("j=",j) #做一些其它的事情 print("do something.") print("end.") def call(j): return j*2 #使用for循环 # for i in yield_test(5): # print(i,",") def createGenerator(): mylist = range(3) for i in mylist: yield i*i mygenerator = createGenerator() print(mygenerator) for i in mygenerator: print(i)
# Copyright 2018 Google LLC # # 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. """Common configs for compatibility_lib.""" # IGNORED_DEPENDENCIES are not direct dependencies for many packages and are # not installed via pip, resulting in unresolvable high priority warnings. IGNORED_DEPENDENCIES = [ 'pip', 'setuptools', 'wheel', ] PKG_LIST = [ 'google-api-core', 'google-api-python-client', 'google-auth', 'google-cloud-bigquery', 'google-cloud-bigquery-datatransfer', 'google-cloud-bigtable', 'google-cloud-container', 'google-cloud-core', 'google-cloud-dataflow', 'google-cloud-datastore', 'google-cloud-dns', 'google-cloud-error-reporting', 'google-cloud-firestore', 'google-cloud-language', 'google-cloud-logging', 'google-cloud-monitoring', 'google-cloud-pubsub', 'google-cloud-resource-manager', 'google-cloud-runtimeconfig', 'google-cloud-spanner', 'google-cloud-speech', 'google-cloud-storage', 'google-cloud-trace', 'google-cloud-translate', 'google-cloud-videointelligence', 'google-cloud-vision', 'google-resumable-media', 'cloud-utils', 'google-apitools', 'googleapis-common-protos', 'grpc-google-iam-v1', 'grpcio', 'gsutil', 'opencensus', 'protobuf', 'protorpc', 'tensorboard', 'tensorflow', 'gcloud', ] PKG_PY_VERSION_NOT_SUPPORTED = { 2: ['tensorflow', ], 3: ['google-cloud-dataflow', ], }
""" Project: algorithms-exercises-using-python Created by robin1885@github on 17-2-20. """ def anagram_solution3(s1, s2): """ @rtype : bool @param s1: str1 @param s2: str2 @return: True or False """ pass
nome = input('Digite o nome do funcionário: ') sal = float(input('Digite o salário do funcionário: ')) if (sal > 1250): aumento = sal * 1.1 print('O funcionário {} receberá o novo salário no valor de R$ {:.2f}'.format(nome, aumento)) else: aumento = sal * 1.15 print('O funcionário {} receberá o novo salário no valor de R$ {:.2f}'.format(nome, aumento))
# Medium # https://leetcode.com/problems/next-greater-element-ii/ # TC: O(N) # SC: O(N) class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: nums = nums + nums stack = [] out = [-1 for _ in nums] for index, num in enumerate(nums): while len(stack) and num > nums[stack[-1]]: out[stack.pop()] = num stack.append(index) return out[:len(nums) // 2]
days = ["Mon", "Thu", "Wed", "Thur", "Fri"] # list(mutable sequence) print(days) days.append("Sat") days.reverse() print(days)
class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() n = len(nums) ans = [] for i in range(0, n-2): if i > 0 and nums[i] == nums[i-1]: continue j,k = i + 1, n - 1 while j < k: s = nums[i] + nums[j] + nums[k] if s > 0: k -= 1 elif s < 0: j += 1 else: ans.append([nums[i], nums[j], nums[k]]) while j<k and nums[j] == nums[j+1]: j += 1 while j<k and nums[k] == nums[k-1]: k -= 1 j, k = j+1, k-1 return ans solution = Solution() print(solution.threeSum( [-1, 0, 1, 2, -1, -4]))
"""Custom exceptions for money operations""" # pylint: disable=missing-docstring class InvalidAmountError(ValueError): def __init__(self): super().__init__("Invalid amount for currency") class CurrencyMismatchError(ValueError): def __init__(self): super().__init__("Currencies must match") class InvalidOperandError(ValueError): def __init__(self): super().__init__("Invalid operand types for operation")
# -*- coding: utf-8 -*- """ file: gromacs_ti.py Functions for setting up a Gromacs based Thermodynamic Integration (TI) calculation. """
class StreamPredictorConsumer(object): def __init__(self, name, algorithm=None, **kw): self.algorithm = algorithm self.name = name self.run_count = 0 self.runs = [] async def handle(self, payload): self.run_count += 1 try: results, err = await self.algorithm(payload) except Exception as emsg: err = str(emsg) results = {} self.runs.append({ 'run_count': self.run_count - 1, 'results': results, 'error': err })
group_template_tag_prefix = 'DRKNS_GROUP_TEMPLATE_' # BEGIN / END unit_template_tag_prefix = 'DRKNS_UNIT_TEMPLATE_' # BEGIN / END groups_tag = 'DRKNS_GROUPS' group_units_tag = 'DRKNS_GROUP_UNITS' group_name_tag = 'DRKNS_GROUP_NAME' unit_name_tag = 'DRKNS_UNIT_NAME' dependency_groups_names_tag = 'DRKNS_DEPENDENCY_GROUPS_NAMES' all_group_names_tag = 'DRKNS_ALL_GROUPS_NAMES'
#!/usr/bin/env python3 def main(): for i in range(1,11): for j in range(1,11): if(j==10): print(i*j) else: print(i*j, end=" ") if __name__ == "__main__": main()
def require(*types): ''' Return a decorator function that requires specified types. types -- tuple each element of which is a type or class or a tuple of several types or classes. Example to require a string then a numeric argument @require(str, (int, long, float)) will do the trick ''' def deco(func): ''' Decorator function to be returned from require(). Returns a function wrapper that validates argument types. ''' def wrapper (*args): ''' Function wrapper that checks argument types. ''' assert len(args) == len(types), 'Wrong number of arguments.' for a, t in zip(args, types): if type(t) == type(()): # any of these types are ok assert sum(isinstance(a, tp) for tp in t) > 0, '''\ %s is not a valid type. Valid types: %s ''' % (a, '\n'.join(str(x) for x in t)) assert isinstance(a, t), '%s is not a %s type' % (a, t) return func(*args) return wrapper return deco @require(int) def inter(int_val): print('int_val is ', int_val) @require(float) def floater(f_val): print('f_val is ', f_val) @require(str, (int, int, float)) def nameAge1(name, age): print('%s is %s years old' % (name, age)) # another way to do the same thing number = (int, float, int) @require(str, number) def nameAge2(name, age): print('%s is %s years old' % (name, age)) nameAge1('Emily', 8) # str, int ok nameAge1('Elizabeth', 4.5) # str, float ok nameAge2('Romita', 9) # str, long ok nameAge2('Emily', 'eight') # raises an exception!
def try_if(l): ret = 0 for x in l: if x == 1: ret += 2 elif x == 0: ret += 4 else: ret -= 2 return ret try_if([0, 1, 0, 1, 2, 3])
class Solution(object): def XXX(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ i, j, k = 0, len(nums) - 1, 0 while k < len(nums): if nums[k] == 0 and k > i: nums[k], nums[i] = nums[i], nums[k] i += 1 elif nums[k] == 2 and k < j: nums[k], nums[j] = nums[j], nums[k] j -= 1 else: k += 1
class World: def __init__(self): pass def get_state(self): pass def execute_action(self,a): pass class GameTree: class GameNode: def __init__(self, state, action, par): self.state = state self.action = action self.visited = 0.0 self.par = par # key = the goal aka desired result, val = the times that goal was reached through this node self.goal_outcomes = dict() # key = state of the system in which this node can be accessed, val = list<GameNode> self.children = dict() def probability(self): """The likelihood of ending up in this state""" return self.visited / self.par.visited def probability_for(self, goal): """The likelihood that the given GameNode will lead the 'player' to their final goal""" return self.goal_outcomes.get(goal,0.0) / self.visited def get_utility(self, goal, policy_params): """Returns the utility that the 'player' will receive if they pick this action""" pass def apply_action(self, world): self.visited += 1.0 world.execute_action(self.action) def update(self, goal, win=0): """ Updates the number of times that this node led to the desired goal :param goal: the goal that was supposed to be reached :param win: 1 if goal was reached 0 otherwise :return: """ self.goal_outcomes[goal] = self.goal_outcomes.get(goal) + win self.par.update(goal, win) def prune(self): pass def get_next_move(self, state, goal, policy_params): """ Returns the best action for a certain goal given the current state of the world :param state: the current state of the world :param goal: the desired final outcome :param policy_params: additional data regarding the choice of a next action :return: GameNode with highest utility """ if goal in self.children: return self.children.get(goal)[0] best = None max_u = 0 nodes = self.children.get(state) for n in nodes: u = n.get_utility(goal, policy_params) if u > max_u: max_u = u best = n return best def __init__(self, policy): self.root = None self.cursor = None self.policy = policy def get_next_action(self, state, goal): if not self.cursor: self.cursor = self.root new_c = self.cursor.get_next_move(state, goal,self.policy) self.cursor = new_c return new_c class AIUser: def __init__(self, world): """ Creates a new AI user :param world: World instance wrapper for the environment """ self.world = world self.game_tree = GameTree(None) def learn(self): pass def execute(self, goal): state = self.world.get_state() while state != goal: a = self.game_tree.get_next_action(state, goal) a.apply_action(self.world) state = self.world.get_state()
namespace = '/map' routes = { 'getAllObjectDest': '/', }
# 최고의 집합 def solution(n, s): if s // n < 1: return [-1] number = s // n left = s % n arr = [number] * n for i in range(n - 1, n - 1 - left, -1): arr[i] += 1 return arr if __name__ == "__main__": n = 2 s = 1 print(solution(n, s))
#Creacion de clase padre class Vehiculo: def __init__(self, color, ruedas): self.color = color self.ruedas = ruedas def __str__(self): return "Color : "+self.color+" ruedas: "+str(self.ruedas) #creacion de una clase hija/o class Coche(Vehiculo): def __init__(self, color, ruedas, velocidad): super().__init__(color, ruedas) self.velocidad = velocidad def __str__(self): return super().__str__() + " velocidad : "+str(self.velocidad)+" km/hr" #Creacion de clase hija/o class Bici(Vehiculo): def __init__(self, color, ruedas, tipo): super().__init__(color, ruedas) self.tipo = tipo def __str__(self): return super().__str__() + " tipo : "+str(self.tipo) #creacion de un objeto carro = Vehiculo("Rojo ",4 ) #enviar impresion print(carro) #Creacion de un objeto coche = Coche("Negro ", 4 , 180) #Enviamos a impresion el nuevo objeto print(coche) #Creacion de un objeto bici = Bici("Negro ", 2 , "Montaña") #Enviamos a impresion el nuevo objeto print(bici)
""" Exercise 1 Many of the built-in functions use variable-length argument tuples. For example, max and min can take any number of arguments: >>> max(1,2,3) 3 But sum does not. >>> sum(1,2,3) TypeError: sum expected at most 2 arguments, got 3 Write a function called sumall that takes any number of arguments and returns their sum. """ def sumall(*args): return sum(args) print(sumall(5, 9, 2)) print(sumall(15, 23, 343, 43)) print(sumall(234, 5, 9, 8, 4, 3, 0, 23))
# Validar uma string def valida_str(texto, min, max): tam = len(texto) if tam < min or tam > max: return False else: return True # Programa Principal texto = input('Digite um string (3-15 caracteres): ') while valida_str(texto, 3, 15): texto = input('Digite uma string (3-15 caracteres): ') print(texto)
# # PySNMP MIB module HH3C-STACK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-STACK-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:29:46 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint") entPhysicalIndex, = mibBuilder.importSymbols("ENTITY-MIB", "entPhysicalIndex") hh3cCommon, = mibBuilder.importSymbols("HH3C-OID-MIB", "hh3cCommon") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Counter32, ModuleIdentity, Bits, Gauge32, TimeTicks, IpAddress, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, Unsigned32, MibIdentifier, Integer32, NotificationType, iso = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "ModuleIdentity", "Bits", "Gauge32", "TimeTicks", "IpAddress", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "Unsigned32", "MibIdentifier", "Integer32", "NotificationType", "iso") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") hh3cStack = ModuleIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 91)) hh3cStack.setRevisions(('2008-04-30 16:50',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: hh3cStack.setRevisionsDescriptions(('The initial revision of this MIB module.',)) if mibBuilder.loadTexts: hh3cStack.setLastUpdated('200804301650Z') if mibBuilder.loadTexts: hh3cStack.setOrganization('Hangzhou H3C Technologies Co., Ltd.') if mibBuilder.loadTexts: hh3cStack.setContactInfo('Platform Team H3C Technologies Co., Ltd. Hai-Dian District Beijing P.R. China Http://www.h3c.com Zip:100085') if mibBuilder.loadTexts: hh3cStack.setDescription('This MIB is used to manage STM (Stack Topology Management) information for IRF (Intelligent Resilient Framework) device. This MIB is applicable to products which support IRF. Some objects in this MIB may be used only for some specific products, so users should refer to the related documents to acquire more detailed information.') hh3cStackGlobalConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1)) hh3cStackMaxMember = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackMaxMember.setStatus('current') if mibBuilder.loadTexts: hh3cStackMaxMember.setDescription('The maximum number of members in a stack.') hh3cStackMemberNum = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackMemberNum.setStatus('current') if mibBuilder.loadTexts: hh3cStackMemberNum.setDescription('The number of members currently in a stack.') hh3cStackMaxConfigPriority = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackMaxConfigPriority.setStatus('current') if mibBuilder.loadTexts: hh3cStackMaxConfigPriority.setDescription('The highest priority that can be configured for a member in a stack.') hh3cStackAutoUpdate = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cStackAutoUpdate.setStatus('current') if mibBuilder.loadTexts: hh3cStackAutoUpdate.setDescription('The function for automatically updating the image from master to slave. When a new device tries to join a stack, the image version is checked. When this function is enabled, if the image version of the new device is different from that of the master, the image of the new device will be updated to be consistent with that of the master. When this function is disabled, the new device can not join the stack if the image version of the new device is different from that of the master. disabled: disable auto update function enabled: enable auto update function') hh3cStackMacPersistence = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("notPersist", 1), ("persistForSixMin", 2), ("persistForever", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cStackMacPersistence.setStatus('current') if mibBuilder.loadTexts: hh3cStackMacPersistence.setDescription('The mode of bridge MAC address persistence. When a stack starts, the bridge MAC address of master board will be used as that of the stack. If the master board leaves the stack, the bridge MAC address of the stack will change based on the mode of bridge MAC address persistence. notPersist: The bridge MAC address of the new master board will be used as that of the stack immediately. persistForSixMin: The bridge MAC address will be reserved for six minutes. In this period, if the master board which has left the stack rejoins the stack, the bridge MAC address of the stack will not change. Otherwise, the bridge MAC address of the new master board will be used as that of the stack. persistForever: Whether the master leaves or not, the bridge MAC address of the stack will never change.') hh3cStackLinkDelayInterval = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(200, 2000), ))).setUnits('millisecond').setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cStackLinkDelayInterval.setStatus('current') if mibBuilder.loadTexts: hh3cStackLinkDelayInterval.setDescription('The delay time for a device in a stack to report the change of stack port link status. If the delay time is configured, a device in a stack will not report the change immediately when the stack port link status changes to down. During the delay period, if the stack port link status is resumed, the device will ignore the current change of the stack port link status. If the stack port link status is not resumed after the delay time, the device will report the change. 0 means no delay, namely, the device will report the change as soon as the stack port link status changes to down. 0: no delay 200-2000(ms): delay time') hh3cStackTopology = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("chainConn", 1), ("ringConn", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackTopology.setStatus('current') if mibBuilder.loadTexts: hh3cStackTopology.setDescription('The topology of the stack. chainConn: chain connection ringConn: ring connection') hh3cStackDeviceConfigTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2), ) if mibBuilder.loadTexts: hh3cStackDeviceConfigTable.setStatus('current') if mibBuilder.loadTexts: hh3cStackDeviceConfigTable.setDescription('This table contains objects to manage device information in a stack.') hh3cStackDeviceConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex")) if mibBuilder.loadTexts: hh3cStackDeviceConfigEntry.setStatus('current') if mibBuilder.loadTexts: hh3cStackDeviceConfigEntry.setDescription('This table contains objects to manage device information in a stack.') hh3cStackMemberID = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackMemberID.setStatus('current') if mibBuilder.loadTexts: hh3cStackMemberID.setDescription('The member ID of the device in a stack.') hh3cStackConfigMemberID = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cStackConfigMemberID.setStatus('current') if mibBuilder.loadTexts: hh3cStackConfigMemberID.setDescription('The configured member ID of the device. The valid value ranges from 1 to the value of hh3cStackMaxMember. After the member ID is configured for a device, if this ID is not the same with that of another device, the ID will be used as the member ID of the device when the device reboots. If a same ID exists, the member ID of the device will be set as another exclusive ID automatically.') hh3cStackPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cStackPriority.setStatus('current') if mibBuilder.loadTexts: hh3cStackPriority.setDescription('The priority of a device in a stack. The valid value ranges from 1 to the value of hh3cStackMaxConfigPriority.') hh3cStackPortNum = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackPortNum.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortNum.setDescription('The number of stack ports which is enabled in a device.') hh3cStackPortMaxNum = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackPortMaxNum.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortMaxNum.setDescription('The maximum number of stack ports in a device.') hh3cStackBoardConfigTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 91, 3), ) if mibBuilder.loadTexts: hh3cStackBoardConfigTable.setStatus('current') if mibBuilder.loadTexts: hh3cStackBoardConfigTable.setDescription('This table contains objects to manage board information of the device in a stack.') hh3cStackBoardConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 91, 3, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex")) if mibBuilder.loadTexts: hh3cStackBoardConfigEntry.setStatus('current') if mibBuilder.loadTexts: hh3cStackBoardConfigEntry.setDescription('This table contains objects to manage board information of the device in a stack.') hh3cStackBoardRole = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("slave", 1), ("master", 2), ("loading", 3), ("other", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackBoardRole.setStatus('current') if mibBuilder.loadTexts: hh3cStackBoardRole.setDescription('The role of the board in a stack. slave: slave board master: master board loading: slave board whose image version is different from that of the master board. other: other') hh3cStackBoardBelongtoMember = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 3, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackBoardBelongtoMember.setStatus('current') if mibBuilder.loadTexts: hh3cStackBoardBelongtoMember.setDescription('The member ID of the device where the current board resides in a stack.') hh3cStackPortInfoTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 91, 4), ) if mibBuilder.loadTexts: hh3cStackPortInfoTable.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortInfoTable.setDescription('This table contains objects to manage stack port information of a device in a stack.') hh3cStackPortInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 91, 4, 1), ).setIndexNames((0, "HH3C-STACK-MIB", "hh3cStackMemberID"), (0, "HH3C-STACK-MIB", "hh3cStackPortIndex")) if mibBuilder.loadTexts: hh3cStackPortInfoEntry.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortInfoEntry.setDescription('This table contains objects to manage stack port information of a device in a stack.') hh3cStackPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 4, 1, 1), Integer32()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hh3cStackPortIndex.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortIndex.setDescription('The index of a stack port of the device in a stack.') hh3cStackPortEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 4, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackPortEnable.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortEnable.setDescription("The status of the stack port of the device in a stack. If no physical port is added to the stack port, its status is 'disabled'; otherwise, its status is 'enabled'. disabled: The stack port is disabled. enabled: The stack port is enabled.") hh3cStackPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 4, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("up", 1), ("down", 2), ("silent", 3), ("disabled", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackPortStatus.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortStatus.setDescription('The link status of the stack port of the device in a stack. up: The link status of a stack port with reasonable physical connection is up. down: The link status of a stack port without physical connection is down. silent: The link status of a stack port which can not be used normally is silent. disabled: The link status of a stack port in disabled status is disabled.') hh3cStackNeighbor = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 4, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackNeighbor.setStatus('current') if mibBuilder.loadTexts: hh3cStackNeighbor.setDescription("The member ID of the stack port's neighbor in a stack. 0 means no neighbor exists.") hh3cStackPhyPortInfoTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 91, 5), ) if mibBuilder.loadTexts: hh3cStackPhyPortInfoTable.setStatus('current') if mibBuilder.loadTexts: hh3cStackPhyPortInfoTable.setDescription('This table contains objects to manage the information for physical ports which can be used for physical connection of stack port in a stack.') hh3cStackPhyPortInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 91, 5, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex")) if mibBuilder.loadTexts: hh3cStackPhyPortInfoEntry.setStatus('current') if mibBuilder.loadTexts: hh3cStackPhyPortInfoEntry.setDescription('This table contains objects to manage the information for physical ports which can be used for physical connection of stack port in a stack.') hh3cStackBelongtoPort = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 5, 1, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cStackBelongtoPort.setStatus('current') if mibBuilder.loadTexts: hh3cStackBelongtoPort.setDescription('The index of the stack port to which the physical port is added. 0 means the physical port is not added to any stack port. The value will be valid after the device in the stack reboots.') hh3cStackTrap = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 91, 6)) hh3cStackTrapOjbects = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 91, 6, 0)) hh3cStackPortLinkStatusChange = NotificationType((1, 3, 6, 1, 4, 1, 25506, 2, 91, 6, 0, 1)).setObjects(("HH3C-STACK-MIB", "hh3cStackMemberID"), ("HH3C-STACK-MIB", "hh3cStackPortIndex"), ("HH3C-STACK-MIB", "hh3cStackPortStatus")) if mibBuilder.loadTexts: hh3cStackPortLinkStatusChange.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortLinkStatusChange.setDescription('The hh3cStackPortLinkStatusChange trap indicates that the link status of the stack port has changed.') hh3cStackTopologyChange = NotificationType((1, 3, 6, 1, 4, 1, 25506, 2, 91, 6, 0, 2)).setObjects(("HH3C-STACK-MIB", "hh3cStackTopology")) if mibBuilder.loadTexts: hh3cStackTopologyChange.setStatus('current') if mibBuilder.loadTexts: hh3cStackTopologyChange.setDescription('The hh3cStackTopologyChange trap indicates that the topology type of the stack has changed.') mibBuilder.exportSymbols("HH3C-STACK-MIB", hh3cStackTopology=hh3cStackTopology, hh3cStackConfigMemberID=hh3cStackConfigMemberID, hh3cStackBelongtoPort=hh3cStackBelongtoPort, hh3cStackTopologyChange=hh3cStackTopologyChange, hh3cStackMacPersistence=hh3cStackMacPersistence, hh3cStackGlobalConfig=hh3cStackGlobalConfig, hh3cStackPortIndex=hh3cStackPortIndex, hh3cStackPriority=hh3cStackPriority, hh3cStackPhyPortInfoTable=hh3cStackPhyPortInfoTable, hh3cStackTrap=hh3cStackTrap, hh3cStackPortMaxNum=hh3cStackPortMaxNum, hh3cStackLinkDelayInterval=hh3cStackLinkDelayInterval, hh3cStackMemberNum=hh3cStackMemberNum, hh3cStackPortEnable=hh3cStackPortEnable, hh3cStackMaxMember=hh3cStackMaxMember, hh3cStackDeviceConfigEntry=hh3cStackDeviceConfigEntry, hh3cStackMemberID=hh3cStackMemberID, hh3cStackBoardConfigEntry=hh3cStackBoardConfigEntry, hh3cStackPhyPortInfoEntry=hh3cStackPhyPortInfoEntry, hh3cStackPortStatus=hh3cStackPortStatus, PYSNMP_MODULE_ID=hh3cStack, hh3cStackBoardConfigTable=hh3cStackBoardConfigTable, hh3cStackPortNum=hh3cStackPortNum, hh3cStackNeighbor=hh3cStackNeighbor, hh3cStackBoardBelongtoMember=hh3cStackBoardBelongtoMember, hh3cStack=hh3cStack, hh3cStackBoardRole=hh3cStackBoardRole, hh3cStackDeviceConfigTable=hh3cStackDeviceConfigTable, hh3cStackPortInfoEntry=hh3cStackPortInfoEntry, hh3cStackAutoUpdate=hh3cStackAutoUpdate, hh3cStackTrapOjbects=hh3cStackTrapOjbects, hh3cStackPortLinkStatusChange=hh3cStackPortLinkStatusChange, hh3cStackPortInfoTable=hh3cStackPortInfoTable, hh3cStackMaxConfigPriority=hh3cStackMaxConfigPriority)
l1=[1,2,3,4,5,6,7,8,9,10] l2=list(map(lambda n:n*n,l1)) print('l2:',l2) l3=list((map(lambda n,m:n*m,l1,l2)))#map function can take more than one sequence argument print('l3:',l3) #if the length of the sequence is not equal then function will perform till same length l3.pop() print('popped l3:',l3) l4=list(map(lambda n,m,o:n+m+o,l1,l2,l3)) print('l4:',l4)
{ 'targets': [ { 'target_name': 'gpiobcm2835nodejs', 'sources': [ 'src/gpiobcm2835nodejs.cc' ], "cflags" : [ "-lrt -lbcm2835" ], 'conditions': [ ['OS=="linux"', { 'cflags!': [ '-lrt -lbcm2835', ], }], ], 'include_dirs': [ 'src/gpio_functions', ], 'libraries': [ '-lbcm2835' ] } ] }
# -*- coding: utf-8 -*- # @Author: 何睿 # @Create Date: 2018-11-12 14:46:42 # @Last Modified by: 何睿 # @Last Modified time: 2018-11-12 14:46:42 class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def middleNode(self, head): """ :type head: ListNode :rtype: ListNode """ if head == None: return None if head.next == None: return head slow, fast = head, head while True: if fast.next == None: return slow if fast.next.next == None: return slow.next slow = slow.next fast = fast.next.next return True
class SpekulatioError(Exception): pass class FrontmatterError(SpekulatioError): pass
class Sql: make_itemdb = ''' CREATE TABLE IF NOT EXISTS ITEMDB ( ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, PRICE REAL, REGDATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ''' insert_itemdb = ''' INSERT INTO ITEMDB (NAME, PRICE) VALUES (?,?) ''' update_itemdb = ''' UPDATE ITEMDB SET NAME = ?, PRICE = ?, WHERE ID = ?''' delete_itemdb = ''' DELET FROM ITEMDB WHERE ID = ? ''' select_itemdb = ''' SELECT * FROM ITEMDB WHERE ID = ? ''' selectall_itemdb = ''' SELECT * FROM ITEMDB '''
def getbounds(img): return tuple([min((si[i] for si in img)) for i in range(2)]), \ tuple([max((si[i] for si in img)) for i in range(2)]) def enhance(img, setval, algo): bounds = getbounds(img) offsets = ((1, 1), (0, 1), (-1, 1), (1, 0), (0, 0), (-1, 0), (1, -1), (0, -1), (-1, -1)) overhang = 2 n_imgset = set() for x in range(bounds[0][0] - overhang, bounds[1][0] + overhang): for y in range(bounds[0][1] - overhang, bounds[1][1] + overhang): idx = sum([(((x + ox, y + oy) in img) == setval) * 2 ** p for p, (ox, oy) in enumerate(offsets)]) if (algo[idx] != setval) == algo[0]: n_imgset.add((x, y)) if algo[0]: setval = not setval return n_imgset, setval def main(input_file='input.txt', verbose=False): algo_raw, img_raw = open(input_file).read().split('\n\n') algo, img_raw = tuple(c == '#' for c in algo_raw), img_raw.split('\n') img = set([(x, y) for x in range(len(img_raw[0])) for y in range(len(img_raw)) if img_raw[y][x] == '#']) setval = True for step in range(50): img, setval = enhance(img, setval, algo) if step == 1: p1 = len(img) p2 = len(img) if verbose: print('Part 1: {0[0]}\nPart 2: {0[1]}'.format([p1, p2])) return p1, p2 if __name__ == "__main__": main(verbose=True)
class TrieNode: def __init__(self): self.children = collections.defaultdict(TrieNode) self.is_word = False class Solution: def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: root = TrieNode() for word in words: cur = root for ch in word: cur = cur.children[ch] cur.is_word = True ans = [] def dfs(cur, path, i, j): if cur.is_word: ans.append(path) cur.is_word = False if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] == '#' or cur.children.get(board[i][j]) == None: return ch = board[i][j] board[i][j] = '#' new_cur = cur.children[ch] dfs(new_cur, path + ch, i - 1, j) dfs(new_cur, path + ch, i + 1, j) dfs(new_cur, path + ch, i, j - 1) dfs(new_cur, path + ch, i, j + 1) board[i][j] = ch for i in range(len(board)): for j in range(len(board[0])): dfs(root, "", i, j) return ans
def rotate(matrix): #code here for i in range(len(matrix)): listt = list(reversed(matrix[i])) for j in range(len(matrix[i])): matrix[i][j] = listt[j] # print(matrix) for i in range(len(matrix)): for j in range(i, len(matrix[i])): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] #{ # Driver Code Starts #Initial Template for Python 3 if __name__ == '__main__': t = int(input()) for _ in range(t): N = int(input()) arr = [int(x) for x in input().split()] matrix = [] for i in range(0, N*N, N): matrix.append(arr[i:i+N]) rotate(matrix) for i in range(N): for j in range(N): print(matrix[i][j], end=' ') print() # } Driver Code Ends
# Like list we can have set and dict comprehensions. # Set comprehensions. # The below set is not ordered. square_set = {num * num for num in range(11)} print(square_set) # Dict Comprehension dict_square = {num: num * num for num in range(11)} print(dict_square) # Use f"string to create a set and dict f_string_square_set = {f"The square of {num} is {num * num}" for num in range(5)} for x in f_string_square_set: print(x) f_string_square_dict = {num: f"the square is {num*num}" for num in range(5)} for k, v in f_string_square_dict.items(): print(k, ":", v)
## -*- encoding: utf-8 -*- """ This file (./sol/linalg_doctest.sage) was *autogenerated* from ./sol/linalg.tex, with sagetex.sty version 2011/05/27 v2.3.1. It contains the contents of all the sageexample environments from this file. You should be able to doctest this file with: sage -t ./sol/linalg_doctest.sage It is always safe to delete this file; it is not used in typesetting your document. Sage example in ./sol/linalg.tex, line 89:: sage: A = matrix(GF(7),[[0,0,3,0,0],[1,0,6,0,0],[0,1,5,0,0], ....: [0,0,0,0,5],[0,0,0,1,5]]) sage: P = A.minpoly(); P x^5 + 4*x^4 + 3*x^2 + 3*x + 1 sage: P.factor() (x^2 + 2*x + 2) * (x^3 + 2*x^2 + x + 4) Sage example in ./sol/linalg.tex, line 100:: sage: e1 = identity_matrix(GF(7),5)[0] sage: e4 = identity_matrix(GF(7),5)[3] sage: A.transpose().maxspin(e1) [(1, 0, 0, 0, 0), (0, 1, 0, 0, 0), (0, 0, 1, 0, 0)] sage: A.transpose().maxspin(e4) [(0, 0, 0, 1, 0), (0, 0, 0, 0, 1)] sage: A.transpose().maxspin(e1 + e4) [(1, 0, 0, 1, 0), (0, 1, 0, 0, 1), (0, 0, 1, 5, 5), (3, 6, 5, 4, 2), (1, 5, 3, 3, 0)] Sage example in ./sol/linalg.tex, line 168:: sage: def Similar(A, B): ....: F1, U1 = A.frobenius(2) ....: F2, U2 = B.frobenius(2) ....: if F1 == F2: ....: return True, ~U2*U1 ....: else: ....: return False, F1 - F2 sage: B = matrix(ZZ, [[0,1,4,0,4],[4,-2,0,-4,-2],[0,0,0,2,1], ....: [-4,2,2,0,-1],[-4,-2,1,2,0]]) sage: U = matrix(ZZ, [[3,3,-9,-14,40],[-1,-2,4,2,1],[2,4,-7,-1,-13], ....: [-1,0,1,4,-15],[-4,-13,26,8,30]]) sage: A = (U^-1 * B * U).change_ring(ZZ) sage: ok, V = Similar(A, B); ok True sage: V [ 1 2824643/1601680 -6818729/1601680 -43439399/11211760 73108601/11211760] [ 0 342591/320336 -695773/320336 -2360063/11211760 -10291875/2242352] [ 0 -367393/640672 673091/640672 -888723/4484704 15889341/4484704] [ 0 661457/3203360 -565971/3203360 13485411/22423520 -69159661/22423520] [ 0 -4846439/3203360 7915157/3203360 -32420037/22423520 285914347/22423520] sage: ok, V = Similar(2*A, B); ok False """
#ANSI Foreground colors black = u"\u001b[30m" red = u"\u001b[31m" green = u"\u001b[32m" yellow = u"\u001b[33m" blue = u"\u001b[34m" magneta = u"\u001b[35m" magenta = magneta cyan = u"\u001b[36m" white = u"\u001b[37m" #ANSI Background colors blackB = u"\u001b[40m" redB = u"\u001b[41m" greenB = u"\u001b[42m" yellowB = u"\u001b[43m" blueB = u"\u001b[44m" magnetaB = u"\u001b[45m" magentaB = magnetaB cyanB = u"\u001b[46m" whiteB = u"\u001b[47m" #ANSI reset "color" reset = u"\u001b[0m" #Unused utility function def printColored(colorA, msg): print(colorA + msg + reset) def ansi(num, end = "m"): return u"\u001b[" + str(num) + str(end) if(__name__ == "__main__"): for j in range(30, 38): print(ansi(j) + str(j) + reset)
LAB_STYLE = """ body { --jp-layout-color0: transparent; --jp-layout-color1: transparent; --jp-layout-color2: transparent; --jp-layout-color3: transparent; --jp-cell-editor-background: transparent; --jp-border-width: 0; --jp-border-color0: transparent; --jp-border-color1: transparent; --jp-border-color2: transparent; --nbcqpdf-height: 1080px; } body, body .jp-ApplicationShell { width: 1920px; height: var(--nbcqpdf-height); min-height: var(--nbcqpdf-height); max-height: var(--nbcqpdf-height); } body .jp-InputArea-editor { border: 0; padding-left: 2em; } body .jp-LabShell.jp-mod-devMode { border: 0 !important; } body .jp-InputPrompt, body .jp-OutputPrompt { display: none; min-width: 0; max-width: 0; } body #jp-main-dock-panel { padding: 0; } body .jp-SideBar.p-TabBar, body #jp-top-panel, body .jp-Toolbar, body .p-DockPanel-tabBar, body .jp-Collapser { display: none; min-height: 0; max-height: 0; min-width: 0; max-width: 0; } """ FORCE_DEV = """ var cfg = document.querySelector("#jupyter-config-data"); if(cfg) { cfg.textContent = cfg.textContent.replace( `"devMode": "False"`, `"devMode": "True"` ) } """ SINGLE_DOCUMENT = """ ;(function(){ var cmd = 'application:set-mode'; var interval = setInterval(function(){ var lab = window.lab if( !lab || !lab.commands || lab.commands.listCommands().indexOf(cmd) == -1 ) { return; } clearInterval(interval); lab.shell.removeClass('jp-mod-devMode'); lab.commands.execute(cmd, {mode: 'single-document'}); if(document.querySelector('body[data-left-sidebar-widget]')) { lab.commands.execute('application:toggle-left-area'); } }, 1000); })(); """ MEASURE = """ var bb = document.querySelector(".jp-Cell:last-child").getBoundingClientRect(); var style = document.createElement('style'); style.textContent = `body { --nbcqpdf-height: ${bb.bottom + 500}px; }`; document.body.appendChild(style); [bb.bottom, bb.right] """ RUN_ALL = """ ;(function(){ function evaluateXPath(aNode, aExpr) { var xpe = new XPathEvaluator(); var nsResolver = xpe.createNSResolver(aNode.ownerDocument == null ? aNode.documentElement : aNode.ownerDocument.documentElement); var result = xpe.evaluate(aExpr, aNode, nsResolver, 0, null); var found = []; var res; while (res = result.iterateNext()) found.push(res); return found; } var cmd = 'notebook:run-all-cells'; var interval = setInterval(function(){ var lab = window.lab if( !lab || !lab.commands || lab.commands.listCommands().indexOf(cmd) == -1 ) { return; } if(!document.querySelector(`*[title="Kernel Idle"]`)){ return; } clearInterval(interval); lab.commands.execute(cmd) .then(function(){ var busyInterval = setInterval(function(){ if(evaluateXPath(document, '//*[text() = "[*]:"]').length) { return; } %s lab.shell.mode = 'multiple-document'; lab.shell.mode = 'single-document'; clearInterval(busyInterval); __QT__.measure(); }, 1000); }) }, 1000); })(); """ % MEASURE APPLY_STYLE = f""" var style = document.createElement("style"); style.textContent = `{LAB_STYLE}`; document.body.appendChild(style); {SINGLE_DOCUMENT} {RUN_ALL} """ BRIDGE = """ new QWebChannel(qt.webChannelTransport, function(channel) { window.__QT__ = { print: function(text){ channel.objects.page.print(text || "Hello World!"); }, measure: function(){ channel.objects.page._measure(); } } __QT__.print(); }); """
#!/usr/bin/env python """ Find the greatest product of five consecutive digits in the 1000-digit number """ num = '\ 73167176531330624919225119674426574742355349194934\ 96983520312774506326239578318016984801869478851843\ 85861560789112949495459501737958331952853208805511\ 12540698747158523863050715693290963295227443043557\ 66896648950445244523161731856403098711121722383113\ 62229893423380308135336276614282806444486645238749\ 30358907296290491560440772390713810515859307960866\ 70172427121883998797908792274921901699720888093776\ 65727333001053367881220235421809751254540594752243\ 52584907711670556013604839586446706324415722155397\ 53697817977846174064955149290862569321978468622482\ 83972241375657056057490261407972968652414535100474\ 82166370484403199890008895243450658541227588666881\ 16427171479924442928230863465674813919123162824586\ 17866458359124566529476545682848912883142607690042\ 24219022671055626321111109370544217506941658960408\ 07198403850962455444362981230987879927244284909188\ 84580156166097919133875499200524063689912560717606\ 05886116467109405077541002256983155200055935729725\ 71636269561882670428252483600823257530420752963450' biggest = 0 i = 0 while i < len(num) - 12: one = int(num[i]) two = int(num[i + 1]) thr = int(num[i + 2]) fou = int(num[i + 3]) fiv = int(num[i + 4]) six = int(num[i + 5]) sev = int(num[i + 6]) eig = int(num[i + 7]) nin = int(num[i + 8]) ten = int(num[i + 9]) ele = int(num[i + 10]) twe = int(num[i + 11]) thi = int(num[i + 12]) product = one * two * thr * fou * fiv * six * sev * eig * nin * ten * ele * twe * thi if product > biggest: biggest = product i += 1 def test_function(): assert biggest == 23514624000
athlete_1 = int(input()) athlete_2 = int(input()) athlete_3 = int(input()) podium = [] if (athlete_1 < athlete_2 and athlete_1 < athlete_3): podium.append(1) if(athlete_2 < athlete_3): podium.append(2) podium.append(3) else: podium.append(3) podium.append(2) elif (athlete_2 < athlete_1 and athlete_2 < athlete_3): podium.append(2) if(athlete_1 < athlete_3): podium.append(1) podium.append(3) else: podium.append(3) podium.append(1) elif (athlete_3 < athlete_1 and athlete_3 < athlete_2): podium.append(3) if(athlete_1 < athlete_2): podium.append(1) podium.append(2) else: podium.append(2) podium.append(1) print(podium[0]) print(podium[1]) print(podium[3])
Number = int(input("\nPlease Enter the Range Number: ")) First_Value = 0 Second_Value = 1 for Num in range(0, Number): if (Num <= 1): Next = Num else: Next = First_Value + Second_Value First_Value = Second_Value Second_Value = Next print(Next)
# -*- coding: utf-8 -*- """ aomie ~~~~~ aomie is a simple Python package to ease the handling of Iberian electricity market data published by the market operator OMIE. :copyright: © 2019 by Guillermo Lozano Branger. :license: MIT, see LICENSE for more details. """ __version__ = '0.0.0'
def Spell_0_10(n): refTuple = ("zero","one","two","three","four","five", "six","seven","eight","nine","ten") return refTuple[n] print(1, " is spelt as ", Spell_0_10(1)) for i in range(11): print("{} is spelt as {}".format(i,Spell_0_10(i))) for i in range (-9,0,1): print("{} is spelt as {}".format(i, Spell_0_10(i)))
"""Registry for behavior configurables.""" _BEHAVIOR_LIST = [] def behaviors(): """Yields the currently registered behaviors in the order in which they were defined.""" for name, cls, brief, level in _BEHAVIOR_LIST: yield name, cls, brief, level def behavior(name, brief, level=0): """Decorator generator which registers a behavior configurable.""" def decorator(cls): cls.__str__ = lambda _: name _BEHAVIOR_LIST.append((name, cls, brief, level)) return cls return decorator def behavior_doc(doc, level=0): """Appends a documentation-only item to the behavior list in the generated documentation.""" _BEHAVIOR_LIST.append((None, None, doc, level))
"""excpetions.py""" class GTMManagerException(Exception): """GTMManagerException""" pass class AuthError(GTMManagerException): pass class VariableNotFound(GTMManagerException): """VariableNotFound""" def __init__(self, variable_name, parent): super(VariableNotFound, self).__init__() self.variable_name = variable_name self.parent = parent def __str__(self): return "Variable {!r} not found in parent {!r}".format( self.variable_name, self.parent ) class TagNotFound(GTMManagerException): """TagNotFound""" def __init__(self, tag_name, parent): super(TagNotFound, self).__init__() self.tag_name = tag_name self.parent = parent def __str__(self): return "Tag {!r} not found in parent {!r}".format(self.tag_name, self.parent) class TriggerNotFound(GTMManagerException): """TriggerNotFound""" def __init__(self, trigger_name, parent): super(TriggerNotFound, self).__init__() self.trigger_name = trigger_name self.parent = parent def __str__(self): return "Trigger {!r} not found in parent {!r}".format( self.trigger_name, self.parent ) class RateLimitExceeded(GTMManagerException): """RateLimitExceeded""" pass
#Plugin to handle dialogues for men and women #Written by Owain for Runefate #31/01/18 #I want to give every spawned NPC a use, and not do what most servers have with useless non functioning NPCs. #Even small things such as NPC dialogues can help make Runefate more rounded and enjoyable. npc_ids = [3078, 3079] dialogue_ids = [7502, 7504, 7506, 7508] def first_click_npc_3078(player): player.getDH().sendDialogues(7500) def chat_7500(player): player.getDH().sendPlayerChat("Hi there.", 591) dialogue = random.choice(dialogue_ids) player.nextDialogue = dialogue; def chat_7502(player): player.getDH().sendNpcChat("Hello, lovely day today isn't it?", 589) def chat_7504(player): player.getDH().sendNpcChat("Can't stop, I'm rather busy.", 589) def chat_7506(player): player.getDH().sendNpcChat("Hey! How are you today?", 589) player.nextDialogue = 7507; def chat_7507(player): player.getDH().sendPlayerChat("I'm great thanks.", 591) def chat_7508(player): player.getDH().sendNpcChat("*Cough* *Splutter*", 589) player.nextDialogue = 7509; def chat_7509(player): player.getDH().sendPlayerChat("Oh dear, I think that might be contagious...", 591)
class ReferenceDummy(): def __init__(self, *args): return def _to_dict(self, *args): return "dummy"
# #1 # def make_negative( number ): # return number if number < 0 else - number # #2 def make_negative( number ): return -abs(number)
# This class parses a gtfs text file class Reader: def __init__(self, file): self.fields = [] self.fp = open(file, "r") self.fields.extend(self.fp.readline().rstrip().split(",")) def get_line(self): data = {} line = self.fp.readline().rstrip().split(",") for el, field in zip (line, self.fields): data[field] = el if len(data) == 1: return None else: return data def end(self): self.fp.close()
# Cajones es una aplicacion que calcula el listado de partes # de una cajonera # unidad de medida en mm # constantes hol_lado = 13 # variables h = 900 a = 600 prof_c = 400 h_c = 120 a_c = 200 hol_sup = 20 hol_inf = 10 hol_int = 40 hol_lateral = 2 esp_lado = 18 esp_sup = 18 esp_inf = 18 esp_c = 15 cubre_der_total = True cubre_iz_total = True def calcular_lado_cajon(prof_c, esp_c): lado_cajon = prof_c - 2 * esp_c return lado_cajon def calcular_a_c(cubre_iz_total, cubre_der_total, esp_lado, hol_lado, hol_lateral, a): if cubre_der_total: espesor_derecho = esp_lado else: espesor_derecho = esp_lado / 2 - hol_lateral if cubre_iz_total: espesor_izquierdo = esp_lado else: espesor_izquierdo = esp_lado / 2 - hol_lateral ancho_cajon = a - espesor_izquierdo - espesor_derecho - 2 * hol_lateral return ancho_cajon def calcular_h_c(h, esp_sup, esp_inf, hol_sup, hol_int, hol_inf): suma_holhura = hol_sup + hol_int + hol_inf suma_espesor = esp_sup + esp_inf espacio_cajones = h - suma_espesor - suma_holhura altura_cajon = espacio_cajones / 3 return altura_cajon h_c = calcular_h_c(h, esp_sup, esp_inf, hol_sup, hol_int, hol_inf) a_c = calcular_a_c(cubre_iz_total, cubre_der_total, esp_lado, hol_lado, hol_lateral, a) l_c = calcular_lado_cajon(prof_c, esp_c) print("frente cajon: ", a_c, " X ", round(h_c)) print("lado cajon: ", l_c, " X ", round(h_c))
#!/usr/bin/env python class TwitterError(Exception): """Base class for Twitter errors""" @property def message(self): '''Returns the first argument used to construct this error.''' return self.args[0] class PythonTwitterDeprecationWarning(DeprecationWarning): """Base class for python-twitter deprecation warnings""" pass class PythonTwitterDeprecationWarning330(PythonTwitterDeprecationWarning): """Warning for features to be removed in version 3.3.0""" pass
def middle(t): '''Write a function called middle that takes a list and returns a new list that contains all but the first and last elements''' return t[1: -1] if __name__ == '__main__': t = [1, 2, 30, 400, 5000] print(t) print(middle(t))
print('\033[34m^=\033[m' * 27) print('Conversor de decimal para binário, octol e hexadecimal') print('\033[34m=^\033[m' * 27) print("""Opção [1] Binário Opção [2] Octal Opção [3] Hexadecimal""") print('\033[34m^=\033[m' * 27) num = int(input('Digite o valor que deseja converter: ')) op = int(input('Digite a opção de conversão que deseja: ')) if op == 1: print('O número {} convertido para Binário é {}'.format(num, bin(num)[2:])) elif op == 2: print('O número {} convertido para Octal é {}'.format(num, oct(num)[2:])) elif op == 3: print('O número {} convertido para Hexadecimal é {}'.format(num, hex(num)[2:])) else: print('\033[31mOpção inválida tente novamente !!!\033[m')
""" File: hailstone.py ----------------------- This program should implement a console program that simulates the execution of the Hailstone sequence, as defined by Douglas Hofstadter. Output format should match what is shown in the sample run in the Assignment 2 Handout. """ def main(): """ This program will first ask user input a number (integer), then it will simulate the execution of the Hailstone sequences of that input. Every round the program will check whether the number is even or odd to decide how to modify the number, until the number reach 1. """ print('This program computes Hailstone sequences') # Variable 'count' will count how many step to reach 1. count = 0 # Variable 'maximum' will finally be the biggest number in each Hailstone sequence. maximum = 0 # Input an integer, if input a float, the program will do floor division then change it to an integer. num = int(float(input('Enter an integer: ')) // 1) # The program will check whether input is at least 1. if num <= 0: print('Input must be at least 1') else: # If the first input is 1, the program stops. if num == 1: print('It took ' + str(count) + ' step(s) to reach 1') else: # The while loop will keep running until the number reach 1. while num != 1: # If the number is even. if num % 2 != 0: print(str(int(num)) + ' is odd, so I make 3n+1: ' + str(int(3 * num + 1))) if num > maximum: maximum = num # Reassign the number. num = 3 * num + 1 count += 1 # If the number is odd. else: print(str(int(num)) + ' is even, so I take half: ' + str(int(num / 2))) if num > maximum: maximum = num # Reassign the number. num = num / 2 count += 1 # Print the results: Steps used and the biggest number in the Hailstone sequences. print('It took ' + str(count) + ' step(s) to reach 1') print('The biggest number in the Hailstone sequences is: ' + str(int(maximum))) if __name__ == "__main__": main()
print("Size of list"); list1 = [1,23,5,2,42,526,52]; print(list1); print(len(list1));
#!/usr/bin/env python # # Copyright 2015 British Broadcasting Corporation # # 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. r""" This module provides functions to analyses the timings of the detected beep/flashes and compare them against expected timings of beep/flashes to determine which observed ones correspond to which expected ones. So for any given light sensor or audio input we have a set of observed timings of beeps/flashes and a set of expected timings of beeps/flashes. The observed are subset range of the expected. "expected" describes N events for the entire video clip. "observed" describes M events observed during synchronised playback of some portion of the video. M <= N. The analysis runs a correlation using "expected" and "observed". The problem we're solving is which portion of the events in "expected" correlates the strongest with the events in "observed". To do this we slide the set of events in "observed" along the set of events in "expected". We start at event 0 in "expected" and compare M events with "observed". Then we do the same starting at event 1 in "expected" and compare M events with "observed". The last index we can use to extract M events in "expected" is N - M. For a given set of M events from expected, we then build a set of time differences, one entry per event. We calculate the variance for the data in this set of differences, and remember this as an indicator of "goodness of match", along with the start index involved. Once we have done this at all possible start points along "expected", we then have N-M variances. The one with the lowest value is the best match. If the master and client were perfectly synchronised, then we'd have a time difference set of all zero's and the variance would be zero. A realistic situation would show the time differences (mostly) clustering around constant value, but the variance will still be low. That is, plotting on a graph with synchronisation timeline values on the x-axis, and time difference values on the y-axis, then the average offset is a horizontal line and the variance quantifies how much the data differs from this ideal. A high variance indicates that the pattern of observed beep/flash timings did not match that particular subset of the expected beep/flash timings. If the pattern for the time differences is sloping, this indicates wall clock drift. """ def variance(dataset): """\ Given a set of time differences, compute the variance in this set :param dataset: list of values :returns: the variance """ avg = sum(dataset)/len(dataset) v = 0.0 for data in dataset: v += (data - avg) * (data - avg) v = v / len(dataset) return v def varianceInTimesWithObservedComparedAgainstExpectedAtIndex(idx, expected, observed): """\ Traverse the list of expected times, starting from index "idx", and the list of observed times, starting from index 0, for the full length of the observed times list, to generate a list of the time difference between each expected time and observed time. Then compute the variance in the time difference, and return it, along with the differences from which it was calculated. :param idx: index into expected times at which start traversal :param expected: list of expected times in units of sync time line clock :param observed: list of tuples of (detected centre flash/pulse time, err bounds), in units of sync time line clock :returns: tuple (variance, differencesAndErrors) * variance = statistical variance of the difference between expected and observed timings * differencesAndErrors is a list, of (diff,err) representing each time difference and the error bound for the respective measurement """ where = idx differences = [] differencesAndErrors = [] for e in observed: # e[0] is the observed time. e[1] is the error bound diff = expected[where] - e[0] differences.append( diff ) differencesAndErrors.append( (diff, e[1]) ) where += 1 return (variance(differences), differencesAndErrors) def correlate(expected, observed): """\ Perform a correlation between a list of expected timings, and a list of observed timings that ought to "match" against some contiguous portion of the expected timings. We work out the last possible index into the expected timings so that traversal from there to the end of its list has the same number of entries as in the observed timings list. Starting at index 0 of the expected list, we then compute the variance in time differences between each expected time and an observed time (running from index 0 of the observed timings). We repeat this from index 1 .. last possible index, each time computing the variance in time differences between each expected time and an observed time (running from index 0 of the observed timings) For each of the runs, we add a tuple of (expected time index, variance computed) to a list. Finally, we then traverse this list, looking for the lowest variance value. This is the point in the expected times that most closely matches the observed timings. :param expected: list of expected times in units of sync time line clock :param observed: list of tuples of (detected centre flash/pulse time, err bounds), in units of sync time line clock :returns (index, timeDifferences): A tuple containing the index in the expected timings corresponding to the first observation, and a list of the time differences between each individual observed and expected flash/beep for the match. if there are more detected flashes/beeps than expected, it is probably due to a wrong input being plugged into on the Arduino, compared to what was asked for via the command line. In this case we return a tuple (-1, None) """ # following list will hold all sets of time differences computed during the correlation. # entry j will hold the set found when observed was compared with expected starting at j. timeDifferencesAndErrorsAtIndices = [] # the observed timings will be a subset of the expected times # so figure out the last start index in the observed timings # that accommodates the length of these observed timings lastPossible = len(expected) - len(observed) varianceAtEachIndex = [] # now look for the set of observed timings against each # possible starting point. Each loop traversal, observed[0] will be compared against # expected[where]. observed[1] against expected[where+1] for where in range(0, lastPossible + 1): variance, diffsAndErrors = varianceInTimesWithObservedComparedAgainstExpectedAtIndex(where, expected, observed) timeDifferencesAndErrorsAtIndices.append(diffsAndErrors) varianceAtEachIndex.append((variance, where)) (lowestVariance, index) = min(varianceAtEachIndex) return (index, timeDifferencesAndErrorsAtIndices) def doComparison(test, startSyncTime, tickRate): """\ Each activated pin results in a test set: the observed and expected times. For each of these tests, perform the comparison. :param A tuple is a ( list of tuples of (observed times (sync time line units), error bounds), list of expected timings (seconds) ) :param startSyncTime: the start value used for the sync time line offered to the client device :param tickRate: the number of ticks per second for the sync time line offered to the client device :returns tuple summary of results of analysis. (index into expected times for video at which strongest correlation (lowest variance) is found, list of expected times for video, list of (diff, err) for the best match, corresponding to the individual time differences and each one's error bound) """ observed, expectedTimesSecs = test # convert to be on the sync timeline expected = [ startSyncTime + tickRate * t for t in expectedTimesSecs ] matchIndex, allTimeDifferencesAndErrors = correlate(expected, observed) timeDifferencesAndErrorsForMatch = allTimeDifferencesAndErrors[matchIndex] return (matchIndex, expected, timeDifferencesAndErrorsForMatch) def runDetection(detector, channels, dueStartTimeUsecs, dueFinishTimeUsecs): """\ for each channel of sample data, detect the beep or flash timings :param detector beep / flash detector to use for the detection :param nActivePins number of arduino inputs that were read during sampling :param channels the data channels for the sample data separated out per pin. This is a list of dictionaries, one per sampled pin. A dictionary is { "pinName": pin name, "isAudio": true or false, "min": list of sampled minimum values for that pin (each value is the minimum over a millisecond period) "max": list of sampled maximum values for that pin (each value is the maximum over same millisecond period) } :param dueStartTimeUsecs :param dueFinishTimeUsecs :return the detected timings list of dictionaries A dictionary is { "pin": pin name, "observed": list of detected timings } where a detected timing is a tuple (centre time of flash or beep, error bounds) in units of ticks of the synchronisation timeline """ timings = [] for channel in channels: isAudio = channel["isAudio"] if isAudio: func = detector.samplesToBeepTimings else: func = detector.samplesToFlashTimings eventDuration = channel["eventDuration"] timings.append({"pinName": channel["pinName"], "observed": func(channel["min"], channel["max"], dueStartTimeUsecs, dueFinishTimeUsecs, eventDuration)}) return timings if __name__ == '__main__': # unit tests in: # ../tests/test_analyse.py pass
FANARTTV_PROJECTKEY = '' TADB_PROJECTKEY = '' TMDB_PROJECTKEY = '' THETVDB_PROJECTKEY = ''
# Regards, Takeda Shingen (Sengoku Era) Questline | Near Momiji Hills 1 (811000001) # Author: Tiger TAKEDA = 9000427 if "1" in sm.getQRValue(58901): # Regards, Takeda Shingen sm.setSpeakerID(TAKEDA) sm.flipDialogue() sm.sendNext("Good, you're here! I was about to pick another fight") sm.flipDialogue() sm.sendSay("We have a problem, and it's not a lack of conditioner. I'll tell ya that!") sm.flipDialogue() sm.sendSay("That warrior you found is in a coma. Lost their fight with consciousness. I guess. I had a letter somewhere here from Momijigaoka (He smashes boxes and chairs looking for the letter )") sm.setQRValue(58901, "2") # Regards, Takeda Shingen elif "2" in sm.getQRValue(58901): # Regards, Takeda Shingen sm.setSpeakerID(TAKEDA) sm.flipDialogue() sm.sendNext("Hm... I don't remember where I left it. It had the instructions on how to lift the spell.. Well, it wasn't that important anyway") sm.flipDialogue() sm.sendSay("Ha ha ha, a real man never sweats over losing such unimportant things!") sm.flipDialogue() sm.sendSay("As I recall, the Oda army is teaching wicked spells to it's soliders. Maybe one of them knocked our new friend out of commission.") response = sm.sendAskYesNo("There are a couple things that need to get done to lift the spell.\r\nYou can help, right?") if response: sm.flipDialogue() sm.sendNext("Ha, I knew you would do it.") sm.flipDialogue() sm.sendSay("First we need to know more about the spells. Eliminate some Oda Warrior Trainee monsters to find clues.") sm.flipDialogue() sm.sendSay("I don't need that many just 30 of them. That should be enough to mash into reason. Now, get to it!") sm.setQRValue(58901, "3") # Regards, Takeda Shingen sm.startQuest(parentID)
array = [3,5,-4,8,11,-1,6] targetSum = 10 def twoNumberSum(array, targetSum): #for loop to iterate the array for i in range(len(array) - 1): firstNum = array[i] for j in range(i + 1, len(array)): secondNum = array[j] if firstNum + secondNum == targetSum: return [firstNum, secondNum] return[] # print(twoNumberSum(firstNum, secondNum)) # Second Solution def twoNumberSum(array, targetSum): nums = {} for num in array: potentialMatch = targetSum - num if potentialMatch in nums: return [potentialMatch, num] else: nums[num] = True return [] # Third Solution def TwoNumSum(array, targetSum): for i in range(len(array)-1): firstNum = array[i] for j in range( i + 1, len(array)): secondNum = array[j] if firstNum + secondNum == targetSum: return [firstNum, secondNum] return []
def can_create_a_Fibonacci_number(int_1, int_2): """ This function checks to see if the sum, difference, product, or module of the two inputs product a Fibonacci number. 1, 1, 2, 3, 5, 8, 13, 21, 34 ... The two inputs are assumed to be integers """ sum = int_1 + int_2 product = int_1 * int_2 if int_1 > int_2: diff = int_1 - int_2 mod = int_1 % int_2 else: diff = int_2 - int_1 mod = int_1 % int_2 possible_fibs = [sum, product, diff, mod] fib1 = 1 fib2 = 2 fib_found = False while fib2 < max(possible_fibs) and not fib_found: new_fib = fib1 + fib2 if new_fib in possible_fibs: fib_found = True if new_fib == sum: print('Sum creates: ', new_fib) elif new_fib == product: print('Product creates: ', new_fib) elif new_fib == diff: print('Difference creates: ', new_fib) else: print('Modulo creates: ', new_fib) fib1 = fib2 fib2 = new_fib if not fib_found: print('No Fibonacci Number found under: ', fib2) can_create_a_Fibonacci_number(30, 33) can_create_a_Fibonacci_number(30, 4) can_create_a_Fibonacci_number(29, 4)
""" The constants module contains some numerical constants for use in the module. Note that modifying these may yield unpredictable results. """ # Force zero values to this amount, for numerical stability MIN_SITE_FRACTION = 1e-12 MIN_PHASE_FRACTION = 1e-12 # Phases with mole fractions less than COMP_DIFFERENCE_TOL apart (by Chebyshev distance) are considered "the same" for # the purposes of CompositionSet addition and removal during energy minimization. COMP_DIFFERENCE_TOL = 1e-2 # 'infinity' for numerical purposes BIGNUM = 1e60
""" The set-covering problem Book: Grokking Algorithms Chapter 8: Greedy Algorithms Suppose you're starting a radio show. You want to reach listeners in all 50 states. You have to decide what stations to play on to reach all those listeners. It costs money to be on each station, so you're trying to minimize the number of stations you play on. You have a list of stations. Each station covers a region, and there's overlap. station | states kone -> id, nv, ut ktwo -> wa, id, mt kthree -> or, nv, ca kfour -> nv, ut kfive -> ca, az How do you figure out the smallest set of stations you can play on to cover all 50 states? -- ### SOLUTION #### Naive Solution - Create a set of states - Create all possible subsets of stations - For each subset, check if it contains all states and pick the smallest How to find the time complexity? For each station, I can add it to the set, or not add it. {} / \ {} {kone} / \ / \ {} {ktwo} {kone} {kone, ktwo} /\... 2^0 + 2^1+ 2^2... 2^n => Sum(2^k) from 0 to n. => 2^(n+1) - 1 Time Complexity: O(2^n) -- Greedy Solution (Approximation Algorithm) - Pick the station with the most states that have not been covered yet. It is ok if some states have already been covered. - Repeat the process until all states are covered. So, we have to go through all stations and check how many states it can cover. Compare this to the next stations and get the one with the max amount of states covered. Do this until all states are covered. Since we might go through the entire list N times for each of the states, this is O(n²). Time Complexity: O(n²) """ def set_cover_greedy(stations, states_needed): final_stations = set() while states_needed: best_station = None covered = set() for station, states_for_station in stations.items(): covered_states_of_stations = states_for_station & states_needed if len(covered_states_of_stations) > len(covered): covered = covered_states_of_stations best_station = station states_needed -= covered final_stations.add(best_station) return final_stations def set_cover_naive(stations, states_needed): subsets = generate_subsets(stations) subsets_with_all_states = get_subsets_with_all_states( stations, subsets, states_needed ) return min(subsets_with_all_states, key=lambda subset: len(subset)) def generate_subsets(stations): keys = list(stations.keys()) subsets = [] def rec_gen_subset(stations, index, current_subset): if index >= len(stations): subsets.append(current_subset) return rec_gen_subset(stations, index + 1, current_subset | set([stations[index]])) rec_gen_subset(stations, index + 1, current_subset) rec_gen_subset(keys, 0, set()) return subsets def get_subsets_with_all_states(states_for_station, subsets, states_needed): subsets_with_all_states = [] for subset in subsets: covered_states = set() for station in subset: covered_states = covered_states | states_for_station[station] if covered_states == states_needed: subsets_with_all_states.append(subset) return subsets_with_all_states def test(stations, states_needed, expected_answer): answer = set_cover_greedy(stations, states_needed) if answer != expected_answer: raise Exception( f"Answer {answer} is incorrect. Expected answer was {expected_answer}" ) if __name__ == "__main__": stations = { "kone": set(["id", "nv", "ut"]), "ktwo": set(["wa", "id", "mt"]), "kthree": set(["or", "nv", "ca"]), "kfour": set(["nv", "ut"]), "kfive": set(["ca", "az"]), } states_needed = set(["id", "nv", "ut", "wa", "mt", "or", "ca", "az"]) test(stations, states_needed, set(["ktwo", "kthree", "kone", "kfive"])) print("All tests passed!")
#!/usr/bin/env python major_version = 0 minor_version = 0 patch_version = 10 def format_version(): return "{0}.{1}.{2}".format(major_version, minor_version, patch_version)
#Um gerenciador de pagementos simples preco = float(input('Qual o valor da compra? ')) pagamento = int(input("""Qual será a forma de pagamento? Digite 0 para pagamento à vista no dinheiro ou cheque Digite 1 para pagamento à vista no cartão Digite 2 para pagamento parcelado em até 2x Digite 3 para pagamento parcelado em 3x ou mais """)) if pagamento == 0: pagamento = 'pagamento à vista em dinheiro ou cheque' saldo = preco - (preco*10/100) print("""Você escolheu a opção {} Você irá pagar {}""".format(pagamento,saldo)) elif pagamento == 1: pagamento = 'pagamento à vista no cartão' saldo = preco - (preco*5/100) print("""Você escolheu a opção {} Você irá pagar {}""".format(pagamento,saldo)) elif pagamento == 2: pagamento = 'pagamento parcelado em até 2x' saldo = preco print("""Você escolheu a opção {} Você irá pagar {}""".format(pagamento,saldo)) elif pagamento == 3: pagamento = 'pagamento parcelado em 3x ou mais' saldo = preco + (preco*20/100) print("""Você escolheu a opção {} Você irá pagar {}""".format(pagamento,saldo))
# BIP39 Wordlist Validator - A tool to validate BIP39 wordlists in Latin # languages. # bip39validator/data_structs.py: Program data structures. # Copyright 2020 Ali Sherief # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # A data structure consisting of # - An array of strings `word_list` # - An array of line numbers `line_numbers` # Each entry in `word_list` is associated with the corresponding entry in # `line_number`. They are expected to have the same length. # It is returned by the following functions: # - sanitize() # And is passed to the following functions: # - compute_levenshtein_distance() class WordAndLineArray: def __init__(self, args): self.word_list = args[0] self.line_numbers = args[1] # A data structure consisting of # - An integer distance `dist` # - A pair of line numbers `line_numbers` # - A pair of words `words` class LevDist: def __init__(self, **kwargs): self.dist = kwargs['dist'] self.line_numbers = kwargs['line_numbers'] self.words = kwargs['words'] class LevDistArray: def __init__(self, lev_dist_arr): self.lev_dist_arr = lev_dist_arr
class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: """ Ideas: 1. Count the frequencies, sort and take top k -> O(N) + O(N log N) 2. heapq.nlargest -> O(N) + O(N log N) 3. Count the frequencies and keep only top k elements in the heap -> O(N) + O(N log K) 4. QuickSelect -> runs in O(N) """ counts = collections.Counter(nums) counts = [item for item in counts.items()] top_k = self.quick_select(counts, k) return [num for num, _ in top_k] def quick_select(self, counts, k): """ [(1,3), (3, 1), (2, 2)] [1,2,3,4,5] k = 3 smaller = [1,2,3] bigger = [4,5] k = 1 smaller = [] bigger = [1,2,3] k = 1 smaller = [1,2] bigger = [3] """ pivot_idx = random.randint(0, len(counts)-1) pivot_count = counts[pivot_idx][1] smaller = [item for item in counts if item[1] < pivot_count] bigger = [item for item in counts if item[1] >= pivot_count] if len(bigger) == k: return bigger if len(bigger) > k: return self.quick_select(bigger, k) return bigger + self.quick_select(smaller, k-len(bigger))
#!/bin/python3 FAVORITE_NUMBER = 1362 GRID = [[0 for j in range(50)] for i in range(50)] TARGET = (31, 39) def check_wall(coordinates): x, y = coordinates if x < 0 or y < 0 or x >= 50 or y >= 50: return False elif GRID[x][y] != 0: return False current = x * x + 3 * x + 2 * x * y + y + y * y current += FAVORITE_NUMBER current = bin(current)[2:].count("1") if current % 2 != 0: GRID[x][y] = -1 return False else: return True def day13(): queue = [(1, 1, 0)] while queue: x, y, steps = queue.pop(0) if (x, y) == TARGET: return steps GRID[x][y] = steps if check_wall((x - 1, y)): queue.append((x - 1, y, steps + 1)) if check_wall((x + 1, y)): queue.append((x + 1, y, steps + 1)) if check_wall((x, y - 1)): queue.append((x, y - 1, steps + 1)) if check_wall((x, y + 1)): queue.append((x, y + 1, steps + 1)) return False print(day13())
# Marcelo Campos de Medeiros # ADS UNIFIP 2020.1 # Patos-PB 03/04/2020 ''' Leia um valor inteiro correspondente à idade de uma pessoa em dias e informe-a em anos, meses e dias Obs.: apenas para facilitar o cálculo, considere todo ano com 365 dias e todo mês com 30 dias. Nos casos de teste nunca haverá uma situação que permite 12 meses e alguns dias, como 360, 363 ou 364. Este é apenas um exercício com objetivo de testar raciocínio matemático simples. Entrada O arquivo de entrada contém um valor inteiro. Saída Imprima a saída conforme exemplo fornecido. ''' td = int(input('n= ')) qa = td // 365 r = td % 365 qm = r // 30 qd = r % 30 print(qa,'ano(s)') print(qm,'{} mes(es)') print(qd,'{} dia(s)')
# coding: utf-8 # author: Fei Gao # # Search A 2d Matrix Ii # Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: # Integers in each row are sorted in ascending from left to right. # Integers in each column are sorted in ascending from top to bottom. # For example, # Consider the following matrix: # [ # [1, 4, 7, 11, 15], # [2, 5, 8, 12, 19], # [3, 6, 9, 16, 22], # [10, 13, 14, 17, 24], # [18, 21, 23, 26, 30] # ] # Given target = 5, return true. # Given target = 20, return false. # Subscribe to see which companies asked this question class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ def search(row1, row2, col1, col2): """Search target in sub matrix[row1:row2][col1:col2]""" # zero elements if row1 >= row2 or col1 >= col2: return False if matrix[row1][col1] == target: return True # target less than up-left corner if target < matrix[row1][col1]: return False # target greater than low-right corner if target > matrix[row2 - 1][col2 - 1]: return False row3 = (row1 + row2 + 1) // 2 col3 = (col1 + col2 + 1) // 2 # print(row1, row3, row2, col1, col3, col2) result = (search(row1, row3, col1, col3) or search(row1, row3, col3, col2) or search(row3, row2, col1, col3) or search(row3, row2, col3, col2)) # print(row1, row2, col1, col2, result) return result return search(0, len(matrix), 0, len(matrix[0])) def main(): solver = Solution() tests = [ ([ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ], 5), ([ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ], 20) ] for test in tests: print(test) print(' ->') result = solver.searchMatrix(*test) print(result) print('~' * 10) pass if __name__ == '__main__': main() pass
""" https://www.hackerrank.com/challenges/dynamic-array/problem """ def dynamicArray(n, queries): seqList = [[] for x in range(n)] lastAnswer = 0 result = [] for q in queries: [qType, seqIndex, number] = q index = (seqIndex ^ lastAnswer) % n seq = seqList[index] if qType == 1: seq.append(number) if qType == 2: lastAnswer = seq[number % len(seq)] result.append(lastAnswer) return result
valor = float(input('Qual é o valor do produto? R$')) # desconto = valor * 0.05 Pode fazer desses dois jeitos # preco = valor - desconto novo = valor - (valor * 5 / 100) print("O produto que custavo R${:.2f}, na promoção de 5% vai custar R${:.2f}".format(valor, novo))
# Criando Exceções - Classes de erros personalizados no python class TaErradoErros(Exception): pass def testar(): raise TaErradoErros('Errado') try: testar() except TaErradoErros as error: print(f'Erro: {error}')
_title = 'KleenExtractor' _description = 'Clean extract system to export folder content and sub content.' _version = '0.1.2' _author = 'Edenskull' _license = 'MIT'
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 1 10:46:16 2020 @author: AzureD Useful tools to splitting and cleaning up input text. """ def cleanly(text: str): """ Splits the text into words at spaces, removing excess spaces. """ segmented = text.split(' ') clean = [s for s in segmented if not s == ''] return clean def prefix(text: str): # NOTE: PEP 616 solved this in python version 3.9+ """ Takes the first word off the text, strips excess spaces and makes sure to always return a list containing a prefix, remainder pair of strings. """ segmented = text.split(' ', 1) # ensure a list of 2 elements unpacked into a prefix, remainder (even if remainder is nothing) prefix, remainder = segmented if len(segmented) == 2 else [text, ''] return(prefix, remainder.lstrip()) # lstrip removes excess spaces from remainder def command(text: str): """ Separates and cleans the command(prefix) from a given text, and lower cases it, returning both the command and the remaining text """ command, remainder = prefix(text) return(command.lower(), remainder)
q = int(input()) for _ in range(q): n = int(input()) m = [] for _ in range(n*2): m.append(list(map(int, input().split(' ')))) # Sorcery here... bigMax = 0 for i in range(n): for j in range(n): try: bigMax += max(m[i][j], m[i][2*n-1-j], m[2*n-1-i][j], m[2*n-1-i][2*n-1-j]) except: pass #print("(" + str(i) + ", " + str(j) + ")") print(bigMax)
secret = 'BEEF0123456789a' skipped_sequential_false_positive = '0123456789a' print('second line') var = 'third line'
#http://www.pythonchallenge.com/pc/def/ocr.html s = "" with open("3.html") as f: for line in f.readlines(): s += line for el in s: if el >= 'a' and el <= 'z': print(el),
# feel free to change these settings APP_NAME = 'Deep Vision' # any string: The application title (desktop and web). ABOUT_TITLE = "Deep Vision" # any string: The about box title (desktop and web). ABOUT_MESSAGE = "Created By : FastAI Student" # any string: The about box contents (desktop and web). APP_TYPE = 'desktop' # desktop, web: Run the app as a desktop or a web application. SHOW_MEDIA = True # True, False: Show images and videos on screen. SAVE_MEDIA = False # True, False: Save images and videos to file. SAVE_MEDIA_PATH = None # any string, None: Save images and videos to this folder, set to None to use application path. SAVE_MEDIA_FILE = None # any string, None: Save images and videos to this file, set to None to use random file name. # Mostly you will not want to change these settings SHOW_LOGS = False # True, False: Print applications logs to console. CAMERA_ID = 0 # numbers: Target camera id, 0 for default camera IMAGES_TYPES = ['*.jpg', '*.jpeg', '*.jpe', '*.png', '*.bmp'] # any image format supported by openCV: Open image dialog file types VIDEOS_TYPES = ['*.mp4', '*.avi'] # any video format supported by openCV: Open video dialog file types SCALE_IMAGES = True # True, False: Scale source image to fit container (desktop or web) # don't change these settings APP_PATH = './'
# coding=utf-8 # Author: Jianghan LI # Question: 114.Flatten_Binary_Tree_to_Linked_List # Date: 2017-04-19 9:15 - 9:21 # 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 flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ if not root: return queue = [root] if root.right: queue.append(root.right) if root.left: queue.append(root.left) while queue: cur = queue.pop() if cur.right: queue.append(cur.right) if cur.left: queue.append(cur.left) root.right = cur root.left = None root = cur root.right = None
num = soma = cont = 0 while True: num = int(input('Digite um número: ')) if num == 999: break soma = soma + num cont = cont + 1 print(f'A soma dos {cont} números digitados é: {soma}')
ch=input(('Enter any alphabet or digit ')) if ch in 'aeiouAEIOU': print(ch,'is a vowel.') elif ch in '0123456789': print(ch,'is a digit.') else: print(ch,'is a consonant.')
''' Write a program to read two integers that are the date and month of birth. They are used to find the user's zodiac sign. The program should print type the birth signs on the screen. The details of each zodiac are as follows. 22 Dec - 19 Jan Capricorn 20 Jan - 18 Feb Aquarius 19 Feb - 20 Mar Pisces 21 Mar - 19 Apr Aries 20 Apr – 20 May Taurus 21 May – 21 Jun Gemini 22 Jun – 22 July Cancer 23 July – 22 Aug Leo 23 Aug – 22 Sep Virgo 23 Sep – 23 Oct Libra 24 Oct – 21 Nov Scorpio 22 Nov – 21 Dec Sagittarius ''' d = int(input()) m = int(input()) if m == 1: print('Capricorn' if d < 20 else 'Aquarius') elif m == 2: print('Aquarius' if d < 19 else 'Pisces') elif m == 3: print('Pisces' if d < 21 else 'Aries') elif m == 4: print('Aries' if d < 20 else 'Taurus') elif m == 5: print('Taurus' if d < 21 else 'Gemini') elif m == 6: print('Gemini' if d < 22 else 'Cancer') elif m == 7: print('Cancer' if d < 23 else 'Leo') elif m == 8: print('Leo' if d < 23 else 'Virgo') elif m == 9: print('Virgo' if d < 23 else 'Libra') elif m == 10: print('Libra' if d < 24 else 'Scorpio') elif m == 11: print('Scorpio' if d < 22 else 'Sagittarius') else: print('Sagittarius' if d < 22 else 'Capricorn')
class MessageWriter: """ This class allows a "message" to be sent to an external recipient. """ def __init__(self, *args, **kwargs): pass def send_message(self, message): """ Sends a message to an external recipient. Usually, this involves creating a connection to an API with any necessary credentials. :param message: :return: """ raise NotImplementedError
comp = float(input('Digite o Comptrimento da parede em metros:')) alt = float(input('Digite a altura da parede em metros: ')) rend = float(input('digite o rendimento da tinta em metros quadrados:')) print('Você possui uma area de {} m².'.format(comp*alt)) print('Sabendo que o rendimento da tinta é de {}m² por litros.'.format(rend)) print('Você necessitará de {} litros de tinta.'.format(((comp * alt) / rend)))
LOCAL_STATE_PATH = "/state" DEFAULT_INSTANCE_TYPE_TRAINING = "ml.m5.large" DEFAULT_INSTANCE_TYPE_PROCESSING = "ml.t3.medium" DEFAULT_INSTANCE_COUNT = 1 DEFAULT_VOLUME_SIZE = 30 # GB DEFAULT_USE_SPOT = True DEFAULT_MAX_RUN = 24 * 60 DEFAULT_MAX_WAIT = 0 DEFAULT_IAM_ROLE = "SageMakerIAMRole" DEFAULT_IAM_BUCKET_POLICY_SUFFIX = "Policy" DEFAULT_REPO_TAG = "latest" TEST_LOG_LINE_PREFIX = "-***-" TEST_LOG_LINE_BLOCK_PREFIX = "*** START " TEST_LOG_LINE_BLOCK_SUFFIX = "*** END " TASK_TYPE_TRAINING = "Training" TASK_TYPE_PROCESSING = "Processing"
""" *Coarsen* """ __all__ = ["Coarsen"] class Coarsen( TensorOperator, ): pass
""" Faça um programa que leia um número de 0 a 9999 e moste na tela cada um dos digitos separados. ex: Digite um número: 1834 Unidade: 4 Dezena: 3 centena: 8 milhar: 1 """ num = int(input('Informe um número: ')) u = num // 1 % 10 d = num // 10 % 10 c = num // 100 % 10 m = num // 1000 % 10 print(f'Analisando o número {num}...') print(f'Unidade {u}') print(f'Dezena {d}') print(f'Centena {c}') print(f'Milhar {m}') # Forma matematica de fazer sem uso dos loops
def avg(values): return sum(values) / len(values) def input_to_list(count): lines = [] for _ in range(count): lines.append(input()) return lines n = int(input()) students_grades_lines = input_to_list(n) students_grades = {} for line in students_grades_lines: student, grade = line.split(" ") if student not in students_grades: students_grades[student] = [] students_grades[student].append(float(grade)) for (student, grades) in students_grades.items(): grades_string = " ".join(map(lambda grade: f'{grade:.2f}', grades)) avg_grade = avg(grades) print(f"{student} -> {grades_string} (avg: {avg_grade:.2f})")
""" ## OSBot-Utils Project with multiple Util classes (to streamline development) Main GitHub repo: https://github.com/owasp-sbot/OSBot-Utils [![Coverage Status](https://coveralls.io/repos/github/owasp-sbot/OSBot-Utils/badge.svg?branch=master)](https://coveralls.io/github/owasp-sbot/OSBot-Utils?branch=master) """
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2022/3/20 4:18 下午 # @Author : xinming # @File : 91_num_decodings.py class Solution(object): def numDecodings(self, s): if not s: return None if s[0]=='0': return 0 n = len(s) dp = [0 for i in range(n)] dp[0]=1 for i in range(1, n): if s[i]!='0': dp[i]+=dp[i-1] if s[i-1]!='0' and (int(s[i-1])*10 + int(s[i]))<=26: if i>1: dp[i]+=dp[i-2] else: dp[i]+=1 return dp[n-1] if __name__=='__main__': s = '1226' s='06' out = Solution().numDecodings(s=s) print(out)
class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: weight = dict() for x in people: if x in weight: weight[x] += 1 else: weight[x] = 1 ans = 0 for x in people: if weight[x] > 0: weight[x]-= 1 upper = limit - x for i in range(upper,0,-1): if i in weight: if weight[i] > 0: weight[i] -= 1 break ans += 1 else: continue return ans
n=int(input()) l=[] k=[] e=[] for i in range (n): t=input() l.append(t) print(l) for j in l: if j not in k: k.append(j) print(k) print(len(k)) for m in range(len(k)): c=0 for d in l: if( k[m]==d): c=c+1 e.append(c) print(e) for i in e: print(i,end=' ')
""" format: def request(login, password): return bool(...) """
class Shop: _small_shop_capacity = 10 def __init__(self, name, shop_type, capacity): self.name = name self.type = shop_type self.capacity = capacity self.items_count = 0 self.items = {} @classmethod def small_shop(cls, name, shop_type): return cls(name, shop_type, cls._small_shop_capacity) def _can_add_item(self): return self.items_count < self.capacity - 1 def _can_remove_amount_of_item(self, item, amount): return item in self.items and amount <= self.items[item] def add_item(self, item): if not self._can_add_item(): return 'Not enough capacity in the shop' if item not in self.items: self.items[item] = 0 self.items[item] += 1 self.items_count += 1 return f'{item} added to the shop' def remove_item(self, item, amount): if not self._can_remove_amount_of_item(item, amount): return f'Cannot remove {amount} {item}' self.items[item] -= amount self.items_count -= amount return f'{amount} {item} removed from the shop' def __str__(self): return f'{self.name} of type {self.type} with capacity {self.capacity}'
for row in range(5,0): for col in range(1,row+1): print(col,end=" ") print()
n = int(input('Primeiro número: ')) r = int(input('Razão: ')) valor = n for c in range(0, 10): print(valor, end=' -> ') valor += r print('ACABOU')
IDENTIFIED_COMMANDS = { 'NS STATUS %s': ['STATUS {username} (\d)', '3'], 'PRIVMSG NickServ ACC %s': ['{username} ACC (\d)', '3'], } IRC_AUTHS = { # 'localhost': {'username': 'Botname', 'realname': 'Bot Real Name'}, } IRC_GROUPCHATS = [ # 'groupchat@localhost', ] IRC_PERMISSIONS = { # 'nekmo@localhost': ['root'], }
class Solution: def decompressRLElist(self, nums: List[int]) -> List[int]: result = [] for i in range(0, len(nums), 2): freq, val = nums[i:i+2] for n in range(freq): result.append(val) return result
# Global Level Configuration File. # Flask Settings # http://flask.pocoo.org/docs/0.12/config/ ''' enable/disable debug mode ''' DEBUG = True ''' enable/disable testing mode ''' TESTING = False ''' explicitly enable or disable the propagation of exceptions. If not set or explicitly set to None this is implicitly true if either TESTING or DEBUG is true. ''' PROPAGATE_EXCEPTIONS = True ''' By default if the application is in debug mode the request context is not popped on exceptions to enable debuggers to introspect the data. This can be disabled by this key. You can also use this setting to force-enable it for non debug execution which might be useful to debug production applications (but also very risky). ''' PRESERVE_CONTEXT_ON_EXCEPTION = True ''' the secret key ''' SECRET_KEY = '' ''' the name of the session cookie ''' SESSION_COOKIE_NAME = '' ''' the domain for the session cookie. If this is not set, the cookie will be valid for all subdomains of SERVER_NAME. ''' #SESSION_COOKIE_DOMAIN = '' ''' the path for the session cookie. If this is not set the cookie will be valid for all of APPLICATION_ROOT or if that is not set for '/'. ''' SESSION_COOKIE_PATH = '' ''' controls if the cookie should be set with the httponly flag. Defaults to True. ''' SESSION_COOKIE_HTTPONLY = False ''' controls if the cookie should be set with the secure flag. Defaults to False. ''' SESSION_COOKIE_SECURE = True ''' the lifetime of a permanent session as datetime.timedelta object. Starting with Flask 0.8 this can also be an integer representing seconds. ''' PERMANENT_SESSION_LIFETIME = 3600 ''' this flag controls how permanent sessions are refreshed. If set to True (which is the default) then the cookie is refreshed each request which automatically bumps the lifetime. If set to False a set-cookie header is only sent if the session is modified. Non permanent sessions are not affected by this. ''' SESSION_REFRESH_EACH_REQUEST = True ''' enable/disable x-sendfile ''' USE_X_SENDFILE = True ''' the name of the logger ''' LOGGER_NAME = None ''' the policy of the default logging handler. The default is 'always' which means that the default logging handler is always active. 'debug' will only activate logging in debug mode, 'production' will only log in production and 'never' disables it entirely. ''' LOGGER_HANDLER_POLICY = 'always' ''' the name and port number of the server. Required for subdomain support (e.g.: 'myapp.dev:5000') Note that localhost does not support subdomains so setting this to “localhost” does not help. Setting a SERVER_NAME also by default enables URL generation without a request context but with an application context. ''' SERVER_NAME = '127.0.0.1:8000' ''' If the application does not occupy a whole domain or subdomain this can be set to the path where the application is configured to live. This is for session cookie as path value. If domains are used, this should be None. ''' APPLICATION_ROOT = None ''' If set to a value in bytes, Flask will reject incoming requests with a content length greater than this by returning a 413 status code. ''' #MAX_CONTENT_LENGTH = 1024 ''' Default cache control max age to use with send_static_file() (the default static file handler) and send_file(), as datetime.timedelta or as seconds. Override this value on a per-file basis using the get_send_file_max_age() hook on Flask or Blueprint, respectively. Defaults to 43200 (12 hours). ''' SEND_FILE_MAX_AGE_DEFAULT = 43200 ''' If this is set to True Flask will not execute the error handlers of HTTP exceptions but instead treat the exception like any other and bubble it through the exception stack. This is helpful for hairy debugging situations where you have to find out where an HTTP exception is coming from. ''' TRAP_HTTP_EXCEPTIONS = False ''' Werkzeug’s internal data structures that deal with request specific data will raise special key errors that are also bad request exceptions. Likewise many operations can implicitly fail with a BadRequest exception for consistency. Since it’s nice for debugging to know why exactly it failed this flag can be used to debug those situations. If this config is set to True you will get a regular traceback instead. ''' TRAP_BAD_REQUEST_ERRORS = True ''' The URL scheme that should be used for URL generation if no URL scheme is available. This defaults to http. ''' PREFERRED_URL_SCHEME = 'http' ''' By default Flask serialize object to ascii-encoded JSON. If this is set to False Flask will not encode to ASCII and output strings as-is and return unicode strings. jsonify will automatically encode it in utf-8 then for transport for instance. ''' JSON_AS_ASCII = False ''' By default Flask will serialize JSON objects in a way that the keys are ordered. This is done in order to ensure that independent of the hash seed of the dictionary the return value will be consistent to not trash external HTTP caches. You can override the default behavior by changing this variable. This is not recommended but might give you a performance improvement on the cost of cacheability. ''' JSON_SORT_KEYS = False ''' If this is set to True (the default) jsonify responses will be pretty printed if they are not requested by an XMLHttpRequest object (controlled by the X-Requested-With header) ''' JSONIFY_PRETTYPRINT_REGULAR = False ''' MIME type used for jsonify responses. ''' JSONIFY_MIMETYPE = None ''' Whether to check for modifications of the template source and reload it automatically. By default the value is None which means that Flask checks original file only in debug mode. ''' TEMPLATES_AUTO_RELOAD = True ''' If this is enabled then every attempt to load a template will write an info message to the logger explaining the attempts to locate the template. This can be useful to figure out why templates cannot be found or wrong templates appear to be loaded. ''' EXPLAIN_TEMPLATE_LOADING = True # SQL Alchemy Settings SQLALCHEMY_ECHO = True # Custom Cache timeout CACHE_TIMEOUT = 3600 CACHE_TYPE = 'simple'
# -*- coding: utf-8 -*- """ Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. Note that the row index starts from 0. Example: Input: 3 Output: [1,3,3,1] Follow up: Could you optimize your algorithm to use only O(k) extra space? 构造杨辉三角 """ class Solution: def genRow(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ result = [] for i in range(1, numRows + 2): if i <= 2: result = [1 for i in range(i)] continue current_line = [] for j in range(i): if j == 0 or j == (i - 1): current_line.append(1) else: tmp = result[j] + result[j - 1] current_line.append(tmp) result = current_line return result if __name__ == '__main__': s = Solution() print(s.getRow(1))