content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
## # This software was developed and / or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted data whose # export/transfer/disclosure is restricted by U.S. law. Dissemination # to non-U.S. persons whether in the United States or abroad requires # an export license or other authorization. # # Contractor Name: Raytheon Company # Contractor Address: 6825 Pine Street, Suite 340 # Mail Stop B8 # Omaha, NE 68106 # 402.291.0100 # # See the AWIPS II Master Rights File ("Master Rights File.pdf") for # further licensing information. ## # # Python wrapper for PointDataView # # # SOFTWARE HISTORY # # Date Ticket# Engineer Description # ------------ ---------- ----------- -------------------------- # 07/20/09 njensen Initial Creation. # # # ## # This is a base file that is not intended to be overridden. ## class PointDataView: def __init__(self, javaPointDataView): self.__javaPdv = javaPointDataView self.__keys = [] keyset = self.__javaPdv.getContainer().getParameters() itr = keyset.iterator() while itr.hasNext(): self.__keys.append(str(itr.next())) def __getitem__(self, key): result = None strValType = self.getType(key) if strValType == 'FLOAT': result = self.__javaPdv.getFloat(key) elif strValType == 'STRING': result = self.__javaPdv.getString(key) elif strValType == 'INT': result = self.__javaPdv.getInt(key) elif strValType == 'LONG': result = self.__javaPdv.getLong(key) return result def getType(self, key): val = self.__javaPdv.getType(key) if val: val = str(val) return val def has_key(self, key): return self.__keys.__contains__(key) def keys(self): return self.__keys def __contains__(self, key): return self.has_key(key) def getFillValue(self, key): # TODO if we get fill value support in pointdata, hook that up return -9999.0 def getNumberAllLevels(self, key): strValType = self.getType(key) jlevels = self.__javaPdv.getNumberAllLevels(key) levels = [] for level in jlevels: level = str(level) if strValType == 'FLOAT': levels.append(float(level)) elif strValType == 'STRING': levels.append(str(level)) elif strValType == 'INT': levels.append(int(level)) elif strValType == 'LONG': levels.append(long(level)) return levels
class Pointdataview: def __init__(self, javaPointDataView): self.__javaPdv = javaPointDataView self.__keys = [] keyset = self.__javaPdv.getContainer().getParameters() itr = keyset.iterator() while itr.hasNext(): self.__keys.append(str(itr.next())) def __getitem__(self, key): result = None str_val_type = self.getType(key) if strValType == 'FLOAT': result = self.__javaPdv.getFloat(key) elif strValType == 'STRING': result = self.__javaPdv.getString(key) elif strValType == 'INT': result = self.__javaPdv.getInt(key) elif strValType == 'LONG': result = self.__javaPdv.getLong(key) return result def get_type(self, key): val = self.__javaPdv.getType(key) if val: val = str(val) return val def has_key(self, key): return self.__keys.__contains__(key) def keys(self): return self.__keys def __contains__(self, key): return self.has_key(key) def get_fill_value(self, key): return -9999.0 def get_number_all_levels(self, key): str_val_type = self.getType(key) jlevels = self.__javaPdv.getNumberAllLevels(key) levels = [] for level in jlevels: level = str(level) if strValType == 'FLOAT': levels.append(float(level)) elif strValType == 'STRING': levels.append(str(level)) elif strValType == 'INT': levels.append(int(level)) elif strValType == 'LONG': levels.append(long(level)) return levels
def hypotenuse_triangle(side1, side2): hypotenuse = side1 ** 2 + side2 ** 2 return hypotenuse print(hypotenuse_triangle(2, 4))
def hypotenuse_triangle(side1, side2): hypotenuse = side1 ** 2 + side2 ** 2 return hypotenuse print(hypotenuse_triangle(2, 4))
# Tuplas sao imutaveis, nao se pode substituir um valor enquanto o programa estiver rodando # oq foi definido no inicio permanece ate o final lanche = ('hamburguer', 'pizza', 'suco', 'refri') print(lanche[1]) print(lanche[-1]) #-1 mostra o ultimo elemento print(sorted(lanche)) #para organizar a lista em ordem alfabetica porem nao vai mudar os iten for comida in lanche: print(f'comi bastante {comida}') # A variavel comida vai percorrer cada valor na lista lanche, vai pegar os nomes print('estou gordo') for cont in range(0, len(lanche)): print(cont) # vai pegar o endereco da lista (0,1,2...) por causa das () print('fim') for food in range(0, len(lanche)): print(lanche[food], f'na posicao {food}') # vai pegar na lista lanche o endereco food 0,1,2,3... print('end')
lanche = ('hamburguer', 'pizza', 'suco', 'refri') print(lanche[1]) print(lanche[-1]) print(sorted(lanche)) for comida in lanche: print(f'comi bastante {comida}') print('estou gordo') for cont in range(0, len(lanche)): print(cont) print('fim') for food in range(0, len(lanche)): print(lanche[food], f'na posicao {food}') print('end')
class Solution: def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ n = len(nums) zeroindex = -1 for i in range(n): if nums[i] == 0 and zeroindex == -1: zeroindex = i elif nums[i] != 0 and zeroindex != -1: nums[zeroindex] = nums[i] nums[i] = 0 zeroindex += 1 return nums if __name__ == '__main__': solution = Solution() print(solution.moveZeroes([3, 0, 1, 1, 2, 0, 5, 0, 2, 0, 4])); else: pass
class Solution: def move_zeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ n = len(nums) zeroindex = -1 for i in range(n): if nums[i] == 0 and zeroindex == -1: zeroindex = i elif nums[i] != 0 and zeroindex != -1: nums[zeroindex] = nums[i] nums[i] = 0 zeroindex += 1 return nums if __name__ == '__main__': solution = solution() print(solution.moveZeroes([3, 0, 1, 1, 2, 0, 5, 0, 2, 0, 4])) else: pass
# Time: O(m * n) # Space: O(1) class Solution(object): def shiftGrid(self, grid, k): """ :type grid: List[List[int]] :type k: int :rtype: List[List[int]] """ def rotate(grids, k): def reverse(grid, start, end): while start < end: start_r, start_c = divmod(start, len(grid[0])) end_r, end_c = divmod(end-1, len(grid[0])) grid[start_r][start_c], grid[end_r][end_c] = grid[end_r][end_c], grid[start_r][start_c] start += 1 end -= 1 k %= len(grid)*len(grid[0]) reverse(grid, 0, len(grid)*len(grid[0])) reverse(grid, 0, k) reverse(grid, k, len(grid)*len(grid[0])) rotate(grid, k) return grid
class Solution(object): def shift_grid(self, grid, k): """ :type grid: List[List[int]] :type k: int :rtype: List[List[int]] """ def rotate(grids, k): def reverse(grid, start, end): while start < end: (start_r, start_c) = divmod(start, len(grid[0])) (end_r, end_c) = divmod(end - 1, len(grid[0])) (grid[start_r][start_c], grid[end_r][end_c]) = (grid[end_r][end_c], grid[start_r][start_c]) start += 1 end -= 1 k %= len(grid) * len(grid[0]) reverse(grid, 0, len(grid) * len(grid[0])) reverse(grid, 0, k) reverse(grid, k, len(grid) * len(grid[0])) rotate(grid, k) return grid
FULL_ACCESS_GMAIL_SCOPE = "https://mail.google.com/" LABELS_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.labels" SEND_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send" READ_ONLY_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.readonly" COMPOSE_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.compose" INSERT_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.insert" MODIFY_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.modify" METADATA_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.metadata" SETTINGS_BASIC_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.settings.basic" SETTINGS_SHARING_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.settings.sharing"
full_access_gmail_scope = 'https://mail.google.com/' labels_gmail_scope = 'https://www.googleapis.com/auth/gmail.labels' send_gmail_scope = 'https://www.googleapis.com/auth/gmail.send' read_only_gmail_scope = 'https://www.googleapis.com/auth/gmail.readonly' compose_gmail_scope = 'https://www.googleapis.com/auth/gmail.compose' insert_gmail_scope = 'https://www.googleapis.com/auth/gmail.insert' modify_gmail_scope = 'https://www.googleapis.com/auth/gmail.modify' metadata_gmail_scope = 'https://www.googleapis.com/auth/gmail.metadata' settings_basic_gmail_scope = 'https://www.googleapis.com/auth/gmail.settings.basic' settings_sharing_gmail_scope = 'https://www.googleapis.com/auth/gmail.settings.sharing'
def read(): x = int(input()) return x a = read() b = read() c = read() d = read() if b == c and b + c == d and b + c + d == a: print("S") else: print("N")
def read(): x = int(input()) return x a = read() b = read() c = read() d = read() if b == c and b + c == d and (b + c + d == a): print('S') else: print('N')
def test_home(client): response = client.get('/') #import pdb;pdb.set_trace() assert response.status_code == 200 assert response.template_name == ['home.html']
def test_home(client): response = client.get('/') assert response.status_code == 200 assert response.template_name == ['home.html']
# MIT licensed # Copyright (c) 2013-2020 lilydjwg <lilydjwg@gmail.com>, et al. HACKAGE_URL = 'https://hackage.haskell.org/package/%s/preferred.json' async def get_version(name, conf, *, cache, **kwargs): key = conf.get('hackage', name) data = await cache.get_json(HACKAGE_URL % key) return data['normal-version'][0]
hackage_url = 'https://hackage.haskell.org/package/%s/preferred.json' async def get_version(name, conf, *, cache, **kwargs): key = conf.get('hackage', name) data = await cache.get_json(HACKAGE_URL % key) return data['normal-version'][0]
load( "//scala:advanced_usage/providers.bzl", _ScalaRulePhase = "ScalaRulePhase", ) load( "//scala/private:phases/phases.bzl", _phase_bloop = "phase_bloop", ) ext_add_phase_bloop = { "attrs": { # "bloopDir": attr.label( # allow_single_file = True, # doc = "Bloop output folder", # ), "_bloop": attr.label( cfg = "host", default = "//scala/bloop", executable = True, ), # "_runner": attr.label( # allow_single_file = True, # default = "//scala/bloop:runner", # ), # "_testrunner": attr.label( # allow_single_file = True, # default = "//scala/bloop:testrunner", # ), # "format": attr.bool( # default = False, # ), }, "phase_providers": [ "//scala/bloop:add_phase_bloop", ], } def _add_phase_bloop_singleton_implementation(ctx): return [ _ScalaRulePhase( custom_phases = [ #TODO plan is to make it a phase at the end then replace it later. Use phases before compile. ("=", "compile", "compile", _phase_bloop), # ("$", "", "bloop", _phase_bloop) # ("after", "compile", "bloop", _phase_bloop) ], ), ] add_phase_bloop_singleton = rule( implementation = _add_phase_bloop_singleton_implementation, )
load('//scala:advanced_usage/providers.bzl', _ScalaRulePhase='ScalaRulePhase') load('//scala/private:phases/phases.bzl', _phase_bloop='phase_bloop') ext_add_phase_bloop = {'attrs': {'_bloop': attr.label(cfg='host', default='//scala/bloop', executable=True)}, 'phase_providers': ['//scala/bloop:add_phase_bloop']} def _add_phase_bloop_singleton_implementation(ctx): return [__scala_rule_phase(custom_phases=[('=', 'compile', 'compile', _phase_bloop)])] add_phase_bloop_singleton = rule(implementation=_add_phase_bloop_singleton_implementation)
angka = { 0: 'tepat', 1: 'satu', 2: 'dua', 3: 'tiga', 4: 'empat', 5: 'lima', 6: 'enam', 7: 'tujuh', 8: 'delapan', 9: 'sembilan', 10: 'sepuluh', 11: 'sebelas', 12: 'dua belas', } def eja(n): lut1 = ['nol', 'satu', 'dua', 'tiga', 'empat', 'lima', 'enam', 'tujuh', 'delapan', 'sembilan', 'sepuluh', 'sebelas', 'dua belas', 'tiga belas', 'empat belas', 'lima belas', 'enam belas', 'tujuh belas', 'delapan belas', 'sembilan belas'] lut20 = ['x', 'x', 'dua puluh', 'tiga puluh', 'empat puluh', 'lima puluh', 'enam puluh', 'tujuh puluh', 'delapan puluh', 'sembilan puluh'] triples = ['x', 'ribu', 'juta', 'miliar', 'biliar', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion'] words = [] shift = 0 hasNumber = False insertpos = -1 while n > 0: ones = n % 10 shiftmod = shift % 3 shiftdiv = shift / 3 if shiftdiv > 0 and shiftmod == 0: insertpos = len(words) hasNumber = False if shiftmod == 2 and ones > 0: words.append('ratus') words.append(lut1[ones]) hasNumber = True if shiftmod == 1 and ones > 0: words.append(lut20[ones]) hasNumber = True if shiftmod == 0: tens = n % 100 if 0 < tens < 20: words.append(lut1[tens]) shift += 1 n = n / 10 hasNumber = True elif ones > 0: words.append(lut1[ones]) hasNumber = True if hasNumber and insertpos >= 0: words.insert(insertpos, triples[shiftdiv]) insertpos = -1 hasNumber = False n = n / 10 shift += 1 # oldones = ones words.reverse() text = ' '.join(words) result = text.split(' ') return result # return words if words else ['nol'] def mid(n): "around `n` +/- 1" return [n-1, n, n+1] def ucapkan(h, m): # jam = angka.get(h) # menit = angka.get(m) jam = eja(h) menit = eja(m) waktu = [] if m in mid(0) + [59]: waktu = [jam, 'tepat'] elif m in mid(15): waktu = [jam, 'seperempat'] elif m in mid(30): jam = eja(h+1) waktu = ['setengah', jam] elif m in mid(45): jam = eja(h+1) waktu = [jam, 'kurang', 'seperempat'] elif m < 30: waktu = [jam, 'lebih', menit] else: # waktu = [jam, menit] jam = eja(h+1) menit = eja(abs(60-m)) waktu = [jam, 'kurang', menit] return flattened(waktu) def flattened(arr): words = [] for r in arr: if isinstance(r, list): words += r else: words.append(r) text = ' '.join(words) result = text.split(' ') return result
angka = {0: 'tepat', 1: 'satu', 2: 'dua', 3: 'tiga', 4: 'empat', 5: 'lima', 6: 'enam', 7: 'tujuh', 8: 'delapan', 9: 'sembilan', 10: 'sepuluh', 11: 'sebelas', 12: 'dua belas'} def eja(n): lut1 = ['nol', 'satu', 'dua', 'tiga', 'empat', 'lima', 'enam', 'tujuh', 'delapan', 'sembilan', 'sepuluh', 'sebelas', 'dua belas', 'tiga belas', 'empat belas', 'lima belas', 'enam belas', 'tujuh belas', 'delapan belas', 'sembilan belas'] lut20 = ['x', 'x', 'dua puluh', 'tiga puluh', 'empat puluh', 'lima puluh', 'enam puluh', 'tujuh puluh', 'delapan puluh', 'sembilan puluh'] triples = ['x', 'ribu', 'juta', 'miliar', 'biliar', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion'] words = [] shift = 0 has_number = False insertpos = -1 while n > 0: ones = n % 10 shiftmod = shift % 3 shiftdiv = shift / 3 if shiftdiv > 0 and shiftmod == 0: insertpos = len(words) has_number = False if shiftmod == 2 and ones > 0: words.append('ratus') words.append(lut1[ones]) has_number = True if shiftmod == 1 and ones > 0: words.append(lut20[ones]) has_number = True if shiftmod == 0: tens = n % 100 if 0 < tens < 20: words.append(lut1[tens]) shift += 1 n = n / 10 has_number = True elif ones > 0: words.append(lut1[ones]) has_number = True if hasNumber and insertpos >= 0: words.insert(insertpos, triples[shiftdiv]) insertpos = -1 has_number = False n = n / 10 shift += 1 words.reverse() text = ' '.join(words) result = text.split(' ') return result def mid(n): """around `n` +/- 1""" return [n - 1, n, n + 1] def ucapkan(h, m): jam = eja(h) menit = eja(m) waktu = [] if m in mid(0) + [59]: waktu = [jam, 'tepat'] elif m in mid(15): waktu = [jam, 'seperempat'] elif m in mid(30): jam = eja(h + 1) waktu = ['setengah', jam] elif m in mid(45): jam = eja(h + 1) waktu = [jam, 'kurang', 'seperempat'] elif m < 30: waktu = [jam, 'lebih', menit] else: jam = eja(h + 1) menit = eja(abs(60 - m)) waktu = [jam, 'kurang', menit] return flattened(waktu) def flattened(arr): words = [] for r in arr: if isinstance(r, list): words += r else: words.append(r) text = ' '.join(words) result = text.split(' ') return result
""" Expert list created from Kompetenzpool data. List contains Microsoft Academic Graph Ids """ kompetenzpool_expert_list = { "Internet of Things": [ 2241467651, 673846798, 2236413454 ], "blockchain": { 1245553041, 2021103267, }, "natural language processing": { 2794237920, 2578689274, }, "autonomous driving": { 2490080048, 2156656717, }, "humanoid robot": { 1047662447, 2570474579, 2772428913, 2588863116, 2910150326, 2248512682, 2565089218, }, "evolutionary algorithm": { 2104163988, 2036573014, }, "remote sensing": [ 1983767936, 2471318715, 2636005816, ], "cellular automaton": [ 183621591, 2484531368, ], "electronic voting": [ 2038785220, ], "kalman filter": [ 154988935, 2165996130, 2228035992, ], "software architecture": [ 2145590652, ], "robot grasping": [ 1047662447, 2565089218, ], "ubiquitous computing": [ 673846798, ], "human-computer interaction": [ 673846798, 332721774, ], "digital health": [ 2021103267, ] }
""" Expert list created from Kompetenzpool data. List contains Microsoft Academic Graph Ids """ kompetenzpool_expert_list = {'Internet of Things': [2241467651, 673846798, 2236413454], 'blockchain': {1245553041, 2021103267}, 'natural language processing': {2794237920, 2578689274}, 'autonomous driving': {2490080048, 2156656717}, 'humanoid robot': {1047662447, 2570474579, 2772428913, 2588863116, 2910150326, 2248512682, 2565089218}, 'evolutionary algorithm': {2104163988, 2036573014}, 'remote sensing': [1983767936, 2471318715, 2636005816], 'cellular automaton': [183621591, 2484531368], 'electronic voting': [2038785220], 'kalman filter': [154988935, 2165996130, 2228035992], 'software architecture': [2145590652], 'robot grasping': [1047662447, 2565089218], 'ubiquitous computing': [673846798], 'human-computer interaction': [673846798, 332721774], 'digital health': [2021103267]}
#!/usr/bin/env python # coding: utf-8 # In[99]: class TreeNode: def __init__(self, val = None, par = None): self.left = None self.right = None self.value = val self.parent = par def left_child(self): return self.left def right_child(self): return self.right def set_value(self, val): self.value = val def get_value(self): return self.value def set_left(self, node): self.left = node node.parent = self return node def set_right(self, node): self.right = node node.parent = self return node def get_parent(self): return self.parent def level(self): result = 0 temp = self while temp.parent is not None: temp = temp.parent result += 1 return result def add(self, item): if item < self.get_value() : if self.left_child() is None: self.set_left(TreeNode(item)) else: self.left_child().add(item) else: if self.right_child() is None: self.set_right(TreeNode(item)) else: self.right_child().add(item) def preOrder(self, resultList): resultList.append(self.value) if self.left_child() is not None: self.left_child().preOrder(resultList) if self.right_child() is not None: self.right_child().preOrder(resultList) def inOrder(self, resultList): if self.left_child() is not None: self.left_child().inOrder(resultList) resultList.append(self.value) if self.right_child() is not None: self.right_child().inOrder(resultList) def postOrder(self, resultList): if self.left_child() is not None: self.left_child().postOrder(resultList) if self.right_child() is not None: self.right_child().postOrder(resultList) resultList.append(self.value) def find(self, item): if self.value == item: return self.value elif item < self.value: if self.left_child() is not None: return self.left_child().find(item) else: raise ValueError() else: if self.right_child() is not None: return self.right_child().find(item) else: raise ValueError() def preOrderStr(self): if self.left_child() is not None: self.left_child().preOrderStr() if self.right_child() is not None: self.right_child().preOrderStr() print("".ljust(self.level()*2), str(self.value)) def __str__(self): return str(self.value) # In[107]: class Pair: ''' Encapsulate letter,count pair as a single entity. Realtional methods make this object comparable using built-in operators. ''' def __init__(self, letter, count = 1): self.letter = letter self.count = count def __eq__(self, other): return self.letter == other.letter def __hash__(self): return hash(self.letter) def __ne__(self, other): return self.letter != other.letter def __lt__(self, other): return self.letter < other.letter def __le__(self, other): return self.letter <= other.letter def __gt__(self, other): return self.letter > other.letter def __ge__(self, other): return self.letter >= other.letter def __repr__(self): return f'({self.letter}, {self.count})' def __str__(self): return f'({self.letter}, {self.count})' class BinarySearchTree: def __init__(self): self.root = None def is_empty(self): return self.root is None def size(self): return self.__size(self.root) def __size(self, node): if node is None: return 0 result = 1 result += self.__size(node.left) result += self.__size(node.right) return result def add(self, item): if self.root is None: self.root = TreeNode(item) else: self.root.add(item) return self.root def find(self, item): if self.root is not None: return self.root.find(item) raise ValueError() def remove(self, item): return self.__remove(self.root, item) def __remove(self, node, item): if node is None: return node if item < node.get_value(): node.set_left(self.__remove(node.left_child(), item)) elif item > node.get_value(): node.set_right(self.__remove(node.right_child(), item)) else: if node.left_child() is None: temp = node.right_child() if temp is not None: temp.parent = node.parent node = None return temp elif node.right_child() is None: temp = node.left_child() if temp is not None: temp.parent = node.parent node = None return temp else: minNode = self.__minValueNode(node.right_child()) node.set_value(minNode.get_value()) node.set_right(self.__remove(node.right_child(), minNode.get_value())) return node def __minValueNode(self, node): current = node while (current.left_child() is not None): current = current.left_child() return current def inOrder(self): result = [] if self.root is not None: self.root.inOrder(result) return result def preOrder(self): result = [] if self.root is not None: self.root.preOrder(result) return result def postOrder(self): result = [] if self.root is not None: self.root.postOrder(result) return result def rebalance(self): orderedList = self.inOrder() self.root = None self.__rebalance(orderedList, 0, len(orderedList) - 1) def __rebalance(self, orderedList, low, high): if (low <= high): mid = (high - low) // 2 + low self.add(orderedList[mid]) self.__rebalance(orderedList, low, mid - 1) self.__rebalance(orderedList, mid + 1, high) def height(self): return self.__recursiveHeight(self.root, 0) def __recursiveHeight(self, node, current): leftValue = current rightValue = current if node.left_child() is not None: leftValue = self.__recursiveHeight(node.left, current + 1) if node.right_child() is not None: rightValue = self.__recursiveHeight(node.right, current + 1) return max(leftValue, rightValue) def __strInsert(self, value, position, char): return str(value[:position] + char + value[position + 1:]) def __str__(self): # if self.root is not None: # self.root.preOrderStr() # return "" totalLayers = self.height() + 1 totalWidth = (2 ** totalLayers) * 2 nodePosition = [None] * (totalLayers) for i in range(totalLayers): nodePosition[i] = [None] * (2 ** i) for j in range(2 ** i): nodePosition[i][j] = [0] * 3 lastLayer = nodePosition[totalLayers - 1] gap = totalWidth // len(lastLayer) for i in range(len(lastLayer)): lastLayer[i][0] = i * gap lastLayer[i][1] = lastLayer[i][0] lastLayer[i][2] = lastLayer[i][0] for i in reversed(range(totalLayers - 1)): for j in range(len(nodePosition[i])): first = nodePosition[i + 1][j * 2][0] second = nodePosition[i + 1][j * 2 + 1][0] nodePosition[i][j][1] = first + 1 nodePosition[i][j][2] = second - 1 nodePosition[i][j][0] = ((second - first) // 2) + first result = [""] * (totalLayers * 2) for i in range(1, len(result), 2): for j in range(totalWidth): result[i] += " " self.__nodePrettyPrint(result, self.root, [0] * (totalLayers), nodePosition, ' ') return "\n".join(result) def __nodePrettyPrint(self, result, node, nodeList, nodePosition, char): level = node.level() startLine = nodePosition[level][nodeList[level]][1] endLine = nodePosition[level][nodeList[level]][2] position = nodePosition[level][nodeList[level]][0] resultLevel = level * 2 nodeList[level] += 1 currentLen = len(result[resultLevel]) for i in range(currentLen - 1, startLine): result[resultLevel] += " " for i in range(startLine, position): result[resultLevel] += "_" result[resultLevel] += str(node.get_value()) for i in range(position + len(str(node.get_value())), endLine): result[resultLevel] += "_" result[resultLevel + 1] = self.__strInsert(result[resultLevel + 1], startLine, '/') if (endLine == startLine): endLine += len(str(node.get_value())) result[resultLevel + 1] = self.__strInsert(result[resultLevel + 1], endLine + 1, '\\') if (node.left_child() is not None): self.__nodePrettyPrint(result, node.left_child(), nodeList, nodePosition, '/') elif (level + 1) < len(nodeList): nextLevel = level + 1 capacity = 1 while nextLevel < len(nodeList): nodeList[nextLevel] += capacity capacity *= 2 nextLevel += 1 if (node.right_child() is not None): self.__nodePrettyPrint(result, node.right_child(), nodeList, nodePosition, '\\') elif (level + 1) < len(nodeList): nextLevel = level + 1 capacity = 1 while nextLevel < len(nodeList): nodeList[nextLevel] += capacity capacity *= 2 nextLevel += 1 # In[109]: myTree = BinarySearchTree() myTree.add(12) myTree.add(7) myTree.add(20) myTree.add(99) myTree.add(32) myTree.add(46) print(myTree) myTree.rebalance() print(myTree) myTree.remove(46) print() print(myTree) myTree.remove(20) print() print(myTree) # "C:\\Users\\Tavish\\Documents\\School\\Teaching\\CS_2420\\Project5\\around-the-world-in-80-days-3.txt" myTree = BinarySearchTree() with open("D:\\UVU\\Code\\Fall2020\\Child-Stuff\\CS2420\\Mod5\\P5\\around-the-world-in-80-days-3.txt", "r") as f: while True: c = f.read(1) if not c: break if c.isalnum(): try: found = myTree.find(Pair(c)) found.count += 1 except ValueError: myTree.add(Pair(c)) # myTree.rebalance() # print(myTree) # In[ ]: # In[ ]:
class Treenode: def __init__(self, val=None, par=None): self.left = None self.right = None self.value = val self.parent = par def left_child(self): return self.left def right_child(self): return self.right def set_value(self, val): self.value = val def get_value(self): return self.value def set_left(self, node): self.left = node node.parent = self return node def set_right(self, node): self.right = node node.parent = self return node def get_parent(self): return self.parent def level(self): result = 0 temp = self while temp.parent is not None: temp = temp.parent result += 1 return result def add(self, item): if item < self.get_value(): if self.left_child() is None: self.set_left(tree_node(item)) else: self.left_child().add(item) elif self.right_child() is None: self.set_right(tree_node(item)) else: self.right_child().add(item) def pre_order(self, resultList): resultList.append(self.value) if self.left_child() is not None: self.left_child().preOrder(resultList) if self.right_child() is not None: self.right_child().preOrder(resultList) def in_order(self, resultList): if self.left_child() is not None: self.left_child().inOrder(resultList) resultList.append(self.value) if self.right_child() is not None: self.right_child().inOrder(resultList) def post_order(self, resultList): if self.left_child() is not None: self.left_child().postOrder(resultList) if self.right_child() is not None: self.right_child().postOrder(resultList) resultList.append(self.value) def find(self, item): if self.value == item: return self.value elif item < self.value: if self.left_child() is not None: return self.left_child().find(item) else: raise value_error() elif self.right_child() is not None: return self.right_child().find(item) else: raise value_error() def pre_order_str(self): if self.left_child() is not None: self.left_child().preOrderStr() if self.right_child() is not None: self.right_child().preOrderStr() print(''.ljust(self.level() * 2), str(self.value)) def __str__(self): return str(self.value) class Pair: """ Encapsulate letter,count pair as a single entity. Realtional methods make this object comparable using built-in operators. """ def __init__(self, letter, count=1): self.letter = letter self.count = count def __eq__(self, other): return self.letter == other.letter def __hash__(self): return hash(self.letter) def __ne__(self, other): return self.letter != other.letter def __lt__(self, other): return self.letter < other.letter def __le__(self, other): return self.letter <= other.letter def __gt__(self, other): return self.letter > other.letter def __ge__(self, other): return self.letter >= other.letter def __repr__(self): return f'({self.letter}, {self.count})' def __str__(self): return f'({self.letter}, {self.count})' class Binarysearchtree: def __init__(self): self.root = None def is_empty(self): return self.root is None def size(self): return self.__size(self.root) def __size(self, node): if node is None: return 0 result = 1 result += self.__size(node.left) result += self.__size(node.right) return result def add(self, item): if self.root is None: self.root = tree_node(item) else: self.root.add(item) return self.root def find(self, item): if self.root is not None: return self.root.find(item) raise value_error() def remove(self, item): return self.__remove(self.root, item) def __remove(self, node, item): if node is None: return node if item < node.get_value(): node.set_left(self.__remove(node.left_child(), item)) elif item > node.get_value(): node.set_right(self.__remove(node.right_child(), item)) elif node.left_child() is None: temp = node.right_child() if temp is not None: temp.parent = node.parent node = None return temp elif node.right_child() is None: temp = node.left_child() if temp is not None: temp.parent = node.parent node = None return temp else: min_node = self.__minValueNode(node.right_child()) node.set_value(minNode.get_value()) node.set_right(self.__remove(node.right_child(), minNode.get_value())) return node def __min_value_node(self, node): current = node while current.left_child() is not None: current = current.left_child() return current def in_order(self): result = [] if self.root is not None: self.root.inOrder(result) return result def pre_order(self): result = [] if self.root is not None: self.root.preOrder(result) return result def post_order(self): result = [] if self.root is not None: self.root.postOrder(result) return result def rebalance(self): ordered_list = self.inOrder() self.root = None self.__rebalance(orderedList, 0, len(orderedList) - 1) def __rebalance(self, orderedList, low, high): if low <= high: mid = (high - low) // 2 + low self.add(orderedList[mid]) self.__rebalance(orderedList, low, mid - 1) self.__rebalance(orderedList, mid + 1, high) def height(self): return self.__recursiveHeight(self.root, 0) def __recursive_height(self, node, current): left_value = current right_value = current if node.left_child() is not None: left_value = self.__recursiveHeight(node.left, current + 1) if node.right_child() is not None: right_value = self.__recursiveHeight(node.right, current + 1) return max(leftValue, rightValue) def __str_insert(self, value, position, char): return str(value[:position] + char + value[position + 1:]) def __str__(self): total_layers = self.height() + 1 total_width = 2 ** totalLayers * 2 node_position = [None] * totalLayers for i in range(totalLayers): nodePosition[i] = [None] * 2 ** i for j in range(2 ** i): nodePosition[i][j] = [0] * 3 last_layer = nodePosition[totalLayers - 1] gap = totalWidth // len(lastLayer) for i in range(len(lastLayer)): lastLayer[i][0] = i * gap lastLayer[i][1] = lastLayer[i][0] lastLayer[i][2] = lastLayer[i][0] for i in reversed(range(totalLayers - 1)): for j in range(len(nodePosition[i])): first = nodePosition[i + 1][j * 2][0] second = nodePosition[i + 1][j * 2 + 1][0] nodePosition[i][j][1] = first + 1 nodePosition[i][j][2] = second - 1 nodePosition[i][j][0] = (second - first) // 2 + first result = [''] * (totalLayers * 2) for i in range(1, len(result), 2): for j in range(totalWidth): result[i] += ' ' self.__nodePrettyPrint(result, self.root, [0] * totalLayers, nodePosition, ' ') return '\n'.join(result) def __node_pretty_print(self, result, node, nodeList, nodePosition, char): level = node.level() start_line = nodePosition[level][nodeList[level]][1] end_line = nodePosition[level][nodeList[level]][2] position = nodePosition[level][nodeList[level]][0] result_level = level * 2 nodeList[level] += 1 current_len = len(result[resultLevel]) for i in range(currentLen - 1, startLine): result[resultLevel] += ' ' for i in range(startLine, position): result[resultLevel] += '_' result[resultLevel] += str(node.get_value()) for i in range(position + len(str(node.get_value())), endLine): result[resultLevel] += '_' result[resultLevel + 1] = self.__strInsert(result[resultLevel + 1], startLine, '/') if endLine == startLine: end_line += len(str(node.get_value())) result[resultLevel + 1] = self.__strInsert(result[resultLevel + 1], endLine + 1, '\\') if node.left_child() is not None: self.__nodePrettyPrint(result, node.left_child(), nodeList, nodePosition, '/') elif level + 1 < len(nodeList): next_level = level + 1 capacity = 1 while nextLevel < len(nodeList): nodeList[nextLevel] += capacity capacity *= 2 next_level += 1 if node.right_child() is not None: self.__nodePrettyPrint(result, node.right_child(), nodeList, nodePosition, '\\') elif level + 1 < len(nodeList): next_level = level + 1 capacity = 1 while nextLevel < len(nodeList): nodeList[nextLevel] += capacity capacity *= 2 next_level += 1 my_tree = binary_search_tree() myTree.add(12) myTree.add(7) myTree.add(20) myTree.add(99) myTree.add(32) myTree.add(46) print(myTree) myTree.rebalance() print(myTree) myTree.remove(46) print() print(myTree) myTree.remove(20) print() print(myTree) my_tree = binary_search_tree() with open('D:\\UVU\\Code\\Fall2020\\Child-Stuff\\CS2420\\Mod5\\P5\\around-the-world-in-80-days-3.txt', 'r') as f: while True: c = f.read(1) if not c: break if c.isalnum(): try: found = myTree.find(pair(c)) found.count += 1 except ValueError: myTree.add(pair(c))
ColorNames = \ { u'aliceblue': (240, 248, 255), u'antiquewhite': (250, 235, 215), u'aqua': (0, 255, 255), u'aquamarine': (127, 255, 212), u'azure': (240, 255, 255), u'beige': (245, 245, 220), u'bisque': (255, 228, 196), u'black': (0, 0, 0), u'blanchedalmond': (255, 235, 205), u'blue': (0, 0, 255), u'blueviolet': (138, 43, 226), u'brown': (165, 42, 42), u'burlywood': (222, 184, 135), u'cadetblue': (95, 158, 160), u'chartreuse': (127, 255, 0), u'chocolate': (210, 105, 30), u'coral': (255, 127, 80), u'cornflowerblue': (100, 149, 237), u'cornsilk': (255, 248, 220), u'crimson': (220, 20, 60), u'cyan': (0, 255, 255), u'darkblue': (0, 0, 139), u'darkcyan': (0, 139, 139), u'darkgoldenrod': (184, 134, 11), u'darkgray': (169, 169, 169), u'darkgreen': (0, 100, 0), u'darkgrey': (169, 169, 169), u'darkkhaki': (189, 183, 107), u'darkmagenta': (139, 0, 139), u'darkolivegreen': (85, 107, 47), u'darkorange': (255, 140, 0), u'darkorchid': (153, 50, 204), u'darkred': (139, 0, 0), u'darksalmon': (233, 150, 122), u'darkseagreen': (143, 188, 143), u'darkslateblue': (72, 61, 139), u'darkslategray': (47, 79, 79), u'darkslategrey': (47, 79, 79), u'darkturquoise': (0, 206, 209), u'darkviolet': (148, 0, 211), u'deeppink': (255, 20, 147), u'deepskyblue': (0, 191, 255), u'dimgray': (105, 105, 105), u'dimgrey': (105, 105, 105), u'dodgerblue': (30, 144, 255), u'firebrick': (178, 34, 34), u'floralwhite': (255, 250, 240), u'forestgreen': (34, 139, 34), u'fuchsia': (255, 0, 255), u'gainsboro': (220, 220, 220), u'ghostwhite': (248, 248, 255), u'gold': (255, 215, 0), u'goldenrod': (218, 165, 32), u'gray': (128, 128, 128), u'green': (0, 128, 0), u'greenyellow': (173, 255, 47), u'grey': (128, 128, 128), u'honeydew': (240, 255, 240), u'hotpink': (255, 105, 180), u'indianred': (205, 92, 92), u'indigo': (75, 0, 130), u'ivory': (255, 255, 240), u'khaki': (240, 230, 140), u'lavender': (230, 230, 250), u'lavenderblush': (255, 240, 245), u'lawngreen': (124, 252, 0), u'lemonchiffon': (255, 250, 205), u'lightblue': (173, 216, 230), u'lightcoral': (240, 128, 128), u'lightcyan': (224, 255, 255), u'lightgoldenrodyellow': (250, 250, 210), u'lightgray': (211, 211, 211), u'lightgreen': (144, 238, 144), u'lightgrey': (211, 211, 211), u'lightpink': (255, 182, 193), u'lightsalmon': (255, 160, 122), u'lightseagreen': (32, 178, 170), u'lightskyblue': (135, 206, 250), u'lightslategray': (119, 136, 153), u'lightslategrey': (119, 136, 153), u'lightsteelblue': (176, 196, 222), u'lightyellow': (255, 255, 224), u'lime': (0, 255, 0), u'limegreen': (50, 205, 50), u'linen': (250, 240, 230), u'magenta': (255, 0, 255), u'maroon': (128, 0, 0), u'mediumaquamarine': (102, 205, 170), u'mediumblue': (0, 0, 205), u'mediumorchid': (186, 85, 211), u'mediumpurple': (147, 112, 219), u'mediumseagreen': (60, 179, 113), u'mediumslateblue': (123, 104, 238), u'mediumspringgreen': (0, 250, 154), u'mediumturquoise': (72, 209, 204), u'mediumvioletred': (199, 21, 133), u'midnightblue': (25, 25, 112), u'mintcream': (245, 255, 250), u'mistyrose': (255, 228, 225), u'moccasin': (255, 228, 181), u'navajowhite': (255, 222, 173), u'navy': (0, 0, 128), u'oldlace': (253, 245, 230), u'olive': (128, 128, 0), u'olivedrab': (107, 142, 35), u'orange': (255, 165, 0), u'orangered': (255, 69, 0), u'orchid': (218, 112, 214), u'palegoldenrod': (238, 232, 170), u'palegreen': (152, 251, 152), u'paleturquoise': (175, 238, 238), u'palevioletred': (219, 112, 147), u'papayawhip': (255, 239, 213), u'peachpuff': (255, 218, 185), u'peru': (205, 133, 63), u'pink': (255, 192, 203), u'plum': (221, 160, 221), u'powderblue': (176, 224, 230), u'purple': (128, 0, 128), u'red': (255, 0, 0), u'rosybrown': (188, 143, 143), u'royalblue': (65, 105, 225), u'saddlebrown': (139, 69, 19), u'salmon': (250, 128, 114), u'sandybrown': (244, 164, 96), u'seagreen': (46, 139, 87), u'seashell': (255, 245, 238), u'sienna': (160, 82, 45), u'silver': (192, 192, 192), u'skyblue': (135, 206, 235), u'slateblue': (106, 90, 205), u'slategray': (112, 128, 144), u'slategrey': (112, 128, 144), u'snow': (255, 250, 250), u'springgreen': (0, 255, 127), u'steelblue': (70, 130, 180), u'tan': (210, 180, 140), u'teal': (0, 128, 128), u'thistle': (216, 191, 216), u'tomato': (255, 99, 71), u'turquoise': (64, 224, 208), u'violet': (238, 130, 238), u'wheat': (245, 222, 179), u'white': (255, 255, 255), u'whitesmoke': (245, 245, 245), u'yellow': (255, 255, 0), u'yellowgreen': (154, 205, 50)}
color_names = {u'aliceblue': (240, 248, 255), u'antiquewhite': (250, 235, 215), u'aqua': (0, 255, 255), u'aquamarine': (127, 255, 212), u'azure': (240, 255, 255), u'beige': (245, 245, 220), u'bisque': (255, 228, 196), u'black': (0, 0, 0), u'blanchedalmond': (255, 235, 205), u'blue': (0, 0, 255), u'blueviolet': (138, 43, 226), u'brown': (165, 42, 42), u'burlywood': (222, 184, 135), u'cadetblue': (95, 158, 160), u'chartreuse': (127, 255, 0), u'chocolate': (210, 105, 30), u'coral': (255, 127, 80), u'cornflowerblue': (100, 149, 237), u'cornsilk': (255, 248, 220), u'crimson': (220, 20, 60), u'cyan': (0, 255, 255), u'darkblue': (0, 0, 139), u'darkcyan': (0, 139, 139), u'darkgoldenrod': (184, 134, 11), u'darkgray': (169, 169, 169), u'darkgreen': (0, 100, 0), u'darkgrey': (169, 169, 169), u'darkkhaki': (189, 183, 107), u'darkmagenta': (139, 0, 139), u'darkolivegreen': (85, 107, 47), u'darkorange': (255, 140, 0), u'darkorchid': (153, 50, 204), u'darkred': (139, 0, 0), u'darksalmon': (233, 150, 122), u'darkseagreen': (143, 188, 143), u'darkslateblue': (72, 61, 139), u'darkslategray': (47, 79, 79), u'darkslategrey': (47, 79, 79), u'darkturquoise': (0, 206, 209), u'darkviolet': (148, 0, 211), u'deeppink': (255, 20, 147), u'deepskyblue': (0, 191, 255), u'dimgray': (105, 105, 105), u'dimgrey': (105, 105, 105), u'dodgerblue': (30, 144, 255), u'firebrick': (178, 34, 34), u'floralwhite': (255, 250, 240), u'forestgreen': (34, 139, 34), u'fuchsia': (255, 0, 255), u'gainsboro': (220, 220, 220), u'ghostwhite': (248, 248, 255), u'gold': (255, 215, 0), u'goldenrod': (218, 165, 32), u'gray': (128, 128, 128), u'green': (0, 128, 0), u'greenyellow': (173, 255, 47), u'grey': (128, 128, 128), u'honeydew': (240, 255, 240), u'hotpink': (255, 105, 180), u'indianred': (205, 92, 92), u'indigo': (75, 0, 130), u'ivory': (255, 255, 240), u'khaki': (240, 230, 140), u'lavender': (230, 230, 250), u'lavenderblush': (255, 240, 245), u'lawngreen': (124, 252, 0), u'lemonchiffon': (255, 250, 205), u'lightblue': (173, 216, 230), u'lightcoral': (240, 128, 128), u'lightcyan': (224, 255, 255), u'lightgoldenrodyellow': (250, 250, 210), u'lightgray': (211, 211, 211), u'lightgreen': (144, 238, 144), u'lightgrey': (211, 211, 211), u'lightpink': (255, 182, 193), u'lightsalmon': (255, 160, 122), u'lightseagreen': (32, 178, 170), u'lightskyblue': (135, 206, 250), u'lightslategray': (119, 136, 153), u'lightslategrey': (119, 136, 153), u'lightsteelblue': (176, 196, 222), u'lightyellow': (255, 255, 224), u'lime': (0, 255, 0), u'limegreen': (50, 205, 50), u'linen': (250, 240, 230), u'magenta': (255, 0, 255), u'maroon': (128, 0, 0), u'mediumaquamarine': (102, 205, 170), u'mediumblue': (0, 0, 205), u'mediumorchid': (186, 85, 211), u'mediumpurple': (147, 112, 219), u'mediumseagreen': (60, 179, 113), u'mediumslateblue': (123, 104, 238), u'mediumspringgreen': (0, 250, 154), u'mediumturquoise': (72, 209, 204), u'mediumvioletred': (199, 21, 133), u'midnightblue': (25, 25, 112), u'mintcream': (245, 255, 250), u'mistyrose': (255, 228, 225), u'moccasin': (255, 228, 181), u'navajowhite': (255, 222, 173), u'navy': (0, 0, 128), u'oldlace': (253, 245, 230), u'olive': (128, 128, 0), u'olivedrab': (107, 142, 35), u'orange': (255, 165, 0), u'orangered': (255, 69, 0), u'orchid': (218, 112, 214), u'palegoldenrod': (238, 232, 170), u'palegreen': (152, 251, 152), u'paleturquoise': (175, 238, 238), u'palevioletred': (219, 112, 147), u'papayawhip': (255, 239, 213), u'peachpuff': (255, 218, 185), u'peru': (205, 133, 63), u'pink': (255, 192, 203), u'plum': (221, 160, 221), u'powderblue': (176, 224, 230), u'purple': (128, 0, 128), u'red': (255, 0, 0), u'rosybrown': (188, 143, 143), u'royalblue': (65, 105, 225), u'saddlebrown': (139, 69, 19), u'salmon': (250, 128, 114), u'sandybrown': (244, 164, 96), u'seagreen': (46, 139, 87), u'seashell': (255, 245, 238), u'sienna': (160, 82, 45), u'silver': (192, 192, 192), u'skyblue': (135, 206, 235), u'slateblue': (106, 90, 205), u'slategray': (112, 128, 144), u'slategrey': (112, 128, 144), u'snow': (255, 250, 250), u'springgreen': (0, 255, 127), u'steelblue': (70, 130, 180), u'tan': (210, 180, 140), u'teal': (0, 128, 128), u'thistle': (216, 191, 216), u'tomato': (255, 99, 71), u'turquoise': (64, 224, 208), u'violet': (238, 130, 238), u'wheat': (245, 222, 179), u'white': (255, 255, 255), u'whitesmoke': (245, 245, 245), u'yellow': (255, 255, 0), u'yellowgreen': (154, 205, 50)}
# https://stackoverflow.com/questions/63626389/how-to-sort-points-along-a-hilbert-curve-without-using-hilbert-indices N=9 # 9 points n=2 # 2 dimension m=3 # order of Hilbert curve def BitTest(x,od): result = x & (1 << od) return int(bool(result)) def BitFlip(b,pos): b ^= 1 << pos return b def partition(idx,A,st,en,od,ax,di): i = st j = en while True: while i < j and BitTest(A[i][ax],od) == di: i = i + 1 while i < j and BitTest(A[j][ax],od) != di: j = j - 1 if j <= i: return i A[i], A[j] = A[j], A[i] idx[i], idx[j] = idx[j], idx[i] def HSort(idx,A,st,en,od,c,e,d,di,cnt): if en<=st: return p = partition(idx,A,st,en,od,(d+c)%n,BitTest(e,(d+c)%n)) if c==n-1: if od==0: return d2= (d+n+n-(2 if di else cnt + 2)) % n e=BitFlip(e,d2) e=BitFlip(e,(d+c)%n) HSort(idx,A,st,p-1,od-1,0,e,d2,False,0) e=BitFlip(e,(d+c)%n) e=BitFlip(e,d2) d2= (d+n+n-(cnt + 2 if di else 2))%n HSort(idx,A,p,en,od-1,0,e,d2,False,0) else: HSort(idx,A,st,p-1,od,c+1,e,d,False,(1 if di else cnt+1)) e=BitFlip(e,(d+c)%n) e=BitFlip(e,(d+c+1)%n) HSort(idx,A,p,en,od,c+1,e,d,True,(cnt+1 if di else 1)) e=BitFlip(e,(d+c+1)%n) e=BitFlip(e,(d+c)%n) # array = [[2,2],[2,4],[3,4],[2,5],[3,5],[1,6],[3,6],[5,6],[3,7]] # HSort(array,st=0,en=N-1,od=m-1,c=0,e=0,d=0,di=False,cnt=0) # print(array) # if False: # idx = self.recursive_sort(pca_X, n_components) # pca_X = pca_X[idx] # pca_X = np.array(pca_X) * 100000000 # pca_X = pca_X.astype(int) # N=len(pca_X) # 9 points # n=2 # 2 dimension # m=10 # order of Hilbert curve # idx = list(range(N)) # HSort(idx, pca_X,st=0,en=N-1,od=m-1,c=0,e=0,d=0,di=False,cnt=0) # else:
n = 9 n = 2 m = 3 def bit_test(x, od): result = x & 1 << od return int(bool(result)) def bit_flip(b, pos): b ^= 1 << pos return b def partition(idx, A, st, en, od, ax, di): i = st j = en while True: while i < j and bit_test(A[i][ax], od) == di: i = i + 1 while i < j and bit_test(A[j][ax], od) != di: j = j - 1 if j <= i: return i (A[i], A[j]) = (A[j], A[i]) (idx[i], idx[j]) = (idx[j], idx[i]) def h_sort(idx, A, st, en, od, c, e, d, di, cnt): if en <= st: return p = partition(idx, A, st, en, od, (d + c) % n, bit_test(e, (d + c) % n)) if c == n - 1: if od == 0: return d2 = (d + n + n - (2 if di else cnt + 2)) % n e = bit_flip(e, d2) e = bit_flip(e, (d + c) % n) h_sort(idx, A, st, p - 1, od - 1, 0, e, d2, False, 0) e = bit_flip(e, (d + c) % n) e = bit_flip(e, d2) d2 = (d + n + n - (cnt + 2 if di else 2)) % n h_sort(idx, A, p, en, od - 1, 0, e, d2, False, 0) else: h_sort(idx, A, st, p - 1, od, c + 1, e, d, False, 1 if di else cnt + 1) e = bit_flip(e, (d + c) % n) e = bit_flip(e, (d + c + 1) % n) h_sort(idx, A, p, en, od, c + 1, e, d, True, cnt + 1 if di else 1) e = bit_flip(e, (d + c + 1) % n) e = bit_flip(e, (d + c) % n)
# Authorization data host = '*****' user = '*****' passwd = '*****' db = 'hr'
host = '*****' user = '*****' passwd = '*****' db = 'hr'
# # PySNMP MIB module ENTERASYS-VLAN-AUTHORIZATION-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-VLAN-AUTHORIZATION-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:04:50 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint") dot1dBasePortEntry, = mibBuilder.importSymbols("BRIDGE-MIB", "dot1dBasePortEntry") etsysModules, = mibBuilder.importSymbols("ENTERASYS-MIB-NAMES", "etsysModules") EnabledStatus, = mibBuilder.importSymbols("P-BRIDGE-MIB", "EnabledStatus") NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") MibIdentifier, Bits, NotificationType, IpAddress, TimeTicks, Counter64, iso, Integer32, Counter32, ObjectIdentity, Unsigned32, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Bits", "NotificationType", "IpAddress", "TimeTicks", "Counter64", "iso", "Integer32", "Counter32", "ObjectIdentity", "Unsigned32", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") etsysVlanAuthorizationMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48)) etsysVlanAuthorizationMIB.setRevisions(('2004-06-02 19:22',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setRevisionsDescriptions(('The initial version of this MIB module',)) if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setLastUpdated('200406021922Z') if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setOrganization('Enterasys Networks, Inc') if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setContactInfo('Postal: Enterasys Networks, Inc. 50 Minuteman Rd. Andover, MA 01810-1008 USA Phone: +1 978 684 1000 E-mail: support@enterasys.com WWW: http://www.enterasys.com') if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setDescription("This MIB module defines a portion of the SNMP MIB under Enterasys Networks' enterprise OID pertaining to proprietary extensions to the IETF Q-BRIDGE-MIB, as specified in RFC2674, pertaining to VLAN authorization, as specified in RFC3580. Specifically, the enabling and disabling of support for the VLAN Tunnel-Type attribute returned from a RADIUS authentication, and how that attribute is applied to the port which initiated the authentication.") class VlanAuthEgressStatus(TextualConvention, Integer32): description = 'The possible egress configurations which may be applied in response to a successful authentication. none(1) No egress manipulation will be made. tagged(2) The authenticating port will be added to the current egress for the VLAN-ID returned. untagged(3) The authenticating port will be added to the current untagged egress for the VLAN-ID returned. dynamic(4) The authenticating port will use information returned in the authentication response to modify the current egress lists.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4)) namedValues = NamedValues(("none", 1), ("tagged", 2), ("untagged", 3), ("dynamic", 4)) etsysVlanAuthorizationObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1)) etsysVlanAuthorizationSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 1)) etsysVlanAuthorizationPorts = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2)) etsysVlanAuthorizationEnable = MibScalar((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 1, 1), EnabledStatus().clone('disabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: etsysVlanAuthorizationEnable.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationEnable.setDescription('The enable/disable state for the VLAN authorization feature. When disabled, no modifications to the VLAN attributes related to packet switching should be enforced.') etsysVlanAuthorizationTable = MibTable((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1), ) if mibBuilder.loadTexts: etsysVlanAuthorizationTable.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationTable.setDescription('Extensions to the table that contains information about every port that is associated with this transparent bridge.') etsysVlanAuthorizationEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1), ) dot1dBasePortEntry.registerAugmentions(("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationEntry")) etsysVlanAuthorizationEntry.setIndexNames(*dot1dBasePortEntry.getIndexNames()) if mibBuilder.loadTexts: etsysVlanAuthorizationEntry.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationEntry.setDescription('A list of extensions that support the management of proprietary features for each port of a transparent bridge. This is indexed by dot1dBasePort.') etsysVlanAuthorizationStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 1), EnabledStatus().clone('enabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: etsysVlanAuthorizationStatus.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationStatus.setDescription('The enabled/disabled status for the application of VLAN authorization on this port, if disabled, the information returned in the VLAN-Tunnel-Type from the authentication will not be applied to the port (although it should be represented in this table). If enabled, those results will be applied to the port.') etsysVlanAuthorizationAdminEgress = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 2), VlanAuthEgressStatus().clone('untagged')).setMaxAccess("readwrite") if mibBuilder.loadTexts: etsysVlanAuthorizationAdminEgress.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationAdminEgress.setDescription('Controls the modification of the current vlan egress list (of the vlan returned in the VLAN-Tunnel-Type, and reported by etsysVlanAuthorizationVlanID) upon successful authentication in the following manner: none(1) No egress manipulation will be made. tagged(2) The authenticating port will be added to the current egress for the VLAN-ID returned. untagged(3) The authenticating port will be added to the current untagged egress for the VLAN-ID returned. dynamic(4) The authenticating port will use information returned in the authentication response to modify the current egress lists. This value is supported only if the device supports a mechanism through which the egress status may be returned through the RADIUS response. Should etsysVlanAuthorizationEnable become disabled, etsysVlanAuthorizationStatus become disabled for a port, or should etsysVlanAuthorizationVlanID become 0 or 4095, all effect on the port egress MUST be removed.') etsysVlanAuthorizationOperEgress = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 3), VlanAuthEgressStatus().clone('none')).setMaxAccess("readonly") if mibBuilder.loadTexts: etsysVlanAuthorizationOperEgress.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationOperEgress.setDescription('Reports the current state of modification to the current vlan egress list (of the vlan returned in the VLAN-Tunnel-Type) upon successful authentication, if etsysVlanAuthorizationStatus is enabled, in the following manner: none(1) No egress manipulation will be made. tagged(2) The authenticating port will be added to the current egress for the VLAN-ID returned. untagged(3) The authenticating port will be added to the current untagged egress for the VLAN-ID returned. The purpose of this leaf is to report, specifically when etsysVlanAuthorizationAdminEgress has been set to dynamic(4), the currently enforced egress modification. If the port is unauthenticated, or no VLAN-ID has been applied, this leaf should return none(1).') etsysVlanAuthorizationVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4094), ValueRangeConstraint(4095, 4095), ))).setMaxAccess("readonly") if mibBuilder.loadTexts: etsysVlanAuthorizationVlanID.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationVlanID.setDescription('The 12 bit VLAN identifier for a given port, used to override the PVID of the given port, obtained as a result of an authentication. A value of zero indicates that there is no authenticated VLAN ID for the given port. Should a port become unauthenticated this value MUST be returned to zero. A value of 4095 indicates that a the port has been authenticated, but that the VLAN returned could not be applied to the port (possibly because of resource constraints or misconfiguration). In this instance, the original PVID should still be applied. Should the feature become disabled or the session terminate, all effect on the Port VLAN ID MUST be removed.') etsysVlanAuthorizationConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2)) etsysVlanAuthorizationGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 1)) etsysVlanAuthorizationCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 2)) etsysVlanAuthorizationGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 1, 1)).setObjects(("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationEnable"), ("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationStatus"), ("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationAdminEgress"), ("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationOperEgress"), ("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationVlanID")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): etsysVlanAuthorizationGroup = etsysVlanAuthorizationGroup.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationGroup.setDescription('A collection of objects relating to VLAN Authorization.') etsysVlanAuthorizationCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 2, 1)).setObjects(("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): etsysVlanAuthorizationCompliance = etsysVlanAuthorizationCompliance.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationCompliance.setDescription('The compliance statement for devices that support the Enterasys VLAN Authorization MIB.') mibBuilder.exportSymbols("ENTERASYS-VLAN-AUTHORIZATION-MIB", etsysVlanAuthorizationVlanID=etsysVlanAuthorizationVlanID, etsysVlanAuthorizationGroup=etsysVlanAuthorizationGroup, etsysVlanAuthorizationEnable=etsysVlanAuthorizationEnable, etsysVlanAuthorizationOperEgress=etsysVlanAuthorizationOperEgress, etsysVlanAuthorizationAdminEgress=etsysVlanAuthorizationAdminEgress, etsysVlanAuthorizationConformance=etsysVlanAuthorizationConformance, VlanAuthEgressStatus=VlanAuthEgressStatus, etsysVlanAuthorizationPorts=etsysVlanAuthorizationPorts, etsysVlanAuthorizationStatus=etsysVlanAuthorizationStatus, etsysVlanAuthorizationCompliance=etsysVlanAuthorizationCompliance, etsysVlanAuthorizationMIB=etsysVlanAuthorizationMIB, etsysVlanAuthorizationGroups=etsysVlanAuthorizationGroups, etsysVlanAuthorizationObjects=etsysVlanAuthorizationObjects, etsysVlanAuthorizationTable=etsysVlanAuthorizationTable, etsysVlanAuthorizationSystem=etsysVlanAuthorizationSystem, etsysVlanAuthorizationEntry=etsysVlanAuthorizationEntry, etsysVlanAuthorizationCompliances=etsysVlanAuthorizationCompliances, PYSNMP_MODULE_ID=etsysVlanAuthorizationMIB)
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, constraints_union, value_range_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'SingleValueConstraint') (dot1d_base_port_entry,) = mibBuilder.importSymbols('BRIDGE-MIB', 'dot1dBasePortEntry') (etsys_modules,) = mibBuilder.importSymbols('ENTERASYS-MIB-NAMES', 'etsysModules') (enabled_status,) = mibBuilder.importSymbols('P-BRIDGE-MIB', 'EnabledStatus') (notification_group, module_compliance, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance', 'ObjectGroup') (mib_identifier, bits, notification_type, ip_address, time_ticks, counter64, iso, integer32, counter32, object_identity, unsigned32, gauge32, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibIdentifier', 'Bits', 'NotificationType', 'IpAddress', 'TimeTicks', 'Counter64', 'iso', 'Integer32', 'Counter32', 'ObjectIdentity', 'Unsigned32', 'Gauge32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') etsys_vlan_authorization_mib = module_identity((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48)) etsysVlanAuthorizationMIB.setRevisions(('2004-06-02 19:22',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setRevisionsDescriptions(('The initial version of this MIB module',)) if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setLastUpdated('200406021922Z') if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setOrganization('Enterasys Networks, Inc') if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setContactInfo('Postal: Enterasys Networks, Inc. 50 Minuteman Rd. Andover, MA 01810-1008 USA Phone: +1 978 684 1000 E-mail: support@enterasys.com WWW: http://www.enterasys.com') if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setDescription("This MIB module defines a portion of the SNMP MIB under Enterasys Networks' enterprise OID pertaining to proprietary extensions to the IETF Q-BRIDGE-MIB, as specified in RFC2674, pertaining to VLAN authorization, as specified in RFC3580. Specifically, the enabling and disabling of support for the VLAN Tunnel-Type attribute returned from a RADIUS authentication, and how that attribute is applied to the port which initiated the authentication.") class Vlanauthegressstatus(TextualConvention, Integer32): description = 'The possible egress configurations which may be applied in response to a successful authentication. none(1) No egress manipulation will be made. tagged(2) The authenticating port will be added to the current egress for the VLAN-ID returned. untagged(3) The authenticating port will be added to the current untagged egress for the VLAN-ID returned. dynamic(4) The authenticating port will use information returned in the authentication response to modify the current egress lists.' status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4)) named_values = named_values(('none', 1), ('tagged', 2), ('untagged', 3), ('dynamic', 4)) etsys_vlan_authorization_objects = mib_identifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1)) etsys_vlan_authorization_system = mib_identifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 1)) etsys_vlan_authorization_ports = mib_identifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2)) etsys_vlan_authorization_enable = mib_scalar((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 1, 1), enabled_status().clone('disabled')).setMaxAccess('readwrite') if mibBuilder.loadTexts: etsysVlanAuthorizationEnable.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationEnable.setDescription('The enable/disable state for the VLAN authorization feature. When disabled, no modifications to the VLAN attributes related to packet switching should be enforced.') etsys_vlan_authorization_table = mib_table((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1)) if mibBuilder.loadTexts: etsysVlanAuthorizationTable.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationTable.setDescription('Extensions to the table that contains information about every port that is associated with this transparent bridge.') etsys_vlan_authorization_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1)) dot1dBasePortEntry.registerAugmentions(('ENTERASYS-VLAN-AUTHORIZATION-MIB', 'etsysVlanAuthorizationEntry')) etsysVlanAuthorizationEntry.setIndexNames(*dot1dBasePortEntry.getIndexNames()) if mibBuilder.loadTexts: etsysVlanAuthorizationEntry.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationEntry.setDescription('A list of extensions that support the management of proprietary features for each port of a transparent bridge. This is indexed by dot1dBasePort.') etsys_vlan_authorization_status = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 1), enabled_status().clone('enabled')).setMaxAccess('readwrite') if mibBuilder.loadTexts: etsysVlanAuthorizationStatus.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationStatus.setDescription('The enabled/disabled status for the application of VLAN authorization on this port, if disabled, the information returned in the VLAN-Tunnel-Type from the authentication will not be applied to the port (although it should be represented in this table). If enabled, those results will be applied to the port.') etsys_vlan_authorization_admin_egress = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 2), vlan_auth_egress_status().clone('untagged')).setMaxAccess('readwrite') if mibBuilder.loadTexts: etsysVlanAuthorizationAdminEgress.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationAdminEgress.setDescription('Controls the modification of the current vlan egress list (of the vlan returned in the VLAN-Tunnel-Type, and reported by etsysVlanAuthorizationVlanID) upon successful authentication in the following manner: none(1) No egress manipulation will be made. tagged(2) The authenticating port will be added to the current egress for the VLAN-ID returned. untagged(3) The authenticating port will be added to the current untagged egress for the VLAN-ID returned. dynamic(4) The authenticating port will use information returned in the authentication response to modify the current egress lists. This value is supported only if the device supports a mechanism through which the egress status may be returned through the RADIUS response. Should etsysVlanAuthorizationEnable become disabled, etsysVlanAuthorizationStatus become disabled for a port, or should etsysVlanAuthorizationVlanID become 0 or 4095, all effect on the port egress MUST be removed.') etsys_vlan_authorization_oper_egress = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 3), vlan_auth_egress_status().clone('none')).setMaxAccess('readonly') if mibBuilder.loadTexts: etsysVlanAuthorizationOperEgress.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationOperEgress.setDescription('Reports the current state of modification to the current vlan egress list (of the vlan returned in the VLAN-Tunnel-Type) upon successful authentication, if etsysVlanAuthorizationStatus is enabled, in the following manner: none(1) No egress manipulation will be made. tagged(2) The authenticating port will be added to the current egress for the VLAN-ID returned. untagged(3) The authenticating port will be added to the current untagged egress for the VLAN-ID returned. The purpose of this leaf is to report, specifically when etsysVlanAuthorizationAdminEgress has been set to dynamic(4), the currently enforced egress modification. If the port is unauthenticated, or no VLAN-ID has been applied, this leaf should return none(1).') etsys_vlan_authorization_vlan_id = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(0, 0), value_range_constraint(1, 4094), value_range_constraint(4095, 4095)))).setMaxAccess('readonly') if mibBuilder.loadTexts: etsysVlanAuthorizationVlanID.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationVlanID.setDescription('The 12 bit VLAN identifier for a given port, used to override the PVID of the given port, obtained as a result of an authentication. A value of zero indicates that there is no authenticated VLAN ID for the given port. Should a port become unauthenticated this value MUST be returned to zero. A value of 4095 indicates that a the port has been authenticated, but that the VLAN returned could not be applied to the port (possibly because of resource constraints or misconfiguration). In this instance, the original PVID should still be applied. Should the feature become disabled or the session terminate, all effect on the Port VLAN ID MUST be removed.') etsys_vlan_authorization_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2)) etsys_vlan_authorization_groups = mib_identifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 1)) etsys_vlan_authorization_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 2)) etsys_vlan_authorization_group = object_group((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 1, 1)).setObjects(('ENTERASYS-VLAN-AUTHORIZATION-MIB', 'etsysVlanAuthorizationEnable'), ('ENTERASYS-VLAN-AUTHORIZATION-MIB', 'etsysVlanAuthorizationStatus'), ('ENTERASYS-VLAN-AUTHORIZATION-MIB', 'etsysVlanAuthorizationAdminEgress'), ('ENTERASYS-VLAN-AUTHORIZATION-MIB', 'etsysVlanAuthorizationOperEgress'), ('ENTERASYS-VLAN-AUTHORIZATION-MIB', 'etsysVlanAuthorizationVlanID')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): etsys_vlan_authorization_group = etsysVlanAuthorizationGroup.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationGroup.setDescription('A collection of objects relating to VLAN Authorization.') etsys_vlan_authorization_compliance = module_compliance((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 2, 1)).setObjects(('ENTERASYS-VLAN-AUTHORIZATION-MIB', 'etsysVlanAuthorizationGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): etsys_vlan_authorization_compliance = etsysVlanAuthorizationCompliance.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationCompliance.setDescription('The compliance statement for devices that support the Enterasys VLAN Authorization MIB.') mibBuilder.exportSymbols('ENTERASYS-VLAN-AUTHORIZATION-MIB', etsysVlanAuthorizationVlanID=etsysVlanAuthorizationVlanID, etsysVlanAuthorizationGroup=etsysVlanAuthorizationGroup, etsysVlanAuthorizationEnable=etsysVlanAuthorizationEnable, etsysVlanAuthorizationOperEgress=etsysVlanAuthorizationOperEgress, etsysVlanAuthorizationAdminEgress=etsysVlanAuthorizationAdminEgress, etsysVlanAuthorizationConformance=etsysVlanAuthorizationConformance, VlanAuthEgressStatus=VlanAuthEgressStatus, etsysVlanAuthorizationPorts=etsysVlanAuthorizationPorts, etsysVlanAuthorizationStatus=etsysVlanAuthorizationStatus, etsysVlanAuthorizationCompliance=etsysVlanAuthorizationCompliance, etsysVlanAuthorizationMIB=etsysVlanAuthorizationMIB, etsysVlanAuthorizationGroups=etsysVlanAuthorizationGroups, etsysVlanAuthorizationObjects=etsysVlanAuthorizationObjects, etsysVlanAuthorizationTable=etsysVlanAuthorizationTable, etsysVlanAuthorizationSystem=etsysVlanAuthorizationSystem, etsysVlanAuthorizationEntry=etsysVlanAuthorizationEntry, etsysVlanAuthorizationCompliances=etsysVlanAuthorizationCompliances, PYSNMP_MODULE_ID=etsysVlanAuthorizationMIB)
#!/usr/bin/env python """ _Step.Templates_ Package for containing Step Template implementations """ __all__ = []
""" _Step.Templates_ Package for containing Step Template implementations """ __all__ = []
class BookStore: def __init__(self, book): self.booklst = book class Book: def __init__(self, title, author, chapter, price): self.title = title self.author = author self.chapter = list(chapter) self.price = int(price) book1 = Book("han kubrat", "Tangra", ['1', '3', '4', '2'], 1) book2 = Book("han Asparuh", "Vitosha", ['12', '123', '55', '22'], 2) book3 = Book("han Tervel", "StaraPlanina", ['155', '33', '41', '245'], 3) lst_book = [book1, book2, book3] bookstor = BookStore(lst_book)
class Bookstore: def __init__(self, book): self.booklst = book class Book: def __init__(self, title, author, chapter, price): self.title = title self.author = author self.chapter = list(chapter) self.price = int(price) book1 = book('han kubrat', 'Tangra', ['1', '3', '4', '2'], 1) book2 = book('han Asparuh', 'Vitosha', ['12', '123', '55', '22'], 2) book3 = book('han Tervel', 'StaraPlanina', ['155', '33', '41', '245'], 3) lst_book = [book1, book2, book3] bookstor = book_store(lst_book)
"""submodopt - A package for maximizing submodular functions""" __version__ = '0.1.0' __author__ = 'Satwik Bhattamishra <satwik55@gmail.com>' __all__ = []
"""submodopt - A package for maximizing submodular functions""" __version__ = '0.1.0' __author__ = 'Satwik Bhattamishra <satwik55@gmail.com>' __all__ = []
# Contains the objects found on our user greetings page. # Imports -------------------------------------------------------------------------------- # Page Objects --------------------------------------------------------------------------- class PatientGreetingPageObject(object): bio = 'This is a test bio.' def get_current_feeling_buttons(self): feeling1element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-0"]') feeling2element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-1"]') feeling3element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-2"]') feeling4element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-3"]') feeling5element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-4"]') feeling6element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-5"]') feeling7element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-6"]') feeling8element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-7"]') feeling9element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-8"]') feeling10element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-9"]') attributes = { 'feeling1 element': feeling1element, 'feeling2 element': feeling2element, 'feeling3 element': feeling3element, 'feeling4 element': feeling4element, 'feeling5 element': feeling5element, 'feeling6 element': feeling6element, 'feeling7 element': feeling7element, 'feeling8 element': feeling8element, 'feeling9 element': feeling9element, 'feeling10 element': feeling10element } return attributes def click_feeling1_button(self): self.get_current_feeling_buttons(self)['feeling1 element'].click() def click_feeling2_button(self): self.get_current_feeling_buttons(self)['feeling2 element'].click() def click_feeling3_button(self): self.get_current_feeling_buttons(self)['feeling3 element'].click() def click_feeling4_button(self): self.get_current_feeling_buttons(self)['feeling4 element'].click() def click_feeling5_button(self): self.get_current_feeling_buttons(self)['feeling5 element'].click() def click_feeling6_button(self): self.get_current_feeling_buttons(self)['feeling6 element'].click() def click_feeling7_button(self): self.get_current_feeling_buttons(self)['feeling7 element'].click() def click_feeling8_button(self): self.get_current_feeling_buttons(self)['feeling8 element'].click() def click_feeling9_button(self): self.get_current_feeling_buttons(self)['feeling9 element'].click() def click_feeling10_button(self): self.get_current_feeling_buttons(self)['feeling10 element'].click() def get_feeling_comparison_buttons(self): attributes = { 'worse element': self.client.find_element_by_xpath('//*[@id="feeling_comparison-0"]'), 'same element': self.client.find_element_by_xpath('//*[@id="feeling_comparison-1"]'), 'better element': self.client.find_element_by_xpath('//*[@id="feeling_comparison-2"]'), } return attributes def click_worse_button(self): self.get_feeling_comparison_buttons(self)['worse element'].click() def click_same_button(self): self.get_feeling_comparison_buttons(self)['same element'].click() def click_better_button(self): self.get_feeling_comparison_buttons(self)['better element'].click() def get_behaviour_buttons(self): attributes = { 'happy element': self.client.find_element_by_xpath('//*[@id="behaviours-0"]'), 'angry element': self.client.find_element_by_xpath('//*[@id="behaviours-1"]'), 'disappointed element': self.client.find_element_by_xpath('//*[@id="behaviours-2"]'), 'done with today element': self.client.find_element_by_xpath('//*[@id="behaviours-3"]'), 'persevering element': self.client.find_element_by_xpath('//*[@id="behaviours-4"]'), 'anxious element': self.client.find_element_by_xpath('//*[@id="behaviours-5"]'), 'confused element': self.client.find_element_by_xpath('//*[@id="behaviours-6"]'), 'worried element': self.client.find_element_by_xpath('//*[@id="behaviours-7"]'), 'ill element': self.client.find_element_by_xpath('//*[@id="behaviours-8"]'), 'exhausted element': self.client.find_element_by_xpath('//*[@id="behaviours-9"]'), 'accomplished element': self.client.find_element_by_xpath('//*[@id="behaviours-10"]'), 'star struck element': self.client.find_element_by_xpath('//*[@id="behaviours-11"]'), 'frightened element': self.client.find_element_by_xpath('//*[@id="behaviours-12"]'), } return attributes def click_happy_element(self): self.get_behaviour_buttons(self)['happy element'].click() def click_angry_element(self): self.get_behaviour_buttons(self)['angry element'].click() def click_disappointed_element(self): self.get_behaviour_buttons(self)['disappointed element'].click() def click_done_with_today_element(self): self.get_behaviour_buttons(self)['done with today element'].click() def click_persevering_element(self): self.get_behaviour_buttons(self)['persevering element'].click() def click_anxious_element(self): self.get_behaviour_buttons(self)['anxious element'].click() def click_confused_element(self): self.get_behaviour_buttons(self)['confused element'].click() def click_worried_element(self): self.get_behaviour_buttons(self)['worried element'].click() def click_ill_element(self): self.get_behaviour_buttons(self)['ill element'].click() def click_exhausted_element(self): self.get_behaviour_buttons(self)['exhausted element'].click() def click_accomplished_element(self): self.get_behaviour_buttons(self)['accomplished element'].click() def click_star_struck_element(self): self.get_behaviour_buttons(self)['star struck element'].click() def click_frightened_element(self): self.get_behaviour_buttons(self)['frightened element'].click() def get_bio_element(self): return self.client.find_element_by_xpath('//*[@id="patient_comment"]') def type_in_bio_form(self, input_to_type=bio): # A function to type text into our bio form box. # Retrieve our form attributes. get_field_element = self.get_bio_element() # After retrieving the field element, simulate typing into a form box. get_field_element.send_keys(input_to_type) print(f"Running Simulation: Currently typing '{input_to_type}' in the bio field.") def clear_password_form(self): # A function to clear the text from within our password form box. # Retrieve our form attributes. get_field_element = self.get_bio_element() get_field_element.clear() # Clears our form. print(f"Running Simulation: Currently clearing the bio field.") def get_submit_button(self): return self.client.find_element_by_xpath('//*[@id="submit"]') def click_submit_button(self): self.get_submit_button(self).click() def get_skip_evaluation_button(self): return self.client.find_element_by_xpath('/html/body/p/a') def click_skip_evaluation_button(self): return self.get_skip_evaluation_button(self).click()
class Patientgreetingpageobject(object): bio = 'This is a test bio.' def get_current_feeling_buttons(self): feeling1element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-0"]') feeling2element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-1"]') feeling3element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-2"]') feeling4element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-3"]') feeling5element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-4"]') feeling6element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-5"]') feeling7element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-6"]') feeling8element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-7"]') feeling9element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-8"]') feeling10element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-9"]') attributes = {'feeling1 element': feeling1element, 'feeling2 element': feeling2element, 'feeling3 element': feeling3element, 'feeling4 element': feeling4element, 'feeling5 element': feeling5element, 'feeling6 element': feeling6element, 'feeling7 element': feeling7element, 'feeling8 element': feeling8element, 'feeling9 element': feeling9element, 'feeling10 element': feeling10element} return attributes def click_feeling1_button(self): self.get_current_feeling_buttons(self)['feeling1 element'].click() def click_feeling2_button(self): self.get_current_feeling_buttons(self)['feeling2 element'].click() def click_feeling3_button(self): self.get_current_feeling_buttons(self)['feeling3 element'].click() def click_feeling4_button(self): self.get_current_feeling_buttons(self)['feeling4 element'].click() def click_feeling5_button(self): self.get_current_feeling_buttons(self)['feeling5 element'].click() def click_feeling6_button(self): self.get_current_feeling_buttons(self)['feeling6 element'].click() def click_feeling7_button(self): self.get_current_feeling_buttons(self)['feeling7 element'].click() def click_feeling8_button(self): self.get_current_feeling_buttons(self)['feeling8 element'].click() def click_feeling9_button(self): self.get_current_feeling_buttons(self)['feeling9 element'].click() def click_feeling10_button(self): self.get_current_feeling_buttons(self)['feeling10 element'].click() def get_feeling_comparison_buttons(self): attributes = {'worse element': self.client.find_element_by_xpath('//*[@id="feeling_comparison-0"]'), 'same element': self.client.find_element_by_xpath('//*[@id="feeling_comparison-1"]'), 'better element': self.client.find_element_by_xpath('//*[@id="feeling_comparison-2"]')} return attributes def click_worse_button(self): self.get_feeling_comparison_buttons(self)['worse element'].click() def click_same_button(self): self.get_feeling_comparison_buttons(self)['same element'].click() def click_better_button(self): self.get_feeling_comparison_buttons(self)['better element'].click() def get_behaviour_buttons(self): attributes = {'happy element': self.client.find_element_by_xpath('//*[@id="behaviours-0"]'), 'angry element': self.client.find_element_by_xpath('//*[@id="behaviours-1"]'), 'disappointed element': self.client.find_element_by_xpath('//*[@id="behaviours-2"]'), 'done with today element': self.client.find_element_by_xpath('//*[@id="behaviours-3"]'), 'persevering element': self.client.find_element_by_xpath('//*[@id="behaviours-4"]'), 'anxious element': self.client.find_element_by_xpath('//*[@id="behaviours-5"]'), 'confused element': self.client.find_element_by_xpath('//*[@id="behaviours-6"]'), 'worried element': self.client.find_element_by_xpath('//*[@id="behaviours-7"]'), 'ill element': self.client.find_element_by_xpath('//*[@id="behaviours-8"]'), 'exhausted element': self.client.find_element_by_xpath('//*[@id="behaviours-9"]'), 'accomplished element': self.client.find_element_by_xpath('//*[@id="behaviours-10"]'), 'star struck element': self.client.find_element_by_xpath('//*[@id="behaviours-11"]'), 'frightened element': self.client.find_element_by_xpath('//*[@id="behaviours-12"]')} return attributes def click_happy_element(self): self.get_behaviour_buttons(self)['happy element'].click() def click_angry_element(self): self.get_behaviour_buttons(self)['angry element'].click() def click_disappointed_element(self): self.get_behaviour_buttons(self)['disappointed element'].click() def click_done_with_today_element(self): self.get_behaviour_buttons(self)['done with today element'].click() def click_persevering_element(self): self.get_behaviour_buttons(self)['persevering element'].click() def click_anxious_element(self): self.get_behaviour_buttons(self)['anxious element'].click() def click_confused_element(self): self.get_behaviour_buttons(self)['confused element'].click() def click_worried_element(self): self.get_behaviour_buttons(self)['worried element'].click() def click_ill_element(self): self.get_behaviour_buttons(self)['ill element'].click() def click_exhausted_element(self): self.get_behaviour_buttons(self)['exhausted element'].click() def click_accomplished_element(self): self.get_behaviour_buttons(self)['accomplished element'].click() def click_star_struck_element(self): self.get_behaviour_buttons(self)['star struck element'].click() def click_frightened_element(self): self.get_behaviour_buttons(self)['frightened element'].click() def get_bio_element(self): return self.client.find_element_by_xpath('//*[@id="patient_comment"]') def type_in_bio_form(self, input_to_type=bio): get_field_element = self.get_bio_element() get_field_element.send_keys(input_to_type) print(f"Running Simulation: Currently typing '{input_to_type}' in the bio field.") def clear_password_form(self): get_field_element = self.get_bio_element() get_field_element.clear() print(f'Running Simulation: Currently clearing the bio field.') def get_submit_button(self): return self.client.find_element_by_xpath('//*[@id="submit"]') def click_submit_button(self): self.get_submit_button(self).click() def get_skip_evaluation_button(self): return self.client.find_element_by_xpath('/html/body/p/a') def click_skip_evaluation_button(self): return self.get_skip_evaluation_button(self).click()
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} Boys = {'Tim': 18,'Charlie':12,'Robert':25} Girls = {'Tiffany':22} studentX=Boys.copy() studentY=Girls.copy() print(studentX) print(studentY) students = list(Dict.keys()) students.sort() for s in students: print(":".join((s,str(Dict[s]))))
dict = {'Tim': 18, 'Charlie': 12, 'Tiffany': 22, 'Robert': 25} boys = {'Tim': 18, 'Charlie': 12, 'Robert': 25} girls = {'Tiffany': 22} student_x = Boys.copy() student_y = Girls.copy() print(studentX) print(studentY) students = list(Dict.keys()) students.sort() for s in students: print(':'.join((s, str(Dict[s]))))
"""Utilities for interacting with databases""" def generate_connect_string( host: str, port: int, db: str, user: str, password: str, ) -> str: conn_string = f"postgresql://{user}:{password}@" if not host.startswith('/'): conn_string += f"{host}:{port}" conn_string += f"/{db}" if host.startswith('/'): conn_string += f"?host={host}" return conn_string
"""Utilities for interacting with databases""" def generate_connect_string(host: str, port: int, db: str, user: str, password: str) -> str: conn_string = f'postgresql://{user}:{password}@' if not host.startswith('/'): conn_string += f'{host}:{port}' conn_string += f'/{db}' if host.startswith('/'): conn_string += f'?host={host}' return conn_string
class RaiseException: def __init__(self, exception: Exception): self.exception = exception
class Raiseexception: def __init__(self, exception: Exception): self.exception = exception
EVENT_ALGO_LOG = "eAlgoLog" EVENT_ALGO_SETTING = "eAlgoSetting" EVENT_ALGO_VARIABLES = "eAlgoVariables" EVENT_ALGO_PARAMETERS = "eAlgoParameters" APP_NAME = "AlgoTrading"
event_algo_log = 'eAlgoLog' event_algo_setting = 'eAlgoSetting' event_algo_variables = 'eAlgoVariables' event_algo_parameters = 'eAlgoParameters' app_name = 'AlgoTrading'
class AminoAcid: def __init__(self,name='AA'): self.name = name self.name3L = '' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.ResWeight = 0 # residue weight (weight - 56) backbone weight is 56 self.ResVol = 0 # Residue volume from http://prowl.rockefeller.edu/aainfo/volume.htm self.SideChainVol = 0 # Side Chain volume is evaluated as ResVol - 0.9 Gly.ResVol self.Hydropathy = 0 # Hydropathy index self.n1 = 0 self.n2 = 0 # n values # -1 when the amino acid (AA) residue has an N donor, short residue. # -2 when the AA residue has an O acceptor, short residue. # -3 when the AA residue has an N donor, long residue that able to bond across two turns. # -5 when the AA residue has an O acceptor, long residue that able to bond across two turns. # -7 when it is a Cystine(C) # 0 when bond is not possible. # 1 when this N or O participating in a bond. # A residu can only participate in one side-chain bond. So when a bond is created # for example with n1, n1 get the bond value and n2 will be assigned 0 def __mul__ (self,other): # Evaluating side chain interaction Prod = self.donor * other.acceptor return Prod # ############ Non Polar, HydroPhobic ########### class Ala(AminoAcid): def __init__(self): AminoAcid.__init__(self,'A') # Alanine # ### # CH3-CH(NH2)-COOH # # # Molecular weight 89.09 Da # Non ploar # Acidity - Natural # Hydrophobicity 0.616 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index 1.8 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point (when protonation accure) pH 6.01 # pKa( alpha-COOH) 2.35 # pKa( alpha-NH2) 9.87 # CAS # 56-41-7 # PubChem ID 5950 # self.name3L = 'ALA' self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.Hydropathy = 1.8 self.ResWeight = 33 self.ResVol = 88.6 self.SideChainVol = 88.6-54.1 class Val(AminoAcid): def __init__(self): AminoAcid.__init__(self,'V') # Valine # ######### # (CH3)2-CH-CH(NH2)-COOH # # # Essential AA (cannot be synthesized by humans) # Molecular weight 117.15 Da # Non ploar # Acidity - Natural # Hydrophobicity 0.825 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index 4.2 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 6.00 # pKa( alpha-COOH) 2.39 # pKa( alpha-NH2) 9.74 # CAS # 72-18-4 # PubChem ID 1182 # self.name3L = 'VAL' self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.Hydropathy = 4.2 self.ResWeight = 61 self.ResVol = 140.0 self.SideChainVol = 140-54.1 class Leu(AminoAcid): def __init__(self): AminoAcid.__init__(self,'L') # Leucine # ############# # (CH3)2-CH-CH2-CH(NH2)-COOH # # # Essential AA # Molecular weight 131.18 Da # Non ploar # Acidity - Natural # Hydrophobicity 0.943 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index 3.8 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 6.01 # pKa( alpha-COOH) 2.33 # pKa( alpha-NH2) 9.74 # CAS # 61-90-5 # PubChem ID 6106 # self.name3L = 'LEU' self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.Hydropathy = 3.8 self.ResWeight = 75 self.ResVol = 166.7 self.SideChainVol = 166.7-54.1 class Ile(AminoAcid): def __init__(self): AminoAcid.__init__(self,'I') # Isoleucine # ############### # CH3-CH2-CH(CH3)-CH(NH2)-COOH # # # Essential AA # Molecular weight 131.18 Da # Non ploar # Acidity - Natural # Hydrophobicity 0.943 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index 4.5 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 6.05 # pKa( alpha-COOH) 2.33 # pKa( alpha-NH2) 9.74 # CAS # 61-90-5 # PubChem ID 6106 # self.Hydropathy = 4.5 self.ResWeight = 75 self.name3L = 'ILE' self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.ResVol = 166.7 self.SideChainVol = 166.7-54.1 class Phe(AminoAcid): def __init__(self): AminoAcid.__init__(self,'F') # Phenylalanine # ###### # Ph-CH2-CH(NH2)-COOH # The residue Ph-CH2 : C6H5-CH2 benzyl # # Essential AA # Molecular weight 165.19 Da # Non ploar # Acidity - Natural # Hydrophobicity 1 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index 2.8 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 5.49 # pKa( alpha-COOH) 2.20 # pKa( alpha-NH2) 9.31 # CAS # 63-91-2 # PubChem ID 994 # self.Hydropathy = 2.8 self.ResWeight = 109 self.name3L = 'PHE' self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.ResVol = 189.9 self.SideChainVol = 189.9-54.1 class Trp(AminoAcid): def __init__(self): AminoAcid.__init__(self,'W') # Tryptophan # ############## # Ph-NH-CH=C-CH2-CH(NH2)-COOH # |________| # # contains an indole functional group. # aromatic heterocyclic organic compound # It has a bicyclic structure, consisting of a six-membered benzene ring fused to # a five-membered nitrogen-containing pyrrole ring # # Essential AA # Molecular weight 204.23 Da # Non ploar # Acidity - Natural # Hydrophobicity 0.878 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -0.9 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 5.89 # pKa( alpha-COOH) 2.46 # pKa( alpha-NH2) 9.41 # CAS # 73-22-3 # PubChem ID 6305 # self.Hydropathy = -0.9 self.ResWeight = 148 self.name3L = 'TRP' self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.ResVol = 227.8 self.SideChainVol = 227.8-54.1 class Met(AminoAcid): def __init__(self): AminoAcid.__init__(self,'M') # Methionine # ############ # CH3-S-(CH2)2-CH(NH2)-COOH # sulfur-containing residue # methyl donor R-CH3 # methionine is incorporated into the N-terminal position of all proteins # in eukaryotes and archaea during translation, although it is usually removed # by post-translational modification # # Essential AA # Molecular weight 149.21 Da # Non ploar # Acidity - Natural # Hydrophobicity 0.738 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index 1.9 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 5.74 # pKa( alpha-COOH) 2.13 # pKa( alpha-NH2) 9.28 # CAS # 63-68-3 # PubChem ID 876 # self.Hydropathy = 1.9 self.ResWeight = 93 self.name3L = 'MET' self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.ResVol = 162.9 self.SideChainVol = 162.9-54.1 class Pro(AminoAcid): def __init__(self): AminoAcid.__init__(self,'P') # Proline # ********** # NH-(CH2)3-CH-COOH # |_________| # Side chain bond to C alpha # exceptional conformational rigidity # usually solvent-exposed. # lacks a hydrogen on the amide group, it cannot act as a hydrogen bond donor, # only as a hydrogen bond acceptor. # # Molecular weight 115.13 Da # Non ploar # Acidity - Natural # Hydrophobicity 0.711 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -1.6 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 6.30 # pKa( alpha-COOH) 1.95 # pKa( alpha-NH2) 10.64 # CAS # 147-85-3 # PubChem ID 614 # self.Hydropathy = -1.6 self.ResWeight = 59 self.name3L = 'PRO' self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0,3:-3,4:-3,5:-3,6:-2} # special value scores self.n1 = 0 self.n2 = 0 self.ResVol = 112.7 self.SideChainVol = 112.7-54.1 # ############ Non Polar Uncharged ########### class Gly(AminoAcid): def __init__(self): AminoAcid.__init__(self,'G') # # NH2-CH2-COOH # # Molecular weight 75.07 Da # Non ploar # Acidity - Natural # Hydrophobicity 0.501 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -0.4 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 6.06 # pKa( alpha-COOH) 2.35 # pKa( alpha-NH2) 9.78 # CAS # 56-40-6 # PubChem ID 750 self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.Hydropathy = -0.4 self.ResWeight = 19 self.name3L = 'GLY' self.SpecialRes = {0:0,3:-3,5:-3} # special value scores self.ResVol = 60.1 self.SideChainVol = 60.1-54.1 # ############ Polar Uncharged ########### class Ser(AminoAcid): def __init__(self): AminoAcid.__init__(self,'S') # Serine # ###### # HO-CH2-CH(NH2)-COOH # # Molecular weight 105.09 Da # Ploar # Acidity - Natural # Hydrophobicity 0.359 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -0.8 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 5.68 # pKa( alpha-COOH) 2.19 # pKa( alpha-NH2) 9.21 # CAS # 56-45-1 # PubChem ID 617 # self.Hydropathy = -0.8 self.ResWeight = 49 self.name3L = 'SER' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.ResVol = 89.0 self.SideChainVol = 89-54.1 class Thr(AminoAcid): def __init__(self): AminoAcid.__init__(self,'T') # Threonine # ########## # CH3-CH(OH)-CH(NH2)-COOH # bearing an alcohol group # # Essential AA # Molecular weight 119.12 Da # Ploar # Acidity - Natural # Hydrophobicity 0.450 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -0.7 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 5.60 # pKa( alpha-COOH) 2.09 # pKa( alpha-NH2) 9.10 # CAS # 72-19-5 # PubChem ID 6288 # self.Hydropathy = -0.7 self.ResWeight = 63 self.name3L = 'THR' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.ResVol = 116.1 self.SideChainVol = 116.1-54.1 class Cys(AminoAcid): def __init__(self): AminoAcid.__init__(self,'C') # Cysteine # ###### # HS-CH2-CH(NH2)-COOH # thiol (R-S-H) side chain # Has Sulfur in side chain # # Molecular weight 121.16 Da # Ploar # Acidity - Natural # Hydrophobicity 0.680 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index 2.5 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 5.05 # pKa( alpha-COOH) 1.92 # pKa( alpha-NH2) 10.70 # CAS # 59-90-4 # PubChem ID 5862 # self.Hydropathy = 2.5 self.ResWeight = 65 self.name3L = 'CYS' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.n1 = -7 self.n2 = 0 self.SpecialRes = {0:0} # special value scores self.ResVol = 108.5 self.SideChainVol = 108.5-54.1 class Tyr(AminoAcid): def __init__(self): AminoAcid.__init__(self,'Y') # Tyrosine # ########### # HO-p-Ph-CH2-CH(NH2)-COOH # # Molecular weight 181.19 Da # Non ploar # Acidity - Natural # Hydrophobicity 0.880 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -1.3 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 5.64 # pKa( alpha-COOH) 2.20 # pKa( alpha-NH2) 9.21 # CAS # 60-18-4 # PubChem ID 1153 # self.Hydropathy = -1.3 self.ResWeight = 125 self.name3L = 'TYR' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.ResVol = 193.6 self.SideChainVol = 193.6-54.1 class Asn(AminoAcid): def __init__(self): AminoAcid.__init__(self,'N') # Asparagine # ########## # H2N-CO-CH2-CH(NH2)-COOH # N Donor - NH2 # # has carboxamide as the side chain's functional group(R-CO-NH2) # side chain can form hydrogen bond interactions with the peptide backbone # often found near the beginning and the end of alpha-helices, # and in turn motifs in beta sheets. # # Molecular weight 132.12 Da # Ploar # Acidity - Natural # Hydrophobicity 0.236 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -3.5 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 5.41 # pKa( alpha-COOH) 2.14 # pKa( alpha-NH2) 8.72 # CAS # 70-47-3 # PubChem ID 236 # self.Hydropathy = -3.5 self.ResWeight = 76 self.name3L = 'ASN' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = -1 self.n2 = -2 self.ResVol = 114.1 self.SideChainVol = 114.1-54.1 class Gln(AminoAcid): def __init__(self): AminoAcid.__init__(self,'Q') # Glutamine # ############# # H2N-CO-(CH2)2-CH(NH2)-COOH # N Donor - NH2 # # Molecular weight 146.14 Da # Ploar # Acidity - Natural # Hydrophobicity 0.251 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -3.5 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 5.65 # pKa( alpha-COOH) 2.17 # pKa( alpha-NH2) 9.13 # CAS # 56-85-9 # PubChem ID 5950 # self.Hydropathy = -3.5 self.ResWeight = 90 self.name3L = 'GLN' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.n1 = -1 self.n2 = -2 self.SpecialRes = {0:0} # special value scores self.ResVol = 143.8 self.SideChainVol = 143.8-54.1 # ########## Polar Acidic ########### class Asp(AminoAcid): def __init__(self): AminoAcid.__init__(self,'D') # Aspartic acid # ######## # HOOC-CH2-CH(NH2)-COOH # # Molecular weight 133.10 Da # Ploar # Acidity - Acidic # Hydrophobicity 0.028 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -3.5 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 2.85 # pKa( alpha-COOH) 1.99 # pKa( alpha-NH2) 9.90 # CAS # 56-84-8 # PubChem ID 5960 # self.Hydropathy = -3.5 self.ResWeight = 77 self.name3L = 'ASP' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 1 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.loop = 0 self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = -2 self.n2 = 0 self.ResVol = 111.1 self.SideChainVol = 111.1-54.1 class Glu(AminoAcid): def __init__(self): AminoAcid.__init__(self,'E') # ########### # HOOC-(CH2)2-CH(NH2)-COOH # # Molecular weight 147.13 Da # Ploar # Acidity - Acidic # Hydrophobicity 0.043 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -3.5 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 3.15 # pKa( alpha-COOH) 2.10 # pKa( alpha-NH2) 9.47 # CAS # 56-86-0 # PubChem ID 611 # self.Hydropathy = -3.5 self.ResWeight = 91 self.name3L = 'GLU' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 1 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.loop = 0 self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = -2 self.n2 = 0 self.ResVol = 138.4 self.SideChainVol = 138.4-54.1 # ############## Polar Basic ############# class Lys(AminoAcid): def __init__(self): AminoAcid.__init__(self,'K') # Lysine # ########## # H2N-(CH2)4-CH(NH2)-COOH # often participates in hydrogen bonding # N Donor - NH2 # # Essential AA # Molecular weight 146.19 Da # Ploar # Acidity - Basic # Hydrophobicity 0.283 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -3.9 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 6.90 # pKa( alpha-COOH) 2.16 # pKa( alpha-NH2) 9.06 # CAS # 56-87-1 # PubChem ID 866 # self.Hydropathy = -3.9 self.ResWeight = 90 self.Hydropathy = -3.9 self.ResWeight = 90 self.name3L = 'LYS' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 1 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.loop = 0 self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = -1 self.n2 = 0 self.ResVol = 168.6 self.SideChainVol = 168.6-54.1 class Arg(AminoAcid): def __init__(self): AminoAcid.__init__(self,'R') # Arginine # ################### # HN=C(NH2)-NH-(CH2)3-CH(NH2)-COOH # N Donor - NH2 # # Molecular weight 174.20 Da # Ploar # Acidity - Basic (strong) # Hydrophobicity 0.000 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -4.5 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point (when protonation accure) pH 10.76 # pKa( alpha-COOH) 1.82 # pKa( alpha-NH2) 8.99 # CAS # 74-79-3 # PubChem ID 5950 # self.Hydropathy = -4.5 self.ResWeight = 118 self.name3L = 'ARG' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 1 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.loop = 1 self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = -1 self.n2 = -3 self.ResVol = 173.4 self.SideChainVol = 173.4-54.1 class His(AminoAcid): def __init__(self): AminoAcid.__init__(self,'H') # Histidine # ################ # NH-CH=N-CH=C-CH2-CH(NH2)-COOH # |__________| # N Donor - NH # The imidazole side chain has two nitrogens with different properties # # Molecular weight 155.15 Da # Ploar # Acidity - Basic (week) # Hydrophobicity 0.165 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -3.2 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 7.60 # pKa( alpha-COOH) 1.80 # pKa( alpha-NH2) 9.33 # CAS # 71-00-1 # PubChem ID 773 # self.Hydropathy = -3.2 self.ResWeight = 99 self.name3L = 'HIS' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0.5 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = -1 self.n2 = 0 self.ResVol = 153.2 self.SideChainVol = 153.2-54.1
class Aminoacid: def __init__(self, name='AA'): self.name = name self.name3L = '' self.Hydrophobic = 0 self.charge = 0 self.polar = 0 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.ResWeight = 0 self.ResVol = 0 self.SideChainVol = 0 self.Hydropathy = 0 self.n1 = 0 self.n2 = 0 def __mul__(self, other): prod = self.donor * other.acceptor return Prod class Ala(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'A') self.name3L = 'ALA' self.Hydrophobic = 1 self.charge = 0 self.polar = 0 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.Hydropathy = 1.8 self.ResWeight = 33 self.ResVol = 88.6 self.SideChainVol = 88.6 - 54.1 class Val(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'V') self.name3L = 'VAL' self.Hydrophobic = 1 self.charge = 0 self.polar = 0 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.Hydropathy = 4.2 self.ResWeight = 61 self.ResVol = 140.0 self.SideChainVol = 140 - 54.1 class Leu(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'L') self.name3L = 'LEU' self.Hydrophobic = 1 self.charge = 0 self.polar = 0 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.Hydropathy = 3.8 self.ResWeight = 75 self.ResVol = 166.7 self.SideChainVol = 166.7 - 54.1 class Ile(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'I') self.Hydropathy = 4.5 self.ResWeight = 75 self.name3L = 'ILE' self.Hydrophobic = 1 self.charge = 0 self.polar = 0 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.ResVol = 166.7 self.SideChainVol = 166.7 - 54.1 class Phe(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'F') self.Hydropathy = 2.8 self.ResWeight = 109 self.name3L = 'PHE' self.Hydrophobic = 1 self.charge = 0 self.polar = 0 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.ResVol = 189.9 self.SideChainVol = 189.9 - 54.1 class Trp(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'W') self.Hydropathy = -0.9 self.ResWeight = 148 self.name3L = 'TRP' self.Hydrophobic = 1 self.charge = 0 self.polar = 0 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.ResVol = 227.8 self.SideChainVol = 227.8 - 54.1 class Met(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'M') self.Hydropathy = 1.9 self.ResWeight = 93 self.name3L = 'MET' self.Hydrophobic = 1 self.charge = 0 self.polar = 0 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.ResVol = 162.9 self.SideChainVol = 162.9 - 54.1 class Pro(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'P') self.Hydropathy = -1.6 self.ResWeight = 59 self.name3L = 'PRO' self.Hydrophobic = 1 self.charge = 0 self.polar = 0 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0, 3: -3, 4: -3, 5: -3, 6: -2} self.n1 = 0 self.n2 = 0 self.ResVol = 112.7 self.SideChainVol = 112.7 - 54.1 class Gly(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'G') self.Hydrophobic = 0 self.Hydropathy = -0.4 self.ResWeight = 19 self.name3L = 'GLY' self.SpecialRes = {0: 0, 3: -3, 5: -3} self.ResVol = 60.1 self.SideChainVol = 60.1 - 54.1 class Ser(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'S') self.Hydropathy = -0.8 self.ResWeight = 49 self.name3L = 'SER' self.Hydrophobic = 0 self.charge = 0 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.ResVol = 89.0 self.SideChainVol = 89 - 54.1 class Thr(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'T') self.Hydropathy = -0.7 self.ResWeight = 63 self.name3L = 'THR' self.Hydrophobic = 0 self.charge = 0 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.ResVol = 116.1 self.SideChainVol = 116.1 - 54.1 class Cys(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'C') self.Hydropathy = 2.5 self.ResWeight = 65 self.name3L = 'CYS' self.Hydrophobic = 0 self.charge = 0 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.n1 = -7 self.n2 = 0 self.SpecialRes = {0: 0} self.ResVol = 108.5 self.SideChainVol = 108.5 - 54.1 class Tyr(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'Y') self.Hydropathy = -1.3 self.ResWeight = 125 self.name3L = 'TYR' self.Hydrophobic = 0 self.charge = 0 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.ResVol = 193.6 self.SideChainVol = 193.6 - 54.1 class Asn(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'N') self.Hydropathy = -3.5 self.ResWeight = 76 self.name3L = 'ASN' self.Hydrophobic = 0 self.charge = 0 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = -1 self.n2 = -2 self.ResVol = 114.1 self.SideChainVol = 114.1 - 54.1 class Gln(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'Q') self.Hydropathy = -3.5 self.ResWeight = 90 self.name3L = 'GLN' self.Hydrophobic = 0 self.charge = 0 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.n1 = -1 self.n2 = -2 self.SpecialRes = {0: 0} self.ResVol = 143.8 self.SideChainVol = 143.8 - 54.1 class Asp(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'D') self.Hydropathy = -3.5 self.ResWeight = 77 self.name3L = 'ASP' self.Hydrophobic = 0 self.charge = 1 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = -2 self.n2 = 0 self.ResVol = 111.1 self.SideChainVol = 111.1 - 54.1 class Glu(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'E') self.Hydropathy = -3.5 self.ResWeight = 91 self.name3L = 'GLU' self.Hydrophobic = 0 self.charge = 1 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = -2 self.n2 = 0 self.ResVol = 138.4 self.SideChainVol = 138.4 - 54.1 class Lys(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'K') self.Hydropathy = -3.9 self.ResWeight = 90 self.Hydropathy = -3.9 self.ResWeight = 90 self.name3L = 'LYS' self.Hydrophobic = 0 self.charge = 1 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = -1 self.n2 = 0 self.ResVol = 168.6 self.SideChainVol = 168.6 - 54.1 class Arg(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'R') self.Hydropathy = -4.5 self.ResWeight = 118 self.name3L = 'ARG' self.Hydrophobic = 0 self.charge = 1 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = -1 self.n2 = -3 self.ResVol = 173.4 self.SideChainVol = 173.4 - 54.1 class His(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'H') self.Hydropathy = -3.2 self.ResWeight = 99 self.name3L = 'HIS' self.Hydrophobic = 0 self.charge = 0.5 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = -1 self.n2 = 0 self.ResVol = 153.2 self.SideChainVol = 153.2 - 54.1
initialized = True class TestFrozenUtf8_1: """\u00b6""" class TestFrozenUtf8_2: """\u03c0""" class TestFrozenUtf8_4: """\U0001f600""" def main(): print("Hello world!") if __name__ == '__main__': main()
initialized = True class Testfrozenutf8_1: """¶""" class Testfrozenutf8_2: """π""" class Testfrozenutf8_4: """😀""" def main(): print('Hello world!') if __name__ == '__main__': main()
''' A collection of classes corresponding to fixed-income securities, to be fed into (and used with) other classes and methods available in this repository (eg trees.py, Monte Carlo, etc) ''' class SelfAmortizingMortgage: def __init__(self, dates=mats6, early=False, rate=5.5 / 100, T=6, N=100): ''' Inputs: *** early: whether you can prepay the security when it is more advantageous to do so *** T: when the mortgage expires (maturity, years) *** N: the face value (dollars) *** rate: the interest rate paid yearly *** dates: numpy nd array with the payment dates of the security ''' self.T = T self.early = early self.rate = rate self.dates = dates # coupon chosen to have value N at time 0, given the mortgage quoted rate self.coupon = N / sum([(1 / pow(1 + self.rate, i)) for i in range(1, self.T + 1)]) if early: self._compute_balance(N) def get_cf(self, t, r, *args, **kwargs): ''' Inputs: *** t: the current time *** r: the current interest rate (at that node in the tree) Outputs: *** the cash-flow of the security for that (time, interest rate) ''' return self.coupon def exercise_early(self, current_value, val_if_exercise_early, t, r): ''' Method to say whether you should exercise early or not Inputs: *** current_value: the value of the contract at that node, if you do not exercise early *** t: the current time *** r: the current interest rate Returns: TRUE if should exercise early, FALSE otherwise ''' if not self.early: print('WARNING: this should not be called when the security does not allow for early exercise') return False return current_value > val_if_exercise_early def _compute_balance(self, N): ''' Makes a list with the amount of principal left at every possible moment, and a list with the interests paid ''' bal_st = [N] interest = [] princ = [] for i in range(self.T + 1): # for each payment until maturity interest.append(bal_st[i] * self.rate) princ.append(self.coupon - interest[i]) if i < self.T: bal_st.append(bal_st[i] - self.coupon + interest[i]) self.balances = bal_st self.interest = interest self.princ = princ def cf_early_exercise(self, t, r): ''' Gives the payoff if the security is exercised early, at time t, with rate r ''' # When a borrower prepays a mortgage, the borrower pays back the remaining principal on # the loan, and does not make any of the remaining scheduled payments return self.balances[t] def get_raw_cf_mat(self, interest_rate_tree, *args, **kwargs): ''' Inputs: *** interest_rate_tree: a 2D numpy array with corresponding interest rates in each cell Returns: *** the payoff matrix corresponding to the security, a matrix of the same dimension ''' payoff_mat = np.zeros((interest_rate_tree.shape[0] + 1, interest_rate_tree.shape[0] + 1)) for time in reversed(range(1, payoff_mat.shape[0])): for node in range(time + 1): payoff_mat[node, time] = self.get_cf(time, interest_rate_tree[max(node - 1, 0), time - 1], *args, **kwargs) return payoff_mat
""" A collection of classes corresponding to fixed-income securities, to be fed into (and used with) other classes and methods available in this repository (eg trees.py, Monte Carlo, etc) """ class Selfamortizingmortgage: def __init__(self, dates=mats6, early=False, rate=5.5 / 100, T=6, N=100): """ Inputs: *** early: whether you can prepay the security when it is more advantageous to do so *** T: when the mortgage expires (maturity, years) *** N: the face value (dollars) *** rate: the interest rate paid yearly *** dates: numpy nd array with the payment dates of the security """ self.T = T self.early = early self.rate = rate self.dates = dates self.coupon = N / sum([1 / pow(1 + self.rate, i) for i in range(1, self.T + 1)]) if early: self._compute_balance(N) def get_cf(self, t, r, *args, **kwargs): """ Inputs: *** t: the current time *** r: the current interest rate (at that node in the tree) Outputs: *** the cash-flow of the security for that (time, interest rate) """ return self.coupon def exercise_early(self, current_value, val_if_exercise_early, t, r): """ Method to say whether you should exercise early or not Inputs: *** current_value: the value of the contract at that node, if you do not exercise early *** t: the current time *** r: the current interest rate Returns: TRUE if should exercise early, FALSE otherwise """ if not self.early: print('WARNING: this should not be called when the security does not allow for early exercise') return False return current_value > val_if_exercise_early def _compute_balance(self, N): """ Makes a list with the amount of principal left at every possible moment, and a list with the interests paid """ bal_st = [N] interest = [] princ = [] for i in range(self.T + 1): interest.append(bal_st[i] * self.rate) princ.append(self.coupon - interest[i]) if i < self.T: bal_st.append(bal_st[i] - self.coupon + interest[i]) self.balances = bal_st self.interest = interest self.princ = princ def cf_early_exercise(self, t, r): """ Gives the payoff if the security is exercised early, at time t, with rate r """ return self.balances[t] def get_raw_cf_mat(self, interest_rate_tree, *args, **kwargs): """ Inputs: *** interest_rate_tree: a 2D numpy array with corresponding interest rates in each cell Returns: *** the payoff matrix corresponding to the security, a matrix of the same dimension """ payoff_mat = np.zeros((interest_rate_tree.shape[0] + 1, interest_rate_tree.shape[0] + 1)) for time in reversed(range(1, payoff_mat.shape[0])): for node in range(time + 1): payoff_mat[node, time] = self.get_cf(time, interest_rate_tree[max(node - 1, 0), time - 1], *args, **kwargs) return payoff_mat
AVG = 70 FUNCTIONS = [ lambda geslacht: 0 if geslacht == 'man' else 4, lambda rookt: -5 if rookt else 5, lambda sport: -3 if not sport else sport, lambda alcohol: 2 if not alcohol else -((alcohol - 7) * 0.5) if alcohol > 7 else 0, lambda fastfood: 3 if not fastfood else 0, ] def levensverwachting(geslacht, roker, sport, alcohol, fastfood): return AVG + sum(func(variable) for (func, variable) in zip(FUNCTIONS, [geslacht, roker, sport, alcohol, fastfood]))
avg = 70 functions = [lambda geslacht: 0 if geslacht == 'man' else 4, lambda rookt: -5 if rookt else 5, lambda sport: -3 if not sport else sport, lambda alcohol: 2 if not alcohol else -((alcohol - 7) * 0.5) if alcohol > 7 else 0, lambda fastfood: 3 if not fastfood else 0] def levensverwachting(geslacht, roker, sport, alcohol, fastfood): return AVG + sum((func(variable) for (func, variable) in zip(FUNCTIONS, [geslacht, roker, sport, alcohol, fastfood])))
class CommentHandlers(object): def __init__(self): self.handlers = [] self.comments = {} def handler(self): def wrapped(func): self.register(func) return func return wrapped def register_handler(self, func): for handler in self.handlers: print(handler.__name__) self.handlers.append(func) def add(self, addr, key, value): if (addr, key) in self.comments: self.comments[(addr, key)].append(value) else: self.comments[(addr, key)] = [value] for handler in self.handlers: handler(addr, key, value)
class Commenthandlers(object): def __init__(self): self.handlers = [] self.comments = {} def handler(self): def wrapped(func): self.register(func) return func return wrapped def register_handler(self, func): for handler in self.handlers: print(handler.__name__) self.handlers.append(func) def add(self, addr, key, value): if (addr, key) in self.comments: self.comments[addr, key].append(value) else: self.comments[addr, key] = [value] for handler in self.handlers: handler(addr, key, value)
def incrementing_time(start=2000, increment=1): while True: yield start start += increment def monotonic_time(start=2000): return incrementing_time(start, increment=0.000001) def static_time(value): while True: yield value
def incrementing_time(start=2000, increment=1): while True: yield start start += increment def monotonic_time(start=2000): return incrementing_time(start, increment=1e-06) def static_time(value): while True: yield value
""" Common constants and functions Markus Konrad <markus.konrad@wzb.eu> """ DEFAULT_TOPIC_NAME_FMT = 'topic_{i1}' DEFAULT_RANK_NAME_FMT = 'rank_{i1}'
""" Common constants and functions Markus Konrad <markus.konrad@wzb.eu> """ default_topic_name_fmt = 'topic_{i1}' default_rank_name_fmt = 'rank_{i1}'
class Solution: def reverseBits(self, n: int) -> int: val = 0 for i in range(32): val <<= 1 val += n & 1 n >>= 1 return val
class Solution: def reverse_bits(self, n: int) -> int: val = 0 for i in range(32): val <<= 1 val += n & 1 n >>= 1 return val
stages = iter(['alpha','beta','gamma']) try: next(stages) next(stages) next(stages) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations'
stages = iter(['alpha', 'beta', 'gamma']) try: next(stages) next(stages) next(stages) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations'
class Payment: def __init__(self): pass def setPayment(self, payment): Payment.payment = payment def getPayment(self): print("Total yang harus dibayarkan Rp. ", Payment.payment)
class Payment: def __init__(self): pass def set_payment(self, payment): Payment.payment = payment def get_payment(self): print('Total yang harus dibayarkan Rp. ', Payment.payment)
#from pageParser ''' lines = [] with open('output111.txt', 'rt') as in_file: for line in in_file: lines.append(line.rstrip('\n')) counter = (len(lines)) holder = 0 for element in range(0, counter): if(lines[holder].find('a') == -1): print("No A is found") lines.remove(lines[holder]) holder+=1 print('holder: ', holder) print('counter: ', counter) print('Line of code', lines[holder]) print(lines[holder].find('a')) holder+=1 if(holder > counter): break #print(len(soup_string)) #for i in soup_string: # if soup_string[i] == "<" and soup_string[i+1] == "a": #print(soup.find_alloutput1 #outputFile = open('output1 ##Opens fileoutput1 #with soup as websiteList: #for line in websiteList: #for i in range(len(line) - 1, -1, -1): #if((line[i] == '*') and (line[i-1] == '*')): #outputFile.write(line[5:i-1] + '\n') #line = line[5:] #outputFile.write(line) #outputFile.close() # header = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'} # sb_get = requests.get("https://www.youtube.com", headers = header) # sb_get.content # scrape_url="https://www.youtube.com" ### search_url="/results?search_query=" # search_hardcode = "game+of+thrones" # website_url = scrape_url + search_url + search_hardcode # sb_get = requests.get(website_url, headers = header) # sb_get.content # soupeddata = BeautifulSoup(sb_get.content, "html.parser") # yt_links = soupeddata.find_all("a", class_ = "yt-uix-tile-link") # # for x in yt_links: # yt_href = x.get("href") # yt_title = x.get("title") # yt_final = scrape_url + yt_href # print(yt_title + '\n' + yt_final + '\n') #page = requests.get("https://play.hbogo.com/") #soup = BeautifulSoup(page.content, 'html.parser') #print(soup.find_all('div')) #url = 'http://www.growingagreenerworld.com/episode125/' #with requests.Session() as session: #session.headers = headers #response = session.get(url) #soup = BeautifulSoup(response.content) #follow the iframe url #response = session.get('http:' + soup.iframe['src'], headers={'Referer': url}) #soup = BeautifulSoup(response.content) # extract the video URL from the script tag # print re.search(r'"url":"(.*?)"', soup.script.text).group(1) #print(soup.find_all('p')) ''' """def findLinks(): halfParsed = [] links = [] lineNum = 1 with open("websiteSource.txt", "r") as sc: lines = (line.rstrip() for line in sc) lines = (line for line in lines if line) for line in enumerate(sc): line = sc.readline() if(line.isspace() == True): continue else: halfParsed.append(line) for element in halfParsed: foundLinks = re.search(r"https?", element) if(foundLinks): links.append(element) for element in links: urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', element) print("********", type(urls)) #for x in urls goingIn = str(urls) htmlChecked.add(goingIn) print(goingIn)"""
""" lines = [] with open('output111.txt', 'rt') as in_file: for line in in_file: lines.append(line.rstrip(' ')) counter = (len(lines)) holder = 0 for element in range(0, counter): if(lines[holder].find('a') == -1): print("No A is found") lines.remove(lines[holder]) holder+=1 print('holder: ', holder) print('counter: ', counter) print('Line of code', lines[holder]) print(lines[holder].find('a')) holder+=1 if(holder > counter): break #print(len(soup_string)) #for i in soup_string: # if soup_string[i] == "<" and soup_string[i+1] == "a": #print(soup.find_alloutput1 #outputFile = open('output1 ##Opens fileoutput1 #with soup as websiteList: #for line in websiteList: #for i in range(len(line) - 1, -1, -1): #if((line[i] == '*') and (line[i-1] == '*')): #outputFile.write(line[5:i-1] + ' ') #line = line[5:] #outputFile.write(line) #outputFile.close() # header = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'} # sb_get = requests.get("https://www.youtube.com", headers = header) # sb_get.content # scrape_url="https://www.youtube.com" ### search_url="/results?search_query=" # search_hardcode = "game+of+thrones" # website_url = scrape_url + search_url + search_hardcode # sb_get = requests.get(website_url, headers = header) # sb_get.content # soupeddata = BeautifulSoup(sb_get.content, "html.parser") # yt_links = soupeddata.find_all("a", class_ = "yt-uix-tile-link") # # for x in yt_links: # yt_href = x.get("href") # yt_title = x.get("title") # yt_final = scrape_url + yt_href # print(yt_title + ' ' + yt_final + ' ') #page = requests.get("https://play.hbogo.com/") #soup = BeautifulSoup(page.content, 'html.parser') #print(soup.find_all('div')) #url = 'http://www.growingagreenerworld.com/episode125/' #with requests.Session() as session: #session.headers = headers #response = session.get(url) #soup = BeautifulSoup(response.content) #follow the iframe url #response = session.get('http:' + soup.iframe['src'], headers={'Referer': url}) #soup = BeautifulSoup(response.content) # extract the video URL from the script tag # print re.search(r'"url":"(.*?)"', soup.script.text).group(1) #print(soup.find_all('p')) """ 'def findLinks():\n halfParsed = []\n links = []\n lineNum = 1\n with open("websiteSource.txt", "r") as sc:\n lines = (line.rstrip() for line in sc)\n lines = (line for line in lines if line) \n for line in enumerate(sc):\n line = sc.readline()\n if(line.isspace() == True):\n continue\n else:\n halfParsed.append(line)\n for element in halfParsed:\n foundLinks = re.search(r"https?", element)\n if(foundLinks):\n links.append(element)\n for element in links:\n urls = re.findall(\'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+\', element)\n print("********", type(urls))\n #for x in urls\n goingIn = str(urls)\n htmlChecked.add(goingIn)\n print(goingIn)'
class Solution: def hammingDistance(self, x: int, y: int) -> int: c = x^y r = 0 while c != 0: r += (c & 1) c = c>>1 return r
class Solution: def hamming_distance(self, x: int, y: int) -> int: c = x ^ y r = 0 while c != 0: r += c & 1 c = c >> 1 return r
v = "vvv" a = [f"aaa{vvv}" "bbb"] print(a)
v = 'vvv' a = [f'aaa{vvv}bbb'] print(a)
# worst case O(n^2) # good case O(n) def insertion_sort(array): for i in range(1, len(array)): key = array[i] j = i -1 while (j>=0 and array[j]>key): # scoot array[j+1] = array[j] j-=1 array[j+1] = key return array arr = [3,-9,5, 100,-2, 294,5,56] sarr = insertion_sort(arr) print(sarr, sorted(arr)) assert(sarr == sorted(arr))
def insertion_sort(array): for i in range(1, len(array)): key = array[i] j = i - 1 while j >= 0 and array[j] > key: array[j + 1] = array[j] j -= 1 array[j + 1] = key return array arr = [3, -9, 5, 100, -2, 294, 5, 56] sarr = insertion_sort(arr) print(sarr, sorted(arr)) assert sarr == sorted(arr)
x=int(input("Enter first number:\n")) y=int(input("Enter second number:\n")) print("Before swapping:\n",x,"\n",y,"\n") #Inputting two numbers from user x,y=y,x #Swapping two variables print("After swapping:\n",x,"\n",y,"\n")
x = int(input('Enter first number:\n')) y = int(input('Enter second number:\n')) print('Before swapping:\n', x, '\n', y, '\n') (x, y) = (y, x) print('After swapping:\n', x, '\n', y, '\n')
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2016 Dean Jackson <deanishe@deanishe.net> # # MIT Licence. See http://opensource.org/licenses/MIT # # Created on 2016-12-17 # """CLI program sub-commands."""
"""CLI program sub-commands."""
n = int(input()) for i in range(1, 10): if n % i != 0: continue for j in range(1, 10): if n % j != 0: continue for k in range(1, 10): if n % k != 0: continue for m in range(1, 10): if n % m != 0: continue for o in range(1, 10): if n % o != 0: continue for p in range(1, 10): if n % i != 0: continue if (i * j * k * m * o * p == n): print("{0}{1}{2}{3}{4}{5}".format(i, j, k, m, o, p), end=' ')
n = int(input()) for i in range(1, 10): if n % i != 0: continue for j in range(1, 10): if n % j != 0: continue for k in range(1, 10): if n % k != 0: continue for m in range(1, 10): if n % m != 0: continue for o in range(1, 10): if n % o != 0: continue for p in range(1, 10): if n % i != 0: continue if i * j * k * m * o * p == n: print('{0}{1}{2}{3}{4}{5}'.format(i, j, k, m, o, p), end=' ')
def clean_path(path): """ Removes illegal characters from path (Windows only) """ return ''.join(i for i in path if i not in '<>:"/\|?*')
def clean_path(path): """ Removes illegal characters from path (Windows only) """ return ''.join((i for i in path if i not in '<>:"/\\|?*'))
reserv_list = set() party_list = set() command = input() while command != 'PARTY': reserv_list.add(command) command = input() if command == 'PARTY': command = input() while command != 'END': party_list.add(command) command = input() diff = abs(len(reserv_list) - len(party_list)) print(diff) losers = (reserv_list-party_list) sort = sorted(losers) for el in sort: print(el)
reserv_list = set() party_list = set() command = input() while command != 'PARTY': reserv_list.add(command) command = input() if command == 'PARTY': command = input() while command != 'END': party_list.add(command) command = input() diff = abs(len(reserv_list) - len(party_list)) print(diff) losers = reserv_list - party_list sort = sorted(losers) for el in sort: print(el)
class Player(object): TEAM_GREEN = 0 TEAM_RED = 1 TEAM_BLUE = 2 def __init__(self, id, front_grey, front_red, front_blue, deck_grey, deck_red, deck_blue): self.id = id self.front_grey = front_grey self.front_red = front_red self.front_blue = front_blue self.deck_grey = deck_grey self.deck_red = deck_red self.deck_blue = deck_blue
class Player(object): team_green = 0 team_red = 1 team_blue = 2 def __init__(self, id, front_grey, front_red, front_blue, deck_grey, deck_red, deck_blue): self.id = id self.front_grey = front_grey self.front_red = front_red self.front_blue = front_blue self.deck_grey = deck_grey self.deck_red = deck_red self.deck_blue = deck_blue
# Advent of code 2021 : Day 1 | Part 2 # Source : https://adventofcode.com/2020/day/1 infile = "aoc/2020/Day 1/input.txt" inputs = list(map(int, open(infile).read().splitlines())) print([i*j*_ for i in inputs for j in inputs for _ in inputs if i + j + _ == 2020][0]) # Answer : 165080960
infile = 'aoc/2020/Day 1/input.txt' inputs = list(map(int, open(infile).read().splitlines())) print([i * j * _ for i in inputs for j in inputs for _ in inputs if i + j + _ == 2020][0])
#!/usr/bin/python class JustCounter: __secret_count = 0 def count(self): self.__secret_count += 1 print(self.__secret_count) counter = JustCounter() counter.count() counter.count() # can't access print(counter.__secret_count)
class Justcounter: __secret_count = 0 def count(self): self.__secret_count += 1 print(self.__secret_count) counter = just_counter() counter.count() counter.count() print(counter.__secret_count)
N = int(input()) A = [int(n) for n in input().split()] ans = [0] + [0]*N for i in range(N-1): ans[A[i]] += 1 for i in range(1, N+1): print(ans[i])
n = int(input()) a = [int(n) for n in input().split()] ans = [0] + [0] * N for i in range(N - 1): ans[A[i]] += 1 for i in range(1, N + 1): print(ans[i])
def solve_part1(numbers, boards): marked = {}.fromkeys(list(boards.keys())) for key in marked: # idx // 5 idx % 5 # row column marked[key] = ([0,0,0,0,0],[0,0,0,0,0]) for number in numbers: for board_idx in boards: try: idx = boards[board_idx].index(number) # Update rows e.g: (marked[idx] [0] [1]) represents row 1 of board idx marked[board_idx] [0] [idx // 5] += 1 # Update columns e.g: (marked[idx] [1] [2]) represents column 2 of board idx marked[board_idx] [1] [idx % 5] += 1 # Full marked row or column (when there is a 5 in any row or column) if 5 in marked[board_idx] [0] or 5 in marked[board_idx] [1]: # This return means: sum each number in the board that is not in the numbers that have been drawn up until now res = sum([n for n in boards[board_idx] if n not in numbers[0: numbers.index(number) + 1]]) # Here i return the solution and some parameters that will be useful in part2 # Solution, current number return res * number, numbers, number, marked, boards, board_idx except: # Number not in board pass def solve_part2(numbers,number,marked,boards, board_idx): # Here we finish what is left of the last iteration from solve_part1() completed_boards_list = [0] * len(boards) completed_boards_list [board_idx] = 1 completed_boards = 1 for board_idx in range(board_idx + 1, len(boards)): try: idx = boards[board_idx].index(number) # Update rows e.g: (marked[idx] [0] [1]) represents row 1 of board idx marked[board_idx] [0] [idx // 5] += 1 # Update columns e.g: (marked[idx] [1] [2]) represents column 2 of board idx marked[board_idx] [1] [idx % 5] += 1 if (5 in marked[board_idx] [0] or 5 in marked[board_idx] [1]) and completed_boards_list[board_idx] == 0: completed_boards_list [board_idx] = 1 completed_boards += 1 if completed_boards == len(boards) - 1: last = completed_boards_list.index(0) elif completed_boards == len(boards): return sum([n for n in boards[last] if n not in numbers[0: numbers.index(number) + 1]]) * number except: # Number not in board pass for number in numbers[numbers.index(number) + 1:]: for board_idx in boards: try: idx = boards[board_idx].index(number) # Update rows e.g: (marked[idx] [0] [1]) represents row 1 of board idx marked[board_idx] [0] [idx // 5] += 1 # Update columns e.g: (marked[idx] [1] [2]) represents column 2 of board idx marked[board_idx] [1] [idx % 5] += 1 if (5 in marked[board_idx] [0] or 5 in marked[board_idx] [1]) and completed_boards_list[board_idx] == 0: completed_boards_list [board_idx] = 1 completed_boards += 1 # If there's only 1 left to win if completed_boards == len(boards) - 1: last = completed_boards_list.index(0) elif completed_boards == len(boards): return sum([n for n in boards[last] if n not in numbers[0: numbers.index(number) + 1]]) * number except: # Number not in board pass """ Coder's note: Sometimes is harder to prepare the input than solving the problem... """ # Get input for part 1 input_file = open('Day4_input.txt','r') # Numbers for bingo numbers = input_file.readline().split(',') # Last number has a "\n" character attached to it, we eliminate it numbers[-1] = numbers[-1][:-1] numbers = [int(num) for num in numbers] # Skip next "\n" in file input_file.readline() boards = {} board_idx = 0 aux = input_file.read().split("\n") # Split leaves '' characters, we must filter them aux = [elem for elem in aux if elem != ''] for i in range(len(aux)//5): boards[board_idx] = aux[5*i] + " " + aux[5*i+1] + " " + aux[5*i + 2] + " " + aux[5*i + 3] + " " + aux[5*i + 4] boards[board_idx] = boards[board_idx].split() boards[board_idx] = [int(num) for num in boards[board_idx]] board_idx +=1 del aux, board_idx # We return this many variable to take advantage of what we have already calculated part1_sol, numbers, number, marked, boards, board_idx = solve_part1(numbers, boards) print("Part 1 solution:",part1_sol) part2_sol = solve_part2(numbers,number,marked,boards, board_idx) print("Part 2 solution:",part2_sol)
def solve_part1(numbers, boards): marked = {}.fromkeys(list(boards.keys())) for key in marked: marked[key] = ([0, 0, 0, 0, 0], [0, 0, 0, 0, 0]) for number in numbers: for board_idx in boards: try: idx = boards[board_idx].index(number) marked[board_idx][0][idx // 5] += 1 marked[board_idx][1][idx % 5] += 1 if 5 in marked[board_idx][0] or 5 in marked[board_idx][1]: res = sum([n for n in boards[board_idx] if n not in numbers[0:numbers.index(number) + 1]]) return (res * number, numbers, number, marked, boards, board_idx) except: pass def solve_part2(numbers, number, marked, boards, board_idx): completed_boards_list = [0] * len(boards) completed_boards_list[board_idx] = 1 completed_boards = 1 for board_idx in range(board_idx + 1, len(boards)): try: idx = boards[board_idx].index(number) marked[board_idx][0][idx // 5] += 1 marked[board_idx][1][idx % 5] += 1 if (5 in marked[board_idx][0] or 5 in marked[board_idx][1]) and completed_boards_list[board_idx] == 0: completed_boards_list[board_idx] = 1 completed_boards += 1 if completed_boards == len(boards) - 1: last = completed_boards_list.index(0) elif completed_boards == len(boards): return sum([n for n in boards[last] if n not in numbers[0:numbers.index(number) + 1]]) * number except: pass for number in numbers[numbers.index(number) + 1:]: for board_idx in boards: try: idx = boards[board_idx].index(number) marked[board_idx][0][idx // 5] += 1 marked[board_idx][1][idx % 5] += 1 if (5 in marked[board_idx][0] or 5 in marked[board_idx][1]) and completed_boards_list[board_idx] == 0: completed_boards_list[board_idx] = 1 completed_boards += 1 if completed_boards == len(boards) - 1: last = completed_boards_list.index(0) elif completed_boards == len(boards): return sum([n for n in boards[last] if n not in numbers[0:numbers.index(number) + 1]]) * number except: pass "\nCoder's note: Sometimes is harder to prepare the input than solving the problem...\n" input_file = open('Day4_input.txt', 'r') numbers = input_file.readline().split(',') numbers[-1] = numbers[-1][:-1] numbers = [int(num) for num in numbers] input_file.readline() boards = {} board_idx = 0 aux = input_file.read().split('\n') aux = [elem for elem in aux if elem != ''] for i in range(len(aux) // 5): boards[board_idx] = aux[5 * i] + ' ' + aux[5 * i + 1] + ' ' + aux[5 * i + 2] + ' ' + aux[5 * i + 3] + ' ' + aux[5 * i + 4] boards[board_idx] = boards[board_idx].split() boards[board_idx] = [int(num) for num in boards[board_idx]] board_idx += 1 del aux, board_idx (part1_sol, numbers, number, marked, boards, board_idx) = solve_part1(numbers, boards) print('Part 1 solution:', part1_sol) part2_sol = solve_part2(numbers, number, marked, boards, board_idx) print('Part 2 solution:', part2_sol)
def count(start, end=None, step=None): if step == 0: raise IndexError if hasattr(step, "__iter__"): raise TypeError if (hasattr(start, "__iter__") or hasattr(end, "__iter__")): return __iter_count(start, end, step) else: return __num_count(start, end, step) def __iter_count(start,end=None, step=None): items = None if hasattr(start, "__iter__"): if step is not None: raise IndexError items = start count = 0 step = end if hasattr(end, "__iter__"): count = start items = end if step is None: step = 1 for item in items: yield count, item count += step def __num_count(start, end=None, step=None): if end is None: end = start start = 0 count = start if step is None: step = 1 if start > end: if step > 0: step *= -1 while count >= end: yield count count += step else: if step < 0: step *= -1 while count <= end: yield count count += step
def count(start, end=None, step=None): if step == 0: raise IndexError if hasattr(step, '__iter__'): raise TypeError if hasattr(start, '__iter__') or hasattr(end, '__iter__'): return __iter_count(start, end, step) else: return __num_count(start, end, step) def __iter_count(start, end=None, step=None): items = None if hasattr(start, '__iter__'): if step is not None: raise IndexError items = start count = 0 step = end if hasattr(end, '__iter__'): count = start items = end if step is None: step = 1 for item in items: yield (count, item) count += step def __num_count(start, end=None, step=None): if end is None: end = start start = 0 count = start if step is None: step = 1 if start > end: if step > 0: step *= -1 while count >= end: yield count count += step else: if step < 0: step *= -1 while count <= end: yield count count += step
#!python2.7 # -*- coding: utf-8 -*- """ Created by kun on 2016/10/10. """ __author__ = 'kun'
""" Created by kun on 2016/10/10. """ __author__ = 'kun'
def prime(n): i=2 while i<=n//2: if n%i==0: return 0 i=i+1 return 1 n=2 sum=0 while n<=2000000: if prime(n): sum=sum+n n=n+1
def prime(n): i = 2 while i <= n // 2: if n % i == 0: return 0 i = i + 1 return 1 n = 2 sum = 0 while n <= 2000000: if prime(n): sum = sum + n n = n + 1
# Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order. # For example, # Given n = 3, # You should return the following matrix: # [ # [ 1, 2, 3 ], # [ 8, 9, 4 ], # [ 7, 6, 5 ] # ] class Solution: # @param {integer} n # @return {integer[][]} def generateMatrix(self, n): matrix = [[0 for x in range(n)] for x in range(n)] boundaries = [n-1, n-1, 0, 1] #r, d, l, u bi = 0 directions = [[0, 1], [1, 0], [0, -1], [-1, 0]] #r, d, l, u di = 0 e = [0, 0] ei = 1 for i in xrange(n*n): matrix[e[0]][e[1]] = i+1 if e[ei] == boundaries[bi]: boundaries[bi] -= directions[di][ei] bi = (bi+1)%4 di = (di+1)%4 ei = (ei+1)%2 e[0] += directions[di][0] e[1] += directions[di][1] return matrix
class Solution: def generate_matrix(self, n): matrix = [[0 for x in range(n)] for x in range(n)] boundaries = [n - 1, n - 1, 0, 1] bi = 0 directions = [[0, 1], [1, 0], [0, -1], [-1, 0]] di = 0 e = [0, 0] ei = 1 for i in xrange(n * n): matrix[e[0]][e[1]] = i + 1 if e[ei] == boundaries[bi]: boundaries[bi] -= directions[di][ei] bi = (bi + 1) % 4 di = (di + 1) % 4 ei = (ei + 1) % 2 e[0] += directions[di][0] e[1] += directions[di][1] return matrix
# # This file contains the Python code from Program 4.20 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm04_20.txt # class LinkedList(object): class Element(object): def insertAfter(self, item): self._next = LinkedList.Element( self._list, item, self._next) if self._list._tail is self: self._list._tail = self._next def insertBefore(self, item): tmp = LinkedList.Element(self._list, item, self) if self is self._list._head: self._list._head = tmp else: prevPtr = self._list._head while prevPtr is not None \ and prevPtr._next is not self: prevPtr = prevPtr._next prevPtr._next = tmp # ...
class Linkedlist(object): class Element(object): def insert_after(self, item): self._next = LinkedList.Element(self._list, item, self._next) if self._list._tail is self: self._list._tail = self._next def insert_before(self, item): tmp = LinkedList.Element(self._list, item, self) if self is self._list._head: self._list._head = tmp else: prev_ptr = self._list._head while prevPtr is not None and prevPtr._next is not self: prev_ptr = prevPtr._next prevPtr._next = tmp
#file = open("data.csv", "r") #for line in file: # print(line) with open("output.csv", "a") as fileout: fileout.write("Hello World") fileout.close()
with open('output.csv', 'a') as fileout: fileout.write('Hello World') fileout.close()
# -*- coding: utf-8 -*- __title__ = 'atomos' __version_info__ = ('0', '3', '1') __version__ = '.'.join(__version_info__) __author__ = 'Max Countryman' __license__ = 'BSD' __copyright__ = 'Copyright 2014 Max Countryman'
__title__ = 'atomos' __version_info__ = ('0', '3', '1') __version__ = '.'.join(__version_info__) __author__ = 'Max Countryman' __license__ = 'BSD' __copyright__ = 'Copyright 2014 Max Countryman'
# Copyright (C) 2019 Intel Corporation # # SPDX-License-Identifier: MIT class Converter: def __init__(self, cmdline_args=None): pass def __call__(self, extractor, save_dir): raise NotImplementedError() def _parse_cmdline(self, cmdline): parser = self.build_cmdline_parser() if len(cmdline) != 0 and cmdline[0] == '--': cmdline = cmdline[1:] args = parser.parse_args(cmdline) return vars(args)
class Converter: def __init__(self, cmdline_args=None): pass def __call__(self, extractor, save_dir): raise not_implemented_error() def _parse_cmdline(self, cmdline): parser = self.build_cmdline_parser() if len(cmdline) != 0 and cmdline[0] == '--': cmdline = cmdline[1:] args = parser.parse_args(cmdline) return vars(args)
class Credential : """ Class that generates new instances of credentials """ credential_list = [] def __init__ (self,account_name,email,password): """ __init__ method that helps us define properties for our objects. """ """ Args: accountname : New name of the account. email : New contact email address. password : New password of the user. """ self.account_name = account_name self.email = email self.password = password def delete_user(self): """ delete_user method deletes user objects from our user_list """ Credential.credential_list.remove(self) @classmethod def find_by_accountname(cls,accountname): """ Method that takes in an account name and returns an account that matches that account name Args: account name: Account name to search for Returns : Account of user that matches the account name. """ for user in cls.credential_list: if user.accountname == accountname: return user @classmethod def user_exist(cls,email): """ Method that checks if a user exists Args: email: Email to search if it exists Returns : Boolean: True or false depending if the contact exists """ for user in cls.credential_list: if user.email == email: return True return False @classmethod def display_users(cls): """ method that returns the user list """ return cls.credential_list
class Credential: """ Class that generates new instances of credentials """ credential_list = [] def __init__(self, account_name, email, password): """ __init__ method that helps us define properties for our objects. """ '\n Args:\n accountname : New name of the account.\n email : New contact email address.\n password : New password of the user.\n ' self.account_name = account_name self.email = email self.password = password def delete_user(self): """ delete_user method deletes user objects from our user_list """ Credential.credential_list.remove(self) @classmethod def find_by_accountname(cls, accountname): """ Method that takes in an account name and returns an account that matches that account name Args: account name: Account name to search for Returns : Account of user that matches the account name. """ for user in cls.credential_list: if user.accountname == accountname: return user @classmethod def user_exist(cls, email): """ Method that checks if a user exists Args: email: Email to search if it exists Returns : Boolean: True or false depending if the contact exists """ for user in cls.credential_list: if user.email == email: return True return False @classmethod def display_users(cls): """ method that returns the user list """ return cls.credential_list
primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251 ] # len(primes) = 54 # symbol_size = 3 # for prime in primes: # column_size = prime * symbol_size # if 1048576 % (column_size) == 1 or \ # 1048576 % (column_size) == (column_size - 1): # print('1048576 % column_size(={}, 3 * prime={}) = {}'. # format(column_size, prime, 1048576 % column_size)) divisions = (17, 32, 41) symbol_size = 3 target_size = 1048576 for d in divisions: column_size = symbol_size * d remainder = target_size % column_size if remainder == 0: padding_size = 0 else: padding_size = column_size - remainder rate = (1048576 + padding_size) / d print('(1048576 + {:3d}) / {} = {}, column_size = {:3d}, division = {}'. format(padding_size, d, rate, column_size, d)) # (1048576 + 35) / 17 = 61683.0, column_size = 51, division = 17 # (1048576 + 32) / 32 = 32769.0, column_size = 96, division = 32 # (1048576 + 122) / 41 = 25578.0, column_size = 123, division = 41 # 1048576 % prime=17 = 16 # 1048576 % prime=32 = 0 # 1048576 % prime=41 = 1 # (1048576 + 1) / 17 = 61681.0 # (1048576 + 0) / 16 = 65536.0 # (1048576 + 40) / 41 = 25576.0 # 1048576 % column_size(= 15, 3 * prime= 5) = 1 # 1048576 % column_size(= 33, 3 * prime=11) = 1 # 1048576 % column_size(= 93, 3 * prime=31) = 1 # 1048576 % column_size(=123, 3 * prime=41) = 1
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251] divisions = (17, 32, 41) symbol_size = 3 target_size = 1048576 for d in divisions: column_size = symbol_size * d remainder = target_size % column_size if remainder == 0: padding_size = 0 else: padding_size = column_size - remainder rate = (1048576 + padding_size) / d print('(1048576 + {:3d}) / {} = {}, column_size = {:3d}, division = {}'.format(padding_size, d, rate, column_size, d))
# -*- coding: utf-8 -*- RADIX = 3 BYTE_RADIX = 256 MAX_TRIT_VALUE = (RADIX - 1) // 2 MIN_TRIT_VALUE = -MAX_TRIT_VALUE NUMBER_OF_TRITS_IN_A_BYTE = 5 NUMBER_OF_TRITS_IN_A_TRYTE = 3 HASH_LENGTH = 243 BYTE_TO_TRITS_MAPPINGS = [[]] * HASH_LENGTH TRYTE_TO_TRITS_MAPPINGS = [[]] * 27 HIGH_INTEGER_BITS = 0xFFFFFFFF HIGH_LONG_BITS = 0xFFFFFFFFFFFFFFFF TRYTE_ALPHABET = '9ABCDEFGHIJKLMNOPQRSTUVWXYZ' MIN_TRYTE_VALUE = -13 MAX_TRYTE_VALUE = 13 def increment(trits, length): for i in range(length): trits[i] += 1 if trits[i] > MAX_TRIT_VALUE: trits[i] = MIN_TRIT_VALUE else: break def init_converter(): global BYTE_TO_TRITS_MAPPINGS, TRYTE_TO_TRITS_MAPPINGS trits = [0] * NUMBER_OF_TRITS_IN_A_BYTE for i in range(HASH_LENGTH): BYTE_TO_TRITS_MAPPINGS[i] = trits[:NUMBER_OF_TRITS_IN_A_BYTE] increment(trits, NUMBER_OF_TRITS_IN_A_BYTE) for i in range(27): TRYTE_TO_TRITS_MAPPINGS[i] = trits[:NUMBER_OF_TRITS_IN_A_TRYTE] increment(trits, NUMBER_OF_TRITS_IN_A_TRYTE) def from_trits_to_binary(trits, offset=0, size=HASH_LENGTH): b = bytearray(b' ' * int((size + NUMBER_OF_TRITS_IN_A_BYTE - 1) / NUMBER_OF_TRITS_IN_A_BYTE)) for i in range(len(b)): value = 0 for j in range(size - i * NUMBER_OF_TRITS_IN_A_BYTE - 1 if (size - i * NUMBER_OF_TRITS_IN_A_BYTE) < NUMBER_OF_TRITS_IN_A_BYTE else 4, -1, -1): value = value * RADIX + trits[offset + i * NUMBER_OF_TRITS_IN_A_BYTE + j] b[i] = value % 256 return bytes(b) def from_binary_to_trits(bs, length): offset = 0 trits = [0] * length for i in range(min(len(bs), length)): # We must convert the binary data # because java using different range with Python index = bs[i] if bs[i] < 127 else bs[i] - 256 + HASH_LENGTH copy_len = length - offset if length - offset < NUMBER_OF_TRITS_IN_A_BYTE else NUMBER_OF_TRITS_IN_A_BYTE trits[offset: offset + copy_len] = BYTE_TO_TRITS_MAPPINGS[index][:copy_len] offset += NUMBER_OF_TRITS_IN_A_BYTE return trits init_converter()
radix = 3 byte_radix = 256 max_trit_value = (RADIX - 1) // 2 min_trit_value = -MAX_TRIT_VALUE number_of_trits_in_a_byte = 5 number_of_trits_in_a_tryte = 3 hash_length = 243 byte_to_trits_mappings = [[]] * HASH_LENGTH tryte_to_trits_mappings = [[]] * 27 high_integer_bits = 4294967295 high_long_bits = 18446744073709551615 tryte_alphabet = '9ABCDEFGHIJKLMNOPQRSTUVWXYZ' min_tryte_value = -13 max_tryte_value = 13 def increment(trits, length): for i in range(length): trits[i] += 1 if trits[i] > MAX_TRIT_VALUE: trits[i] = MIN_TRIT_VALUE else: break def init_converter(): global BYTE_TO_TRITS_MAPPINGS, TRYTE_TO_TRITS_MAPPINGS trits = [0] * NUMBER_OF_TRITS_IN_A_BYTE for i in range(HASH_LENGTH): BYTE_TO_TRITS_MAPPINGS[i] = trits[:NUMBER_OF_TRITS_IN_A_BYTE] increment(trits, NUMBER_OF_TRITS_IN_A_BYTE) for i in range(27): TRYTE_TO_TRITS_MAPPINGS[i] = trits[:NUMBER_OF_TRITS_IN_A_TRYTE] increment(trits, NUMBER_OF_TRITS_IN_A_TRYTE) def from_trits_to_binary(trits, offset=0, size=HASH_LENGTH): b = bytearray(b' ' * int((size + NUMBER_OF_TRITS_IN_A_BYTE - 1) / NUMBER_OF_TRITS_IN_A_BYTE)) for i in range(len(b)): value = 0 for j in range(size - i * NUMBER_OF_TRITS_IN_A_BYTE - 1 if size - i * NUMBER_OF_TRITS_IN_A_BYTE < NUMBER_OF_TRITS_IN_A_BYTE else 4, -1, -1): value = value * RADIX + trits[offset + i * NUMBER_OF_TRITS_IN_A_BYTE + j] b[i] = value % 256 return bytes(b) def from_binary_to_trits(bs, length): offset = 0 trits = [0] * length for i in range(min(len(bs), length)): index = bs[i] if bs[i] < 127 else bs[i] - 256 + HASH_LENGTH copy_len = length - offset if length - offset < NUMBER_OF_TRITS_IN_A_BYTE else NUMBER_OF_TRITS_IN_A_BYTE trits[offset:offset + copy_len] = BYTE_TO_TRITS_MAPPINGS[index][:copy_len] offset += NUMBER_OF_TRITS_IN_A_BYTE return trits init_converter()
""" `adafruit_hid` ==================================================== This driver simulates USB HID devices. Currently keyboard and mouse are implemented. * Author(s): Scott Shawcroft, Dan Halbert """
""" `adafruit_hid` ==================================================== This driver simulates USB HID devices. Currently keyboard and mouse are implemented. * Author(s): Scott Shawcroft, Dan Halbert """
class AttributeDict(dict): __slots__ = () __getattr__ = dict.__getitem__ __setattr__ = dict.__setitem__ def __init__(self, dictionary: dict = {}): super().__init__() self.update(dictionary) _defaults = AttributeDict({ "master": "master", "develop": "develop", "features": "feature", "fixes": "bugfix", "releases": "release", "hotfixes": "hotfix", "others": ["spike"], }) class Gitflow(AttributeDict): """ Contains all settings related to branches from YAML file. It extends :class:`AttributeDict <AttributeDict>`, so settings may be accessed like properties: ``gitflow.features`` It will contain custom settings if you add them in YAML file as a child of ``branches`` node. """ def __init__(self, settings: dict): defaults = _defaults.copy() if settings and settings.get('branches', None): defaults.update(settings['branches']) super().__init__(dictionary=defaults) class RulesContainer: def __init__(self, rules: dict): if not rules or not rules.get('rules', None): raise KeyError('Yaml file does not contain rules') self._rules = rules['rules'] @property def rules(self): return self._rules.keys() def args_for(self, rule) -> dict: return self._rules.get(rule, {}) def consume(self, rule: str): del self._rules[rule]
class Attributedict(dict): __slots__ = () __getattr__ = dict.__getitem__ __setattr__ = dict.__setitem__ def __init__(self, dictionary: dict={}): super().__init__() self.update(dictionary) _defaults = attribute_dict({'master': 'master', 'develop': 'develop', 'features': 'feature', 'fixes': 'bugfix', 'releases': 'release', 'hotfixes': 'hotfix', 'others': ['spike']}) class Gitflow(AttributeDict): """ Contains all settings related to branches from YAML file. It extends :class:`AttributeDict <AttributeDict>`, so settings may be accessed like properties: ``gitflow.features`` It will contain custom settings if you add them in YAML file as a child of ``branches`` node. """ def __init__(self, settings: dict): defaults = _defaults.copy() if settings and settings.get('branches', None): defaults.update(settings['branches']) super().__init__(dictionary=defaults) class Rulescontainer: def __init__(self, rules: dict): if not rules or not rules.get('rules', None): raise key_error('Yaml file does not contain rules') self._rules = rules['rules'] @property def rules(self): return self._rules.keys() def args_for(self, rule) -> dict: return self._rules.get(rule, {}) def consume(self, rule: str): del self._rules[rule]
#encoding:utf-8 subreddit = 'HQDesi' t_channel = '@r_HqDesi' def send_post(submission, r2t): return r2t.send_simple(submission)
subreddit = 'HQDesi' t_channel = '@r_HqDesi' def send_post(submission, r2t): return r2t.send_simple(submission)
class OrderElement: def __init__(self, product, quantity): self.product = product self.quantity = quantity def calculate_price(self): return self.product.unit_price * self.quantity def __str__(self): return f"{self.product} x {self.quantity}"
class Orderelement: def __init__(self, product, quantity): self.product = product self.quantity = quantity def calculate_price(self): return self.product.unit_price * self.quantity def __str__(self): return f'{self.product} x {self.quantity}'
#!/usr/bin/env python3 class Parser: def __init__(self): self.token = None self.remained_token = None '''from regex string to NFA class''' def parse(self, regex_str): if len(regex_str) == 0: print("The compiled content is empty. Stop parsing.") return None regex_str_list = [i for i in regex_str] + [None] self.token = regex_str_list[0] self.remained_token = regex_str_list[1:] result = self.re() return result def advance(self): self.token = self.remained_token[0] self.remained_token = self.remained_token[1:] '''<RE> ::= (<simple-RE> "|" RE>) | <simple-RE>''' def re(self): result = self.simple_re() while self.token == "|": result_head = self.token self.advance() rhs = self.simple_re() result = [result_head, result, rhs] rhs = result return result '''<simple-RE> ::= <basic-RE>+''' def simple_re(self): result = self.basic_re() # self.token != ")" and self.token != "|" is used to fix the bug while self.token != None and self.token != ")" and self.token != "|": result_head = "CONC" # concat rhs = self.basic_re() result = [result_head, result, rhs] rhs = result return result '''<basic-RE> ::= <elementary-RE> "*" | <elementary-RE> "?" | elementary-RE> "+" | <elementary-RE>''' def basic_re(self): result = self.elementary_re() if self.token == "*": self.advance() result = ["STAR", result] elif self.token == "?": self.advance() result = ["QUESTION", result] elif self.token == "+": self.advance() result = ["PLUS", result] return result '''<elementary-RE> ::= <group> | <any> | <char> | <char-set>''' '''<group> ::= "(" <RE> ")"''' def elementary_re(self): # <group> ::= "(" <RE> ")" if self.token == "(": self.advance() result = self.re() if self.token != ")": raise("Except \")\", found %s", self.token) self.advance() result = [result] elif self.token == ".": self.advance() result = "ANY" elif self.token == "[": result = self.char_set() else: result = self.char() return result '''<char> ::= any non metacharacter | "\" metacharacter''' '''metacharacter = set{ \ * + . \ [ ] ( ) | }''' def char(self): meta_char_list = ["*", "+", ".", "\\", "[", "]", "(", ")", "|", "?"] # \ + metacharacter if self.token == "\\": self.advance() if self.token in meta_char_list: result = self.token self.advance() return result else: # exception description exception_desc = "Expect" + ", ".join(meta_char_list) + " , found \"%s\"" % self.token raise(exception_desc) else: if self.token in meta_char_list: print("Caution: \"%s\" is not recommended to be singly used." % self.token) result = self.token self.advance() return result '''<char-set> ::= <positive-set> | <negative-set>''' def char_set(self): # token [ is checked in elementary_re. so advance() self.advance() '''<negative-set> ::= "[^" <set-items> "]"''' if self.token == "^": result_rhs = self.set_items() result = ["NOT", result_rhs] else: result = self.set_items() return result def set_items(self): result = ["SET"] if self.token != "]": result.append(self.set_item()) return result '''<set-item> ::= <range> | <char> <range> ::= <char> "-" <char>''' def set_item(self): result = self.char() # range = <char> "-" <char> if self.token == "-": result_lhs = result self.advance() result_rhs = self.char() result = ["RANGE", result_lhs, result_rhs] return result regex_parser = Parser() print(regex_parser.parse("(abc)")) print(regex_parser.parse("(a|bc)")) print(regex_parser.parse("a*bc")) print(regex_parser.parse("(a*|b)c")) print(regex_parser.parse("a+bc")) print(regex_parser.parse("(a+|b)c")) print(regex_parser.parse("a*+bc")) print(regex_parser.parse("a*+bc"))
class Parser: def __init__(self): self.token = None self.remained_token = None 'from regex string to NFA class' def parse(self, regex_str): if len(regex_str) == 0: print('The compiled content is empty. Stop parsing.') return None regex_str_list = [i for i in regex_str] + [None] self.token = regex_str_list[0] self.remained_token = regex_str_list[1:] result = self.re() return result def advance(self): self.token = self.remained_token[0] self.remained_token = self.remained_token[1:] '<RE> \t::= (<simple-RE> "|" RE>) | <simple-RE>' def re(self): result = self.simple_re() while self.token == '|': result_head = self.token self.advance() rhs = self.simple_re() result = [result_head, result, rhs] rhs = result return result '<simple-RE> \t::= <basic-RE>+' def simple_re(self): result = self.basic_re() while self.token != None and self.token != ')' and (self.token != '|'): result_head = 'CONC' rhs = self.basic_re() result = [result_head, result, rhs] rhs = result return result '<basic-RE> \t::=\t<elementary-RE> "*" | <elementary-RE> "?" | elementary-RE> "+" | <elementary-RE>' def basic_re(self): result = self.elementary_re() if self.token == '*': self.advance() result = ['STAR', result] elif self.token == '?': self.advance() result = ['QUESTION', result] elif self.token == '+': self.advance() result = ['PLUS', result] return result '<elementary-RE> \t::=\t<group> | <any> | <char> | <char-set>' '<group> \t::= \t"(" <RE> ")"' def elementary_re(self): if self.token == '(': self.advance() result = self.re() if self.token != ')': raise ('Except ")", found %s', self.token) self.advance() result = [result] elif self.token == '.': self.advance() result = 'ANY' elif self.token == '[': result = self.char_set() else: result = self.char() return result '<char> \t::= \tany non metacharacter | "" metacharacter' 'metacharacter = set{ \\ * + . \\ [ ] ( ) | }' def char(self): meta_char_list = ['*', '+', '.', '\\', '[', ']', '(', ')', '|', '?'] if self.token == '\\': self.advance() if self.token in meta_char_list: result = self.token self.advance() return result else: exception_desc = 'Expect' + ', '.join(meta_char_list) + ' , found "%s"' % self.token raise exception_desc else: if self.token in meta_char_list: print('Caution: "%s" is not recommended to be singly used.' % self.token) result = self.token self.advance() return result '<char-set> \t::= \t<positive-set> | <negative-set>' def char_set(self): self.advance() '<negative-set> \t::= \t"[^" <set-items> "]"' if self.token == '^': result_rhs = self.set_items() result = ['NOT', result_rhs] else: result = self.set_items() return result def set_items(self): result = ['SET'] if self.token != ']': result.append(self.set_item()) return result '<set-item> \t::= \t<range> | <char>\n <range> \t::= \t<char> "-" <char>' def set_item(self): result = self.char() if self.token == '-': result_lhs = result self.advance() result_rhs = self.char() result = ['RANGE', result_lhs, result_rhs] return result regex_parser = parser() print(regex_parser.parse('(abc)')) print(regex_parser.parse('(a|bc)')) print(regex_parser.parse('a*bc')) print(regex_parser.parse('(a*|b)c')) print(regex_parser.parse('a+bc')) print(regex_parser.parse('(a+|b)c')) print(regex_parser.parse('a*+bc')) print(regex_parser.parse('a*+bc'))
def isgreaterthan20(number1,number2): print(number1) print(number2) num=20 num1=10 isgreaterthan20(num,num1)
def isgreaterthan20(number1, number2): print(number1) print(number2) num = 20 num1 = 10 isgreaterthan20(num, num1)
class Solution: def findDuplicates(self, nums): """ :type nums: List[int] :rtype: List[int] """ memo={} for i,v in enumerate(nums): if memo.get(v) is None: memo[v]=1 else: memo[v]+=1 result=[] for i in memo: if memo[i]==2: result.append(i) return result if __name__=='__main__': solution = Solution() t1=[4,3,2,7,8,2,3,1] print(solution.findDuplicates(t1))
class Solution: def find_duplicates(self, nums): """ :type nums: List[int] :rtype: List[int] """ memo = {} for (i, v) in enumerate(nums): if memo.get(v) is None: memo[v] = 1 else: memo[v] += 1 result = [] for i in memo: if memo[i] == 2: result.append(i) return result if __name__ == '__main__': solution = solution() t1 = [4, 3, 2, 7, 8, 2, 3, 1] print(solution.findDuplicates(t1))
# -*- coding:utf-8 -*- """ Description: Transaction Type in AntShares Usage: from AntShares.Core.TransactionType import TransactionType """ class TransactionType(object): MinerTransaction = 0x00 IssueTransaction = 0x01 ClaimTransaction = 0x02 EnrollmentTransaction = 0x20 VotingTransaction = 0x24 RegisterTransaction = 0x40 ContractTransaction = 0x80 AgencyTransaction = 0xb0
""" Description: Transaction Type in AntShares Usage: from AntShares.Core.TransactionType import TransactionType """ class Transactiontype(object): miner_transaction = 0 issue_transaction = 1 claim_transaction = 2 enrollment_transaction = 32 voting_transaction = 36 register_transaction = 64 contract_transaction = 128 agency_transaction = 176
class InvalidIdError(RuntimeError): def __init__(self, id_value): super(InvalidIdError, self).__init__() self.id = id_value
class Invalididerror(RuntimeError): def __init__(self, id_value): super(InvalidIdError, self).__init__() self.id = id_value
sku = [{"name": "id", "type": "varchar(256)"}, {"name": "object", "type": "varchar(256)"}, {"name": "active", "type": "boolean"}, {"name": "attributes", "type": "varchar(max)"}, {"name": "created", "type": "timestamp"}, {"name": "currency", "type": "varchar(256)"}, {"name": "image", "type": "varchar(256)"}, {"name": "inventory", "type": "varchar(512)"}, {"name": "livemode", "type": "boolean"}, {"name": "metadata", "type": "varchar(max)"}, {"name": "package_dimensions", "type": "varchar(512)"}, {"name": "price", "type": "integer"}, {"name": "product", "type": "varchar(256)"}, {"name": "updated", "type": "timestamp"}]
sku = [{'name': 'id', 'type': 'varchar(256)'}, {'name': 'object', 'type': 'varchar(256)'}, {'name': 'active', 'type': 'boolean'}, {'name': 'attributes', 'type': 'varchar(max)'}, {'name': 'created', 'type': 'timestamp'}, {'name': 'currency', 'type': 'varchar(256)'}, {'name': 'image', 'type': 'varchar(256)'}, {'name': 'inventory', 'type': 'varchar(512)'}, {'name': 'livemode', 'type': 'boolean'}, {'name': 'metadata', 'type': 'varchar(max)'}, {'name': 'package_dimensions', 'type': 'varchar(512)'}, {'name': 'price', 'type': 'integer'}, {'name': 'product', 'type': 'varchar(256)'}, {'name': 'updated', 'type': 'timestamp'}]
def import_code_query(path, project_name=None, language=None): if not path: raise Exception('An importCode query requires a project path') if project_name and language: fmt_str = u"""importCode(inputPath=\"%s\", projectName=\"%s\", language=\"%s\")""" return fmt_str % (path, project_name, language) if project_name and (language is None): fmt_str = u"""importCode(inputPath=\"%s\", projectName=\"%s\")""" return fmt_str % (path, project_name) return u"importCode(\"%s\")" % (path) def workspace_query(): return "workspace"
def import_code_query(path, project_name=None, language=None): if not path: raise exception('An importCode query requires a project path') if project_name and language: fmt_str = u'importCode(inputPath="%s", projectName="%s",\nlanguage="%s")' return fmt_str % (path, project_name, language) if project_name and language is None: fmt_str = u'importCode(inputPath="%s", projectName="%s")' return fmt_str % (path, project_name) return u'importCode("%s")' % path def workspace_query(): return 'workspace'
#no refactoring class hash_test: participant = ["leo","kiki","eden"] completion = ["leo","kiki"] p = 31 m = 0xfffff x = 0 hash_table = list([0 for i in range(m)]) unfinished = list() # polynomial rolling hash function. for i in participant: print(i) mod_value=0 for j in i: mod_value = mod_value + ord(j)*pow(p,x) x+=1 hash_table[mod_value % m] = 1 #hash for completion for k in completion: print(k) mod_value=0 for j in i: mod_value = mod_value + ord(j)*pow(p,x) x+=1 if hash_table[mod_value % m] != 1: unfinished.append(i) print("unfinished="+i)
class Hash_Test: participant = ['leo', 'kiki', 'eden'] completion = ['leo', 'kiki'] p = 31 m = 1048575 x = 0 hash_table = list([0 for i in range(m)]) unfinished = list() for i in participant: print(i) mod_value = 0 for j in i: mod_value = mod_value + ord(j) * pow(p, x) x += 1 hash_table[mod_value % m] = 1 for k in completion: print(k) mod_value = 0 for j in i: mod_value = mod_value + ord(j) * pow(p, x) x += 1 if hash_table[mod_value % m] != 1: unfinished.append(i) print('unfinished=' + i)
# -*- coding: utf-8 - # # This file is part of tproxy released under the MIT license. # See the NOTICE for more information. version_info = (0, 5, 4) __version__ = ".".join(map(str, version_info))
version_info = (0, 5, 4) __version__ = '.'.join(map(str, version_info))
"""Errors raised by mailmerge.""" class MailmergeError(Exception): """Top level exception raised by mailmerge functions."""
"""Errors raised by mailmerge.""" class Mailmergeerror(Exception): """Top level exception raised by mailmerge functions."""
def eh_primo(x): if (x==3) or (x==2): return True if (x<2) or (x%2==0): return False for i in range(3, int(x**0.5)+1, 2): if x%i==0: return False return True def sup_primo(num): while num >= 10: sup = num % 10 num = int(num / 10) if not eh_primo(sup): return 0 if((num == 2) or (num == 3) or (num == 5) or (num == 7)): return True else: return False while(True): try: # (Entrada) n = input() if len(n)==0: break else: n = int(n) if not eh_primo(n): print("Nada") else: if sup_primo(n): print("Super") else: print("Primo") except EOFError: break
def eh_primo(x): if x == 3 or x == 2: return True if x < 2 or x % 2 == 0: return False for i in range(3, int(x ** 0.5) + 1, 2): if x % i == 0: return False return True def sup_primo(num): while num >= 10: sup = num % 10 num = int(num / 10) if not eh_primo(sup): return 0 if num == 2 or num == 3 or num == 5 or (num == 7): return True else: return False while True: try: n = input() if len(n) == 0: break else: n = int(n) if not eh_primo(n): print('Nada') elif sup_primo(n): print('Super') else: print('Primo') except EOFError: break
# -*- coding: iso-8859-1 -*- """ MoinMoin - Widget base class @copyright: 2002 Juergen Hermann <jh@web.de> @license: GNU GPL, see COPYING for details. """ class Widget: def __init__(self, request, **kw): self.request = request def render(self): raise NotImplementedError
""" MoinMoin - Widget base class @copyright: 2002 Juergen Hermann <jh@web.de> @license: GNU GPL, see COPYING for details. """ class Widget: def __init__(self, request, **kw): self.request = request def render(self): raise NotImplementedError
#listing #representacion de grafos a,b,c,d,e,f,g,h = range(8) N = [{b:2,c:1,d:3,e:9,f:4}, #a {c:4,e:3}, #b {d:8}, #c {e:7}, #d {f:5}, #e {c:2,g:2,h:2}, #f {f:1,h:6}, #g {f:9,g:8}] #h print(b in N[a]) #neighborhood membership/es vecino b de a?? print(len(N[f])) #degree of f print(N[a][b]) #edge weight for (a,b) input() #matrix for graphs #matriz de adyacencia # a b c d e f g h M = [[0,1,1,1,1,1,0,0], #a [0,0,1,0,1,0,0,0], #b [0,0,0,1,0,0,0,0], #c [0,0,0,0,1,0,0,0], #d [0,0,0,0,0,1,0,0], #e [0,0,0,1,0,0,1,1], #f [0,0,0,0,0,1,0,1], #g [0,0,0,0,0,1,1,0]] #h print(sum(M[a])) input() #representacionde nodos con infinito a traves de matrices: #a weight matrix with infinite weighr for missing edges print("------------------------------") a,b,c,d,e,f,g,h = range(8) _ = float('inf') # a b c d e f g h G = [[0,2,1,3,9,4,_,_], #a [_,0,4,_,3,_,_,_], #b [_,_,0,8,_,_,_,_], #c [_,_,_,0,7,_,_,_], #d [_,_,_,_,0,5,_,_], #e [_,_,2,_,_,0,2,2], #f [_,_,_,_,_,1,0,6], #g [_,_,_,_,_,9,8,0]] #h print(G[a][b] < _) print(G[c][e] < _) print(sum(1 for g in G[a] if g < _)-1) #degree #note: 1 is substracted from G[a] because we dont want the o from the diagonal input()
(a, b, c, d, e, f, g, h) = range(8) n = [{b: 2, c: 1, d: 3, e: 9, f: 4}, {c: 4, e: 3}, {d: 8}, {e: 7}, {f: 5}, {c: 2, g: 2, h: 2}, {f: 1, h: 6}, {f: 9, g: 8}] print(b in N[a]) print(len(N[f])) print(N[a][b]) input() m = [[0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 0, 1, 1, 0]] print(sum(M[a])) input() print('------------------------------') (a, b, c, d, e, f, g, h) = range(8) _ = float('inf') g = [[0, 2, 1, 3, 9, 4, _, _], [_, 0, 4, _, 3, _, _, _], [_, _, 0, 8, _, _, _, _], [_, _, _, 0, 7, _, _, _], [_, _, _, _, 0, 5, _, _], [_, _, 2, _, _, 0, 2, 2], [_, _, _, _, _, 1, 0, 6], [_, _, _, _, _, 9, 8, 0]] print(G[a][b] < _) print(G[c][e] < _) print(sum((1 for g in G[a] if g < _)) - 1) input()
class Config(object): _instance = None def __new__(self): if not self._instance: self._instance = super(Config, self).__new__(self) return self._instance def setConfig(self, config): self.config = config def get(self, key): return self.config[key] def getAll(self): return self.config
class Config(object): _instance = None def __new__(self): if not self._instance: self._instance = super(Config, self).__new__(self) return self._instance def set_config(self, config): self.config = config def get(self, key): return self.config[key] def get_all(self): return self.config
# Faca um programa que tenha uma funcao # chamada area(), # que receba as dimensoes de um terreno # retangular(largura e comprimento) e mostre a # area do terreno def area(larg, comp): a = larg * comp print(f'A area de um terreno {larg} x {comp} eh de {a}m2.') print(' Controle de Terrenos') print('-' * 20) l = float(input('Largura (m): ')) c = float(input('Comprimento (m): ')) area(l, c)
def area(larg, comp): a = larg * comp print(f'A area de um terreno {larg} x {comp} eh de {a}m2.') print(' Controle de Terrenos') print('-' * 20) l = float(input('Largura (m): ')) c = float(input('Comprimento (m): ')) area(l, c)
class Solution: def findMinFibonacciNumbers(self, k: int) -> int: fib = [] fib.extend([1, 1]) j = 1 i = 2 # calculate fibonacci number greater than k while j < k: x = fib[i - 1] + fib[i - 2] fib.append(x) i += 1 j = x count = 0 for i in range(len(fib) - 1, -1, -1): print(fib[i], k) if fib[i] == k: count += 1 break elif fib[i] < k: k = k - fib[i] count += 1 return count
class Solution: def find_min_fibonacci_numbers(self, k: int) -> int: fib = [] fib.extend([1, 1]) j = 1 i = 2 while j < k: x = fib[i - 1] + fib[i - 2] fib.append(x) i += 1 j = x count = 0 for i in range(len(fib) - 1, -1, -1): print(fib[i], k) if fib[i] == k: count += 1 break elif fib[i] < k: k = k - fib[i] count += 1 return count
input() groups = sorted([ int(i) for i in input().split() ], reverse=True) cars = 0 i = 0 j = len(groups) - 1 while i <= j: g = groups[i] if g == 4: i += 1 cars += 1 continue cur_car = g while groups[j] <= 4 - cur_car and i < j: cur_car += groups[j] j -= 1 i += 1 cars += 1 print(cars)
input() groups = sorted([int(i) for i in input().split()], reverse=True) cars = 0 i = 0 j = len(groups) - 1 while i <= j: g = groups[i] if g == 4: i += 1 cars += 1 continue cur_car = g while groups[j] <= 4 - cur_car and i < j: cur_car += groups[j] j -= 1 i += 1 cars += 1 print(cars)
def auto_newline(text: str, max_line_length: int): def wrap_line_helper(line: str): words = line.split(" ") wrapped_line = [] current_line = "" for word in words: current_line += word if len(current_line) > max_line_length: current_line = " ".join(current_line.split(" ")[:-1]) wrapped_line.append(current_line) current_line = word current_line += " " wrapped_line.append(current_line[:-1]) return "\n".join(wrapped_line) lines = text.split("\n") wrapped_lines = [] for line1 in lines: wrapped_lines.append(wrap_line_helper(line1)) return "\n".join(wrapped_lines)
def auto_newline(text: str, max_line_length: int): def wrap_line_helper(line: str): words = line.split(' ') wrapped_line = [] current_line = '' for word in words: current_line += word if len(current_line) > max_line_length: current_line = ' '.join(current_line.split(' ')[:-1]) wrapped_line.append(current_line) current_line = word current_line += ' ' wrapped_line.append(current_line[:-1]) return '\n'.join(wrapped_line) lines = text.split('\n') wrapped_lines = [] for line1 in lines: wrapped_lines.append(wrap_line_helper(line1)) return '\n'.join(wrapped_lines)
def explore(lines): y = 0 x = lines[0].index('|') dx = 0 dy = 1 answer = '' steps = 0 while True: x += dx y += dy if lines[y][x] == '+': if x < (len(lines[y]) - 1) and lines[y][x+1].strip() and dx != -1: dx = 1 dy = 0 elif y < (len(lines) - 1) and x < len(lines[y+1]) and lines[y+1][x].strip() and dy != -1: dx = 0 dy = 1 elif y > 0 and x < len(lines[y-1]) and lines[y-1][x].strip() and dy != 1: dx = 0 dy = -1 elif x > 0 and lines[y][x-1].strip() and dx != 1: dx = -1 dy = 0 elif lines[y][x] == ' ': break elif lines[y][x] not in ('-', '|'): answer += lines[y][x] steps += 1 return answer, steps + 1 def test_explore(): assert ('ABCDEF', 38) == explore(open("input/dec19_test").readlines()) if __name__ == "__main__": print(explore(open("input/dec19").readlines()))
def explore(lines): y = 0 x = lines[0].index('|') dx = 0 dy = 1 answer = '' steps = 0 while True: x += dx y += dy if lines[y][x] == '+': if x < len(lines[y]) - 1 and lines[y][x + 1].strip() and (dx != -1): dx = 1 dy = 0 elif y < len(lines) - 1 and x < len(lines[y + 1]) and lines[y + 1][x].strip() and (dy != -1): dx = 0 dy = 1 elif y > 0 and x < len(lines[y - 1]) and lines[y - 1][x].strip() and (dy != 1): dx = 0 dy = -1 elif x > 0 and lines[y][x - 1].strip() and (dx != 1): dx = -1 dy = 0 elif lines[y][x] == ' ': break elif lines[y][x] not in ('-', '|'): answer += lines[y][x] steps += 1 return (answer, steps + 1) def test_explore(): assert ('ABCDEF', 38) == explore(open('input/dec19_test').readlines()) if __name__ == '__main__': print(explore(open('input/dec19').readlines()))
# Search in Rotated Sorted Array: https://leetcode.com/problems/search-in-rotated-sorted-array/ # There is an integer array nums sorted in ascending order (with distinct values). # Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. # Given the array nums after the rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. # You must write an algorithm with O(log n) runtime complexity. # This is a basic binary search the only difference is that we need to check if the values are sorted from high to mid so that we know wether to follow the traditional patern # or to traverse the other way as the shift occurs on the other side class Solution: def search(self, nums, target: int) -> int: lo, hi = 0, len(nums) - 1 while lo <= hi: mid = lo + (hi - lo) // 2 if nums[mid] == target: return mid else: # Is it properly sorted? if nums[mid] >= nums[lo]: # Now since we know where it is supposed to be we need to check if it can be here if target >= nums[lo] and target <= nums[mid]: hi = mid - 1 else: lo = mid + 1 else: if target <= nums[hi] and target > nums[mid]: lo = mid + 1 else: hi = mid - 1 return -1 # So this is pretty standard the only weird hiccup is finding whether or not you have a sorted segment or not # this runs in o(logn) and O(1) # Score Card # Did I need hints? N # Did you finish within 30 min? 10 # Was the solution optimal? This is optimal # Were there any bugs? No # 5 5 5 5 = 5
class Solution: def search(self, nums, target: int) -> int: (lo, hi) = (0, len(nums) - 1) while lo <= hi: mid = lo + (hi - lo) // 2 if nums[mid] == target: return mid elif nums[mid] >= nums[lo]: if target >= nums[lo] and target <= nums[mid]: hi = mid - 1 else: lo = mid + 1 elif target <= nums[hi] and target > nums[mid]: lo = mid + 1 else: hi = mid - 1 return -1
class Solution: def rotate(self, nums: List[int], k: int) -> None: k %= len(nums) if k > 0: for i, v in enumerate(nums[-k:] + nums[0:-k]): nums[i] = v
class Solution: def rotate(self, nums: List[int], k: int) -> None: k %= len(nums) if k > 0: for (i, v) in enumerate(nums[-k:] + nums[0:-k]): nums[i] = v
# sort given sequence given that the numbers go from 1 to n def cyclic_sort(seq): for i in range(len(seq)): num = seq[i] if num != seq[num-1]: # swap seq[num-1], seq[i] = seq[i], seq[num-1] def main(): seq = [5,4,1,2,3] cyclic_sort(seq) print(f'seq = {seq}') if __name__ == "__main__": main()
def cyclic_sort(seq): for i in range(len(seq)): num = seq[i] if num != seq[num - 1]: (seq[num - 1], seq[i]) = (seq[i], seq[num - 1]) def main(): seq = [5, 4, 1, 2, 3] cyclic_sort(seq) print(f'seq = {seq}') if __name__ == '__main__': main()
class Student: # Using a global base for all the available courses numReg = [] # We will initalise the student class def __init__(self, number, name, family, courses=None): if courses is None: courses = [] self.number = number self.numReg.append(self) self.name = name self.family = family self.courses = courses # This is used to display the student details def displayStudent(self): print('You are logged in as ' + self.name + ' ' + self.family) # This is used to display the number of courses a student takes up during his term/semester def displayStudentCourses(self, numStudent): if self.number == numStudent: if self.courses: print(self.courses) else: print('You have not selected any courses. Please choose a course.') # Using this, the selected course will be added to the student's portfolio/data def studentCourseAdding(self, wantedCourse, numStudent): if self.number == numStudent: self.courses.append(wantedCourse) print('You Added ' + wantedCourse + ' to your schedule, successfully!')
class Student: num_reg = [] def __init__(self, number, name, family, courses=None): if courses is None: courses = [] self.number = number self.numReg.append(self) self.name = name self.family = family self.courses = courses def display_student(self): print('You are logged in as ' + self.name + ' ' + self.family) def display_student_courses(self, numStudent): if self.number == numStudent: if self.courses: print(self.courses) else: print('You have not selected any courses. Please choose a course.') def student_course_adding(self, wantedCourse, numStudent): if self.number == numStudent: self.courses.append(wantedCourse) print('You Added ' + wantedCourse + ' to your schedule, successfully!')
class Task: """ Abstract class defining a task. A task is an atomic action (i.e: switch on/off light, play music, etc ...) It can take arguments which will be defined by the user (i.e: turn off light between 9 am and 1 pm. 9 and 1 can be defined as parameters given by user). """ def __init__(self, name: str): assert len(name) > 0, "A task name can't be empty" self.name = name self.arguments = {} def register_argument(self, name: str, arg_type: dict): """ Registers an argument with the specified name and the specified type. This argument will then be filled up by user. Example: import arg_type register_argument("age", arg_type.integer(min=0)) :param name: the argument name (str) :param arg_type: the argument type (dict: {type: str}), please use arg_type package to specify this argument """ assert "type" in arg_type, "Argument 'arg_type' must contain key 'type'" if name in self.arguments: print("[WARNING] Task {} registers two arguments with the same name ({}). " "Second registration will override first one.".format(self.name, name)) self.arguments[name] = arg_type def on_validation(self, arg_values: dict): """ Called when user entered valid arguments. You can use this method to perform additional checks on values (i.e if an argument correspond to a website url, ping this website to see if it exists). :param arg_values: a dict mapping arguments name to their value :return: a tuple containing two values. The first one indicates if the values for arguments are still valid, the second one is the error message which will be displayed in case the first value is False """ return True, None def execute_task(self, arg_values: dict): """ Executes the action corresponding to the task. :param arg_values: a dict linking each argument name to it's value """ print("The task {} does nothing when ran.".format(self.name))
class Task: """ Abstract class defining a task. A task is an atomic action (i.e: switch on/off light, play music, etc ...) It can take arguments which will be defined by the user (i.e: turn off light between 9 am and 1 pm. 9 and 1 can be defined as parameters given by user). """ def __init__(self, name: str): assert len(name) > 0, "A task name can't be empty" self.name = name self.arguments = {} def register_argument(self, name: str, arg_type: dict): """ Registers an argument with the specified name and the specified type. This argument will then be filled up by user. Example: import arg_type register_argument("age", arg_type.integer(min=0)) :param name: the argument name (str) :param arg_type: the argument type (dict: {type: str}), please use arg_type package to specify this argument """ assert 'type' in arg_type, "Argument 'arg_type' must contain key 'type'" if name in self.arguments: print('[WARNING] Task {} registers two arguments with the same name ({}). Second registration will override first one.'.format(self.name, name)) self.arguments[name] = arg_type def on_validation(self, arg_values: dict): """ Called when user entered valid arguments. You can use this method to perform additional checks on values (i.e if an argument correspond to a website url, ping this website to see if it exists). :param arg_values: a dict mapping arguments name to their value :return: a tuple containing two values. The first one indicates if the values for arguments are still valid, the second one is the error message which will be displayed in case the first value is False """ return (True, None) def execute_task(self, arg_values: dict): """ Executes the action corresponding to the task. :param arg_values: a dict linking each argument name to it's value """ print('The task {} does nothing when ran.'.format(self.name))
############################################################################### ############################################################################### #Copyright (c) 2016, Andy Schroder #See the file README.md for licensing information. ############################################################################### ############################################################################### ################################################################################################# #Input parameters ################################################################################################# ########################### #cycle input parameters ########################### CycleInputParameters['MaximumTemperature']=650.0+273.0 CycleInputParameters['StartingProperties']['Temperature']=273.0+47 CycleInputParameters['FluidType']='Carbon Dioxide' CycleInputParameters['PowerOutput']=1.0*10**6 #1MW ########################### #common recuperator parameters DeltaPPerDeltaT=0 ########################### #piston related design assumptions and required pressure ratio ########################### CycleInputParameters['Piston']['MassFraction']=1.0 CycleInputParameters['Piston']['IsentropicEfficiency']=1.0 ########################### #heater related design assumptions ########################### CycleInputParameters['SecondPlusThirdHeating']['MaximumTemperature']=CycleInputParameters['MaximumTemperature'] CycleInputParameters['SecondPlusThirdHeating']['MassFraction']=1 CycleInputParameters['SecondPlusThirdHeating']['DeltaPPerDeltaT']=DeltaPPerDeltaT ########################### #cooler related design assumptions ########################### CycleInputParameters['TotalFractionCooler']['MinimumTemperature']=CycleInputParameters['StartingProperties']['Temperature'] CycleInputParameters['TotalFractionCooler']['MassFraction']=1 CycleInputParameters['TotalFractionCooler']['DeltaPPerDeltaT']=DeltaPPerDeltaT ########################### #recuperator related design assumptions ########################### CycleInputParameters['HTRecuperator']['NumberofTemperatures']=200 #keep in mind that the resolution of the data being interpolated is the real upper limit on the usefulness of this value CycleInputParameters['HTRecuperator']['LowPressure']['MassFraction']=1 CycleInputParameters['HTRecuperator']['HighPressure']['MassFraction']=1 CycleInputParameters['HTRecuperator']['HighPressure']['ConstantVolume']=True CycleInputParameters['HTRecuperator']['DeltaPPerDeltaT']=DeltaPPerDeltaT #maybe this should be different for high and low pressure sides? CycleInputParameters['HTRecuperator']['MinimumDeltaT']=0 ################################################################################################# #end Input parameters #################################################################################################
CycleInputParameters['MaximumTemperature'] = 650.0 + 273.0 CycleInputParameters['StartingProperties']['Temperature'] = 273.0 + 47 CycleInputParameters['FluidType'] = 'Carbon Dioxide' CycleInputParameters['PowerOutput'] = 1.0 * 10 ** 6 delta_p_per_delta_t = 0 CycleInputParameters['Piston']['MassFraction'] = 1.0 CycleInputParameters['Piston']['IsentropicEfficiency'] = 1.0 CycleInputParameters['SecondPlusThirdHeating']['MaximumTemperature'] = CycleInputParameters['MaximumTemperature'] CycleInputParameters['SecondPlusThirdHeating']['MassFraction'] = 1 CycleInputParameters['SecondPlusThirdHeating']['DeltaPPerDeltaT'] = DeltaPPerDeltaT CycleInputParameters['TotalFractionCooler']['MinimumTemperature'] = CycleInputParameters['StartingProperties']['Temperature'] CycleInputParameters['TotalFractionCooler']['MassFraction'] = 1 CycleInputParameters['TotalFractionCooler']['DeltaPPerDeltaT'] = DeltaPPerDeltaT CycleInputParameters['HTRecuperator']['NumberofTemperatures'] = 200 CycleInputParameters['HTRecuperator']['LowPressure']['MassFraction'] = 1 CycleInputParameters['HTRecuperator']['HighPressure']['MassFraction'] = 1 CycleInputParameters['HTRecuperator']['HighPressure']['ConstantVolume'] = True CycleInputParameters['HTRecuperator']['DeltaPPerDeltaT'] = DeltaPPerDeltaT CycleInputParameters['HTRecuperator']['MinimumDeltaT'] = 0
#D def fibonacci(N :int) -> int: if N == 1: return 1 elif N == 2: return 1 else: return fibonacci(N-2)+fibonacci(N-1) def main(): # input N = int(input()) # compute # output print(fibonacci(N)) if __name__ == '__main__': main()
def fibonacci(N: int) -> int: if N == 1: return 1 elif N == 2: return 1 else: return fibonacci(N - 2) + fibonacci(N - 1) def main(): n = int(input()) print(fibonacci(N)) if __name__ == '__main__': main()
class Solution: def countVowelStrings(self, n: int) -> int: d = ['a', 'e', 'i', 'o', 'u'] path = [] count = 0 def backtracking(n, start): nonlocal count if n == 0: count += 1 return for i in range(start, 5): path.append(d[i]) backtracking(n-1, i) path.pop() return backtracking(n, 0) return count
class Solution: def count_vowel_strings(self, n: int) -> int: d = ['a', 'e', 'i', 'o', 'u'] path = [] count = 0 def backtracking(n, start): nonlocal count if n == 0: count += 1 return for i in range(start, 5): path.append(d[i]) backtracking(n - 1, i) path.pop() return backtracking(n, 0) return count
class _EventTarget: '''https://developer.mozilla.org/en-US/docs/Web/API/EventTarget''' NotImplemented class _Node(_EventTarget): '''https://developer.mozilla.org/en-US/docs/Web/API/Node''' NotImplemented class _Element(_Node): '''ref of https://developer.mozilla.org/en-US/docs/Web/API/Element''' NotImplemented
class _Eventtarget: """https://developer.mozilla.org/en-US/docs/Web/API/EventTarget""" NotImplemented class _Node(_EventTarget): """https://developer.mozilla.org/en-US/docs/Web/API/Node""" NotImplemented class _Element(_Node): """ref of https://developer.mozilla.org/en-US/docs/Web/API/Element""" NotImplemented
# This is function for sorting the array using bubble sort def bubble_sort(length, array): # It takes two arguments -> Length of the array and the array itself. for i in range(length): j = 0 for j in range(0, length-i-1): if array[j] > array[j+1]: array[j], array[j+1] = array[j+1], array[j] return array #Returns sorted array # This is the main function of the program def main(): length = int(input('Enter the length of the array to be entered : ')) # Taking the length of array array = [int(i) for i in input('Enter Array Elements : ').split()] # Taking array elements sorted_array = bubble_sort(length,array) # Calling the function for sorting the array using bubble sort print("Sorted Array is : ") for i in sorted_array: # Printing the sorted array print(i, end = " ") # Running the main code of the program if __name__ == '__main__': main()
def bubble_sort(length, array): for i in range(length): j = 0 for j in range(0, length - i - 1): if array[j] > array[j + 1]: (array[j], array[j + 1]) = (array[j + 1], array[j]) return array def main(): length = int(input('Enter the length of the array to be entered : ')) array = [int(i) for i in input('Enter Array Elements : ').split()] sorted_array = bubble_sort(length, array) print('Sorted Array is : ') for i in sorted_array: print(i, end=' ') if __name__ == '__main__': main()
print(type(1)) print(type('runnob')) print(type([2])) print(type({0:'zero'}))
print(type(1)) print(type('runnob')) print(type([2])) print(type({0: 'zero'}))
""" Primality testing """ _tiny_primes = [2, 3, 5, 7, 11, 13, 17, 19] _max_tiny_prime = 19 _tiny_primes_set = set(_tiny_primes) def _is_tiny_prime(n): return n <= _max_tiny_prime and n in _tiny_primes_set def _has_tiny_factor(n): for p in _tiny_primes: if n % p == 0: return True return False def _factor_pow2(n): """Factor powers of two from n. Return (s, t), with t odd, such that n = 2**s * t.""" s, t = 0, n while not t & 1: t >>= 1 s += 1 return s, t def _test(n, base): """Miller-Rabin strong pseudoprime test for one base. Return False if n is definitely composite, True if n is probably prime, with a probability greater than 3/4.""" n = int(n) if n < 2: return False s, t = _factor_pow2(n-1) b = pow(base, t, n) if b == 1 or b == n-1: return True else: for j in xrange(1, s): b = (b**2) % n if b == n-1: return True return False def mr(n, bases): """Perform a Miller-Rabin strong pseudoprime test on n using a given list of bases/witnesses. Reference: Richard Crandall & Carl Pomerance (2005), "Prime Numbers: A Computational Perspective", Springer, 2nd edition, 135-138 """ n = int(n) for base in bases: if not _test(n, base): return False return True def mr_safe(n): """For n < 1e16, use the Miller-Rabin test to determine with certainty (unless the code is buggy!) whether n is prime. Reference for the bounds: http://primes.utm.edu/prove/prove2_3.html """ n = int(n) if n < 1373653: return mr(n, [2, 3]) if n < 25326001: return mr(n, [2, 3, 5]) if n < 2152302898747: return mr(n, [2, 3, 5, 7, 11]) if n < 3474749660383: return mr(n, [2, 3, 5, 7, 11, 13]) if n < 341550071728321: return mr(n, [2, 3, 5, 7, 11, 13, 17]) if n < 10000000000000000: return mr(n, [2, 3, 7, 61, 24251]) raise ValueError("n too large") def isprime(n): """ Test whether n is a prime number. Negative primes (e.g. -2) are not considered prime. The function first looks for trivial factors, and if none is found, performs a Miller-Rabin strong pseudoprime test. Example usage ============= >>> isprime(13) True >>> isprime(15) False """ n = int(n) if n < 2: return False if n & 1 == 0: return n == 2 if _is_tiny_prime(n): return True if _has_tiny_factor(n): return False try: return mr_safe(n) except ValueError: # Should be good enough for practical purposes return mr(n, [2,3,5,7,11,13,17,19])
""" Primality testing """ _tiny_primes = [2, 3, 5, 7, 11, 13, 17, 19] _max_tiny_prime = 19 _tiny_primes_set = set(_tiny_primes) def _is_tiny_prime(n): return n <= _max_tiny_prime and n in _tiny_primes_set def _has_tiny_factor(n): for p in _tiny_primes: if n % p == 0: return True return False def _factor_pow2(n): """Factor powers of two from n. Return (s, t), with t odd, such that n = 2**s * t.""" (s, t) = (0, n) while not t & 1: t >>= 1 s += 1 return (s, t) def _test(n, base): """Miller-Rabin strong pseudoprime test for one base. Return False if n is definitely composite, True if n is probably prime, with a probability greater than 3/4.""" n = int(n) if n < 2: return False (s, t) = _factor_pow2(n - 1) b = pow(base, t, n) if b == 1 or b == n - 1: return True else: for j in xrange(1, s): b = b ** 2 % n if b == n - 1: return True return False def mr(n, bases): """Perform a Miller-Rabin strong pseudoprime test on n using a given list of bases/witnesses. Reference: Richard Crandall & Carl Pomerance (2005), "Prime Numbers: A Computational Perspective", Springer, 2nd edition, 135-138 """ n = int(n) for base in bases: if not _test(n, base): return False return True def mr_safe(n): """For n < 1e16, use the Miller-Rabin test to determine with certainty (unless the code is buggy!) whether n is prime. Reference for the bounds: http://primes.utm.edu/prove/prove2_3.html """ n = int(n) if n < 1373653: return mr(n, [2, 3]) if n < 25326001: return mr(n, [2, 3, 5]) if n < 2152302898747: return mr(n, [2, 3, 5, 7, 11]) if n < 3474749660383: return mr(n, [2, 3, 5, 7, 11, 13]) if n < 341550071728321: return mr(n, [2, 3, 5, 7, 11, 13, 17]) if n < 10000000000000000: return mr(n, [2, 3, 7, 61, 24251]) raise value_error('n too large') def isprime(n): """ Test whether n is a prime number. Negative primes (e.g. -2) are not considered prime. The function first looks for trivial factors, and if none is found, performs a Miller-Rabin strong pseudoprime test. Example usage ============= >>> isprime(13) True >>> isprime(15) False """ n = int(n) if n < 2: return False if n & 1 == 0: return n == 2 if _is_tiny_prime(n): return True if _has_tiny_factor(n): return False try: return mr_safe(n) except ValueError: return mr(n, [2, 3, 5, 7, 11, 13, 17, 19])
class Solution: def reverseStr(self, s, k): """ :type s: str :type k: int :rtype: str """ result = '' for i in range(0, len(s), 2*k): result += s[i:i+k][::-1] + s[i+k:i+2*k] return result
class Solution: def reverse_str(self, s, k): """ :type s: str :type k: int :rtype: str """ result = '' for i in range(0, len(s), 2 * k): result += s[i:i + k][::-1] + s[i + k:i + 2 * k] return result
# author: Fei Gao # # Count And Say # # The count-and-say sequence is the sequence of integers beginning as follows: # 1, 11, 21, 1211, 111221, ... # 1 is read off as "one 1" or 11. # 11 is read off as "two 1s" or 21. # 21 is read off as "one 2, then one 1" or 1211. # Given an integer n, generate the nth sequence. # Note: The sequence of integers will be represented as a string. class Solution: # @return a string def countAndSay(self, n): def process(s): l = [] start = 0 for end in range(1, len(s)): if s[end] != s[end-1]: l.append(s[start:end]) start = end l.append(s[start:]) res = '' for ls in l: res += str(len(ls)) + ls[0] return res seq = ['', '1'] for i in range(1, n): seq.append(process(seq[i])) return seq[n] def main(): solver = Solution() for n in range(10): print(n, ': ', solver.countAndSay(n)) pass if __name__ == '__main__': main() pass
class Solution: def count_and_say(self, n): def process(s): l = [] start = 0 for end in range(1, len(s)): if s[end] != s[end - 1]: l.append(s[start:end]) start = end l.append(s[start:]) res = '' for ls in l: res += str(len(ls)) + ls[0] return res seq = ['', '1'] for i in range(1, n): seq.append(process(seq[i])) return seq[n] def main(): solver = solution() for n in range(10): print(n, ': ', solver.countAndSay(n)) pass if __name__ == '__main__': main() pass
file = open('file.txt', 'r') f = file.readlines() readingList = [] for line in f: readingList.append(line.strip()) print(readingList) file.close()
file = open('file.txt', 'r') f = file.readlines() reading_list = [] for line in f: readingList.append(line.strip()) print(readingList) file.close()
""" Write a Python program to get a single string from two given strings, separated by a space and swap the fisrt two characters of each string sample string: 'abc', 'xyz' expected result: 'xyc abz' """ def swap_char(str1, str2): char1 = str1[0:2] char2 = str2[0:2] str1 = str1.replace(char1, char2) str2 = str2.replace(char2, char1) return str1 + ' ' + str2 print(swap_char("abc", "xyz"))
""" Write a Python program to get a single string from two given strings, separated by a space and swap the fisrt two characters of each string sample string: 'abc', 'xyz' expected result: 'xyc abz' """ def swap_char(str1, str2): char1 = str1[0:2] char2 = str2[0:2] str1 = str1.replace(char1, char2) str2 = str2.replace(char2, char1) return str1 + ' ' + str2 print(swap_char('abc', 'xyz'))
#right rotation of array #it avoids unnecessary no. of recursions for large no. of rotations. def right_rot(arr,s):# s is the no. of times to rotate n=len(arr) s=s%n #print(s) for a in range(s): store=arr[n-1] for i in range(n-2,-1,-1): arr[i+1]=arr[i] arr[0]=store return(arr) arr = [11,1,2,3,4] s = 1 print(right_rot(arr,s))
def right_rot(arr, s): n = len(arr) s = s % n for a in range(s): store = arr[n - 1] for i in range(n - 2, -1, -1): arr[i + 1] = arr[i] arr[0] = store return arr arr = [11, 1, 2, 3, 4] s = 1 print(right_rot(arr, s))