content
stringlengths 7
1.05M
|
---|
#!/usr/bin/env python
""" Problem 38 daily-coding-problem.com """
def n_queens(n, board=[]):
''' see https://www.dailycodingproblem.com/blog/an-introduction-to-backtracking/'''
if n == len(board):
return 1
count = 0
for col in range(n):
board.append(col)
if is_valid(board):
count += n_queens(n, board)
board.pop()
return count
def is_valid(board):
current_queen_row, current_queen_col = len(board) - 1, board[-1]
# Check if any queens can attack the last queen.
for row, col in enumerate(board[:-1]):
diff = abs(current_queen_col - col)
if diff == 0 or diff == current_queen_row - row:
return False
return True
if __name__ == "__main__":
assert n_queens(1) == 1
assert n_queens(4) == 2
assert n_queens(7) == 40
assert n_queens(10) == 724 |
class American(object):
pass
class NewYorker(American):
pass
anAmerican = American()
aNewYorker = NewYorker()
|
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
# hash表方法
hashmap1 = {}
hashmap2 = {}
for s1, t1 in zip(s, t):
# 建立一次对应关系之后,发现于原来的不一致
# (原来存在过,但是这个是新的)
if hashmap1.get(s1, t1) != t1 or hashmap2.get(t1, s1) != s1:
return False
# 建立对应关系
hashmap1[s1] = t1
hashmap2[t1] = s1
return True
def isIsomorphic(self, s: str, t: str) -> bool:
# index方法
if len(s) != len(t):
return False
else:
for i in range(len(s)):
# 比如'egg' 'bag'
if s.index(s[i]) != t.index(t[i]):
return False
return True |
# [7 kyu] Descending Order
#
# Author: Hsins
# Date: 2019/12/31
def descending_order(num):
return int("".join(sorted(str(num), reverse=True)))
|
def minimum_bracket_reversals(input_string):
if len(input_string) % 2 == 1:
return -1
stack = Stack()
count = 0
for bracket in input_string:
if stack.is_empty():
stack.push(bracket)
else:
top = stack.top()
if top != bracket:
if top == '{':
stack.pop()
continue
stack.push(bracket)
ls = list()
while not stack.is_empty():
first = stack.pop()
second = stack.pop()
ls.append(first)
ls.append(second)
if first == '}' and second == '}':
count += 1
elif first == '{' and second == '}':
count += 2
elif first == '{' and second == '{':
count += 1
return count
|
'''解説読んだ'''
H,W,A,B=[int(x) for x in input().split()]
[print(''.join(["0" if j<A else "1" for j in range(W)])) if i<B else print(''.join(["1" if j<A else "0" for j in range(W)])) for i in range(H)]
# 読みやすいバージョン
for i in range(H):
if i < B:
print(''.join(["0" if j < A else "1" for j in range(W)]))
else:
print(''.join(["1" if j < A else "0" for j in range(W)]))
|
# -*- coding: utf-8 -*-
"""
460. LFU Cache
Design and implement a data structure for Least Frequently Used (LFU) cache.
It should support the following operations: get and set.
"""
class LFUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
def get(self, key):
"""
:type key: int
:rtype: int
"""
def set(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
"""
# Your LFUCache object will be instantiated and called as such:
# obj = LFUCache(capacity)
# param_1 = obj.get(key)
# obj.set(key,value)
def main():
pass
if __name__ == "__main__":
main()
|
def intercalaEmOrdem(lista1, lista2):
intercalada = []
lista1.sort()
lista2.sort()
while len(lista1) > 0 and len(lista2) > 0:
if lista1[0] < lista2[0]:
intercalada.append(lista1.pop(0))
else:
intercalada.append(lista2.pop(0))
if len(lista1) > 0:
intercalada += lista1
if len(lista2) > 0:
intercalada += lista2
return intercalada
lista1 = [2, 4, 6, 8, 10]
lista2 = [1, 3, 5, 7, 9]
print(intercalaEmOrdem(lista1, lista2))
|
def f2(a):
global b
print(a)
print(b)
b = 9
print(b)
b = 5
f2(3) |
#
# PySNMP MIB module CPQCLUSTER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CPQCLUSTER-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:27:15 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint")
compaq, cpqHoTrapFlags = mibBuilder.importSymbols("CPQHOST-MIB", "compaq", "cpqHoTrapFlags")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
sysName, = mibBuilder.importSymbols("SNMPv2-MIB", "sysName")
Gauge32, Counter64, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Unsigned32, Integer32, TimeTicks, iso, Counter32, MibIdentifier, Bits, ObjectIdentity, NotificationType, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Counter64", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Unsigned32", "Integer32", "TimeTicks", "iso", "Counter32", "MibIdentifier", "Bits", "ObjectIdentity", "NotificationType", "IpAddress")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
cpqCluster = MibIdentifier((1, 3, 6, 1, 4, 1, 232, 15))
cpqClusterMibRev = MibIdentifier((1, 3, 6, 1, 4, 1, 232, 15, 1))
cpqClusterComponent = MibIdentifier((1, 3, 6, 1, 4, 1, 232, 15, 2))
cpqClusterTrap = MibIdentifier((1, 3, 6, 1, 4, 1, 232, 15, 3))
cpqClusterInterface = MibIdentifier((1, 3, 6, 1, 4, 1, 232, 15, 2, 1))
cpqClusterInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 232, 15, 2, 2))
cpqClusterNode = MibIdentifier((1, 3, 6, 1, 4, 1, 232, 15, 2, 3))
cpqClusterResource = MibIdentifier((1, 3, 6, 1, 4, 1, 232, 15, 2, 4))
cpqClusterInterconnect = MibIdentifier((1, 3, 6, 1, 4, 1, 232, 15, 2, 5))
cpqClusterNetwork = MibIdentifier((1, 3, 6, 1, 4, 1, 232, 15, 2, 6))
cpqClusterOsCommon = MibIdentifier((1, 3, 6, 1, 4, 1, 232, 15, 2, 1, 4))
cpqClusterMibRevMajor = MibScalar((1, 3, 6, 1, 4, 1, 232, 15, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterMibRevMajor.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterMibRevMajor.setDescription('The Major Revision level of the MIB. A change in the major revision level represents a major change in the architecture of the MIB. A change in the major revision level may indicate a significant change in the information supported and/or the meaning of the supported information. Correct interpretation of data may require a MIB document with the same major revision level.')
cpqClusterMibRevMinor = MibScalar((1, 3, 6, 1, 4, 1, 232, 15, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterMibRevMinor.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterMibRevMinor.setDescription('The Minor Revision level of the MIB. A change in the minor revision level may represent some minor additional support, no changes to any pre-existing information has occurred.')
cpqClusterMibCondition = MibScalar((1, 3, 6, 1, 4, 1, 232, 15, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("ok", 2), ("degraded", 3), ("failed", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterMibCondition.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterMibCondition.setDescription('The overall condition of the cluster represented by this MIB. This variable is the same as cpqClusterCondition in the Cluster Info Group. It is a combination of the Cluster node conditions, the resource conditions, and the network conditions as defined later in the Cluster Node group the Cluster Resource group, and the Cluster Network group. other(1) The cluster condition can not be determined. Every node condition, resource condition, and network condition is undetermined. ok(2) The cluster condition is functioning normally. Every node condition, resource condition, and network condition is ok. degraded(3) The cluster condition is degraded if at least one node condition is failed or degraded or at least one resource condition, or one network condition is degraded. failed(4) The cluster condition is failed if every node condition is failed, or at least one resource condition is failed, or at least one network condition is failed.')
cpqClusterOsCommonPollFreq = MibScalar((1, 3, 6, 1, 4, 1, 232, 15, 2, 1, 4, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cpqClusterOsCommonPollFreq.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterOsCommonPollFreq.setDescription("The Insight Agent's polling frequency. The frequency, in seconds, at which the Insight Agent requests information from the device driver. A frequency of zero (0) indicates that the Insight Agent retrieves the information upon request of a management station, it does not poll the device driver at a specific interval. If the poll frequency is zero (0) all attempts to write to this object will fail. If the poll frequency is non-zero, setting this value will change the polling frequency of the Insight Agent. Setting the poll frequency to zero (0) will always fail, an agent may also choose to fail any request to change the poll frequency to a value that would severely impact system performance.")
cpqClusterOsCommonModuleTable = MibTable((1, 3, 6, 1, 4, 1, 232, 15, 2, 1, 4, 2), )
if mibBuilder.loadTexts: cpqClusterOsCommonModuleTable.setStatus('deprecated')
if mibBuilder.loadTexts: cpqClusterOsCommonModuleTable.setDescription('A table of software modules that provide an interface to the device this MIB describes.')
cpqClusterOsCommonModuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 232, 15, 2, 1, 4, 2, 1), ).setIndexNames((0, "CPQCLUSTER-MIB", "cpqClusterOsCommonModuleIndex"))
if mibBuilder.loadTexts: cpqClusterOsCommonModuleEntry.setStatus('deprecated')
if mibBuilder.loadTexts: cpqClusterOsCommonModuleEntry.setDescription('A description of a software module that provides an interface to the device this MIB describes.')
cpqClusterOsCommonModuleIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 1, 4, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterOsCommonModuleIndex.setStatus('deprecated')
if mibBuilder.loadTexts: cpqClusterOsCommonModuleIndex.setDescription('A unique index for this module description.')
cpqClusterOsCommonModuleName = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 1, 4, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterOsCommonModuleName.setStatus('deprecated')
if mibBuilder.loadTexts: cpqClusterOsCommonModuleName.setDescription('The module name.')
cpqClusterOsCommonModuleVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 1, 4, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 5))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterOsCommonModuleVersion.setStatus('deprecated')
if mibBuilder.loadTexts: cpqClusterOsCommonModuleVersion.setDescription('The module version in XX.YY format. Where XX is the major version number and YY is the minor version number. This field will be null (size 0) string if the agent cannot provide the module version.')
cpqClusterOsCommonModuleDate = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 1, 4, 2, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(7, 7)).setFixedLength(7)).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterOsCommonModuleDate.setStatus('deprecated')
if mibBuilder.loadTexts: cpqClusterOsCommonModuleDate.setDescription('The module date. field octets contents range ===== ====== ======= ===== 1 1-2 year 0..65536 2 3 month 1..12 3 4 day 1..31 4 5 hour 0..23 5 6 minute 0..59 6 7 second 0..60 (use 60 for leap-second) This field will be set to year = 0 if the agent cannot provide the module date. The hour, minute, and second field will be set to zero (0) if they are not relevant. The year field is set with the most significant octet first.')
cpqClusterOsCommonModulePurpose = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 1, 4, 2, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterOsCommonModulePurpose.setStatus('deprecated')
if mibBuilder.loadTexts: cpqClusterOsCommonModulePurpose.setDescription('The purpose of the module described in this entry.')
cpqClusterName = MibScalar((1, 3, 6, 1, 4, 1, 232, 15, 2, 2, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cpqClusterName.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterName.setDescription('The name of the cluster.')
cpqClusterCondition = MibScalar((1, 3, 6, 1, 4, 1, 232, 15, 2, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("ok", 2), ("degraded", 3), ("failed", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterCondition.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterCondition.setDescription('The cluster condition as reported by this node. It is a combination of the Cluster node conditions, resource conditions, and network conditions as defined later in the Cluster Node group, Cluster Resource group, and Cluster Network group. other(1) The cluster condition can not be determined. Every node condition, resource condition, and network condition is undetermined. ok(2) The cluster condition is functioning normally. Every node condition, resource condition, and network condition is ok. degraded(3) The cluster condition is degraded if at least one node condition is failed or degraded or at least one resource condition, or one network condition is degraded. failed(4) The cluster condition is failed if every node condition is failed, or at least one resource condition is failed, or at least one network condition is failed.')
cpqClusterIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 232, 15, 2, 2, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterIpAddress.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterIpAddress.setDescription("The first cluster static IP address enumerated. This cluster IP address and any other cluster IP address are in the Cluster Resource Group with the resource type 'IP Address'.")
cpqClusterQuorumResource = MibScalar((1, 3, 6, 1, 4, 1, 232, 15, 2, 2, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterQuorumResource.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterQuorumResource.setDescription('The Quorum resource name for the cluster. This number is the index into the resource table which contains the Quorum resource. -1 No Quorum resource available. 0..64 Index into the resource table.')
cpqClusterMajorVersion = MibScalar((1, 3, 6, 1, 4, 1, 232, 15, 2, 2, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterMajorVersion.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterMajorVersion.setDescription('Identifies the major version number of the cluster software.')
cpqClusterMinorVersion = MibScalar((1, 3, 6, 1, 4, 1, 232, 15, 2, 2, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterMinorVersion.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterMinorVersion.setDescription('Identifies the minor version number of the cluster software.')
cpqClusterCSDVersion = MibScalar((1, 3, 6, 1, 4, 1, 232, 15, 2, 2, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterCSDVersion.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterCSDVersion.setDescription('The latest Service Pack installed on the system. If no Service Pack has been installed, the string is empty.')
cpqClusterVendorId = MibScalar((1, 3, 6, 1, 4, 1, 232, 15, 2, 2, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterVendorId.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterVendorId.setDescription('The cluster software vendor identifier information.')
cpqClusterResourceAggregateCondition = MibScalar((1, 3, 6, 1, 4, 1, 232, 15, 2, 2, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("ok", 2), ("degraded", 3), ("failed", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterResourceAggregateCondition.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterResourceAggregateCondition.setDescription('The cluster resource aggregate condition as reported by this node. This condition is derived directly from each and every Cluster resource condition as defined later in the Cluster Resource group. other(1) The condition can not be determined, which equates to each and every resource condition as undetermined. ok(2) The condition is functioning normally, which equates to each and every resource condition as ok. degraded(3) The condition is degraded if at least one resource condition is degraded. failed(4) The condition is failed if at least one resource condition is failed.')
cpqClusterNetworkAggregateCondition = MibScalar((1, 3, 6, 1, 4, 1, 232, 15, 2, 2, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("ok", 2), ("degraded", 3), ("failed", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterNetworkAggregateCondition.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterNetworkAggregateCondition.setDescription('The cluster network aggregate condition as reported by this node. This condition is derived directly from the condition of each Cluster network with a role of internal, or clientAndInternal or client as defined later in the Cluster Network group. Networks with a role of none are not considered in overall condition. other(1) The condition can not be determined, all network conditions are undetermined. ok(2) The condition is functioning normally, which equates to each and every network condition as ok. degraded(3) The condition is degraded if at least one network condition is degraded. failed(4) The condition is failed if at least one network condition is failed.')
cpqClusterNodeTable = MibTable((1, 3, 6, 1, 4, 1, 232, 15, 2, 3, 1), )
if mibBuilder.loadTexts: cpqClusterNodeTable.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterNodeTable.setDescription('A table of cluster node entries.')
cpqClusterNodeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 232, 15, 2, 3, 1, 1), ).setIndexNames((0, "CPQCLUSTER-MIB", "cpqClusterNodeIndex"))
if mibBuilder.loadTexts: cpqClusterNodeEntry.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterNodeEntry.setDescription('A description of a cluster node')
cpqClusterNodeIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterNodeIndex.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterNodeIndex.setDescription('A unique index for this node entry.')
cpqClusterNodeName = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 3, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterNodeName.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterNodeName.setDescription('The name of the node.')
cpqClusterNodeStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("nodeUp", 2), ("nodeDown", 3), ("nodePaused", 4), ("nodeJoining", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterNodeStatus.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterNodeStatus.setDescription('The current status of the node. The following values are defined: other(1) - Indicates that an error has occurred and the exact state of the node could not be determined, or the node status is unavailable. nodeUp(2) - The node is operating as an active member of a cluster. A node that is up responds to updates to the cluster database, can host and manage groups, and can maintain communication with other nodes in the cluster. nodeDown(3) - The node is trying to form or rejoin a cluster or is down. A node that is down is not an active cluster member and it may or may not be running. The Cluster Service may have started and then failed, or may have failed to start completely. nodePaused(4) - The node is operating as an active member of a cluster but cannot host any resources or resource groups,is up but cluster activity is paused. Nodes that are undergoing maintenance are typically placed in this state. nodeJoining(5) - The node is in the process of joining a cluster. This is a short lived state.')
cpqClusterNodeCondition = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 3, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("ok", 2), ("degraded", 3), ("failed", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterNodeCondition.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterNodeCondition.setDescription('The current condition of the node. The following values are defined: other(1) - The node status is unavailable, or could not be determined. ok(2) - The node status is nodeUp. degraded(3) - The node status is nodeUnavailable or nodePaused or nodeJoining. failed(4) - The node status is nodeDown.')
cpqClusterResourceTable = MibTable((1, 3, 6, 1, 4, 1, 232, 15, 2, 4, 1), )
if mibBuilder.loadTexts: cpqClusterResourceTable.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterResourceTable.setDescription('A table of resources managed by the cluster reported by this MIB.')
cpqClusterResourceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 232, 15, 2, 4, 1, 1), ).setIndexNames((0, "CPQCLUSTER-MIB", "cpqClusterResourceIndex"))
if mibBuilder.loadTexts: cpqClusterResourceEntry.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterResourceEntry.setDescription('The properties describing a resource managed by the cluster.')
cpqClusterResourceIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterResourceIndex.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterResourceIndex.setDescription('A unique index for this resource entry.')
cpqClusterResourceName = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 4, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterResourceName.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterResourceName.setDescription('The name of the resource. It must be unique within the cluster.')
cpqClusterResourceType = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 4, 1, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterResourceType.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterResourceType.setDescription("The resource type, such as 'Physical Disk', 'Generic Application', 'IP Address', 'File Share', 'Network Name', etc..")
cpqClusterResourceState = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 4, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("other", 1), ("online", 2), ("offline", 3), ("failed", 4), ("onlinePending", 5), ("offlinePending", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterResourceState.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterResourceState.setDescription("The resource's current state. The following values are defined: other(1) - Indicates that an error has occurred and the exact state of the resource could not be determined or the resource state is unavailable. online(2) - The resource is online and functioning normally. offline(3) - The resource is offline. failed(4) - The resource has failed. onlinePending(5) - The resource is in the process of coming online. offlinePending(6)- The resource is in the process of going offline.")
cpqClusterResourceOwnerNode = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 4, 1, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterResourceOwnerNode.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterResourceOwnerNode.setDescription('The node in the cluster where the group of the resource is currently online.')
cpqClusterResourcePhysId = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 4, 1, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterResourcePhysId.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterResourcePhysId.setDescription("The physical identification for resource type 'Physical Disk'. It contains the following components: storage box name, logical drive NN. where NN is a number from 0..n. It is blank for all other resource types.")
cpqClusterResourceCondition = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 4, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("ok", 2), ("degraded", 3), ("failed", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterResourceCondition.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterResourceCondition.setDescription('The resource condition. The following values are defined: other(1) - Unable to determine the resource condition. ok(2) - The resource status is online. degraded(3) - The resource status is unavailable or offline or online pending or offline pending. failed(4) - The resource status is failed.')
cpqClusterResourceDriveLetter = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 4, 1, 1, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterResourceDriveLetter.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterResourceDriveLetter.setDescription("The drive letter with semi-colon of a physical disk such as x:. Blank if the resource type is not 'Physical Disk'.")
cpqClusterResourceIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 4, 1, 1, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterResourceIpAddress.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterResourceIpAddress.setDescription("A cluster IP address expressed as xxx.xxx.xxx.xxx where xxx is a decimal number between 0 and 255. Blank if the resource type is not 'IP Address'.")
cpqClusterResourceGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 4, 1, 1, 10), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterResourceGroupName.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterResourceGroupName.setDescription('The name of the cluster group that the resource belongs to.')
cpqClusterInterconnectTable = MibTable((1, 3, 6, 1, 4, 1, 232, 15, 2, 5, 1), )
if mibBuilder.loadTexts: cpqClusterInterconnectTable.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterInterconnectTable.setDescription('A table of network interfaces used by the node for communication.')
cpqClusterInterconnectEntry = MibTableRow((1, 3, 6, 1, 4, 1, 232, 15, 2, 5, 1, 1), ).setIndexNames((0, "CPQCLUSTER-MIB", "cpqClusterInterconnectIndex"))
if mibBuilder.loadTexts: cpqClusterInterconnectEntry.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterInterconnectEntry.setDescription('The properties describing the interconnect.')
cpqClusterInterconnectIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 5, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterInterconnectIndex.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterInterconnectIndex.setDescription('Uniquely identifies the interconnect entry.')
cpqClusterInterconnectPhysId = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 5, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterInterconnectPhysId.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterInterconnectPhysId.setDescription('The physical identification of the device. For an embedded NIC the value format is as followed: 1) for embedded NIC, Embedded NIC, Base I/O Addr: <base addr> 2) Known slot number, Slot: <slot number>, Base I/O Addr: <base addr> 3) Unknown slot number, Slot: unknown, Base I/O Addr: <base addr>')
cpqClusterInterconnectTransport = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 5, 1, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterInterconnectTransport.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterInterconnectTransport.setDescription('The network transport used by the interconnect. For example, Tcpip.')
cpqClusterInterconnectAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 5, 1, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterInterconnectAddress.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterInterconnectAddress.setDescription('The address used by the interconnect expressed in the format specified by the transport type.')
cpqClusterInterconnectNetworkName = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 5, 1, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterInterconnectNetworkName.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterInterconnectNetworkName.setDescription('This interconnect is a part of this network. The network name is used to correlate information in the network table.')
cpqClusterInterconnectNodeName = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 5, 1, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterInterconnectNodeName.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterInterconnectNodeName.setDescription('The name of the node in which the network interface is installed.')
cpqClusterInterconnectRole = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 5, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 1), ("client", 2), ("internal", 3), ("clientAndInternal", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterInterconnectRole.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterInterconnectRole.setDescription('The communications role of the interconnect in the cluster. The following values are defined: none(1) - The interconnect is not used by the cluster. client(2) - The interconnect is used to connect client systems to the cluster. internal(3) - The interconnect is used to carry internal cluster communication. clientAndInternal(4) - The interconnect is used to connect client systems and for internal cluster communication.')
cpqClusterNetworkTable = MibTable((1, 3, 6, 1, 4, 1, 232, 15, 2, 6, 1), )
if mibBuilder.loadTexts: cpqClusterNetworkTable.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterNetworkTable.setDescription('A table of networks available for communication with other nodes or clients.')
cpqClusterNetworkEntry = MibTableRow((1, 3, 6, 1, 4, 1, 232, 15, 2, 6, 1, 1), ).setIndexNames((0, "CPQCLUSTER-MIB", "cpqClusterNetworkIndex"))
if mibBuilder.loadTexts: cpqClusterNetworkEntry.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterNetworkEntry.setDescription('The properties describing the network.')
cpqClusterNetworkIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 6, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterNetworkIndex.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterNetworkIndex.setDescription('Uniquely identifies the network entry.')
cpqClusterNetworkName = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 6, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterNetworkName.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterNetworkName.setDescription('The text name of the network.')
cpqClusterNetworkAddressMask = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 6, 1, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterNetworkAddressMask.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterNetworkAddressMask.setDescription('The network IP address mask expressed as xxx.xxx.xxx.xxx where xxx is a decimal number between 0 and 255.')
cpqClusterNetworkDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 6, 1, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterNetworkDescription.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterNetworkDescription.setDescription('The text description of the network.')
cpqClusterNetworkRole = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 6, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 1), ("client", 2), ("internal", 3), ("clientAndInternal", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterNetworkRole.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterNetworkRole.setDescription('The communications role of the network in the cluster. The following values are defined: none(1) - The network is not used by the cluster. client(2) - The network is used to connect client systems to the cluster. internal(3) - The network is used to carry internal cluster communication. clientAndInternal(4) - The network is used to connect client systems and for internal cluster communication.')
cpqClusterNetworkState = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 6, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("online", 2), ("offline", 3), ("partitioned", 4), ("unavailable", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterNetworkState.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterNetworkState.setDescription("The network's current state. The following values are defined: other(1) - Indicates that an error has occurred and the exact state of the network could not be determined. online(2) - The network is operational; all of the nodes in the cluster can communicate. offline(3) - The network is not operational; none of the nodes on the network can communicate. partitioned(4) - The network is operational, but two or more nodes on the network cannot communicate. Typically a path-specific problem has occurred. unavailable(5) - The network is unavailable to the cluster because the network's role is 'none'.")
cpqClusterNetworkCondition = MibTableColumn((1, 3, 6, 1, 4, 1, 232, 15, 2, 6, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("ok", 2), ("degraded", 3), ("failed", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cpqClusterNetworkCondition.setStatus('mandatory')
if mibBuilder.loadTexts: cpqClusterNetworkCondition.setDescription('The network condition uses cpqClusterNetworkState to determine the network condition. The following values are defined: other(1) - The network state indicates that an error has occurred and the exact state of the network could not be determined or the network state is unavailable. ok(2) - The network state is online or unavailable. degraded(3) - The network state is partitioned. failed(4) - The network state is offline.')
cpqClusterDegraded = NotificationType((1, 3, 6, 1, 4, 1, 232) + (0,15001)).setObjects(("SNMPv2-MIB", "sysName"), ("CPQHOST-MIB", "cpqHoTrapFlags"), ("CPQCLUSTER-MIB", "cpqClusterName"))
if mibBuilder.loadTexts: cpqClusterDegraded.setDescription('This trap will be sent any time the condition of the cluster becomes degraded.')
cpqClusterFailed = NotificationType((1, 3, 6, 1, 4, 1, 232) + (0,15002)).setObjects(("SNMPv2-MIB", "sysName"), ("CPQHOST-MIB", "cpqHoTrapFlags"), ("CPQCLUSTER-MIB", "cpqClusterName"))
if mibBuilder.loadTexts: cpqClusterFailed.setDescription('This trap will be sent any time the condition of the cluster becomes failed.')
cpqClusterNodeDegraded = NotificationType((1, 3, 6, 1, 4, 1, 232) + (0,15003)).setObjects(("SNMPv2-MIB", "sysName"), ("CPQHOST-MIB", "cpqHoTrapFlags"), ("CPQCLUSTER-MIB", "cpqClusterNodeName"))
if mibBuilder.loadTexts: cpqClusterNodeDegraded.setDescription('This trap will be sent any time the condition of a node in the cluster becomes degraded. User Action: Make a note of the cluster node name then check the node for the cause of the degraded condition.')
cpqClusterNodeFailed = NotificationType((1, 3, 6, 1, 4, 1, 232) + (0,15004)).setObjects(("SNMPv2-MIB", "sysName"), ("CPQHOST-MIB", "cpqHoTrapFlags"), ("CPQCLUSTER-MIB", "cpqClusterNodeName"))
if mibBuilder.loadTexts: cpqClusterNodeFailed.setDescription('This trap will be sent any time the condition of a node in the cluster becomes failed. User Action: Make a note of the cluster node name then check the node for the cause of the failure.')
cpqClusterResourceDegraded = NotificationType((1, 3, 6, 1, 4, 1, 232) + (0,15005)).setObjects(("SNMPv2-MIB", "sysName"), ("CPQHOST-MIB", "cpqHoTrapFlags"), ("CPQCLUSTER-MIB", "cpqClusterResourceName"))
if mibBuilder.loadTexts: cpqClusterResourceDegraded.setDescription('This trap will be sent any time the condition of a cluster resource becomes degraded. User Action: Make a note of the cluster resource name then check the resource for the cause of the degraded condition.')
cpqClusterResourceFailed = NotificationType((1, 3, 6, 1, 4, 1, 232) + (0,15006)).setObjects(("SNMPv2-MIB", "sysName"), ("CPQHOST-MIB", "cpqHoTrapFlags"), ("CPQCLUSTER-MIB", "cpqClusterResourceName"))
if mibBuilder.loadTexts: cpqClusterResourceFailed.setDescription('This trap will be sent any time the condition of a cluster resource becomes failed. User Action: Make a note of the cluster resource name then check the resource for the cause of the failure.')
cpqClusterNetworkDegraded = NotificationType((1, 3, 6, 1, 4, 1, 232) + (0,15007)).setObjects(("SNMPv2-MIB", "sysName"), ("CPQHOST-MIB", "cpqHoTrapFlags"), ("CPQCLUSTER-MIB", "cpqClusterNetworkName"))
if mibBuilder.loadTexts: cpqClusterNetworkDegraded.setDescription('This trap will be sent any time the condition of a cluster network becomes degraded. User Action: Make a note of the cluster network name then check the network for the cause of the degraded condition.')
cpqClusterNetworkFailed = NotificationType((1, 3, 6, 1, 4, 1, 232) + (0,15008)).setObjects(("SNMPv2-MIB", "sysName"), ("CPQHOST-MIB", "cpqHoTrapFlags"), ("CPQCLUSTER-MIB", "cpqClusterNetworkName"))
if mibBuilder.loadTexts: cpqClusterNetworkFailed.setDescription('This trap will be sent any time the condition of a cluster network becomes failed. User Action: Make a note of the cluster network name then check the network for the cause of the failure.')
mibBuilder.exportSymbols("CPQCLUSTER-MIB", cpqClusterOsCommonModuleVersion=cpqClusterOsCommonModuleVersion, cpqClusterOsCommon=cpqClusterOsCommon, cpqClusterCondition=cpqClusterCondition, cpqClusterMinorVersion=cpqClusterMinorVersion, cpqClusterMajorVersion=cpqClusterMajorVersion, cpqClusterMibRevMinor=cpqClusterMibRevMinor, cpqClusterResourceOwnerNode=cpqClusterResourceOwnerNode, cpqClusterMibRev=cpqClusterMibRev, cpqClusterOsCommonModuleTable=cpqClusterOsCommonModuleTable, cpqClusterOsCommonModuleDate=cpqClusterOsCommonModuleDate, cpqClusterInterconnectEntry=cpqClusterInterconnectEntry, cpqClusterNodeEntry=cpqClusterNodeEntry, cpqClusterNetworkIndex=cpqClusterNetworkIndex, cpqClusterIpAddress=cpqClusterIpAddress, cpqClusterInterconnectNetworkName=cpqClusterInterconnectNetworkName, cpqClusterNodeName=cpqClusterNodeName, cpqClusterResourcePhysId=cpqClusterResourcePhysId, cpqClusterDegraded=cpqClusterDegraded, cpqClusterTrap=cpqClusterTrap, cpqClusterNetworkDegraded=cpqClusterNetworkDegraded, cpqClusterMibRevMajor=cpqClusterMibRevMajor, cpqClusterNetwork=cpqClusterNetwork, cpqClusterResourceGroupName=cpqClusterResourceGroupName, cpqClusterFailed=cpqClusterFailed, cpqClusterNetworkEntry=cpqClusterNetworkEntry, cpqClusterInterface=cpqClusterInterface, cpqClusterNetworkFailed=cpqClusterNetworkFailed, cpqClusterResourceDegraded=cpqClusterResourceDegraded, cpqClusterNodeDegraded=cpqClusterNodeDegraded, cpqClusterNetworkTable=cpqClusterNetworkTable, cpqClusterInterconnectPhysId=cpqClusterInterconnectPhysId, cpqClusterResourceName=cpqClusterResourceName, cpqClusterNodeCondition=cpqClusterNodeCondition, cpqClusterInterconnectTransport=cpqClusterInterconnectTransport, cpqClusterNetworkName=cpqClusterNetworkName, cpqClusterOsCommonModulePurpose=cpqClusterOsCommonModulePurpose, cpqClusterNode=cpqClusterNode, cpqClusterName=cpqClusterName, cpqClusterNodeStatus=cpqClusterNodeStatus, cpqClusterOsCommonPollFreq=cpqClusterOsCommonPollFreq, cpqClusterResourceIpAddress=cpqClusterResourceIpAddress, cpqClusterNetworkAddressMask=cpqClusterNetworkAddressMask, cpqClusterResourceAggregateCondition=cpqClusterResourceAggregateCondition, cpqClusterOsCommonModuleIndex=cpqClusterOsCommonModuleIndex, cpqClusterResourceDriveLetter=cpqClusterResourceDriveLetter, cpqCluster=cpqCluster, cpqClusterNodeIndex=cpqClusterNodeIndex, cpqClusterInterconnect=cpqClusterInterconnect, cpqClusterResourceIndex=cpqClusterResourceIndex, cpqClusterResourceType=cpqClusterResourceType, cpqClusterNetworkState=cpqClusterNetworkState, cpqClusterNodeFailed=cpqClusterNodeFailed, cpqClusterInterconnectNodeName=cpqClusterInterconnectNodeName, cpqClusterInterconnectAddress=cpqClusterInterconnectAddress, cpqClusterResourceCondition=cpqClusterResourceCondition, cpqClusterInterconnectRole=cpqClusterInterconnectRole, cpqClusterQuorumResource=cpqClusterQuorumResource, cpqClusterResourceState=cpqClusterResourceState, cpqClusterInfo=cpqClusterInfo, cpqClusterNetworkCondition=cpqClusterNetworkCondition, cpqClusterResourceFailed=cpqClusterResourceFailed, cpqClusterCSDVersion=cpqClusterCSDVersion, cpqClusterNetworkDescription=cpqClusterNetworkDescription, cpqClusterMibCondition=cpqClusterMibCondition, cpqClusterOsCommonModuleEntry=cpqClusterOsCommonModuleEntry, cpqClusterNetworkAggregateCondition=cpqClusterNetworkAggregateCondition, cpqClusterOsCommonModuleName=cpqClusterOsCommonModuleName, cpqClusterInterconnectIndex=cpqClusterInterconnectIndex, cpqClusterVendorId=cpqClusterVendorId, cpqClusterResource=cpqClusterResource, cpqClusterInterconnectTable=cpqClusterInterconnectTable, cpqClusterComponent=cpqClusterComponent, cpqClusterNetworkRole=cpqClusterNetworkRole, cpqClusterNodeTable=cpqClusterNodeTable, cpqClusterResourceEntry=cpqClusterResourceEntry, cpqClusterResourceTable=cpqClusterResourceTable)
|
#!/usr/bin/env python
f = open('/Users/kosta/dev/advent-of-code-17/day10/input.txt')
lengths = list(map(int, f.readline().split(',')))
hash_list = list(range(256))
skip = 0
cur_index = 0
for length in lengths:
if cur_index + length > len(hash_list):
sub_list = hash_list[cur_index:]
sub_list.extend(hash_list[:cur_index + length - len(hash_list)])
sub_list.reverse()
hash_list[cur_index:] = sub_list[:len(hash_list) - cur_index]
hash_list[:cur_index + length - len(hash_list)] = sub_list[(len(hash_list) - cur_index):]
cur_index = (cur_index + length + skip) % len(hash_list)
else:
sub_list = hash_list[cur_index:cur_index+length]
sub_list.reverse()
hash_list[cur_index:cur_index+length] = sub_list
cur_index += length + skip
skip+=1
result = hash_list[0] * hash_list[1]
print(result) |
def softmax(x):
t = np.exp(x)
return t/t.sum()
q_relu = softmax(C @ relu(A @ x + b) + d)
q_sigmoid = softmax(C @ sigmoid(A @ x + b) + d) |
"""Image-to-text implementation based on http://arxiv.org/abs/1411.4555.
"Show and Tell: A Neural Image Caption Generator"
Oriol Vinyals, Alexander Toshev, Samy Bengio, Dumitru Erhan
"""
class ShowAndTellModel(object):
"""Image-to-text implementation based on http://arxiv.org/abs/1411.4555.
"Show and Tell: A Neural Image Caption Generator"
Oriol Vinyals, Alexander Toshev, Samy Bengio, Dumitru Erhan
"""
def __init__(self, config, mode, train_inception=False):
"""Basic setup.
Args:
config: Object containing configuration parameters.
mode: "train", "eval" or "inference".
train_inception: Whether the inception submodel variables are trainable.
"""
assert mode in ["train", "eval", "inference"]
self.config = config
self.mode = mode
self.train_inception = train_inception
self.reader = tf.TFRecordReader()
self.initializer = tf.random_uniform_initializer(minval=-self.config.initializer_scale, maxval=self.config.initializer_scale)
self.images = None
self.input_seqs = None
self.target_seqs = None
self.input_mask = None
self.image_embeddings = None
self.seq_embeddings = None
self.total_loss = None
self.target_cross_entropy_losses = None
self.target_cross_entropy_loss_weights = None
self.inception_variables = []
self.init_fn = None
self.global_step = None
def is_training(self):
"""Returns true if the model is built for training mode."""
return self.mode == "train"
def process_image(self, encoded_image, thread_id=0):
"""Decodes and processes an image string.
Args:
encoded_image: A scalar string Tensor; the encoded image.
thread_id: Preprocessing thread id used to select the ordering of color
distortions.
Returns:
A float32 Tensor of shape [height, width, 3]; the processed image.
"""
return image_processing.process_image(encoded_image, is_training=self.is_training(), height=self.config.image_height, width=self.config.image_width, thread_id=thread_id, image_format=self.config.image_format)
def build_inputs(self):
"""Input prefetching, preprocessing and batching.
Outputs:
self.images
self.input_seqs
self.target_seqs (training and eval only)
self.input_mask (training and eval only)
"""
if self.mode == "inference":
image_feed = tf.placeholder(dtype=tf.string, shape=[], name="image_feed")
input_feed = tf.placeholder(dtype=tf.int64, shape=[None], name="input_feed")
images = tf.expand_dims(self.process_image(image_feed), 0)
input_seqs = tf.expand_dims(input_feed, 1)
target_seqs = None
input_mask = None
else:
input_queue = input_ops.prefetch_input_data(self.reader, self.config.input_file_pattern, is_training=self.is_training(), batch_size=self.config.batch_size, values_per_shard=self.config.values_per_input_shard, input_queue_capacity_factor=self.config.input_queue_capacity_factor, num_reader_threads=self.config.num_input_reader_threads)
assert self.config.num_preprocess_threads % 2 == 0
images_and_captions = []
for thread_id in range(self.config.num_preprocess_threads):
serialized_sequence_example = input_queue.dequeue()
encoded_image, caption = input_ops.parse_sequence_example(serialized_sequence_example, image_feature=self.config.image_feature_name, caption_feature=self.config.caption_feature_name)
image = self.process_image(encoded_image, thread_id=thread_id)
images_and_captions.append([image, caption])
queue_capacity = 2 * self.config.num_preprocess_threads * self.config.batch_size
images, input_seqs, target_seqs, input_mask = input_ops.batch_with_dynamic_pad(images_and_captions, batch_size=self.config.batch_size, queue_capacity=queue_capacity)
self.images = images
self.input_seqs = input_seqs
self.target_seqs = target_seqs
self.input_mask = input_mask
def build_image_embeddings(self):
"""Builds the image model subgraph and generates image embeddings.
Inputs:
self.images
Outputs:
self.image_embeddings
"""
inception_output = image_embedding.inception_v3(self.images, trainable=self.train_inception, is_training=self.is_training())
self.inception_variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope="InceptionV3")
with tf.variable_scope("image_embedding") as scope:
image_embeddings = tf.contrib.layers.fully_connected(inputs=inception_output, num_outputs=self.config.embedding_size, activation_fn=None, weights_initializer=self.initializer, biases_initializer=None, scope=scope)
tf.constant(self.config.embedding_size, name="embedding_size")
self.image_embeddings = image_embeddings
def build_seq_embeddings(self):
"""Builds the input sequence embeddings.
Inputs:
self.input_seqs
Outputs:
self.seq_embeddings
"""
with tf.variable_scope("seq_embedding"), tf.device("/cpu:0"):
embedding_map = tf.get_variable(name="map", shape=[self.config.vocab_size, self.config.embedding_size], initializer=self.initializer)
seq_embeddings = tf.nn.embedding_lookup(embedding_map, self.input_seqs)
self.seq_embeddings = seq_embeddings
def build_model(self):
"""Builds the model.
Inputs:
self.image_embeddings
self.seq_embeddings
self.target_seqs (training and eval only)
self.input_mask (training and eval only)
Outputs:
self.total_loss (training and eval only)
self.target_cross_entropy_losses (training and eval only)
self.target_cross_entropy_loss_weights (training and eval only)
"""
lstm_cell = tf.contrib.rnn.BasicLSTMCell(num_units=self.config.num_lstm_units, state_is_tuple=True)
if self.mode == "train":
lstm_cell = tf.contrib.rnn.DropoutWrapper(lstm_cell, input_keep_prob=self.config.lstm_dropout_keep_prob, output_keep_prob=self.config.lstm_dropout_keep_prob)
with tf.variable_scope("lstm", initializer=self.initializer) as lstm_scope:
zero_state = lstm_cell.zero_state(batch_size=self.image_embeddings.get_shape()[0], dtype=tf.float32)
_, initial_state = lstm_cell(self.image_embeddings, zero_state)
lstm_scope.reuse_variables()
if self.mode == "inference":
tf.concat(axis=1, values=initial_state, name="initial_state")
state_feed = tf.placeholder(dtype=tf.float32, shape=[None, sum(lstm_cell.state_size)], name="state_feed")
state_tuple = tf.split(value=state_feed, num_or_size_splits=2, axis=1)
lstm_outputs, state_tuple = lstm_cell(inputs=tf.squeeze(self.seq_embeddings, axis=[1]), state=state_tuple)
tf.concat(axis=1, values=state_tuple, name="state")
else:
sequence_length = tf.reduce_sum(self.input_mask, 1)
lstm_outputs, _ = tf.nn.dynamic_rnn(cell=lstm_cell, inputs=self.seq_embeddings, sequence_length=sequence_length, initial_state=initial_state, dtype=tf.float32, scope=lstm_scope)
lstm_outputs = tf.reshape(lstm_outputs, [-1, lstm_cell.output_size])
with tf.variable_scope("logits") as logits_scope:
logits = tf.contrib.layers.fully_connected(inputs=lstm_outputs, num_outputs=self.config.vocab_size, activation_fn=None, weights_initializer=self.initializer, scope=logits_scope)
if self.mode == "inference":
tf.nn.softmax(logits, name="softmax")
else:
targets = tf.reshape(self.target_seqs, [-1])
weights = tf.to_float(tf.reshape(self.input_mask, [-1]))
losses = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=targets, logits=logits)
batch_loss = tf.div(tf.reduce_sum(tf.multiply(losses, weights)), tf.reduce_sum(weights), name="batch_loss")
tf.losses.add_loss(batch_loss)
total_loss = tf.losses.get_total_loss()
tf.summary.scalar("losses/batch_loss", batch_loss)
tf.summary.scalar("losses/total_loss", total_loss)
for var in tf.trainable_variables():
tf.summary.histogram("parameters/" + var.op.name, var)
self.total_loss = total_loss
self.target_cross_entropy_losses = losses
self.target_cross_entropy_loss_weights = weights
def setup_inception_initializer(self):
"""Sets up the function to restore inception variables from checkpoint."""
if self.mode != "inference":
saver = tf.train.Saver(self.inception_variables)
def restore_fn(sess):
tf.logging.info("Restoring Inception variables from checkpoint file %s", self.config.inception_checkpoint_file)
saver.restore(sess, self.config.inception_checkpoint_file)
self.init_fn = restore_fn
def setup_global_step(self):
"""Sets up the global step Tensor."""
global_step = tf.Variable(initial_value=0, name="global_step", trainable=False, collections=[tf.GraphKeys.GLOBAL_STEP, tf.GraphKeys.GLOBAL_VARIABLES])
self.global_step = global_step
def build(self):
"""Creates all ops for training and evaluation."""
self.build_inputs()
self.build_image_embeddings()
self.build_seq_embeddings()
self.build_model()
self.setup_inception_initializer()
self.setup_global_step() |
# Filters and the expression register are two really cool ways of calling arbitrary code from vim.
# Filters are just anything that takes your text via stdin and gives you something via stdout
# Filters can be invoked via `!{motion}` or `!` while selecting, and can call arbitrary scripts
# Examples with either `!}` or `v}!`:
# - !grep cat
# - !sed s/dog/cat/
# - !sed s/cat/dog/
# - !echo foo
#
# This works with arbitrary scripts (do_stuff_to_my_code.sh, print_funny_comment.sh, etc) as well!
"The quick brown fox jumps over the lazy dog"
"The quick brown fox jumps over the lazy dog"
"The quick brown fox jumps over the lazy cat"
"The quick brown fox jumps over the lazy dog"
# Expression registers are similar but not quite--They are for evaluating arbitrary vimscript expressions. This MAY
# include a system() that shells out to something external, but probably not the greatest idea. Like other registers,
# you can access the expression register via <CTRL-r>--In this case, `<CTRL-r>=`.
# Ex: `<CTRL-r>=1+1<CR>` from insert mode will print '2'
|
#encoding:utf-8
subreddit = 'india'
t_channel = '@r_indiaa'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
"""
Problem:
There are three types of edits that can be performed on strings: insert
a character, remove a character, or replace a character. Given two
strings, write a function to check if they are one edit (or zero edits)
away.
Implementation:
An initial solution might check for all three cases separately. In my
solution, I decided to go with using the ASCII values of the letters
to determine whether they were within the edit distance. This worked
very well for the insertion and deletion cases, but failed for
replacement.
For replacement, we have to add the letters of each string into sets.
We then take the set difference. If the set difference has one or no
characters remaining, then we know we're within one replacement.
Otherwise, we would have to replace more than one character, and we
can return false.
Efficiency:
Time: O(A + B)
Space: O(A + B)
"""
def ord_sum(string: str) -> int:
"""
Sum the ASCII values of the characters of a passed string.
Args:
string (str): The string whose ASCII values we are summing.
Returns:
int: The sum of each letter's ASCII value.
"""
return sum([ord(c) for c in string])
def one_away(str1: str, str2: str) -> bool:
"""
Check if the first string is at most one 'edit' away from the second.
An 'edit' is defined as a character insertion, deletion,
or replacement.
Args:
str1 (str): The first string we are checking.
str2 (str): The second string we are checking.
Returns:
bool: True if string one is at most one 'edit' away from the other.
"""
if abs(len(str1) - len(str2)) > 1:
return False
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_values = {ord(c) for c in alphabet}
str1_value = ord_sum(str1)
str2_value = ord_sum(str2)
difference = abs(str1_value - str2_value)
# The strings are the same.
if difference == 0:
return True
# The strings are one insertion or deletion apart.
if difference in ascii_values:
return True
# The strings are one replacement apart.
s1_chars = {c for c in str1}
s2_chars = {c for c in str2}
return len(s1_chars - s2_chars) <= 1
# Zero edits
assert one_away('pale', 'pale')
# Removal
assert one_away('pale', 'ple')
# Insertion
assert one_away('pales', 'pale')
# Replacement
assert one_away('pale', 'bale')
# Two replacements apart
assert not one_away('pale', 'bake')
# One string is two characters longer
assert not one_away('palest', 'bake')
|
#Write a program that reads the words in words.txt and stores them as keys in a dictionary.
#It doesn’t matter what the values are. Then you can use the in operator as a fast way
#to check whether a string is in the dictionary.
name = input("Enter file:")
if len(name) < 1:
name = "text.txt"
handle = open(name)
counts = dict()
for line in handle:
words = list(line.split())
for word in words:
counts[word] = counts.get(word,0) + 1
print(counts)
key = input ("Enter key: ")
if key in counts:
x = counts[key]
print ("The key", key, "opens value", x)
else :
x = 0
print ("Key not in counts")
|
microcode = '''
def macroop VCVTSD2SS_XMM_XMM {
cvtf2f xmm0, xmm0m, destSize=4, srcSize=8, ext=Scalar
movfph2h xmm0, xmm0v, dataSize=4
movfp xmm1, xmm1v, dataSize=8
vclear dest=xmm2, destVL=16
};
def macroop VCVTSD2SS_XMM_M {
ldfp ufp1, seg, sib, disp, dataSize=8
cvtf2f xmm0, ufp1, destSize=4, srcSize=8, ext=Scalar
movfph2h xmm0, xmm0v, dataSize=4
movfp xmm1, xmm1v, dataSize=8
vclear dest=xmm2, destVL=16
};
def macroop VCVTSD2SS_XMM_P {
rdip t7
ldfp ufp1, seg, riprel, disp, dataSize=8
cvtf2f xmm0, ufp1, destSize=4, srcSize=8, ext=Scalar
movfph2h xmm0, xmm0v, dataSize=4
movfp xmm1, xmm1v, dataSize=8
vclear dest=xmm2, destVL=16
};
''' |
# --- Day 2: I Was Told There Would Be No Math ---
def createLineList(input):
lineList = [line.rstrip('\r\n') for line in open(input)]
return lineList
def createDimList(lines):
dimList = []
for L in lines:
dim = L.split("x")
for i in range(0, len(dim)):
dim[i] = int(dim[i])
dimList.append(dim)
return dimList
def createAreaList(dimensions):
areaList = []
for d in dimensions:
lw = d[0] * d[1]
wh = d[1] * d[2]
hl = d[2] * d[0]
slack = min(lw, wh, hl)
area = 2 * lw + 2 * wh + 2 * hl + slack
areaList.append(area)
return areaList
def createRibbonList(dimensions):
lenList = []
for d in dimensions:
l = d[0]
w = d[1]
h = d[2]
ribbonLen = l * 2 + w * 2 + h * 2 - max(l, w, h) * 2
bowLen = l * w * h
totalLen = ribbonLen + bowLen
lenList.append(totalLen)
return lenList
line_list = createLineList("input.txt")
dim_list = createDimList(line_list)
area_list = createAreaList(dim_list)
ribbon_list = createRibbonList(dim_list)
print("The total amount of wrapping paper required is " + str(sum(area_list)) + " square feet.")
print("The total amount of ribbons required is " + str(sum(ribbon_list)) + " feet.")
|
"""
Problem:
Write a function that returns the bitwise AND of all integers between M and N,
inclusive.
"""
def bitwise_and_on_range(start: int, end: int) -> int:
# using naive approach
result = start
for num in range(start + 1, end + 1):
result = result & num
return result
if __name__ == "__main__":
print(bitwise_and_on_range(3, 4))
print(bitwise_and_on_range(5, 6))
print(bitwise_and_on_range(126, 127))
print(bitwise_and_on_range(127, 215))
print(bitwise_and_on_range(129, 215))
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(1)
"""
|
__author__ = 'burakks41'
line1 = input().split()
line2 = input().split()
flowers = int(line1[0])
persons = int(line1[1])
person = [0] * persons
flowers_cost = sorted([int(n) for n in line2],reverse=True)
sum = 0
for i in range(flowers):
x, person[i % persons] = person[i % persons], person[i % persons] + 1
sum += flowers_cost[i] * (x+1)
print(sum)
|
"""
返回字符串中第一个不重复的字符
输入:ABCACDBEFD
输出:E
"""
str01="ABCACDBEFD"
for i in str01:
if str01.count(i)==1:
print(i)
break
# def not_repead(str01):
# for i in str01:
# if str01.count(i) == 1:
# return i
#
# res=not_repead("ABCACDBEFD")
# print(res) |
# You are given an array of non-negative integers numbers. You are allowed to choose any number from this array and swap any two digits in it. If after the swap operation the number contains leading zeros, they can be omitted and not considered (eg: 010 will be considered just 10).
# Your task is to check whether it is possible to apply the swap operation at most once, so that the elements of the resulting array are strictly increasing.
# Example
# For numbers = [1, 5, 10, 20], the output should be makeIncreasing(numbers) = true.
# The initial array is already strictly increasing, so no actions are required.
# For numbers = [1, 3, 900, 10], the output should be makeIncreasing(numbers) = true.
# By choosing numbers[2] = 900 and swapping its first and third digits, the resulting number 009 is considered to be just 9. So the updated array will look like [1, 3, 9, 10], which is strictly increasing.
# For numbers = [13, 31, 30], the output should be makeIncreasing(numbers) = false.
# The initial array elements are not increasing.
# By swapping the digits of numbers[0] = 13, the array becomes [31, 31, 30] which is not strictly increasing;
# By swapping the digits of numbers[1] = 31, the array becomes [13, 13, 30] which is not strictly increasing;
# By swapping the digits of numbers[2] = 30, the array becomes [13, 31, 3] which is not strictly increasing;
# So, it's not possible to obtain a strictly increasing array, and the answer is false.
def compare(arr1, arr2):
store = []
for i in range(len(arr1)):
if arr1[i] != arr2[i]:
store.append(i)
return store
def getOptions(str):
store = []
for i in range(len(str) - 1):
store.append(int(str[i + 1:] + str[:i + 1]))
return store
def check(i, arr):
curr = str(arr[i])
options = getOptions(curr)
if i == 0:
for v in options:
if v < arr[i + 1]:
return True
elif i == len(arr) - 1:
for v in options:
if v > arr[i - 1]:
return True
else:
for v in options:
if v > arr[i - 1] and v < arr[i + 1]:
return True
return False
def makeIncreasing(numbers):
b = sorted(numbers)
store = compare(numbers, b)
print(store)
if len(store) > 2 and store[-1] - store[0] != len(store) - 1:
return False
if len(store) == 0:
return True
if check(store[0], numbers) or check(store[1], numbers):
return True
else:
return False
|
def balanced_split_exists(arr):
if len(arr) < 2 or sum(arr) % 2 != 0:
return False
arr.sort() # n log n
l, r = 0, len(arr) - 1
left_sum, right_sum = arr[l], arr[r]
while l <= r:
if arr[l] >= arr[r]:
return False
if left_sum < right_sum:
l += 1
left_sum += arr[l]
elif right_sum < left_sum:
r -= 1
right_sum += arr[r]
else:
l += 1
r -= 1
left_sum += arr[l]
right_sum += arr[r]
return True
# Test cases:
print(balanced_split_exists([5, 5]) == False)
print(balanced_split_exists([1, 5, 7, 1]) == True)
print(balanced_split_exists([12, 7, 6, 7, 6]) == False)
print(balanced_split_exists([2, 1, 2, 5]) == True)
print(balanced_split_exists([3, 6, 3, 4, 4]) == False)
print(balanced_split_exists([]) == False)
print(balanced_split_exists([0]) == False)
print(balanced_split_exists([1, 5, 4]) == True)
print(balanced_split_exists([5, 1, 6, 5, 5]) == False)
print(balanced_split_exists([0, 1, 0, 2, 3, 4]) == False)
print(balanced_split_exists([0, 1, 4, 4, 2, 3]) == False)
print(balanced_split_exists([1, 1, 1, 1, 1, 2, 3]) == True)
print(balanced_split_exists([1, 1, 1, 1, 1, 2, 3, 4]) == True)
print(balanced_split_exists([1, 1, 1, 1, 1, 2, 2, 2, 3, 4, 4]) == True)
print(balanced_split_exists([4, 4, 4, 4, 4, 4, 8, 8, 8]) == True)
print(balanced_split_exists([5, 7, 20, 12, 5, 7, 6, 14, 5, 5, 6]) == True)
print(balanced_split_exists([5, 7, 20, 12, 5, 7, 6, 7, 14, 5, 5, 6]) == False)
print(balanced_split_exists([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) == False)
|
def get_hours_since_midnight(total_seconds):
hours = total_seconds // 3600
return hours
total_seconds = int(input('Enter a number of seconds: '))
hours = get_hours_since_midnight(total_seconds)
format(hours,'02d')
def get_minutes(total_seconds):
minutes = ( total_seconds % 3600)
minutes //= 60
return minutes
minutes = get_minutes(total_seconds)
format(minutes, '02d')
def get_seconds(total_seconds, minutes):
seconds = (total_seconds % 3600) % 60
return seconds
seconds = get_seconds(total_seconds, minutes)
print('The time since midnight is %02d:%02d:%0d' %(hours,minutes,seconds))
|
# 常量性质的东西都放到这里
# 普通脚本只放功能性的东西
domains = {
'JP':'https://www.amazon.co.jp',
'UK':'https://www.amazon.co.uk',
'ES':'https://www.amazon.es',
'FR':'https://www.amazon.fr',
'US':'https://www.amazon.com',
'IT':'https://www.amazon.it',
'DE':'https://www.amazon.de',
'CA':'https://www.amazon.ca',
'AU':'https://www.amazon.com.au',
}
listing_urls = {
'JP':'https://www.amazon.co.jp/dp/{}',
'UK':'https://www.amazon.co.uk/dp/{}',
'ES':'https://www.amazon.es/dp/{}',
'FR':'https://www.amazon.fr/dp/{}',
'US':'https://www.amazon.com/dp/{}',
'IT':'https://www.amazon.it/dp/{}',
'DE':'https://www.amazon.de/dp/{}',
'CA':'https://www.amazon.ca/dp/{}',
'AU':'https://www.amazon.com.au/dp/{}',
}
BASE_URL = '/product-reviews/{}/ref=cm_cr_arp_d_viewopt_srt?ie=UTF8&showViewpoints=1&filterByStar=critical&pageNumber=1&sortBy=recent'
|
# Copyright (C) 2018-present [email protected]. All rights reserved.
# Distributed under the terms and conditions of the Apache License.
# See accompanying files LICENSE.
CSHARP_MANAGER_TEMPLATE = """
public class %s
{
public const char TABUGEN_CSV_SEP = '%s'; // CSV field delimiter
public const char TABUGEN_CSV_QUOTE = '"'; // CSV field quote
public const char TABUGEN_ARRAY_DELIM = '%s'; // array item delimiter
public const char TABUGEN_MAP_DELIM1 = '%s'; // map item delimiter
public const char TABUGEN_MAP_DELIM2 = '%s'; // map key-value delimiter
// self-defined boolean value parse
public static bool ParseBool(string text)
{
if (text == null || text.Length == 0) {
return false;
}
return string.Equals(text, "1") ||
string.Equals(text, "Y") ||
string.Equals(text, "ON");
}
"""
|
brd = {
'name': ('Raspberry Pi B+/2'),
'port': {
'rpigpio': {
'gpio' : {
# BCM/Functional RPi pin names.
'bcm2_sda' : '3',
'bcm3_scl' : '5',
'bcm4_gpclk0': '7',
'bcm17' : '11',
'bcm27_pcm_d': '13',
'bcm22' : '15',
'bcm10_mosi' : '19',
'bcm9_miso' : '21',
'bcm11_sclk' : '23',
'bcm5' : '29',
'bcm6' : '31',
'bcm13' : '33',
'bcm19_miso' : '35',
'bcm26' : '37',
'bcm21_sclk' : '40',
'bcm20_mosi' : '38',
'bcm16' : '36',
'bcm12' : '32',
'bcm7_ce1' : '26',
'bcm8_ce0' : '24',
'bcm25' : '22',
'bcm24' : '18',
'bcm23' : '16',
'bcm18_pcm_c': '12',
'bcm15_rxd' : '10',
'bcm14_txd' : '8',
# Functional RPi pin names.
# 'bcm2' : '3',
# 'bcm3' : '5',
# 'bcm4' : '7',
# 'bcm5' : '29',
# 'bcm6' : '31',
# 'bcm7' : '26',
# 'bcm8' : '24',
# 'bcm9' : '21',
# 'bcm10': '19',
# 'bcm11': '23',
# 'bcm12': '32',
# 'bcm13': '33',
# 'bcm14': '8',
# 'bcm15': '10',
# 'bcm16': '36',
# 'bcm17': '11',
# 'bcm18': '12',
# 'bcm19': '35',
# 'bcm20': '38',
# 'bcm21': '40',
# 'bcm22': '15',
# 'bcm23': '16',
# 'bcm24': '18',
# 'bcm25': '22',
# 'bcm26': '37',
# 'bcm27': '13',
# Positional RPi pin names.
# 'gpio03': '3',
# 'gpio05': '5',
# 'gpio07': '7',
# 'gpio29': '29',
# 'gpio31': '31',
# 'gpio26': '26',
# 'gpio24': '24',
# 'gpio21': '21',
# 'gpio19': '19',
# 'gpio23': '23',
# 'gpio32': '32',
# 'gpio33': '33',
# 'gpio08': '8',
# 'gpio10': '10',
# 'gpio36': '36',
# 'gpio11': '11',
# 'gpio12': '12',
# 'gpio35': '35',
# 'gpio38': '38',
# 'gpio40': '40',
# 'gpio15': '15',
# 'gpio16': '16',
# 'gpio18': '18',
# 'gpio22': '22',
# 'gpio37': '37',
# 'gpio13': '13',
}
}
}
}
|
n = int(input())
X = list(map(int, input().split()))
X.sort()
def median(n, X):
if n % 2 == 0:
numerator = X[int(n / 2)] + X[int(n / 2 - 1)]
median_value = numerator / 2
else:
median_value = X[int(n / 2)]
return int(median_value)
print(median(int(n / 2), X[: int(n / 2)]))
print(median(n, X))
if n % 2 == 0:
print(median(int(n / 2), X[int(n / 2) :]))
else:
print(median(int(n / 2), X[int(n / 2) + 1 :]))
|
{
'includes': [ '../common.gyp' ],
'targets': [
{
'target_name': 'libzxing',
'type': 'static_library',
'include_dirs': [
'core/src',
],
'sources': [
'core/src/bigint/BigInteger.cc',
'core/src/bigint/BigIntegerAlgorithms.cc',
'core/src/bigint/BigIntegerUtils.cc',
'core/src/bigint/BigUnsigned.cc',
'core/src/bigint/BigUnsignedInABase.cc',
'core/src/zxing/BarcodeFormat.cpp',
'core/src/zxing/Binarizer.cpp',
'core/src/zxing/BinaryBitmap.cpp',
'core/src/zxing/ChecksumException.cpp',
'core/src/zxing/DecodeHints.cpp',
'core/src/zxing/Exception.cpp',
'core/src/zxing/FormatException.cpp',
'core/src/zxing/InvertedLuminanceSource.cpp',
'core/src/zxing/LuminanceSource.cpp',
'core/src/zxing/MultiFormatReader.cpp',
'core/src/zxing/Reader.cpp',
'core/src/zxing/Result.cpp',
'core/src/zxing/ResultIO.cpp',
'core/src/zxing/ResultPoint.cpp',
'core/src/zxing/ResultPointCallback.cpp',
'core/src/zxing/aztec/AztecDetectorResult.cpp',
'core/src/zxing/aztec/AztecReader.cpp',
'core/src/zxing/aztec/decoder/1Decoder.cpp',
'core/src/zxing/aztec/detector/1Detector.cpp',
'core/src/zxing/common/BitArray.cpp',
'core/src/zxing/common/BitArrayIO.cpp',
'core/src/zxing/common/BitMatrix.cpp',
'core/src/zxing/common/BitSource.cpp',
'core/src/zxing/common/CharacterSetECI.cpp',
'core/src/zxing/common/DecoderResult.cpp',
'core/src/zxing/common/DetectorResult.cpp',
'core/src/zxing/common/GlobalHistogramBinarizer.cpp',
'core/src/zxing/common/GreyscaleLuminanceSource.cpp',
'core/src/zxing/common/GreyscaleRotatedLuminanceSource.cpp',
'core/src/zxing/common/GridSampler.cpp',
'core/src/zxing/common/HybridBinarizer.cpp',
'core/src/zxing/common/IllegalArgumentException.cpp',
'core/src/zxing/common/PerspectiveTransform.cpp',
'core/src/zxing/common/Str.cpp',
'core/src/zxing/common/StringUtils.cpp',
'core/src/zxing/common/detector/MonochromeRectangleDetector.cpp',
'core/src/zxing/common/detector/WhiteRectangleDetector.cpp',
'core/src/zxing/common/reedsolomon/GenericGF.cpp',
'core/src/zxing/common/reedsolomon/GenericGFPoly.cpp',
'core/src/zxing/common/reedsolomon/ReedSolomonDecoder.cpp',
'core/src/zxing/common/reedsolomon/ReedSolomonException.cpp',
'core/src/zxing/datamatrix/1Version.cpp',
'core/src/zxing/datamatrix/DataMatrixReader.cpp',
'core/src/zxing/datamatrix/decoder/1BitMatrixParser.cpp',
'core/src/zxing/datamatrix/decoder/1DataBlock.cpp',
'core/src/zxing/datamatrix/decoder/1DecodedBitStreamParser.cpp',
'core/src/zxing/datamatrix/decoder/2Decoder.cpp',
'core/src/zxing/datamatrix/detector/2Detector.cpp',
'core/src/zxing/datamatrix/detector/CornerPoint.cpp',
'core/src/zxing/datamatrix/detector/DetectorException.cpp',
'core/src/zxing/multi/ByQuadrantReader.cpp',
'core/src/zxing/multi/GenericMultipleBarcodeReader.cpp',
'core/src/zxing/multi/MultipleBarcodeReader.cpp',
'core/src/zxing/multi/qrcode/QRCodeMultiReader.cpp',
'core/src/zxing/multi/qrcode/detector/MultiDetector.cpp',
'core/src/zxing/multi/qrcode/detector/MultiFinderPatternFinder.cpp',
'core/src/zxing/oned/CodaBarReader.cpp',
'core/src/zxing/oned/Code128Reader.cpp',
'core/src/zxing/oned/Code39Reader.cpp',
'core/src/zxing/oned/Code93Reader.cpp',
'core/src/zxing/oned/EAN13Reader.cpp',
'core/src/zxing/oned/EAN8Reader.cpp',
'core/src/zxing/oned/ITFReader.cpp',
'core/src/zxing/oned/MultiFormatOneDReader.cpp',
'core/src/zxing/oned/MultiFormatUPCEANReader.cpp',
'core/src/zxing/oned/OneDReader.cpp',
'core/src/zxing/oned/OneDResultPoint.cpp',
'core/src/zxing/oned/UPCAReader.cpp',
'core/src/zxing/oned/UPCEANReader.cpp',
'core/src/zxing/oned/UPCEReader.cpp',
'core/src/zxing/pdf417/PDF417Reader.cpp',
'core/src/zxing/pdf417/decoder/2BitMatrixParser.cpp',
'core/src/zxing/pdf417/decoder/2DecodedBitStreamParser.cpp',
'core/src/zxing/pdf417/decoder/3Decoder.cpp',
'core/src/zxing/pdf417/decoder/ec/ErrorCorrection.cpp',
'core/src/zxing/pdf417/decoder/ec/ModulusGF.cpp',
'core/src/zxing/pdf417/decoder/ec/ModulusPoly.cpp',
'core/src/zxing/pdf417/detector/3Detector.cpp',
'core/src/zxing/pdf417/detector/LinesSampler.cpp',
'core/src/zxing/qrcode/2Version.cpp',
'core/src/zxing/qrcode/ErrorCorrectionLevel.cpp',
'core/src/zxing/qrcode/FormatInformation.cpp',
'core/src/zxing/qrcode/QRCodeReader.cpp',
'core/src/zxing/qrcode/decoder/2DataBlock.cpp',
'core/src/zxing/qrcode/decoder/3BitMatrixParser.cpp',
'core/src/zxing/qrcode/decoder/3DecodedBitStreamParser.cpp',
'core/src/zxing/qrcode/decoder/4Decoder.cpp',
'core/src/zxing/qrcode/decoder/DataMask.cpp',
'core/src/zxing/qrcode/decoder/Mode.cpp',
'core/src/zxing/qrcode/detector/4Detector.cpp',
'core/src/zxing/qrcode/detector/AlignmentPattern.cpp',
'core/src/zxing/qrcode/detector/AlignmentPatternFinder.cpp',
'core/src/zxing/qrcode/detector/FinderPattern.cpp',
'core/src/zxing/qrcode/detector/FinderPatternFinder.cpp',
'core/src/zxing/qrcode/detector/FinderPatternInfo.cpp',
],
'conditions': [
['OS=="win"',
{
'include_dirs': [
'core/src/win32/zxing/',
],
'sources': [
'core/src/win32/zxing/win_iconv.c',
],
}
],
],
},
]
}
|
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 1 10:11:25 2022
@author: User
"""
# contadore de 1 en 1
cont = 0
cont +=1 #--> cont= cont + 1
# 1.- contar numero del 1 al 10 y mostrar en la pantalla
while cont < 10:
cont = cont + 1
print(cont)
# 2.- Sumar los numeros del 1 al 10
# list = {1,2,3,.....10}
# range (1,n) --> [1,2,3,....,(n-1)]
sum=0
for num in range(1,11): # [1,2,3....]
sum = sum + num
print (f'La suma total del 1 al 10 es: {sum}')
# 3.- Multiplicador
mult = 1
for num in range(1,11): # [1,2,3...10]
mult=mult*num
print (f'la multiplicacion es: {mult}')
# 4.- mostrar los pares del 1 al 10
for num in range (1,11):
if num % 2 == 0:
print (" numero pares:", num)
# 5.- mostrar los numeros impares
print()
for num in range (1,11):
if num % 2 == 1:
print (" los numeros impares son:", num)
## Ejercicio de clase 01
print()
print("Ejercicio de clase # 1")
print()
print("Contar la cantitatd de elementos de:[1,3,4,66,55,4]")
list = [1,3,4,66,55,4]
cont = 0
for num in list:
cont = cont + 1
print(f'- La cantidad de digitos es: {cont}')
print()
print("lista de los numeros impares y pares es:[1,3,4,66,55,4]")
list = [1,3,4,66,55,4]
for num in list:
if num % 2 == 1:
print ("- Los numeros impares son:", num)
print()
for num in list:
if num % 2 == 0:
print ("- Los numeros pares son:", num)
# Ejercicio de clase 02
print()
print("Ejercicio de clase # 2")
print()
print("Mostrar la suma y la multiplicacion de los numeros mostrados es:[1,3,4,66,55,4]")
list = [1,3,4,66,55,4]
sum = 0
for num in list:
sum = sum + num
print ("- La suma es =", sum)
mult = 1
for num in list:
mult = mult*num
print("- La multiplicacion es =", mult)
|
# /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# 20221BSI0153.py Aqui Entra o Nome do Arquivo do Código fonte
#
# Copyright 2022 Marllon Christiani dos Santos Ribeiro
#
def main():
# Declaração de variáveis
massa = float(0.000)
massa = float(input())
segundos = int(0)
minutos = int(0)
horas = int(0)
#Inicio
if massa >= 0 :
while massa >= 0 :
massaInicial = float(massa)
#CALCULA A DIVISAO DA MASSA E A CONTAGEM DO TEMPO
while massa >= 0.5 :
massa = massa/2 ;
segundos += 50 ;
# CALCULA OS SEGUNDOS E MINUTOS
while segundos >= 60 :
segundos -= 60 ;
minutos += 1 ;
#CALCULA OS MINUTOS E AS HORAS
while minutos >= 60 :
minutos -= 60 ;
horas += 1 ;
#Arredonda a massa final
print(f"MASSA INICIAL={massaInicial:.3f} MASSA FINAL={massa:.3f} TEMPO DECORRIDO={horas}:{minutos}:{segundos}") ;
massa = float(input())
#Reseta o Tempo
segundos = int(0)
minutos = int(0)
horas = int(0)
print("FIM")
else:
print("FIM");
if __name__ == "__main__":
main()
#Fim |
# --------------
# Code starts here
class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes']
new_class = (class_1 + class_2)
print (new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
# Code ends here
# --------------
# Code starts here
courses = {'Math': 65, 'English': 70, 'History': 80,'French': 70, 'Science': 60 }
print(courses.values())
total = (sum(courses.values()))
print(total)
percentage = ((total/500) * 100)
print(percentage)
# Code ends here
# --------------
# Code starts here
mathematics = {'Geoffrey Hinton': 78, 'Andrew Ng': 95,'Sebastian Raschka': 65,'Yoshua Benjio': 50,'Hilary Mason': 70,'Corinna Cortes': 66, 'Peter Warden': 75}
topper = max(mathematics,key = mathematics.get)
print (topper)
# Code ends here
# --------------
# Given string
topper = 'andrew ng'
# Code starts here
first_name = (topper.split()[0])
last_name = (topper.split()[1])
full_name = last_name + " " + first_name
certificate_name = (full_name.upper())
print (certificate_name)
# Code ends here
|
def increment(x, by=1):
return x + by
def tokenize(sentence):
return pos_tag(word_tokenize(sentence))
def synsets(sentence):
tokens = tokenize(sentence)
return remove_none(tagged_to_synset(*t) for t in tokens)
def remove_none(xs):
return [x for x in xs if x is not None]
def score(synset, synsets):
return max(synset.path_similarity(s) for s in synsets)
def sentence_similarity(sentence1, sentence2):
synsets1 = synsets(sentence1)
synsets2 = synsets(sentence2)
scores = remove_none(score(s, synsets2) for s in synsets1)
return float(sum(scores)) / len(scores)
|
#56-desenvolva um programa que leia o nome, idade e o sexo de 4 pessoas. no final do program,mostre:
#a media de idade do grupo
#qual e o nome do homem mais velho
#quantas mulheres tem menos de 20 anos
somaidade = 0
mediaidade=0
maioridadehome=0
nomevelho=''
totmulher20=0
for p in range(1, 5):
print('{}ª pessoa:'.format(p))
nome = str(input('NOME: ')).strip()
idade = int(input('IDADE: '))
sexo = str(input('SEXO [M/F] : ')).strip
somaidade = somaidade+idade
if p==1 and sexo in 'Mm':
maioridadehome=idade
nomevelho=nome
if sexo in 'Mm' and idade > maioridadehome:
maioridadehome=idade
nomevelho=nome
if sexo in 'Ff' and idade < 20:
totmulher20+= 1
mediaidade = somaidade/4
print('a media da idade do grupo e de {} anos.'.format(mediaidade))
print('o homem mais velho tem {} anos e se chama {}.'.format(maioridadehome, nomevelho ))
print('ao todo sao {} mulheres com menos de 20 anos. '.format(totmulher20))
#FIM//A\\ |
# Function to find the first occurrence of a given number
# in a sorted list of integers
def findFirstOccurrence(A, x):
(left, right) = (0, len(A) - 1)
result = -1
while left <= right:
# find the mid-value in the search space and compares it with the target
mid = (left + right) // 2
# if the key is located, update the result and
# search towards the left (lower indices)
if x == A[mid]:
result = mid
right = mid - 1
# if the key is less than the middle element, discard the right half
elif x < A[mid]:
right = mid - 1
# if the key is more than the middle element, discard the left half
else:
left = mid + 1
# return the leftmost index, or -1 if the element is not found
return result
# Function to find the last occurrence of a given number
# in a sorted list of integers
def findLastOccurrence(A, x):
# search space is `A[left…right]`
(left, right) = (0, len(A) - 1)
# initialize the result by -1
result = -1
# loop till the search space is exhausted
while left <= right:
# find the mid-value in the search space and compares it with the target
mid = (left + right) // 2
# if the key is located, update the result and
# search towards the right (higher indices)
if x == A[mid]:
result = mid
left = mid + 1
# if the key is less than the middle element, discard the right half
elif x < A[mid]:
right = mid - 1
# if the key is more than the middle element, discard the left half
else:
left = mid + 1
# return the leftmost index, or -1 if the element is not found
return result
for i in range(int(input())):
_ = int(input())
array = list(map(int, input().split()))
find = int(input())
# result = search(array,find,0,len(array)-1)
f1 = findFirstOccurrence(array, find)
f2 = findLastOccurrence(array, find)
print(find,"-",f2-f1+1)
|
class Solution(object):
def bruteforce(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
result = ''
if len(strs) == 0:
return ''
i = 0
d = {i: len(v) for i,v in enumerate(strs)}
count = min(d.values())
for i in range(1, count+1):
prefix = strs[0][:i]
for s in strs:
if s[:i] != prefix:
return result
result = prefix
return result
def optimized(self, strs):
result = ""
for n in zip(*strs):
if (len(set(n))) == 1:
result = result + n[0]
else:
return result
return result
s = Solution()
input_1 = ["flower","flow","flight"]
input_2 = ["dog","racecar","car"]
print(f'Input 1: {input_1}')
print(f'Bruteforce Solution: \n{s.bruteforce(input_1)}')
print(f'Optimized Solution: \n{s.bruteforce(input_1)}')
print(f'\nInput 2: {input_2}')
print(f'Bruteforce Solution: \n{s.bruteforce(input_2)}')
print(f'Optimized Solution: \n{s.bruteforce(input_2)}')
|
n = int(input(">> "))
sum = 0
for i in range(n):
sum = sum + (i+1)
print("1 から " + str(n) + " までの和は " + str(sum)) |
s1 = input()
s2 = input()
pairs = set()
for i in range(len(s2) - 1):
pairs.add(s2[i:i + 2])
ans = 0
for i in range(len(s1) - 1):
if s1[i: i + 2] in pairs:
ans += 1
print(ans)
|
# makes a BST from an array
class Node:
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right
def bst_from_array(array, start, end):
if start >= end:
return None
mid = (start + end) // 2
value = array[mid]
left = bst_from_array(array, start, mid)
right = bst_from_array(array, mid + 1, end)
return Node(value, left, right)
def print_bst(start):
queue = [(start, 0)]
print('PRINTING')
while queue:
node, depth = queue.pop()
print(' ' * depth + str(node.value))
if left := node.left:
queue.append((left, depth + 1))
if right := node.right:
queue.append((right, depth + 1))
def make_bst_and_print(num: int):
bst = bst_from_array(list(range(num)), 0, num)
print_bst(bst)
|
# Author: Tianyao (Till) Chen
# Email: [email protected]
# File: settings.py
class Settings:
"""The class to store all the settings for Alien Invasion."""
def __init__(self):
"""Initialize the static settings."""
# Screen settings.
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
# Ship settings
self.ship_limit = 3
# Bullet settings.
self.bullet_width = 3
self.bullet_height = 15
self.bullet_color = (60, 60, 60)
self.bullets_allowed = 3
# Alien settings.
self.fleet_drop_speed = 15
# Speedup scale
self.speedup_scale = 1.5
self.init_dynamic_settings()
def init_dynamic_settings(self):
"""Initialize the settings that might change during the game."""
self.ship_speed = 6
self.bullet_speed = 10.0
self.alien_speed = 3.0
self.fleet_direction = 1 # 1 means right, -1 means left
# Scoring
self.alien_points = 50
def speed_up(self):
"""Speed up the game."""
self.ship_speed *= self.speedup_scale
self.alien_speed *= self.speedup_scale
self.bullet_speed *= self.speedup_scale
self.alien_points *= self.speedup_scale
|
'''
Created on 24.05.2011
@author: Sergey Khayrulin
'''
class Position(object):
'''
Definition for position of point
'''
def __init__(self,proximal_point=None,distal_point=None):
'''
Constructor
'''
self.distal_point = distal_point
self.proximal_point = proximal_point #if null than = distal point of parent |
sum_counter = 0
# 600851475143
number = 600851475143
for i in range(2, 10000):
for j in range(1, i + 1):
if i % j == 0:
sum_counter += 1
if sum_counter == 2:
# print(i, end= " ")
if number % i == 0:
print()
print(f"prime factors for {number} : {i}", end=" ")
print()
sum_counter = 0
print()
|
'''Szablon z zarysem prostego "framework'u" dla tworzenia prostych gier.
'''
##
# jeżeli używamy dodatkowych modułów to zaimportujmy je tutaj
# ...
##
# definicje funkcji i zmiennych globalnych powinny znaleźć się tutaj
# ...
##
# kod głównej pętli gry
#
printGameDescription()
# flaga kontynuacji gry: True = gramy (kolejna) runde
keep_playing = True
max_guesses = getMaxNumberOfGuesses()
# główna pętla gry
while keep_playing:
riddle = getRiddle()
riddle_guessed = False
guess = 0
while guess < max_guesses and not riddle_guessed:
print ("Proba: ", guess + 1)
user_guess_valid = False
while not user_guess_valid:
user_guess = getUserGuess()
user_guess_valid = validateGuess(user_guess)
riddle_guessed = evaluateGuess(riddle, user_guess)
guess += 1
# sprawdzamy czy gra sie skonczyla, bo wyczerpala sie ilosc prob
# czy dlatego, ze gracz zgadl
if riddle_guessed:
printCongratulations(riddle)
else:
print("Nie ma więcej prób. Przegrałeś :(")
# zapytanie o kontynuacje gry
next_game = input("Jeszcze jedna zagadka (T/n)?")
if next_game == "n":
# nie, konczymy...
keep_playing = False
|
class MemoryItem:
def __init__(self, observation, action, next_observation, reward, done, info):
self.observation = observation
self.action = action
self.next_observation = next_observation
self.reward = reward
self.done = done
self.info = info
|
class Queen:
def __init__(self, pos, visited):
self.pos = pos
self.visited = visited
|
VALID_USER = {
"username": "Test",
"email": "[email protected]",
"password": "Test@123",
"password2": "Test@123",
}
|
class Solution:
def minJumps(self, arr, n):
jumps = [-1] * n
jumps[0] = 0
front = 0
rear = 0
while rear < n :
remaining_jumps = arr[rear] - (front - rear)
while remaining_jumps > 0 and front < n-1:
front += 1
j = jumps[rear]
jumps[front] = j + 1
remaining_jumps -= 1
rear += 1
if rear > front :
break
return jumps[n-1]
if __name__ == '__main__':
T=int(input())
for i in range(T):
n = int(input())
Arr = [int(x) for x in input().split()]
ob = Solution()
ans = ob.minJumps(Arr,n)
print(ans)
|
#
# Copyright (c) 2013-2014, PagerDuty, Inc. <[email protected]>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
class MockQueue:
def __init__(
self,
event=None,
status=None,
detailed_snapshot=None,
cleanup_age_secs=None
):
self.event = event
self.status = status
self.expected_detailed_snapshot = detailed_snapshot
self.expected_cleanup_age = cleanup_age_secs
self.consume_code = None
self.cleaned_up = False
def get_stats(self, detailed_snapshot=False):
if detailed_snapshot == self.expected_detailed_snapshot:
return self.status
raise Exception(
"Received detailed_snapshot=%s; expected detailed_snapshot=%s" %
(detailed_snapshot, self.expected_detailed_snapshot)
)
def flush(self, consume_func, stop_check_func):
self.consume_code = consume_func(self.event, self.event)
def cleanup(self, before):
if before == self.expected_cleanup_age:
self.cleaned_up = True
else:
raise Exception(
"Received cleanup_before=%s, expected=%s" %
(before, self.expected_cleanup_age)
)
|
# 3. File Writer
# Create a program that creates a file called my_first_file.txt.
# In that file write a single line with the content: 'I just created my first file!'
# file = open("my_first_file.txt", "w")
#
# file.write('I just created my first file!')
#
# file.close()
# With manager is better than just open as it automatically closes file
with open("my_first_file.txt", "w") as file:
file.write('I just created my first file!')
|
# Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários superiores a R$1250,00, calcule um aumento de 10%. Para os inferiores ou iguais, o aumento é de 15%.
print('-' * 100)
print('{: ^100}'.format('EXERCÍCIO 034 - AUMENTOS MÚLTIPLOS'))
print('-' * 100)
salario = float(input('Digite seu salário: R$ '))
if salario > 1250:
aumento = salario * 1.10
else:
aumento = salario * 1.15
print(f'Seu novo salário é R$ {aumento:.2f}')
print('-' * 100)
input('Pressione ENTER para sair...')
|
# 4-5. Summing a Million: Make a list of the numbers from one to one million, and then use min() and max()
# to make sure your list actually starts at one and ends at one million.
# Also, use the sum() function to see how quickly Python can add a million numbers.
numbers = list(range(1, 1000001))
print(min(numbers))
print(max(numbers))
print(sum(numbers)) |
print('-=' * 20)
print('{:^40}'.format('\033[32mPRODUTO ALEATÓRIO QUALQUER.CIA\033[m'))
print('-=' * 20)
cont = soma = 0
print('DIGITE \033[1;30m0\033[m PARA FINALIZAR A OPERAÇÃO')
while True:
cont += 1
n = float(input(f'Produto {cont}: R$ '))
soma += n
if n == 0:
print(f'TOTAL: R$ {soma}')
n1 = int(input('Dinheiro a ser recebido: '))
if n1 - soma >= 0:
print(f'TROCO: {(n1 - soma):.2f}\n'
f'OBRIGADO POR FREQUENTAR AS PRODUTO ALEATÓRIO QUALQUER.CIA!!')
break
else:
n2 = str(input('\033[31mDinheiro insuficiente,\033[m Gostaria de adicionar mais dinheiro ou cancelar a compra? [A/C]')).strip().upper()
if n2 == 'A':
print('OK, DIGITE O VALOR A SER ADICIONADO: ')
n3 = float(input('--------'))
if (n3 + n1) - soma < 0:
print('\033[31mDINHEIRO AINDA INSUFICIENTE\033[m, NÃO É POSSÍVEL REALIZAR MAIS ADIÇÕES, REFAÇA O PROCESSO.')
break
else:
print(F'TROCO DE R${(n3 + n1) - soma}, OBRIGADO PELA PREFERÊNCIA !!!')
break
else:
print('\033[31mOPERAÇÃO CANCELADA.\033[m')
break
|
def print_formatted(number):
# your code goes here
if number in range (1,100):
l = len(bin(number)[2:])
for i in range (1,n+1):
decimal = str(i).rjust(l)
octal = str(oct(i)[2:]).rjust(l)
hexadecimal = hex(i)[2:].rjust(l)
binary = bin(i)[2:].rjust(l)
print (decimal + ' ' + octal + ' ' + hexadecimal.upper() + ' ' + binary)
else:
print ("Input not valid. Retry")
if __name__ == '__main__':
n = int(input())
print_formatted(n) |
def get_city_year(p0, perc, delta, p):
years = 1
curr = p0 + p0 * (0.01 * perc) + delta
if curr <= p0: # remember == would imply stagnation
return -1
else:
while curr < p:
curr = curr + curr * (0.01 * perc) + delta
years += 1
return years
print(get_city_year(1000, 2, -50, 5000))
print(get_city_year(1500, 5, 100, 5000))
print(get_city_year(1500000, 2.5, 10000, 2000000))
print(get_city_year(1000, 2, -20, 2000)) |
#First Example - uncomment lines or change values to test the code
phone_balance = 7.62
bank_balance = 104.39
#phone_balance = 12.34
#bank_balance = 25
if phone_balance < 10:
phone_balance += 10
bank_balance -= 10
print(phone_balance)
print(bank_balance)
#Second Example
#change the number to experiment!
number = 145346334
#number = 5 #3 sir
if number % 2 == 0:
print("The number " + str(number) + " is even.")
else:
print("The number " + str(number) + " is odd.")
#Third Example
#change the age to experiment with the pricing
age = 35
#set the age limits for bus fares
free_up_to_age = 4
child_up_to_age = 18
senior_from_age = 65
#set bus fares
concession_ticket = 1.25
adult_ticket = 2.50
#ticket price logic
if age <= free_up_to_age:
ticket_price = 0
elif age <= child_up_to_age:
ticket_price = concession_ticket
elif age >= senior_from_age:
ticket_price = concession_ticket
else:
ticket_price = adult_ticket
message = "Somebody who is {} years old will pay ${} to ride the bus.".format(age,ticket_price)
print(message)
|
print('pypypy')
print('pypypy111')
print('pycharm1111')
print('pycharm222')
print('pypypy222')
print('pycharm3333')
print('pypypy333')
hheheheh
# zuishuaidezishi
ssshhhhhhh
|
# Design
# a
# stack
# that
# supports
# push, pop, top, and retrieving
# the
# minimum
# element in constant
# time.
#
# Implement
# the
# MinStack
#
#
# class:
#
#
# MinStack()
# initializes
# the
# stack
# object.
# void
# push(int
# val) pushes
# the
# element
# val
# onto
# the
# stack.
# void
# pop()
# removes
# the
# element
# on
# the
# top
# of
# the
# stack.
# int
# top()
# gets
# the
# top
# element
# of
# the
# stack.
# int
# getMin()
# retrieves
# the
# minimum
# element in the
# stack.
#
# Example
# 1:
#
# Input
# ["MinStack", "push", "push", "push", "getMin", "pop", "top", "getMin"]
# [[], [-2], [0], [-3], [], [], [], []]
#
# Output
# [null, null, null, null, -3, null, 0, -2]
#
# Explanation
# MinStack
# minStack = new
# MinStack();
# minStack.push(-2);
# minStack.push(0);
# minStack.push(-3);
# minStack.getMin(); // return -3
# minStack.pop();
# minStack.top(); // return 0
# minStack.getMin(); // return -2
#
# Constraints:
#
# -231 <= val <= 231 - 1
# Methods
# pop, top and getMin
# operations
# will
# always
# be
# called
# on
# non - empty
# stacks.
# At
# most
# 3 * 104
# calls
# will
# be
# made
# to
# push, pop, top, and getMin.
class MinStack:
def __init__(self):
self.stack = []
def push(self, val: int) -> None:
self.stack.append(val)
def pop(self) -> None:
if (len(self.stack) > 0):
self.stack.pop()
def top(self) -> int:
if (len(self.stack) > 0):
return self.stack[-1]
def getMin(self) -> int:
if (len(self.stack) > 0):
return min(self.stack)
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin() |
def baseline_opt_default_args(prob_type):
defaults = {}
defaults['simpleVar'] = 100
defaults['simpleIneq'] = 50
defaults['simpleEq'] = 50
defaults['simpleEx'] = 10000
defaults['nonconvexVar'] = 100
defaults['nonconvexIneq'] = 50
defaults['nonconvexEq'] = 50
defaults['nonconvexEx'] = 10000
if prob_type == 'simple':
defaults['corrEps'] = 1e-4
elif prob_type == 'nonconvex':
defaults['corrEps'] = 1e-4
elif 'acopf' in prob_type:
defaults['corrEps'] = 1e-4
return defaults
def baseline_nn_default_args(prob_type):
defaults = {}
defaults['simpleVar'] = 100
defaults['simpleIneq'] = 50
defaults['simpleEq'] = 50
defaults['simpleEx'] = 10000
defaults['nonconvexVar'] = 100
defaults['nonconvexIneq'] = 50
defaults['nonconvexEq'] = 50
defaults['nonconvexEx'] = 10000
defaults['saveAllStats'] = True
defaults['resultsSaveFreq'] = 50
if prob_type == 'simple':
defaults['epochs'] = 1000
defaults['batchSize'] = 200
defaults['lr'] = 1e-4
defaults['hiddenSize'] = 200
defaults['softWeight'] = 100
defaults['softWeightEqFrac'] = 0.5
defaults['useTestCorr'] = True
defaults['corrTestMaxSteps'] = 10
defaults['corrEps'] = 1e-4
defaults['corrLr'] = 1e-7
defaults['corrMomentum'] = 0.5
elif prob_type == 'nonconvex':
defaults['epochs'] = 1000
defaults['batchSize'] = 200
defaults['lr'] = 1e-4
defaults['hiddenSize'] = 200
defaults['softWeight'] = 100
defaults['softWeightEqFrac'] = 0.5
defaults['useTestCorr'] = True
defaults['corrTestMaxSteps'] = 10
defaults['corrEps'] = 1e-4
defaults['corrLr'] = 1e-7
defaults['corrMomentum'] = 0.5
elif 'acopf' in prob_type:
defaults['epochs'] = 1000
defaults['batchSize'] = 200
defaults['lr'] = 1e-3
defaults['hiddenSize'] = 200
defaults['softWeight'] = 100
defaults['softWeightEqFrac'] = 0.5
defaults['useTestCorr'] = True
defaults['corrTestMaxSteps'] = 5
defaults['corrEps'] = 1e-4
defaults['corrLr'] = 1e-5
defaults['corrMomentum'] = 0.5
else:
raise NotImplementedError
return defaults
def baseline_eq_nn_default_args(prob_type):
defaults = {}
defaults['simpleVar'] = 100
defaults['simpleIneq'] = 50
defaults['simpleEq'] = 50
defaults['simpleEx'] = 10000
defaults['nonconvexVar'] = 100
defaults['nonconvexIneq'] = 50
defaults['nonconvexEq'] = 50
defaults['nonconvexEx'] = 10000
defaults['saveAllStats'] = True
defaults['resultsSaveFreq'] = 50
if prob_type == 'simple':
defaults['epochs'] = 1000
defaults['batchSize'] = 200
defaults['lr'] = 1e-4
defaults['hiddenSize'] = 200
defaults['softWeightEqFrac'] = 0.5
defaults['useTestCorr'] = True
defaults['corrMode'] = 'partial'
defaults['corrTestMaxSteps'] = 10
defaults['corrEps'] = 1e-4
defaults['corrLr'] = 1e-7
defaults['corrMomentum'] = 0.5
elif prob_type == 'nonconvex':
defaults['epochs'] = 1000
defaults['batchSize'] = 200
defaults['lr'] = 1e-4
defaults['hiddenSize'] = 200
defaults['softWeightEqFrac'] = 0.5
defaults['useTestCorr'] = True
defaults['corrMode'] = 'partial'
defaults['corrTestMaxSteps'] = 10
defaults['corrEps'] = 1e-4
defaults['corrLr'] = 1e-7
defaults['corrMomentum'] = 0.5
elif 'acopf' in prob_type:
defaults['epochs'] = 1000
defaults['batchSize'] = 200
defaults['lr'] = 1e-3
defaults['hiddenSize'] = 200
defaults['softWeightEqFrac'] = 0.5
defaults['useTestCorr'] = True
defaults['corrMode'] = 'full'
defaults['corrTestMaxSteps'] = 5
defaults['corrEps'] = 1e-4
defaults['corrLr'] = 1e-5
defaults['corrMomentum'] = 0.5
else:
raise NotImplementedError
return defaults
def method_default_args(prob_type):
defaults = {}
defaults['simpleVar'] = 100
defaults['simpleIneq'] = 50
defaults['simpleEq'] = 50
defaults['simpleEx'] = 10000
defaults['nonconvexVar'] = 100
defaults['nonconvexIneq'] = 50
defaults['nonconvexEq'] = 50
defaults['nonconvexEx'] = 10000
defaults['saveAllStats'] = True
defaults['resultsSaveFreq'] = 50
if prob_type == 'simple':
defaults['epochs'] = 1000
defaults['batchSize'] = 200
defaults['lr'] = 1e-4
defaults['hiddenSize'] = 200
defaults['softWeight'] = 10 # use 100 if useCompl=False
defaults['softWeightEqFrac'] = 0.5
defaults['useCompl'] = True
defaults['useTrainCorr'] = True
defaults['useTestCorr'] = True
defaults['corrMode'] = 'partial' # use 'full' if useCompl=False
defaults['corrTrainSteps'] = 10
defaults['corrTestMaxSteps'] = 10
defaults['corrEps'] = 1e-4
defaults['corrLr'] = 1e-7
defaults['corrMomentum'] = 0.5
elif prob_type == 'nonconvex':
defaults['epochs'] = 1000
defaults['batchSize'] = 200
defaults['lr'] = 1e-4
defaults['hiddenSize'] = 200
defaults['softWeight'] = 10 # use 100 if useCompl=False
defaults['softWeightEqFrac'] = 0.5
defaults['useCompl'] = True
defaults['useTrainCorr'] = True
defaults['useTestCorr'] = True
defaults['corrMode'] = 'partial' # use 'full' if useCompl=False
defaults['corrTrainSteps'] = 10
defaults['corrTestMaxSteps'] = 10
defaults['corrEps'] = 1e-4
defaults['corrLr'] = 1e-7
defaults['corrMomentum'] = 0.5
elif 'acopf' in prob_type:
defaults['epochs'] = 1000
defaults['batchSize'] = 200
defaults['lr'] = 1e-3
defaults['hiddenSize'] = 200
defaults['softWeight'] = 10 # use 100 if useCompl=False
defaults['softWeightEqFrac'] = 0.5
defaults['useCompl'] = True
defaults['useTrainCorr'] = True
defaults['useTestCorr'] = True
defaults['corrMode'] = 'partial' # use 'full' if useCompl=False
defaults['corrTrainSteps'] = 5
defaults['corrTestMaxSteps'] = 5
defaults['corrEps'] = 1e-4
defaults['corrLr'] = 1e-4 # use 1e-5 if useCompl=False
defaults['corrMomentum'] = 0.5
else:
raise NotImplementedError
return defaults |
class S1C1():
@staticmethod
def ret_true():
return True
@staticmethod
def hex_to_base64(hx):
return "x"
|
# Given n balloons, indexed from 0 to n-1.
# Each balloon is painted with a number on it represented by array nums.
# You are asked to burst all the balloons.
# If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins.
# Here left and right are adjacent indices of i.
# After the burst, the left and right then becomes adjacent.
# Find the maximum coins you can collect by bursting the balloons wisely.
# Note:
# You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
# 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100
# Example:
# Input: [3,1,5,8]
# Output: 167
# Explanation: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
# coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
class Solution(object):
def maxCoins(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 动态规划 O(n^3)
# 状态: dp[i][j]表示戳爆从第i到第j个气球得到的最大金币数。
# 状态转移方程: dp[i][j]=max(dp[i][j],
# dp[i][k−1] + num[i−1] * nums[k] * nums[j+1] + dp[k+1][j])
# 其中,k可以理解成[i,j]范围里最后戳破的一个气球。
# 时间复杂度O(n^3): 三层循环
# 空间复杂度O(n^2): dp[i][j]数组的大小是(n+2)*(n+2)
n = len(nums)
nums = [1] + nums + [1]
dp = [[0 for _ in range(n+2)] for _ in range(n+2)]
for i in range(1, n+1):
dp[i][i] = nums[i-1] * nums[i] * nums[i+1]
for i in range(1, n):
for l in range(1, n):
r = l + i
if r > n:
continue
temp = 0
for k in range(l, r+1):
temp = max(temp, dp[l][k-1] + nums[l-1] * nums[k] * nums[r+1] + dp[k+1][r])
dp[l][r] = temp
return dp[1][n]
|
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
def calc_hba1c(value):
"""
Calculate the HbA1c from the given average blood glucose value.
This formula is the same one used by Accu-Chek:
https://www.accu-chek.com/us/glucose-monitoring/a1c-calculator.html#
"""
if value:
return ((46.7 + value) / 28.7)
else:
return 0
def round_value(value):
"""
Round the given value to 1 decimal place.
If the value is 0 or None, then simply return 0.
"""
if value:
return round(float(value), 1)
else:
return 0
def percent(part, whole):
"""
Get the percentage of the given values.
If the the total/whole is 0 or none, then simply return 0.
"""
if whole:
return round_value(100 * float(part)/float(whole))
else:
return 0
def to_mmol(value):
"""
Convert a given value in mg/dL to mmol/L rounded to 1 decimal place.
"""
return round((float(value) / 18.018), 1)
def to_mg(value):
"""
Convert a given value in mmol/L to mg/dL rounded to nearest integer.
"""
try:
return int(round((float(value) * 18.018), 0))
except ValueError:
# We're catching ValueError here as some browsers like Firefox won't
# validate the input for us. We're returning the value entered as this
# will be passed in to the Django validator which will return the
# validation error message.
return value
def glucose_by_unit_setting(user, value):
"""
Return the glucose value based on the unit setting.
Glucose values are stored in mg/dL in the database. If a user's setting
is set to mmol/L, convert the value.
"""
if user.settings.glucose_unit.name == 'mmol/L':
return to_mmol(value)
else:
return value
|
s = input()
answer = len(s)
k = s.count('a')
for i in range(len(s)):
cnt = 0
for j in range(k):
if s[(i+j)%len(s)] == 'b':
cnt+=1
if cnt < answer:
answer = cnt
print(answer) |
def math():
i_put = input()
if len(i_put) <= 140:
print('TWEET')
else:
print('MUTE')
if __name__ == '__main__':
math()
|
'''
A better way to implement the fibonacci series
T(n) = 2n + 2
'''
def fibonacci(n):
# Taking 1st two fibonacci nubers as 0 and 1
FibArray = [0, 1]
while len(FibArray) < n + 1:
FibArray.append(0)
if n <= 1:
return n
else:
if FibArray[n - 1] == 0:
FibArray[n - 1] = fibonacci(n - 1)
if FibArray[n - 2] == 0:
FibArray[n - 2] = fibonacci(n - 2)
FibArray[n] = FibArray[n - 2] + FibArray[n - 1]
return FibArray[n]
print(fibonacci(9)) |
eval_cfgs = [
dict(
metrics=dict(type='OPE'),
dataset=dict(type='OTB100'),
hypers=dict(
epoch=list(range(31, 51, 2)),
window=dict(
weight=[0.200, 0.300, 0.400]
)
)
),
] |
class Solution:
# Enumerate shortest length (Accepted), O(n*l) time, O(l) space (n = len(strs), l = len(shortest str))
def longestCommonPrefix(self, strs: List[str]) -> str:
min_len = min(len(s) for s in strs)
res = ""
for i in range(min_len):
c = strs[0][i]
for s in strs:
if s[i] != c:
return res
res += c
return res
# Enumerate shortest (Top Voted), O(n*l) time, O(l) space
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
shortest = min(strs, key=len)
for i, ch in enumerate(shortest):
for other in strs:
if other[i] != ch:
return shortest[:i]
return shortest
|
n = int(input("Please enter the size of the table: "))
# print the first row (header)
print(" ", end = "")
for i in range(1, n + 1):
print(" ", i, end = "")
print() # new line
# print the actual table
for row in range(1, n + 1):
# print row number at the beginning of each row
print(" ", row, end = "")
# print Xs if column number divides row number
for col in range(1, n + 1):
if col % row == 0:
print(" X", end = "")
else:
print(" ", end = "")
print() # new line at the end of each line
|
# Copyright 2018 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# DO NOT MANUALLY EDIT!
# Generated by //scripts/sdk/bazel/generate.py.
load("@io_bazel_rules_dart//dart/build_rules/internal:pub.bzl", "pub_repository")
def setup_dart():
pub_repository(
name = "vendor_meta",
output = ".",
package = "meta",
version = "1.1.6",
pub_deps = [],
)
pub_repository(
name = "vendor_logging",
output = ".",
package = "logging",
version = "0.11.3+2",
pub_deps = [],
)
pub_repository(
name = "vendor_uuid",
output = ".",
package = "uuid",
version = "1.0.3",
pub_deps = [],
)
|
# 给你一根长度为 n 的绳子,请把绳子剪成整数长度的 m 段(m、n都是整数,n>1并且m>1),每段绳子的长度记为 k[0],k[1]...k[m] 。请问 k[0]*k[1]*...*k[m] 可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
#
# 示例 1:
#
# 输入: 2
# 输出: 1
# 解释: 2 = 1 + 1, 1 × 1 = 1
# 示例 2:
#
# 输入: 10
# 输出: 36
# 解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36
# 提示:
#
# 2 <= n <= 58
# 注意:本题与主站 343 题相同:https://leetcode-cn.com/problems/integer-break/
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/jian-sheng-zi-lcof
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution:
def cuttingRope(self, n: int) -> int:
if n == 2 or n == 3:
return n - 1
if n % 3 == 0:
return 3 ** (n // 3)
if n % 3 == 1:
return 3 ** (n // 3 - 1) * 2 * 2
return 3 ** (n // 3) * 2
|
def split(list):
n = len(list)
if n == 1:
return list, []
middle = int(n/2)
return list[0:middle], list[middle:n]
def merge_sort(list):
if len(list) == 0:
return list
a, b = split(list)
if a == list:
return a
else:
new_a = merge_sort(a)
new_b = merge_sort(b)
a_len = len(new_a)
b_len = len(new_b)
a_iter = 0
b_iter = 0
result = []
while a_iter < a_len and b_iter < b_len:
if new_a[a_iter] < new_b[b_iter]:
result.append(new_a[a_iter])
a_iter += 1
else:
result.append(new_b[b_iter])
b_iter += 1
while a_iter < a_len:
result.append(new_a[a_iter])
a_iter += 1
while b_iter < b_len:
result.append(new_b[b_iter])
b_iter += 1
return result
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# We would need to create an map out of in-order array to access index easily
class Solution:
# Faster solution
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
def helper(in_left=0, in_right=len(inorder)):
# Using index in preorder list.
nonlocal pre_idx
# base cases
if in_right <= in_left:
return None
# Preorder element left set as the curr node.
node_val = preorder[pre_idx]
node = TreeNode(node_val)
# We find where this element in
in_idx = inorderMap[node_val]
# Finally increase to the next index in preorder
pre_idx += 1
# left
node.left = helper(in_left, in_idx)
# right
node.right = helper(in_idx + 1, in_right)
# Finally return the node as root for that level
return node
# Index element to set to zeroth element of preorder.
pre_idx = 0
# Hashmap of value to index of inOrder array.
inorderMap = {v:k for k,v in enumerate(inorder)}
return helper()
# def buildTree(self, preorder, inorder):
# if inorder:
# ind = inorder.index(preorder.pop(0))
# root = TreeNode(inorder[ind])
# root.left = self.buildTree(preorder, inorder[0:ind])
# root.right = self.buildTree(preorder, inorder[ind+1:])
# return root
|
"""
Buffer the StreetTrees feature class by 20 meters
"""
# Import modules
# Set variables
# Execute operation
|
# 静态方法和显式类名称可能对于处理一个类本地的数据来说可能是更好地方法'
# 类方法可能更适合处理对层级中的每个类不同的数据
# 静态方法统计实例
class SpamStatic:
numInstance = 0
def __init__(self):
SpamStatic.numInstance += 1
def printNumInstance():
print(SpamStatic.numInstance)
printNumInstance = staticmethod(printNumInstance)
# 类方法统计实例
class Spam:
numInstance = 0
def count(cls):
cls.numInstance += 1
def __init__(self):
self.count()
count = classmethod(count)
class Sub(Spam):
numInstance = 0
def __init__(self):
Spam.__init__(self)
class Other(Spam):
numInstance = 0
x = Spam()
y1, y2 = Sub(), Sub()
z1, z2, z3 = Other(), Other(), Other()
print(x.numInstance, y1.numInstance, z1.numInstance)
|
class Solution:
def partitionLabels(self, S):
"""
:type S: str
:rtype: List[int]
"""
positions = dict()
for i, c in enumerate(S):
if c not in positions:
positions[c] = []
positions[c].append(i)
result = []
end = -1
while True:
st = end + 1
if st >= len(S):
break
end = positions[S[st]][-1]
while True:
extend = max(positions[c][-1] for c in S[st:end + 1])
if extend > end:
end = extend
else:
break
result.append(end - st + 1)
return result
sol = Solution().partitionLabels
print(sol("ababcbacadefegdehijhklij"))
|
a = 3
b = 4
z = a + b
print(z)
|
expected = 'Jana III Sobieskiego'
a = ' Jana III Sobieskiego '
b = 'ul Jana III SobIESkiego'
c = '\tul. Jana trzeciego Sobieskiego'
d = 'ulicaJana III Sobieskiego'
e = 'UL. JA\tNA 3 SOBIES\tKIEGO'
f = 'UL. jana III SOBiesKIEGO'
g = 'ULICA JANA III SOBIESKIEGO '
h = 'ULICA. JANA III SOBIeskieGO'
i = ' Jana 3 Sobieskiego '
j = 'Jana III\tSobieskiego '
k = 'ul.Jana III Sob\n\nieskiego\n'
a = a.strip()
b = b.upper().replace('UL', '').strip().title().replace('Iii', 'III')
c = c.upper().replace('UL.', '').strip().title().replace('Trzeciego', 'III')
d = d.upper().replace('ULICA', '').strip().title().replace('Iii', 'III')
e = e.upper().replace('UL.', '').strip().replace('\t', '').title().replace('3', 'III')
f = f.upper().replace('UL.', '').strip().title().replace('Iii', 'III')
g = g.upper().replace('ULICA', '').strip().title().replace('Iii', 'III')
h = h.upper().replace('ULICA.', '').strip().title().replace('Iii', 'III')
i = i.strip().replace('3', 'III')
j = j.strip().replace('\t', ' ')
k = k.upper().replace('UL.', '').replace('\n', '').title().replace('Iii', 'III')
expected = 'Jana III Sobieskiego'
print(f'{a == expected}\t a: "{a}"')
print(f'{b == expected}\t b: "{b}"')
print(f'{c == expected}\t c: "{c}"')
print(f'{d == expected}\t d: "{d}"')
print(f'{e == expected}\t e: "{e}"')
print(f'{f == expected}\t f: "{f}"')
print(f'{g == expected}\t g: "{g}"')
print(f'{h == expected}\t h: "{h}"')
print(f'{i == expected}\t i: "{i}"')
print(f'{j == expected}\t j: "{j}"')
print(f'{k == expected}\t k: "{k}"')
|
#
# PySNMP MIB module CISCO-CALL-TRACKER-TCP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CALL-TRACKER-TCP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:34:55 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")
ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint")
cctActiveCallId, cctHistoryIndex = mibBuilder.importSymbols("CISCO-CALL-TRACKER-MIB", "cctActiveCallId", "cctHistoryIndex")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
CiscoPort, = mibBuilder.importSymbols("CISCO-TC", "CiscoPort")
NotificationGroup, ObjectGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ObjectGroup", "ModuleCompliance")
iso, NotificationType, Counter32, TimeTicks, MibIdentifier, Counter64, Unsigned32, Bits, Gauge32, ModuleIdentity, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "NotificationType", "Counter32", "TimeTicks", "MibIdentifier", "Counter64", "Unsigned32", "Bits", "Gauge32", "ModuleIdentity", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "ObjectIdentity")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
ciscoCallTrackerTCPMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 164))
ciscoCallTrackerTCPMIB.setRevisions(('2005-12-06 00:00', '2000-06-07 00:00',))
if mibBuilder.loadTexts: ciscoCallTrackerTCPMIB.setLastUpdated('200512060000Z')
if mibBuilder.loadTexts: ciscoCallTrackerTCPMIB.setOrganization('Cisco Systems, Inc.')
ccttMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 164, 1))
ccttActive = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 164, 1, 1))
ccttHistory = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 164, 1, 2))
ccttActiveTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 164, 1, 1, 1), )
if mibBuilder.loadTexts: ccttActiveTable.setStatus('current')
ccttActiveEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 164, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-CALL-TRACKER-MIB", "cctActiveCallId"))
if mibBuilder.loadTexts: ccttActiveEntry.setStatus('current')
ccttActiveLocalIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 164, 1, 1, 1, 1, 1), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ccttActiveLocalIpAddress.setStatus('current')
ccttActiveLocalTcpPort = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 164, 1, 1, 1, 1, 2), CiscoPort()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ccttActiveLocalTcpPort.setStatus('current')
ccttActiveRemoteIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 164, 1, 1, 1, 1, 3), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ccttActiveRemoteIpAddress.setStatus('current')
ccttActiveRemoteTcpPort = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 164, 1, 1, 1, 1, 4), CiscoPort()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ccttActiveRemoteTcpPort.setStatus('current')
ccttActiveDestinationFailures = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 164, 1, 1, 1, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ccttActiveDestinationFailures.setStatus('current')
ccttHistoryTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 164, 1, 2, 1), )
if mibBuilder.loadTexts: ccttHistoryTable.setStatus('current')
ccttHistoryEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 164, 1, 2, 1, 1), ).setIndexNames((0, "CISCO-CALL-TRACKER-MIB", "cctHistoryIndex"))
if mibBuilder.loadTexts: ccttHistoryEntry.setStatus('current')
ccttHistoryLocalIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 164, 1, 2, 1, 1, 1), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ccttHistoryLocalIpAddress.setStatus('current')
ccttHistoryLocalTcpPort = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 164, 1, 2, 1, 1, 2), CiscoPort()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ccttHistoryLocalTcpPort.setStatus('current')
ccttHistoryRemoteIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 164, 1, 2, 1, 1, 3), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ccttHistoryRemoteIpAddress.setStatus('current')
ccttHistoryRemoteTcpPort = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 164, 1, 2, 1, 1, 4), CiscoPort()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ccttHistoryRemoteTcpPort.setStatus('current')
ccttHistoryDestinationFailures = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 164, 1, 2, 1, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ccttHistoryDestinationFailures.setStatus('current')
ccttMIBNotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 164, 2))
ccttMIBNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 164, 2, 0))
ccttMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 164, 3))
ccttMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 164, 3, 1))
ccttMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 164, 3, 2))
ccttMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 164, 3, 1, 1)).setObjects(("CISCO-CALL-TRACKER-TCP-MIB", "ccttActiveGroup"), ("CISCO-CALL-TRACKER-TCP-MIB", "ccttHistoryGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ccttMIBCompliance = ccttMIBCompliance.setStatus('current')
ccttActiveGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 164, 3, 2, 2)).setObjects(("CISCO-CALL-TRACKER-TCP-MIB", "ccttActiveLocalIpAddress"), ("CISCO-CALL-TRACKER-TCP-MIB", "ccttActiveLocalTcpPort"), ("CISCO-CALL-TRACKER-TCP-MIB", "ccttActiveRemoteIpAddress"), ("CISCO-CALL-TRACKER-TCP-MIB", "ccttActiveRemoteTcpPort"), ("CISCO-CALL-TRACKER-TCP-MIB", "ccttActiveDestinationFailures"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ccttActiveGroup = ccttActiveGroup.setStatus('current')
ccttHistoryGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 164, 3, 2, 3)).setObjects(("CISCO-CALL-TRACKER-TCP-MIB", "ccttHistoryLocalIpAddress"), ("CISCO-CALL-TRACKER-TCP-MIB", "ccttHistoryLocalTcpPort"), ("CISCO-CALL-TRACKER-TCP-MIB", "ccttHistoryRemoteIpAddress"), ("CISCO-CALL-TRACKER-TCP-MIB", "ccttHistoryRemoteTcpPort"), ("CISCO-CALL-TRACKER-TCP-MIB", "ccttHistoryDestinationFailures"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ccttHistoryGroup = ccttHistoryGroup.setStatus('current')
mibBuilder.exportSymbols("CISCO-CALL-TRACKER-TCP-MIB", PYSNMP_MODULE_ID=ciscoCallTrackerTCPMIB, ccttActiveDestinationFailures=ccttActiveDestinationFailures, ccttMIBObjects=ccttMIBObjects, ciscoCallTrackerTCPMIB=ciscoCallTrackerTCPMIB, ccttActiveLocalIpAddress=ccttActiveLocalIpAddress, ccttMIBCompliance=ccttMIBCompliance, ccttActive=ccttActive, ccttActiveRemoteTcpPort=ccttActiveRemoteTcpPort, ccttHistoryTable=ccttHistoryTable, ccttHistory=ccttHistory, ccttMIBCompliances=ccttMIBCompliances, ccttActiveEntry=ccttActiveEntry, ccttMIBNotificationPrefix=ccttMIBNotificationPrefix, ccttHistoryDestinationFailures=ccttHistoryDestinationFailures, ccttHistoryRemoteIpAddress=ccttHistoryRemoteIpAddress, ccttActiveLocalTcpPort=ccttActiveLocalTcpPort, ccttActiveGroup=ccttActiveGroup, ccttActiveTable=ccttActiveTable, ccttHistoryEntry=ccttHistoryEntry, ccttMIBConformance=ccttMIBConformance, ccttHistoryRemoteTcpPort=ccttHistoryRemoteTcpPort, ccttHistoryLocalTcpPort=ccttHistoryLocalTcpPort, ccttHistoryGroup=ccttHistoryGroup, ccttMIBNotifications=ccttMIBNotifications, ccttMIBGroups=ccttMIBGroups, ccttHistoryLocalIpAddress=ccttHistoryLocalIpAddress, ccttActiveRemoteIpAddress=ccttActiveRemoteIpAddress)
|
def test_index(client):
res = client.get("/")
json_data = res.get_json()
assert json_data["msg"] == "Don't panic"
assert res.status_code == 200
|
#!/usr/bin/env python
numbers = [1,2,3,4,5,8,3,2,3,1,1,1]
def bubblesort(numbers):
# Keep a boolean to determine if we switched
switched = True
# One round of sorting
while switched:
switched = False
indexA = 0
indexB = 1
while indexB < len(numbers):
numberA = numbers[indexA]
numberB = numbers[indexB]
# If the two numbers are our of order, change them
if numberA > numberB:
holder = numbers[indexA]
numbers[indexA] = numbers[indexB]
numbers[indexB] = holder
switched = True
indexA+=1
indexB+=1
print('Sorted numbers are %s' % numbers)
return numbers
bubblesort(numbers)
|
#作业:实现一个闰年的函数
def run_nian(year):
return (year%4==0 and year%100!=0) or year%400==0
#断言: 4个测试用例
assert run_nian(2004)==True
assert run_nian(2005)==False
assert run_nian(2000)==True
assert run_nian(2100)==False |
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = None
count = 0
for n in nums:
if res is None:
res = n
count = 1
elif res == n:
count += 1
elif res !=n:
count -= 1
if count == 0:
res = None
return res |
"""
7.3 – Múltiplos de dez: Peça um número ao usuário e, em seguida, informe se o
número é múltiplo de dez ou não.
"""
numero = int(input("Digite o valor de um número: "))
if numero % 10 == 0:
print(f"O número digitado {numero} é múltiplo de 10")
else:
print(f"O número digitado {numero} não é múltiplo de 10") |
class Solution:
def transpose(self, A: List[List[int]]) -> List[List[int]]:
output=[]
rows=len(A)
cols=len(A[0])
output=[[0]*rows for i in range(cols)]
for i in range(0,len(A)):
for j in range(0,len(A[0])):
output[j][i]=A[i][j]
return output
|
# -*- coding: utf-8 -*-
# author: Phan Minh Tâm
# source has refer to java source of BURL method: http://web.informatik.uni-mannheim.de/AnyBURL/IJCAI/ijcai19.html file CompletionResult.java
class CompletionResult(object):
def __init__(self, triple):
self.triple = triple
self.head_results = []
self.tail_results = []
def add_head_results(self, heads, k):
if k > 0:
self.add_results(heads, self.head_results, k)
else:
self.add_results(heads, self.headResults)
def add_tail_results(self, tails, k):
if k > 0:
self.add_results(tails, self.tail_results, k)
else:
self.add_results(tails, self.tail_results)
def add_results(self, candidates, results, k=None):
if k != None:
for candidate in candidates:
if candidate != '':
results.append(candidate)
k -= 1
if k == 0:
return
else:
for candidate in candidates:
if candidate != '':
results.append(candidate)
def __str__(self):
return 'triple:{}\n{}{}'.format(self.triple, self.head_results, self.tail_results) |
""" spin multiplicities
"""
def spin(mult):
""" number of unpaired electrons
"""
return mult - 1
|
def missing_values1 (data):
"""
Deals in place with missing values in specified columns:
'fields_of_study', 'title', 'abstract', 'authors', 'venue', 'references', 'topics'
"""
data.loc[data['fields_of_study'].isnull(), 'fields_of_study'] = ""
data.loc[data['title'].isnull(), 'title'] = ""
data.loc[data['abstract'].isnull(), 'abstract'] = ""
data.loc[data['authors'].isnull(), 'authors'] = ""
data.loc[data['venue'].isnull(), 'venue'] = ""
data.loc[data['references'].isnull(), 'references'] = data['references'].mean()
data.loc[data['topics'].isnull(), 'topics'] = ""
def missing_values2 (data):
"""
Deals in place with missing values in specified columns: 'open_access' and 'year'
"""
# Open_access, thanks to jreback (27th of July 2016) https://github.com/pandas-dev/pandas/issues/13809
OpAc_by_venue = data.groupby('venue').open_access.apply(lambda x: x.mode()) # Take mode for each venue
OpAc_by_venue = OpAc_by_venue.to_dict()
missing_OpAc = data.loc[data['open_access'].isnull(),]
for i, i_paper in missing_OpAc.iterrows():
venue = i_paper['venue']
doi = i_paper['doi']
index = data[data['doi'] == doi].index[0]
if venue in OpAc_by_venue.keys(): # If a known venue, append the most frequent value for that venue
data.loc[index,'open_access'] = OpAc_by_venue[venue] # Set most frequent occurrence
else: # Else take most occurring value in entire dataset
data.loc[index,'open_access'] = data.open_access.mode()[0] # Thanks to BENY (2nd of February, 2018) https://stackoverflow.com/questions/48590268/pandas-get-the-most-frequent-values-of-a-column
# Year
year_by_venue = data.groupby('venue').year.apply(lambda x: x.mean()) # Take mean for each venue
year_by_venue = year_by_venue.to_dict()
missing_year = data.loc[data['year'].isnull(),]
for i, i_paper in missing_year.iterrows():
venue = i_paper['venue']
doi = i_paper['doi']
index = data[data['doi'] == doi].index[0]
if venue in year_by_venue.keys(): # If a known venue, append the mean value for that venue
data.loc[index, 'year'] = year_by_venue[venue] # Set mean publication year
else: # Else take mean value of entire dataset
data.loc[index,'year'] = data.year.mean()
|
def Settings( **kwargs ):
return {
'flags': [
'-O3', '-std=gnu11', '-fms-extensions',
'-Wno-microsoft-anon-tag',
'-Iinclude/', '-Ilib/', '-pthread',
'-Wall', '-Werror', '-pedantic']
}
|
#
# @lc app=leetcode id=257 lang=python
#
# [257] Binary Tree Paths
#
# https://leetcode.com/problems/binary-tree-paths/description/
#
# algorithms
# Easy (45.03%)
# Likes: 835
# Dislikes: 65
# Total Accepted: 221.4K
# Total Submissions: 484.4K
# Testcase Example: '[1,2,3,null,5]'
#
# Given a binary tree, return all root-to-leaf paths.
#
# Note: A leaf is a node with no children.
#
# Example:
#
#
# Input:
#
# 1
# / \
# 2 3
# \
# 5
#
# Output: ["1->2->5", "1->3"]
#
# Explanation: All root-to-leaf paths are: 1->2->5, 1->3
#
#
# 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 binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
return self.findPath(root, "{}".format(root.val))
def findPath(self, root, path):
if not root.left and not root.right:
return [path]
elif not root.right:
return self.findPath(root.left, path+"->{}".format(root.left.val))
elif not root.left:
return self.findPath(root.right, path+"->{}".format(root.right.val))
else:
lp = self.findPath(root.left, path+"->{}".format(root.left.val))
rp = self.findPath(root.right, path+"->{}".format(root.right.val))
return lp + rp
|
def traduz(palavras, eng2port):
traduzido = []
for p in palavras:
traduzido.append(eng2port[p])
return traduzido
palavras = ['blackberry', 'cherry', 'plum', 'apple', 'pineapple']
eng2port = {'pineapple': 'abacaxi', 'plum': 'ameixa', 'blackberry': 'amora', 'apple': 'maçã', 'cashew': 'caju', 'cherry': 'cereja'}
print(traduz(palavras, eng2port)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
'快速排序'
def partition(self, arr, start, end):
'找轴点应该在的位置,左侧比他小,右侧比他大'
low = start
high = end
pivot = arr[start] #选定轴点,‘坑’
while low < high: #直到访问完所有元素
while low < high and arr[high] >= pivot: #右指针元素大于轴点
high -= 1 #右指针左移
arr[low] = arr[high] #右指针元素小于轴点,将其入坑;此时high位置为新坑
#目前右边的都比轴点大
while low <high and arr[low] < pivot: #左指针元素小于轴点
low += 1 #左指针右移
arr[high] = arr[low] #左指针元素大于轴点,将其入新坑high;此时low为新新坑
#目前左边的都比轴点小
arr[low] = pivot #轴点位置'坑'确定,一轮结束
return low
def quick_sort(self, arr, left, right):
if left < right:
temp = self.partition(arr, left, right) #轴点位置
self.quick_sort(arr, left, temp - 1)
self.quick_sort(arr, temp + 1, right)
return arr
'TopK 基于快速排序partition方法'
def getLeastNumbers(self, arr, k):
if k > len(arr) or k <= 0:
return []
start = 0
end = len(arr) - 1
index = self.partition(arr, start, end)
while index != k-1:
if index > k-1:
end = index - 1
index = self.partition(arr, start, end)
if index < k-1:
start = index + 1
index = self.partition(arr, start, end)
return arr[:k]
'归并排序'
def merge(self, a, b):
c = []
h = j = 0
while j < len(a) and h < len(b):
if a[j] < b[h]:
c.append(a[j])
j += 1
else:
c.append(b[h])
h += 1
if j == len(a):
for i in b[h:]:
c.append(i)
else:
for i in a[j:]:
c.append(i)
return c
def MergeSort(self, lists):
if len(lists) <= 1:
return lists
middle = int(len(lists)/2)
left = self.MergeSort(lists[:middle])
right = self.MergeSort(lists[middle:])
return self.merge(left, right)
'堆排序'
def heap_adjust(self, A,i,size):
left = 2*i+1
right = 2*i+2
max_index = i
if left < size and A[left] > A[max_index] :
max_index = left
if right < size and A[right] > A[max_index]:
max_index = right
if max_index != i:
temp = A[i]
A[i] =A[max_index]
A[max_index] = temp
self.heap_adjust(A,max_index,size) #以替换的点为父节点,再调整所在的堆
def build_heap(self, A,size):
for i in range(size//2,-1,-1):
self.heap_adjust(A,i,size)
def heap_sort(self, A):
size = len(A)
self.build_heap(A,size) #初始化堆
for i in range(len(A)-1,0,-1):
temp = A[i]
A[i] = A[0]
A[0] = temp #将最大元素置于数组后的位置
self.heap_adjust(A,0,i)
return A
if __name__ == '__main__':
nums = [3,2,5,4,6,9,11,33,22]
test = Solution()
res = test.quick_sort(nums, 0, len(nums)-1)
res = test.MergeSort(nums)
res = test.heap_sort(nums)
print('sorted nums is:', res)
|
schema = {
# Schema definition, of the CLARA items.
'main_scale': {
'type': 'string',
'minlength': 1,
'maxlength': 20,
'required': True
},
'itembank_id': {
'type': 'string',
'minlength': 1,
'maxlength': 4,
'required': True
},
'presenting_order': {
'type': 'integer',
'required': True
},
'clara_item': {
'type': 'string',
'minlength': 1,
'maxlength': 255,
'required': True
},
'language': {
'type': 'string',
'minlength': 2,
'maxlength': 2,
'required': True
},
}
clara_items = {
# 'title' tag used in item links. Defaults to the resource title minus
# the final, plural 's' (works fine in most cases but not for 'people')
# 'item_title': 'person',
# by default the standard item entry point is defined as
# '/people/<ObjectId>'. We leave it untouched, and we also enable an
# additional read-only entry point. This way consumers can also perform
# GET requests at '/people/<lastname>'.
# 'additional_lookup': {
# 'url': 'regex("[\w]+")',
# 'field': 'language'
# },
# We choose to override global cache-control directives for this resource.
'cache_control': 'max-age=10,must-revalidate',
'cache_expires': 10,
# most global settings can be overridden at resource level
'resource_methods': ['GET'],
'schema': schema
}
|
n,d = map(int,raw_input().split())
c = map(int,raw_input().split(' '))
gc = 0
for i in range(len(c)):
if c[i]+d in c and c[i]+2*d in c:
gc+=1
print (gc) |
{
"targets": [
{
"target_name": "glace",
"sources": [
"target/glace.cc",
],
"include_dirs": [
"target/deps/include",
],
"libraries": [],
"library_dirs": [
"/usr/local/lib"
]
}
]
}
|
OUT_FORMAT_CONVERSION = {
"t": "",
"b": "b",
"u": "bu",
}
|
Scale.default = Scale.egyptian
Root.default = 0
Clock.bpm = 110
~p1 >> play('m', dur=PDur(3,16), sample=[0,2,3])
~p2 >> play('V', dur=1, pan=[-1,1], sample=var([0,2],[24,8]))
~p3 >> play('n', dur=var([.5,.25,.125,2/3],[24,4,2,2]))
p_all.lpf = 0
p_all.rate = .5
~s1 >> space(P[0,3,5,1]+(0,3), dur=4, chop=6, slide=0, echo=.5, room=.5, mix=.5)
~s2 >> glass(P[0,3,5,var([1,8,7],[16,8,8])], oct=4, amp=2)
|
""""
Copyright 2019 by J. Christopher Wagner (jwag). All rights reserved.
:license: MIT, see LICENSE for more details.
This packages contains OPTIONAL models for various ORMs/databases that can be used
to quickly get the required DB models setup.
These models have the fields for ALL features. This makes it easy for applications
to add features w/o a DB migration (and modern DBs are pretty efficient at storing
empty values!).
"""
|
params = {
# file to load wav from
'file': 'C:/Users/qweis/Documents/GitHub/unknown-pleasures/wavs/famous.wav',
# output file for images
'save_loc': 'covers/frame.png',
# save location for video
'vid_save': 'time_test.mp4',
# number of spacers between each data point
'spacers': 5,
# number of pixels added as offset per wave
'offset': 10,
# how many amp data points per line
'data_line': 40,
# number of lines
'n_lines': 80,
# percentage of actual data that is added as noise at end
'noise_frac': 1,
# min ticks to reach mean when drawing connecting line
'min_ticks': 5,
# how much range does the random noise have
'random_noise_range': 1,
# noise range for connecting line
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,0,-3,4
4,-2,3,-5
3,6,7,3
0,-3,-7,2
4,-6,-7,2
1,-7,0,0
8,0,-7,-4
6,-1,8,4"""
def distance(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1]) + abs(a[2] - b[2]) + abs(a[3] - b[3])
constellations = []
for line in input.splitlines():
x, y, z, t = (int(a) for a in line.split(","))
s = (x, y, z, t)
matching_constellations = []
for c in constellations:
for star in c:
if distance(star, s) <= 3:
matching_constellations.append(c)
break
resulting_constellation = {s}
for c in matching_constellations:
constellations.remove(c)
resulting_constellation |= c
constellations.append(frozenset(resulting_constellation))
print(len(constellations))
|
# The Twitter API keys needed to send tweets
# Two applications for the same account are needed,
# since two streamers can't be run on the same account
# main account. needs all privileges
CONSUMER_KEY = "enter your consumer key here"
CONSUMER_SECRET = "enter your secret consumer key here"
ACCESS_TOKEN = "enter your access token here"
ACCESS_TOKEN_SECRET = "enter your secret access token here"
# account for mining users. needs all privileges
MINE_CONSUMER_KEY = "enter your consumer key here"
MINE_CONSUMER_SECRET = "enter your secret consumer key here"
MINE_ACCESS_TOKEN = "enter your access token here"
MINE_ACCESS_TOKEN_SECRET = "enter your secret access token here"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.