content
stringlengths
7
1.05M
# # @lc app=leetcode id=205 lang=python3 # # [205] Isomorphic Strings # # https://leetcode.com/problems/isomorphic-strings/description/ # # algorithms # Easy (40.89%) # Likes: 2445 # Dislikes: 520 # Total Accepted: 402.9K # Total Submissions: 974.8K # Testcase Example: '"egg"\n"add"' # # Given two strings s and t, determine if they are isomorphic. # # Two strings s and t are isomorphic if the characters in s can be replaced to # get t. # # All occurrences of a character must be replaced with another character while # preserving the order of characters. No two characters may map to the same # character, but a character may map to itself. # # # Example 1: # Input: s = "egg", t = "add" # Output: true # Example 2: # Input: s = "foo", t = "bar" # Output: false # Example 3: # Input: s = "paper", t = "title" # Output: true # # # Constraints: # # # 1 <= s.length <= 5 * 10^4 # t.length == s.length # s and t consist of any valid ascii character. # # # # @lc code=start class Solution: def isIsomorphic(self, s: str, t: str) -> bool: if not s or not t or len(s) == 0 or len(t) == 0 or len(s) != len(t): return False s2t, t2s = {}, {} n = len(s) for i in range(n): if s[i] not in s2t: if t[i] in t2s and t2s[t[i]] != s[i]: return False s2t[s[i]] = t[i] t2s[t[i]] = s[i] else: # mapping contains s[i] if t[i] != s2t[s[i]]: return False return True # @lc code=end
class Solution: def maxAreaOfIsland(self, grid: List[List[int]]) -> int: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]] area_list = [] image_y = len(grid) image_x = len(grid[0]) initial_x = [0] * image_x visit = [] # initial_y, visit, current, neighbor, image = [], [], [], [], [] for i in range(image_y): # initial_y.append(initial_x.copy()) # current.append(initial_x.copy()) visit.append(initial_x.copy()) # neighbor.append(initial_x.copy()) for p in range(image_y): for q in range(image_x): if grid[p][q] == 1 and visit[p][q] != 1: # initial_x = [0] * image_x current, neighbor, image = [], [], [] for i in range(image_y): current.append(initial_x.copy()) image.append(initial_x.copy()) neighbor.append(initial_x.copy()) neighbor[p][q] = 1 while 1: current = neighbor.copy() neighbor_list = [] for i in range(image_y): for j in range(image_x): if current[i][j] == 1: if i - 1 >= 0: if visit[i - 1][j] != 1: neighbor_list.append([i - 1, j]) visit[i - 1][j] = 1 if i + 1 <= image_y - 1: if visit[i + 1][j] != 1: neighbor_list.append([i + 1, j]) visit[i + 1][j] = 1 if j - 1 >= 0: if visit[i][j - 1] != 1: neighbor_list.append([i, j - 1]) visit[i][j - 1] = 1 if j + 1 <= image_x - 1: if visit[i][j + 1] != 1: neighbor_list.append([i, j + 1]) visit[i][j + 1] = 1 if neighbor_list == []: area = 0 for i in image: area += sum(i) # area = sum(image) break neighbor = [] for i in range(image_y): neighbor.append(initial_x.copy()) for i, j in enumerate(neighbor_list): r = j[0] c = j[1] if grid[r][c] == 1: image[r][c] = 1 neighbor[r][c] = 1 area_list.append(area)
""" programa que leia vários numeros inteiros pelo teclado. O programa só vai parar quando o usuário digitar 999 que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag(999)) """ numero = contador = soma = 0 while numero != 999: numero = int(input('Digite um valor [999 para Sair] ')) if numero != 999: contador += 1 soma += numero print(f'Você informou {contador} numero[s].') print(f'A soma do[s] valor[es] é {soma}.')
# event manager permissions are set to expire this many days after event ends CBAC_VALID_AFTER_EVENT_DAYS = 180 # when a superuser overrides permissions, this is how many minutes the temporary permissions last CBAC_SUDO_VALID_MINUTES = 20 # these claims are used, if present, when sudoing. Note that sudo cannot give you a {} permission CBAC_SUDO_CLAIMS = ['organization', 'event', 'app']
"""This module contains the filter and regressor managers used by task to apply the filters and regressors. Both those classes use a side operation manager that implement the generic functions. This allow to apply the filters and regressors as early as possible during the triplet generation to optimise the performances. """
def is_isogram(string): found = [] for letter in string.lower(): if letter in found: return False if letter.isalpha(): found.append(letter) return True
class speedadjustclass(): def __init__(self): self.speedadjust = 1.0 return def speedincrease(self): self.speedadjust = round(min(3.0, self.speedadjust + 0.05), 2) print("In speedincrease",self.speedadjust) def speeddecrease(self): self.speedadjust = round(max(0.5, self.speedadjust - 0.05), 2) print("In speeddecrease",self.speedadjust) def run(self): return self.speedadjust
# getting input from user and pars it to the integer your_weight = input("Enter your Weight in kg: ") print(type(your_weight)) # to parse value of variable, we have to put it in seperate line or put it equal new variable int_weight_parser = int(your_weight) print(type(int_weight_parser)) # formatted String first_name = "pooya" last_name = "panahandeh" message = f'mr. {first_name} {last_name}, welcome to the python world.' print(message) # print the lenght of the string print(len(message)) # find special element in string print(message.find('p')) # replace string with another one print(message.replace('python', 'your python')) # boolean string function to check our string for specific value, the result will be true or false. print('python' in message) # the result will be true.
class Solution: def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ first = second = third = -math.inf for num in nums: if num > first: first, second, third = num, first, second elif num != first and num > second: second, third = num, second elif num != first and num != second and num > third: third = num return third if third != -math.inf else first
""" This is a collection of default transaction data used to test various components. """ UNIT = 100000000 """This structure is used throughout the test suite to populate transactions with standardized and tested data.""" #removed pubkey hash, may need to be re-added. DEFAULT_PARAMS = { 'addresses': [ ['Ukn3L4dgG13R3dSdxLvAAJizeiaW7cyUFz', 'cUuSAEXmiYMpu2Eu8QR52NzpsYB5MayhaX312ERZA5sUFQrMcaPY', '02cc8d98faf3bbe40b552be2d6dee21c54f14d7bbaf8e8b5867c9809658b85877d'], ['Ubq467qkiW2UvjD5Uhi23XKKyo7UcKAZTJ', 'cVprLzpeu5GdpjS8QkjB28YV2Hws3GK5eYmTtehDvY8ca4wjseVU', '02d577d18c9e2ac72c9bf7f5315e8eb579da19932e1a1c2d0a41524cb1b1109b0d'], ['UXJo7MANGsCfJM8LwRdkRsWWBxw6Tdshxt', 'cUsVQA8ZLtXottTgX1UpkmA4LyTNRdPtMW77uo8efXxNRmWuUYSR', '0312aa06fe0e0921369dd139ca6afd016ff9e0b5aad875730f7363ab8ac41cc6de'], ['UZ1XAmDF6Br2JKxahJWhuHzGawK7zxPtYW', 'cR93X24nNQwmXFBP1M1LRCr1qzy3ntQ4dhivBMtcwv5CnDwAb8c3', '029b9ea7a174c83e3a19038be991c61704ee325a451c1088bd5ee20f25b4ab9778'], ['UghGAbjYf5PoPcT5qFbxZ7VQb4MmvoPJeb', 'cNZd35p5P28urNGbJxDWeio1Az4Ubf2PtW4EPwjoVgPwgdUkqctC', '031a1cb595dd1c82a133c95331ceadc8fb6a67f087be67918a105743ea8f963b52'], ['UWskqPBEfw5sX5h6VKcTqqzBtiVBj2xBcQ', 'cQc5jyEuB4UvP4cUKALdKQTXB2HQXxRXcc2yrxYQUr8QLk8rzdHV', '028bc039d11b0f0a011ac13a58d8358e20b2e94a5f83045d64884ed996aa2e461e'], ['UWhVEVTAxrWsSMRPioQCqscAoUKhq42WQf', 'cV8ZpATSSkFF8rdsUepti5WotDj4bqGcVYXb82xTYuTscK95Rt5j', '03ea7e6a32ebe34979ad3c2be4f8ff2fe71316899f5cb134c94acd945e23edc223'], ['UShuxcmo5nojGPYqmsi6wbab81NZocdhtg', '', ''], # Empty address for testing purposes [ 'cVM1qQSP2exM9mHrsinN7wKZXZUvog56dhcWzanfXzmscNbHVPMd', '02c3ec578a7ff69a91756b63a47269294afd28113c5762fca9f95e60fdc49050e8'] ['UkUTb6dHLNZstq27N4eJBkurpMXFRuv2M8', 'cW3nKqAPmmjJbrjqAdCk1SLSGAzyhWEoDXQ1fK6pV9xajKbgCfne', '02d980ad0429af8f575a4935fb1d210ceeb3d75d36510c0d6788142700d066f6a5'] ], 'quantity': UNIT, 'small': round(UNIT / 2), 'expiration': 10, 'fee_required': 900000, 'fee_provided': 1000000, 'fee_multiplier': .05, 'unspendable': 'UUnoPartyXburnTestnetXXXXXXXXFEeN4', 'burn_start': 2000, 'burn_end': 400000, 'burn_quantity': int(.62 * UNIT), 'burn_verysmall_quantity': int(.0001 * UNIT), 'default_block_index': 2000 + 501, 'default_block_hash': '2d62095b10a709084b1854b262de77cb9f4f7cd76ba569657df8803990ffbfc6c12bca3c18a44edae9498e1f0f054072e16eef32dfa5e3dd4be149009115b4b8' #TODO: need to update this value } #pubkeyhash - removed from lines 36/37 DEFAULT_PARAMS['privkey'] = {addr: priv for (addr, priv, pub) in DEFAULT_PARAMS['addresses']} DEFAULT_PARAMS['pubkey'] = {addr: pub for (addr, priv, pub) in DEFAULT_PARAMS['addresses']} ADDR = [a[0] for a in DEFAULT_PARAMS['addresses']] SHORT_ADDR_BYTES = ['6f' + a[1] for a in DEFAULT_PARAMS['addresses']] DP = DEFAULT_PARAMS MULTISIGADDR = [ '1_{}_{}_2'.format(ADDR[0], ADDR[1]), '1_{}_{}_2'.format(ADDR[2], ADDR[1]), '1_{}_{}_2'.format(ADDR[0], ADDR[2]), '2_{}_{}_2'.format(ADDR[0], ADDR[1]), '2_{}_{}_2'.format(ADDR[2], ADDR[1]), '1_{}_{}_{}_3'.format(ADDR[0], ADDR[2], ADDR[1]), '1_{}_{}_{}_3'.format(ADDR[0], ADDR[2], ADDR[3]), '2_{}_{}_{}_3'.format(ADDR[0], ADDR[2], ADDR[1]), '2_{}_{}_{}_3'.format(ADDR[0], ADDR[2], ADDR[3]), '3_{}_{}_{}_3'.format(ADDR[0], ADDR[2], ADDR[1]), '3_{}_{}_{}_3'.format(ADDR[0], ADDR[2], ADDR[3]) ] #TODO: GET Pay to script / segwit testnet addresses P2SH_ADDR = [ 'DEyXVRPjTKZVP7nkcHkXCHJyZb78wLvVJC' # 2of2 Ukn3L4dgG13R3dSdxLvAAJizeiaW7cyUFz Ubq467qkiW2UvjD5Uhi23XKKyo7UcKAZTJ 'D9xjPTUFrNPUTNKPnS3UXnMSLd6sNgR7Jf', # 2of3 Ukn3L4dgG13R3dSdxLvAAJizeiaW7cyUFz Ubq467qkiW2UvjD5Uhi23XKKyo7UcKAZTJ UXJo7MANGsCfJM8LwRdkRsWWBxw6Tdshxt ] #P2WPKH_ADDR = [ # 'tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx' #]
a = 200 b = 33 c = 500 if a > b and c > a: print("Both conditions are True")
# Time: O(m + n) # Space: O(m + n) # 445 # You are given two linked lists representing two non-negative numbers. # The most significant digit comes first and each of their nodes contain # a single digit. # Add the two numbers and return it as a linked list. # # You may assume the two numbers do not contain any leading zero, # except the number 0 itself. # # Follow up: # What if you cannot modify the input lists? In other words, # reversing the lists is not allowed. # # Example: # # Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) # Output: 7 -> 8 -> 0 -> 7 # 本题的主要难点在于链表中数位的顺序与我们做加法的顺序是相反的,为了*逆序*处理所有数位, # 我们可以使用栈:把所有数字压入栈中,再依次取出相加。 # Definition for singly-linked list. class ListNode(object): def __init__(self, x = 0, next = None): self.val = x self.next = next def __repr__(self): return "{}->{}".format(self.val, self.next) class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ stk1, stk2 = [], [] while l1: stk1.append(l1.val) l1 = l1.next while l2: stk2.append(l2.val) l2 = l2.next head, carry = None, 0 while stk1 or stk2 or carry: if stk1: carry += stk1.pop() if stk2: carry += stk2.pop() carry, v = divmod(carry, 10) cur = ListNode(v, head) head = cur return head # result list can be built from back to front, not need final reverse. def addTwoNumbers_reverseInput(self, l1, l2): def reverse(l): prev = None while l: l.next, prev, l = prev, l, l.next return prev l1r, l2r = reverse(l1), reverse(l2) head, c = None, 0 while l1r or l2r or c: if l1r: c += l1r.val l1r = l1r.next if l2r: c += l2r.val l2r = l2r.next c, v = divmod(c, 10) cur = ListNode(v, head) head = cur return head l1 = ListNode(7) l1.next = ListNode(2) l1.next.next = ListNode(4) l1.next.next.next = ListNode(3) l2 = ListNode(5) l2.next = ListNode(6) l2.next.next = ListNode(4) ans = Solution().addTwoNumbers(l1, l2) print(ans) # 7 -> 8 -> 0 -> 7
# MetaPrint.py # Copyright (c) 2008-2017 Chris Gonnerman # 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 author nor the names of any 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 # AUTHOR 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. """ MetaPrint.py defines a class and utility functions for use by programs which also use MSWinPrint.py for output. MetaPrint exposes a document class which replicates the functionality of MSWinPrint, but rather than actually printing, a document object collects the output generated so that it can be replayed, either via MSWinPrint or ImagePrint. This is useful mainly to preview a print job (by running the MetaPrint document through ImagePrint) and subsequently actually print it (via MSWinPrint). document is a class for creating and running print jobs. Presently, the source is the only documentation for this class. """ class document: def __init__(self, desc = None, printer = None, papersize = "letter", orientation = "portrait", duplex = "normal"): self.font = None self.printer = printer self.papersize = papersize self.orientation = orientation self.duplex = duplex self.page = 0 self.pagelist = [] self.pagedata = [] if desc is not None: self.desc = desc else: self.desc = "MetaPrint.py print job" def begin_document(self, desc = None): if desc: self.desc = desc def end_document(self): if self.pagedata: self.end_page() def end_page(self): if self.pagedata: self.pagelist.append(self.pagedata) self.pagedata = [] if self.font is not None: self.pagedata.append(self.font) def line(self, from_, to): self.pagedata.append(("line", (from_, to))) def rectangle(self, box): self.pagedata.append(("rectangle", box)) def text(self, position, text): self.pagedata.append(("text", (position, text))) def setfont(self, name, size, bold = None, italic = 0): self.font = ("font", (name, size, bold, italic)) self.pagedata.append(self.font) def image(self, position, image, size): self.pagedata.append(("image", (position, image, size))) def setink(self, ink): self.pagedata.append(("setink", (ink,))) def setfill(self, onoff): self.pagedata.append(("setfill", (onoff,))) def runpage(self, doc, page): for op, args in page: if op == "line": doc.line(*args) elif op == "rectangle": doc.rectangle(args) elif op == "text": doc.text(*args) elif op == "font": doc.setfont(*args) elif op == "image": doc.image(*args) elif op == "setink": doc.setink(*args) elif op == "setfill": doc.setfill(*args) doc.end_page() def run(self, doc, pageno = None): if pageno is None: for page in self.pagelist: self.runpage(doc, page) else: self.runpage(doc, self.pagelist[pageno]) # end of file.
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Default value constants exposed by core utilities.""" DEFAULT_REGISTRY = 'gcr.io' REGIONAL_REGISTRIES = ['us.gcr.io', 'eu.gcr.io', 'asia.gcr.io'] BUCKET_REGISTRIES = ['b.gcr.io', 'bucket.gcr.io'] APPENGINE_REGISTRY = 'appengine.gcr.io' SPECIALTY_REGISTRIES = BUCKET_REGISTRIES + [APPENGINE_REGISTRY] ALL_SUPPORTED_REGISTRIES = ([DEFAULT_REGISTRY] + REGIONAL_REGISTRIES + SPECIALTY_REGISTRIES) DEFAULT_DEVSHELL_IMAGE = (DEFAULT_REGISTRY + '/dev_con/cloud-dev-common:prod') METADATA_IMAGE = DEFAULT_REGISTRY + '/google_appengine/faux-metadata:latest'
#print is function when we want to print something on output print("My name is Dhruv") #You will notice something strange if you try to print any directory #print("C:\Users\dhruv\Desktop\dhruv.github.io") #Yes unicodeescape error # Remember i told about escape character on previous tutorial # yes it causing problems # now place "r" in starting of sentence print(r"C:\Users\dhruv\Desktop\dhruv.github.io") #yes it is printed # what what r means ? r means Rush string # it means that " take the string as it , take no special meaning in this perticular STRING " # One amazing thing you can do is , string can be store in variables #You can also Add and Multiply strings myname = "Dhruv " myname + "Patel" myname * 5 # now press run # Do check my shell file for refrence
SECRET_KEY = '-dummy-key-' INSTALLED_APPS = [ 'pgcomments', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', }, }
names = ["libquadmath0", "libssl1.0.0"] status = {"libquadmath0": {"Name": "libquadmath0", "Dependencies": ["gcc-5-base", "libc6"], "Description": "GCC Quad-Precision Math Library<br/> A library, which provides quad-precision mathematical functions on targets<br/> supporting the __float128 datatype. The library is used to provide on such<br/> targets the REAL(16) type in the GNU Fortran compiler.<br/>", "Need me": ["libssl1.0.0"]}, "libssl1.0.0": {"Name": "libssl1.0.0", "Dependencies": ["libc6", "zlib1g", "libquadmath0"], "Description": "SSL shared libraries<br/> libssl and libcrypto shared libraries needed by programs like<br/> apache-ssl, telnet-ssl and openssh.<br/> .<br/> It is part of the OpenSSL implementation of SSL.<br/>", "Alternatives": ["debconf"]} } unsure = {"libssl1.0.0": [" debconf (>= 0.5) ", " libquadmath0\n"]} before_alt = {"libquadmath0": {"Name": "libquadmath0", "Dependencies": ["gcc-5-base", "libc6"], "Description": "GCC Quad-Precision Math Library<br/> A library, which provides quad-precision mathematical functions on targets<br/> supporting the __float128 datatype. The library is used to provide on such<br/> targets the REAL(16) type in the GNU Fortran compiler.<br/>"}, "libssl1.0.0": {"Name": "libssl1.0.0", "Dependencies": ["libc6", "zlib1g"], "Description": "SSL shared libraries<br/> libssl and libcrypto shared libraries needed by programs like<br/> apache-ssl, telnet-ssl and openssh.<br/> .<br/> It is part of the OpenSSL implementation of SSL.<br/>"} } before_need = {"libquadmath0": {"Name": "libquadmath0", "Dependencies": ["gcc-5-base", "libc6"], "Description": "GCC Quad-Precision Math Library<br/> A library, which provides quad-precision mathematical functions on targets<br/> supporting the __float128 datatype. The library is used to provide on such<br/> targets the REAL(16) type in the GNU Fortran compiler.<br/>"}, "libssl1.0.0": {"Name": "libssl1.0.0", "Dependencies": ["libc6", "zlib1g", "libquadmath0"], "Description": "SSL shared libraries<br/> libssl and libcrypto shared libraries needed by programs like<br/> apache-ssl, telnet-ssl and openssh.<br/> .<br/> It is part of the OpenSSL implementation of SSL.<br/>"} } lines = ["Package: libquadmath0\n", "Status: install ok installed\n", "Priority: optional\n", "Section: libs\n", "Installed-Size: 265\n", "Maintainer: Ubuntu Core developers <[email protected]>\n", "Architecture: amd64\n", "Multi-Arch: same\n", "Source: gcc-5\n", "Version: 5.4.0-6ubuntu1~16.04.12\n", "Depends: gcc-5-base (= 5.4.0-6ubuntu1~16.04.12), libc6 (>= 2.23)\n", "Description: GCC Quad-Precision Math Library\n", " A library, which provides quad-precision mathematical functions on targets\n", " supporting the __float128 datatype. The library is used to provide on such\n", " targets the REAL(16) type in the GNU Fortran compiler.\n", "Homepage: http://gcc.gnu.org/\n", "Original-Maintainer: Debian GCC Maintainers <[email protected]>\n", "\n", "Package: libssl1.0.0\n", "Status: install ok installed\n", "Multi-Arch: same\n", "Priority: important\n", "Section: libs\n", "Installed-Size: 2836\n", "Maintainer: Ubuntu Developers <[email protected]>\n", "Architecture: amd64\n", "Source: openssl\n", "Version: 1.0.1-4ubuntu5.5\n", "Depends: libc6 (>= 2.14), zlib1g (>= 1:1.1.4), debconf (>= 0.5) | libquadmath0\n", "Pre-Depends: multiarch-support\n", "Breaks: openssh-client (<< 1:5.9p1-4), openssh-server (<< 1:5.9p1-4)\n", "Description: SSL shared libraries\n", " libssl and libcrypto shared libraries needed by programs like\n", " apache-ssl, telnet-ssl and openssh.\n", " .\n", " It is part of the OpenSSL implementation of SSL.\n", "Original-Maintainer: Debian OpenSSL Team <[email protected]>\n", "\n"]
# 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 maxDepth(self, root): """ :type root: TreeNode :rtype: int """ # dfs search if not root: return 0 #return max(self.maxDepth(root.left),self.maxDepth(root.right))+1 # the recursive method is very straightforward # in real or interview, need to implement using stack and some advanced traval tech # not level by level """ ### simple bfs stck=[root] depth=0 # bfs search while stck: tmp=[] depth+=1 for cur in stck: if cur.left: tmp.append(cur.left) if cur.right: tmp.append(cur.right) stck=tmp return depth """ ### implement not level by level stck=[root] depth=0 # record the previous route prenode=None while stck: cur=stck[-1] # if prenode is above cur node if not prenode or prenode.left==cur or prenode.right==cur: # left has priority to add, if--elif not if---if if cur.left: stck.append(cur.left) elif cur.right: stck.append(cur.right) # else if the travel back from bottom, the left subtree is completed elif cur.left==prenode: if cur.right: stck.append(cur.right) # reach the leaf node, prenode and cur reach the same node else: stck.pop() # move pre to next route prenode=cur depth=max(depth,len(stck)) return depth
"""Exceptions""" class LibvirtConnectionError(Exception): """Error to indicate something went wrong with the LibvirtConnection class""" pass class DomainNotFoundError(Exception): """Error to indicate something went wrong with the LibvirtConnection class""" pass
S = input() scale_list = ["Do", "", "Re", "", "Mi", "Fa", "", "So", "", "La", "", "Si"] order = "WBWBWWBWBWBW" * 3 print(scale_list[order.find(S)])
class Solution: def solve(self, nums): uniques = set() j = 0 ans = 0 for i in range(len(nums)): while j < len(nums) and nums[j] not in uniques: uniques.add(nums[j]) j += 1 ans = max(ans, len(uniques)) uniques.remove(nums[i]) return ans
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if len(prices) == 0: return 0 min_price, max_profit = prices[0], 0 for i in prices[1:]: min_price = min(min_price, i) profit = i - min_price max_profit = max(profit, max_profit) # print(min_price) print(prices.index(max_profit + min_price)) return max_profit arr = [7, 1, 5, 6, 3, 2] s = Solution() print(s.maxProfit(arr))
""" patterns - Package of different software patterns. Provided patterns: * `abstractf` - abstract factory * `threetier` - 3-tier software architecture Use: Each submodule is self-contained. If you don't want the whole package, you can take the files you need. Usage examples are in the examples directory. """ __author__ = 'jason'
#!/usr/bin/python3 def append_after(filename="", search_string="", new_string=""): """appends after search string instances in file """ with open(filename, 'r', encoding='utf-8') as myFile: lines = myFile.readlines() for i, line in enumerate(lines): if search_string in line: lines.insert(i + 1, new_string) with open(filename, 'w', encoding='utf-8') as myFile: content = "".join(lines) myFile.write(content)
MUSHISHI_ID = 457 FULLMETAL_ID = 25 GINKO_ID = 425 KANA_HANAZAWA_ID = 185 YEAR = 2018 SEASON = "winter" DAY = "monday" TYPE = "anime" SUBTYPE = "tv" GENRE = 1 PRODUCER = 37 MAGAZINE = 83 USERNAME = "Nekomata1037" CLUB_ID = 379
""" A Mapping module """ class DataMapping: """DataMapping""" def __init__(self, data: dict, keys_map: dict): """__init__ :param data: :type data: dict :param keys_map: :type keys_map: dict data = {'username': 'John', 'email': '[email protected]'} keys_map = {'username': 'user', 'email': 'myemail'} """ self.data = data self.keys_map = keys_map async def mapping(self) -> dict: """mapping :rtype: dict """ return {val: self.data[key] for key, val in self.keys_map.items() if key in self.data}
def setup(): size(500,500) smooth() background(50) strokeWeight(5) stroke(250) noLoop() cx=250 cy=250 cR=200 i=0 def draw(): global cx,cy, cR, i while i < 2*PI: i +=PI/6 x1 = cos(i)*cR+cx y1 = sin(i)*cR+cy line(x1,y1,x1,y1) line(cx,cy,cx,cy) def keyPressed(): if key =="s": saveFrame("Photo")
BUCKET_NAME = "o43-gpnhack-data-hh" MANTICORE_URL = "http://manticore:9308" ELASTICSEARCH_URL = "http://elasticsearch:9200" QDRANT_URL = 'http://qdrant:6333' # 113 - Россия, 1 - Москва, 83 - Смоленск DEFAULT_HH_AREAS = [113]
# Here is the code from the generators2.py file # From the demo # Can you refactor any or all of it to use comprehensions? # More chaining # Courtesy of my friend Jim Prior def gen_fibonacci(): a, b = 0, 1 while True: a, b = b, a + b yield b def gen_even(gen): return (number for number in gen if number % 2 == 0) def error(): raise StopIteration def gen_lte(gen, max): return (error() if number > max else number for number in gen) # Now it's easy to combine generators in different ways. for num in gen_lte(gen_even(gen_fibonacci()), 20): print(num) print("") for num in gen_lte(gen_fibonacci(), 1000): print(num)
#from models import HVAC class HvacBuildingTracker(): """ Creates a tracker that will manage the data that the hvac building generates """ def __init__(self): """Creates an instance of the hvac building tracker """ self.__HouseTempArr = [] self.__OutsideTempArr = [] self.__AvgPowerPerSecArr = [] def AddSample(self, houseTemp: float, outsideTemp: float, avgPwrPerSecond: float): """Adds a sample of the data for the house Arguments: houseTemp {float} -- The current house temperature in C outsideTemp {float} -- The current outside temperature in C avgPwrPerSecond {float} -- The average watts per second """ self.__HouseTempArr.append(houseTemp) self.__OutsideTempArr.append(outsideTemp) self.__AvgPowerPerSecArr.append(avgPwrPerSecond) def GetHouseTempArray(self, isCelsius:bool = True): if isCelsius: return self.__HouseTempArr # convert an array to farienheit return self.__convertCArrayToF(self.__HouseTempArr) def GetOutsideTempArray(self, isCelsius:bool = True): if isCelsius: return self.__OutsideTempArr # convert an array to farienheit return self.__convertCArrayToF(self.__OutsideTempArr) def __convertCArrayToF(self, C_Array): f_array = [] for c in C_Array: #convert f = (c * (9/5))+32 f_array.append(f) return f_array
def main(): value = 1 if value == 0: print("False") elif value == 1: print("True") else: print("Undefined") if __name__ == "__main__": main()
# -*- coding: UTF-8 -*- logger.info("Loading 16 objects to table ledger_matchrule...") # fields: id, account, journal loader.save(create_ledger_matchrule(1,2,1)) loader.save(create_ledger_matchrule(2,2,2)) loader.save(create_ledger_matchrule(3,4,3)) loader.save(create_ledger_matchrule(4,2,4)) loader.save(create_ledger_matchrule(5,4,4)) loader.save(create_ledger_matchrule(6,17,4)) loader.save(create_ledger_matchrule(7,2,5)) loader.save(create_ledger_matchrule(8,4,5)) loader.save(create_ledger_matchrule(9,17,5)) loader.save(create_ledger_matchrule(10,2,6)) loader.save(create_ledger_matchrule(11,4,6)) loader.save(create_ledger_matchrule(12,17,6)) loader.save(create_ledger_matchrule(13,2,7)) loader.save(create_ledger_matchrule(14,4,7)) loader.save(create_ledger_matchrule(15,17,7)) loader.save(create_ledger_matchrule(16,6,8)) loader.flush_deferred_objects()
#!/bin/python3 # https://www.hackerrank.com/challenges/py-check-subset/problem # Author : Sagar Malik ([email protected]) n = int(input()) for _ in range(n): K = int(input()) first = set(input().split()) t = int(input()) second = set(input().split()) print(len(first-second) == 0)
class Pipelines(object): def __init__(self, client): self._client = client def get_pipeline(self, pipeline_id, **kwargs): url = 'pipelines/{}'.format(pipeline_id) return self._client._get(self._client.BASE_URL + url, **kwargs) def get_all_pipelines(self, **kwargs): url = 'pipelines' return self._client._get(self._client.BASE_URL + url, **kwargs) def get_pipeline_deals(self, pipeline_id, **kwargs): url = 'pipelines/{}/deals'.format(pipeline_id) return self._client._get(self._client.BASE_URL + url, **kwargs)
def grow_plants(db, messenger, object): # # grow plant db.increment_property_of_component('plant', object['entity'], 'growth', object['growth_rate']) return [] def ripen_fruit(db, messenger, object): db.increment_property_of_component('plant', object['entity'], 'fruit_growth', object['fruit_growth_rate']) return []
for c in range(1,50): if c%2==0: print('.',end='') print(c,end=' ')
__author__ = 'khomitsevich' ATTRIBUTES_COUNT: int = 14 class Metrics: """ Metrics data class. """ # TODO: Initialization process should be more clearer, better to pass dict with keys as class parameter titles def __init__(self, filepath:str, filename:str, args:list): self.__argument_count_validation(filepath, filename, args) self.__non_empty_arguments_validation(filepath, filename, args) self.name = filename self.step = float(args[0].replace(',', '.')) self.angel = float(args[1].replace(',', '.')) self.last_dots_count = float(args[2].replace(',', '.')) self.in_to_out_coef = float(args[3].replace(',', '.')) self.out_to_in_coef = float(args[4].replace(',', '.')) self.dice = float(args[5].replace(',', '.')) self.spec = float(args[6].replace(',', '.')) self.sens = float(args[7].replace(',', '.')) self.accu = float(args[8].replace(',', '.')) self.time_of_work_with_init = float(args[9].replace(',', '.')) self.time_of_work_wihout_init = float(args[10].replace(',', '.')) self.otsu_treshold = float(args[11].replace(',', '.')) self.average_in = float(args[12].replace(',', '.')) self.average_out = float(args[13].replace(',', '.')) def __repr__(self): return """Metrics: ('name': {self.name}, 'step': {self.step}, 'angel': {self.angel}, 'last_dots_count': {self.last_dots_count}, 'in_to_out_coef': {self.in_to_out_coef}, 'out_to_in_coef': {self.out_to_in_coef}, 'dice': {self.dice}, 'spec': {self.spec}, 'sens': {self.sens}, 'accu': {self.accu}, 'time_of_work_with_init': {self.time_of_work_with_init}, 'time_of_work_wihout_init': {self.time_of_work_wihout_init}, 'otsu_treshold': {self.otsu_treshold}, 'average_in': {self.average_in}, 'average_out': {self.average_out}) """.format(self=self) def __str__(self): return self.__repr__ def __argument_count_validation(self, filepath:str, filename:str, args:list): if len(args) != ATTRIBUTES_COUNT: error_message = f"WARNING: At instance '{filename}' on path '{filepath}' has been passed list with '{len(args)}' arguments, should be {ATTRIBUTES_COUNT}." print(error_message) raise ValueError(error_message) def __non_empty_arguments_validation(self, filepath:str, filename:str, args:list): for arg in args: if arg is None: error_message = f"WARNING: Found an empty argument at file: '{filename}' on path '{filepath}'." print(error_message) raise ValueError(error_message)
# input sell price a = input("Input Final Sale Price") # input P&P cost b = input("Input P&P Costs") # add a & b together to get total # fees = total * 0.128 + 0.3 //12.8% + 30p # total - fees = profit # output total # output fees # output profit # output description explaining forumla # output note explaining that fees are charged on P&P as well as sale price.
#!/usr/bin/env python3 #https://codeforces.com/problemset/problem/11178/B #need a state machine to be clear! #state: 'S', 'W', 'WO' #trans: # 1. 'S---meet vv--->W'; # 2. 'W---meet vv--->W'; #update w,wow # 3. 'W---meet o--->WO'; #update wo # 4. 'WO--meet o--->WO'; #update wo # 5. 'WO--meet vv--->W'; #update w,wow # could be simplified into update logic on w/wow and wo respectively! # 注意人类可能习惯使用乘法/把o和w合起来算,而算法上简单的实现正好相反!!! # 计算思维的好例子! (对比数学..数学相当于CISC,而算法可能是RISC!) # 一开始想用w-list,o-list来记录连续的o和w,发现是错误的做法;所以开始画状态机,画出状态机后才发现逻辑可大大简化.. s = input() #1e6 w = 0 wo = 0 wow = 0 for i in range(1,len(s)): if s[i]=='v' and s[i-1]=='v': w += 1 wow += wo continue if s[i]=='o': wo += w print(wow)
class ValidationError(Exception): """ Base class """ pass class AppStoreValidationError(ValidationError): message = None def __init__( self, message: str ): self.message = message super().__init__(message) def __str__(self) -> str: return self.message
class Solution: def isPalindrome(self, x: int) -> bool: if x < 0 or (not x % 10 and x): return False rev = 0 while x > rev: rev = rev * 10 + x % 10 x //= 10 return rev == x or rev//10 == x
valorc = float(input('Qual o valor da Casa? R$ ')) salario = float(input('Qual o valor do salario? R$')) anos = int(input('Em quantos anos deseja pagar? ')) prest = valorc / (anos * 12) if prest > (salario * (30/100)): print('Fincanciamento Negado') else: print('Financiamento Autorizado')
''' Unit tests module for PaPaS module ''' __all__ = []
""" EM PYTHON TUDO É UM OBJETO: incluindo classes Metaclasses são as "classes" que criam classes. type é uma metaclasse (!!!???) """ # Criando uma metaclasse que define como as classes que a herdarem devem # funcionar class Meta(type): def __new__(mcs, name, bases, namespace): """ mcs = Metaclasse name = Nome da classe que esta sendo criada bases = Classes pai da classe sendo criada namespace = Contem todo o atributo de classe e todo o método que é criado na mesma. Toda classe possui um namespace. """ # print(name) # Saída: A e B, pois são as classes criadas com a Meta if name == 'A': # Definindo o comportamento da classe A # Retorna a classe return type.__new__(mcs, name, bases, namespace) # print(namespace) # Mostra tudo que existe em B """ Saída seria: {'__module__': '__main__', '__qualname__': 'B', 'b_fala': <function B.b_fala at 0x000001FD9C25BAF0>} """ if 'b_fala' not in namespace: # Se b_fala não existir em B, faça: print(f'Oi, você precisa criar o método b_fala em {name}') else: # Se não for um método, faça: if not callable(namespace['b_fala']): print(f'b_fala precisa ser um método, não atributo em {name}') # Impedindo que o attr_classe de A seja sobrescrito pelas instancias if 'attr_classe' in namespace: """ Toda vez que a classe B é criada e o atributo attr_classe é definido em B ele é removido. Mantendo o valor de attr_classe de A """ print(f'{name} tentou sobrescrever o atributo mas foi impedido!') del namespace['attr_classe'] return type.__new__(mcs, name, bases, namespace) class A(metaclass=Meta): # Definindo Meta como a metaclasse de A """ Toda classe que herdar A, se comportará da forma que for definida na metaclasse Meta, conforme herança. """ attr_classe = 'Valor A' # Atributo de exemplo que não deve ser reescrito def fala(self): self.b_fala() class B(A): attr_classe = 'Valor B' # Tentanto sobrescrever attr herdado de A b_fala = 'Oi' # def b_fala(self): # print('Olá') pass class C(B): attr_classe = 'Valor C' b = B() # b.fala() # Chamando um método da classe A que chama um método de B print(b.attr_classe) c = C() """ A type é uma metaclasse também utilizada para criar classes. Exemplo de criação de classe manualmente com o Type: A = type( 'A', # Nome da classe (), # De quem a classe será herdada {'attr': 'Olá mundo!'} # Atributos da classe ) a = A() print(a.attr) # Olá mundo! print(type(a)) # <class '__main__.A'> """
termo = int(input('Quantos termos vocêr quer da Sequeência Fibonacci: ')) t1 = 0 t2 = 1 print('{} - {} - '.format(t1, t2), end='') c = 3 while c <= termo: t3 = t1 + t2 print(t3, end=' - ') t1 = t2 t2 = t3 c += 1 print('Fim')
N = int(input()) for i in range(N): n, k = map(int, input().split()) ranges = {n: 1} max_range = 0 while k > 0: max_range, count_range = max(ranges.items()) if k > count_range: k -= count_range del ranges[max_range] range_1, range_2 = (max_range - 1)//2, max_range//2 ranges[range_1] = ranges.get(range_1, 0) + count_range ranges[range_2] = ranges.get(range_2, 0) + count_range else: print('Case #{}: {} {}'.format(i + 1, max_range//2, (max_range - 1)//2, )) break
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 18 12:51:41 2019 @author: barnafi """ class PhysicalParameters: def __init__(self, **kwargs): keys = kwargs.keys() def setter(_x, default): return kwargs[_x] if _x in keys else default # Simluation specifications self.dim = setter("dim", 2) self.dt = kwargs["dt"] self.t0 = kwargs['t0'] # Initial time self.sim_time = kwargs["sim_time"] self.Niter = (self.sim_time - self.t0)/self.dt self.ys_degree = setter("ys_degree", 2) self.uf_degree = setter("uf_degree", 2) self.us_degree = setter("us_degree", 1) self.p_degree = setter("p_degree", 1) self.approach = setter("approach", "Default") # Default/Burtschell self.active_stress = setter("active_stress", False) # Physical parameters self.rhos0 = self.rhos = setter("rhos", 2e3) # Solid density self.rhof = setter("rhof", 2e3) # Fluid density self.phi0 = self.phi = setter("phi", lambda t: 0.1) # porosity self.mu_f = setter("mu_f", 0.035) # Fluid viscosity self.ks = setter("ks", 2e8) # bulk modulus if "E" in keys and "nu" in keys: self.E = setter("E", 1e6) # Young's modulus self.nu = setter("nu", 0.4) # Poisson ratio self.lmbda = self.E*self.nu/((1+self.nu)*(1-2*self.nu)) # Lamé params self.mu_s = self.E/(2*(1+self.nu)) # Lamé params elif "lmbda" in keys and "mu_s" in keys: self.lmbda = setter("lmbda", 10) # Lamé params self.mu_s = setter("mu_s", 5) # Lamé params self.E = self.mu_s*(3*self.lmbda+2*self.mu_s)/(self.lmbda + self.mu_s) self.nu = self.lmbda/(2*(self.lmbda + self.mu_s)) self.gamma = setter("gamma", 20) # Nitsche parameter for no slip self.D = setter("D", 1e7) # Permeability, i.e k_f^{-1}, constant for now self.AS = setter("AS", 1e3) self.beta = setter("beta", 10) class PhysicalParametersSolid: def __init__(self, **kwargs): keys = kwargs.keys() def setter(_x, default): return kwargs[_x] if _x in keys else default # Simluation specifications self.dt = kwargs["dt"] self.t0 = kwargs['t0'] # Initial time self.sim_time = kwargs["sim_time"] self.Niter = int((self.sim_time - self.t0)/self.dt) self.ys_degree = setter("ys_degree", 2) # Physical parameters self.ks = setter("ks", 2e8) # bulk modulus self.rhos = self.rhos = setter("rhos", 1e3) # Solid density if "E" in keys and "nu" in keys: self.E = setter("E", 1e6) # Young's modulus self.nu = setter("nu", 0.4) # Poisson ratio self.lmbda = self.E*self.nu/((1+self.nu)*(1-2*self.nu)) # Lamé params self.mu_s = self.E/(2*(1+self.nu)) # Lamé params else: self.lmbda = setter("lmbda", 10) # Lamé params self.mu_s = setter("mu_s", 5) # Lamé params self.E = self.mu_s*(3*self.lmbda+2*self.mu_s)/(self.lmbda + self.mu_s) self.nu = self.lmbda/(2*(self.lmbda + self.mu_s)) # Activation parameter self.AS = setter("AS", 1e3) class OutputParameters: def __init__(self, **kwargs): keys = kwargs.keys() def setter(_x, default): return kwargs[_x] if _x in keys else default # Solution storage self.name = setter("name", "result") # Keep lists of solutions for convergence self.storeSolutions = setter("store_solutions", False) # Export solutions to xdmf (only serial) self.exportSolutions = setter("export_solutions", True) # Amount of iterations before exporting, it%saveEvery == 0 self.saveEvery = setter("save_every", 1) # Verbose output self.verbose = setter("verbose", True) class ExternalForces: def __init__(self, **kwargs): self.ff = kwargs['ff'] # Load on fluid equation self.fs = kwargs['fs'] # Load on solid equation self.ts = kwargs['ts'] # Neumann solid traction self.tf = kwargs['tf'] # Neumann fluid traction self.theta = kwargs['theta'] # Mass source/sink self.activeStress = kwargs['active_stress'] if 'active_stress' in kwargs.keys() else None
""" While thinking abou this problem, many might come up with a DP algorithm. But this problem is much easier than DP problem. First, scan the input string, and store the maximum occurance index of every leter. Then, scan the input string again, considering the maximum occurance of each letter.While scanning, if you encounter a letter whose maxium occurance index is larger than current, update maximum occurance. If the scanning index equals the maximum occurance index, then we get a new break. """ class Solution: def partitionLabels(self, S): """ :type S: str :rtype: List[int] """ # S = "ababcbacadefegdehijhklij" ret = [] map = {} # last = {c: i for i, c in enumerate(S)} for i, s in enumerate(S): map[s] = i partition = prev = 0 for i, s in enumerate(S): partition = max(partition, map[s]) if i == partition: ret.append(partition + 1 - prev) prev = partition + 1 return ret S = "eaaaabaaec" s = Solution() print(s.partitionLabels(S))
alpha_num_dict = { 'a':1, 'b':2, 'c':3 }
# Creating an empty Tuple Tuple1 = (Hello) print("Initial empty Tuple: ") print(Tuple1) A=(1,2,3,4) B=('a','b','c') C=(5,6,7,8) #second tuple print(A,'length= ',len(A)) print(B,'length= ',len(B)) print(A<C) print(A+C) print(max(A)) print(min(B)) tuple('hey') 'good'*3
# # PySNMP MIB module DSA-MIB (http://pysnmp.sf.net) # ASN.1 source http://mibs.snmplabs.com:80/asn1/DSA-MIB # Produced by pysmi-0.0.7 at Sun Feb 14 00:11:07 2016 # On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose # Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52) # ( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion") ( DistinguishedName, applIndex, ) = mibBuilder.importSymbols("NETWORK-SERVICES-MIB", "DistinguishedName", "applIndex") ( NotificationGroup, ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") ( MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, Gauge32, iso, NotificationType, Bits, Counter32, mib_2, ModuleIdentity, Integer32, ObjectIdentity, IpAddress, TimeTicks, MibIdentifier, Counter64, ) = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "Gauge32", "iso", "NotificationType", "Bits", "Counter32", "mib-2", "ModuleIdentity", "Integer32", "ObjectIdentity", "IpAddress", "TimeTicks", "MibIdentifier", "Counter64") ( DisplayString, TimeStamp, TextualConvention, ) = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TimeStamp", "TextualConvention") dsaMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 29)) if mibBuilder.loadTexts: dsaMIB.setLastUpdated('9311250000Z') if mibBuilder.loadTexts: dsaMIB.setOrganization('IETF Mail and Directory Management Working\n Group') if mibBuilder.loadTexts: dsaMIB.setContactInfo(' Glenn Mansfield\n\n Postal: AIC Systems Laboratory\n 6-6-3, Minami Yoshinari\n Aoba-ku, Sendai, 989-32\n JP\n\n Tel: +81 22 279 3310\n Fax: +81 22 279 3640\n E-Mail: [email protected]') if mibBuilder.loadTexts: dsaMIB.setDescription(' The MIB module for monitoring Directory System Agents.') dsaOpsTable = MibTable((1, 3, 6, 1, 2, 1, 29, 1), ) if mibBuilder.loadTexts: dsaOpsTable.setDescription(' The table holding information related to the\n DSA operations.') dsaOpsEntry = MibTableRow((1, 3, 6, 1, 2, 1, 29, 1, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex")) if mibBuilder.loadTexts: dsaOpsEntry.setDescription(' Entry containing operations related statistics\n for a DSA.') dsaAnonymousBinds = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaAnonymousBinds.setDescription(' Number of anonymous binds to this DSA from DUAs\n since application start.') dsaUnauthBinds = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaUnauthBinds.setDescription(' Number of un-authenticated binds to this\n DSA since application start.') dsaSimpleAuthBinds = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaSimpleAuthBinds.setDescription(' Number of binds to this DSA that were authenticated\n using simple authentication procedures since\n application start.') dsaStrongAuthBinds = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaStrongAuthBinds.setDescription(' Number of binds to this DSA that were authenticated\n using the strong authentication procedures since\n application start. This includes the binds that were\n authenticated using external authentication procedures.') dsaBindSecurityErrors = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaBindSecurityErrors.setDescription(' Number of bind operations that have been rejected\n by this DSA due to inappropriateAuthentication or\n invalidCredentials.') dsaInOps = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaInOps.setDescription(' Number of operations forwarded to this DSA\n from DUAs or other DSAs since application\n start up.') dsaReadOps = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaReadOps.setDescription(' Number of read operations serviced by\n this DSA since application startup.') dsaCompareOps = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaCompareOps.setDescription(' Number of compare operations serviced by\n this DSA since application startup.') dsaAddEntryOps = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaAddEntryOps.setDescription(' Number of addEntry operations serviced by\n this DSA since application startup.') dsaRemoveEntryOps = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaRemoveEntryOps.setDescription(' Number of removeEntry operations serviced by\n this DSA since application startup.') dsaModifyEntryOps = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 11), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaModifyEntryOps.setDescription(' Number of modifyEntry operations serviced by\n this DSA since application startup.') dsaModifyRDNOps = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 12), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaModifyRDNOps.setDescription(' Number of modifyRDN operations serviced by\n this DSA since application startup.') dsaListOps = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 13), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaListOps.setDescription(' Number of list operations serviced by\n this DSA since application startup.') dsaSearchOps = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 14), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaSearchOps.setDescription(' Number of search operations- baseObjectSearches,\n oneLevelSearches and subTreeSearches, serviced\n by this DSA since application startup.') dsaOneLevelSearchOps = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 15), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaOneLevelSearchOps.setDescription(' Number of oneLevelSearch operations serviced\n by this DSA since application startup.') dsaWholeTreeSearchOps = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 16), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaWholeTreeSearchOps.setDescription(' Number of wholeTreeSearch operations serviced\n by this DSA since application startup.') dsaReferrals = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 17), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaReferrals.setDescription(' Number of referrals returned by this DSA in response\n to requests for operations since application startup.') dsaChainings = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 18), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaChainings.setDescription(' Number of operations forwarded by this DSA\n to other DSAs since application startup.') dsaSecurityErrors = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 19), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaSecurityErrors.setDescription(' Number of operations forwarded to this DSA\n which did not meet the security requirements. ') dsaErrors = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 1, 1, 20), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaErrors.setDescription(' Number of operations that could not be serviced\n due to errors other than security errors, and\n referrals.\n A partially serviced operation will not be counted\n as an error.\n The errors include NameErrors, UpdateErrors, Attribute\n errors and ServiceErrors.') dsaEntriesTable = MibTable((1, 3, 6, 1, 2, 1, 29, 2), ) if mibBuilder.loadTexts: dsaEntriesTable.setDescription(' The table holding information related to the\n\n entry statistics and cache performance of the DSAs.') dsaEntriesEntry = MibTableRow((1, 3, 6, 1, 2, 1, 29, 2, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex")) if mibBuilder.loadTexts: dsaEntriesEntry.setDescription(' Entry containing statistics pertaining to entries\n held by a DSA.') dsaMasterEntries = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 2, 1, 1), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaMasterEntries.setDescription(' Number of entries mastered in the DSA.') dsaCopyEntries = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 2, 1, 2), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaCopyEntries.setDescription(' Number of entries for which systematic (slave)\n copies are maintained in the DSA.') dsaCacheEntries = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 2, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaCacheEntries.setDescription(' Number of entries cached (non-systematic copies) in\n the DSA. This will include the entries that are\n cached partially. The negative cache is not counted.') dsaCacheHits = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 2, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaCacheHits.setDescription(' Number of operations that were serviced from\n the locally held cache since application\n startup.') dsaSlaveHits = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 2, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaSlaveHits.setDescription(' Number of operations that were serviced from\n the locally held object replications [ shadow\n entries] since application startup.') dsaIntTable = MibTable((1, 3, 6, 1, 2, 1, 29, 3), ) if mibBuilder.loadTexts: dsaIntTable.setDescription(' Each row of this table contains some details\n related to the history of the interaction\n of the monitored DSAs with their respective\n peer DSAs.') dsaIntEntry = MibTableRow((1, 3, 6, 1, 2, 1, 29, 3, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex"), (0, "DSA-MIB", "dsaIntIndex")) if mibBuilder.loadTexts: dsaIntEntry.setDescription(' Entry containing interaction details of a DSA\n with a peer DSA.') dsaIntIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1,2147483647))) if mibBuilder.loadTexts: dsaIntIndex.setDescription(' Together with applIndex it forms the unique key to\n identify the conceptual row which contains useful info\n on the (attempted) interaction between the DSA (referred\n to by applIndex) and a peer DSA.') dsaName = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 3, 1, 2), DistinguishedName()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaName.setDescription(' Distinguished Name of the peer DSA to which this\n entry pertains.') dsaTimeOfCreation = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 3, 1, 3), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaTimeOfCreation.setDescription(' The value of sysUpTime when this row was created.\n If the entry was created before the network management\n subsystem was initialized, this object will contain\n a value of zero.') dsaTimeOfLastAttempt = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 3, 1, 4), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaTimeOfLastAttempt.setDescription(' The value of sysUpTime when the last attempt was made\n to contact this DSA. If the last attempt was made before\n the network management subsystem was initialized, this\n object will contain a value of zero.') dsaTimeOfLastSuccess = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 3, 1, 5), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaTimeOfLastSuccess.setDescription(' The value of sysUpTime when the last attempt made to\n contact this DSA was successful. If there have\n been no successful attempts this entry will have a value\n of zero. If the last successful attempt was made before\n the network management subsystem was initialized, this\n object will contain a value of zero.') dsaFailuresSinceLastSuccess = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 3, 1, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaFailuresSinceLastSuccess.setDescription(' The number of failures since the last time an\n attempt to contact this DSA was successful. If\n there has been no successful attempts, this counter\n will contain the number of failures since this entry\n was created.') dsaFailures = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 3, 1, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaFailures.setDescription(' Cumulative failures since the creation of\n this entry.') dsaSuccesses = MibTableColumn((1, 3, 6, 1, 2, 1, 29, 3, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsaSuccesses.setDescription(' Cumulative successes since the creation of\n this entry.') dsaConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 29, 4)) dsaGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 29, 4, 1)) dsaCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 29, 4, 2)) dsaOpsCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 29, 4, 2, 1)).setObjects(*(("DSA-MIB", "dsaOpsGroup"),)) if mibBuilder.loadTexts: dsaOpsCompliance.setDescription('The compliance statement for SNMPv2 entities\n which implement the DSA-MIB for monitoring\n DSA operations.') dsaEntryCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 29, 4, 2, 2)).setObjects(*(("DSA-MIB", "dsaOpsGroup"), ("DSA-MIB", "dsaEntryGroup"),)) if mibBuilder.loadTexts: dsaEntryCompliance.setDescription('The compliance statement for SNMPv2 entities\n which implement the DSA-MIB for monitoring\n DSA operations, entry statistics and cache\n performance.') dsaIntCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 29, 4, 2, 3)).setObjects(*(("DSA-MIB", "dsaOpsGroup"), ("DSA-MIB", "dsaIntGroup"),)) if mibBuilder.loadTexts: dsaIntCompliance.setDescription(' The compliance statement for SNMPv2 entities\n which implement the DSA-MIB for monitoring DSA\n operations and the interaction of the DSA with\n peer DSAs.') dsaOpsGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 29, 4, 1, 1)).setObjects(*(("DSA-MIB", "dsaAnonymousBinds"), ("DSA-MIB", "dsaUnauthBinds"), ("DSA-MIB", "dsaSimpleAuthBinds"), ("DSA-MIB", "dsaStrongAuthBinds"), ("DSA-MIB", "dsaBindSecurityErrors"), ("DSA-MIB", "dsaInOps"), ("DSA-MIB", "dsaReadOps"), ("DSA-MIB", "dsaCompareOps"), ("DSA-MIB", "dsaAddEntryOps"), ("DSA-MIB", "dsaRemoveEntryOps"), ("DSA-MIB", "dsaModifyEntryOps"), ("DSA-MIB", "dsaModifyRDNOps"), ("DSA-MIB", "dsaListOps"), ("DSA-MIB", "dsaSearchOps"), ("DSA-MIB", "dsaOneLevelSearchOps"), ("DSA-MIB", "dsaWholeTreeSearchOps"), ("DSA-MIB", "dsaReferrals"), ("DSA-MIB", "dsaChainings"), ("DSA-MIB", "dsaSecurityErrors"), ("DSA-MIB", "dsaErrors"),)) if mibBuilder.loadTexts: dsaOpsGroup.setDescription(' A collection of objects for monitoring the DSA\n operations.') dsaEntryGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 29, 4, 1, 2)).setObjects(*(("DSA-MIB", "dsaMasterEntries"), ("DSA-MIB", "dsaCopyEntries"), ("DSA-MIB", "dsaCacheEntries"), ("DSA-MIB", "dsaCacheHits"), ("DSA-MIB", "dsaSlaveHits"),)) if mibBuilder.loadTexts: dsaEntryGroup.setDescription(' A collection of objects for monitoring the DSA\n entry statistics and cache performance.') dsaIntGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 29, 4, 1, 3)).setObjects(*(("DSA-MIB", "dsaName"), ("DSA-MIB", "dsaTimeOfCreation"), ("DSA-MIB", "dsaTimeOfLastAttempt"), ("DSA-MIB", "dsaTimeOfLastSuccess"), ("DSA-MIB", "dsaFailuresSinceLastSuccess"), ("DSA-MIB", "dsaFailures"), ("DSA-MIB", "dsaSuccesses"),)) if mibBuilder.loadTexts: dsaIntGroup.setDescription(" A collection of objects for monitoring the DSA's\n interaction with peer DSAs.") mibBuilder.exportSymbols("DSA-MIB", dsaErrors=dsaErrors, dsaOpsGroup=dsaOpsGroup, dsaTimeOfLastSuccess=dsaTimeOfLastSuccess, dsaGroups=dsaGroups, dsaWholeTreeSearchOps=dsaWholeTreeSearchOps, dsaConformance=dsaConformance, dsaOneLevelSearchOps=dsaOneLevelSearchOps, dsaBindSecurityErrors=dsaBindSecurityErrors, dsaOpsEntry=dsaOpsEntry, dsaSuccesses=dsaSuccesses, dsaOpsCompliance=dsaOpsCompliance, dsaSearchOps=dsaSearchOps, dsaMasterEntries=dsaMasterEntries, dsaTimeOfLastAttempt=dsaTimeOfLastAttempt, dsaUnauthBinds=dsaUnauthBinds, dsaEntryCompliance=dsaEntryCompliance, dsaFailuresSinceLastSuccess=dsaFailuresSinceLastSuccess, dsaMIB=dsaMIB, dsaSecurityErrors=dsaSecurityErrors, dsaModifyEntryOps=dsaModifyEntryOps, dsaIntCompliance=dsaIntCompliance, dsaName=dsaName, dsaOpsTable=dsaOpsTable, dsaIntIndex=dsaIntIndex, dsaTimeOfCreation=dsaTimeOfCreation, dsaChainings=dsaChainings, dsaInOps=dsaInOps, dsaCacheEntries=dsaCacheEntries, dsaEntryGroup=dsaEntryGroup, dsaEntriesEntry=dsaEntriesEntry, dsaStrongAuthBinds=dsaStrongAuthBinds, dsaIntEntry=dsaIntEntry, dsaSimpleAuthBinds=dsaSimpleAuthBinds, dsaReadOps=dsaReadOps, dsaRemoveEntryOps=dsaRemoveEntryOps, dsaModifyRDNOps=dsaModifyRDNOps, dsaFailures=dsaFailures, dsaListOps=dsaListOps, dsaCacheHits=dsaCacheHits, dsaIntTable=dsaIntTable, dsaEntriesTable=dsaEntriesTable, PYSNMP_MODULE_ID=dsaMIB, dsaCompliances=dsaCompliances, dsaCompareOps=dsaCompareOps, dsaCopyEntries=dsaCopyEntries, dsaSlaveHits=dsaSlaveHits, dsaAnonymousBinds=dsaAnonymousBinds, dsaIntGroup=dsaIntGroup, dsaReferrals=dsaReferrals, dsaAddEntryOps=dsaAddEntryOps)
# basic model configuration related and data and training (model specific configuration is declared with Notebook) args = { "batch_size":128, "lr":1e-3, "epochs":10, }
# # @lc app=leetcode id=103 lang=python # # [103] Binary Tree Zigzag Level Order Traversal # # https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/description/ # # algorithms # Medium (40.48%) # Likes: 957 # Dislikes: 59 # Total Accepted: 222.2K # Total Submissions: 530.4K # Testcase Example: '[3,9,20,null,null,15,7]' # # Given a binary tree, return the zigzag level order traversal of its nodes' # values. (ie, from left to right, then right to left for the next level and # alternate between). # # # For example: # Given binary tree [3,9,20,null,null,15,7], # # ⁠ 3 # ⁠ / \ # ⁠ 9 20 # ⁠ / \ # ⁠ 15 7 # # # # return its zigzag level order traversal as: # # [ # ⁠ [3], # ⁠ [20,9], # ⁠ [15,7] # ] # # # # 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 zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] nodes = [[root]] result = [] flag = True while nodes: level = [] current = [] roots = nodes.pop() for root in roots: if flag: current.append(root.val) else: current.insert(0, root.val) if root.left: level.append(root.left) if root.right: level.append(root.right) nodes.append(level) result.append(current) flag = not flag if not level: break return result # if __name__ == "__main__": # s = Solution() # head = TreeNode(3) # head.left = TreeNode(9) # head.right = TreeNode(20) # head.right.left = TreeNode(15) # head.right.right = TreeNode(7) # print s.zigzagLevelOrder(head)
marks = [[1,2,3],[4,5,6],[7,8,9]] rotate = [[False for i in range(len(marks[0]))] for j in range(len(marks))] for row, items in enumerate(marks): for col, val in enumerate(items): rotate[col][row] = val for row in marks: print(row) for row in rotate: print(row)
# do a bunch of ternary operations on an NA object x = 1 / 0 assert type(x) is NA assert type(pow(x, 2)) is NA assert type(pow(2, x)) is NA assert type(x ** 2) is NA assert type(2 ** x) is NA
# first line: 10 @memory.cache def read_wav(): wav = dl.data.get_smashing_baby() return wavfile.read(wav)
#!/usr/bin/python3 # 3-print_reversed_list_integer.py def print_reversed_list_integer(my_list=[]): """Print all integers of a list in reverse order.""" if isinstance(my_list, list): my_list.reverse() for i in my_list: print("{:d}".format(i))
# coding: utf-8 ######################################################################### # 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> # # author yeeku.H.lee [email protected] # # # # version 1.0 # # # # Copyright (C), 2001-2018, yeeku.H.Lee # # # # This program is protected by copyright laws. # # # # Program Name: # # # # <br>Date: # ######################################################################### def check_key (key): ''' 该函数将会负责检查序列的索引,该索引必须是整数值,否则引发TypeError 且程序要求索引必须为非负整数,否则引发IndexError ''' if not isinstance(key, int): raise TypeError('索引值必须是整数') if key < 0: raise IndexError('索引值必须是非负整数') if key >= 26 ** 3: raise IndexError('索引值不能超过%d' % 26 ** 3) class StringSeq: def __init__(self): # 用于存储被修改的数据 self.__changed = {} # 用于存储已删除元素的索引 self.__deleted = [] def __len__(self): return 26 ** 3 def __getitem__(self, key): ''' 根据索引获取序列中元素 ''' check_key(key) # 如果在self.__changed中找到已经修改后的数据 if key in self.__changed : return self.__changed[key] # 如果key在self.__deleted中,说明该元素已被删除 if key in self.__deleted : return None # 否则根据计算规则返回序列元素 three = key // (26 * 26) two = ( key - three * 26 * 26) // 26 one = key % 26 return chr(65 + three) + chr(65 + two) + chr(65 + one) def __setitem__(self, key, value): ''' 根据索引修改序列中元素 ''' check_key(key) # 将修改的元素以key-value对的形式保存在__changed中 self.__changed[key] = value def __delitem__(self, key): ''' 根据索引删除序列中元素 ''' check_key(key) # 如果__deleted列表中没有包含被删除key,添加被删除的key if key not in self.__deleted : self.__deleted.append(key) # 如果__changed中包含被删除key,删除它 if key in self.__changed : del self.__changed[key] # 创建序列 sq = StringSeq() # 获取序列的长度,实际上就是返回__len__()方法的返回值 print(len(sq)) print(sq[26*26]) # 打印没修改之后的sq[1] print(sq[1]) # 'AAB' # 修改sq[1]元素 sq[1] = 'fkit' # 打印修改之后的sq[1] print(sq[1]) # 'fkit' # 删除sq[1] del sq[1] print(sq[1]) # None # 再次对sq[1]赋值 sq[1] = 'crazyit' print(sq[1]) # crazyit
class Config: BASE_DIR = "/usr/local/lib/python3.9/site-packages" FACEBOOK_PACKAGE = "facebook_business" ADOBJECT_DIR = "adobjects" # https://github.com/facebook/facebook-python-business-sdk/tree/master/facebook_business/adobjects FULL_PATH = f"{BASE_DIR}/{FACEBOOK_PACKAGE}/{ADOBJECT_DIR}" NEO4J_HOST = "bolt://service-neo4j:7687" EXCLUSION_LIST = ["__init__.py", "abstractobject.py", "abstractcrudobject.py"]
__version__ = "2.0.1" __version_info__ = tuple(int(num) for num in __version__.split(".")) default_app_config = "dbfiles.apps.DBFilesConfig"
fo = open("list.txt", "r") lines = fo.readlines() outf = open("out.txt", "w") for line in lines: l = line.replace("\n","") ls = l.split(",") pl = "first: " + ls[0] + " second: " + ls[1] + " third: " + ls[2] outf.write(pl) outf.close()
# coding: utf-8 # created by Martin Haese, Tel FRM 10763 # last modified 01.02.2018 # to call it # ssh -X refsans@refsansctrl01 oder 02 # cd /refsanscontrol/src/nicos-core # INSTRUMENT=nicos_mlz.refsans bin/nicos-monitor -S monitor_scatgeo description = 'REFSANS scattering geometry monitor' group = 'special' # Legende fuer _componentpositioncol # dev='...' stellt hier nur die moeglichen Werte dar, keine devices _componentpositioncol = Column( # Block(' x: component position in beam direction (b3 = 0.0mm) ', [ Block(' x: component position in beam direction ', [ BlockRow( Field(name='goniometer', dev='goniometer_x', width=14, unit='mm'), Field(name='sample center', dev='sample_x', width=14, unit='mm'), Field(name='monitor pos', dev='monitor_pos', width=14, unit='mm'), Field(name='backguard pos', dev='backguard_pos', width=14, unit='mm'), Field(name='tube pivot', dev='tube_pivot', width=10), Field(name='table origin', dev='table_zero', width=14, unit='mm'), Field(name='table', dev='table_pos', width=14, unit='mm'), Field(name='dist b3 gonio', dev='b3_gonio', width=14, unit='mm'), Field(name='dist b3 sample', dev='b3_sample', width=14, unit='mm'), Field(name='dist b3 monitor', dev='b3_monitor', width=14, unit='mm'), # Field(name='dist b3 backguard', dev='b3_backguard', width=14, unit='mm'), Field(name='det_pivot', dev='det_pivot', width=10), Field(name='det_table', dev='det_table', width=14, unit='mm'), Field(name='dist sample det', dev='sample_det', width=14, unit='mm'), Field(name='flight path', dev='flight_path', width=14, unit='mm'), ), ], ), ) # Legende fuer _componentlateralcol # dev='...' stellt hier nur die moeglichen Werte dar, keine devices _componentlateralcol = Column( Block(' y: lateral component position and angle (b3 = 0.0mm) ', [ # Block(' y: lateral component position ', [ BlockRow( Field(name='sample y', dev='probenwechsler', width=14, unit='mm'), Field(name='sample phi', dev='sample_phi', width=14, unit='deg'), Field(name='tube y', dev='tube_y', width=14, unit='mm'), Field(name='tube angle', dev='tube_lateral_angle', width=14, unit='deg'), Field(name='probenwechsler', dev='probenwechsler', width=14, unit='mm'), Field(name='gonio_y', dev='gonio_y', width=14, unit='mm'), Field(name='det y', dev='det_y', width=14, unit='mm'), Field(name='beamstop y', dev='beamstop_y', width=14, unit='mm'), ), ], ), ) # Legende fuer _componentverticalcol # dev='...' stellt hier nur die moeglichen Werte dar, keine devices _componentverticalcol = Column( Block(' z: vertical component position and angle (b3 = 0.0mm) ', [ # Block(' z: vertical component position ', [ BlockRow( Field(name='sample z', dev='sample_z', width=14, unit='mm'), Field(name='sample theta', dev='sample_theta', width=14, unit='deg'), Field(name='backguard', dev='backguard_z', width=14, unit='mm'), Field(name='tube', dev='tube_z', width=14, unit='mm'), Field(name='tube angle', dev='tube_vertical_angle', width=14, unit='deg'), Field(name='beamstop', dev='beamstop_z', width=14, unit='mm'), Field(name='gonio_z', dev='gonio_z', width=14, unit='mm'), Field(name='backguard', dev='backguard', width=14, unit='mm'), Field(name='det_yoke', dev='det_yoke', width=14, unit='mm'), Field(name='beamstop z', dev='beamstop_z', width=14, unit='mm'), ), ], ), ) # Legende fuer _componentanglescol # dev='...' stellt hier nur die moeglichen Werte dar, keine devices _componentanglescol = Column( Block(' component angles ', [ BlockRow( Field(name='gonio_theta', dev='gonio_theta', width=14, unit='deg'), Field(name='gonio_phi', dev='gonio_phi', width=14, unit='deg'), Field(name='gonio_omega', dev='gonio_omega', width=14, unit='deg'), Field(name='det hor angle', dev='det_hor_angle', width=14, unit='deg'), Field(name='det vert angle', dev='det_vert_angle', width=14, unit='deg'), Field(name='beam_tilt', dev='beam_tilt', width=14, unit='mrad'), ), ], ), ) # Legende fuer _topgoniometercol # dev='...' stellt hier nur die moeglichen Werte dar, keine devices _topgoniometercol = Column( Block(' top goniometer ', [ BlockRow( Field(name='top_theta', dev='top_theta', width=14, unit='deg'), Field(name='top_phi', dev='top_phi', width=14, unit='deg'), Field(name='top_omega', dev='top_omega', width=14, unit='deg'), Field(name='top_x', dev='top_x', width=14, unit='mm'), Field(name='top_y', dev='top_y', width=14, unit='mm'), Field(name='top_z', dev='top_z', width=14, unit='mm'), ), ], ), ) # Legende fuer _autocollimatorcol # dev='...' stellt hier nur die moeglichen Werte dar, keine devices _autocollimatorcol = Column( Block(' autocollimator ', [ BlockRow( Field(name='ac_theta', dev='ac_theta', width=14, unit='deg'), Field(name='ac_phi', dev='ac_phi', width=14, unit='deg'), Field(name='ac_error', dev='ac_error', width=14, unit='deg'), ), ], ), ) # Legende fuer _altimetercol # dev='...' stellt hier nur die moeglichen Werte dar, keine devices _altimetercol = Column( Block(' altimeter ', [ BlockRow( Field(name='height', dev='altimeter', width=14, unit='mm'), ), ], ), ) # Legende fuer _samplesizecol # dev='...' stellt hier nur die moeglichen Werte dar, keine devices _samplesizecol = Column( Block(' sample size ', [ BlockRow( Field(name='length', key='sample/length', width=14, unit='mm'), Field(name='width', key='sample/width', width=14, unit='mm'), Field(name='footprint', dev='footprint', width=14, unit='mm'), ), ], ), ) # Legende fuer _sampletempcol # dev='...' stellt hier nur die moeglichen Werte dar, keine devices _sampletempcol = Column( Block(' sample temperature ', [ BlockRow( Field(name='julabo', dev='temp_julabo', width=14, unit='deg C'), Field(name='cryo', dev='temp_cryo', width=14, unit='K'), ), ], ), ) # Legende fuer _samplethumicol # dev='...' stellt hier nur die moeglichen Werte dar, keine devices _samplethumicol = Column( Block(' sample ', [ BlockRow( Field(name='humidity', dev='humidity', width=14, unit='%'), ), ], ), ) devices = dict( Monitor = device('nicos.services.monitor.qt.Monitor', title = description, loglevel = 'info', cache = 'localhost', valuefont = 'Consolas', padding = 5, layout = [ Row(_componentpositioncol), Row(_componentlateralcol, _sampletempcol), Row(_componentverticalcol, _altimetercol, _samplethumicol), Row(_autocollimatorcol, _samplesizecol), Row(_componentanglescol), Row(_topgoniometercol), ], ), )
#!/usr/bin/env python ''' --- Day 12: Passage Pathing --- With your submarine's subterranean subsystems subsisting suboptimally, the only way you're getting out of this cave anytime soon is by finding a path yourself. Not just a path - the only way to know if you've found the best path is to find all of them. Fortunately, the sensors are still mostly working, and so you build a rough map of the remaining caves (your puzzle input). For example: start-A start-b A-c A-b b-d A-end b-end This is a list of how all of the caves are connected. You start in the cave named start, and your destination is the cave named end. An entry like b-d means that cave b is connected to cave d - that is, you can move between them. So, the above cave system looks roughly like this: start / \ c--A-----b--d \ / end Your goal is to find the number of distinct paths that start at start, end at end, and don't visit small caves more than once. There are two types of caves: big caves (written in uppercase, like A) and small caves (written in lowercase, like b). It would be a waste of time to visit any small cave more than once, but big caves are large enough that it might be worth visiting them multiple times. So, all paths you find should visit small caves at most once, and can visit big caves any number of times. Given these rules, there are 10 paths through this example cave system: start,A,b,A,c,A,end start,A,b,A,end start,A,b,end start,A,c,A,b,A,end start,A,c,A,b,end start,A,c,A,end start,A,end start,b,A,c,A,end start,b,A,end start,b,end (Each line in the above list corresponds to a single path; the caves visited by that path are listed in the order they are visited and separated by commas.) Note that in this cave system, cave d is never visited by any path: to do so, cave b would need to be visited twice (once on the way to cave d and a second time when returning from cave d), and since cave b is small, this is not allowed. Here is a slightly larger example: dc-end HN-start start-kj dc-start dc-HN LN-dc HN-end kj-sa kj-HN kj-dc The 19 paths through it are as follows: start,HN,dc,HN,end start,HN,dc,HN,kj,HN,end start,HN,dc,end start,HN,dc,kj,HN,end start,HN,end start,HN,kj,HN,dc,HN,end start,HN,kj,HN,dc,end start,HN,kj,HN,end start,HN,kj,dc,HN,end start,HN,kj,dc,end start,dc,HN,end start,dc,HN,kj,HN,end start,dc,end start,dc,kj,HN,end start,kj,HN,dc,HN,end start,kj,HN,dc,end start,kj,HN,end start,kj,dc,HN,end start,kj,dc,end Finally, this even larger example has 226 paths through it: fs-end he-DX fs-he start-DX pj-DX end-zg zg-sl zg-pj pj-he RW-he fs-DX pj-RW zg-RW start-pj he-WI zg-he pj-fs start-RW How many paths through this cave system are there that visit small caves at most once? Your puzzle answer was 3485. --- Part Two --- After reviewing the available paths, you realize you might have time to visit a single small cave twice. Specifically, big caves can be visited any number of times, a single small cave can be visited at most twice, and the remaining small caves can be visited at most once. However, the caves named start and end can only be visited exactly once each: once you leave the start cave, you may not return to it, and once you reach the end cave, the path must end immediately. Now, the 36 possible paths through the first example above are: start,A,b,A,b,A,c,A,end start,A,b,A,b,A,end start,A,b,A,b,end start,A,b,A,c,A,b,A,end start,A,b,A,c,A,b,end start,A,b,A,c,A,c,A,end start,A,b,A,c,A,end start,A,b,A,end start,A,b,d,b,A,c,A,end start,A,b,d,b,A,end start,A,b,d,b,end start,A,b,end start,A,c,A,b,A,b,A,end start,A,c,A,b,A,b,end start,A,c,A,b,A,c,A,end start,A,c,A,b,A,end start,A,c,A,b,d,b,A,end start,A,c,A,b,d,b,end start,A,c,A,b,end start,A,c,A,c,A,b,A,end start,A,c,A,c,A,b,end start,A,c,A,c,A,end start,A,c,A,end start,A,end start,b,A,b,A,c,A,end start,b,A,b,A,end start,b,A,b,end start,b,A,c,A,b,A,end start,b,A,c,A,b,end start,b,A,c,A,c,A,end start,b,A,c,A,end start,b,A,end start,b,d,b,A,c,A,end start,b,d,b,A,end start,b,d,b,end start,b,end The slightly larger example above now has 103 paths through it, and the even larger example now has 3509 paths through it. Given these new rules, how many paths through this cave system are there? Your puzzle answer was 85062. ''' graph_map = {} class PassageMap: def __init__(self, part_1): self.graph = {} self.small_caves = {} self.paths_to_end = 0 self.small_cave_travel_twice = False self.part_1 = part_1 def add_node(self, start, end): # Add the start and end node in the graph, these are bi-directional graphs if start not in self.graph: self.graph[start] = [] if end not in self.graph: self.graph[end] = [] if start.islower(): if start not in self.small_caves: self.small_caves[start] = 0 if end.islower(): if end not in self.small_caves: self.small_caves[end] = 0 self.graph[start].append(end) self.graph[end].append(start) def depth_first_search_to_end(self, current_cave='start'): # using depth first search find all the paths to end for cave in self.graph[current_cave]: if cave == 'start': # ignore start cave continue if cave == 'end': # we are at the end of the path self.paths_to_end += 1 continue # Check the small caves we have traverse if cave in self.small_caves: if self.small_caves[cave] >= 1: if self.part_1 or self.small_cave_travel_twice: continue self.small_cave_travel_twice = True self.small_caves[cave] += 1 # Go deeper self.depth_first_search_to_end(cave) if cave in self.small_caves: # decrease the number of small caves self.small_caves[cave] -= 1 if self.small_caves[cave] == 1: self.small_cave_travel_twice = False def number_paths_to_end(self): return self.paths_to_end def reset(self, part_1): self.paths_to_end = 0 self.part_1 = part_1 passage_map = PassageMap(part_1=True) with open('input_data.txt', 'r') as f: line = f.readline() while line: start, end = line.strip().split('-') passage_map.add_node(start, end) line = f.readline() passage_map.depth_first_search_to_end() print(f"number of paths to end for part-1: {passage_map.number_paths_to_end()}") passage_map.reset(part_1=False) passage_map.depth_first_search_to_end() print(f"number of paths to end for part-2: {passage_map.number_paths_to_end()}")
intervals = [(2, 15), (36, 45), (9, 29), (16, 23), (4, 9)] def room_num(intervals): intervals_sorted = sorted(intervals, key=lambda x: x[0]) rooms = 1 room_open_time = [intervals_sorted[0][1]] for interval in intervals_sorted[1:]: if interval[0] < min(room_open_time): rooms += 1 room_open_time.append(interval[1]) else: room_open_time[room_open_time.index(min(room_open_time))] = interval[1] return rooms print(room_num(intervals))
""" Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. """ class Solution(): def contains_dups(self, nums, k): nhash = {} for i in range(len(nums)): if nhash.get(nums[i]): j = max(nhash[nums[i]]) if i - j <= k: return True nhash[nums[i]].append(i) else: nhash[nums[i]] = [i] return False nums = [1, 2, 3, 1] k = 3 # nums = [1, 2, 3, 1, 2, 3] # k = 2 s = Solution() print(s.contains_dups(nums, k))
def web_page_wifi(): html = """<!DOCTYPE html><html lang="de"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <form action="/get"> <h1>Wifi configuration</h1> <br> <a href= "mailto:[email protected]">contact support</a> <br> <br> <label for="ssid">SSID:</label> <input type="text" id="ssid" name="ssid"><br><br> <label for="password">Password:</label> <input type="password" id="password" name="password"><br><br> <input type="hidden" id="helpvarcryptoticker" name="helpvarcryptoticker"><br> <input type="submit" value="Submit"> </form></body>""" return html
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ----------------------------------------- @Author: isky @Email: [email protected] @Created: 2019/11/19 ------------------------------------------ @Modify: 2019/11/19 ------------------------------------------ @Description: """
def merge(pic_1, pic_2): return { 'id': pic_1['id'] + pic_2['id'], 'tags': pic_1['tags'] | pic_2['tags'], } def get_score_table(pics): score_table = {} for i in range(len(pics)): for j in range(i + 1, len(pics)): r = len(pics[i]['tags'] & pics[j]['tags']) p = len(pics[i]['tags']) - r q = len(pics[j]['tags']) - r score = min([r, p, q]) if i not in score_table: score_table[i] = [] if j not in score_table: score_table[j] = [] score_table[i].append((score, j)) score_table[j].append((score, i)) for idx in score_table: score_table[idx].sort(key=lambda x: -x[0]) return score_table def get_slides(h_pics, v_pics): get_num_tags = lambda pic: len(pic['tags']) sorted_v_pics = sorted(v_pics, key=get_num_tags) v_slides = [merge(sorted_v_pics[2 * i], sorted_v_pics[2 * i + 1]) for i in range(len(sorted_v_pics) // 2)] slides = sorted(h_pics + v_slides, key=get_num_tags) partition = 10 top_tier = slides[-len(slides) // partition:] score_table = get_score_table(top_tier) seen_table = {top_tier_idx: 0 for top_tier_idx in score_table} selected_id = set([0]) sorted_top_tier = [top_tier[0]] last_idx = 0 for i in range(len(top_tier) - 1): for j in range(seen_table[last_idx], len(top_tier) - 1): next_idx = score_table[last_idx][j][1] if next_idx not in selected_id: sorted_top_tier.append(top_tier[next_idx]) seen_table[last_idx] = j selected_id.add(next_idx) last_idx = next_idx break return slides[:-len(slides) // partition] + sorted_top_tier def get_score(slides): score = 0 for i in range(len(slides) - 1): r = len(slides[i]['tags'] & slides[i + 1]['tags']) p = len(slides[i]['tags']) - r q = len(slides[i + 1]['tags']) - r score += min([p, q, r]) return score sol_folder = 'top_tier' datasets = ['a_example', 'b_lovely_landscapes', 'c_memorable_moments', 'd_pet_pictures', 'e_shiny_selfies'] # datasets = ['d_pet_pictures'] max_score = {dataset: 0 for dataset in datasets} ref_ans = {dataset: [] for dataset in datasets} random_round = 1 for dataset in datasets: f = open('QualificationRound/{}.txt'.format(dataset)) n = int(f.readline()) h_pics, v_pics = [], [] for i in range(n): tags = f.readline().strip().split() pic_type, num_tags, tags = tags[0], int(tags[1]), set(tags[2:]) if pic_type == 'H': h_pics.append({ 'id': [str(i)], 'tags': tags, }) elif pic_type == 'V': v_pics.append({ 'id': [str(i)], 'tags': tags }) for a in range(random_round): slides = get_slides(h_pics, v_pics) score = get_score(slides) if score > max_score[dataset]: max_score[dataset] = score ref_ans[dataset] = slides for dataset in datasets: wf = open('QualificationRound/{}/{}.txt'.format(sol_folder, dataset), 'w') wf.write('{}\n'.format(len(ref_ans[dataset]))) for slide in ref_ans[dataset]: wf.write('{}\n'.format(' '.join(slide['id']))) wf.close() # for i in range(len(slides)): # print(slides[i]['tags']) # if(i!=len(slides)-1): # middle = len(slides[i]['tags'].intersection(slides[i+1]['tags'])) # left = len(slides[i]['tags']) - middle # right = len(slides[i+1]['tags']) - middle # print(left, middle, right, min(left,middle,right))
def for_E(): """We are creating user defined function for alphabetical pattern of capital E with "*" symbol""" row=7 col=5 for i in range(row): for j in range(col): if i==0 or i==3 or i==6 or j==0: print("*",end=" ") else: print(" ",end=" ") print() def while_E(): i=0 while i<7: j=0 while j<5: if i==0 or i==3 or i==6 or j==0 : print("*",end=" ") else: print(" ",end=" ") j+=1 i+=1 print()
def part1(inp): drawn_numbers = [int(x) for x in inp.pop(0).split(",")] boards = [] for i in range(len(inp) // 6): inp.pop(0) board = [[int(x) for x in inp.pop(0).split()] for j in range(5)] boards.append(board) for num in drawn_numbers: for board in boards: mark_board(board, num) if check_for_win(board): return num * sum( [sum(x for x in board[i][:] if x != -1) for i in range(len(board))] ) def part2(inp): drawn_numbers = [int(x) for x in inp.pop(0).split(",")] boards = [] for i in range(len(inp) // 6): inp.pop(0) board = [[int(x) for x in inp.pop(0).split()] for j in range(5)] boards.append(board) boards_won = set() for num in drawn_numbers: for i, board in enumerate(boards): if i in boards_won: continue mark_board(board, num) if check_for_win(board): boards_won.add(i) if len(boards_won) == len(boards): return num * sum( [sum(x for x in board[i][:] if x != -1) for i in range(len(board))] ) def mark_board(board, num): for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == num: board[i][j] = -1 def check_for_win(board): for row in board: if all(x == -1 for x in row): return True for col in range(len(board[0])): if all(board[i][col] == -1 for i in range(len(board))): return True return False # def part2(inp): def test_check_for_win(): board = [ [1, 2, 3, 4], [1, 2, 3, 4], [-1, -1, -1, -1], [1, 2, 3, 4], ] assert check_for_win(board) is True board[2] = [1, 1, 1, 1] assert check_for_win(board) is False board[0][1] = -1 board[1][1] = -1 board[2][1] = -1 board[3][1] = -1 assert check_for_win(board) is True def test_day4_sample(): with open("/Users/sep/CLionProjects/aoc-2021/src/test_files/day4_sample.txt") as f: inp = [s.rstrip("\n").lstrip() for s in f.readlines()] assert part1(inp) == 4512 def test_day4_submission(): with open( "/Users/sep/CLionProjects/aoc-2021/src/test_files/day4_submission.txt" ) as f: inp = [s.rstrip("\n") for s in f.readlines()] assert part1(inp) == 16674 def test_day4_part2_sample(): with open("/Users/sep/CLionProjects/aoc-2021/src/test_files/day4_sample.txt") as f: inp = [s.rstrip("\n") for s in f.readlines()] assert part2(inp) == 1924 def test_day4_part2_submission(): with open( "/Users/sep/CLionProjects/aoc-2021/src/test_files/day4_submission.txt" ) as f: inp = [s.rstrip("\n") for s in f.readlines()] assert part2(inp) == 7075
""" Purpose: stackoverflow solution. Date created: 2021-03-04 Title: How to generate a lists of lists or nested from user input while outputting amount of times a word is stated? URL: https://stackoverflow.com/questions/66483811/how-to-generate-a-lists-of-lists-or-nested-from-user-input-while-outputting-amou/66484266#66484266 Contributor(s): Mark M. """ sample = "Nice day #running #10k #power #running" # Output: [running,10k, power, running] and [[running,2],[10k,1],[power,1]] def incr(el, ddict): if not el in ddict: ddict[el] = 1 else: ddict[el] += 1 def process_input(string, key_char = "#"): # Creating a clean list of keywords by a given target character. base_list = [i.replace(f"{key_char}", "") for i in string.split(" ") if i[0] == f"{key_char}"] # We can use the list.count() function on a set of keywords # to return the instance of each word within a given string. word_count_list = [[w, base_list.count(w)] for w in set(base_list)] return base_list, word_count_list process_input(sample)
print('\n========= R$ =========') val = float(input('Digite o valor da moéda: -> ')) print('\n========= U$ =========') dol = float(input('Digite o valor do dólar: -> ')) conv = val / dol print('\n======= conversão =======') print('O valor da conversão é U$: {:.2f}'.format(conv)) print('\n=========================')
class Version(str): SEPARATOR = '.' def __new__(cls, version=""): obj = str.__new__(cls, version) obj._list = None return obj @property def list(self): if self._list is None: self._list = [] for item in self.split(Version.SEPARATOR): self._list.append(int(item) if item.isdigit() else item) return self._list def serialize(self): return str(self) @staticmethod def deserialize(data): if not data: return None return Version(data) def __cmp__(self, other): if other is None: return cmp(self.list, None) if isinstance(other, basestring): other = Version(other) return cmp(self.list, other.list) def __gt__(self, other): return cmp(self, other) == 1 def __lt__(self, other): return cmp(self, other) == -1 def __le__(self, other): c = cmp(self, other) return c in [0, -1] def __ge__(self, other): c = cmp(self, other) return c in [0, 1]
class Solution: """ @param nums: an array of integers @param k: an integer @return: the number of unique k-diff pairs """ def findPairs(self, nums, k): ans = 0 num_set = set(nums) if k == 0: num_dict = dict([(num, 0) for num in num_set]) for num in nums: num_dict[num] += 1 for num, times in num_dict.items(): if times > 1: ans += 1 else: possible_nums = set() for num in num_set: possible_nums.add(num + k) possible_nums.add(num - k) if num in possible_nums: ans += 1 return ans
# MEDIUM # this is like Word Break => DFS + Memoization # define a lambda x,y: x {+,-,*} y # scan the string s: # break at operators "+-*" => left = s[:operator] right = s[operator+1:] # recurse each left, right: # try every possible operations of left and right # Time O(N!) Space O(N) class Solution: def diffWaysToCompute(self, input: str) -> List[int]: self.memo = {} self.ops = { "+": lambda x,y: x+y, "-": lambda x,y: x-y, "*": lambda x,y: x*y, } return self.dfs(input) def dfs(self,s): result = [] if s in self.memo: return self.memo[s] for i in range(len(s)): if s[i] in {"+","-","*"}: left = s[:i] right = s[i+1:] l = self.dfs(left) r = self.dfs(right) for a in l: for b in r: result.append(self.ops[s[i]](a,b)) if not result: result.append(int(s)) self.memo[s] = result return result
#!/usr/bin/env python3 # day007.py # By Sebastian Raaphorst, 2019. # We memoize the auxiliary internal function in calculate_decodings, because the recursion explodes into # already-solved sub-problems. # For the last test, without memoization, it takes class Memoize: def __init__(self, f): self.f = f self.memo = {} def __call__(self, *args): if not args in self.memo: self.memo[args] = self.f(*args) return self.memo[args] def calculate_decodings(enc: str) -> int: """ Given an encoded string consisting of numbers, using the decoding: a -> 1, b -> 2, ..., z -> 26, calculate the number of ways in which the string can be decoded. :param enc: the string to decode :return: the number of possible decodings >>> calculate_decodings('111') 3 >>> calculate_decodings('121') 3 >>> calculate_decodings('131') 2 >>> calculate_decodings('1234') 3 >>> calculate_decodings('2563') 2 >>> calculate_decodings('4123') 3 >>> calculate_decodings('1101') 1 >>> calculate_decodings('11101') 2 >>> calculate_decodings('1001') 0 # 17 is 1/7 or 17 2 choices # 224 is 2/2/4 or 22/4 or 2/24 3 choices # 3 is 3 1 choice # 15 is 1/5 or 15 2 choices # 9 is 9 1 choice # 20 is 20 1 choice # 22 is 2/2 or 22 2 choices # Total = 2^3 * 3 = 24 choices >>> calculate_decodings('1722431592022') 24 # On my MacBook pro: # cProfile.run("calculate_decodings('111111111111111111111111111111111111')") # * without memoization, this takes 76.355 seconds. # * with memoization, this takes less than 0.01 seconds. # Profiled using: # import cProfile # cProfile.run(...) # Note that using a string entirely of 1s and / or 2s leads to the Fibonacci numbers, as we must break # the string into bits of lengths 1 and 2, which is equivalent to the coding of a 1xn board with # squares and dominoes. >>> calculate_decodings('111111111111111111111111111111111111') 24157817 """ # General strategy: we break this down into a case-by-case basis and recursively ascertain the number of possible # decoding. To begin with, the numbers: # (A) 3 - 6 are the same and will be treated as such; and # (B) 7 - 9 are the same. # This, we begin by converting these characters to tokens A and B respectively to simplify the processing # and to increase the chances at memoization. enc = enc.translate(enc.maketrans({'3': 'A', '4': 'A', '5': 'A', '6': 'A', '7': 'B', '8': 'B', '9': 'B'})) # Now we use an auxiliary method to consider all possible cases. # There could be some optimization here: slicing + comparing is slightly faster than startswith, and # >>> timeit.timeit('"1234".startswith("12")', number=10000000) # 1.5383420000434853 # >>> timeit.timeit('"1234"[:2] == "12"', number=10000000) # 1.2081479519838467 # and furthermore, the long if statement might be faster if using sets, e.g. # if len(2) > 1 and ((s[0] == '1' and s[1] in S1) or (s[0] == '2' and s[2] in S2) # but I think it is clearer what is happening with the list of startswith. @Memoize def aux(s: str) -> int: # Base case 1: if s is empty, there is a unique decoding. if len(s) <= 1: return 1 # Base case 2: if the first character of s is 0, we have made a mistake. # This could occur in, e.g., 110 when we consider 110 to be 11/0 instead of 1/10. if s[0] == '0': return 0 # Base case 2: if s contains a single character, we only have one decoding. if len(s) == 1: assert s[0] != '0', f"{s} contains 0 in illegal position" return 1 # If s starts with either A or B, then we can only decode to the symbol that was changed to A or B # so this part of the encoding is fixed. Advance and recurse. if s.startswith('A') or s.startswith('B'): return aux(s[1:]) # If s starts with either 10 or 20, then we can only decode to j or t. Advance and recurse. if s.startswith('10') or s.startswith('20'): return aux(s[2:]) # If s starts with 2B, then we can only decode to b for 2 and the symbol represented by B. # Advance and recurse. if s.startswith('2B'): return aux(s[2:]) # Now the mixed case: # If s starts with 11, 12, 1A, or 1B, then it can be decoded into two possibilities. # If s starts with 21, 22, or 2A, then it too can be decoded into two possibilities. if s.startswith('11') or s.startswith('12') or s.startswith('1A') or s.startswith('1B') or \ s.startswith('21') or s.startswith('22') or s.startswith('2A'): return aux(s[1:]) + aux(s[2:]) # If we reached this point, something went wrong: an illegal character? assert False, f"{s} is badly formed" return aux(enc)
""" -The zip functions takes some iterators and zips Them on Tuples. - Used to parallel iterations - Retun a zip object which is an iterators of zip. the zip function takes the len of the shortest zip ands used it as main path to zip to the other zip. """ countries = "Ecuador" capitals = "Quito" countries_capitals = zip(countries, capitals) print(list(countries_capitals))
git_response = { "login": "dimddev", "id": 57534, "node_id": "MdQ6VXnlc4U3NTM0NDA=", "avatar_url": "https://avatars1.githubusercontent.com/u/5753440?v=4", "gravatar_id": "", "url": "https://api.github.com/users/dimddev", "html_url": "https://github.com/dimddev", "followers_url": "https://api.github.com/users/dimddev/followers", "following_url": "https://api.github.com/users/dimddev/following{/other_user}", "gists_url": "https://api.github.com/users/dimddev/gists{/gist_id}", "starred_url": "https://api.github.com/users/dimddev/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/dimddev/subscriptions", "organizations_url": "https://api.github.com/users/dimddev/orgs", "repos_url": "https://api.github.com/users/dimddev/repos", "events_url": "https://api.github.com/users/dimddev/events{/privacy}", "received_events_url": "https://api.github.com/users/dimddev/received_events", "type": "User", "site_admin": "false", "name": "Di Mita Hakini", "company": "null", "blog": "http://nasa.gov", "location": "Sofia", "email": "[email protected]", "hireable": "null", "bio": "null", "public_repos": 34, "public_gists": 2, "followers": 21, "following": 12, "created_at": "2013-10-23T06:07:30Z", "updated_at": "2019-08-24T09:06:41Z", "private_gists": 1, "total_private_repos": 0, "owned_private_repos": 0, "disk_usage": 5819, "collaborators": 0, "two_factor_authentication": "false", "plan": { "name": "free", "space": 976562499, "collaborators": 0, "private_repos": 10000 } } fresh_response = { "active": 'false', "address": "Sofia", "company_id": 'null', "view_all_tickets": 'null', "deleted": 'false', "description": 'null', "email": "[email protected]", "id": 47003672837, "job_title": 'null', "language": "en", "mobile": 'null', "name": "Di Mita Hakini", "phone": 'null', "time_zone": "Baghdad", "twitter_id": 'null', "custom_fields": {}, "tags": [], "other_emails": [], "facebook_id": 'null', "created_at": "2019-09-30T14:05:52Z", "updated_at": "2019-09-30T14:05:52Z", "other_companies": [], "unique_external_id": 'null', "avatar": 'null' }
continuar = '' countwomen = 0 countmen = 0 maioridade = 0 while continuar != 'N': print('\033[1;34mCadastre uma Pessoa\033[m') print('===' * 10) idade = int(input('Idade: ')) if idade > 18: maioridade = maioridade + 1 sexo = str(input('Digite o sexo[M/F]: ').upper().strip()) if sexo == 'F': if idade < 20: countwomen = countwomen + 1 elif sexo == 'M': countmen = countmen + 1 while sexo != 'M' and sexo != 'F': print('\033[1;4;31mOpção inválida!\033[m') print('\033[1;31mDigite uma opção válida\033[m') sexo = str(input('Digite o sexo [M/F]: ').upper().strip()) print('\033[1;35m==\033[m' * 10) dec = str(input('Quer continuar[S/N]? ')).upper().strip() if dec == 'N': break print('\033[1;35m==\033[m' * 10) while dec != 'S' and dec != 'N': print('\033[1;4;31mOpção inválida!\033[m') print('\033[1;31mDigite uma opção válida\033[m') dec = str(input('Quer continuar[S/N]?')).upper().strip() print('=' * 10) print('\033[1;32mPROGRAMA FINALIZADO!\033[m') print(f'''Ao todo foram {countmen} homens cadastrados, {countwomen} mulheres com menos de 20 anos, e {maioridade} pessoas com mais de 18 anos.''')
# # user-statistician: Github action for generating a user stats card # # Copyright (c) 2021 Vincent A Cicirello # https://www.cicirello.org/ # # MIT License # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # Notes on the included themes: # # The light, dark, and dark-dimmed themes are based on # GitHub's themes, and color-palette (see # https://primer.style/css/support/color-system # and https://primer.style/primitives/). # # Specifically, from the link above we use: # * background color (bg): bg.canvasInset # * border color: box.blueBorder # * icons: icon.info # * text: text.primary # * title: bg.canvasInverse # # Notes to Potential Contributors: # # (1) For those who want to contribute a theme, # please check the combination of your background # color with text color, and background with title # color for accessibility at this site, # https://colorable.jxnblk.com/, and make sure the # combination has a rating of at least AA. You can also # simply run the test cases, which will automatically # verify that the text color and the background color have # a contrast ratio of at least 4.5:1, which is AA. # The contrast ratio between the background and title # colors should also be at least 4.5:1 (also enforced by test cases). # # (2) Before contributing a new color theme, ask yourself # whether it will likely have broad appeal or a narrow # audience. For example, if it is just the color palette # of your personal website or blog, then a theme may not # be necessary. You can simply use the colors input for # your usage. # # (3) Is it similar to one of the existing themes? Or does it # provide users with something truly new to choose from? # # (4) Please add the new theme alphabetized by theme name. # # (5) Include a comment with your GitHub userid indicating you # are the contributor of the theme (see the existing themes). # # (6) You can use either 3-digit hex, 6-digit hex, or named colors. # # (7) The existing test cases will automatically test that your # colors are valid hex, or valid named colors. # See https://developer.mozilla.org/en-US/docs/Web/CSS/color_value # for list of named colors. colorMapping = { # Contributor: cicirello (part of initial theme set) "dark" : { "bg" : "#090c10", "border" : "#0d419d", "icons" : "#79c0ff", "text" : "#c9d1d9", "title" : "#f0f6fc" }, # Contributor: cicirello (part of initial theme set) "dark-dimmed" : { "bg" : "#1e2228", "border" : "#1b4b91", "icons" : "#6cb6ff", "text" : "#adbac7", "title" : "#cdd9e5" }, # Contributor: cicirello (part of initial theme set) "light" : { "bg" : "#f6f8fa", "border" : "#c8e1ff", "icons" : "#0366d6", "text" : "#24292e", "title" : "#24292e" } }
class Node: def __init__(self, element, parent, left_child, right_child): self.element = element self.parent = parent self.left_child = left_child self.right_child = right_child def getElement(self): return self.element def getParent(self): return self.parent def getLeftChild(self): return self.left_child def getRightChild(self): return self.right_child def setElement(self, element): self.element = element def setParent(self, parent): self.parent = parent def setLeftChild(self, node): self.left_child = node def setRightChild(self, node): self.right_child = node def getSibling(self): parent = self.getParent() if parent.getLeftChild() == self: return parent.getRightChild() else: return parent.getLeftChild() def hasLeftChild(self): return self.getLeftChild() != None def hasRightChild(self): return self.getRightChild() != None def hasParent(self): return self.getParent() != None def isLeftChild(self): if self.hasParent() == False: return False else: parent = self.getParent() return parent.getLeftChild() == self def isRightChild(self): if self.hasParent() == False: return False else: parent = self.getParent() return parent.getRightChild() == self def isInternal(self): return self.hasLeftChild() or self.hasRightChild() def isExternal(self): return not self.isInternal() def hasElement(self): return self.getElement() != None """ def hasNonExternalNodeChild(self): if self.isExternal() == True: return False else: left_child_is_not_external = self.getLeftChild().isExternal() == False right_child_is_not_external = self.getRightChild().isExternal() == False return left_child_is_not_external or right_child_is_not_external """ # show string corresponding to entry def toString(self): if self.hasElement() == False: returnNone else: return self.getElement().toString() # show only key corresponding to entry def toKeyString(self): if self.hasElement() == False: return None else: return self.getElement().toKeyString()
# These default settings initally apply to all installations of the config_app. # # This file _is_ and should remain under version control. # DEBUG = False SQLALCHEMY_ECHO = False SECRET_KEY = b'default_SECRET_KEY' # # IMPORTANT: Do _not_ edit this file. # Instead, over-ride with settings in the instance/config.py file. #
class Solution: def getHint(self, secret: str, guess: str) -> str: index = 0 secret = list(secret) guess = list(guess) A = 0 while index < len(secret): # count A if secret[index] == guess[index]: secret = secret[:index] + secret[index + 1:] guess = guess[:index] + guess[index + 1:] A += 1 else: index += 1 # count B B = 0 di = collections.defaultdict(int) for s in secret: di[s] += 1 for g in guess: if di[g] > 0: di[g] -= 1 B += 1 return '{}A{}B'.format(A, B)
#Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros com valores inteiros. Seu programa tem que analisar todos os valores e dizer qual deles é o maior. def maior(*num): maximo=max(num) print(f'dos numeros {num}',end=' ') print(f'foram informados {len(num)}') print(f"O maior número é {maximo}") maior(1,6,8,9,5,4,2) maior(6,5,3,7) maior(0) maior(4,2,1)
COLOMBIA_PLACES_FILTERS = [ # Colombia {'country': 'CO', 'location': 'Bogota'}, {'country': 'CO', 'location': 'Medellin'}, # TODO: solve issue, meetup is not returning results for cali even though it actually exist a django group {'country': 'CO', 'location': 'Cali'}, {'country': 'CO', 'location': 'Barranquilla'}, {'country': 'CO', 'location': 'Santa marta'}, {'country': 'CO', 'location': 'Pasto'}, ] LATAM_PLACES_FILTERS = [ # Argentina {'country': 'AR', 'location': 'Buenos Aires'}, {'country': 'AR', 'location': 'Cordoba'}, # TODO: solve issue, when this filter is enabled, US groups are being returned. Only AR groups should ve returned #{'country': 'AR', 'location': 'La Plata'}, # Bolivia {'country': 'BO', 'location': 'Santa Cruz de la Sierra'}, {'country': 'BO', 'location': 'El Alto'}, {'country': 'BO', 'location': 'La Paz'}, {'country': 'BO', 'location': 'Cochabamba'}, # # Brazil {'country': 'BR', 'location': 'sao paulo'}, {'country': 'BR', 'location': 'brasilia'}, # Chile {'country': 'CL', 'location': 'Santiago'}, # # # # Costa Rica # TODO: solve issue, when this filter is enabled, US groups are being returned. Only AR groups should ve returned # {'country': 'CR', 'location': 'San Jose'}, # # # # Cuba # TODO: solve issue, when this filter is enabled, US groups are being returned. Only AR groups should ve returned # {'country': 'CU', 'location': 'Habana'}, # Ecuador {'country': 'EC', 'location': 'quito'}, # Guatemala {'country': 'GT', 'location': 'Guatemala'}, # Honduras {'country': 'HN', 'location': 'Tegucigalpa'}, # Mexico {'country': 'MX', 'location': 'ciudad de mexico'}, {'country': 'MX', 'location': 'Ecatepec'}, {'country': 'MX', 'location': 'Guadalajara'}, {'country': 'MX', 'location': 'Puebla'}, {'country': 'MX', 'location': 'Monterrey'}, # Paraguay {'country': 'PY', 'location': 'asuncion'}, # Peru {'country': 'PE', 'location': 'Lima'}, # Uruguay {'country': 'UY', 'location': 'Montevideo'}, # El Salvador {'country': 'SV', 'location': 'San Salvador'}, ] # add colombia filters to latam filters LATAM_PLACES_FILTERS.extend(COLOMBIA_PLACES_FILTERS) # Keyword filers that contain the criteria a group would be considered in the statistics KEYWORD_FILTERS = [ # general keywords "Django", "Python", "PyData", "PyLadies", "Py", # special group names "Grupy-SP", ] LOCATION_CODES = { "CO": "Colombia", "LATAM": "LATAM" }
# -*- coding: utf-8 -*- n = int(input()) t = [] for _ in range(n): t.append(int(input())) for i in range(n): if i > 0 and i < n - 1: print(sum(t[i - 1:i + 2])) elif i == 0: print(sum(t[:2])) else: print(sum(t[i - 1:]))
N = int(input()) lst = [list(map(int,input().split())) for i in range(N)] for i in range(N-2): for j in range(i+1,N-1): for k in range(j+1,N): x0,y0 = lst[i] x1,y1 = lst[j] x2,y2 = lst[k] x0 -= x2 x1 -= x2 y0 -= y2 y1 -= y2 if x0*y1==x1*y0: print("Yes") exit() print("No")
class ConsoleLine: body = None current_character = None type = None
class KeyExReturn: def __init__(self): self._status_code = None self._msg = None def __call__(self): return self._msg, self._status_code def status_code(self): return self._status_code def message(self): return self._msg class OK(KeyExReturn): def __init__(self, data): super().__init__() self._status_code = 200 self._msg = data class Success(KeyExReturn): def __init__(self, data): super().__init__() self._status_code = 201 self._msg = data class NonUniqueKey(KeyExReturn): def __init__(self, dev_id): super().__init__() self._status_code = 400 self._msg = "Device ID {} already exists; and could not be added.".format(dev_id) class Forbidden(KeyExReturn): def __init__(self): super().__init__() self._status_code = 403 self._msg = "Server is inactive and not accepting new registration requests." class MissingJSON(KeyExReturn): def __init__(self, data): super().__init__() self._status_code = 400 self._msg = "Missing or invalid values in JSON data received:\n{}".format(data) class BadJSON(KeyExReturn): def __init__(self, data): super().__init__() self._status_code = 400 self._msg = "Malformed JSON data received:\n{}".format(data) class DatabaseError(KeyExReturn): def __init__(self, data): super().__init__() self._status_code = 500 self._msg = "A database error occurred - {}".format(data) class DatabaseConnectionError(KeyExReturn): def __init__(self): super().__init__() self._status_code = 500 self._msg = "An internal database error has occurred..." class SignatureVerificationError(KeyExReturn): def __init__(self): super().__init__() self._status_code = 400 self._msg = "The signature did not verify" class CSRVerificationError(KeyExReturn): def __init__(self): super().__init__() self._status_code = 400 self._msg = "The CSR data did not verify" class IDNotFound(KeyExReturn): def __init__(self): super().__init__() self._status_code = 404 self._msg = "The specified device identity was not found"
# Radix sort in Python def counting_sort(array, place): size = len(array) output = [0] * size count = [0] * 10 for i in range(0, size): index = array[i] // place count[index % 10] += 1 for i in range(1, 10): count[i] += count[i - 1] i = size - 1 while i >= 0: index = array[i] // place output[count[index % 10] - 1] = array[i] count[index % 10] -= 1 i -= 1 for i in range(0, size): array[i] = output[i] def radix_sort(array): max_element = max(array) place = 1 while max_element // place > 0: counting_sort(array, place) place *= 10 data = [121, 432, 564, 23, 1, 45, 788] radix_sort(data) print(data)
class Fields: #rearrange the field order at will #if renaming or adding additional fields modifying target.csv is required values = ['Timestamp', 'Transaction Id', 'Payment ID', 'Note', 'Receive/Send Address', 'Debit', 'Credit', 'Network Fee', 'Balance', 'Currency']
fixed_answers = { 'how_to': [ {'values': {'product': 'mister proper'}, 'expected_response': 'Two cups per 5 litres of water should do it!'}, {'values': {'product': 'Braun'}, 'expected_response': 'First of all, plug the trimmer to the electric current. Secondly, turn it on by pressing the upper bottom. You can additionally adjust the velocity.'} ], 'earn_prize': [ {'values': {}, 'expected_response': 'May I suggest using Pantene clarifying shampoo? Check your email for a 20% discount thanks to using Emma.'} ], 'going_to': [ {'values': {'action': 'use Ariel'}, 'expected_response': 'Laundry is the only thing that should be separated by color'}, {'values': {'action': 'use Olay'}, 'expected_response': 'If you go to the app Skin Advisor by Olay you can get insights and track your progress!'}, {'values': {'action': 'brush my teeth'}, 'expected_response': 'Don’t forget to close the water tap while you do it. Start off by brushing your bottom left teeth. I’ll tell you when to switch.'}, {'values': {'action': 'do the dishes'}, 'expected_response': 'Let me tell you a fairytale. Once upon a time there lived a lovely princess with fair skin and blue eyes. She was so fair that she was named Snow White.'}, {'values': {'action': 'change the diapers'}, 'expected_response': 'It’s dad’s turn. You have changed your baby’s diapers 4 times today, this complies with the recommended rates for your baby.'} ] }
TABLES = ["departments", "dept_manager", "dept_emp", "titles", "salaries"] QUERYLIST_CREATE_STRUCTURE = [ "DROP TABLE IF EXISTS dept_emp, dept_manager, titles, salaries, employees, departments;", """CREATE TABLE employees ( emp_no INT NOT NULL, birth_date DATE NOT NULL, first_name VARCHAR(14) NOT NULL, last_name VARCHAR(16) NOT NULL, gender ENUM ('M','F') NOT NULL, hire_date DATE NOT NULL, PRIMARY KEY (emp_no) );""", """CREATE TABLE departments ( dept_no CHAR(4) NOT NULL, dept_name VARCHAR(40) NOT NULL, PRIMARY KEY (dept_no), UNIQUE KEY (dept_name) );""", """CREATE TABLE dept_manager ( emp_no INT NOT NULL, dept_no CHAR(4) NOT NULL, from_date DATE NOT NULL, to_date DATE NOT NULL, FOREIGN KEY (emp_no) REFERENCES employees (emp_no) ON DELETE CASCADE, FOREIGN KEY (dept_no) REFERENCES departments (dept_no) ON DELETE CASCADE, PRIMARY KEY (emp_no,dept_no) );""", """CREATE TABLE dept_emp ( emp_no INT NOT NULL, dept_no CHAR(4) NOT NULL, from_date DATE NOT NULL, to_date DATE NOT NULL, FOREIGN KEY (emp_no) REFERENCES employees (emp_no) ON DELETE CASCADE, FOREIGN KEY (dept_no) REFERENCES departments (dept_no) ON DELETE CASCADE, PRIMARY KEY (emp_no,dept_no) );""", """CREATE TABLE titles ( emp_no INT NOT NULL, title VARCHAR(50) NOT NULL, from_date DATE NOT NULL, to_date DATE, FOREIGN KEY (emp_no) REFERENCES employees (emp_no) ON DELETE CASCADE, PRIMARY KEY (emp_no,title, from_date) );""", """CREATE TABLE salaries ( emp_no INT NOT NULL, salary INT NOT NULL, from_date DATE NOT NULL, to_date DATE NOT NULL, FOREIGN KEY (emp_no) REFERENCES employees (emp_no) ON DELETE CASCADE, PRIMARY KEY (emp_no, from_date) );""" ] QUERY_DROP_STRUCTURE = "DROP TABLE IF EXISTS dept_emp, dept_manager, titles, salaries, departments;" QUERYLIST_CREATE_DUMMY_STRUCTURE = [ "CREATE TABLE dummy_departments SELECT * FROM departments;", "CREATE TABLE dummy_dept_manager SELECT * FROM dept_manager;", "CREATE TABLE dummy_dept_emp SELECT * FROM dept_emp;", "CREATE TABLE dummy_titles SELECT * FROM titles;", "CREATE TABLE dummy_salaries SELECT * FROM salaries;" ] QUERY_SELECT_SIMPLE = """SELECT * FROM `employees` JOIN `titles` ON `titles`.`emp_no` = `employees`.`emp_no` WHERE `gender`='F' AND `title`='Engineer'; """ QUERY_SELECT_SORT = "SELECT * FROM employees ORDER BY `last_name`;" QUERY_SELECT_JOIN = """SELECT `first_name`, `last_name`, `title` FROM `employees` JOIN `titles` ON `employees`.`emp_no` = `titles`.`emp_no` WHERE `from_date` < '2000-01-01' AND `to_date` > '2000-01-01'; """ QUERY_SELECT_GROUP = """SELECT `departments`.`dept_name`, COUNT(1) FROM `dept_emp` JOIN `departments` ON `departments`.`dept_no` = `dept_emp`.`dept_no` GROUP BY `departments`.`dept_no`; """ QUERY_SELECT_AGGREGATE = """SELECT `employees`.`first_name`, `employees`.`last_name`, SUM(`salaries`.`salary`) AS SumSalary, AVG(`salaries`.`salary`) AS AvgSalary, MAX(`salaries`.`salary`) AS MaxSalary, MIN(`salaries`.`salary`) AS MinSalary FROM `salaries` JOIN `employees` ON `employees`.`emp_no` = `salaries`.`emp_no` GROUP BY `employees`.`emp_no` ORDER BY `AvgSalary` DESC; """ QUERY_DIS_FULL_GROUP_BY = "SET SESSION sql_mode = TRIM(BOTH ',' FROM REPLACE(@@SESSION.sql_mode, 'ONLY_FULL_GROUP_BY', ''));" QUERY_CHANGE_ENGINE_MYISAM = "SET default_storage_engine='MyISAM';" QUERY_CHANGE_ENGINE_INNODB = "SET default_storage_engine='InnoDB';" QUERY_MULTIPLY_EMPLOYEES = "INSERT INTO `employees` SELECT * FROM `employees`;" def query_select_string(args): return f"""SELECT `first_name`, `last_name` FROM `employees` WHERE `first_name` LIKE '{args[0]}%' AND `last_name` LIKE '{args[1]}%'; """ def make_query_on_dummy(query: str): for table in TABLES: query = query.replace(table, f"dummy_{table}") return query
lista_numeros = [1, 4, 7, 9] numero_usuario = 10 while numero_usuario < 0 and numero_usuario > 9: numero_usuario = int(input('Ingresa tu numero del 0-9')) if numero_usuario in lista_numeros: print('El numero está dentro de la lista') else: print('El numero no está dentro de la lista')
""" Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid. For example, There is one obstacle in the middle of a 3x3 grid as illustrated below. [ [0,0,0], [0,1,0], [0,0,0] ] The total number of unique paths is 2. Note: m and n will be at most 100. """ class Solution: # @param obstacleGrid, a list of lists of integers # @return an integer def uniquePathsWithObstacles(self, obstacleGrid): n = len(obstacleGrid) m = len(obstacleGrid[0]) t = [[-1 for i in range(m)] for j in range(n)] return self.unique_paths(obstacleGrid, m - 1, n - 1, t) def unique_paths(self, grid, x, y, t): if x == 0 and y == 0: t[y][x] = 1 if grid[y][x] == 0 else 0 return t[y][x] elif grid[y][x] == 1: t[y][x] = 0 return t[y][x] elif t[y][x] != -1: return t[y][x] elif x > 0 and y == 0: t[y][x] = self.unique_paths(grid, x - 1, y, t) return t[y][x] elif y > 0 and x == 0: t[y][x] = self.unique_paths(grid, x, y - 1, t) return t[y][x] else: a = self.unique_paths(grid, x - 1, y, t) b = self.unique_paths(grid, x, y - 1, t) t[y][x] = a + b return t[y][x]
''' URL: https://leetcode.com/problems/basic-calculator/ Time complexity: O(n) Space complexity: O(n) ''' class Solution: def _get_next_num(self, i, s): curr_num = "" while i < len(s) and s[i].isdigit(): curr_num += s[i] i += 1 return i-1, int(curr_num) def calculate(self, s): """ :type s: str :rtype: int """ stack = [(0, 1)] prev_char = None i = 0 while i < len(s): char = s[i] if char == ' ': i += 1 continue if char.isdigit(): i, num = self._get_next_num(i, s) if prev_char == '-': stack[-1] = (stack[-1][0]-num, stack[-1][1]) else: stack[-1] = (stack[-1][0]+num, stack[-1][1]) elif char == ')': val, sign = stack.pop() if len(stack) > 0: stack[-1] = (stack[-1][0] + val * sign, stack[-1][1]) else: return val * sign elif char == '(': if prev_char == '-': sign = -1 else: sign = 1 stack.append((0, sign)) prev_char = char i += 1 if len(stack) > 0: return (stack[-1][0] * stack[-1][1]) return -1
FILENAME = "input.txt" class Expression: def __init__(self, expression_str: str): expression_list = expression_str.split() if len(expression_list) == 1: self.parse_expression(None, None, expression_list[0]) elif len(expression_list) == 2: self.parse_expression(None, *expression_list) else: self.parse_expression(*expression_list) def parse_expression( self, left_literal: str | None, operator: str | None, right_literal: str ): try: self._left_literal = int(left_literal) except: self._left_literal = left_literal try: self._right_literal = int(right_literal) except: self._right_literal = right_literal self._operator = operator def eval(self, table) -> int: if self._left_literal is not None: if isinstance(self._left_literal, int): left = self._left_literal else: left = table.get_value(self._left_literal) if isinstance(self._right_literal, int): right = self._right_literal else: right = table.get_value(self._right_literal) if self._operator == "AND": return left & right elif self._operator == "OR": return left | right elif self._operator == "NOT": return 2**16 - right - 1 elif self._operator == "LSHIFT": return left << right elif self._operator == "RSHIFT": return left >> right elif self._operator is None: return right else: raise ValueError(f"Unknown operator: {self._operator}") class Table: def __init__(self): self._variable_dict = dict() def process_expression(self, variable: str, expression: Expression): self._variable_dict[variable] = expression def get_value(self, variable: str) -> int: result = self._variable_dict[variable].eval(self) self._variable_dict[variable] = Expression(str(result)) return result def get_input() -> Table: table = Table() with open(FILENAME) as file: for line in file.readlines(): lhs, rhs = line.strip().split(" -> ") table.process_expression(rhs, Expression(lhs)) return table def part_1(): table = get_input() WIRE_VAR = "a" result = table.get_value(WIRE_VAR) print(f"Signal {result} is ultimately provided to wire {WIRE_VAR}") def part_2(): table1 = get_input() table2 = get_input() WIRE_VAR = "a" a_signal = table1.get_value(WIRE_VAR) table2.process_expression("b", Expression(str(a_signal))) result = table2.get_value(WIRE_VAR) print(f"Signal {result} is ultimately provided to wire {WIRE_VAR}") if __name__ == "__main__": # part_1() # part_2() pass
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/workspace/src/ros_control/controller_manager_msgs/msg/ControllerState.msg;/workspace/src/ros_control/controller_manager_msgs/msg/ControllerStatistics.msg;/workspace/src/ros_control/controller_manager_msgs/msg/ControllersStatistics.msg;/workspace/src/ros_control/controller_manager_msgs/msg/HardwareInterfaceResources.msg" services_str = "/workspace/src/ros_control/controller_manager_msgs/srv/ListControllerTypes.srv;/workspace/src/ros_control/controller_manager_msgs/srv/ListControllers.srv;/workspace/src/ros_control/controller_manager_msgs/srv/LoadController.srv;/workspace/src/ros_control/controller_manager_msgs/srv/ReloadControllerLibraries.srv;/workspace/src/ros_control/controller_manager_msgs/srv/SwitchController.srv;/workspace/src/ros_control/controller_manager_msgs/srv/UnloadController.srv" pkg_name = "controller_manager_msgs" dependencies_str = "std_msgs" langs = "gencpp;geneus;genlisp;gennodejs;genpy" dep_include_paths_str = "controller_manager_msgs;/workspace/src/ros_control/controller_manager_msgs/msg;std_msgs;/opt/ros/melodic/share/std_msgs/cmake/../msg" PYTHON_EXECUTABLE = "/usr/bin/python2" package_has_static_sources = 'TRUE' == 'TRUE' genmsg_check_deps_script = "/opt/ros/melodic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
a=[] while True: b=input("Enter Number(Break Using String):") if b.isalpha(): break else: a.append(int(b)) continue c=a[0] for x in a: if c>x: c=x else: continue d=0 if c in a: d=a.index(c) print ("Index:",d) print ("Number:",c)
''' PROBLEM: Length of Last Word Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string. If the last word does not exist, return 0. Note: A word is defined as a maximal substring consisting of non-space characters only. Example: Input: "Hello World" Output: 5 Problem link : https://leetcode.com/problems/length-of-last-word/ ''' ''' APPROACH - We can convert string into list of words and can calculate length using reverse indexing ''' class Solution: def lengthOfLastWord(self, s: str) -> int: a = s.split() if (len(a)>=1): return len(a[-1]) else: return 0