content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
command = input() numbers = [int(n) for n in input().split()] command_numbers = [] def add_command_numbers(num): if (num % 2 == 0 and command == "Even") or (num % 2 != 0 and command == "Odd"): command_numbers.append(num) for n in numbers: add_command_numbers(n) print(sum(command_numbers)*len(numbers))
command = input() numbers = [int(n) for n in input().split()] command_numbers = [] def add_command_numbers(num): if num % 2 == 0 and command == 'Even' or (num % 2 != 0 and command == 'Odd'): command_numbers.append(num) for n in numbers: add_command_numbers(n) print(sum(command_numbers) * len(numbers))
class Env(object): user='test' password='test' port=5432 host='localhost' dbname='todo' development=False env = Env()
class Env(object): user = 'test' password = 'test' port = 5432 host = 'localhost' dbname = 'todo' development = False env = env()
day09 = __import__("day-09") process = day09.process_gen rotor = { 0: {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}, 1: {'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N'}, } diff = { 'N': (0, 1), 'E': (1, 0), 'S': (0, -1), 'W': (-1, 0), } def draw(data, panels): direction = 'N' coord = (0, 0) try: inp = [] g = process(data, inp) while True: current_color = panels.get(coord, 0) inp.append(current_color) color = next(g) panels[coord] = color rotate = next(g) direction = rotor[rotate][direction] dd = diff[direction] coord = coord[0] + dd[0], coord[1] + dd[1] except StopIteration: pass return panels def test_case1(): with open('day-11.txt', 'r') as f: text = f.read().strip() data = [int(x) for x in text.split(',')] panels = dict() draw(data, panels) xmin = min(x[0] for x in panels.keys()) xmax = max(x[0] for x in panels.keys()) ymin = min(x[1] for x in panels.keys()) ymax = max(x[1] for x in panels.keys()) w = xmax - xmin h = ymax - ymin for j in range(ymin, ymax): for i in range(xmin, xmax): c = (i, j) color = panels.get(c, 0) print('#' if color == 1 else '.', end='') print() assert len(panels) == 2339 def test_case2(): with open('day-11.txt', 'r') as f: text = f.read().strip() data = [int(x) for x in text.split(',')] panels = dict() panels[(0, 0)] = 1 draw(data, panels) xmin = min(x[0] for x in panels.keys()) - 2 xmax = max(x[0] for x in panels.keys()) + 2 ymin = min(x[1] for x in panels.keys()) - 2 ymax = max(x[1] for x in panels.keys()) + 2 w = xmax - xmin h = ymax - ymin for j in range(ymax, ymin, -1): for i in range(xmin, xmax): c = (i, j) color = panels.get(c, 0) print('#' if color == 1 else '.', end='') print() assert False
day09 = __import__('day-09') process = day09.process_gen rotor = {0: {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}, 1: {'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N'}} diff = {'N': (0, 1), 'E': (1, 0), 'S': (0, -1), 'W': (-1, 0)} def draw(data, panels): direction = 'N' coord = (0, 0) try: inp = [] g = process(data, inp) while True: current_color = panels.get(coord, 0) inp.append(current_color) color = next(g) panels[coord] = color rotate = next(g) direction = rotor[rotate][direction] dd = diff[direction] coord = (coord[0] + dd[0], coord[1] + dd[1]) except StopIteration: pass return panels def test_case1(): with open('day-11.txt', 'r') as f: text = f.read().strip() data = [int(x) for x in text.split(',')] panels = dict() draw(data, panels) xmin = min((x[0] for x in panels.keys())) xmax = max((x[0] for x in panels.keys())) ymin = min((x[1] for x in panels.keys())) ymax = max((x[1] for x in panels.keys())) w = xmax - xmin h = ymax - ymin for j in range(ymin, ymax): for i in range(xmin, xmax): c = (i, j) color = panels.get(c, 0) print('#' if color == 1 else '.', end='') print() assert len(panels) == 2339 def test_case2(): with open('day-11.txt', 'r') as f: text = f.read().strip() data = [int(x) for x in text.split(',')] panels = dict() panels[0, 0] = 1 draw(data, panels) xmin = min((x[0] for x in panels.keys())) - 2 xmax = max((x[0] for x in panels.keys())) + 2 ymin = min((x[1] for x in panels.keys())) - 2 ymax = max((x[1] for x in panels.keys())) + 2 w = xmax - xmin h = ymax - ymin for j in range(ymax, ymin, -1): for i in range(xmin, xmax): c = (i, j) color = panels.get(c, 0) print('#' if color == 1 else '.', end='') print() assert False
class MagicalGirlLevelOneDivTwo: def theMinDistance(self, d, x, y): return min( sorted( (a ** 2 + b ** 2) ** 0.5 for a in xrange(x - d, x + d + 1) for b in xrange(y - d, y + d + 1) ) )
class Magicalgirllevelonedivtwo: def the_min_distance(self, d, x, y): return min(sorted(((a ** 2 + b ** 2) ** 0.5 for a in xrange(x - d, x + d + 1) for b in xrange(y - d, y + d + 1))))
test = 1 while True: n = int(input()) if n == 0: break participantes = [int(x) for x in input().split()] vencedor = [participantes[x] for x in range(n) if participantes[x] == (x + 1)] print(f'Teste {test}') test += 1 print(vencedor[0]) print()
test = 1 while True: n = int(input()) if n == 0: break participantes = [int(x) for x in input().split()] vencedor = [participantes[x] for x in range(n) if participantes[x] == x + 1] print(f'Teste {test}') test += 1 print(vencedor[0]) print()
# Check if there are two adjacent digits that are the same def adjacent_in_list(li=()): for c in range(0, len(li)-1): if li[c] == li[c+1]: return True return False # Check if the list doesn't get smaller as the index increases def list_gets_bigger(li=()): for c in range(0, len(li)-1): if li[c] > li[c+1]: return False else: return True def password_criteria(n, mini, maxi): n_list = [] n = str(n) for c in range(0, len(n)): n_list += [int(n[c])] if int(n) > maxi or int(n) < mini: # Check if the number is in the range return False elif not adjacent_in_list(n_list): return False elif list_gets_bigger(n_list): return True passwords = [] for c0 in range(146810, 612564): if password_criteria(c0, 146810, 612564): passwords += [c0] print(len(passwords), passwords)
def adjacent_in_list(li=()): for c in range(0, len(li) - 1): if li[c] == li[c + 1]: return True return False def list_gets_bigger(li=()): for c in range(0, len(li) - 1): if li[c] > li[c + 1]: return False else: return True def password_criteria(n, mini, maxi): n_list = [] n = str(n) for c in range(0, len(n)): n_list += [int(n[c])] if int(n) > maxi or int(n) < mini: return False elif not adjacent_in_list(n_list): return False elif list_gets_bigger(n_list): return True passwords = [] for c0 in range(146810, 612564): if password_criteria(c0, 146810, 612564): passwords += [c0] print(len(passwords), passwords)
FARMINGPRACTICES_TYPE_URI = "https://w3id.org/okn/o/sdm#FarmingPractices" FARMINGPRACTICES_TYPE_NAME = "FarmingPractices" POINTBASEDGRID_TYPE_URI = "https://w3id.org/okn/o/sdm#PointBasedGrid" POINTBASEDGRID_TYPE_NAME = "PointBasedGrid" SUBSIDY_TYPE_URI = "https://w3id.org/okn/o/sdm#Subsidy" SUBSIDY_TYPE_NAME = "Subsidy" GRID_TYPE_URI = "https://w3id.org/okn/o/sdm#Grid" GRID_TYPE_NAME = "Grid" TIMEINTERVAL_TYPE_URI = "https://w3id.org/okn/o/sdm#TimeInterval" TIMEINTERVAL_TYPE_NAME = "TimeInterval" EMPIRICALMODEL_TYPE_URI = "https://w3id.org/okn/o/sdm#EmpiricalModel" EMPIRICALMODEL_TYPE_NAME = "EmpiricalModel" GEOSHAPE_TYPE_URI = "https://w3id.org/okn/o/sdm#GeoShape" GEOSHAPE_TYPE_NAME = "GeoShape" MODEL_TYPE_URI = "https://w3id.org/okn/o/sdm#Model" MODEL_TYPE_NAME = "Model" REGION_TYPE_URI = "https://w3id.org/okn/o/sdm#Region" REGION_TYPE_NAME = "Region" GEOCOORDINATES_TYPE_URI = "https://w3id.org/okn/o/sdm#GeoCoordinates" GEOCOORDINATES_TYPE_NAME = "GeoCoordinates" SPATIALLYDISTRIBUTEDGRID_TYPE_URI = "https://w3id.org/okn/o/sdm#SpatiallyDistributedGrid" SPATIALLYDISTRIBUTEDGRID_TYPE_NAME = "SpatiallyDistributedGrid" EMULATOR_TYPE_URI = "https://w3id.org/okn/o/sdm#Emulator" EMULATOR_TYPE_NAME = "Emulator" MODELCONFIGURATION_TYPE_URI = "https://w3id.org/okn/o/sdm#ModelConfiguration" MODELCONFIGURATION_TYPE_NAME = "ModelConfiguration" THEORYGUIDEDMODEL_TYPE_URI = "https://w3id.org/okn/o/sdm#Theory-GuidedModel" THEORYGUIDEDMODEL_TYPE_NAME = "Theory-GuidedModel" NUMERICALINDEX_TYPE_URI = "https://w3id.org/okn/o/sdm#NumericalIndex" NUMERICALINDEX_TYPE_NAME = "NumericalIndex" PROCESS_TYPE_URI = "https://w3id.org/okn/o/sdm#Process" PROCESS_TYPE_NAME = "Process" HYBRIDMODEL_TYPE_URI = "https://w3id.org/okn/o/sdm#HybridModel" HYBRIDMODEL_TYPE_NAME = "HybridModel" MODELCONFIGURATIONSETUP_TYPE_URI = "https://w3id.org/okn/o/sdm#ModelConfigurationSetup" MODELCONFIGURATIONSETUP_TYPE_NAME = "ModelConfigurationSetup" CAUSALDIAGRAM_TYPE_URI = "https://w3id.org/okn/o/sdm#CausalDiagram" CAUSALDIAGRAM_TYPE_NAME = "CausalDiagram" SPATIALRESOLUTION_TYPE_URI = "https://w3id.org/okn/o/sdm#SpatialResolution" SPATIALRESOLUTION_TYPE_NAME = "SpatialResolution" EQUATION_TYPE_URI = "https://w3id.org/okn/o/sdm#Equation" EQUATION_TYPE_NAME = "Equation" INTERVENTION_TYPE_URI = "https://w3id.org/okn/o/sdm#Intervention" INTERVENTION_TYPE_NAME = "Intervention" SAMPLEEXECUTION_TYPE_URI = "https://w3id.org/okn/o/sd#SampleExecution" SAMPLEEXECUTION_TYPE_NAME = "SampleExecution" VISUALIZATION_TYPE_URI = "https://w3id.org/okn/o/sd#Visualization" VISUALIZATION_TYPE_NAME = "Visualization" IMAGE_TYPE_URI = "https://w3id.org/okn/o/sd#Image" IMAGE_TYPE_NAME = "Image" SOURCECODE_TYPE_URI = "https://w3id.org/okn/o/sd#SourceCode" SOURCECODE_TYPE_NAME = "SourceCode" ORGANIZATION_TYPE_URI = "https://w3id.org/okn/o/sd#Organization" ORGANIZATION_TYPE_NAME = "Organization" DATASETSPECIFICATION_TYPE_URI = "https://w3id.org/okn/o/sd#DatasetSpecification" DATASETSPECIFICATION_TYPE_NAME = "DatasetSpecification" UNIT_TYPE_URI = "https://w3id.org/okn/o/sd#Unit" UNIT_TYPE_NAME = "Unit" CONFIGURATIONSETUP_TYPE_URI = "https://w3id.org/okn/o/sd#ConfigurationSetup" CONFIGURATIONSETUP_TYPE_NAME = "ConfigurationSetup" ICASAVARIABLE_TYPE_URI = "https://w3id.org/okn/o/sd#ICASAVariable" ICASAVARIABLE_TYPE_NAME = "ICASAVariable" SAMPLECOLLECTION_TYPE_URI = "https://w3id.org/okn/o/sd#SampleCollection" SAMPLECOLLECTION_TYPE_NAME = "SampleCollection" STANDARDVARIABLE_TYPE_URI = "https://w3id.org/okn/o/sd#StandardVariable" STANDARDVARIABLE_TYPE_NAME = "StandardVariable" SOFTWAREIMAGE_TYPE_URI = "https://w3id.org/okn/o/sd#SoftwareImage" SOFTWAREIMAGE_TYPE_NAME = "SoftwareImage" SOFTWARE_TYPE_URI = "https://w3id.org/okn/o/sd#Software" SOFTWARE_TYPE_NAME = "Software" VARIABLEPRESENTATION_TYPE_URI = "https://w3id.org/okn/o/sd#VariablePresentation" VARIABLEPRESENTATION_TYPE_NAME = "VariablePresentation" SOFTWARECONFIGURATION_TYPE_URI = "https://w3id.org/okn/o/sd#SoftwareConfiguration" SOFTWARECONFIGURATION_TYPE_NAME = "SoftwareConfiguration" SOFTWAREVERSION_TYPE_URI = "https://w3id.org/okn/o/sd#SoftwareVersion" SOFTWAREVERSION_TYPE_NAME = "SoftwareVersion" FUNDINGINFORMATION_TYPE_URI = "https://w3id.org/okn/o/sd#FundingInformation" FUNDINGINFORMATION_TYPE_NAME = "FundingInformation" SAMPLERESOURCE_TYPE_URI = "https://w3id.org/okn/o/sd#SampleResource" SAMPLERESOURCE_TYPE_NAME = "SampleResource" PARAMETER_TYPE_URI = "https://w3id.org/okn/o/sd#Parameter" PARAMETER_TYPE_NAME = "Parameter" SVOVARIABLE_TYPE_URI = "https://w3id.org/okn/o/sd#SVOVariable" SVOVARIABLE_TYPE_NAME = "SVOVariable" PERSON_TYPE_URI = "https://w3id.org/okn/o/sd#Person" PERSON_TYPE_NAME = "Person" VARIABLE_TYPE_URI = "https://w3id.org/okn/o/sd#Variable" VARIABLE_TYPE_NAME = "Variable"
farmingpractices_type_uri = 'https://w3id.org/okn/o/sdm#FarmingPractices' farmingpractices_type_name = 'FarmingPractices' pointbasedgrid_type_uri = 'https://w3id.org/okn/o/sdm#PointBasedGrid' pointbasedgrid_type_name = 'PointBasedGrid' subsidy_type_uri = 'https://w3id.org/okn/o/sdm#Subsidy' subsidy_type_name = 'Subsidy' grid_type_uri = 'https://w3id.org/okn/o/sdm#Grid' grid_type_name = 'Grid' timeinterval_type_uri = 'https://w3id.org/okn/o/sdm#TimeInterval' timeinterval_type_name = 'TimeInterval' empiricalmodel_type_uri = 'https://w3id.org/okn/o/sdm#EmpiricalModel' empiricalmodel_type_name = 'EmpiricalModel' geoshape_type_uri = 'https://w3id.org/okn/o/sdm#GeoShape' geoshape_type_name = 'GeoShape' model_type_uri = 'https://w3id.org/okn/o/sdm#Model' model_type_name = 'Model' region_type_uri = 'https://w3id.org/okn/o/sdm#Region' region_type_name = 'Region' geocoordinates_type_uri = 'https://w3id.org/okn/o/sdm#GeoCoordinates' geocoordinates_type_name = 'GeoCoordinates' spatiallydistributedgrid_type_uri = 'https://w3id.org/okn/o/sdm#SpatiallyDistributedGrid' spatiallydistributedgrid_type_name = 'SpatiallyDistributedGrid' emulator_type_uri = 'https://w3id.org/okn/o/sdm#Emulator' emulator_type_name = 'Emulator' modelconfiguration_type_uri = 'https://w3id.org/okn/o/sdm#ModelConfiguration' modelconfiguration_type_name = 'ModelConfiguration' theoryguidedmodel_type_uri = 'https://w3id.org/okn/o/sdm#Theory-GuidedModel' theoryguidedmodel_type_name = 'Theory-GuidedModel' numericalindex_type_uri = 'https://w3id.org/okn/o/sdm#NumericalIndex' numericalindex_type_name = 'NumericalIndex' process_type_uri = 'https://w3id.org/okn/o/sdm#Process' process_type_name = 'Process' hybridmodel_type_uri = 'https://w3id.org/okn/o/sdm#HybridModel' hybridmodel_type_name = 'HybridModel' modelconfigurationsetup_type_uri = 'https://w3id.org/okn/o/sdm#ModelConfigurationSetup' modelconfigurationsetup_type_name = 'ModelConfigurationSetup' causaldiagram_type_uri = 'https://w3id.org/okn/o/sdm#CausalDiagram' causaldiagram_type_name = 'CausalDiagram' spatialresolution_type_uri = 'https://w3id.org/okn/o/sdm#SpatialResolution' spatialresolution_type_name = 'SpatialResolution' equation_type_uri = 'https://w3id.org/okn/o/sdm#Equation' equation_type_name = 'Equation' intervention_type_uri = 'https://w3id.org/okn/o/sdm#Intervention' intervention_type_name = 'Intervention' sampleexecution_type_uri = 'https://w3id.org/okn/o/sd#SampleExecution' sampleexecution_type_name = 'SampleExecution' visualization_type_uri = 'https://w3id.org/okn/o/sd#Visualization' visualization_type_name = 'Visualization' image_type_uri = 'https://w3id.org/okn/o/sd#Image' image_type_name = 'Image' sourcecode_type_uri = 'https://w3id.org/okn/o/sd#SourceCode' sourcecode_type_name = 'SourceCode' organization_type_uri = 'https://w3id.org/okn/o/sd#Organization' organization_type_name = 'Organization' datasetspecification_type_uri = 'https://w3id.org/okn/o/sd#DatasetSpecification' datasetspecification_type_name = 'DatasetSpecification' unit_type_uri = 'https://w3id.org/okn/o/sd#Unit' unit_type_name = 'Unit' configurationsetup_type_uri = 'https://w3id.org/okn/o/sd#ConfigurationSetup' configurationsetup_type_name = 'ConfigurationSetup' icasavariable_type_uri = 'https://w3id.org/okn/o/sd#ICASAVariable' icasavariable_type_name = 'ICASAVariable' samplecollection_type_uri = 'https://w3id.org/okn/o/sd#SampleCollection' samplecollection_type_name = 'SampleCollection' standardvariable_type_uri = 'https://w3id.org/okn/o/sd#StandardVariable' standardvariable_type_name = 'StandardVariable' softwareimage_type_uri = 'https://w3id.org/okn/o/sd#SoftwareImage' softwareimage_type_name = 'SoftwareImage' software_type_uri = 'https://w3id.org/okn/o/sd#Software' software_type_name = 'Software' variablepresentation_type_uri = 'https://w3id.org/okn/o/sd#VariablePresentation' variablepresentation_type_name = 'VariablePresentation' softwareconfiguration_type_uri = 'https://w3id.org/okn/o/sd#SoftwareConfiguration' softwareconfiguration_type_name = 'SoftwareConfiguration' softwareversion_type_uri = 'https://w3id.org/okn/o/sd#SoftwareVersion' softwareversion_type_name = 'SoftwareVersion' fundinginformation_type_uri = 'https://w3id.org/okn/o/sd#FundingInformation' fundinginformation_type_name = 'FundingInformation' sampleresource_type_uri = 'https://w3id.org/okn/o/sd#SampleResource' sampleresource_type_name = 'SampleResource' parameter_type_uri = 'https://w3id.org/okn/o/sd#Parameter' parameter_type_name = 'Parameter' svovariable_type_uri = 'https://w3id.org/okn/o/sd#SVOVariable' svovariable_type_name = 'SVOVariable' person_type_uri = 'https://w3id.org/okn/o/sd#Person' person_type_name = 'Person' variable_type_uri = 'https://w3id.org/okn/o/sd#Variable' variable_type_name = 'Variable'
# # @lc app=leetcode id=49 lang=python3 # # [49] Group Anagrams # # https://leetcode.com/problems/group-anagrams/description/ # # algorithms # Medium (60.66%) # Likes: 7901 # Dislikes: 277 # Total Accepted: 1.2M # Total Submissions: 1.9M # Testcase Example: '["eat","tea","tan","ate","nat","bat"]' # # Given an array of strings strs, group the anagrams together. You can return # the answer in any order. # # An Anagram is a word or phrase formed by rearranging the letters of a # different word or phrase, typically using all the original letters exactly # once. # # # Example 1: # Input: strs = ["eat","tea","tan","ate","nat","bat"] # Output: [["bat"],["nat","tan"],["ate","eat","tea"]] # Example 2: # Input: strs = [""] # Output: [[""]] # Example 3: # Input: strs = ["a"] # Output: [["a"]] # # # Constraints: # # # 1 <= strs.length <= 10^4 # 0 <= strs[i].length <= 100 # strs[i] consists of lowercase English letters. # # # # @lc code=start class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: d = {} for str in strs: str_sort = ''.join(sorted(str)) if str_sort in d: d[str_sort].append(str) else: d[str_sort] = [str] return list(d.values()) # @lc code=end
class Solution: def group_anagrams(self, strs: List[str]) -> List[List[str]]: d = {} for str in strs: str_sort = ''.join(sorted(str)) if str_sort in d: d[str_sort].append(str) else: d[str_sort] = [str] return list(d.values())
# Copyright (c) 2019 Pavel Vavruska # 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. class Config: def __init__( self, fov, is_perspective_correction_on, is_metric_on, pixel_size, dynamic_lighting, texture_filtering ): self.__fov = fov self.__is_perspective_correction_on = is_perspective_correction_on self.__is_metric_on = is_metric_on self.__pixel_size = pixel_size self.__dynamic_lighting = dynamic_lighting self.__texture_filtering = texture_filtering @property def fov(self): return self.__fov @property def is_perspective_correction_on(self): return self.__is_perspective_correction_on @property def is_metric_on(self): return self.__is_metric_on @property def pixel_size(self): return self.__pixel_size @property def dynamic_lighting(self): return self.__dynamic_lighting @property def texture_filtering(self): return self.__texture_filtering def set_fov(self, fov): self.__fov = fov def toggle_perspective_correction_on(self): self.__is_perspective_correction_on = not self.is_perspective_correction_on def toggle_metric_on(self): self.__is_metric_on = not self.__is_metric_on def set_pixel_size(self, pixel_size): self.__pixel_size = pixel_size def increase_pixel_size(self): if self.pixel_size < 10: self.__pixel_size = self.pixel_size + 1 def decrease_pixel_size(self): if self.pixel_size > 1: self.__pixel_size = self.pixel_size - 1 def toggle_dynamic_lighting(self): self.__dynamic_lighting = not self.__dynamic_lighting def toggle_texture_filtering(self): self.__texture_filtering = not self.__texture_filtering
class Config: def __init__(self, fov, is_perspective_correction_on, is_metric_on, pixel_size, dynamic_lighting, texture_filtering): self.__fov = fov self.__is_perspective_correction_on = is_perspective_correction_on self.__is_metric_on = is_metric_on self.__pixel_size = pixel_size self.__dynamic_lighting = dynamic_lighting self.__texture_filtering = texture_filtering @property def fov(self): return self.__fov @property def is_perspective_correction_on(self): return self.__is_perspective_correction_on @property def is_metric_on(self): return self.__is_metric_on @property def pixel_size(self): return self.__pixel_size @property def dynamic_lighting(self): return self.__dynamic_lighting @property def texture_filtering(self): return self.__texture_filtering def set_fov(self, fov): self.__fov = fov def toggle_perspective_correction_on(self): self.__is_perspective_correction_on = not self.is_perspective_correction_on def toggle_metric_on(self): self.__is_metric_on = not self.__is_metric_on def set_pixel_size(self, pixel_size): self.__pixel_size = pixel_size def increase_pixel_size(self): if self.pixel_size < 10: self.__pixel_size = self.pixel_size + 1 def decrease_pixel_size(self): if self.pixel_size > 1: self.__pixel_size = self.pixel_size - 1 def toggle_dynamic_lighting(self): self.__dynamic_lighting = not self.__dynamic_lighting def toggle_texture_filtering(self): self.__texture_filtering = not self.__texture_filtering
def dijkstra(graph): start = "A" times = {a: float("inf") for a in graph.keys()} times[start] = 0 a = list(times) while a: node_selected = min(a, key=lambda k: times[k]) print("node selected", node_selected) a.remove(node_selected) for node, t in graph[node_selected].items(): if times[node_selected] + t < times[node]: times[node] = times[node_selected] + t print(times) graph = { "A": {"B": 4, "D": 3}, "B": {"C": 1}, "C": {}, "D": {"B": 1, "C": 3} } dijkstra(graph)
def dijkstra(graph): start = 'A' times = {a: float('inf') for a in graph.keys()} times[start] = 0 a = list(times) while a: node_selected = min(a, key=lambda k: times[k]) print('node selected', node_selected) a.remove(node_selected) for (node, t) in graph[node_selected].items(): if times[node_selected] + t < times[node]: times[node] = times[node_selected] + t print(times) graph = {'A': {'B': 4, 'D': 3}, 'B': {'C': 1}, 'C': {}, 'D': {'B': 1, 'C': 3}} dijkstra(graph)
globalVar = 0 dataset = 'berlin' max_len = 1024 nb_features = 36 nb_attention_param = 256 attention_init_value = 1.0 / 256 nb_hidden_units = 512 # number of hidden layer units dropout_rate = 0.5 nb_lstm_cells = 128 nb_classes = 7 frame_size = 0.025 # 25 msec segments step = 0.01 # 10 msec time step
global_var = 0 dataset = 'berlin' max_len = 1024 nb_features = 36 nb_attention_param = 256 attention_init_value = 1.0 / 256 nb_hidden_units = 512 dropout_rate = 0.5 nb_lstm_cells = 128 nb_classes = 7 frame_size = 0.025 step = 0.01
# Problem: https://docs.google.com/document/d/1D-3t64PnsEpcF6kKz5ZaquoMMB-r5UyYGyZzM4hjyi0/edit?usp=sharing def create_dict(): ''' Create a dictionary including the roles and their damages. ''' n = int(input('Enter the number of your party members: ')) party = {} # initialize a dictionary named party for _ in range(n): # prompt the user for the role and its damage inputs = input('Enter the role and its nominal damage (separated by a space): ').split() role = inputs[0] damage = float(inputs[1]) party[damage] = role return party def main(): ''' define main function. ''' party = create_dict() # determine the dictionary named party sorted_damage = sorted(party) # sorted the roles' damage print() # for readability # determine and display the role who attacks from front damage_front = party[sorted_damage[-1]] print('The role who attacks from front:', damage_front) # determine and display the role who attacks from one side damage_side = party[sorted_damage[-3]] print('The role who attacks from one side:', damage_side) # determine and display the role who attacks from other side damage_other_side = party[sorted_damage[-4]] print('The role who attacks from other side:', damage_other_side) # determine and display the role who attacks from back damage_back = party[sorted_damage[-2]] print('The role who attacks from back:', damage_back) # determine and display the total damaged total_damaged = sorted_damage[-1]/2 + sum(sorted_damage[-4:-2]) + sorted_damage[-2]*2 print('The total damage dealt to the cyclops by the party:', total_damaged) # call main funciton main()
def create_dict(): """ Create a dictionary including the roles and their damages. """ n = int(input('Enter the number of your party members: ')) party = {} for _ in range(n): inputs = input('Enter the role and its nominal damage (separated by a space): ').split() role = inputs[0] damage = float(inputs[1]) party[damage] = role return party def main(): """ define main function. """ party = create_dict() sorted_damage = sorted(party) print() damage_front = party[sorted_damage[-1]] print('The role who attacks from front:', damage_front) damage_side = party[sorted_damage[-3]] print('The role who attacks from one side:', damage_side) damage_other_side = party[sorted_damage[-4]] print('The role who attacks from other side:', damage_other_side) damage_back = party[sorted_damage[-2]] print('The role who attacks from back:', damage_back) total_damaged = sorted_damage[-1] / 2 + sum(sorted_damage[-4:-2]) + sorted_damage[-2] * 2 print('The total damage dealt to the cyclops by the party:', total_damaged) main()
class Solution: def kthGrammar(self, n: int, k: int) -> int: if n == 1: return 0 noOfBits = (2 ** (n-1) ) / 2 if k <= noOfBits: return self.kthGrammar(n-1, k) else: return int (not self.kthGrammar(n-1, k - noOfBits))
class Solution: def kth_grammar(self, n: int, k: int) -> int: if n == 1: return 0 no_of_bits = 2 ** (n - 1) / 2 if k <= noOfBits: return self.kthGrammar(n - 1, k) else: return int(not self.kthGrammar(n - 1, k - noOfBits))
# Testing def print_hi(name): print(f'Hi, {name}') # Spewcialized max function # arr = [2, 5, 6, 1, 7, 4] def my_bad_max(a_list): temp_max = 0 counter = 0 for index, num in enumerate(a_list): for other_num in a_list[0:index]: counter = counter + 1 value = num - other_num if value > temp_max: temp_max = value print(f'I\'ve itrerated {counter} times...') return temp_max def my_good_max(a_list): temp_max = 0 temp_max_value = 0 counter = 0 for value in reversed(a_list): counter = counter + 1 if value > temp_max_value: temp_max_value = value if temp_max_value - value > temp_max: temp_max = temp_max_value - value print(f'I\'ve itrerated {counter} times...') return temp_max if __name__ == '__main__': arr = [2, 5, 6, 1, 7, 4] print(my_good_max(arr))
def print_hi(name): print(f'Hi, {name}') def my_bad_max(a_list): temp_max = 0 counter = 0 for (index, num) in enumerate(a_list): for other_num in a_list[0:index]: counter = counter + 1 value = num - other_num if value > temp_max: temp_max = value print(f"I've itrerated {counter} times...") return temp_max def my_good_max(a_list): temp_max = 0 temp_max_value = 0 counter = 0 for value in reversed(a_list): counter = counter + 1 if value > temp_max_value: temp_max_value = value if temp_max_value - value > temp_max: temp_max = temp_max_value - value print(f"I've itrerated {counter} times...") return temp_max if __name__ == '__main__': arr = [2, 5, 6, 1, 7, 4] print(my_good_max(arr))
class ForthException(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg class CompileException(ForthException): pass
class Forthexception(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg class Compileexception(ForthException): pass
detik_input = int(input()) jam = detik_input // 3600 detik_input -= jam * 3600 menit = detik_input // 60 detik_input -= menit * 60 detik = detik_input print(jam) print(menit) print(detik)
detik_input = int(input()) jam = detik_input // 3600 detik_input -= jam * 3600 menit = detik_input // 60 detik_input -= menit * 60 detik = detik_input print(jam) print(menit) print(detik)
word1 = input() word2 = input() # How many letters does the longest word contain? len_word1 = len(word1) len_word2 = len(word2) max_len = 0 if len_word1 >= len_word2: max_len = len_word1 else: max_len = len_word2 print(max_len)
word1 = input() word2 = input() len_word1 = len(word1) len_word2 = len(word2) max_len = 0 if len_word1 >= len_word2: max_len = len_word1 else: max_len = len_word2 print(max_len)
def _(line): new_indent = 0 for section in line: if (section != ''): break new_indent = new_indent + 1 return new_indent
def _(line): new_indent = 0 for section in line: if section != '': break new_indent = new_indent + 1 return new_indent
class Something: def __eq__(self, other: object) -> bool: pass class Reference: pass __book_url__ = "dummy" __book_version__ = "dummy" associate_ref_with(Reference)
class Something: def __eq__(self, other: object) -> bool: pass class Reference: pass __book_url__ = 'dummy' __book_version__ = 'dummy' associate_ref_with(Reference)
class RSI(object): def __init__(self, OHLC, period): self.OHLC = OHLC self.period = period self.gain_loss = self.gain_loss_calc() def gain_loss_calc(self): data = self.OHLC["close"] gain_loss = [] for i in range(1, len(data)): change = float(data[i]) - float(data[i-1]) if change >= 0: gain_loss.append({"gain": change, "loss": 0}) else: gain_loss.append({"gain": 0, "loss": abs(change)}) return gain_loss def first_avg_calc(self): gain_loss = self.gain_loss gain = 0 loss = 0 for i in range(0, self.period): gain += gain_loss[i]["gain"] loss += gain_loss[i]["loss"] gain = gain / self.period loss = loss / self.period return {"gain": gain, "loss": loss} def rsi_calc(self): gain_loss = self.gain_loss prev_avg_gain_loss = self.first_avg_calc() avg_gain = 0 avg_loss = 0 for i in range(self.period, len(gain_loss)): avg_gain = ((prev_avg_gain_loss["gain"] * (self.period - 1)) + gain_loss[i]["gain"]) / self.period prev_avg_gain_loss["gain"] = avg_gain avg_loss = ((prev_avg_gain_loss["loss"] * (self.period - 1)) + gain_loss[i]["loss"]) / self.period prev_avg_gain_loss["loss"] = avg_loss rs = avg_gain / avg_loss rsi = 100 - (100 / (1 + rs)) return rsi
class Rsi(object): def __init__(self, OHLC, period): self.OHLC = OHLC self.period = period self.gain_loss = self.gain_loss_calc() def gain_loss_calc(self): data = self.OHLC['close'] gain_loss = [] for i in range(1, len(data)): change = float(data[i]) - float(data[i - 1]) if change >= 0: gain_loss.append({'gain': change, 'loss': 0}) else: gain_loss.append({'gain': 0, 'loss': abs(change)}) return gain_loss def first_avg_calc(self): gain_loss = self.gain_loss gain = 0 loss = 0 for i in range(0, self.period): gain += gain_loss[i]['gain'] loss += gain_loss[i]['loss'] gain = gain / self.period loss = loss / self.period return {'gain': gain, 'loss': loss} def rsi_calc(self): gain_loss = self.gain_loss prev_avg_gain_loss = self.first_avg_calc() avg_gain = 0 avg_loss = 0 for i in range(self.period, len(gain_loss)): avg_gain = (prev_avg_gain_loss['gain'] * (self.period - 1) + gain_loss[i]['gain']) / self.period prev_avg_gain_loss['gain'] = avg_gain avg_loss = (prev_avg_gain_loss['loss'] * (self.period - 1) + gain_loss[i]['loss']) / self.period prev_avg_gain_loss['loss'] = avg_loss rs = avg_gain / avg_loss rsi = 100 - 100 / (1 + rs) return rsi
# -*- coding: utf8 -*- __author__ = 'D. Belavin' class NodeTree: __slots__ = ['key', 'payload', 'parent', 'left', 'right', 'height'] def __init__(self, key, payload, parent=None, left=None, right=None): self.key = key self.payload = payload self.parent = parent self.left = left self.right = right self.height = 1 def has_left_child(self): return self.left def has_right_child(self): return self.right def is_left_knot(self): return self.parent and self.parent.left == self def is_right_knot(self): return self.parent and self.parent.right == self def is_root(self): return not self.parent def has_leaf(self): return not(self.left or self.right) def has_any_children(self): return self.left or self.right def has_both_children(self): return self.left and self.right def replace_node_date(self, key, payload, left, right): # swap root and his child (left or right) self.key = key self.payload = payload self.left = left self.right = right if self.has_left_child(): self.left.parent = self if self.has_right_child(): self.right.parent = self def find_min(self): curr = self while curr.has_left_child(): curr = curr.left return curr def find_successor(self): succ = None # has right child if self.has_right_child(): succ = self.right.find_min() else: if self.parent: # self.parent.left == self if self.is_left_knot(): succ = self.parent else: self.parent.right = None # say that there is no right child succ = self.parent.find_successor() # from the left of the parent self.parent.right = self # return the right child to the place return succ def splice_out(self): # cut off node if self.has_leaf(): # self.parent.left == self if self.is_left_knot(): self.parent.left = None # self.parent.right == self else: self.parent.right = None # self has left or right child elif self.has_any_children(): # has left child if self.has_left_child(): # self.parent.left == self if self.is_left_knot(): self.parent.left = self.left # self.parent.right == self else: self.parent.right = self.left # give away parent self.left.parent = self.parent # has right child else: # self.parent.left == self if self.is_left_knot(): self.parent.left = self.right # self.parent.right == self else: self.parent.right = self.right # give away parent self.right.parent = self.parent def __iter__(self): if self: if self.has_left_child(): for element in self.left: yield element yield self.key if self.has_right_child(): for element in self.right: yield element class AVLTree: def __init__(self): self.root = None self.size = 0 def _height(self, node): if node: return node.height return 0 def _get_balance(self, node): if node: return self._height(node.left) - self._height(node.right) return 0 def _height_up(self, node): # exhibit the height return 1 + max(self._height(node.left), self._height(node.right)) def _left_rotate(self, rot_node): # rot_node.right = rot_node.right.left new_node = rot_node.right rot_node.right = new_node.left # give away left child if new_node.has_left_child(): new_node.left.parent = rot_node # give away parent new_node.parent = rot_node.parent # rot_node == self.root if rot_node.is_root(): self.root = new_node new_node.parent = None else: # rot_node.parent.left == rot_node if rot_node.is_left_knot(): rot_node.parent.left = new_node # rot_node.parent.right == rot_node else: rot_node.parent.right = new_node # rot_node is left child new_node new_node.left = rot_node rot_node.parent = new_node # exhibit the height rot_node.height = self._height_up(rot_node) new_node.height = self._height_up(new_node) def _right_rotate(self, rot_node): # rot_node.left = rot_node.left.right new_node = rot_node.left rot_node.left = new_node.right # give away right child if new_node.has_right_child(): new_node.right.parent = rot_node # give away parent new_node.parent = rot_node.parent # rot_node == self.root if rot_node.is_root(): self.root = new_node new_node.parent = None else: # rot_node.parent.left == rot_node if rot_node.is_left_knot(): rot_node.parent.left = new_node # rot_node.parent.right == rot_node else: rot_node.parent.right = new_node # rot_node is right child new_node new_node.right = rot_node rot_node.parent = new_node # exhibit the height rot_node.height = self._height_up(rot_node) new_node.height = self._height_up(new_node) def _fix_balance(self, node): node.height = self._height_up(node) balance = self._get_balance(node) if balance > 1: # big left rotate if self._get_balance(node.left) < 0: self._left_rotate(node.left) self._right_rotate(node) # small right rotate else: self._right_rotate(node) elif balance < -1: # big right rotate if self._get_balance(node.right) > 0: self._right_rotate(node.right) self._left_rotate(node) # small left rotate else: self._left_rotate(node) def _insert(self, key, payload, curr_node): # Important place. Responsible for inserting duplicate keys. # If you remove these conditions, you can set duplicate keys. # If we leave, we get the structure of a dict (map). # If we leave this condition, and remove the payload, # then we get the basis for the "set" structure. if key == curr_node.key: curr_node.payload = payload else: # go to the left if key < curr_node.key: if curr_node.has_left_child(): self._insert(key, payload, curr_node.left) else: # curr_node.left == None curr_node.left = NodeTree(key, payload, parent=curr_node) self.size += 1 # go to the right else: if curr_node.has_right_child(): self._insert(key, payload, curr_node.right) else: # curr_node.right == None curr_node.right = NodeTree(key, payload, parent=curr_node) self.size += 1 self._fix_balance(curr_node) def insert(self, key, payload): if self.root: self._insert(key, payload, self.root) else: self.root = NodeTree(key, payload) self.size += 1 def _get(self, key, curr_node): # find not key, stop recursion if not curr_node: return None # find key, stop recursion elif key == curr_node.key: return curr_node # go to the left elif key < curr_node.key: return self._get(key, curr_node.left) # go to the right else: return self._get(key, curr_node.right) def get(self, key): if self.root: res = self._get(key, self.root) if res: return res.payload else: return None # can be replaced by an "raise KeyError" else: return None # can be replaced by an "raise KeyError" def _delete(self, node): if node.has_leaf(): # node not has children # node.parent.left == node if node.is_left_knot(): node.parent.left = None # node.parent.right == node else: node.parent.right = None self._fix_balance(node.parent) elif node.has_both_children(): # node has two children succ = node.find_successor() succ.splice_out() node.key = succ.key node.payload = succ.payload self._fix_balance(succ.parent) else: # node has any child if node.has_any_children(): # has left child if node.has_left_child(): # node.parent.left == node if node.is_left_knot(): node.parent.left = node.left node.left.parent = node.parent self._fix_balance(node.parent) # node.parent.right == node elif node.is_right_knot(): node.parent.right = node.left node.left.parent = node.parent self._fix_balance(node.parent) else: # node has not parent, means node == self.root # but node has left child node.replace_node_date(node.left.key, node.left.payload, node.left.left, node.left.right) self._fix_balance(node) # has right child else: # node.parent.left == node if node.is_left_knot(): node.parent.left = node.right node.right.parent = node.parent self._fix_balance(node.parent) # node.parent.right == node elif node.is_right_knot(): node.parent.right = node.right node.right.parent = node.parent self._fix_balance(node.parent) else: # node has not parent, means node == self.root # but node has right child node.replace_node_date(node.right.key, node.right.payload, node.right.left, node.right.right) self._fix_balance(node) def delete(self, key): if self.size > 1: remove_node = self._get(key, self.root) if remove_node: self._delete(remove_node) self.size -= 1 else: raise KeyError('key not in tree.') elif self.size == 1 and self.root.key == key: self.root = None self.size -= 1 else: raise KeyError('key not in tree.') def __len__(self): return self.size def __setitem__(self, key, payload): self.insert(key, payload) def __delitem__(self, key): self.delete(key) def __getitem__(self, key): return self.get(key) def __contains__(self, key): if self._get(key, self.root): return True else: return False def __iter__(self): if self.root: return self.root.__iter__() return iter([]) def clear_tree(self): self.root = None self.size = 0
__author__ = 'D. Belavin' class Nodetree: __slots__ = ['key', 'payload', 'parent', 'left', 'right', 'height'] def __init__(self, key, payload, parent=None, left=None, right=None): self.key = key self.payload = payload self.parent = parent self.left = left self.right = right self.height = 1 def has_left_child(self): return self.left def has_right_child(self): return self.right def is_left_knot(self): return self.parent and self.parent.left == self def is_right_knot(self): return self.parent and self.parent.right == self def is_root(self): return not self.parent def has_leaf(self): return not (self.left or self.right) def has_any_children(self): return self.left or self.right def has_both_children(self): return self.left and self.right def replace_node_date(self, key, payload, left, right): self.key = key self.payload = payload self.left = left self.right = right if self.has_left_child(): self.left.parent = self if self.has_right_child(): self.right.parent = self def find_min(self): curr = self while curr.has_left_child(): curr = curr.left return curr def find_successor(self): succ = None if self.has_right_child(): succ = self.right.find_min() elif self.parent: if self.is_left_knot(): succ = self.parent else: self.parent.right = None succ = self.parent.find_successor() self.parent.right = self return succ def splice_out(self): if self.has_leaf(): if self.is_left_knot(): self.parent.left = None else: self.parent.right = None elif self.has_any_children(): if self.has_left_child(): if self.is_left_knot(): self.parent.left = self.left else: self.parent.right = self.left self.left.parent = self.parent else: if self.is_left_knot(): self.parent.left = self.right else: self.parent.right = self.right self.right.parent = self.parent def __iter__(self): if self: if self.has_left_child(): for element in self.left: yield element yield self.key if self.has_right_child(): for element in self.right: yield element class Avltree: def __init__(self): self.root = None self.size = 0 def _height(self, node): if node: return node.height return 0 def _get_balance(self, node): if node: return self._height(node.left) - self._height(node.right) return 0 def _height_up(self, node): return 1 + max(self._height(node.left), self._height(node.right)) def _left_rotate(self, rot_node): new_node = rot_node.right rot_node.right = new_node.left if new_node.has_left_child(): new_node.left.parent = rot_node new_node.parent = rot_node.parent if rot_node.is_root(): self.root = new_node new_node.parent = None elif rot_node.is_left_knot(): rot_node.parent.left = new_node else: rot_node.parent.right = new_node new_node.left = rot_node rot_node.parent = new_node rot_node.height = self._height_up(rot_node) new_node.height = self._height_up(new_node) def _right_rotate(self, rot_node): new_node = rot_node.left rot_node.left = new_node.right if new_node.has_right_child(): new_node.right.parent = rot_node new_node.parent = rot_node.parent if rot_node.is_root(): self.root = new_node new_node.parent = None elif rot_node.is_left_knot(): rot_node.parent.left = new_node else: rot_node.parent.right = new_node new_node.right = rot_node rot_node.parent = new_node rot_node.height = self._height_up(rot_node) new_node.height = self._height_up(new_node) def _fix_balance(self, node): node.height = self._height_up(node) balance = self._get_balance(node) if balance > 1: if self._get_balance(node.left) < 0: self._left_rotate(node.left) self._right_rotate(node) else: self._right_rotate(node) elif balance < -1: if self._get_balance(node.right) > 0: self._right_rotate(node.right) self._left_rotate(node) else: self._left_rotate(node) def _insert(self, key, payload, curr_node): if key == curr_node.key: curr_node.payload = payload else: if key < curr_node.key: if curr_node.has_left_child(): self._insert(key, payload, curr_node.left) else: curr_node.left = node_tree(key, payload, parent=curr_node) self.size += 1 elif curr_node.has_right_child(): self._insert(key, payload, curr_node.right) else: curr_node.right = node_tree(key, payload, parent=curr_node) self.size += 1 self._fix_balance(curr_node) def insert(self, key, payload): if self.root: self._insert(key, payload, self.root) else: self.root = node_tree(key, payload) self.size += 1 def _get(self, key, curr_node): if not curr_node: return None elif key == curr_node.key: return curr_node elif key < curr_node.key: return self._get(key, curr_node.left) else: return self._get(key, curr_node.right) def get(self, key): if self.root: res = self._get(key, self.root) if res: return res.payload else: return None else: return None def _delete(self, node): if node.has_leaf(): if node.is_left_knot(): node.parent.left = None else: node.parent.right = None self._fix_balance(node.parent) elif node.has_both_children(): succ = node.find_successor() succ.splice_out() node.key = succ.key node.payload = succ.payload self._fix_balance(succ.parent) elif node.has_any_children(): if node.has_left_child(): if node.is_left_knot(): node.parent.left = node.left node.left.parent = node.parent self._fix_balance(node.parent) elif node.is_right_knot(): node.parent.right = node.left node.left.parent = node.parent self._fix_balance(node.parent) else: node.replace_node_date(node.left.key, node.left.payload, node.left.left, node.left.right) self._fix_balance(node) elif node.is_left_knot(): node.parent.left = node.right node.right.parent = node.parent self._fix_balance(node.parent) elif node.is_right_knot(): node.parent.right = node.right node.right.parent = node.parent self._fix_balance(node.parent) else: node.replace_node_date(node.right.key, node.right.payload, node.right.left, node.right.right) self._fix_balance(node) def delete(self, key): if self.size > 1: remove_node = self._get(key, self.root) if remove_node: self._delete(remove_node) self.size -= 1 else: raise key_error('key not in tree.') elif self.size == 1 and self.root.key == key: self.root = None self.size -= 1 else: raise key_error('key not in tree.') def __len__(self): return self.size def __setitem__(self, key, payload): self.insert(key, payload) def __delitem__(self, key): self.delete(key) def __getitem__(self, key): return self.get(key) def __contains__(self, key): if self._get(key, self.root): return True else: return False def __iter__(self): if self.root: return self.root.__iter__() return iter([]) def clear_tree(self): self.root = None self.size = 0
class Member(object): def __init__(self, interval, membership): self.interval = interval self.membership = membership def is_max(self): return self.membership == 1.0 def __str__(self): return str(self.membership) + "/" + str(self.interval) def __hash__(self): return self.interval
class Member(object): def __init__(self, interval, membership): self.interval = interval self.membership = membership def is_max(self): return self.membership == 1.0 def __str__(self): return str(self.membership) + '/' + str(self.interval) def __hash__(self): return self.interval
class SparkConstants: SIMPLE_CRED = 'org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider' TEMP_CRED = 'org.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider' CRED_PROVIDER_KEY = 'spark.hadoop.fs.s3a.aws.credentials.provider' CRED_ACCESS_KEY = 'spark.hadoop.fs.s3a.access.key' CRED_SECRET_KEY = 'spark.hadoop.fs.s3a.secret.key' CRED_TOKEN_KEY = 'spark.hadoop.fs.s3a.session.token'
class Sparkconstants: simple_cred = 'org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider' temp_cred = 'org.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider' cred_provider_key = 'spark.hadoop.fs.s3a.aws.credentials.provider' cred_access_key = 'spark.hadoop.fs.s3a.access.key' cred_secret_key = 'spark.hadoop.fs.s3a.secret.key' cred_token_key = 'spark.hadoop.fs.s3a.session.token'
load(":providers.bzl", "PrismaDataModel") def _prisma_datamodel_impl(ctx): return [ PrismaDataModel(datamodels = ctx.files.srcs), DefaultInfo( files = depset(ctx.files.srcs), runfiles = ctx.runfiles(files = ctx.files.srcs), ), ] prisma_datamodel = rule( implementation = _prisma_datamodel_impl, attrs = { "srcs": attr.label_list( allow_files = [".prisma"], allow_empty = False, mandatory = True, ), }, )
load(':providers.bzl', 'PrismaDataModel') def _prisma_datamodel_impl(ctx): return [prisma_data_model(datamodels=ctx.files.srcs), default_info(files=depset(ctx.files.srcs), runfiles=ctx.runfiles(files=ctx.files.srcs))] prisma_datamodel = rule(implementation=_prisma_datamodel_impl, attrs={'srcs': attr.label_list(allow_files=['.prisma'], allow_empty=False, mandatory=True)})
instr = input() deviate = int(input()) for x in instr: if x.isalpha(): uni = ord(x) if x.islower(): x = chr(97 + ((uni + deviate) - 97) % 26) elif x.isupper(): x = chr(65 + ((uni + deviate) - 65) % 26) print(x, end="") print()
instr = input() deviate = int(input()) for x in instr: if x.isalpha(): uni = ord(x) if x.islower(): x = chr(97 + (uni + deviate - 97) % 26) elif x.isupper(): x = chr(65 + (uni + deviate - 65) % 26) print(x, end='') print()
dd, mm, aa = input().split('/') print(f'{dd}-{mm}-{aa}') print(f'{mm}-{dd}-{aa}') print(f'{aa}/{mm}/{dd}')
(dd, mm, aa) = input().split('/') print(f'{dd}-{mm}-{aa}') print(f'{mm}-{dd}-{aa}') print(f'{aa}/{mm}/{dd}')
MODULUS_NUM = 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559787 MODULUS_BITS = 381 LIMB_SIZES = [55, 55, 51, 55, 55, 55, 55] WORD_SIZE = 64 # Check that MODULUS_BITS is correct assert(2**MODULUS_BITS > MODULUS_NUM) assert(2**(MODULUS_BITS - 1) < MODULUS_NUM) # Check that limb sizes are correct tmp = 0 for i in range(0, len(LIMB_SIZES)): assert(LIMB_SIZES[i] < WORD_SIZE) tmp += LIMB_SIZES[i] assert(tmp == MODULUS_BITS) # Compute the value of the modulus in this representation MODULUS = [] tmp = MODULUS_NUM print("MODULUS = [") for i in range(0, len(LIMB_SIZES)): this_modulus_num = tmp & ((2**LIMB_SIZES[i]) - 1) MODULUS.append(this_modulus_num) tmp = tmp >> LIMB_SIZES[i] print("\t", hex(this_modulus_num), ",") print("]") # Each word in our representation has an associated "magnitude" M # in which the word is guaranteed to be less than or equal to (2^LIMB_SIZE - 1)*M # Initialize LARGEST_MAGNITUDE_CARRIES to some high number LARGEST_MAGNITUDE_CARRIES = 2**WORD_SIZE - 1 for i in range(0, len(LIMB_SIZES)): largest_mag = int(2**WORD_SIZE / (2**LIMB_SIZES[i])) assert((((2**LIMB_SIZES[i]) - 1)*largest_mag) < 2**WORD_SIZE) assert((((2**LIMB_SIZES[i]) - 1)*(largest_mag+1)) > 2**WORD_SIZE) if LARGEST_MAGNITUDE_CARRIES > largest_mag: LARGEST_MAGNITUDE_CARRIES = largest_mag print("Largest magnitude allowed for carries:", LARGEST_MAGNITUDE_CARRIES) NEGATION_MULTIPLES_OF_MODULUS = 0 for i in range(0, len(LIMB_SIZES)): tmp = 0 while (tmp * MODULUS[i]) <= ((2**LIMB_SIZES[i]) - 1): tmp = tmp + 1 if NEGATION_MULTIPLES_OF_MODULUS < tmp: NEGATION_MULTIPLES_OF_MODULUS = tmp print("Scale necessary for negations:", NEGATION_MULTIPLES_OF_MODULUS)
modulus_num = 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559787 modulus_bits = 381 limb_sizes = [55, 55, 51, 55, 55, 55, 55] word_size = 64 assert 2 ** MODULUS_BITS > MODULUS_NUM assert 2 ** (MODULUS_BITS - 1) < MODULUS_NUM tmp = 0 for i in range(0, len(LIMB_SIZES)): assert LIMB_SIZES[i] < WORD_SIZE tmp += LIMB_SIZES[i] assert tmp == MODULUS_BITS modulus = [] tmp = MODULUS_NUM print('MODULUS = [') for i in range(0, len(LIMB_SIZES)): this_modulus_num = tmp & 2 ** LIMB_SIZES[i] - 1 MODULUS.append(this_modulus_num) tmp = tmp >> LIMB_SIZES[i] print('\t', hex(this_modulus_num), ',') print(']') largest_magnitude_carries = 2 ** WORD_SIZE - 1 for i in range(0, len(LIMB_SIZES)): largest_mag = int(2 ** WORD_SIZE / 2 ** LIMB_SIZES[i]) assert (2 ** LIMB_SIZES[i] - 1) * largest_mag < 2 ** WORD_SIZE assert (2 ** LIMB_SIZES[i] - 1) * (largest_mag + 1) > 2 ** WORD_SIZE if LARGEST_MAGNITUDE_CARRIES > largest_mag: largest_magnitude_carries = largest_mag print('Largest magnitude allowed for carries:', LARGEST_MAGNITUDE_CARRIES) negation_multiples_of_modulus = 0 for i in range(0, len(LIMB_SIZES)): tmp = 0 while tmp * MODULUS[i] <= 2 ** LIMB_SIZES[i] - 1: tmp = tmp + 1 if NEGATION_MULTIPLES_OF_MODULUS < tmp: negation_multiples_of_modulus = tmp print('Scale necessary for negations:', NEGATION_MULTIPLES_OF_MODULUS)
DICTIONARY = {'A': 'awesome', 'C': 'confident', 'B': 'beautiful', 'E': 'eager', 'D': 'disturbing', 'G': 'gregarious', 'F': 'fantastic', 'I': 'ingestable', 'H': 'hippy', 'K': 'klingon', 'J': 'joke', 'M': 'mustache', 'L': 'literal', 'O': 'oscillating', 'N': 'newtonian', 'Q': 'queen', 'P': 'perfect', 'S': 'stylish', 'R': 'rant', 'U': 'underlying', 'T': 'turn', 'W': 'weird', 'V': 'volcano', 'Y': 'yogic', 'X': 'xylophone', 'Z': 'zero'} def make_backronym(acronym): return ' '.join(DICTIONARY[a] for a in acronym.upper())
dictionary = {'A': 'awesome', 'C': 'confident', 'B': 'beautiful', 'E': 'eager', 'D': 'disturbing', 'G': 'gregarious', 'F': 'fantastic', 'I': 'ingestable', 'H': 'hippy', 'K': 'klingon', 'J': 'joke', 'M': 'mustache', 'L': 'literal', 'O': 'oscillating', 'N': 'newtonian', 'Q': 'queen', 'P': 'perfect', 'S': 'stylish', 'R': 'rant', 'U': 'underlying', 'T': 'turn', 'W': 'weird', 'V': 'volcano', 'Y': 'yogic', 'X': 'xylophone', 'Z': 'zero'} def make_backronym(acronym): return ' '.join((DICTIONARY[a] for a in acronym.upper()))
# find the non-repeating integer in an array # set operations (including 'in' operation) are O(1) on average, and one loop that runs n times makes O(n) def single(array): repeated = set() not_repeated = set() for i in array: if i in repeated: continue elif i in not_repeated: repeated.add(i) not_repeated.remove(i) else: not_repeated.add(i) return not_repeated array1 = [2, 'a', 'l', 3, 'l', 5, 4, 'k', 2, 3, 4, 'a', 6, 'c', 4, 'm', 6, 'm', 'k', 9, 10, 9, 8, 7, 8, 10, 7] print(single(array1)) # {'c', 5}
def single(array): repeated = set() not_repeated = set() for i in array: if i in repeated: continue elif i in not_repeated: repeated.add(i) not_repeated.remove(i) else: not_repeated.add(i) return not_repeated array1 = [2, 'a', 'l', 3, 'l', 5, 4, 'k', 2, 3, 4, 'a', 6, 'c', 4, 'm', 6, 'm', 'k', 9, 10, 9, 8, 7, 8, 10, 7] print(single(array1))
def lstrip0(iterable, obj): i = 0 iterable_list = list(iterable) while i < len(iterable_list): if iterable_list[i] != obj: break i += 1 for k in range(i, len(iterable_list)): yield iterable_list[k] def lstrip(iterable, obj, key_func=None): if not key_func: key_func = lambda x: x == obj i = 0 iterable_list = list(iterable) while i < len(iterable_list): if key_func(iterable_list[i]) is False: break i += 1 for k in range(i, len(iterable_list)): yield iterable_list[k] if __name__ == "__main__": lstrip0([1,1,1], 1) lstrip([1,1,1], 1)
def lstrip0(iterable, obj): i = 0 iterable_list = list(iterable) while i < len(iterable_list): if iterable_list[i] != obj: break i += 1 for k in range(i, len(iterable_list)): yield iterable_list[k] def lstrip(iterable, obj, key_func=None): if not key_func: key_func = lambda x: x == obj i = 0 iterable_list = list(iterable) while i < len(iterable_list): if key_func(iterable_list[i]) is False: break i += 1 for k in range(i, len(iterable_list)): yield iterable_list[k] if __name__ == '__main__': lstrip0([1, 1, 1], 1) lstrip([1, 1, 1], 1)
def extendList(val, lst=[]): lst.append(val) return lst list1 = extendList(10) list2 = extendList(123,[]) list3 = extendList('a') print("list1 = %s" % list1) print("list2 = %s" % list2) print("list3 = %s" % list3)
def extend_list(val, lst=[]): lst.append(val) return lst list1 = extend_list(10) list2 = extend_list(123, []) list3 = extend_list('a') print('list1 = %s' % list1) print('list2 = %s' % list2) print('list3 = %s' % list3)
# Given an array nums of integers, # return how many of them contain an even number of digits. def find_numbers_easy(nums): even_number_count = 0 for num in nums: if len(str(num)) % 2 == 0: even_number_count += 1 return even_number_count def find_numbers_hard(nums): even_number_count = 0 for num in nums: digit_count = 0 while num > 0: digit_count += 1 print(digit_count) num = num // 10 # normal integer division print(num) if digit_count % 2 == 0: even_number_count += 1 return even_number_count nums = [12, 345, 2, 6, 7896] find_numbers_easy(nums) # ? find_numbers_hard(nums) # ?
def find_numbers_easy(nums): even_number_count = 0 for num in nums: if len(str(num)) % 2 == 0: even_number_count += 1 return even_number_count def find_numbers_hard(nums): even_number_count = 0 for num in nums: digit_count = 0 while num > 0: digit_count += 1 print(digit_count) num = num // 10 print(num) if digit_count % 2 == 0: even_number_count += 1 return even_number_count nums = [12, 345, 2, 6, 7896] find_numbers_easy(nums) find_numbers_hard(nums)
# GENERATED VERSION FILE # TIME: Tue Sep 28 14:27:47 2021 __version__ = '1.0rc1+c42460f' short_version = '1.0rc1'
__version__ = '1.0rc1+c42460f' short_version = '1.0rc1'
#!/usr/bin/env python3 bag_of_words = __import__('0-bag_of_words').bag_of_words sentences = ["Holberton school is Awesome!", "Machine learning is awesome", "NLP is the future!", "The children are our future", "Our children's children are our grandchildren", "The cake was not very good", "No one said that the cake was not very good", "Life is beautiful"] E, F = bag_of_words(sentences) print(E) print(F)
bag_of_words = __import__('0-bag_of_words').bag_of_words sentences = ['Holberton school is Awesome!', 'Machine learning is awesome', 'NLP is the future!', 'The children are our future', "Our children's children are our grandchildren", 'The cake was not very good', 'No one said that the cake was not very good', 'Life is beautiful'] (e, f) = bag_of_words(sentences) print(E) print(F)
x=4 itersLeft=x Sum=0 while(itersLeft!=0): Sum=Sum+x itersLeft=itersLeft-1 print(Sum) print(itersLeft) print(str(x)+"**"+" 2 = "+str(Sum))
x = 4 iters_left = x sum = 0 while itersLeft != 0: sum = Sum + x iters_left = itersLeft - 1 print(Sum) print(itersLeft) print(str(x) + '**' + ' 2 = ' + str(Sum))
class BinarySearch: def __init__(self, arr, target): self.arr = arr self.target = target def binary_search(self): lo, hi = 0, len(self.arr) while lo<hi: mid = lo + (hi-lo)//2 # dont use (lo+hi)//2. Integer overflow. # https://en.wikipedia.org/wiki/Binary_search_algorithm#Implementation_issues if self.arr[mid] == self.target: return mid if self.arr[mid] > self.target: hi = mid-1 else: lo = mid+1 return -1 # input in python3 returns a string n = int(input('Enter the size of array')) # example of using map # a = ['1', '2'] conver it into int # a = list(map(int, a)) in python2 this will work a=map(int,a) # in python3 map returns a map object which is a generator where as in py2 map returns a list # n is used so that even if we enter n+1 numbers list will only contain n number arr = list(map(int, input("Enter the number").strip().split()))[:n] target = int(input("Enter the number to be searched")) print(BinarySearch(arr, target).binary_search())
class Binarysearch: def __init__(self, arr, target): self.arr = arr self.target = target def binary_search(self): (lo, hi) = (0, len(self.arr)) while lo < hi: mid = lo + (hi - lo) // 2 if self.arr[mid] == self.target: return mid if self.arr[mid] > self.target: hi = mid - 1 else: lo = mid + 1 return -1 n = int(input('Enter the size of array')) arr = list(map(int, input('Enter the number').strip().split()))[:n] target = int(input('Enter the number to be searched')) print(binary_search(arr, target).binary_search())
class connectionFinder: def __init__(self, length): self.id = [0] * length self.size = [0] * length for i in range(length): self.id[i] = i self.size[i] = i # Id2 will become a root of Id1 : def union(self, id1, id2): rootA = self.find(id1) rootB = self.find(id2) self.id[rootA] = rootB print(self.id) # Optimization to remove skewed tree and construct weighted binary tree: def weightedUnion(self, id1, id2): root1 = self.find(id1) root2 = self.find(id2) size1 = self.size[root1] size2 = self.size[root2] if size1 < size2: # Make small one child self.id[root1] = root2 self.size[root2] += self.size[root1] else: self.id[root2] = root1 self.size[root1] += self.size[root2] def find(self, x): if self.id[x] == x: return x x = self.id[self.id[x]] # To cut the overhead next when we call this find method for the same root self.id[x] = x return self.find(x) def isConnected(self, id1, id2): return self.find(id1) == self.find(id2) uf = connectionFinder(10) uf.union(1, 2) print(" check ", uf.isConnected(1, 2))
class Connectionfinder: def __init__(self, length): self.id = [0] * length self.size = [0] * length for i in range(length): self.id[i] = i self.size[i] = i def union(self, id1, id2): root_a = self.find(id1) root_b = self.find(id2) self.id[rootA] = rootB print(self.id) def weighted_union(self, id1, id2): root1 = self.find(id1) root2 = self.find(id2) size1 = self.size[root1] size2 = self.size[root2] if size1 < size2: self.id[root1] = root2 self.size[root2] += self.size[root1] else: self.id[root2] = root1 self.size[root1] += self.size[root2] def find(self, x): if self.id[x] == x: return x x = self.id[self.id[x]] self.id[x] = x return self.find(x) def is_connected(self, id1, id2): return self.find(id1) == self.find(id2) uf = connection_finder(10) uf.union(1, 2) print(' check ', uf.isConnected(1, 2))
expected_output = { "vrf": { "vrf1": { "lib_entry": { "10.11.0.0/24": { "rev": "7", "remote_binding": { "label": { "imp-null": { "lsr_id": {"10.132.0.1": {"label_space_id": {0: {}}}} } } }, }, "10.12.0.0/24": { "label_binding": {"label": {"17": {}}}, "rev": "8", "remote_binding": { "label": { "imp-null": { "lsr_id": {"10.132.0.1": {"label_space_id": {0: {}}}} } } }, }, "10.0.0.0/24": { "rev": "6", "remote_binding": { "label": { "imp-null": { "lsr_id": {"10.132.0.1": {"label_space_id": {0: {}}}} } } }, }, } }, "default": { "lib_entry": { "10.11.0.0/24": { "label_binding": {"label": {"imp-null": {}}}, "rev": "15", "remote_binding": { "label": { "imp-null": { "lsr_id": {"10.131.0.1": {"label_space_id": {0: {}}}} } } }, }, "10.0.0.0/24": { "label_binding": {"label": {"imp-null": {}}}, "rev": "4", "remote_binding": { "label": { "imp-null": { "lsr_id": {"10.131.0.1": {"label_space_id": {0: {}}}} } } }, }, } }, } }
expected_output = {'vrf': {'vrf1': {'lib_entry': {'10.11.0.0/24': {'rev': '7', 'remote_binding': {'label': {'imp-null': {'lsr_id': {'10.132.0.1': {'label_space_id': {0: {}}}}}}}}, '10.12.0.0/24': {'label_binding': {'label': {'17': {}}}, 'rev': '8', 'remote_binding': {'label': {'imp-null': {'lsr_id': {'10.132.0.1': {'label_space_id': {0: {}}}}}}}}, '10.0.0.0/24': {'rev': '6', 'remote_binding': {'label': {'imp-null': {'lsr_id': {'10.132.0.1': {'label_space_id': {0: {}}}}}}}}}}, 'default': {'lib_entry': {'10.11.0.0/24': {'label_binding': {'label': {'imp-null': {}}}, 'rev': '15', 'remote_binding': {'label': {'imp-null': {'lsr_id': {'10.131.0.1': {'label_space_id': {0: {}}}}}}}}, '10.0.0.0/24': {'label_binding': {'label': {'imp-null': {}}}, 'rev': '4', 'remote_binding': {'label': {'imp-null': {'lsr_id': {'10.131.0.1': {'label_space_id': {0: {}}}}}}}}}}}}
nmr = int(input("Digite um numero: ")) if nmr %2 == 0: print("Numero par") else: print("Numero impar")
nmr = int(input('Digite um numero: ')) if nmr % 2 == 0: print('Numero par') else: print('Numero impar')
class DefaultConfig(object): # Flask Settings # ------------------------------ # There is a whole bunch of more settings available here: # http://flask.pocoo.org/docs/0.11/config/#builtin-configuration-values DEBUG = False TESTING = False
class Defaultconfig(object): debug = False testing = False
n = int(input()) ss = input().split() s = int(ss[0]) a = [] for i in range(n): ss = input().split() a.append((int(ss[0]), int(ss[1]))) a.sort(key=lambda x: x[0] * x[1]) ans = 0 for i in range(n): if (s // (a[i])[1] > ans): ans = s // (a[i])[1] s *= (a[i])[0] print(ans)
n = int(input()) ss = input().split() s = int(ss[0]) a = [] for i in range(n): ss = input().split() a.append((int(ss[0]), int(ss[1]))) a.sort(key=lambda x: x[0] * x[1]) ans = 0 for i in range(n): if s // a[i][1] > ans: ans = s // a[i][1] s *= a[i][0] print(ans)
def city_formatter(city, country): formatted = f"{city.title()}, {country.title()}" return formatted print(city_formatter('hello', 'world'))
def city_formatter(city, country): formatted = f'{city.title()}, {country.title()}' return formatted print(city_formatter('hello', 'world'))
''' Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time. Return that integer. Example: Input: arr = [1,2,2,6,6,6,6,7,10] Output: 6 Constraints: - 1 <= arr.length <= 10^4 - 0 <= arr[i] <= 10^5 ''' #Difficulty: Easy #18 / 18 test cases passed. #Runtime: 120 ms #Memory Usage: 15.9 MB #Runtime: 120 ms, faster than 14.93% of Python3 online submissions for Element Appearing More Than 25% In Sorted Array. #Memory Usage: 15.9 MB, less than 12.26% of Python3 online submissions for Element Appearing More Than 25% In Sorted Array. class Solution: def findSpecialInteger(self, arr: List[int]) -> int: length = len(arr) nums = set(arr) if length == 1: return arr[0] for num in nums: n = self.binarySearch(arr, num, length) if n: return n def binarySearch(self, arr: int, num: int, length: int) -> int: l = 0 r = length - 1 q = length // 4 while l < r: m = (l+r) // 2 if arr[m] == num and arr[min(length-1, m+q)] == num: return num elif num > arr[m]: l = m + 1 else: r = m - 1
""" Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time. Return that integer. Example: Input: arr = [1,2,2,6,6,6,6,7,10] Output: 6 Constraints: - 1 <= arr.length <= 10^4 - 0 <= arr[i] <= 10^5 """ class Solution: def find_special_integer(self, arr: List[int]) -> int: length = len(arr) nums = set(arr) if length == 1: return arr[0] for num in nums: n = self.binarySearch(arr, num, length) if n: return n def binary_search(self, arr: int, num: int, length: int) -> int: l = 0 r = length - 1 q = length // 4 while l < r: m = (l + r) // 2 if arr[m] == num and arr[min(length - 1, m + q)] == num: return num elif num > arr[m]: l = m + 1 else: r = m - 1
class json_to_csv(): def __init__(self): self.stri='' self.st='' self.a=[] self.b=[] self.p='' def read_js(self,path): self.p=path l=open(path,'r').readlines() for i in l: i=i.replace('\t','') i=i.replace('\n','') self.stri+=i self.st=self.stri def write_cs(self,path=None,head=None): self.st=self.stri self.st=self.st.replace('{','') self.st=self.st.replace('}','') while len(self.st)!=0: try: i=self.st.index(':') k=self.st[:i] k=k.replace(' ','') if k not in self.a: self.a.append(k) self.st=self.st[i+1:] try : i=self.st.index(',') self.b.append(self.st[:i]) self.st=self.st[i+1:] except : self.b.append(self.st[:]) self.st='' except: self.st='' for i in range(len(self.b)): self.b[i]=self.b[i].replace(' ','') if path==None: m=self.p.index('.') self.p=(self.p[:m]+'.csv') f=open(self.p,'w') else : f=open(path,'w') if head==None: for i in self.a: if self.a.index(i)!=len(self.a)-1: f.write(i) f.write(',') else: f.write(i) f.write('\n') for i in range(len(self.b)): if i%len(self.a)!=len(self.a)-1: f.write(self.b[i]) f.write(',') else: f.write(self.b[i]) f.write('\n') else : for i in head: if head.index(i)!=len(head)-1: f.write(i) f.write(',') else: f.write(i) f.write('\n') for i in self.b: if self.b.index(i)%len(self.a)!=len(self.a)-1: f.write(i) f.write(',') else: f.write(i) f.write('\n')
class Json_To_Csv: def __init__(self): self.stri = '' self.st = '' self.a = [] self.b = [] self.p = '' def read_js(self, path): self.p = path l = open(path, 'r').readlines() for i in l: i = i.replace('\t', '') i = i.replace('\n', '') self.stri += i self.st = self.stri def write_cs(self, path=None, head=None): self.st = self.stri self.st = self.st.replace('{', '') self.st = self.st.replace('}', '') while len(self.st) != 0: try: i = self.st.index(':') k = self.st[:i] k = k.replace(' ', '') if k not in self.a: self.a.append(k) self.st = self.st[i + 1:] try: i = self.st.index(',') self.b.append(self.st[:i]) self.st = self.st[i + 1:] except: self.b.append(self.st[:]) self.st = '' except: self.st = '' for i in range(len(self.b)): self.b[i] = self.b[i].replace(' ', '') if path == None: m = self.p.index('.') self.p = self.p[:m] + '.csv' f = open(self.p, 'w') else: f = open(path, 'w') if head == None: for i in self.a: if self.a.index(i) != len(self.a) - 1: f.write(i) f.write(',') else: f.write(i) f.write('\n') for i in range(len(self.b)): if i % len(self.a) != len(self.a) - 1: f.write(self.b[i]) f.write(',') else: f.write(self.b[i]) f.write('\n') else: for i in head: if head.index(i) != len(head) - 1: f.write(i) f.write(',') else: f.write(i) f.write('\n') for i in self.b: if self.b.index(i) % len(self.a) != len(self.a) - 1: f.write(i) f.write(',') else: f.write(i) f.write('\n')
def es5(tree): # inserisci qui il tuo codice d={} for x in tree.f: d1=es5(x) for x in d1: if x in d: d[x]=d[x] | d1[x] else: d[x]=d1[x] y=len(tree.f) if y in d: d[y]=d[y]| {tree.id} else: d[y]= {tree.id} return d
def es5(tree): d = {} for x in tree.f: d1 = es5(x) for x in d1: if x in d: d[x] = d[x] | d1[x] else: d[x] = d1[x] y = len(tree.f) if y in d: d[y] = d[y] | {tree.id} else: d[y] = {tree.id} return d
#!/home/jepoy/anaconda3/bin/python def main(): x = dict(Buffy = 'meow', Zilla = 'grrr', Angel = 'purr') kitten(**x) def kitten(**kwargs): if len(kwargs): for k in kwargs: print('Kitten {} says {}'.format(k, kwargs[k])) else: print('Meow.') if __name__ == '__main__': main()
def main(): x = dict(Buffy='meow', Zilla='grrr', Angel='purr') kitten(**x) def kitten(**kwargs): if len(kwargs): for k in kwargs: print('Kitten {} says {}'.format(k, kwargs[k])) else: print('Meow.') if __name__ == '__main__': main()
def resolve(): ''' code here ''' x, y = [int(item) for item in input().split()] res = 0 if x < 0 and abs(y) - abs(x) >= 0: res += 1 elif x > 0 and abs(y) - abs(x) <= 0: res += 1 res += abs(abs(x) - abs(y)) if y > 0 and abs(y) - abs(x) < 0: res += 1 elif y < 0 and abs(y) - abs(x) > 0: res += 1 print(res) if __name__ == "__main__": resolve()
def resolve(): """ code here """ (x, y) = [int(item) for item in input().split()] res = 0 if x < 0 and abs(y) - abs(x) >= 0: res += 1 elif x > 0 and abs(y) - abs(x) <= 0: res += 1 res += abs(abs(x) - abs(y)) if y > 0 and abs(y) - abs(x) < 0: res += 1 elif y < 0 and abs(y) - abs(x) > 0: res += 1 print(res) if __name__ == '__main__': resolve()
def asm2(param_1, param_2): # push ebp # mov ebp,esp # sub esp,0x10 eax = param_2 # mov eax,DWORD PTR [ebp+0xc] local_1 = eax # mov DWORD PTR [ebp-0x4],eax eax = param_1 # mov eax,DWORD PTR [ebp+0x8] local_2 = eax # mov eax,DWORD PTR [ebp+0x8] while param_1 <= 0x9886:# cmp DWORD PTR [ebp+0x8],0x9886 # jle part_a local_1 += 0x1 # add DWORD PTR [ebp-0x4],0x1 param_1 += 0x41 # add DWORD PTR [ebp+0x8],0x41 eax = local_1 # mov eax,DWORD PTR [ebp-0x4] return eax # mov esp,ebp # pop ebp # ret print(hex(asm2(0xe, 0x21)))
def asm2(param_1, param_2): eax = param_2 local_1 = eax eax = param_1 local_2 = eax while param_1 <= 39046: local_1 += 1 param_1 += 65 eax = local_1 return eax print(hex(asm2(14, 33)))
class _SpeechOperation(): def add_done_callback(callback): pass
class _Speechoperation: def add_done_callback(callback): pass
def main(): a = 1 if True else 2 print(a) if __name__ == '__main__': main()
def main(): a = 1 if True else 2 print(a) if __name__ == '__main__': main()
# Birth should occur before death of an individual def userStory03(listOfPeople): flag = True def changeDateToNum(date): # date format must be like "2018-10-06" if date == "NA": return 0 # 0 will not larger than any date, for later comparison else: tempDate = date.split('-') return int(tempDate[0] + tempDate[1] + tempDate[2]) for people in listOfPeople: if people.Death != "NA": BirthdayNum = changeDateToNum(people.Birthday) DeathNum = changeDateToNum(people.Death) if BirthdayNum > DeathNum: print("ERROR: INDIVIDUAL: US03: Birthday of " + people.ID + " occur after Death") flag = False return flag
def user_story03(listOfPeople): flag = True def change_date_to_num(date): if date == 'NA': return 0 else: temp_date = date.split('-') return int(tempDate[0] + tempDate[1] + tempDate[2]) for people in listOfPeople: if people.Death != 'NA': birthday_num = change_date_to_num(people.Birthday) death_num = change_date_to_num(people.Death) if BirthdayNum > DeathNum: print('ERROR: INDIVIDUAL: US03: Birthday of ' + people.ID + ' occur after Death') flag = False return flag
name = input("Enter your name: ") age = input("Enter your age: ") print("Hello " + name + " ! Your are " + age + " Years old now.") num1 = input("Enter a number: ") num2 = input("Enter another number: ") result = num1 + num2 print(result) # We need int casting number num1 and num2 result = int(num1) + int(num2) print(result) # Adding two Float number num1 = input("Enter a number: ") num2 = input("Enter another number: ") result = float(num1) + float(num2) print(result)
name = input('Enter your name: ') age = input('Enter your age: ') print('Hello ' + name + ' ! Your are ' + age + ' Years old now.') num1 = input('Enter a number: ') num2 = input('Enter another number: ') result = num1 + num2 print(result) result = int(num1) + int(num2) print(result) num1 = input('Enter a number: ') num2 = input('Enter another number: ') result = float(num1) + float(num2) print(result)
# -*- coding: utf-8 -*- def find_message(message: str) -> str: result: str = "" for i in list(message): if i.isupper(): result += i return result # another pattern return ''.join(i for i in message if i.isupper()) if __name__ == '__main__': print("Example:") print(find_message(('How are you? Eh, ok. Low or Lower? ' + 'Ohhh.'))) # These "asserts" are used for self-checking and not for an auto-testing assert find_message(('How are you? Eh, ok. Low or Lower? ' + 'Ohhh.')) == 'HELLO' assert find_message('hello world!') == '' assert find_message('HELLO WORLD!!!') == 'HELLOWORLD' print("Coding complete? Click 'Check' to earn cool rewards!")
def find_message(message: str) -> str: result: str = '' for i in list(message): if i.isupper(): result += i return result return ''.join((i for i in message if i.isupper())) if __name__ == '__main__': print('Example:') print(find_message('How are you? Eh, ok. Low or Lower? ' + 'Ohhh.')) assert find_message('How are you? Eh, ok. Low or Lower? ' + 'Ohhh.') == 'HELLO' assert find_message('hello world!') == '' assert find_message('HELLO WORLD!!!') == 'HELLOWORLD' print("Coding complete? Click 'Check' to earn cool rewards!")
class Vector(object): SHORTHAND = 'V' def __init__(self, **kwargs): super(Vector, self).__init__() self.vector = kwargs def dot(self, other): product = 0 for member, value in self.vector.items(): product += value * other.member(member) return product def apply(self, other): for member, effect in other.vector.items(): value = self.member(member) self.vector[member] = value + effect def member(self, name, default=0): return self.vector.get(name, default) def __str__(self): return '%s(%s)' % (self.SHORTHAND, ','.join(['%s=%.3f' % (key, value) for key, value in self.vector.items()]))
class Vector(object): shorthand = 'V' def __init__(self, **kwargs): super(Vector, self).__init__() self.vector = kwargs def dot(self, other): product = 0 for (member, value) in self.vector.items(): product += value * other.member(member) return product def apply(self, other): for (member, effect) in other.vector.items(): value = self.member(member) self.vector[member] = value + effect def member(self, name, default=0): return self.vector.get(name, default) def __str__(self): return '%s(%s)' % (self.SHORTHAND, ','.join(['%s=%.3f' % (key, value) for (key, value) in self.vector.items()]))
#!/usr/bin/env python3 def first(iterable, default=None, key=None): if key is None: for el in iterable: if el is not None: return el else: for el in iterable: if key(el) is not None: return el return default
def first(iterable, default=None, key=None): if key is None: for el in iterable: if el is not None: return el else: for el in iterable: if key(el) is not None: return el return default
pattern_zero=[0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667] pattern_odd=[0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667] pattern_even=[0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667] averages_even={0.0: [0.0], 0.25: [0.5], 0.916666666667: [0.5], 0.138888888889: [0.8333333333333, 0.1666666666667], 0.583333333333: [0.5], 0.555555555556: [0.3333333333333, 0.6666666666667], 0.222222222222: [0.3333333333333, 0.6666666666667], 0.333333333333: [0.0], 0.805555555556: [0.8333333333333, 0.1666666666667], 0.888888888889: [0.3333333333333, 0.6666666666667], 0.472222222222: [0.8333333333333, 0.1666666666667], 0.666666666667: [0.0]} averages_odd={0.0: [0.0], 0.25: [0.5], 0.916666666667: [0.5], 0.138888888889: [0.8333333333333, 0.1666666666667], 0.583333333333: [0.5], 0.555555555556: [0.3333333333333, 0.6666666666667], 0.222222222222: [0.3333333333333, 0.6666666666667], 0.333333333333: [0.0], 0.805555555556: [0.8333333333333, 0.1666666666667], 0.888888888889: [0.3333333333333, 0.6666666666667], 0.472222222222: [0.8333333333333, 0.1666666666667], 0.666666666667: [0.0]}
pattern_zero = [0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667] pattern_odd = [0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667] pattern_even = [0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667] averages_even = {0.0: [0.0], 0.25: [0.5], 0.916666666667: [0.5], 0.138888888889: [0.8333333333333, 0.1666666666667], 0.583333333333: [0.5], 0.555555555556: [0.3333333333333, 0.6666666666667], 0.222222222222: [0.3333333333333, 0.6666666666667], 0.333333333333: [0.0], 0.805555555556: [0.8333333333333, 0.1666666666667], 0.888888888889: [0.3333333333333, 0.6666666666667], 0.472222222222: [0.8333333333333, 0.1666666666667], 0.666666666667: [0.0]} averages_odd = {0.0: [0.0], 0.25: [0.5], 0.916666666667: [0.5], 0.138888888889: [0.8333333333333, 0.1666666666667], 0.583333333333: [0.5], 0.555555555556: [0.3333333333333, 0.6666666666667], 0.222222222222: [0.3333333333333, 0.6666666666667], 0.333333333333: [0.0], 0.805555555556: [0.8333333333333, 0.1666666666667], 0.888888888889: [0.3333333333333, 0.6666666666667], 0.472222222222: [0.8333333333333, 0.1666666666667], 0.666666666667: [0.0]}
Pathogen = { 'name': 'pathogen', 'fields': [ {'name': 'reported_name'}, {'name': 'drug_resistance'}, {'name': 'authority'}, {'name': 'tax_order'}, {'name': 'class'}, {'name': 'family'}, {'name': 'genus'}, {'name': 'species'}, {'name': 'sub_species'} ] }
pathogen = {'name': 'pathogen', 'fields': [{'name': 'reported_name'}, {'name': 'drug_resistance'}, {'name': 'authority'}, {'name': 'tax_order'}, {'name': 'class'}, {'name': 'family'}, {'name': 'genus'}, {'name': 'species'}, {'name': 'sub_species'}]}
def merge(di1, di2, fu=None): di3 = {} for ke in sorted(di1.keys() | di2.keys()): if ke in di1 and ke in di2: if fu is None: va1 = di1[ke] va2 = di2[ke] if isinstance(va1, dict) and isinstance(va2, dict): di3[ke] = merge(va1, va2) else: di3[ke] = va2 else: di3[ke] = fu(di1[ke], di2[ke]) elif ke in di1: di3[ke] = di1[ke] elif ke in di2: di3[ke] = di2[ke] return di3
def merge(di1, di2, fu=None): di3 = {} for ke in sorted(di1.keys() | di2.keys()): if ke in di1 and ke in di2: if fu is None: va1 = di1[ke] va2 = di2[ke] if isinstance(va1, dict) and isinstance(va2, dict): di3[ke] = merge(va1, va2) else: di3[ke] = va2 else: di3[ke] = fu(di1[ke], di2[ke]) elif ke in di1: di3[ke] = di1[ke] elif ke in di2: di3[ke] = di2[ke] return di3
def read_list(t): return [t(x) for x in input().split()] def read_line(t): return t(input()) def read_lines(t, N): return [t(input()) for _ in range(N)] N, Q = read_list(int) array = read_list(int) C = [[0, 0, 0]] for a in array: c = C[-1][:] c[a % 3] += 1 C.append(c) for _ in range(Q): l, r = read_list(int) c1, c2 = C[l-1], C[r] if c2[0] - c1[0] == 1: print(0) else: print(2 if (c2[2]-c1[2]) % 2 == 1 else 1)
def read_list(t): return [t(x) for x in input().split()] def read_line(t): return t(input()) def read_lines(t, N): return [t(input()) for _ in range(N)] (n, q) = read_list(int) array = read_list(int) c = [[0, 0, 0]] for a in array: c = C[-1][:] c[a % 3] += 1 C.append(c) for _ in range(Q): (l, r) = read_list(int) (c1, c2) = (C[l - 1], C[r]) if c2[0] - c1[0] == 1: print(0) else: print(2 if (c2[2] - c1[2]) % 2 == 1 else 1)
arr=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] n=4#col m=4#row #print matrix in spiral form loop=0 while(loop<n/2): for i in range(loop,n-loop-1): print(arr[loop][i],end=" ") for i in range(loop,m-loop-1): print(arr[i][m-loop-1],end=" ") for i in range(n-1-loop,loop-1+1,-1): print(arr[m-loop-1][i],end=" ") for i in range(m-loop-1,loop,-1): print(arr[i][loop],end=" ") loop+=1
arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] n = 4 m = 4 loop = 0 while loop < n / 2: for i in range(loop, n - loop - 1): print(arr[loop][i], end=' ') for i in range(loop, m - loop - 1): print(arr[i][m - loop - 1], end=' ') for i in range(n - 1 - loop, loop - 1 + 1, -1): print(arr[m - loop - 1][i], end=' ') for i in range(m - loop - 1, loop, -1): print(arr[i][loop], end=' ') loop += 1
class Color: red = None green = None blue = None white = None bit_color = None def __init__(self, red, green, blue, white=0): self.red = red self.green = green self.blue = blue self.white = white def get_rgb(self): return 'rgb(%d,%d,%d)' % (self.red, self.green, self.blue) def get_hex(self): return '#%02x%02x%02x' % (self.red, self.green, self.blue) def get_hsv(self): red = self.red / 255.0 green = self.green / 255.0 blue = self.blue / 255.0 median_max = max(red, green, blue) median_min = min(red, green, blue) difference = median_max - median_min if median_max == median_min: hue = 0 elif median_max == red: hue = (60 * ((green - blue) / difference) + 360) % 360 elif median_max == green: hue = (60 * ((blue - red) / difference) + 120) % 360 elif median_max == blue: hue = (60 * ((red - green) / difference) + 240) % 360 else: hue = 0 if median_max == 0: saturation = 0 else: saturation = difference / median_max value = median_max return 'hsv(%d,%d,%d)' % (hue, saturation, value) def get_bit(self): return (self.white << 24) | (self.red << 16) | (self.green << 8) | self.blue def __str__(self): return '%d,%d,%d' % (self.red, self.green, self.blue)
class Color: red = None green = None blue = None white = None bit_color = None def __init__(self, red, green, blue, white=0): self.red = red self.green = green self.blue = blue self.white = white def get_rgb(self): return 'rgb(%d,%d,%d)' % (self.red, self.green, self.blue) def get_hex(self): return '#%02x%02x%02x' % (self.red, self.green, self.blue) def get_hsv(self): red = self.red / 255.0 green = self.green / 255.0 blue = self.blue / 255.0 median_max = max(red, green, blue) median_min = min(red, green, blue) difference = median_max - median_min if median_max == median_min: hue = 0 elif median_max == red: hue = (60 * ((green - blue) / difference) + 360) % 360 elif median_max == green: hue = (60 * ((blue - red) / difference) + 120) % 360 elif median_max == blue: hue = (60 * ((red - green) / difference) + 240) % 360 else: hue = 0 if median_max == 0: saturation = 0 else: saturation = difference / median_max value = median_max return 'hsv(%d,%d,%d)' % (hue, saturation, value) def get_bit(self): return self.white << 24 | self.red << 16 | self.green << 8 | self.blue def __str__(self): return '%d,%d,%d' % (self.red, self.green, self.blue)
N = int(input()) ano = N // 365 resto = N % 365 mes = resto // 30 dia = resto % 30 print(str(ano) + " ano(s)") print(str(mes) + " mes(es)") print(str(dia) + " dia(s)")
n = int(input()) ano = N // 365 resto = N % 365 mes = resto // 30 dia = resto % 30 print(str(ano) + ' ano(s)') print(str(mes) + ' mes(es)') print(str(dia) + ' dia(s)')
r, c = (map(int, input().split(' '))) for row in range(r): for col in range(c): print(f'{chr(97 + row)}{chr(97 + row + col)}{chr(97 + row)}', end=' ') print()
(r, c) = map(int, input().split(' ')) for row in range(r): for col in range(c): print(f'{chr(97 + row)}{chr(97 + row + col)}{chr(97 + row)}', end=' ') print()
'''Colocando cores no terminal do python''' # \033[0;033;44m codigo para colocar as cores # tipo de texto em cod (estilo do texto) # 0 - sem estilo nenhum # 1 - negrito # 4 - sublinhado # 7 - inverter as confgs # cores em cod (cores do texto) # 30 - branco # 31 - vermelho # 32 - verde # 33 - amarelo # 34 - azul # 35 - lilas # 36 - ciano # 37 - cinza # back em cod (cores de fundo) # 40 - branco # 41 - vermelho # 42 - verde # 43 - amarelo # 44 - azul # 45 - lilas # 46 - ciano # 47 - cinza
"""Colocando cores no terminal do python"""
valid_passport = 0 invalid_passport = 0 def get_key(p_line): keys = [] for i in p_line.split(): keys.append(i.split(':')[0]) return keys def check_validation(keys): for_valid = ' '.join(sorted(['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'])) # CID is optional if 'cid' in keys: keys.remove('cid') keys = ' '.join(sorted(keys)) if for_valid == keys: return True else: return False with open('passport.txt') as file: passport_line = '' current_line = True while current_line: current_line = file.readline() if current_line != '\n': passport_line += ' ' + current_line[:-1] else: passport_line = get_key(passport_line) if check_validation(passport_line): valid_passport += 1 else: invalid_passport += 1 passport_line = '' passport_line = get_key(passport_line) if check_validation(passport_line): valid_passport += 1 else: invalid_passport += 1 passport_line = '' print(f'Valid Passport : {valid_passport}') print(f'Invalid Passport : {invalid_passport}')
valid_passport = 0 invalid_passport = 0 def get_key(p_line): keys = [] for i in p_line.split(): keys.append(i.split(':')[0]) return keys def check_validation(keys): for_valid = ' '.join(sorted(['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'])) if 'cid' in keys: keys.remove('cid') keys = ' '.join(sorted(keys)) if for_valid == keys: return True else: return False with open('passport.txt') as file: passport_line = '' current_line = True while current_line: current_line = file.readline() if current_line != '\n': passport_line += ' ' + current_line[:-1] else: passport_line = get_key(passport_line) if check_validation(passport_line): valid_passport += 1 else: invalid_passport += 1 passport_line = '' passport_line = get_key(passport_line) if check_validation(passport_line): valid_passport += 1 else: invalid_passport += 1 passport_line = '' print(f'Valid Passport : {valid_passport}') print(f'Invalid Passport : {invalid_passport}')
class Security: def __init__(self, name, ticker, country, ir_website, currency): self.name = name.strip() self.ticker = ticker.strip() self.country = country.strip() self.currency = currency.strip() self.ir_website = ir_website.strip() @staticmethod def summary(name, ticker): return f"{name} ({ticker})" @staticmethod def example_input(): return "Air-Products APD.US US http://investors.airproducts.com/upcoming-events USD"
class Security: def __init__(self, name, ticker, country, ir_website, currency): self.name = name.strip() self.ticker = ticker.strip() self.country = country.strip() self.currency = currency.strip() self.ir_website = ir_website.strip() @staticmethod def summary(name, ticker): return f'{name} ({ticker})' @staticmethod def example_input(): return 'Air-Products APD.US US http://investors.airproducts.com/upcoming-events USD'
def plot_frames(motion, ax, times=1, fps=0.01): joints = [j for j in motion.joint_names() if not j.startswith('ignore_')] x, ys = [], [] for t, frame in motion.frames(fps): x.append(t) ys.append(frame.positions) if t > motion.length() * times: break for joint in joints: ax.plot(x, [y[joint] for y in ys], label=joint)
def plot_frames(motion, ax, times=1, fps=0.01): joints = [j for j in motion.joint_names() if not j.startswith('ignore_')] (x, ys) = ([], []) for (t, frame) in motion.frames(fps): x.append(t) ys.append(frame.positions) if t > motion.length() * times: break for joint in joints: ax.plot(x, [y[joint] for y in ys], label=joint)
default_vimrc = "\ set fileencoding=utf-8 fileformat=unix\n\ call plug#begin('~/.vim/plugged')\n\ Plug 'prabirshrestha/async.vim'\n\ Plug 'prabirshrestha/vim-lsp'\n\ Plug 'prabirshrestha/asyncomplete.vim'\n\ Plug 'prabirshrestha/asyncomplete-lsp.vim'\n\ Plug 'mattn/vim-lsp-settings'\n\ Plug 'prabirshrestha/asyncomplete-file.vim'\n\ Plug 'prabirshrestha/asyncomplete-buffer.vim'\n\ Plug 'vim-airline/vim-airline'\n\ Plug 'vim-airline/vim-airline-themes'\n\ Plug 'elzr/vim-json'\n\ Plug 'cohama/lexima.vim'\n\ Plug '{}'\n\ Plug 'cespare/vim-toml'\n\ Plug 'tpope/vim-markdown'\n\ Plug 'kannokanno/previm'\n\ Plug 'tyru/open-browser.vim'\n\ Plug 'ryanoasis/vim-devicons'\n\ Plug 'scrooloose/nerdtree'\n\ Plug 'mattn/emmet-vim'\n\ Plug 'vim/killersheep'\n\ \n\ call plug#end()\n\ \n\ syntax enable\n\ colorscheme {}\n\ set background=dark\n\ \n\ set hlsearch\n\ set cursorline\n\ set cursorcolumn\n\ set number\n\ set foldmethod=marker\n\ set backspace=indent,eol,start\n\ set clipboard^=unnamedplus\n\ set nostartofline\n\ noremap <silent><C-x> :bdelete<CR>\n\ noremap <silent><C-h> :bprevious<CR>\n\ noremap <silent><C-l> :bnext<CR>\n\ set ruler\n\ set noerrorbells\n\ set laststatus={}\n\ set shiftwidth={}\n\ set tabstop={}\n\ set softtabstop={}\n\ set expandtab\n\ set smarttab\n\ set cindent\n\ " indent_setting_base = "\ augroup {}Indent\n\ autocmd!\n\ autocmd FileType {} set tabstop={} softtabstop={} shitwidth={}\n\ augroup END\n\ "
default_vimrc = "set fileencoding=utf-8 fileformat=unix\ncall plug#begin('~/.vim/plugged')\nPlug 'prabirshrestha/async.vim'\nPlug 'prabirshrestha/vim-lsp'\nPlug 'prabirshrestha/asyncomplete.vim'\nPlug 'prabirshrestha/asyncomplete-lsp.vim'\nPlug 'mattn/vim-lsp-settings'\nPlug 'prabirshrestha/asyncomplete-file.vim'\nPlug 'prabirshrestha/asyncomplete-buffer.vim'\nPlug 'vim-airline/vim-airline'\nPlug 'vim-airline/vim-airline-themes'\nPlug 'elzr/vim-json'\nPlug 'cohama/lexima.vim'\nPlug '{}'\nPlug 'cespare/vim-toml'\nPlug 'tpope/vim-markdown'\nPlug 'kannokanno/previm'\nPlug 'tyru/open-browser.vim'\nPlug 'ryanoasis/vim-devicons'\nPlug 'scrooloose/nerdtree'\nPlug 'mattn/emmet-vim'\nPlug 'vim/killersheep'\n\ncall plug#end()\n\nsyntax enable\ncolorscheme {}\nset background=dark\n\nset hlsearch\nset cursorline\nset cursorcolumn\nset number\nset foldmethod=marker\nset backspace=indent,eol,start\nset clipboard^=unnamedplus\nset nostartofline\nnoremap <silent><C-x> :bdelete<CR>\nnoremap <silent><C-h> :bprevious<CR>\nnoremap <silent><C-l> :bnext<CR>\nset ruler\nset noerrorbells\nset laststatus={}\nset shiftwidth={}\nset tabstop={}\nset softtabstop={}\nset expandtab\nset smarttab\nset cindent\n" indent_setting_base = 'augroup {}Indent\n autocmd!\n autocmd FileType {} set tabstop={} softtabstop={} shitwidth={}\naugroup END\n'
extensions = ["myst_parser"] exclude_patterns = ["_build"] copyright = "2020, Executable Book Project" myst_enable_extensions = ["deflist"]
extensions = ['myst_parser'] exclude_patterns = ['_build'] copyright = '2020, Executable Book Project' myst_enable_extensions = ['deflist']
# Given a list and a num. Write a function to return boolean if that element is not in the list. def check_num_in_list(alist, num): for i in alist: if num in alist and num%2 != 0: return True else: return False sample = check_num_in_list([2,7,3,1,6,9], 6) print(sample)
def check_num_in_list(alist, num): for i in alist: if num in alist and num % 2 != 0: return True else: return False sample = check_num_in_list([2, 7, 3, 1, 6, 9], 6) print(sample)
z = 10 y = 0 x = y < z and z > y or y > z and z < y print(x) # X = True
z = 10 y = 0 x = y < z and z > y or (y > z and z < y) print(x)
# Merge Sort: D&C Algo, Breaks data into individual pieces and merges them, uses recursion to operate on datasets. Key is to understand how to merge 2 sorted arrays. items = [6, 20, 8, 9, 19, 56, 23, 87, 41, 49, 53] def mergesort(dataset): if len(dataset) > 1: mid = len(dataset) // 2 leftarr = dataset[:mid] rightarr = dataset[mid:] # TODO: Recursively break down the arrays mergesort(leftarr) mergesort(rightarr) # TODO: Perform merging i = 0 # index into the left array j = 0 # index into the right array k = 0 # index into the merger array while i < len(leftarr) and j < len(rightarr): if(leftarr[i] <= rightarr[j]): dataset[k] = leftarr[i] i += 1 else: dataset[k] = rightarr[j] j += 1 k += 1 while i < len(leftarr): dataset[k] = leftarr[i] i += 1 k += 1 while j < len(rightarr): dataset[k] = rightarr[j] j += 1 k += 1 print(items) mergesort(items) print(items)
items = [6, 20, 8, 9, 19, 56, 23, 87, 41, 49, 53] def mergesort(dataset): if len(dataset) > 1: mid = len(dataset) // 2 leftarr = dataset[:mid] rightarr = dataset[mid:] mergesort(leftarr) mergesort(rightarr) i = 0 j = 0 k = 0 while i < len(leftarr) and j < len(rightarr): if leftarr[i] <= rightarr[j]: dataset[k] = leftarr[i] i += 1 else: dataset[k] = rightarr[j] j += 1 k += 1 while i < len(leftarr): dataset[k] = leftarr[i] i += 1 k += 1 while j < len(rightarr): dataset[k] = rightarr[j] j += 1 k += 1 print(items) mergesort(items) print(items)
def nameCreator(playerName): firstLetter = playerName.split(" ")[1][0] try: lastName = playerName.split(" ")[1][0:5] except: lastNameSize = len(playerName.split(" ")[1]) lastName = playerName.split(" ")[1][len(lastNameSize)] firstName = playerName[0:2] return lastName + firstName + '0', firstLetter
def name_creator(playerName): first_letter = playerName.split(' ')[1][0] try: last_name = playerName.split(' ')[1][0:5] except: last_name_size = len(playerName.split(' ')[1]) last_name = playerName.split(' ')[1][len(lastNameSize)] first_name = playerName[0:2] return (lastName + firstName + '0', firstLetter)
# Author : Aniruddha Krishna Jha # Date : 22/10/2021 '''********************************************************************************** Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0). Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. **********************************************************************************''' class Solution: def maxEqualFreq(self, nums: List[int]) -> int: cnt,freq,maxF,res = collections.defaultdict(int), collections.defaultdict(int),0,0 for i,num in enumerate(nums): cnt[num] += 1 freq[cnt[num]-1] -= 1 freq[cnt[num]] += 1 maxF = max(maxF,cnt[num]) if maxF*freq[maxF] == i or (maxF-1)*(freq[maxF-1]+1) == i or maxF == 1: res = i + 1 return res
"""********************************************************************************** Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0). Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. **********************************************************************************""" class Solution: def max_equal_freq(self, nums: List[int]) -> int: (cnt, freq, max_f, res) = (collections.defaultdict(int), collections.defaultdict(int), 0, 0) for (i, num) in enumerate(nums): cnt[num] += 1 freq[cnt[num] - 1] -= 1 freq[cnt[num]] += 1 max_f = max(maxF, cnt[num]) if maxF * freq[maxF] == i or (maxF - 1) * (freq[maxF - 1] + 1) == i or maxF == 1: res = i + 1 return res
class BTNode: '''Binary Tree Node class - do not modify''' def __init__(self, value, left, right): '''Stores a reference to the value, left child node, and right child node. If no left or right child, attributes should be None.''' self.value = value self.left = left self.right = right class BST: def __init__(self): # reference to root node - do not modify self.root = None def insert(self, value): '''Takes a numeric value as argument. Inserts value into tree, maintaining correct ordering. Returns nothing.''' if self.root is None: self.root = BTNode(value, None, None) return self.insert2(self.root, value) def insert2(self, node, value): if value < node.value: if node.left is None: node.left = BTNode(value, None, None) return self.insert2(node.left, value) elif value > node.value: if node.right is None: node.right = BTNode(value, None, None) return self.insert2(node.right, value) else: return def search(self, value): '''Takes a numeric value as argument. Returns True if its in the tree, false otherwise.''' return self.search2(self.root, value) def search2(self, node, value): if node is None: return False if value == node.value: return True elif value < node.value: return self.search2(node.left, value) else: return self.search2(node.right, value) def height(self): '''Returns the height of the tree. A tree with 0 or 1 nodes has a height of 0.''' return self.height2(self.root) - 1 def height2(self, node): if node is None: return 0 return max(self.height2(node.left), self.height2(node.right)) + 1 def preorder(self): '''Returns a list of the values in the tree, in pre-order order.''' return self.preorder2(self.root, []) def preorder2(self, node, lst): if node is not None: lst.append(node.value) self.preorder2(node.left, lst) self.preorder2(node.right, lst) return lst #bst = BST() #for value in [4, 2, 5, 3, 1, 6, 7]: # bst.insert(value) ## BST now looks like this: ## 4 ## / \ ## 2 5 ## / \ \ ## 1 3 6 ## \ ## 7 #print(bst.search(5)) # True #print(bst.search(8)) # False #print(bst.preorder()) # [4, 2, 1, 3, 5, 6, 7] #print(bst.height()) # 3
class Btnode: """Binary Tree Node class - do not modify""" def __init__(self, value, left, right): """Stores a reference to the value, left child node, and right child node. If no left or right child, attributes should be None.""" self.value = value self.left = left self.right = right class Bst: def __init__(self): self.root = None def insert(self, value): """Takes a numeric value as argument. Inserts value into tree, maintaining correct ordering. Returns nothing.""" if self.root is None: self.root = bt_node(value, None, None) return self.insert2(self.root, value) def insert2(self, node, value): if value < node.value: if node.left is None: node.left = bt_node(value, None, None) return self.insert2(node.left, value) elif value > node.value: if node.right is None: node.right = bt_node(value, None, None) return self.insert2(node.right, value) else: return def search(self, value): """Takes a numeric value as argument. Returns True if its in the tree, false otherwise.""" return self.search2(self.root, value) def search2(self, node, value): if node is None: return False if value == node.value: return True elif value < node.value: return self.search2(node.left, value) else: return self.search2(node.right, value) def height(self): """Returns the height of the tree. A tree with 0 or 1 nodes has a height of 0.""" return self.height2(self.root) - 1 def height2(self, node): if node is None: return 0 return max(self.height2(node.left), self.height2(node.right)) + 1 def preorder(self): """Returns a list of the values in the tree, in pre-order order.""" return self.preorder2(self.root, []) def preorder2(self, node, lst): if node is not None: lst.append(node.value) self.preorder2(node.left, lst) self.preorder2(node.right, lst) return lst
checksum = 0 with open("Day 2 - input", "r") as file: for line in file: row = [int(i) for i in line.split()] result = max(row) - min(row) checksum += result print(f"The checksum is {checksum}")
checksum = 0 with open('Day 2 - input', 'r') as file: for line in file: row = [int(i) for i in line.split()] result = max(row) - min(row) checksum += result print(f'The checksum is {checksum}')
def bytes_to(bytes_value, to_unit, bytes_size=1024): units = {'k': 1, 'm': 2, 'g': 3, 't': 4, 'p': 5, 'e': 6} return round(float(bytes_value) / (bytes_size ** units[to_unit]), 2) def convert_to_human(value): if value < 1024: return str(value) + 'b' if value < 1048576: return str(bytes_to(value, 'k')) + 'k' if value < 1073741824: return str(bytes_to(value, 'm')) + 'm' return str(bytes_to(value, 'g')) + 'g' def convert_to_human_with_limits(value, limit): if value < limit: return convert_to_human(value) return "[bold magenta]" + convert_to_human(value) + "[/]"
def bytes_to(bytes_value, to_unit, bytes_size=1024): units = {'k': 1, 'm': 2, 'g': 3, 't': 4, 'p': 5, 'e': 6} return round(float(bytes_value) / bytes_size ** units[to_unit], 2) def convert_to_human(value): if value < 1024: return str(value) + 'b' if value < 1048576: return str(bytes_to(value, 'k')) + 'k' if value < 1073741824: return str(bytes_to(value, 'm')) + 'm' return str(bytes_to(value, 'g')) + 'g' def convert_to_human_with_limits(value, limit): if value < limit: return convert_to_human(value) return '[bold magenta]' + convert_to_human(value) + '[/]'
TLDS = [ "ABB", "ABBOTT", "ABOGADO", "AC", "ACADEMY", "ACCENTURE", "ACCOUNTANT", "ACCOUNTANTS", "ACTIVE", "ACTOR", "AD", "ADS", "ADULT", "AE", "AEG", "AERO", "AF", "AFL", "AG", "AGENCY", "AI", "AIG", "AIRFORCE", "AL", "ALLFINANZ", "ALSACE", "AM", "AMSTERDAM", "AN", "ANDROID", "AO", "APARTMENTS", "AQ", "AQUARELLE", "AR", "ARCHI", "ARMY", "ARPA", "AS", "ASIA", "ASSOCIATES", "AT", "ATTORNEY", "AU", "AUCTION", "AUDIO", "AUTO", "AUTOS", "AW", "AX", "AXA", "AZ", "AZURE", "BA", "BAND", "BANK", "BAR", "BARCLAYCARD", "BARCLAYS", "BARGAINS", "BAUHAUS", "BAYERN", "BB", "BBC", "BBVA", "BD", "BE", "BEER", "BERLIN", "BEST", "BF", "BG", "BH", "BHARTI", "BI", "BIBLE", "BID", "BIKE", "BING", "BINGO", "BIO", "BIZ", "BJ", "BLACK", "BLACKFRIDAY", "BLOOMBERG", "BLUE", "BM", "BMW", "BN", "BNL", "BNPPARIBAS", "BO", "BOATS", "BOND", "BOO", "BOUTIQUE", "BR", "BRADESCO", "BRIDGESTONE", "BROKER", "BROTHER", "BRUSSELS", "BS", "BT", "BUDAPEST", "BUILD", "BUILDERS", "BUSINESS", "BUZZ", "BV", "BW", "BY", "BZ", "BZH", "CA", "CAB", "CAFE", "CAL", "CAMERA", "CAMP", "CANCERRESEARCH", "CANON", "CAPETOWN", "CAPITAL", "CARAVAN", "CARDS", "CARE", "CAREER", "CAREERS", "CARS", "CARTIER", "CASA", "CASH", "CASINO", "CAT", "CATERING", "CBA", "CBN", "CC", "CD", "CENTER", "CEO", "CERN", "CF", "CFA", "CFD", "CG", "CH", "CHANNEL", "CHAT", "CHEAP", "CHLOE", "CHRISTMAS", "CHROME", "CHURCH", "CI", "CISCO", "CITIC", "CITY", "CK", "CL", "CLAIMS", "CLEANING", "CLICK", "CLINIC", "CLOTHING", "CLOUD", "CLUB", "CM", "CN", "CO", "COACH", "CODES", "COFFEE", "COLLEGE", "COLOGNE", "COM", "COMMBANK", "COMMUNITY", "COMPANY", "COMPUTER", "CONDOS", "CONSTRUCTION", "CONSULTING", "CONTRACTORS", "COOKING", "COOL", "COOP", "CORSICA", "COUNTRY", "COUPONS", "COURSES", "CR", "CREDIT", "CREDITCARD", "CRICKET", "CROWN", "CRS", "CRUISES", "CU", "CUISINELLA", "CV", "CW", "CX", "CY", "CYMRU", "CYOU", "CZ", "DABUR", "DAD", "DANCE", "DATE", "DATING", "DATSUN", "DAY", "DCLK", "DE", "DEALS", "DEGREE", "DELIVERY", "DEMOCRAT", "DENTAL", "DENTIST", "DESI", "DESIGN", "DEV", "DIAMONDS", "DIET", "DIGITAL", "DIRECT", "DIRECTORY", "DISCOUNT", "DJ", "DK", "DM", "DNP", "DO", "DOCS", "DOG", "DOHA", "DOMAINS", "DOOSAN", "DOWNLOAD", "DRIVE", "DURBAN", "DVAG", "DZ", "EARTH", "EAT", "EC", "EDU", "EDUCATION", "EE", "EG", "EMAIL", "EMERCK", "ENERGY", "ENGINEER", "ENGINEERING", "ENTERPRISES", "EPSON", "EQUIPMENT", "ER", "ERNI", "ES", "ESQ", "ESTATE", "ET", "EU", "EUROVISION", "EUS", "EVENTS", "EVERBANK", "EXCHANGE", "EXPERT", "EXPOSED", "EXPRESS", "FAIL", "FAITH", "FAN", "FANS", "FARM", "FASHION", "FEEDBACK", "FI", "FILM", "FINANCE", "FINANCIAL", "FIRMDALE", "FISH", "FISHING", "FIT", "FITNESS", "FJ", "FK", "FLIGHTS", "FLORIST", "FLOWERS", "FLSMIDTH", "FLY", "FM", "FO", "FOO", "FOOTBALL", "FOREX", "FORSALE", "FORUM", "FOUNDATION", "FR", "FRL", "FROGANS", "FUND", "FURNITURE", "FUTBOL", "FYI", "GA", "GAL", "GALLERY", "GARDEN", "GB", "GBIZ", "GD", "GDN", "GE", "GENT", "GENTING", "GF", "GG", "GGEE", "GH", "GI", "GIFT", "GIFTS", "GIVES", "GL", "GLASS", "GLE", "GLOBAL", "GLOBO", "GM", "GMAIL", "GMO", "GMX", "GN", "GOLD", "GOLDPOINT", "GOLF", "GOO", "GOOG", "GOOGLE", "GOP", "GOV", "GP", "GQ", "GR", "GRAPHICS", "GRATIS", "GREEN", "GRIPE", "GS", "GT", "GU", "GUGE", "GUIDE", "GUITARS", "GURU", "GW", "GY", "HAMBURG", "HANGOUT", "HAUS", "HEALTHCARE", "HELP", "HERE", "HERMES", "HIPHOP", "HITACHI", "HIV", "HK", "HM", "HN", "HOCKEY", "HOLDINGS", "HOLIDAY", "HOMEDEPOT", "HOMES", "HONDA", "HORSE", "HOST", "HOSTING", "HOTELES", "HOTMAIL", "HOUSE", "HOW", "HR", "HT", "HU", "IBM", "ICBC", "ICU", "ID", "IE", "IFM", "IL", "IM", "IMMO", "IMMOBILIEN", "IN", "INDUSTRIES", "INFINITI", "INFO", "ING", "INK", "INSTITUTE", "INSURE", "INT", "INTERNATIONAL", "INVESTMENTS", "IO", "IQ", "IR", "IRISH", "IS", "IT", "IWC", "JAVA", "JCB", "JE", "JETZT", "JEWELRY", "JLC", "JLL", "JM", "JO", "JOBS", "JOBURG", "JP", "JUEGOS", "KAUFEN", "KDDI", "KE", "KG", "KH", "KI", "KIM", "KITCHEN", "KIWI", "KM", "KN", "KOELN", "KOMATSU", "KP", "KR", "KRD", "KRED", "KW", "KY", "KYOTO", "KZ", "LA", "LACAIXA", "LAND", "LASALLE", "LAT", "LATROBE", "LAW", "LAWYER", "LB", "LC", "LDS", "LEASE", "LECLERC", "LEGAL", "LGBT", "LI", "LIAISON", "LIDL", "LIFE", "LIGHTING", "LIMITED", "LIMO", "LINK", "LK", "LOAN", "LOANS", "LOL", "LONDON", "LOTTE", "LOTTO", "LOVE", "LR", "LS", "LT", "LTDA", "LU", "LUPIN", "LUXE", "LUXURY", "LV", "LY", "MA", "MADRID", "MAIF", "MAISON", "MANAGEMENT", "MANGO", "MARKET", "MARKETING", "MARKETS", "MARRIOTT", "MBA", "MC", "MD", "ME", "MEDIA", "MEET", "MELBOURNE", "MEME", "MEMORIAL", "MEN", "MENU", "MG", "MH", "MIAMI", "MICROSOFT", "MIL", "MINI", "MK", "ML", "MM", "MMA", "MN", "MO", "MOBI", "MODA", "MOE", "MONASH", "MONEY", "MONTBLANC", "MORMON", "MORTGAGE", "MOSCOW", "MOTORCYCLES", "MOV", "MOVIE", "MOVISTAR", "MP", "MQ", "MR", "MS", "MT", "MTN", "MTPC", "MU", "MUSEUM", "MV", "MW", "MX", "MY", "MZ", "NA", "NADEX", "NAGOYA", "NAME", "NAVY", "NC", "NE", "NEC", "NET", "NETBANK", "NETWORK", "NEUSTAR", "NEW", "NEWS", "NEXUS", "NF", "NG", "NGO", "NHK", "NI", "NICO", "NINJA", "NISSAN", "NL", "NO", "NP", "NR", "NRA", "NRW", "NTT", "NU", "NYC", "NZ", "OFFICE", "OKINAWA", "OM", "OMEGA", "ONE", "ONG", "ONL", "ONLINE", "OOO", "ORACLE", "ORG", "ORGANIC", "OSAKA", "OTSUKA", "OVH", "PA", "PAGE", "PANERAI", "PARIS", "PARTNERS", "PARTS", "PARTY", "PE", "PF", "PG", "PH", "PHARMACY", "PHILIPS", "PHOTO", "PHOTOGRAPHY", "PHOTOS", "PHYSIO", "PIAGET", "PICS", "PICTET", "PICTURES", "PINK", "PIZZA", "PK", "PL", "PLACE", "PLAY", "PLUMBING", "PLUS", "PM", "PN", "POHL", "POKER", "PORN", "POST", "PR", "PRAXI", "PRESS", "PRO", "PROD", "PRODUCTIONS", "PROF", "PROPERTIES", "PROPERTY", "PS", "PT", "PUB", "PW", "PY", "QA", "QPON", "QUEBEC", "RACING", "RE", "REALTOR", "REALTY", "RECIPES", "RED", "REDSTONE", "REHAB", "REISE", "REISEN", "REIT", "REN", "RENT", "RENTALS", "REPAIR", "REPORT", "REPUBLICAN", "REST", "RESTAURANT", "REVIEW", "REVIEWS", "RICH", "RICOH", "RIO", "RIP", "RO", "ROCKS", "RODEO", "RS", "RSVP", "RU", "RUHR", "RUN", "RW", "RYUKYU", "SA", "SAARLAND", "SALE", "SAMSUNG", "SANDVIK", "SANDVIKCOROMANT", "SAP", "SARL", "SAXO", "SB", "SC", "SCA", "SCB", "SCHMIDT", "SCHOLARSHIPS", "SCHOOL", "SCHULE", "SCHWARZ", "SCIENCE", "SCOR", "SCOT", "SD", "SE", "SEAT", "SENER", "SERVICES", "SEW", "SEX", "SEXY", "SG", "SH", "SHIKSHA", "SHOES", "SHOW", "SHRIRAM", "SI", "SINGLES", "SITE", "SJ", "SK", "SKI", "SKY", "SKYPE", "SL", "SM", "SN", "SNCF", "SO", "SOCCER", "SOCIAL", "SOFTWARE", "SOHU", "SOLAR", "SOLUTIONS", "SONY", "SOY", "SPACE", "SPIEGEL", "SPREADBETTING", "SR", "ST", "STARHUB", "STATOIL", "STUDY", "STYLE", "SU", "SUCKS", "SUPPLIES", "SUPPLY", "SUPPORT", "SURF", "SURGERY", "SUZUKI", "SV", "SWATCH", "SWISS", "SX", "SY", "SYDNEY", "SYSTEMS", "SZ", "TAIPEI", "TATAR", "TATTOO", "TAX", "TAXI", "TC", "TD", "TEAM", "TECH", "TECHNOLOGY", "TEL", "TELEFONICA", "TEMASEK", "TENNIS", "TF", "TG", "TH", "THD", "THEATER", "TICKETS", "TIENDA", "TIPS", "TIRES", "TIROL", "TJ", "TK", "TL", "TM", "TN", "TO", "TODAY", "TOKYO", "TOOLS", "TOP", "TORAY", "TOSHIBA", "TOURS", "TOWN", "TOYS", "TR", "TRADE", "TRADING", "TRAINING", "TRAVEL", "TRUST", "TT", "TUI", "TV", "TW", "TZ", "UA", "UG", "UK", "UNIVERSITY", "UNO", "UOL", "US", "UY", "UZ", "VA", "VACATIONS", "VC", "VE", "VEGAS", "VENTURES", "VERSICHERUNG", "VET", "VG", "VI", "VIAJES", "VIDEO", "VILLAS", "VISION", "VISTA", "VISTAPRINT", "VLAANDEREN", "VN", "VODKA", "VOTE", "VOTING", "VOTO", "VOYAGE", "VU", "WALES", "WALTER", "WANG", "WATCH", "WEBCAM", "WEBSITE", "WED", "WEDDING", "WEIR", "WF", "WHOSWHO", "WIEN", "WIKI", "WILLIAMHILL", "WIN", "WINDOWS", "WME", "WORK", "WORKS", "WORLD", "WS", "WTC", "WTF", "XBOX", "XEROX", "XIN", "XN--1QQW23A", "XN--30RR7Y", "XN--3BST00M", "XN--3DS443G", "XN--3E0B707E", "XN--45BRJ9C", "XN--45Q11C", "XN--4GBRIM", "XN--55QW42G", "XN--55QX5D", "XN--6FRZ82G", "XN--6QQ986B3XL", "XN--80ADXHKS", "XN--80AO21A", "XN--80ASEHDB", "XN--80ASWG", "XN--90A3AC", "XN--90AIS", "XN--9ET52U", "XN--B4W605FERD", "XN--C1AVG", "XN--CG4BKI", "XN--CLCHC0EA0B2G2A9GCD", "XN--CZR694B", "XN--CZRS0T", "XN--CZRU2D", "XN--D1ACJ3B", "XN--D1ALF", "XN--ESTV75G", "XN--FIQ228C5HS", "XN--FIQ64B", "XN--FIQS8S", "XN--FIQZ9S", "XN--FJQ720A", "XN--FLW351E", "XN--FPCRJ9C3D", "XN--FZC2C9E2C", "XN--GECRJ9C", "XN--H2BRJ9C", "XN--HXT814E", "XN--I1B6B1A6A2E", "XN--IMR513N", "XN--IO0A7I", "XN--J1AMH", "XN--J6W193G", "XN--KCRX77D1X4A", "XN--KPRW13D", "XN--KPRY57D", "XN--KPUT3I", "XN--L1ACC", "XN--LGBBAT1AD8J", "XN--MGB9AWBF", "XN--MGBA3A4F16A", "XN--MGBAAM7A8H", "XN--MGBAB2BD", "XN--MGBAYH7GPA", "XN--MGBBH1A71E", "XN--MGBC0A9AZCG", "XN--MGBERP4A5D4AR", "XN--MGBPL2FH", "XN--MGBX4CD0AB", "XN--MXTQ1M", "XN--NGBC5AZD", "XN--NODE", "XN--NQV7F", "XN--NQV7FS00EMA", "XN--NYQY26A", "XN--O3CW4H", "XN--OGBPF8FL", "XN--P1ACF", "XN--P1AI", "XN--PGBS0DH", "XN--Q9JYB4C", "XN--QCKA1PMC", "XN--RHQV96G", "XN--S9BRJ9C", "XN--SES554G", "XN--UNUP4Y", "XN--VERMGENSBERATER-CTB", "XN--VERMGENSBERATUNG-PWB", "XN--VHQUV", "XN--VUQ861B", "XN--WGBH1C", "XN--WGBL6A", "XN--XHQ521B", "XN--XKC2AL3HYE2A", "XN--XKC2DL3A5EE0H", "XN--Y9A3AQ", "XN--YFRO4I67O", "XN--YGBI2AMMX", "XN--ZFR164B", "XXX", "XYZ", "YACHTS", "YANDEX", "YE", "YODOBASHI", "YOGA", "YOKOHAMA", "YOUTUBE", "YT", "ZA", "ZIP", "ZM", "ZONE", "ZUERICH", "ZW", ]
tlds = ['ABB', 'ABBOTT', 'ABOGADO', 'AC', 'ACADEMY', 'ACCENTURE', 'ACCOUNTANT', 'ACCOUNTANTS', 'ACTIVE', 'ACTOR', 'AD', 'ADS', 'ADULT', 'AE', 'AEG', 'AERO', 'AF', 'AFL', 'AG', 'AGENCY', 'AI', 'AIG', 'AIRFORCE', 'AL', 'ALLFINANZ', 'ALSACE', 'AM', 'AMSTERDAM', 'AN', 'ANDROID', 'AO', 'APARTMENTS', 'AQ', 'AQUARELLE', 'AR', 'ARCHI', 'ARMY', 'ARPA', 'AS', 'ASIA', 'ASSOCIATES', 'AT', 'ATTORNEY', 'AU', 'AUCTION', 'AUDIO', 'AUTO', 'AUTOS', 'AW', 'AX', 'AXA', 'AZ', 'AZURE', 'BA', 'BAND', 'BANK', 'BAR', 'BARCLAYCARD', 'BARCLAYS', 'BARGAINS', 'BAUHAUS', 'BAYERN', 'BB', 'BBC', 'BBVA', 'BD', 'BE', 'BEER', 'BERLIN', 'BEST', 'BF', 'BG', 'BH', 'BHARTI', 'BI', 'BIBLE', 'BID', 'BIKE', 'BING', 'BINGO', 'BIO', 'BIZ', 'BJ', 'BLACK', 'BLACKFRIDAY', 'BLOOMBERG', 'BLUE', 'BM', 'BMW', 'BN', 'BNL', 'BNPPARIBAS', 'BO', 'BOATS', 'BOND', 'BOO', 'BOUTIQUE', 'BR', 'BRADESCO', 'BRIDGESTONE', 'BROKER', 'BROTHER', 'BRUSSELS', 'BS', 'BT', 'BUDAPEST', 'BUILD', 'BUILDERS', 'BUSINESS', 'BUZZ', 'BV', 'BW', 'BY', 'BZ', 'BZH', 'CA', 'CAB', 'CAFE', 'CAL', 'CAMERA', 'CAMP', 'CANCERRESEARCH', 'CANON', 'CAPETOWN', 'CAPITAL', 'CARAVAN', 'CARDS', 'CARE', 'CAREER', 'CAREERS', 'CARS', 'CARTIER', 'CASA', 'CASH', 'CASINO', 'CAT', 'CATERING', 'CBA', 'CBN', 'CC', 'CD', 'CENTER', 'CEO', 'CERN', 'CF', 'CFA', 'CFD', 'CG', 'CH', 'CHANNEL', 'CHAT', 'CHEAP', 'CHLOE', 'CHRISTMAS', 'CHROME', 'CHURCH', 'CI', 'CISCO', 'CITIC', 'CITY', 'CK', 'CL', 'CLAIMS', 'CLEANING', 'CLICK', 'CLINIC', 'CLOTHING', 'CLOUD', 'CLUB', 'CM', 'CN', 'CO', 'COACH', 'CODES', 'COFFEE', 'COLLEGE', 'COLOGNE', 'COM', 'COMMBANK', 'COMMUNITY', 'COMPANY', 'COMPUTER', 'CONDOS', 'CONSTRUCTION', 'CONSULTING', 'CONTRACTORS', 'COOKING', 'COOL', 'COOP', 'CORSICA', 'COUNTRY', 'COUPONS', 'COURSES', 'CR', 'CREDIT', 'CREDITCARD', 'CRICKET', 'CROWN', 'CRS', 'CRUISES', 'CU', 'CUISINELLA', 'CV', 'CW', 'CX', 'CY', 'CYMRU', 'CYOU', 'CZ', 'DABUR', 'DAD', 'DANCE', 'DATE', 'DATING', 'DATSUN', 'DAY', 'DCLK', 'DE', 'DEALS', 'DEGREE', 'DELIVERY', 'DEMOCRAT', 'DENTAL', 'DENTIST', 'DESI', 'DESIGN', 'DEV', 'DIAMONDS', 'DIET', 'DIGITAL', 'DIRECT', 'DIRECTORY', 'DISCOUNT', 'DJ', 'DK', 'DM', 'DNP', 'DO', 'DOCS', 'DOG', 'DOHA', 'DOMAINS', 'DOOSAN', 'DOWNLOAD', 'DRIVE', 'DURBAN', 'DVAG', 'DZ', 'EARTH', 'EAT', 'EC', 'EDU', 'EDUCATION', 'EE', 'EG', 'EMAIL', 'EMERCK', 'ENERGY', 'ENGINEER', 'ENGINEERING', 'ENTERPRISES', 'EPSON', 'EQUIPMENT', 'ER', 'ERNI', 'ES', 'ESQ', 'ESTATE', 'ET', 'EU', 'EUROVISION', 'EUS', 'EVENTS', 'EVERBANK', 'EXCHANGE', 'EXPERT', 'EXPOSED', 'EXPRESS', 'FAIL', 'FAITH', 'FAN', 'FANS', 'FARM', 'FASHION', 'FEEDBACK', 'FI', 'FILM', 'FINANCE', 'FINANCIAL', 'FIRMDALE', 'FISH', 'FISHING', 'FIT', 'FITNESS', 'FJ', 'FK', 'FLIGHTS', 'FLORIST', 'FLOWERS', 'FLSMIDTH', 'FLY', 'FM', 'FO', 'FOO', 'FOOTBALL', 'FOREX', 'FORSALE', 'FORUM', 'FOUNDATION', 'FR', 'FRL', 'FROGANS', 'FUND', 'FURNITURE', 'FUTBOL', 'FYI', 'GA', 'GAL', 'GALLERY', 'GARDEN', 'GB', 'GBIZ', 'GD', 'GDN', 'GE', 'GENT', 'GENTING', 'GF', 'GG', 'GGEE', 'GH', 'GI', 'GIFT', 'GIFTS', 'GIVES', 'GL', 'GLASS', 'GLE', 'GLOBAL', 'GLOBO', 'GM', 'GMAIL', 'GMO', 'GMX', 'GN', 'GOLD', 'GOLDPOINT', 'GOLF', 'GOO', 'GOOG', 'GOOGLE', 'GOP', 'GOV', 'GP', 'GQ', 'GR', 'GRAPHICS', 'GRATIS', 'GREEN', 'GRIPE', 'GS', 'GT', 'GU', 'GUGE', 'GUIDE', 'GUITARS', 'GURU', 'GW', 'GY', 'HAMBURG', 'HANGOUT', 'HAUS', 'HEALTHCARE', 'HELP', 'HERE', 'HERMES', 'HIPHOP', 'HITACHI', 'HIV', 'HK', 'HM', 'HN', 'HOCKEY', 'HOLDINGS', 'HOLIDAY', 'HOMEDEPOT', 'HOMES', 'HONDA', 'HORSE', 'HOST', 'HOSTING', 'HOTELES', 'HOTMAIL', 'HOUSE', 'HOW', 'HR', 'HT', 'HU', 'IBM', 'ICBC', 'ICU', 'ID', 'IE', 'IFM', 'IL', 'IM', 'IMMO', 'IMMOBILIEN', 'IN', 'INDUSTRIES', 'INFINITI', 'INFO', 'ING', 'INK', 'INSTITUTE', 'INSURE', 'INT', 'INTERNATIONAL', 'INVESTMENTS', 'IO', 'IQ', 'IR', 'IRISH', 'IS', 'IT', 'IWC', 'JAVA', 'JCB', 'JE', 'JETZT', 'JEWELRY', 'JLC', 'JLL', 'JM', 'JO', 'JOBS', 'JOBURG', 'JP', 'JUEGOS', 'KAUFEN', 'KDDI', 'KE', 'KG', 'KH', 'KI', 'KIM', 'KITCHEN', 'KIWI', 'KM', 'KN', 'KOELN', 'KOMATSU', 'KP', 'KR', 'KRD', 'KRED', 'KW', 'KY', 'KYOTO', 'KZ', 'LA', 'LACAIXA', 'LAND', 'LASALLE', 'LAT', 'LATROBE', 'LAW', 'LAWYER', 'LB', 'LC', 'LDS', 'LEASE', 'LECLERC', 'LEGAL', 'LGBT', 'LI', 'LIAISON', 'LIDL', 'LIFE', 'LIGHTING', 'LIMITED', 'LIMO', 'LINK', 'LK', 'LOAN', 'LOANS', 'LOL', 'LONDON', 'LOTTE', 'LOTTO', 'LOVE', 'LR', 'LS', 'LT', 'LTDA', 'LU', 'LUPIN', 'LUXE', 'LUXURY', 'LV', 'LY', 'MA', 'MADRID', 'MAIF', 'MAISON', 'MANAGEMENT', 'MANGO', 'MARKET', 'MARKETING', 'MARKETS', 'MARRIOTT', 'MBA', 'MC', 'MD', 'ME', 'MEDIA', 'MEET', 'MELBOURNE', 'MEME', 'MEMORIAL', 'MEN', 'MENU', 'MG', 'MH', 'MIAMI', 'MICROSOFT', 'MIL', 'MINI', 'MK', 'ML', 'MM', 'MMA', 'MN', 'MO', 'MOBI', 'MODA', 'MOE', 'MONASH', 'MONEY', 'MONTBLANC', 'MORMON', 'MORTGAGE', 'MOSCOW', 'MOTORCYCLES', 'MOV', 'MOVIE', 'MOVISTAR', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MTN', 'MTPC', 'MU', 'MUSEUM', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NADEX', 'NAGOYA', 'NAME', 'NAVY', 'NC', 'NE', 'NEC', 'NET', 'NETBANK', 'NETWORK', 'NEUSTAR', 'NEW', 'NEWS', 'NEXUS', 'NF', 'NG', 'NGO', 'NHK', 'NI', 'NICO', 'NINJA', 'NISSAN', 'NL', 'NO', 'NP', 'NR', 'NRA', 'NRW', 'NTT', 'NU', 'NYC', 'NZ', 'OFFICE', 'OKINAWA', 'OM', 'OMEGA', 'ONE', 'ONG', 'ONL', 'ONLINE', 'OOO', 'ORACLE', 'ORG', 'ORGANIC', 'OSAKA', 'OTSUKA', 'OVH', 'PA', 'PAGE', 'PANERAI', 'PARIS', 'PARTNERS', 'PARTS', 'PARTY', 'PE', 'PF', 'PG', 'PH', 'PHARMACY', 'PHILIPS', 'PHOTO', 'PHOTOGRAPHY', 'PHOTOS', 'PHYSIO', 'PIAGET', 'PICS', 'PICTET', 'PICTURES', 'PINK', 'PIZZA', 'PK', 'PL', 'PLACE', 'PLAY', 'PLUMBING', 'PLUS', 'PM', 'PN', 'POHL', 'POKER', 'PORN', 'POST', 'PR', 'PRAXI', 'PRESS', 'PRO', 'PROD', 'PRODUCTIONS', 'PROF', 'PROPERTIES', 'PROPERTY', 'PS', 'PT', 'PUB', 'PW', 'PY', 'QA', 'QPON', 'QUEBEC', 'RACING', 'RE', 'REALTOR', 'REALTY', 'RECIPES', 'RED', 'REDSTONE', 'REHAB', 'REISE', 'REISEN', 'REIT', 'REN', 'RENT', 'RENTALS', 'REPAIR', 'REPORT', 'REPUBLICAN', 'REST', 'RESTAURANT', 'REVIEW', 'REVIEWS', 'RICH', 'RICOH', 'RIO', 'RIP', 'RO', 'ROCKS', 'RODEO', 'RS', 'RSVP', 'RU', 'RUHR', 'RUN', 'RW', 'RYUKYU', 'SA', 'SAARLAND', 'SALE', 'SAMSUNG', 'SANDVIK', 'SANDVIKCOROMANT', 'SAP', 'SARL', 'SAXO', 'SB', 'SC', 'SCA', 'SCB', 'SCHMIDT', 'SCHOLARSHIPS', 'SCHOOL', 'SCHULE', 'SCHWARZ', 'SCIENCE', 'SCOR', 'SCOT', 'SD', 'SE', 'SEAT', 'SENER', 'SERVICES', 'SEW', 'SEX', 'SEXY', 'SG', 'SH', 'SHIKSHA', 'SHOES', 'SHOW', 'SHRIRAM', 'SI', 'SINGLES', 'SITE', 'SJ', 'SK', 'SKI', 'SKY', 'SKYPE', 'SL', 'SM', 'SN', 'SNCF', 'SO', 'SOCCER', 'SOCIAL', 'SOFTWARE', 'SOHU', 'SOLAR', 'SOLUTIONS', 'SONY', 'SOY', 'SPACE', 'SPIEGEL', 'SPREADBETTING', 'SR', 'ST', 'STARHUB', 'STATOIL', 'STUDY', 'STYLE', 'SU', 'SUCKS', 'SUPPLIES', 'SUPPLY', 'SUPPORT', 'SURF', 'SURGERY', 'SUZUKI', 'SV', 'SWATCH', 'SWISS', 'SX', 'SY', 'SYDNEY', 'SYSTEMS', 'SZ', 'TAIPEI', 'TATAR', 'TATTOO', 'TAX', 'TAXI', 'TC', 'TD', 'TEAM', 'TECH', 'TECHNOLOGY', 'TEL', 'TELEFONICA', 'TEMASEK', 'TENNIS', 'TF', 'TG', 'TH', 'THD', 'THEATER', 'TICKETS', 'TIENDA', 'TIPS', 'TIRES', 'TIROL', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TODAY', 'TOKYO', 'TOOLS', 'TOP', 'TORAY', 'TOSHIBA', 'TOURS', 'TOWN', 'TOYS', 'TR', 'TRADE', 'TRADING', 'TRAINING', 'TRAVEL', 'TRUST', 'TT', 'TUI', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UK', 'UNIVERSITY', 'UNO', 'UOL', 'US', 'UY', 'UZ', 'VA', 'VACATIONS', 'VC', 'VE', 'VEGAS', 'VENTURES', 'VERSICHERUNG', 'VET', 'VG', 'VI', 'VIAJES', 'VIDEO', 'VILLAS', 'VISION', 'VISTA', 'VISTAPRINT', 'VLAANDEREN', 'VN', 'VODKA', 'VOTE', 'VOTING', 'VOTO', 'VOYAGE', 'VU', 'WALES', 'WALTER', 'WANG', 'WATCH', 'WEBCAM', 'WEBSITE', 'WED', 'WEDDING', 'WEIR', 'WF', 'WHOSWHO', 'WIEN', 'WIKI', 'WILLIAMHILL', 'WIN', 'WINDOWS', 'WME', 'WORK', 'WORKS', 'WORLD', 'WS', 'WTC', 'WTF', 'XBOX', 'XEROX', 'XIN', 'XN--1QQW23A', 'XN--30RR7Y', 'XN--3BST00M', 'XN--3DS443G', 'XN--3E0B707E', 'XN--45BRJ9C', 'XN--45Q11C', 'XN--4GBRIM', 'XN--55QW42G', 'XN--55QX5D', 'XN--6FRZ82G', 'XN--6QQ986B3XL', 'XN--80ADXHKS', 'XN--80AO21A', 'XN--80ASEHDB', 'XN--80ASWG', 'XN--90A3AC', 'XN--90AIS', 'XN--9ET52U', 'XN--B4W605FERD', 'XN--C1AVG', 'XN--CG4BKI', 'XN--CLCHC0EA0B2G2A9GCD', 'XN--CZR694B', 'XN--CZRS0T', 'XN--CZRU2D', 'XN--D1ACJ3B', 'XN--D1ALF', 'XN--ESTV75G', 'XN--FIQ228C5HS', 'XN--FIQ64B', 'XN--FIQS8S', 'XN--FIQZ9S', 'XN--FJQ720A', 'XN--FLW351E', 'XN--FPCRJ9C3D', 'XN--FZC2C9E2C', 'XN--GECRJ9C', 'XN--H2BRJ9C', 'XN--HXT814E', 'XN--I1B6B1A6A2E', 'XN--IMR513N', 'XN--IO0A7I', 'XN--J1AMH', 'XN--J6W193G', 'XN--KCRX77D1X4A', 'XN--KPRW13D', 'XN--KPRY57D', 'XN--KPUT3I', 'XN--L1ACC', 'XN--LGBBAT1AD8J', 'XN--MGB9AWBF', 'XN--MGBA3A4F16A', 'XN--MGBAAM7A8H', 'XN--MGBAB2BD', 'XN--MGBAYH7GPA', 'XN--MGBBH1A71E', 'XN--MGBC0A9AZCG', 'XN--MGBERP4A5D4AR', 'XN--MGBPL2FH', 'XN--MGBX4CD0AB', 'XN--MXTQ1M', 'XN--NGBC5AZD', 'XN--NODE', 'XN--NQV7F', 'XN--NQV7FS00EMA', 'XN--NYQY26A', 'XN--O3CW4H', 'XN--OGBPF8FL', 'XN--P1ACF', 'XN--P1AI', 'XN--PGBS0DH', 'XN--Q9JYB4C', 'XN--QCKA1PMC', 'XN--RHQV96G', 'XN--S9BRJ9C', 'XN--SES554G', 'XN--UNUP4Y', 'XN--VERMGENSBERATER-CTB', 'XN--VERMGENSBERATUNG-PWB', 'XN--VHQUV', 'XN--VUQ861B', 'XN--WGBH1C', 'XN--WGBL6A', 'XN--XHQ521B', 'XN--XKC2AL3HYE2A', 'XN--XKC2DL3A5EE0H', 'XN--Y9A3AQ', 'XN--YFRO4I67O', 'XN--YGBI2AMMX', 'XN--ZFR164B', 'XXX', 'XYZ', 'YACHTS', 'YANDEX', 'YE', 'YODOBASHI', 'YOGA', 'YOKOHAMA', 'YOUTUBE', 'YT', 'ZA', 'ZIP', 'ZM', 'ZONE', 'ZUERICH', 'ZW']
class Bank: def __init__(self): self.inf = 0 self._observers = [] def register_observer(self, observer): self._observers.append(observer) def notify_observers(self): print("Inflacja na poziomie: ", format(self.inf, '.2f')) for observer in self._observers: observer.notify(self)
class Bank: def __init__(self): self.inf = 0 self._observers = [] def register_observer(self, observer): self._observers.append(observer) def notify_observers(self): print('Inflacja na poziomie: ', format(self.inf, '.2f')) for observer in self._observers: observer.notify(self)
fruta = 'kiwi' if fruta == 'kiwi': print("El valor es kiwi") elif fruta == 'manzana': print("Es una manzana") elif fruta == 'manzana2': pass #si no sabemos que poner y no marque error else: print("No son iguales") mensaje = 'El valor es kiwi' if fruta == 'kiwis' else False print(mensaje)
fruta = 'kiwi' if fruta == 'kiwi': print('El valor es kiwi') elif fruta == 'manzana': print('Es una manzana') elif fruta == 'manzana2': pass else: print('No son iguales') mensaje = 'El valor es kiwi' if fruta == 'kiwis' else False print(mensaje)
# Status code API_HANDLER_OK_CODE = 200 API_HANDLER_ERROR_CODE = 400 # REST parameters SERVICE_HANDLER_POST_ARG_KEY = "key" SERVICE_HANDLER_POST_BODY_KEY = "body_key"
api_handler_ok_code = 200 api_handler_error_code = 400 service_handler_post_arg_key = 'key' service_handler_post_body_key = 'body_key'
def get_paginated_result(query, page, per_page, field, timestamp): new_query = query if page != 1 and timestamp != None: new_query = query.filter( field < timestamp ) try: return new_query.paginate( per_page=per_page, page=page ).items, 200 except: response_object = { 'status': 'error', 'message': 'end of content', } return response_object, 470
def get_paginated_result(query, page, per_page, field, timestamp): new_query = query if page != 1 and timestamp != None: new_query = query.filter(field < timestamp) try: return (new_query.paginate(per_page=per_page, page=page).items, 200) except: response_object = {'status': 'error', 'message': 'end of content'} return (response_object, 470)
#!/usr/bin/env python3 # encoding: utf-8 def _subclasses(cls): try: return cls.__subclasses__() except TypeError: return type.__subclasses__(cls) class _SubclassNode: __slots__ = frozenset(('cls', 'children')) def __init__(self, cls, children=None): self.cls = cls self.children = children or [] def __repr__(self): if not self.children: return repr(self.cls) return '<{0.__class__.__qualname__} {0.cls} {0.children}>'.format(self) def subclasses(cls, root=None): root = root or _SubclassNode(cls) root.children.extend(map(_SubclassNode, _subclasses(cls))) for child in root.children: subclasses(child.cls, child) return root if __name__ == '__main__': class A: pass class B(A): pass class C(A): pass class D(B, C): pass class E(A): pass print(subclasses(A))
def _subclasses(cls): try: return cls.__subclasses__() except TypeError: return type.__subclasses__(cls) class _Subclassnode: __slots__ = frozenset(('cls', 'children')) def __init__(self, cls, children=None): self.cls = cls self.children = children or [] def __repr__(self): if not self.children: return repr(self.cls) return '<{0.__class__.__qualname__} {0.cls} {0.children}>'.format(self) def subclasses(cls, root=None): root = root or __subclass_node(cls) root.children.extend(map(_SubclassNode, _subclasses(cls))) for child in root.children: subclasses(child.cls, child) return root if __name__ == '__main__': class A: pass class B(A): pass class C(A): pass class D(B, C): pass class E(A): pass print(subclasses(A))
def longest_uppercase(input,k): final_out = 0 for i in input: test_letters = i for j in input: if len(test_letters) == k : break if test_letters.find(j) >= 0: pass else: test_letters += j max = 0 count = 0 for m in input : if test_letters.find(m) == -1: if count > max: max = count count = 0 else: count += 1 if len(input) <= k: return len(input) if final_out < max: final_out = max return final_out
def longest_uppercase(input, k): final_out = 0 for i in input: test_letters = i for j in input: if len(test_letters) == k: break if test_letters.find(j) >= 0: pass else: test_letters += j max = 0 count = 0 for m in input: if test_letters.find(m) == -1: if count > max: max = count count = 0 else: count += 1 if len(input) <= k: return len(input) if final_out < max: final_out = max return final_out
# The following dependencies were calculated from: # # generate_workspace --artifact=io.opencensus:opencensus-api:0.12.2 --artifact=io.opencensus:opencensus-contrib-zpages:0.12.2 --artifact=io.opencensus:opencensus-exporter-trace-logging:0.12.2 --artifact=io.opencensus:opencensus-impl:0.12.2 --repositories=http://repo.maven.apache.org/maven2 def opencensus_maven_jars(): # io.opencensus:opencensus-impl-core:jar:0.12.2 got requested version # io.opencensus:opencensus-contrib-zpages:jar:0.12.2 got requested version # io.opencensus:opencensus-contrib-grpc-metrics:jar:0.12.2 got requested version # io.opencensus:opencensus-api:jar:0.12.2 # io.opencensus:opencensus-exporter-trace-logging:jar:0.12.2 got requested version # io.opencensus:opencensus-impl:jar:0.12.2 got requested version native.maven_jar( name = "com_google_code_findbugs_jsr305", artifact = "com.google.code.findbugs:jsr305:3.0.1", repository = "http://repo.maven.apache.org/maven2/", sha1 = "f7be08ec23c21485b9b5a1cf1654c2ec8c58168d", ) # io.opencensus:opencensus-api:jar:0.12.2 native.maven_jar( name = "io_grpc_grpc_context", artifact = "io.grpc:grpc-context:1.9.0", repository = "http://repo.maven.apache.org/maven2/", sha1 = "28b0836f48c9705abf73829bbc536dba29a1329a", ) native.maven_jar( name = "io_opencensus_opencensus_exporter_trace_logging", artifact = "io.opencensus:opencensus-exporter-trace-logging:0.12.2", repository = "http://repo.maven.apache.org/maven2/", sha1 = "15b8b3d2c9b3ffd2d8e242d252ee056a1c30d203", ) # io.opencensus:opencensus-impl-core:jar:0.12.2 got requested version # io.opencensus:opencensus-contrib-zpages:jar:0.12.2 got requested version # io.opencensus:opencensus-contrib-grpc-metrics:jar:0.12.2 got requested version # io.opencensus:opencensus-api:jar:0.12.2 # io.opencensus:opencensus-exporter-trace-logging:jar:0.12.2 got requested version # io.opencensus:opencensus-impl:jar:0.12.2 got requested version native.maven_jar( name = "com_google_errorprone_error_prone_annotations", artifact = "com.google.errorprone:error_prone_annotations:2.2.0", repository = "http://repo.maven.apache.org/maven2/", sha1 = "88e3c593e9b3586e1c6177f89267da6fc6986f0c", ) native.maven_jar( name = "io_opencensus_opencensus_contrib_zpages", artifact = "io.opencensus:opencensus-contrib-zpages:0.12.2", repository = "http://repo.maven.apache.org/maven2/", sha1 = "44f8d5b81b20f9f0d34091baecffd67c2ce0c952", ) # io.opencensus:opencensus-impl:jar:0.12.2 native.maven_jar( name = "com_lmax_disruptor", artifact = "com.lmax:disruptor:3.3.9", repository = "http://repo.maven.apache.org/maven2/", sha1 = "7898f8e8dc2d908d4ae5240fbb17eb1a9c213b9b", ) # io.opencensus:opencensus-impl-core:jar:0.12.2 got requested version # io.opencensus:opencensus-contrib-zpages:jar:0.12.2 got requested version # io.opencensus:opencensus-api:jar:0.12.2 # io.opencensus:opencensus-exporter-trace-logging:jar:0.12.2 got requested version native.maven_jar( name = "com_google_guava_guava", artifact = "com.google.guava:guava:19.0", repository = "http://repo.maven.apache.org/maven2/", sha1 = "6ce200f6b23222af3d8abb6b6459e6c44f4bb0e9", ) # io.opencensus:opencensus-contrib-zpages:jar:0.12.2 native.maven_jar( name = "io_opencensus_opencensus_contrib_grpc_metrics", artifact = "io.opencensus:opencensus-contrib-grpc-metrics:0.12.2", repository = "http://repo.maven.apache.org/maven2/", sha1 = "20dd982bd8942fc6d612fedd4466cda0461267ec", ) # io.opencensus:opencensus-impl-core:jar:0.12.2 got requested version # io.opencensus:opencensus-contrib-zpages:jar:0.12.2 got requested version # io.opencensus:opencensus-contrib-grpc-metrics:jar:0.12.2 got requested version # io.opencensus:opencensus-exporter-trace-logging:jar:0.12.2 got requested version # io.opencensus:opencensus-impl:jar:0.12.2 got requested version native.maven_jar( name = "io_opencensus_opencensus_api", artifact = "io.opencensus:opencensus-api:0.12.2", repository = "http://repo.maven.apache.org/maven2/", sha1 = "a2d524b62869350942106ab8f9a1f5adb1212775", ) # io.opencensus:opencensus-impl:jar:0.12.2 native.maven_jar( name = "io_opencensus_opencensus_impl_core", artifact = "io.opencensus:opencensus-impl-core:0.12.2", repository = "http://repo.maven.apache.org/maven2/", sha1 = "9e059704131a4455b3bd6d84cfa8e6875551d647", ) native.maven_jar( name = "io_opencensus_opencensus_impl", artifact = "io.opencensus:opencensus-impl:0.12.2", repository = "http://repo.maven.apache.org/maven2/", sha1 = "4e5cd57bddbd9b47cd16cc8b0b608b43355b223f", ) def opencensus_java_libraries(): native.java_library( name = "com_google_code_findbugs_jsr305", visibility = ["//visibility:public"], exports = ["@com_google_code_findbugs_jsr305//jar"], ) native.java_library( name = "io_grpc_grpc_context", visibility = ["//visibility:public"], exports = ["@io_grpc_grpc_context//jar"], ) native.java_library( name = "io_opencensus_opencensus_exporter_trace_logging", visibility = ["//visibility:public"], exports = ["@io_opencensus_opencensus_exporter_trace_logging//jar"], runtime_deps = [ ":com_google_code_findbugs_jsr305", ":com_google_errorprone_error_prone_annotations", ":com_google_guava_guava", ":io_opencensus_opencensus_api", ], ) native.java_library( name = "com_google_errorprone_error_prone_annotations", visibility = ["//visibility:public"], exports = ["@com_google_errorprone_error_prone_annotations//jar"], ) native.java_library( name = "io_opencensus_opencensus_contrib_zpages", visibility = ["//visibility:public"], exports = ["@io_opencensus_opencensus_contrib_zpages//jar"], runtime_deps = [ ":com_google_code_findbugs_jsr305", ":com_google_errorprone_error_prone_annotations", ":com_google_guava_guava", ":io_opencensus_opencensus_api", ":io_opencensus_opencensus_contrib_grpc_metrics", ], ) native.java_library( name = "com_lmax_disruptor", visibility = ["//visibility:public"], exports = ["@com_lmax_disruptor//jar"], ) native.java_library( name = "com_google_guava_guava", visibility = ["//visibility:public"], exports = ["@com_google_guava_guava//jar"], ) native.java_library( name = "io_opencensus_opencensus_contrib_grpc_metrics", visibility = ["//visibility:public"], exports = ["@io_opencensus_opencensus_contrib_grpc_metrics//jar"], runtime_deps = [ ":com_google_code_findbugs_jsr305", ":com_google_errorprone_error_prone_annotations", ":io_opencensus_opencensus_api", ], ) native.java_library( name = "io_opencensus_opencensus_api", visibility = ["//visibility:public"], exports = ["@io_opencensus_opencensus_api//jar"], runtime_deps = [ ":com_google_code_findbugs_jsr305", ":com_google_errorprone_error_prone_annotations", ":com_google_guava_guava", ":io_grpc_grpc_context", ], ) native.java_library( name = "io_opencensus_opencensus_impl_core", visibility = ["//visibility:public"], exports = ["@io_opencensus_opencensus_impl_core//jar"], runtime_deps = [ ":com_google_code_findbugs_jsr305", ":com_google_errorprone_error_prone_annotations", ":com_google_guava_guava", ":io_opencensus_opencensus_api", ], ) native.java_library( name = "io_opencensus_opencensus_impl", visibility = ["//visibility:public"], exports = ["@io_opencensus_opencensus_impl//jar"], runtime_deps = [ ":com_google_code_findbugs_jsr305", ":com_google_errorprone_error_prone_annotations", ":com_google_guava_guava", ":com_lmax_disruptor", ":io_opencensus_opencensus_api", ":io_opencensus_opencensus_impl_core", ], )
def opencensus_maven_jars(): native.maven_jar(name='com_google_code_findbugs_jsr305', artifact='com.google.code.findbugs:jsr305:3.0.1', repository='http://repo.maven.apache.org/maven2/', sha1='f7be08ec23c21485b9b5a1cf1654c2ec8c58168d') native.maven_jar(name='io_grpc_grpc_context', artifact='io.grpc:grpc-context:1.9.0', repository='http://repo.maven.apache.org/maven2/', sha1='28b0836f48c9705abf73829bbc536dba29a1329a') native.maven_jar(name='io_opencensus_opencensus_exporter_trace_logging', artifact='io.opencensus:opencensus-exporter-trace-logging:0.12.2', repository='http://repo.maven.apache.org/maven2/', sha1='15b8b3d2c9b3ffd2d8e242d252ee056a1c30d203') native.maven_jar(name='com_google_errorprone_error_prone_annotations', artifact='com.google.errorprone:error_prone_annotations:2.2.0', repository='http://repo.maven.apache.org/maven2/', sha1='88e3c593e9b3586e1c6177f89267da6fc6986f0c') native.maven_jar(name='io_opencensus_opencensus_contrib_zpages', artifact='io.opencensus:opencensus-contrib-zpages:0.12.2', repository='http://repo.maven.apache.org/maven2/', sha1='44f8d5b81b20f9f0d34091baecffd67c2ce0c952') native.maven_jar(name='com_lmax_disruptor', artifact='com.lmax:disruptor:3.3.9', repository='http://repo.maven.apache.org/maven2/', sha1='7898f8e8dc2d908d4ae5240fbb17eb1a9c213b9b') native.maven_jar(name='com_google_guava_guava', artifact='com.google.guava:guava:19.0', repository='http://repo.maven.apache.org/maven2/', sha1='6ce200f6b23222af3d8abb6b6459e6c44f4bb0e9') native.maven_jar(name='io_opencensus_opencensus_contrib_grpc_metrics', artifact='io.opencensus:opencensus-contrib-grpc-metrics:0.12.2', repository='http://repo.maven.apache.org/maven2/', sha1='20dd982bd8942fc6d612fedd4466cda0461267ec') native.maven_jar(name='io_opencensus_opencensus_api', artifact='io.opencensus:opencensus-api:0.12.2', repository='http://repo.maven.apache.org/maven2/', sha1='a2d524b62869350942106ab8f9a1f5adb1212775') native.maven_jar(name='io_opencensus_opencensus_impl_core', artifact='io.opencensus:opencensus-impl-core:0.12.2', repository='http://repo.maven.apache.org/maven2/', sha1='9e059704131a4455b3bd6d84cfa8e6875551d647') native.maven_jar(name='io_opencensus_opencensus_impl', artifact='io.opencensus:opencensus-impl:0.12.2', repository='http://repo.maven.apache.org/maven2/', sha1='4e5cd57bddbd9b47cd16cc8b0b608b43355b223f') def opencensus_java_libraries(): native.java_library(name='com_google_code_findbugs_jsr305', visibility=['//visibility:public'], exports=['@com_google_code_findbugs_jsr305//jar']) native.java_library(name='io_grpc_grpc_context', visibility=['//visibility:public'], exports=['@io_grpc_grpc_context//jar']) native.java_library(name='io_opencensus_opencensus_exporter_trace_logging', visibility=['//visibility:public'], exports=['@io_opencensus_opencensus_exporter_trace_logging//jar'], runtime_deps=[':com_google_code_findbugs_jsr305', ':com_google_errorprone_error_prone_annotations', ':com_google_guava_guava', ':io_opencensus_opencensus_api']) native.java_library(name='com_google_errorprone_error_prone_annotations', visibility=['//visibility:public'], exports=['@com_google_errorprone_error_prone_annotations//jar']) native.java_library(name='io_opencensus_opencensus_contrib_zpages', visibility=['//visibility:public'], exports=['@io_opencensus_opencensus_contrib_zpages//jar'], runtime_deps=[':com_google_code_findbugs_jsr305', ':com_google_errorprone_error_prone_annotations', ':com_google_guava_guava', ':io_opencensus_opencensus_api', ':io_opencensus_opencensus_contrib_grpc_metrics']) native.java_library(name='com_lmax_disruptor', visibility=['//visibility:public'], exports=['@com_lmax_disruptor//jar']) native.java_library(name='com_google_guava_guava', visibility=['//visibility:public'], exports=['@com_google_guava_guava//jar']) native.java_library(name='io_opencensus_opencensus_contrib_grpc_metrics', visibility=['//visibility:public'], exports=['@io_opencensus_opencensus_contrib_grpc_metrics//jar'], runtime_deps=[':com_google_code_findbugs_jsr305', ':com_google_errorprone_error_prone_annotations', ':io_opencensus_opencensus_api']) native.java_library(name='io_opencensus_opencensus_api', visibility=['//visibility:public'], exports=['@io_opencensus_opencensus_api//jar'], runtime_deps=[':com_google_code_findbugs_jsr305', ':com_google_errorprone_error_prone_annotations', ':com_google_guava_guava', ':io_grpc_grpc_context']) native.java_library(name='io_opencensus_opencensus_impl_core', visibility=['//visibility:public'], exports=['@io_opencensus_opencensus_impl_core//jar'], runtime_deps=[':com_google_code_findbugs_jsr305', ':com_google_errorprone_error_prone_annotations', ':com_google_guava_guava', ':io_opencensus_opencensus_api']) native.java_library(name='io_opencensus_opencensus_impl', visibility=['//visibility:public'], exports=['@io_opencensus_opencensus_impl//jar'], runtime_deps=[':com_google_code_findbugs_jsr305', ':com_google_errorprone_error_prone_annotations', ':com_google_guava_guava', ':com_lmax_disruptor', ':io_opencensus_opencensus_api', ':io_opencensus_opencensus_impl_core'])
# -- Project information ----------------------------------------------------- project = 'showyourwork' copyright = '2021, Rodrigo Luger' author = 'Rodrigo Luger' release = '1.0.0' # -- General configuration --------------------------------------------------- extensions = [] templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] master_doc = 'index' # -- Options for HTML output ------------------------------------------------- html_theme = 'sphinx_book_theme' html_copy_source = True html_show_sourcelink = True html_sourcelink_suffix = "" html_title = "showyourwork" html_logo = "_static/logo.png" html_static_path = ["_static"] html_css_files = [] html_theme_options = { "repository_url": "https://github.com/rodluger/showyourwork", "repository_branch": "main", "use_edit_page_button": True, "use_issues_button": True, "use_repository_button": True, "use_download_button": True, "logo_only": True, "use_fullscreen_button": False, "path_to_docs": "docs/", }
project = 'showyourwork' copyright = '2021, Rodrigo Luger' author = 'Rodrigo Luger' release = '1.0.0' extensions = [] templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] master_doc = 'index' html_theme = 'sphinx_book_theme' html_copy_source = True html_show_sourcelink = True html_sourcelink_suffix = '' html_title = 'showyourwork' html_logo = '_static/logo.png' html_static_path = ['_static'] html_css_files = [] html_theme_options = {'repository_url': 'https://github.com/rodluger/showyourwork', 'repository_branch': 'main', 'use_edit_page_button': True, 'use_issues_button': True, 'use_repository_button': True, 'use_download_button': True, 'logo_only': True, 'use_fullscreen_button': False, 'path_to_docs': 'docs/'}
''' #3-1 b=0 c=0 while 1 : a=input("Enthe an integer, the input ends if it is :") if((a>0)|(a<0)): if a>0: b=a else: c=-a if(a==0): print("zheng shu {},fushu {},pingjunshu {}".format(b,c,(b+c))) break ''' ''' #3-2 j = 0 for i in range(15): s = 10000+10000*0.05 j = j + s if i==10: a = j print(a) if i == 11: b = j d = b-a print(d) print(j-a) ''' ''' #3-3 s=10000 for i in range(10): s=s+s*0.05 print(s) n=s for i in range(4): n=n+n*0.05 print(n) ''' ''' #3-4 a=0 for i in range(100,1000): if(i%5==0 and i%6==0): a=a+1 print("%3d" % i, end=" ") if(a%10==0): print(" ") ''' ''' #3-5 import math n=0.0 while 1: n = n+1.0 if n*n*n<12000: print(n) break if n*n>=12000: print(n) break ''' ''' #3-5 n=1 while(n<12000): if(n*n>12000): print(n) break n=n+1 s=1 while(s<12000): if(s*s*s>12000): print(s-1) break s=s+1 ''' ''' #3-6 p = eval(raw_input(">>")) y = eval(raw_input(">>")) n = 0.05 while n<8.125: n = n+0.125 s = p*pow((1.0+n),1) print(s) m = s/12 print(m) ''' ''' #3-7 n=0 for i in range(1,50001): n=n+1/i print(n) s=50000 m=0 while(s>0): m=m+1/s s=s-1 print(m) ''' ''' #3-8 a=1.0 b=3.0 sum1=0 while (a<=97): sum1=sum1+a/b a=a+2 b=b+2 print(sum1) ''' ''' #3-9 #_*_coding:utf8- a=input(">>") b=0 sum=0 for i in range(1,a+1): sum+=pow((-1),(a+1))/2*a-1 b=sum*4 print(b) ''' ''' #3-9-2 n=0 for i in range(1,100000): n=n+pow((-1),i+1)/(2*i-1) if(i%10000==0): print(4*n) ''' ''' #3-10 for i in range(1,10001): n=0 for j in range(1,i/2+1): if(i%j==0): n=n+j if(n==i): print(i) ''' ''' #3-11 a=0 for i in range(1,8): for j in range(i+1,8): print("sum {}".format((i)+(j))) a=a+1 print "sum",a '''
""" #3-1 b=0 c=0 while 1 : a=input("Enthe an integer, the input ends if it is :") if((a>0)|(a<0)): if a>0: b=a else: c=-a if(a==0): print("zheng shu {},fushu {},pingjunshu {}".format(b,c,(b+c))) break """ '\n#3-2\nj = 0\nfor i in range(15):\n s = 10000+10000*0.05\n j = j + s\n if i==10:\n a = j\n print(a)\n if i == 11:\n b = j\n d = b-a\n print(d)\nprint(j-a)\n' '\n#3-3\ns=10000\nfor i in range(10):\n s=s+s*0.05\nprint(s)\nn=s\nfor i in range(4):\n n=n+n*0.05\nprint(n)\n' '\n#3-4\na=0\nfor i in range(100,1000):\n if(i%5==0 and i%6==0):\n a=a+1\n print("%3d" % i, end=" ")\n if(a%10==0):\n print(" ")\n\n' '\n#3-5\nimport math\nn=0.0\nwhile 1:\n n = n+1.0\n if n*n*n<12000:\n print(n)\n break\n\n if n*n>=12000:\n print(n)\n break\n' '\n#3-5\nn=1\nwhile(n<12000):\n if(n*n>12000):\n print(n)\n break\n n=n+1\ns=1\nwhile(s<12000):\n if(s*s*s>12000):\n print(s-1)\n break\n s=s+1\n' '\n#3-6\np = eval(raw_input(">>"))\ny = eval(raw_input(">>"))\nn = 0.05\nwhile n<8.125:\n n = n+0.125\n s = p*pow((1.0+n),1)\n print(s)\n m = s/12\n print(m)\n' '\n#3-7\nn=0\nfor i in range(1,50001):\n n=n+1/i\nprint(n)\ns=50000\nm=0\nwhile(s>0):\n m=m+1/s\n s=s-1\nprint(m)\n' '\n#3-8\na=1.0\nb=3.0\nsum1=0\nwhile (a<=97):\n sum1=sum1+a/b\n a=a+2\n b=b+2\nprint(sum1)\n' '\n#3-9\n#_*_coding:utf8-\na=input(">>")\nb=0\nsum=0\nfor i in range(1,a+1):\n sum+=pow((-1),(a+1))/2*a-1\nb=sum*4\nprint(b)\n' '\n#3-9-2\nn=0\nfor i in range(1,100000):\n n=n+pow((-1),i+1)/(2*i-1)\n if(i%10000==0):\n print(4*n)\n' '\n#3-10\n\nfor i in range(1,10001):\n n=0\n for j in range(1,i/2+1):\n if(i%j==0):\n n=n+j\n if(n==i):\n print(i)\n' '\n#3-11\na=0\nfor i in range(1,8):\n for j in range(i+1,8):\n print("sum {}".format((i)+(j)))\n a=a+1\nprint "sum",a\n'
def mergeSort(myList): print("Splitting ",myList) if (len(myList) > 1): mid = len(myList)//2 leftList = myList[:mid] rightList = myList[mid:] mergeSort(leftList) mergeSort(rightList) i = 0 j = 0 k = 0 while ((i < len(leftList)) and (j < len(rightList))): if (leftList[i] < rightList[j]): myList[k] = leftList[i] i = i + 1 else: myList[k] = rightList[j] j = j + 1 k = k + 1 while (i < len(leftList)): myList[k] = leftList[i] i = i + 1 k = k + 1 while (j < len(rightList)): myList[k] = rightList[j] j = j + 1 k = k + 1 print("Merging ",myList) myList = [3,1,4,10,9,6,2,5,8,7] mergeSort(myList) print(myList)
def merge_sort(myList): print('Splitting ', myList) if len(myList) > 1: mid = len(myList) // 2 left_list = myList[:mid] right_list = myList[mid:] merge_sort(leftList) merge_sort(rightList) i = 0 j = 0 k = 0 while i < len(leftList) and j < len(rightList): if leftList[i] < rightList[j]: myList[k] = leftList[i] i = i + 1 else: myList[k] = rightList[j] j = j + 1 k = k + 1 while i < len(leftList): myList[k] = leftList[i] i = i + 1 k = k + 1 while j < len(rightList): myList[k] = rightList[j] j = j + 1 k = k + 1 print('Merging ', myList) my_list = [3, 1, 4, 10, 9, 6, 2, 5, 8, 7] merge_sort(myList) print(myList)
while True: relax = master.relax() relax.optimize() pi = [c.Pi for c in relax.getConstrs()] knapsack = Model("KP") knapsack.ModelSense=-1 y = {} for i in range(m): y[i] = knapsack.addVar(ub=q[i], vtype="I", name="y[%d]"%i) knapsack.update() knapsack.addConstr(quicksum(w[i]*y[i] for i in range(m)) <= B, "width") knapsack.setObjective(quicksum(pi[i]*y[i] for i in range(m)), GRB.MAXIMIZE) knapsack.optimize() if knapsack.ObjVal < 1+EPS: break pat = [int(y[i].X+0.5) for i in y] t.append(pat) col = Column() for i in range(m): if t[K][i] > 0: col.addTerms(t[K][i], orders[i]) x[K] = master.addVar(obj=1, vtype="I", name="x[%d]"%K, column=col) master.update() K += 1 master.optimize() rolls = [] for k in x: for j in range(int(x[k].X + .5)): rolls.append(sorted([w[i] for i in range(m) if t[k][i]>0 for j in range(t[k][i])])) rolls.sort() return rolls t = [] m = len(w) for i in range(m): pat = [0]*m pat[i] = int(B/w[i]) t.append(pat)
while True: relax = master.relax() relax.optimize() pi = [c.Pi for c in relax.getConstrs()] knapsack = model('KP') knapsack.ModelSense = -1 y = {} for i in range(m): y[i] = knapsack.addVar(ub=q[i], vtype='I', name='y[%d]' % i) knapsack.update() knapsack.addConstr(quicksum((w[i] * y[i] for i in range(m))) <= B, 'width') knapsack.setObjective(quicksum((pi[i] * y[i] for i in range(m))), GRB.MAXIMIZE) knapsack.optimize() if knapsack.ObjVal < 1 + EPS: break pat = [int(y[i].X + 0.5) for i in y] t.append(pat) col = column() for i in range(m): if t[K][i] > 0: col.addTerms(t[K][i], orders[i]) x[K] = master.addVar(obj=1, vtype='I', name='x[%d]' % K, column=col) master.update() k += 1 master.optimize() rolls = [] for k in x: for j in range(int(x[k].X + 0.5)): rolls.append(sorted([w[i] for i in range(m) if t[k][i] > 0 for j in range(t[k][i])])) rolls.sort() return rolls t = [] m = len(w) for i in range(m): pat = [0] * m pat[i] = int(B / w[i]) t.append(pat)
def hasDoubleDigits(p): previous = '' for c in p: if c == previous: return True previous = c return False def neverDecreases(p): previous = -1 for c in p: current = int(c) if current < previous: return False previous = current return True def isValidPassword(p): return hasDoubleDigits(p) and neverDecreases(p) def findNumberOfPasswords(min, max): current = min count = 0 while current <= max: s = str(current) if isValidPassword(s): count += 1 current += 1 return count MIN_VALUE = 245182 MAX_VALUE = 790572 print(findNumberOfPasswords(MIN_VALUE, MAX_VALUE))
def has_double_digits(p): previous = '' for c in p: if c == previous: return True previous = c return False def never_decreases(p): previous = -1 for c in p: current = int(c) if current < previous: return False previous = current return True def is_valid_password(p): return has_double_digits(p) and never_decreases(p) def find_number_of_passwords(min, max): current = min count = 0 while current <= max: s = str(current) if is_valid_password(s): count += 1 current += 1 return count min_value = 245182 max_value = 790572 print(find_number_of_passwords(MIN_VALUE, MAX_VALUE))
# a red shadow with some blur and a offset cmykShadow((3, 3), 10, (1, 0, 0, 0)) # draw a rect rect(100, 100, 30, 30)
cmyk_shadow((3, 3), 10, (1, 0, 0, 0)) rect(100, 100, 30, 30)
# # PySNMP MIB module NSLDAP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NSLDAP-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:25:08 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint") URLString, DistinguishedName, applIndex = mibBuilder.importSymbols("NETWORK-SERVICES-MIB", "URLString", "DistinguishedName", "applIndex") ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup") iso, NotificationType, Integer32, Counter32, ObjectIdentity, ModuleIdentity, Counter64, Gauge32, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Bits, MibIdentifier, TimeTicks, enterprises, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "NotificationType", "Integer32", "Counter32", "ObjectIdentity", "ModuleIdentity", "Counter64", "Gauge32", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Bits", "MibIdentifier", "TimeTicks", "enterprises", "IpAddress") DisplayString, TimeStamp, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TimeStamp", "TextualConvention") netscape = MibIdentifier((1, 3, 6, 1, 4, 1, 1450)) nsldap = ModuleIdentity((1, 3, 6, 1, 4, 1, 1450, 7)) if mibBuilder.loadTexts: nsldap.setLastUpdated('9707310000Z') if mibBuilder.loadTexts: nsldap.setOrganization('Netscape Communications Corp') if mibBuilder.loadTexts: nsldap.setContactInfo(' Frank Chen Postal: Netscape Communications Corp 501 East Middlefield Rd Mountain View, CA 94043 Tel: (415) 937 - 3703 Fax: (415) 937 - 4164 E-mail: frank@netscape.com') if mibBuilder.loadTexts: nsldap.setDescription(' An implementation of the MADMAN mib for monitoring LDAP/CLDAP and X.500 directories described in internet draft: draft-ietf-madman-ds-mib-103.txt used for iPlanet Directory Server 5') dsOpsTable = MibTable((1, 3, 6, 1, 4, 1, 1450, 7, 1), ) if mibBuilder.loadTexts: dsOpsTable.setStatus('current') if mibBuilder.loadTexts: dsOpsTable.setDescription(' The table holding information related to the DS operations.') dsOpsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex")) if mibBuilder.loadTexts: dsOpsEntry.setStatus('current') if mibBuilder.loadTexts: dsOpsEntry.setDescription(' Entry containing operations related statistics for a DS.') dsAnonymousBinds = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsAnonymousBinds.setStatus('current') if mibBuilder.loadTexts: dsAnonymousBinds.setDescription(' Number of anonymous binds to this DS from UAs since application start.') dsUnAuthBinds = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsUnAuthBinds.setStatus('current') if mibBuilder.loadTexts: dsUnAuthBinds.setDescription(' Number of un-authenticated binds to this DS since application start.') dsSimpleAuthBinds = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsSimpleAuthBinds.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 8.1.2.1.1. and, RFC1777 Section 4.1') if mibBuilder.loadTexts: dsSimpleAuthBinds.setStatus('current') if mibBuilder.loadTexts: dsSimpleAuthBinds.setDescription(' Number of binds to this DS that were authenticated using simple authentication procedures since application start.') dsStrongAuthBinds = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsStrongAuthBinds.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Sections 8.1.2.1.2 & 8.1.2.1.3. and, RFC1777 Section 4.1.') if mibBuilder.loadTexts: dsStrongAuthBinds.setStatus('current') if mibBuilder.loadTexts: dsStrongAuthBinds.setDescription(' Number of binds to this DS that were authenticated using the strong authentication procedures since application start. This includes the binds that were authenticated using external authentication procedures.') dsBindSecurityErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsBindSecurityErrors.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 12.7.2 and, RFC1777 Section 4.') if mibBuilder.loadTexts: dsBindSecurityErrors.setStatus('current') if mibBuilder.loadTexts: dsBindSecurityErrors.setDescription(' Number of bind operations that have been rejected by this DS due to inappropriateAuthentication or invalidCredentials.') dsInOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsInOps.setStatus('current') if mibBuilder.loadTexts: dsInOps.setDescription(' Number of operations forwarded to this DS from UAs or other DSs since application start up.') dsReadOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsReadOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 9.1.') if mibBuilder.loadTexts: dsReadOps.setStatus('current') if mibBuilder.loadTexts: dsReadOps.setDescription(' Number of read operations serviced by this DS since application startup.') dsCompareOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsCompareOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 9.2. and, RFC1777 section 4.8') if mibBuilder.loadTexts: dsCompareOps.setStatus('current') if mibBuilder.loadTexts: dsCompareOps.setDescription(' Number of compare operations serviced by this DS since application startup.') dsAddEntryOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsAddEntryOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.1. and, RFC1777 Section 4.5.') if mibBuilder.loadTexts: dsAddEntryOps.setStatus('current') if mibBuilder.loadTexts: dsAddEntryOps.setDescription(' Number of addEntry operations serviced by this DS since application startup.') dsRemoveEntryOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsRemoveEntryOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.2. and, RFC1777 Section 4.6.') if mibBuilder.loadTexts: dsRemoveEntryOps.setStatus('current') if mibBuilder.loadTexts: dsRemoveEntryOps.setDescription(' Number of removeEntry operations serviced by this DS since application startup.') dsModifyEntryOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 11), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsModifyEntryOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.3. and, RFC1777 Section 4.4.') if mibBuilder.loadTexts: dsModifyEntryOps.setStatus('current') if mibBuilder.loadTexts: dsModifyEntryOps.setDescription(' Number of modifyEntry operations serviced by this DS since application startup.') dsModifyRDNOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 12), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsModifyRDNOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.4.and, RFC1777 Section 4.7') if mibBuilder.loadTexts: dsModifyRDNOps.setStatus('current') if mibBuilder.loadTexts: dsModifyRDNOps.setDescription(' Number of modifyRDN operations serviced by this DS since application startup.') dsListOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 13), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsListOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.1.') if mibBuilder.loadTexts: dsListOps.setStatus('current') if mibBuilder.loadTexts: dsListOps.setDescription(' Number of list operations serviced by this DS since application startup.') dsSearchOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 14), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsSearchOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.2. and, RFC1777 Section 4.3.') if mibBuilder.loadTexts: dsSearchOps.setStatus('current') if mibBuilder.loadTexts: dsSearchOps.setDescription(' Number of search operations- baseObject searches, oneLevel searches and wholeSubtree searches, serviced by this DS since application startup.') dsOneLevelSearchOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 15), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsOneLevelSearchOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.2.2.2. and, RFC1777 Section 4.3.') if mibBuilder.loadTexts: dsOneLevelSearchOps.setStatus('current') if mibBuilder.loadTexts: dsOneLevelSearchOps.setDescription(' Number of oneLevel search operations serviced by this DS since application startup.') dsWholeSubtreeSearchOps = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 16), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsWholeSubtreeSearchOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.2.2.2. and, RFC1777 Section 4.3.') if mibBuilder.loadTexts: dsWholeSubtreeSearchOps.setStatus('current') if mibBuilder.loadTexts: dsWholeSubtreeSearchOps.setDescription(' Number of wholeSubtree search operations serviced by this DS since application startup.') dsReferrals = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 17), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsReferrals.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 12.6.') if mibBuilder.loadTexts: dsReferrals.setStatus('current') if mibBuilder.loadTexts: dsReferrals.setDescription(' Number of referrals returned by this DS in response to requests for operations since application startup.') dsChainings = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 18), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsChainings.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.518, 1988: Section 14.') if mibBuilder.loadTexts: dsChainings.setStatus('current') if mibBuilder.loadTexts: dsChainings.setDescription(' Number of operations forwarded by this DS to other DSs since application startup.') dsSecurityErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 19), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsSecurityErrors.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 12.7. and, RFC1777 Section 4.') if mibBuilder.loadTexts: dsSecurityErrors.setStatus('current') if mibBuilder.loadTexts: dsSecurityErrors.setDescription(' Number of operations forwarded to this DS which did not meet the security requirements. ') dsErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 20), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsErrors.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Sections 12.4, 12.5, 12.8 & 12.9. and, RFC1777 Section 4.') if mibBuilder.loadTexts: dsErrors.setStatus('current') if mibBuilder.loadTexts: dsErrors.setDescription(' Number of operations that could not be serviced due to errors other than security errors, and referrals. A partially serviced operation will not be counted as an error. The errors include NameErrors, UpdateErrors, Attribute errors and ServiceErrors.') dsEntriesTable = MibTable((1, 3, 6, 1, 4, 1, 1450, 7, 2), ) if mibBuilder.loadTexts: dsEntriesTable.setStatus('current') if mibBuilder.loadTexts: dsEntriesTable.setDescription(' The table holding information related to the entry statistics and cache performance of the DSs.') dsEntriesEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex")) if mibBuilder.loadTexts: dsEntriesEntry.setStatus('current') if mibBuilder.loadTexts: dsEntriesEntry.setDescription(' Entry containing statistics pertaining to entries held by a DS.') dsMasterEntries = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 1), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsMasterEntries.setStatus('current') if mibBuilder.loadTexts: dsMasterEntries.setDescription(' Number of entries mastered in the DS.') dsCopyEntries = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 2), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsCopyEntries.setStatus('current') if mibBuilder.loadTexts: dsCopyEntries.setDescription(' Number of entries for which systematic (slave) copies are maintained in the DS.') dsCacheEntries = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsCacheEntries.setStatus('current') if mibBuilder.loadTexts: dsCacheEntries.setDescription(' Number of entries cached (non-systematic copies) in the DS. This will include the entries that are cached partially. The negative cache is not counted.') dsCacheHits = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsCacheHits.setStatus('current') if mibBuilder.loadTexts: dsCacheHits.setDescription(' Number of operations that were serviced from the locally held cache since application startup.') dsSlaveHits = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsSlaveHits.setStatus('current') if mibBuilder.loadTexts: dsSlaveHits.setDescription(' Number of operations that were serviced from the locally held object replications ( shadow entries) since application startup.') dsIntTable = MibTable((1, 3, 6, 1, 4, 1, 1450, 7, 3), ) if mibBuilder.loadTexts: dsIntTable.setStatus('current') if mibBuilder.loadTexts: dsIntTable.setDescription(' Each row of this table contains some details related to the history of the interaction of the monitored DSs with their respective peer DSs.') dsIntEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex"), (0, "NSLDAP-MIB", "dsIntIndex")) if mibBuilder.loadTexts: dsIntEntry.setStatus('current') if mibBuilder.loadTexts: dsIntEntry.setDescription(' Entry containing interaction details of a DS with a peer DS.') dsIntIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: dsIntIndex.setStatus('current') if mibBuilder.loadTexts: dsIntIndex.setDescription(' Together with applIndex it forms the unique key to identify the conceptual row which contains useful info on the (attempted) interaction between the DS (referred to by applIndex) and a peer DS.') dsName = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 2), DistinguishedName()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsName.setStatus('current') if mibBuilder.loadTexts: dsName.setDescription(' Distinguished Name of the peer DS to which this entry pertains.') dsTimeOfCreation = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 3), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsTimeOfCreation.setStatus('current') if mibBuilder.loadTexts: dsTimeOfCreation.setDescription(' The value of sysUpTime when this row was created. If the entry was created before the network management subsystem was initialized, this object will contain a value of zero.') dsTimeOfLastAttempt = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 4), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsTimeOfLastAttempt.setStatus('current') if mibBuilder.loadTexts: dsTimeOfLastAttempt.setDescription(' The value of sysUpTime when the last attempt was made to contact this DS. If the last attempt was made before the network management subsystem was initialized, this object will contain a value of zero.') dsTimeOfLastSuccess = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 5), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsTimeOfLastSuccess.setStatus('current') if mibBuilder.loadTexts: dsTimeOfLastSuccess.setDescription(' The value of sysUpTime when the last attempt made to contact this DS was successful. If there have been no successful attempts this entry will have a value of zero. If the last successful attempt was made before the network management subsystem was initialized, this object will contain a value of zero.') dsFailuresSinceLastSuccess = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsFailuresSinceLastSuccess.setStatus('current') if mibBuilder.loadTexts: dsFailuresSinceLastSuccess.setDescription(' The number of failures since the last time an attempt to contact this DS was successful. If there has been no successful attempts, this counter will contain the number of failures since this entry was created.') dsFailures = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsFailures.setStatus('current') if mibBuilder.loadTexts: dsFailures.setDescription(' Cumulative failures since the creation of this entry.') dsSuccesses = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsSuccesses.setStatus('current') if mibBuilder.loadTexts: dsSuccesses.setDescription(' Cumulative successes since the creation of this entry.') dsURL = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 9), URLString()).setMaxAccess("readonly") if mibBuilder.loadTexts: dsURL.setStatus('current') if mibBuilder.loadTexts: dsURL.setDescription(' URL of the DS application.') dsEntityTable = MibTable((1, 3, 6, 1, 4, 1, 1450, 7, 5), ) if mibBuilder.loadTexts: dsEntityTable.setStatus('current') if mibBuilder.loadTexts: dsEntityTable.setDescription('This table holds general information related to an installed instance of a directory server') dsEntityEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1), ).setIndexNames((0, "NETWORK-SERVICES-MIB", "applIndex")) if mibBuilder.loadTexts: dsEntityEntry.setStatus('current') if mibBuilder.loadTexts: dsEntityEntry.setDescription('Entry of general information about an installed instance of a directory server') dsEntityDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: dsEntityDescr.setStatus('mandatory') if mibBuilder.loadTexts: dsEntityDescr.setDescription('A general textual description of this directory server.') dsEntityVers = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: dsEntityVers.setStatus('mandatory') if mibBuilder.loadTexts: dsEntityVers.setDescription('The version of this directory server') dsEntityOrg = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: dsEntityOrg.setStatus('mandatory') if mibBuilder.loadTexts: dsEntityOrg.setDescription('Organization responsible for directory server at this installation') dsEntityLocation = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: dsEntityLocation.setStatus('mandatory') if mibBuilder.loadTexts: dsEntityLocation.setDescription('Physical location of this entity (directory server). For example: hostname, building number, lab number, etc.') dsEntityContact = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: dsEntityContact.setStatus('mandatory') if mibBuilder.loadTexts: dsEntityContact.setDescription('Contact person(s)responsible for the directory server at this installation, together with information on how to conact.') dsEntityName = MibTableColumn((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: dsEntityName.setStatus('mandatory') if mibBuilder.loadTexts: dsEntityName.setDescription('Name assigned to this entity at the installation site') nsDirectoryServerDown = NotificationType((1, 3, 6, 1, 4, 1, 1450) + (0,7001)).setObjects(("NSLDAP-MIB", "dsEntityDescr"), ("NSLDAP-MIB", "dsEntityVers"), ("NSLDAP-MIB", "dsEntityLocation"), ("NSLDAP-MIB", "dsEntityContact")) if mibBuilder.loadTexts: nsDirectoryServerDown.setDescription('This trap is generated whenever the agent detects the directory server to be (potentially) Down.') nsDirectoryServerStart = NotificationType((1, 3, 6, 1, 4, 1, 1450) + (0,7002)).setObjects(("NSLDAP-MIB", "dsEntityDescr"), ("NSLDAP-MIB", "dsEntityVers"), ("NSLDAP-MIB", "dsEntityLocation")) if mibBuilder.loadTexts: nsDirectoryServerStart.setDescription('This trap is generated whenever the agent detects the directory server to have (re)started.') mibBuilder.exportSymbols("NSLDAP-MIB", dsEntityTable=dsEntityTable, dsSuccesses=dsSuccesses, dsOpsTable=dsOpsTable, dsAnonymousBinds=dsAnonymousBinds, dsReadOps=dsReadOps, dsOpsEntry=dsOpsEntry, dsErrors=dsErrors, nsDirectoryServerDown=nsDirectoryServerDown, dsSimpleAuthBinds=dsSimpleAuthBinds, netscape=netscape, nsDirectoryServerStart=nsDirectoryServerStart, dsEntriesTable=dsEntriesTable, dsSearchOps=dsSearchOps, dsModifyEntryOps=dsModifyEntryOps, dsEntityVers=dsEntityVers, dsFailures=dsFailures, dsOneLevelSearchOps=dsOneLevelSearchOps, dsSecurityErrors=dsSecurityErrors, dsMasterEntries=dsMasterEntries, dsChainings=dsChainings, dsEntityName=dsEntityName, dsBindSecurityErrors=dsBindSecurityErrors, dsCacheEntries=dsCacheEntries, dsInOps=dsInOps, dsCompareOps=dsCompareOps, dsRemoveEntryOps=dsRemoveEntryOps, dsWholeSubtreeSearchOps=dsWholeSubtreeSearchOps, dsReferrals=dsReferrals, dsEntityOrg=dsEntityOrg, dsSlaveHits=dsSlaveHits, dsName=dsName, dsListOps=dsListOps, dsModifyRDNOps=dsModifyRDNOps, dsTimeOfLastAttempt=dsTimeOfLastAttempt, nsldap=nsldap, dsEntityLocation=dsEntityLocation, dsURL=dsURL, dsEntityEntry=dsEntityEntry, dsIntTable=dsIntTable, PYSNMP_MODULE_ID=nsldap, dsCacheHits=dsCacheHits, dsIntIndex=dsIntIndex, dsFailuresSinceLastSuccess=dsFailuresSinceLastSuccess, dsStrongAuthBinds=dsStrongAuthBinds, dsTimeOfLastSuccess=dsTimeOfLastSuccess, dsEntityContact=dsEntityContact, dsAddEntryOps=dsAddEntryOps, dsTimeOfCreation=dsTimeOfCreation, dsEntityDescr=dsEntityDescr, dsCopyEntries=dsCopyEntries, dsIntEntry=dsIntEntry, dsUnAuthBinds=dsUnAuthBinds, dsEntriesEntry=dsEntriesEntry)
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, constraints_union, value_size_constraint, value_range_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueSizeConstraint', 'ValueRangeConstraint', 'SingleValueConstraint') (url_string, distinguished_name, appl_index) = mibBuilder.importSymbols('NETWORK-SERVICES-MIB', 'URLString', 'DistinguishedName', 'applIndex') (object_group, module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ObjectGroup', 'ModuleCompliance', 'NotificationGroup') (iso, notification_type, integer32, counter32, object_identity, module_identity, counter64, gauge32, unsigned32, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, bits, mib_identifier, time_ticks, enterprises, ip_address) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'NotificationType', 'Integer32', 'Counter32', 'ObjectIdentity', 'ModuleIdentity', 'Counter64', 'Gauge32', 'Unsigned32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'Bits', 'MibIdentifier', 'TimeTicks', 'enterprises', 'IpAddress') (display_string, time_stamp, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TimeStamp', 'TextualConvention') netscape = mib_identifier((1, 3, 6, 1, 4, 1, 1450)) nsldap = module_identity((1, 3, 6, 1, 4, 1, 1450, 7)) if mibBuilder.loadTexts: nsldap.setLastUpdated('9707310000Z') if mibBuilder.loadTexts: nsldap.setOrganization('Netscape Communications Corp') if mibBuilder.loadTexts: nsldap.setContactInfo(' Frank Chen Postal: Netscape Communications Corp 501 East Middlefield Rd Mountain View, CA 94043 Tel: (415) 937 - 3703 Fax: (415) 937 - 4164 E-mail: frank@netscape.com') if mibBuilder.loadTexts: nsldap.setDescription(' An implementation of the MADMAN mib for monitoring LDAP/CLDAP and X.500 directories described in internet draft: draft-ietf-madman-ds-mib-103.txt used for iPlanet Directory Server 5') ds_ops_table = mib_table((1, 3, 6, 1, 4, 1, 1450, 7, 1)) if mibBuilder.loadTexts: dsOpsTable.setStatus('current') if mibBuilder.loadTexts: dsOpsTable.setDescription(' The table holding information related to the DS operations.') ds_ops_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1)).setIndexNames((0, 'NETWORK-SERVICES-MIB', 'applIndex')) if mibBuilder.loadTexts: dsOpsEntry.setStatus('current') if mibBuilder.loadTexts: dsOpsEntry.setDescription(' Entry containing operations related statistics for a DS.') ds_anonymous_binds = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 1), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsAnonymousBinds.setStatus('current') if mibBuilder.loadTexts: dsAnonymousBinds.setDescription(' Number of anonymous binds to this DS from UAs since application start.') ds_un_auth_binds = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 2), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsUnAuthBinds.setStatus('current') if mibBuilder.loadTexts: dsUnAuthBinds.setDescription(' Number of un-authenticated binds to this DS since application start.') ds_simple_auth_binds = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 3), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsSimpleAuthBinds.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 8.1.2.1.1. and, RFC1777 Section 4.1') if mibBuilder.loadTexts: dsSimpleAuthBinds.setStatus('current') if mibBuilder.loadTexts: dsSimpleAuthBinds.setDescription(' Number of binds to this DS that were authenticated using simple authentication procedures since application start.') ds_strong_auth_binds = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 4), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsStrongAuthBinds.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Sections 8.1.2.1.2 & 8.1.2.1.3. and, RFC1777 Section 4.1.') if mibBuilder.loadTexts: dsStrongAuthBinds.setStatus('current') if mibBuilder.loadTexts: dsStrongAuthBinds.setDescription(' Number of binds to this DS that were authenticated using the strong authentication procedures since application start. This includes the binds that were authenticated using external authentication procedures.') ds_bind_security_errors = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 5), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsBindSecurityErrors.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 12.7.2 and, RFC1777 Section 4.') if mibBuilder.loadTexts: dsBindSecurityErrors.setStatus('current') if mibBuilder.loadTexts: dsBindSecurityErrors.setDescription(' Number of bind operations that have been rejected by this DS due to inappropriateAuthentication or invalidCredentials.') ds_in_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 6), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsInOps.setStatus('current') if mibBuilder.loadTexts: dsInOps.setDescription(' Number of operations forwarded to this DS from UAs or other DSs since application start up.') ds_read_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 7), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsReadOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 9.1.') if mibBuilder.loadTexts: dsReadOps.setStatus('current') if mibBuilder.loadTexts: dsReadOps.setDescription(' Number of read operations serviced by this DS since application startup.') ds_compare_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 8), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsCompareOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 9.2. and, RFC1777 section 4.8') if mibBuilder.loadTexts: dsCompareOps.setStatus('current') if mibBuilder.loadTexts: dsCompareOps.setDescription(' Number of compare operations serviced by this DS since application startup.') ds_add_entry_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 9), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsAddEntryOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.1. and, RFC1777 Section 4.5.') if mibBuilder.loadTexts: dsAddEntryOps.setStatus('current') if mibBuilder.loadTexts: dsAddEntryOps.setDescription(' Number of addEntry operations serviced by this DS since application startup.') ds_remove_entry_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 10), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsRemoveEntryOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.2. and, RFC1777 Section 4.6.') if mibBuilder.loadTexts: dsRemoveEntryOps.setStatus('current') if mibBuilder.loadTexts: dsRemoveEntryOps.setDescription(' Number of removeEntry operations serviced by this DS since application startup.') ds_modify_entry_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 11), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsModifyEntryOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.3. and, RFC1777 Section 4.4.') if mibBuilder.loadTexts: dsModifyEntryOps.setStatus('current') if mibBuilder.loadTexts: dsModifyEntryOps.setDescription(' Number of modifyEntry operations serviced by this DS since application startup.') ds_modify_rdn_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 12), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsModifyRDNOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 11.4.and, RFC1777 Section 4.7') if mibBuilder.loadTexts: dsModifyRDNOps.setStatus('current') if mibBuilder.loadTexts: dsModifyRDNOps.setDescription(' Number of modifyRDN operations serviced by this DS since application startup.') ds_list_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 13), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsListOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.1.') if mibBuilder.loadTexts: dsListOps.setStatus('current') if mibBuilder.loadTexts: dsListOps.setDescription(' Number of list operations serviced by this DS since application startup.') ds_search_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 14), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsSearchOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.2. and, RFC1777 Section 4.3.') if mibBuilder.loadTexts: dsSearchOps.setStatus('current') if mibBuilder.loadTexts: dsSearchOps.setDescription(' Number of search operations- baseObject searches, oneLevel searches and wholeSubtree searches, serviced by this DS since application startup.') ds_one_level_search_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 15), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsOneLevelSearchOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.2.2.2. and, RFC1777 Section 4.3.') if mibBuilder.loadTexts: dsOneLevelSearchOps.setStatus('current') if mibBuilder.loadTexts: dsOneLevelSearchOps.setDescription(' Number of oneLevel search operations serviced by this DS since application startup.') ds_whole_subtree_search_ops = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 16), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsWholeSubtreeSearchOps.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 10.2.2.2. and, RFC1777 Section 4.3.') if mibBuilder.loadTexts: dsWholeSubtreeSearchOps.setStatus('current') if mibBuilder.loadTexts: dsWholeSubtreeSearchOps.setDescription(' Number of wholeSubtree search operations serviced by this DS since application startup.') ds_referrals = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 17), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsReferrals.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 12.6.') if mibBuilder.loadTexts: dsReferrals.setStatus('current') if mibBuilder.loadTexts: dsReferrals.setDescription(' Number of referrals returned by this DS in response to requests for operations since application startup.') ds_chainings = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 18), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsChainings.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.518, 1988: Section 14.') if mibBuilder.loadTexts: dsChainings.setStatus('current') if mibBuilder.loadTexts: dsChainings.setDescription(' Number of operations forwarded by this DS to other DSs since application startup.') ds_security_errors = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 19), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsSecurityErrors.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Section 12.7. and, RFC1777 Section 4.') if mibBuilder.loadTexts: dsSecurityErrors.setStatus('current') if mibBuilder.loadTexts: dsSecurityErrors.setDescription(' Number of operations forwarded to this DS which did not meet the security requirements. ') ds_errors = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 1, 1, 20), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsErrors.setReference(' CCITT Blue Book Fascicle VIII.8 - Rec. X.511, 1988: Sections 12.4, 12.5, 12.8 & 12.9. and, RFC1777 Section 4.') if mibBuilder.loadTexts: dsErrors.setStatus('current') if mibBuilder.loadTexts: dsErrors.setDescription(' Number of operations that could not be serviced due to errors other than security errors, and referrals. A partially serviced operation will not be counted as an error. The errors include NameErrors, UpdateErrors, Attribute errors and ServiceErrors.') ds_entries_table = mib_table((1, 3, 6, 1, 4, 1, 1450, 7, 2)) if mibBuilder.loadTexts: dsEntriesTable.setStatus('current') if mibBuilder.loadTexts: dsEntriesTable.setDescription(' The table holding information related to the entry statistics and cache performance of the DSs.') ds_entries_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1)).setIndexNames((0, 'NETWORK-SERVICES-MIB', 'applIndex')) if mibBuilder.loadTexts: dsEntriesEntry.setStatus('current') if mibBuilder.loadTexts: dsEntriesEntry.setDescription(' Entry containing statistics pertaining to entries held by a DS.') ds_master_entries = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 1), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsMasterEntries.setStatus('current') if mibBuilder.loadTexts: dsMasterEntries.setDescription(' Number of entries mastered in the DS.') ds_copy_entries = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 2), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsCopyEntries.setStatus('current') if mibBuilder.loadTexts: dsCopyEntries.setDescription(' Number of entries for which systematic (slave) copies are maintained in the DS.') ds_cache_entries = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 3), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsCacheEntries.setStatus('current') if mibBuilder.loadTexts: dsCacheEntries.setDescription(' Number of entries cached (non-systematic copies) in the DS. This will include the entries that are cached partially. The negative cache is not counted.') ds_cache_hits = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 4), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsCacheHits.setStatus('current') if mibBuilder.loadTexts: dsCacheHits.setDescription(' Number of operations that were serviced from the locally held cache since application startup.') ds_slave_hits = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 2, 1, 5), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsSlaveHits.setStatus('current') if mibBuilder.loadTexts: dsSlaveHits.setDescription(' Number of operations that were serviced from the locally held object replications ( shadow entries) since application startup.') ds_int_table = mib_table((1, 3, 6, 1, 4, 1, 1450, 7, 3)) if mibBuilder.loadTexts: dsIntTable.setStatus('current') if mibBuilder.loadTexts: dsIntTable.setDescription(' Each row of this table contains some details related to the history of the interaction of the monitored DSs with their respective peer DSs.') ds_int_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1)).setIndexNames((0, 'NETWORK-SERVICES-MIB', 'applIndex'), (0, 'NSLDAP-MIB', 'dsIntIndex')) if mibBuilder.loadTexts: dsIntEntry.setStatus('current') if mibBuilder.loadTexts: dsIntEntry.setDescription(' Entry containing interaction details of a DS with a peer DS.') ds_int_index = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))) if mibBuilder.loadTexts: dsIntIndex.setStatus('current') if mibBuilder.loadTexts: dsIntIndex.setDescription(' Together with applIndex it forms the unique key to identify the conceptual row which contains useful info on the (attempted) interaction between the DS (referred to by applIndex) and a peer DS.') ds_name = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 2), distinguished_name()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsName.setStatus('current') if mibBuilder.loadTexts: dsName.setDescription(' Distinguished Name of the peer DS to which this entry pertains.') ds_time_of_creation = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 3), time_stamp()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsTimeOfCreation.setStatus('current') if mibBuilder.loadTexts: dsTimeOfCreation.setDescription(' The value of sysUpTime when this row was created. If the entry was created before the network management subsystem was initialized, this object will contain a value of zero.') ds_time_of_last_attempt = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 4), time_stamp()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsTimeOfLastAttempt.setStatus('current') if mibBuilder.loadTexts: dsTimeOfLastAttempt.setDescription(' The value of sysUpTime when the last attempt was made to contact this DS. If the last attempt was made before the network management subsystem was initialized, this object will contain a value of zero.') ds_time_of_last_success = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 5), time_stamp()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsTimeOfLastSuccess.setStatus('current') if mibBuilder.loadTexts: dsTimeOfLastSuccess.setDescription(' The value of sysUpTime when the last attempt made to contact this DS was successful. If there have been no successful attempts this entry will have a value of zero. If the last successful attempt was made before the network management subsystem was initialized, this object will contain a value of zero.') ds_failures_since_last_success = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 6), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsFailuresSinceLastSuccess.setStatus('current') if mibBuilder.loadTexts: dsFailuresSinceLastSuccess.setDescription(' The number of failures since the last time an attempt to contact this DS was successful. If there has been no successful attempts, this counter will contain the number of failures since this entry was created.') ds_failures = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 7), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsFailures.setStatus('current') if mibBuilder.loadTexts: dsFailures.setDescription(' Cumulative failures since the creation of this entry.') ds_successes = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 8), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsSuccesses.setStatus('current') if mibBuilder.loadTexts: dsSuccesses.setDescription(' Cumulative successes since the creation of this entry.') ds_url = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 3, 1, 9), url_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: dsURL.setStatus('current') if mibBuilder.loadTexts: dsURL.setDescription(' URL of the DS application.') ds_entity_table = mib_table((1, 3, 6, 1, 4, 1, 1450, 7, 5)) if mibBuilder.loadTexts: dsEntityTable.setStatus('current') if mibBuilder.loadTexts: dsEntityTable.setDescription('This table holds general information related to an installed instance of a directory server') ds_entity_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1)).setIndexNames((0, 'NETWORK-SERVICES-MIB', 'applIndex')) if mibBuilder.loadTexts: dsEntityEntry.setStatus('current') if mibBuilder.loadTexts: dsEntityEntry.setDescription('Entry of general information about an installed instance of a directory server') ds_entity_descr = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 1), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly') if mibBuilder.loadTexts: dsEntityDescr.setStatus('mandatory') if mibBuilder.loadTexts: dsEntityDescr.setDescription('A general textual description of this directory server.') ds_entity_vers = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly') if mibBuilder.loadTexts: dsEntityVers.setStatus('mandatory') if mibBuilder.loadTexts: dsEntityVers.setDescription('The version of this directory server') ds_entity_org = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 3), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly') if mibBuilder.loadTexts: dsEntityOrg.setStatus('mandatory') if mibBuilder.loadTexts: dsEntityOrg.setDescription('Organization responsible for directory server at this installation') ds_entity_location = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 4), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly') if mibBuilder.loadTexts: dsEntityLocation.setStatus('mandatory') if mibBuilder.loadTexts: dsEntityLocation.setDescription('Physical location of this entity (directory server). For example: hostname, building number, lab number, etc.') ds_entity_contact = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 5), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly') if mibBuilder.loadTexts: dsEntityContact.setStatus('mandatory') if mibBuilder.loadTexts: dsEntityContact.setDescription('Contact person(s)responsible for the directory server at this installation, together with information on how to conact.') ds_entity_name = mib_table_column((1, 3, 6, 1, 4, 1, 1450, 7, 5, 1, 6), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly') if mibBuilder.loadTexts: dsEntityName.setStatus('mandatory') if mibBuilder.loadTexts: dsEntityName.setDescription('Name assigned to this entity at the installation site') ns_directory_server_down = notification_type((1, 3, 6, 1, 4, 1, 1450) + (0, 7001)).setObjects(('NSLDAP-MIB', 'dsEntityDescr'), ('NSLDAP-MIB', 'dsEntityVers'), ('NSLDAP-MIB', 'dsEntityLocation'), ('NSLDAP-MIB', 'dsEntityContact')) if mibBuilder.loadTexts: nsDirectoryServerDown.setDescription('This trap is generated whenever the agent detects the directory server to be (potentially) Down.') ns_directory_server_start = notification_type((1, 3, 6, 1, 4, 1, 1450) + (0, 7002)).setObjects(('NSLDAP-MIB', 'dsEntityDescr'), ('NSLDAP-MIB', 'dsEntityVers'), ('NSLDAP-MIB', 'dsEntityLocation')) if mibBuilder.loadTexts: nsDirectoryServerStart.setDescription('This trap is generated whenever the agent detects the directory server to have (re)started.') mibBuilder.exportSymbols('NSLDAP-MIB', dsEntityTable=dsEntityTable, dsSuccesses=dsSuccesses, dsOpsTable=dsOpsTable, dsAnonymousBinds=dsAnonymousBinds, dsReadOps=dsReadOps, dsOpsEntry=dsOpsEntry, dsErrors=dsErrors, nsDirectoryServerDown=nsDirectoryServerDown, dsSimpleAuthBinds=dsSimpleAuthBinds, netscape=netscape, nsDirectoryServerStart=nsDirectoryServerStart, dsEntriesTable=dsEntriesTable, dsSearchOps=dsSearchOps, dsModifyEntryOps=dsModifyEntryOps, dsEntityVers=dsEntityVers, dsFailures=dsFailures, dsOneLevelSearchOps=dsOneLevelSearchOps, dsSecurityErrors=dsSecurityErrors, dsMasterEntries=dsMasterEntries, dsChainings=dsChainings, dsEntityName=dsEntityName, dsBindSecurityErrors=dsBindSecurityErrors, dsCacheEntries=dsCacheEntries, dsInOps=dsInOps, dsCompareOps=dsCompareOps, dsRemoveEntryOps=dsRemoveEntryOps, dsWholeSubtreeSearchOps=dsWholeSubtreeSearchOps, dsReferrals=dsReferrals, dsEntityOrg=dsEntityOrg, dsSlaveHits=dsSlaveHits, dsName=dsName, dsListOps=dsListOps, dsModifyRDNOps=dsModifyRDNOps, dsTimeOfLastAttempt=dsTimeOfLastAttempt, nsldap=nsldap, dsEntityLocation=dsEntityLocation, dsURL=dsURL, dsEntityEntry=dsEntityEntry, dsIntTable=dsIntTable, PYSNMP_MODULE_ID=nsldap, dsCacheHits=dsCacheHits, dsIntIndex=dsIntIndex, dsFailuresSinceLastSuccess=dsFailuresSinceLastSuccess, dsStrongAuthBinds=dsStrongAuthBinds, dsTimeOfLastSuccess=dsTimeOfLastSuccess, dsEntityContact=dsEntityContact, dsAddEntryOps=dsAddEntryOps, dsTimeOfCreation=dsTimeOfCreation, dsEntityDescr=dsEntityDescr, dsCopyEntries=dsCopyEntries, dsIntEntry=dsIntEntry, dsUnAuthBinds=dsUnAuthBinds, dsEntriesEntry=dsEntriesEntry)
def deleteDigit(n): n = str(n) return max([int(n[:index] + n[index + 1:]) for index in range(len(n))]) print(deleteDigit(152))
def delete_digit(n): n = str(n) return max([int(n[:index] + n[index + 1:]) for index in range(len(n))]) print(delete_digit(152))
name = 'tinymce' authors = 'Joost Cassee' version = 'trunk' release = version
name = 'tinymce' authors = 'Joost Cassee' version = 'trunk' release = version
# # PySNMP MIB module PPVPN-TC (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PPVPN-TC # Produced by pysmi-0.3.4 at Mon Apr 29 20:33:05 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion", "SingleValueConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Integer32, IpAddress, Gauge32, Unsigned32, ModuleIdentity, Bits, Counter64, Counter32, MibIdentifier, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, ObjectIdentity, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "IpAddress", "Gauge32", "Unsigned32", "ModuleIdentity", "Bits", "Counter64", "Counter32", "MibIdentifier", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "ObjectIdentity", "NotificationType") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") class VPNId(TextualConvention, OctetString): reference = "RFC 2685, Fox & Gleeson, 'Virtual Private Networks Identifier', September 1999." status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 7) mibBuilder.exportSymbols("PPVPN-TC", VPNId=VPNId)
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_range_constraint, value_size_constraint, constraints_union, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ValueSizeConstraint', 'ConstraintsUnion', 'SingleValueConstraint') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (integer32, ip_address, gauge32, unsigned32, module_identity, bits, counter64, counter32, mib_identifier, time_ticks, mib_scalar, mib_table, mib_table_row, mib_table_column, iso, object_identity, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'IpAddress', 'Gauge32', 'Unsigned32', 'ModuleIdentity', 'Bits', 'Counter64', 'Counter32', 'MibIdentifier', 'TimeTicks', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'iso', 'ObjectIdentity', 'NotificationType') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') class Vpnid(TextualConvention, OctetString): reference = "RFC 2685, Fox & Gleeson, 'Virtual Private Networks Identifier', September 1999." status = 'current' subtype_spec = OctetString.subtypeSpec + value_size_constraint(0, 7) mibBuilder.exportSymbols('PPVPN-TC', VPNId=VPNId)
with open('../input.txt','rt') as f: lst = set(map(int,f.readlines())) for x in lst: if 2020-x in lst: print(x*(2020-x))
with open('../input.txt', 'rt') as f: lst = set(map(int, f.readlines())) for x in lst: if 2020 - x in lst: print(x * (2020 - x))
print("Calculator has started") while True: a = float(input("Enter first number ")) b = float(input("Enter second number ")) chooseop=1 while (chooseop == 1) | (chooseop == 2) | (chooseop == 3) | (chooseop == 4): chooseop = int(input("Enter 1 for addition, 2 for subtraction, 3 for multiplication and 4 for division ")) print(chooseop) if chooseop == 1: print(a+b) break elif chooseop == 2: print(a-b) break elif chooseop == 3: print(a*b) break elif chooseop == 4: if b == 0: print("Can't divide by zero") else: print(a/b) break elif (chooseop != 1) & (chooseop != 2) & (chooseop != 3) & (chooseop != 4): print("Invalid operation number")
print('Calculator has started') while True: a = float(input('Enter first number ')) b = float(input('Enter second number ')) chooseop = 1 while (chooseop == 1) | (chooseop == 2) | (chooseop == 3) | (chooseop == 4): chooseop = int(input('Enter 1 for addition, 2 for subtraction, 3 for multiplication and 4 for division ')) print(chooseop) if chooseop == 1: print(a + b) break elif chooseop == 2: print(a - b) break elif chooseop == 3: print(a * b) break elif chooseop == 4: if b == 0: print("Can't divide by zero") else: print(a / b) break elif (chooseop != 1) & (chooseop != 2) & (chooseop != 3) & (chooseop != 4): print('Invalid operation number')
class node: def __init__(self,value=None): self.value=value self.left_child=None self.right_child=None self.parent=None # pointer to parent node in tree self.height=1 # height of node in tree (max dist. to leaf) NEW FOR AVL class AVLTree: def __init__(self): self.root=None def __repr__(self): if self.root==None: return '' content='\n' # to hold final string cur_nodes=[self.root] # all nodes at current level cur_height=self.root.height # height of nodes at current level sep=' '*(2**(cur_height-1)) # variable sized separator between elements while True: cur_height+=-1 # decrement current height if len(cur_nodes)==0: break cur_row=' ' next_row='' next_nodes=[] if all(n is None for n in cur_nodes): break for n in cur_nodes: if n==None: cur_row+=' '+sep next_row+=' '+sep next_nodes.extend([None,None]) continue if n.value!=None: buf=' '*int((5-len(str(n.value)))/2) cur_row+='%s%s%s'%(buf,str(n.value),buf)+sep else: cur_row+=' '*5+sep if n.left_child!=None: next_nodes.append(n.left_child) next_row+=' /'+sep else: next_row+=' '+sep next_nodes.append(None) if n.right_child!=None: next_nodes.append(n.right_child) next_row+='\ '+sep else: next_row+=' '+sep next_nodes.append(None) content+=(cur_height*' '+cur_row+'\n'+cur_height*' '+next_row+'\n') cur_nodes=next_nodes sep=' '*int(len(sep)/2) # cut separator size in half return content def insert(self,value): if self.root==None: self.root=node(value) else: self._insert(value,self.root) def _insert(self,value,cur_node): if value<cur_node.value: if cur_node.left_child==None: cur_node.left_child=node(value) cur_node.left_child.parent=cur_node # set parent self._inspect_insertion(cur_node.left_child) else: self._insert(value,cur_node.left_child) elif value>cur_node.value: if cur_node.right_child==None: cur_node.right_child=node(value) cur_node.right_child.parent=cur_node # set parent self._inspect_insertion(cur_node.right_child) else: self._insert(value,cur_node.right_child) else: print("Value already in tree!") def print_tree(self): if self.root!=None: self._print_tree(self.root) def _print_tree(self,cur_node): if cur_node!=None: self._print_tree(cur_node.left_child) print ('%s, h=%d'%(str(cur_node.value),cur_node.height)) self._print_tree(cur_node.right_child) def height(self): if self.root!=None: return self._height(self.root,0) else: return 0 def _height(self,cur_node,cur_height): if cur_node==None: return cur_height left_height=self._height(cur_node.left_child,cur_height+1) right_height=self._height(cur_node.right_child,cur_height+1) return max(left_height,right_height) def find(self,value): if self.root!=None: return self._find(value,self.root) else: return None def _find(self,value,cur_node): if value==cur_node.value: return cur_node elif value<cur_node.value and cur_node.left_child!=None: return self._find(value,cur_node.left_child) elif value>cur_node.value and cur_node.right_child!=None: return self._find(value,cur_node.right_child) def delete_value(self,value): return self.delete_node(self.find(value)) def delete_node(self,node): ## ----- # Improvements since prior lesson # Protect against deleting a node not found in the tree if node==None or self.find(node.value)==None: print("Node to be deleted not found in the tree!") return None ## ----- # returns the node with min value in tree rooted at input node def min_value_node(n): current=n while current.left_child!=None: current=current.left_child return current # returns the number of children for the specified node def num_children(n): num_children=0 if n.left_child!=None: num_children+=1 if n.right_child!=None: num_children+=1 return num_children # get the parent of the node to be deleted node_parent=node.parent # get the number of children of the node to be deleted node_children=num_children(node) # break operation into different cases based on the # structure of the tree & node to be deleted # CASE 1 (node has no children) if node_children==0: if node_parent!=None: # remove reference to the node from the parent if node_parent.left_child==node: node_parent.left_child=None else: node_parent.right_child=None else: self.root=None # CASE 2 (node has a single child) if node_children==1: # get the single child node if node.left_child!=None: child=node.left_child else: child=node.right_child if node_parent!=None: # replace the node to be deleted with its child if node_parent.left_child==node: node_parent.left_child=child else: node_parent.right_child=child else: self.root=child # correct the parent pointer in node child.parent=node_parent # CASE 3 (node has two children) if node_children==2: # get the inorder successor of the deleted node successor=min_value_node(node.right_child) # copy the inorder successor's value to the node formerly # holding the value we wished to delete node.value=successor.value # delete the inorder successor now that it's value was # copied into the other node self.delete_node(successor) # exit function so we don't call the _inspect_deletion twice return if node_parent!=None: # fix the height of the parent of current node node_parent.height=1+max(self.get_height(node_parent.left_child),self.get_height(node_parent.right_child)) # begin to traverse back up the tree checking if there are # any sections which now invalidate the AVL balance rules self._inspect_deletion(node_parent) def search(self,value): if self.root!=None: return self._search(value,self.root) else: return False def _search(self,value,cur_node): if value==cur_node.value: return True elif value<cur_node.value and cur_node.left_child!=None: return self._search(value,cur_node.left_child) elif value>cur_node.value and cur_node.right_child!=None: return self._search(value,cur_node.right_child) return False # Functions added for AVL... def _inspect_insertion(self,cur_node,path=[]): if cur_node.parent==None: return path=[cur_node]+path left_height =self.get_height(cur_node.parent.left_child) right_height=self.get_height(cur_node.parent.right_child) if abs(left_height-right_height)>1: path=[cur_node.parent]+path self._rebalance_node(path[0],path[1],path[2]) return new_height=1+cur_node.height if new_height>cur_node.parent.height: cur_node.parent.height=new_height self._inspect_insertion(cur_node.parent,path) def _inspect_deletion(self,cur_node): if cur_node==None: return left_height =self.get_height(cur_node.left_child) right_height=self.get_height(cur_node.right_child) if abs(left_height-right_height)>1: y=self.taller_child(cur_node) x=self.taller_child(y) self._rebalance_node(cur_node,y,x) self._inspect_deletion(cur_node.parent) def _rebalance_node(self,z,y,x): if y==z.left_child and x==y.left_child: self._right_rotate(z) elif y==z.left_child and x==y.right_child: self._left_rotate(y) self._right_rotate(z) elif y==z.right_child and x==y.right_child: self._left_rotate(z) elif y==z.right_child and x==y.left_child: self._right_rotate(y) self._left_rotate(z) else: raise Exception('_rebalance_node: z,y,x node configuration not recognized!') def _right_rotate(self,z): sub_root=z.parent y=z.left_child t3=y.right_child y.right_child=z z.parent=y z.left_child=t3 if t3!=None: t3.parent=z y.parent=sub_root if y.parent==None: self.root=y else: if y.parent.left_child==z: y.parent.left_child=y else: y.parent.right_child=y z.height=1+max(self.get_height(z.left_child), self.get_height(z.right_child)) y.height=1+max(self.get_height(y.left_child), self.get_height(y.right_child)) def _left_rotate(self,z): sub_root=z.parent y=z.right_child t2=y.left_child y.left_child=z z.parent=y z.right_child=t2 if t2!=None: t2.parent=z y.parent=sub_root if y.parent==None: self.root=y else: if y.parent.left_child==z: y.parent.left_child=y else: y.parent.right_child=y z.height=1+max(self.get_height(z.left_child), self.get_height(z.right_child)) y.height=1+max(self.get_height(y.left_child), self.get_height(y.right_child)) def get_height(self,cur_node): if cur_node==None: return 0 return cur_node.height def taller_child(self,cur_node): left=self.get_height(cur_node.left_child) right=self.get_height(cur_node.right_child) return cur_node.left_child if left>=right else cur_node.right_child
class Node: def __init__(self, value=None): self.value = value self.left_child = None self.right_child = None self.parent = None self.height = 1 class Avltree: def __init__(self): self.root = None def __repr__(self): if self.root == None: return '' content = '\n' cur_nodes = [self.root] cur_height = self.root.height sep = ' ' * 2 ** (cur_height - 1) while True: cur_height += -1 if len(cur_nodes) == 0: break cur_row = ' ' next_row = '' next_nodes = [] if all((n is None for n in cur_nodes)): break for n in cur_nodes: if n == None: cur_row += ' ' + sep next_row += ' ' + sep next_nodes.extend([None, None]) continue if n.value != None: buf = ' ' * int((5 - len(str(n.value))) / 2) cur_row += '%s%s%s' % (buf, str(n.value), buf) + sep else: cur_row += ' ' * 5 + sep if n.left_child != None: next_nodes.append(n.left_child) next_row += ' /' + sep else: next_row += ' ' + sep next_nodes.append(None) if n.right_child != None: next_nodes.append(n.right_child) next_row += '\\ ' + sep else: next_row += ' ' + sep next_nodes.append(None) content += cur_height * ' ' + cur_row + '\n' + cur_height * ' ' + next_row + '\n' cur_nodes = next_nodes sep = ' ' * int(len(sep) / 2) return content def insert(self, value): if self.root == None: self.root = node(value) else: self._insert(value, self.root) def _insert(self, value, cur_node): if value < cur_node.value: if cur_node.left_child == None: cur_node.left_child = node(value) cur_node.left_child.parent = cur_node self._inspect_insertion(cur_node.left_child) else: self._insert(value, cur_node.left_child) elif value > cur_node.value: if cur_node.right_child == None: cur_node.right_child = node(value) cur_node.right_child.parent = cur_node self._inspect_insertion(cur_node.right_child) else: self._insert(value, cur_node.right_child) else: print('Value already in tree!') def print_tree(self): if self.root != None: self._print_tree(self.root) def _print_tree(self, cur_node): if cur_node != None: self._print_tree(cur_node.left_child) print('%s, h=%d' % (str(cur_node.value), cur_node.height)) self._print_tree(cur_node.right_child) def height(self): if self.root != None: return self._height(self.root, 0) else: return 0 def _height(self, cur_node, cur_height): if cur_node == None: return cur_height left_height = self._height(cur_node.left_child, cur_height + 1) right_height = self._height(cur_node.right_child, cur_height + 1) return max(left_height, right_height) def find(self, value): if self.root != None: return self._find(value, self.root) else: return None def _find(self, value, cur_node): if value == cur_node.value: return cur_node elif value < cur_node.value and cur_node.left_child != None: return self._find(value, cur_node.left_child) elif value > cur_node.value and cur_node.right_child != None: return self._find(value, cur_node.right_child) def delete_value(self, value): return self.delete_node(self.find(value)) def delete_node(self, node): if node == None or self.find(node.value) == None: print('Node to be deleted not found in the tree!') return None def min_value_node(n): current = n while current.left_child != None: current = current.left_child return current def num_children(n): num_children = 0 if n.left_child != None: num_children += 1 if n.right_child != None: num_children += 1 return num_children node_parent = node.parent node_children = num_children(node) if node_children == 0: if node_parent != None: if node_parent.left_child == node: node_parent.left_child = None else: node_parent.right_child = None else: self.root = None if node_children == 1: if node.left_child != None: child = node.left_child else: child = node.right_child if node_parent != None: if node_parent.left_child == node: node_parent.left_child = child else: node_parent.right_child = child else: self.root = child child.parent = node_parent if node_children == 2: successor = min_value_node(node.right_child) node.value = successor.value self.delete_node(successor) return if node_parent != None: node_parent.height = 1 + max(self.get_height(node_parent.left_child), self.get_height(node_parent.right_child)) self._inspect_deletion(node_parent) def search(self, value): if self.root != None: return self._search(value, self.root) else: return False def _search(self, value, cur_node): if value == cur_node.value: return True elif value < cur_node.value and cur_node.left_child != None: return self._search(value, cur_node.left_child) elif value > cur_node.value and cur_node.right_child != None: return self._search(value, cur_node.right_child) return False def _inspect_insertion(self, cur_node, path=[]): if cur_node.parent == None: return path = [cur_node] + path left_height = self.get_height(cur_node.parent.left_child) right_height = self.get_height(cur_node.parent.right_child) if abs(left_height - right_height) > 1: path = [cur_node.parent] + path self._rebalance_node(path[0], path[1], path[2]) return new_height = 1 + cur_node.height if new_height > cur_node.parent.height: cur_node.parent.height = new_height self._inspect_insertion(cur_node.parent, path) def _inspect_deletion(self, cur_node): if cur_node == None: return left_height = self.get_height(cur_node.left_child) right_height = self.get_height(cur_node.right_child) if abs(left_height - right_height) > 1: y = self.taller_child(cur_node) x = self.taller_child(y) self._rebalance_node(cur_node, y, x) self._inspect_deletion(cur_node.parent) def _rebalance_node(self, z, y, x): if y == z.left_child and x == y.left_child: self._right_rotate(z) elif y == z.left_child and x == y.right_child: self._left_rotate(y) self._right_rotate(z) elif y == z.right_child and x == y.right_child: self._left_rotate(z) elif y == z.right_child and x == y.left_child: self._right_rotate(y) self._left_rotate(z) else: raise exception('_rebalance_node: z,y,x node configuration not recognized!') def _right_rotate(self, z): sub_root = z.parent y = z.left_child t3 = y.right_child y.right_child = z z.parent = y z.left_child = t3 if t3 != None: t3.parent = z y.parent = sub_root if y.parent == None: self.root = y elif y.parent.left_child == z: y.parent.left_child = y else: y.parent.right_child = y z.height = 1 + max(self.get_height(z.left_child), self.get_height(z.right_child)) y.height = 1 + max(self.get_height(y.left_child), self.get_height(y.right_child)) def _left_rotate(self, z): sub_root = z.parent y = z.right_child t2 = y.left_child y.left_child = z z.parent = y z.right_child = t2 if t2 != None: t2.parent = z y.parent = sub_root if y.parent == None: self.root = y elif y.parent.left_child == z: y.parent.left_child = y else: y.parent.right_child = y z.height = 1 + max(self.get_height(z.left_child), self.get_height(z.right_child)) y.height = 1 + max(self.get_height(y.left_child), self.get_height(y.right_child)) def get_height(self, cur_node): if cur_node == None: return 0 return cur_node.height def taller_child(self, cur_node): left = self.get_height(cur_node.left_child) right = self.get_height(cur_node.right_child) return cur_node.left_child if left >= right else cur_node.right_child
class Boid(): def __init__(self, x,y,width,height): self.position = Vector(x,y)
class Boid: def __init__(self, x, y, width, height): self.position = vector(x, y)
# Area of a Triangle print("Write a function that takes the base and height of a triangle and return its area.") def area(): base = float(int(input("Enter the Base of the Triangle : "))) height = float(int(input("Enter the height of the Triangle : "))) total_area = (base * height)/2 print(total_area) area() # Program not closed emmidately input("Please Click to Enter to End the Program ")
print('Write a function that takes the base and height of a triangle and return its area.') def area(): base = float(int(input('Enter the Base of the Triangle : '))) height = float(int(input('Enter the height of the Triangle : '))) total_area = base * height / 2 print(total_area) area() input('Please Click to Enter to End the Program ')