content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
fig, ax = plt.subplots() im = ax.pcolor(grouped_pivot, cmap='RdBu') #label names row_labels = grouped_pivot.columns.levels[1] col_labels = grouped_pivot.index #move ticks and labels to the center ax.set_xticks(np.arange(grouped_pivot.shape[1]) + 0.5, minor=False) ax.set_yticks(np.arange(grouped_pivot.shape[0]) + 0.5, minor=False) #insert labels ax.set_xticklabels(row_labels, minor=False) ax.set_yticklabels(col_labels, minor=False) #rotate label if too long plt.xticks(rotation=90) fig.colorbar(im) plt.show()
(fig, ax) = plt.subplots() im = ax.pcolor(grouped_pivot, cmap='RdBu') row_labels = grouped_pivot.columns.levels[1] col_labels = grouped_pivot.index ax.set_xticks(np.arange(grouped_pivot.shape[1]) + 0.5, minor=False) ax.set_yticks(np.arange(grouped_pivot.shape[0]) + 0.5, minor=False) ax.set_xticklabels(row_labels, minor=False) ax.set_yticklabels(col_labels, minor=False) plt.xticks(rotation=90) fig.colorbar(im) plt.show()
def sayhello(name): return "Hello, " + name + ", nice to meet you!" if __name__ == "__main__": print(sayhello(input("What is your name? ")))
def sayhello(name): return 'Hello, ' + name + ', nice to meet you!' if __name__ == '__main__': print(sayhello(input('What is your name? ')))
# using cube coordinates: https://www.redblobgames.com/grids/hexagons/ def update(tile, command): x, y, z = tile if command == 'w': x -= 1 y += 1 elif command == 'e': x += 1 y -= 1 elif command == 'nw': y += 1 z -= 1 elif command == 'se': y -= 1 z += 1 elif command == 'ne': x += 1 z -= 1 elif command == 'sw': x -= 1 z += 1 assert x + y + z == 0 return [x, y, z] def neighbors(tile): directions = ['w', 'e', 'nw', 'ne', 'sw', 'se'] return [update(tile, direction) for direction in directions] # input with open('input.txt') as f: lines = f.readlines() # part 1 flipped = [] for line in lines: commands = line.replace('w', 'w,').replace('e', 'e,').split(',')[:-1] tile = [0, 0, 0] for command in commands: tile = update(tile, command) flipped.remove(tile) if tile in flipped else flipped.append(tile) ans1 = len(flipped) # part 2 for _ in range(100): possible = [] for tile in flipped: possible += [adj for adj in neighbors(tile) if adj not in possible] possible += [tile for tile in flipped if tile not in possible] next_flipped = flipped.copy() for tile in possible: num = len([adj for adj in neighbors(tile) if adj in flipped]) if tile in flipped: if num == 0 or num > 2: next_flipped.remove(tile) else: if num == 2: next_flipped.append(tile) flipped = next_flipped ans2 = len(flipped) # output answer = [] answer.append('Part 1: {}'.format(ans1)) answer.append('Part 2: {}'.format(ans2)) with open('solution.txt', 'w') as f: f.writelines('\n'.join(answer)+'\n')
def update(tile, command): (x, y, z) = tile if command == 'w': x -= 1 y += 1 elif command == 'e': x += 1 y -= 1 elif command == 'nw': y += 1 z -= 1 elif command == 'se': y -= 1 z += 1 elif command == 'ne': x += 1 z -= 1 elif command == 'sw': x -= 1 z += 1 assert x + y + z == 0 return [x, y, z] def neighbors(tile): directions = ['w', 'e', 'nw', 'ne', 'sw', 'se'] return [update(tile, direction) for direction in directions] with open('input.txt') as f: lines = f.readlines() flipped = [] for line in lines: commands = line.replace('w', 'w,').replace('e', 'e,').split(',')[:-1] tile = [0, 0, 0] for command in commands: tile = update(tile, command) flipped.remove(tile) if tile in flipped else flipped.append(tile) ans1 = len(flipped) for _ in range(100): possible = [] for tile in flipped: possible += [adj for adj in neighbors(tile) if adj not in possible] possible += [tile for tile in flipped if tile not in possible] next_flipped = flipped.copy() for tile in possible: num = len([adj for adj in neighbors(tile) if adj in flipped]) if tile in flipped: if num == 0 or num > 2: next_flipped.remove(tile) elif num == 2: next_flipped.append(tile) flipped = next_flipped ans2 = len(flipped) answer = [] answer.append('Part 1: {}'.format(ans1)) answer.append('Part 2: {}'.format(ans2)) with open('solution.txt', 'w') as f: f.writelines('\n'.join(answer) + '\n')
# Demo Python For Loops - The range() Function ''' The range() Function - Part 2 The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6): ''' # Using the start parameter: for x in range(2, 7): print(x)
""" The range() Function - Part 2 The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6): """ for x in range(2, 7): print(x)
# Copyright (c) Facebook, Inc. and its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def create_ThriftUnicodeDecodeError_from_UnicodeDecodeError(error, field_name): if isinstance(error, ThriftUnicodeDecodeError): error.field_names.append(field_name) return error return ThriftUnicodeDecodeError( error.encoding, error.object, error.start, error.end, error.reason, field_name ) class ThriftUnicodeDecodeError(UnicodeDecodeError): def __init__(self, encoding, object, start, end, reason, field_name): super(ThriftUnicodeDecodeError, self).__init__(encoding, object, start, end, reason) self.field_names = [field_name] def __str__(self): return "{error} when decoding field '{field}'".format( error=super(ThriftUnicodeDecodeError, self).__str__(), field="->".join(reversed(self.field_names)) )
def create__thrift_unicode_decode_error_from__unicode_decode_error(error, field_name): if isinstance(error, ThriftUnicodeDecodeError): error.field_names.append(field_name) return error return thrift_unicode_decode_error(error.encoding, error.object, error.start, error.end, error.reason, field_name) class Thriftunicodedecodeerror(UnicodeDecodeError): def __init__(self, encoding, object, start, end, reason, field_name): super(ThriftUnicodeDecodeError, self).__init__(encoding, object, start, end, reason) self.field_names = [field_name] def __str__(self): return "{error} when decoding field '{field}'".format(error=super(ThriftUnicodeDecodeError, self).__str__(), field='->'.join(reversed(self.field_names)))
class Enactor: def __init__(self, dev_info, sftp_location, sftp_port, sftp_username, sftp_password, sftp_key_location, sftp_directory): pass def stop(self): pass def enact_light_plan(self, dev, BL_Quota, NL_Quota): return True def enact_socket_plan(self, dev, AC_total): return True def retreive_previous_plan_AC(self, dev): return None def retreive_previous_plan_DC(self, dev): return None def check_diff_light(self, prev_plan, BL_Quota, NL_Quota): return 1.0 def check_diff_socket(self, prev_plan, AC_total): return 1.0
class Enactor: def __init__(self, dev_info, sftp_location, sftp_port, sftp_username, sftp_password, sftp_key_location, sftp_directory): pass def stop(self): pass def enact_light_plan(self, dev, BL_Quota, NL_Quota): return True def enact_socket_plan(self, dev, AC_total): return True def retreive_previous_plan_ac(self, dev): return None def retreive_previous_plan_dc(self, dev): return None def check_diff_light(self, prev_plan, BL_Quota, NL_Quota): return 1.0 def check_diff_socket(self, prev_plan, AC_total): return 1.0
class Solution: def reverse(self, x: int): flag = 0 minus = "-" if x < 0: flag = 1 x = x * -1 result= str(x) result = ''.join(reversed(result)) x = int(result) if flag == 1: x = x * -1 if x > 2147483647 or x < -2147483647: return 0 return x
class Solution: def reverse(self, x: int): flag = 0 minus = '-' if x < 0: flag = 1 x = x * -1 result = str(x) result = ''.join(reversed(result)) x = int(result) if flag == 1: x = x * -1 if x > 2147483647 or x < -2147483647: return 0 return x
class Solution: def compareVersion(self, version1: str, version2: str) -> int: v1 = [int(x) for x in version1.split('.')] v2 = [int(x) for x in version2.split('.')] while v1 and v1[-1] == 0: v1.pop() while v2 and v2[-1] == 0: v2.pop() if v1 < v2: return -1 elif v1 > v2: return 1 else: return 0
class Solution: def compare_version(self, version1: str, version2: str) -> int: v1 = [int(x) for x in version1.split('.')] v2 = [int(x) for x in version2.split('.')] while v1 and v1[-1] == 0: v1.pop() while v2 and v2[-1] == 0: v2.pop() if v1 < v2: return -1 elif v1 > v2: return 1 else: return 0
def star(N): for i in range(0,N): for j in range(0,i+1): print("*",end = "") print("\r") if __name__ == '__main__': N = int(input()) star(N)
def star(N): for i in range(0, N): for j in range(0, i + 1): print('*', end='') print('\r') if __name__ == '__main__': n = int(input()) star(N)
class Solution: def isBalanced(self, root: TreeNode) -> bool: return self.height(root) != -1 def height(self, root): if not root: return 0 lh = self.height(root.right) if lh == -1: return -1 rh = self.height(root.left) if rh == -1: return -1 if abs(lh - rh) > 1: return -1 return max(lh, rh) + 1
class Solution: def is_balanced(self, root: TreeNode) -> bool: return self.height(root) != -1 def height(self, root): if not root: return 0 lh = self.height(root.right) if lh == -1: return -1 rh = self.height(root.left) if rh == -1: return -1 if abs(lh - rh) > 1: return -1 return max(lh, rh) + 1
class Metrics: listMetric = {} def addMetric(self, metric): self.listMetric[metric.getName()] = metric.getData() def getMetrics(self): return self.listMetric
class Metrics: list_metric = {} def add_metric(self, metric): self.listMetric[metric.getName()] = metric.getData() def get_metrics(self): return self.listMetric
# coding: utf-8 class Maxipago(object): def __init__(self, maxid, api_key, api_version='3.1.1.15', sandbox=False): self.maxid = maxid self.api_key = api_key self.api_version = api_version self.sandbox = sandbox def __getattr__(self, name): try: class_name = ''.join([n.title() for n in name.split('_') + ['manager']]) module = __import__('maxipago.managers.{0}'.format(name), fromlist=['']) klass = getattr(module, class_name) return klass(self.maxid, self.api_key, self.api_version, self.sandbox) except ImportError: if name in self.__dict__: return self.__dict__.get('name') except AttributeError: raise AttributeError
class Maxipago(object): def __init__(self, maxid, api_key, api_version='3.1.1.15', sandbox=False): self.maxid = maxid self.api_key = api_key self.api_version = api_version self.sandbox = sandbox def __getattr__(self, name): try: class_name = ''.join([n.title() for n in name.split('_') + ['manager']]) module = __import__('maxipago.managers.{0}'.format(name), fromlist=['']) klass = getattr(module, class_name) return klass(self.maxid, self.api_key, self.api_version, self.sandbox) except ImportError: if name in self.__dict__: return self.__dict__.get('name') except AttributeError: raise AttributeError
# Copyright 2009-2017 Ram Rachum. # This program is distributed under the MIT license. '''Defines different rounding options for binary search.''' # todo: Confirm that `*_IF_BOTH` options are used are used in all places that # currently ~use them. class Rounding: '''Base class for rounding options for binary search.''' class BOTH(Rounding): ''' Get a tuple `(low, high)` of the 2 items that surround the specified value. If there's an exact match, gives it twice in the tuple, i.e. `(match, match)`. ''' class EXACT(Rounding): '''Get the item that has exactly the same value has the specified value.''' class CLOSEST(Rounding): '''Get the item which has a value closest to the specified value.''' class LOW(Rounding): ''' Get the item with a value that is just below the specified value. i.e. the highest item which has a value lower or equal to the specified value. ''' class HIGH(Rounding): ''' Get the item with a value that is just above the specified value. i.e. the lowest item which has a value higher or equal to the specified value. ''' class LOW_IF_BOTH(Rounding): ''' Get the item with a value that is just below the specified value. i.e. the highest item which has a value lower or equal to the specified value. Before it returns the item, it checks if there also exists an item with a value *higher* than the specified value or equal to it. If there isn't, it returns `None`. (If there's an exact match, this rounding will return it.) ''' class HIGH_IF_BOTH(Rounding): ''' Get the item with a value that is just above the specified value. i.e. the lowest item which has a value higher or equal to the specified value. Before it returns the item, it checks if there also exists an item with a value *lower* than the specified value or equal to it. If there isn't, it returns `None`. (If there's an exact match, this rounding will return it.) ''' class CLOSEST_IF_BOTH(Rounding): ''' Get the item which has a value closest to the specified value. Before it returns the item, it checks if there also exists an item which is "on the other side" of the specified value. e.g. if the closest item is higher than the specified item, it will confirm that there exists an item *below* the specified value. (And vice versa.) If there isn't it returns `None`. (If there's an exact match, this rounding will return it.) ''' class LOW_OTHERWISE_HIGH(Rounding): ''' Get the item with a value that is just below the specified value. i.e. the highest item which has a value lower or equal to the specified value. If there is no item below, give the one just above. (If there's an exact match, this rounding will return it.) ''' class HIGH_OTHERWISE_LOW(Rounding): ''' Get the item with a value that is just above the specified value. i.e. the lowest item which has a value higher or equal to the specified value. If there is no item above, give the one just below. (If there's an exact match, this rounding will return it.) ''' roundings = (LOW, LOW_IF_BOTH, LOW_OTHERWISE_HIGH, HIGH, HIGH_IF_BOTH, HIGH_OTHERWISE_LOW, EXACT, CLOSEST, CLOSEST_IF_BOTH, BOTH) '''List of all the available roundings.'''
"""Defines different rounding options for binary search.""" class Rounding: """Base class for rounding options for binary search.""" class Both(Rounding): """ Get a tuple `(low, high)` of the 2 items that surround the specified value. If there's an exact match, gives it twice in the tuple, i.e. `(match, match)`. """ class Exact(Rounding): """Get the item that has exactly the same value has the specified value.""" class Closest(Rounding): """Get the item which has a value closest to the specified value.""" class Low(Rounding): """ Get the item with a value that is just below the specified value. i.e. the highest item which has a value lower or equal to the specified value. """ class High(Rounding): """ Get the item with a value that is just above the specified value. i.e. the lowest item which has a value higher or equal to the specified value. """ class Low_If_Both(Rounding): """ Get the item with a value that is just below the specified value. i.e. the highest item which has a value lower or equal to the specified value. Before it returns the item, it checks if there also exists an item with a value *higher* than the specified value or equal to it. If there isn't, it returns `None`. (If there's an exact match, this rounding will return it.) """ class High_If_Both(Rounding): """ Get the item with a value that is just above the specified value. i.e. the lowest item which has a value higher or equal to the specified value. Before it returns the item, it checks if there also exists an item with a value *lower* than the specified value or equal to it. If there isn't, it returns `None`. (If there's an exact match, this rounding will return it.) """ class Closest_If_Both(Rounding): """ Get the item which has a value closest to the specified value. Before it returns the item, it checks if there also exists an item which is "on the other side" of the specified value. e.g. if the closest item is higher than the specified item, it will confirm that there exists an item *below* the specified value. (And vice versa.) If there isn't it returns `None`. (If there's an exact match, this rounding will return it.) """ class Low_Otherwise_High(Rounding): """ Get the item with a value that is just below the specified value. i.e. the highest item which has a value lower or equal to the specified value. If there is no item below, give the one just above. (If there's an exact match, this rounding will return it.) """ class High_Otherwise_Low(Rounding): """ Get the item with a value that is just above the specified value. i.e. the lowest item which has a value higher or equal to the specified value. If there is no item above, give the one just below. (If there's an exact match, this rounding will return it.) """ roundings = (LOW, LOW_IF_BOTH, LOW_OTHERWISE_HIGH, HIGH, HIGH_IF_BOTH, HIGH_OTHERWISE_LOW, EXACT, CLOSEST, CLOSEST_IF_BOTH, BOTH) 'List of all the available roundings.'
expected_output = { "interfaces": { "GigabitEthernet1/0/1": { "name": "foo bar", "down_time": "00:00:00", "up_time": "4d5h", }, } }
expected_output = {'interfaces': {'GigabitEthernet1/0/1': {'name': 'foo bar', 'down_time': '00:00:00', 'up_time': '4d5h'}}}
data = [ [0, 'Does your animal fly?', 1, 2], [1, 'Is your flying animal a bird?', 3, 4], [2, 'Does your animal live underwater?', 7, 8], [3, 'Is your bird native to Australia?', 5, 6], [4, 'Is it a fruit bat?'], [5, 'Is it a kookaburra?'], [6, 'Is it a blue jay?'], [7, 'Is your animal a mammal?', 9, 10], [8, 'Is it a wombat?'], [9, 'Is it a blue whale?'], [10, 'Is it a goldfish?'], ] i = 0 while True: question = data[i][1] x = input(question + ' ') if len(data[i]) == 2: break if x == 'y': i = data[i][2] if x == 'n': i = data[i][3] print('Thanks for playing')
data = [[0, 'Does your animal fly?', 1, 2], [1, 'Is your flying animal a bird?', 3, 4], [2, 'Does your animal live underwater?', 7, 8], [3, 'Is your bird native to Australia?', 5, 6], [4, 'Is it a fruit bat?'], [5, 'Is it a kookaburra?'], [6, 'Is it a blue jay?'], [7, 'Is your animal a mammal?', 9, 10], [8, 'Is it a wombat?'], [9, 'Is it a blue whale?'], [10, 'Is it a goldfish?']] i = 0 while True: question = data[i][1] x = input(question + ' ') if len(data[i]) == 2: break if x == 'y': i = data[i][2] if x == 'n': i = data[i][3] print('Thanks for playing')
def riverSizes(matrix): # Write your code here. if not matrix: return [] sizes=[] visited=[[False for values in row] for row in matrix] for i in range(len(matrix)): for j in range(len(matrix[0])): if visited[i][j]: continue getSize(i,j,visited,matrix,sizes) return sizes def getSize(i,j,visited,matrix,sizes): currentRiverSize=0 nodesToExplore=[[i,j]] while nodesToExplore: currentNode=nodesToExplore.pop() x,y=currentNode if visited[x][y]: continue visited[x][y]=True if matrix[x][y]==0: continue currentRiverSize+=1 unvisitedNeighbours=getNeighbours(x,y,visited,matrix) for nodes in unvisitedNeighbours: nodesToExplore.append(nodes) if currentRiverSize>0: sizes.append(currentRiverSize) def getNeighbours(i,j,visited,matrix): toReturn =[] if i>0 and not visited[i-1][j]: toReturn.append([i-1,j]) if i<len(matrix)-1 and not visited[i+1][j]: toReturn.append([i+1,j]) if j>0 and not visited[i][j-1]: toReturn.append([i,j-1]) if j<len(matrix[0])-1 and not visited[i][j+1]: toReturn.append([i,j+1]) return toReturn
def river_sizes(matrix): if not matrix: return [] sizes = [] visited = [[False for values in row] for row in matrix] for i in range(len(matrix)): for j in range(len(matrix[0])): if visited[i][j]: continue get_size(i, j, visited, matrix, sizes) return sizes def get_size(i, j, visited, matrix, sizes): current_river_size = 0 nodes_to_explore = [[i, j]] while nodesToExplore: current_node = nodesToExplore.pop() (x, y) = currentNode if visited[x][y]: continue visited[x][y] = True if matrix[x][y] == 0: continue current_river_size += 1 unvisited_neighbours = get_neighbours(x, y, visited, matrix) for nodes in unvisitedNeighbours: nodesToExplore.append(nodes) if currentRiverSize > 0: sizes.append(currentRiverSize) def get_neighbours(i, j, visited, matrix): to_return = [] if i > 0 and (not visited[i - 1][j]): toReturn.append([i - 1, j]) if i < len(matrix) - 1 and (not visited[i + 1][j]): toReturn.append([i + 1, j]) if j > 0 and (not visited[i][j - 1]): toReturn.append([i, j - 1]) if j < len(matrix[0]) - 1 and (not visited[i][j + 1]): toReturn.append([i, j + 1]) return toReturn
# G00364712 Robert Higgins - Exercise 2 # Collatz Conjecture https://en.wikipedia.org/wiki/Collatz_conjecture nStr = input("Enter a positive integer:") n = int(nStr) while n > 1: if n % 2 == 0: n = n/2 print(int(n)) else: n = (3*n) + 1 print(int(n)) # Output below for user input 23 # Enter a positive integer:23 # 70 # 35 # 106 # 53 # 160 # 80 # 40 # 20 # 10 # 5 # 16 # 8 # 4 # 2 # 1
n_str = input('Enter a positive integer:') n = int(nStr) while n > 1: if n % 2 == 0: n = n / 2 print(int(n)) else: n = 3 * n + 1 print(int(n))
def functie(l,n): for a in range(1,n+1): l.append(a**n) list=[] n = int(input("n = ")) functie(list,n) print(list)
def functie(l, n): for a in range(1, n + 1): l.append(a ** n) list = [] n = int(input('n = ')) functie(list, n) print(list)
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( A , arr_size , sum ) : for i in range ( 0 , arr_size - 1 ) : s = set ( ) curr_sum = sum - A [ i ] for j in range ( i + 1 , arr_size ) : if ( curr_sum - A [ j ] ) in s : print ( "Triplet is" , A [ i ] , ", " , A [ j ] , ", " , curr_sum - A [ j ] ) return True s.add ( A [ j ] ) return False #TOFILL if __name__ == '__main__': param = [ ([1, 6, 8, 8, 9, 11, 13, 13, 15, 17, 21, 24, 38, 38, 42, 43, 46, 46, 47, 54, 55, 56, 57, 58, 60, 60, 60, 62, 63, 63, 65, 66, 67, 67, 69, 81, 84, 84, 85, 86, 95, 99],27,24,), ([20, -86, -24, 38, -32, -64, -72, 72, 68, 94, 18, -60, -4, -18, -18, -70, 6, -86, 46, -16, 46, -28],21,20,), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1],17,13,), ([13, 96, 31, 39, 23, 39, 50, 10, 21, 64, 41, 54, 44, 97, 24, 91, 79, 86, 38, 49, 77, 71, 8, 98, 85, 36, 37, 65, 42, 48],17,18,), ([-86, -68, -58, -56, -54, -54, -48, -40, -36, -32, -26, -16, -14, -12, -12, -4, -4, -4, 0, 10, 22, 22, 30, 54, 62, 68, 88, 88],21,25,), ([0, 1, 1, 1, 1, 0, 0],5,3,), ([8, 8, 9, 13, 20, 24, 29, 52, 53, 96],9,8,), ([18, -92, -10, 26, 58, -48, 38, 66, -98, -72, 4, 76, -52, 20, 60, -56, 96, 60, -10, -26, -64, -66, -22, -86, 74, 82, 2, -14, 76, 82, 40, 70, -40, -2, -46, -38, 22, 98, 58],30,30,), ([1, 1, 1, 1],2,2,), ([72],0,0,) ] n_success = 0 for i, parameters_set in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success+=1 print("#Results: %i, %i" % (n_success, len(param)))
def f_gold(A, arr_size, sum): for i in range(0, arr_size - 1): s = set() curr_sum = sum - A[i] for j in range(i + 1, arr_size): if curr_sum - A[j] in s: print('Triplet is', A[i], ', ', A[j], ', ', curr_sum - A[j]) return True s.add(A[j]) return False if __name__ == '__main__': param = [([1, 6, 8, 8, 9, 11, 13, 13, 15, 17, 21, 24, 38, 38, 42, 43, 46, 46, 47, 54, 55, 56, 57, 58, 60, 60, 60, 62, 63, 63, 65, 66, 67, 67, 69, 81, 84, 84, 85, 86, 95, 99], 27, 24), ([20, -86, -24, 38, -32, -64, -72, 72, 68, 94, 18, -60, -4, -18, -18, -70, 6, -86, 46, -16, 46, -28], 21, 20), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1], 17, 13), ([13, 96, 31, 39, 23, 39, 50, 10, 21, 64, 41, 54, 44, 97, 24, 91, 79, 86, 38, 49, 77, 71, 8, 98, 85, 36, 37, 65, 42, 48], 17, 18), ([-86, -68, -58, -56, -54, -54, -48, -40, -36, -32, -26, -16, -14, -12, -12, -4, -4, -4, 0, 10, 22, 22, 30, 54, 62, 68, 88, 88], 21, 25), ([0, 1, 1, 1, 1, 0, 0], 5, 3), ([8, 8, 9, 13, 20, 24, 29, 52, 53, 96], 9, 8), ([18, -92, -10, 26, 58, -48, 38, 66, -98, -72, 4, 76, -52, 20, 60, -56, 96, 60, -10, -26, -64, -66, -22, -86, 74, 82, 2, -14, 76, 82, 40, 70, -40, -2, -46, -38, 22, 98, 58], 30, 30), ([1, 1, 1, 1], 2, 2), ([72], 0, 0)] n_success = 0 for (i, parameters_set) in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success += 1 print('#Results: %i, %i' % (n_success, len(param)))
# ------- MAIN SETTINGS ----------- # SQLITE_DB_PATH = u'/Users/sidhshar/Downloads/dbstore/pp.sqlite' JSON_DATA_FILENAME = 'pp.json' MASTER_JSON_FILENAME = 'master.json' STOP_COUNT = 2 # ------- STORAGE SETTINGS ----------- # INPUT_STORE_DIRECTORY = u'/Users/sidhshar/Downloads/photodirip' OUTPUT_STORE_DIRECTORY = u'/Users/sidhshar/Downloads/photodirop' TYPE_JPG_FAMILY = ('jpg', 'jpeg') TYPE_VIDEO_FAMILY = ('mp4,' '3gp,') ALLOWED_EXTENSIONS = () # TYPE_JPG_FAMILY + TYPE_VIDEO_FAMILY
sqlite_db_path = u'/Users/sidhshar/Downloads/dbstore/pp.sqlite' json_data_filename = 'pp.json' master_json_filename = 'master.json' stop_count = 2 input_store_directory = u'/Users/sidhshar/Downloads/photodirip' output_store_directory = u'/Users/sidhshar/Downloads/photodirop' type_jpg_family = ('jpg', 'jpeg') type_video_family = 'mp4,3gp,' allowed_extensions = ()
def make_key(*args): return "ti:" + ":".join(args) def make_refset_key(pmid): return make_key("article", pmid, "refset")
def make_key(*args): return 'ti:' + ':'.join(args) def make_refset_key(pmid): return make_key('article', pmid, 'refset')
#!/usr/bin/env python # coding: utf-8 # This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). # # Solution Notebook # ## Problem: Find an element in a sorted array that has been rotated a number of times. # # * [Constraints](#Constraints) # * [Test Cases](#Test-Cases) # * [Algorithm](#Algorithm) # * [Code](#Code) # * [Unit Test](#Unit-Test) # ## Constraints # # * Is the input an array of ints? # * Yes # * Can the input have duplicates? # * Yes # * Do we know how many times the array was rotated? # * No # * Was the array originally sorted in increasing or decreasing order? # * Increasing # * For the output, do we return the index? # * Yes # * Can we assume the inputs are valid? # * No # * Can we assume this fits memory? # * Yes # ## Test Cases # # * None -> Exception # * [] -> None # * Not found -> None # * General case with duplicates # * General case without duplicates # ## Algorithm # # ### General case without dupes # # <pre> # # index 0 1 2 3 4 5 6 7 8 9 # input [ 1, 3, 5, 6, 7, 8, 9, 10, 12, 14] # input rotated 1x [10, 12, 14, 1, 3, 5, 6, 7, 8, 9] # input rotated 2x [ 5, 6, 7, 8, 9, 10, 12, 14, 1, 3] # input rotated 3x [10, 12, 14, 1, 3, 5, 6, 7, 8, 9] # # find 1 # len = 10 # mid = 10 // 2 = 5 # s m e # index 0 1 2 3 4 5 6 7 8 9 # input [10, 12, 14, 1, 3, 5, 6, 7, 8, 9] # # input[start] > input[mid]: Left half is rotated # input[end] >= input[mid]: Right half is sorted # 1 is not within input[mid+1] to input[end] on the right side, go left # # s m e # index 0 1 2 3 4 5 6 7 8 9 # input [10, 12, 14, 1, 3, 5, 6, 7, 8, 9] # # input[start] <= input[mid]: Right half is rotated # input[end] >= input[mid]: Left half is sorted # 1 is not within input[left] to input[mid-1] on the left side, go right # # </pre> # # ### General case with dupes # # <pre> # # s m e # index 0 1 2 3 4 5 6 7 8 9 # input [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 2] # # input[start] == input[mid], input[mid] != input[end], go right # # input rotated 1x [ 1, 1, 2, 1, 1, 1, 1, 1, 1, 1] # # input[start] == input[mid] == input[end], search both sides # # </pre> # # Complexity: # * Time: O(log n) if there are no duplicates, else O(n) # * Space: O(m), where m is the recursion depth # ## Code # In[1]: class Array(object): def search_sorted_array(self, array, val): if array is None or val is None: raise TypeError('array or val cannot be None') if not array: return None return self._search_sorted_array(array, val, start=0, end=len(array) - 1) def _search_sorted_array(self, array, val, start, end): if end < start: return None mid = (start + end) // 2 if array[mid] == val: return mid # Left side is sorted if array[start] < array[mid]: if array[start] <= val < array[mid]: return self._search_sorted_array(array, val, start, mid - 1) else: return self._search_sorted_array(array, val, mid + 1, end) # Right side is sorted elif array[start] > array[mid]: if array[mid] < val <= array[end]: return self._search_sorted_array(array, val, mid + 1, end) else: return self._search_sorted_array(array, val, start, mid - 1) # Duplicates else: if array[mid] != array[end]: return self._search_sorted_array(array, val, mid + 1, end) else: result = self._search_sorted_array(array, val, start, mid - 1) if result != None: return result else: return self._search_sorted_array(array, val, mid + 1, end) # ## Unit Test # In[2]: get_ipython().run_cell_magic('writefile', 'test_search_sorted_array.py', "import unittest\n\n\nclass TestArray(unittest.TestCase):\n\n def test_search_sorted_array(self):\n array = Array()\n self.assertRaises(TypeError, array.search_sorted_array, None)\n self.assertEqual(array.search_sorted_array([3, 1, 2], 0), None)\n self.assertEqual(array.search_sorted_array([3, 1, 2], 0), None)\n data = [10, 12, 14, 1, 3, 5, 6, 7, 8, 9]\n self.assertEqual(array.search_sorted_array(data, val=1), 3)\n data = [ 1, 1, 2, 1, 1, 1, 1, 1, 1, 1]\n self.assertEqual(array.search_sorted_array(data, val=2), 2)\n print('Success: test_search_sorted_array')\n\n\ndef main():\n test = TestArray()\n test.test_search_sorted_array()\n\n\nif __name__ == '__main__':\n main()") # In[3]: get_ipython().run_line_magic('run', '-i test_search_sorted_array.py')
class Array(object): def search_sorted_array(self, array, val): if array is None or val is None: raise type_error('array or val cannot be None') if not array: return None return self._search_sorted_array(array, val, start=0, end=len(array) - 1) def _search_sorted_array(self, array, val, start, end): if end < start: return None mid = (start + end) // 2 if array[mid] == val: return mid if array[start] < array[mid]: if array[start] <= val < array[mid]: return self._search_sorted_array(array, val, start, mid - 1) else: return self._search_sorted_array(array, val, mid + 1, end) elif array[start] > array[mid]: if array[mid] < val <= array[end]: return self._search_sorted_array(array, val, mid + 1, end) else: return self._search_sorted_array(array, val, start, mid - 1) elif array[mid] != array[end]: return self._search_sorted_array(array, val, mid + 1, end) else: result = self._search_sorted_array(array, val, start, mid - 1) if result != None: return result else: return self._search_sorted_array(array, val, mid + 1, end) get_ipython().run_cell_magic('writefile', 'test_search_sorted_array.py', "import unittest\n\n\nclass TestArray(unittest.TestCase):\n\n def test_search_sorted_array(self):\n array = Array()\n self.assertRaises(TypeError, array.search_sorted_array, None)\n self.assertEqual(array.search_sorted_array([3, 1, 2], 0), None)\n self.assertEqual(array.search_sorted_array([3, 1, 2], 0), None)\n data = [10, 12, 14, 1, 3, 5, 6, 7, 8, 9]\n self.assertEqual(array.search_sorted_array(data, val=1), 3)\n data = [ 1, 1, 2, 1, 1, 1, 1, 1, 1, 1]\n self.assertEqual(array.search_sorted_array(data, val=2), 2)\n print('Success: test_search_sorted_array')\n\n\ndef main():\n test = TestArray()\n test.test_search_sorted_array()\n\n\nif __name__ == '__main__':\n main()") get_ipython().run_line_magic('run', '-i test_search_sorted_array.py')
def iterable(source): def callbag(start, sink): if (start != 0): return for i in source: sink(1, i) return callbag
def iterable(source): def callbag(start, sink): if start != 0: return for i in source: sink(1, i) return callbag
'''1. Write a Python program to check the sum of three elements (each from an array) from three arrays is equal to a target value. Print all those three-element combinations. Sample data: /* X = [10, 20, 20, 20] Y = [10, 20, 30, 40] Z = [10, 30, 40, 20] target = 70 */ ''' X = [10, 20, 20, 20] Y = [10, 20, 30, 40] Z = [10, 30, 40, 20] for x in X: for y in Y: for z in Z: if x+y+z==70: print((x, y, z))
"""1. Write a Python program to check the sum of three elements (each from an array) from three arrays is equal to a target value. Print all those three-element combinations. Sample data: /* X = [10, 20, 20, 20] Y = [10, 20, 30, 40] Z = [10, 30, 40, 20] target = 70 */ """ x = [10, 20, 20, 20] y = [10, 20, 30, 40] z = [10, 30, 40, 20] for x in X: for y in Y: for z in Z: if x + y + z == 70: print((x, y, z))
def request_numbers(): numbers = [] for n in range(3): number = float(input("Number: ")) numbers.append(number) return numbers def main(): numbers = request_numbers() ordered = list(sorted(numbers)) if numbers == ordered: print("Aumentando") elif numbers == ordered[::-1]: print("Disminiyendo") else: print("Ninguno") if __name__ == '__main__': main()
def request_numbers(): numbers = [] for n in range(3): number = float(input('Number: ')) numbers.append(number) return numbers def main(): numbers = request_numbers() ordered = list(sorted(numbers)) if numbers == ordered: print('Aumentando') elif numbers == ordered[::-1]: print('Disminiyendo') else: print('Ninguno') if __name__ == '__main__': main()
## ## Karkinos - b0bb ## ## https://twitter.com/0xb0bb ## https://github.com/0xb0bb/karkinos ## MAJOR_VERSION = 0 MINOR_VERSION = 2 KARKINOS_VERSION = 'Karkinos v%d.%d' % (MAJOR_VERSION, MINOR_VERSION)
major_version = 0 minor_version = 2 karkinos_version = 'Karkinos v%d.%d' % (MAJOR_VERSION, MINOR_VERSION)
#!/usr/bin/env python3 if __name__ == '__main__': numbers = [[6, 1, 6], [6], [5, 6, 6], [5], [4], [7, 5, 7, 2], [5, 8], [9], [7], [5, 6], [3, 4], [8], [4, 9, 3, 6], [8, 2, 4], [9, 7], [6, 8], [2, 5], [2, 4], [8, 3, 4], [5, 2], [4], [4, 4, 5, 5], [5, 1], [1, 4, 8], [6, 5], [5, 7, 8, 9], [1], [6], [3], [6], [7, 3, 8, 8], [6], [2, 5, 4], [7], [3, 7], [1, 9, 1, 1], [2, 6, 2], [2, 7, 5], [6, 3, 7], [6, 1], [6, 3, 9, 7], [4, 3, 3]] squares = [sum([n**2 for n in subnumbers]) for subnumbers in numbers] print(squares)
if __name__ == '__main__': numbers = [[6, 1, 6], [6], [5, 6, 6], [5], [4], [7, 5, 7, 2], [5, 8], [9], [7], [5, 6], [3, 4], [8], [4, 9, 3, 6], [8, 2, 4], [9, 7], [6, 8], [2, 5], [2, 4], [8, 3, 4], [5, 2], [4], [4, 4, 5, 5], [5, 1], [1, 4, 8], [6, 5], [5, 7, 8, 9], [1], [6], [3], [6], [7, 3, 8, 8], [6], [2, 5, 4], [7], [3, 7], [1, 9, 1, 1], [2, 6, 2], [2, 7, 5], [6, 3, 7], [6, 1], [6, 3, 9, 7], [4, 3, 3]] squares = [sum([n ** 2 for n in subnumbers]) for subnumbers in numbers] print(squares)
SEPN = f"\n{'=' * 40}" SEP = f"{SEPN}\n" QUERY_SPLIT_SIZE = 5000 SEQUENCE = 'sequence' TABLE = 'table' PRIMARY = 'primary' UNIQUE = 'unique' FOREIGN = 'foreign'
sepn = f"\n{'=' * 40}" sep = f'{SEPN}\n' query_split_size = 5000 sequence = 'sequence' table = 'table' primary = 'primary' unique = 'unique' foreign = 'foreign'
# Numbers in Python can be of two types: Integers and Floats # They're very important as many ML algorithms can only deal # with numbers and will ignore/crash on any other kind of input # because they're based complex math algorithms # Integers have unbound size in Python 3! lucky_number = 13 universe_number = 42 # Floats are numbers that have a decimal point! pi = 3.14 a_third = 0.333 # We can do basic math calculations using the operators / + - * % and ** times_two = lucky_number * 2 square = universe_number ** 2 mod = 3 % 2 # results in the remainder of the division of 3 by 2 (1 in this case) # In the example below we calculate the area of a circle radius = 50 area_of_circle = pi * (radius ** 2) print(area_of_circle)
lucky_number = 13 universe_number = 42 pi = 3.14 a_third = 0.333 times_two = lucky_number * 2 square = universe_number ** 2 mod = 3 % 2 radius = 50 area_of_circle = pi * radius ** 2 print(area_of_circle)
# Runs all 1d datasets. Experiment(description='Run all 1D datasets', data_dir='../data/1d_data/', max_depth=8, random_order=False, k=2, debug=False, local_computation=True, n_rand=3, sd=4, max_jobs=500, verbose=True, make_predictions=False, skip_complete=True, results_dir='../results/Feb 10 1D results/', iters=200)
experiment(description='Run all 1D datasets', data_dir='../data/1d_data/', max_depth=8, random_order=False, k=2, debug=False, local_computation=True, n_rand=3, sd=4, max_jobs=500, verbose=True, make_predictions=False, skip_complete=True, results_dir='../results/Feb 10 1D results/', iters=200)
# 1.2 Palindrome Tester def is_palindrome(input_string): length = len(input_string) palindrome = True for i in range(0, length // 2): if input_string[i] != input_string[length - i - 1]: palindrome = False return palindrome
def is_palindrome(input_string): length = len(input_string) palindrome = True for i in range(0, length // 2): if input_string[i] != input_string[length - i - 1]: palindrome = False return palindrome
class Gurney: def greeting(self): print('welcome to Simple Calculator Alpha 0.1') def main(self): firstNumber = float(input('Enter your first number: ')) operator = float(input('enter your operator: ')) secondNumber = float(input('Enter your third number:')) if (operator == '+'): simpleCalculator.add(self, firstNumber, operator, secondNumber) elif (operator == '-'): simpleCalculator.subtract(self, firstNumber, operator, secondNumber) elif (operator == '*'): simplecalculator.mult(self, firstNumber, operator, secondNumber) elif (operator == '/'): simplecalculator.mult(self, firstNumber, operator, secondNumber) def add(self, firstNumber, operator, secondNumber): print(firstNumber, '+', secondNumber, '=', firstNumber + secondNumber) def subtract(self, firstNumber, operator, secondNumber): print(firstNumber, '-', secondNumber, '=', firstNumber - secondNUmber) def mult(self, firstNumber, operator, secondNumber): print(firstNumber, '*', secondNumber, '=', firstNumber * secondNumber) def div(self, firstNumber, operator, secondNumber): print(firstNumber, '/', secondNumber, '=', firstNumber / secondNumber) class Daniel: def __init__(self): self.user_string = '' def loop(self): while True: arg = input('-> ') if arg == 'quit': print(self.user_string) break else: self.user_string += arg class Jonathan: def __init__(self): self.user_string = '' def add(self, uno, dos): addop = uno + dos return addop def subtract(self, num1, num2): subop = num1 - num2 return subop def multiply(self, num1, num2): multop = num1 * num2 return multop def divide(self, num1, num2): divop = num1 / num2 return divop def main(self): print('ezpz calculatorino') while True: num1 = int(input('Enter your first number: ')) op = input('Choose an operator(+,-,*,/)') num2 = int(input('Enter your second number: ')) if (op == '+'): answer = Jonathan().add( num1, num2) print(num1, "+", num2, "=", answer) break elif (op == '-'): answer = Jonathan().subtract(num1, num2) print(num1, "-", num2, "=", answer) break elif (op == '*'): answer = Jonathan().multiply(num1, num2) print(num1, "*", num2, "=", answer) break elif (op == '/'): answer = Jonathan().divide(num1, num2) print(num1, "/", num2, "=", answer) break else: print('invalid string') if __name__ == '__main__': g = Gurney() g.loop() d = Daniel() d.loop() j = Jonathan() j.main()
class Gurney: def greeting(self): print('welcome to Simple Calculator Alpha 0.1') def main(self): first_number = float(input('Enter your first number: ')) operator = float(input('enter your operator: ')) second_number = float(input('Enter your third number:')) if operator == '+': simpleCalculator.add(self, firstNumber, operator, secondNumber) elif operator == '-': simpleCalculator.subtract(self, firstNumber, operator, secondNumber) elif operator == '*': simplecalculator.mult(self, firstNumber, operator, secondNumber) elif operator == '/': simplecalculator.mult(self, firstNumber, operator, secondNumber) def add(self, firstNumber, operator, secondNumber): print(firstNumber, '+', secondNumber, '=', firstNumber + secondNumber) def subtract(self, firstNumber, operator, secondNumber): print(firstNumber, '-', secondNumber, '=', firstNumber - secondNUmber) def mult(self, firstNumber, operator, secondNumber): print(firstNumber, '*', secondNumber, '=', firstNumber * secondNumber) def div(self, firstNumber, operator, secondNumber): print(firstNumber, '/', secondNumber, '=', firstNumber / secondNumber) class Daniel: def __init__(self): self.user_string = '' def loop(self): while True: arg = input('-> ') if arg == 'quit': print(self.user_string) break else: self.user_string += arg class Jonathan: def __init__(self): self.user_string = '' def add(self, uno, dos): addop = uno + dos return addop def subtract(self, num1, num2): subop = num1 - num2 return subop def multiply(self, num1, num2): multop = num1 * num2 return multop def divide(self, num1, num2): divop = num1 / num2 return divop def main(self): print('ezpz calculatorino') while True: num1 = int(input('Enter your first number: ')) op = input('Choose an operator(+,-,*,/)') num2 = int(input('Enter your second number: ')) if op == '+': answer = jonathan().add(num1, num2) print(num1, '+', num2, '=', answer) break elif op == '-': answer = jonathan().subtract(num1, num2) print(num1, '-', num2, '=', answer) break elif op == '*': answer = jonathan().multiply(num1, num2) print(num1, '*', num2, '=', answer) break elif op == '/': answer = jonathan().divide(num1, num2) print(num1, '/', num2, '=', answer) break else: print('invalid string') if __name__ == '__main__': g = gurney() g.loop() d = daniel() d.loop() j = jonathan() j.main()
symbology = 'code93' cases = [ ('001.png', 'CODE93', dict(includetext=True)), ('002.png', 'CODE93^SFT/A', dict(parsefnc=True, includecheck=True)), ]
symbology = 'code93' cases = [('001.png', 'CODE93', dict(includetext=True)), ('002.png', 'CODE93^SFT/A', dict(parsefnc=True, includecheck=True))]
class Solution: def minimumDeletions(self, s: str) -> int: n = len(s) a = 0 res = 0 for i in range(n - 1, -1, -1): if s[i] == 'a': a += 1 elif s[i] == 'b': if a > 0: a -= 1 res += 1 return res s = "aababbab" res = Solution().minimumDeletions(s) print(res)
class Solution: def minimum_deletions(self, s: str) -> int: n = len(s) a = 0 res = 0 for i in range(n - 1, -1, -1): if s[i] == 'a': a += 1 elif s[i] == 'b': if a > 0: a -= 1 res += 1 return res s = 'aababbab' res = solution().minimumDeletions(s) print(res)
num1=100 num2=200 num3=300 a b c 1 2 3 ttttt e f g 9 8 7
num1 = 100 num2 = 200 num3 = 300 a b c 1 2 3 ttttt e f g 9 8 7
#Find the Runner-Up Score! if __name__ == '__main__': n = int(raw_input()) arr = map(int, raw_input().split()) arr=sorted(arr) a=arr[0] b=arr[0] for i in range(1,n): if(arr[i]==a): pass elif(arr[i]>a): a=arr[i] b=arr[i-1] print(b)
if __name__ == '__main__': n = int(raw_input()) arr = map(int, raw_input().split()) arr = sorted(arr) a = arr[0] b = arr[0] for i in range(1, n): if arr[i] == a: pass elif arr[i] > a: a = arr[i] b = arr[i - 1] print(b)
# Variables that contains the user credentials to access Twitter API ACCESS_TOKEN = "" ACCESS_TOKEN_SECRET = "" CONSUMER_KEY = "" CONSUMER_SECRET = ""
access_token = '' access_token_secret = '' consumer_key = '' consumer_secret = ''
SECRET_KEY = '\xa6\xbaG\x80\xc9-$s\xd5~\x031N\x8f\xd9/\x88\xd0\xba#B\x9c\xcd_' DEBUG = False DB_HOST = 'localhost' DB_USER = 'grupo35' DB_PASS = 'OTRiYWJhYjU3YWMy' DB_NAME = 'grupo35' SQLALCHEMY_DATABASE_URI = 'mysql://grupo35:OTRiYWJhYjU3YWMy@localhost/grupo35' SQLALCHEMY_TRACK_MODIFICATIONS = False
secret_key = '¦ºG\x80É-$sÕ~\x031N\x8fÙ/\x88к#B\x9cÍ_' debug = False db_host = 'localhost' db_user = 'grupo35' db_pass = 'OTRiYWJhYjU3YWMy' db_name = 'grupo35' sqlalchemy_database_uri = 'mysql://grupo35:OTRiYWJhYjU3YWMy@localhost/grupo35' sqlalchemy_track_modifications = False
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def inorderTraversal(self, root: 'TreeNode') -> 'List[int]': out = [] self.traverse(root, out) return out def traverse(self, root, out): if root: self.traverse(root.left, out) out.append(root.val) self.traverse(root.right, out)
class Solution: def inorder_traversal(self, root: 'TreeNode') -> 'List[int]': out = [] self.traverse(root, out) return out def traverse(self, root, out): if root: self.traverse(root.left, out) out.append(root.val) self.traverse(root.right, out)
# Created by MechAviv # Quest ID :: 17620 # [Commerci Republic] Eye for an Eye sm.setSpeakerID(9390217) sm.sendNext("Now, what dream can I make come true for you? Remember, anything in the entire world is yours for the asking.") sm.setSpeakerID(9390217) sm.setPlayerAsSpeaker() sm.sendSay("Can you introduce me to Gilberto Daniella?") sm.setSpeakerID(9390217) sm.sendSay("I offer to make your wildest dreams come true, and that is what you want?") # Unhandled Stat Changed [MP] Packet: 00 00 00 10 00 00 00 00 00 00 C6 0A 00 00 FF 00 00 00 00 sm.setSpeakerID(9390217) sm.setPlayerAsSpeaker() sm.sendSay("Yup, I really want to meet #bGILBERTO DANIELLA#k.") sm.setSpeakerID(9390217) sm.sendSay("I heard you the first time. It's just...") sm.setSpeakerID(9390217) sm.setPlayerAsSpeaker() sm.sendSay("What?") sm.setSpeakerID(9390217) sm.sendSay("Well, I thought you'd ask for something difficult, like borrowing my hat.") sm.setSpeakerID(9390217) sm.setPlayerAsSpeaker() sm.sendSay("That was next on my list.") sm.setSpeakerID(9390217) if sm.sendAskYesNo("To get to the Daniella Merchant Union office, head east from this spot, past the town fountain. It's the white building with golden ornamentation."): sm.setSpeakerID(9390217) sm.sendNext("I'll let them know you're on your way. Be polite when you talk to Gilberto. He is quite powerful in Commerci.") sm.startQuest(17620) else: sm.setSpeakerID(9390217) sm.sendSayOkay("Still sorting through your deepest desires? Let me know when you know what you want.")
sm.setSpeakerID(9390217) sm.sendNext('Now, what dream can I make come true for you? Remember, anything in the entire world is yours for the asking.') sm.setSpeakerID(9390217) sm.setPlayerAsSpeaker() sm.sendSay('Can you introduce me to Gilberto Daniella?') sm.setSpeakerID(9390217) sm.sendSay('I offer to make your wildest dreams come true, and that is what you want?') sm.setSpeakerID(9390217) sm.setPlayerAsSpeaker() sm.sendSay('Yup, I really want to meet #bGILBERTO DANIELLA#k.') sm.setSpeakerID(9390217) sm.sendSay("I heard you the first time. It's just...") sm.setSpeakerID(9390217) sm.setPlayerAsSpeaker() sm.sendSay('What?') sm.setSpeakerID(9390217) sm.sendSay("Well, I thought you'd ask for something difficult, like borrowing my hat.") sm.setSpeakerID(9390217) sm.setPlayerAsSpeaker() sm.sendSay('That was next on my list.') sm.setSpeakerID(9390217) if sm.sendAskYesNo("To get to the Daniella Merchant Union office, head east from this spot, past the town fountain. It's the white building with golden ornamentation."): sm.setSpeakerID(9390217) sm.sendNext("I'll let them know you're on your way. Be polite when you talk to Gilberto. He is quite powerful in Commerci.") sm.startQuest(17620) else: sm.setSpeakerID(9390217) sm.sendSayOkay('Still sorting through your deepest desires? Let me know when you know what you want.')
#!/usr/bin/env python3 f = "day10.input.txt" # f = "day10.ex.txt" ns = open(f).read().strip().split("\n") ns = [int(x) for x in ns] ns.sort() ns.insert(0, 0) ns.append(max(ns) + 3) def part1(): count1 = 0 count3 = 0 for i in range(len(ns) - 1): diff = ns[i + 1] - ns[i] if diff == 1: count1 += 1 if diff == 3: count3 += 1 return count1 * count3 checked = {} def get_num_ways(pos): # last if pos == len(ns) - 1: return 1 if pos in checked: return checked[pos] total = 0 for i in range(pos + 1, len(ns)): if ns[i] - ns[pos] <= 3: total += get_num_ways(i) checked[pos] = total return total def part2(): return get_num_ways(0) print(part1()) print(part2())
f = 'day10.input.txt' ns = open(f).read().strip().split('\n') ns = [int(x) for x in ns] ns.sort() ns.insert(0, 0) ns.append(max(ns) + 3) def part1(): count1 = 0 count3 = 0 for i in range(len(ns) - 1): diff = ns[i + 1] - ns[i] if diff == 1: count1 += 1 if diff == 3: count3 += 1 return count1 * count3 checked = {} def get_num_ways(pos): if pos == len(ns) - 1: return 1 if pos in checked: return checked[pos] total = 0 for i in range(pos + 1, len(ns)): if ns[i] - ns[pos] <= 3: total += get_num_ways(i) checked[pos] = total return total def part2(): return get_num_ways(0) print(part1()) print(part2())
def sub_dict(dic, *keys, **renames): d1 = {k: v for k, v in dic.items() if k in keys} d2 = {renames[k]: v for k, v in dic.items() if k in renames.keys()} return d1 | d2
def sub_dict(dic, *keys, **renames): d1 = {k: v for (k, v) in dic.items() if k in keys} d2 = {renames[k]: v for (k, v) in dic.items() if k in renames.keys()} return d1 | d2
# TODO: Figure out if this is even being used... class logging(object): def __init__(self, arg): super(logging, self).__init__() self.arg = arg
class Logging(object): def __init__(self, arg): super(logging, self).__init__() self.arg = arg
# https://www.codewars.com/kata/51ba717bb08c1cd60f00002f/train/python def solution(args): print(args) i = j = 0 result = [] section = [] while i < len(args): section.append(str(args[j])) while j + 1 < len(args) and args[j] + 1 == args[j + 1]: section.append(str(args[j + 1])) j += 1 if(len(section) > 2): result.append(section[0] + '-' + section[-1]) else: result.extend(section) i += len(section) j = i section = [] return ','.join(result)
def solution(args): print(args) i = j = 0 result = [] section = [] while i < len(args): section.append(str(args[j])) while j + 1 < len(args) and args[j] + 1 == args[j + 1]: section.append(str(args[j + 1])) j += 1 if len(section) > 2: result.append(section[0] + '-' + section[-1]) else: result.extend(section) i += len(section) j = i section = [] return ','.join(result)
''' Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter. Do not modify the linked list. Example 1: Input: head = [3,2,0,-4], pos = 1 Output: tail connects to node index 1 Explanation: There is a cycle in the linked list, where tail connects to the second node. Example 2: Input: head = [1,2], pos = 0 Output: tail connects to node index 0 Explanation: There is a cycle in the linked list, where tail connects to the first node. Example 3: Input: head = [1], pos = -1 Output: no cycle Explanation: There is no cycle in the linked list. '''
""" Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter. Do not modify the linked list. Example 1: Input: head = [3,2,0,-4], pos = 1 Output: tail connects to node index 1 Explanation: There is a cycle in the linked list, where tail connects to the second node. Example 2: Input: head = [1,2], pos = 0 Output: tail connects to node index 0 Explanation: There is a cycle in the linked list, where tail connects to the first node. Example 3: Input: head = [1], pos = -1 Output: no cycle Explanation: There is no cycle in the linked list. """
def is_a_leap_year(year): if (year % 400 == 0): return True elif (year % 100 == 0): return False elif (year % 4 == 0): return True return False def get_number_of_days(month, is_a_leap_year): if (month == 4 or month == 6 or month == 9 or month == 11): return 30 if (month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12): return 31 if is_a_leap_year: return 29 return 28 # Note: for the days, we go from 0 to 6 in order to use the modulo # Whereas for the months, we go from 1 to 12 for a more conventional notation # 1 Jan 1900 was a Monday day_on_1st_day_of_month = 0 number_of_matching_sundays = 0 # From 1900 to 2000 for current_year in range(1900, 2001): leap_year = is_a_leap_year(current_year) for month in range(1, 13): day_on_1st_day_of_month += get_number_of_days(month, leap_year) day_on_1st_day_of_month %= 7 if (day_on_1st_day_of_month == 6 and current_year > 1900 and not (current_year == 2000 and month == 12)): number_of_matching_sundays += 1 print(number_of_matching_sundays)
def is_a_leap_year(year): if year % 400 == 0: return True elif year % 100 == 0: return False elif year % 4 == 0: return True return False def get_number_of_days(month, is_a_leap_year): if month == 4 or month == 6 or month == 9 or (month == 11): return 30 if month == 1 or month == 3 or month == 5 or (month == 7) or (month == 8) or (month == 10) or (month == 12): return 31 if is_a_leap_year: return 29 return 28 day_on_1st_day_of_month = 0 number_of_matching_sundays = 0 for current_year in range(1900, 2001): leap_year = is_a_leap_year(current_year) for month in range(1, 13): day_on_1st_day_of_month += get_number_of_days(month, leap_year) day_on_1st_day_of_month %= 7 if day_on_1st_day_of_month == 6 and current_year > 1900 and (not (current_year == 2000 and month == 12)): number_of_matching_sundays += 1 print(number_of_matching_sundays)
class WordCount: # @param {str} line a text, for example "Bye Bye see you next" def mapper(self, _, line): # Write your code here # Please use 'yield key, value' for word in line.split(): yield word, 1 # @param key is from mapper # @param values is a set of value with the same key def reducer(self, key, values): # Write your code here # Please use 'yield key, value' yield key, sum(values)
class Wordcount: def mapper(self, _, line): for word in line.split(): yield (word, 1) def reducer(self, key, values): yield (key, sum(values))
CLIENT_ID = "affordability-c31256e5-39c4-4b20-905a-7500c583c591" CLIENT_SECRET = "eea983ac6dde3d1db86efe5793c7f6ec64b3d9c3ca6c81f4b71380109a723050" API_BASE = "https://api.nordicapigateway.com/" # If Python 2.x is used, only ASCII characters can be used in the values below. SECRET_KEY = "0401" # for local session storage. USERHASH = "test-user-id" INCLUDE_TRANSACTION_DETAILS = False # Set to True, if transaction details should be included. This requires special permissions for your client app!
client_id = 'affordability-c31256e5-39c4-4b20-905a-7500c583c591' client_secret = 'eea983ac6dde3d1db86efe5793c7f6ec64b3d9c3ca6c81f4b71380109a723050' api_base = 'https://api.nordicapigateway.com/' secret_key = '0401' userhash = 'test-user-id' include_transaction_details = False
MEDIA_INTENT = 'media' FEELING_INTENTS = ['smalltalk.appraisal.good', 'smalltalk.user.can_not_sleep', 'smalltalk.appraisal.thank_you', 'smalltalk.user.good', 'smalltalk.user.happy', 'smalltalk.user.sad', 'smalltalk.appraisal.bad', 'smalltalk.agent.happy', 'smalltalk.user.sick'] AFFIRMATION_INTENTS = ['yes', 'correct', 'smalltalk.dialog.correct', 'smalltalk.agent.right', 'smalltalk.appraisal.good'] NEGATION_INTENTS = ['no', 'wrong', 'smalltalk.dialog.wrong', 'skip', 'smalltalk.agent.wrong', 'smalltalk.dialog.wrong', 'smalltalk.appraisal.bad', 'repeat'] SMALLTALK_INTENTS = [ 'who_are_you', 'tell_a_joke', 'smalltalk.user.will_be_back', 'smalltalk.agent.be_clever', 'smalltalk.user.looks_like', 'smalltalk.user.sick', 'smalltalk.user.joking', 'smalltalk.greetings.nice_to_talk_to_you', 'smalltalk.agent.marry_user', 'smalltalk.agent.talk_to_me', 'smalltalk.user.has_birthday', 'smalltalk.user.wants_to_see_agent_again', 'smalltalk.user.happy', 'smalltalk.greetings.whatsup', 'smalltalk.agent.acquaintance', 'smalltalk.greetings.goodnight', 'smalltalk.user.lonely', 'smalltalk.emotions.wow', 'smalltalk.appraisal.bad', 'smalltalk.agent.funny', 'smalltalk.agent.birth_date', 'smalltalk.agent.occupation', 'smalltalk.appraisal.no_problem', 'smalltalk.agent.age', 'smalltalk.user.going_to_bed', 'smalltalk.user.bored', 'smalltalk.agent.bad', 'smalltalk.user.misses_agent', 'smalltalk.agent.beautiful', 'smalltalk.user.testing_agent', 'smalltalk.appraisal.good', 'smalltalk.agent.there', 'smalltalk.agent.annoying', 'smalltalk.user.angry', 'smalltalk.agent.busy', 'smalltalk.dialog.sorry', 'smalltalk.agent.right', 'smalltalk.appraisal.welcome', 'smalltalk.agent.suck', 'smalltalk.agent.happy', 'smalltalk.user.busy', 'smalltalk.user.excited', 'smalltalk.appraisal.well_done', 'smalltalk.agent.hobby', 'smalltalk.agent.family', 'smalltalk.agent.clever', 'smalltalk.agent.ready', 'smalltalk.greetings.nice_to_see_you', 'smalltalk.dialog.i_do_not_care', 'smalltalk.user.wants_to_talk', 'smalltalk.greetings.how_are_you', 'smalltalk.agent.sure', 'smalltalk.emotions.ha_ha', 'smalltalk.agent.my_friend', 'smalltalk.user.waits', 'smalltalk.agent.real', 'smalltalk.appraisal.thank_you', 'smalltalk.dialog.what_do_you_mean', 'smalltalk.user.back', 'smalltalk.agent.origin', 'smalltalk.agent.good', 'smalltalk.agent.drunk', 'smalltalk.agent.chatbot', 'smalltalk.dialog.hug', 'smalltalk.user.does_not_want_to_talk', 'smalltalk.greetings.start', 'smalltalk.user.sleepy', 'smalltalk.user.tired', 'smalltalk.greetings.nice_to_meet_you', 'smalltalk.greetings.goodevening', 'smalltalk.agent.answer_my_question', 'smalltalk.user.sad', 'smalltalk.agent.boss', 'smalltalk.agent.can_you_help', 'smalltalk.agent.crazy', 'smalltalk.user.likes_agent', 'smalltalk.agent.residence', 'smalltalk.user.can_not_sleep', 'smalltalk.agent.fired', 'smalltalk.agent.date_user', 'smalltalk.agent.hungry', 'smalltalk.agent.boring', 'smalltalk.dialog.hold_on', 'smalltalk.user.good', 'smalltalk.greetings.goodmorning', 'smalltalk.user.needs_advice', 'smalltalk.user.loves_agent', 'smalltalk.user.here', 'smalltalk.agent.make_sandwich' ] ASTONISHED_AMAZED = ['astonished_interest', 'smalltalk.user.wow'] REQUEST_HELP = ['smalltalk.agent.can_you_help', 'clarify'] START = ['start', 'hello', 'smalltalk.greetings' 'smalltalk.greetings.whatsup', 'smalltalk.greetings.nice_to_see_you', 'smalltalk.greetings.start', 'smalltalk.greetings.goodevening', 'smalltalk.greetings.goodmorning', 'smalltalk.greetings.hello', ]
media_intent = 'media' feeling_intents = ['smalltalk.appraisal.good', 'smalltalk.user.can_not_sleep', 'smalltalk.appraisal.thank_you', 'smalltalk.user.good', 'smalltalk.user.happy', 'smalltalk.user.sad', 'smalltalk.appraisal.bad', 'smalltalk.agent.happy', 'smalltalk.user.sick'] affirmation_intents = ['yes', 'correct', 'smalltalk.dialog.correct', 'smalltalk.agent.right', 'smalltalk.appraisal.good'] negation_intents = ['no', 'wrong', 'smalltalk.dialog.wrong', 'skip', 'smalltalk.agent.wrong', 'smalltalk.dialog.wrong', 'smalltalk.appraisal.bad', 'repeat'] smalltalk_intents = ['who_are_you', 'tell_a_joke', 'smalltalk.user.will_be_back', 'smalltalk.agent.be_clever', 'smalltalk.user.looks_like', 'smalltalk.user.sick', 'smalltalk.user.joking', 'smalltalk.greetings.nice_to_talk_to_you', 'smalltalk.agent.marry_user', 'smalltalk.agent.talk_to_me', 'smalltalk.user.has_birthday', 'smalltalk.user.wants_to_see_agent_again', 'smalltalk.user.happy', 'smalltalk.greetings.whatsup', 'smalltalk.agent.acquaintance', 'smalltalk.greetings.goodnight', 'smalltalk.user.lonely', 'smalltalk.emotions.wow', 'smalltalk.appraisal.bad', 'smalltalk.agent.funny', 'smalltalk.agent.birth_date', 'smalltalk.agent.occupation', 'smalltalk.appraisal.no_problem', 'smalltalk.agent.age', 'smalltalk.user.going_to_bed', 'smalltalk.user.bored', 'smalltalk.agent.bad', 'smalltalk.user.misses_agent', 'smalltalk.agent.beautiful', 'smalltalk.user.testing_agent', 'smalltalk.appraisal.good', 'smalltalk.agent.there', 'smalltalk.agent.annoying', 'smalltalk.user.angry', 'smalltalk.agent.busy', 'smalltalk.dialog.sorry', 'smalltalk.agent.right', 'smalltalk.appraisal.welcome', 'smalltalk.agent.suck', 'smalltalk.agent.happy', 'smalltalk.user.busy', 'smalltalk.user.excited', 'smalltalk.appraisal.well_done', 'smalltalk.agent.hobby', 'smalltalk.agent.family', 'smalltalk.agent.clever', 'smalltalk.agent.ready', 'smalltalk.greetings.nice_to_see_you', 'smalltalk.dialog.i_do_not_care', 'smalltalk.user.wants_to_talk', 'smalltalk.greetings.how_are_you', 'smalltalk.agent.sure', 'smalltalk.emotions.ha_ha', 'smalltalk.agent.my_friend', 'smalltalk.user.waits', 'smalltalk.agent.real', 'smalltalk.appraisal.thank_you', 'smalltalk.dialog.what_do_you_mean', 'smalltalk.user.back', 'smalltalk.agent.origin', 'smalltalk.agent.good', 'smalltalk.agent.drunk', 'smalltalk.agent.chatbot', 'smalltalk.dialog.hug', 'smalltalk.user.does_not_want_to_talk', 'smalltalk.greetings.start', 'smalltalk.user.sleepy', 'smalltalk.user.tired', 'smalltalk.greetings.nice_to_meet_you', 'smalltalk.greetings.goodevening', 'smalltalk.agent.answer_my_question', 'smalltalk.user.sad', 'smalltalk.agent.boss', 'smalltalk.agent.can_you_help', 'smalltalk.agent.crazy', 'smalltalk.user.likes_agent', 'smalltalk.agent.residence', 'smalltalk.user.can_not_sleep', 'smalltalk.agent.fired', 'smalltalk.agent.date_user', 'smalltalk.agent.hungry', 'smalltalk.agent.boring', 'smalltalk.dialog.hold_on', 'smalltalk.user.good', 'smalltalk.greetings.goodmorning', 'smalltalk.user.needs_advice', 'smalltalk.user.loves_agent', 'smalltalk.user.here', 'smalltalk.agent.make_sandwich'] astonished_amazed = ['astonished_interest', 'smalltalk.user.wow'] request_help = ['smalltalk.agent.can_you_help', 'clarify'] start = ['start', 'hello', 'smalltalk.greetingssmalltalk.greetings.whatsup', 'smalltalk.greetings.nice_to_see_you', 'smalltalk.greetings.start', 'smalltalk.greetings.goodevening', 'smalltalk.greetings.goodmorning', 'smalltalk.greetings.hello']
x1, v1, x2, v2 = map(int, input().strip().split(' ')) if v1 == v2: print("NO") else: j = (x1 - x2) // (v2 - v1) print("YES" if j > 0 and (x1+v1*j == x2+v2*j) else "NO")
(x1, v1, x2, v2) = map(int, input().strip().split(' ')) if v1 == v2: print('NO') else: j = (x1 - x2) // (v2 - v1) print('YES' if j > 0 and x1 + v1 * j == x2 + v2 * j else 'NO')
with open("meeting.in", "r") as inputFile: numberOfFields, numberOfPaths = map(int, list(inputFile.readline().strip().split())) paths = [list(map(int, line.strip().split())) for line in inputFile.readlines()] bessiepassable, elsiepassable = {str(i[0])+str(i[1]):i[2] for i in paths}, {str(i[0])+str(i[1]):i[3] for i in paths} def remove_dups(strvar): return "".join(sorted(list(set(strvar)))) def lenofpath(strvar, dictvar): distance = 0 for n in range(0, len(strvar)-1): distance = distance + dictvar[strvar[n]+strvar[n+1]] return distance fieldsPath = list(set([str(i[0])+str(i[1]) for i in paths])) first = [i for i in fieldsPath if i[0] == "1"] second = [remove_dups(k+j) for k in first for j in fieldsPath if j[0] != "1" and k[1] == j[0]] cowpath = [i for i in first+second if i[0] == "1" and i[-1] == str(numberOfFields)] bessie, elsie = {}, {} for path in cowpath: bessie[path], elsie[path] = lenofpath(path, bessiepassable), lenofpath(path, elsiepassable) with open("meeting.out", "w") as outputField: print(min([i for x in list(elsie.values()) for i in list(bessie.values()) if i == x]), file=outputField)
with open('meeting.in', 'r') as input_file: (number_of_fields, number_of_paths) = map(int, list(inputFile.readline().strip().split())) paths = [list(map(int, line.strip().split())) for line in inputFile.readlines()] (bessiepassable, elsiepassable) = ({str(i[0]) + str(i[1]): i[2] for i in paths}, {str(i[0]) + str(i[1]): i[3] for i in paths}) def remove_dups(strvar): return ''.join(sorted(list(set(strvar)))) def lenofpath(strvar, dictvar): distance = 0 for n in range(0, len(strvar) - 1): distance = distance + dictvar[strvar[n] + strvar[n + 1]] return distance fields_path = list(set([str(i[0]) + str(i[1]) for i in paths])) first = [i for i in fieldsPath if i[0] == '1'] second = [remove_dups(k + j) for k in first for j in fieldsPath if j[0] != '1' and k[1] == j[0]] cowpath = [i for i in first + second if i[0] == '1' and i[-1] == str(numberOfFields)] (bessie, elsie) = ({}, {}) for path in cowpath: (bessie[path], elsie[path]) = (lenofpath(path, bessiepassable), lenofpath(path, elsiepassable)) with open('meeting.out', 'w') as output_field: print(min([i for x in list(elsie.values()) for i in list(bessie.values()) if i == x]), file=outputField)
class Solution: def evalRPN(self, tokens: List[str]) -> int: t = -1 for i in range(len(tokens)): if tokens[i] == '+': tokens[t - 1] += tokens[t] t -= 1 elif tokens[i] == '-': tokens[t - 1] -= tokens[t] t -= 1 elif tokens[i] == '*': tokens[t - 1] *= tokens[t] t -= 1 elif tokens[i] == '/': tokens[t - 1] /= tokens[t] if tokens[t - 1] < 0: tokens[t - 1] = math.ceil(tokens[t - 1]) else: tokens[t - 1] = math.floor(tokens[t - 1]) t -= 1 else: t += 1 tokens[t] = int(tokens[i]) return tokens[0]
class Solution: def eval_rpn(self, tokens: List[str]) -> int: t = -1 for i in range(len(tokens)): if tokens[i] == '+': tokens[t - 1] += tokens[t] t -= 1 elif tokens[i] == '-': tokens[t - 1] -= tokens[t] t -= 1 elif tokens[i] == '*': tokens[t - 1] *= tokens[t] t -= 1 elif tokens[i] == '/': tokens[t - 1] /= tokens[t] if tokens[t - 1] < 0: tokens[t - 1] = math.ceil(tokens[t - 1]) else: tokens[t - 1] = math.floor(tokens[t - 1]) t -= 1 else: t += 1 tokens[t] = int(tokens[i]) return tokens[0]
def rotate(A, B, C): return (B[0] - A[0]) * (C[1] - B[1]) - (B[1] - A[1]) * (C[0] - B[0]) def jarvismarch(A): points_count = len(A) processing_indexes = range(points_count) # start point for i in range(1, points_count): if A[processing_indexes[i]][0] < A[processing_indexes[0]][0]: processing_indexes[i], processing_indexes[0] = processing_indexes[0], processing_indexes[i] result_indexes = [processing_indexes[0]] processing_indexes = [processing_indexes[i] for i in range(1, len(processing_indexes))] processing_indexes.append(result_indexes[0]) while True: right = 0 for i in range(1, len(processing_indexes)): if rotate(A[result_indexes[-1]], A[processing_indexes[right]], A[processing_indexes[i]]) < 0: right = i if processing_indexes[right] == result_indexes[0]: break else: result_indexes.append(processing_indexes[right]) del processing_indexes[right] return result_indexes if __name__ == '__main__': points = ((0, 0), (0, 2), (2, 0), (2, 2), (1, 1)) print(jarvismarch(points))
def rotate(A, B, C): return (B[0] - A[0]) * (C[1] - B[1]) - (B[1] - A[1]) * (C[0] - B[0]) def jarvismarch(A): points_count = len(A) processing_indexes = range(points_count) for i in range(1, points_count): if A[processing_indexes[i]][0] < A[processing_indexes[0]][0]: (processing_indexes[i], processing_indexes[0]) = (processing_indexes[0], processing_indexes[i]) result_indexes = [processing_indexes[0]] processing_indexes = [processing_indexes[i] for i in range(1, len(processing_indexes))] processing_indexes.append(result_indexes[0]) while True: right = 0 for i in range(1, len(processing_indexes)): if rotate(A[result_indexes[-1]], A[processing_indexes[right]], A[processing_indexes[i]]) < 0: right = i if processing_indexes[right] == result_indexes[0]: break else: result_indexes.append(processing_indexes[right]) del processing_indexes[right] return result_indexes if __name__ == '__main__': points = ((0, 0), (0, 2), (2, 0), (2, 2), (1, 1)) print(jarvismarch(points))
class NodoAST: def __init__(self, contenido): self._contenido = contenido self._hijos = [] def getContenido(self): return self._contenido def getHijos(self): return self._hijos def setHijo(self, hijo): self._hijos.append(hijo)
class Nodoast: def __init__(self, contenido): self._contenido = contenido self._hijos = [] def get_contenido(self): return self._contenido def get_hijos(self): return self._hijos def set_hijo(self, hijo): self._hijos.append(hijo)
#This program displays a date in the form #(Month day, Year like March 12, 2014 #ALGORITHM in pseudocode #1. get a date string in the form mm/dd/yyyy from the user #2. use the split method to remove the seperator('/') # and assign the results to a variable. #3. determine the month the user entered # if month is 01: # month is Januray # if month is 02: # month is February # if month is 03: # month is March # if month is 04: # month is April # this keep going till # if month is 12: # month is December #3. using indexes, print the date in the variable #CODE def main(): date_string = input('Enter a date in the form "mm/dd/yyyy": ') date_list = get_date_list(date_string) def get_date_list(date_string): date_list = date_string.split('/') #Determining the month mm = date_list[0] if mm == '01': mm = 'January' elif mm == '02': mm = 'February' elif mm == '03': mm = 'March' elif mm == '04': mm = 'April' elif mm == '05': mm = 'May' elif mm == '06': mm = 'June' elif mm == '07': mm = 'July' elif mm == '08': mm = 'August' elif mm == '09': mm = 'September' elif mm == '10': mm = 'October' elif mm == '11': mm = 'November' elif mm == '12': mm = 'December' #displayin results print('A reform of the date you entered is: ',\ mm,date_list[1]+',',date_list[2]) main()
def main(): date_string = input('Enter a date in the form "mm/dd/yyyy": ') date_list = get_date_list(date_string) def get_date_list(date_string): date_list = date_string.split('/') mm = date_list[0] if mm == '01': mm = 'January' elif mm == '02': mm = 'February' elif mm == '03': mm = 'March' elif mm == '04': mm = 'April' elif mm == '05': mm = 'May' elif mm == '06': mm = 'June' elif mm == '07': mm = 'July' elif mm == '08': mm = 'August' elif mm == '09': mm = 'September' elif mm == '10': mm = 'October' elif mm == '11': mm = 'November' elif mm == '12': mm = 'December' print('A reform of the date you entered is: ', mm, date_list[1] + ',', date_list[2]) main()
n1 = float(input('Valor do produto (R$): ')) n2 = float(input('Desconto em porcentagem (%): ')) d = n2/100 d1 = n1*d nv = n1-d1 print('Novo valor do produto com {}% de desconto: R${:.2f}'.format(n2,nv))
n1 = float(input('Valor do produto (R$): ')) n2 = float(input('Desconto em porcentagem (%): ')) d = n2 / 100 d1 = n1 * d nv = n1 - d1 print('Novo valor do produto com {}% de desconto: R${:.2f}'.format(n2, nv))
mem_key_cache = 'cache' mem_key_metadata = 'meta' mem_key_sponsor = 'sponsor' mem_key_total_open_source_spaces = 'oss' mem_key_creeps_by_role = 'roles_alive' mem_key_work_parts_by_role = 'roles_work' mem_key_carry_parts_by_role = 'roles_carry' mem_key_creeps_by_role_and_replacement_time = 'rt_map' mem_key_prepping_defenses = 'prepping_defenses' mem_key_storage_use_enabled = 'full_storage_use' mem_key_focusing_home = 'focusing_home' mem_key_upgrading_paused = 'upgrading_paused' mem_key_building_paused = 'building_paused' mem_key_spawn_requests = '_requests' mem_key_planned_role_to_spawn = 'next_role' mem_key_observer_plans = 'observer_plan' mem_key_flag_for_testing_spawning_in_simulation = 'completely_sim_testing' mem_key_pause_all_room_operations = 'pause' mem_key_empty_all_resources_into_room = 'empty_to' mem_key_sell_all_but_empty_resources_to = 'sabet' mem_key_room_reserved_up_until_tick = 'rea' mem_key_currently_under_siege = 'attack' mem_key_remotes_safe_when_under_siege = 'remotes_safe' mem_key_remotes_explicitly_marked_under_attack = 'remotes_attack' mem_key_stored_hostiles = 'danger' mem_key_defense_mind_storage = 'defense' mem_key_linking_mind_storage = 'links' mem_key_mineral_mind_storage = 'market' mem_key_building_priority_walls = 'prio_walls' mem_key_building_priority_spawn = 'prio_spawn' mem_key_there_might_be_energy_lying_around = 'tons' mem_key_now_supporting = 's' mem_key_alive_squads = 'st' mem_key_urgency = 'urgency' mem_key_message = 'm' mem_key_dismantler_squad_opts = 'dm_opts' mem_key_squad_memory = 'sqmem' cache_key_spending_now = 'ss' cache_key_squads = 'sqds'
mem_key_cache = 'cache' mem_key_metadata = 'meta' mem_key_sponsor = 'sponsor' mem_key_total_open_source_spaces = 'oss' mem_key_creeps_by_role = 'roles_alive' mem_key_work_parts_by_role = 'roles_work' mem_key_carry_parts_by_role = 'roles_carry' mem_key_creeps_by_role_and_replacement_time = 'rt_map' mem_key_prepping_defenses = 'prepping_defenses' mem_key_storage_use_enabled = 'full_storage_use' mem_key_focusing_home = 'focusing_home' mem_key_upgrading_paused = 'upgrading_paused' mem_key_building_paused = 'building_paused' mem_key_spawn_requests = '_requests' mem_key_planned_role_to_spawn = 'next_role' mem_key_observer_plans = 'observer_plan' mem_key_flag_for_testing_spawning_in_simulation = 'completely_sim_testing' mem_key_pause_all_room_operations = 'pause' mem_key_empty_all_resources_into_room = 'empty_to' mem_key_sell_all_but_empty_resources_to = 'sabet' mem_key_room_reserved_up_until_tick = 'rea' mem_key_currently_under_siege = 'attack' mem_key_remotes_safe_when_under_siege = 'remotes_safe' mem_key_remotes_explicitly_marked_under_attack = 'remotes_attack' mem_key_stored_hostiles = 'danger' mem_key_defense_mind_storage = 'defense' mem_key_linking_mind_storage = 'links' mem_key_mineral_mind_storage = 'market' mem_key_building_priority_walls = 'prio_walls' mem_key_building_priority_spawn = 'prio_spawn' mem_key_there_might_be_energy_lying_around = 'tons' mem_key_now_supporting = 's' mem_key_alive_squads = 'st' mem_key_urgency = 'urgency' mem_key_message = 'm' mem_key_dismantler_squad_opts = 'dm_opts' mem_key_squad_memory = 'sqmem' cache_key_spending_now = 'ss' cache_key_squads = 'sqds'
# -*- coding: utf-8 -*- # Scrapy settings for watches project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://doc.scrapy.org/en/latest/topics/settings.html # https://doc.scrapy.org/en/latest/topics/downloader-middleware.html # https://doc.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = 'watches' SPIDER_MODULES = ['watches.spiders'] NEWSPIDER_MODULE = 'watches.spiders' REDIRECT_ENABLED = False # Retry many times since proxies often fail RETRY_TIMES = 10 # Retry on most error codes since proxies fail for different reasons RETRY_HTTP_CODES = [500, 503, 504, 400, 403, 404, 408] # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'watches (+http://www.yourdomain.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = False # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs DOWNLOAD_DELAY = 0.2 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) COOKIES_ENABLED = False
bot_name = 'watches' spider_modules = ['watches.spiders'] newspider_module = 'watches.spiders' redirect_enabled = False retry_times = 10 retry_http_codes = [500, 503, 504, 400, 403, 404, 408] robotstxt_obey = False download_delay = 0.2 cookies_enabled = False
#!/usr/bin/env python ####################################### # Installation module for eyewitness ####################################### # AUTHOR OF MODULE NAME AUTHOR="Kirk Hayes (l0gan)" # DESCRIPTION OF THE MODULE DESCRIPTION="This module will install/update EyeWitness." # INSTALL TYPE GIT, SVN, FILE DOWNLOAD # OPTIONS = GIT, SVN, FILE INSTALL_TYPE="GIT" # LOCATION OF THE FILE OR GIT/SVN REPOSITORY REPOSITORY_LOCATION="https://github.com/FortyNorthSecurity/EyeWitness" # WHERE DO YOU WANT TO INSTALL IT INSTALL_LOCATION="eyewitness" # DEPENDS FOR DEBIAN INSTALLS DEBIAN="git,python-setuptools,libffi-dev,libssl-dev" # COMMANDS TO RUN AFTER AFTER_COMMANDS="cd {INSTALL_LOCATION}Python/setup,./setup.sh" LAUNCHER="eyewitness"
author = 'Kirk Hayes (l0gan)' description = 'This module will install/update EyeWitness.' install_type = 'GIT' repository_location = 'https://github.com/FortyNorthSecurity/EyeWitness' install_location = 'eyewitness' debian = 'git,python-setuptools,libffi-dev,libssl-dev' after_commands = 'cd {INSTALL_LOCATION}Python/setup,./setup.sh' launcher = 'eyewitness'
users = {'email1': 'password1'} links = [ # fake array of posts { 'author': 'users', 'date' : "04-08-2017", 'description': 'cool information site', 'link': 'https://www.wikipedia.org', 'tags': None }, { 'author': 'user', 'date' : "06-08-2017", 'description': 'worst site I\'ve ever used', 'link': 'www.facebook.org', 'tags': None }, { 'author': 'user', 'date' : "01-08-2017", 'description': 'other cool site', 'link': 'www.python.org', 'tags': None } ]
users = {'email1': 'password1'} links = [{'author': 'users', 'date': '04-08-2017', 'description': 'cool information site', 'link': 'https://www.wikipedia.org', 'tags': None}, {'author': 'user', 'date': '06-08-2017', 'description': "worst site I've ever used", 'link': 'www.facebook.org', 'tags': None}, {'author': 'user', 'date': '01-08-2017', 'description': 'other cool site', 'link': 'www.python.org', 'tags': None}]
# OAuth app keys DROPBOX_BUSINESS_FILEACCESS_KEY = None DROPBOX_BUSINESS_FILEACCESS_SECRET = None DROPBOX_BUSINESS_MANAGEMENT_KEY = None DROPBOX_BUSINESS_MANAGEMENT_SECRET = None DROPBOX_BUSINESS_AUTH_CSRF_TOKEN = 'dropboxbusiness-auth-csrf-token' TEAM_FOLDER_NAME_FORMAT = '{title}_GRDM_{guid}' # available: {title} {guid} GROUP_NAME_FORMAT = 'GRDM_{guid}' # available: {title} {guid} ADMIN_GROUP_NAME = 'GRDM-ADMIN' USE_PROPERTY_TIMESTAMP = True PROPERTY_GROUP_NAME = 'GRDM' PROPERTY_KEY_TIMESTAMP_STATUS = 'timestamp-status' PROPERTY_KEYS = (PROPERTY_KEY_TIMESTAMP_STATUS,) PROPERTY_MAX_DATA_SIZE = 1000 PROPERTY_SPLIT_DATA_CONF = { 'timestamp': { 'max_size': 5000, } } # Max file size permitted by frontend in megabytes MAX_UPLOAD_SIZE = 5 * 1024 EPPN_TO_EMAIL_MAP = { # e.g. # 'john@idp.example.com': 'john.smith@mail.example.com', } EMAIL_TO_EPPN_MAP = dict( [(EPPN_TO_EMAIL_MAP[k], k) for k in EPPN_TO_EMAIL_MAP] ) DEBUG_FILEACCESS_TOKEN = None DEBUG_MANAGEMENT_TOKEN = None DEBUG_ADMIN_DBMID = None
dropbox_business_fileaccess_key = None dropbox_business_fileaccess_secret = None dropbox_business_management_key = None dropbox_business_management_secret = None dropbox_business_auth_csrf_token = 'dropboxbusiness-auth-csrf-token' team_folder_name_format = '{title}_GRDM_{guid}' group_name_format = 'GRDM_{guid}' admin_group_name = 'GRDM-ADMIN' use_property_timestamp = True property_group_name = 'GRDM' property_key_timestamp_status = 'timestamp-status' property_keys = (PROPERTY_KEY_TIMESTAMP_STATUS,) property_max_data_size = 1000 property_split_data_conf = {'timestamp': {'max_size': 5000}} max_upload_size = 5 * 1024 eppn_to_email_map = {} email_to_eppn_map = dict([(EPPN_TO_EMAIL_MAP[k], k) for k in EPPN_TO_EMAIL_MAP]) debug_fileaccess_token = None debug_management_token = None debug_admin_dbmid = None
colors = { 'default': (0, 'WHITE', 'BLACK', 'NORMAL'), 'title': (1, 'YELLOW', 'BLUE', 'BOLD'), 'status': (2, 'YELLOW', 'BLUE', 'BOLD'), 'error': (3, 'RED', 'BLACK', 'BOLD'), 'highlight': (4, 'YELLOW', 'MAGENTA', 'BOLD'), }
colors = {'default': (0, 'WHITE', 'BLACK', 'NORMAL'), 'title': (1, 'YELLOW', 'BLUE', 'BOLD'), 'status': (2, 'YELLOW', 'BLUE', 'BOLD'), 'error': (3, 'RED', 'BLACK', 'BOLD'), 'highlight': (4, 'YELLOW', 'MAGENTA', 'BOLD')}
#-----------------problem parameters----------------------- depot = [] capacity = 120 time_dist_factor = 10 # time per job converted to distance num_salesmen = 5 # --------------------------------------------------------- population = 50 nodes = [] node_num = 0 gnd_truth_tsp = [] gnd_truth_dist_list = [] # i-th element is distance between i-th and i+1 th element of gnd_truth_tsp gnd_truth_dist_from_depot = [] # i-th element is distance of i-th element of gnd_truth_tsp from depot def print_error(msg): print("ERROR: "+msg) exit()
depot = [] capacity = 120 time_dist_factor = 10 num_salesmen = 5 population = 50 nodes = [] node_num = 0 gnd_truth_tsp = [] gnd_truth_dist_list = [] gnd_truth_dist_from_depot = [] def print_error(msg): print('ERROR: ' + msg) exit()
class MeuObjeto: def __init__(self, id, nome, sobrenome): self.id = id self.nome = nome self.sobrenome = sobrenome
class Meuobjeto: def __init__(self, id, nome, sobrenome): self.id = id self.nome = nome self.sobrenome = sobrenome
def retry_until(condition): def retry(request): try: return request() except Exception as exception: if condition(exception): return retry(request) else: raise exception return retry def retry(max_retries): retries = [0] def retry_count(): retries[0] += 1 return retries[0] return retry_until(lambda _: retry_count() != max_retries)
def retry_until(condition): def retry(request): try: return request() except Exception as exception: if condition(exception): return retry(request) else: raise exception return retry def retry(max_retries): retries = [0] def retry_count(): retries[0] += 1 return retries[0] return retry_until(lambda _: retry_count() != max_retries)
fig, ax = plt.subplots() ax.hist(my_dataset.Zr, bins='auto', density=True, histtype='step', linewidth=2, cumulative=1, color='tab:blue') ax.set_xlabel('Zr [ppm]') ax.set_ylabel('Likelihood of occurrence')
(fig, ax) = plt.subplots() ax.hist(my_dataset.Zr, bins='auto', density=True, histtype='step', linewidth=2, cumulative=1, color='tab:blue') ax.set_xlabel('Zr [ppm]') ax.set_ylabel('Likelihood of occurrence')
heights = [161, 164, 156, 144, 158, 170, 163, 163, 157] can_ride_coaster = [can for can in heights if can > 161] print(can_ride_coaster)
heights = [161, 164, 156, 144, 158, 170, 163, 163, 157] can_ride_coaster = [can for can in heights if can > 161] print(can_ride_coaster)
i = 1 while (i<=10): print(i, end=" ") i += 1 print()
i = 1 while i <= 10: print(i, end=' ') i += 1 print()
def my_function(*args, **kwargs): for arg in args: print('arg:', arg) for key in kwargs.keys(): print('key:', key, 'has value: ', kwargs[key]) my_function('John', 'Denise', daughter='Phoebe', son='Adam') print('-' * 50) my_function('Paul', 'Fiona', son_number_one='Andrew', son_number_two='James', daughter='Joselyn') def named(**kwargs): for key in kwargs.keys(): print('arg:', key, 'has value:', kwargs[key]) named(a=1, b=2, c=3) def printer(*args): for arg in args: print('arg:', arg, end=", ") print() a = (1, 2, 3, 4) b = [1, 2, 3, 4] printer(0, 1, 2, 3, 4, 5) printer(0, a, 5) printer(0, b, 5) printer(0, *a) printer(0, *b) printer(0, *[1, 2, 3, 4])
def my_function(*args, **kwargs): for arg in args: print('arg:', arg) for key in kwargs.keys(): print('key:', key, 'has value: ', kwargs[key]) my_function('John', 'Denise', daughter='Phoebe', son='Adam') print('-' * 50) my_function('Paul', 'Fiona', son_number_one='Andrew', son_number_two='James', daughter='Joselyn') def named(**kwargs): for key in kwargs.keys(): print('arg:', key, 'has value:', kwargs[key]) named(a=1, b=2, c=3) def printer(*args): for arg in args: print('arg:', arg, end=', ') print() a = (1, 2, 3, 4) b = [1, 2, 3, 4] printer(0, 1, 2, 3, 4, 5) printer(0, a, 5) printer(0, b, 5) printer(0, *a) printer(0, *b) printer(0, *[1, 2, 3, 4])
class A: def __init__(self): print("A") super().__init__() class B1(A): def __init__(self): print("B1") super().__init__() class B2(A): def __init__(self): print("B2") super().__init__() class C(B1, A): def __init__(self): print("C") super().__init__() C()
class A: def __init__(self): print('A') super().__init__() class B1(A): def __init__(self): print('B1') super().__init__() class B2(A): def __init__(self): print('B2') super().__init__() class C(B1, A): def __init__(self): print('C') super().__init__() c()
props.bf_Shank_Dia = 10.0 #props.bf_Pitch = 1.5 # Coarse props.bf_Pitch = 1.25 # Fine props.bf_Crest_Percent = 10 props.bf_Root_Percent = 10 props.bf_Major_Dia = 10.0 props.bf_Minor_Dia = props.bf_Major_Dia - (1.082532 * props.bf_Pitch) props.bf_Hex_Head_Flat_Distance = 17.0 props.bf_Hex_Head_Height = 6.4 props.bf_Cap_Head_Dia = 16.0 props.bf_Cap_Head_Height = 10.0 props.bf_CounterSink_Head_Dia = 20.0 props.bf_Allen_Bit_Flat_Distance = 8.0 props.bf_Allen_Bit_Depth = 5.0 props.bf_Pan_Head_Dia = 20.0 props.bf_Dome_Head_Dia = 20.0 props.bf_Philips_Bit_Dia = props.bf_Pan_Head_Dia * (1.82 / 5.6) #props.bf_Phillips_Bit_Depth = Get_Phillips_Bit_Height(props.bf_Philips_Bit_Dia) props.bf_Hex_Nut_Height = 8.0 props.bf_Hex_Nut_Flat_Distance = 17.0 props.bf_Thread_Length = 20 props.bf_Shank_Length = 0.0
props.bf_Shank_Dia = 10.0 props.bf_Pitch = 1.25 props.bf_Crest_Percent = 10 props.bf_Root_Percent = 10 props.bf_Major_Dia = 10.0 props.bf_Minor_Dia = props.bf_Major_Dia - 1.082532 * props.bf_Pitch props.bf_Hex_Head_Flat_Distance = 17.0 props.bf_Hex_Head_Height = 6.4 props.bf_Cap_Head_Dia = 16.0 props.bf_Cap_Head_Height = 10.0 props.bf_CounterSink_Head_Dia = 20.0 props.bf_Allen_Bit_Flat_Distance = 8.0 props.bf_Allen_Bit_Depth = 5.0 props.bf_Pan_Head_Dia = 20.0 props.bf_Dome_Head_Dia = 20.0 props.bf_Philips_Bit_Dia = props.bf_Pan_Head_Dia * (1.82 / 5.6) props.bf_Hex_Nut_Height = 8.0 props.bf_Hex_Nut_Flat_Distance = 17.0 props.bf_Thread_Length = 20 props.bf_Shank_Length = 0.0
def dividedtimes(x): if not isinstance(x, int): raise TypeError('x must be integer.') elif x <= 2: raise ValueError('x must be greater than 2.') counter = 0 while x >= 2: x = x / 2 counter += 1 return counter
def dividedtimes(x): if not isinstance(x, int): raise type_error('x must be integer.') elif x <= 2: raise value_error('x must be greater than 2.') counter = 0 while x >= 2: x = x / 2 counter += 1 return counter
def bubbleSort(list): for i in range(0,len(list)-1): for j in range(0,len(list)-i-1): if list[j] > list[j+1]: print("\n%d > %d"%(list[j],list[j+1])) (list[j], list[j+1]) = (list[j+1], list[j]) print("\nNext Pass\n") print("\nThe elements are now sorted in ascending order:\n") for i in list: print("\t%d\t"%(i),end="") n = int(input("\nEnter the number of elements : \n")) list = [] print("\nEnter the elements one be one:\n") for i in range(n): list.append(int(input())) bubbleSort(list)
def bubble_sort(list): for i in range(0, len(list) - 1): for j in range(0, len(list) - i - 1): if list[j] > list[j + 1]: print('\n%d > %d' % (list[j], list[j + 1])) (list[j], list[j + 1]) = (list[j + 1], list[j]) print('\nNext Pass\n') print('\nThe elements are now sorted in ascending order:\n') for i in list: print('\t%d\t' % i, end='') n = int(input('\nEnter the number of elements : \n')) list = [] print('\nEnter the elements one be one:\n') for i in range(n): list.append(int(input())) bubble_sort(list)
# pylint: disable=missing-docstring,redefined-builtin,unsubscriptable-object # pylint: disable=invalid-name,too-few-public-methods,attribute-defined-outside-init class Repository: def _transfer(self, bytes=-1): self._bytesTransfered = 0 bufff = True while bufff and (bytes < 0 or self._bytesTransfered < bytes): bufff = bufff[: bytes - self._bytesTransfered] self._bytesTransfered += len(bufff)
class Repository: def _transfer(self, bytes=-1): self._bytesTransfered = 0 bufff = True while bufff and (bytes < 0 or self._bytesTransfered < bytes): bufff = bufff[:bytes - self._bytesTransfered] self._bytesTransfered += len(bufff)
# Copyright 2016 Check Point Software Technologies LTD # # 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. # URI Strings URI = 'https://te-api.checkpoint.com/tecloud/api/v1/file/' TOKEN_URI = 'https://cloudinfra-gw.portal.checkpoint.com/auth/external' PORT = "18194" REMOTE_DIR = "tecloud/api/v1/file" QUERY = 'query' UPLOAD = 'upload' DOWNLOAD = 'download' QUERY_SELECTOR = '%s%s' % (URI, QUERY) UPLOAD_SELECTOR = '%s%s' % (URI, UPLOAD) DOWNLOAD_SELECTOR = '%s%s' % (URI, DOWNLOAD) def get_selector(ip_address,selector): url = "" if ip_address: url = 'https://%s:%s/%s/%s' % (ip_address, PORT, REMOTE_DIR, selector) elif selector == QUERY: url = QUERY_SELECTOR elif selector == UPLOAD: url = UPLOAD_SELECTOR elif selector == DOWNLOAD: url = DOWNLOAD_SELECTOR return url # Request Strings MD5 = 'md5' SHA1 = 'sha1' SHA256 = 'sha256' TE = 'te' TEX = 'extraction' PDF = 'pdf' XML = 'xml' SUMMARY = 'summary' # Response Strings STATUS = 'status' LABEL = 'label' RESPONSE = 'response' FOUND = 'FOUND' PARTIALLY_FOUND = 'PARTIALLY_FOUND' NOT_FOUND = 'NOT_FOUND' UPLOAD_SUCCESS = 'UPLOAD_SUCCESS' PENDING = 'PENDING' NO_QUOTA = 'NO_QUOTA' FORBIDDEN = 'FORBIDDEN' BENIGN = 'benign' MALICIOUS = 'malicious' ERROR = 'error' MESSAGE = 'message' # TE Strings TE_VERDICT = 'combined_verdict' TE_SEVERITY = 'severity' TE_CONFIDENCE = 'confidence' TE_VERDICT_MALICIOUS = 'verdict is Malicious' TE_VERDICT_BENIGN = 'verdict is Benign'
uri = 'https://te-api.checkpoint.com/tecloud/api/v1/file/' token_uri = 'https://cloudinfra-gw.portal.checkpoint.com/auth/external' port = '18194' remote_dir = 'tecloud/api/v1/file' query = 'query' upload = 'upload' download = 'download' query_selector = '%s%s' % (URI, QUERY) upload_selector = '%s%s' % (URI, UPLOAD) download_selector = '%s%s' % (URI, DOWNLOAD) def get_selector(ip_address, selector): url = '' if ip_address: url = 'https://%s:%s/%s/%s' % (ip_address, PORT, REMOTE_DIR, selector) elif selector == QUERY: url = QUERY_SELECTOR elif selector == UPLOAD: url = UPLOAD_SELECTOR elif selector == DOWNLOAD: url = DOWNLOAD_SELECTOR return url md5 = 'md5' sha1 = 'sha1' sha256 = 'sha256' te = 'te' tex = 'extraction' pdf = 'pdf' xml = 'xml' summary = 'summary' status = 'status' label = 'label' response = 'response' found = 'FOUND' partially_found = 'PARTIALLY_FOUND' not_found = 'NOT_FOUND' upload_success = 'UPLOAD_SUCCESS' pending = 'PENDING' no_quota = 'NO_QUOTA' forbidden = 'FORBIDDEN' benign = 'benign' malicious = 'malicious' error = 'error' message = 'message' te_verdict = 'combined_verdict' te_severity = 'severity' te_confidence = 'confidence' te_verdict_malicious = 'verdict is Malicious' te_verdict_benign = 'verdict is Benign'
g=[] for a in range (1000): if a%3==0 or a%5==0: g.append(a) print(sum(g))
g = [] for a in range(1000): if a % 3 == 0 or a % 5 == 0: g.append(a) print(sum(g))
#Strinping Names: Person_name = " Chandler Bing " print("Person Name with tab space :\t"+Person_name) print("Person Name in new line :\n"+Person_name) print("Person Name with space removed from left side :"+Person_name.lstrip()) print("Person Name with space removed from right side :"+Person_name.rstrip()) print("Person Name with space removed from both sides:"+Person_name.strip())
person_name = ' Chandler Bing ' print('Person Name with tab space :\t' + Person_name) print('Person Name in new line :\n' + Person_name) print('Person Name with space removed from left side :' + Person_name.lstrip()) print('Person Name with space removed from right side :' + Person_name.rstrip()) print('Person Name with space removed from both sides:' + Person_name.strip())
def divisibleSumPairs(n, k, ar): count = 0 for i in range(len(ar)-1): for j in range(i+1, len(ar)): if (ar[i]+ar[j])%k == 0: count += 1 return count
def divisible_sum_pairs(n, k, ar): count = 0 for i in range(len(ar) - 1): for j in range(i + 1, len(ar)): if (ar[i] + ar[j]) % k == 0: count += 1 return count
# Python3 Binary Tree to Doubly Linked List # 10 # / \ # 12 15 ---> head ---> 25<->12<->30<->10<->36<->15 # / \ / # 25 30 36 # def tree2DLL(root, head): if not root: return prev = None tree2DLL(root.left) if not prev: head = prev else: root.left = prev prev.right = root prev = root
def tree2_dll(root, head): if not root: return prev = None tree2_dll(root.left) if not prev: head = prev else: root.left = prev prev.right = root prev = root
class Synapse: def __init__(self, label, input, weight, next_neurons): self.label = label self.input = input self.weight = weight self.next_neurons = next_neurons
class Synapse: def __init__(self, label, input, weight, next_neurons): self.label = label self.input = input self.weight = weight self.next_neurons = next_neurons
''' Created on 2020-09-10 @author: wf ''' class Labels(object): ''' NLTK labels ''' default=['GPE','PERSON','ORGANIZATION'] geo=['GPE']
""" Created on 2020-09-10 @author: wf """ class Labels(object): """ NLTK labels """ default = ['GPE', 'PERSON', 'ORGANIZATION'] geo = ['GPE']
''' Substring Concatenation Asked in: Facebook https://www.interviewbit.com/problems/substring-concatenation/ You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters. Example : S: "barfoothefoobarman" L: ["foo", "bar"] You should return the indices: [0,9]. (order does not matter). ''' # @param A : string # @param B : tuple of strings # @return a list of integers def findSubstring(A, B): ans = [] n = len(B) l = len(B[0]) hash_key = ''.join(sorted(B)) l_hash = len(hash_key) for i in range(len(A)-l_hash+1): C = [A[i+j*l:i+j*l+l]for j in range(n)] C = ''.join(sorted(C)) if C==hash_key: ans.append(i) return ans if __name__=='__main__': data = [ [ ["barfoothefoobarman", ["foo", "bar"]], [0,9] ] ] for d in data: print('input', d[0], 'output', findSubstring(*d[0]))
""" Substring Concatenation Asked in: Facebook https://www.interviewbit.com/problems/substring-concatenation/ You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters. Example : S: "barfoothefoobarman" L: ["foo", "bar"] You should return the indices: [0,9]. (order does not matter). """ def find_substring(A, B): ans = [] n = len(B) l = len(B[0]) hash_key = ''.join(sorted(B)) l_hash = len(hash_key) for i in range(len(A) - l_hash + 1): c = [A[i + j * l:i + j * l + l] for j in range(n)] c = ''.join(sorted(C)) if C == hash_key: ans.append(i) return ans if __name__ == '__main__': data = [[['barfoothefoobarman', ['foo', 'bar']], [0, 9]]] for d in data: print('input', d[0], 'output', find_substring(*d[0]))
def trunk_1(arr_1, size_1): result_1 = [] while arr: pop_data = [arr_1.pop(0) for _ in range(size_1)] result_1.append(pop_data) return result_1 def trunk_2(arr_2, size_2): arrs = [] while len(arr_2) > size_2: pice = arr_2[:size_2] arrs.append(pice) arr_2 = arr_2[size:] arrs.append(arr_2) return arrs def trunk_3(arr, size): result = [] count = 0 while count < len(arr): result.append(arr[count:count+size]) count += size return result if __name__ == "__main__": ''' arr = [1, 2, 3, 4, 5, 6] size = 2 result = [[1, 2], [3, 4], [5, 6]] ''' arr = [1, 2, 3, 4, 5, 6] size = 2 result = trunk_1(arr, size) print(result)
def trunk_1(arr_1, size_1): result_1 = [] while arr: pop_data = [arr_1.pop(0) for _ in range(size_1)] result_1.append(pop_data) return result_1 def trunk_2(arr_2, size_2): arrs = [] while len(arr_2) > size_2: pice = arr_2[:size_2] arrs.append(pice) arr_2 = arr_2[size:] arrs.append(arr_2) return arrs def trunk_3(arr, size): result = [] count = 0 while count < len(arr): result.append(arr[count:count + size]) count += size return result if __name__ == '__main__': '\n arr = [1, 2, 3, 4, 5, 6]\n size = 2\n result = [[1, 2], [3, 4], [5, 6]]\n ' arr = [1, 2, 3, 4, 5, 6] size = 2 result = trunk_1(arr, size) print(result)
#!/usr/bin/env python if __name__ == "__main__": print("Hello world from copied executable")
if __name__ == '__main__': print('Hello world from copied executable')
data = open("day3.txt", "r").read().splitlines() openSquare = data[0][0] tree = data[0][6] def howManyTrees(right, down): position = right iterator = down trees = 0 openSquares = 0 for rowIterator in range(0, int((len(data))/down) - 1): row = data[iterator] res_row = row * 100 obstacle = res_row[position] position += right if obstacle == openSquare: openSquares += 1 elif obstacle == tree: trees += 1 iterator += down print("Trees encountered for right ", right, " down ", down, " is ", trees) return trees first = howManyTrees(1,1) second = howManyTrees(3,1) third = howManyTrees(5,1) fourth = howManyTrees(7,1) fifth = howManyTrees(1,2) finalResult = first * second * third * fourth * fifth print("Multiplied trees", finalResult)
data = open('day3.txt', 'r').read().splitlines() open_square = data[0][0] tree = data[0][6] def how_many_trees(right, down): position = right iterator = down trees = 0 open_squares = 0 for row_iterator in range(0, int(len(data) / down) - 1): row = data[iterator] res_row = row * 100 obstacle = res_row[position] position += right if obstacle == openSquare: open_squares += 1 elif obstacle == tree: trees += 1 iterator += down print('Trees encountered for right ', right, ' down ', down, ' is ', trees) return trees first = how_many_trees(1, 1) second = how_many_trees(3, 1) third = how_many_trees(5, 1) fourth = how_many_trees(7, 1) fifth = how_many_trees(1, 2) final_result = first * second * third * fourth * fifth print('Multiplied trees', finalResult)
n = int(input()) d = [[0,0,0] for i in range(n + 1)] for i in range(1, n + 1): (r, g, b) = [int(i) for i in input().split()] d[i][0] = r + min(d[i - 1][1], d[i - 1][2]) d[i][1] = g + min(d[i - 1][0], d[i - 1][2]) d[i][2] = b + min(d[i - 1][0], d[i - 1][1]) print(min(d[n]))
n = int(input()) d = [[0, 0, 0] for i in range(n + 1)] for i in range(1, n + 1): (r, g, b) = [int(i) for i in input().split()] d[i][0] = r + min(d[i - 1][1], d[i - 1][2]) d[i][1] = g + min(d[i - 1][0], d[i - 1][2]) d[i][2] = b + min(d[i - 1][0], d[i - 1][1]) print(min(d[n]))
# Test passwords are randomly hashed def test_passwords_hashed_randomly(test_app, test_database, add_user): user_one = add_user( "test_user_one", "test_user_one@mail.com", "test_password" ) user_two = add_user( "test_user_two", "test_user_two@mail.com", "test_password" ) assert user_one.password != user_two.password assert user_one.password != "test_password" assert user_two.password != "test_password"
def test_passwords_hashed_randomly(test_app, test_database, add_user): user_one = add_user('test_user_one', 'test_user_one@mail.com', 'test_password') user_two = add_user('test_user_two', 'test_user_two@mail.com', 'test_password') assert user_one.password != user_two.password assert user_one.password != 'test_password' assert user_two.password != 'test_password'
# Defination for mathematical operation def math(token_ip_stream,toko): if token_ip_stream[0][0] == 'INOUT' and token_ip_stream[1][0] == 'IDENTIFIRE' and token_ip_stream[2][1] == "=" and token_ip_stream[3][1] == toko[0][0] and token_ip_stream[5][1] == toko[1][0] and token_ip_stream[6][0] == "STATEMENT_END" : if token_ip_stream[4][1] == "+": toko[2][1] = int(toko[0][1]) + int(toko[1][1]) toko[-1][0] = " " elif token_ip_stream[4][1] == "-": toko[2][1] = int(toko[0][1]) - int(toko[1][1]) toko[-1][0] = " " elif token_ip_stream[4][1] == "*": toko[2][1] = int(toko[0][1]) * int(toko[1][1]) toko[-1][0] = " " elif token_ip_stream[4][1] == "%": toko[2][1] = int(toko[0][1]) % int(toko[1][1]) toko[-1][0] = " " elif token_ip_stream[4][1] == "@": toko[2][1] = int(toko[0][1]) // int(toko[1][1]) toko[-1][0] = " " elif token_ip_stream[4][1] == "/": toko[2][1] = int(toko[0][1]) / int(toko[1][1]) toko[-1][0] = " " else : print("Syntax ERROR : you miss the operator or you have wrong syntax [Ex. ~ num1 = a + b .] or Statement MISSING : You miss the Statement end notation '.'") return (toko) # Defination for assignment operation def assignmentOpp(token_ip_stream): toko = [] token_chk = 1 for i in range(0 ,len(toko)): tokens_id=toko[i][0] tokens_val=toko[i][1] for token in range(0,len(token_ip_stream)): if token_ip_stream[token][1]== '=': toko.append([token_ip_stream[token-1][1],token_ip_stream[token +1][1]]) return (toko)
def math(token_ip_stream, toko): if token_ip_stream[0][0] == 'INOUT' and token_ip_stream[1][0] == 'IDENTIFIRE' and (token_ip_stream[2][1] == '=') and (token_ip_stream[3][1] == toko[0][0]) and (token_ip_stream[5][1] == toko[1][0]) and (token_ip_stream[6][0] == 'STATEMENT_END'): if token_ip_stream[4][1] == '+': toko[2][1] = int(toko[0][1]) + int(toko[1][1]) toko[-1][0] = ' ' elif token_ip_stream[4][1] == '-': toko[2][1] = int(toko[0][1]) - int(toko[1][1]) toko[-1][0] = ' ' elif token_ip_stream[4][1] == '*': toko[2][1] = int(toko[0][1]) * int(toko[1][1]) toko[-1][0] = ' ' elif token_ip_stream[4][1] == '%': toko[2][1] = int(toko[0][1]) % int(toko[1][1]) toko[-1][0] = ' ' elif token_ip_stream[4][1] == '@': toko[2][1] = int(toko[0][1]) // int(toko[1][1]) toko[-1][0] = ' ' elif token_ip_stream[4][1] == '/': toko[2][1] = int(toko[0][1]) / int(toko[1][1]) toko[-1][0] = ' ' else: print("Syntax ERROR : you miss the operator or you have wrong syntax [Ex. ~ num1 = a + b .] or Statement MISSING : You miss the Statement end notation '.'") return toko def assignment_opp(token_ip_stream): toko = [] token_chk = 1 for i in range(0, len(toko)): tokens_id = toko[i][0] tokens_val = toko[i][1] for token in range(0, len(token_ip_stream)): if token_ip_stream[token][1] == '=': toko.append([token_ip_stream[token - 1][1], token_ip_stream[token + 1][1]]) return toko
# Given an array of integers, write a function that returns true if there is a triplet (a, b, c) that satisfies a2 + b2 = c2. # First way is brute force def is_triplet(array): # Base case, if array is under 3 elements, not possible if len(array) < 3: return False # Iterate through first element options for i in range(len(array) - 2): for j in range(i + 1, len(array) - 1): for k in range(j, len(array)): A = array[i] * array[i] B = array[j] * array[j] C = array[k] * array[k] # generate all combinations if (A + B == C) or (A + C == B) or (B + C == A): print(array[i], array[j], array[k]) return True return False print(is_triplet([3, 1, 4, 6, 5])) # above is N^3 # Next idea - take square of every number # sort the array of squared numbers # set the last element to A # find B and C def is_triplet(array): if len(array) < 3: return False # Take square of all elements array = [A*A for A in array] # Sort the squared value array.sort() # Set the last element to be A (the largest) # A^2 = B^2 + C^2 for i in range(len(array) - 1, 1, -1): # Fix A, this is a squared A = array[i] # Start from index 0 up to A j = 0 k = len(array) - 1 # last index # Keep going until we cross while j < k: B = array[j] C = array[k] # Check for a triple if (A == C + B): print(A, B, C) return True # Check if we need the numbers to be bigger elif (A > C + B): j = j+ 1 else: k = k -1 return False # Driver program to test above function */ array = [3, 1, 4, 6, 5] print(is_triplet(array))
def is_triplet(array): if len(array) < 3: return False for i in range(len(array) - 2): for j in range(i + 1, len(array) - 1): for k in range(j, len(array)): a = array[i] * array[i] b = array[j] * array[j] c = array[k] * array[k] if A + B == C or A + C == B or B + C == A: print(array[i], array[j], array[k]) return True return False print(is_triplet([3, 1, 4, 6, 5])) def is_triplet(array): if len(array) < 3: return False array = [A * A for a in array] array.sort() for i in range(len(array) - 1, 1, -1): a = array[i] j = 0 k = len(array) - 1 while j < k: b = array[j] c = array[k] if A == C + B: print(A, B, C) return True elif A > C + B: j = j + 1 else: k = k - 1 return False array = [3, 1, 4, 6, 5] print(is_triplet(array))
climacell_yr_map = { "6201": "48", # heavy freezing rain "6001": "12", # freezing rain "6200": "47", # light freezing rain "6000": "47", # freeing drizzle "7101": "48", # heavy ice pellets "7000": "12", # ice pellets "7102": "47", # light ice pellets "5101": "50", # heavy snow "5000": "13", # snow "5100": "49", # light snow "5001": "49", # flurries "8000": "11", # thunderstorm "4201": "10", # heavy rain "4001": "09", # rain "4200": "46", # light rain "4000": "46", # drizzle "2100": "15", # light fog "2000": "15", # fog "1001": "04", # cloudy "1102": "03", # mostly cloudy "1101": "02", # partly cloudy "1100": "01", # mostly clear "1000": "01", # clear "0": "unknown_weather", # UNKNOWN "3000": "01", # light wind "3001": "01", # wind "3002": "01", # strong wind }
climacell_yr_map = {'6201': '48', '6001': '12', '6200': '47', '6000': '47', '7101': '48', '7000': '12', '7102': '47', '5101': '50', '5000': '13', '5100': '49', '5001': '49', '8000': '11', '4201': '10', '4001': '09', '4200': '46', '4000': '46', '2100': '15', '2000': '15', '1001': '04', '1102': '03', '1101': '02', '1100': '01', '1000': '01', '0': 'unknown_weather', '3000': '01', '3001': '01', '3002': '01'}
# read answer, context, question # generate vocabulary file for elmo batcher pre = ['dev', 'train'] fs = ['answer', 'context', 'question'] result = set() for p in pre: for f in fs: print ('Processing ' + p + '.' +f) with open('../../data/' + p + '.' + f) as ff: content = ff.readlines() for line in content: for token in line.split(): result.add(token) ff = open('../../data/elmo_voca.txt', 'w') max_length = 0 for item in result: if len(item) > max_length: max_length = len(item) ff.write(item + '\n') ff.write('</S>\n') ff.write('<S>\n') ff.write('<UNK>\n') ff.close() print ('max length of the token in the data:' + str(max_length))
pre = ['dev', 'train'] fs = ['answer', 'context', 'question'] result = set() for p in pre: for f in fs: print('Processing ' + p + '.' + f) with open('../../data/' + p + '.' + f) as ff: content = ff.readlines() for line in content: for token in line.split(): result.add(token) ff = open('../../data/elmo_voca.txt', 'w') max_length = 0 for item in result: if len(item) > max_length: max_length = len(item) ff.write(item + '\n') ff.write('</S>\n') ff.write('<S>\n') ff.write('<UNK>\n') ff.close() print('max length of the token in the data:' + str(max_length))
''' Insert 5 numbers in the right position without using .sort() Then show the list orderned ''' my_list = [] for c in range(0, 5): num = int(input('Type a number: ')) if c == 0 or num > my_list[-1]: my_list.append(num) print('Add this number at the end.') else: pos = 0 while pos < len(my_list): if num <= my_list[pos]: my_list.insert(pos, num) print(f'The number was added in the {pos} position') break pos +=1 print(my_list)
""" Insert 5 numbers in the right position without using .sort() Then show the list orderned """ my_list = [] for c in range(0, 5): num = int(input('Type a number: ')) if c == 0 or num > my_list[-1]: my_list.append(num) print('Add this number at the end.') else: pos = 0 while pos < len(my_list): if num <= my_list[pos]: my_list.insert(pos, num) print(f'The number was added in the {pos} position') break pos += 1 print(my_list)
# Wi-Fi Diagnostic Tree print(' Please reboot your computer and try to connect.') answer = input('Did that fix the problem? ') if answer != 'yes': print('Reboot your computer and try to connect.') answer = input('Did that fix the problem? ') if answer != 'yes': print('Make sure the cables between the router and modem are ' 'plugged in firmly.') answer = input('Did that fix the problem? ') if answer != 'yes': print('Move the router to a new location and try to connect.') answer = input('Did that fix the problem? ') if answer != 'yes': print('Get a New router.')
print(' Please reboot your computer and try to connect.') answer = input('Did that fix the problem? ') if answer != 'yes': print('Reboot your computer and try to connect.') answer = input('Did that fix the problem? ') if answer != 'yes': print('Make sure the cables between the router and modem are plugged in firmly.') answer = input('Did that fix the problem? ') if answer != 'yes': print('Move the router to a new location and try to connect.') answer = input('Did that fix the problem? ') if answer != 'yes': print('Get a New router.')
class Dictionary: def __init__(self): self.words = set() def check(self, word): return word.lower() in self.words def load(self, dictionary): file = open(dictionary, 'r') for line in file: self.words.add(line.rstrip('\n')) file.close() return True def size(self): return len(self.words) def unload(self): return True
class Dictionary: def __init__(self): self.words = set() def check(self, word): return word.lower() in self.words def load(self, dictionary): file = open(dictionary, 'r') for line in file: self.words.add(line.rstrip('\n')) file.close() return True def size(self): return len(self.words) def unload(self): return True
class Map: def __init__(self, x, y): self.wall = False self.small_dot = False self.big_dot = False self.eaten = False self.x = x self.y = y #--- drawing on map ---# def draw_dot(self): if self.small_dot: if not self.eaten: fill(255, 255, 0) noStroke() ellipse(self.x, self.y, 3, 3) elif self.big_dot: if not self.eaten: fill(255, 255, 0) noStroke() ellipse(self.x, self.y, 6, 6)
class Map: def __init__(self, x, y): self.wall = False self.small_dot = False self.big_dot = False self.eaten = False self.x = x self.y = y def draw_dot(self): if self.small_dot: if not self.eaten: fill(255, 255, 0) no_stroke() ellipse(self.x, self.y, 3, 3) elif self.big_dot: if not self.eaten: fill(255, 255, 0) no_stroke() ellipse(self.x, self.y, 6, 6)
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. ### CONTROLS (non-tunable) ### # general TYPE_OF_RUN = train # train, test, test_episodes, render LOAD_MODEL_FROM = None SAVE_MODELS_TO = models/debugging_wmg_dynamic_state_Collins2018_train10_test15.pth # worker.py ENV = Collins2018_Env ENV_RANDOM_SEED = 2 # Use an integer for deterministic training. AGENT_RANDOM_SEED = 1 REPORTING_INTERVAL = 5_000 TOTAL_STEPS = 10_000_000 ANNEAL_LR = False NUM_EPISODES_TO_TEST = 5 # A3cAgent AGENT_NET = WMG_State_Network # WMG V2 = False LAYER_TYPE = GTrXL-I # Collins2018_Env MIN_NUM_OBJECTS = 3 MAX_NUM_OBJECTS = 10 NUM_ACTIONS = 3 NUM_REPEATS = 13 MAX_OBSERVATIONS = 15 ONE_HOT_PATTERNS = False ALLOW_DELIBERATION = False USE_SUCCESS_RATE = False HELDOUT_TESTING = True HELDOUT_NUM_OBJECTS = 15 ### HYPERPARAMETERS (tunable) ### # A3cAgent A3C_T_MAX = 16 LEARNING_RATE = 0.00016 DISCOUNT_FACTOR = 0.5 GRADIENT_CLIP = 16.0 ENTROPY_TERM_STRENGTH = 0.01 ADAM_EPS = 1e-06 REWARD_SCALE = 2.0 WEIGHT_DECAY = 0. # WMG WMG_MAX_OBS = 0 WMG_MAX_MEMOS = 15 WMG_INIT_MEMOS = 3 WMG_MEMO_SIZE = 20 WMG_NUM_LAYERS = 1 WMG_NUM_ATTENTION_HEADS = 2 WMG_ATTENTION_HEAD_SIZE = 24 WMG_HIDDEN_SIZE = 24 AC_HIDDEN_LAYER_SIZE = 64
type_of_run = train load_model_from = None save_models_to = models / debugging_wmg_dynamic_state_Collins2018_train10_test15.pth env = Collins2018_Env env_random_seed = 2 agent_random_seed = 1 reporting_interval = 5000 total_steps = 10000000 anneal_lr = False num_episodes_to_test = 5 agent_net = WMG_State_Network v2 = False layer_type = GTrXL - I min_num_objects = 3 max_num_objects = 10 num_actions = 3 num_repeats = 13 max_observations = 15 one_hot_patterns = False allow_deliberation = False use_success_rate = False heldout_testing = True heldout_num_objects = 15 a3_c_t_max = 16 learning_rate = 0.00016 discount_factor = 0.5 gradient_clip = 16.0 entropy_term_strength = 0.01 adam_eps = 1e-06 reward_scale = 2.0 weight_decay = 0.0 wmg_max_obs = 0 wmg_max_memos = 15 wmg_init_memos = 3 wmg_memo_size = 20 wmg_num_layers = 1 wmg_num_attention_heads = 2 wmg_attention_head_size = 24 wmg_hidden_size = 24 ac_hidden_layer_size = 64
class B: pass class A: pass
class B: pass class A: pass
class Solution: def maxScore(self, cards, k): pre = [0] for card in cards: pre.append(pre[-1] + card) ans = 0 n = len(pre) for i in range(k + 1): ans = max(pre[i] + pre[-1] - pre[n - 1 - k + i], ans) return ans
class Solution: def max_score(self, cards, k): pre = [0] for card in cards: pre.append(pre[-1] + card) ans = 0 n = len(pre) for i in range(k + 1): ans = max(pre[i] + pre[-1] - pre[n - 1 - k + i], ans) return ans
def fitness(L, books, D, B_scores, L_signuptimes, L_shipperday): #assert len(books) == len(L) score = 0. d = 0 for l in L: d += L_signuptimes[l] number_of_books = (D - d) * L_shipperday[l] score += sum(books[l][:number_of_books]) return score
def fitness(L, books, D, B_scores, L_signuptimes, L_shipperday): score = 0.0 d = 0 for l in L: d += L_signuptimes[l] number_of_books = (D - d) * L_shipperday[l] score += sum(books[l][:number_of_books]) return score
MESSAGE_PRIORITY = ( (-2, 'Stumm'), (-1, 'Ruhig'), (0, 'Normal'), (1, 'Wichtig'), (2, 'Emergency'), )
message_priority = ((-2, 'Stumm'), (-1, 'Ruhig'), (0, 'Normal'), (1, 'Wichtig'), (2, 'Emergency'))