content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def fibonacci(n): if n == 0: return (0, 1) else: a, b = fibonacci(n // 2) c = a * (b * 2 - a) d = a * a + b * b if n % 2 == 0: return (c, d) else: return (d, c + d) x = 0 y = 0 num = 1 while len(str(x)) < 1000: x, y = fibonacci(num) num += 1 print(len(str(y)),len(str(x)),num)
def fibonacci(n): if n == 0: return (0, 1) else: (a, b) = fibonacci(n // 2) c = a * (b * 2 - a) d = a * a + b * b if n % 2 == 0: return (c, d) else: return (d, c + d) x = 0 y = 0 num = 1 while len(str(x)) < 1000: (x, y) = fibonacci(num) num += 1 print(len(str(y)), len(str(x)), num)
def add(x, y): return x + y print(add(5, 7)) # -- Written as a lambda -- add = lambda x, y: x + y print(add(5, 7)) # Four parts # lambda # parameters # : # return value # Lambdas are meant to be short functions, often used without giving them a name. # For example, in conjunction with built-in function map # map applies the function to all values in the sequence def double(x): return x * 2 sequence = [1, 3, 5, 9] doubled = [ double(x) for x in sequence ] # Put the result of double(x) in a new list, for each of the values in `sequence` doubled = map(double, sequence) print(list(doubled)) # -- Written as a lambda -- sequence = [1, 3, 5, 9] doubled = map(lambda x: x * 2, sequence) print(list(doubled)) # -- Important to remember -- # Lambdas are just functions without a name. # They are used to return a value calculated from its parameters. # Almost always single-line, so don't do anything complicated in them. # Very often better to just define a function and give it a proper name.
def add(x, y): return x + y print(add(5, 7)) add = lambda x, y: x + y print(add(5, 7)) def double(x): return x * 2 sequence = [1, 3, 5, 9] doubled = [double(x) for x in sequence] doubled = map(double, sequence) print(list(doubled)) sequence = [1, 3, 5, 9] doubled = map(lambda x: x * 2, sequence) print(list(doubled))
""" atpthings.util -------------- Utilities """
""" atpthings.util -------------- Utilities """
def test_3_5_15(n): if (n % 15 == 0) and n != 0 : return 'FizzBuzz' elif n % 3 ==0 and n != 0: return 'Fizz' elif n % 5 == 0 and n != 0: return 'Buzz' else: return n def coundown(): for x in range (0,101): print(test_3_5_15(x)) coundown()
def test_3_5_15(n): if n % 15 == 0 and n != 0: return 'FizzBuzz' elif n % 3 == 0 and n != 0: return 'Fizz' elif n % 5 == 0 and n != 0: return 'Buzz' else: return n def coundown(): for x in range(0, 101): print(test_3_5_15(x)) coundown()
def average(data): if isinstance(data[0], int): return sum(data) / len(data) else: raw_data = list(map(lambda r: r.value, data)) return sum(raw_data) / len(raw_data) def minimum(data, index=0): if index == 0: data_slice = data else: data_slice = data[index:] return min(data_slice) def maximum(data, index=0): if index == 0: data_slice = data else: data_slice = data[index:] return max(data_slice) def data_range(data): return minimum(data), maximum(data) def median(data): sorted_data = sorted(data) data_length = len(data) index = (data_length - 1) // 2 if data_length % 2: return sorted_data[index] else: return (sorted_data[index] + sorted_data[index + 1]) / 2.0 def celsius_to_fahrenheit(celsius): return (celsius * 9 / 5) + 32 def fahrenheit_to_celsius(fahrenheit): return (fahrenheit - 32) * 5/9
def average(data): if isinstance(data[0], int): return sum(data) / len(data) else: raw_data = list(map(lambda r: r.value, data)) return sum(raw_data) / len(raw_data) def minimum(data, index=0): if index == 0: data_slice = data else: data_slice = data[index:] return min(data_slice) def maximum(data, index=0): if index == 0: data_slice = data else: data_slice = data[index:] return max(data_slice) def data_range(data): return (minimum(data), maximum(data)) def median(data): sorted_data = sorted(data) data_length = len(data) index = (data_length - 1) // 2 if data_length % 2: return sorted_data[index] else: return (sorted_data[index] + sorted_data[index + 1]) / 2.0 def celsius_to_fahrenheit(celsius): return celsius * 9 / 5 + 32 def fahrenheit_to_celsius(fahrenheit): return (fahrenheit - 32) * 5 / 9
EXCHANGE_MAX_NAME_LENGTH = 100 EXCHANGE_MAX_DESCRIPTION_LENGTH = 1000 FOLDER_FORBIDDEN_CHARS = {'/', '\\', ':', '*', '"', '<', '>', '?', '|'} FOLDER_MAX_NAME_LENGTH = 60 def validate_folder(folder): if 'name' not in folder: raise Exception('No name') for c in VALIDATE_FOLDER_FORBIDDEN_CHARS: if c in folder['name']: raise Exception('Not allowed in name: {}'.format(c)) if len(folder['name']) > VALIDATE_FOLDER_MAX_NAME_LENGTH: raise Exception('Exceed 60 characters: {}'.format(len(folder['name']))) GROUP_MAX_NAME_LENGTH = 49 GROUP_MAX_NOTE_LENGTH = 200 GROUP_MAX_ENTITY_COUNT_DELETE = 100
exchange_max_name_length = 100 exchange_max_description_length = 1000 folder_forbidden_chars = {'/', '\\', ':', '*', '"', '<', '>', '?', '|'} folder_max_name_length = 60 def validate_folder(folder): if 'name' not in folder: raise exception('No name') for c in VALIDATE_FOLDER_FORBIDDEN_CHARS: if c in folder['name']: raise exception('Not allowed in name: {}'.format(c)) if len(folder['name']) > VALIDATE_FOLDER_MAX_NAME_LENGTH: raise exception('Exceed 60 characters: {}'.format(len(folder['name']))) group_max_name_length = 49 group_max_note_length = 200 group_max_entity_count_delete = 100
class OperationStaResult(object): def __init__(self): self.total = None self.wait = None self.processing = None self.success = None self.fail = None self.stop = None self.timeout = None def getTotal(self): return self.total def setTotal(self, total): self.total = total def getWait(self): return self.wait def setWait(self, wait): self.wait = wait def getProcessing(self): return self.processing def setProcessing(self, processing): self.processing = processing def getSuccess(self): return self.success def setSuccess(self, success): self.success = success def getFail(self): return self.fail def setFail(self, fail): self.fail = fail def getStop(self): return self.stop def setStop(self, stop): self.stop = stop def getTimeout(self): return self.timeout def setTimeout(self, timeout): self.timeout = timeout
class Operationstaresult(object): def __init__(self): self.total = None self.wait = None self.processing = None self.success = None self.fail = None self.stop = None self.timeout = None def get_total(self): return self.total def set_total(self, total): self.total = total def get_wait(self): return self.wait def set_wait(self, wait): self.wait = wait def get_processing(self): return self.processing def set_processing(self, processing): self.processing = processing def get_success(self): return self.success def set_success(self, success): self.success = success def get_fail(self): return self.fail def set_fail(self, fail): self.fail = fail def get_stop(self): return self.stop def set_stop(self, stop): self.stop = stop def get_timeout(self): return self.timeout def set_timeout(self, timeout): self.timeout = timeout
""" This very high-level module determines/implements the specific behavior of the "standard" Necrobot running on the Crypt of the Necrobot server. Package Requirements -------------------- botbase util daily race stats user Dependencies ------------ mainchannel botbase/ cmd_admin daily/ cmd_daily racebot/ cmd_seedgen cmd_color cmd_role race/ cmd_racemake cmd_racestats user/ cmd_user pmbotchannel botbase/ cmd_admin daily/ cmd_daily racebot/ cmd_seedgen race/ cmd_racemake cmd_racestats user/ cmd_user """
""" This very high-level module determines/implements the specific behavior of the "standard" Necrobot running on the Crypt of the Necrobot server. Package Requirements -------------------- botbase util daily race stats user Dependencies ------------ mainchannel botbase/ cmd_admin daily/ cmd_daily racebot/ cmd_seedgen cmd_color cmd_role race/ cmd_racemake cmd_racestats user/ cmd_user pmbotchannel botbase/ cmd_admin daily/ cmd_daily racebot/ cmd_seedgen race/ cmd_racemake cmd_racestats user/ cmd_user """
# Copyright 2018 Google LLC # # 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. """Common configs for compatibility_lib.""" # IGNORED_DEPENDENCIES are not direct dependencies for many packages and are # not installed via pip, resulting in unresolvable high priority warnings. IGNORED_DEPENDENCIES = [ 'pip', 'setuptools', 'wheel', ] PKG_LIST = [ 'google-api-core', 'google-api-python-client', 'google-auth', 'google-cloud-bigquery', 'google-cloud-bigquery-datatransfer', 'google-cloud-bigtable', 'google-cloud-container', 'google-cloud-core', 'google-cloud-dataflow', 'google-cloud-datastore', 'google-cloud-dns', 'google-cloud-error-reporting', 'google-cloud-firestore', 'google-cloud-language', 'google-cloud-logging', 'google-cloud-monitoring', 'google-cloud-pubsub', 'google-cloud-resource-manager', 'google-cloud-runtimeconfig', 'google-cloud-spanner', 'google-cloud-speech', 'google-cloud-storage', 'google-cloud-trace', 'google-cloud-translate', 'google-cloud-videointelligence', 'google-cloud-vision', 'google-resumable-media', 'cloud-utils', 'google-apitools', 'googleapis-common-protos', 'grpc-google-iam-v1', 'grpcio', 'gsutil', 'opencensus', 'protobuf', 'protorpc', 'tensorboard', 'tensorflow', 'gcloud', ] PKG_PY_VERSION_NOT_SUPPORTED = { 2: ['tensorflow', ], 3: ['google-cloud-dataflow', ], }
"""Common configs for compatibility_lib.""" ignored_dependencies = ['pip', 'setuptools', 'wheel'] pkg_list = ['google-api-core', 'google-api-python-client', 'google-auth', 'google-cloud-bigquery', 'google-cloud-bigquery-datatransfer', 'google-cloud-bigtable', 'google-cloud-container', 'google-cloud-core', 'google-cloud-dataflow', 'google-cloud-datastore', 'google-cloud-dns', 'google-cloud-error-reporting', 'google-cloud-firestore', 'google-cloud-language', 'google-cloud-logging', 'google-cloud-monitoring', 'google-cloud-pubsub', 'google-cloud-resource-manager', 'google-cloud-runtimeconfig', 'google-cloud-spanner', 'google-cloud-speech', 'google-cloud-storage', 'google-cloud-trace', 'google-cloud-translate', 'google-cloud-videointelligence', 'google-cloud-vision', 'google-resumable-media', 'cloud-utils', 'google-apitools', 'googleapis-common-protos', 'grpc-google-iam-v1', 'grpcio', 'gsutil', 'opencensus', 'protobuf', 'protorpc', 'tensorboard', 'tensorflow', 'gcloud'] pkg_py_version_not_supported = {2: ['tensorflow'], 3: ['google-cloud-dataflow']}
""" Project: algorithms-exercises-using-python Created by robin1885@github on 17-2-20. """ def anagram_solution3(s1, s2): """ @rtype : bool @param s1: str1 @param s2: str2 @return: True or False """ pass
""" Project: algorithms-exercises-using-python Created by robin1885@github on 17-2-20. """ def anagram_solution3(s1, s2): """ @rtype : bool @param s1: str1 @param s2: str2 @return: True or False """ pass
# Medium # https://leetcode.com/problems/next-greater-element-ii/ # TC: O(N) # SC: O(N) class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: nums = nums + nums stack = [] out = [-1 for _ in nums] for index, num in enumerate(nums): while len(stack) and num > nums[stack[-1]]: out[stack.pop()] = num stack.append(index) return out[:len(nums) // 2]
class Solution: def next_greater_elements(self, nums: List[int]) -> List[int]: nums = nums + nums stack = [] out = [-1 for _ in nums] for (index, num) in enumerate(nums): while len(stack) and num > nums[stack[-1]]: out[stack.pop()] = num stack.append(index) return out[:len(nums) // 2]
days = ["Mon", "Thu", "Wed", "Thur", "Fri"] # list(mutable sequence) print(days) days.append("Sat") days.reverse() print(days)
days = ['Mon', 'Thu', 'Wed', 'Thur', 'Fri'] print(days) days.append('Sat') days.reverse() print(days)
class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() n = len(nums) ans = [] for i in range(0, n-2): if i > 0 and nums[i] == nums[i-1]: continue j,k = i + 1, n - 1 while j < k: s = nums[i] + nums[j] + nums[k] if s > 0: k -= 1 elif s < 0: j += 1 else: ans.append([nums[i], nums[j], nums[k]]) while j<k and nums[j] == nums[j+1]: j += 1 while j<k and nums[k] == nums[k-1]: k -= 1 j, k = j+1, k-1 return ans solution = Solution() print(solution.threeSum( [-1, 0, 1, 2, -1, -4]))
class Solution(object): def three_sum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() n = len(nums) ans = [] for i in range(0, n - 2): if i > 0 and nums[i] == nums[i - 1]: continue (j, k) = (i + 1, n - 1) while j < k: s = nums[i] + nums[j] + nums[k] if s > 0: k -= 1 elif s < 0: j += 1 else: ans.append([nums[i], nums[j], nums[k]]) while j < k and nums[j] == nums[j + 1]: j += 1 while j < k and nums[k] == nums[k - 1]: k -= 1 (j, k) = (j + 1, k - 1) return ans solution = solution() print(solution.threeSum([-1, 0, 1, 2, -1, -4]))
"""Custom exceptions for money operations""" # pylint: disable=missing-docstring class InvalidAmountError(ValueError): def __init__(self): super().__init__("Invalid amount for currency") class CurrencyMismatchError(ValueError): def __init__(self): super().__init__("Currencies must match") class InvalidOperandError(ValueError): def __init__(self): super().__init__("Invalid operand types for operation")
"""Custom exceptions for money operations""" class Invalidamounterror(ValueError): def __init__(self): super().__init__('Invalid amount for currency') class Currencymismatcherror(ValueError): def __init__(self): super().__init__('Currencies must match') class Invalidoperanderror(ValueError): def __init__(self): super().__init__('Invalid operand types for operation')
# -*- coding: utf-8 -*- """ file: gromacs_ti.py Functions for setting up a Gromacs based Thermodynamic Integration (TI) calculation. """
""" file: gromacs_ti.py Functions for setting up a Gromacs based Thermodynamic Integration (TI) calculation. """
class StreamPredictorConsumer(object): def __init__(self, name, algorithm=None, **kw): self.algorithm = algorithm self.name = name self.run_count = 0 self.runs = [] async def handle(self, payload): self.run_count += 1 try: results, err = await self.algorithm(payload) except Exception as emsg: err = str(emsg) results = {} self.runs.append({ 'run_count': self.run_count - 1, 'results': results, 'error': err })
class Streampredictorconsumer(object): def __init__(self, name, algorithm=None, **kw): self.algorithm = algorithm self.name = name self.run_count = 0 self.runs = [] async def handle(self, payload): self.run_count += 1 try: (results, err) = await self.algorithm(payload) except Exception as emsg: err = str(emsg) results = {} self.runs.append({'run_count': self.run_count - 1, 'results': results, 'error': err})
group_template_tag_prefix = 'DRKNS_GROUP_TEMPLATE_' # BEGIN / END unit_template_tag_prefix = 'DRKNS_UNIT_TEMPLATE_' # BEGIN / END groups_tag = 'DRKNS_GROUPS' group_units_tag = 'DRKNS_GROUP_UNITS' group_name_tag = 'DRKNS_GROUP_NAME' unit_name_tag = 'DRKNS_UNIT_NAME' dependency_groups_names_tag = 'DRKNS_DEPENDENCY_GROUPS_NAMES' all_group_names_tag = 'DRKNS_ALL_GROUPS_NAMES'
group_template_tag_prefix = 'DRKNS_GROUP_TEMPLATE_' unit_template_tag_prefix = 'DRKNS_UNIT_TEMPLATE_' groups_tag = 'DRKNS_GROUPS' group_units_tag = 'DRKNS_GROUP_UNITS' group_name_tag = 'DRKNS_GROUP_NAME' unit_name_tag = 'DRKNS_UNIT_NAME' dependency_groups_names_tag = 'DRKNS_DEPENDENCY_GROUPS_NAMES' all_group_names_tag = 'DRKNS_ALL_GROUPS_NAMES'
#!/usr/bin/env python3 def main(): for i in range(1,11): for j in range(1,11): if(j==10): print(i*j) else: print(i*j, end=" ") if __name__ == "__main__": main()
def main(): for i in range(1, 11): for j in range(1, 11): if j == 10: print(i * j) else: print(i * j, end=' ') if __name__ == '__main__': main()
def require(*types): ''' Return a decorator function that requires specified types. types -- tuple each element of which is a type or class or a tuple of several types or classes. Example to require a string then a numeric argument @require(str, (int, long, float)) will do the trick ''' def deco(func): ''' Decorator function to be returned from require(). Returns a function wrapper that validates argument types. ''' def wrapper (*args): ''' Function wrapper that checks argument types. ''' assert len(args) == len(types), 'Wrong number of arguments.' for a, t in zip(args, types): if type(t) == type(()): # any of these types are ok assert sum(isinstance(a, tp) for tp in t) > 0, '''\ %s is not a valid type. Valid types: %s ''' % (a, '\n'.join(str(x) for x in t)) assert isinstance(a, t), '%s is not a %s type' % (a, t) return func(*args) return wrapper return deco @require(int) def inter(int_val): print('int_val is ', int_val) @require(float) def floater(f_val): print('f_val is ', f_val) @require(str, (int, int, float)) def nameAge1(name, age): print('%s is %s years old' % (name, age)) # another way to do the same thing number = (int, float, int) @require(str, number) def nameAge2(name, age): print('%s is %s years old' % (name, age)) nameAge1('Emily', 8) # str, int ok nameAge1('Elizabeth', 4.5) # str, float ok nameAge2('Romita', 9) # str, long ok nameAge2('Emily', 'eight') # raises an exception!
def require(*types): """ Return a decorator function that requires specified types. types -- tuple each element of which is a type or class or a tuple of several types or classes. Example to require a string then a numeric argument @require(str, (int, long, float)) will do the trick """ def deco(func): """ Decorator function to be returned from require(). Returns a function wrapper that validates argument types. """ def wrapper(*args): """ Function wrapper that checks argument types. """ assert len(args) == len(types), 'Wrong number of arguments.' for (a, t) in zip(args, types): if type(t) == type(()): assert sum((isinstance(a, tp) for tp in t)) > 0, '%s is not a valid type. Valid types:\n%s\n' % (a, '\n'.join((str(x) for x in t))) assert isinstance(a, t), '%s is not a %s type' % (a, t) return func(*args) return wrapper return deco @require(int) def inter(int_val): print('int_val is ', int_val) @require(float) def floater(f_val): print('f_val is ', f_val) @require(str, (int, int, float)) def name_age1(name, age): print('%s is %s years old' % (name, age)) number = (int, float, int) @require(str, number) def name_age2(name, age): print('%s is %s years old' % (name, age)) name_age1('Emily', 8) name_age1('Elizabeth', 4.5) name_age2('Romita', 9) name_age2('Emily', 'eight')
def try_if(l): ret = 0 for x in l: if x == 1: ret += 2 elif x == 0: ret += 4 else: ret -= 2 return ret try_if([0, 1, 0, 1, 2, 3])
def try_if(l): ret = 0 for x in l: if x == 1: ret += 2 elif x == 0: ret += 4 else: ret -= 2 return ret try_if([0, 1, 0, 1, 2, 3])
class Solution(object): def XXX(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ i, j, k = 0, len(nums) - 1, 0 while k < len(nums): if nums[k] == 0 and k > i: nums[k], nums[i] = nums[i], nums[k] i += 1 elif nums[k] == 2 and k < j: nums[k], nums[j] = nums[j], nums[k] j -= 1 else: k += 1
class Solution(object): def xxx(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ (i, j, k) = (0, len(nums) - 1, 0) while k < len(nums): if nums[k] == 0 and k > i: (nums[k], nums[i]) = (nums[i], nums[k]) i += 1 elif nums[k] == 2 and k < j: (nums[k], nums[j]) = (nums[j], nums[k]) j -= 1 else: k += 1
class World: def __init__(self): pass def get_state(self): pass def execute_action(self,a): pass class GameTree: class GameNode: def __init__(self, state, action, par): self.state = state self.action = action self.visited = 0.0 self.par = par # key = the goal aka desired result, val = the times that goal was reached through this node self.goal_outcomes = dict() # key = state of the system in which this node can be accessed, val = list<GameNode> self.children = dict() def probability(self): """The likelihood of ending up in this state""" return self.visited / self.par.visited def probability_for(self, goal): """The likelihood that the given GameNode will lead the 'player' to their final goal""" return self.goal_outcomes.get(goal,0.0) / self.visited def get_utility(self, goal, policy_params): """Returns the utility that the 'player' will receive if they pick this action""" pass def apply_action(self, world): self.visited += 1.0 world.execute_action(self.action) def update(self, goal, win=0): """ Updates the number of times that this node led to the desired goal :param goal: the goal that was supposed to be reached :param win: 1 if goal was reached 0 otherwise :return: """ self.goal_outcomes[goal] = self.goal_outcomes.get(goal) + win self.par.update(goal, win) def prune(self): pass def get_next_move(self, state, goal, policy_params): """ Returns the best action for a certain goal given the current state of the world :param state: the current state of the world :param goal: the desired final outcome :param policy_params: additional data regarding the choice of a next action :return: GameNode with highest utility """ if goal in self.children: return self.children.get(goal)[0] best = None max_u = 0 nodes = self.children.get(state) for n in nodes: u = n.get_utility(goal, policy_params) if u > max_u: max_u = u best = n return best def __init__(self, policy): self.root = None self.cursor = None self.policy = policy def get_next_action(self, state, goal): if not self.cursor: self.cursor = self.root new_c = self.cursor.get_next_move(state, goal,self.policy) self.cursor = new_c return new_c class AIUser: def __init__(self, world): """ Creates a new AI user :param world: World instance wrapper for the environment """ self.world = world self.game_tree = GameTree(None) def learn(self): pass def execute(self, goal): state = self.world.get_state() while state != goal: a = self.game_tree.get_next_action(state, goal) a.apply_action(self.world) state = self.world.get_state()
class World: def __init__(self): pass def get_state(self): pass def execute_action(self, a): pass class Gametree: class Gamenode: def __init__(self, state, action, par): self.state = state self.action = action self.visited = 0.0 self.par = par self.goal_outcomes = dict() self.children = dict() def probability(self): """The likelihood of ending up in this state""" return self.visited / self.par.visited def probability_for(self, goal): """The likelihood that the given GameNode will lead the 'player' to their final goal""" return self.goal_outcomes.get(goal, 0.0) / self.visited def get_utility(self, goal, policy_params): """Returns the utility that the 'player' will receive if they pick this action""" pass def apply_action(self, world): self.visited += 1.0 world.execute_action(self.action) def update(self, goal, win=0): """ Updates the number of times that this node led to the desired goal :param goal: the goal that was supposed to be reached :param win: 1 if goal was reached 0 otherwise :return: """ self.goal_outcomes[goal] = self.goal_outcomes.get(goal) + win self.par.update(goal, win) def prune(self): pass def get_next_move(self, state, goal, policy_params): """ Returns the best action for a certain goal given the current state of the world :param state: the current state of the world :param goal: the desired final outcome :param policy_params: additional data regarding the choice of a next action :return: GameNode with highest utility """ if goal in self.children: return self.children.get(goal)[0] best = None max_u = 0 nodes = self.children.get(state) for n in nodes: u = n.get_utility(goal, policy_params) if u > max_u: max_u = u best = n return best def __init__(self, policy): self.root = None self.cursor = None self.policy = policy def get_next_action(self, state, goal): if not self.cursor: self.cursor = self.root new_c = self.cursor.get_next_move(state, goal, self.policy) self.cursor = new_c return new_c class Aiuser: def __init__(self, world): """ Creates a new AI user :param world: World instance wrapper for the environment """ self.world = world self.game_tree = game_tree(None) def learn(self): pass def execute(self, goal): state = self.world.get_state() while state != goal: a = self.game_tree.get_next_action(state, goal) a.apply_action(self.world) state = self.world.get_state()
namespace = '/map' routes = { 'getAllObjectDest': '/', }
namespace = '/map' routes = {'getAllObjectDest': '/'}
""" Exercise 1 Many of the built-in functions use variable-length argument tuples. For example, max and min can take any number of arguments: >>> max(1,2,3) 3 But sum does not. >>> sum(1,2,3) TypeError: sum expected at most 2 arguments, got 3 Write a function called sumall that takes any number of arguments and returns their sum. """ def sumall(*args): return sum(args) print(sumall(5, 9, 2)) print(sumall(15, 23, 343, 43)) print(sumall(234, 5, 9, 8, 4, 3, 0, 23))
""" Exercise 1 Many of the built-in functions use variable-length argument tuples. For example, max and min can take any number of arguments: >>> max(1,2,3) 3 But sum does not. >>> sum(1,2,3) TypeError: sum expected at most 2 arguments, got 3 Write a function called sumall that takes any number of arguments and returns their sum. """ def sumall(*args): return sum(args) print(sumall(5, 9, 2)) print(sumall(15, 23, 343, 43)) print(sumall(234, 5, 9, 8, 4, 3, 0, 23))
# Validar uma string def valida_str(texto, min, max): tam = len(texto) if tam < min or tam > max: return False else: return True # Programa Principal texto = input('Digite um string (3-15 caracteres): ') while valida_str(texto, 3, 15): texto = input('Digite uma string (3-15 caracteres): ') print(texto)
def valida_str(texto, min, max): tam = len(texto) if tam < min or tam > max: return False else: return True texto = input('Digite um string (3-15 caracteres): ') while valida_str(texto, 3, 15): texto = input('Digite uma string (3-15 caracteres): ') print(texto)
# # PySNMP MIB module HH3C-STACK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-STACK-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:29:46 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint") entPhysicalIndex, = mibBuilder.importSymbols("ENTITY-MIB", "entPhysicalIndex") hh3cCommon, = mibBuilder.importSymbols("HH3C-OID-MIB", "hh3cCommon") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Counter32, ModuleIdentity, Bits, Gauge32, TimeTicks, IpAddress, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, Unsigned32, MibIdentifier, Integer32, NotificationType, iso = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "ModuleIdentity", "Bits", "Gauge32", "TimeTicks", "IpAddress", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "Unsigned32", "MibIdentifier", "Integer32", "NotificationType", "iso") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") hh3cStack = ModuleIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 91)) hh3cStack.setRevisions(('2008-04-30 16:50',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: hh3cStack.setRevisionsDescriptions(('The initial revision of this MIB module.',)) if mibBuilder.loadTexts: hh3cStack.setLastUpdated('200804301650Z') if mibBuilder.loadTexts: hh3cStack.setOrganization('Hangzhou H3C Technologies Co., Ltd.') if mibBuilder.loadTexts: hh3cStack.setContactInfo('Platform Team H3C Technologies Co., Ltd. Hai-Dian District Beijing P.R. China Http://www.h3c.com Zip:100085') if mibBuilder.loadTexts: hh3cStack.setDescription('This MIB is used to manage STM (Stack Topology Management) information for IRF (Intelligent Resilient Framework) device. This MIB is applicable to products which support IRF. Some objects in this MIB may be used only for some specific products, so users should refer to the related documents to acquire more detailed information.') hh3cStackGlobalConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1)) hh3cStackMaxMember = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackMaxMember.setStatus('current') if mibBuilder.loadTexts: hh3cStackMaxMember.setDescription('The maximum number of members in a stack.') hh3cStackMemberNum = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackMemberNum.setStatus('current') if mibBuilder.loadTexts: hh3cStackMemberNum.setDescription('The number of members currently in a stack.') hh3cStackMaxConfigPriority = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackMaxConfigPriority.setStatus('current') if mibBuilder.loadTexts: hh3cStackMaxConfigPriority.setDescription('The highest priority that can be configured for a member in a stack.') hh3cStackAutoUpdate = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cStackAutoUpdate.setStatus('current') if mibBuilder.loadTexts: hh3cStackAutoUpdate.setDescription('The function for automatically updating the image from master to slave. When a new device tries to join a stack, the image version is checked. When this function is enabled, if the image version of the new device is different from that of the master, the image of the new device will be updated to be consistent with that of the master. When this function is disabled, the new device can not join the stack if the image version of the new device is different from that of the master. disabled: disable auto update function enabled: enable auto update function') hh3cStackMacPersistence = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("notPersist", 1), ("persistForSixMin", 2), ("persistForever", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cStackMacPersistence.setStatus('current') if mibBuilder.loadTexts: hh3cStackMacPersistence.setDescription('The mode of bridge MAC address persistence. When a stack starts, the bridge MAC address of master board will be used as that of the stack. If the master board leaves the stack, the bridge MAC address of the stack will change based on the mode of bridge MAC address persistence. notPersist: The bridge MAC address of the new master board will be used as that of the stack immediately. persistForSixMin: The bridge MAC address will be reserved for six minutes. In this period, if the master board which has left the stack rejoins the stack, the bridge MAC address of the stack will not change. Otherwise, the bridge MAC address of the new master board will be used as that of the stack. persistForever: Whether the master leaves or not, the bridge MAC address of the stack will never change.') hh3cStackLinkDelayInterval = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(200, 2000), ))).setUnits('millisecond').setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cStackLinkDelayInterval.setStatus('current') if mibBuilder.loadTexts: hh3cStackLinkDelayInterval.setDescription('The delay time for a device in a stack to report the change of stack port link status. If the delay time is configured, a device in a stack will not report the change immediately when the stack port link status changes to down. During the delay period, if the stack port link status is resumed, the device will ignore the current change of the stack port link status. If the stack port link status is not resumed after the delay time, the device will report the change. 0 means no delay, namely, the device will report the change as soon as the stack port link status changes to down. 0: no delay 200-2000(ms): delay time') hh3cStackTopology = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("chainConn", 1), ("ringConn", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackTopology.setStatus('current') if mibBuilder.loadTexts: hh3cStackTopology.setDescription('The topology of the stack. chainConn: chain connection ringConn: ring connection') hh3cStackDeviceConfigTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2), ) if mibBuilder.loadTexts: hh3cStackDeviceConfigTable.setStatus('current') if mibBuilder.loadTexts: hh3cStackDeviceConfigTable.setDescription('This table contains objects to manage device information in a stack.') hh3cStackDeviceConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex")) if mibBuilder.loadTexts: hh3cStackDeviceConfigEntry.setStatus('current') if mibBuilder.loadTexts: hh3cStackDeviceConfigEntry.setDescription('This table contains objects to manage device information in a stack.') hh3cStackMemberID = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackMemberID.setStatus('current') if mibBuilder.loadTexts: hh3cStackMemberID.setDescription('The member ID of the device in a stack.') hh3cStackConfigMemberID = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cStackConfigMemberID.setStatus('current') if mibBuilder.loadTexts: hh3cStackConfigMemberID.setDescription('The configured member ID of the device. The valid value ranges from 1 to the value of hh3cStackMaxMember. After the member ID is configured for a device, if this ID is not the same with that of another device, the ID will be used as the member ID of the device when the device reboots. If a same ID exists, the member ID of the device will be set as another exclusive ID automatically.') hh3cStackPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cStackPriority.setStatus('current') if mibBuilder.loadTexts: hh3cStackPriority.setDescription('The priority of a device in a stack. The valid value ranges from 1 to the value of hh3cStackMaxConfigPriority.') hh3cStackPortNum = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackPortNum.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortNum.setDescription('The number of stack ports which is enabled in a device.') hh3cStackPortMaxNum = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackPortMaxNum.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortMaxNum.setDescription('The maximum number of stack ports in a device.') hh3cStackBoardConfigTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 91, 3), ) if mibBuilder.loadTexts: hh3cStackBoardConfigTable.setStatus('current') if mibBuilder.loadTexts: hh3cStackBoardConfigTable.setDescription('This table contains objects to manage board information of the device in a stack.') hh3cStackBoardConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 91, 3, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex")) if mibBuilder.loadTexts: hh3cStackBoardConfigEntry.setStatus('current') if mibBuilder.loadTexts: hh3cStackBoardConfigEntry.setDescription('This table contains objects to manage board information of the device in a stack.') hh3cStackBoardRole = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("slave", 1), ("master", 2), ("loading", 3), ("other", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackBoardRole.setStatus('current') if mibBuilder.loadTexts: hh3cStackBoardRole.setDescription('The role of the board in a stack. slave: slave board master: master board loading: slave board whose image version is different from that of the master board. other: other') hh3cStackBoardBelongtoMember = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 3, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackBoardBelongtoMember.setStatus('current') if mibBuilder.loadTexts: hh3cStackBoardBelongtoMember.setDescription('The member ID of the device where the current board resides in a stack.') hh3cStackPortInfoTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 91, 4), ) if mibBuilder.loadTexts: hh3cStackPortInfoTable.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortInfoTable.setDescription('This table contains objects to manage stack port information of a device in a stack.') hh3cStackPortInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 91, 4, 1), ).setIndexNames((0, "HH3C-STACK-MIB", "hh3cStackMemberID"), (0, "HH3C-STACK-MIB", "hh3cStackPortIndex")) if mibBuilder.loadTexts: hh3cStackPortInfoEntry.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortInfoEntry.setDescription('This table contains objects to manage stack port information of a device in a stack.') hh3cStackPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 4, 1, 1), Integer32()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hh3cStackPortIndex.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortIndex.setDescription('The index of a stack port of the device in a stack.') hh3cStackPortEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 4, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackPortEnable.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortEnable.setDescription("The status of the stack port of the device in a stack. If no physical port is added to the stack port, its status is 'disabled'; otherwise, its status is 'enabled'. disabled: The stack port is disabled. enabled: The stack port is enabled.") hh3cStackPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 4, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("up", 1), ("down", 2), ("silent", 3), ("disabled", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackPortStatus.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortStatus.setDescription('The link status of the stack port of the device in a stack. up: The link status of a stack port with reasonable physical connection is up. down: The link status of a stack port without physical connection is down. silent: The link status of a stack port which can not be used normally is silent. disabled: The link status of a stack port in disabled status is disabled.') hh3cStackNeighbor = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 4, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cStackNeighbor.setStatus('current') if mibBuilder.loadTexts: hh3cStackNeighbor.setDescription("The member ID of the stack port's neighbor in a stack. 0 means no neighbor exists.") hh3cStackPhyPortInfoTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 91, 5), ) if mibBuilder.loadTexts: hh3cStackPhyPortInfoTable.setStatus('current') if mibBuilder.loadTexts: hh3cStackPhyPortInfoTable.setDescription('This table contains objects to manage the information for physical ports which can be used for physical connection of stack port in a stack.') hh3cStackPhyPortInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 91, 5, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex")) if mibBuilder.loadTexts: hh3cStackPhyPortInfoEntry.setStatus('current') if mibBuilder.loadTexts: hh3cStackPhyPortInfoEntry.setDescription('This table contains objects to manage the information for physical ports which can be used for physical connection of stack port in a stack.') hh3cStackBelongtoPort = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 91, 5, 1, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cStackBelongtoPort.setStatus('current') if mibBuilder.loadTexts: hh3cStackBelongtoPort.setDescription('The index of the stack port to which the physical port is added. 0 means the physical port is not added to any stack port. The value will be valid after the device in the stack reboots.') hh3cStackTrap = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 91, 6)) hh3cStackTrapOjbects = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 91, 6, 0)) hh3cStackPortLinkStatusChange = NotificationType((1, 3, 6, 1, 4, 1, 25506, 2, 91, 6, 0, 1)).setObjects(("HH3C-STACK-MIB", "hh3cStackMemberID"), ("HH3C-STACK-MIB", "hh3cStackPortIndex"), ("HH3C-STACK-MIB", "hh3cStackPortStatus")) if mibBuilder.loadTexts: hh3cStackPortLinkStatusChange.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortLinkStatusChange.setDescription('The hh3cStackPortLinkStatusChange trap indicates that the link status of the stack port has changed.') hh3cStackTopologyChange = NotificationType((1, 3, 6, 1, 4, 1, 25506, 2, 91, 6, 0, 2)).setObjects(("HH3C-STACK-MIB", "hh3cStackTopology")) if mibBuilder.loadTexts: hh3cStackTopologyChange.setStatus('current') if mibBuilder.loadTexts: hh3cStackTopologyChange.setDescription('The hh3cStackTopologyChange trap indicates that the topology type of the stack has changed.') mibBuilder.exportSymbols("HH3C-STACK-MIB", hh3cStackTopology=hh3cStackTopology, hh3cStackConfigMemberID=hh3cStackConfigMemberID, hh3cStackBelongtoPort=hh3cStackBelongtoPort, hh3cStackTopologyChange=hh3cStackTopologyChange, hh3cStackMacPersistence=hh3cStackMacPersistence, hh3cStackGlobalConfig=hh3cStackGlobalConfig, hh3cStackPortIndex=hh3cStackPortIndex, hh3cStackPriority=hh3cStackPriority, hh3cStackPhyPortInfoTable=hh3cStackPhyPortInfoTable, hh3cStackTrap=hh3cStackTrap, hh3cStackPortMaxNum=hh3cStackPortMaxNum, hh3cStackLinkDelayInterval=hh3cStackLinkDelayInterval, hh3cStackMemberNum=hh3cStackMemberNum, hh3cStackPortEnable=hh3cStackPortEnable, hh3cStackMaxMember=hh3cStackMaxMember, hh3cStackDeviceConfigEntry=hh3cStackDeviceConfigEntry, hh3cStackMemberID=hh3cStackMemberID, hh3cStackBoardConfigEntry=hh3cStackBoardConfigEntry, hh3cStackPhyPortInfoEntry=hh3cStackPhyPortInfoEntry, hh3cStackPortStatus=hh3cStackPortStatus, PYSNMP_MODULE_ID=hh3cStack, hh3cStackBoardConfigTable=hh3cStackBoardConfigTable, hh3cStackPortNum=hh3cStackPortNum, hh3cStackNeighbor=hh3cStackNeighbor, hh3cStackBoardBelongtoMember=hh3cStackBoardBelongtoMember, hh3cStack=hh3cStack, hh3cStackBoardRole=hh3cStackBoardRole, hh3cStackDeviceConfigTable=hh3cStackDeviceConfigTable, hh3cStackPortInfoEntry=hh3cStackPortInfoEntry, hh3cStackAutoUpdate=hh3cStackAutoUpdate, hh3cStackTrapOjbects=hh3cStackTrapOjbects, hh3cStackPortLinkStatusChange=hh3cStackPortLinkStatusChange, hh3cStackPortInfoTable=hh3cStackPortInfoTable, hh3cStackMaxConfigPriority=hh3cStackMaxConfigPriority)
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_range_constraint, constraints_intersection, single_value_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ValueRangeConstraint', 'ConstraintsIntersection', 'SingleValueConstraint', 'ValueSizeConstraint') (ent_physical_index,) = mibBuilder.importSymbols('ENTITY-MIB', 'entPhysicalIndex') (hh3c_common,) = mibBuilder.importSymbols('HH3C-OID-MIB', 'hh3cCommon') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (counter32, module_identity, bits, gauge32, time_ticks, ip_address, object_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, counter64, unsigned32, mib_identifier, integer32, notification_type, iso) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter32', 'ModuleIdentity', 'Bits', 'Gauge32', 'TimeTicks', 'IpAddress', 'ObjectIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter64', 'Unsigned32', 'MibIdentifier', 'Integer32', 'NotificationType', 'iso') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') hh3c_stack = module_identity((1, 3, 6, 1, 4, 1, 25506, 2, 91)) hh3cStack.setRevisions(('2008-04-30 16:50',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: hh3cStack.setRevisionsDescriptions(('The initial revision of this MIB module.',)) if mibBuilder.loadTexts: hh3cStack.setLastUpdated('200804301650Z') if mibBuilder.loadTexts: hh3cStack.setOrganization('Hangzhou H3C Technologies Co., Ltd.') if mibBuilder.loadTexts: hh3cStack.setContactInfo('Platform Team H3C Technologies Co., Ltd. Hai-Dian District Beijing P.R. China Http://www.h3c.com Zip:100085') if mibBuilder.loadTexts: hh3cStack.setDescription('This MIB is used to manage STM (Stack Topology Management) information for IRF (Intelligent Resilient Framework) device. This MIB is applicable to products which support IRF. Some objects in this MIB may be used only for some specific products, so users should refer to the related documents to acquire more detailed information.') hh3c_stack_global_config = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1)) hh3c_stack_max_member = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hh3cStackMaxMember.setStatus('current') if mibBuilder.loadTexts: hh3cStackMaxMember.setDescription('The maximum number of members in a stack.') hh3c_stack_member_num = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hh3cStackMemberNum.setStatus('current') if mibBuilder.loadTexts: hh3cStackMemberNum.setDescription('The number of members currently in a stack.') hh3c_stack_max_config_priority = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hh3cStackMaxConfigPriority.setStatus('current') if mibBuilder.loadTexts: hh3cStackMaxConfigPriority.setDescription('The highest priority that can be configured for a member in a stack.') hh3c_stack_auto_update = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('disabled', 1), ('enabled', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: hh3cStackAutoUpdate.setStatus('current') if mibBuilder.loadTexts: hh3cStackAutoUpdate.setDescription('The function for automatically updating the image from master to slave. When a new device tries to join a stack, the image version is checked. When this function is enabled, if the image version of the new device is different from that of the master, the image of the new device will be updated to be consistent with that of the master. When this function is disabled, the new device can not join the stack if the image version of the new device is different from that of the master. disabled: disable auto update function enabled: enable auto update function') hh3c_stack_mac_persistence = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('notPersist', 1), ('persistForSixMin', 2), ('persistForever', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: hh3cStackMacPersistence.setStatus('current') if mibBuilder.loadTexts: hh3cStackMacPersistence.setDescription('The mode of bridge MAC address persistence. When a stack starts, the bridge MAC address of master board will be used as that of the stack. If the master board leaves the stack, the bridge MAC address of the stack will change based on the mode of bridge MAC address persistence. notPersist: The bridge MAC address of the new master board will be used as that of the stack immediately. persistForSixMin: The bridge MAC address will be reserved for six minutes. In this period, if the master board which has left the stack rejoins the stack, the bridge MAC address of the stack will not change. Otherwise, the bridge MAC address of the new master board will be used as that of the stack. persistForever: Whether the master leaves or not, the bridge MAC address of the stack will never change.') hh3c_stack_link_delay_interval = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 6), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(0, 0), value_range_constraint(200, 2000)))).setUnits('millisecond').setMaxAccess('readwrite') if mibBuilder.loadTexts: hh3cStackLinkDelayInterval.setStatus('current') if mibBuilder.loadTexts: hh3cStackLinkDelayInterval.setDescription('The delay time for a device in a stack to report the change of stack port link status. If the delay time is configured, a device in a stack will not report the change immediately when the stack port link status changes to down. During the delay period, if the stack port link status is resumed, the device will ignore the current change of the stack port link status. If the stack port link status is not resumed after the delay time, the device will report the change. 0 means no delay, namely, the device will report the change as soon as the stack port link status changes to down. 0: no delay 200-2000(ms): delay time') hh3c_stack_topology = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 91, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('chainConn', 1), ('ringConn', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: hh3cStackTopology.setStatus('current') if mibBuilder.loadTexts: hh3cStackTopology.setDescription('The topology of the stack. chainConn: chain connection ringConn: ring connection') hh3c_stack_device_config_table = mib_table((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2)) if mibBuilder.loadTexts: hh3cStackDeviceConfigTable.setStatus('current') if mibBuilder.loadTexts: hh3cStackDeviceConfigTable.setDescription('This table contains objects to manage device information in a stack.') hh3c_stack_device_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2, 1)).setIndexNames((0, 'ENTITY-MIB', 'entPhysicalIndex')) if mibBuilder.loadTexts: hh3cStackDeviceConfigEntry.setStatus('current') if mibBuilder.loadTexts: hh3cStackDeviceConfigEntry.setDescription('This table contains objects to manage device information in a stack.') hh3c_stack_member_id = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hh3cStackMemberID.setStatus('current') if mibBuilder.loadTexts: hh3cStackMemberID.setDescription('The member ID of the device in a stack.') hh3c_stack_config_member_id = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2, 1, 2), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: hh3cStackConfigMemberID.setStatus('current') if mibBuilder.loadTexts: hh3cStackConfigMemberID.setDescription('The configured member ID of the device. The valid value ranges from 1 to the value of hh3cStackMaxMember. After the member ID is configured for a device, if this ID is not the same with that of another device, the ID will be used as the member ID of the device when the device reboots. If a same ID exists, the member ID of the device will be set as another exclusive ID automatically.') hh3c_stack_priority = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2, 1, 3), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: hh3cStackPriority.setStatus('current') if mibBuilder.loadTexts: hh3cStackPriority.setDescription('The priority of a device in a stack. The valid value ranges from 1 to the value of hh3cStackMaxConfigPriority.') hh3c_stack_port_num = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2, 1, 4), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hh3cStackPortNum.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortNum.setDescription('The number of stack ports which is enabled in a device.') hh3c_stack_port_max_num = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 91, 2, 1, 5), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hh3cStackPortMaxNum.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortMaxNum.setDescription('The maximum number of stack ports in a device.') hh3c_stack_board_config_table = mib_table((1, 3, 6, 1, 4, 1, 25506, 2, 91, 3)) if mibBuilder.loadTexts: hh3cStackBoardConfigTable.setStatus('current') if mibBuilder.loadTexts: hh3cStackBoardConfigTable.setDescription('This table contains objects to manage board information of the device in a stack.') hh3c_stack_board_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 25506, 2, 91, 3, 1)).setIndexNames((0, 'ENTITY-MIB', 'entPhysicalIndex')) if mibBuilder.loadTexts: hh3cStackBoardConfigEntry.setStatus('current') if mibBuilder.loadTexts: hh3cStackBoardConfigEntry.setDescription('This table contains objects to manage board information of the device in a stack.') hh3c_stack_board_role = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 91, 3, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('slave', 1), ('master', 2), ('loading', 3), ('other', 4)))).setMaxAccess('readonly') if mibBuilder.loadTexts: hh3cStackBoardRole.setStatus('current') if mibBuilder.loadTexts: hh3cStackBoardRole.setDescription('The role of the board in a stack. slave: slave board master: master board loading: slave board whose image version is different from that of the master board. other: other') hh3c_stack_board_belongto_member = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 91, 3, 1, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hh3cStackBoardBelongtoMember.setStatus('current') if mibBuilder.loadTexts: hh3cStackBoardBelongtoMember.setDescription('The member ID of the device where the current board resides in a stack.') hh3c_stack_port_info_table = mib_table((1, 3, 6, 1, 4, 1, 25506, 2, 91, 4)) if mibBuilder.loadTexts: hh3cStackPortInfoTable.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortInfoTable.setDescription('This table contains objects to manage stack port information of a device in a stack.') hh3c_stack_port_info_entry = mib_table_row((1, 3, 6, 1, 4, 1, 25506, 2, 91, 4, 1)).setIndexNames((0, 'HH3C-STACK-MIB', 'hh3cStackMemberID'), (0, 'HH3C-STACK-MIB', 'hh3cStackPortIndex')) if mibBuilder.loadTexts: hh3cStackPortInfoEntry.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortInfoEntry.setDescription('This table contains objects to manage stack port information of a device in a stack.') hh3c_stack_port_index = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 91, 4, 1, 1), integer32()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: hh3cStackPortIndex.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortIndex.setDescription('The index of a stack port of the device in a stack.') hh3c_stack_port_enable = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 91, 4, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('disabled', 1), ('enabled', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: hh3cStackPortEnable.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortEnable.setDescription("The status of the stack port of the device in a stack. If no physical port is added to the stack port, its status is 'disabled'; otherwise, its status is 'enabled'. disabled: The stack port is disabled. enabled: The stack port is enabled.") hh3c_stack_port_status = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 91, 4, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('up', 1), ('down', 2), ('silent', 3), ('disabled', 4)))).setMaxAccess('readonly') if mibBuilder.loadTexts: hh3cStackPortStatus.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortStatus.setDescription('The link status of the stack port of the device in a stack. up: The link status of a stack port with reasonable physical connection is up. down: The link status of a stack port without physical connection is down. silent: The link status of a stack port which can not be used normally is silent. disabled: The link status of a stack port in disabled status is disabled.') hh3c_stack_neighbor = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 91, 4, 1, 4), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hh3cStackNeighbor.setStatus('current') if mibBuilder.loadTexts: hh3cStackNeighbor.setDescription("The member ID of the stack port's neighbor in a stack. 0 means no neighbor exists.") hh3c_stack_phy_port_info_table = mib_table((1, 3, 6, 1, 4, 1, 25506, 2, 91, 5)) if mibBuilder.loadTexts: hh3cStackPhyPortInfoTable.setStatus('current') if mibBuilder.loadTexts: hh3cStackPhyPortInfoTable.setDescription('This table contains objects to manage the information for physical ports which can be used for physical connection of stack port in a stack.') hh3c_stack_phy_port_info_entry = mib_table_row((1, 3, 6, 1, 4, 1, 25506, 2, 91, 5, 1)).setIndexNames((0, 'ENTITY-MIB', 'entPhysicalIndex')) if mibBuilder.loadTexts: hh3cStackPhyPortInfoEntry.setStatus('current') if mibBuilder.loadTexts: hh3cStackPhyPortInfoEntry.setDescription('This table contains objects to manage the information for physical ports which can be used for physical connection of stack port in a stack.') hh3c_stack_belongto_port = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 91, 5, 1, 1), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: hh3cStackBelongtoPort.setStatus('current') if mibBuilder.loadTexts: hh3cStackBelongtoPort.setDescription('The index of the stack port to which the physical port is added. 0 means the physical port is not added to any stack port. The value will be valid after the device in the stack reboots.') hh3c_stack_trap = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 2, 91, 6)) hh3c_stack_trap_ojbects = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 2, 91, 6, 0)) hh3c_stack_port_link_status_change = notification_type((1, 3, 6, 1, 4, 1, 25506, 2, 91, 6, 0, 1)).setObjects(('HH3C-STACK-MIB', 'hh3cStackMemberID'), ('HH3C-STACK-MIB', 'hh3cStackPortIndex'), ('HH3C-STACK-MIB', 'hh3cStackPortStatus')) if mibBuilder.loadTexts: hh3cStackPortLinkStatusChange.setStatus('current') if mibBuilder.loadTexts: hh3cStackPortLinkStatusChange.setDescription('The hh3cStackPortLinkStatusChange trap indicates that the link status of the stack port has changed.') hh3c_stack_topology_change = notification_type((1, 3, 6, 1, 4, 1, 25506, 2, 91, 6, 0, 2)).setObjects(('HH3C-STACK-MIB', 'hh3cStackTopology')) if mibBuilder.loadTexts: hh3cStackTopologyChange.setStatus('current') if mibBuilder.loadTexts: hh3cStackTopologyChange.setDescription('The hh3cStackTopologyChange trap indicates that the topology type of the stack has changed.') mibBuilder.exportSymbols('HH3C-STACK-MIB', hh3cStackTopology=hh3cStackTopology, hh3cStackConfigMemberID=hh3cStackConfigMemberID, hh3cStackBelongtoPort=hh3cStackBelongtoPort, hh3cStackTopologyChange=hh3cStackTopologyChange, hh3cStackMacPersistence=hh3cStackMacPersistence, hh3cStackGlobalConfig=hh3cStackGlobalConfig, hh3cStackPortIndex=hh3cStackPortIndex, hh3cStackPriority=hh3cStackPriority, hh3cStackPhyPortInfoTable=hh3cStackPhyPortInfoTable, hh3cStackTrap=hh3cStackTrap, hh3cStackPortMaxNum=hh3cStackPortMaxNum, hh3cStackLinkDelayInterval=hh3cStackLinkDelayInterval, hh3cStackMemberNum=hh3cStackMemberNum, hh3cStackPortEnable=hh3cStackPortEnable, hh3cStackMaxMember=hh3cStackMaxMember, hh3cStackDeviceConfigEntry=hh3cStackDeviceConfigEntry, hh3cStackMemberID=hh3cStackMemberID, hh3cStackBoardConfigEntry=hh3cStackBoardConfigEntry, hh3cStackPhyPortInfoEntry=hh3cStackPhyPortInfoEntry, hh3cStackPortStatus=hh3cStackPortStatus, PYSNMP_MODULE_ID=hh3cStack, hh3cStackBoardConfigTable=hh3cStackBoardConfigTable, hh3cStackPortNum=hh3cStackPortNum, hh3cStackNeighbor=hh3cStackNeighbor, hh3cStackBoardBelongtoMember=hh3cStackBoardBelongtoMember, hh3cStack=hh3cStack, hh3cStackBoardRole=hh3cStackBoardRole, hh3cStackDeviceConfigTable=hh3cStackDeviceConfigTable, hh3cStackPortInfoEntry=hh3cStackPortInfoEntry, hh3cStackAutoUpdate=hh3cStackAutoUpdate, hh3cStackTrapOjbects=hh3cStackTrapOjbects, hh3cStackPortLinkStatusChange=hh3cStackPortLinkStatusChange, hh3cStackPortInfoTable=hh3cStackPortInfoTable, hh3cStackMaxConfigPriority=hh3cStackMaxConfigPriority)
l1=[1,2,3,4,5,6,7,8,9,10] l2=list(map(lambda n:n*n,l1)) print('l2:',l2) l3=list((map(lambda n,m:n*m,l1,l2)))#map function can take more than one sequence argument print('l3:',l3) #if the length of the sequence is not equal then function will perform till same length l3.pop() print('popped l3:',l3) l4=list(map(lambda n,m,o:n+m+o,l1,l2,l3)) print('l4:',l4)
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] l2 = list(map(lambda n: n * n, l1)) print('l2:', l2) l3 = list(map(lambda n, m: n * m, l1, l2)) print('l3:', l3) l3.pop() print('popped l3:', l3) l4 = list(map(lambda n, m, o: n + m + o, l1, l2, l3)) print('l4:', l4)
{ 'targets': [ { 'target_name': 'gpiobcm2835nodejs', 'sources': [ 'src/gpiobcm2835nodejs.cc' ], "cflags" : [ "-lrt -lbcm2835" ], 'conditions': [ ['OS=="linux"', { 'cflags!': [ '-lrt -lbcm2835', ], }], ], 'include_dirs': [ 'src/gpio_functions', ], 'libraries': [ '-lbcm2835' ] } ] }
{'targets': [{'target_name': 'gpiobcm2835nodejs', 'sources': ['src/gpiobcm2835nodejs.cc'], 'cflags': ['-lrt -lbcm2835'], 'conditions': [['OS=="linux"', {'cflags!': ['-lrt -lbcm2835']}]], 'include_dirs': ['src/gpio_functions'], 'libraries': ['-lbcm2835']}]}
class SpekulatioError(Exception): pass class FrontmatterError(SpekulatioError): pass
class Spekulatioerror(Exception): pass class Frontmattererror(SpekulatioError): pass
class Sql: make_itemdb = ''' CREATE TABLE IF NOT EXISTS ITEMDB ( ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, PRICE REAL, REGDATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ''' insert_itemdb = ''' INSERT INTO ITEMDB (NAME, PRICE) VALUES (?,?) ''' update_itemdb = ''' UPDATE ITEMDB SET NAME = ?, PRICE = ?, WHERE ID = ?''' delete_itemdb = ''' DELET FROM ITEMDB WHERE ID = ? ''' select_itemdb = ''' SELECT * FROM ITEMDB WHERE ID = ? ''' selectall_itemdb = ''' SELECT * FROM ITEMDB '''
class Sql: make_itemdb = '\n CREATE TABLE IF NOT EXISTS ITEMDB (\n ID INTEGER PRIMARY KEY AUTOINCREMENT,\n NAME TEXT,\n PRICE REAL,\n REGDATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n )\n ' insert_itemdb = '\n INSERT INTO ITEMDB (NAME, PRICE) VALUES (?,?)\n ' update_itemdb = '\n UPDATE ITEMDB SET NAME = ?, PRICE = ?, WHERE ID = ?' delete_itemdb = '\n DELET FROM ITEMDB WHERE ID = ?\n ' select_itemdb = '\n SELECT * FROM ITEMDB WHERE ID = ?\n ' selectall_itemdb = '\n SELECT * FROM ITEMDB\n '
def getbounds(img): return tuple([min((si[i] for si in img)) for i in range(2)]), \ tuple([max((si[i] for si in img)) for i in range(2)]) def enhance(img, setval, algo): bounds = getbounds(img) offsets = ((1, 1), (0, 1), (-1, 1), (1, 0), (0, 0), (-1, 0), (1, -1), (0, -1), (-1, -1)) overhang = 2 n_imgset = set() for x in range(bounds[0][0] - overhang, bounds[1][0] + overhang): for y in range(bounds[0][1] - overhang, bounds[1][1] + overhang): idx = sum([(((x + ox, y + oy) in img) == setval) * 2 ** p for p, (ox, oy) in enumerate(offsets)]) if (algo[idx] != setval) == algo[0]: n_imgset.add((x, y)) if algo[0]: setval = not setval return n_imgset, setval def main(input_file='input.txt', verbose=False): algo_raw, img_raw = open(input_file).read().split('\n\n') algo, img_raw = tuple(c == '#' for c in algo_raw), img_raw.split('\n') img = set([(x, y) for x in range(len(img_raw[0])) for y in range(len(img_raw)) if img_raw[y][x] == '#']) setval = True for step in range(50): img, setval = enhance(img, setval, algo) if step == 1: p1 = len(img) p2 = len(img) if verbose: print('Part 1: {0[0]}\nPart 2: {0[1]}'.format([p1, p2])) return p1, p2 if __name__ == "__main__": main(verbose=True)
def getbounds(img): return (tuple([min((si[i] for si in img)) for i in range(2)]), tuple([max((si[i] for si in img)) for i in range(2)])) def enhance(img, setval, algo): bounds = getbounds(img) offsets = ((1, 1), (0, 1), (-1, 1), (1, 0), (0, 0), (-1, 0), (1, -1), (0, -1), (-1, -1)) overhang = 2 n_imgset = set() for x in range(bounds[0][0] - overhang, bounds[1][0] + overhang): for y in range(bounds[0][1] - overhang, bounds[1][1] + overhang): idx = sum([(((x + ox, y + oy) in img) == setval) * 2 ** p for (p, (ox, oy)) in enumerate(offsets)]) if (algo[idx] != setval) == algo[0]: n_imgset.add((x, y)) if algo[0]: setval = not setval return (n_imgset, setval) def main(input_file='input.txt', verbose=False): (algo_raw, img_raw) = open(input_file).read().split('\n\n') (algo, img_raw) = (tuple((c == '#' for c in algo_raw)), img_raw.split('\n')) img = set([(x, y) for x in range(len(img_raw[0])) for y in range(len(img_raw)) if img_raw[y][x] == '#']) setval = True for step in range(50): (img, setval) = enhance(img, setval, algo) if step == 1: p1 = len(img) p2 = len(img) if verbose: print('Part 1: {0[0]}\nPart 2: {0[1]}'.format([p1, p2])) return (p1, p2) if __name__ == '__main__': main(verbose=True)
class TrieNode: def __init__(self): self.children = collections.defaultdict(TrieNode) self.is_word = False class Solution: def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: root = TrieNode() for word in words: cur = root for ch in word: cur = cur.children[ch] cur.is_word = True ans = [] def dfs(cur, path, i, j): if cur.is_word: ans.append(path) cur.is_word = False if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] == '#' or cur.children.get(board[i][j]) == None: return ch = board[i][j] board[i][j] = '#' new_cur = cur.children[ch] dfs(new_cur, path + ch, i - 1, j) dfs(new_cur, path + ch, i + 1, j) dfs(new_cur, path + ch, i, j - 1) dfs(new_cur, path + ch, i, j + 1) board[i][j] = ch for i in range(len(board)): for j in range(len(board[0])): dfs(root, "", i, j) return ans
class Trienode: def __init__(self): self.children = collections.defaultdict(TrieNode) self.is_word = False class Solution: def find_words(self, board: List[List[str]], words: List[str]) -> List[str]: root = trie_node() for word in words: cur = root for ch in word: cur = cur.children[ch] cur.is_word = True ans = [] def dfs(cur, path, i, j): if cur.is_word: ans.append(path) cur.is_word = False if i < 0 or i >= len(board) or j < 0 or (j >= len(board[0])) or (board[i][j] == '#') or (cur.children.get(board[i][j]) == None): return ch = board[i][j] board[i][j] = '#' new_cur = cur.children[ch] dfs(new_cur, path + ch, i - 1, j) dfs(new_cur, path + ch, i + 1, j) dfs(new_cur, path + ch, i, j - 1) dfs(new_cur, path + ch, i, j + 1) board[i][j] = ch for i in range(len(board)): for j in range(len(board[0])): dfs(root, '', i, j) return ans
def rotate(matrix): #code here for i in range(len(matrix)): listt = list(reversed(matrix[i])) for j in range(len(matrix[i])): matrix[i][j] = listt[j] # print(matrix) for i in range(len(matrix)): for j in range(i, len(matrix[i])): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] #{ # Driver Code Starts #Initial Template for Python 3 if __name__ == '__main__': t = int(input()) for _ in range(t): N = int(input()) arr = [int(x) for x in input().split()] matrix = [] for i in range(0, N*N, N): matrix.append(arr[i:i+N]) rotate(matrix) for i in range(N): for j in range(N): print(matrix[i][j], end=' ') print() # } Driver Code Ends
def rotate(matrix): for i in range(len(matrix)): listt = list(reversed(matrix[i])) for j in range(len(matrix[i])): matrix[i][j] = listt[j] for i in range(len(matrix)): for j in range(i, len(matrix[i])): (matrix[i][j], matrix[j][i]) = (matrix[j][i], matrix[i][j]) if __name__ == '__main__': t = int(input()) for _ in range(t): n = int(input()) arr = [int(x) for x in input().split()] matrix = [] for i in range(0, N * N, N): matrix.append(arr[i:i + N]) rotate(matrix) for i in range(N): for j in range(N): print(matrix[i][j], end=' ') print()
# Like list we can have set and dict comprehensions. # Set comprehensions. # The below set is not ordered. square_set = {num * num for num in range(11)} print(square_set) # Dict Comprehension dict_square = {num: num * num for num in range(11)} print(dict_square) # Use f"string to create a set and dict f_string_square_set = {f"The square of {num} is {num * num}" for num in range(5)} for x in f_string_square_set: print(x) f_string_square_dict = {num: f"the square is {num*num}" for num in range(5)} for k, v in f_string_square_dict.items(): print(k, ":", v)
square_set = {num * num for num in range(11)} print(square_set) dict_square = {num: num * num for num in range(11)} print(dict_square) f_string_square_set = {f'The square of {num} is {num * num}' for num in range(5)} for x in f_string_square_set: print(x) f_string_square_dict = {num: f'the square is {num * num}' for num in range(5)} for (k, v) in f_string_square_dict.items(): print(k, ':', v)
## -*- encoding: utf-8 -*- """ This file (./sol/linalg_doctest.sage) was *autogenerated* from ./sol/linalg.tex, with sagetex.sty version 2011/05/27 v2.3.1. It contains the contents of all the sageexample environments from this file. You should be able to doctest this file with: sage -t ./sol/linalg_doctest.sage It is always safe to delete this file; it is not used in typesetting your document. Sage example in ./sol/linalg.tex, line 89:: sage: A = matrix(GF(7),[[0,0,3,0,0],[1,0,6,0,0],[0,1,5,0,0], ....: [0,0,0,0,5],[0,0,0,1,5]]) sage: P = A.minpoly(); P x^5 + 4*x^4 + 3*x^2 + 3*x + 1 sage: P.factor() (x^2 + 2*x + 2) * (x^3 + 2*x^2 + x + 4) Sage example in ./sol/linalg.tex, line 100:: sage: e1 = identity_matrix(GF(7),5)[0] sage: e4 = identity_matrix(GF(7),5)[3] sage: A.transpose().maxspin(e1) [(1, 0, 0, 0, 0), (0, 1, 0, 0, 0), (0, 0, 1, 0, 0)] sage: A.transpose().maxspin(e4) [(0, 0, 0, 1, 0), (0, 0, 0, 0, 1)] sage: A.transpose().maxspin(e1 + e4) [(1, 0, 0, 1, 0), (0, 1, 0, 0, 1), (0, 0, 1, 5, 5), (3, 6, 5, 4, 2), (1, 5, 3, 3, 0)] Sage example in ./sol/linalg.tex, line 168:: sage: def Similar(A, B): ....: F1, U1 = A.frobenius(2) ....: F2, U2 = B.frobenius(2) ....: if F1 == F2: ....: return True, ~U2*U1 ....: else: ....: return False, F1 - F2 sage: B = matrix(ZZ, [[0,1,4,0,4],[4,-2,0,-4,-2],[0,0,0,2,1], ....: [-4,2,2,0,-1],[-4,-2,1,2,0]]) sage: U = matrix(ZZ, [[3,3,-9,-14,40],[-1,-2,4,2,1],[2,4,-7,-1,-13], ....: [-1,0,1,4,-15],[-4,-13,26,8,30]]) sage: A = (U^-1 * B * U).change_ring(ZZ) sage: ok, V = Similar(A, B); ok True sage: V [ 1 2824643/1601680 -6818729/1601680 -43439399/11211760 73108601/11211760] [ 0 342591/320336 -695773/320336 -2360063/11211760 -10291875/2242352] [ 0 -367393/640672 673091/640672 -888723/4484704 15889341/4484704] [ 0 661457/3203360 -565971/3203360 13485411/22423520 -69159661/22423520] [ 0 -4846439/3203360 7915157/3203360 -32420037/22423520 285914347/22423520] sage: ok, V = Similar(2*A, B); ok False """
""" This file (./sol/linalg_doctest.sage) was *autogenerated* from ./sol/linalg.tex, with sagetex.sty version 2011/05/27 v2.3.1. It contains the contents of all the sageexample environments from this file. You should be able to doctest this file with: sage -t ./sol/linalg_doctest.sage It is always safe to delete this file; it is not used in typesetting your document. Sage example in ./sol/linalg.tex, line 89:: sage: A = matrix(GF(7),[[0,0,3,0,0],[1,0,6,0,0],[0,1,5,0,0], ....: [0,0,0,0,5],[0,0,0,1,5]]) sage: P = A.minpoly(); P x^5 + 4*x^4 + 3*x^2 + 3*x + 1 sage: P.factor() (x^2 + 2*x + 2) * (x^3 + 2*x^2 + x + 4) Sage example in ./sol/linalg.tex, line 100:: sage: e1 = identity_matrix(GF(7),5)[0] sage: e4 = identity_matrix(GF(7),5)[3] sage: A.transpose().maxspin(e1) [(1, 0, 0, 0, 0), (0, 1, 0, 0, 0), (0, 0, 1, 0, 0)] sage: A.transpose().maxspin(e4) [(0, 0, 0, 1, 0), (0, 0, 0, 0, 1)] sage: A.transpose().maxspin(e1 + e4) [(1, 0, 0, 1, 0), (0, 1, 0, 0, 1), (0, 0, 1, 5, 5), (3, 6, 5, 4, 2), (1, 5, 3, 3, 0)] Sage example in ./sol/linalg.tex, line 168:: sage: def Similar(A, B): ....: F1, U1 = A.frobenius(2) ....: F2, U2 = B.frobenius(2) ....: if F1 == F2: ....: return True, ~U2*U1 ....: else: ....: return False, F1 - F2 sage: B = matrix(ZZ, [[0,1,4,0,4],[4,-2,0,-4,-2],[0,0,0,2,1], ....: [-4,2,2,0,-1],[-4,-2,1,2,0]]) sage: U = matrix(ZZ, [[3,3,-9,-14,40],[-1,-2,4,2,1],[2,4,-7,-1,-13], ....: [-1,0,1,4,-15],[-4,-13,26,8,30]]) sage: A = (U^-1 * B * U).change_ring(ZZ) sage: ok, V = Similar(A, B); ok True sage: V [ 1 2824643/1601680 -6818729/1601680 -43439399/11211760 73108601/11211760] [ 0 342591/320336 -695773/320336 -2360063/11211760 -10291875/2242352] [ 0 -367393/640672 673091/640672 -888723/4484704 15889341/4484704] [ 0 661457/3203360 -565971/3203360 13485411/22423520 -69159661/22423520] [ 0 -4846439/3203360 7915157/3203360 -32420037/22423520 285914347/22423520] sage: ok, V = Similar(2*A, B); ok False """
#ANSI Foreground colors black = u"\u001b[30m" red = u"\u001b[31m" green = u"\u001b[32m" yellow = u"\u001b[33m" blue = u"\u001b[34m" magneta = u"\u001b[35m" magenta = magneta cyan = u"\u001b[36m" white = u"\u001b[37m" #ANSI Background colors blackB = u"\u001b[40m" redB = u"\u001b[41m" greenB = u"\u001b[42m" yellowB = u"\u001b[43m" blueB = u"\u001b[44m" magnetaB = u"\u001b[45m" magentaB = magnetaB cyanB = u"\u001b[46m" whiteB = u"\u001b[47m" #ANSI reset "color" reset = u"\u001b[0m" #Unused utility function def printColored(colorA, msg): print(colorA + msg + reset) def ansi(num, end = "m"): return u"\u001b[" + str(num) + str(end) if(__name__ == "__main__"): for j in range(30, 38): print(ansi(j) + str(j) + reset)
black = u'\x1b[30m' red = u'\x1b[31m' green = u'\x1b[32m' yellow = u'\x1b[33m' blue = u'\x1b[34m' magneta = u'\x1b[35m' magenta = magneta cyan = u'\x1b[36m' white = u'\x1b[37m' black_b = u'\x1b[40m' red_b = u'\x1b[41m' green_b = u'\x1b[42m' yellow_b = u'\x1b[43m' blue_b = u'\x1b[44m' magneta_b = u'\x1b[45m' magenta_b = magnetaB cyan_b = u'\x1b[46m' white_b = u'\x1b[47m' reset = u'\x1b[0m' def print_colored(colorA, msg): print(colorA + msg + reset) def ansi(num, end='m'): return u'\x1b[' + str(num) + str(end) if __name__ == '__main__': for j in range(30, 38): print(ansi(j) + str(j) + reset)
LAB_STYLE = """ body { --jp-layout-color0: transparent; --jp-layout-color1: transparent; --jp-layout-color2: transparent; --jp-layout-color3: transparent; --jp-cell-editor-background: transparent; --jp-border-width: 0; --jp-border-color0: transparent; --jp-border-color1: transparent; --jp-border-color2: transparent; --nbcqpdf-height: 1080px; } body, body .jp-ApplicationShell { width: 1920px; height: var(--nbcqpdf-height); min-height: var(--nbcqpdf-height); max-height: var(--nbcqpdf-height); } body .jp-InputArea-editor { border: 0; padding-left: 2em; } body .jp-LabShell.jp-mod-devMode { border: 0 !important; } body .jp-InputPrompt, body .jp-OutputPrompt { display: none; min-width: 0; max-width: 0; } body #jp-main-dock-panel { padding: 0; } body .jp-SideBar.p-TabBar, body #jp-top-panel, body .jp-Toolbar, body .p-DockPanel-tabBar, body .jp-Collapser { display: none; min-height: 0; max-height: 0; min-width: 0; max-width: 0; } """ FORCE_DEV = """ var cfg = document.querySelector("#jupyter-config-data"); if(cfg) { cfg.textContent = cfg.textContent.replace( `"devMode": "False"`, `"devMode": "True"` ) } """ SINGLE_DOCUMENT = """ ;(function(){ var cmd = 'application:set-mode'; var interval = setInterval(function(){ var lab = window.lab if( !lab || !lab.commands || lab.commands.listCommands().indexOf(cmd) == -1 ) { return; } clearInterval(interval); lab.shell.removeClass('jp-mod-devMode'); lab.commands.execute(cmd, {mode: 'single-document'}); if(document.querySelector('body[data-left-sidebar-widget]')) { lab.commands.execute('application:toggle-left-area'); } }, 1000); })(); """ MEASURE = """ var bb = document.querySelector(".jp-Cell:last-child").getBoundingClientRect(); var style = document.createElement('style'); style.textContent = `body { --nbcqpdf-height: ${bb.bottom + 500}px; }`; document.body.appendChild(style); [bb.bottom, bb.right] """ RUN_ALL = """ ;(function(){ function evaluateXPath(aNode, aExpr) { var xpe = new XPathEvaluator(); var nsResolver = xpe.createNSResolver(aNode.ownerDocument == null ? aNode.documentElement : aNode.ownerDocument.documentElement); var result = xpe.evaluate(aExpr, aNode, nsResolver, 0, null); var found = []; var res; while (res = result.iterateNext()) found.push(res); return found; } var cmd = 'notebook:run-all-cells'; var interval = setInterval(function(){ var lab = window.lab if( !lab || !lab.commands || lab.commands.listCommands().indexOf(cmd) == -1 ) { return; } if(!document.querySelector(`*[title="Kernel Idle"]`)){ return; } clearInterval(interval); lab.commands.execute(cmd) .then(function(){ var busyInterval = setInterval(function(){ if(evaluateXPath(document, '//*[text() = "[*]:"]').length) { return; } %s lab.shell.mode = 'multiple-document'; lab.shell.mode = 'single-document'; clearInterval(busyInterval); __QT__.measure(); }, 1000); }) }, 1000); })(); """ % MEASURE APPLY_STYLE = f""" var style = document.createElement("style"); style.textContent = `{LAB_STYLE}`; document.body.appendChild(style); {SINGLE_DOCUMENT} {RUN_ALL} """ BRIDGE = """ new QWebChannel(qt.webChannelTransport, function(channel) { window.__QT__ = { print: function(text){ channel.objects.page.print(text || "Hello World!"); }, measure: function(){ channel.objects.page._measure(); } } __QT__.print(); }); """
lab_style = '\n body {\n --jp-layout-color0: transparent;\n --jp-layout-color1: transparent;\n --jp-layout-color2: transparent;\n --jp-layout-color3: transparent;\n --jp-cell-editor-background: transparent;\n --jp-border-width: 0;\n --jp-border-color0: transparent;\n --jp-border-color1: transparent;\n --jp-border-color2: transparent;\n --nbcqpdf-height: 1080px;\n }\n body,\n body .jp-ApplicationShell {\n width: 1920px;\n height: var(--nbcqpdf-height);\n min-height: var(--nbcqpdf-height);\n max-height: var(--nbcqpdf-height);\n }\n body .jp-InputArea-editor {\n border: 0;\n padding-left: 2em;\n }\n body .jp-LabShell.jp-mod-devMode {\n border: 0 !important;\n }\n body .jp-InputPrompt,\n body .jp-OutputPrompt {\n display: none;\n min-width: 0;\n max-width: 0;\n }\n body #jp-main-dock-panel {\n padding: 0;\n }\n body .jp-SideBar.p-TabBar,\n body #jp-top-panel,\n body .jp-Toolbar,\n body .p-DockPanel-tabBar,\n body .jp-Collapser {\n display: none;\n min-height: 0;\n max-height: 0;\n min-width: 0;\n max-width: 0;\n }\n' force_dev = '\n var cfg = document.querySelector("#jupyter-config-data");\n if(cfg) {\n cfg.textContent = cfg.textContent.replace(\n `"devMode": "False"`,\n `"devMode": "True"`\n )\n }\n' single_document = "\n ;(function(){\n var cmd = 'application:set-mode';\n var interval = setInterval(function(){\n var lab = window.lab\n if(\n !lab ||\n !lab.commands ||\n lab.commands.listCommands().indexOf(cmd) == -1\n ) {\n return;\n }\n clearInterval(interval);\n lab.shell.removeClass('jp-mod-devMode');\n lab.commands.execute(cmd, {mode: 'single-document'});\n if(document.querySelector('body[data-left-sidebar-widget]')) {\n lab.commands.execute('application:toggle-left-area');\n }\n }, 1000);\n })();\n" measure = '\n var bb = document.querySelector(".jp-Cell:last-child").getBoundingClientRect();\n var style = document.createElement(\'style\');\n style.textContent = `body { --nbcqpdf-height: ${bb.bottom + 500}px; }`;\n document.body.appendChild(style);\n [bb.bottom, bb.right]\n' run_all = '\n ;(function(){\n function evaluateXPath(aNode, aExpr) {\n var xpe = new XPathEvaluator();\n var nsResolver = xpe.createNSResolver(aNode.ownerDocument == null ?\n aNode.documentElement : aNode.ownerDocument.documentElement);\n var result = xpe.evaluate(aExpr, aNode, nsResolver, 0, null);\n var found = [];\n var res;\n while (res = result.iterateNext())\n found.push(res);\n return found;\n }\n\n var cmd = \'notebook:run-all-cells\';\n var interval = setInterval(function(){\n var lab = window.lab\n if(\n !lab ||\n !lab.commands ||\n lab.commands.listCommands().indexOf(cmd) == -1\n ) {\n return;\n }\n if(!document.querySelector(`*[title="Kernel Idle"]`)){\n return;\n }\n clearInterval(interval);\n lab.commands.execute(cmd)\n .then(function(){\n var busyInterval = setInterval(function(){\n if(evaluateXPath(document, \'//*[text() = "[*]:"]\').length) {\n return;\n }\n %s\n lab.shell.mode = \'multiple-document\';\n lab.shell.mode = \'single-document\';\n clearInterval(busyInterval);\n __QT__.measure();\n }, 1000);\n })\n }, 1000);\n })();\n' % MEASURE apply_style = f'\n var style = document.createElement("style");\n style.textContent = `{LAB_STYLE}`;\n document.body.appendChild(style);\n {SINGLE_DOCUMENT}\n {RUN_ALL}\n' bridge = '\nnew QWebChannel(qt.webChannelTransport, function(channel) {\n window.__QT__ = {\n print: function(text){\n channel.objects.page.print(text || "Hello World!");\n },\n measure: function(){\n channel.objects.page._measure();\n }\n }\n __QT__.print();\n});\n'
#!/usr/bin/env python """ Find the greatest product of five consecutive digits in the 1000-digit number """ num = '\ 73167176531330624919225119674426574742355349194934\ 96983520312774506326239578318016984801869478851843\ 85861560789112949495459501737958331952853208805511\ 12540698747158523863050715693290963295227443043557\ 66896648950445244523161731856403098711121722383113\ 62229893423380308135336276614282806444486645238749\ 30358907296290491560440772390713810515859307960866\ 70172427121883998797908792274921901699720888093776\ 65727333001053367881220235421809751254540594752243\ 52584907711670556013604839586446706324415722155397\ 53697817977846174064955149290862569321978468622482\ 83972241375657056057490261407972968652414535100474\ 82166370484403199890008895243450658541227588666881\ 16427171479924442928230863465674813919123162824586\ 17866458359124566529476545682848912883142607690042\ 24219022671055626321111109370544217506941658960408\ 07198403850962455444362981230987879927244284909188\ 84580156166097919133875499200524063689912560717606\ 05886116467109405077541002256983155200055935729725\ 71636269561882670428252483600823257530420752963450' biggest = 0 i = 0 while i < len(num) - 12: one = int(num[i]) two = int(num[i + 1]) thr = int(num[i + 2]) fou = int(num[i + 3]) fiv = int(num[i + 4]) six = int(num[i + 5]) sev = int(num[i + 6]) eig = int(num[i + 7]) nin = int(num[i + 8]) ten = int(num[i + 9]) ele = int(num[i + 10]) twe = int(num[i + 11]) thi = int(num[i + 12]) product = one * two * thr * fou * fiv * six * sev * eig * nin * ten * ele * twe * thi if product > biggest: biggest = product i += 1 def test_function(): assert biggest == 23514624000
""" Find the greatest product of five consecutive digits in the 1000-digit number """ num = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450' biggest = 0 i = 0 while i < len(num) - 12: one = int(num[i]) two = int(num[i + 1]) thr = int(num[i + 2]) fou = int(num[i + 3]) fiv = int(num[i + 4]) six = int(num[i + 5]) sev = int(num[i + 6]) eig = int(num[i + 7]) nin = int(num[i + 8]) ten = int(num[i + 9]) ele = int(num[i + 10]) twe = int(num[i + 11]) thi = int(num[i + 12]) product = one * two * thr * fou * fiv * six * sev * eig * nin * ten * ele * twe * thi if product > biggest: biggest = product i += 1 def test_function(): assert biggest == 23514624000
athlete_1 = int(input()) athlete_2 = int(input()) athlete_3 = int(input()) podium = [] if (athlete_1 < athlete_2 and athlete_1 < athlete_3): podium.append(1) if(athlete_2 < athlete_3): podium.append(2) podium.append(3) else: podium.append(3) podium.append(2) elif (athlete_2 < athlete_1 and athlete_2 < athlete_3): podium.append(2) if(athlete_1 < athlete_3): podium.append(1) podium.append(3) else: podium.append(3) podium.append(1) elif (athlete_3 < athlete_1 and athlete_3 < athlete_2): podium.append(3) if(athlete_1 < athlete_2): podium.append(1) podium.append(2) else: podium.append(2) podium.append(1) print(podium[0]) print(podium[1]) print(podium[3])
athlete_1 = int(input()) athlete_2 = int(input()) athlete_3 = int(input()) podium = [] if athlete_1 < athlete_2 and athlete_1 < athlete_3: podium.append(1) if athlete_2 < athlete_3: podium.append(2) podium.append(3) else: podium.append(3) podium.append(2) elif athlete_2 < athlete_1 and athlete_2 < athlete_3: podium.append(2) if athlete_1 < athlete_3: podium.append(1) podium.append(3) else: podium.append(3) podium.append(1) elif athlete_3 < athlete_1 and athlete_3 < athlete_2: podium.append(3) if athlete_1 < athlete_2: podium.append(1) podium.append(2) else: podium.append(2) podium.append(1) print(podium[0]) print(podium[1]) print(podium[3])
Number = int(input("\nPlease Enter the Range Number: ")) First_Value = 0 Second_Value = 1 for Num in range(0, Number): if (Num <= 1): Next = Num else: Next = First_Value + Second_Value First_Value = Second_Value Second_Value = Next print(Next)
number = int(input('\nPlease Enter the Range Number: ')) first__value = 0 second__value = 1 for num in range(0, Number): if Num <= 1: next = Num else: next = First_Value + Second_Value first__value = Second_Value second__value = Next print(Next)
def Spell_0_10(n): refTuple = ("zero","one","two","three","four","five", "six","seven","eight","nine","ten") return refTuple[n] print(1, " is spelt as ", Spell_0_10(1)) for i in range(11): print("{} is spelt as {}".format(i,Spell_0_10(i))) for i in range (-9,0,1): print("{} is spelt as {}".format(i, Spell_0_10(i)))
def spell_0_10(n): ref_tuple = ('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten') return refTuple[n] print(1, ' is spelt as ', spell_0_10(1)) for i in range(11): print('{} is spelt as {}'.format(i, spell_0_10(i))) for i in range(-9, 0, 1): print('{} is spelt as {}'.format(i, spell_0_10(i)))
"""Registry for behavior configurables.""" _BEHAVIOR_LIST = [] def behaviors(): """Yields the currently registered behaviors in the order in which they were defined.""" for name, cls, brief, level in _BEHAVIOR_LIST: yield name, cls, brief, level def behavior(name, brief, level=0): """Decorator generator which registers a behavior configurable.""" def decorator(cls): cls.__str__ = lambda _: name _BEHAVIOR_LIST.append((name, cls, brief, level)) return cls return decorator def behavior_doc(doc, level=0): """Appends a documentation-only item to the behavior list in the generated documentation.""" _BEHAVIOR_LIST.append((None, None, doc, level))
"""Registry for behavior configurables.""" _behavior_list = [] def behaviors(): """Yields the currently registered behaviors in the order in which they were defined.""" for (name, cls, brief, level) in _BEHAVIOR_LIST: yield (name, cls, brief, level) def behavior(name, brief, level=0): """Decorator generator which registers a behavior configurable.""" def decorator(cls): cls.__str__ = lambda _: name _BEHAVIOR_LIST.append((name, cls, brief, level)) return cls return decorator def behavior_doc(doc, level=0): """Appends a documentation-only item to the behavior list in the generated documentation.""" _BEHAVIOR_LIST.append((None, None, doc, level))
"""excpetions.py""" class GTMManagerException(Exception): """GTMManagerException""" pass class AuthError(GTMManagerException): pass class VariableNotFound(GTMManagerException): """VariableNotFound""" def __init__(self, variable_name, parent): super(VariableNotFound, self).__init__() self.variable_name = variable_name self.parent = parent def __str__(self): return "Variable {!r} not found in parent {!r}".format( self.variable_name, self.parent ) class TagNotFound(GTMManagerException): """TagNotFound""" def __init__(self, tag_name, parent): super(TagNotFound, self).__init__() self.tag_name = tag_name self.parent = parent def __str__(self): return "Tag {!r} not found in parent {!r}".format(self.tag_name, self.parent) class TriggerNotFound(GTMManagerException): """TriggerNotFound""" def __init__(self, trigger_name, parent): super(TriggerNotFound, self).__init__() self.trigger_name = trigger_name self.parent = parent def __str__(self): return "Trigger {!r} not found in parent {!r}".format( self.trigger_name, self.parent ) class RateLimitExceeded(GTMManagerException): """RateLimitExceeded""" pass
"""excpetions.py""" class Gtmmanagerexception(Exception): """GTMManagerException""" pass class Autherror(GTMManagerException): pass class Variablenotfound(GTMManagerException): """VariableNotFound""" def __init__(self, variable_name, parent): super(VariableNotFound, self).__init__() self.variable_name = variable_name self.parent = parent def __str__(self): return 'Variable {!r} not found in parent {!r}'.format(self.variable_name, self.parent) class Tagnotfound(GTMManagerException): """TagNotFound""" def __init__(self, tag_name, parent): super(TagNotFound, self).__init__() self.tag_name = tag_name self.parent = parent def __str__(self): return 'Tag {!r} not found in parent {!r}'.format(self.tag_name, self.parent) class Triggernotfound(GTMManagerException): """TriggerNotFound""" def __init__(self, trigger_name, parent): super(TriggerNotFound, self).__init__() self.trigger_name = trigger_name self.parent = parent def __str__(self): return 'Trigger {!r} not found in parent {!r}'.format(self.trigger_name, self.parent) class Ratelimitexceeded(GTMManagerException): """RateLimitExceeded""" pass
#Plugin to handle dialogues for men and women #Written by Owain for Runefate #31/01/18 #I want to give every spawned NPC a use, and not do what most servers have with useless non functioning NPCs. #Even small things such as NPC dialogues can help make Runefate more rounded and enjoyable. npc_ids = [3078, 3079] dialogue_ids = [7502, 7504, 7506, 7508] def first_click_npc_3078(player): player.getDH().sendDialogues(7500) def chat_7500(player): player.getDH().sendPlayerChat("Hi there.", 591) dialogue = random.choice(dialogue_ids) player.nextDialogue = dialogue; def chat_7502(player): player.getDH().sendNpcChat("Hello, lovely day today isn't it?", 589) def chat_7504(player): player.getDH().sendNpcChat("Can't stop, I'm rather busy.", 589) def chat_7506(player): player.getDH().sendNpcChat("Hey! How are you today?", 589) player.nextDialogue = 7507; def chat_7507(player): player.getDH().sendPlayerChat("I'm great thanks.", 591) def chat_7508(player): player.getDH().sendNpcChat("*Cough* *Splutter*", 589) player.nextDialogue = 7509; def chat_7509(player): player.getDH().sendPlayerChat("Oh dear, I think that might be contagious...", 591)
npc_ids = [3078, 3079] dialogue_ids = [7502, 7504, 7506, 7508] def first_click_npc_3078(player): player.getDH().sendDialogues(7500) def chat_7500(player): player.getDH().sendPlayerChat('Hi there.', 591) dialogue = random.choice(dialogue_ids) player.nextDialogue = dialogue def chat_7502(player): player.getDH().sendNpcChat("Hello, lovely day today isn't it?", 589) def chat_7504(player): player.getDH().sendNpcChat("Can't stop, I'm rather busy.", 589) def chat_7506(player): player.getDH().sendNpcChat('Hey! How are you today?', 589) player.nextDialogue = 7507 def chat_7507(player): player.getDH().sendPlayerChat("I'm great thanks.", 591) def chat_7508(player): player.getDH().sendNpcChat('*Cough* *Splutter*', 589) player.nextDialogue = 7509 def chat_7509(player): player.getDH().sendPlayerChat('Oh dear, I think that might be contagious...', 591)
class ReferenceDummy(): def __init__(self, *args): return def _to_dict(self, *args): return "dummy"
class Referencedummy: def __init__(self, *args): return def _to_dict(self, *args): return 'dummy'
# #1 # def make_negative( number ): # return number if number < 0 else - number # #2 def make_negative( number ): return -abs(number)
def make_negative(number): return -abs(number)
# This class parses a gtfs text file class Reader: def __init__(self, file): self.fields = [] self.fp = open(file, "r") self.fields.extend(self.fp.readline().rstrip().split(",")) def get_line(self): data = {} line = self.fp.readline().rstrip().split(",") for el, field in zip (line, self.fields): data[field] = el if len(data) == 1: return None else: return data def end(self): self.fp.close()
class Reader: def __init__(self, file): self.fields = [] self.fp = open(file, 'r') self.fields.extend(self.fp.readline().rstrip().split(',')) def get_line(self): data = {} line = self.fp.readline().rstrip().split(',') for (el, field) in zip(line, self.fields): data[field] = el if len(data) == 1: return None else: return data def end(self): self.fp.close()
# Cajones es una aplicacion que calcula el listado de partes # de una cajonera # unidad de medida en mm # constantes hol_lado = 13 # variables h = 900 a = 600 prof_c = 400 h_c = 120 a_c = 200 hol_sup = 20 hol_inf = 10 hol_int = 40 hol_lateral = 2 esp_lado = 18 esp_sup = 18 esp_inf = 18 esp_c = 15 cubre_der_total = True cubre_iz_total = True def calcular_lado_cajon(prof_c, esp_c): lado_cajon = prof_c - 2 * esp_c return lado_cajon def calcular_a_c(cubre_iz_total, cubre_der_total, esp_lado, hol_lado, hol_lateral, a): if cubre_der_total: espesor_derecho = esp_lado else: espesor_derecho = esp_lado / 2 - hol_lateral if cubre_iz_total: espesor_izquierdo = esp_lado else: espesor_izquierdo = esp_lado / 2 - hol_lateral ancho_cajon = a - espesor_izquierdo - espesor_derecho - 2 * hol_lateral return ancho_cajon def calcular_h_c(h, esp_sup, esp_inf, hol_sup, hol_int, hol_inf): suma_holhura = hol_sup + hol_int + hol_inf suma_espesor = esp_sup + esp_inf espacio_cajones = h - suma_espesor - suma_holhura altura_cajon = espacio_cajones / 3 return altura_cajon h_c = calcular_h_c(h, esp_sup, esp_inf, hol_sup, hol_int, hol_inf) a_c = calcular_a_c(cubre_iz_total, cubre_der_total, esp_lado, hol_lado, hol_lateral, a) l_c = calcular_lado_cajon(prof_c, esp_c) print("frente cajon: ", a_c, " X ", round(h_c)) print("lado cajon: ", l_c, " X ", round(h_c))
hol_lado = 13 h = 900 a = 600 prof_c = 400 h_c = 120 a_c = 200 hol_sup = 20 hol_inf = 10 hol_int = 40 hol_lateral = 2 esp_lado = 18 esp_sup = 18 esp_inf = 18 esp_c = 15 cubre_der_total = True cubre_iz_total = True def calcular_lado_cajon(prof_c, esp_c): lado_cajon = prof_c - 2 * esp_c return lado_cajon def calcular_a_c(cubre_iz_total, cubre_der_total, esp_lado, hol_lado, hol_lateral, a): if cubre_der_total: espesor_derecho = esp_lado else: espesor_derecho = esp_lado / 2 - hol_lateral if cubre_iz_total: espesor_izquierdo = esp_lado else: espesor_izquierdo = esp_lado / 2 - hol_lateral ancho_cajon = a - espesor_izquierdo - espesor_derecho - 2 * hol_lateral return ancho_cajon def calcular_h_c(h, esp_sup, esp_inf, hol_sup, hol_int, hol_inf): suma_holhura = hol_sup + hol_int + hol_inf suma_espesor = esp_sup + esp_inf espacio_cajones = h - suma_espesor - suma_holhura altura_cajon = espacio_cajones / 3 return altura_cajon h_c = calcular_h_c(h, esp_sup, esp_inf, hol_sup, hol_int, hol_inf) a_c = calcular_a_c(cubre_iz_total, cubre_der_total, esp_lado, hol_lado, hol_lateral, a) l_c = calcular_lado_cajon(prof_c, esp_c) print('frente cajon: ', a_c, ' X ', round(h_c)) print('lado cajon: ', l_c, ' X ', round(h_c))
#!/usr/bin/env python class TwitterError(Exception): """Base class for Twitter errors""" @property def message(self): '''Returns the first argument used to construct this error.''' return self.args[0] class PythonTwitterDeprecationWarning(DeprecationWarning): """Base class for python-twitter deprecation warnings""" pass class PythonTwitterDeprecationWarning330(PythonTwitterDeprecationWarning): """Warning for features to be removed in version 3.3.0""" pass
class Twittererror(Exception): """Base class for Twitter errors""" @property def message(self): """Returns the first argument used to construct this error.""" return self.args[0] class Pythontwitterdeprecationwarning(DeprecationWarning): """Base class for python-twitter deprecation warnings""" pass class Pythontwitterdeprecationwarning330(PythonTwitterDeprecationWarning): """Warning for features to be removed in version 3.3.0""" pass
def middle(t): '''Write a function called middle that takes a list and returns a new list that contains all but the first and last elements''' return t[1: -1] if __name__ == '__main__': t = [1, 2, 30, 400, 5000] print(t) print(middle(t))
def middle(t): """Write a function called middle that takes a list and returns a new list that contains all but the first and last elements""" return t[1:-1] if __name__ == '__main__': t = [1, 2, 30, 400, 5000] print(t) print(middle(t))
""" File: hailstone.py ----------------------- This program should implement a console program that simulates the execution of the Hailstone sequence, as defined by Douglas Hofstadter. Output format should match what is shown in the sample run in the Assignment 2 Handout. """ def main(): """ This program will first ask user input a number (integer), then it will simulate the execution of the Hailstone sequences of that input. Every round the program will check whether the number is even or odd to decide how to modify the number, until the number reach 1. """ print('This program computes Hailstone sequences') # Variable 'count' will count how many step to reach 1. count = 0 # Variable 'maximum' will finally be the biggest number in each Hailstone sequence. maximum = 0 # Input an integer, if input a float, the program will do floor division then change it to an integer. num = int(float(input('Enter an integer: ')) // 1) # The program will check whether input is at least 1. if num <= 0: print('Input must be at least 1') else: # If the first input is 1, the program stops. if num == 1: print('It took ' + str(count) + ' step(s) to reach 1') else: # The while loop will keep running until the number reach 1. while num != 1: # If the number is even. if num % 2 != 0: print(str(int(num)) + ' is odd, so I make 3n+1: ' + str(int(3 * num + 1))) if num > maximum: maximum = num # Reassign the number. num = 3 * num + 1 count += 1 # If the number is odd. else: print(str(int(num)) + ' is even, so I take half: ' + str(int(num / 2))) if num > maximum: maximum = num # Reassign the number. num = num / 2 count += 1 # Print the results: Steps used and the biggest number in the Hailstone sequences. print('It took ' + str(count) + ' step(s) to reach 1') print('The biggest number in the Hailstone sequences is: ' + str(int(maximum))) if __name__ == "__main__": main()
""" File: hailstone.py ----------------------- This program should implement a console program that simulates the execution of the Hailstone sequence, as defined by Douglas Hofstadter. Output format should match what is shown in the sample run in the Assignment 2 Handout. """ def main(): """ This program will first ask user input a number (integer), then it will simulate the execution of the Hailstone sequences of that input. Every round the program will check whether the number is even or odd to decide how to modify the number, until the number reach 1. """ print('This program computes Hailstone sequences') count = 0 maximum = 0 num = int(float(input('Enter an integer: ')) // 1) if num <= 0: print('Input must be at least 1') elif num == 1: print('It took ' + str(count) + ' step(s) to reach 1') else: while num != 1: if num % 2 != 0: print(str(int(num)) + ' is odd, so I make 3n+1: ' + str(int(3 * num + 1))) if num > maximum: maximum = num num = 3 * num + 1 count += 1 else: print(str(int(num)) + ' is even, so I take half: ' + str(int(num / 2))) if num > maximum: maximum = num num = num / 2 count += 1 print('It took ' + str(count) + ' step(s) to reach 1') print('The biggest number in the Hailstone sequences is: ' + str(int(maximum))) if __name__ == '__main__': main()
print("Size of list"); list1 = [1,23,5,2,42,526,52]; print(list1); print(len(list1));
print('Size of list') list1 = [1, 23, 5, 2, 42, 526, 52] print(list1) print(len(list1))
#!/usr/bin/env python # # Copyright 2015 British Broadcasting Corporation # # 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. r""" This module provides functions to analyses the timings of the detected beep/flashes and compare them against expected timings of beep/flashes to determine which observed ones correspond to which expected ones. So for any given light sensor or audio input we have a set of observed timings of beeps/flashes and a set of expected timings of beeps/flashes. The observed are subset range of the expected. "expected" describes N events for the entire video clip. "observed" describes M events observed during synchronised playback of some portion of the video. M <= N. The analysis runs a correlation using "expected" and "observed". The problem we're solving is which portion of the events in "expected" correlates the strongest with the events in "observed". To do this we slide the set of events in "observed" along the set of events in "expected". We start at event 0 in "expected" and compare M events with "observed". Then we do the same starting at event 1 in "expected" and compare M events with "observed". The last index we can use to extract M events in "expected" is N - M. For a given set of M events from expected, we then build a set of time differences, one entry per event. We calculate the variance for the data in this set of differences, and remember this as an indicator of "goodness of match", along with the start index involved. Once we have done this at all possible start points along "expected", we then have N-M variances. The one with the lowest value is the best match. If the master and client were perfectly synchronised, then we'd have a time difference set of all zero's and the variance would be zero. A realistic situation would show the time differences (mostly) clustering around constant value, but the variance will still be low. That is, plotting on a graph with synchronisation timeline values on the x-axis, and time difference values on the y-axis, then the average offset is a horizontal line and the variance quantifies how much the data differs from this ideal. A high variance indicates that the pattern of observed beep/flash timings did not match that particular subset of the expected beep/flash timings. If the pattern for the time differences is sloping, this indicates wall clock drift. """ def variance(dataset): """\ Given a set of time differences, compute the variance in this set :param dataset: list of values :returns: the variance """ avg = sum(dataset)/len(dataset) v = 0.0 for data in dataset: v += (data - avg) * (data - avg) v = v / len(dataset) return v def varianceInTimesWithObservedComparedAgainstExpectedAtIndex(idx, expected, observed): """\ Traverse the list of expected times, starting from index "idx", and the list of observed times, starting from index 0, for the full length of the observed times list, to generate a list of the time difference between each expected time and observed time. Then compute the variance in the time difference, and return it, along with the differences from which it was calculated. :param idx: index into expected times at which start traversal :param expected: list of expected times in units of sync time line clock :param observed: list of tuples of (detected centre flash/pulse time, err bounds), in units of sync time line clock :returns: tuple (variance, differencesAndErrors) * variance = statistical variance of the difference between expected and observed timings * differencesAndErrors is a list, of (diff,err) representing each time difference and the error bound for the respective measurement """ where = idx differences = [] differencesAndErrors = [] for e in observed: # e[0] is the observed time. e[1] is the error bound diff = expected[where] - e[0] differences.append( diff ) differencesAndErrors.append( (diff, e[1]) ) where += 1 return (variance(differences), differencesAndErrors) def correlate(expected, observed): """\ Perform a correlation between a list of expected timings, and a list of observed timings that ought to "match" against some contiguous portion of the expected timings. We work out the last possible index into the expected timings so that traversal from there to the end of its list has the same number of entries as in the observed timings list. Starting at index 0 of the expected list, we then compute the variance in time differences between each expected time and an observed time (running from index 0 of the observed timings). We repeat this from index 1 .. last possible index, each time computing the variance in time differences between each expected time and an observed time (running from index 0 of the observed timings) For each of the runs, we add a tuple of (expected time index, variance computed) to a list. Finally, we then traverse this list, looking for the lowest variance value. This is the point in the expected times that most closely matches the observed timings. :param expected: list of expected times in units of sync time line clock :param observed: list of tuples of (detected centre flash/pulse time, err bounds), in units of sync time line clock :returns (index, timeDifferences): A tuple containing the index in the expected timings corresponding to the first observation, and a list of the time differences between each individual observed and expected flash/beep for the match. if there are more detected flashes/beeps than expected, it is probably due to a wrong input being plugged into on the Arduino, compared to what was asked for via the command line. In this case we return a tuple (-1, None) """ # following list will hold all sets of time differences computed during the correlation. # entry j will hold the set found when observed was compared with expected starting at j. timeDifferencesAndErrorsAtIndices = [] # the observed timings will be a subset of the expected times # so figure out the last start index in the observed timings # that accommodates the length of these observed timings lastPossible = len(expected) - len(observed) varianceAtEachIndex = [] # now look for the set of observed timings against each # possible starting point. Each loop traversal, observed[0] will be compared against # expected[where]. observed[1] against expected[where+1] for where in range(0, lastPossible + 1): variance, diffsAndErrors = varianceInTimesWithObservedComparedAgainstExpectedAtIndex(where, expected, observed) timeDifferencesAndErrorsAtIndices.append(diffsAndErrors) varianceAtEachIndex.append((variance, where)) (lowestVariance, index) = min(varianceAtEachIndex) return (index, timeDifferencesAndErrorsAtIndices) def doComparison(test, startSyncTime, tickRate): """\ Each activated pin results in a test set: the observed and expected times. For each of these tests, perform the comparison. :param A tuple is a ( list of tuples of (observed times (sync time line units), error bounds), list of expected timings (seconds) ) :param startSyncTime: the start value used for the sync time line offered to the client device :param tickRate: the number of ticks per second for the sync time line offered to the client device :returns tuple summary of results of analysis. (index into expected times for video at which strongest correlation (lowest variance) is found, list of expected times for video, list of (diff, err) for the best match, corresponding to the individual time differences and each one's error bound) """ observed, expectedTimesSecs = test # convert to be on the sync timeline expected = [ startSyncTime + tickRate * t for t in expectedTimesSecs ] matchIndex, allTimeDifferencesAndErrors = correlate(expected, observed) timeDifferencesAndErrorsForMatch = allTimeDifferencesAndErrors[matchIndex] return (matchIndex, expected, timeDifferencesAndErrorsForMatch) def runDetection(detector, channels, dueStartTimeUsecs, dueFinishTimeUsecs): """\ for each channel of sample data, detect the beep or flash timings :param detector beep / flash detector to use for the detection :param nActivePins number of arduino inputs that were read during sampling :param channels the data channels for the sample data separated out per pin. This is a list of dictionaries, one per sampled pin. A dictionary is { "pinName": pin name, "isAudio": true or false, "min": list of sampled minimum values for that pin (each value is the minimum over a millisecond period) "max": list of sampled maximum values for that pin (each value is the maximum over same millisecond period) } :param dueStartTimeUsecs :param dueFinishTimeUsecs :return the detected timings list of dictionaries A dictionary is { "pin": pin name, "observed": list of detected timings } where a detected timing is a tuple (centre time of flash or beep, error bounds) in units of ticks of the synchronisation timeline """ timings = [] for channel in channels: isAudio = channel["isAudio"] if isAudio: func = detector.samplesToBeepTimings else: func = detector.samplesToFlashTimings eventDuration = channel["eventDuration"] timings.append({"pinName": channel["pinName"], "observed": func(channel["min"], channel["max"], dueStartTimeUsecs, dueFinishTimeUsecs, eventDuration)}) return timings if __name__ == '__main__': # unit tests in: # ../tests/test_analyse.py pass
""" This module provides functions to analyses the timings of the detected beep/flashes and compare them against expected timings of beep/flashes to determine which observed ones correspond to which expected ones. So for any given light sensor or audio input we have a set of observed timings of beeps/flashes and a set of expected timings of beeps/flashes. The observed are subset range of the expected. "expected" describes N events for the entire video clip. "observed" describes M events observed during synchronised playback of some portion of the video. M <= N. The analysis runs a correlation using "expected" and "observed". The problem we're solving is which portion of the events in "expected" correlates the strongest with the events in "observed". To do this we slide the set of events in "observed" along the set of events in "expected". We start at event 0 in "expected" and compare M events with "observed". Then we do the same starting at event 1 in "expected" and compare M events with "observed". The last index we can use to extract M events in "expected" is N - M. For a given set of M events from expected, we then build a set of time differences, one entry per event. We calculate the variance for the data in this set of differences, and remember this as an indicator of "goodness of match", along with the start index involved. Once we have done this at all possible start points along "expected", we then have N-M variances. The one with the lowest value is the best match. If the master and client were perfectly synchronised, then we'd have a time difference set of all zero's and the variance would be zero. A realistic situation would show the time differences (mostly) clustering around constant value, but the variance will still be low. That is, plotting on a graph with synchronisation timeline values on the x-axis, and time difference values on the y-axis, then the average offset is a horizontal line and the variance quantifies how much the data differs from this ideal. A high variance indicates that the pattern of observed beep/flash timings did not match that particular subset of the expected beep/flash timings. If the pattern for the time differences is sloping, this indicates wall clock drift. """ def variance(dataset): """ Given a set of time differences, compute the variance in this set :param dataset: list of values :returns: the variance """ avg = sum(dataset) / len(dataset) v = 0.0 for data in dataset: v += (data - avg) * (data - avg) v = v / len(dataset) return v def variance_in_times_with_observed_compared_against_expected_at_index(idx, expected, observed): """ Traverse the list of expected times, starting from index "idx", and the list of observed times, starting from index 0, for the full length of the observed times list, to generate a list of the time difference between each expected time and observed time. Then compute the variance in the time difference, and return it, along with the differences from which it was calculated. :param idx: index into expected times at which start traversal :param expected: list of expected times in units of sync time line clock :param observed: list of tuples of (detected centre flash/pulse time, err bounds), in units of sync time line clock :returns: tuple (variance, differencesAndErrors) * variance = statistical variance of the difference between expected and observed timings * differencesAndErrors is a list, of (diff,err) representing each time difference and the error bound for the respective measurement """ where = idx differences = [] differences_and_errors = [] for e in observed: diff = expected[where] - e[0] differences.append(diff) differencesAndErrors.append((diff, e[1])) where += 1 return (variance(differences), differencesAndErrors) def correlate(expected, observed): """ Perform a correlation between a list of expected timings, and a list of observed timings that ought to "match" against some contiguous portion of the expected timings. We work out the last possible index into the expected timings so that traversal from there to the end of its list has the same number of entries as in the observed timings list. Starting at index 0 of the expected list, we then compute the variance in time differences between each expected time and an observed time (running from index 0 of the observed timings). We repeat this from index 1 .. last possible index, each time computing the variance in time differences between each expected time and an observed time (running from index 0 of the observed timings) For each of the runs, we add a tuple of (expected time index, variance computed) to a list. Finally, we then traverse this list, looking for the lowest variance value. This is the point in the expected times that most closely matches the observed timings. :param expected: list of expected times in units of sync time line clock :param observed: list of tuples of (detected centre flash/pulse time, err bounds), in units of sync time line clock :returns (index, timeDifferences): A tuple containing the index in the expected timings corresponding to the first observation, and a list of the time differences between each individual observed and expected flash/beep for the match. if there are more detected flashes/beeps than expected, it is probably due to a wrong input being plugged into on the Arduino, compared to what was asked for via the command line. In this case we return a tuple (-1, None) """ time_differences_and_errors_at_indices = [] last_possible = len(expected) - len(observed) variance_at_each_index = [] for where in range(0, lastPossible + 1): (variance, diffs_and_errors) = variance_in_times_with_observed_compared_against_expected_at_index(where, expected, observed) timeDifferencesAndErrorsAtIndices.append(diffsAndErrors) varianceAtEachIndex.append((variance, where)) (lowest_variance, index) = min(varianceAtEachIndex) return (index, timeDifferencesAndErrorsAtIndices) def do_comparison(test, startSyncTime, tickRate): """ Each activated pin results in a test set: the observed and expected times. For each of these tests, perform the comparison. :param A tuple is a ( list of tuples of (observed times (sync time line units), error bounds), list of expected timings (seconds) ) :param startSyncTime: the start value used for the sync time line offered to the client device :param tickRate: the number of ticks per second for the sync time line offered to the client device :returns tuple summary of results of analysis. (index into expected times for video at which strongest correlation (lowest variance) is found, list of expected times for video, list of (diff, err) for the best match, corresponding to the individual time differences and each one's error bound) """ (observed, expected_times_secs) = test expected = [startSyncTime + tickRate * t for t in expectedTimesSecs] (match_index, all_time_differences_and_errors) = correlate(expected, observed) time_differences_and_errors_for_match = allTimeDifferencesAndErrors[matchIndex] return (matchIndex, expected, timeDifferencesAndErrorsForMatch) def run_detection(detector, channels, dueStartTimeUsecs, dueFinishTimeUsecs): """ for each channel of sample data, detect the beep or flash timings :param detector beep / flash detector to use for the detection :param nActivePins number of arduino inputs that were read during sampling :param channels the data channels for the sample data separated out per pin. This is a list of dictionaries, one per sampled pin. A dictionary is { "pinName": pin name, "isAudio": true or false, "min": list of sampled minimum values for that pin (each value is the minimum over a millisecond period) "max": list of sampled maximum values for that pin (each value is the maximum over same millisecond period) } :param dueStartTimeUsecs :param dueFinishTimeUsecs :return the detected timings list of dictionaries A dictionary is { "pin": pin name, "observed": list of detected timings } where a detected timing is a tuple (centre time of flash or beep, error bounds) in units of ticks of the synchronisation timeline """ timings = [] for channel in channels: is_audio = channel['isAudio'] if isAudio: func = detector.samplesToBeepTimings else: func = detector.samplesToFlashTimings event_duration = channel['eventDuration'] timings.append({'pinName': channel['pinName'], 'observed': func(channel['min'], channel['max'], dueStartTimeUsecs, dueFinishTimeUsecs, eventDuration)}) return timings if __name__ == '__main__': pass
FANARTTV_PROJECTKEY = '' TADB_PROJECTKEY = '' TMDB_PROJECTKEY = '' THETVDB_PROJECTKEY = ''
fanarttv_projectkey = '' tadb_projectkey = '' tmdb_projectkey = '' thetvdb_projectkey = ''
# Regards, Takeda Shingen (Sengoku Era) Questline | Near Momiji Hills 1 (811000001) # Author: Tiger TAKEDA = 9000427 if "1" in sm.getQRValue(58901): # Regards, Takeda Shingen sm.setSpeakerID(TAKEDA) sm.flipDialogue() sm.sendNext("Good, you're here! I was about to pick another fight") sm.flipDialogue() sm.sendSay("We have a problem, and it's not a lack of conditioner. I'll tell ya that!") sm.flipDialogue() sm.sendSay("That warrior you found is in a coma. Lost their fight with consciousness. I guess. I had a letter somewhere here from Momijigaoka (He smashes boxes and chairs looking for the letter )") sm.setQRValue(58901, "2") # Regards, Takeda Shingen elif "2" in sm.getQRValue(58901): # Regards, Takeda Shingen sm.setSpeakerID(TAKEDA) sm.flipDialogue() sm.sendNext("Hm... I don't remember where I left it. It had the instructions on how to lift the spell.. Well, it wasn't that important anyway") sm.flipDialogue() sm.sendSay("Ha ha ha, a real man never sweats over losing such unimportant things!") sm.flipDialogue() sm.sendSay("As I recall, the Oda army is teaching wicked spells to it's soliders. Maybe one of them knocked our new friend out of commission.") response = sm.sendAskYesNo("There are a couple things that need to get done to lift the spell.\r\nYou can help, right?") if response: sm.flipDialogue() sm.sendNext("Ha, I knew you would do it.") sm.flipDialogue() sm.sendSay("First we need to know more about the spells. Eliminate some Oda Warrior Trainee monsters to find clues.") sm.flipDialogue() sm.sendSay("I don't need that many just 30 of them. That should be enough to mash into reason. Now, get to it!") sm.setQRValue(58901, "3") # Regards, Takeda Shingen sm.startQuest(parentID)
takeda = 9000427 if '1' in sm.getQRValue(58901): sm.setSpeakerID(TAKEDA) sm.flipDialogue() sm.sendNext("Good, you're here! I was about to pick another fight") sm.flipDialogue() sm.sendSay("We have a problem, and it's not a lack of conditioner. I'll tell ya that!") sm.flipDialogue() sm.sendSay('That warrior you found is in a coma. Lost their fight with consciousness. I guess. I had a letter somewhere here from Momijigaoka (He smashes boxes and chairs looking for the letter )') sm.setQRValue(58901, '2') elif '2' in sm.getQRValue(58901): sm.setSpeakerID(TAKEDA) sm.flipDialogue() sm.sendNext("Hm... I don't remember where I left it. It had the instructions on how to lift the spell.. Well, it wasn't that important anyway") sm.flipDialogue() sm.sendSay('Ha ha ha, a real man never sweats over losing such unimportant things!') sm.flipDialogue() sm.sendSay("As I recall, the Oda army is teaching wicked spells to it's soliders. Maybe one of them knocked our new friend out of commission.") response = sm.sendAskYesNo('There are a couple things that need to get done to lift the spell.\r\nYou can help, right?') if response: sm.flipDialogue() sm.sendNext('Ha, I knew you would do it.') sm.flipDialogue() sm.sendSay('First we need to know more about the spells. Eliminate some Oda Warrior Trainee monsters to find clues.') sm.flipDialogue() sm.sendSay("I don't need that many just 30 of them. That should be enough to mash into reason. Now, get to it!") sm.setQRValue(58901, '3') sm.startQuest(parentID)
array = [3,5,-4,8,11,-1,6] targetSum = 10 def twoNumberSum(array, targetSum): #for loop to iterate the array for i in range(len(array) - 1): firstNum = array[i] for j in range(i + 1, len(array)): secondNum = array[j] if firstNum + secondNum == targetSum: return [firstNum, secondNum] return[] # print(twoNumberSum(firstNum, secondNum)) # Second Solution def twoNumberSum(array, targetSum): nums = {} for num in array: potentialMatch = targetSum - num if potentialMatch in nums: return [potentialMatch, num] else: nums[num] = True return [] # Third Solution def TwoNumSum(array, targetSum): for i in range(len(array)-1): firstNum = array[i] for j in range( i + 1, len(array)): secondNum = array[j] if firstNum + secondNum == targetSum: return [firstNum, secondNum] return []
array = [3, 5, -4, 8, 11, -1, 6] target_sum = 10 def two_number_sum(array, targetSum): for i in range(len(array) - 1): first_num = array[i] for j in range(i + 1, len(array)): second_num = array[j] if firstNum + secondNum == targetSum: return [firstNum, secondNum] return [] def two_number_sum(array, targetSum): nums = {} for num in array: potential_match = targetSum - num if potentialMatch in nums: return [potentialMatch, num] else: nums[num] = True return [] def two_num_sum(array, targetSum): for i in range(len(array) - 1): first_num = array[i] for j in range(i + 1, len(array)): second_num = array[j] if firstNum + secondNum == targetSum: return [firstNum, secondNum] return []
def can_create_a_Fibonacci_number(int_1, int_2): """ This function checks to see if the sum, difference, product, or module of the two inputs product a Fibonacci number. 1, 1, 2, 3, 5, 8, 13, 21, 34 ... The two inputs are assumed to be integers """ sum = int_1 + int_2 product = int_1 * int_2 if int_1 > int_2: diff = int_1 - int_2 mod = int_1 % int_2 else: diff = int_2 - int_1 mod = int_1 % int_2 possible_fibs = [sum, product, diff, mod] fib1 = 1 fib2 = 2 fib_found = False while fib2 < max(possible_fibs) and not fib_found: new_fib = fib1 + fib2 if new_fib in possible_fibs: fib_found = True if new_fib == sum: print('Sum creates: ', new_fib) elif new_fib == product: print('Product creates: ', new_fib) elif new_fib == diff: print('Difference creates: ', new_fib) else: print('Modulo creates: ', new_fib) fib1 = fib2 fib2 = new_fib if not fib_found: print('No Fibonacci Number found under: ', fib2) can_create_a_Fibonacci_number(30, 33) can_create_a_Fibonacci_number(30, 4) can_create_a_Fibonacci_number(29, 4)
def can_create_a__fibonacci_number(int_1, int_2): """ This function checks to see if the sum, difference, product, or module of the two inputs product a Fibonacci number. 1, 1, 2, 3, 5, 8, 13, 21, 34 ... The two inputs are assumed to be integers """ sum = int_1 + int_2 product = int_1 * int_2 if int_1 > int_2: diff = int_1 - int_2 mod = int_1 % int_2 else: diff = int_2 - int_1 mod = int_1 % int_2 possible_fibs = [sum, product, diff, mod] fib1 = 1 fib2 = 2 fib_found = False while fib2 < max(possible_fibs) and (not fib_found): new_fib = fib1 + fib2 if new_fib in possible_fibs: fib_found = True if new_fib == sum: print('Sum creates: ', new_fib) elif new_fib == product: print('Product creates: ', new_fib) elif new_fib == diff: print('Difference creates: ', new_fib) else: print('Modulo creates: ', new_fib) fib1 = fib2 fib2 = new_fib if not fib_found: print('No Fibonacci Number found under: ', fib2) can_create_a__fibonacci_number(30, 33) can_create_a__fibonacci_number(30, 4) can_create_a__fibonacci_number(29, 4)
""" The constants module contains some numerical constants for use in the module. Note that modifying these may yield unpredictable results. """ # Force zero values to this amount, for numerical stability MIN_SITE_FRACTION = 1e-12 MIN_PHASE_FRACTION = 1e-12 # Phases with mole fractions less than COMP_DIFFERENCE_TOL apart (by Chebyshev distance) are considered "the same" for # the purposes of CompositionSet addition and removal during energy minimization. COMP_DIFFERENCE_TOL = 1e-2 # 'infinity' for numerical purposes BIGNUM = 1e60
""" The constants module contains some numerical constants for use in the module. Note that modifying these may yield unpredictable results. """ min_site_fraction = 1e-12 min_phase_fraction = 1e-12 comp_difference_tol = 0.01 bignum = 1e+60
#!/usr/bin/env python major_version = 0 minor_version = 0 patch_version = 10 def format_version(): return "{0}.{1}.{2}".format(major_version, minor_version, patch_version)
major_version = 0 minor_version = 0 patch_version = 10 def format_version(): return '{0}.{1}.{2}'.format(major_version, minor_version, patch_version)
# BIP39 Wordlist Validator - A tool to validate BIP39 wordlists in Latin # languages. # bip39validator/data_structs.py: Program data structures. # Copyright 2020 Ali Sherief # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # A data structure consisting of # - An array of strings `word_list` # - An array of line numbers `line_numbers` # Each entry in `word_list` is associated with the corresponding entry in # `line_number`. They are expected to have the same length. # It is returned by the following functions: # - sanitize() # And is passed to the following functions: # - compute_levenshtein_distance() class WordAndLineArray: def __init__(self, args): self.word_list = args[0] self.line_numbers = args[1] # A data structure consisting of # - An integer distance `dist` # - A pair of line numbers `line_numbers` # - A pair of words `words` class LevDist: def __init__(self, **kwargs): self.dist = kwargs['dist'] self.line_numbers = kwargs['line_numbers'] self.words = kwargs['words'] class LevDistArray: def __init__(self, lev_dist_arr): self.lev_dist_arr = lev_dist_arr
class Wordandlinearray: def __init__(self, args): self.word_list = args[0] self.line_numbers = args[1] class Levdist: def __init__(self, **kwargs): self.dist = kwargs['dist'] self.line_numbers = kwargs['line_numbers'] self.words = kwargs['words'] class Levdistarray: def __init__(self, lev_dist_arr): self.lev_dist_arr = lev_dist_arr
class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: """ Ideas: 1. Count the frequencies, sort and take top k -> O(N) + O(N log N) 2. heapq.nlargest -> O(N) + O(N log N) 3. Count the frequencies and keep only top k elements in the heap -> O(N) + O(N log K) 4. QuickSelect -> runs in O(N) """ counts = collections.Counter(nums) counts = [item for item in counts.items()] top_k = self.quick_select(counts, k) return [num for num, _ in top_k] def quick_select(self, counts, k): """ [(1,3), (3, 1), (2, 2)] [1,2,3,4,5] k = 3 smaller = [1,2,3] bigger = [4,5] k = 1 smaller = [] bigger = [1,2,3] k = 1 smaller = [1,2] bigger = [3] """ pivot_idx = random.randint(0, len(counts)-1) pivot_count = counts[pivot_idx][1] smaller = [item for item in counts if item[1] < pivot_count] bigger = [item for item in counts if item[1] >= pivot_count] if len(bigger) == k: return bigger if len(bigger) > k: return self.quick_select(bigger, k) return bigger + self.quick_select(smaller, k-len(bigger))
class Solution: def top_k_frequent(self, nums: List[int], k: int) -> List[int]: """ Ideas: 1. Count the frequencies, sort and take top k -> O(N) + O(N log N) 2. heapq.nlargest -> O(N) + O(N log N) 3. Count the frequencies and keep only top k elements in the heap -> O(N) + O(N log K) 4. QuickSelect -> runs in O(N) """ counts = collections.Counter(nums) counts = [item for item in counts.items()] top_k = self.quick_select(counts, k) return [num for (num, _) in top_k] def quick_select(self, counts, k): """ [(1,3), (3, 1), (2, 2)] [1,2,3,4,5] k = 3 smaller = [1,2,3] bigger = [4,5] k = 1 smaller = [] bigger = [1,2,3] k = 1 smaller = [1,2] bigger = [3] """ pivot_idx = random.randint(0, len(counts) - 1) pivot_count = counts[pivot_idx][1] smaller = [item for item in counts if item[1] < pivot_count] bigger = [item for item in counts if item[1] >= pivot_count] if len(bigger) == k: return bigger if len(bigger) > k: return self.quick_select(bigger, k) return bigger + self.quick_select(smaller, k - len(bigger))
#!/bin/python3 FAVORITE_NUMBER = 1362 GRID = [[0 for j in range(50)] for i in range(50)] TARGET = (31, 39) def check_wall(coordinates): x, y = coordinates if x < 0 or y < 0 or x >= 50 or y >= 50: return False elif GRID[x][y] != 0: return False current = x * x + 3 * x + 2 * x * y + y + y * y current += FAVORITE_NUMBER current = bin(current)[2:].count("1") if current % 2 != 0: GRID[x][y] = -1 return False else: return True def day13(): queue = [(1, 1, 0)] while queue: x, y, steps = queue.pop(0) if (x, y) == TARGET: return steps GRID[x][y] = steps if check_wall((x - 1, y)): queue.append((x - 1, y, steps + 1)) if check_wall((x + 1, y)): queue.append((x + 1, y, steps + 1)) if check_wall((x, y - 1)): queue.append((x, y - 1, steps + 1)) if check_wall((x, y + 1)): queue.append((x, y + 1, steps + 1)) return False print(day13())
favorite_number = 1362 grid = [[0 for j in range(50)] for i in range(50)] target = (31, 39) def check_wall(coordinates): (x, y) = coordinates if x < 0 or y < 0 or x >= 50 or (y >= 50): return False elif GRID[x][y] != 0: return False current = x * x + 3 * x + 2 * x * y + y + y * y current += FAVORITE_NUMBER current = bin(current)[2:].count('1') if current % 2 != 0: GRID[x][y] = -1 return False else: return True def day13(): queue = [(1, 1, 0)] while queue: (x, y, steps) = queue.pop(0) if (x, y) == TARGET: return steps GRID[x][y] = steps if check_wall((x - 1, y)): queue.append((x - 1, y, steps + 1)) if check_wall((x + 1, y)): queue.append((x + 1, y, steps + 1)) if check_wall((x, y - 1)): queue.append((x, y - 1, steps + 1)) if check_wall((x, y + 1)): queue.append((x, y + 1, steps + 1)) return False print(day13())
# coding: utf-8 # author: Fei Gao # # Search A 2d Matrix Ii # Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: # Integers in each row are sorted in ascending from left to right. # Integers in each column are sorted in ascending from top to bottom. # For example, # Consider the following matrix: # [ # [1, 4, 7, 11, 15], # [2, 5, 8, 12, 19], # [3, 6, 9, 16, 22], # [10, 13, 14, 17, 24], # [18, 21, 23, 26, 30] # ] # Given target = 5, return true. # Given target = 20, return false. # Subscribe to see which companies asked this question class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ def search(row1, row2, col1, col2): """Search target in sub matrix[row1:row2][col1:col2]""" # zero elements if row1 >= row2 or col1 >= col2: return False if matrix[row1][col1] == target: return True # target less than up-left corner if target < matrix[row1][col1]: return False # target greater than low-right corner if target > matrix[row2 - 1][col2 - 1]: return False row3 = (row1 + row2 + 1) // 2 col3 = (col1 + col2 + 1) // 2 # print(row1, row3, row2, col1, col3, col2) result = (search(row1, row3, col1, col3) or search(row1, row3, col3, col2) or search(row3, row2, col1, col3) or search(row3, row2, col3, col2)) # print(row1, row2, col1, col2, result) return result return search(0, len(matrix), 0, len(matrix[0])) def main(): solver = Solution() tests = [ ([ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ], 5), ([ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ], 20) ] for test in tests: print(test) print(' ->') result = solver.searchMatrix(*test) print(result) print('~' * 10) pass if __name__ == '__main__': main() pass
class Solution(object): def search_matrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ def search(row1, row2, col1, col2): """Search target in sub matrix[row1:row2][col1:col2]""" if row1 >= row2 or col1 >= col2: return False if matrix[row1][col1] == target: return True if target < matrix[row1][col1]: return False if target > matrix[row2 - 1][col2 - 1]: return False row3 = (row1 + row2 + 1) // 2 col3 = (col1 + col2 + 1) // 2 result = search(row1, row3, col1, col3) or search(row1, row3, col3, col2) or search(row3, row2, col1, col3) or search(row3, row2, col3, col2) return result return search(0, len(matrix), 0, len(matrix[0])) def main(): solver = solution() tests = [([[1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30]], 5), ([[1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30]], 20)] for test in tests: print(test) print(' ->') result = solver.searchMatrix(*test) print(result) print('~' * 10) pass if __name__ == '__main__': main() pass
""" https://www.hackerrank.com/challenges/dynamic-array/problem """ def dynamicArray(n, queries): seqList = [[] for x in range(n)] lastAnswer = 0 result = [] for q in queries: [qType, seqIndex, number] = q index = (seqIndex ^ lastAnswer) % n seq = seqList[index] if qType == 1: seq.append(number) if qType == 2: lastAnswer = seq[number % len(seq)] result.append(lastAnswer) return result
""" https://www.hackerrank.com/challenges/dynamic-array/problem """ def dynamic_array(n, queries): seq_list = [[] for x in range(n)] last_answer = 0 result = [] for q in queries: [q_type, seq_index, number] = q index = (seqIndex ^ lastAnswer) % n seq = seqList[index] if qType == 1: seq.append(number) if qType == 2: last_answer = seq[number % len(seq)] result.append(lastAnswer) return result
_title = 'KleenExtractor' _description = 'Clean extract system to export folder content and sub content.' _version = '0.1.2' _author = 'Edenskull' _license = 'MIT'
_title = 'KleenExtractor' _description = 'Clean extract system to export folder content and sub content.' _version = '0.1.2' _author = 'Edenskull' _license = 'MIT'
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 1 10:46:16 2020 @author: AzureD Useful tools to splitting and cleaning up input text. """ def cleanly(text: str): """ Splits the text into words at spaces, removing excess spaces. """ segmented = text.split(' ') clean = [s for s in segmented if not s == ''] return clean def prefix(text: str): # NOTE: PEP 616 solved this in python version 3.9+ """ Takes the first word off the text, strips excess spaces and makes sure to always return a list containing a prefix, remainder pair of strings. """ segmented = text.split(' ', 1) # ensure a list of 2 elements unpacked into a prefix, remainder (even if remainder is nothing) prefix, remainder = segmented if len(segmented) == 2 else [text, ''] return(prefix, remainder.lstrip()) # lstrip removes excess spaces from remainder def command(text: str): """ Separates and cleans the command(prefix) from a given text, and lower cases it, returning both the command and the remaining text """ command, remainder = prefix(text) return(command.lower(), remainder)
""" Created on Sat Aug 1 10:46:16 2020 @author: AzureD Useful tools to splitting and cleaning up input text. """ def cleanly(text: str): """ Splits the text into words at spaces, removing excess spaces. """ segmented = text.split(' ') clean = [s for s in segmented if not s == ''] return clean def prefix(text: str): """ Takes the first word off the text, strips excess spaces and makes sure to always return a list containing a prefix, remainder pair of strings. """ segmented = text.split(' ', 1) (prefix, remainder) = segmented if len(segmented) == 2 else [text, ''] return (prefix, remainder.lstrip()) def command(text: str): """ Separates and cleans the command(prefix) from a given text, and lower cases it, returning both the command and the remaining text """ (command, remainder) = prefix(text) return (command.lower(), remainder)
q = int(input()) for _ in range(q): n = int(input()) m = [] for _ in range(n*2): m.append(list(map(int, input().split(' ')))) # Sorcery here... bigMax = 0 for i in range(n): for j in range(n): try: bigMax += max(m[i][j], m[i][2*n-1-j], m[2*n-1-i][j], m[2*n-1-i][2*n-1-j]) except: pass #print("(" + str(i) + ", " + str(j) + ")") print(bigMax)
q = int(input()) for _ in range(q): n = int(input()) m = [] for _ in range(n * 2): m.append(list(map(int, input().split(' ')))) big_max = 0 for i in range(n): for j in range(n): try: big_max += max(m[i][j], m[i][2 * n - 1 - j], m[2 * n - 1 - i][j], m[2 * n - 1 - i][2 * n - 1 - j]) except: pass print(bigMax)
secret = 'BEEF0123456789a' skipped_sequential_false_positive = '0123456789a' print('second line') var = 'third line'
secret = 'BEEF0123456789a' skipped_sequential_false_positive = '0123456789a' print('second line') var = 'third line'
#http://www.pythonchallenge.com/pc/def/ocr.html s = "" with open("3.html") as f: for line in f.readlines(): s += line for el in s: if el >= 'a' and el <= 'z': print(el),
s = '' with open('3.html') as f: for line in f.readlines(): s += line for el in s: if el >= 'a' and el <= 'z': (print(el),)
# feel free to change these settings APP_NAME = 'Deep Vision' # any string: The application title (desktop and web). ABOUT_TITLE = "Deep Vision" # any string: The about box title (desktop and web). ABOUT_MESSAGE = "Created By : FastAI Student" # any string: The about box contents (desktop and web). APP_TYPE = 'desktop' # desktop, web: Run the app as a desktop or a web application. SHOW_MEDIA = True # True, False: Show images and videos on screen. SAVE_MEDIA = False # True, False: Save images and videos to file. SAVE_MEDIA_PATH = None # any string, None: Save images and videos to this folder, set to None to use application path. SAVE_MEDIA_FILE = None # any string, None: Save images and videos to this file, set to None to use random file name. # Mostly you will not want to change these settings SHOW_LOGS = False # True, False: Print applications logs to console. CAMERA_ID = 0 # numbers: Target camera id, 0 for default camera IMAGES_TYPES = ['*.jpg', '*.jpeg', '*.jpe', '*.png', '*.bmp'] # any image format supported by openCV: Open image dialog file types VIDEOS_TYPES = ['*.mp4', '*.avi'] # any video format supported by openCV: Open video dialog file types SCALE_IMAGES = True # True, False: Scale source image to fit container (desktop or web) # don't change these settings APP_PATH = './'
app_name = 'Deep Vision' about_title = 'Deep Vision' about_message = 'Created By : FastAI Student' app_type = 'desktop' show_media = True save_media = False save_media_path = None save_media_file = None show_logs = False camera_id = 0 images_types = ['*.jpg', '*.jpeg', '*.jpe', '*.png', '*.bmp'] videos_types = ['*.mp4', '*.avi'] scale_images = True app_path = './'
# coding=utf-8 # Author: Jianghan LI # Question: 114.Flatten_Binary_Tree_to_Linked_List # Date: 2017-04-19 9:15 - 9:21 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ if not root: return queue = [root] if root.right: queue.append(root.right) if root.left: queue.append(root.left) while queue: cur = queue.pop() if cur.right: queue.append(cur.right) if cur.left: queue.append(cur.left) root.right = cur root.left = None root = cur root.right = None
class Solution(object): def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ if not root: return queue = [root] if root.right: queue.append(root.right) if root.left: queue.append(root.left) while queue: cur = queue.pop() if cur.right: queue.append(cur.right) if cur.left: queue.append(cur.left) root.right = cur root.left = None root = cur root.right = None
ch=input(('Enter any alphabet or digit ')) if ch in 'aeiouAEIOU': print(ch,'is a vowel.') elif ch in '0123456789': print(ch,'is a digit.') else: print(ch,'is a consonant.')
ch = input('Enter any alphabet or digit ') if ch in 'aeiouAEIOU': print(ch, 'is a vowel.') elif ch in '0123456789': print(ch, 'is a digit.') else: print(ch, 'is a consonant.')
class MessageWriter: """ This class allows a "message" to be sent to an external recipient. """ def __init__(self, *args, **kwargs): pass def send_message(self, message): """ Sends a message to an external recipient. Usually, this involves creating a connection to an API with any necessary credentials. :param message: :return: """ raise NotImplementedError
class Messagewriter: """ This class allows a "message" to be sent to an external recipient. """ def __init__(self, *args, **kwargs): pass def send_message(self, message): """ Sends a message to an external recipient. Usually, this involves creating a connection to an API with any necessary credentials. :param message: :return: """ raise NotImplementedError
LOCAL_STATE_PATH = "/state" DEFAULT_INSTANCE_TYPE_TRAINING = "ml.m5.large" DEFAULT_INSTANCE_TYPE_PROCESSING = "ml.t3.medium" DEFAULT_INSTANCE_COUNT = 1 DEFAULT_VOLUME_SIZE = 30 # GB DEFAULT_USE_SPOT = True DEFAULT_MAX_RUN = 24 * 60 DEFAULT_MAX_WAIT = 0 DEFAULT_IAM_ROLE = "SageMakerIAMRole" DEFAULT_IAM_BUCKET_POLICY_SUFFIX = "Policy" DEFAULT_REPO_TAG = "latest" TEST_LOG_LINE_PREFIX = "-***-" TEST_LOG_LINE_BLOCK_PREFIX = "*** START " TEST_LOG_LINE_BLOCK_SUFFIX = "*** END " TASK_TYPE_TRAINING = "Training" TASK_TYPE_PROCESSING = "Processing"
local_state_path = '/state' default_instance_type_training = 'ml.m5.large' default_instance_type_processing = 'ml.t3.medium' default_instance_count = 1 default_volume_size = 30 default_use_spot = True default_max_run = 24 * 60 default_max_wait = 0 default_iam_role = 'SageMakerIAMRole' default_iam_bucket_policy_suffix = 'Policy' default_repo_tag = 'latest' test_log_line_prefix = '-***-' test_log_line_block_prefix = '*** START ' test_log_line_block_suffix = '*** END ' task_type_training = 'Training' task_type_processing = 'Processing'
""" *Coarsen* """ __all__ = ["Coarsen"] class Coarsen( TensorOperator, ): pass
""" *Coarsen* """ __all__ = ['Coarsen'] class Coarsen(TensorOperator): pass
def avg(values): return sum(values) / len(values) def input_to_list(count): lines = [] for _ in range(count): lines.append(input()) return lines n = int(input()) students_grades_lines = input_to_list(n) students_grades = {} for line in students_grades_lines: student, grade = line.split(" ") if student not in students_grades: students_grades[student] = [] students_grades[student].append(float(grade)) for (student, grades) in students_grades.items(): grades_string = " ".join(map(lambda grade: f'{grade:.2f}', grades)) avg_grade = avg(grades) print(f"{student} -> {grades_string} (avg: {avg_grade:.2f})")
def avg(values): return sum(values) / len(values) def input_to_list(count): lines = [] for _ in range(count): lines.append(input()) return lines n = int(input()) students_grades_lines = input_to_list(n) students_grades = {} for line in students_grades_lines: (student, grade) = line.split(' ') if student not in students_grades: students_grades[student] = [] students_grades[student].append(float(grade)) for (student, grades) in students_grades.items(): grades_string = ' '.join(map(lambda grade: f'{grade:.2f}', grades)) avg_grade = avg(grades) print(f'{student} -> {grades_string} (avg: {avg_grade:.2f})')
""" ## OSBot-Utils Project with multiple Util classes (to streamline development) Main GitHub repo: https://github.com/owasp-sbot/OSBot-Utils [![Coverage Status](https://coveralls.io/repos/github/owasp-sbot/OSBot-Utils/badge.svg?branch=master)](https://coveralls.io/github/owasp-sbot/OSBot-Utils?branch=master) """
""" ## OSBot-Utils Project with multiple Util classes (to streamline development) Main GitHub repo: https://github.com/owasp-sbot/OSBot-Utils [![Coverage Status](https://coveralls.io/repos/github/owasp-sbot/OSBot-Utils/badge.svg?branch=master)](https://coveralls.io/github/owasp-sbot/OSBot-Utils?branch=master) """
class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: weight = dict() for x in people: if x in weight: weight[x] += 1 else: weight[x] = 1 ans = 0 for x in people: if weight[x] > 0: weight[x]-= 1 upper = limit - x for i in range(upper,0,-1): if i in weight: if weight[i] > 0: weight[i] -= 1 break ans += 1 else: continue return ans
class Solution: def num_rescue_boats(self, people: List[int], limit: int) -> int: weight = dict() for x in people: if x in weight: weight[x] += 1 else: weight[x] = 1 ans = 0 for x in people: if weight[x] > 0: weight[x] -= 1 upper = limit - x for i in range(upper, 0, -1): if i in weight: if weight[i] > 0: weight[i] -= 1 break ans += 1 else: continue return ans
n=int(input()) l=[] k=[] e=[] for i in range (n): t=input() l.append(t) print(l) for j in l: if j not in k: k.append(j) print(k) print(len(k)) for m in range(len(k)): c=0 for d in l: if( k[m]==d): c=c+1 e.append(c) print(e) for i in e: print(i,end=' ')
n = int(input()) l = [] k = [] e = [] for i in range(n): t = input() l.append(t) print(l) for j in l: if j not in k: k.append(j) print(k) print(len(k)) for m in range(len(k)): c = 0 for d in l: if k[m] == d: c = c + 1 e.append(c) print(e) for i in e: print(i, end=' ')
""" format: def request(login, password): return bool(...) """
""" format: def request(login, password): return bool(...) """
class Shop: _small_shop_capacity = 10 def __init__(self, name, shop_type, capacity): self.name = name self.type = shop_type self.capacity = capacity self.items_count = 0 self.items = {} @classmethod def small_shop(cls, name, shop_type): return cls(name, shop_type, cls._small_shop_capacity) def _can_add_item(self): return self.items_count < self.capacity - 1 def _can_remove_amount_of_item(self, item, amount): return item in self.items and amount <= self.items[item] def add_item(self, item): if not self._can_add_item(): return 'Not enough capacity in the shop' if item not in self.items: self.items[item] = 0 self.items[item] += 1 self.items_count += 1 return f'{item} added to the shop' def remove_item(self, item, amount): if not self._can_remove_amount_of_item(item, amount): return f'Cannot remove {amount} {item}' self.items[item] -= amount self.items_count -= amount return f'{amount} {item} removed from the shop' def __str__(self): return f'{self.name} of type {self.type} with capacity {self.capacity}'
class Shop: _small_shop_capacity = 10 def __init__(self, name, shop_type, capacity): self.name = name self.type = shop_type self.capacity = capacity self.items_count = 0 self.items = {} @classmethod def small_shop(cls, name, shop_type): return cls(name, shop_type, cls._small_shop_capacity) def _can_add_item(self): return self.items_count < self.capacity - 1 def _can_remove_amount_of_item(self, item, amount): return item in self.items and amount <= self.items[item] def add_item(self, item): if not self._can_add_item(): return 'Not enough capacity in the shop' if item not in self.items: self.items[item] = 0 self.items[item] += 1 self.items_count += 1 return f'{item} added to the shop' def remove_item(self, item, amount): if not self._can_remove_amount_of_item(item, amount): return f'Cannot remove {amount} {item}' self.items[item] -= amount self.items_count -= amount return f'{amount} {item} removed from the shop' def __str__(self): return f'{self.name} of type {self.type} with capacity {self.capacity}'
for row in range(5,0): for col in range(1,row+1): print(col,end=" ") print()
for row in range(5, 0): for col in range(1, row + 1): print(col, end=' ') print()
IDENTIFIED_COMMANDS = { 'NS STATUS %s': ['STATUS {username} (\d)', '3'], 'PRIVMSG NickServ ACC %s': ['{username} ACC (\d)', '3'], } IRC_AUTHS = { # 'localhost': {'username': 'Botname', 'realname': 'Bot Real Name'}, } IRC_GROUPCHATS = [ # 'groupchat@localhost', ] IRC_PERMISSIONS = { # 'nekmo@localhost': ['root'], }
identified_commands = {'NS STATUS %s': ['STATUS {username} (\\d)', '3'], 'PRIVMSG NickServ ACC %s': ['{username} ACC (\\d)', '3']} irc_auths = {} irc_groupchats = [] irc_permissions = {}
class Solution: def decompressRLElist(self, nums: List[int]) -> List[int]: result = [] for i in range(0, len(nums), 2): freq, val = nums[i:i+2] for n in range(freq): result.append(val) return result
class Solution: def decompress_rl_elist(self, nums: List[int]) -> List[int]: result = [] for i in range(0, len(nums), 2): (freq, val) = nums[i:i + 2] for n in range(freq): result.append(val) return result
filename = "myFile1.py" with open(filename, "r") as f: for line in f: print(f)
filename = 'myFile1.py' with open(filename, 'r') as f: for line in f: print(f)
""" domonic.constants ==================================== """ namespaces = {'xml': 'http://www.w3.org/XML/1998/namespace', 'svg': 'http://www.w3.org/2000/svg', 'xlink': 'http://www.w3.org/1999/xlink', 'xmlns': 'http://www.w3.org/2000/xmlns/', 'xm': 'http://www.w3.org/2001/xml-events', 'xh': 'http://www.w3.org/1999/xhtml'} # gravitational_constant = 6.67384e-11 # planck_constant = 6.62606957e-34 # speed_of_light = 299792458 # electron_charge = 1.602176565e-19 # electron_mass = 9.10938291e-31 # proton_mass = 1.672621777e-27 # neutron_mass = 1.674927351e-27 # atomic_mass_unit = 1.660539040e-24 # avogadro_constant = 6.02214129e23 # boltzmann_constant = 1.3806488e-23 # gas_constant = 8.3144621 # i love #copilot
""" domonic.constants ==================================== """ namespaces = {'xml': 'http://www.w3.org/XML/1998/namespace', 'svg': 'http://www.w3.org/2000/svg', 'xlink': 'http://www.w3.org/1999/xlink', 'xmlns': 'http://www.w3.org/2000/xmlns/', 'xm': 'http://www.w3.org/2001/xml-events', 'xh': 'http://www.w3.org/1999/xhtml'}
m = 35.0 / 8.0 n = int(35/8) print(m) print(n)
m = 35.0 / 8.0 n = int(35 / 8) print(m) print(n)
class Dealer: def __init__(self): self.__hand = None def select_action(self): if self.hand_total() < 17: return 1 else: return 0 def give_card(self, card): self.__hand.add_card(card) def revealed_card(self): cards = self.__hand.cards() return cards[0] def is_busted(self): return self.__hand.is_busted() def new_hand(self, hand): self.__hand = hand def hand(self): return self.__hand def hand_total(self): return self.__hand.total()
class Dealer: def __init__(self): self.__hand = None def select_action(self): if self.hand_total() < 17: return 1 else: return 0 def give_card(self, card): self.__hand.add_card(card) def revealed_card(self): cards = self.__hand.cards() return cards[0] def is_busted(self): return self.__hand.is_busted() def new_hand(self, hand): self.__hand = hand def hand(self): return self.__hand def hand_total(self): return self.__hand.total()
# https://cses.fi/problemset/task/1083 d = [False for _ in range(int(input()))] for i in input().split(' '): d[int(i) - 1] = True for i, b in enumerate(d): if not b: print(i + 1) exit()
d = [False for _ in range(int(input()))] for i in input().split(' '): d[int(i) - 1] = True for (i, b) in enumerate(d): if not b: print(i + 1) exit()
{ "targets": [ { "target_name": "lib/daemon", "sources": [ "src/daemon.cc" ] } ] }
{'targets': [{'target_name': 'lib/daemon', 'sources': ['src/daemon.cc']}]}
class CommandTools: @staticmethod def get_token(): """ Simple helper that will return the token stored in the text file. :return: Your Robinhood API token """ robinhood_token_file = open('robinhood_token.txt') current_token = robinhood_token_file.read() return current_token
class Commandtools: @staticmethod def get_token(): """ Simple helper that will return the token stored in the text file. :return: Your Robinhood API token """ robinhood_token_file = open('robinhood_token.txt') current_token = robinhood_token_file.read() return current_token
def main(): st = input("") print(st[0]) print(end="") main()
def main(): st = input('') print(st[0]) print(end='') main()
# This program demonstrates how to use the remove # method to remove an item from a list. def main(): # Create a list with some items. food = ['Pizza', 'Burgers', 'Chips'] # Display the list. print('Here are the items in the food list:') print(food) # Get the item to change. item = input('Which item should I remove? ') try: # Remove the item. food.remove(item) # Display the list. print('Here is the revised list:') print(food) except ValueError: print('That item was not found in the list.') # Call the main function. main()
def main(): food = ['Pizza', 'Burgers', 'Chips'] print('Here are the items in the food list:') print(food) item = input('Which item should I remove? ') try: food.remove(item) print('Here is the revised list:') print(food) except ValueError: print('That item was not found in the list.') main()
class TeamNotFound(Exception): """Raise when the team is not found in the database""" class NoMatchData(Exception): """Raise when data for match cant be created"""
class Teamnotfound(Exception): """Raise when the team is not found in the database""" class Nomatchdata(Exception): """Raise when data for match cant be created"""
def computepay(h, r): print("In computepay") if h>40: pay = 40 * r + (h - 40) * 1.5 * r else: pay = h * r return pay hrs = input("Enter Hours:") h = float(hrs) rate = input("Enter Rate:") r = float(rate) pay = computepay(h,r) print(pay)
def computepay(h, r): print('In computepay') if h > 40: pay = 40 * r + (h - 40) * 1.5 * r else: pay = h * r return pay hrs = input('Enter Hours:') h = float(hrs) rate = input('Enter Rate:') r = float(rate) pay = computepay(h, r) print(pay)
"""Scheduling errors.""" class AssignmentError(Exception): """Raised for errors when generating assignments.""" def __init__(self, message: str): self.message = message
"""Scheduling errors.""" class Assignmenterror(Exception): """Raised for errors when generating assignments.""" def __init__(self, message: str): self.message = message
''' MIT License Name cs225sp20_env Python Package URL https://github.com/Xiwei-Wang/cs225sp20_env Version 1.0 Creation Date 26 April 2020 Copyright(c) 2020 Instructors, TAs and Some Students of UIUC CS 225 SP20 ZJUI Course Instructorts: Prof. Dr. Klaus-Dieter Schewe TAs: Tingou Liang, Run Zhang, Enyi Jiang, Xiang Li Group 1 Students: Shen Zheng, Haozhe Chen, Ruiqi Li, Xiwei Wang Other Students: Zhongbo Zhu Above all, due to academic integrity, students who will take UIUC CS 225 ZJUI Course taught with Python later than Spring 2020 semester are NOT authorized with the access to this package. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --------- File cs225sp20_env/Tree/Trie.py Version 1.0 ''' # %% class Trie: class TrieNode: def __init__(self,item,next=None,follows=None): self.item = item self.next = next self.follows = follows def __init__(self): self.start = None def insert(self,item): if type(item) == str: item = list(item) self.start = Trie.__insert(self.start,item) def __contains__(self,item): if type(item) == str: item = list(item) return Trie.__contains(self.start,item+["#"]) def __insert(node,item): if item == []: # end condition if node != None: newnode = Trie.TrieNode('#',next=node) else: newnode = Trie.TrieNode("#") return newnode if node == None: # if trie is empty key = item.pop(0) # one letter per node newnode = Trie.TrieNode(key) newnode.follows = Trie.__insert(newnode.follows,item) return newnode else: key = item[0] if node.item == key: # letter already in the trie key = item.pop(0) node.follows = Trie.__insert(node.follows,item) else: node.next = Trie.__insert(node.next,item) return node def __contains(node,item): if type(item) == str: item = list(item) if item == []: return True if node == None: return False key = item[0] if node.item == key: key = item.pop(0) return Trie.__contains(node.follows,item) return Trie.__contains(node.next,item) # a print function which can print out structure of tries # to help better understand def print_trie(self,show_start = False): if show_start: print('start\n |\n ',end='') self.__print_trie(self.start,1) else: self.__print_trie(self.start,0) def __print_trie(self, root, level_f): if(root == None): return if(root.item != '#'): print(root.item, '-', end='') else: # print(root.item, end='') # modified print(root.item, end='\n') self.__print_trie(root.follows, level_f+1) if(root.next!=None): # print('\n') # commented str_sp = ' '*level_f*3 print(str_sp+'|') print(str_sp, end='') self.__print_trie(root.next,level_f) return # %% if __name__ == '__main__': trie = Trie() for word in [ 'cow','cowboy', 'cat','rat','rabbit','dog', 'pear','peer','pier']: trie.insert(word) assert 'cow' in trie assert 'cowboy' in trie assert 'pear' in trie assert 'peer' in trie assert 'pier' in trie trie.print_trie()
""" MIT License Name cs225sp20_env Python Package URL https://github.com/Xiwei-Wang/cs225sp20_env Version 1.0 Creation Date 26 April 2020 Copyright(c) 2020 Instructors, TAs and Some Students of UIUC CS 225 SP20 ZJUI Course Instructorts: Prof. Dr. Klaus-Dieter Schewe TAs: Tingou Liang, Run Zhang, Enyi Jiang, Xiang Li Group 1 Students: Shen Zheng, Haozhe Chen, Ruiqi Li, Xiwei Wang Other Students: Zhongbo Zhu Above all, due to academic integrity, students who will take UIUC CS 225 ZJUI Course taught with Python later than Spring 2020 semester are NOT authorized with the access to this package. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --------- File cs225sp20_env/Tree/Trie.py Version 1.0 """ class Trie: class Trienode: def __init__(self, item, next=None, follows=None): self.item = item self.next = next self.follows = follows def __init__(self): self.start = None def insert(self, item): if type(item) == str: item = list(item) self.start = Trie.__insert(self.start, item) def __contains__(self, item): if type(item) == str: item = list(item) return Trie.__contains(self.start, item + ['#']) def __insert(node, item): if item == []: if node != None: newnode = Trie.TrieNode('#', next=node) else: newnode = Trie.TrieNode('#') return newnode if node == None: key = item.pop(0) newnode = Trie.TrieNode(key) newnode.follows = Trie.__insert(newnode.follows, item) return newnode else: key = item[0] if node.item == key: key = item.pop(0) node.follows = Trie.__insert(node.follows, item) else: node.next = Trie.__insert(node.next, item) return node def __contains(node, item): if type(item) == str: item = list(item) if item == []: return True if node == None: return False key = item[0] if node.item == key: key = item.pop(0) return Trie.__contains(node.follows, item) return Trie.__contains(node.next, item) def print_trie(self, show_start=False): if show_start: print('start\n |\n ', end='') self.__print_trie(self.start, 1) else: self.__print_trie(self.start, 0) def __print_trie(self, root, level_f): if root == None: return if root.item != '#': print(root.item, '-', end='') else: print(root.item, end='\n') self.__print_trie(root.follows, level_f + 1) if root.next != None: str_sp = ' ' * level_f * 3 print(str_sp + '|') print(str_sp, end='') self.__print_trie(root.next, level_f) return if __name__ == '__main__': trie = trie() for word in ['cow', 'cowboy', 'cat', 'rat', 'rabbit', 'dog', 'pear', 'peer', 'pier']: trie.insert(word) assert 'cow' in trie assert 'cowboy' in trie assert 'pear' in trie assert 'peer' in trie assert 'pier' in trie trie.print_trie()
def merge(list0,list1): result = [] while len(list1) and len(list0): if list0[0]<list1[0]: result.append(list0.pop(0)) else: result.append(list1.pop(0)) result.extend(list0) result.extend(list1) return result def mergesort(item): if len(item)<=1: return item mid = int(len(item)/2) left = item[0:mid] right = item[mid:len(item)] left = mergesort(left) right = mergesort(right) result = merge(left,right) return result if __name__ == '__main__': print('Enter a list of numbrt saperated by space.') arr = list(map(int,input().split())) print(mergesort(arr))
def merge(list0, list1): result = [] while len(list1) and len(list0): if list0[0] < list1[0]: result.append(list0.pop(0)) else: result.append(list1.pop(0)) result.extend(list0) result.extend(list1) return result def mergesort(item): if len(item) <= 1: return item mid = int(len(item) / 2) left = item[0:mid] right = item[mid:len(item)] left = mergesort(left) right = mergesort(right) result = merge(left, right) return result if __name__ == '__main__': print('Enter a list of numbrt saperated by space.') arr = list(map(int, input().split())) print(mergesort(arr))
# Link - https://leetcode.com/problems/unique-morse-code-words/ ''' Runtime: 28 ms, faster than 95.58% of Python3 online submissions for Unique Morse Code Words. Memory Usage: 13.6 MB, less than 99.77% of Python3 online submissions for Unique Morse Code Words. ''' class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] answers = [] for i in words: z = '' for j in i: z += morse[ord(j) - 97] answers.append(z) return len(set(answers))
""" Runtime: 28 ms, faster than 95.58% of Python3 online submissions for Unique Morse Code Words. Memory Usage: 13.6 MB, less than 99.77% of Python3 online submissions for Unique Morse Code Words. """ class Solution: def unique_morse_representations(self, words: List[str]) -> int: morse = ['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--', '-..-', '-.--', '--..'] answers = [] for i in words: z = '' for j in i: z += morse[ord(j) - 97] answers.append(z) return len(set(answers))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # services - Waqas Bhatti (wbhatti@astro.princeton.edu) - Oct 2017 # License: MIT. See the LICENSE file for more details. '''This contains various modules to query online data services. These are not exhaustive and are meant to support other astrobase modules. - :py:mod:`astrobase.services.dust`: interface to the 2MASS DUST extinction/emission service. - :py:mod:`astrobase.services.gaia`: interface to the GAIA TAP+ ADQL query service. - :py:mod:`astrobase.services.lccs`: interface to the `LCC-Server <https://github.com/waqasbhatti/lcc-server>`_ API. - :py:mod:`astrobase.services.mast`: interface to the MAST catalogs at STScI and the TESS Input Catalog in particular. - :py:mod:`astrobase.services.simbad`: interface to the CDS SIMBAD service. - :py:mod:`astrobase.services.skyview`: interface to the NASA SkyView finder-chart and cutout service. - :py:mod:`astrobase.services.trilegal`: interface to the Girardi TRILEGAL galaxy model forms and service. - :py:mod:`astrobase.services.limbdarkening`: utilities to get stellar limb darkening coefficients for use during transit fitting. - :py:mod:`astrobase.services.identifiers`: utilities to convert from SIMBAD object names to GAIA DR2 source identifiers and TESS Input Catalogs IDs. - :py:mod:`astrobase.services.tesslightcurves`: utilities to download various TESS light curve products from MAST. - :py:mod:`astrobase.services.alltesslightcurves`: utilities to download all TESS light curve products from MAST for a given TIC ID. For a much broader interface to online data services, use the astroquery package by A. Ginsburg, B. Sipocz, et al.: http://astroquery.readthedocs.io '''
"""This contains various modules to query online data services. These are not exhaustive and are meant to support other astrobase modules. - :py:mod:`astrobase.services.dust`: interface to the 2MASS DUST extinction/emission service. - :py:mod:`astrobase.services.gaia`: interface to the GAIA TAP+ ADQL query service. - :py:mod:`astrobase.services.lccs`: interface to the `LCC-Server <https://github.com/waqasbhatti/lcc-server>`_ API. - :py:mod:`astrobase.services.mast`: interface to the MAST catalogs at STScI and the TESS Input Catalog in particular. - :py:mod:`astrobase.services.simbad`: interface to the CDS SIMBAD service. - :py:mod:`astrobase.services.skyview`: interface to the NASA SkyView finder-chart and cutout service. - :py:mod:`astrobase.services.trilegal`: interface to the Girardi TRILEGAL galaxy model forms and service. - :py:mod:`astrobase.services.limbdarkening`: utilities to get stellar limb darkening coefficients for use during transit fitting. - :py:mod:`astrobase.services.identifiers`: utilities to convert from SIMBAD object names to GAIA DR2 source identifiers and TESS Input Catalogs IDs. - :py:mod:`astrobase.services.tesslightcurves`: utilities to download various TESS light curve products from MAST. - :py:mod:`astrobase.services.alltesslightcurves`: utilities to download all TESS light curve products from MAST for a given TIC ID. For a much broader interface to online data services, use the astroquery package by A. Ginsburg, B. Sipocz, et al.: http://astroquery.readthedocs.io """