content
stringlengths
7
1.05M
# Lopez Chaidez Luis Enrique DDSIV def hello_user(name): """Function that returns a string that says hello to the name that you introduce Args: name (String): Name that you want to add to the string Returns: String: It returns '¡Hola {name}!' """ return '¡Hola ' + name + '!' name = input('Introduce tu nombre: ') print(hello_user(name))
# Import Data commands = [] with open('../input/day_2.txt') as f: lines = f.read().splitlines() for line in lines: splitline = line.split(" ") splitline[1] = int(splitline[1]) commands.append(splitline) # Process Data positionHorizontal = 0 positionVertical = 0 for command in commands: direction = command[0] amount = command[1] if direction == 'forward': positionHorizontal += amount elif direction == 'down': positionVertical += amount elif direction == 'up': positionVertical -= amount print(f'Horizontal Movement: {positionHorizontal}') print(f'Vertical Movement: {positionVertical}') print(f'Multiplied Movement: {positionHorizontal * positionVertical}')
# def display_message(): # print("本章学习了定义函数") # for i in range(10): # display_message() # def favourite_book(title): # print(f"One of my favorite books is {title}.") # favourite_book("Alice in Wonderlan") # def make_shirt(a = 'T', b = 'I love Python'): # return f"订购的shirt的尺码为{a}\n打印的内容为{b}" # print(make_shirt()) # 8-6 # def city_country(city, country): # a = f"{city}, {country}" # return a.title() # print(city_country("santiago", "chile")) # 8-7 # def make_album(singer, album, count=None): # if count != None: # a = {"name": singer, "album": album, "count": count} # else: # a = {"name": singer, "album": album} # return a # print(make_album("d", "song1", 4)) # print(make_album("b", "song2")) # print(make_album("c", "song3")) # def make_album(singer, album, count=None): # if count != None: # a = {"name": singer, "album": album, "count": count} # return a # a = {"name": singer, "album": album} # return a # 8-8 def make_album(singer, album, count=None): a = {"name": singer, "album": album} if count: a["count"] = count return a while True: b = input("请输入singer: ") if b == "quit": break c = input("请输入专辑的名称:") if c == "quit": break print(make_album(b, c))
def product(fracs): t = reduce(lambda x, y: x * y, fracs, 1) return t.numerator, t.denominator
#Copyright 2010 Google Inc. # #Licensed under the Apache License, Version 2.0 (the "License"); #you may not use this file except in compliance with the License. #You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #Unless required by applicable law or agreed to in writing, software #distributed under the License is distributed on an "AS IS" BASIS, #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #See the License for the specific language governing permissions and #limitations under the License. def slugify(inStr): removelist = ["a", "an", "as", "at", "before", "but", "by", "for","from","is", "in", "into", "like", "of", "off", "on", "onto","per","since", "than", "the", "this", "that", "to", "up", "via","with"]; for a in removelist: aslug = re.sub(r'\b'+a+r'\b','',inStr) aslug = re.sub('[^\w\s-]', '', aslug).strip().lower() aslug = re.sub('\s+', '-', aslug) return aslug
# Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços. frase = str(input('\nDigite uma frase: ')) min = ''.join(frase.lower().split()) rev = ''.join(frase.lower().split())[::-1] if(min == rev): print('A frase é um palíndromo') else: print('A frase não é um palíndromo')
'this crashed pychecker from calendar.py in Python 2.2' class X: 'd' def test(self, item): return [e for e in item].__getslice__() # this crashed in 2.2, but not 2.3 def f(a): a.a = [x for x in range(2) if x > 1]
#!/usr/bin/env python3 def round_down_to_even(value): return value & ~1 for _ in range(int(input())): input() # don't need n a = list(map(int, input().split())) for i in range(0, round_down_to_even(len(a)), 2): if a[i] > a[i + 1]: a[i], a[i + 1] = a[i + 1], a[i] print(*a)
# coding: utf-8 # 作者:Pscly # 创建日期: # 用意: # a = [1,2,3,4,5] # a.pop(0) # a.append(4) # print(a) # for i, j in enumerate(a,1): # print(i, j) # print(a[:-1]) a = '123456' print(a.split('x'))
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim:fileencoding=utf_8 """Add doc string """ __author__ = 'M. Kocher' __copyright__ = "" __credits__ = ['M. Kocher'] __license__ = 'MIT License' __maintainer__ = 'M. Kocher' __email__ = '[email protected]' __version__ = '0.1'
num = [int(x) for x in input("Enter the Numbers : ").split()] index=[int(x) for x in input("Enter the Index : ").split()] target=[] for i in range(len(num)): target.insert(index[i], num[i]) print("The Target array is :",target)
def func(param1=True, param2="default val"): """Description of func with docstring groups style (Googledoc). Parameters ---------- param1 : descr of param1 that has True for default value param2 : descr of param2 (Default value = 'default val') Returns ------- type some value Raises ------ keyError raises key exception TypeError raises type exception """ pass class A: """ """ def method(self, param1, param2=None): """ Parameters ---------- param1 : param param2: (Default value = None) param2 : (Default value = None) Returns ------- """ pass
# Python Program to find Power of a Number number = int(input(" Please Enter any Positive Integer : ")) exponent = int(input(" Please Enter Exponent Value : ")) power = 1 for i in range(1, exponent + 1): power = power * number print("The Result of {0} Power {1} = {2}".format(number, exponent, power)) # by aditya
# anything above 0xa0 is printed as Unicode by CPython # the abobe is CPython implementation detail, stick to ASCII for c in range(0x80): print("0x%02x: %s" % (c, repr(chr(c)))) print("PASS")
# Title : Linked list :- delete element at front and back of a list # Author : Kiran raj R. # Date : 30:10:2020 class Node: """Create a node with value provided, the pointer to next is set to None""" def __init__(self, value): self.value = value self.next = None class Simply_linked_list: """create a empty singly linked list """ def __init__(self): self.head = None def printList(self): linked_list = [] temp = self.head while(temp): linked_list.append(temp.value) temp = temp.next print(f"The elements are {linked_list}") def search_list(self, item): temp = self.head while temp.next != None: temp = temp.next if temp.value == item: print(f"Found {temp.value}") break def delete_fist_elem(self): if self.head == None: print("The linked list is empty") else: self.head = self.head.next def delete_elem_end(self): # print(elem.next, elem.value) if self.head == None: print("The linked list is empty") else: temp = self.head while temp != None: if temp.next.next == None: temp.next = None temp = temp.next sl_list = Simply_linked_list() sl_list.head = Node(1) node2 = Node(2) node3 = Node(3) node4 = Node(4) node5 = Node(5) sl_list.head.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 sl_list.printList() sl_list.search_list(20) sl_list.search_list(2) sl_list.search_list(3) print("List before deletion at start: ", end="") sl_list.printList() sl_list.delete_fist_elem() print(f"List after deletion at start: ", end="") sl_list.printList() print("List before deletion at end: ", end="") sl_list.printList() sl_list.delete_elem_end() print(f"List after deletion at end: ", end="") sl_list.printList()
def solution(A,B): """ * 문제 이해 및 추상화 - 길이가 같은 각 배열에서 숫자를 뽑고 곱한 뒤 그 합이 가장 작은 값을 리턴 - arr1 정방향 sort, arr2 역방향 sort - 곱하면서 summation """ A.sort() B.sort(reverse=True) return sum([i[0]*i[1] for i in zip(A,B)]) A = [1,4,2] B = [5,4,4] solution(A,B)
TEMPLATE = """ # Related Pages Here is a list of all related documentation pages: {% for page in nodes -%} * [*{{page.title}}*]({{page.url}}) {{page.brief}} {% endfor -%} """
''' URL: https://leetcode.com/problems/reverse-words-in-a-string-iii/ Difficulty: Easy Description: Reverse Words in a String III Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1: Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc" Note: In the string, each word is separated by single space and there will not be any extra space in the string. ''' class Solution: def reverseWords(self, s): output = "" for word in s.split(" "): output += word[::-1] + " " return output[:-1]
""" link: https://leetcode-cn.com/problems/magical-string problem: 某字符串固定以 122 开头,且仅由 1,2 俩字符组成,且每组 1,2 出现的数量正好可以拼回该字符前序子串,求 该字符的前 n 位有多少个 1, n ∈ [0,10^5] solution: 模拟。 """ class Solution: def magicalString(self, n: int) -> int: if not n: return 0 f = [0] * (n + 5) f[0], f[1], f[2] = 1, 2, 2 i, j, cnt, c = 2, 3, 1, 1 while j < n: if f[i] == 1: f[j] = c j += 1 else: f[j], f[j + 1] = c, c j += 2 if c == 1: cnt += f[i] if j > n: cnt -= j - n c = 3 - c i += 1 return cnt
"""Top-level package for Copernicus Marine ToolBox.""" __author__ = """E.U. Copernicus Marine Service Information""" __email__ = '[email protected]' __version__ = '0.1.17'
# PROCURANDO UMA STRING DENTRO DA OUTRA nome = str(input('Digite seu nome: ').strip().lower()) print("silva" in nome.split()) # DESSA MANEIRA EVITA-SE QUE SILVA SEJA CONFUNDIDO DENTRO DE OUTRA STRING.
'''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.''' # Bitcoin Cash (BCH) qpz32c4lg7x7lnk9jg6qg7s4uavdce89myax5v5nuk # Ether (ETH) - 0x843d3DEC2A4705BD4f45F674F641cE2D0022c9FB # Litecoin (LTC) - Lfk5y4F7KZa9oRxpazETwjQnHszEPvqPvu # Bitcoin (BTC) - 34L8qWiQyKr8k4TnHDacfjbaSqQASbBtTd # contact :- [email protected] """ The nested brackets problem is a problem that determines if a sequence of brackets are properly nested. A sequence of brackets s is considered properly nested if any of the following conditions are true: - s is empty - s has the form (U) or [U] or {U} where U is a properly nested string - s has the form VW where V and W are properly nested strings For example, the string "()()[()]" is properly nested but "[(()]" is not. The function called is_balanced takes as input a string S which is a sequence of brackets and returns true if S is nested and false otherwise. """ def is_balanced(S): stack = [] open_brackets = set({"(", "[", "{"}) closed_brackets = set({")", "]", "}"}) open_to_closed = dict({"{": "}", "[": "]", "(": ")"}) for i in range(len(S)): if S[i] in open_brackets: stack.append(S[i]) elif S[i] in closed_brackets: if len(stack) == 0 or ( len(stack) > 0 and open_to_closed[stack.pop()] != S[i] ): return False return len(stack) == 0 def main(): S = input("Enter sequence of brackets: ") if is_balanced(S): print((S, "is balanced")) else: print((S, "is not balanced")) if __name__ == "__main__": main()
class Node: def __init__(self, ch): self.ch = ch self.children = {} self.isWordTerminal = False class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = Node('\0') def insert(self, word: str) -> None: """ Inserts a word into the trie. """ current = self.root for ch in word: if ch not in current.children: current.children[ch] = Node(ch) current = current.children[ch] current.isWordTerminal = True def get_node(self, word: str): current = self.root for ch in word: if ch in current.children: current = current.children[ch] else: return None return current def search(self, word: str) -> bool: """ Returns if the word is in the trie. """ node = self.get_node(word) if node is not None: if node.isWordTerminal: return True return False def startsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ return self.get_node(prefix) is not None # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix)
# # PySNMP MIB module HP-ICF-CONNECTION-RATE-FILTER (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-CONNECTION-RATE-FILTER # Produced by pysmi-0.3.4 at Wed May 1 13:33:37 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) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint") hpSwitch, = mibBuilder.importSymbols("HP-ICF-OID", "hpSwitch") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") InetAddress, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressType") NotificationGroup, ObjectGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ObjectGroup", "ModuleCompliance") MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, MibIdentifier, Gauge32, NotificationType, IpAddress, Counter32, Integer32, Counter64, Bits, ObjectIdentity, Unsigned32, iso, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "MibIdentifier", "Gauge32", "NotificationType", "IpAddress", "Counter32", "Integer32", "Counter64", "Bits", "ObjectIdentity", "Unsigned32", "iso", "ModuleIdentity") TextualConvention, TruthValue, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "TruthValue", "DisplayString") hpicfConnectionRateFilter = ModuleIdentity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24)) hpicfConnectionRateFilter.setRevisions(('2009-05-12 01:08', '2004-09-07 01:08',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: hpicfConnectionRateFilter.setRevisionsDescriptions(("Added 'hpicfConnectionRateFilterSensitivity', 'hpicfConnectionRateFilterIfModeValue'.", 'Added Connection Rate Filter MIBs.',)) if mibBuilder.loadTexts: hpicfConnectionRateFilter.setLastUpdated('200905120108Z') if mibBuilder.loadTexts: hpicfConnectionRateFilter.setOrganization('HP Networking') if mibBuilder.loadTexts: hpicfConnectionRateFilter.setContactInfo('Hewlett Packard Company 8000 Foothills Blvd. Roseville, CA 95747') if mibBuilder.loadTexts: hpicfConnectionRateFilter.setDescription('This MIB module describes objects for management of the Connection Rate Filter feature in the HP Switch product line.') hpicfConnectionRateFilterNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 0)) hpicfConnectionRateFilterNotificationControl = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 1)) hpicfConnectionRateFilterObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 2)) hpicfConnectionRateFilterConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 3)) hpicfConnectionRateFilterIfModeConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 4)) hpicfConnectionRateFilterNotification = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 0, 1)).setObjects(("HP-ICF-CONNECTION-RATE-FILTER", "hpicifConnectionRateFilterVlanId"), ("HP-ICF-CONNECTION-RATE-FILTER", "hpicifConnectionRateFilterInetAddress"), ("HP-ICF-CONNECTION-RATE-FILTER", "hpicifConnectionRateFilterInetAddressType"), ("HP-ICF-CONNECTION-RATE-FILTER", "hpicifConnectionRateFilterMode")) if mibBuilder.loadTexts: hpicfConnectionRateFilterNotification.setStatus('current') if mibBuilder.loadTexts: hpicfConnectionRateFilterNotification.setDescription('This Notification indicates that the host associated with the specified IP Address has been flagged by the connection rate filter and may have been throttled or blocked.') hpicifConnectionRateFilterVlanId = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 2, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4094))).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hpicifConnectionRateFilterVlanId.setStatus('current') if mibBuilder.loadTexts: hpicifConnectionRateFilterVlanId.setDescription('This variable uniquely identifies the vlan on which the host was flagged by the connection rate filter.') hpicifConnectionRateFilterInetAddress = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 2, 2), InetAddress()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hpicifConnectionRateFilterInetAddress.setStatus('current') if mibBuilder.loadTexts: hpicifConnectionRateFilterInetAddress.setDescription('This variable uniquely identifies the IP address of the host flagged by the connection rate filter.') hpicifConnectionRateFilterInetAddressType = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 2, 3), InetAddressType()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hpicifConnectionRateFilterInetAddressType.setStatus('current') if mibBuilder.loadTexts: hpicifConnectionRateFilterInetAddressType.setDescription('This variable uniquely identifies the type of IP address of the host flagged by the connection rate filter.') hpicifConnectionRateFilterMode = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 2, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("inform", 0), ("throttle", 1), ("block", 2)))).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hpicifConnectionRateFilterMode.setStatus('current') if mibBuilder.loadTexts: hpicifConnectionRateFilterMode.setDescription('This variable identifies the mode applied to the host flagged by the connection rate filter.') hpicfConnectionRateFilterIfModeConfigTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 4, 1), ) if mibBuilder.loadTexts: hpicfConnectionRateFilterIfModeConfigTable.setStatus('current') if mibBuilder.loadTexts: hpicfConnectionRateFilterIfModeConfigTable.setDescription('This table contains objects for configuring mode of the host flagged by the connection rate filter.') hpicfConnectionRateFilterIfModeConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 4, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex")) if mibBuilder.loadTexts: hpicfConnectionRateFilterIfModeConfigEntry.setStatus('current') if mibBuilder.loadTexts: hpicfConnectionRateFilterIfModeConfigEntry.setDescription('An entry in the hpicfConnectionRateFilterIfModeConfigEntry contains objects for configuring mode of the host flagged by the connection rate filter.') hpicfConnectionRateFilterIfModeValue = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 4, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("inform", 1), ("throttle", 2), ("block", 3))).clone('none')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpicfConnectionRateFilterIfModeValue.setStatus('current') if mibBuilder.loadTexts: hpicfConnectionRateFilterIfModeValue.setDescription('This variable identifies the mode applied to the host flagged by the connection rate filter.') hpicfConnectionRateFilterNotificationControlEnable = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 1, 1), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpicfConnectionRateFilterNotificationControlEnable.setStatus('current') if mibBuilder.loadTexts: hpicfConnectionRateFilterNotificationControlEnable.setDescription('This object controls, whether or not notifications from the agent are enabled. The value true(1) means that notifications are enabled; the value false(2) means that they are not. The default value is enabled.') hpicfConnectionRateFilterSensitivity = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 0), ("low", 1), ("medium", 2), ("high", 3), ("aggressive", 4))).clone('none')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpicfConnectionRateFilterSensitivity.setStatus('current') if mibBuilder.loadTexts: hpicfConnectionRateFilterSensitivity.setDescription('This variable is for setting the level of filtering required for connection-rate-filter.') hpicfConnectionRateFilterCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 3, 1)) hpicfConnectionRateFilterGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 3, 2)) hpicfConnectionRateFilterCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 3, 1, 1)).setObjects(("HP-ICF-CONNECTION-RATE-FILTER", "hpicfConnectionRateFilterNotifyGroup"), ("HP-ICF-CONNECTION-RATE-FILTER", "hpicfConnectionRateFilterObjectGroup"), ("HP-ICF-CONNECTION-RATE-FILTER", "hpicfConnectionRateFilterNotifyGroup"), ("HP-ICF-CONNECTION-RATE-FILTER", "hpicfConnectionRateFilterObjectGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hpicfConnectionRateFilterCompliance = hpicfConnectionRateFilterCompliance.setStatus('current') if mibBuilder.loadTexts: hpicfConnectionRateFilterCompliance.setDescription('A compliance statement for HP Routing switches with Connection Rate Filtering capability') hpicfConnectionRateFilterCompliance1 = ModuleCompliance((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 3, 1, 2)).setObjects(("HP-ICF-CONNECTION-RATE-FILTER", "hpicfConnectionRateFilterObjectGroup1")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hpicfConnectionRateFilterCompliance1 = hpicfConnectionRateFilterCompliance1.setStatus('current') if mibBuilder.loadTexts: hpicfConnectionRateFilterCompliance1.setDescription('A compliance statement for HP Routing switches with Connection Rate Filtering capability') hpicfConnectionRateFilterNotifyGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 3, 2, 1)).setObjects(("HP-ICF-CONNECTION-RATE-FILTER", "hpicfConnectionRateFilterNotification")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hpicfConnectionRateFilterNotifyGroup = hpicfConnectionRateFilterNotifyGroup.setStatus('current') if mibBuilder.loadTexts: hpicfConnectionRateFilterNotifyGroup.setDescription('A collection of notifications used to indicate changes in Connection Rate Filter status') hpicfConnectionRateFilterObjectGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 3, 2, 2)).setObjects(("HP-ICF-CONNECTION-RATE-FILTER", "hpicfConnectionRateFilterNotificationControlEnable"), ("HP-ICF-CONNECTION-RATE-FILTER", "hpicfConnectionRateFilterIfModeValue"), ("HP-ICF-CONNECTION-RATE-FILTER", "hpicfConnectionRateFilterSensitivity")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hpicfConnectionRateFilterObjectGroup = hpicfConnectionRateFilterObjectGroup.setStatus('current') if mibBuilder.loadTexts: hpicfConnectionRateFilterObjectGroup.setDescription('A collection of objects for configuring the Connection Rate Filter.') hpicfConnectionRateFilterObjectGroup1 = ObjectGroup((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 24, 3, 2, 3)).setObjects(("HP-ICF-CONNECTION-RATE-FILTER", "hpicifConnectionRateFilterVlanId"), ("HP-ICF-CONNECTION-RATE-FILTER", "hpicifConnectionRateFilterInetAddress"), ("HP-ICF-CONNECTION-RATE-FILTER", "hpicifConnectionRateFilterInetAddressType"), ("HP-ICF-CONNECTION-RATE-FILTER", "hpicifConnectionRateFilterMode")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hpicfConnectionRateFilterObjectGroup1 = hpicfConnectionRateFilterObjectGroup1.setStatus('current') if mibBuilder.loadTexts: hpicfConnectionRateFilterObjectGroup1.setDescription('A collection of objects for configuring the Connection Rate Filter.') mibBuilder.exportSymbols("HP-ICF-CONNECTION-RATE-FILTER", hpicfConnectionRateFilterNotificationControl=hpicfConnectionRateFilterNotificationControl, hpicfConnectionRateFilterNotification=hpicfConnectionRateFilterNotification, hpicfConnectionRateFilterIfModeConfigEntry=hpicfConnectionRateFilterIfModeConfigEntry, hpicfConnectionRateFilter=hpicfConnectionRateFilter, hpicfConnectionRateFilterObjects=hpicfConnectionRateFilterObjects, PYSNMP_MODULE_ID=hpicfConnectionRateFilter, hpicfConnectionRateFilterIfModeConfig=hpicfConnectionRateFilterIfModeConfig, hpicfConnectionRateFilterNotifyGroup=hpicfConnectionRateFilterNotifyGroup, hpicifConnectionRateFilterInetAddress=hpicifConnectionRateFilterInetAddress, hpicfConnectionRateFilterObjectGroup1=hpicfConnectionRateFilterObjectGroup1, hpicfConnectionRateFilterObjectGroup=hpicfConnectionRateFilterObjectGroup, hpicfConnectionRateFilterNotificationControlEnable=hpicfConnectionRateFilterNotificationControlEnable, hpicifConnectionRateFilterMode=hpicifConnectionRateFilterMode, hpicfConnectionRateFilterCompliance1=hpicfConnectionRateFilterCompliance1, hpicfConnectionRateFilterGroups=hpicfConnectionRateFilterGroups, hpicfConnectionRateFilterConformance=hpicfConnectionRateFilterConformance, hpicfConnectionRateFilterSensitivity=hpicfConnectionRateFilterSensitivity, hpicfConnectionRateFilterCompliance=hpicfConnectionRateFilterCompliance, hpicfConnectionRateFilterIfModeValue=hpicfConnectionRateFilterIfModeValue, hpicifConnectionRateFilterInetAddressType=hpicifConnectionRateFilterInetAddressType, hpicfConnectionRateFilterCompliances=hpicfConnectionRateFilterCompliances, hpicifConnectionRateFilterVlanId=hpicifConnectionRateFilterVlanId, hpicfConnectionRateFilterIfModeConfigTable=hpicfConnectionRateFilterIfModeConfigTable, hpicfConnectionRateFilterNotifications=hpicfConnectionRateFilterNotifications)
_base_ = [ '../_base_/datasets/togal.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py' ] # model settings norm_cfg = dict(type='BN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained=None, backbone=dict( type='Unet', encoder_name="tu-tf_efficientnetv2_b3", encoder_depth=5 ), decode_head=dict( type='FCNHead', in_channels=16, in_index=-1, channels=16, num_convs=1, concat_input=False, dropout_ratio=0.1, num_classes=2, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), # model training and testing settings train_cfg=dict(), test_cfg=dict(mode='slide', crop_size=(256, 256), stride=(170, 170)))
class DimFieldModel: def __init__( self, *kwargs, field_key: str, project_id: str, name: str, control_type: str, default_value: str = None, counted_character: bool, counted_character_date_from_key: int, counted_character_time_from_key: int, counted_character_date_to_key: int, counted_character_time_to_key: int, counted_character_from_timestamp: str, counted_character_to_timestamp: str, is_sub_field: bool = False, ): self.field_key = field_key self.project_id = project_id self.name = name self.control_type = control_type self.default_value = default_value self.counted_character = counted_character self.counted_character_date_from_key = counted_character_date_from_key self.counted_character_time_from_key = counted_character_time_from_key self.counted_character_date_to_key = counted_character_date_to_key self.counted_character_time_to_key = counted_character_time_to_key self.counted_character_from_timestamp = counted_character_from_timestamp self.counted_character_to_timestamp = counted_character_to_timestamp self.is_sub_field = is_sub_field
nome = input('what is your name? ') idade = input('how old are you ' + nome + '?') peso = input('what is your weight {}?'.format(nome) + '?') print('dados: {}'.format(nome) + ' Weight:' + peso + 'Idade:' + idade)
""" All the custom exceptions types """ class PylasError(Exception): pass class UnknownExtraType(PylasError): pass class PointFormatNotSupported(PylasError): pass class FileVersionNotSupported(PylasError): pass class LazPerfNotFound(PylasError): pass class IncompatibleDataFormat(PylasError): pass
# common classes_file = './data/classes/voc.names' num_classes = 1 input_image_h = 448 input_image_w = 448 down_ratio = 4 max_objs = 150 ot_nodes = ['detector/hm/Sigmoid', "detector/wh/Relu", "detector/reg/Relu"] moving_ave_decay = 0.9995 # train train_data_file = './data/dataset/voc_train.txt' batch_size = 4 epochs = 80 # learning rate lr_type="exponential"# "exponential","piecewise","CosineAnnealing" lr = 1e-3 # exponential lr_decay_steps = 5000 # exponential lr_decay_rate = 0.95 # exponential lr_boundaries = [40000,60000] # piecewise lr_piecewise = [0.0001, 0.00001, 0.000001] # piecewise warm_up_epochs = 2 # CosineAnnealing init_lr= 1e-4 # CosineAnnealing end_lr = 1e-6 # CosineAnnealing pre_train = True depth = 1 # test test_data_file = './data/dataset/voc_test.txt' score_threshold = 0.3 use_nms = True nms_thresh = 0.4 weight_file = './checkpoint' write_image = True write_image_path = './eval/JPEGImages/' show_label = True
# _*_ coding=utf-8 _*_ class Config(): def __init__(self): self.device = '1' self.data_dir = '../data' self.logging_dir = 'log' self.samples_dir = 'samples' self.testing_dir = 'test_samples' self.checkpt_dir = 'checkpoints' self.max_srclen = 25 self.max_tgtlen = 25 self.vocab_path = '../data/vocab' #self.embed_path = '../data/vocab_embeddings' self.embed_path = None self.vocab_size = 20000 self.emb_dim = 512 self.graph_seed = 123456 self.enc_num_block = 6 self.enc_head = 8 self.dec_num_block = 6 self.dec_head = 8 self.d_model = 512 self.d_k = 64 self.d_q = 64 self.d_v = 64 self.d_ff = 2048 self.dropout = 0.1 self.lr = 1e-3 self.warmming_up = 2000 self.StepLR_size = 5 self.StepLR_gamma = 0.95 self.batch_size = 512 self.total_epoch_num = 100 self.eval_per_batch = None # set 'number' of 'None'
t1 = ('OI', 2.0, [40, 50]) print(t1[2:]) t = 1, 4, "THiago" tupla1 = 1, 2, 3, 4, 5 tulpla2 = 6, 7, 8, 9, 10 print(tupla1 + tulpla2) # concatena
avtobots = {"Оптімус Прайм": "Грузовик Peterbilt 379", "Бамблбі": "Chevrolet Camaro", "Джаз": "Porsche 935 Turbo"} for key in avtobots: if key == "Оптімус Прайм": print("Оптімус Прайм прибув")
yformat = u"%(d1)i\xB0%(d2)02i'%(d3)02.2f''" xformat = u"%(hour)ih%(minute)02im%(second)02.2fs" def getFormatDict(tick): degree1 = int(tick) degree2 = int((tick * 100 - degree1 * 100)) degree3 = ((tick * 10000 - degree1 * 10000 - degree2 * 100)) tick = (tick + 360) % 360 totalhours = float(tick * 24.0 / 360) hours = int(totalhours) minutes = int((totalhours*60 - hours*60)) seconds = (totalhours * 3600 - hours * 3600 - minutes * 60) values = {"d1":degree1, "d2":degree2, "d3":degree3, "hour":hours, "minute":minutes, "second":seconds} return values def formatX(tick): values = getFormatDict(tick) return xformat % values def formatY(tick): values = getFormatDict(tick) return yformat % values
print(""" 090) Faça um programa que leia nome e média de um aluno, guardando também a situação em um dicionário. No final, mostre o conteúdo a estrutura na tela. """) nome = input('Informe o nome do(a) aluno(a): ').strip() media = float(input(f'Informe e a média de {nome}: ').strip()) erro = 0 if 7 <= media <= 10: situacao = 'Aprovado' elif 5 <= media <= 6.9: situacao = 'Em recuperação' elif 0 <= media < 5: situacao = 'Reprovado' else: erro = 1 situacao = 'Erro ao informar dados. Procure a Adminstração da Escola.' if erro == 1: print(situacao) else: aluno = {'Nome': nome, 'Média': media, 'Situação': situacao } print('-'*30) for chave, valor in aluno.items(): print(f'{chave}: {valor}') print('-'*30)
print('MyMy',end=' ') print('Popsicle') print('Balloon','Helium','Blimp',sep=' and ')
N,M=map(int,input().split()) A=[int(input()) for i in range(M)][::-1] ans=[] s=set() for a in A: if a not in s:ans.append(a) s.add(a) for i in range(1,N+1): if i not in s:ans.append(i) print(*ans,sep="\n")
""" link: https://leetcode.com/problems/power-of-four problem: 问num是否是4的幂,要求O(1) solution: 位运算 """ class Solution: def isPowerOfFour(self, num: int) -> bool: return num > 0 and num & (num - 1) == 0 and num & 0xaaaaaaaa == 0
#fix me.. but for now lets just pass the data back.. def compress(data): return data def decompress(data): return data
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 1 09:26:03 2022 @author: thejorabek """ '''son=10 print(son,type(son)) son=3.14 print(son,type(son)) son='Salom Foundationchilar' print(son,type(son)) son=True print(son,type(son)) son=int() print(son,type(son)) print("Assalom",123,3.14,True,sep='salom') print(1,2,3,4,5,6,7,8,9,10,sep='+',end='') print(' =',1+2+3+4+5+6+7+8+9+10) print(float(son)) print(str(son)) print(bool(son)) son=1 print(bool(son))''' '''a=int(input('a=')) b=int(input('b=')) c=a a=b b=c print("a =",a) print("b =",b)''' '''a=int(input('a=')) b=int(input('b=')) c=int(input('c=')) d=b b=a a=c c=d print('a=',a) print('b=',b) print('c=',c)''' '''a=int(input('a=')) b=int(input('b=')) c=int(input('c=')) d=a a=b b=c c=d print('a=',a) print('b=',b) print('c=',c)''' '''son=int(input("Sonni kiriting: ")) son+=1 print("son=",son,type(son)) fson=float(input("Haqiqiy sonni kiriting: ")) print("fson=",fson,type(fson)) bson=bool(input()) print("bson=",bson) text=input("Textni kiriting: ") print(text,type(text)) text='Salom bolalar' print(text) text="Salom o'rdak" print(text) text="""Salom "Salom BRO" bolalar 'O'rdak' Hello Foundation Ch\tao \nBRO""" print(text)''' '''text="Salom" print(len(text)) print(text[0],text[1],text[2],text[3],text[4]) print(text[-1],text[-2],text[-3],text[-4],text[-5],sep="") print(*text) text="Salom bolalar" print(*text[0:len(text):2],sep=',') # 0-indeksdan oxirigacha 2 ta qadamda sakrash print(*text[::-1]) # stringni teskari chiqarish print(text[:5]) # boshidan 5-indeksgacha chiqarish print(text[6:]) # 6-indeksdan oxirigacha chiqarish # [start : end : step] # start - boshlanish indeksi, end - tugash indeksi, step - oshirish yoki kamayish qadami'''
# -*- coding: utf-8 -*- def find_first_unique_char(s): """ 字符串中找到第一个出现的唯一字符 :param s: :return: """ char_dict = dict() unique_char = list() for char in s: if char_dict.get(char): unique_char.remove(char) else: print(unique_char) unique_char.append(char) char_dict[char] = True print(unique_char) return unique_char[0] if __name__ == '__main__': s = "asdfgashdgflpooh" r = find_first_unique_char(s) print(r)
print('Hello World!!!') if True: print('FROM if') num = 1 while num <= 10: print(num) num += 1 list_ = [1, 2, 3, 4, 5] for i in range(1, 7): print(i)
# -*- coding: utf-8 -*- """ Created on Fri Dec 29 10:35:53 2017 @author: User """ L = [[1,2], [35,4,78], [7,8,1,10],[2,3], [9,1,45]] #def testA(L): # aFactor = 2 # for m in L: # for ind, element in enumerate(m): # newElement = element*aFactor # m.pop(ind) # this works # m.insert(ind, newElement) # this works # return L # #print(testA(L)) # and this works as well def testA(L): for m in L: for ind, element in enumerate(m): m[ind] *= 2 return L print(testA(L))
# -*- coding: utf-8 -*- # Authors: Y. Jia <[email protected]> def binary_search(arr, target, begin=None, end=None): """ :param arr: :param target: :param begin: :param end: :return: """ if begin is None: begin = 0 if end is None: end = len(arr) - 1 if end < begin or end < 0: return False, None elif end == begin: if arr[end] == target: return True, end else: return False, None mid = begin + (end - begin) / 2 if arr[mid] == target: return True, mid elif arr[mid] < target: return binary_search(arr, target, mid + 1, end) else: return binary_search(arr, target, begin, mid - 1)
# # PySNMP MIB module LOWPAN-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LOWPAN-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:58:25 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") NotificationGroup, ObjectGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ObjectGroup", "ModuleCompliance") Integer32, IpAddress, NotificationType, ObjectIdentity, mib_2, Counter32, ModuleIdentity, iso, Gauge32, TimeTicks, Counter64, Unsigned32, Bits, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "IpAddress", "NotificationType", "ObjectIdentity", "mib-2", "Counter32", "ModuleIdentity", "iso", "Gauge32", "TimeTicks", "Counter64", "Unsigned32", "Bits", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") lowpanMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 226)) lowpanMIB.setRevisions(('2014-10-10 00:00',)) if mibBuilder.loadTexts: lowpanMIB.setLastUpdated('201410100000Z') if mibBuilder.loadTexts: lowpanMIB.setOrganization('IETF IPv6 over Networks of Resource-constrained Nodes Working Group') lowpanNotifications = MibIdentifier((1, 3, 6, 1, 2, 1, 226, 0)) lowpanObjects = MibIdentifier((1, 3, 6, 1, 2, 1, 226, 1)) lowpanConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 226, 2)) lowpanStats = MibIdentifier((1, 3, 6, 1, 2, 1, 226, 1, 1)) lowpanReasmTimeout = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 1), Unsigned32()).setUnits('seconds').setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanReasmTimeout.setStatus('current') lowpanInReceives = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanInReceives.setStatus('current') lowpanInHdrErrors = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanInHdrErrors.setStatus('current') lowpanInMeshReceives = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanInMeshReceives.setStatus('current') lowpanInMeshForwds = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanInMeshForwds.setStatus('current') lowpanInMeshDelivers = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanInMeshDelivers.setStatus('current') lowpanInReasmReqds = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanInReasmReqds.setStatus('current') lowpanInReasmFails = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanInReasmFails.setStatus('current') lowpanInReasmOKs = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanInReasmOKs.setStatus('current') lowpanInCompReqds = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanInCompReqds.setStatus('current') lowpanInCompFails = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 11), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanInCompFails.setStatus('current') lowpanInCompOKs = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 12), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanInCompOKs.setStatus('current') lowpanInDiscards = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 13), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanInDiscards.setStatus('current') lowpanInDelivers = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 14), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanInDelivers.setStatus('current') lowpanOutRequests = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 15), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanOutRequests.setStatus('current') lowpanOutCompReqds = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 16), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanOutCompReqds.setStatus('current') lowpanOutCompFails = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 17), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanOutCompFails.setStatus('current') lowpanOutCompOKs = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 18), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanOutCompOKs.setStatus('current') lowpanOutFragReqds = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 19), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanOutFragReqds.setStatus('current') lowpanOutFragFails = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 20), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanOutFragFails.setStatus('current') lowpanOutFragOKs = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 21), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanOutFragOKs.setStatus('current') lowpanOutFragCreates = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 22), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanOutFragCreates.setStatus('current') lowpanOutMeshHopLimitExceeds = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 23), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanOutMeshHopLimitExceeds.setStatus('current') lowpanOutMeshNoRoutes = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 24), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanOutMeshNoRoutes.setStatus('current') lowpanOutMeshRequests = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 25), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanOutMeshRequests.setStatus('current') lowpanOutMeshForwds = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 26), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanOutMeshForwds.setStatus('current') lowpanOutMeshTransmits = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 27), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanOutMeshTransmits.setStatus('current') lowpanOutDiscards = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 28), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanOutDiscards.setStatus('current') lowpanOutTransmits = MibScalar((1, 3, 6, 1, 2, 1, 226, 1, 1, 29), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanOutTransmits.setStatus('current') lowpanIfStatsTable = MibTable((1, 3, 6, 1, 2, 1, 226, 1, 2), ) if mibBuilder.loadTexts: lowpanIfStatsTable.setStatus('current') lowpanIfStatsEntry = MibTableRow((1, 3, 6, 1, 2, 1, 226, 1, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex")) if mibBuilder.loadTexts: lowpanIfStatsEntry.setStatus('current') lowpanIfReasmTimeout = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 1), Unsigned32()).setUnits('seconds').setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfReasmTimeout.setStatus('current') lowpanIfInReceives = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfInReceives.setStatus('current') lowpanIfInHdrErrors = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfInHdrErrors.setStatus('current') lowpanIfInMeshReceives = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfInMeshReceives.setStatus('current') lowpanIfInMeshForwds = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfInMeshForwds.setStatus('current') lowpanIfInMeshDelivers = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfInMeshDelivers.setStatus('current') lowpanIfInReasmReqds = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfInReasmReqds.setStatus('current') lowpanIfInReasmFails = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfInReasmFails.setStatus('current') lowpanIfInReasmOKs = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfInReasmOKs.setStatus('current') lowpanIfInCompReqds = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfInCompReqds.setStatus('current') lowpanIfInCompFails = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 11), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfInCompFails.setStatus('current') lowpanIfInCompOKs = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 12), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfInCompOKs.setStatus('current') lowpanIfInDiscards = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 13), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfInDiscards.setStatus('current') lowpanIfInDelivers = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 14), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfInDelivers.setStatus('current') lowpanIfOutRequests = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 15), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfOutRequests.setStatus('current') lowpanIfOutCompReqds = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 16), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfOutCompReqds.setStatus('current') lowpanIfOutCompFails = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 17), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfOutCompFails.setStatus('current') lowpanIfOutCompOKs = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 18), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfOutCompOKs.setStatus('current') lowpanIfOutFragReqds = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 19), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfOutFragReqds.setStatus('current') lowpanIfOutFragFails = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 20), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfOutFragFails.setStatus('current') lowpanIfOutFragOKs = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 21), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfOutFragOKs.setStatus('current') lowpanIfOutFragCreates = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 22), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfOutFragCreates.setStatus('current') lowpanIfOutMeshHopLimitExceeds = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 23), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfOutMeshHopLimitExceeds.setStatus('current') lowpanIfOutMeshNoRoutes = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 24), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfOutMeshNoRoutes.setStatus('current') lowpanIfOutMeshRequests = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 25), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfOutMeshRequests.setStatus('current') lowpanIfOutMeshForwds = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 26), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfOutMeshForwds.setStatus('current') lowpanIfOutMeshTransmits = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 27), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfOutMeshTransmits.setStatus('current') lowpanIfOutDiscards = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 28), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfOutDiscards.setStatus('current') lowpanIfOutTransmits = MibTableColumn((1, 3, 6, 1, 2, 1, 226, 1, 2, 1, 29), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lowpanIfOutTransmits.setStatus('current') lowpanGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 226, 2, 1)) lowpanCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 226, 2, 2)) lowpanCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 226, 2, 2, 1)).setObjects(("LOWPAN-MIB", "lowpanStatsGroup"), ("LOWPAN-MIB", "lowpanStatsMeshGroup"), ("LOWPAN-MIB", "lowpanIfStatsGroup"), ("LOWPAN-MIB", "lowpanIfStatsMeshGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): lowpanCompliance = lowpanCompliance.setStatus('current') lowpanStatsGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 226, 2, 1, 1)).setObjects(("LOWPAN-MIB", "lowpanReasmTimeout"), ("LOWPAN-MIB", "lowpanInReceives"), ("LOWPAN-MIB", "lowpanInHdrErrors"), ("LOWPAN-MIB", "lowpanInMeshReceives"), ("LOWPAN-MIB", "lowpanInReasmReqds"), ("LOWPAN-MIB", "lowpanInReasmFails"), ("LOWPAN-MIB", "lowpanInReasmOKs"), ("LOWPAN-MIB", "lowpanInCompReqds"), ("LOWPAN-MIB", "lowpanInCompFails"), ("LOWPAN-MIB", "lowpanInCompOKs"), ("LOWPAN-MIB", "lowpanInDiscards"), ("LOWPAN-MIB", "lowpanInDelivers"), ("LOWPAN-MIB", "lowpanOutRequests"), ("LOWPAN-MIB", "lowpanOutCompReqds"), ("LOWPAN-MIB", "lowpanOutCompFails"), ("LOWPAN-MIB", "lowpanOutCompOKs"), ("LOWPAN-MIB", "lowpanOutFragReqds"), ("LOWPAN-MIB", "lowpanOutFragFails"), ("LOWPAN-MIB", "lowpanOutFragOKs"), ("LOWPAN-MIB", "lowpanOutFragCreates"), ("LOWPAN-MIB", "lowpanOutDiscards"), ("LOWPAN-MIB", "lowpanOutTransmits")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): lowpanStatsGroup = lowpanStatsGroup.setStatus('current') lowpanStatsMeshGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 226, 2, 1, 2)).setObjects(("LOWPAN-MIB", "lowpanInMeshForwds"), ("LOWPAN-MIB", "lowpanInMeshDelivers"), ("LOWPAN-MIB", "lowpanOutMeshHopLimitExceeds"), ("LOWPAN-MIB", "lowpanOutMeshNoRoutes"), ("LOWPAN-MIB", "lowpanOutMeshRequests"), ("LOWPAN-MIB", "lowpanOutMeshForwds"), ("LOWPAN-MIB", "lowpanOutMeshTransmits")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): lowpanStatsMeshGroup = lowpanStatsMeshGroup.setStatus('current') lowpanIfStatsGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 226, 2, 1, 3)).setObjects(("LOWPAN-MIB", "lowpanIfReasmTimeout"), ("LOWPAN-MIB", "lowpanIfInReceives"), ("LOWPAN-MIB", "lowpanIfInHdrErrors"), ("LOWPAN-MIB", "lowpanIfInMeshReceives"), ("LOWPAN-MIB", "lowpanIfInReasmReqds"), ("LOWPAN-MIB", "lowpanIfInReasmFails"), ("LOWPAN-MIB", "lowpanIfInReasmOKs"), ("LOWPAN-MIB", "lowpanIfInCompReqds"), ("LOWPAN-MIB", "lowpanIfInCompFails"), ("LOWPAN-MIB", "lowpanIfInCompOKs"), ("LOWPAN-MIB", "lowpanIfInDiscards"), ("LOWPAN-MIB", "lowpanIfInDelivers"), ("LOWPAN-MIB", "lowpanIfOutRequests"), ("LOWPAN-MIB", "lowpanIfOutCompReqds"), ("LOWPAN-MIB", "lowpanIfOutCompFails"), ("LOWPAN-MIB", "lowpanIfOutCompOKs"), ("LOWPAN-MIB", "lowpanIfOutFragReqds"), ("LOWPAN-MIB", "lowpanIfOutFragFails"), ("LOWPAN-MIB", "lowpanIfOutFragOKs"), ("LOWPAN-MIB", "lowpanIfOutFragCreates"), ("LOWPAN-MIB", "lowpanIfOutDiscards"), ("LOWPAN-MIB", "lowpanIfOutTransmits")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): lowpanIfStatsGroup = lowpanIfStatsGroup.setStatus('current') lowpanIfStatsMeshGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 226, 2, 1, 4)).setObjects(("LOWPAN-MIB", "lowpanIfInMeshForwds"), ("LOWPAN-MIB", "lowpanIfInMeshDelivers"), ("LOWPAN-MIB", "lowpanIfOutMeshHopLimitExceeds"), ("LOWPAN-MIB", "lowpanIfOutMeshNoRoutes"), ("LOWPAN-MIB", "lowpanIfOutMeshRequests"), ("LOWPAN-MIB", "lowpanIfOutMeshForwds"), ("LOWPAN-MIB", "lowpanIfOutMeshTransmits")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): lowpanIfStatsMeshGroup = lowpanIfStatsMeshGroup.setStatus('current') mibBuilder.exportSymbols("LOWPAN-MIB", lowpanIfOutFragCreates=lowpanIfOutFragCreates, lowpanIfReasmTimeout=lowpanIfReasmTimeout, lowpanOutFragCreates=lowpanOutFragCreates, lowpanOutFragReqds=lowpanOutFragReqds, lowpanReasmTimeout=lowpanReasmTimeout, lowpanOutMeshHopLimitExceeds=lowpanOutMeshHopLimitExceeds, lowpanIfStatsTable=lowpanIfStatsTable, lowpanIfInCompReqds=lowpanIfInCompReqds, lowpanOutRequests=lowpanOutRequests, lowpanIfOutTransmits=lowpanIfOutTransmits, lowpanIfInReasmOKs=lowpanIfInReasmOKs, lowpanIfOutCompReqds=lowpanIfOutCompReqds, lowpanMIB=lowpanMIB, lowpanInReasmOKs=lowpanInReasmOKs, lowpanOutMeshRequests=lowpanOutMeshRequests, lowpanOutMeshTransmits=lowpanOutMeshTransmits, lowpanInHdrErrors=lowpanInHdrErrors, lowpanIfOutDiscards=lowpanIfOutDiscards, PYSNMP_MODULE_ID=lowpanMIB, lowpanNotifications=lowpanNotifications, lowpanInMeshReceives=lowpanInMeshReceives, lowpanOutMeshForwds=lowpanOutMeshForwds, lowpanIfOutFragReqds=lowpanIfOutFragReqds, lowpanInReasmFails=lowpanInReasmFails, lowpanIfOutRequests=lowpanIfOutRequests, lowpanInReceives=lowpanInReceives, lowpanIfStatsGroup=lowpanIfStatsGroup, lowpanInCompReqds=lowpanInCompReqds, lowpanInReasmReqds=lowpanInReasmReqds, lowpanOutDiscards=lowpanOutDiscards, lowpanInCompFails=lowpanInCompFails, lowpanIfInMeshDelivers=lowpanIfInMeshDelivers, lowpanCompliance=lowpanCompliance, lowpanInMeshDelivers=lowpanInMeshDelivers, lowpanIfStatsEntry=lowpanIfStatsEntry, lowpanOutCompReqds=lowpanOutCompReqds, lowpanIfOutFragFails=lowpanIfOutFragFails, lowpanObjects=lowpanObjects, lowpanStats=lowpanStats, lowpanOutFragFails=lowpanOutFragFails, lowpanIfInReasmReqds=lowpanIfInReasmReqds, lowpanInMeshForwds=lowpanInMeshForwds, lowpanIfOutCompFails=lowpanIfOutCompFails, lowpanIfOutCompOKs=lowpanIfOutCompOKs, lowpanConformance=lowpanConformance, lowpanIfInReceives=lowpanIfInReceives, lowpanOutFragOKs=lowpanOutFragOKs, lowpanOutCompFails=lowpanOutCompFails, lowpanIfInCompOKs=lowpanIfInCompOKs, lowpanIfInReasmFails=lowpanIfInReasmFails, lowpanStatsGroup=lowpanStatsGroup, lowpanIfOutMeshTransmits=lowpanIfOutMeshTransmits, lowpanStatsMeshGroup=lowpanStatsMeshGroup, lowpanIfInCompFails=lowpanIfInCompFails, lowpanIfOutMeshHopLimitExceeds=lowpanIfOutMeshHopLimitExceeds, lowpanGroups=lowpanGroups, lowpanIfOutFragOKs=lowpanIfOutFragOKs, lowpanInCompOKs=lowpanInCompOKs, lowpanOutCompOKs=lowpanOutCompOKs, lowpanIfInMeshForwds=lowpanIfInMeshForwds, lowpanIfInDelivers=lowpanIfInDelivers, lowpanCompliances=lowpanCompliances, lowpanIfOutMeshNoRoutes=lowpanIfOutMeshNoRoutes, lowpanInDiscards=lowpanInDiscards, lowpanIfOutMeshForwds=lowpanIfOutMeshForwds, lowpanIfInHdrErrors=lowpanIfInHdrErrors, lowpanInDelivers=lowpanInDelivers, lowpanIfInDiscards=lowpanIfInDiscards, lowpanOutMeshNoRoutes=lowpanOutMeshNoRoutes, lowpanOutTransmits=lowpanOutTransmits, lowpanIfOutMeshRequests=lowpanIfOutMeshRequests, lowpanIfStatsMeshGroup=lowpanIfStatsMeshGroup, lowpanIfInMeshReceives=lowpanIfInMeshReceives)
def split_targets(targets, target_sizes): results = [] offset = 0 for size in target_sizes: results.append(targets[offset:offset + size]) offset += size return results
class Aggrraidtype(basestring): """ raid_dp|raid4 Possible values: <ul> <li> "raid_dp" , <li> "raid4" , <li> "raid0" , <li> "mixed_raid_type" </ul> """ @staticmethod def get_api_name(): return "aggrraidtype"
""" interploation search # interploation and binary are both require a SORTED list let said you have the follow phone number prefix array, and you are looking for 1144 0011, 0022, 0033, 1144, 1166, 1188, 3322, 3344, 3399 instead of using binary search in the middle, or linear search from the left. we only want to search the subset with same prefix, like inside [1144, 1166, 1188] to calculate the mid mid = low + ((high - low) / (A[high] - A[low])) * (x - A[low]) # x is the value we are seeking """ data = list(range(1_000_001)) search_value = 999_999 def linear_search(search_value, data): for index, value in enumerate(data): if value == search_value: print(f"Element is found after {index} attempts") def binary_search(search_value, data): left = 0 right = len(data) - 1 attempts = 1 founded = False while not founded: mid = ((right - left) // 2) + left # print(f"left {left}") # print(f'right {right}') # print(f"mid {mid}") if data[mid] == search_value: print(f"Element is found after {attempts} attempts") founded = True if search_value < data[mid]: right = mid - 1 else: left = mid + 1 attempts += 1 def interploation_search(search_value, data): left = 0 right = len(data) - 1 attempts = 1 founded = False while not founded: mid = int( left + ((right - left) / data[right] - data[left]) * (search_value - data[left]) ) # print(f"left {left}") # print(f"right {right}") # print(f"mid {mid}") if data[mid] == search_value: print(f"Element is found after {attempts} attempts") founded = True if search_value < data[mid]: right = mid - 1 else: left = mid + 1 attempts += 1 linear_search(search_value, data) binary_search(search_value, data) interploation_search(search_value, data)
# This sample tests the case where a finally clause contains some conditional # logic that narrows the type of an expression. This narrowed type should # persist after the finally clause. def func1(): file = None try: file = open("test.txt") except Exception: return None finally: if file: file.close() reveal_type(file, expected_text="TextIOWrapper") def func2(): file = None try: file = open("test.txt") except Exception: pass finally: if file: file.close() reveal_type(file, expected_text="TextIOWrapper | None") def func3(): file = None try: file = open("test.txt") finally: pass reveal_type(file, expected_text="TextIOWrapper")
def remove_passwords(instances): clean_instances = [] for instance in instances: clean_instance = {} for k in instance.keys(): if k != 'password': clean_instance[k] = instance[k] clean_instances.append(clean_instance) return clean_instances
class cURL: def __init__(self, url_='.'): self.url = url_ def replace(self, replaceURL_, start_, end_): ''' example: 'https://www.google.com/search' https:// -> -1 www.google.com -> 0 search -> 1 ''' if start_ == -1: start_ = 0 else: start_ +=2 end_ += 2 urllist = self.url.split('/') wrongURL = '/'.join(urllist[start_:end_]) newURL= self.url.replace(wrongURL,replaceURL_) return newURL
def get_primes(n): # Based on Eratosthenes Sieve # Initially all numbers are prime until proven otherwise # False = Prime number, True = Compose number nonprimes = n * [False] count = 0 nonprimes[0] = nonprimes[1] = True prime_numbers = [] for i in range(2, n): if not nonprimes[i]: prime_numbers.append(i) count += 1 for j in range(2*i, n, i): nonprimes[j] = True return prime_numbers
""" link: https://leetcode-cn.com/problems/the-maze-ii problem: 求二维迷宫矩阵中,小球从 A 点到 B 点的最短路径,小球只能沿一个方向滚动直至碰壁 solution: BFS。广搜反复松弛,检查目标点是否优于之前搜索结果。 """ class Solution: def shortestDistance(self, maze: List[List[int]], start: List[int], destination: List[int]) -> int: if not maze or not maze[0]: return -1 n, m, q = len(maze), len(maze[0]), [(start[0], start[1])] visit = [[-1 for _ in range(m)] for _ in range(n)] visit[start[0]][start[1]] = 0 d = [(1, 0), (-1, 0), (0, 1), (0, -1)] while q: x, y = q[0][0], q[0][1] q.pop(0) for ii, jj in d: i, j, cnt = x + ii, y + jj, 1 while 0 <= i < n and 0 <= j < m and maze[i][j] == 0: i, j = i + ii, j + jj cnt += 1 i, j = i - ii, j - jj cnt -= 1 if visit[i][j] == -1 or visit[i][j] > visit[x][y] + cnt: visit[i][j] = visit[x][y] + cnt q.append((i, j)) return visit[destination[0]][destination[1]]
'''DATALOADERS''' def LoadModel(name): # print(name) # classes = [] # D = 0 # H = 0 # W = 0 # Height = 0 # Width = 0 # Bands = 0 # samples = 0 if name == 'PaviaU': classes = [] #Size of 3D images D = 610 H = 340 W = 103 #Size of patches Height = 27 Width = 21 Bands = 103 samples = 2400 patch = 300000 elif name == 'IndianPines': classes = ["Undefined", "Alfalfa", "Corn-notill", "Corn-mintill", "Corn", "Grass-pasture", "Grass-trees", "Grass-pasture-mowed", "Hay-windrowed", "Oats", "Soybean-notill", "Soybean-mintill", "Soybean-clean", "Wheat", "Woods", "Buildings-Grass-Trees-Drives", "Stone-Steel-Towers"] #Size of 3D images D = 145 H = 145 W = 200 #Size of patches # Height = 17 # Width = 17 Height = 19 Width = 17 Bands = 200 samples = 4000 patch = 300000 elif name == 'Botswana': classes = ["Undefined", "Water", "Hippo grass", "Floodplain grasses 1", "Floodplain grasses 2", "Reeds", "Riparian", "Firescar", "Island interior", "Acacia woodlands", "Acacia shrublands", "Acacia grasslands", "Short mopane", "Mixed mopane", "Exposed soils"] #Size of 3D images D = 1476 H = 256 W = 145 #Size of patches Height = 31 Width = 21 Bands = 145 samples = 1500 patch = 30000 elif name == 'KSC': classes = ["Undefined", "Scrub", "Willow swamp", "Cabbage palm hammock", "Cabbage palm/oak hammock", "Slash pine", "Oak/broadleaf hammock", "Hardwood swamp", "Graminoid marsh", "Spartina marsh", "Cattail marsh", "Salt marsh", "Mud flats", "Wate"] #Size of 3D images D = 512 H = 614 W = 176 #Size of patches Height = 31 Width = 27 Bands = 176 samples = 2400 patch = 30000 elif name == 'Salinas': classes = [] #Size of 3D images D = 512 H = 217 W = 204 #Size of patches Height = 21 Width = 17 Bands = 204 samples = 2600 patch = 300000 elif name == 'SalinasA': classes = [] #Size of 3D images D = 83 H = 86 W = 204 #Size of patches Height = 15 Width = 11 Bands = 204 samples = 2400 patch = 300000 elif name == 'Samson': classes = [] #Size of 3D images D = 95 H = 95 W = 156 #Size of patches Height = 10 Width = 10 Bands = 156 samples = 1200 patch = 30000 return Width, Height, Bands, samples, D, H, W, classes, patch
parallel = dict( data=1, pipeline=1, tensor=dict(size=4, mode='2d'), )
# -*- coding: utf-8 -*- """ #============================================================================= # ProjectName: leetcode # FileName: the_difference_between_two_sorted_arrays # Desc: 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2 # 请找出这 存在nums1数组中,但是不存在nums2数组中的所有数字,要求算法的时间复杂度为 O(log (m+n)) # 示例 1: # nums1 = [1, 3] # nums2 = [2, 3] # 结果是 [1] # Author: seekplum # Email: [email protected] # HomePage: seekplum.github.io # Create: 2019-04-26 19:03 #============================================================================= """ # def check(num, pos): # return 1 if num >= b[pos] else 0 # # # # l = 0 # # r = len(b) # def divide(l, r, num): # while l <= r: # mid = (l + r) / 2 # result = check(num, mid) # if result == 1: # r = mid - 1 # elif result == 0: # l = mid + 1 # # return num == b[l] def divide(nums1, nums2): """查存在nums1但不存在nums2的所有元素 """ result = [] i = 0 j = 0 length1 = len(nums1) length2 = len(nums2) while i < length1 and j < length2: num1 = nums1[i] num2 = nums2[j] if num1 < num2: result.append(num1) i += 1 elif num1 > num2: j += 1 else: i += 1 j += 1 # 处理 nums1 数组中还有元素未对比的情况 result.extend(nums1[i:]) return result
# -*- coding: utf-8 -*- project = "thumbtack-client" copyright = "2019, The MITRE Corporation" author = "The MITRE Corporation" version = "0.3.0" release = "0.3.0" extensions = [ "sphinx.ext.autodoc", "sphinx.ext.napoleon", "sphinx.ext.viewcode", ] templates_path = ["_templates"] source_suffix = ".rst" master_doc = "index" language = None exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] pygments_style = "sphinx" html_theme = "sphinx_rtd_theme" html_theme_options = { # 'canonical_url': '', # 'analytics_id': '', # 'logo_only': False, "display_version": True, "prev_next_buttons_location": "bottom", # 'style_external_links': False, # 'vcs_pageview_mode': '', # Toc options "collapse_navigation": False, "sticky_navigation": True, "navigation_depth": 2, # 'includehidden': True, # 'titles_only': False } htmlhelp_basename = "thumbtack-clientdoc" latex_elements = {} latex_documents = [ ( master_doc, "thumbtack-client.tex", "thumbtack-client Documentation", "The MITRE Corporation", "manual", ), ] man_pages = [ (master_doc, "thumbtack-client", "thumbtack-client Documentation", [author], 1) ] texinfo_documents = [ ( master_doc, "thumbtack-client", "thumbtack-client Documentation", author, "thumbtack-client", "One line description of project.", "Miscellaneous", ), ]
def main(): result = 0 with open("input.txt") as input_file: for x in input_file: x = int(x) while True: x = x // 3 - 2 if x < 0: break result += x print(result) if __name__ == "__main__": main()
DATAMART_AUGMENT_PROCESS = 'DATAMART_AUGMENT_PROCESS' # ---------------------------------------------- # Related to the "Add User Dataset" process # ---------------------------------------------- ADD_USER_DATASET_PROCESS = 'ADD_USER_DATASET_PROCESS' ADD_USER_DATASET_PROCESS_NO_WORKSPACE = 'ADD_USER_DATASET_PROCESS_NO_WORKSPACE' NEW_DATASET_DOC_PATH = 'new_dataset_doc_path' DATASET_NAME_FROM_UI = 'name' # from dataset.js DATASET_NAME = 'dataset_name' # from dataset.js SKIP_CREATE_NEW_CONFIG = 'SKIP_CREATE_NEW_CONFIG' # ---------------------------------------------- # Extensions # ---------------------------------------------- EXT_CSV = '.csv' EXT_TAB = '.tab' EXT_TSV = '.tsv' EXT_XLS = '.xls' EXT_XLSX = '.xlsx' VALID_EXTENSIONS = (EXT_CSV, EXT_TAB, EXT_TSV, EXT_XLS, EXT_XLSX) # ---------------------------------------------- # For creating a datasetDoc # ---------------------------------------------- DATASET_SCHEMA_VERSION = '4.0.0' # create a datasetDoc PROBLEM_SCHEMA_VERSION = '4.0.0' # Map Pandas types to the types used in the datasetDoc # mapping from: https://pbpython.com/pandas_dtypes.html # -> https://gitlab.datadrivendiscovery.org/MIT-LL/d3m_data_supply/blob/shared/schemas/datasetSchema.json DTYPES = { 'int64': 'integer', 'float64': 'real', 'bool': 'boolean', 'object': 'string', 'datetime64': 'dateTime', 'category': 'categorical' }
alpha_num_dict = { 'a':1, 'b':2, 'c':3 } alpha_num_dict['a'] = 10 print(alpha_num_dict['a'])
""" 面试题 13:机器人的运动范围 题目:地上有一个 m 行 n 列的方格。一个机器人从坐标 (0, 0) 的格子开始移动,它 每一次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标的数位之和 大于 k 的格子。例如,当 k 为 18 时,机器人能够进入方格 (35, 37),因为 3+5+3+7=18。 但它不能进入方格 (35, 38),因为 3+5+3+8=19。请问该机器人能够到达多少个格子? """ def moving_count(rows: int, cols: int, threshold: int) -> int: """ Count moving steps under the given rows, clos and threshold. Parameters ----------- rows: int Matrix rows cols: int Matrix cols threshold: int The given condition Returns --------- out: int How many cells can reach. Notes ------ We could treat the (row, col) as the center of a cell. """ if rows <= 0 or cols <= 0 or threshold < 0: return 0 visited = [] for i in range(rows): tmp = [] for j in range(cols): tmp.append(False) visited.append(tmp) res = moving_count_core(rows, cols, 0, 0, threshold, visited) return res def moving_count_core(rows, cols, row, col, threshold, visited) -> int: """ Recursive caculation. Notes -------- The key points are as belows: - condition threshold - condition visited - count 1+ because the cell it stands is surely it can enter. - do not need to go back """ count = 0 if (row >= 0 and row < rows and col >= 0 and col < cols and get_digit_num(row) + get_digit_num(col) <= threshold and not visited[row][col]): visited[row][col] = True count = 1 + ( moving_count_core(rows, cols, row+1, col, threshold, visited) + moving_count_core(rows, cols, row-1, col, threshold, visited) + moving_count_core(rows, cols, row, col+1, threshold, visited) + moving_count_core(rows, cols, row, col-1, threshold, visited) ) return count def get_digit_num(num: int) -> int: """ Return sum of each in a number. """ res = 0 while num: res += num % 10 num //= 10 return res if __name__ == '__main__': res = moving_count(1, 10, 9) print(res)
""" Time: Best: O(n) Average: O(n^2) Worst: O(n^2) Space: O(1) Stable: Yes Worst Case Scenario: Reverse Sorted Array Algorithm Overview: This algorithm works like how a person would normally sort a hand of cards from left to right. You take the second card and compare with all the cards to the left, shifting over each card which is larger than the card you are trying to sort. The algorithm starts at the second element, and persists the element's index in a pointer. It then iterates over all the items to the left by moving the pointer back until either the index pointer is at 0 or it finds an element on the left hand side which is less than the current item. It then persists the element before that item. """ def insertion_sort(arr): # Assume that the first element in the list is sorted, begin iteration at second element, index 1 for current_index in range(1, len(arr)): # current item is the not sorted item we want to put in the correct place in the sorted array # Everything to the left of this item is sorted, and this item and everything to the right is not sorted current_item = arr[current_index] # pointer to the index where the above item should go, initialized at the current item's current position insert_index = current_index # while your previous index does not go beyond the min index (0) # and the current item is smaller than the previous item while insert_index > 0 and current_item < arr[insert_index - 1]: # Copy the larger item before the current item to the current item's place arr[insert_index] = arr[insert_index - 1] # push your insert pointer back insert_index -= 1 # Either your previous pointer will now be 0 in which case you have reached the start of the array # or you reached an item smaller than the current item # This exists the loop # Now you can move the current item to the empty space created by moving the other items forward # and begin the next pass of the sorting algorithm arr[insert_index] = current_item if __name__ == '__main__': arr = [8, 3, 1, 2] insertion_sort(arr) print(arr)
# https://leetcode.com/problems/minimum-size-subarray-sum/ class Solution: def minSubArrayLen(self, target: int, nums: list[int]) -> int: min_len = float('inf') curr_sum = 0 nums_added = 0 for idx in range(len(nums)): num = nums[idx] if num >= target: return 1 curr_sum += num nums_added += 1 while nums_added > 1 and ( curr_sum - nums[idx - nums_added + 1] >= target): curr_sum -= nums[idx - nums_added + 1] nums_added -= 1 if curr_sum >= target: min_len = min(min_len, nums_added) return 0 if min_len == float('inf') else min_len
#!/usr/bin/env python # encoding: utf-8 class Dynamic(str): """Wrapper for the strings that need to be dynamically interpreted by the generated Python files.""" pass
#!/usr/bin/env python # -*- coding: utf-8 -*- """View module for Find Convex Hull program Notes ----- Comments are omitted because code is self-explanatory. """ colors = [ 'aquamarine', 'azure', 'blue', 'brown', 'chartreuse', 'chocolate', 'coral', 'crimson', 'cyan', 'darkblue', 'darkgreen', 'fuchsia', 'gold', 'green', 'grey', 'indigo', 'khaki', 'lavender', 'lightblue', 'lightgreen', 'lime', 'magenta', 'maroon', 'navy', 'olive', 'orange', 'orangered', 'orchid', 'pink', 'plum', 'purple', 'red', 'salmon', 'sienna', 'tan', 'teal', 'tomato', 'turquoise', 'violet', 'wheat', 'yellow', 'yellowgreen', ] colors = list(map(lambda x: f"xkcd:{x}", colors)) def displayHeader(title: str) -> None: n = (60 - len(title) - 4) // 2 if n > 0: header = f"\n {'=' * n} {title} {'=' * n}\n" else: header = f"\n {title}\n" print(header) def displayList(lst: list, key = None) -> None: maxSpace = len(str(len(lst))) for i in range(len(lst)): x = lst[i][key] if key else lst[i] spacing = maxSpace - len(str(i + 1)) + 4 print(f"{' ' * spacing}{i + 1}. {x}") print('') def toTitle(label: str) -> str: return label.replace('_', ' ').title() def inputInt(prompt: str, minval: int = None, maxval: int = None, exclude: list = None) -> int: while True: try: inp = int(input(prompt + " ")) if (minval is not None and inp < minval) or (maxval is not None and inp > maxval): print(f"Number must be between {minval} and {maxval}.") raise Exception if exclude is not None and inp in exclude: print(f"Number cannot be {inp}.") raise Exception return inp except ValueError: print("Invalid number.") except Exception: pass
class DataGridSelectionUnit(Enum,IComparable,IFormattable,IConvertible): """ Defines constants that specify whether cells,rows,or both,are used for selection in a System.Windows.Controls.DataGrid control. enum DataGridSelectionUnit,values: Cell (0),CellOrRowHeader (2),FullRow (1) """ def __eq__(self,*args): """ x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """ pass def __format__(self,*args): """ __format__(formattable: IFormattable,format: str) -> str """ pass def __ge__(self,*args): pass def __gt__(self,*args): pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __le__(self,*args): pass def __lt__(self,*args): pass def __ne__(self,*args): pass def __reduce_ex__(self,*args): pass def __str__(self,*args): pass Cell=None CellOrRowHeader=None FullRow=None value__=None
class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: l = 0 r = len(A) - 1 while l < r: if A[l] % 2 == 1 and A[r] % 2 == 0: A[l], A[r] = A[r], A[l] if A[l] % 2 == 0: l += 1 if A[r] % 2 == 1: r -= 1 return A
peso = float(input('Peso em Kilogramas: ')) altura = float(input('Altura em Centimetros: ')) imc = peso / ((altura / 100) ** 2) print('O IMC esta em {:.2f}'.format(imc)) if imc < 18.5: print('Abaixo do Peso!') elif imc <= 25: print('Peso Ideal') elif imc <= 30: print('Sobrepeso') elif imc <= 40: print('Obesidade') elif imc > 40: print('Obesidade Morbida')
def test(): assert ( 'spacy.blank("en")' in __solution__ ), "Você inicializou um fluxo de processamento em Inglês vazio?" assert "DocBin(docs=docs)" in __solution__, "Você criou o DocBin corretamente?" assert "doc_bin.to_disk(" in __solution__, "Você utilizou o método to_disk?" assert "train.spacy" in __solution__, "Você criou um arquivo com o nome correto?" __msg__.good("Muito bem! Tudo certo por aqui.")
""" Place class. Part of the StoryTechnologies project. August 17, 2019 Brett Alistair Kromkamp ([email protected]) """ class TimeInterval: def __init__(self, from_time_point: str, to_time_point: str) -> None: self.from_time_point = from_time_point self.to_time_point = to_time_point
class Menu(object): def __init__(self): gameList = None; def _populateGameList(self): pass def chooseGame(self): pass def start(self): pass
class Solution: # @param {integer[]} candidates # @param {integer} target # @return {integer[][]} def combinationSum2(self, candidates, target): self.results = [] candidates.sort() self.combination(candidates, target, 0, []) return self.results def combination(self,candidates, target, start, result): if target == 0 : self.results.append(result[:]) elif target > 0: for i in range(start, len(candidates)): if i > start and candidates[i] == candidates[i-1]: continue result.append(candidates[i]) self.combination(candidates, target-candidates[i], i + 1, result) result.pop()
cadastro = list() while True: pessoa = dict() pessoa['nome'] = str(input('Nome: ')) pessoa['sexo'] = str(input('Sexo: ')) pessoa['idade'] = int(input('Idade: ')) cadastro.append(pessoa.copy()) resp = str(input('Quer continuar? (S/N) ')) if resp in "Nn": break print("-="*30) total = len(cadastro) print(f'- O grupo tem {total} pessoas.') mulheres = list() soma = 0 for p in cadastro: soma = soma + p['idade'] if p['sexo'] in "Ff": mulheres.append(p['nome']) media = soma / total print(f'- A média de idade é de {media} anos.') print(f'- As mulheres cadastradas foram: {mulheres}.') print("- Lista das pessoas que estão acima da média:") for p in cadastro: if p['idade'] > media: for k, v in p.items(): print(f'{k} = {v}; ', end='') print() print("<< ENCERRADO >>")
# -*- coding: utf-8 -*- """ file_utils module to hold simple bioinformatics course text file parsing class """ INPUT_STRING = 'Input' OUTPUT_STRING = 'Output' class FileUtil(object): """ Holds I/O values parsed from course text files for example problems Initialized with a text file, parses 'Input' and 'Output' values to object attributes. Args: filename (str): filename pointing to supplied text file Attributes: inputs (list): inputs from supplied text file outputs (list): expected outputs from supplied text file """ def __init__(self, filename): self.parse_file(filename) def parse_file(self, filename): """ Helper function parses course text files and returns the list of inputs and, if provided, the list of expected outputs If no input string is found all items before output string are returned to inputs, if neither input string nor output string is found then all items are returned to input string. Space delimited strings are separated. Args: filename (str): filename pointing to supplied text file Returns: inputs (list): inputs from supplied text file outputs (list): expected outputs from supplied text file """ with open(filename, 'r') as f: raw_text = f.read() raw_args = [s for i in raw_text.splitlines() for s in i.split(' ')] try: input_index = raw_args.index(INPUT_STRING) except ValueError: input_index = -1 try: output_index = raw_args.index(OUTPUT_STRING) except ValueError: output_index = len(raw_args) self.inputs = raw_args[input_index+1:output_index] self.outputs = raw_args[output_index+1:]
t = int(input()) def solve(): candy = 0 x = input() r, c = map(int, input().split()) a = [] for _ in range(r): a.append(input()) for i in range(r): for j in range(c - 2): if a[i][j] == '>' and a[i][j + 1] == 'o' and a[i][j + 2] == '<': candy += 1 for i in range(r - 2): for j in range(c): if a[i][j] == 'v' and a[i + 1][j] == 'o' and a[i + 2][j] == '^': candy += 1 print(candy) for _ in range(t): solve()
# Write_a_function # Created by JKChang # 14/08/2018, 10:58 # Tag: # Description: https://www.hackerrank.com/challenges/write-a-function/problem # In the Gregorian calendar three criteria must be taken into account to identify leap years: # The year can be evenly divided by 4, is a leap year, unless: # The year can be evenly divided by 100, it is NOT a leap year, unless: # The year is also evenly divisible by 400. Then it is a leap year. def is_leap(year): leap = False if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: leap = True return leap year = int(input()) print(is_leap(year))
class NorthInDTO(object): def __init__(self): self.platformIp = None self.platformPort = None def getPlatformIp(self): return self.platformIp def setPlatformIp(self, platformIp): self.platformIp = platformIp def getPlatformPort(self): return self.platformPort def setPlatformPort(self, platformPort): self.platformPort = platformPort
h, m = map(int, input().split()) if h - 1 < 0: h = 23 m += 15 print(h,m) elif m - 45 < 0: h -= 1 m += 15 print(h, m) else: m -= 45 print(h, m)
class Settings(): """ This is just variables stored as properties of a class. It still needs (allthough void) .inputs(), .output() and .build() and defines whatever else is handy. (It is nice, as in this case, to separate constants from methods.) """ def inputs(self): return None def output(self): return None def build(self): pass query = 'felines'
anum1 = int(input('Digite 1° valor: ')) bnum2 = int(input('Digite 2° valor: ')) cnum3 = int(input('Digite 3° valor: ')) #verificando quem é menor menor = anum1 if bnum2 < anum1 and bnum2 < cnum3: menor = bnum2 if cnum3 < anum1 and cnum3 < bnum2: menor = cnum3 #verificando quem é maior maior = anum1 if bnum2 > anum1 and bnum2 > cnum3: maior = bnum2 if cnum3 > anum1 and cnum3 > bnum2: maior = cnum3 print('O menor valor digitado foi {}'.format(menor)) print('O maior valor digitado foi {}'.format(maior))
# 009.py 리스트 = [i for i in range(10)] for i in 리스트 : print(i) ''' 1 2 3 4 5 6 7 8 9 ''' for i in 'kimminsu' : print(i) ''' k i m m i n s u '''
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Advent of Code 2020 Day 4, Part 2 """ class Passport: def __init__(self, byr=-1, iyr=-1, eyr=-1, hgt=-1, hfc=-1, ecl=-1, pid=-1, cid=-1): self.fields = { 'byr': byr, 'iyr': iyr, 'eyr': eyr, 'hgt': hgt, 'hcl': hfc, 'ecl': ecl, 'pid': pid, 'cid': cid, } def parse(line): fields = line.split() field_dict = {} for field in fields: key1, value1 = field.split(':') field_dict[key1] = value1 return field_dict def is_invalid(key, value): if key == 'byr' and (int(value) < 1920 or int(value) > 2002): return True if key == 'iyr' and (int(value) < 2010 or int(value) > 2020): return True if key == 'eyr' and (int(value) < 2020 or int(value) > 2030): return True if key == 'hgt': if value[-2:] == 'cm': if int(value[:-2]) < 150 or int(value[:-2]) > 193: return True elif value[-2:] == 'in': if int(value[:-2]) < 59 or int(value[:-2]) > 76: return True else: return True if key == 'hcl': if value[0] != '#': return True value = value[1:] if len(value) != 6: return True for c in value: if not (c.isdigit() or c in 'abcdef'): return True if key == 'ecl': if value not in ('amb', 'blu', 'brn', 'grn', 'gry', 'hzl', 'oth'): return True if key == 'pid': if len(value) != 9: return True return False def main(): with open('in.txt') as f: lines = f.readlines() counter = 0 total_passports = 0 passport = Passport() for line in lines: line = line.strip() if len(line) == 0: for key, value in passport.fields.items(): if key != 'cid' and value == -1 or is_invalid(key, value): counter += 1 break total_passports += 1 passport = Passport() d = parse(line) for key, value in d.items(): passport.fields[key] = value print(total_passports - counter) if __name__ == '__main__': main()
class Pessoa: def __init__(self, nome, email, celular): self.nome = nome self.email = email self.celular = celular def get_nome(self): return f"Caro(a) {self.nome}" def get_email(self): return(self.email) def get_celular(self): return(self.celular) def set_nome(self, nome): self.nome = nome def set_email(self, email): self.email = email def set_celular(self, celular): self.celular = celular class Aluno(Pessoa): def __init__(self, nome, email, celular, sigla, m, r, d=[]): super().__init__(nome, email, celular) self.sigla = sigla self.mensalidade = m self.ra = r self.disciplina = d def __repr__(self): return 'Aluno: %s | Curso: %s' %(self.nome,self.sigla) ###Getando os atrigutos (Devolvendo os valores deles) def get_sigla(self): return(f"{self.sigla[0]},{self.sigla[1]},{self.sigla[2]}") def get_mensalidade(self): return 'R$ %.2f' %self.mensalidade def get_ra(self): return self.ra def get_disciplina(self): return self.disciplina #### setando os atributos ( Dando valor a eles.) def set_disciplina(self, m): self.disciplina.append(m) def set_mensalidade(self, mensalidade): self.mensalidade = mensalidade def set_sigla(self, sigla): self.sigla = sigla def set_ra(self, ra): self.ra = ra class Professor(Pessoa): def __init__(self, nome, email, celular, v): super().__init__(nome, email, celular) self.valor_hora = float(v) def __repr__(self): return 'Prof: %s ' %(self.nome) def get_nome(self): return f"Mestre {self.nome}" def get_valor_hora(self): return self.valor_hora def set_valor_hora(self, valor): self.valor_hora = float(valor) aluno = Aluno("tuiu","[email protected]",11961015070,"ADS",690.00,1800648) print(aluno) print(aluno.get_nome()) aluno.set_nome("Ricardo Martins") print(aluno.get_nome()) aluno1 = Aluno("tuiu","[email protected]",11961015070,"ADS",690.00,1800648,["logica","matematica"]) print(aluno1.get_disciplina()) aluno1.set_disciplina("aleluia") print(aluno1.get_disciplina()) prof = Professor("ilana","[email protected]",156,150) print (prof) print(prof.get_nome())
class Solution: def trailingZeroes(self, n: int) -> int: l2 = [self.func(i, 2) for i in range(1, n+1) if i % 2 == 0] l5 = [self.func(i, 5) for i in range(1, n + 1) if i % 5 == 0] suml2 = sum(l2) suml5 = sum(l5) r = min(suml2, suml5) return r def func(self, n, i): count = 0 while n > 0: if n % i == 0: count += 1 n = n // i else: break return count def trailingZeroes2(self, n: int) -> int: fact = self.factorial(n) count = 0 while fact > 0: if fact % 10 == 0: count += 1 fact = fact // 10 else: break return count def factorial(self, n: int): if n == 0: return 1 res = 1 while n > 0: res = res * n n -= 1 return res n = 3 n = 5 n = 0 n = 10 n = 8785 s = Solution() print(s.trailingZeroes(n)) # print(s.factorial2(n)) print(s.trailingZeroes2(n))
css = """ body { font-family: Roboto, Helvetica, Arial, sans-serif; font-size:14px; color: #555555; background-color:#f5f5f5; margin-left: 5px; } .container{ padding-right:5px; padding-left:5px; margin-right:auto; margin-left:auto } .panel{ margin-bottom:20px; background-color:#fff; border:1px solid #ddd; border-radius:1px; } .panel-footer{ padding:2px 25px; background-color:#ffffff; border:1px solid transparent; font-size:13px; text-decoration:none !important; text-decoration:none; } .panel-body{ padding:5px; background-color:#f5f5f5; } table { font-family: arial, sans-serif; border-collapse: collapse; background-color: #ffffff; width:100%; } th { font-size:13px; background-color: #e2e2e2; border: 1px solid #f2f2f2; text-align: left; padding: 8px; } td { font-size:14px; border: 1px solid #f2f2f2; text-align: left; padding: 8px; } tr:nth-child(odd) { background-color: #f2f2f2; } .pass, .pass:link, .pass:visited { color:#FFFFFF; background-color:#4CAF50; text-decoration: none; padding: 3px 11px; text-align: center; font-size:12px; } .pass:hover { background-color: #5ec162; } .fail, .fail:link, .fail:visited { color:#FFFFFF; background-color:#ba2828; text-decoration: none; padding: 3px 11px; text-align: center; font-size:12px; } .fail:hover, .fail2:hover { background-color: #d83434; } .fail2, .fail2:link, .fail2:visited { color:#FFFFFF; background-color:#ba2828; text-decoration: none; padding: 3px 8px; text-align: center; font-size:12px; } .skip, .skip:link, .skip:visited { color:#FFFFFF; background-color:#FFC300; text-decoration: none; padding: 3px 11px; text-align: center; font-size:12px; } .skip:hover, .skip2:hover { background-color: #FF5733; } .skip2, .skip2:link, .skip2:visited { color:#FFFFFF; background-color:#FFC300; text-decoration: none; padding: 3px 8px; text-align: center; font-size:12px; } .testrail, .testrail:link, .testrail:visited { color: #555555; text-decoration: none; """
def solution(N): # write your code in Python 3.6 binary = to_binary(N) started = False max_gap = 0 current_gap = 0 for i in range(len(binary)): if not started: started = binary[i] == '1' else: if binary[i] == '1': max_gap = max(current_gap, max_gap) current_gap = 0 else: current_gap += 1 return max_gap def to_binary(n): """ Converts a given positive number to its representation as a binary string """ binary = '' partial_m = n while partial_m > 0: binary = str(partial_m % 2) + binary partial_m = partial_m // 2 print(binary) return binary
def soma(num1, num2): print(f'A soma dos numeros eh igual é: {num1+num2}') def sub(num1, num2): print(f'A soma dos numeros eh igual é: {num1-num2}') def mult(num1, num2): print(f'A soma dos numeros eh igual é: {num1*num2}') def divi(num1, num2): print(f'A soma dos numeros eh igual é: {num1/num2}')
# Here follows example input: fs = 48000 # Sample rate (Hz) base_freq = 100. # Base frequency (Hz) bpm = 120 # Beats per minute
class Solution: def is_isomorphic(self, s: str, t: str) -> bool: """ 根据值在两个字符串中的索引是否相同 """ for i, v in enumerate(s): if s.find(v) != t.find(t[i]): return False return True def other_solution(self, s, t): """ 将s中的字符对应的t中的字符存入字典,如果不符合条件则为False """ d = {} for i, v in enumerate(s): if d.get(v): if d[v] != t[i]: return False elif t[i] in d.values(): return False d[v] = t[i] return True if __name__ == "__main__": print(Solution().test("abc", "bac"))
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def verticalTraversal(self, root: 'TreeNode') -> 'List[List[int]]': queue = collections.deque([(root, 0, 0)]) d = collections.defaultdict(list) while queue: node, x, y = queue.popleft() d[x].append((y, node.val)) if node.left: queue.append((node.left, x - 1, y + 1)) if node.right: queue.append((node.right, x + 1, y + 1)) ans = [] for key in sorted(d): lst = sorted(d[key]) ans.append([b for a, b in lst]) return ans
VALIGN_TOP = "top" VALIGN_CENTER = "center" VALIGN_BASELINE = "baseline" VALIGN_BOTTOM = "bottom" HALIGN_LEFT = "left" HALIGN_CENTER = "center" HALIGN_RIGHT = "right" PROPAGATE_UP = "up" PROPAGATE_DOWN = "down" NO_PROPAGATION = "local" NO_LOCAL_INVOKE = "nolocal" BOLD = "bold" NORMAL = "normal" SEMIBOLD = "semibold" LEFT = "left" CENTER = "center" RIGHT = "right"
def sum_numbers(first_int, second_int): """Returns the sum of the two integers""" result = first_int + second_int return result def subtract(third_int): """Returns the difference between the result of sum_numbers and the third integer""" diff = sum_numbers(first_int=number_1, second_int=number_2) - third_int return diff def add_and_subtract(first_int, second_int, third_int): """Receives all the three integers and returns the other two functions""" sum_numbers(first_int, second_int) subtract(third_int) number_1 = int(input()) number_2 = int(input()) number_3 = int(input()) add_and_subtract(number_1, number_2, number_3) print(subtract(number_3)) # def sum_numbers(num_1: int, num_2: int): # """Returns the sum of the two arguments""" # # total = num_1 + num_2 # # return total # # def subtract(sum_1: int, num_3: int): # """Returns the difference between sum_numbers # and num_3""" # # difference = sum_1 - num_3 # # return difference # # def add_and_subtract(num_1: int, num_2: int, num_3: int): # """Receives all the three integers and # returns the other two functions""" # # sum_1 = sum_numbers(num_1, num_2) # result = subtract(sum_1, num_3) # # return result # # number_1 = int(input()) # number_2 = int(input()) # number_3 = int(input()) # # print(add_and_subtract(number_1, number_2, number_3))
# -*- coding: utf-8 -*- """ Created on 2018-6-12 @author: cheng.li """ class PortfolioBuilderException(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return str(self.msg)
# hackerrank problem of problem solving # problem statement : Picking Numbers def pickingNumbers(arr) : left = 0 max_sum = 0;max_left = 0;max_right=0 for i in range(1, len(arr)) : if abs(arr[i] - arr[i-1]) > 1 : number = i - left if number > max_sum : max_sum = number max_left = left max_right = i-1 left = i return max_sum+1 if __name__ == "__main__" : print(pickingNumbers([1, 2, 2, 3, 1, 2]))
st = input() sum = 0 for s in st: t = ord(s) if t >= ord('a'): sum += t - ord('a') + 1 else: sum += t - ord('A') + 27 ii = 2 for i in range(2, sum + 1): if sum % i == 0: ii = i break if ii == sum or sum == 1 : print('It is a prime word.') else : print('It is not a prime word.')
def is_before_after(img_path): """ check weather image is a before after :param img_path: :return: """
mainstr="the quick brown fox jumped over the lazy dog. the dog slept over the verandah" newstr=mainstr.split(" ") i=0 a=" " while i<len(newstr): if newstr[i]=="over": a=a+"on"+" " else: a=a+newstr[i]+" " i+=1 print(a)
def chemelements(): periodic_elements = ["Ac","Al","Ag","Am","Ar","As","At","Au","B","Ba","Bh","Bi","Be", "Bk","Br","C","Ca","Cd","Ce","Cf","Cl","Cm","Co","Cr","Cs","Cu", "Db","Dy","Er","Es","Eu","F","Fe","Fm","Fr","Ga","Gd","Ge","H", "He","Hf","Hg","Ho","Hs","I","In","Ir","K","Kr","La","Li","Lr", "Lu","Md","Mg","Mn","Mo","Mt","N","Na","Nb","Nd","Ne","Ni","No", "Np","O","Os","P","Pa","Pb","Pd","Pm","Po","Pr","Pt","Pu","Ra", "Rb","Re","Rf","Rh","Rn","Ru","S","Sb","Sc","Se","Sg","Si","Sm", "Sn","Sr","Ta","Tb","Tc","Te","Th","Ti","Tl","Tm","U","Uun","Uuu", "Uub","Uut","Uuq","Uup","Uuh","Uus","Uuo","V","W","Xe","Y","Yb", "Zn","Zr"] return periodic_elements
"""Top-level package for evq.""" __author__ = """Sylwester Czmil""" __email__ = '[email protected]' __version__ = '0.0.2'
# -*- coding: utf-8 -*- """Top-level package for MagniPy.""" __author__ = """Daniel Gilman""" __email__ = '[email protected]' __version__ = '0.1.0'
class Foo(): def g(self): pass class Bar(): def f(self): pass