content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
''' Mysql Table Create Queries ''' tables = [ # master_config Table ''' CREATE TABLE IF NOT EXISTS master_config ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, author VARCHAR(20) NOT NULL, PRIMARY KEY(id) ); ''', ''' CREATE TABLE IF NOT EXISTS user ( id VARCHAR(200) NOT NULL, pw VARCHAR(200) NOT NULL, PRIMARY KEY(id) ); ''', ]
""" Mysql Table Create Queries """ tables = ['\n CREATE TABLE IF NOT EXISTS master_config (\n id INT UNSIGNED NOT NULL AUTO_INCREMENT,\n author VARCHAR(20) NOT NULL,\n PRIMARY KEY(id)\n );\n', '\n CREATE TABLE IF NOT EXISTS user (\n id VARCHAR(200) NOT NULL,\n pw VARCHAR(200) NOT NULL,\n PRIMARY KEY(id)\n );\n']
x,y = map(int,input().split()) if x+y < 10: print(x+y) else: print("error")
(x, y) = map(int, input().split()) if x + y < 10: print(x + y) else: print('error')
class Address(object): ADDRESS_UTIM = 0 ADDRESS_UHOST = 1 ADDRESS_DEVICE = 2 ADDRESS_PLATFORM = 3
class Address(object): address_utim = 0 address_uhost = 1 address_device = 2 address_platform = 3
s = "a quick {0} brown fox {2} jumped over {1} the lazy dog"; x = 100; y = 200; z = 300; t = s.format(x,y,z); print(t);
s = 'a quick {0} brown fox {2} jumped over {1} the lazy dog' x = 100 y = 200 z = 300 t = s.format(x, y, z) print(t)
def uncollapse(s): for n in ['zero','one','two','three','four','five','six','seven','eight','nine']: s=s.replace(n,n+' ') return s[:-1] def G(s): for n in ['zero','one','two','three','four','five','six','seven','eight','nine']: s=s.replace(n,n+' ') return s[:-1]
def uncollapse(s): for n in ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']: s = s.replace(n, n + ' ') return s[:-1] def g(s): for n in ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']: s = s.replace(n, n + ' ') return s[:-1]
"""This file defines the unified tensor framework interface required by DGL unit testing, other than the ones used in the framework itself. """ ############################################################################### # Tensor, data type and context interfaces def cuda(): """Context object for CUDA.""" pass def is_cuda_available(): """Check whether CUDA is available.""" pass ############################################################################### # Tensor functions on feature data # -------------------------------- # These functions are performance critical, so it's better to have efficient # implementation in each framework. def array_equal(a, b): """Check whether the two tensors are *exactly* equal.""" pass def allclose(a, b, rtol=1e-4, atol=1e-4): """Check whether the two tensors are numerically close to each other.""" pass def randn(shape): """Generate a tensor with elements from standard normal distribution.""" pass def full(shape, fill_value, dtype, ctx): pass def narrow_row_set(x, start, stop, new): """Set a slice of the given tensor to a new value.""" pass def sparse_to_numpy(x): """Convert a sparse tensor to a numpy array.""" pass def clone(x): pass def reduce_sum(x): """Sums all the elements into a single scalar.""" pass def softmax(x, dim): """Softmax Operation on Tensors""" pass def spmm(x, y): """Sparse dense matrix multiply""" pass def add(a, b): """Compute a + b""" pass def sub(a, b): """Compute a - b""" pass def mul(a, b): """Compute a * b""" pass def div(a, b): """Compute a / b""" pass def sum(x, dim, keepdims=False): """Computes the sum of array elements over given axes""" pass def max(x, dim): """Computes the max of array elements over given axes""" pass def min(x, dim): """Computes the min of array elements over given axes""" pass def prod(x, dim): """Computes the prod of array elements over given axes""" pass def matmul(a, b): """Compute Matrix Multiplication between a and b""" pass def dot(a, b): """Compute Dot between a and b""" pass ############################################################################### # Tensor functions used *only* on index tensor # ---------------- # These operators are light-weighted, so it is acceptable to fallback to # numpy operators if currently missing in the framework. Ideally in the future, # DGL should contain all the operations on index, so this set of operators # should be gradually removed. ############################################################################### # Other interfaces # ---------------- # These are not related to tensors. Some of them are temporary workarounds that # should be included in DGL in the future.
"""This file defines the unified tensor framework interface required by DGL unit testing, other than the ones used in the framework itself. """ def cuda(): """Context object for CUDA.""" pass def is_cuda_available(): """Check whether CUDA is available.""" pass def array_equal(a, b): """Check whether the two tensors are *exactly* equal.""" pass def allclose(a, b, rtol=0.0001, atol=0.0001): """Check whether the two tensors are numerically close to each other.""" pass def randn(shape): """Generate a tensor with elements from standard normal distribution.""" pass def full(shape, fill_value, dtype, ctx): pass def narrow_row_set(x, start, stop, new): """Set a slice of the given tensor to a new value.""" pass def sparse_to_numpy(x): """Convert a sparse tensor to a numpy array.""" pass def clone(x): pass def reduce_sum(x): """Sums all the elements into a single scalar.""" pass def softmax(x, dim): """Softmax Operation on Tensors""" pass def spmm(x, y): """Sparse dense matrix multiply""" pass def add(a, b): """Compute a + b""" pass def sub(a, b): """Compute a - b""" pass def mul(a, b): """Compute a * b""" pass def div(a, b): """Compute a / b""" pass def sum(x, dim, keepdims=False): """Computes the sum of array elements over given axes""" pass def max(x, dim): """Computes the max of array elements over given axes""" pass def min(x, dim): """Computes the min of array elements over given axes""" pass def prod(x, dim): """Computes the prod of array elements over given axes""" pass def matmul(a, b): """Compute Matrix Multiplication between a and b""" pass def dot(a, b): """Compute Dot between a and b""" pass
# based on https://nlp.stanford.edu/software/dependencies_manual.pdf DEPENDENCY_DEFINITONS = { 'acomp': 'adjectival_complement', 'advcl': 'adverbial_clause_modifier', 'advmod': 'adverb_modifier', 'agent': 'agent', 'amod': 'adjectival_modifier', 'appos': 'appositional_modifier', 'aux': 'auxiliary', 'auxpass': 'passive_auxiliary', 'cc': 'coordination', 'ccomp': 'clausal_complement', 'conj': 'conjunct', 'cop': 'copula', 'csubj': 'clausal_subject', 'csubjpass': 'clausal_passive_subject', 'dep': 'dependent', 'det': 'determiner', 'discourse': 'discourse_element', 'dobj': 'direct_object', 'expl': 'expletive', 'goeswith': 'goes_with', 'iobj': 'indirect_object', 'mark': 'marker', 'mwe': 'multiword_expression', 'neg': 'negation_modifier', 'nn': 'noun_compound_modifier', 'npadvmod': 'noun_phrase_as_adverbial_modifier', 'nsubj': 'nominal_subject', 'nsubjpass': 'passive_nominal_subject', 'num': 'numeric_modifier', 'nummod': 'numeric_modifier', 'number': 'element_of_compound_number', 'parataxis': 'parataxis', 'pcomp': 'prepositional_complement', 'pobj': 'preposition_object', 'poss': 'possession_modifier', 'possessive': 'possessive_modifier', 'preconj': 'preconjunct', 'predet': 'predeterminer', 'prep': 'prepositional_modifier', 'prepc': 'prepositional_clausal_modifier', 'prt': 'phrasal_verb_particle', 'punct': 'punctuation', 'quantmod': 'quantifier_phrase_modifier', 'rcmod': 'relative_clause_modifier', 'ref': 'referent', 'root': 'root', 'tmod': 'temporal_modifier', 'vmod': 'reduced_nonfinite_verbal_modifier', 'xcomp': 'open_clausal_complement', 'xsubj': 'controlling_subject', 'attr': 'attributive', 'relcl': 'relative_clause_modifier', 'intj': 'interjection' }
dependency_definitons = {'acomp': 'adjectival_complement', 'advcl': 'adverbial_clause_modifier', 'advmod': 'adverb_modifier', 'agent': 'agent', 'amod': 'adjectival_modifier', 'appos': 'appositional_modifier', 'aux': 'auxiliary', 'auxpass': 'passive_auxiliary', 'cc': 'coordination', 'ccomp': 'clausal_complement', 'conj': 'conjunct', 'cop': 'copula', 'csubj': 'clausal_subject', 'csubjpass': 'clausal_passive_subject', 'dep': 'dependent', 'det': 'determiner', 'discourse': 'discourse_element', 'dobj': 'direct_object', 'expl': 'expletive', 'goeswith': 'goes_with', 'iobj': 'indirect_object', 'mark': 'marker', 'mwe': 'multiword_expression', 'neg': 'negation_modifier', 'nn': 'noun_compound_modifier', 'npadvmod': 'noun_phrase_as_adverbial_modifier', 'nsubj': 'nominal_subject', 'nsubjpass': 'passive_nominal_subject', 'num': 'numeric_modifier', 'nummod': 'numeric_modifier', 'number': 'element_of_compound_number', 'parataxis': 'parataxis', 'pcomp': 'prepositional_complement', 'pobj': 'preposition_object', 'poss': 'possession_modifier', 'possessive': 'possessive_modifier', 'preconj': 'preconjunct', 'predet': 'predeterminer', 'prep': 'prepositional_modifier', 'prepc': 'prepositional_clausal_modifier', 'prt': 'phrasal_verb_particle', 'punct': 'punctuation', 'quantmod': 'quantifier_phrase_modifier', 'rcmod': 'relative_clause_modifier', 'ref': 'referent', 'root': 'root', 'tmod': 'temporal_modifier', 'vmod': 'reduced_nonfinite_verbal_modifier', 'xcomp': 'open_clausal_complement', 'xsubj': 'controlling_subject', 'attr': 'attributive', 'relcl': 'relative_clause_modifier', 'intj': 'interjection'}
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def sumOfLeftLeaves(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 sum = 0 if root.left is not None and root.left.left is None and root.left.right is None: sum = root.left.val return sum + self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right) if __name__ == '__main__': solution = Solution() node = TreeNode(3) node.left = TreeNode(9) node.right = TreeNode(20) node.right.left = TreeNode(15) node.right.right = TreeNode(7) print(solution.sumOfLeftLeaves(node)) else: pass
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def sum_of_left_leaves(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 sum = 0 if root.left is not None and root.left.left is None and (root.left.right is None): sum = root.left.val return sum + self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right) if __name__ == '__main__': solution = solution() node = tree_node(3) node.left = tree_node(9) node.right = tree_node(20) node.right.left = tree_node(15) node.right.right = tree_node(7) print(solution.sumOfLeftLeaves(node)) else: pass
"""The functional module implements various functional needed for reinforcement learning calculations. Exposed functions: * :py:func:`loss.entropy` * :py:func:`loss.policy_gradient` * :py:func:`vtrace.from_logits` """
"""The functional module implements various functional needed for reinforcement learning calculations. Exposed functions: * :py:func:`loss.entropy` * :py:func:`loss.policy_gradient` * :py:func:`vtrace.from_logits` """
class GH_GrasshopperLibraryInfo(GH_AssemblyInfo): """ GH_GrasshopperLibraryInfo() """ AuthorContact=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: AuthorContact(self: GH_GrasshopperLibraryInfo) -> str """ AuthorName=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: AuthorName(self: GH_GrasshopperLibraryInfo) -> str """ Description=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: Description(self: GH_GrasshopperLibraryInfo) -> str """ Icon=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: Icon(self: GH_GrasshopperLibraryInfo) -> Bitmap """ Id=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: Id(self: GH_GrasshopperLibraryInfo) -> Guid """ License=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: License(self: GH_GrasshopperLibraryInfo) -> GH_LibraryLicense """ Name=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: Name(self: GH_GrasshopperLibraryInfo) -> str """ Version=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: Version(self: GH_GrasshopperLibraryInfo) -> str """
class Gh_Grasshopperlibraryinfo(GH_AssemblyInfo): """ GH_GrasshopperLibraryInfo() """ author_contact = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Get: AuthorContact(self: GH_GrasshopperLibraryInfo) -> str\n\n\n\n' author_name = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Get: AuthorName(self: GH_GrasshopperLibraryInfo) -> str\n\n\n\n' description = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Get: Description(self: GH_GrasshopperLibraryInfo) -> str\n\n\n\n' icon = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Get: Icon(self: GH_GrasshopperLibraryInfo) -> Bitmap\n\n\n\n' id = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Get: Id(self: GH_GrasshopperLibraryInfo) -> Guid\n\n\n\n' license = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Get: License(self: GH_GrasshopperLibraryInfo) -> GH_LibraryLicense\n\n\n\n' name = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Get: Name(self: GH_GrasshopperLibraryInfo) -> str\n\n\n\n' version = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Get: Version(self: GH_GrasshopperLibraryInfo) -> str\n\n\n\n'
class Solution: def reverse(self, x: int) -> int: s = '' if x < 0: s += '-' x *= -1 else: s += '0' while x > 0: tmp = x % 10 s += str(tmp) x = x // 10 res = int(s) if res > 2**31 - 1 or res < - 2**31: return 0 else: return res if __name__ == '__main__': s = Solution() print(s.reverse(1534236469))
class Solution: def reverse(self, x: int) -> int: s = '' if x < 0: s += '-' x *= -1 else: s += '0' while x > 0: tmp = x % 10 s += str(tmp) x = x // 10 res = int(s) if res > 2 ** 31 - 1 or res < -2 ** 31: return 0 else: return res if __name__ == '__main__': s = solution() print(s.reverse(1534236469))
#!/usr/bin/env python # encoding: utf-8 """ surrounded_regions.py Created by Shengwei on 2014-07-15. """ # https://oj.leetcode.com/problems/surrounded-regions/ # tags: hard, matrix, bfs """ Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. For example, X X X X X O O X X X O X X O X X After running your function, the board should be: X X X X X X X X X X X X X O X X """ # https://oj.leetcode.com/discuss/6454/dp-bfs-solution-o-n # http://blog.shengwei.li/leetcode-surrounded-regions/ def flip(board, row, col, value): char_array = list(board[row]) char_array[col] = value board[row] = ''.join(char_array) def mark_escaped(board, row, col, marker): bfs = [(row, col)] while bfs: row, col = bfs.pop(0) if row >= 0 and row < len(board) and col >= 0 and col < len(board[row]): if board[row][col] == 'O' and marker[row][col] != -1: marker[row][col] = -1 bfs.append((row, col - 1)) bfs.append((row, col + 1)) bfs.append((row - 1, col)) bfs.append((row + 1, col)) class Solution: # @param board, a 2D array # Capture all regions by modifying the input board in-place. # Do not return any value. def solve(self, board): if len(board) < 3 or len(board[0]) < 3: return marker = [[0] * m for _ in xrange(n)] for i in xrange(0, len(board)): mark_escaped(board, i, 0, marker) mark_escaped(board, i, len(board[i]) - 1, marker) for j in xrange(0, len(board[0])): mark_escaped(board, 0, j, marker) mark_escaped(board, len(board) - 1, j, marker) for i in xrange(1, len(board) - 1): for j in xrange(1, len(board[i]) - 1): if marker[i][j] != -1 and board[i][j] == 'O': flip(board, i, j, 'X')
""" surrounded_regions.py Created by Shengwei on 2014-07-15. """ "\nGiven a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.\n\nA region is captured by flipping all 'O's into 'X's in that surrounded region.\n\nFor example,\nX X X X\nX O O X\nX X O X\nX O X X\nAfter running your function, the board should be:\n\nX X X X\nX X X X\nX X X X\nX O X X\n" def flip(board, row, col, value): char_array = list(board[row]) char_array[col] = value board[row] = ''.join(char_array) def mark_escaped(board, row, col, marker): bfs = [(row, col)] while bfs: (row, col) = bfs.pop(0) if row >= 0 and row < len(board) and (col >= 0) and (col < len(board[row])): if board[row][col] == 'O' and marker[row][col] != -1: marker[row][col] = -1 bfs.append((row, col - 1)) bfs.append((row, col + 1)) bfs.append((row - 1, col)) bfs.append((row + 1, col)) class Solution: def solve(self, board): if len(board) < 3 or len(board[0]) < 3: return marker = [[0] * m for _ in xrange(n)] for i in xrange(0, len(board)): mark_escaped(board, i, 0, marker) mark_escaped(board, i, len(board[i]) - 1, marker) for j in xrange(0, len(board[0])): mark_escaped(board, 0, j, marker) mark_escaped(board, len(board) - 1, j, marker) for i in xrange(1, len(board) - 1): for j in xrange(1, len(board[i]) - 1): if marker[i][j] != -1 and board[i][j] == 'O': flip(board, i, j, 'X')
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param headA: the first list @param headB: the second list @return: a ListNode """ def getIntersectionNode(self, headA, headB): # write your code here if not headA or not headB: return None # Find last ListNode a = headA while a.next: a = a.next a.next = headB # Fast - Slow pointers haveIntersection = False slow, fast = headA, headA while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: haveIntersection = True break if haveIntersection: third = headA while third != slow: third = third.next slow = slow.next return slow return None
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param headA: the first list @param headB: the second list @return: a ListNode """ def get_intersection_node(self, headA, headB): if not headA or not headB: return None a = headA while a.next: a = a.next a.next = headB have_intersection = False (slow, fast) = (headA, headA) while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: have_intersection = True break if haveIntersection: third = headA while third != slow: third = third.next slow = slow.next return slow return None
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: result = ListNode(0) curr = result carry = 0 while l1 or l2: x = l1.val if l1 else 0 y = l2.val if l2 else 0 value = carry + x + y carry = value // 10 curr.next = ListNode(value % 10) curr = curr.next l1 = l1.next if l1 else None l2 = l2.next if l2 else None if carry > 0: curr.next = ListNode(carry) return result.next
class Solution: def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode: result = list_node(0) curr = result carry = 0 while l1 or l2: x = l1.val if l1 else 0 y = l2.val if l2 else 0 value = carry + x + y carry = value // 10 curr.next = list_node(value % 10) curr = curr.next l1 = l1.next if l1 else None l2 = l2.next if l2 else None if carry > 0: curr.next = list_node(carry) return result.next
string = "PATTERN" strlen = len(string) for x in range(0, strlen): print(string[0:strlen-x])
string = 'PATTERN' strlen = len(string) for x in range(0, strlen): print(string[0:strlen - x])
#Donal Maher # Check if one number divides by another def sleep_in(weekday, vacation): if (weekday and vacation == False): return False else: return True result = sleep_in(False, False) print("The result is {} ".format(result))
def sleep_in(weekday, vacation): if weekday and vacation == False: return False else: return True result = sleep_in(False, False) print('The result is {} '.format(result))
def calc(n1 ,op ,n2): result = 0 if op == '+': result = n1 + n2 elif op == '-': result = n1 - n2 elif op == '*': result = n1 * n2 elif op == '/': result = n1 / n2 else: result = 0 return result num1 = input('Input num1...') num2 = input('Input num2...') op = input('Input op...') data = calc(int(num1), op , int(num2)) print(data)
def calc(n1, op, n2): result = 0 if op == '+': result = n1 + n2 elif op == '-': result = n1 - n2 elif op == '*': result = n1 * n2 elif op == '/': result = n1 / n2 else: result = 0 return result num1 = input('Input num1...') num2 = input('Input num2...') op = input('Input op...') data = calc(int(num1), op, int(num2)) print(data)
n = int(input()) L = list(map(int,input().split())) ans = 1 c = L[0] cnt = 1 for i in L[1:]: if c <= i: cnt+=1 c = i ans = max(ans,cnt) else: cnt = 1 c = i c = L[0] cnt = 1 for i in L[1:]: if c >= i: cnt+=1 c = i ans = max(ans,cnt) else: cnt = 1 c = i print(ans)
n = int(input()) l = list(map(int, input().split())) ans = 1 c = L[0] cnt = 1 for i in L[1:]: if c <= i: cnt += 1 c = i ans = max(ans, cnt) else: cnt = 1 c = i c = L[0] cnt = 1 for i in L[1:]: if c >= i: cnt += 1 c = i ans = max(ans, cnt) else: cnt = 1 c = i print(ans)
# -*- coding: utf-8 -*- class Config(object): def __init__(self, bucket, root): self.bucket = bucket self.root = root
class Config(object): def __init__(self, bucket, root): self.bucket = bucket self.root = root
def find_best_investment(arr): if len(arr) < 2: return None, None current_min = arr[0] current_max_profit = -float("inf") result = (None, None) for item in arr[1:]: current_profit = item - current_min if current_profit > current_max_profit: current_max_profit = current_profit result = (current_min, item) if item < current_min: current_min = item return result if __name__ == '__main__': print(find_best_investment([1, 2, -1, 4, 5, 6, 7]))
def find_best_investment(arr): if len(arr) < 2: return (None, None) current_min = arr[0] current_max_profit = -float('inf') result = (None, None) for item in arr[1:]: current_profit = item - current_min if current_profit > current_max_profit: current_max_profit = current_profit result = (current_min, item) if item < current_min: current_min = item return result if __name__ == '__main__': print(find_best_investment([1, 2, -1, 4, 5, 6, 7]))
def returnValues(z): results = [(x, y) for x in range(z) for y in range(z) if x + y == 5 if x > y] return results print(returnValues(10))
def return_values(z): results = [(x, y) for x in range(z) for y in range(z) if x + y == 5 if x > y] return results print(return_values(10))
# This file is used on sr restored train set (which includes dev segments) tagged with their segment headers # It splits the set into the dev and train sets using the header information dev_path = 'dev/text' # stores dev segment information restored_sr = 'train/text_restored_by_inference_version2_with_timing' # restored full train + dev segments with headers save_dev = open('../../data/sr_restored_split_by_inference_version2/dev', 'a') save_train = open('../../data/sr_restored_split_by_inference_version2/train','a') def convert_word(text): t = text.strip() if t == '': return '' # get first punctuation for i in range(len(t)): if t[i] == ',': return t[:i] + "\t" + "COMMA" elif t[i]== '.': return t[:i] + "\t" + "PERIOD" elif t[i] == '?': return t[:i] + "\t" + "QUESTION" return t + "\t" + "O" def get_dev_headers(file_path): ''' takes in data file processed by sr which labels lines by their id (swXXXXX) returns the number of unique files in that data file ''' data_file = open(file_path, "r", encoding="utf-8") lines = data_file.readlines() lines = list(map(lambda x: x.split(" ")[0], lines)) lines = list(dict.fromkeys(lines)) lines.sort() return set(lines) dev_headers = get_dev_headers(dev_path) data_file = open(restored_sr, "r", encoding="utf-8") lines = data_file.readlines() for l in lines: line = l.split(' ', 1) segment_header = line[0] segment_text = line[1] segment = segment_text.split(' ') word_list = list(map(convert_word, segment)) if segment_header in dev_headers: save_dev.write('\n'.join(word_list)) save_dev.write('\n') else: save_train.write('\n'.join(word_list)) save_train.write('\n')
dev_path = 'dev/text' restored_sr = 'train/text_restored_by_inference_version2_with_timing' save_dev = open('../../data/sr_restored_split_by_inference_version2/dev', 'a') save_train = open('../../data/sr_restored_split_by_inference_version2/train', 'a') def convert_word(text): t = text.strip() if t == '': return '' for i in range(len(t)): if t[i] == ',': return t[:i] + '\t' + 'COMMA' elif t[i] == '.': return t[:i] + '\t' + 'PERIOD' elif t[i] == '?': return t[:i] + '\t' + 'QUESTION' return t + '\t' + 'O' def get_dev_headers(file_path): """ takes in data file processed by sr which labels lines by their id (swXXXXX) returns the number of unique files in that data file """ data_file = open(file_path, 'r', encoding='utf-8') lines = data_file.readlines() lines = list(map(lambda x: x.split(' ')[0], lines)) lines = list(dict.fromkeys(lines)) lines.sort() return set(lines) dev_headers = get_dev_headers(dev_path) data_file = open(restored_sr, 'r', encoding='utf-8') lines = data_file.readlines() for l in lines: line = l.split(' ', 1) segment_header = line[0] segment_text = line[1] segment = segment_text.split(' ') word_list = list(map(convert_word, segment)) if segment_header in dev_headers: save_dev.write('\n'.join(word_list)) save_dev.write('\n') else: save_train.write('\n'.join(word_list)) save_train.write('\n')
"""FrequencyEstimator.py Estimate frequencies of items in a data stream. D. Eppstein, Feb 2016.""" class FrequencyEstimator: """Estimate frequencies of a stream of items to a specified accuracy (e.g. accuracy=0.1 means within 10% of actual frequency) using only O(1/accuracy) bytes of memory.""" def __init__(self, accuracy): self._counts = {} self._howmany = int(1./accuracy) self._total = 0 def __iadd__(self, key): """FrequencyEstimator += key counts another copy of the key. This operation takes amortized constant time, but the worst-case time may be O(1/accuracy).""" self._total += 1 if key in self._counts: self._counts[key] += 1 # Already there, increment its counter. elif len(self._counts) < self._howmany: self._counts[key] = 1 # We have room to add it, so do. else: # We need to make some room, by decrementing all the counters # and clearing out the keys that this reduces to zero. # This happens on at most 1/(howmany+1) of the calls to add(), # so we have enough (amortized) time to loop over all keys. # # One complication is that we can't loop over and modify # the keys in the dict at the same time, without wasting # space making a second list of keys, so instead we build # a linked list of keys to eliminate within the dict itself. # # As a side note, we should not immediately use the space to # add the new key. It is not necessary, and makes the data # structure less accurate by increasing the potential # rate of decrements from 1/(howmany+1) to 1/howmany. # anchor = linkchain = object() # nonce sentinel for key in self._counts: self._counts[key] -= 1 if self._counts[key] == 0: self._counts[key] = linkchain linkchain = key while linkchain != anchor: victim, linkchain = linkchain, self._counts[linkchain] del self._counts[victim] return self def __iter__(self): """iter(FrequencyEstimator) loops through the most frequent keys.""" return iter(self._counts) def __getitem__(self, key): """FrequencyEstimator[key] estimates the frequency of the key.""" if key not in self._counts: return 0 return self._counts[key]*1.0/self._total
"""FrequencyEstimator.py Estimate frequencies of items in a data stream. D. Eppstein, Feb 2016.""" class Frequencyestimator: """Estimate frequencies of a stream of items to a specified accuracy (e.g. accuracy=0.1 means within 10% of actual frequency) using only O(1/accuracy) bytes of memory.""" def __init__(self, accuracy): self._counts = {} self._howmany = int(1.0 / accuracy) self._total = 0 def __iadd__(self, key): """FrequencyEstimator += key counts another copy of the key. This operation takes amortized constant time, but the worst-case time may be O(1/accuracy).""" self._total += 1 if key in self._counts: self._counts[key] += 1 elif len(self._counts) < self._howmany: self._counts[key] = 1 else: anchor = linkchain = object() for key in self._counts: self._counts[key] -= 1 if self._counts[key] == 0: self._counts[key] = linkchain linkchain = key while linkchain != anchor: (victim, linkchain) = (linkchain, self._counts[linkchain]) del self._counts[victim] return self def __iter__(self): """iter(FrequencyEstimator) loops through the most frequent keys.""" return iter(self._counts) def __getitem__(self, key): """FrequencyEstimator[key] estimates the frequency of the key.""" if key not in self._counts: return 0 return self._counts[key] * 1.0 / self._total
async with pyryver.Ryver("organization_name", "username", "password") as ryver: await ryver.load_chats() a_user = ryver.get_user(username="tylertian123") a_forum = ryver.get_groupchat(display_name="Off-Topic")
async with pyryver.Ryver('organization_name', 'username', 'password') as ryver: await ryver.load_chats() a_user = ryver.get_user(username='tylertian123') a_forum = ryver.get_groupchat(display_name='Off-Topic')
# tests require to import from Faiss module # so thus require PYTHONPATH # the other option would be installing via requirements # but that would always be a different version # only required for CI. DO NOT add real tests here, but in top-level integration def test_dummy(): pass
def test_dummy(): pass
numbers = [int(n) for n in input().split(", ")] count_of_beggars = int(input()) collected = [] index = 0 for i in range(count_of_beggars): current_list = [] for index in range(0, len(numbers) + 1, count_of_beggars): index += i if index < len(numbers): current_list.append(numbers[index]) collected.append(sum(current_list)) print(collected) # nums_str = input().split(', ') # count = int(input()) # # nums = [] # # for num in nums_str: # nums.append(int(num)) # # result_sum = [0] * count # # for i in range(len(nums)): # index = i % count # result_sum[index] += nums[i] # # print(result_sum)
numbers = [int(n) for n in input().split(', ')] count_of_beggars = int(input()) collected = [] index = 0 for i in range(count_of_beggars): current_list = [] for index in range(0, len(numbers) + 1, count_of_beggars): index += i if index < len(numbers): current_list.append(numbers[index]) collected.append(sum(current_list)) print(collected)
# list comprehension is an elegant way to creats list based on exesting list # We can use this one liner comprehensioner for dictnory ans sets also. #l1 = [3,5,6,7,8,90,12,34,67,0] ''' # For addind even in l2 l2 =[] for item in l1: if item%2 == 0: l2.append(item) print(l2) ''' ''' # Shortcut to write the same: l2 = [item for item in l1 if item < 8] l3 = [item for item in l1 if item%2 ==0] # creating a list for print(l2) print(l3) ''' # print a reaptated element from both list. l4 = ['am' , 'em' , 'fcgh' , 'em' , 'em'] l5 = ['am', 'f' , 'em' , 'rg' , 'em'] flist = [item for item in l4+l5 if item == 'em'] #print(flist) #print(flist.count('em')) a= [4,6,8,5,4,4,4] b = [4,5,6,4,5,4] c = [i for i in a+b if i==4] print(c) print(c.count(4))
""" # For addind even in l2 l2 =[] for item in l1: if item%2 == 0: l2.append(item) print(l2) """ '\n# Shortcut to write the same:\nl2 = [item for item in l1 if item < 8]\nl3 = [item for item in l1 if item%2 ==0] # creating a list for \nprint(l2)\nprint(l3)\n' l4 = ['am', 'em', 'fcgh', 'em', 'em'] l5 = ['am', 'f', 'em', 'rg', 'em'] flist = [item for item in l4 + l5 if item == 'em'] a = [4, 6, 8, 5, 4, 4, 4] b = [4, 5, 6, 4, 5, 4] c = [i for i in a + b if i == 4] print(c) print(c.count(4))
''' Created on Apr 11, 2017 tutorial: https://www.youtube.com/watch?v=nefopNkZmB4&list=PL6gx4Cwl9DGAcbMi1sH6oAMk4JHw91mC_&index=3 modules: https://www.youtube.com/watch?v=sKYiQLRe254 @author: halil ''' class BayesianFilter(object): ''' classdocs ''' def __init__(self): ''' Constructor ''' print ("hello bayesian filter!")
""" Created on Apr 11, 2017 tutorial: https://www.youtube.com/watch?v=nefopNkZmB4&list=PL6gx4Cwl9DGAcbMi1sH6oAMk4JHw91mC_&index=3 modules: https://www.youtube.com/watch?v=sKYiQLRe254 @author: halil """ class Bayesianfilter(object): """ classdocs """ def __init__(self): """ Constructor """ print('hello bayesian filter!')
""" This is one solution to the cash machine challenge. It will be good to re run this when they start to do OOP and see how subtly different the code is. I have got around the local scope of the subroutines by declaring thst I will be using the global variables at the start of the subroutines. This is not the only way you can get around this. You can also use parameters and return values. The code loads the account number, pin and balance from the file each time it runs the menu and saves them back to the file each time the balance is changed. """ accNo = "" pin = "" balance = 1000 loggedIn = False def saveData(): fileName = "user.txt" try: fout = open(fileName, "w") except OSError: print("Cannot open", fileName) else: user = accNo + "," + pin + "," + str(balance) userCode = "" for letter in user: userCode = userCode + chr(ord(letter)+10) fout.write(userCode + "\n") fout.close() print("Success!") def getData(): global accNo, pin, balance, loggedIn fileName = "user.txt" try: my_file = open(fileName, "r") except OSError: print("Cannot open", fileName) else: fileRead = my_file.readlines() userDecode = "" for line in fileRead: for letter in line: userDecode = userDecode + chr(ord(letter)-10) userDetails = userDecode.split(",") accNo = userDetails[0] pin = userDetails[1] balance = userDetails[2] # when the balance is read from the file it has the \n new line # character included. This must be removed before you can cast it # to a float. balance = balance[:-1] print(balance) try: balance = float(balance) except ValueError: print("There has been an error loading the balance.") print(userDecode, userDetails) # menu is an array of option that are printed out # the return value is the option number as a string. def menu(): menuList = ["1. Login", "2. Logout", "3. Display Account Balance", "4. Withdraw Funds", "5. Deposit Funds", "6. Exit"] for i in menuList: print(i) choice = input("\nEnter the number of your option: ") return choice def optionOne(): aNumber = input("Enter your account Number: ") apin = input("Enter your pin number: ") if aNumber == accNo: if apin == pin: return True else: print("Pin is incorrect.") optionOne() else: print("Account Number is incorrect.") optionOne() def optionTwo(): print("You have logged out") return False def optionthree(): print("Your balance is:", balance) def optionfour(): global balance print("Please enter the withdrawal amount:") try: amount = float(input()) except ValueError: print("Please enter a valid number.") optionfour() else: if balance >= amount: balance = round(balance - amount, 2) saveData() else: print("Sorry you don't have enough money!") def optionfive(): global balance print("Please enter the deposit amount:") try: amount = float(input()) except ValueError: print("Please enter a valid number.") optionfive() else: balance = round(balance + amount, 2) saveData() def main(): global loggedIn exitApp = False while not exitApp: getData() option = menu() if option == "1": loggedIn = optionOne() elif option == "2": loggedIn = optionTwo() elif option == "3": if loggedIn: optionthree() else: print("You must be logged in to view your balance.") elif option == "4": if loggedIn: optionfour() else: print("You must be logged in to withdraw funds.") elif option == "5": if loggedIn: optionfive() else: print("You must be logged in to deposit funds.") elif option == "6": exitApp = True main()
""" This is one solution to the cash machine challenge. It will be good to re run this when they start to do OOP and see how subtly different the code is. I have got around the local scope of the subroutines by declaring thst I will be using the global variables at the start of the subroutines. This is not the only way you can get around this. You can also use parameters and return values. The code loads the account number, pin and balance from the file each time it runs the menu and saves them back to the file each time the balance is changed. """ acc_no = '' pin = '' balance = 1000 logged_in = False def save_data(): file_name = 'user.txt' try: fout = open(fileName, 'w') except OSError: print('Cannot open', fileName) else: user = accNo + ',' + pin + ',' + str(balance) user_code = '' for letter in user: user_code = userCode + chr(ord(letter) + 10) fout.write(userCode + '\n') fout.close() print('Success!') def get_data(): global accNo, pin, balance, loggedIn file_name = 'user.txt' try: my_file = open(fileName, 'r') except OSError: print('Cannot open', fileName) else: file_read = my_file.readlines() user_decode = '' for line in fileRead: for letter in line: user_decode = userDecode + chr(ord(letter) - 10) user_details = userDecode.split(',') acc_no = userDetails[0] pin = userDetails[1] balance = userDetails[2] balance = balance[:-1] print(balance) try: balance = float(balance) except ValueError: print('There has been an error loading the balance.') print(userDecode, userDetails) def menu(): menu_list = ['1. Login', '2. Logout', '3. Display Account Balance', '4. Withdraw Funds', '5. Deposit Funds', '6. Exit'] for i in menuList: print(i) choice = input('\nEnter the number of your option: ') return choice def option_one(): a_number = input('Enter your account Number: ') apin = input('Enter your pin number: ') if aNumber == accNo: if apin == pin: return True else: print('Pin is incorrect.') option_one() else: print('Account Number is incorrect.') option_one() def option_two(): print('You have logged out') return False def optionthree(): print('Your balance is:', balance) def optionfour(): global balance print('Please enter the withdrawal amount:') try: amount = float(input()) except ValueError: print('Please enter a valid number.') optionfour() else: if balance >= amount: balance = round(balance - amount, 2) save_data() else: print("Sorry you don't have enough money!") def optionfive(): global balance print('Please enter the deposit amount:') try: amount = float(input()) except ValueError: print('Please enter a valid number.') optionfive() else: balance = round(balance + amount, 2) save_data() def main(): global loggedIn exit_app = False while not exitApp: get_data() option = menu() if option == '1': logged_in = option_one() elif option == '2': logged_in = option_two() elif option == '3': if loggedIn: optionthree() else: print('You must be logged in to view your balance.') elif option == '4': if loggedIn: optionfour() else: print('You must be logged in to withdraw funds.') elif option == '5': if loggedIn: optionfive() else: print('You must be logged in to deposit funds.') elif option == '6': exit_app = True main()
"""Simplest possible f-string with one string variable.""" name = "Peter" print(f"Hello {name}")
"""Simplest possible f-string with one string variable.""" name = 'Peter' print(f'Hello {name}')
rules = {} appearances = {} original = input() input() while True: try: l, r = input().split(" -> ") except: break rules[l] = r appearances[l] = 0 for i in range(len(original)-1): a = original[i] b = original[i+1] appearances[a+b] += 1 def polymerization(d): new = {x: 0 for x in rules} singular = {x: 0 for x in rules.values()} for ((a, b), c) in rules.items(): new[a+c] += d[a+b] new[c+b] += d[a+b] singular[c] += d[a+b] singular[a] += d[a+b] #last letter of the word is a K (not not counted above) singular["K"] += 1 return new, singular for i in range(40): (appearances, sing) = polymerization(appearances) counts = [(v, k) for (k, v) in sing.items()] counts.sort() print(counts[-1][0] - counts[0][0])
rules = {} appearances = {} original = input() input() while True: try: (l, r) = input().split(' -> ') except: break rules[l] = r appearances[l] = 0 for i in range(len(original) - 1): a = original[i] b = original[i + 1] appearances[a + b] += 1 def polymerization(d): new = {x: 0 for x in rules} singular = {x: 0 for x in rules.values()} for ((a, b), c) in rules.items(): new[a + c] += d[a + b] new[c + b] += d[a + b] singular[c] += d[a + b] singular[a] += d[a + b] singular['K'] += 1 return (new, singular) for i in range(40): (appearances, sing) = polymerization(appearances) counts = [(v, k) for (k, v) in sing.items()] counts.sort() print(counts[-1][0] - counts[0][0])
class AccountManagement: """ All Account requests allow managing the authenticated user's account or are in some way connected to account management. """ def __init__(self, resolve): self.resolve = resolve def get_account_information(self): """ Returns the account details of the authenticated user. :return: Response Object - Account """ request_method = 'GET' resource_url = '/account' return self.resolve(request_method, resource_url) def change_vacation_status(self, on_vacation: bool, cancel_orders: bool = False, relist_items: bool = False): """ Updates the vacation status of the user. :param on_vacation: Boolean flag if the user is on vacation or not :param cancel_orders: Boolean flag to cancel open orders, resp. request cancellation for open orders :param relist_items: Boolean flag to relist items for canceled orders; only applies if cancelOrders is also provided and set to true for all orders, that are effectively canceled :return: Response Object - Account """ request_method = 'PUT' resource_url = f'/account/vacation' params = { 'onVacation': 'true' if on_vacation else 'false', 'cancelOrders': 'true' if cancel_orders else 'false', 'relistItems': 'true' if relist_items else 'false' } return self.resolve(request_method, resource_url, params=params) def change_display_language(self, new_language: int): """ Updates the display language of the authenticated user. :param new_language: 1: English, 2: French, 3: German, 4: Spanish, 5: English :return: Response Object - Account """ if not isinstance(new_language, int) or new_language < 1 or new_language > 5: raise ValueError('The new language must be a number between 1 and 5.') request_method = 'PUT' resource_url = '/account/language' params = {'idDisplayLanguage': new_language} return self.resolve(request_method, resource_url, params=params) def get_message_overview(self): """ Returns the message thread overview of the authenticated user. :return: Response Object - Message Thread """ request_method = 'GET' resource_url = '/account/messages' return self.resolve(request_method, resource_url) def get_messages_from(self, other_user_id: int): """ Returns the message thread with a specified other user. :param other_user_id: ID of the other user (as integer) :return: Response Object - Message Thread """ if not isinstance(other_user_id, int): raise ValueError('The user id must be an integer.') request_method = 'GET' resource_url = f'/account/messages/{other_user_id}' return self.resolve(request_method, resource_url) def get_message_from(self, other_user_id: int, message_id: str): """ Returns a specified message with a specified other user. :param other_user_id: ID of the other user (as integer) :param message_id: ID of the message (as string) :return: Response Object - Message Thread """ if not isinstance(other_user_id, int): raise ValueError('The user id must be an integer.') if not isinstance(message_id, str): raise ValueError('The message id must be a (hex) string.') request_method = 'GET' resource_url = f'/account/messages/{other_user_id}/{message_id}' return self.resolve(request_method, resource_url) def send_message(self, other_user_id: int, message: str): """ Creates a new message sent to a specified other user. :param other_user_id: ID of the other user (as integer) :param message: Text of the message to send. Use '\n' for newline. :return: Response Object - Message Thread (With only the message just sent) """ if not isinstance(other_user_id, int): raise ValueError('The user id must be an integer.') request_method = 'POST' resource_url = f'/account/messages/{other_user_id}' data = {'message': message} return self.resolve(request_method, resource_url, data=data) def delete_message(self, other_user_id: int, message_id: str): """ Deletes a specified message to a specified other user. The message will be delete just for you, it is still visible to the other user. :param other_user_id: ID of the other user (as integer) :param message_id: ID of the message (as string) :return: Empty """ if not isinstance(other_user_id, int): raise ValueError('The user id must be an integer.') if not isinstance(message_id, str): raise ValueError('The message id must be a (hex) string.') request_method = 'DELETE' resource_url = f'/account/messages/{other_user_id}/{message_id}' return self.resolve(request_method, resource_url) def delete_messages_from(self, other_user_id: int): """ Deletes a complete message thread to a specified other user. :param other_user_id: ID of the other user (as integer) :return: Empty """ if not isinstance(other_user_id, int): raise ValueError('The user id must be an integer.') request_method = 'DELETE' resource_url = f'/account/messages/{other_user_id}' return self.resolve(request_method, resource_url) def get_unread_messages(self): """ Returns all unread messages. This request returns only messages where the authenticated user is the receiver. Note: As of Jan 2020 there is a confirmed issue with this method on the MKM backend resulting in a Bad Request (400) status code for some users. :return: Response Object - Message """ request_method = 'GET' resource_url = '/account/messages/find' params = {'unread': 'true'} return self.resolve(request_method, resource_url, params=params) def get_messages_between(self, start_date: str, end_date: str = None): """ Returns all messages between the start and end date. If the end date is omitted, the current date is assumed. The safest format to use is the ISO 8601 representation: E.g. 2017-12-08T14:41:12+0100 (YYYY-MM-DDTHH:MM:SS+HHMM) for 8th of December, 2017, 14:41:12 CET Be aware that the colon (:) in time representations is a reserved character and needs to be percent encoded. Note: As of Jan 2020 there is a confirmed issue with this method on the MKM backend resulting in a Bad Request (400) status code for some users. :param start_date: The earliest date to get messages :param end_date: The lastest date to get messages (current date if omitted) :return: Response Object - Message """ request_method = 'GET' resource_url = '/account/messages/find' params = {'startDate': start_date} if end_date is not None: params['endDate'] = end_date return self.resolve(request_method, resource_url, params=params) def redeem_coupon(self, coupon_code): """ Redeems one coupon. :param coupon_code: Code of the coupon to redeem :return: Response Object - Account plus CodeRedemption """ request_method = 'POST' resource_url = f'/account/coupon' data = {'couponCode': coupon_code} return self.resolve(request_method, resource_url, data=data)
class Accountmanagement: """ All Account requests allow managing the authenticated user's account or are in some way connected to account management. """ def __init__(self, resolve): self.resolve = resolve def get_account_information(self): """ Returns the account details of the authenticated user. :return: Response Object - Account """ request_method = 'GET' resource_url = '/account' return self.resolve(request_method, resource_url) def change_vacation_status(self, on_vacation: bool, cancel_orders: bool=False, relist_items: bool=False): """ Updates the vacation status of the user. :param on_vacation: Boolean flag if the user is on vacation or not :param cancel_orders: Boolean flag to cancel open orders, resp. request cancellation for open orders :param relist_items: Boolean flag to relist items for canceled orders; only applies if cancelOrders is also provided and set to true for all orders, that are effectively canceled :return: Response Object - Account """ request_method = 'PUT' resource_url = f'/account/vacation' params = {'onVacation': 'true' if on_vacation else 'false', 'cancelOrders': 'true' if cancel_orders else 'false', 'relistItems': 'true' if relist_items else 'false'} return self.resolve(request_method, resource_url, params=params) def change_display_language(self, new_language: int): """ Updates the display language of the authenticated user. :param new_language: 1: English, 2: French, 3: German, 4: Spanish, 5: English :return: Response Object - Account """ if not isinstance(new_language, int) or new_language < 1 or new_language > 5: raise value_error('The new language must be a number between 1 and 5.') request_method = 'PUT' resource_url = '/account/language' params = {'idDisplayLanguage': new_language} return self.resolve(request_method, resource_url, params=params) def get_message_overview(self): """ Returns the message thread overview of the authenticated user. :return: Response Object - Message Thread """ request_method = 'GET' resource_url = '/account/messages' return self.resolve(request_method, resource_url) def get_messages_from(self, other_user_id: int): """ Returns the message thread with a specified other user. :param other_user_id: ID of the other user (as integer) :return: Response Object - Message Thread """ if not isinstance(other_user_id, int): raise value_error('The user id must be an integer.') request_method = 'GET' resource_url = f'/account/messages/{other_user_id}' return self.resolve(request_method, resource_url) def get_message_from(self, other_user_id: int, message_id: str): """ Returns a specified message with a specified other user. :param other_user_id: ID of the other user (as integer) :param message_id: ID of the message (as string) :return: Response Object - Message Thread """ if not isinstance(other_user_id, int): raise value_error('The user id must be an integer.') if not isinstance(message_id, str): raise value_error('The message id must be a (hex) string.') request_method = 'GET' resource_url = f'/account/messages/{other_user_id}/{message_id}' return self.resolve(request_method, resource_url) def send_message(self, other_user_id: int, message: str): """ Creates a new message sent to a specified other user. :param other_user_id: ID of the other user (as integer) :param message: Text of the message to send. Use ' ' for newline. :return: Response Object - Message Thread (With only the message just sent) """ if not isinstance(other_user_id, int): raise value_error('The user id must be an integer.') request_method = 'POST' resource_url = f'/account/messages/{other_user_id}' data = {'message': message} return self.resolve(request_method, resource_url, data=data) def delete_message(self, other_user_id: int, message_id: str): """ Deletes a specified message to a specified other user. The message will be delete just for you, it is still visible to the other user. :param other_user_id: ID of the other user (as integer) :param message_id: ID of the message (as string) :return: Empty """ if not isinstance(other_user_id, int): raise value_error('The user id must be an integer.') if not isinstance(message_id, str): raise value_error('The message id must be a (hex) string.') request_method = 'DELETE' resource_url = f'/account/messages/{other_user_id}/{message_id}' return self.resolve(request_method, resource_url) def delete_messages_from(self, other_user_id: int): """ Deletes a complete message thread to a specified other user. :param other_user_id: ID of the other user (as integer) :return: Empty """ if not isinstance(other_user_id, int): raise value_error('The user id must be an integer.') request_method = 'DELETE' resource_url = f'/account/messages/{other_user_id}' return self.resolve(request_method, resource_url) def get_unread_messages(self): """ Returns all unread messages. This request returns only messages where the authenticated user is the receiver. Note: As of Jan 2020 there is a confirmed issue with this method on the MKM backend resulting in a Bad Request (400) status code for some users. :return: Response Object - Message """ request_method = 'GET' resource_url = '/account/messages/find' params = {'unread': 'true'} return self.resolve(request_method, resource_url, params=params) def get_messages_between(self, start_date: str, end_date: str=None): """ Returns all messages between the start and end date. If the end date is omitted, the current date is assumed. The safest format to use is the ISO 8601 representation: E.g. 2017-12-08T14:41:12+0100 (YYYY-MM-DDTHH:MM:SS+HHMM) for 8th of December, 2017, 14:41:12 CET Be aware that the colon (:) in time representations is a reserved character and needs to be percent encoded. Note: As of Jan 2020 there is a confirmed issue with this method on the MKM backend resulting in a Bad Request (400) status code for some users. :param start_date: The earliest date to get messages :param end_date: The lastest date to get messages (current date if omitted) :return: Response Object - Message """ request_method = 'GET' resource_url = '/account/messages/find' params = {'startDate': start_date} if end_date is not None: params['endDate'] = end_date return self.resolve(request_method, resource_url, params=params) def redeem_coupon(self, coupon_code): """ Redeems one coupon. :param coupon_code: Code of the coupon to redeem :return: Response Object - Account plus CodeRedemption """ request_method = 'POST' resource_url = f'/account/coupon' data = {'couponCode': coupon_code} return self.resolve(request_method, resource_url, data=data)
n, m = map(int, input().split()) res = [] for _ in range(m): res.append(int(input())) res.sort() price, ans = 0,0 for i in range(m): result = min(m-i, n) if ans < res[i] * result: price = res[i] ans = res[i] * result print(price, ans)
(n, m) = map(int, input().split()) res = [] for _ in range(m): res.append(int(input())) res.sort() (price, ans) = (0, 0) for i in range(m): result = min(m - i, n) if ans < res[i] * result: price = res[i] ans = res[i] * result print(price, ans)
__version__ = "0.3.1" __logo__ = [ " _ _", "| | _____ | |__ _ __ __ _", "| |/ / _ \\| '_ \\| '__/ _` |", "| < (_) | |_) | | | (_| |", "|_|\\_\\___/|_.__/|_| \\__,_|", " " ]
__version__ = '0.3.1' __logo__ = [' _ _', '| | _____ | |__ _ __ __ _', "| |/ / _ \\| '_ \\| '__/ _` |", '| < (_) | |_) | | | (_| |', '|_|\\_\\___/|_.__/|_| \\__,_|', ' ']
def _RELIC__word_list_prep(): file = open('stopwords.txt') new_file = open('stopwords_new.txt', 'w') for line in file: if line.strip(): new_file.write(line) file.close() new_file.close()
def _relic__word_list_prep(): file = open('stopwords.txt') new_file = open('stopwords_new.txt', 'w') for line in file: if line.strip(): new_file.write(line) file.close() new_file.close()
# There are a total of n courses you have to take, labeled from 0 to n - 1. # Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] # Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? # For example: # 2, [[1,0]] # There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. # 2, [[1,0],[0,1]] # There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. # Note: # The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented. # You may assume that there are no duplicate edges in the input prerequisites. class Solution(object): def canFinish(self, numCourses, prerequisites): """ O(V+E) :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool """ zero_indegree = [] indegree = {} outdegree = {} # save the indegree and outdegree for i, j in prerequisites: if i not in indegree: indegree[i] = set() if j not in outdegree: outdegree[j] = set() indegree[i].add(j) outdegree[j].add(i) # find zero indegree in the graph for i in range(numCourses): if i not in indegree: zero_indegree.append(i) while zero_indegree: prerequest = zero_indegree.pop(0) if prerequest in outdegree: for course in outdegree[prerequest]: indegree[course].remove(prerequest) # empty if not indegree[course]: zero_indegree.append(course) del (outdegree[prerequest]) # check out degree if outdegree: return False return True def canFinish(self, n, pres): oud = [[] for _ in range(n)] # indegree ind = [0] * n # outdegree for succ,pre in pres: ind[succ] += 1 oud[pre].append(succ) dq = [] for i in range(n): if ind[i] == 0: dq.append(i) count = 0 while dq: pre_course = dq.pop(0) count += 1 for succ in oud[pre_course]: ind[succ] -= 1 if ind[succ] == 0: dq.append(succ) return count == n
class Solution(object): def can_finish(self, numCourses, prerequisites): """ O(V+E) :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool """ zero_indegree = [] indegree = {} outdegree = {} for (i, j) in prerequisites: if i not in indegree: indegree[i] = set() if j not in outdegree: outdegree[j] = set() indegree[i].add(j) outdegree[j].add(i) for i in range(numCourses): if i not in indegree: zero_indegree.append(i) while zero_indegree: prerequest = zero_indegree.pop(0) if prerequest in outdegree: for course in outdegree[prerequest]: indegree[course].remove(prerequest) if not indegree[course]: zero_indegree.append(course) del outdegree[prerequest] if outdegree: return False return True def can_finish(self, n, pres): oud = [[] for _ in range(n)] ind = [0] * n for (succ, pre) in pres: ind[succ] += 1 oud[pre].append(succ) dq = [] for i in range(n): if ind[i] == 0: dq.append(i) count = 0 while dq: pre_course = dq.pop(0) count += 1 for succ in oud[pre_course]: ind[succ] -= 1 if ind[succ] == 0: dq.append(succ) return count == n
""" Web server settings """ # 433 MHz Outlet Codes ----------------------------------------------------------------------------- rfcodes = {'1': {'on': '21811', 'off': '21820'}, '2': {'on': '21955', 'off': '21964'}, '3': {'on': '22275', 'off': '22284'}, '4': {'on': '23811', 'off': '23820'}, '5': {'on': '29955', 'off': '29964'}, '6': {'on': '10000', 'off': '10010'}, '7': {'on': '11000', 'off': '11010'}, '8': {'on': '12000', 'off': '12010'}, '9': {'on': '13000', 'off': '13010'}} # 433 MHz transmission settings -------------------------------------------------------------------- codesend = {'pin': '0', # Set pin number (GPIO: 17 | Pin #: 13) 'length': '189', # Set pulse length 'exec': './codesend'} # Set codesend script path (should be in rfoutlet) # LED settings ------------------------------------------------------------------------------------- led_settings = {'on': 24, # Green LED GPIO 'off': 23, # Red LED GPIO 'num': 2, # Number of times to blink 'speed': 0.15, # Speed of blink (s) 'blink': False} # Blink when outlets are switched # Weather settings --------------------------------------------------------------------------------- weather_settings = {'city': 'pittsburgh', 'state': 'PA', 'unit': 'C', 'precision': 1} # Bus API settings --------------------------------------------------------------------------------- pgh_api_key = "LMJrK9vutafSVnViFmFvjaXvY" bus_stops = {'id': [8245, 3144, 8192], 'name': ['Summerlea', 'Bellefonte', 'Graham'], 'max_prd': 1} # --------------------------------------------------------------------------------------------------
""" Web server settings """ rfcodes = {'1': {'on': '21811', 'off': '21820'}, '2': {'on': '21955', 'off': '21964'}, '3': {'on': '22275', 'off': '22284'}, '4': {'on': '23811', 'off': '23820'}, '5': {'on': '29955', 'off': '29964'}, '6': {'on': '10000', 'off': '10010'}, '7': {'on': '11000', 'off': '11010'}, '8': {'on': '12000', 'off': '12010'}, '9': {'on': '13000', 'off': '13010'}} codesend = {'pin': '0', 'length': '189', 'exec': './codesend'} led_settings = {'on': 24, 'off': 23, 'num': 2, 'speed': 0.15, 'blink': False} weather_settings = {'city': 'pittsburgh', 'state': 'PA', 'unit': 'C', 'precision': 1} pgh_api_key = 'LMJrK9vutafSVnViFmFvjaXvY' bus_stops = {'id': [8245, 3144, 8192], 'name': ['Summerlea', 'Bellefonte', 'Graham'], 'max_prd': 1}
# acutal is the list of actual labels, pred is the list of predicted labels. # sensitive is the column of sensitive attribute, target_group is s in S = s # positive_pred is the favorable result in prediction task. e.g. get approved for a loan def calibration_pos(actual,pred,sensitive,target_group,positive_pred): tot_pred_pos = 0 act_pos = 0 for act, pred_val, sens in zip(actual, pred,sensitive): # the case S != s if sens != target_group: continue else: # Yhat = 1 if pred_val == positive_pred: tot_pred_pos += 1 # the case both Yhat = 1 and Y = 1 if act == positive_pred: act_pos +=1 if act_pos == 0 and tot_pred_pos ==0: return 1 if tot_pred_pos == 0: return 0 return act_pos/tot_pred_pos
def calibration_pos(actual, pred, sensitive, target_group, positive_pred): tot_pred_pos = 0 act_pos = 0 for (act, pred_val, sens) in zip(actual, pred, sensitive): if sens != target_group: continue elif pred_val == positive_pred: tot_pred_pos += 1 if act == positive_pred: act_pos += 1 if act_pos == 0 and tot_pred_pos == 0: return 1 if tot_pred_pos == 0: return 0 return act_pos / tot_pred_pos
# Problem Link: https://www.hackerrank.com/contests/projecteuler/challenges/euler013/problem sum = 0 for _ in range(int(input())): sum += int(input()) print(str(sum)[:10])
sum = 0 for _ in range(int(input())): sum += int(input()) print(str(sum)[:10])
# -*- coding: utf-8 -*- # # -- General configuration ------------------------------------- source_suffix = ".rst" master_doc = "index" project = u"Sphinx theme for dynamic html presentation style" copyright = u"2012-2021, Sphinx-users.jp" version = "0.5.0" # -- Options for HTML output ----------------------------------- extensions = [ "sphinxjp.themes.impressjs", ] html_theme = "impressjs" html_use_index = False
source_suffix = '.rst' master_doc = 'index' project = u'Sphinx theme for dynamic html presentation style' copyright = u'2012-2021, Sphinx-users.jp' version = '0.5.0' extensions = ['sphinxjp.themes.impressjs'] html_theme = 'impressjs' html_use_index = False
"""Custom mail app exceptions""" class MultiEmailValidationError(Exception): """ General exception for failures while validating multiple emails """ def __init__(self, invalid_emails, msg=None): """ Args: invalid_emails (set of str): All email addresses that failed validation msg (str): A custom exception message """ self.invalid_emails = invalid_emails super().__init__(msg)
"""Custom mail app exceptions""" class Multiemailvalidationerror(Exception): """ General exception for failures while validating multiple emails """ def __init__(self, invalid_emails, msg=None): """ Args: invalid_emails (set of str): All email addresses that failed validation msg (str): A custom exception message """ self.invalid_emails = invalid_emails super().__init__(msg)
operators = { '+': (lambda a, b: a + b), '-': (lambda a, b: a - b), '*': (lambda a, b: a * b), '/': (lambda a, b: a / b), '**': (lambda a, b: a ** b), '^': (lambda a, b: a ** b) } priorities = { '+': 1, '-': 1, '*': 2, '/': 2, '**': 3, '^': 3 } op_chars = {char for op in operators for char in op} def evaluate(expression): infix = _parse_tokens(expression.replace(' ', '')) postfix = _postfix(infix) stack = [] for token in postfix: if _is_number(token): stack.append(ExpressionNode(token)) if token in operators: t1, t2 = stack.pop(), stack.pop() node = ExpressionNode(token) node.left, node.right = t1, t2 stack.append(node) return stack.pop().result() class ExpressionNode: def __init__(self, value): self.value = value self.left = None self.right = None def result(self): if _is_number(self.value): return _to_number(self.value) else: return operators[self.value]( self.right.result(), self.left.result()) def _postfix(tokens): stack = ['('] tokens.append(')') postfix = [] for token in tokens: if _is_number(token): postfix.append(token) elif token == '(': stack.append('(') elif token == ')': while stack[-1] != '(': postfix.append(stack.pop()) stack.pop() else: while _priority(token) <= _priority(stack[-1]): postfix.append(stack.pop()) stack.append(token) return postfix def _priority(token): if token in priorities: return priorities[token] return 0 def _parse_tokens(exp): tokens = [] next_token = "" pos = 0 while pos < len(exp): if _is_number(exp[pos]): next_token, pos = _read_next_value(exp, pos) elif exp[pos] in op_chars: next_token, pos = _read_next_operator(exp, pos) elif exp[pos] in ('(', ')'): next_token = exp[pos] else: raise ValueError("Unrecognized character at position " + str(pos)) tokens.append(next_token) pos += 1 return tokens def _read_next_value(exp, pos): token = "" while pos < len(exp) and (_is_number(exp[pos]) or exp[pos] == '.'): token += exp[pos] pos += 1 return token, pos - 1 def _read_next_operator(exp, pos): token = "" while (pos < len(exp) and exp[pos] in op_chars): token += exp[pos] pos += 1 return token, pos - 1 def _to_number(str): try: return int(str) except ValueError: return float(str) def _is_number(str): try: complex(str) return True except ValueError: return False
operators = {'+': lambda a, b: a + b, '-': lambda a, b: a - b, '*': lambda a, b: a * b, '/': lambda a, b: a / b, '**': lambda a, b: a ** b, '^': lambda a, b: a ** b} priorities = {'+': 1, '-': 1, '*': 2, '/': 2, '**': 3, '^': 3} op_chars = {char for op in operators for char in op} def evaluate(expression): infix = _parse_tokens(expression.replace(' ', '')) postfix = _postfix(infix) stack = [] for token in postfix: if _is_number(token): stack.append(expression_node(token)) if token in operators: (t1, t2) = (stack.pop(), stack.pop()) node = expression_node(token) (node.left, node.right) = (t1, t2) stack.append(node) return stack.pop().result() class Expressionnode: def __init__(self, value): self.value = value self.left = None self.right = None def result(self): if _is_number(self.value): return _to_number(self.value) else: return operators[self.value](self.right.result(), self.left.result()) def _postfix(tokens): stack = ['('] tokens.append(')') postfix = [] for token in tokens: if _is_number(token): postfix.append(token) elif token == '(': stack.append('(') elif token == ')': while stack[-1] != '(': postfix.append(stack.pop()) stack.pop() else: while _priority(token) <= _priority(stack[-1]): postfix.append(stack.pop()) stack.append(token) return postfix def _priority(token): if token in priorities: return priorities[token] return 0 def _parse_tokens(exp): tokens = [] next_token = '' pos = 0 while pos < len(exp): if _is_number(exp[pos]): (next_token, pos) = _read_next_value(exp, pos) elif exp[pos] in op_chars: (next_token, pos) = _read_next_operator(exp, pos) elif exp[pos] in ('(', ')'): next_token = exp[pos] else: raise value_error('Unrecognized character at position ' + str(pos)) tokens.append(next_token) pos += 1 return tokens def _read_next_value(exp, pos): token = '' while pos < len(exp) and (_is_number(exp[pos]) or exp[pos] == '.'): token += exp[pos] pos += 1 return (token, pos - 1) def _read_next_operator(exp, pos): token = '' while pos < len(exp) and exp[pos] in op_chars: token += exp[pos] pos += 1 return (token, pos - 1) def _to_number(str): try: return int(str) except ValueError: return float(str) def _is_number(str): try: complex(str) return True except ValueError: return False
states = ["Washington", "Oregon", "California"] for x in states: print(x) print("Washington" in states) print("Tennessee" in states) print("Washington" not in states) states2 = ["Arizona", "Ohio", "Louisiana"] best_states = states + states2 print(best_states) print(best_states[1:3]) print(best_states[:2]) print(best_states[4:])
states = ['Washington', 'Oregon', 'California'] for x in states: print(x) print('Washington' in states) print('Tennessee' in states) print('Washington' not in states) states2 = ['Arizona', 'Ohio', 'Louisiana'] best_states = states + states2 print(best_states) print(best_states[1:3]) print(best_states[:2]) print(best_states[4:])
#!/usr/local/bin/python # -*- coding: utf-8 -*- ## # Calculates and display a restaurant bill with tax and tips # @author: rafael magalhaes # Tax Rate in percent TAX = 8/100 # Tip percentage TIP = 18/100 # Getting the meal value print("Welcome to grand total restaurant app.") meal_value = float(input("How much was the ordered total meal: ")) # calculate and display the grand total amount tax_value = meal_value * TAX tip_value = meal_value * TIP grand_total = meal_value + tax_value + tip_value print("\n\nGreat Meal! Your meal and total amount is:\n") print("${:10,.2f} - Net meal ordered value".format(meal_value)) print("${:10,.2f} - State TAX of meal".format(tax_value)) print("${:10,.2f} - Suggested TIP of the meal".format(tip_value)) print("---------------------") print("${:10,.2f} - Grand TOTAL\n".format(grand_total))
tax = 8 / 100 tip = 18 / 100 print('Welcome to grand total restaurant app.') meal_value = float(input('How much was the ordered total meal: ')) tax_value = meal_value * TAX tip_value = meal_value * TIP grand_total = meal_value + tax_value + tip_value print('\n\nGreat Meal! Your meal and total amount is:\n') print('${:10,.2f} - Net meal ordered value'.format(meal_value)) print('${:10,.2f} - State TAX of meal'.format(tax_value)) print('${:10,.2f} - Suggested TIP of the meal'.format(tip_value)) print('---------------------') print('${:10,.2f} - Grand TOTAL\n'.format(grand_total))
# Topics topics = { # Letter A "Amor post mortem" : ["Love beyond death.", "The nature of love is eternal, a bond that goes beyond physical death."] , "Amor bonus" : ["Good love.", "The nature of love is good."] , "Amor ferus" : ["Fiery love.", "A negative nature of the physical love, reference to passionate, rough sex."] , "Amor mixtus" : ["Mix love.", "The complex nature of love when the physical and spiritual parts merge."] # Letter B , "Beatus ille" : ["Blissful thee.", "A praise to the simple life, farm and rural instead of the hustle of the modern life."] # Letter C , "Carpe diem" : ["Seize the day.", "To enjoy the present and not worry about the future; to live in the moment."] , "Collige virgo rosas" : ["Grab the roses, virgin.", "The irrecoverable nature of youth and beauty; an invitation to enjoy love (represented in the symbol of a rose) before time takes away our youth."] , "Contempus mundi" : ["Contempt to the world.", "Contempt to the world and the terrenal life, nothing but a valley of pain and tears."] # Letter D , "Descriptio puellae" : ["Description of a young girl.", "Description of a young girl in a descendant order, head, neck, chest, ..."] , "Dum vivimus, vivamus" : ["While we're alive, we live.", "The idea of life as something transient and inalienable, hence an invitation to enjoy and seize it."] # Letter F , "Fugit irreparabile tempus" : ["Time passes irredeemably.", "The idea of time as something that cannot be recovered, life itself is fleeting and transient."] , "Furor amoris" : ["Passionate love.", "The idea of love as a disease that negates all reason and logic."] # Letter H , "Homo viator" : ["Traveling man.", "The idea of the living man as an itinerant being, consider your existence as a journey through life."] # Letter I , "Ignis amoris" : ["The fire of love.", "The idea of love as a fire that burns inside you."] # Letter L , "Locus amoenus" : ["A nice scene.", "The mythical nature of the ideal scene described by its bucolic elements, almost always related to love."] # Letter M , "Memento mori" : ["Reminder of your death.", "Death is certain, the end of everyone's life, a reminder to never forget."] , "Militia est vita hominis super terra" : ["The life of men on this earth is a struggle.", "The idea of life as a military thing, a field of war against everyone; society, other men, love, destiny, ..."] , "Militia species amor est" : ["Love is a struggle.", "The idea of love as a struggle between the two lovers."] # Letter O , "Omnia mors aequat" : ["Death sets everyone equal.", "Death as an equality force, it doesn't care about hierarchy, richness or power; upon its arrival all humans are the same."] , "Oculos Sicarii" : ["Murdering eyes.", "The idea of a stare that would kill you if it could."] # Letter P , "Peregrinatio vitae" : ["Life as a journey.", "The idea of life as a journey, a road which where the man must walk through."] # Letter Q , "Quodomo fabula, sic vita" : ["Life is like theater.", "The idea that life is a play with the man itself as protagonist."] , "Quotidie morimur" : ["We die every day.", "Life has a determined time, by each moment that passes we're closer to the end of our journey which is death."] # Letter R , "Recusatio" : ["Rejection.", "Reject others values and actions."] , "Religio amoris" : ["Worship love.", "Love is a cult which man is bound to serve, as such we must free ourselves from it."] , "Ruit hora" : ["Time runs.", "By nature time is fleeting, hence life is too. As such we're running towards our inevitable death."] # Letter S , "Sic transit gloria mundi" : ["Glory is mundane and it passes by.", "Fortune, glory and reputation are all fleeting, death takes everything away."] , "Somnium, imago mortis" : ["Sleep, an image of death.", "When a man sleeps it's as though he was dead."] # Letter T , "Theatrum mundi" : ["The world, a theater.", "The idea of the world and life as a play, think of them as different dramatic scenarios in which actors -mankind- represent their lives on an already written play."] # Letter U , "Ubi sunt" : ["Where are they?", "The idea of the unkown, beyond death nothing is certain."] # Letter V , "Vanitas vanitatis" : ["Vanity of vanities.", "Looks are decieving, human ambitions are vain, thus they should be rejected."] , "Varium et mutabile semper femina" : ["Wayward and unsettled, women are.", "Women have a wayward nature, they change and never settle."] , "Venatus amoris" : ["The hunt for love.", "Love is presented as a hunt, where one hunts for its lover."] , "Vita flumen" : ["Life is a river.", "Existence is a river that always goes foward, never stopping, until it reaches the sea. Death."] , "Vita somnium" : ["Life is a dream.", "Life is irreal, strange and fleeting, much like a dream."] } first_word = [] for phrase in topics: templo = phrase.split(" ",1)[0].lower() tempup = phrase.split(" ",1)[0].capitalize() first_word.append(templo) first_word.append(tempup)
topics = {'Amor post mortem': ['Love beyond death.', 'The nature of love is eternal, a bond that goes beyond physical death.'], 'Amor bonus': ['Good love.', 'The nature of love is good.'], 'Amor ferus': ['Fiery love.', 'A negative nature of the physical love, reference to passionate, rough sex.'], 'Amor mixtus': ['Mix love.', 'The complex nature of love when the physical and spiritual parts merge.'], 'Beatus ille': ['Blissful thee.', 'A praise to the simple life, farm and rural instead of the hustle of the modern life.'], 'Carpe diem': ['Seize the day.', 'To enjoy the present and not worry about the future; to live in the moment.'], 'Collige virgo rosas': ['Grab the roses, virgin.', 'The irrecoverable nature of youth and beauty; an invitation to enjoy love (represented in the symbol of a rose) before time takes away our youth.'], 'Contempus mundi': ['Contempt to the world.', 'Contempt to the world and the terrenal life, nothing but a valley of pain and tears.'], 'Descriptio puellae': ['Description of a young girl.', 'Description of a young girl in a descendant order, head, neck, chest, ...'], 'Dum vivimus, vivamus': ["While we're alive, we live.", 'The idea of life as something transient and inalienable, hence an invitation to enjoy and seize it.'], 'Fugit irreparabile tempus': ['Time passes irredeemably.', 'The idea of time as something that cannot be recovered, life itself is fleeting and transient.'], 'Furor amoris': ['Passionate love.', 'The idea of love as a disease that negates all reason and logic.'], 'Homo viator': ['Traveling man.', 'The idea of the living man as an itinerant being, consider your existence as a journey through life.'], 'Ignis amoris': ['The fire of love.', 'The idea of love as a fire that burns inside you.'], 'Locus amoenus': ['A nice scene.', 'The mythical nature of the ideal scene described by its bucolic elements, almost always related to love.'], 'Memento mori': ['Reminder of your death.', "Death is certain, the end of everyone's life, a reminder to never forget."], 'Militia est vita hominis super terra': ['The life of men on this earth is a struggle.', 'The idea of life as a military thing, a field of war against everyone; society, other men, love, destiny, ...'], 'Militia species amor est': ['Love is a struggle.', 'The idea of love as a struggle between the two lovers.'], 'Omnia mors aequat': ['Death sets everyone equal.', "Death as an equality force, it doesn't care about hierarchy, richness or power; upon its arrival all humans are the same."], 'Oculos Sicarii': ['Murdering eyes.', 'The idea of a stare that would kill you if it could.'], 'Peregrinatio vitae': ['Life as a journey.', 'The idea of life as a journey, a road which where the man must walk through.'], 'Quodomo fabula, sic vita': ['Life is like theater.', 'The idea that life is a play with the man itself as protagonist.'], 'Quotidie morimur': ['We die every day.', "Life has a determined time, by each moment that passes we're closer to the end of our journey which is death."], 'Recusatio': ['Rejection.', 'Reject others values and actions.'], 'Religio amoris': ['Worship love.', 'Love is a cult which man is bound to serve, as such we must free ourselves from it.'], 'Ruit hora': ['Time runs.', "By nature time is fleeting, hence life is too. As such we're running towards our inevitable death."], 'Sic transit gloria mundi': ['Glory is mundane and it passes by.', 'Fortune, glory and reputation are all fleeting, death takes everything away.'], 'Somnium, imago mortis': ['Sleep, an image of death.', "When a man sleeps it's as though he was dead."], 'Theatrum mundi': ['The world, a theater.', 'The idea of the world and life as a play, think of them as different dramatic scenarios in which actors -mankind- represent their lives on an already written play.'], 'Ubi sunt': ['Where are they?', 'The idea of the unkown, beyond death nothing is certain.'], 'Vanitas vanitatis': ['Vanity of vanities.', 'Looks are decieving, human ambitions are vain, thus they should be rejected.'], 'Varium et mutabile semper femina': ['Wayward and unsettled, women are.', 'Women have a wayward nature, they change and never settle.'], 'Venatus amoris': ['The hunt for love.', 'Love is presented as a hunt, where one hunts for its lover.'], 'Vita flumen': ['Life is a river.', 'Existence is a river that always goes foward, never stopping, until it reaches the sea. Death.'], 'Vita somnium': ['Life is a dream.', 'Life is irreal, strange and fleeting, much like a dream.']} first_word = [] for phrase in topics: templo = phrase.split(' ', 1)[0].lower() tempup = phrase.split(' ', 1)[0].capitalize() first_word.append(templo) first_word.append(tempup)
def xfail(fun, excp): flag = False try: fun() except excp: flag = True assert flag
def xfail(fun, excp): flag = False try: fun() except excp: flag = True assert flag
def reverse_words(text): # 7 kyu reverse = [] words = text.split(' ') for word in words: reverse.append(word[::-1]) return ' '.join(reverse) t = "This is an example!" print(reverse_words(t))
def reverse_words(text): reverse = [] words = text.split(' ') for word in words: reverse.append(word[::-1]) return ' '.join(reverse) t = 'This is an example!' print(reverse_words(t))
with open('p11_grid.txt', 'r') as file: lines = file.readlines() n = [] for line in lines: a = line.split(' ') b = [] for i in a: b.append(int(i)) n.append(b) N = 0 for i in range(20): for j in range(20): horizontal, vertical, diag1, diag2 = 0, 0, 0, 0 if j < 17: horizontal = n[i][j]*n[i][j+1]*n[i][j+2]*n[i][j+3] if horizontal > N: N = horizontal if i < 17: vertical = n[i][j]*n[i+1][j]*n[i+2][j]*n[i+3][j] if vertical > N: N = vertical if i < 17 and j < 17: diag1 = n[i][j]*n[i+1][j+1]*n[i+2][j+2]*n[i+3][j+3] if diag1 > N: N = diag1 if i > 3 and j < 17: diag2 = n[i-1][j]*n[i-2][j+1]*n[i-3][j+2]*n[i-4][j+3] if diag2 > N: N = diag2 print(N)
with open('p11_grid.txt', 'r') as file: lines = file.readlines() n = [] for line in lines: a = line.split(' ') b = [] for i in a: b.append(int(i)) n.append(b) n = 0 for i in range(20): for j in range(20): (horizontal, vertical, diag1, diag2) = (0, 0, 0, 0) if j < 17: horizontal = n[i][j] * n[i][j + 1] * n[i][j + 2] * n[i][j + 3] if horizontal > N: n = horizontal if i < 17: vertical = n[i][j] * n[i + 1][j] * n[i + 2][j] * n[i + 3][j] if vertical > N: n = vertical if i < 17 and j < 17: diag1 = n[i][j] * n[i + 1][j + 1] * n[i + 2][j + 2] * n[i + 3][j + 3] if diag1 > N: n = diag1 if i > 3 and j < 17: diag2 = n[i - 1][j] * n[i - 2][j + 1] * n[i - 3][j + 2] * n[i - 4][j + 3] if diag2 > N: n = diag2 print(N)
class BST: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right class TreeInfo: def __init__(self, numberOfNodesVisited, latestVisitedNodeValue): self.numberOfNodesVisited = numberOfNodesVisited self.latestVisitedNodeValue = latestVisitedNodeValue # O(h + k) time | O(h) space, where h is the height/depth and k the kth largest element. def findKthLargestValueInBst(tree, k): # To solve this problem, what we do is to traverse from right - visit - left. And when we reach a visit element we add a counter and # keep track of it's value. We will add +1 every time until counter = k. We create a DS to store the treeInfo value treeInfo = TreeInfo(0, -1) reverseInOrderTraverse(tree, k, treeInfo) return treeInfo.latestVisitedNodeValue def reverseInOrderTraverse(node, k, treeInfo): # base case, when the node is none or the number of nodes visited is equal to k, we simply return until # find Kth largest value, where we return the latest visited node value. if node == None or treeInfo.numberOfNodesVisited >= k: return # reverse in order: right - visited - left reverseInOrderTraverse(node.right, k, treeInfo) if treeInfo.numberOfNodesVisited < k: treeInfo.numberOfNodesVisited += 1 treeInfo.latestVisitedNodeValue = node.value # if numberOfNodesVisited is less than k, we want to return; but if is equal to k we don't want, we want to inmediately return # otherwise it will update the value reverseInOrderTraverse(node.left, k, treeInfo)
class Bst: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right class Treeinfo: def __init__(self, numberOfNodesVisited, latestVisitedNodeValue): self.numberOfNodesVisited = numberOfNodesVisited self.latestVisitedNodeValue = latestVisitedNodeValue def find_kth_largest_value_in_bst(tree, k): tree_info = tree_info(0, -1) reverse_in_order_traverse(tree, k, treeInfo) return treeInfo.latestVisitedNodeValue def reverse_in_order_traverse(node, k, treeInfo): if node == None or treeInfo.numberOfNodesVisited >= k: return reverse_in_order_traverse(node.right, k, treeInfo) if treeInfo.numberOfNodesVisited < k: treeInfo.numberOfNodesVisited += 1 treeInfo.latestVisitedNodeValue = node.value reverse_in_order_traverse(node.left, k, treeInfo)
class ObjectA: """first type of object to be matched when running the gale-shapley algorithm""" def __init__(self, name: str): self.name = name def __repr__(self): return self.name class ObjectB: """second type of object to be matched when running the gale-shapley algorithm""" def __init__(self, name: str): self.name = name def __repr__(self): return self.name def gale_shapley(preferences_a: dict[ObjectA, list[ObjectB]], preferences_b: dict[ObjectB, list[ObjectA]]) -> \ dict[ObjectA, ObjectB]: """computes a stable matching given a two lists of objects and the preferences :param preferences_a: dictionary with all objects_a and the list of their preferences :param preferences_b: dictionary with all objects_b and the list of their preferences :return: dictionary of the stable matching from objects_b to objects_a """ matching_a = {} matching_b = {} unmatched_a = list(preferences_a.keys()) while unmatched_a: new_a = unmatched_a[0] if not preferences_a[new_a]: unmatched_a.remove(new_a) continue potential_b = preferences_a[new_a].pop(0) if potential_b in matching_a.values(): current_a = matching_b[potential_b] if preferences_b[potential_b].index(new_a) > preferences_b[potential_b].index(current_a): continue matching_a.pop(current_a) unmatched_a.append(current_a) matching_a[new_a] = potential_b matching_b[potential_b] = new_a unmatched_a.remove(new_a) return matching_a
class Objecta: """first type of object to be matched when running the gale-shapley algorithm""" def __init__(self, name: str): self.name = name def __repr__(self): return self.name class Objectb: """second type of object to be matched when running the gale-shapley algorithm""" def __init__(self, name: str): self.name = name def __repr__(self): return self.name def gale_shapley(preferences_a: dict[ObjectA, list[ObjectB]], preferences_b: dict[ObjectB, list[ObjectA]]) -> dict[ObjectA, ObjectB]: """computes a stable matching given a two lists of objects and the preferences :param preferences_a: dictionary with all objects_a and the list of their preferences :param preferences_b: dictionary with all objects_b and the list of their preferences :return: dictionary of the stable matching from objects_b to objects_a """ matching_a = {} matching_b = {} unmatched_a = list(preferences_a.keys()) while unmatched_a: new_a = unmatched_a[0] if not preferences_a[new_a]: unmatched_a.remove(new_a) continue potential_b = preferences_a[new_a].pop(0) if potential_b in matching_a.values(): current_a = matching_b[potential_b] if preferences_b[potential_b].index(new_a) > preferences_b[potential_b].index(current_a): continue matching_a.pop(current_a) unmatched_a.append(current_a) matching_a[new_a] = potential_b matching_b[potential_b] = new_a unmatched_a.remove(new_a) return matching_a
class Solution: def mostCommonWord(self, paragraph, banned): """ :type paragraph: str :type banned: List[str] :rtype: str """ return collections.Counter(word for word in re.sub("[!?',;.]", " ", paragraph).lower().split() if word not in banned).most_common(1)[0][0]
class Solution: def most_common_word(self, paragraph, banned): """ :type paragraph: str :type banned: List[str] :rtype: str """ return collections.Counter((word for word in re.sub("[!?',;.]", ' ', paragraph).lower().split() if word not in banned)).most_common(1)[0][0]
def compute(data): lines = data.split('\n') pairs = { '(':')', '[':']', '{':'}', '<':'>', } p1_scores = { ')':3, ']':57, '}':1197, '>':25137, } p2_scores = { ')':1, ']':2, '}':3, '>':4, } p1_score = 0 p2_score = [] for l in lines: stack = [] corrupt = False for c in l: if c in pairs.keys(): stack.append(c) elif c in pairs.values(): m = stack.pop() if pairs[m] != c: # print(f'corrupted: {l}') # print(f"{m} doesn't match {c} expected {pairs[m]}") p1_score += p1_scores[c] corrupt = True break if len(stack) > 0 and not corrupt: print(stack) # complete the braces - inverse of the stack: stack.reverse() completion_cost = 0 for c in stack: completion_cost = completion_cost * 5 completion_cost += p2_scores[pairs[c]] print(f'completion score for {l} is {completion_cost} from {stack}') p2_score.append(completion_cost) p2_score.sort() print(f'p1 = {p1_score}') middle = int(len(p2_score)/2) print(p2_score) print(f'middle of {len(p2_score)} is {middle}') print(f'p2 = {p2_score[middle]}') test_data = """[({(<(())[]>[[{[]{<()<>> [(()[<>])]({[<{<<[]>>( {([(<{}[<>[]}>{[]{[(<()> (((({<>}<{<{<>}{[]{[]{} [[<[([]))<([[{}[[()]]] [{[{({}]{}}([{[{{{}}([] {<[[]]>}<{[{[{[]{()[[[] [<(<(<(<{}))><([]([]() <{([([[(<>()){}]>(<<{{ <{([{{}}[<[[[<>{}]]]>[]]""" real_data = """{[[<{(<{[{{[{[[]{}]{<>{}}}({<>()}{{}{}})]}{({[<>{}]({}[])})[{[{}[]](()<>)}<[{}{}]{()<>}>]}}]<(({{{(){}}{[][] <<<({((<{<([([<>{}]<{}<>>]{<{}<>>({}<>)}])>}{({(([()[]]{[]()})({{}<>}<(){}>))[(<<><>>[()[]]){{()[]}< <<<[(({{(([[[[<><>][<><>]]]([[{}{}](<><>)][(<>[]){[]()}])])([[(<{}<>>(()[]))(<[][]>)]]{{<[[]{}]{< ({({([{{[[[{(<(){}><[]{}>)}]]][(<<([()[]](()[]))>[[[{}[]]{[]<>}](<()>[()<>]]]>(<(({}<>){<>[]}){<[]()>}>{[{( [([{(<[<<[({<[()<>][{}]>({{}{}})}({[<>{}][()()]}[([][]){()[]}]))]>>]>)<<[((([[{{()()}(<>{})}[(<>( {[[{<[[[[([[{[()[]]<[]()>}<({}())<[]<>>>]({<{}[]>}<<{}<>>>)](([(<>{}){[][]}]<[(){}]({}{})>)[((()){[]})<{{} {{<<((({(<[({<<>[]><{}{}>}((<>[])([]())))[((()[]){[]{}})]]{<([{}[]]<<>[]>)(({}[]}{[][]})><<([][])([][])>>} ([[(<({[[{[{<[<><>]({}())>}](<[[{}[]](<><>)]{{()<>}[{}]}>{((<><>]<()()>)([(){}]<()>)})}{[<{({}())<<><>>}[(() (<((([[<<[<[{[()[]][[]{}]}{([]<>){[]{}}}]>]>>{{([[({<>()}(<>{}))]<{(()<>)([])}([<>{}}{{}()})> (<({{<(<{[{<{[(){}][<>{}]}{[[][]]{<>{}}}>}<(([[][]][<>()])[[{}{}][{}()]])>]}>{{{([<(()())> (<[{<<(<<<((<[<>[]]>)({[[]<>]}<({}<>)([][])>))[{<[[]()](<>())>{<[]<>><{}()>}}(<<{}<>>(<>[] <[[(((([[(<[{((){})<{}<>>}{({}<>><{}<>>}]([{<>()}([]<>)]<{()()}({}[])>)>)]{{({([{}<>])(<<>() <({<(<{[{<<[[[{}[]][()[]]](<()()><()>)]>>[(((([]<>){(){}})<{{}()}({}())>)[<[[]()]{<>[]}><[()[]][<>()]>])[(<<< ([[[{(<<<([[[<<>[]>]]{<([]<>){[]{}}><<[]>({}<>)>}]<(<<{}<>>([])><{<>[]}<{}<>>>)([{[]()}<<> <({<<(<{(<<(({[]<>}{{}{}})(<<>[]><<>[]>))(<<<><>><[]{}>>{[()[]][()[]]})>>){{<{([{}()]{<>()}){<[][]>({}<>)}} (([{{(<[([([([[]()]({}))<<[][]><{}()>>][[[{}<>][<>{}]]]){[{[[][]]<{}{}>}<<()<>>(<>())>]}])<{{[(({})<[]()>){[< {(<<[<{<<{(([[()<>]{<>[]}]{[{}{}]{<>()}})<([[][]]{[]<>}){(()<>)<[]<>>}>)[[{{[]}}]]}<{{((<>)<{}>){ <{<{<{{[<{{<<<<>[]>{()[]}>><[<<>()>{{}[]}]<[{}]{[]()}>>}}>[[{(((<>{}]({}()))<<{}()>[[]()]>)}]{{({[<>() <[[<<([{([{{[[()()]<{}<>>][{{}()}<()()>]}({([]<>)<<>[]>}{[[][]][()[]]})}[((<{}{}><()[]>){<<>()>((){} <<{([[{[<{[<([()()]{()<>}>[<[]<>>[[]<>]]>{{[{}{}][()<>]}<[[]{}][{}{}]>}]<((({}<>)<<><>>){{<><>}[()<>]})> [[[[[{({((([<[<>{}]<{}()>>[<{}[]>[[]{}]]]{{{()<>}<{}[]>>([()()]{{}()})})))}[{{[({<{}[]>}<[[]()]>)( {[[<[([{((<[<[{}[]][<><>]>({{}{}}[{}{}])]{{({}{}){{}[]}><[{}[]]([]())>}>[{<{()<>}([]())>}]))(<[([[()][[][]] [(({[((<{<{<<[[]<>]<{}[]>>>{[<[]{}>[[]{}]]{((){})<[]>}}}<<<{{}{}}<<>()>>{<<>[]>([]{})}>>>}{[{{{<[]()>(()<>)}< {[[[{<([{[<{([<>()]{<>[])){<<><>>([]<>)}}<{[(){}]<()<>>}>>([[<()<>>((){})]][<<[]{}><()()>>(<[ [{(<{[({[{[{{(<>{})({}{})}<(<>[])>}([<()<>>[()<>]]{(()<>)<{}()>})]{([{{}{}}(()<>)][{()()>])[<<[][]>(<>[])> [[{[{([<<<<([{[][]}{<>()}]([[]<>]<<>[]>))<{[<>()][<>{}]}[((){})]>><[[<{}<>>([]())]]>><<{{(() <{[<<[[[<{{[<<[]{}>[()<>]><{()()}<()[]>>][[[<>{}][[]()]][<<>>{{}[]}]]}{<<<[]()>({}<>)>>(<[[]()]{<>[]} {(([({{<(<<[(({}{})[()[]])<<{}{}>(()[])>](([()[]]<{}()>){{<><>}<[][]>})>((<{()()}[{}()]>[{<>()} <(({(([[<[{[{<{}>(())}{<{}[]>[<>[]]}]{<{()}><<()()>[{}{}]>}}]({<<<()[]>{()<>}>>}[[{(<>){[]}}((()) {{<{<<(([[[{{[{}{}]{<>[]}}}{[<{}<>>[{}<>]]{{[][]}{[]]}}]({<([][])[<>]>{(()())<<><>>}}([([][]){{}()}]<{()[]}{[ [<<<<<[{<{{({[[]()](<>())}{{[]{}}([][])})}(<<[{}{}]({}<>)>[<<>>{()}]>)>({[(<[][]>{{}[]})][[(()())<(){}>]{<()< {({<<([[(<(([(()[])]{{{}<>)((){})}))[([<(){}>[<>()]]{{<><>}})<({<>{}}(<>[]))>]>({[{([]()){(){ <{[<(<{[(<<{(({}[])(<>()))}[{<[]<>><()[]>}<<{}{}>(<>{})>]>{{{<{}<>>[{}()]}}[<<()()}>(([]{})([] {<[(([{{{[(<<[{}()]>{(<>())[[]{}]}>){{[{{}[]}{()<>}]{(()<>)<<><>>}}}]}{(<[([[]][{}[]])]>)[[((<{}[]})[ ([[[({({{[<<[<[]<>><()>]>{([<><>])(<<><>><<>()>)}>[(([[][]]{()<>}>)([{(){}}({}<>)])]][(<<{{}{}}{() {([({[{{{[(<<<<><>>([][])>[<[]<>>[()<>]]>)[[(<()[]>)(<<>()>[()<>])]({<[][]>{[][]}}[<()()>[<>[]]])]](<<{<<><> <((({{<[[({[(([]<>)[[]<>])]{{<{}>{[]<>}}(([][])[()[]])}}{[{<()<>>[()[]]}{{[]<>}{[]()}}]}){([{{{}{}}[( {<<[[{[<(([[{([][])[<>()]}<{<><>}>](<<[][]>[[]{}]>[{<>}{{}<>}])]{<([()<>]<()[]>)(<[][]>(<>[]))>[{[[]< ([{((<[<<([[[{<>()}(<>())]([(){}](<>[]))][[<[]>]]]<{<[{}[]][[][]]>}([<[]()><<>{}>]<{(){}}[{}{}]>)>)>({([ ([{(<<[<{<[[(<[][]>{<><>}){<<>()>}]{({()[]}<<>()>)}][{({(){}}[()()])<[<><>]<<>[]>>}]>}<<[({< {<({[({{<[[({{(){}}<<>[]>}<({}[]){()())>)<{([]{})([]())}>]]>(<{[((<>[]){[]()})<<()<>>({}<>)>]{{{()[]}}} {({[[<(<{[[{<<[]()>[()()]>([<>{}]{<>[]))}<{([]())(()<>)}<<[]><[][]>>>][({<{}><[]()>})[<[()[]][()()]>{<{}<>> {({(((<{<[<(<({}<>)[()()]>{<[]{}><()<>>})[<({}<>)><(<>)<()()>>]>(<(([][])<()<>>)<<<><>>([])>>{(<[]{}> [{{[([<<(<[<({<><>}{[]()})[{<><>}]>{<(()[])><[<><>]>}][<{[{}<>][[]<>]}(([]{}))>[[([])<{}[]>]{<(){}>({}())}]] {[<<((<<[([[([()[]]({}()))(<{}()>{(){}})][((<>[]]{{}{}})((()<>)<<><>>)]]{[<(<>[])<[]>>([<>()]{[] ((({({{<[(((<[<>[]]([]<>)>[<[]{}>{<><>}])<{[<>()][()<>]}{<{}<>>[[]()]}>))<[<{(<><>)<()<>>}>[<[[]<>]<[]{ {<<<{<({([({((<><>)[[][]]){[()<>]{<><>}}}<[{[]<>}[<>[]]][[()<>]{(){}}]>)<[[[[]<>]]((<><>))}(<<()<>><<><>>><[[ (({{[({<{<{[[<<>[]>([][])]{<<>()>{{}()>}]{[<<>[]>[{}{}]][{()()}{[]<>}]}}([({{}[]}{{}()}){(()<>){()<>}} (<([({{{{<[<{{<>[]}{{}}}<[{}{}]<{}{}>>><{{(){}}([]{})}>](<[([]())[()]]>[(<[]<>>[[]{}])])>[{(<[[][]]<{} ((({[{{{([<{{<<><>><[][]>}{({}())<<>{}>}}[{([]())}[<<>()>({}[])]]>{<[<<>[]]<()<>>][[()[]][<>[]]]>[{[[] <(<<[[<{({{[(([][]))([<><>][{}{}])]}})}>]](<([{{[{<{[][]}[{}<>]>([{}()])}]}([{{(())}{{{}{}}<[]{} <([<[{{({[(({({}{})<{}()>}))[[((<><>)<{}>)[[[][]]((){})]]<<<[]()>{()[]}>>]]{<<(<[]<>>[<>{}]){({}())}>>}}{[[ [<<[(({<({{{[{[][]}{(){}}][<()()>]}((<{}{}>>[{{}[]}])}{<[(<>[])[(){}]](<<><>>({}<>))><(({}()) [([{<{(([[[([{{}[]}<(){}>])]<{([[]()][[]<>])([{}{}]([][]))}>]({<<([][]){()<>}>>{([()<>]([])){{{}()}{[][]} {<({[<[(({{({<(){}><[][]>}[{<>()}({})])<[[{}]{<><>}]<<[]{}>([]{})>>}[(({[]<>})([(){}]<()[]>))]}))]><<( {<<[[<[[[((<[<{}<>><<><>>]<({}[])([]{})>>{<{()<>}>{([]{})[()[]]}}>[[<({}<>)([]{})>(<{}()>[[]()])][[<()<>><[] {((({(<{[[[({<<>[]><{}<>>}[{[][]}[<>()]]){([<>()][[]()])({[]<>}{{}<>})}]<<{[{}<>]<{}()>}<(()){(){}}>>{ <[[{<<([<[{{(({}()){[]{}}){{{}[]}{<>()}}}}{<{[<><>]<{}{}>}(({}()){()<>})>(<(<>{})[<>()]>{<<><>>{[][]}} {{([{(((({<{[({}{}){{}{}}]{(<>{})[{}{}]}}[{[()[]][{}()]}{(()[])(()())}]><({(<>[])}((())<[]>))>}<{{{{{}<> ({(([({(<<<((({}[])((){}))((<><>)[[][]]))((<()<>><(){}>){{{}()}(()[])})><([[{}<>][()[]]])(([<> <<<<<{({{([(([{}{}]<{}()>))][<<{<>[]}{<>}>({()<>}{{}()})>[([<><>]{{}()})([[]{}])}]){({[([]<>)<[][]>][{<><> ((<[<<{{<([{{[{}<>]{{}<>}}([[][]]<<>{}>)}{[[[]{}]])]{[<<{}<>>{{}{}}><({}<>)>]([(<><>)[{}()]])})(< <(((<[(((<([[{(){}}<<>()>]]<{<<>{}><(){}>}<{[][]}{[]{}}>>)>{<<{{<><>}{[]<>}}{{<>[]}<[]()>}>[{{{}()}{[]<> {[<{((<<[<<([(()()){{}()}](([]{}){<>()>))>{({((){})({}())}[[()][<><>]])<([{}[]][[]{}])(([]{}){()<>} (<[({[(([[{[[<{}{}><<>{}>][<<>{}>]]([{<>()}<<>{}>]{{[]{}}({}())})}([({{}()}{{}()})][[<<>[]>[<>{}]]{<<>[])}]) {<{(((<([[[<[(<>())[()[]]]<<()[]><{}<>>>>]<{({<>()}(()<>)){<<><>>{{}[]}}}{(<()<>><<>[]>){{[]()}[[]()]}}>][(<[ <<[[<(({{{{<{{[]()}({}<>)}[(<>{}){[]{}}]>[<{[][]}{{}{}}>]}{{(<<>()><{}{}>)[{{}[])[(){}]]}(([()[]][{}[]]){< (<(<<<([{((<[[{}[]]{{}}]<({}<>)<()<>>>})<(<[<>{}]<{}<>>><([]<>)([]<>)>)[{<{}<>>[()()]}[(<>[])] <{(([([[<<([{{<><>}[<><>}}{[{}<>]{{}<>}}]{([[]()]<()[]>)[({}<>){[][]}]})({[((){})<<>[]>][{<>()}[[]<>] <<<{{<{[({<<[[[]][[][]]]({[]()}{{}[]})>>{[({{}<>}{[][]})[[{}()]{[]}]]}}([[[[<>[]]<{}[]>]{[{}{ {<{{([([<{[[{([]<>)[()<>]}][{<()()>}<{{}<>}([]{})>]]{{[{[][]}<{}[]>]([<>()]{{}{}})}{(({}{})(( <{<((<{<{([<((()<>){()[]}){[[]<>](()[])}><(([]()])<[[]()]{{}<>}>>]{({<()><()()>}[[()<>]<<>[]>] [<[{[(<<[(<<<(<>[])[[]]>{<(){}>}><([<>[]]{<>{}})[{<><>}{[]()}]>>{[(<[]<>>)<[{}<>]{<>()}>]{<(()())[[][]]>[ [<<<{[(<<[({{{<>[]}<[]()>}{<<>[]>(<>[]]}})]>>{[[<({([][]){{}()}}[{<>()}({}())])({(()[])(<> [<[[<{<{{{{{<([]())[<>()]><{()<>}[<><>]>}}}}}><<{(([{<[][]>{[]()}}[{[][]}{{}<>}>][(({}())({}()) <[[{{[<{<<[<(<<>[]>)<<()()>{{}[]}>>{<{()<>}[<><>]>[{{}{}}{()}]}]{(<([]<>)({}())>{<[]{}>}){[({}())]{( ({{[(([(<{[[{(()<>)({}())}<({}{}){{}}>](((()())<{}()>)[<{}<>><{}()>])]({{([][])({}<>)}<({}())<[] {[(<[<{[(([<(<[]()><{}()>)<<[][]><()>>>][<<[{}[]]<{}{}>](<<>>{<>[]})>[{(<>())[<>]}<{[]<>}(( [{{(<{{[{<<<<(<><>)>(({}[]))><<[[]{}][<>()]>>>({[({}{}){<>{}}]<[<><>]>})>}<[<{{<{}{}>{<><>}}}>]<( {<{<<{[{<[[[<<{}[]>{()<>}>(<()[]>({}<>))]{<((){})[<><>]><{<>{}}{<>()}>}]({([()[]]{[]()})}([{()()}}<(<>() [<<([(<[<[[([(<>{}){()<>}][<{}()><{}()>])]((([()<>]{()<>})[[<><>]]))][{([{{}{}}]<{<>}[{}()]>)[[{ <[[{([({<<<(<([]<>)<<><>>>[{[]()}<(){}>])>>>({(([[<>{}]([]<>)]{[(){}](()())})([{<>()}([]<>)]))<[{[{}()]{<>[]} <(([{<{[[<({[({}()){{}[]}]{<{}[]>[{}<>]}}[[[{}<>](<><>)][<()()>({}<>)]])<{{[{}<>]{<>[]}}}([[{}[]]<<>{}>])>> {(<[([[[{[<[[<[]()>[{}{}]][<()[]>{[]()}]]>[[[(<>[]){<>[]}][{<>{}}<()[]>]]]](<{{([]())[()()]]<[{}[]][[]( [([[[<<<{({[[{[][]}<()[]>]][{{[]()}([]<>)}({()<>})]))[<{<[<>{}]{[]{}}>({<>{}}[()()])}><<([<>[]]{{}[]})[<[][] {(({({<{([[[[<[]{}>(<>{})]{({}())(()<>)}]]<{{<[]()>(()())}{([][])}}<{[[][]]<()<>>}{(<>{})({} [{{<[{(<{({<[{[]<>}[[]()]][[{}<>]{{}()}]>(<[()()]>([{}[]]{(){}}))}{{{({}<>)<<><>>}({[]<>)<{}>)}})([<({ (<[{{{{<(<[<{{()()}{[]{}}}<([]{}){<>()}>>[({{}<>}{{}[]})]][[({{}()}(<>[])){<[][]>[<>()]}]]>]>{[( [{<(<<{[<(<[<({}[])({}{})>]{<{{}()}<<><>>>{<{}{}>(()())}}>)>][({<[[<(){}>(<>())](({}{}){{}()} {([[{<{<{(([<([]<>)[<>]>{(<>[]){<>[]}}][<[(){}]{{}()}>((<>[]))])<({[()<>](()[])}){<[()<>]{<>{}}>{([])<() <[{[{(<<({[((<[]{}>{[]{}})([()[]]<(){}>))<{<<>[]>[{}]}{<{}<>>{()}}>]{{{(<>())}(({}<>))}<<{()<>}({}())>([{}< <(<[{{<{{[([{{(){}}<<>{}>}(<(){}>)][[{{}<>}(()<>)]]){([<<>{}>[()()]][{[]()}<{}()>])}]<{([{[]}([][] <[[{<{[<{([<[<[]<>][{}]]<({}{})([])>>]({{(<><>)[[]<>]}<<{}[]>[[]<>]>}))}([<(({()()}{[]<>}))<{<()[]><[]()>}((( ({{{<{([{<[{{[{}<>](<><>)}[[<>()]({}[])]}[[<(){}>({}<>)]<(()())({}())>])>[<<<[[][]][(){}]><([ ((<{[<[[(((<[<<>()>([]())]<(()<>){()[]}>>[<{(){}}{{}}>[[(){}}<[]{}>]])<[[[[][]][{}()]]{[{}()][ (({[[<{({[[[[[<><>]<[]{}>]<(<>{}){[]()}>][(([]<>){()[]})([<>{}]<()<>>)]]]}[[<{<(<><>)<{}[]>>}<<{<> <{({[{(([[{(<(()[])<(){}>>{<{}{}>{<><>}})[<(()())<[]{}>>]}[{{{[]}[()[]]}[<()[]><<>{}>]}{<[<><>]{[] [<[<<{<{{<[(<{(){}}[<>()]><({}<>)<<>{}>))<<<()<>>({}<>)><[<><>][()]>>](({({}()){()()}}<[[]<>]<<>{}>>)<[[[] {<{(<(<[<([{<{{}[]}(()[])>[({}())<[][]>]}<<{()()}[<><>]>>]<{{[[]{}]{<><>}}(({}{})[[]])}({(<>[])<<>{}> {{{[[((<[(<<[[{}()]<[]<>>]{<()[]>}>[<<()()>>([<><>]((){}))]>{<<[{}{}][{}()]>[(()())[<>[]]]>{{ <({<{[{<[<({{[<><>]{<>[]}}<{[]<>}<<><>>]}{{[{}{}]{{}{}}}{<[]<>>{[][]}}})(<({()<>}<{}[]>){([]{}) {<(<<[<{([{[({{}<>}[()()]){(()<>)[{}<>]}]}])}>]{{(<[<<((()())<<>()>)>{([[]{}]((){}))<({}<>)({}< [<(<[[{{[([[<<[]{}>{[]<>}>{(<>[])[{}{}]>]([[[]<>](()())])])([[<{<>{}}(<><>)><({}<>)<()>>][({[]<>} [<{({{[<([{<{[()[]][(){}]}>[([<>[]]{{}})]}<<((()<>}(()()))<[(){}]>>((({}())[{}<>]){({}<>)<<>[]>})>]{<<{<{}[] [[<{<{({(<{<{({}())[{}]}([()[]]{{}()})>}((([{}{}]{()<>})<[<>()]{<>[]}>)[([()<>]<<><>>)[[()[]]{[]}]]]>){([[[ {<(([<<[<{(((<()<>>{{}()})({[]{}}[[]{}]))(([{}[]]{[]<>})<<[]>(<>{})>))}[{{<(<><>]<<>>>}}({[({}[]) [[{{[([<[({[{(<>()}[<>[]]}{{<>{}}<[]{}>}]{{{()[]}([]{})}([()<>]{()<>})}}[<{(<>)<<><>>}{{<>[]}<<>[]>}>({< {{[{{{<([<{<{<{}<>>}{[(){}]{{}()}}><{{[]()}<{}>}>)[[{[{}{}]{()<>}}<(<>{}){[]{}}>][[(()<>)(<>())]({[]<>}[()[] ((<({<{[(<[{[<<>><{}()>][[{}[]>]}{({()<>}[{}[]])[(()())]}][<<{<>{}}<<><>>>[{[][]}{<>()}]>]>[<({({}()){{ [([<<({({[<{(((){}){<>{}})(({}<>))}{<[[]()][{}{}]>{([][])<[][]>}}>]<<(<{<>()}[()[]]>[<(){}>[<>()>])<<[{}(""" compute(real_data)
def compute(data): lines = data.split('\n') pairs = {'(': ')', '[': ']', '{': '}', '<': '>'} p1_scores = {')': 3, ']': 57, '}': 1197, '>': 25137} p2_scores = {')': 1, ']': 2, '}': 3, '>': 4} p1_score = 0 p2_score = [] for l in lines: stack = [] corrupt = False for c in l: if c in pairs.keys(): stack.append(c) elif c in pairs.values(): m = stack.pop() if pairs[m] != c: p1_score += p1_scores[c] corrupt = True break if len(stack) > 0 and (not corrupt): print(stack) stack.reverse() completion_cost = 0 for c in stack: completion_cost = completion_cost * 5 completion_cost += p2_scores[pairs[c]] print(f'completion score for {l} is {completion_cost} from {stack}') p2_score.append(completion_cost) p2_score.sort() print(f'p1 = {p1_score}') middle = int(len(p2_score) / 2) print(p2_score) print(f'middle of {len(p2_score)} is {middle}') print(f'p2 = {p2_score[middle]}') test_data = '[({(<(())[]>[[{[]{<()<>>\n[(()[<>])]({[<{<<[]>>(\n{([(<{}[<>[]}>{[]{[(<()>\n(((({<>}<{<{<>}{[]{[]{}\n[[<[([]))<([[{}[[()]]]\n[{[{({}]{}}([{[{{{}}([]\n{<[[]]>}<{[{[{[]{()[[[]\n[<(<(<(<{}))><([]([]()\n<{([([[(<>()){}]>(<<{{\n<{([{{}}[<[[[<>{}]]]>[]]' real_data = '{[[<{(<{[{{[{[[]{}]{<>{}}}({<>()}{{}{}})]}{({[<>{}]({}[])})[{[{}[]](()<>)}<[{}{}]{()<>}>]}}]<(({{{(){}}{[][]\n<<<({((<{<([([<>{}]<{}<>>]{<{}<>>({}<>)}])>}{({(([()[]]{[]()})({{}<>}<(){}>))[(<<><>>[()[]]){{()[]}<\n<<<[(({{(([[[[<><>][<><>]]]([[{}{}](<><>)][(<>[]){[]()}])])([[(<{}<>>(()[]))(<[][]>)]]{{<[[]{}]{<\n({({([{{[[[{(<(){}><[]{}>)}]]][(<<([()[]](()[]))>[[[{}[]]{[]<>}](<()>[()<>]]]>(<(({}<>){<>[]}){<[]()>}>{[{(\n[([{(<[<<[({<[()<>][{}]>({{}{}})}({[<>{}][()()]}[([][]){()[]}]))]>>]>)<<[((([[{{()()}(<>{})}[(<>(\n{[[{<[[[[([[{[()[]]<[]()>}<({}())<[]<>>>]({<{}[]>}<<{}<>>>)](([(<>{}){[][]}]<[(){}]({}{})>)[((()){[]})<{{}\n{{<<((({(<[({<<>[]><{}{}>}((<>[])([]())))[((()[]){[]{}})]]{<([{}[]]<<>[]>)(({}[]}{[][]})><<([][])([][])>>}\n([[(<({[[{[{<[<><>]({}())>}](<[[{}[]](<><>)]{{()<>}[{}]}>{((<><>]<()()>)([(){}]<()>)})}{[<{({}())<<><>>}[(()\n(<((([[<<[<[{[()[]][[]{}]}{([]<>){[]{}}}]>]>>{{([[({<>()}(<>{}))]<{(()<>)([])}([<>{}}{{}()})>\n(<({{<(<{[{<{[(){}][<>{}]}{[[][]]{<>{}}}>}<(([[][]][<>()])[[{}{}][{}()]])>]}>{{{([<(()())>\n(<[{<<(<<<((<[<>[]]>)({[[]<>]}<({}<>)([][])>))[{<[[]()](<>())>{<[]<>><{}()>}}(<<{}<>>(<>[]\n<[[(((([[(<[{((){})<{}<>>}{({}<>><{}<>>}]([{<>()}([]<>)]<{()()}({}[])>)>)]{{({([{}<>])(<<>()\n<({<(<{[{<<[[[{}[]][()[]]](<()()><()>)]>>[(((([]<>){(){}})<{{}()}({}())>)[<[[]()]{<>[]}><[()[]][<>()]>])[(<<<\n([[[{(<<<([[[<<>[]>]]{<([]<>){[]{}}><<[]>({}<>)>}]<(<<{}<>>([])><{<>[]}<{}<>>>)([{[]()}<<>\n<({<<(<{(<<(({[]<>}{{}{}})(<<>[]><<>[]>))(<<<><>><[]{}>>{[()[]][()[]]})>>){{<{([{}()]{<>()}){<[][]>({}<>)}}\n(([{{(<[([([([[]()]({}))<<[][]><{}()>>][[[{}<>][<>{}]]]){[{[[][]]<{}{}>}<<()<>>(<>())>]}])<{{[(({})<[]()>){[<\n{(<<[<{<<{(([[()<>]{<>[]}]{[{}{}]{<>()}})<([[][]]{[]<>}){(()<>)<[]<>>}>)[[{{[]}}]]}<{{((<>)<{}>){\n<{<{<{{[<{{<<<<>[]>{()[]}>><[<<>()>{{}[]}]<[{}]{[]()}>>}}>[[{(((<>{}]({}()))<<{}()>[[]()]>)}]{{({[<>()\n<[[<<([{([{{[[()()]<{}<>>][{{}()}<()()>]}({([]<>)<<>[]>}{[[][]][()[]]})}[((<{}{}><()[]>){<<>()>((){}\n<<{([[{[<{[<([()()]{()<>}>[<[]<>>[[]<>]]>{{[{}{}][()<>]}<[[]{}][{}{}]>}]<((({}<>)<<><>>){{<><>}[()<>]})>\n[[[[[{({((([<[<>{}]<{}()>>[<{}[]>[[]{}]]]{{{()<>}<{}[]>>([()()]{{}()})})))}[{{[({<{}[]>}<[[]()]>)(\n{[[<[([{((<[<[{}[]][<><>]>({{}{}}[{}{}])]{{({}{}){{}[]}><[{}[]]([]())>}>[{<{()<>}([]())>}]))(<[([[()][[][]]\n[(({[((<{<{<<[[]<>]<{}[]>>>{[<[]{}>[[]{}]]{((){})<[]>}}}<<<{{}{}}<<>()>>{<<>[]>([]{})}>>>}{[{{{<[]()>(()<>)}<\n{[[[{<([{[<{([<>()]{<>[])){<<><>>([]<>)}}<{[(){}]<()<>>}>>([[<()<>>((){})]][<<[]{}><()()>>(<[\n[{(<{[({[{[{{(<>{})({}{})}<(<>[])>}([<()<>>[()<>]]{(()<>)<{}()>})]{([{{}{}}(()<>)][{()()>])[<<[][]>(<>[])>\n[[{[{([<<<<([{[][]}{<>()}]([[]<>]<<>[]>))<{[<>()][<>{}]}[((){})]>><[[<{}<>>([]())]]>><<{{(()\n<{[<<[[[<{{[<<[]{}>[()<>]><{()()}<()[]>>][[[<>{}][[]()]][<<>>{{}[]}]]}{<<<[]()>({}<>)>>(<[[]()]{<>[]}\n{(([({{<(<<[(({}{})[()[]])<<{}{}>(()[])>](([()[]]<{}()>){{<><>}<[][]>})>((<{()()}[{}()]>[{<>()}\n<(({(([[<[{[{<{}>(())}{<{}[]>[<>[]]}]{<{()}><<()()>[{}{}]>}}]({<<<()[]>{()<>}>>}[[{(<>){[]}}((())\n{{<{<<(([[[{{[{}{}]{<>[]}}}{[<{}<>>[{}<>]]{{[][]}{[]]}}]({<([][])[<>]>{(()())<<><>>}}([([][]){{}()}]<{()[]}{[\n[<<<<<[{<{{({[[]()](<>())}{{[]{}}([][])})}(<<[{}{}]({}<>)>[<<>>{()}]>)>({[(<[][]>{{}[]})][[(()())<(){}>]{<()<\n{({<<([[(<(([(()[])]{{{}<>)((){})}))[([<(){}>[<>()]]{{<><>}})<({<>{}}(<>[]))>]>({[{([]()){(){\n<{[<(<{[(<<{(({}[])(<>()))}[{<[]<>><()[]>}<<{}{}>(<>{})>]>{{{<{}<>>[{}()]}}[<<()()}>(([]{})([]\n{<[(([{{{[(<<[{}()]>{(<>())[[]{}]}>){{[{{}[]}{()<>}]{(()<>)<<><>>}}}]}{(<[([[]][{}[]])]>)[[((<{}[]})[\n([[[({({{[<<[<[]<>><()>]>{([<><>])(<<><>><<>()>)}>[(([[][]]{()<>}>)([{(){}}({}<>)])]][(<<{{}{}}{()\n{([({[{{{[(<<<<><>>([][])>[<[]<>>[()<>]]>)[[(<()[]>)(<<>()>[()<>])]({<[][]>{[][]}}[<()()>[<>[]]])]](<<{<<><>\n<((({{<[[({[(([]<>)[[]<>])]{{<{}>{[]<>}}(([][])[()[]])}}{[{<()<>>[()[]]}{{[]<>}{[]()}}]}){([{{{}{}}[(\n{<<[[{[<(([[{([][])[<>()]}<{<><>}>](<<[][]>[[]{}]>[{<>}{{}<>}])]{<([()<>]<()[]>)(<[][]>(<>[]))>[{[[]<\n([{((<[<<([[[{<>()}(<>())]([(){}](<>[]))][[<[]>]]]<{<[{}[]][[][]]>}([<[]()><<>{}>]<{(){}}[{}{}]>)>)>({([\n([{(<<[<{<[[(<[][]>{<><>}){<<>()>}]{({()[]}<<>()>)}][{({(){}}[()()])<[<><>]<<>[]>>}]>}<<[({<\n{<({[({{<[[({{(){}}<<>[]>}<({}[]){()())>)<{([]{})([]())}>]]>(<{[((<>[]){[]()})<<()<>>({}<>)>]{{{()[]}}}\n{({[[<(<{[[{<<[]()>[()()]>([<>{}]{<>[]))}<{([]())(()<>)}<<[]><[][]>>>][({<{}><[]()>})[<[()[]][()()]>{<{}<>>\n{({(((<{<[<(<({}<>)[()()]>{<[]{}><()<>>})[<({}<>)><(<>)<()()>>]>(<(([][])<()<>>)<<<><>>([])>>{(<[]{}>\n[{{[([<<(<[<({<><>}{[]()})[{<><>}]>{<(()[])><[<><>]>}][<{[{}<>][[]<>]}(([]{}))>[[([])<{}[]>]{<(){}>({}())}]]\n{[<<((<<[([[([()[]]({}()))(<{}()>{(){}})][((<>[]]{{}{}})((()<>)<<><>>)]]{[<(<>[])<[]>>([<>()]{[]\n((({({{<[(((<[<>[]]([]<>)>[<[]{}>{<><>}])<{[<>()][()<>]}{<{}<>>[[]()]}>))<[<{(<><>)<()<>>}>[<[[]<>]<[]{\n{<<<{<({([({((<><>)[[][]]){[()<>]{<><>}}}<[{[]<>}[<>[]]][[()<>]{(){}}]>)<[[[[]<>]]((<><>))}(<<()<>><<><>>><[[\n(({{[({<{<{[[<<>[]>([][])]{<<>()>{{}()>}]{[<<>[]>[{}{}]][{()()}{[]<>}]}}([({{}[]}{{}()}){(()<>){()<>}}\n(<([({{{{<[<{{<>[]}{{}}}<[{}{}]<{}{}>>><{{(){}}([]{})}>](<[([]())[()]]>[(<[]<>>[[]{}])])>[{(<[[][]]<{}\n((({[{{{([<{{<<><>><[][]>}{({}())<<>{}>}}[{([]())}[<<>()>({}[])]]>{<[<<>[]]<()<>>][[()[]][<>[]]]>[{[[]\n<(<<[[<{({{[(([][]))([<><>][{}{}])]}})}>]](<([{{[{<{[][]}[{}<>]>([{}()])}]}([{{(())}{{{}{}}<[]{}\n<([<[{{({[(({({}{})<{}()>}))[[((<><>)<{}>)[[[][]]((){})]]<<<[]()>{()[]}>>]]{<<(<[]<>>[<>{}]){({}())}>>}}{[[\n[<<[(({<({{{[{[][]}{(){}}][<()()>]}((<{}{}>>[{{}[]}])}{<[(<>[])[(){}]](<<><>>({}<>))><(({}())\n[([{<{(([[[([{{}[]}<(){}>])]<{([[]()][[]<>])([{}{}]([][]))}>]({<<([][]){()<>}>>{([()<>]([])){{{}()}{[][]}\n{<({[<[(({{({<(){}><[][]>}[{<>()}({})])<[[{}]{<><>}]<<[]{}>([]{})>>}[(({[]<>})([(){}]<()[]>))]}))]><<(\n{<<[[<[[[((<[<{}<>><<><>>]<({}[])([]{})>>{<{()<>}>{([]{})[()[]]}}>[[<({}<>)([]{})>(<{}()>[[]()])][[<()<>><[]\n{((({(<{[[[({<<>[]><{}<>>}[{[][]}[<>()]]){([<>()][[]()])({[]<>}{{}<>})}]<<{[{}<>]<{}()>}<(()){(){}}>>{\n<[[{<<([<[{{(({}()){[]{}}){{{}[]}{<>()}}}}{<{[<><>]<{}{}>}(({}()){()<>})>(<(<>{})[<>()]>{<<><>>{[][]}}\n{{([{(((({<{[({}{}){{}{}}]{(<>{})[{}{}]}}[{[()[]][{}()]}{(()[])(()())}]><({(<>[])}((())<[]>))>}<{{{{{}<>\n({(([({(<<<((({}[])((){}))((<><>)[[][]]))((<()<>><(){}>){{{}()}(()[])})><([[{}<>][()[]]])(([<>\n<<<<<{({{([(([{}{}]<{}()>))][<<{<>[]}{<>}>({()<>}{{}()})>[([<><>]{{}()})([[]{}])}]){({[([]<>)<[][]>][{<><>\n((<[<<{{<([{{[{}<>]{{}<>}}([[][]]<<>{}>)}{[[[]{}]])]{[<<{}<>>{{}{}}><({}<>)>]([(<><>)[{}()]])})(<\n<(((<[(((<([[{(){}}<<>()>]]<{<<>{}><(){}>}<{[][]}{[]{}}>>)>{<<{{<><>}{[]<>}}{{<>[]}<[]()>}>[{{{}()}{[]<>\n{[<{((<<[<<([(()()){{}()}](([]{}){<>()>))>{({((){})({}())}[[()][<><>]])<([{}[]][[]{}])(([]{}){()<>}\n(<[({[(([[{[[<{}{}><<>{}>][<<>{}>]]([{<>()}<<>{}>]{{[]{}}({}())})}([({{}()}{{}()})][[<<>[]>[<>{}]]{<<>[])}])\n{<{(((<([[[<[(<>())[()[]]]<<()[]><{}<>>>>]<{({<>()}(()<>)){<<><>>{{}[]}}}{(<()<>><<>[]>){{[]()}[[]()]}}>][(<[\n<<[[<(({{{{<{{[]()}({}<>)}[(<>{}){[]{}}]>[<{[][]}{{}{}}>]}{{(<<>()><{}{}>)[{{}[])[(){}]]}(([()[]][{}[]]){<\n(<(<<<([{((<[[{}[]]{{}}]<({}<>)<()<>>>})<(<[<>{}]<{}<>>><([]<>)([]<>)>)[{<{}<>>[()()]}[(<>[])]\n<{(([([[<<([{{<><>}[<><>}}{[{}<>]{{}<>}}]{([[]()]<()[]>)[({}<>){[][]}]})({[((){})<<>[]>][{<>()}[[]<>]\n<<<{{<{[({<<[[[]][[][]]]({[]()}{{}[]})>>{[({{}<>}{[][]})[[{}()]{[]}]]}}([[[[<>[]]<{}[]>]{[{}{\n{<{{([([<{[[{([]<>)[()<>]}][{<()()>}<{{}<>}([]{})>]]{{[{[][]}<{}[]>]([<>()]{{}{}})}{(({}{})((\n<{<((<{<{([<((()<>){()[]}){[[]<>](()[])}><(([]()])<[[]()]{{}<>}>>]{({<()><()()>}[[()<>]<<>[]>]\n[<[{[(<<[(<<<(<>[])[[]]>{<(){}>}><([<>[]]{<>{}})[{<><>}{[]()}]>>{[(<[]<>>)<[{}<>]{<>()}>]{<(()())[[][]]>[\n[<<<{[(<<[({{{<>[]}<[]()>}{<<>[]>(<>[]]}})]>>{[[<({([][]){{}()}}[{<>()}({}())])({(()[])(<>\n[<[[<{<{{{{{<([]())[<>()]><{()<>}[<><>]>}}}}}><<{(([{<[][]>{[]()}}[{[][]}{{}<>}>][(({}())({}())\n<[[{{[<{<<[<(<<>[]>)<<()()>{{}[]}>>{<{()<>}[<><>]>[{{}{}}{()}]}]{(<([]<>)({}())>{<[]{}>}){[({}())]{(\n({{[(([(<{[[{(()<>)({}())}<({}{}){{}}>](((()())<{}()>)[<{}<>><{}()>])]({{([][])({}<>)}<({}())<[]\n{[(<[<{[(([<(<[]()><{}()>)<<[][]><()>>>][<<[{}[]]<{}{}>](<<>>{<>[]})>[{(<>())[<>]}<{[]<>}((\n[{{(<{{[{<<<<(<><>)>(({}[]))><<[[]{}][<>()]>>>({[({}{}){<>{}}]<[<><>]>})>}<[<{{<{}{}>{<><>}}}>]<(\n{<{<<{[{<[[[<<{}[]>{()<>}>(<()[]>({}<>))]{<((){})[<><>]><{<>{}}{<>()}>}]({([()[]]{[]()})}([{()()}}<(<>()\n[<<([(<[<[[([(<>{}){()<>}][<{}()><{}()>])]((([()<>]{()<>})[[<><>]]))][{([{{}{}}]<{<>}[{}()]>)[[{\n<[[{([({<<<(<([]<>)<<><>>>[{[]()}<(){}>])>>>({(([[<>{}]([]<>)]{[(){}](()())})([{<>()}([]<>)]))<[{[{}()]{<>[]}\n<(([{<{[[<({[({}()){{}[]}]{<{}[]>[{}<>]}}[[[{}<>](<><>)][<()()>({}<>)]])<{{[{}<>]{<>[]}}}([[{}[]]<<>{}>])>>\n{(<[([[[{[<[[<[]()>[{}{}]][<()[]>{[]()}]]>[[[(<>[]){<>[]}][{<>{}}<()[]>]]]](<{{([]())[()()]]<[{}[]][[](\n[([[[<<<{({[[{[][]}<()[]>]][{{[]()}([]<>)}({()<>})]))[<{<[<>{}]{[]{}}>({<>{}}[()()])}><<([<>[]]{{}[]})[<[][]\n{(({({<{([[[[<[]{}>(<>{})]{({}())(()<>)}]]<{{<[]()>(()())}{([][])}}<{[[][]]<()<>>}{(<>{})({}\n[{{<[{(<{({<[{[]<>}[[]()]][[{}<>]{{}()}]>(<[()()]>([{}[]]{(){}}))}{{{({}<>)<<><>>}({[]<>)<{}>)}})([<({\n(<[{{{{<(<[<{{()()}{[]{}}}<([]{}){<>()}>>[({{}<>}{{}[]})]][[({{}()}(<>[])){<[][]>[<>()]}]]>]>{[(\n[{<(<<{[<(<[<({}[])({}{})>]{<{{}()}<<><>>>{<{}{}>(()())}}>)>][({<[[<(){}>(<>())](({}{}){{}()}\n{([[{<{<{(([<([]<>)[<>]>{(<>[]){<>[]}}][<[(){}]{{}()}>((<>[]))])<({[()<>](()[])}){<[()<>]{<>{}}>{([])<()\n<[{[{(<<({[((<[]{}>{[]{}})([()[]]<(){}>))<{<<>[]>[{}]}{<{}<>>{()}}>]{{{(<>())}(({}<>))}<<{()<>}({}())>([{}<\n<(<[{{<{{[([{{(){}}<<>{}>}(<(){}>)][[{{}<>}(()<>)]]){([<<>{}>[()()]][{[]()}<{}()>])}]<{([{[]}([][]\n<[[{<{[<{([<[<[]<>][{}]]<({}{})([])>>]({{(<><>)[[]<>]}<<{}[]>[[]<>]>}))}([<(({()()}{[]<>}))<{<()[]><[]()>}(((\n({{{<{([{<[{{[{}<>](<><>)}[[<>()]({}[])]}[[<(){}>({}<>)]<(()())({}())>])>[<<<[[][]][(){}]><([\n((<{[<[[(((<[<<>()>([]())]<(()<>){()[]}>>[<{(){}}{{}}>[[(){}}<[]{}>]])<[[[[][]][{}()]]{[{}()][\n(({[[<{({[[[[[<><>]<[]{}>]<(<>{}){[]()}>][(([]<>){()[]})([<>{}]<()<>>)]]]}[[<{<(<><>)<{}[]>>}<<{<>\n<{({[{(([[{(<(()[])<(){}>>{<{}{}>{<><>}})[<(()())<[]{}>>]}[{{{[]}[()[]]}[<()[]><<>{}>]}{<[<><>]{[]\n[<[<<{<{{<[(<{(){}}[<>()]><({}<>)<<>{}>))<<<()<>>({}<>)><[<><>][()]>>](({({}()){()()}}<[[]<>]<<>{}>>)<[[[]\n{<{(<(<[<([{<{{}[]}(()[])>[({}())<[][]>]}<<{()()}[<><>]>>]<{{[[]{}]{<><>}}(({}{})[[]])}({(<>[])<<>{}>\n{{{[[((<[(<<[[{}()]<[]<>>]{<()[]>}>[<<()()>>([<><>]((){}))]>{<<[{}{}][{}()]>[(()())[<>[]]]>{{\n<({<{[{<[<({{[<><>]{<>[]}}<{[]<>}<<><>>]}{{[{}{}]{{}{}}}{<[]<>>{[][]}}})(<({()<>}<{}[]>){([]{})\n{<(<<[<{([{[({{}<>}[()()]){(()<>)[{}<>]}]}])}>]{{(<[<<((()())<<>()>)>{([[]{}]((){}))<({}<>)({}<\n[<(<[[{{[([[<<[]{}>{[]<>}>{(<>[])[{}{}]>]([[[]<>](()())])])([[<{<>{}}(<><>)><({}<>)<()>>][({[]<>}\n[<{({{[<([{<{[()[]][(){}]}>[([<>[]]{{}})]}<<((()<>}(()()))<[(){}]>>((({}())[{}<>]){({}<>)<<>[]>})>]{<<{<{}[]\n[[<{<{({(<{<{({}())[{}]}([()[]]{{}()})>}((([{}{}]{()<>})<[<>()]{<>[]}>)[([()<>]<<><>>)[[()[]]{[]}]]]>){([[[\n{<(([<<[<{(((<()<>>{{}()})({[]{}}[[]{}]))(([{}[]]{[]<>})<<[]>(<>{})>))}[{{<(<><>]<<>>>}}({[({}[])\n[[{{[([<[({[{(<>()}[<>[]]}{{<>{}}<[]{}>}]{{{()[]}([]{})}([()<>]{()<>})}}[<{(<>)<<><>>}{{<>[]}<<>[]>}>({<\n{{[{{{<([<{<{<{}<>>}{[(){}]{{}()}}><{{[]()}<{}>}>)[[{[{}{}]{()<>}}<(<>{}){[]{}}>][[(()<>)(<>())]({[]<>}[()[]\n((<({<{[(<[{[<<>><{}()>][[{}[]>]}{({()<>}[{}[]])[(()())]}][<<{<>{}}<<><>>>[{[][]}{<>()}]>]>[<({({}()){{\n[([<<({({[<{(((){}){<>{}})(({}<>))}{<[[]()][{}{}]>{([][])<[][]>}}>]<<(<{<>()}[()[]]>[<(){}>[<>()>])<<[{}(' compute(real_data)
n = int(input()) count = 0 a_prev, b_prev = -1, 0 for _ in range(n): a, b = map(int, input().split()) start = max(a_prev, b_prev) end = min(a, b) if end >= start: count += end - start + 1 if a_prev == b_prev: count -= 1 a_prev, b_prev = a, b print(count)
n = int(input()) count = 0 (a_prev, b_prev) = (-1, 0) for _ in range(n): (a, b) = map(int, input().split()) start = max(a_prev, b_prev) end = min(a, b) if end >= start: count += end - start + 1 if a_prev == b_prev: count -= 1 (a_prev, b_prev) = (a, b) print(count)
# Copyright 2021 by Saithalavi M, saithalavi@gmail.com # All rights reserved. # This file is part of the Nessaid readline Framework, nessaid_readline python package # and is released under the "MIT License Agreement". Please see the LICENSE # file included as part of this package. # # common CR = "\x0d" LF = "\x0a" BACKSPACE = "\x7f" SPACE = "\x20" TAB = "\x09" ESC = "\x1b" INSERT = "\x1b\x5b\x32\x7e" DELETE = "\x1b\x5b\x33\x7e" PAGE_UP = "\x1b\x5b\x35\x7e" PAGE_DOWN = "\x1b\x5b\x36\x7e" HOME = "\x1b\x5b\x48" END = "\x1b\x5b\x46" # cursors UP = "\x1b\x5b\x41" DOWN = "\x1b\x5b\x42" LEFT = "\x1b\x5b\x44" RIGHT = "\x1b\x5b\x43" # CTRL CTRL_A = '\x01' CTRL_B = '\x02' CTRL_C = '\x03' CTRL_D = '\x04' CTRL_E = '\x05' CTRL_F = '\x06' CTRL_G = '\x07' # CTRL_H is '\x08', '\b', BACKSPACE # CTRL_I is '\x09', '\t', TAB # CTRL_J is '\x0a', '\n', LF CTRL_K = '\x0b' CTRL_L = '\x0c' # CTRL_M is '\x0d', '\r', CR CTRL_N = '\x0e' CTRL_O = '\x0f' CTRL_P = '\x10' CTRL_Q = '\x11' CTRL_R = '\x12' CTRL_S = '\x13' CTRL_T = '\x14' CTRL_U = '\x15' CTRL_V = '\x16' CTRL_W = '\x17' CTRL_X = '\x18' CTRL_Y = '\x19' CTRL_Z = '\x1a' # ALT ALT_A = "\x1b" + 'a' ALT_B = "\x1b" + 'b' ALT_C = "\x1b" + 'c' ALT_D = "\x1b" + 'd' ALT_E = "\x1b" + 'e' ALT_F = "\x1b" + 'f' ALT_G = "\x1b" + 'g' ALT_H = "\x1b" + 'h' ALT_I = "\x1b" + 'i' ALT_J = "\x1b" + 'j' ALT_K = "\x1b" + 'k' ALT_L = "\x1b" + 'l' ALT_M = "\x1b" + 'm' ALT_N = "\x1b" + 'n' ALT_O = "\x1b" + 'o' ALT_P = "\x1b" + 'p' ALT_Q = "\x1b" + 'q' ALT_R = "\x1b" + 'r' ALT_S = "\x1b" + 's' ALT_T = "\x1b" + 't' ALT_U = "\x1b" + 'u' ALT_V = "\x1b" + 'v' ALT_W = "\x1b" + 'w' ALT_X = "\x1b" + 'x' ALT_Y = "\x1b" + 'y' ALT_Z = "\x1b" + 'z' # CTRL + ALT CTRL_ALT_A = "\x1b" + CTRL_A CTRL_ALT_B = "\x1b" + CTRL_B CTRL_ALT_C = "\x1b" + CTRL_C CTRL_ALT_D = "\x1b" + CTRL_D CTRL_ALT_E = "\x1b" + CTRL_E CTRL_ALT_F = "\x1b" + CTRL_F CTRL_ALT_G = "\x1b" + CTRL_G CTRL_ALT_H = "\x1b" + '\x08' CTRL_ALT_I = "\x1b" + '\x09' CTRL_ALT_J = "\x1b" + '\x0a' CTRL_ALT_K = "\x1b" + CTRL_K CTRL_ALT_L = "\x1b" + CTRL_L CTRL_ALT_M = "\x1b" + '\x0d' CTRL_ALT_N = "\x1b" + CTRL_N CTRL_ALT_O = "\x1b" + CTRL_O CTRL_ALT_P = "\x1b" + CTRL_P CTRL_ALT_Q = "\x1b" + CTRL_Q CTRL_ALT_R = "\x1b" + CTRL_R CTRL_ALT_S = "\x1b" + CTRL_S CTRL_ALT_T = "\x1b" + CTRL_T CTRL_ALT_U = "\x1b" + CTRL_U CTRL_ALT_V = "\x1b" + CTRL_V CTRL_ALT_W = "\x1b" + CTRL_W CTRL_ALT_X = "\x1b" + CTRL_X CTRL_ALT_Y = "\x1b" + CTRL_Y CTRL_ALT_Z = "\x1b" + CTRL_Z CTRL_ALT_DELETE = "\x1b\x5b\x33\x5e" KEY_NAME_MAP = { "cr": CR, "lf": LF, "tab": TAB, "page-up": PAGE_UP, "page-down": PAGE_DOWN, "insert": INSERT, "delete": DELETE, "backspace": BACKSPACE, "home": HOME, "end": END, "left": LEFT, "right": RIGHT, "up": UP, "down": DOWN, "esc": ESC, "escape": ESC, "ctrl-a": CTRL_A, "ctrl-b": CTRL_B, "ctrl-c": CTRL_C, "ctrl-d": CTRL_D, "ctrl-e": CTRL_E, "ctrl-f": CTRL_F, "ctrl-g": CTRL_G, "ctrl-k": CTRL_K, "ctrl-l": CTRL_L, "ctrl-n": CTRL_N, "ctrl-o": CTRL_O, "ctrl-p": CTRL_P, "ctrl-q": CTRL_Q, "ctrl-r": CTRL_R, "ctrl-s": CTRL_S, "ctrl-t": CTRL_T, "ctrl-u": CTRL_U, "ctrl-v": CTRL_V, "ctrl-w": CTRL_W, "ctrl-x": CTRL_X, "ctrl-y": CTRL_Y, "ctrl-z": CTRL_Z, "alt-a": ALT_A, "alt-b": ALT_B, "alt-c": ALT_C, "alt-d": ALT_D, "alt-e": ALT_E, "alt-f": ALT_F, "alt-g": ALT_G, "alt-h": ALT_H, "alt-i": ALT_I, "alt-j": ALT_J, "alt-k": ALT_K, "alt-l": ALT_L, "alt-m": ALT_M, "alt-n": ALT_N, "alt-o": ALT_O, "alt-p": ALT_P, "alt-q": ALT_Q, "alt-r": ALT_R, "alt-s": ALT_S, "alt-t": ALT_T, "alt-u": ALT_U, "alt-v": ALT_V, "alt-w": ALT_W, "alt-x": ALT_X, "alt-y": ALT_Y, "alt-z": ALT_Z, "ctrl-alt-a": CTRL_ALT_A, "ctrl-alt-b": CTRL_ALT_B, "ctrl-alt-c": CTRL_ALT_C, "ctrl-alt-d": CTRL_ALT_D, "ctrl-alt-e": CTRL_ALT_E, "ctrl-alt-f": CTRL_ALT_F, "ctrl-alt-g": CTRL_ALT_G, "ctrl-alt-h": CTRL_ALT_H, "ctrl-alt-i": CTRL_ALT_I, "ctrl-alt-j": CTRL_ALT_J, "ctrl-alt-k": CTRL_ALT_K, "ctrl-alt-l": CTRL_ALT_L, "ctrl-alt-m": CTRL_ALT_M, "ctrl-alt-n": CTRL_ALT_N, "ctrl-alt-o": CTRL_ALT_O, "ctrl-alt-p": CTRL_ALT_P, "ctrl-alt-q": CTRL_ALT_Q, "ctrl-alt-r": CTRL_ALT_R, "ctrl-alt-s": CTRL_ALT_S, "ctrl-alt-t": CTRL_ALT_T, "ctrl-alt-u": CTRL_ALT_U, "ctrl-alt-v": CTRL_ALT_V, "ctrl-alt-w": CTRL_ALT_W, "ctrl-alt-x": CTRL_ALT_X, "ctrl-alt-y": CTRL_ALT_Y, "ctrl-alt-z": CTRL_ALT_Z, "ctrl-alt-delete": CTRL_ALT_DELETE, }
cr = '\r' lf = '\n' backspace = '\x7f' space = ' ' tab = '\t' esc = '\x1b' insert = '\x1b[2~' delete = '\x1b[3~' page_up = '\x1b[5~' page_down = '\x1b[6~' home = '\x1b[H' end = '\x1b[F' up = '\x1b[A' down = '\x1b[B' left = '\x1b[D' right = '\x1b[C' ctrl_a = '\x01' ctrl_b = '\x02' ctrl_c = '\x03' ctrl_d = '\x04' ctrl_e = '\x05' ctrl_f = '\x06' ctrl_g = '\x07' ctrl_k = '\x0b' ctrl_l = '\x0c' ctrl_n = '\x0e' ctrl_o = '\x0f' ctrl_p = '\x10' ctrl_q = '\x11' ctrl_r = '\x12' ctrl_s = '\x13' ctrl_t = '\x14' ctrl_u = '\x15' ctrl_v = '\x16' ctrl_w = '\x17' ctrl_x = '\x18' ctrl_y = '\x19' ctrl_z = '\x1a' alt_a = '\x1b' + 'a' alt_b = '\x1b' + 'b' alt_c = '\x1b' + 'c' alt_d = '\x1b' + 'd' alt_e = '\x1b' + 'e' alt_f = '\x1b' + 'f' alt_g = '\x1b' + 'g' alt_h = '\x1b' + 'h' alt_i = '\x1b' + 'i' alt_j = '\x1b' + 'j' alt_k = '\x1b' + 'k' alt_l = '\x1b' + 'l' alt_m = '\x1b' + 'm' alt_n = '\x1b' + 'n' alt_o = '\x1b' + 'o' alt_p = '\x1b' + 'p' alt_q = '\x1b' + 'q' alt_r = '\x1b' + 'r' alt_s = '\x1b' + 's' alt_t = '\x1b' + 't' alt_u = '\x1b' + 'u' alt_v = '\x1b' + 'v' alt_w = '\x1b' + 'w' alt_x = '\x1b' + 'x' alt_y = '\x1b' + 'y' alt_z = '\x1b' + 'z' ctrl_alt_a = '\x1b' + CTRL_A ctrl_alt_b = '\x1b' + CTRL_B ctrl_alt_c = '\x1b' + CTRL_C ctrl_alt_d = '\x1b' + CTRL_D ctrl_alt_e = '\x1b' + CTRL_E ctrl_alt_f = '\x1b' + CTRL_F ctrl_alt_g = '\x1b' + CTRL_G ctrl_alt_h = '\x1b' + '\x08' ctrl_alt_i = '\x1b' + '\t' ctrl_alt_j = '\x1b' + '\n' ctrl_alt_k = '\x1b' + CTRL_K ctrl_alt_l = '\x1b' + CTRL_L ctrl_alt_m = '\x1b' + '\r' ctrl_alt_n = '\x1b' + CTRL_N ctrl_alt_o = '\x1b' + CTRL_O ctrl_alt_p = '\x1b' + CTRL_P ctrl_alt_q = '\x1b' + CTRL_Q ctrl_alt_r = '\x1b' + CTRL_R ctrl_alt_s = '\x1b' + CTRL_S ctrl_alt_t = '\x1b' + CTRL_T ctrl_alt_u = '\x1b' + CTRL_U ctrl_alt_v = '\x1b' + CTRL_V ctrl_alt_w = '\x1b' + CTRL_W ctrl_alt_x = '\x1b' + CTRL_X ctrl_alt_y = '\x1b' + CTRL_Y ctrl_alt_z = '\x1b' + CTRL_Z ctrl_alt_delete = '\x1b[3^' key_name_map = {'cr': CR, 'lf': LF, 'tab': TAB, 'page-up': PAGE_UP, 'page-down': PAGE_DOWN, 'insert': INSERT, 'delete': DELETE, 'backspace': BACKSPACE, 'home': HOME, 'end': END, 'left': LEFT, 'right': RIGHT, 'up': UP, 'down': DOWN, 'esc': ESC, 'escape': ESC, 'ctrl-a': CTRL_A, 'ctrl-b': CTRL_B, 'ctrl-c': CTRL_C, 'ctrl-d': CTRL_D, 'ctrl-e': CTRL_E, 'ctrl-f': CTRL_F, 'ctrl-g': CTRL_G, 'ctrl-k': CTRL_K, 'ctrl-l': CTRL_L, 'ctrl-n': CTRL_N, 'ctrl-o': CTRL_O, 'ctrl-p': CTRL_P, 'ctrl-q': CTRL_Q, 'ctrl-r': CTRL_R, 'ctrl-s': CTRL_S, 'ctrl-t': CTRL_T, 'ctrl-u': CTRL_U, 'ctrl-v': CTRL_V, 'ctrl-w': CTRL_W, 'ctrl-x': CTRL_X, 'ctrl-y': CTRL_Y, 'ctrl-z': CTRL_Z, 'alt-a': ALT_A, 'alt-b': ALT_B, 'alt-c': ALT_C, 'alt-d': ALT_D, 'alt-e': ALT_E, 'alt-f': ALT_F, 'alt-g': ALT_G, 'alt-h': ALT_H, 'alt-i': ALT_I, 'alt-j': ALT_J, 'alt-k': ALT_K, 'alt-l': ALT_L, 'alt-m': ALT_M, 'alt-n': ALT_N, 'alt-o': ALT_O, 'alt-p': ALT_P, 'alt-q': ALT_Q, 'alt-r': ALT_R, 'alt-s': ALT_S, 'alt-t': ALT_T, 'alt-u': ALT_U, 'alt-v': ALT_V, 'alt-w': ALT_W, 'alt-x': ALT_X, 'alt-y': ALT_Y, 'alt-z': ALT_Z, 'ctrl-alt-a': CTRL_ALT_A, 'ctrl-alt-b': CTRL_ALT_B, 'ctrl-alt-c': CTRL_ALT_C, 'ctrl-alt-d': CTRL_ALT_D, 'ctrl-alt-e': CTRL_ALT_E, 'ctrl-alt-f': CTRL_ALT_F, 'ctrl-alt-g': CTRL_ALT_G, 'ctrl-alt-h': CTRL_ALT_H, 'ctrl-alt-i': CTRL_ALT_I, 'ctrl-alt-j': CTRL_ALT_J, 'ctrl-alt-k': CTRL_ALT_K, 'ctrl-alt-l': CTRL_ALT_L, 'ctrl-alt-m': CTRL_ALT_M, 'ctrl-alt-n': CTRL_ALT_N, 'ctrl-alt-o': CTRL_ALT_O, 'ctrl-alt-p': CTRL_ALT_P, 'ctrl-alt-q': CTRL_ALT_Q, 'ctrl-alt-r': CTRL_ALT_R, 'ctrl-alt-s': CTRL_ALT_S, 'ctrl-alt-t': CTRL_ALT_T, 'ctrl-alt-u': CTRL_ALT_U, 'ctrl-alt-v': CTRL_ALT_V, 'ctrl-alt-w': CTRL_ALT_W, 'ctrl-alt-x': CTRL_ALT_X, 'ctrl-alt-y': CTRL_ALT_Y, 'ctrl-alt-z': CTRL_ALT_Z, 'ctrl-alt-delete': CTRL_ALT_DELETE}
""" Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root. For example: Given the below binary tree, 1 / \ 2 3 Return 6. """ # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return an integer def maxPathSum(self, root): self.current_max = float("-inf") self.traverse_tree(root) return self.current_max def traverse_tree(self, root): if root == None: return 0 # calc left max left_max = max(0, self.traverse_tree(root.left)) # calc right max right_max = max(0, self.traverse_tree(root.right)) # update current_max root_max_sum = root.val + left_max + right_max self.current_max = max(self.current_max, root_max_sum) #return the max path sum from this root return max(left_max, right_max) + root.val
""" Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root. For example: Given the below binary tree, 1 / 2 3 Return 6. """ class Solution: def max_path_sum(self, root): self.current_max = float('-inf') self.traverse_tree(root) return self.current_max def traverse_tree(self, root): if root == None: return 0 left_max = max(0, self.traverse_tree(root.left)) right_max = max(0, self.traverse_tree(root.right)) root_max_sum = root.val + left_max + right_max self.current_max = max(self.current_max, root_max_sum) return max(left_max, right_max) + root.val
"""Ext macros.""" load("@b//:lib2.bzl", "bar") foo = bar
"""Ext macros.""" load('@b//:lib2.bzl', 'bar') foo = bar
# The contents of this file is free and unencumbered software released into the # public domain. For more information, please refer to <http://unlicense.org/> manga_query = ''' query ($id: Int,$search: String) { Page (perPage: 10) { media (id: $id, type: MANGA,search: $search) { id title { romaji english native } description (asHtml: false) startDate{ year } type format status siteUrl averageScore genres bannerImage } } } '''
manga_query = '\nquery ($id: Int,$search: String) {\n Page (perPage: 10) {\n media (id: $id, type: MANGA,search: $search) {\n id\n title {\n romaji\n english\n native\n }\n description (asHtml: false)\n startDate{\n year\n }\n type\n format\n status\n siteUrl\n averageScore\n genres\n bannerImage\n }\n }\n}\n'
# this code will accept an input string and check if it is a plandrome # it will then return true if it is a plaindrome and false if it is not def reverse(str1): if(len(str1) == 0): return str1 else: return reverse(str1[1:]) + str1[0] string = input("Please enter your own String : ") # check for strings str1 = reverse(string) print("String in reverse Order : ", str1) if(string == str1): print("This is a Palindrome String") else: print("This is Not a Palindrome String")
def reverse(str1): if len(str1) == 0: return str1 else: return reverse(str1[1:]) + str1[0] string = input('Please enter your own String : ') str1 = reverse(string) print('String in reverse Order : ', str1) if string == str1: print('This is a Palindrome String') else: print('This is Not a Palindrome String')
ticket_dict1 = { "pagination": { "object_count": 2, "continuation": None, "page_count": 1, "page_size": 50, "has_more_items": False, "page_number": 1 }, "ticket_classes": [ { "actual_cost": None, "actual_fee": { "display": "$7.72", "currency": "USD", "value": 772, "major_value": "7.72" }, "cost": { "display": "$100.00", "currency": "USD", "value": 10000, "major_value": "100.00" }, "fee": { "display": "$7.72", "currency": "USD", "value": 772, "major_value": "7.72" }, "tax": { "display": "$0.00", "currency": "USD", "value": 0, "major_value": "0.00" }, "resource_uri": "https://www.eventbriteapi.com/v3/events/158717222485/ticket_classes/567567567/", "display_name": "Regular Price", "name": "Regular Price", "description": None, "sorting": 1, "donation": False, "free": False, "minimum_quantity": 1, "maximum_quantity": 10, "maximum_quantity_per_order": 10, "on_sale_status": "AVAILABLE", "has_pdf_ticket": True, "order_confirmation_message": None, "delivery_methods": [ "electronic" ], "category": "admission", "sales_channels": [ "online", "atd" ], "secondary_assignment_enabled": False, "event_id": "12122222111111", "image_id": None, "id": "278648077", "capacity": 300, "quantity_total": 300, "quantity_sold": 0, "sales_start": "2021-06-02T04:00:00Z", "sales_end": "2021-09-03T19:00:00Z", "sales_end_relative": None, "hidden": False, "hidden_currently": False, "include_fee": False, "split_fee": False, "hide_description": True, "hide_sale_dates": False, "auto_hide": False, "payment_constraints": [] }, { "actual_cost": None, "actual_fee": None, "cost": None, "fee": None, "tax": None, "resource_uri": "https://www.eventbriteapi.com/v3/events/158717222485/ticket_classes/678678678/", "display_name": "Super Special Free Admission", "name": "Super Special Free Admission", "description": None, "sorting": 2, "donation": False, "free": True, "minimum_quantity": 1, "maximum_quantity": 1, "maximum_quantity_per_order": 1, "on_sale_status": "AVAILABLE", "has_pdf_ticket": True, "order_confirmation_message": None, "delivery_methods": [ "electronic" ], "category": "admission", "sales_channels": [ "online", "atd" ], "secondary_assignment_enabled": False, "event_id": "12122222111111", "image_id": None, "id": "278648079", "capacity": 50, "quantity_total": 50, "quantity_sold": 0, "sales_start": "2021-06-02T04:00:00Z", "sales_end": "2021-09-03T19:00:00Z", "sales_end_relative": None, "hidden": True, "hidden_currently": True, "include_fee": False, "split_fee": False, "hide_description": True, "hide_sale_dates": False, "auto_hide": False, "payment_constraints": [] } ] } ticket_dict2 = { "pagination": { "object_count": 2, "continuation": None, "page_count": 1, "page_size": 50, "has_more_items": False, "page_number": 1 }, "ticket_classes": [ { "actual_cost": None, "actual_fee": { "display": "$7.72", "currency": "USD", "value": 772, "major_value": "7.72" }, "cost": { "display": "$100.00", "currency": "USD", "value": 10000, "major_value": "100.00" }, "fee": { "display": "$7.72", "currency": "USD", "value": 772, "major_value": "7.72" }, "tax": { "display": "$0.00", "currency": "USD", "value": 0, "major_value": "0.00" }, "resource_uri": "https://www.eventbriteapi.com/v3/events/158717222485/ticket_classes/3255985/", "display_name": "Regular Price", "name": "Regular Price", "description": None, "sorting": 1, "donation": False, "free": False, "minimum_quantity": 1, "maximum_quantity": 10, "maximum_quantity_per_order": 10, "on_sale_status": "AVAILABLE", "has_pdf_ticket": True, "order_confirmation_message": None, "delivery_methods": [ "electronic" ], "category": "admission", "sales_channels": [ "online", "atd" ], "secondary_assignment_enabled": False, "event_id": "2222333332323232", "image_id": None, "id": "278648077", "capacity": 300, "quantity_total": 300, "quantity_sold": 0, "sales_start": "2021-06-02T04:00:00Z", "sales_end": "2021-09-03T19:00:00Z", "sales_end_relative": None, "hidden": False, "hidden_currently": False, "include_fee": False, "split_fee": False, "hide_description": True, "hide_sale_dates": False, "auto_hide": False, "payment_constraints": [] }, { "actual_cost": None, "actual_fee": None, "cost": None, "fee": None, "tax": None, "resource_uri": "https://www.eventbriteapi.com/v3/events/158717222485/ticket_classes/890890890/", "display_name": "Super Special Free Admission", "name": "Super Special Free Admission", "description": None, "sorting": 2, "donation": False, "free": True, "minimum_quantity": 1, "maximum_quantity": 1, "maximum_quantity_per_order": 1, "on_sale_status": "AVAILABLE", "has_pdf_ticket": True, "order_confirmation_message": None, "delivery_methods": [ "electronic" ], "category": "admission", "sales_channels": [ "online", "atd" ], "secondary_assignment_enabled": False, "event_id": "2222333332323232", "image_id": None, "id": "278648079", "capacity": 50, "quantity_total": 50, "quantity_sold": 0, "sales_start": "2021-06-02T04:00:00Z", "sales_end": "2021-09-03T19:00:00Z", "sales_end_relative": None, "hidden": True, "hidden_currently": True, "include_fee": False, "split_fee": False, "hide_description": True, "hide_sale_dates": False, "auto_hide": False, "payment_constraints": [] } ] } ticket_dict3 = { "pagination": { "object_count": 2, "continuation": None, "page_count": 1, "page_size": 50, "has_more_items": False, "page_number": 1 }, "ticket_classes": [ { "actual_cost": None, "actual_fee": { "display": "$7.72", "currency": "USD", "value": 772, "major_value": "7.72" }, "cost": { "display": "$100.00", "currency": "USD", "value": 10000, "major_value": "100.00" }, "fee": { "display": "$7.72", "currency": "USD", "value": 772, "major_value": "7.72" }, "tax": { "display": "$0.00", "currency": "USD", "value": 0, "major_value": "0.00" }, "resource_uri": "https://www.eventbriteapi.com/v3/events/158717222485/ticket_classes/098098098/", "display_name": "Regular Price", "name": "Regular Price", "description": None, "sorting": 1, "donation": False, "free": False, "minimum_quantity": 1, "maximum_quantity": 10, "maximum_quantity_per_order": 10, "on_sale_status": "AVAILABLE", "has_pdf_ticket": True, "order_confirmation_message": None, "delivery_methods": [ "electronic" ], "category": "admission", "sales_channels": [ "online", "atd" ], "secondary_assignment_enabled": False, "event_id": "44454545454545454", "image_id": None, "id": "278648077", "capacity": 300, "quantity_total": 300, "quantity_sold": 0, "sales_start": "2021-06-02T04:00:00Z", "sales_end": "2021-09-03T19:00:00Z", "sales_end_relative": None, "hidden": False, "hidden_currently": False, "include_fee": False, "split_fee": False, "hide_description": True, "hide_sale_dates": False, "auto_hide": False, "payment_constraints": [] }, { "actual_cost": None, "actual_fee": None, "cost": None, "fee": None, "tax": None, "resource_uri": "https://www.eventbriteapi.com/v3/events/158717222485/ticket_classes/987987987/", "display_name": "Super Special Free Admission", "name": "Super Special Free Admission", "description": None, "sorting": 2, "donation": False, "free": True, "minimum_quantity": 1, "maximum_quantity": 1, "maximum_quantity_per_order": 1, "on_sale_status": "AVAILABLE", "has_pdf_ticket": True, "order_confirmation_message": None, "delivery_methods": [ "electronic" ], "category": "admission", "sales_channels": [ "online", "atd" ], "secondary_assignment_enabled": False, "event_id": "44454545454545454", "image_id": None, "id": "278648079", "capacity": 50, "quantity_total": 50, "quantity_sold": 0, "sales_start": "2021-06-02T04:00:00Z", "sales_end": "2021-09-03T19:00:00Z", "sales_end_relative": None, "hidden": True, "hidden_currently": True, "include_fee": False, "split_fee": False, "hide_description": True, "hide_sale_dates": False, "auto_hide": False, "payment_constraints": [] } ] }
ticket_dict1 = {'pagination': {'object_count': 2, 'continuation': None, 'page_count': 1, 'page_size': 50, 'has_more_items': False, 'page_number': 1}, 'ticket_classes': [{'actual_cost': None, 'actual_fee': {'display': '$7.72', 'currency': 'USD', 'value': 772, 'major_value': '7.72'}, 'cost': {'display': '$100.00', 'currency': 'USD', 'value': 10000, 'major_value': '100.00'}, 'fee': {'display': '$7.72', 'currency': 'USD', 'value': 772, 'major_value': '7.72'}, 'tax': {'display': '$0.00', 'currency': 'USD', 'value': 0, 'major_value': '0.00'}, 'resource_uri': 'https://www.eventbriteapi.com/v3/events/158717222485/ticket_classes/567567567/', 'display_name': 'Regular Price', 'name': 'Regular Price', 'description': None, 'sorting': 1, 'donation': False, 'free': False, 'minimum_quantity': 1, 'maximum_quantity': 10, 'maximum_quantity_per_order': 10, 'on_sale_status': 'AVAILABLE', 'has_pdf_ticket': True, 'order_confirmation_message': None, 'delivery_methods': ['electronic'], 'category': 'admission', 'sales_channels': ['online', 'atd'], 'secondary_assignment_enabled': False, 'event_id': '12122222111111', 'image_id': None, 'id': '278648077', 'capacity': 300, 'quantity_total': 300, 'quantity_sold': 0, 'sales_start': '2021-06-02T04:00:00Z', 'sales_end': '2021-09-03T19:00:00Z', 'sales_end_relative': None, 'hidden': False, 'hidden_currently': False, 'include_fee': False, 'split_fee': False, 'hide_description': True, 'hide_sale_dates': False, 'auto_hide': False, 'payment_constraints': []}, {'actual_cost': None, 'actual_fee': None, 'cost': None, 'fee': None, 'tax': None, 'resource_uri': 'https://www.eventbriteapi.com/v3/events/158717222485/ticket_classes/678678678/', 'display_name': 'Super Special Free Admission', 'name': 'Super Special Free Admission', 'description': None, 'sorting': 2, 'donation': False, 'free': True, 'minimum_quantity': 1, 'maximum_quantity': 1, 'maximum_quantity_per_order': 1, 'on_sale_status': 'AVAILABLE', 'has_pdf_ticket': True, 'order_confirmation_message': None, 'delivery_methods': ['electronic'], 'category': 'admission', 'sales_channels': ['online', 'atd'], 'secondary_assignment_enabled': False, 'event_id': '12122222111111', 'image_id': None, 'id': '278648079', 'capacity': 50, 'quantity_total': 50, 'quantity_sold': 0, 'sales_start': '2021-06-02T04:00:00Z', 'sales_end': '2021-09-03T19:00:00Z', 'sales_end_relative': None, 'hidden': True, 'hidden_currently': True, 'include_fee': False, 'split_fee': False, 'hide_description': True, 'hide_sale_dates': False, 'auto_hide': False, 'payment_constraints': []}]} ticket_dict2 = {'pagination': {'object_count': 2, 'continuation': None, 'page_count': 1, 'page_size': 50, 'has_more_items': False, 'page_number': 1}, 'ticket_classes': [{'actual_cost': None, 'actual_fee': {'display': '$7.72', 'currency': 'USD', 'value': 772, 'major_value': '7.72'}, 'cost': {'display': '$100.00', 'currency': 'USD', 'value': 10000, 'major_value': '100.00'}, 'fee': {'display': '$7.72', 'currency': 'USD', 'value': 772, 'major_value': '7.72'}, 'tax': {'display': '$0.00', 'currency': 'USD', 'value': 0, 'major_value': '0.00'}, 'resource_uri': 'https://www.eventbriteapi.com/v3/events/158717222485/ticket_classes/3255985/', 'display_name': 'Regular Price', 'name': 'Regular Price', 'description': None, 'sorting': 1, 'donation': False, 'free': False, 'minimum_quantity': 1, 'maximum_quantity': 10, 'maximum_quantity_per_order': 10, 'on_sale_status': 'AVAILABLE', 'has_pdf_ticket': True, 'order_confirmation_message': None, 'delivery_methods': ['electronic'], 'category': 'admission', 'sales_channels': ['online', 'atd'], 'secondary_assignment_enabled': False, 'event_id': '2222333332323232', 'image_id': None, 'id': '278648077', 'capacity': 300, 'quantity_total': 300, 'quantity_sold': 0, 'sales_start': '2021-06-02T04:00:00Z', 'sales_end': '2021-09-03T19:00:00Z', 'sales_end_relative': None, 'hidden': False, 'hidden_currently': False, 'include_fee': False, 'split_fee': False, 'hide_description': True, 'hide_sale_dates': False, 'auto_hide': False, 'payment_constraints': []}, {'actual_cost': None, 'actual_fee': None, 'cost': None, 'fee': None, 'tax': None, 'resource_uri': 'https://www.eventbriteapi.com/v3/events/158717222485/ticket_classes/890890890/', 'display_name': 'Super Special Free Admission', 'name': 'Super Special Free Admission', 'description': None, 'sorting': 2, 'donation': False, 'free': True, 'minimum_quantity': 1, 'maximum_quantity': 1, 'maximum_quantity_per_order': 1, 'on_sale_status': 'AVAILABLE', 'has_pdf_ticket': True, 'order_confirmation_message': None, 'delivery_methods': ['electronic'], 'category': 'admission', 'sales_channels': ['online', 'atd'], 'secondary_assignment_enabled': False, 'event_id': '2222333332323232', 'image_id': None, 'id': '278648079', 'capacity': 50, 'quantity_total': 50, 'quantity_sold': 0, 'sales_start': '2021-06-02T04:00:00Z', 'sales_end': '2021-09-03T19:00:00Z', 'sales_end_relative': None, 'hidden': True, 'hidden_currently': True, 'include_fee': False, 'split_fee': False, 'hide_description': True, 'hide_sale_dates': False, 'auto_hide': False, 'payment_constraints': []}]} ticket_dict3 = {'pagination': {'object_count': 2, 'continuation': None, 'page_count': 1, 'page_size': 50, 'has_more_items': False, 'page_number': 1}, 'ticket_classes': [{'actual_cost': None, 'actual_fee': {'display': '$7.72', 'currency': 'USD', 'value': 772, 'major_value': '7.72'}, 'cost': {'display': '$100.00', 'currency': 'USD', 'value': 10000, 'major_value': '100.00'}, 'fee': {'display': '$7.72', 'currency': 'USD', 'value': 772, 'major_value': '7.72'}, 'tax': {'display': '$0.00', 'currency': 'USD', 'value': 0, 'major_value': '0.00'}, 'resource_uri': 'https://www.eventbriteapi.com/v3/events/158717222485/ticket_classes/098098098/', 'display_name': 'Regular Price', 'name': 'Regular Price', 'description': None, 'sorting': 1, 'donation': False, 'free': False, 'minimum_quantity': 1, 'maximum_quantity': 10, 'maximum_quantity_per_order': 10, 'on_sale_status': 'AVAILABLE', 'has_pdf_ticket': True, 'order_confirmation_message': None, 'delivery_methods': ['electronic'], 'category': 'admission', 'sales_channels': ['online', 'atd'], 'secondary_assignment_enabled': False, 'event_id': '44454545454545454', 'image_id': None, 'id': '278648077', 'capacity': 300, 'quantity_total': 300, 'quantity_sold': 0, 'sales_start': '2021-06-02T04:00:00Z', 'sales_end': '2021-09-03T19:00:00Z', 'sales_end_relative': None, 'hidden': False, 'hidden_currently': False, 'include_fee': False, 'split_fee': False, 'hide_description': True, 'hide_sale_dates': False, 'auto_hide': False, 'payment_constraints': []}, {'actual_cost': None, 'actual_fee': None, 'cost': None, 'fee': None, 'tax': None, 'resource_uri': 'https://www.eventbriteapi.com/v3/events/158717222485/ticket_classes/987987987/', 'display_name': 'Super Special Free Admission', 'name': 'Super Special Free Admission', 'description': None, 'sorting': 2, 'donation': False, 'free': True, 'minimum_quantity': 1, 'maximum_quantity': 1, 'maximum_quantity_per_order': 1, 'on_sale_status': 'AVAILABLE', 'has_pdf_ticket': True, 'order_confirmation_message': None, 'delivery_methods': ['electronic'], 'category': 'admission', 'sales_channels': ['online', 'atd'], 'secondary_assignment_enabled': False, 'event_id': '44454545454545454', 'image_id': None, 'id': '278648079', 'capacity': 50, 'quantity_total': 50, 'quantity_sold': 0, 'sales_start': '2021-06-02T04:00:00Z', 'sales_end': '2021-09-03T19:00:00Z', 'sales_end_relative': None, 'hidden': True, 'hidden_currently': True, 'include_fee': False, 'split_fee': False, 'hide_description': True, 'hide_sale_dates': False, 'auto_hide': False, 'payment_constraints': []}]}
# sorting n=7 print(n) arr=[5,1,1,2,10,2,1] arr.sort() for i in arr: print(i,end=' ')
n = 7 print(n) arr = [5, 1, 1, 2, 10, 2, 1] arr.sort() for i in arr: print(i, end=' ')
n = int(input()) for _ in range(n): (d, m) = map(int, input().split(' ')) days = list(map(int, input().split(' '))) day_of_week = 0 friday_13s = 0 for month in range(m): for day in range(1, days[month] + 1): if day_of_week == 5 and day == 13: friday_13s += 1 day_of_week = (day_of_week + 1) % 7 print(friday_13s)
n = int(input()) for _ in range(n): (d, m) = map(int, input().split(' ')) days = list(map(int, input().split(' '))) day_of_week = 0 friday_13s = 0 for month in range(m): for day in range(1, days[month] + 1): if day_of_week == 5 and day == 13: friday_13s += 1 day_of_week = (day_of_week + 1) % 7 print(friday_13s)
class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} letters = list(s) start, end = 0, len(letters) - 1 while start < end: while start < end and letters[start] not in vowels: start += 1 while start < end and letters[end] not in vowels: end -= 1 letters[start], letters[end] = letters[end], letters[start] start += 1 end -= 1 return ''.join(letters)
class Solution(object): def reverse_vowels(self, s): """ :type s: str :rtype: str """ vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} letters = list(s) (start, end) = (0, len(letters) - 1) while start < end: while start < end and letters[start] not in vowels: start += 1 while start < end and letters[end] not in vowels: end -= 1 (letters[start], letters[end]) = (letters[end], letters[start]) start += 1 end -= 1 return ''.join(letters)
f = open("13.txt", "r") sum = 0 while (1): num = 0 line = f.readline() if line: line = line.strip('\n') for i in range(0, len(line)): num = num * 10 + int(line[i]) sum += num else: break ans = str(sum) for i in range(0, 10): print(ans[i], end = '')
f = open('13.txt', 'r') sum = 0 while 1: num = 0 line = f.readline() if line: line = line.strip('\n') for i in range(0, len(line)): num = num * 10 + int(line[i]) sum += num else: break ans = str(sum) for i in range(0, 10): print(ans[i], end='')
def from_file(input, output, fasta, fai): """ Args: input - A 23andme data file, output - Output VCF file, fasta - An uncompressed reference genome GRCh37 fasta file fai - The fasta index for for the reference """ args = { 'input': input, 'output': output, 'fasta': fasta, 'fai': fai } fai = __load_fai__(args) snps = __load_23andme_data__(args.input) records = __get_vcf_records__(snps, fai, args) __write_vcf__(args.output, records) def __load_fai__(args): index = {} with open(args.fai) as f: for line in f: toks = line.split('\t') chrom = 'chr' + toks[0] if chrom == 'chrMT': chrom = 'chrM' length = int(toks[1]) start = int(toks[2]) linebases = int(toks[3]) linewidth = int(toks[4]) index[chrom] = (start, length, linebases, linewidth) return index def __get_vcf_records__(pos_list, fai, args): with open(args.fasta) as f: def get_alts(ref, genotype): for x in genotype: assert x in 'ACGT' if len(genotype) == 1: if ref in genotype: return [] return [genotype] if ref == genotype[0] and ref == genotype[1]: return [] if ref == genotype[0]: return [genotype[1]] if ref == genotype[1]: return [genotype[0]] return [genotype[0], genotype[1]] for (rsid, chrom, pos, genotype) in pos_list: start, _, linebases, linewidth = fai[chrom] n_lines = int(pos / linebases) n_bases = pos % linebases n_bytes = start + n_lines * linewidth + n_bases f.seek(n_bytes) ref = f.read(1) alts = get_alts(ref, genotype) pos = str(pos + 1) diploid = len(genotype) == 2 assert ref not in alts assert len(alts) <= 2 if diploid: if len(alts) == 2: if alts[0] == alts[1]: yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '1/1') else: yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '1/2') yield (chrom, pos, rsid, ref, alts[1], '.', '.', '.', 'GT', '2/1') elif len(alts) == 1: yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '0/1') elif len(alts) == 1: yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '1') def __load_23andme_data__(input): with open(input) as f: for line in f: if line.startswith('#'): continue if line.strip(): rsid, chrom, pos, genotype = line.strip().split('\t') if chrom == 'MT': chrom = 'M' chrom = 'chr' + chrom if genotype != '--': skip = False for x in genotype: if x not in 'ACTG': skip = True if not skip: yield rsid, chrom, int(pos) - 1, genotype # subtract one because positions are 1-based indices def __write_vcf_header__(f): f.write( """##fileformat=VCFv4.2 ##source=23andme_to_vcf ##reference=GRCh37 ##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype"> #CHROM POS ID REF ALT QUAL FILTER INFO FORMAT SAMPLE """) def __write_vcf__(outfile, records): with open(outfile, 'w') as f: __write_vcf_header__(f) for record in records: f.write('\t'.join(record) + '\n')
def from_file(input, output, fasta, fai): """ Args: input - A 23andme data file, output - Output VCF file, fasta - An uncompressed reference genome GRCh37 fasta file fai - The fasta index for for the reference """ args = {'input': input, 'output': output, 'fasta': fasta, 'fai': fai} fai = __load_fai__(args) snps = __load_23andme_data__(args.input) records = __get_vcf_records__(snps, fai, args) __write_vcf__(args.output, records) def __load_fai__(args): index = {} with open(args.fai) as f: for line in f: toks = line.split('\t') chrom = 'chr' + toks[0] if chrom == 'chrMT': chrom = 'chrM' length = int(toks[1]) start = int(toks[2]) linebases = int(toks[3]) linewidth = int(toks[4]) index[chrom] = (start, length, linebases, linewidth) return index def __get_vcf_records__(pos_list, fai, args): with open(args.fasta) as f: def get_alts(ref, genotype): for x in genotype: assert x in 'ACGT' if len(genotype) == 1: if ref in genotype: return [] return [genotype] if ref == genotype[0] and ref == genotype[1]: return [] if ref == genotype[0]: return [genotype[1]] if ref == genotype[1]: return [genotype[0]] return [genotype[0], genotype[1]] for (rsid, chrom, pos, genotype) in pos_list: (start, _, linebases, linewidth) = fai[chrom] n_lines = int(pos / linebases) n_bases = pos % linebases n_bytes = start + n_lines * linewidth + n_bases f.seek(n_bytes) ref = f.read(1) alts = get_alts(ref, genotype) pos = str(pos + 1) diploid = len(genotype) == 2 assert ref not in alts assert len(alts) <= 2 if diploid: if len(alts) == 2: if alts[0] == alts[1]: yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '1/1') else: yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '1/2') yield (chrom, pos, rsid, ref, alts[1], '.', '.', '.', 'GT', '2/1') elif len(alts) == 1: yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '0/1') elif len(alts) == 1: yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '1') def __load_23andme_data__(input): with open(input) as f: for line in f: if line.startswith('#'): continue if line.strip(): (rsid, chrom, pos, genotype) = line.strip().split('\t') if chrom == 'MT': chrom = 'M' chrom = 'chr' + chrom if genotype != '--': skip = False for x in genotype: if x not in 'ACTG': skip = True if not skip: yield (rsid, chrom, int(pos) - 1, genotype) def __write_vcf_header__(f): f.write('##fileformat=VCFv4.2\n ##source=23andme_to_vcf\n ##reference=GRCh37\n ##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype">\n #CHROM POS ID REF ALT QUAL FILTER INFO FORMAT SAMPLE\n ') def __write_vcf__(outfile, records): with open(outfile, 'w') as f: __write_vcf_header__(f) for record in records: f.write('\t'.join(record) + '\n')
#!/usr/bin/env python3 def string_to_max_list(s): """Given an input string, convert it to a descendant list of numbers from the length of the string down to 0""" out_list = list(range(len(s) - 1, -1, -1)) return out_list def string_to_min_list(s): out_list = list(range(len(s))) out_list[0], out_list[1] = out_list[1], out_list[0] return out_list def list_to_base10_int(in_list): my_int = 0 base = len(in_list) exp = base - 1 for item in in_list: my_int += item*base**exp exp -= 1 return my_int def main(): t = int(input()) for i in range(1, t + 1): s = input() my_max_int = list_to_base10_int(string_to_max_list(s)) my_min_int = list_to_base10_int(string_to_min_list(s)) my_diff = my_max_int - my_min_int print("Case #{}: {}".format(i, my_diff)) if __name__ == "__main__": main()
def string_to_max_list(s): """Given an input string, convert it to a descendant list of numbers from the length of the string down to 0""" out_list = list(range(len(s) - 1, -1, -1)) return out_list def string_to_min_list(s): out_list = list(range(len(s))) (out_list[0], out_list[1]) = (out_list[1], out_list[0]) return out_list def list_to_base10_int(in_list): my_int = 0 base = len(in_list) exp = base - 1 for item in in_list: my_int += item * base ** exp exp -= 1 return my_int def main(): t = int(input()) for i in range(1, t + 1): s = input() my_max_int = list_to_base10_int(string_to_max_list(s)) my_min_int = list_to_base10_int(string_to_min_list(s)) my_diff = my_max_int - my_min_int print('Case #{}: {}'.format(i, my_diff)) if __name__ == '__main__': main()
def getNewAddress(): pass def pushRawP2PKHTxn(): pass def pushRawP2SHTxn(): pass def pushRawBareP2WPKHTxn(): pass def pushRawBareP2WSHTxn(): pass def pushRawP2SH_P2WPKHTxn(): pass def pushRawP2SH_P2WSHTxn(): pass def getSignedTxn(): pass
def get_new_address(): pass def push_raw_p2_pkh_txn(): pass def push_raw_p2_sh_txn(): pass def push_raw_bare_p2_wpkh_txn(): pass def push_raw_bare_p2_wsh_txn(): pass def push_raw_p2_sh_p2_wpkh_txn(): pass def push_raw_p2_sh_p2_wsh_txn(): pass def get_signed_txn(): pass
def nextPermutation(nums: list[int]) -> None: """ Do not return anything, modify nums in-place instead. """ def reverse(nums, left, right): while left < right: nums[left], nums[right] = nums[right], nums[left] left += 1 right -= 1 if not nums: return a = None for i in range(len(nums) - 2, -1, -1): if nums[i] < nums[i + 1]: a = i break if a is None: reverse(nums, 0, len(nums) - 1) return b = None for i in range(len(nums) - 1, a, -1): if nums[a] < nums[i]: b = i break nums[a], nums[b] = nums[b], nums[a] reverse(nums, a+1, len(nums) - 1)
def next_permutation(nums: list[int]) -> None: """ Do not return anything, modify nums in-place instead. """ def reverse(nums, left, right): while left < right: (nums[left], nums[right]) = (nums[right], nums[left]) left += 1 right -= 1 if not nums: return a = None for i in range(len(nums) - 2, -1, -1): if nums[i] < nums[i + 1]: a = i break if a is None: reverse(nums, 0, len(nums) - 1) return b = None for i in range(len(nums) - 1, a, -1): if nums[a] < nums[i]: b = i break (nums[a], nums[b]) = (nums[b], nums[a]) reverse(nums, a + 1, len(nums) - 1)
""" Mercedes Me APIs Author: G. Ravera For more details about this component, please refer to the documentation at https://github.com/xraver/mercedes_me_api/ """ # Software Name & Version NAME = "Mercedes Me API" DOMAIN = "mercedesmeapi" VERSION = "0.8" # Software Parameters TOKEN_FILE = ".mercedesme_token" CREDENTIALS_FILE = ".mercedesme_credentials" RESOURCES_FILE = ".mercedesme_resources" # Mercedes me Application Parameters REDIRECT_URL = "https://localhost" SCOPE = "mb:vehicle:mbdata:fuelstatus%20mb:vehicle:mbdata:vehiclestatus%20mb:vehicle:mbdata:vehiclelock%20mb:vehicle:mbdata:evstatus%20offline_access" URL_RES_PREFIX = "https://api.mercedes-benz.com/vehicledata/v2" # File Parameters CONF_CLIENT_ID = "CLIENT_ID" CONF_CLIENT_SECRET = "CLIENT_SECRET" CONF_VEHICLE_ID = "VEHICLE_ID"
""" Mercedes Me APIs Author: G. Ravera For more details about this component, please refer to the documentation at https://github.com/xraver/mercedes_me_api/ """ name = 'Mercedes Me API' domain = 'mercedesmeapi' version = '0.8' token_file = '.mercedesme_token' credentials_file = '.mercedesme_credentials' resources_file = '.mercedesme_resources' redirect_url = 'https://localhost' scope = 'mb:vehicle:mbdata:fuelstatus%20mb:vehicle:mbdata:vehiclestatus%20mb:vehicle:mbdata:vehiclelock%20mb:vehicle:mbdata:evstatus%20offline_access' url_res_prefix = 'https://api.mercedes-benz.com/vehicledata/v2' conf_client_id = 'CLIENT_ID' conf_client_secret = 'CLIENT_SECRET' conf_vehicle_id = 'VEHICLE_ID'
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-12-29 15:17 albert_models_google = { 'albert_base_zh': 'https://storage.googleapis.com/albert_models/albert_base_zh.tar.gz', 'albert_large_zh': 'https://storage.googleapis.com/albert_models/albert_large_zh.tar.gz', 'albert_xlarge_zh': 'https://storage.googleapis.com/albert_models/albert_xlarge_zh.tar.gz', 'albert_xxlarge_zh': 'https://storage.googleapis.com/albert_models/albert_xxlarge_zh.tar.gz', }
albert_models_google = {'albert_base_zh': 'https://storage.googleapis.com/albert_models/albert_base_zh.tar.gz', 'albert_large_zh': 'https://storage.googleapis.com/albert_models/albert_large_zh.tar.gz', 'albert_xlarge_zh': 'https://storage.googleapis.com/albert_models/albert_xlarge_zh.tar.gz', 'albert_xxlarge_zh': 'https://storage.googleapis.com/albert_models/albert_xxlarge_zh.tar.gz'}
class Solution(object): def getMoneyAmount(self, n): """ :type n: int :rtype: int """ cache = [[0] * (n + 1) for _ in xrange(n + 1)] def dc(cache, start, end): if start >= end: return 0 if cache[start][end] != 0: return cache[start][end] minV = float("inf") for i in range(start, end + 1): left = dc(cache, start, i - 1) right = dc(cache, i + 1, end) minV = min(minV, max(left, right) + i) if minV != float("inf"): cache[start][end] = minV return cache[start][end] dc(cache, 1, n) return cache[1][n]
class Solution(object): def get_money_amount(self, n): """ :type n: int :rtype: int """ cache = [[0] * (n + 1) for _ in xrange(n + 1)] def dc(cache, start, end): if start >= end: return 0 if cache[start][end] != 0: return cache[start][end] min_v = float('inf') for i in range(start, end + 1): left = dc(cache, start, i - 1) right = dc(cache, i + 1, end) min_v = min(minV, max(left, right) + i) if minV != float('inf'): cache[start][end] = minV return cache[start][end] dc(cache, 1, n) return cache[1][n]
AWR_CONFIGS = { "Ant-v2": { "actor_net_layers": [128, 64], "actor_stepsize": 0.00005, "actor_momentum": 0.9, "actor_init_output_scale": 0.01, "actor_batch_size": 256, "actor_steps": 1000, "action_std": 0.2, "critic_net_layers": [128, 64], "critic_stepsize": 0.01, "critic_momentum": 0.9, "critic_batch_size": 256, "critic_steps": 200, "discount": 0.99, "samples_per_iter": 2048, "replay_buffer_size": 50000, "normalizer_samples": 300000, "weight_clip": 20, "td_lambda": 0.95, "temp": 1.0, }, "HalfCheetah-v2": { "actor_net_layers": [128, 64], "actor_stepsize": 0.00005, "actor_momentum": 0.9, "actor_init_output_scale": 0.01, "actor_batch_size": 256, "actor_steps": 1000, "action_std": 0.4, "critic_net_layers": [128, 64], "critic_stepsize": 0.01, "critic_momentum": 0.9, "critic_batch_size": 256, "critic_steps": 200, "discount": 0.99, "samples_per_iter": 2048, "replay_buffer_size": 50000, "normalizer_samples": 300000, "weight_clip": 20, "td_lambda": 0.95, "temp": 1.0, }, "Hopper-v2": { "actor_net_layers": [128, 64], "actor_stepsize": 0.0001, "actor_momentum": 0.9, "actor_init_output_scale": 0.01, "actor_batch_size": 256, "actor_steps": 1000, "action_std": 0.4, "critic_net_layers": [128, 64], "critic_stepsize": 0.01, "critic_momentum": 0.9, "critic_batch_size": 256, "critic_steps": 200, "discount": 0.99, "samples_per_iter": 2048, "replay_buffer_size": 50000, "normalizer_samples": 300000, "weight_clip": 20, "td_lambda": 0.95, "temp": 1.0, }, "Humanoid-v2": { "actor_net_layers": [128, 64], "actor_stepsize": 0.00001, "actor_momentum": 0.9, "actor_init_output_scale": 0.01, "actor_batch_size": 256, "actor_steps": 1000, "action_std": 0.4, "critic_net_layers": [128, 64], "critic_stepsize": 0.01, "critic_momentum": 0.9, "critic_batch_size": 256, "critic_steps": 200, "discount": 0.99, "samples_per_iter": 2048, "replay_buffer_size": 50000, "normalizer_samples": 300000, "weight_clip": 20, "td_lambda": 0.95, "temp": 1.0, }, "LunarLander-v2": { "actor_net_layers": [128, 64], "actor_stepsize": 0.0005, "actor_momentum": 0.9, "actor_init_output_scale": 0.01, "actor_batch_size": 256, "actor_steps": 1000, "action_l2_weight": 0.001, "critic_net_layers": [128, 64], "critic_stepsize": 0.01, "critic_momentum": 0.9, "critic_batch_size": 256, "critic_steps": 200, "discount": 0.99, "samples_per_iter": 2048, "replay_buffer_size": 50000, "normalizer_samples": 100000, "weight_clip": 20, "td_lambda": 0.95, "temp": 1.0, }, "LunarLanderContinuous-v2": { "actor_net_layers": [128, 64], "actor_stepsize": 0.0001, "actor_momentum": 0.9, "actor_init_output_scale": 0.01, "actor_batch_size": 256, "actor_steps": 1000, "action_std": 0.2, "critic_net_layers": [128, 64], "critic_stepsize": 0.01, "critic_momentum": 0.9, "critic_batch_size": 256, "critic_steps": 200, "discount": 0.99, "samples_per_iter": 2048, "replay_buffer_size": 50000, "normalizer_samples": 300000, "weight_clip": 20, "td_lambda": 0.95, "temp": 1.0, }, "Reacher-v2": { "actor_net_layers": [128, 64], "actor_stepsize": 0.0001, "actor_momentum": 0.9, "actor_init_output_scale": 0.01, "actor_batch_size": 256, "actor_steps": 1000, "action_std": 0.2, "critic_net_layers": [128, 64], "critic_stepsize": 0.01, "critic_momentum": 0.9, "critic_batch_size": 256, "critic_steps": 200, "discount": 0.99, "samples_per_iter": 2048, "replay_buffer_size": 50000, "normalizer_samples": 300000, "weight_clip": 20, "td_lambda": 0.95, "temp": 1.0, }, "Walker2d-v2": { "actor_net_layers": [128, 64], "actor_stepsize": 0.000025, "actor_momentum": 0.9, "actor_init_output_scale": 0.01, "actor_batch_size": 256, "actor_steps": 1000, "action_std": 0.4, "critic_net_layers": [128, 64], "critic_stepsize": 0.01, "critic_momentum": 0.9, "critic_batch_size": 256, "critic_steps": 200, "discount": 0.99, "samples_per_iter": 2048, "replay_buffer_size": 50000, "normalizer_samples": 300000, "weight_clip": 20, "td_lambda": 0.95, "temp": 1.0, } }
awr_configs = {'Ant-v2': {'actor_net_layers': [128, 64], 'actor_stepsize': 5e-05, 'actor_momentum': 0.9, 'actor_init_output_scale': 0.01, 'actor_batch_size': 256, 'actor_steps': 1000, 'action_std': 0.2, 'critic_net_layers': [128, 64], 'critic_stepsize': 0.01, 'critic_momentum': 0.9, 'critic_batch_size': 256, 'critic_steps': 200, 'discount': 0.99, 'samples_per_iter': 2048, 'replay_buffer_size': 50000, 'normalizer_samples': 300000, 'weight_clip': 20, 'td_lambda': 0.95, 'temp': 1.0}, 'HalfCheetah-v2': {'actor_net_layers': [128, 64], 'actor_stepsize': 5e-05, 'actor_momentum': 0.9, 'actor_init_output_scale': 0.01, 'actor_batch_size': 256, 'actor_steps': 1000, 'action_std': 0.4, 'critic_net_layers': [128, 64], 'critic_stepsize': 0.01, 'critic_momentum': 0.9, 'critic_batch_size': 256, 'critic_steps': 200, 'discount': 0.99, 'samples_per_iter': 2048, 'replay_buffer_size': 50000, 'normalizer_samples': 300000, 'weight_clip': 20, 'td_lambda': 0.95, 'temp': 1.0}, 'Hopper-v2': {'actor_net_layers': [128, 64], 'actor_stepsize': 0.0001, 'actor_momentum': 0.9, 'actor_init_output_scale': 0.01, 'actor_batch_size': 256, 'actor_steps': 1000, 'action_std': 0.4, 'critic_net_layers': [128, 64], 'critic_stepsize': 0.01, 'critic_momentum': 0.9, 'critic_batch_size': 256, 'critic_steps': 200, 'discount': 0.99, 'samples_per_iter': 2048, 'replay_buffer_size': 50000, 'normalizer_samples': 300000, 'weight_clip': 20, 'td_lambda': 0.95, 'temp': 1.0}, 'Humanoid-v2': {'actor_net_layers': [128, 64], 'actor_stepsize': 1e-05, 'actor_momentum': 0.9, 'actor_init_output_scale': 0.01, 'actor_batch_size': 256, 'actor_steps': 1000, 'action_std': 0.4, 'critic_net_layers': [128, 64], 'critic_stepsize': 0.01, 'critic_momentum': 0.9, 'critic_batch_size': 256, 'critic_steps': 200, 'discount': 0.99, 'samples_per_iter': 2048, 'replay_buffer_size': 50000, 'normalizer_samples': 300000, 'weight_clip': 20, 'td_lambda': 0.95, 'temp': 1.0}, 'LunarLander-v2': {'actor_net_layers': [128, 64], 'actor_stepsize': 0.0005, 'actor_momentum': 0.9, 'actor_init_output_scale': 0.01, 'actor_batch_size': 256, 'actor_steps': 1000, 'action_l2_weight': 0.001, 'critic_net_layers': [128, 64], 'critic_stepsize': 0.01, 'critic_momentum': 0.9, 'critic_batch_size': 256, 'critic_steps': 200, 'discount': 0.99, 'samples_per_iter': 2048, 'replay_buffer_size': 50000, 'normalizer_samples': 100000, 'weight_clip': 20, 'td_lambda': 0.95, 'temp': 1.0}, 'LunarLanderContinuous-v2': {'actor_net_layers': [128, 64], 'actor_stepsize': 0.0001, 'actor_momentum': 0.9, 'actor_init_output_scale': 0.01, 'actor_batch_size': 256, 'actor_steps': 1000, 'action_std': 0.2, 'critic_net_layers': [128, 64], 'critic_stepsize': 0.01, 'critic_momentum': 0.9, 'critic_batch_size': 256, 'critic_steps': 200, 'discount': 0.99, 'samples_per_iter': 2048, 'replay_buffer_size': 50000, 'normalizer_samples': 300000, 'weight_clip': 20, 'td_lambda': 0.95, 'temp': 1.0}, 'Reacher-v2': {'actor_net_layers': [128, 64], 'actor_stepsize': 0.0001, 'actor_momentum': 0.9, 'actor_init_output_scale': 0.01, 'actor_batch_size': 256, 'actor_steps': 1000, 'action_std': 0.2, 'critic_net_layers': [128, 64], 'critic_stepsize': 0.01, 'critic_momentum': 0.9, 'critic_batch_size': 256, 'critic_steps': 200, 'discount': 0.99, 'samples_per_iter': 2048, 'replay_buffer_size': 50000, 'normalizer_samples': 300000, 'weight_clip': 20, 'td_lambda': 0.95, 'temp': 1.0}, 'Walker2d-v2': {'actor_net_layers': [128, 64], 'actor_stepsize': 2.5e-05, 'actor_momentum': 0.9, 'actor_init_output_scale': 0.01, 'actor_batch_size': 256, 'actor_steps': 1000, 'action_std': 0.4, 'critic_net_layers': [128, 64], 'critic_stepsize': 0.01, 'critic_momentum': 0.9, 'critic_batch_size': 256, 'critic_steps': 200, 'discount': 0.99, 'samples_per_iter': 2048, 'replay_buffer_size': 50000, 'normalizer_samples': 300000, 'weight_clip': 20, 'td_lambda': 0.95, 'temp': 1.0}}
""" Custom exceptions for runpandas """ class InvalidFileError(Exception): def __init__(self, msg): message = "It doesn't like a valid %s file!" % (msg) super().__init__(message) class RequiredColumnError(Exception): def __init__(self, column, cls=None): if cls is None: message = "{!r} column not found".format(column) else: message = "{!r} column should be of type {!s}".format(column, cls) super().__init__(message)
""" Custom exceptions for runpandas """ class Invalidfileerror(Exception): def __init__(self, msg): message = "It doesn't like a valid %s file!" % msg super().__init__(message) class Requiredcolumnerror(Exception): def __init__(self, column, cls=None): if cls is None: message = '{!r} column not found'.format(column) else: message = '{!r} column should be of type {!s}'.format(column, cls) super().__init__(message)
class MonoMacPackage (Package): def __init__ (self): self.pkgconfig_version = '1.0' self.maccore_tag = '0b71453' self.maccore_source_dir_name = 'mono-maccore-0b71453' self.monomac_tag = 'ae428c7' self.monomac_source_dir_name = 'mono-monomac-ae428c7' Package.__init__ (self, 'monomac', self.monomac_tag) self.sources = [ 'https://github.com/mono/maccore/tarball/%{maccore_tag}', 'https://github.com/mono/monomac/tarball/%{monomac_tag}' ] def prep (self): self.sh ('tar xf "%{sources[0]}"') self.sh ('tar xf "%{sources[1]}"') self.sh ('mv %{maccore_source_dir_name} maccore') self.sh ('mv %{monomac_source_dir_name} monomac') self.cd ('monomac/src') def build (self): self.sh ('make') def install (self): self.sh ('mkdir -p %{prefix}/lib/monomac') self.sh ('mkdir -p %{prefix}/share/pkgconfig') self.sh ('echo "Libraries=%{prefix}/lib/monomac/MonoMac.dll\n\nName: MonoMac\nDescription: Mono Mac bindings\nVersion:%{pkgconfig_version}\nLibs: -r:%{prefix}/lib/monomac/MonoMac.dll" > %{prefix}/share/pkgconfig/monomac.pc') self.sh ('cp MonoMac.dll %{prefix}/lib/monomac') MonoMacPackage ()
class Monomacpackage(Package): def __init__(self): self.pkgconfig_version = '1.0' self.maccore_tag = '0b71453' self.maccore_source_dir_name = 'mono-maccore-0b71453' self.monomac_tag = 'ae428c7' self.monomac_source_dir_name = 'mono-monomac-ae428c7' Package.__init__(self, 'monomac', self.monomac_tag) self.sources = ['https://github.com/mono/maccore/tarball/%{maccore_tag}', 'https://github.com/mono/monomac/tarball/%{monomac_tag}'] def prep(self): self.sh('tar xf "%{sources[0]}"') self.sh('tar xf "%{sources[1]}"') self.sh('mv %{maccore_source_dir_name} maccore') self.sh('mv %{monomac_source_dir_name} monomac') self.cd('monomac/src') def build(self): self.sh('make') def install(self): self.sh('mkdir -p %{prefix}/lib/monomac') self.sh('mkdir -p %{prefix}/share/pkgconfig') self.sh('echo "Libraries=%{prefix}/lib/monomac/MonoMac.dll\n\nName: MonoMac\nDescription: Mono Mac bindings\nVersion:%{pkgconfig_version}\nLibs: -r:%{prefix}/lib/monomac/MonoMac.dll" > %{prefix}/share/pkgconfig/monomac.pc') self.sh('cp MonoMac.dll %{prefix}/lib/monomac') mono_mac_package()
# flake8: noqa # Disable all security c.NotebookApp.token = "" c.NotebookApp.password = "" c.NotebookApp.open_browser = True c.NotebookApp.ip = "localhost"
c.NotebookApp.token = '' c.NotebookApp.password = '' c.NotebookApp.open_browser = True c.NotebookApp.ip = 'localhost'
"""STATES""" ON = "ON" OFF = "OFF"
"""STATES""" on = 'ON' off = 'OFF'
"""Message type identifiers for Connections.""" MESSAGE_FAMILY = "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/credential-issuance/0.1" CREDENTIAL_OFFER = f"{MESSAGE_FAMILY}/credential-offer" CREDENTIAL_REQUEST = f"{MESSAGE_FAMILY}/credential-request" CREDENTIAL_ISSUE = f"{MESSAGE_FAMILY}/credential-issue" MESSAGE_TYPES = { CREDENTIAL_OFFER: ( "aries_cloudagent.messaging.credentials.messages." + "credential_offer.CredentialOffer" ), CREDENTIAL_REQUEST: ( "aries_cloudagent.messaging.credentials.messages." + "credential_request.CredentialRequest" ), CREDENTIAL_ISSUE: ( "aries_cloudagent.messaging.credentials.messages." + "credential_issue.CredentialIssue" ), }
"""Message type identifiers for Connections.""" message_family = 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/credential-issuance/0.1' credential_offer = f'{MESSAGE_FAMILY}/credential-offer' credential_request = f'{MESSAGE_FAMILY}/credential-request' credential_issue = f'{MESSAGE_FAMILY}/credential-issue' message_types = {CREDENTIAL_OFFER: 'aries_cloudagent.messaging.credentials.messages.' + 'credential_offer.CredentialOffer', CREDENTIAL_REQUEST: 'aries_cloudagent.messaging.credentials.messages.' + 'credential_request.CredentialRequest', CREDENTIAL_ISSUE: 'aries_cloudagent.messaging.credentials.messages.' + 'credential_issue.CredentialIssue'}
# -*- coding: utf-8 -*- def comp_mass_magnets(self): """Compute the mass of the hole magnets Parameters ---------- self : HoleM50 A HoleM50 object Returns ------- Mmag: float mass of the 2 Magnets [kg] """ M = 0 # magnet_0 and magnet_1 can have different materials if self.magnet_0: M += self.H3 * self.W4 * self.magnet_0.Lmag * self.magnet_0.mat_type.struct.rho if self.magnet_1: M += self.H3 * self.W4 * self.magnet_1.Lmag * self.magnet_1.mat_type.struct.rho return M
def comp_mass_magnets(self): """Compute the mass of the hole magnets Parameters ---------- self : HoleM50 A HoleM50 object Returns ------- Mmag: float mass of the 2 Magnets [kg] """ m = 0 if self.magnet_0: m += self.H3 * self.W4 * self.magnet_0.Lmag * self.magnet_0.mat_type.struct.rho if self.magnet_1: m += self.H3 * self.W4 * self.magnet_1.Lmag * self.magnet_1.mat_type.struct.rho return M
A, B = map(int, input().split()) if A > 8 or B > 8: print(":(") else: print("Yay!")
(a, b) = map(int, input().split()) if A > 8 or B > 8: print(':(') else: print('Yay!')
class PointObject(RhinoObject): # no doc def DuplicatePointGeometry(self): """ DuplicatePointGeometry(self: PointObject) -> Point """ pass PointGeometry = property( lambda self: object(), lambda self, v: None, lambda self: None ) """Get: PointGeometry(self: PointObject) -> Point """
class Pointobject(RhinoObject): def duplicate_point_geometry(self): """ DuplicatePointGeometry(self: PointObject) -> Point """ pass point_geometry = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Get: PointGeometry(self: PointObject) -> Point\n\n\n\n'
# Copyright 2021 Jake Arkinstall # # Work based on efforts copyrighted 2018 The Bazel Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. load("//toolchain/internal:common.bzl", _python = "python") # If a new Circle version is missing from this list, please add the details here # and send a PR on github. To calculate the sha256, use # ``` # curl -s https://www.circle-lang.org/linux/build_{X}.tgz | sha256sum # ``` _circle_builds = { "141": struct( version = "141", url = "https://www.circle-lang.org/linux/build_141.tgz", sha256 = "90228ff369fb478bd4c0f86092725a22ec775924bdfff201cd4529ed9a969848", ), "142": struct( version = "142", url = "https://www.circle-lang.org/linux/build_142.tgz", sha256 = "fda3c2ea0f9bfb02e9627f1cb401e6f67a85a778c5ca26bd543101d51f274711", ), } def download_circle(rctx): circle_version = str(rctx.attr.circle_version) if circle_version not in _circle_builds: fail("Circle version %s has not been configured in toolchain/internal/circle_builds.bzl" % circle_version) spec = _circle_builds[circle_version] rctx.download_and_extract( spec.url, sha256 = spec.sha256, )
load('//toolchain/internal:common.bzl', _python='python') _circle_builds = {'141': struct(version='141', url='https://www.circle-lang.org/linux/build_141.tgz', sha256='90228ff369fb478bd4c0f86092725a22ec775924bdfff201cd4529ed9a969848'), '142': struct(version='142', url='https://www.circle-lang.org/linux/build_142.tgz', sha256='fda3c2ea0f9bfb02e9627f1cb401e6f67a85a778c5ca26bd543101d51f274711')} def download_circle(rctx): circle_version = str(rctx.attr.circle_version) if circle_version not in _circle_builds: fail('Circle version %s has not been configured in toolchain/internal/circle_builds.bzl' % circle_version) spec = _circle_builds[circle_version] rctx.download_and_extract(spec.url, sha256=spec.sha256)
def add(matA,matB): dimA = [] dimB = [] # find dimensions of arrA a = matA b = matB while type(a) == list: dimA.append(len(a)) a = a[0] # find dimensions of arrB while type(b) == list: dimB.append(len(b)) b = b[0] #is it possible to add them if dimA != dimB: raise Exception("dimension mismath {} != {}".format(dimA,dimB)) #add em together newArr = [[0 for _ in range(dimA[1])] for _ in range(dimA[0])] for i in range(dimA[0]): for j in range(dimA[1]): newArr[i][j] = matA[i][j] + matB[i][j] return newArr
def add(matA, matB): dim_a = [] dim_b = [] a = matA b = matB while type(a) == list: dimA.append(len(a)) a = a[0] while type(b) == list: dimB.append(len(b)) b = b[0] if dimA != dimB: raise exception('dimension mismath {} != {}'.format(dimA, dimB)) new_arr = [[0 for _ in range(dimA[1])] for _ in range(dimA[0])] for i in range(dimA[0]): for j in range(dimA[1]): newArr[i][j] = matA[i][j] + matB[i][j] return newArr
# This file contains code that can be used later which cannot fit in right now. '''This is the function to run 'map'. This is paused so that PyCUDA can support dynamic parallelism. if stmt.count('map') > 0: self.kernel_final.append(kernel+"}") start = stmt.index('map') + 2 declar = self.device_py[self.device_func_name.index(stmt[start])] print declar, stmt caller = stmt[start+1:-1] called = declar[declar.index('('):-2] print caller, called end = len(stmt) - 1 map_name = "map_" + str(stmt[start]) print map_name self.map_func.append(map_name) # self.global_func.append(map_name) kernel = "__device__ void " + map_name + "( " args = [] # print self.device_py, self.device_sentences, self.device_func_name, self.device_var_nam, self.device_type_vars for i in declar[3:-2]: if i != ",": args.append(i) kernel += str(self.type_vars[self.var_nam.index(caller[called.index(i)])]) + " " + str(i) + "," # print self.type_args, self.var_nam, self.type_args[self.var_nam.index(i)] kernel += str(self.type_vars[self.var_nam.index(stmt[0])]) + " " + str(stmt[0]) kernel += "){\n" + "int tid = threadIdx.x + blockIdx.x * blockDim.x;\n" shh = shlex.shlex(self.device_sentences[self.device_func_name.index(stmt[start])][0]) self.ismap.append(True) print self.type_vars kernel += stmt[0] + "[tid] = " print self.device_sentences[self.device_func_name.index(stmt[start])] if shh.get_token() == 'return': j = shh.get_token() while j is not shh.eof: if j in args: kernel += j + "[tid] " else: kernel += j j = shh.get_token() kernel += ";\n" # print kernel # print stmt[0] print "Printing Kernel", kernel return kernel'''
"""This is the function to run 'map'. This is paused so that PyCUDA can support dynamic parallelism. if stmt.count('map') > 0: self.kernel_final.append(kernel+"}") start = stmt.index('map') + 2 declar = self.device_py[self.device_func_name.index(stmt[start])] print declar, stmt caller = stmt[start+1:-1] called = declar[declar.index('('):-2] print caller, called end = len(stmt) - 1 map_name = "map_" + str(stmt[start]) print map_name self.map_func.append(map_name) # self.global_func.append(map_name) kernel = "__device__ void " + map_name + "( " args = [] # print self.device_py, self.device_sentences, self.device_func_name, self.device_var_nam, self.device_type_vars for i in declar[3:-2]: if i != ",": args.append(i) kernel += str(self.type_vars[self.var_nam.index(caller[called.index(i)])]) + " " + str(i) + "," # print self.type_args, self.var_nam, self.type_args[self.var_nam.index(i)] kernel += str(self.type_vars[self.var_nam.index(stmt[0])]) + " " + str(stmt[0]) kernel += "){ " + "int tid = threadIdx.x + blockIdx.x * blockDim.x; " shh = shlex.shlex(self.device_sentences[self.device_func_name.index(stmt[start])][0]) self.ismap.append(True) print self.type_vars kernel += stmt[0] + "[tid] = " print self.device_sentences[self.device_func_name.index(stmt[start])] if shh.get_token() == 'return': j = shh.get_token() while j is not shh.eof: if j in args: kernel += j + "[tid] " else: kernel += j j = shh.get_token() kernel += "; " # print kernel # print stmt[0] print "Printing Kernel", kernel return kernel"""
""" Code implementing standard data types. Can depend on core and calc, and no other Sauronlab packages. """
""" Code implementing standard data types. Can depend on core and calc, and no other Sauronlab packages. """
class Solution(object): def calculateMinimumHP(self, dungeon): """ :type dungeon: List[List[int]] :rtype: int """ if not dungeon: return 0 N = len(dungeon) M = len(dungeon[0]) matrix = [] for i in range(N): row = [0] * M matrix.append(row) matrix[N - 1][M - 1] = ( 1 if dungeon[N - 1][M - 1] >= 0 else -dungeon[N - 1][M - 1] + 1 ) for n in range(M + N - 1, -1, -1): for x in range(N): y = n - x if y < 0 or y >= M: continue candidates = [] if x + 1 < N: candidates.append(matrix[x + 1][y]) if y + 1 < M: candidates.append(matrix[x][y + 1]) if not candidates: continue min_need = min(candidates) if dungeon[x][y] >= 0: if dungeon[x][y] >= min_need: matrix[x][y] = 1 else: matrix[x][y] = min_need - dungeon[x][y] else: matrix[x][y] = min_need - dungeon[x][y] return matrix[0][0]
class Solution(object): def calculate_minimum_hp(self, dungeon): """ :type dungeon: List[List[int]] :rtype: int """ if not dungeon: return 0 n = len(dungeon) m = len(dungeon[0]) matrix = [] for i in range(N): row = [0] * M matrix.append(row) matrix[N - 1][M - 1] = 1 if dungeon[N - 1][M - 1] >= 0 else -dungeon[N - 1][M - 1] + 1 for n in range(M + N - 1, -1, -1): for x in range(N): y = n - x if y < 0 or y >= M: continue candidates = [] if x + 1 < N: candidates.append(matrix[x + 1][y]) if y + 1 < M: candidates.append(matrix[x][y + 1]) if not candidates: continue min_need = min(candidates) if dungeon[x][y] >= 0: if dungeon[x][y] >= min_need: matrix[x][y] = 1 else: matrix[x][y] = min_need - dungeon[x][y] else: matrix[x][y] = min_need - dungeon[x][y] return matrix[0][0]
# Copyright 2017 Rice University # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class RetReverseMapper: def __init__(self, vocab): self.vocab = vocab self.ret_type = [] self.num_data = 0 return def add_data(self, ret_type): self.ret_type.extend(ret_type) self.num_data += len(ret_type) def get_element(self, id): return self.ret_type[id] def decode_ret(self, ret_type): print('--Ret Type--') print(self.vocab.chars_type[ret_type]) def reset(self): self.ret_type = [] self.num_data = 0
class Retreversemapper: def __init__(self, vocab): self.vocab = vocab self.ret_type = [] self.num_data = 0 return def add_data(self, ret_type): self.ret_type.extend(ret_type) self.num_data += len(ret_type) def get_element(self, id): return self.ret_type[id] def decode_ret(self, ret_type): print('--Ret Type--') print(self.vocab.chars_type[ret_type]) def reset(self): self.ret_type = [] self.num_data = 0
names = [] children = [] with open("day7.txt") as f: for line in f.readlines(): data = line.split('->') names.append(data[0].split(" ")[0]) if len(data) == 2: [x.strip() for x in data[1].split(',')] children.append([x.strip() for x in data[1].split(',')]) children = [element for sublist in children for element in sublist] print("Result = ", [x for x in names if x not in children])
names = [] children = [] with open('day7.txt') as f: for line in f.readlines(): data = line.split('->') names.append(data[0].split(' ')[0]) if len(data) == 2: [x.strip() for x in data[1].split(',')] children.append([x.strip() for x in data[1].split(',')]) children = [element for sublist in children for element in sublist] print('Result = ', [x for x in names if x not in children])
# Implementation of EA def gcd(p, q): while q != 0: (p, q) = (q, p % q) return p # Implementation of the EEA def extgcd(r0, r1): u, v, s, t = 1, 0, 0, 1 # Swap arguments if r1 is smaller if r1 < r0: temp = r1 r1 = r0 r0 = temp # While Loop to cumpute params while r1 != 0: q = r0//r1 r0, r1 = r1, r0-q*r1 u, s = s, u-q*s v, t = t, v-q*t return r0, u, v # User Interface function def main(): print("Geben sie r0 ein: ") r0 = int(input()) print("Geben sie r1 ein: ") r1 = int(input()) print("----- Ergebnis ----") a1, u1, v1 = extgcd(r0, r1) print("GCD: ", a1) print("s: ", u1) print("t: ", v1) if __name__ == "__main__": main()
def gcd(p, q): while q != 0: (p, q) = (q, p % q) return p def extgcd(r0, r1): (u, v, s, t) = (1, 0, 0, 1) if r1 < r0: temp = r1 r1 = r0 r0 = temp while r1 != 0: q = r0 // r1 (r0, r1) = (r1, r0 - q * r1) (u, s) = (s, u - q * s) (v, t) = (t, v - q * t) return (r0, u, v) def main(): print('Geben sie r0 ein: ') r0 = int(input()) print('Geben sie r1 ein: ') r1 = int(input()) print('----- Ergebnis ----') (a1, u1, v1) = extgcd(r0, r1) print('GCD: ', a1) print('s: ', u1) print('t: ', v1) if __name__ == '__main__': main()
year=int(input("Enter any year to check for leap year: ")) if year%4==0: if year%100==0: if year%400==0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year))
year = int(input('Enter any year to check for leap year: ')) if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print('{0} is a leap year'.format(year)) else: print('{0} is not a leap year'.format(year)) else: print('{0} is a leap year'.format(year)) else: print('{0} is not a leap year'.format(year))
s = input().strip() while(s != '0'): tam = len(s) i = 1 anagrama = 1 while(i <= tam): anagrama = anagrama * i i = i + 1 print(anagrama) s = input().strip()
s = input().strip() while s != '0': tam = len(s) i = 1 anagrama = 1 while i <= tam: anagrama = anagrama * i i = i + 1 print(anagrama) s = input().strip()
# # @lc app=leetcode.cn id=1587 lang=python3 # # [1587] parallel-courses-ii # None # @lc code=end
None
class Solution: def findComplement(self, num: int) -> int: num = bin(num)[2:] ans = '' for i in num: if i == "1": ans += '0' else: ans += '1' ans = int(ans, 2) return ans
class Solution: def find_complement(self, num: int) -> int: num = bin(num)[2:] ans = '' for i in num: if i == '1': ans += '0' else: ans += '1' ans = int(ans, 2) return ans
# # PySNMP MIB module AT-PIM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AT-PIM-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:30:27 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion") modules, = mibBuilder.importSymbols("AT-SMI-MIB", "modules") pimNeighborIfIndex, pimInterfaceStatus = mibBuilder.importSymbols("PIM-MIB", "pimNeighborIfIndex", "pimInterfaceStatus") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") IpAddress, Counter32, ModuleIdentity, TimeTicks, ObjectIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, Integer32, iso, Unsigned32, NotificationType, Bits, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Counter32", "ModuleIdentity", "TimeTicks", "ObjectIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "Integer32", "iso", "Unsigned32", "NotificationType", "Bits", "Gauge32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") pim4 = ModuleIdentity((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97)) pim4.setRevisions(('2005-01-20 15:25',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: pim4.setRevisionsDescriptions(('Initial Revision',)) if mibBuilder.loadTexts: pim4.setLastUpdated('200501201525Z') if mibBuilder.loadTexts: pim4.setOrganization('Allied Telesis, Inc') if mibBuilder.loadTexts: pim4.setContactInfo('http://www.alliedtelesis.com') if mibBuilder.loadTexts: pim4.setDescription('Contains definitions of managed objects for the handling PIM4 enterprise functions on AT switches. ') pim4Events = MibIdentifier((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 0)) pim4NeighbourAddedTrap = NotificationType((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 0, 1)).setObjects(("PIM-MIB", "pimNeighborIfIndex")) if mibBuilder.loadTexts: pim4NeighbourAddedTrap.setStatus('current') if mibBuilder.loadTexts: pim4NeighbourAddedTrap.setDescription('A pim4NeighbourAddedTrap trap signifies that a PIM neighbour has been added') pim4NeighbourDeletedTrap = NotificationType((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 0, 2)).setObjects(("PIM-MIB", "pimNeighborIfIndex")) if mibBuilder.loadTexts: pim4NeighbourDeletedTrap.setStatus('current') if mibBuilder.loadTexts: pim4NeighbourDeletedTrap.setDescription('A pim4NeighbourDeletedTrap trap signifies that a PIM neighbour has been deleted') pim4InterfaceUpTrap = NotificationType((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 0, 3)).setObjects(("PIM-MIB", "pimInterfaceStatus")) if mibBuilder.loadTexts: pim4InterfaceUpTrap.setStatus('current') if mibBuilder.loadTexts: pim4InterfaceUpTrap.setDescription('A pimInterfaceUp trap signifies that a PIM interface has been enabled and is active') pim4InterfaceDownTrap = NotificationType((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 0, 4)).setObjects(("PIM-MIB", "pimInterfaceStatus")) if mibBuilder.loadTexts: pim4InterfaceDownTrap.setStatus('current') if mibBuilder.loadTexts: pim4InterfaceDownTrap.setDescription('A pimInterfaceDown trap signifies that a PIM interface has been disabled and is inactive') pim4ErrorTrap = NotificationType((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 0, 5)).setObjects(("AT-PIM-MIB", "pim4ErrorTrapType")) if mibBuilder.loadTexts: pim4ErrorTrap.setStatus('current') if mibBuilder.loadTexts: pim4ErrorTrap.setDescription('A pim4ErrorTrap trap is generated when a PIM error is incremented') pim4ErrorTrapType = MibScalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("pim4InvalidPacket", 1), ("pim4InvalidDestinationError", 2), ("pim4FragmentError", 3), ("pim4LengthError", 4), ("pim4GroupaddressError", 5), ("pim4SourceaddressError", 6), ("pim4MissingOptionError", 7), ("pim4GeneralError", 8), ("pim4InternalError", 9), ("pim4RpaddressError", 10)))).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: pim4ErrorTrapType.setStatus('current') if mibBuilder.loadTexts: pim4ErrorTrapType.setDescription('The type of the last error that resulted in a error trap being sent. The default value is 0 if no errors have been detected') mibBuilder.exportSymbols("AT-PIM-MIB", pim4InterfaceDownTrap=pim4InterfaceDownTrap, pim4NeighbourAddedTrap=pim4NeighbourAddedTrap, pim4ErrorTrap=pim4ErrorTrap, pim4InterfaceUpTrap=pim4InterfaceUpTrap, pim4NeighbourDeletedTrap=pim4NeighbourDeletedTrap, pim4=pim4, pim4Events=pim4Events, PYSNMP_MODULE_ID=pim4, pim4ErrorTrapType=pim4ErrorTrapType)
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, single_value_constraint, value_range_constraint, constraints_intersection, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'SingleValueConstraint', 'ValueRangeConstraint', 'ConstraintsIntersection', 'ConstraintsUnion') (modules,) = mibBuilder.importSymbols('AT-SMI-MIB', 'modules') (pim_neighbor_if_index, pim_interface_status) = mibBuilder.importSymbols('PIM-MIB', 'pimNeighborIfIndex', 'pimInterfaceStatus') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (ip_address, counter32, module_identity, time_ticks, object_identity, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column, counter64, integer32, iso, unsigned32, notification_type, bits, gauge32) = mibBuilder.importSymbols('SNMPv2-SMI', 'IpAddress', 'Counter32', 'ModuleIdentity', 'TimeTicks', 'ObjectIdentity', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter64', 'Integer32', 'iso', 'Unsigned32', 'NotificationType', 'Bits', 'Gauge32') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') pim4 = module_identity((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97)) pim4.setRevisions(('2005-01-20 15:25',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: pim4.setRevisionsDescriptions(('Initial Revision',)) if mibBuilder.loadTexts: pim4.setLastUpdated('200501201525Z') if mibBuilder.loadTexts: pim4.setOrganization('Allied Telesis, Inc') if mibBuilder.loadTexts: pim4.setContactInfo('http://www.alliedtelesis.com') if mibBuilder.loadTexts: pim4.setDescription('Contains definitions of managed objects for the handling PIM4 enterprise functions on AT switches. ') pim4_events = mib_identifier((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 0)) pim4_neighbour_added_trap = notification_type((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 0, 1)).setObjects(('PIM-MIB', 'pimNeighborIfIndex')) if mibBuilder.loadTexts: pim4NeighbourAddedTrap.setStatus('current') if mibBuilder.loadTexts: pim4NeighbourAddedTrap.setDescription('A pim4NeighbourAddedTrap trap signifies that a PIM neighbour has been added') pim4_neighbour_deleted_trap = notification_type((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 0, 2)).setObjects(('PIM-MIB', 'pimNeighborIfIndex')) if mibBuilder.loadTexts: pim4NeighbourDeletedTrap.setStatus('current') if mibBuilder.loadTexts: pim4NeighbourDeletedTrap.setDescription('A pim4NeighbourDeletedTrap trap signifies that a PIM neighbour has been deleted') pim4_interface_up_trap = notification_type((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 0, 3)).setObjects(('PIM-MIB', 'pimInterfaceStatus')) if mibBuilder.loadTexts: pim4InterfaceUpTrap.setStatus('current') if mibBuilder.loadTexts: pim4InterfaceUpTrap.setDescription('A pimInterfaceUp trap signifies that a PIM interface has been enabled and is active') pim4_interface_down_trap = notification_type((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 0, 4)).setObjects(('PIM-MIB', 'pimInterfaceStatus')) if mibBuilder.loadTexts: pim4InterfaceDownTrap.setStatus('current') if mibBuilder.loadTexts: pim4InterfaceDownTrap.setDescription('A pimInterfaceDown trap signifies that a PIM interface has been disabled and is inactive') pim4_error_trap = notification_type((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 0, 5)).setObjects(('AT-PIM-MIB', 'pim4ErrorTrapType')) if mibBuilder.loadTexts: pim4ErrorTrap.setStatus('current') if mibBuilder.loadTexts: pim4ErrorTrap.setDescription('A pim4ErrorTrap trap is generated when a PIM error is incremented') pim4_error_trap_type = mib_scalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 97, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=named_values(('pim4InvalidPacket', 1), ('pim4InvalidDestinationError', 2), ('pim4FragmentError', 3), ('pim4LengthError', 4), ('pim4GroupaddressError', 5), ('pim4SourceaddressError', 6), ('pim4MissingOptionError', 7), ('pim4GeneralError', 8), ('pim4InternalError', 9), ('pim4RpaddressError', 10)))).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: pim4ErrorTrapType.setStatus('current') if mibBuilder.loadTexts: pim4ErrorTrapType.setDescription('The type of the last error that resulted in a error trap being sent. The default value is 0 if no errors have been detected') mibBuilder.exportSymbols('AT-PIM-MIB', pim4InterfaceDownTrap=pim4InterfaceDownTrap, pim4NeighbourAddedTrap=pim4NeighbourAddedTrap, pim4ErrorTrap=pim4ErrorTrap, pim4InterfaceUpTrap=pim4InterfaceUpTrap, pim4NeighbourDeletedTrap=pim4NeighbourDeletedTrap, pim4=pim4, pim4Events=pim4Events, PYSNMP_MODULE_ID=pim4, pim4ErrorTrapType=pim4ErrorTrapType)
def create_phone_number(n): return (f'({n[0]}{n[1]}{n[2]}) {n[3]}{n[4]}{n[5]}-{n[6]}{n[7]}{n[8]}{n[9]}') # Best Practices def create_phone_number(n): print ("({}{}{}) {}{}{}-{}{}{}{}".format(*n))
def create_phone_number(n): return f'({n[0]}{n[1]}{n[2]}) {n[3]}{n[4]}{n[5]}-{n[6]}{n[7]}{n[8]}{n[9]}' def create_phone_number(n): print('({}{}{}) {}{}{}-{}{}{}{}'.format(*n))
class Class: def __init__(self, name): self.name = name self.fields = [] def __str__(self): lines = ['class %s:' % self.name] if not self.fields: lines.append(' pass') else: lines.append(' def __init__(self):') for f in self.fields: lines.append(' %s' % f) return '\n'.join(lines)
class Class: def __init__(self, name): self.name = name self.fields = [] def __str__(self): lines = ['class %s:' % self.name] if not self.fields: lines.append(' pass') else: lines.append(' def __init__(self):') for f in self.fields: lines.append(' %s' % f) return '\n'.join(lines)
class LCS: def __init__(self,str1,str2): self.str1=str1 self.str2=str2 self.m=len(str1) self.n=len(str2) self.dp = [[0 for x in range(self.n + 1)] for x in range(self.m + 1)] def lcs_length(self): for i in range(self.m): for j in range(self.n): if self.str1[i] == self.str2[j]: self.dp[i+1][j+1]=self.dp[i][j]+1 else: self.dp[i+1][j+1]=max(self.dp[i][j+1],self.dp[i+1][j]) return self.dp[-1][-1] def lcs_sequence(self): index = self.dp[self.m][self.n] seq = [""] * (index+1) seq[index] = "" i,j = self.m,self.n while i > 0 and j > 0: if self.str1[i-1] == self.str2[j-1]: seq[index-1] = self.str1[i-1] i = i - 1 j = j - 1 index -= 1 elif self.dp[i][j-1] < self.dp[i-1][j]: i = i - 1 else: j = j - 1 seq_str=''.join(seq[:-1]) return seq_str str1 = "CDEFGABC" str2 = "CEFDABGAC" MySeq=LCS(str1,str2) print('Least Common Subsequence length-->',MySeq.lcs_length()) print('Least Common Subsequence-->',MySeq.lcs_sequence()) ##OUTPUT: ''' Least Common Subsequence length--> 6 Least Common Subsequence--> CEFABC '''
class Lcs: def __init__(self, str1, str2): self.str1 = str1 self.str2 = str2 self.m = len(str1) self.n = len(str2) self.dp = [[0 for x in range(self.n + 1)] for x in range(self.m + 1)] def lcs_length(self): for i in range(self.m): for j in range(self.n): if self.str1[i] == self.str2[j]: self.dp[i + 1][j + 1] = self.dp[i][j] + 1 else: self.dp[i + 1][j + 1] = max(self.dp[i][j + 1], self.dp[i + 1][j]) return self.dp[-1][-1] def lcs_sequence(self): index = self.dp[self.m][self.n] seq = [''] * (index + 1) seq[index] = '' (i, j) = (self.m, self.n) while i > 0 and j > 0: if self.str1[i - 1] == self.str2[j - 1]: seq[index - 1] = self.str1[i - 1] i = i - 1 j = j - 1 index -= 1 elif self.dp[i][j - 1] < self.dp[i - 1][j]: i = i - 1 else: j = j - 1 seq_str = ''.join(seq[:-1]) return seq_str str1 = 'CDEFGABC' str2 = 'CEFDABGAC' my_seq = lcs(str1, str2) print('Least Common Subsequence length-->', MySeq.lcs_length()) print('Least Common Subsequence-->', MySeq.lcs_sequence()) '\nLeast Common Subsequence length--> 6\nLeast Common Subsequence--> CEFABC\n\n'
# Copyright (c) 2014 Eventbrite, Inc. All rights reserved. # See "LICENSE" file for license. """These functions should be made available via cs2mako in the Mako context""" def include(clearsilver_name): """loads clearsilver file and returns a rendered mako file""" pass # need to put whatever ported clearsilver functions we have in here
"""These functions should be made available via cs2mako in the Mako context""" def include(clearsilver_name): """loads clearsilver file and returns a rendered mako file""" pass
################################################################################ ## ## This library is free software; you can redistribute it and/or ## modify it under the terms of the GNU Lesser General Public ## License as published by the Free Software Foundation; either ## version 2.1 of the License, or (at your option) any later version. ## ## This library is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public ## License along with this library; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ## ## (C) Copyrights Dr. Michel F. Sanner and TSRI 2016 ## ################################################################################ ######################################################################## # # Date: 2015 Authors: Michel Sanner # # sanner@scripps.edu # # The Scripps Research Institute (TSRI) # Molecular Graphics Lab # La Jolla, CA 92037, USA # # Copyright: Michel Sanner and TSRI 2015 # ######################################################################### # # $Header: /mnt/raid/services/cvs/python/packages/share1.5/mglutil/util/io.py,v 1.1.4.1 2017/07/26 22:31:38 annao Exp $ # # $Id: io.py,v 1.1.4.1 2017/07/26 22:31:38 annao Exp $ # class Stream: def __init__(self): self.lines = [] def write(self, line): self.lines.append(line) # helper class to make stdout set of lines look like a file that ProDy can parse class BufferAsFile: def __init__(self, lines): self.lines = lines def readlines(self): return self.lines
class Stream: def __init__(self): self.lines = [] def write(self, line): self.lines.append(line) class Bufferasfile: def __init__(self, lines): self.lines = lines def readlines(self): return self.lines
parties = [] class Political(): @staticmethod def exists(name): """ Checks if a party with the same name exists Returns a boolean """ for party in parties: if party["name"] == name: return True return False def create_political_party(self, name, hqAddress, logoUrl): party= { "party_id": len(parties)+1, "name": name, "hqAddress": hqAddress, "logoUrl": logoUrl } parties.append(party) return party def get_political_parties(self): if len(parties) == 0: print('List is empty') return parties def get_specific_political_party(self, party_id): if parties: for party in parties: if party['party_id'] == party_id: return party def edit_political_party(self, data, party_id): if parties: for party in parties: if party['party_id'] == party_id: # return party party["name"] = data.get( 'name', party["name"]) party["hqAddress"] = data.get( 'hqAddress', party["hqAddress"]) party["logoUrl"] = data.get( 'logoUrl', party["logoUrl"]) return parties def delete_political_party(self, party_id): if parties: for party in parties: if party['party_id'] == party_id: parties.remove(party) return party return None
parties = [] class Political: @staticmethod def exists(name): """ Checks if a party with the same name exists Returns a boolean """ for party in parties: if party['name'] == name: return True return False def create_political_party(self, name, hqAddress, logoUrl): party = {'party_id': len(parties) + 1, 'name': name, 'hqAddress': hqAddress, 'logoUrl': logoUrl} parties.append(party) return party def get_political_parties(self): if len(parties) == 0: print('List is empty') return parties def get_specific_political_party(self, party_id): if parties: for party in parties: if party['party_id'] == party_id: return party def edit_political_party(self, data, party_id): if parties: for party in parties: if party['party_id'] == party_id: party['name'] = data.get('name', party['name']) party['hqAddress'] = data.get('hqAddress', party['hqAddress']) party['logoUrl'] = data.get('logoUrl', party['logoUrl']) return parties def delete_political_party(self, party_id): if parties: for party in parties: if party['party_id'] == party_id: parties.remove(party) return party return None
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 16 11:05:36 2021 @author: Olli Nevalainen (Finnish Meteorological Institute) """
""" Created on Tue Mar 16 11:05:36 2021 @author: Olli Nevalainen (Finnish Meteorological Institute) """
# Copyright (c) 2019 The Bazel Utils Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. load("//:conditions.bzl", "if_windows") load("//:warnings.bzl", "default_warnings") ############################################################################### # warning ############################################################################### # NOTE: Should be combiend wih safest_code_linkopts() in "linkopts.bzl" def safest_code_copts(): return select({ "@com_chokobole_bazel_utils//:windows": [ "/W4", ], "@com_chokobole_bazel_utils//:clang_or_clang_cl": [ "-Wextra", ], "//conditions:default": [ "-Wall", "-Werror", ], }) + default_warnings() # NOTE: Should be combiend wih safer_code_linkopts() in "linkopts.bzl" def safer_code_copts(): return if_windows([ "/W3", ], [ "-Wall", "-Werror", ]) + default_warnings() ############################################################################### # symbol visibility ############################################################################### def visibility_hidden(): return if_windows([], ["-fvisibility=hidden"]) ############################################################################### # sanitizers ############################################################################### # NOTE: Should be combiend wih asan_linkopts() in "linkopts.bzl" def asan_copts(): return ["-fsanitize=address"]
load('//:conditions.bzl', 'if_windows') load('//:warnings.bzl', 'default_warnings') def safest_code_copts(): return select({'@com_chokobole_bazel_utils//:windows': ['/W4'], '@com_chokobole_bazel_utils//:clang_or_clang_cl': ['-Wextra'], '//conditions:default': ['-Wall', '-Werror']}) + default_warnings() def safer_code_copts(): return if_windows(['/W3'], ['-Wall', '-Werror']) + default_warnings() def visibility_hidden(): return if_windows([], ['-fvisibility=hidden']) def asan_copts(): return ['-fsanitize=address']