content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#!/usr/bin/env python3 def get_vertices(wire): x = y = steps = 0 vertices = [(x, y, 0)] for edge in wire: length = int(edge[1:]) steps += length if edge[0] == "R": x += length if edge[0] == "L": x -= length if edge[0] == "U": y += length if edge[0] == "D": y -= length vertices.append((x, y, steps)) return vertices def get_intersections(edges1, edges2): intersections = [] for i in range(len(edges1) - 1): for j in range(len(edges2) - 1): intersection = get_intersection( edges1[i], edges1[i + 1], edges2[j], edges2[j + 1] ) if intersection: intersections.append(intersection) # remove 0,0 if any try: intersections.remove((0, 0, 0)) except Exception: pass return intersections def get_distance(vert): return abs(vert[0]) + abs(vert[1]) def get_intersection(e1from, e1to, e2from, e2to): e1x1, e1y1, steps_e1 = e1from e1x2, e1y2, _ = e1to e2x1, e2y1, steps_e2 = e2from e2x2, e2y2, _ = e2to if e1y1 == e1y2 and e2x1 == e2x2: # e1 is horizontal and e2 is vertical if (e2y1 <= e1y1 <= e2y2 or e2y1 >= e1y1 >= e2y2) and ( e1x1 <= e2x1 <= e1x2 or e1x1 >= e2x1 >= e1x2 ): steps = steps_e1 + steps_e2 + abs(e2x1 - e1x1) + abs(e1y1 - e2y1) return (e2x1, e1y1, steps) elif e2y1 == e2y2 and e1x1 == e1x2: # e1 is vertical and e2 is horizontal if (e1y1 <= e2y1 <= e1y2 or e1y1 >= e2y1 >= e1y2) and ( e2x1 <= e1x1 <= e2x2 or e2x1 >= e1x1 >= e2x2 ): steps = steps_e1 + steps_e2 + abs(e1x1 - e2x1) + abs(e2y1 - e1y1) return (e1x1, e2y1, steps) def get_closest_intersection(edges1, edges2): ints = get_intersections(edges1, edges2) return min(map(lambda vert: get_distance(vert), ints)) def get_min_path_intersection(edges1, edges2): ints = get_intersections(edges1, edges2) return min(map(lambda vert: vert[2], ints)) def test1(): wire1 = ["R8", "U5", "L5", "D3"] wire2 = ["U7", "R6", "D4", "L4"] edges1 = get_vertices(wire1) edges2 = get_vertices(wire2) assert get_closest_intersection(edges1, edges2) == 6 assert get_min_path_intersection(edges1, edges2) == 30 def test2(): wire1 = ["R75", "D30", "R83", "U83", "L12", "D49", "R71", "U7", "L72"] wire2 = ["U62", "R66", "U55", "R34", "D71", "R55", "D58", "R83"] edges1 = get_vertices(wire1) edges2 = get_vertices(wire2) assert get_closest_intersection(edges1, edges2) == 159 assert get_min_path_intersection(edges1, edges2) == 610 if __name__ == "__main__": with open("../inputs/day03.txt") as ip: lines = ip.readlines() wire1 = lines[0].strip().split(",") edges1 = get_vertices(wire1) wire2 = lines[1].strip().split(",") edges2 = get_vertices(wire2) print( "Distanct to closest intersection", get_closest_intersection(edges1, edges2) ) print("Min Steps to intersection", get_min_path_intersection(edges1, edges2))
def get_vertices(wire): x = y = steps = 0 vertices = [(x, y, 0)] for edge in wire: length = int(edge[1:]) steps += length if edge[0] == 'R': x += length if edge[0] == 'L': x -= length if edge[0] == 'U': y += length if edge[0] == 'D': y -= length vertices.append((x, y, steps)) return vertices def get_intersections(edges1, edges2): intersections = [] for i in range(len(edges1) - 1): for j in range(len(edges2) - 1): intersection = get_intersection(edges1[i], edges1[i + 1], edges2[j], edges2[j + 1]) if intersection: intersections.append(intersection) try: intersections.remove((0, 0, 0)) except Exception: pass return intersections def get_distance(vert): return abs(vert[0]) + abs(vert[1]) def get_intersection(e1from, e1to, e2from, e2to): (e1x1, e1y1, steps_e1) = e1from (e1x2, e1y2, _) = e1to (e2x1, e2y1, steps_e2) = e2from (e2x2, e2y2, _) = e2to if e1y1 == e1y2 and e2x1 == e2x2: if (e2y1 <= e1y1 <= e2y2 or e2y1 >= e1y1 >= e2y2) and (e1x1 <= e2x1 <= e1x2 or e1x1 >= e2x1 >= e1x2): steps = steps_e1 + steps_e2 + abs(e2x1 - e1x1) + abs(e1y1 - e2y1) return (e2x1, e1y1, steps) elif e2y1 == e2y2 and e1x1 == e1x2: if (e1y1 <= e2y1 <= e1y2 or e1y1 >= e2y1 >= e1y2) and (e2x1 <= e1x1 <= e2x2 or e2x1 >= e1x1 >= e2x2): steps = steps_e1 + steps_e2 + abs(e1x1 - e2x1) + abs(e2y1 - e1y1) return (e1x1, e2y1, steps) def get_closest_intersection(edges1, edges2): ints = get_intersections(edges1, edges2) return min(map(lambda vert: get_distance(vert), ints)) def get_min_path_intersection(edges1, edges2): ints = get_intersections(edges1, edges2) return min(map(lambda vert: vert[2], ints)) def test1(): wire1 = ['R8', 'U5', 'L5', 'D3'] wire2 = ['U7', 'R6', 'D4', 'L4'] edges1 = get_vertices(wire1) edges2 = get_vertices(wire2) assert get_closest_intersection(edges1, edges2) == 6 assert get_min_path_intersection(edges1, edges2) == 30 def test2(): wire1 = ['R75', 'D30', 'R83', 'U83', 'L12', 'D49', 'R71', 'U7', 'L72'] wire2 = ['U62', 'R66', 'U55', 'R34', 'D71', 'R55', 'D58', 'R83'] edges1 = get_vertices(wire1) edges2 = get_vertices(wire2) assert get_closest_intersection(edges1, edges2) == 159 assert get_min_path_intersection(edges1, edges2) == 610 if __name__ == '__main__': with open('../inputs/day03.txt') as ip: lines = ip.readlines() wire1 = lines[0].strip().split(',') edges1 = get_vertices(wire1) wire2 = lines[1].strip().split(',') edges2 = get_vertices(wire2) print('Distanct to closest intersection', get_closest_intersection(edges1, edges2)) print('Min Steps to intersection', get_min_path_intersection(edges1, edges2))
dim=10.0 eta=0.5 steps=100 #must be integer (no decimal point) rneighb=eta
dim = 10.0 eta = 0.5 steps = 100 rneighb = eta
# automatically generated by the FlatBuffers compiler, do not modify # namespace: apemodefb class EAnimCurvePropertyFb(object): LclTranslation = 0 RotationOffset = 1 RotationPivot = 2 PreRotation = 3 PostRotation = 4 LclRotation = 5 ScalingOffset = 6 ScalingPivot = 7 LclScaling = 8 GeometricTranslation = 9 GeometricRotation = 10 GeometricScaling = 11
class Eanimcurvepropertyfb(object): lcl_translation = 0 rotation_offset = 1 rotation_pivot = 2 pre_rotation = 3 post_rotation = 4 lcl_rotation = 5 scaling_offset = 6 scaling_pivot = 7 lcl_scaling = 8 geometric_translation = 9 geometric_rotation = 10 geometric_scaling = 11
__author__ = 'tylin' # from .bleu import Bleu # # __all__ = ['Bleu']
__author__ = 'tylin'
# General ES Constants COUNT = 'count' CREATE = 'create' DOCS = 'docs' FIELD = 'field' FIELDS = 'fields' HITS = 'hits' ID = '_id' INDEX = 'index' INDEX_NAME = 'index_name' ITEMS = 'items' KILOMETERS = 'km' MAPPING_DYNAMIC = 'dynamic' MAPPING_MULTI_FIELD = 'multi_field' MAPPING_NULL_VALUE = 'null_value' MILES = 'mi' OK = 'ok' PROPERTIES = 'properties' PROPERTY_TYPE = 'type' SCORE = '_score' SOURCE = '_source' TOTAL = 'total' TTL = '_ttl' TYPE = '_type' UID = '_uid' UNIT = 'unit' URL = 'url' URLS = 'urls' # Matching / Filtering AND = "and" BOOL = 'bool' DOC_TYPE = 'doc_type' FILTER = 'filter' FILTERED = 'filtered' MATCH_ALL = 'match_all' MUST = 'must' MUST_NOT = 'must_not' OR = "or" QUERY = 'query' SHOULD = 'should' SORT = 'sort' TERMS = 'terms' TERM = 'term' # Sorting / Misc. ASC = 'asc' DESC = 'desc' FACET_FILTER = 'facet_filter' FACETS = 'facets' FROM = 'from' OFFSET = 'offset' ORDER = 'order' SIZE = 'size' TO = 'to' # Runtime Constants DEFAULT_PAGE_SIZE = 20
count = 'count' create = 'create' docs = 'docs' field = 'field' fields = 'fields' hits = 'hits' id = '_id' index = 'index' index_name = 'index_name' items = 'items' kilometers = 'km' mapping_dynamic = 'dynamic' mapping_multi_field = 'multi_field' mapping_null_value = 'null_value' miles = 'mi' ok = 'ok' properties = 'properties' property_type = 'type' score = '_score' source = '_source' total = 'total' ttl = '_ttl' type = '_type' uid = '_uid' unit = 'unit' url = 'url' urls = 'urls' and = 'and' bool = 'bool' doc_type = 'doc_type' filter = 'filter' filtered = 'filtered' match_all = 'match_all' must = 'must' must_not = 'must_not' or = 'or' query = 'query' should = 'should' sort = 'sort' terms = 'terms' term = 'term' asc = 'asc' desc = 'desc' facet_filter = 'facet_filter' facets = 'facets' from = 'from' offset = 'offset' order = 'order' size = 'size' to = 'to' default_page_size = 20
load("//third_party:common.bzl", "err_out", "execute") _LLVM_BINARIES = [ "clang", "clang-cpp", "ld.lld", "llvm-ar", "llvm-as", "llvm-nm", "llvm-objcopy", "llvm-objdump", "llvm-profdata", "llvm-dwp", "llvm-ranlib", "llvm-readelf", "llvm-strip", "llvm-symbolizer", ] _LLVM_VERSION_MINIMAL = "10.0.0" def _label(filename): return Label("//third_party/llvm_toolchain:{}".format(filename)) def _check_llvm_binaries(repository_ctx, llvm_dir): for binary in _LLVM_BINARIES: binary_path = "{}/bin/{}".format(llvm_dir, binary) if not repository_ctx.path(binary_path).exists: fail("{} doesn't exist".format(binary_path)) def _retrieve_clang_version(repository_ctx, clang_binary): script_path = repository_ctx.path(Label("//third_party/llvm_toolchain:find_clang_version.py")) python_bin = repository_ctx.which("python3") result = execute(repository_ctx, [python_bin, script_path, clang_binary]) if result.return_code: fail("Failed to run find_clang_version.py: {}".format(err_out(result))) llvm_version = result.stdout.strip() actual_version = [int(m) for m in llvm_version.split(".")] minimal_version = [int(m) for m in _LLVM_VERSION_MINIMAL.split(".")] if actual_version < minimal_version: fail("Minimal llvm version supported is {}, got: {}".format(_LLVM_VERSION_MINIMAL, llvm_version)) return result.stdout.strip() def _local_config_llvm_impl(repository_ctx): llvm_dir = repository_ctx.os.environ.get("LLVM_DIR", None) if not llvm_dir: fail("LLVM_DIR not set.") if llvm_dir.endswith("/"): llvm_dir = llvm_dir[:-1] _check_llvm_binaries(repository_ctx, llvm_dir) clang_binary = "{}/bin/clang".format(llvm_dir) llvm_version = _retrieve_clang_version(repository_ctx, clang_binary) repository_ctx.symlink(_label("cc_toolchain_config.bzl"), "cc_toolchain_config.bzl") arch = repository_ctx.execute(["uname", "-m"]).stdout.strip() repository_ctx.template( "toolchains.bzl", _label("toolchains.bzl.tpl"), { "%{arch}": arch, }, ) repository_ctx.template( "BUILD", _label("BUILD.tpl"), { "%{arch}": arch, "%{llvm_dir}": llvm_dir, "%{llvm_version}": llvm_version, }, ) local_config_llvm = repository_rule( implementation = _local_config_llvm_impl, environ = ["LLVM_DIR"], local = True, configure = True, )
load('//third_party:common.bzl', 'err_out', 'execute') _llvm_binaries = ['clang', 'clang-cpp', 'ld.lld', 'llvm-ar', 'llvm-as', 'llvm-nm', 'llvm-objcopy', 'llvm-objdump', 'llvm-profdata', 'llvm-dwp', 'llvm-ranlib', 'llvm-readelf', 'llvm-strip', 'llvm-symbolizer'] _llvm_version_minimal = '10.0.0' def _label(filename): return label('//third_party/llvm_toolchain:{}'.format(filename)) def _check_llvm_binaries(repository_ctx, llvm_dir): for binary in _LLVM_BINARIES: binary_path = '{}/bin/{}'.format(llvm_dir, binary) if not repository_ctx.path(binary_path).exists: fail("{} doesn't exist".format(binary_path)) def _retrieve_clang_version(repository_ctx, clang_binary): script_path = repository_ctx.path(label('//third_party/llvm_toolchain:find_clang_version.py')) python_bin = repository_ctx.which('python3') result = execute(repository_ctx, [python_bin, script_path, clang_binary]) if result.return_code: fail('Failed to run find_clang_version.py: {}'.format(err_out(result))) llvm_version = result.stdout.strip() actual_version = [int(m) for m in llvm_version.split('.')] minimal_version = [int(m) for m in _LLVM_VERSION_MINIMAL.split('.')] if actual_version < minimal_version: fail('Minimal llvm version supported is {}, got: {}'.format(_LLVM_VERSION_MINIMAL, llvm_version)) return result.stdout.strip() def _local_config_llvm_impl(repository_ctx): llvm_dir = repository_ctx.os.environ.get('LLVM_DIR', None) if not llvm_dir: fail('LLVM_DIR not set.') if llvm_dir.endswith('/'): llvm_dir = llvm_dir[:-1] _check_llvm_binaries(repository_ctx, llvm_dir) clang_binary = '{}/bin/clang'.format(llvm_dir) llvm_version = _retrieve_clang_version(repository_ctx, clang_binary) repository_ctx.symlink(_label('cc_toolchain_config.bzl'), 'cc_toolchain_config.bzl') arch = repository_ctx.execute(['uname', '-m']).stdout.strip() repository_ctx.template('toolchains.bzl', _label('toolchains.bzl.tpl'), {'%{arch}': arch}) repository_ctx.template('BUILD', _label('BUILD.tpl'), {'%{arch}': arch, '%{llvm_dir}': llvm_dir, '%{llvm_version}': llvm_version}) local_config_llvm = repository_rule(implementation=_local_config_llvm_impl, environ=['LLVM_DIR'], local=True, configure=True)
valid=False def marray(arr,*args,**kwargs): return arr def unitsDict(*args,**kwargs): return None def varMeta(*args,**kwargs): return None
valid = False def marray(arr, *args, **kwargs): return arr def units_dict(*args, **kwargs): return None def var_meta(*args, **kwargs): return None
{ 'OS-EXT-STS:task_state': None, 'addresses': {'int-net': [ {'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:5d:9e:22', 'version': 4, 'addr': '192.168.1.8', 'OS-EXT-IPS:type': 'fixed' }, {'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:5d:9e:22', 'version': 4, 'addr': '192.168.166.23', 'OS-EXT-IPS:type': 'floating' } ] }, 'OS-EXT-STS:vm_state': 'active', 'OS-EXT-SRV-ATTR:instance_name': 'instance-00000002', 'OS-SRV-USG:launched_at': '2018-10-26T09:36:46.000000', 'id': '61205745-b2bf-4db0-ad50-e7a60bf08bd5', 'security_groups': [{'name': 'defalt'}], 'user_id': 'd2fcc0c45a134de28dba429dbef2c3ba', 'progress': 0, 'OS-EXT-STS:power_state': 1, 'OS-EXT-AZ:availability_zone': 'nova', 'status': 'ACTIVE', 'updated': '2018-10-26T09:36:46Z', 'hostId': '1b6fa73a7ea8e40dc812954fe751d3aa812e6b52489ddb5360f5d36e', 'OS-EXT-SRV-ATTR:host': 'control-node', 'OS-SRV-USG:terminated_at': None, 'OS-EXT-SRV-ATTR:hypervisor_hostname': 'control-node', 'name': 'test', 'created': '2018-10-26T09:36:38Z', 'tenant_id': 'a95424bbdca6410092073d564f1f4012', } # ip netns add ns1 # ovs-vsctl add-port br-int tap0 tag=1 -- set Interface tap0 type=internal # ip a # ovs-vsctl show # ip link set tap0 netns ns1 # ip netns exec ns1 ip addr add 192.168.1.3/24 dev tap0 # ip netns exec ns1 ifconfig tap0 promisc up # ip netns exec ns1 ip a # ip netns exec ns1 ping 192.168.1.1 # ip netns add ns1 # ip netns show # ip netns exec ns1 ip a # ip netns exec ns1 ip tuntap add tap0 mode tap # ip netns exec ns1 ip a # ip netns exec ns1 ip aadr add 192.168.1.3/24 dev tap0 # ip netns exec ns1 ip addr add 192.168.1.3/24 dev tap0 # ip netns exec ns1 ip a # ip netns exec ns1 ip set tap0 up # ip netns exec ns1 ip link set tap0 up # ovs-ofctl dump-ports br-int qvo3ef787ad-67 # ovs-vsctl list interface br-ex
{'OS-EXT-STS:task_state': None, 'addresses': {'int-net': [{'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:5d:9e:22', 'version': 4, 'addr': '192.168.1.8', 'OS-EXT-IPS:type': 'fixed'}, {'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:5d:9e:22', 'version': 4, 'addr': '192.168.166.23', 'OS-EXT-IPS:type': 'floating'}]}, 'OS-EXT-STS:vm_state': 'active', 'OS-EXT-SRV-ATTR:instance_name': 'instance-00000002', 'OS-SRV-USG:launched_at': '2018-10-26T09:36:46.000000', 'id': '61205745-b2bf-4db0-ad50-e7a60bf08bd5', 'security_groups': [{'name': 'defalt'}], 'user_id': 'd2fcc0c45a134de28dba429dbef2c3ba', 'progress': 0, 'OS-EXT-STS:power_state': 1, 'OS-EXT-AZ:availability_zone': 'nova', 'status': 'ACTIVE', 'updated': '2018-10-26T09:36:46Z', 'hostId': '1b6fa73a7ea8e40dc812954fe751d3aa812e6b52489ddb5360f5d36e', 'OS-EXT-SRV-ATTR:host': 'control-node', 'OS-SRV-USG:terminated_at': None, 'OS-EXT-SRV-ATTR:hypervisor_hostname': 'control-node', 'name': 'test', 'created': '2018-10-26T09:36:38Z', 'tenant_id': 'a95424bbdca6410092073d564f1f4012'}
with open('input.txt') as f: lines = f.readlines() count = 0 curDepth = 0 for line in lines: newDepth = int(line) if curDepth != 0: if newDepth > curDepth: count += 1 curDepth = newDepth print(count)
with open('input.txt') as f: lines = f.readlines() count = 0 cur_depth = 0 for line in lines: new_depth = int(line) if curDepth != 0: if newDepth > curDepth: count += 1 cur_depth = newDepth print(count)
def add(x, y=3): print(x + y) add(5) # 8 add(5, 8) # 13 add(y=3) # Error, missing x # -- Order of default parameters -- # def add(x=5, y): # Not OK, default parameters must go after non-default # print(x + y) # -- Usually don't use variables as default value -- default_y = 3 def add(x, y=default_y): sum = x + y print(sum) add(2) # 5 default_y = 4 print(default_y) # 4 add(2) # 5, even though we re-defined default_y
def add(x, y=3): print(x + y) add(5) add(5, 8) add(y=3) default_y = 3 def add(x, y=default_y): sum = x + y print(sum) add(2) default_y = 4 print(default_y) add(2)
''' Filippo Aleotti [email protected] 29 November 2019 I PROFESSIONAL MASTER'S PROGRAM, II LEVEL "SIMUR", Imola 2019 Given a list of integer, store the frequency of each value in a dict, where the key is the value. ''' def are_equals(dict1, dict2): ''' check if two dict are equal. Both the dicts have str keys and integer values ''' for k,v in dict1.items(): if k not in dict2.keys(): return False if dict2[k] != v: return False return True def frequency_extractor(input_list): output_dict = {} for element in input_list: if str(element) not in output_dict.keys(): output_dict[str(element)] = 1 else: output_dict[str(element)] += 1 return output_dict frequency_1 = frequency_extractor([0,1,0,2,2,1,2,1,0,0,2,1,1]) frequency_2 = frequency_extractor([1,2,2,2,0,5,3]) assert are_equals(frequency_1, {'0':4,'1':5,'2':4}) assert are_equals(frequency_2, {'0':1,'1':1,'2':3,'3':1,'5':1})
""" Filippo Aleotti [email protected] 29 November 2019 I PROFESSIONAL MASTER'S PROGRAM, II LEVEL "SIMUR", Imola 2019 Given a list of integer, store the frequency of each value in a dict, where the key is the value. """ def are_equals(dict1, dict2): """ check if two dict are equal. Both the dicts have str keys and integer values """ for (k, v) in dict1.items(): if k not in dict2.keys(): return False if dict2[k] != v: return False return True def frequency_extractor(input_list): output_dict = {} for element in input_list: if str(element) not in output_dict.keys(): output_dict[str(element)] = 1 else: output_dict[str(element)] += 1 return output_dict frequency_1 = frequency_extractor([0, 1, 0, 2, 2, 1, 2, 1, 0, 0, 2, 1, 1]) frequency_2 = frequency_extractor([1, 2, 2, 2, 0, 5, 3]) assert are_equals(frequency_1, {'0': 4, '1': 5, '2': 4}) assert are_equals(frequency_2, {'0': 1, '1': 1, '2': 3, '3': 1, '5': 1})
#!/usr/bin/env python print("Hello from cx_Freeze Advanced #1\n") module = __import__("testfreeze_1")
print('Hello from cx_Freeze Advanced #1\n') module = __import__('testfreeze_1')
# Create a function that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers. def even_or_odd(number): if number % 2 == 0: return "Even" else: return "Odd" assert (even_or_odd(2)) == "Even", "Debe devolver Even" assert (even_or_odd(0)) == "Even", "Debe devolver Even" assert (even_or_odd(7)) == "Odd", "Debe devolver Odd" assert (even_or_odd(1)) == "Odd", "Debe devolver Odd"
def even_or_odd(number): if number % 2 == 0: return 'Even' else: return 'Odd' assert even_or_odd(2) == 'Even', 'Debe devolver Even' assert even_or_odd(0) == 'Even', 'Debe devolver Even' assert even_or_odd(7) == 'Odd', 'Debe devolver Odd' assert even_or_odd(1) == 'Odd', 'Debe devolver Odd'
class Solution: def isAlienSorted(self, words, order): """ :type words: List[str] :type order: str :rtype: bool """ order = {alpha: index for index, alpha in enumerate(order)} for i in range(len(words) - 1): flag = True for j in range(min(len(words[i]), len(words[i + 1]))): if order[words[i][j]] < order[words[i + 1][j]]: flag = False break elif order[words[i][j]] > order[words[i + 1][j]]: return False if flag and len(words[i]) > len(words[i + 1]): return False return True
class Solution: def is_alien_sorted(self, words, order): """ :type words: List[str] :type order: str :rtype: bool """ order = {alpha: index for (index, alpha) in enumerate(order)} for i in range(len(words) - 1): flag = True for j in range(min(len(words[i]), len(words[i + 1]))): if order[words[i][j]] < order[words[i + 1][j]]: flag = False break elif order[words[i][j]] > order[words[i + 1][j]]: return False if flag and len(words[i]) > len(words[i + 1]): return False return True
class Producto: """Producto de venta""" def __init__(self, nombre, desc, precio): self.nombre = nombre self.descripcion = desc self.precio = precio # Es una salida para la muestra de la info def formateo_textual(self): textoFinal = "" for atr in [self.nombre, self.descripcion, self.precio]: textoFinal += atr + "\n" return textoFinal class ListaProductos: """Productos de una orden""" def __init__(self, productos): # Lista de ids de productos self.nombreArchivo = "save.p" self.lista = productos def carga_data(self): with open(self.nombreArchivo, "rb") as file: carga = pickle.load(file) return carga def guarda_data(self): with open(self.nombreArchivo, "wb") as file: pickle.dump(self.lista, file) listaDeProductos = [ Producto("Cafe", "chico", "30"), Producto("cafeLeche", "taza", "50") ] # Solo pata testing productos = ListaProductos(listaDeProductos)
class Producto: """Producto de venta""" def __init__(self, nombre, desc, precio): self.nombre = nombre self.descripcion = desc self.precio = precio def formateo_textual(self): texto_final = '' for atr in [self.nombre, self.descripcion, self.precio]: texto_final += atr + '\n' return textoFinal class Listaproductos: """Productos de una orden""" def __init__(self, productos): self.nombreArchivo = 'save.p' self.lista = productos def carga_data(self): with open(self.nombreArchivo, 'rb') as file: carga = pickle.load(file) return carga def guarda_data(self): with open(self.nombreArchivo, 'wb') as file: pickle.dump(self.lista, file) lista_de_productos = [producto('Cafe', 'chico', '30'), producto('cafeLeche', 'taza', '50')] productos = lista_productos(listaDeProductos)
n = int(input()) L = list(map(int,input().split())) A = list(set(L[:])) d = {} A.sort() for i in range(len(A)): d[A[i]] = i for i in L: print(d[i],end = " ")
n = int(input()) l = list(map(int, input().split())) a = list(set(L[:])) d = {} A.sort() for i in range(len(A)): d[A[i]] = i for i in L: print(d[i], end=' ')
""" Jour de fete - Django_JDF Convertion de nombres en toutes lettres @date: 2014/09/12 @copyright: 2014 by Luc LEGER <[email protected]> @license: MIT """ class numbers : def __init__(self) : self.schu=["","UN ","DEUX ","TROIS ","QUATRE ","CINQ ","SIX ","SEPT ","HUIT ","NEUF "] self.schud=["DIX ","ONZE ","DOUZE ","TREIZE ","QUATORZE ","QUINZE ","SEIZE ","DIX SEPT ","DIX HUIT ","DIX NEUF "] self.schd=["","DIX ","VINGT ","TRENTE ","QUARANTE ","CINQUANTE ","SOIXANTE ","SOIXANTE ","QUATRE VINGT ","QUATRE VINGT "] def convNumber2letter(self,nombre): s='' reste=nombre i=1000000000 while i>0: y=reste/i if y!=0: centaine=y/100 dizaine=(y - centaine*100)/10 unite=y-centaine*100-dizaine*10 if centaine==1: s+="CENT " elif centaine!=0: s+=self.schu[centaine]+"CENT " if dizaine==0 and unite==0: s=s[:-1]+"S " if dizaine not in [0,1]: s+=self.schd[dizaine] if unite==0: if dizaine in [1,7,9]: s+="DIX " elif dizaine==8: s=s[:-1]+"S " elif unite==1: if dizaine in [1,9]: s+="ONZE " elif dizaine==7: s+="ET ONZE " elif dizaine in [2,3,4,5,6]: s+="ET UN " elif dizaine in [0,8]: s+="UN " elif unite in [2,3,4,5,6,7,8,9]: if dizaine in [1,7,9]: s+=self.schud[unite] else: s+=self.schu[unite] if i==1000000000: if y>1: s+="MILLIARDS " else: s+="MILLIARD " if i==1000000: if y>1: s+="MILLIONS " else: s+="MILLIONS " if i==1000: s+="MILLE " #end if y!=0 reste -= y*i dix=False i/=1000; #end while if len(s)==0: s+="ZERO " return s
""" Jour de fete - Django_JDF Convertion de nombres en toutes lettres @date: 2014/09/12 @copyright: 2014 by Luc LEGER <[email protected]> @license: MIT """ class Numbers: def __init__(self): self.schu = ['', 'UN ', 'DEUX ', 'TROIS ', 'QUATRE ', 'CINQ ', 'SIX ', 'SEPT ', 'HUIT ', 'NEUF '] self.schud = ['DIX ', 'ONZE ', 'DOUZE ', 'TREIZE ', 'QUATORZE ', 'QUINZE ', 'SEIZE ', 'DIX SEPT ', 'DIX HUIT ', 'DIX NEUF '] self.schd = ['', 'DIX ', 'VINGT ', 'TRENTE ', 'QUARANTE ', 'CINQUANTE ', 'SOIXANTE ', 'SOIXANTE ', 'QUATRE VINGT ', 'QUATRE VINGT '] def conv_number2letter(self, nombre): s = '' reste = nombre i = 1000000000 while i > 0: y = reste / i if y != 0: centaine = y / 100 dizaine = (y - centaine * 100) / 10 unite = y - centaine * 100 - dizaine * 10 if centaine == 1: s += 'CENT ' elif centaine != 0: s += self.schu[centaine] + 'CENT ' if dizaine == 0 and unite == 0: s = s[:-1] + 'S ' if dizaine not in [0, 1]: s += self.schd[dizaine] if unite == 0: if dizaine in [1, 7, 9]: s += 'DIX ' elif dizaine == 8: s = s[:-1] + 'S ' elif unite == 1: if dizaine in [1, 9]: s += 'ONZE ' elif dizaine == 7: s += 'ET ONZE ' elif dizaine in [2, 3, 4, 5, 6]: s += 'ET UN ' elif dizaine in [0, 8]: s += 'UN ' elif unite in [2, 3, 4, 5, 6, 7, 8, 9]: if dizaine in [1, 7, 9]: s += self.schud[unite] else: s += self.schu[unite] if i == 1000000000: if y > 1: s += 'MILLIARDS ' else: s += 'MILLIARD ' if i == 1000000: if y > 1: s += 'MILLIONS ' else: s += 'MILLIONS ' if i == 1000: s += 'MILLE ' reste -= y * i dix = False i /= 1000 if len(s) == 0: s += 'ZERO ' return s
# Url https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/ class Solution: def subtractProductAndSum(self, n): prod, sum_n, curr = 1, 0, 0 while n != 0: curr = n % 10 prod = prod * curr sum_n = sum_n + curr n = n//10 return prod - sum_n if __name__ == '__main__': a = Solution() print(a.subtractProductAndSum(234))
class Solution: def subtract_product_and_sum(self, n): (prod, sum_n, curr) = (1, 0, 0) while n != 0: curr = n % 10 prod = prod * curr sum_n = sum_n + curr n = n // 10 return prod - sum_n if __name__ == '__main__': a = solution() print(a.subtractProductAndSum(234))
# Work out the first ten digits of the sum of N 50 digit numbers. total = 0 for x in range(int(input())): total += int(input().rstrip()) print(str(total)[:10])
total = 0 for x in range(int(input())): total += int(input().rstrip()) print(str(total)[:10])
__author__ = "Sylvain Dangin" __licence__ = "Apache 2.0" __version__ = "1.0" __maintainer__ = "Sylvain Dangin" __email__ = "[email protected]" __status__ = "Development" class concat(): def action(input_data, params, current_row, current_index): """Concat multiple columns in the cell. :param input_data: Not used. :param params: Dict with following keys: - col_list: List of columns to concat in the cell. - separator (optional): Separator to put between columns. :param current_row: Not used :param current_index: Not used :return: Value to set. :rtype: str """ if isinstance(params, dict): col_list = [] if 'col_list' in params: for col in params['col_list']: col_list.append(current_row[col - 1]) if 'separator' in params: return params['separator'].join(col_list) else: return ''.join(col_list) return input_data
__author__ = 'Sylvain Dangin' __licence__ = 'Apache 2.0' __version__ = '1.0' __maintainer__ = 'Sylvain Dangin' __email__ = '[email protected]' __status__ = 'Development' class Concat: def action(input_data, params, current_row, current_index): """Concat multiple columns in the cell. :param input_data: Not used. :param params: Dict with following keys: - col_list: List of columns to concat in the cell. - separator (optional): Separator to put between columns. :param current_row: Not used :param current_index: Not used :return: Value to set. :rtype: str """ if isinstance(params, dict): col_list = [] if 'col_list' in params: for col in params['col_list']: col_list.append(current_row[col - 1]) if 'separator' in params: return params['separator'].join(col_list) else: return ''.join(col_list) return input_data
""" This module is for generating a Markov chain order two from a text. """ def generate_markov_chain(tweet_array): """ Input assumes text is an array of tweets, each tweet with words separated by spaces with no new lines. This requires some changes to most transcripts ahead of time. Output will be a dictionary with each pair of words that exists in the text as a key and a list of words that follow that pair as the value. """ tweets_copy = tweet_array[:] markov_chain = {} for tweet in tweets_copy: word_array = tweet.split() for i in range(len(word_array) - 2): # - 2 to not analyze the last word as first in pair first_word = strip_word(word_array[i]) second_word = strip_word(word_array[i + 1]) third_word = strip_word(word_array[i + 2]) pair = first_word + ' ' + second_word if pair not in markov_chain: markov_chain[pair] = [third_word] else: markov_chain[pair].append(third_word) return markov_chain def strip_word(string): """ This function strips the words of any surrounding spaces or quotation marks from an input string, but does not replace any single quotes inside words (e.g. "isn't") """ return string.strip().strip("'").strip('"')
""" This module is for generating a Markov chain order two from a text. """ def generate_markov_chain(tweet_array): """ Input assumes text is an array of tweets, each tweet with words separated by spaces with no new lines. This requires some changes to most transcripts ahead of time. Output will be a dictionary with each pair of words that exists in the text as a key and a list of words that follow that pair as the value. """ tweets_copy = tweet_array[:] markov_chain = {} for tweet in tweets_copy: word_array = tweet.split() for i in range(len(word_array) - 2): first_word = strip_word(word_array[i]) second_word = strip_word(word_array[i + 1]) third_word = strip_word(word_array[i + 2]) pair = first_word + ' ' + second_word if pair not in markov_chain: markov_chain[pair] = [third_word] else: markov_chain[pair].append(third_word) return markov_chain def strip_word(string): """ This function strips the words of any surrounding spaces or quotation marks from an input string, but does not replace any single quotes inside words (e.g. "isn't") """ return string.strip().strip("'").strip('"')
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: class TaskName(): Classify_Task = "classify" Detect2d_Task = "detect2d" Segment_Task = "segment" PC_Classify_Task = "pc_classify"
class Taskname: classify__task = 'classify' detect2d__task = 'detect2d' segment__task = 'segment' pc__classify__task = 'pc_classify'
class TheEquation: def leastSum(self, X, Y, P): m = 2*P for i in xrange(1, P+1): for j in xrange(1, P+1): if (X*i + Y*j)%P == 0: m = min(m, i+j) return m
class Theequation: def least_sum(self, X, Y, P): m = 2 * P for i in xrange(1, P + 1): for j in xrange(1, P + 1): if (X * i + Y * j) % P == 0: m = min(m, i + j) return m
#!/usr/bin/env python3 """ Top students """ def top_students(mongo_collection: object): """function that returns all students sorted by average score""" top = mongo_collection.aggregate([ { "$project": { "name": "$name", "averageScore": {"$avg": "$topics.score"} } }, {"$sort": {"averageScore": -1}} ]) return top
""" Top students """ def top_students(mongo_collection: object): """function that returns all students sorted by average score""" top = mongo_collection.aggregate([{'$project': {'name': '$name', 'averageScore': {'$avg': '$topics.score'}}}, {'$sort': {'averageScore': -1}}]) return top
#!/usr/bin/env python3 class FakeSerial: def __init__(self): self._last_written_data = None self._response = None self.read_data = [] @property def last_written_data(self): return self._last_written_data @property def response(self): return self._response @response.setter def response(self, value): self._response = bytearray(value) def write(self, data): self._last_written_data = data def read(self): while self._response: yield bytes([self._response.pop(0)]) def read_until(self, expected): output = b'' for b in self.read(): if b == expected: break output += b return output
class Fakeserial: def __init__(self): self._last_written_data = None self._response = None self.read_data = [] @property def last_written_data(self): return self._last_written_data @property def response(self): return self._response @response.setter def response(self, value): self._response = bytearray(value) def write(self, data): self._last_written_data = data def read(self): while self._response: yield bytes([self._response.pop(0)]) def read_until(self, expected): output = b'' for b in self.read(): if b == expected: break output += b return output
# coding=utf-8 # Definition for singly-linked list. class ListNode(object): def __init__(self, x, next=None): self.val = x self.next = next class DoubleNode(object): def __init__(self, key, val, pre=None, next=None): self.key = key self.val = val self.pre = pre self.next = next # Definition for a binary tree node. class TreeNode(object): def __init__(self, x, left=None, right=None): self.val = x self.left = left self.right = right class TrieNode(object): def __init__(self, end=False): self.children = [] for i in range(26): self.children.append(None) self.end = end def set_end(self): self.end = True @property def is_end(self): return self.end class RandomNode(object): def __init__(self, val, next, random): self.val = val self.next = next self.random = random class GraphNode(object): def __init__(self, val, neighbors): self.val = val self.neighbors = neighbors class QuadTreeNode(object): def __init__(self, val, is_leaf, top_left, top_right, bottom_left, bottom_right): self.val = val self.is_leaf = is_leaf self.top_left = top_left self.top_right = top_right self.bottom_left = bottom_left self.bottom_right = bottom_right
class Listnode(object): def __init__(self, x, next=None): self.val = x self.next = next class Doublenode(object): def __init__(self, key, val, pre=None, next=None): self.key = key self.val = val self.pre = pre self.next = next class Treenode(object): def __init__(self, x, left=None, right=None): self.val = x self.left = left self.right = right class Trienode(object): def __init__(self, end=False): self.children = [] for i in range(26): self.children.append(None) self.end = end def set_end(self): self.end = True @property def is_end(self): return self.end class Randomnode(object): def __init__(self, val, next, random): self.val = val self.next = next self.random = random class Graphnode(object): def __init__(self, val, neighbors): self.val = val self.neighbors = neighbors class Quadtreenode(object): def __init__(self, val, is_leaf, top_left, top_right, bottom_left, bottom_right): self.val = val self.is_leaf = is_leaf self.top_left = top_left self.top_right = top_right self.bottom_left = bottom_left self.bottom_right = bottom_right
seen = [] # Prduces the length of the longest Substring # thats comprised of just unique characters def max_diff(string): seen = [0]*256 curr_start = 0 max_start = 0 unique = 0 max_unique = 0 for n,i in enumerate(string): if seen[assn_num(i)] == 0: unique += 1 else: if unique > max_unique: max_unique = unique while unique > 1: if seen[assn_num(string[curr_start])] == 1: unique -= 1 seen[assn_num(string[curr_start])] -= 1 curr_start += 1 else: seen[assn_num(string[curr_start])] -= 1 curr_start += 1 seen[assn_num(i)] += 1 if unique > max_unique: max_unique = unique return max_unique def assn_num(char): num = ord(char)-ord('a') return num
seen = [] def max_diff(string): seen = [0] * 256 curr_start = 0 max_start = 0 unique = 0 max_unique = 0 for (n, i) in enumerate(string): if seen[assn_num(i)] == 0: unique += 1 else: if unique > max_unique: max_unique = unique while unique > 1: if seen[assn_num(string[curr_start])] == 1: unique -= 1 seen[assn_num(string[curr_start])] -= 1 curr_start += 1 else: seen[assn_num(string[curr_start])] -= 1 curr_start += 1 seen[assn_num(i)] += 1 if unique > max_unique: max_unique = unique return max_unique def assn_num(char): num = ord(char) - ord('a') return num
# package org.apache.helix.messaging.handling #from org.apache.helix.messaging.handling import * #from java.util import HashMap #from java.util import Map class HelixTaskResult: def __init__(self): self._success = False self._message = "" self._taskResultMap = {} self._interrupted = False self._exception = None def isSucess(self): """ Returns boolean """ return self._success def isInterrupted(self): """ Returns boolean """ return self._interrupted def setInterrupted(self, interrupted): """ Returns void Parameters: interrupted: boolean """ self._interrupted = interrupted def setSuccess(self, success): """ Returns void Parameters: success: boolean """ self._success = success def getMessage(self): """ Returns String """ return self._message def setMessage(self, message): """ Returns void Parameters: message: String """ self._message = message def getTaskResultMap(self): """ Returns Map<String, String> """ return self._taskResultMap def setException(self, e): """ Returns void Parameters: e: Exception """ self._exception = e def getException(self): """ Returns Exception """ return self._exception
class Helixtaskresult: def __init__(self): self._success = False self._message = '' self._taskResultMap = {} self._interrupted = False self._exception = None def is_sucess(self): """ Returns boolean """ return self._success def is_interrupted(self): """ Returns boolean """ return self._interrupted def set_interrupted(self, interrupted): """ Returns void Parameters: interrupted: boolean """ self._interrupted = interrupted def set_success(self, success): """ Returns void Parameters: success: boolean """ self._success = success def get_message(self): """ Returns String """ return self._message def set_message(self, message): """ Returns void Parameters: message: String """ self._message = message def get_task_result_map(self): """ Returns Map<String, String> """ return self._taskResultMap def set_exception(self, e): """ Returns void Parameters: e: Exception """ self._exception = e def get_exception(self): """ Returns Exception """ return self._exception
def _test_sources_aspect_impl(target, ctx): result = depset() if hasattr(ctx.rule.attr, "tags") and "NODE_MODULE_MARKER" in ctx.rule.attr.tags: return struct(node_test_sources=result) if hasattr(ctx.rule.attr, "deps"): for dep in ctx.rule.attr.deps: if hasattr(dep, "node_test_sources"): result = depset(transitive=[result, dep.node_test_sources]) elif hasattr(target, "files"): result = depset([f for f in target.files.to_list() if f.path.endswith(".test.js")], transitive=[result]) return struct(node_test_sources=result) test_sources_aspect = aspect( _test_sources_aspect_impl, attr_aspects=["deps"], )
def _test_sources_aspect_impl(target, ctx): result = depset() if hasattr(ctx.rule.attr, 'tags') and 'NODE_MODULE_MARKER' in ctx.rule.attr.tags: return struct(node_test_sources=result) if hasattr(ctx.rule.attr, 'deps'): for dep in ctx.rule.attr.deps: if hasattr(dep, 'node_test_sources'): result = depset(transitive=[result, dep.node_test_sources]) elif hasattr(target, 'files'): result = depset([f for f in target.files.to_list() if f.path.endswith('.test.js')], transitive=[result]) return struct(node_test_sources=result) test_sources_aspect = aspect(_test_sources_aspect_impl, attr_aspects=['deps'])
def is_prime(n): if n > 1: for i in range(2, n // 2 + 1): if (n % i) == 0: return False else: return True else: return False def fibonacci(n): n1, n2 = 1, 1 count = 0 if n == 1: print(n1) else: while count < n: if not is_prime(n1) and n1 % 5 != 0: print(n1, end=' ') else: print(0, end=' ') n3 = n1 + n2 n1 = n2 n2 = n3 count += 1 n = int(input("Enter the number:")) fibonacci(n)
def is_prime(n): if n > 1: for i in range(2, n // 2 + 1): if n % i == 0: return False else: return True else: return False def fibonacci(n): (n1, n2) = (1, 1) count = 0 if n == 1: print(n1) else: while count < n: if not is_prime(n1) and n1 % 5 != 0: print(n1, end=' ') else: print(0, end=' ') n3 = n1 + n2 n1 = n2 n2 = n3 count += 1 n = int(input('Enter the number:')) fibonacci(n)
###################################################################################### # Date: 2016/July/11 # # Module: module_2DScatter.py # # VERSION: 0.9 # # AUTHOR: Matt Thoburn ([email protected]); # edited by Miguel A. Ibarra-Arellano([email protected]) # # DESCRIPTION: This module contains a primary method (quickPlot) # and two depreciated methods which are not to be used # # makeScatter is to be called from other scripts which require a graph ####################################################################################### def scatter2D(ax,x,y,colorList,ec='black'): """ This function is to be called by makeScatter2D, creates a 2D scatter plot on a given axis with colors determined by the given colorHandler or an optional override :Arguments: :type ax: matplotlib Axis2D :param ax: Axis on which scatter plot will be drawn :type x: list of floats :param x: list of x values to be plotted :type y: list of floats :param y: list of y values to be plotted :type colorList: list :param colorList: list of colors to be used for plotting :type ec: str :param ec: Edge color for markers :Return: :type ax: Matplotlib Axis :param ax: axis with scatter plotted onto it """ ax.scatter(x,y,color=colorList,marker='o',s=50,edgecolors=ec) return ax def scatter3D(ax,x,y,z,colorList): """ This function is to be called by makeScatter3D, creates a 3D scatter plot on a given axis with colors determined by the given colorHandler. :Arguments: :type ax: matplotlib Axis3D :param ax: Axis on which scatter plot will be drawn :type x: list of floats :param x: list of x values to be plotted :type y: list of floats :param y: list of y values to be plotted :type z: list of floats :param z: list of z values to be plotted :type colorList: list :param colorList: list of colors to be used for plotting :Return: :type ax: Matplotlib Axis :param ax: axis with scatter plotted onto it """ ax.scatter(xs=x,ys=y,zs=z,c=colorList,marker='o',s=50,depthshade=False) return ax
def scatter2_d(ax, x, y, colorList, ec='black'): """ This function is to be called by makeScatter2D, creates a 2D scatter plot on a given axis with colors determined by the given colorHandler or an optional override :Arguments: :type ax: matplotlib Axis2D :param ax: Axis on which scatter plot will be drawn :type x: list of floats :param x: list of x values to be plotted :type y: list of floats :param y: list of y values to be plotted :type colorList: list :param colorList: list of colors to be used for plotting :type ec: str :param ec: Edge color for markers :Return: :type ax: Matplotlib Axis :param ax: axis with scatter plotted onto it """ ax.scatter(x, y, color=colorList, marker='o', s=50, edgecolors=ec) return ax def scatter3_d(ax, x, y, z, colorList): """ This function is to be called by makeScatter3D, creates a 3D scatter plot on a given axis with colors determined by the given colorHandler. :Arguments: :type ax: matplotlib Axis3D :param ax: Axis on which scatter plot will be drawn :type x: list of floats :param x: list of x values to be plotted :type y: list of floats :param y: list of y values to be plotted :type z: list of floats :param z: list of z values to be plotted :type colorList: list :param colorList: list of colors to be used for plotting :Return: :type ax: Matplotlib Axis :param ax: axis with scatter plotted onto it """ ax.scatter(xs=x, ys=y, zs=z, c=colorList, marker='o', s=50, depthshade=False) return ax
class Solution: def maxProfit(self, prices: List[int]) -> int: running_min = prices[0] best_trans1 = [0] for p in prices[1:]: if p < running_min: running_min = p best_trans1.append(max(p - running_min, best_trans1[-1])) running_max = prices[-1] best = best_trans1.pop() best_trans2 = 0 for p in prices[:0:-1]: if p > running_max: running_max = p if running_max - p > best_trans2: best_trans2 = running_max - p trans1 = best_trans1.pop() if best_trans2 + trans1 > best: best = best_trans2 + trans1 return best
class Solution: def max_profit(self, prices: List[int]) -> int: running_min = prices[0] best_trans1 = [0] for p in prices[1:]: if p < running_min: running_min = p best_trans1.append(max(p - running_min, best_trans1[-1])) running_max = prices[-1] best = best_trans1.pop() best_trans2 = 0 for p in prices[:0:-1]: if p > running_max: running_max = p if running_max - p > best_trans2: best_trans2 = running_max - p trans1 = best_trans1.pop() if best_trans2 + trans1 > best: best = best_trans2 + trans1 return best
# -*- coding: utf-8 -*- """ Created on Wed Jan 30 16:46:12 2019 @author: Alexandre Janin """ """Exceptions raised by pypStag""" class PypStagError(Exception): """ Main class for all pypStag """ pass class PackageWarning(PypStagError): """Raised when a precise package is needed""" def __init__(self,pack): super().__init__('Error package import!\n'+\ '>> the following package is needed:'+pack) class NoFileError(PypStagError): """Raised when stagData.import find no file during the importation""" def __init__(self,directory,fname): super().__init__('Error on the input data !\n'+\ '>> The expected following file does not exist !\n'+\ ' | File requested: '+fname+'\n'+\ ' | On directory : '+directory) class StagTypeError(PypStagError): """Raised unexpected type""" def __init__(self,givenType,expectedType): super().__init__('Error on input type\n'+\ 'Unexpected type given: '+str(givenType)+'\n'+\ 'Expected type for input is: '+str(expectedType)) class InputGridGeometryError(PypStagError): """Raised when stagData.import have a wrong input geometry""" def __init__(self,geom): super().__init__('Error on the input geometry!\n'+\ "The proposed geometry '"+geom+"' is not contained in\n"+\ 'the allowed geometries supported by stagData object.') class CloudBuildIndexError(PypStagError): """Raised when stagCloudData have a wrong index input""" def __init__(self,geom): super().__init__('Error on the input index!\n'+\ "You have to set an 'indices' list or set a begining and end index and a file step.") class GridGeometryInDevError(PypStagError): """Raised when stagData.import have an unconform input geometry""" def __init__(self,geom): super().__init__('Error on the input geometry !\n'+\ "The input geometry '"+geom+"' is not suported now\n"+\ 'in the current version of pypStag... Be patient and take a coffee!') class FieldTypeInDevError(PypStagError): """Raised when stagData.import have an unknown fieldType not yet supported""" def __init__(self,fieldType): super().__init__('Error on the input stagData.fieldType !\n'+\ "The input fieldType '"+fieldType+"' is not supported now\n"+\ 'in the current versin of pypStag... Be patient and take a coffee !') class GridGeometryError(PypStagError): """Raised when the geometry of a stagData object is not the expected geometry""" def __init__(self,INgeom,EXgeom): super().__init__('Error on the input geometry !\n'+\ "The input geometry '"+INgeom+"' you chose during the construction\n"+\ 'of the StagData object is not the one expected here!\n'+\ 'Expected geometry corresponding to your input file: '+EXgeom) class VisuGridGeometryError(PypStagError): """Raised when the geometry of a stagData object is not the expected geometry for a visualization tool""" def __init__(self,INgeom,EXgeom): super().__init__('Error on the input geometry !\n'+\ "The input geometry '"+INgeom+"' of your StagData object is incoherent\n"+\ 'with the function you are using or its input parameters!\n'+\ 'Expected geometry: '+EXgeom) class GridInterpolationError(PypStagError): """Raised when unknown input for interpolation grid""" def __init__(self,interpGeom): super().__init__('Error on the proposed interpolation grid!\n'+\ "The selected grid geometry '"+interpGeom+"' is not supported\n"+\ 'for the moment or is wrong!') class fieldTypeError(PypStagError): """Raised unexpected field type""" def __init__(self,expectedFieldtype): super().__init__('Error on the StagData Field Type\n'+\ 'Unexpected value of StagData.fiedType\n'+\ 'StagData.fieldType must be here: '+expectedFieldtype) class SliceAxisError(PypStagError): """Raised when unknown axis is set in input""" def __init__(self,wrongaxis): super().__init__('Error in input axis!\n'+\ 'Unexpected value of axis: '+str(wrongaxis)) class IncoherentSliceAxisError(PypStagError): """Raised when incoherent axis is set in input, incoherent according to the grid geometry.""" def __init__(self,wrongaxis): super().__init__('Error in input axis!\n'+\ 'Incoherent value of axis: '+str(wrongaxis)+', with the grid geomtry:') class MetaFileInappropriateError(PypStagError): """Raised when the reader function of StagMetaData recieved an inappropriate file.""" def __init__(self,ftype,allowedType): super().__init__('Error on the input of the meta file reader!\n'+\ 'Inappropriate meta file in input.\n'+\ 'Type you entered: '+ftype+'\n'+\ 'Type must be in: \n'+\ str(allowedType)) class MetaCheckFieldUnknownError(PypStagError): """Raised when the reader function of StagMetaData recieved an inappropriate file.""" def __init__(self,field,allowedFields): super().__init__('Error on the input field of the StagMetaData.check() function\n'+\ 'Unknown field: '+field+'\n'+\ 'The input field must be in: \n'+\ str(allowedFields))
""" Created on Wed Jan 30 16:46:12 2019 @author: Alexandre Janin """ 'Exceptions raised by pypStag' class Pypstagerror(Exception): """ Main class for all pypStag """ pass class Packagewarning(PypStagError): """Raised when a precise package is needed""" def __init__(self, pack): super().__init__('Error package import!\n' + '>> the following package is needed:' + pack) class Nofileerror(PypStagError): """Raised when stagData.import find no file during the importation""" def __init__(self, directory, fname): super().__init__('Error on the input data !\n' + '>> The expected following file does not exist !\n' + ' | File requested: ' + fname + '\n' + ' | On directory : ' + directory) class Stagtypeerror(PypStagError): """Raised unexpected type""" def __init__(self, givenType, expectedType): super().__init__('Error on input type\n' + 'Unexpected type given: ' + str(givenType) + '\n' + 'Expected type for input is: ' + str(expectedType)) class Inputgridgeometryerror(PypStagError): """Raised when stagData.import have a wrong input geometry""" def __init__(self, geom): super().__init__('Error on the input geometry!\n' + "The proposed geometry '" + geom + "' is not contained in\n" + 'the allowed geometries supported by stagData object.') class Cloudbuildindexerror(PypStagError): """Raised when stagCloudData have a wrong index input""" def __init__(self, geom): super().__init__('Error on the input index!\n' + "You have to set an 'indices' list or set a begining and end index and a file step.") class Gridgeometryindeverror(PypStagError): """Raised when stagData.import have an unconform input geometry""" def __init__(self, geom): super().__init__('Error on the input geometry !\n' + "The input geometry '" + geom + "' is not suported now\n" + 'in the current version of pypStag... Be patient and take a coffee!') class Fieldtypeindeverror(PypStagError): """Raised when stagData.import have an unknown fieldType not yet supported""" def __init__(self, fieldType): super().__init__('Error on the input stagData.fieldType !\n' + "The input fieldType '" + fieldType + "' is not supported now\n" + 'in the current versin of pypStag... Be patient and take a coffee !') class Gridgeometryerror(PypStagError): """Raised when the geometry of a stagData object is not the expected geometry""" def __init__(self, INgeom, EXgeom): super().__init__('Error on the input geometry !\n' + "The input geometry '" + INgeom + "' you chose during the construction\n" + 'of the StagData object is not the one expected here!\n' + 'Expected geometry corresponding to your input file: ' + EXgeom) class Visugridgeometryerror(PypStagError): """Raised when the geometry of a stagData object is not the expected geometry for a visualization tool""" def __init__(self, INgeom, EXgeom): super().__init__('Error on the input geometry !\n' + "The input geometry '" + INgeom + "' of your StagData object is incoherent\n" + 'with the function you are using or its input parameters!\n' + 'Expected geometry: ' + EXgeom) class Gridinterpolationerror(PypStagError): """Raised when unknown input for interpolation grid""" def __init__(self, interpGeom): super().__init__('Error on the proposed interpolation grid!\n' + "The selected grid geometry '" + interpGeom + "' is not supported\n" + 'for the moment or is wrong!') class Fieldtypeerror(PypStagError): """Raised unexpected field type""" def __init__(self, expectedFieldtype): super().__init__('Error on the StagData Field Type\n' + 'Unexpected value of StagData.fiedType\n' + 'StagData.fieldType must be here: ' + expectedFieldtype) class Sliceaxiserror(PypStagError): """Raised when unknown axis is set in input""" def __init__(self, wrongaxis): super().__init__('Error in input axis!\n' + 'Unexpected value of axis: ' + str(wrongaxis)) class Incoherentsliceaxiserror(PypStagError): """Raised when incoherent axis is set in input, incoherent according to the grid geometry.""" def __init__(self, wrongaxis): super().__init__('Error in input axis!\n' + 'Incoherent value of axis: ' + str(wrongaxis) + ', with the grid geomtry:') class Metafileinappropriateerror(PypStagError): """Raised when the reader function of StagMetaData recieved an inappropriate file.""" def __init__(self, ftype, allowedType): super().__init__('Error on the input of the meta file reader!\n' + 'Inappropriate meta file in input.\n' + 'Type you entered: ' + ftype + '\n' + 'Type must be in: \n' + str(allowedType)) class Metacheckfieldunknownerror(PypStagError): """Raised when the reader function of StagMetaData recieved an inappropriate file.""" def __init__(self, field, allowedFields): super().__init__('Error on the input field of the StagMetaData.check() function\n' + 'Unknown field: ' + field + '\n' + 'The input field must be in: \n' + str(allowedFields))
version = "dev 0.0" running = False def init(): global running if not running: print("JFUtils-python \"" + version + "\" by jonnelafin") running = True
version = 'dev 0.0' running = False def init(): global running if not running: print('JFUtils-python "' + version + '" by jonnelafin') running = True
"""Utility functions not closely tied to other spec_tools types.""" # Copyright (c) 2018-2019 Collabora, Ltd. # Copyright (c) 2013-2019 The Khronos Group Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def getElemName(elem, default=None): """Get the name associated with an element, either a name child or name attribute.""" name_elem = elem.find('name') if name_elem is not None: return name_elem.text # Fallback if there is no child. return elem.get('name', default) def getElemType(elem, default=None): """Get the type associated with an element, either a type child or type attribute.""" type_elem = elem.find('type') if type_elem is not None: return type_elem.text # Fallback if there is no child. return elem.get('type', default) def _conditional_string_strip_append(my_list, optional_str): if not optional_str: return stripped = optional_str.strip() if not stripped: return my_list.append(stripped) def getParamOrMemberFullType(elem, default=None): """Get the full type associated with a member or param element. This includes the text preceding, within, and following the 'type' tag.""" parts = [] for node in elem.iter(): _conditional_string_strip_append(parts, node.text) _conditional_string_strip_append(parts, node.tail) if node.tag == 'type': return ' '.join(parts) # Fallback if there is no child with a "type" tag return default def findFirstWithPredicate(collection, pred): """Return the first element that satisfies the predicate, or None if none exist. NOTE: Some places where this is used might be better served by changing to a dictionary. """ for elt in collection: if pred(elt): return elt return None def findNamedElem(elems, name): """Traverse a collection of elements with 'name' nodes or attributes, looking for and returning one with the right name. NOTE: Many places where this is used might be better served by changing to a dictionary. """ return findFirstWithPredicate(elems, lambda elem: getElemName(elem) == name) def findTypedElem(elems, typename): """Traverse a collection of elements with 'type' nodes or attributes, looking for and returning one with the right typename. NOTE: Many places where this is used might be better served by changing to a dictionary. """ return findFirstWithPredicate(elems, lambda elem: getElemType(elem) == typename) def findNamedObject(collection, name): """Traverse a collection of elements with 'name' attributes, looking for and returning one with the right name. NOTE: Many places where this is used might be better served by changing to a dictionary. """ return findFirstWithPredicate(collection, lambda elt: elt.name == name)
"""Utility functions not closely tied to other spec_tools types.""" def get_elem_name(elem, default=None): """Get the name associated with an element, either a name child or name attribute.""" name_elem = elem.find('name') if name_elem is not None: return name_elem.text return elem.get('name', default) def get_elem_type(elem, default=None): """Get the type associated with an element, either a type child or type attribute.""" type_elem = elem.find('type') if type_elem is not None: return type_elem.text return elem.get('type', default) def _conditional_string_strip_append(my_list, optional_str): if not optional_str: return stripped = optional_str.strip() if not stripped: return my_list.append(stripped) def get_param_or_member_full_type(elem, default=None): """Get the full type associated with a member or param element. This includes the text preceding, within, and following the 'type' tag.""" parts = [] for node in elem.iter(): _conditional_string_strip_append(parts, node.text) _conditional_string_strip_append(parts, node.tail) if node.tag == 'type': return ' '.join(parts) return default def find_first_with_predicate(collection, pred): """Return the first element that satisfies the predicate, or None if none exist. NOTE: Some places where this is used might be better served by changing to a dictionary. """ for elt in collection: if pred(elt): return elt return None def find_named_elem(elems, name): """Traverse a collection of elements with 'name' nodes or attributes, looking for and returning one with the right name. NOTE: Many places where this is used might be better served by changing to a dictionary. """ return find_first_with_predicate(elems, lambda elem: get_elem_name(elem) == name) def find_typed_elem(elems, typename): """Traverse a collection of elements with 'type' nodes or attributes, looking for and returning one with the right typename. NOTE: Many places where this is used might be better served by changing to a dictionary. """ return find_first_with_predicate(elems, lambda elem: get_elem_type(elem) == typename) def find_named_object(collection, name): """Traverse a collection of elements with 'name' attributes, looking for and returning one with the right name. NOTE: Many places where this is used might be better served by changing to a dictionary. """ return find_first_with_predicate(collection, lambda elt: elt.name == name)
class FiniteAutomataState: def __init__(self, structure): self.states = [] self.alphabet = [] self.initial = [] self.finals = [] self.transitions = {} self._file = open(structure, "r") self._load() # print(self.validate()) def _load(self): reading = "none" reading = "none" line = self._file.readline() def classify(mode, probe): if mode == "states": spec = probe.split(', ') self.states.extend(spec) elif mode == "initial": spec = probe.split(', ') self.initial.extend(spec) elif mode == "alpha": spec = probe.split(', ') self.alphabet.extend(spec) elif mode == "trans": values = probe.split(", ") if (values[0], values[1]) in self.transitions.keys(): self.transitions[(values[0], values[1])].append(values[2]) else: self.transitions[(values[0], values[1])] = [values[2]] elif mode == "final": tokens = probe.split(", ") self.finals.extend(tokens) while line: if line.strip()[0] == '#': reading = line.strip()[1:] else: classify(reading, line.strip()) line = self._file.readline() def validate(self): if self.initial[0] not in self.states: return False for final in self.finals: if final not in self.states: return False for key in self.transitions.keys(): state = key[0] symbol = key[1] if state not in self.states or symbol not in self.alphabet: return False for dest in self.transitions[key]: if dest not in self.states: return False return True def dfa(self): for key in self.transitions.keys(): if len(self.transitions[key]) > 1: return False return True def accepted(self, sequence): if self.dfa(): crt = self.initial[0] for symbol in sequence: if (crt, symbol) in self.transitions.keys(): crt = self.transitions[(crt, symbol)][0] else: return False return crt in self.finals return False
class Finiteautomatastate: def __init__(self, structure): self.states = [] self.alphabet = [] self.initial = [] self.finals = [] self.transitions = {} self._file = open(structure, 'r') self._load() def _load(self): reading = 'none' reading = 'none' line = self._file.readline() def classify(mode, probe): if mode == 'states': spec = probe.split(', ') self.states.extend(spec) elif mode == 'initial': spec = probe.split(', ') self.initial.extend(spec) elif mode == 'alpha': spec = probe.split(', ') self.alphabet.extend(spec) elif mode == 'trans': values = probe.split(', ') if (values[0], values[1]) in self.transitions.keys(): self.transitions[values[0], values[1]].append(values[2]) else: self.transitions[values[0], values[1]] = [values[2]] elif mode == 'final': tokens = probe.split(', ') self.finals.extend(tokens) while line: if line.strip()[0] == '#': reading = line.strip()[1:] else: classify(reading, line.strip()) line = self._file.readline() def validate(self): if self.initial[0] not in self.states: return False for final in self.finals: if final not in self.states: return False for key in self.transitions.keys(): state = key[0] symbol = key[1] if state not in self.states or symbol not in self.alphabet: return False for dest in self.transitions[key]: if dest not in self.states: return False return True def dfa(self): for key in self.transitions.keys(): if len(self.transitions[key]) > 1: return False return True def accepted(self, sequence): if self.dfa(): crt = self.initial[0] for symbol in sequence: if (crt, symbol) in self.transitions.keys(): crt = self.transitions[crt, symbol][0] else: return False return crt in self.finals return False
#!/usr/bin/python compteur = 0 i,j = 3,1 terrain = [] fichier = open('day3_input.txt') for l in fichier: terrain.append(fichier.readline().strip('\n')) nblig = len(terrain) nbcol = len(terrain[0]) print('nblig : %s / nbcol : %s' % (nblig,nbcol)) for f in terrain: print(f) while j<nblig: #print(i,j,terrain[j][i],compteur) if terrain[j][i] == '#': compteur = compteur +1 print(terrain[j][0:i-1]+'X'+terrain[j][i+1:nbcol-1]) else: print(terrain[j][0:i-1]+'O'+terrain[j][i+1:nbcol-1]) i = (i+3)%nbcol j = j+1 print(compteur)
compteur = 0 (i, j) = (3, 1) terrain = [] fichier = open('day3_input.txt') for l in fichier: terrain.append(fichier.readline().strip('\n')) nblig = len(terrain) nbcol = len(terrain[0]) print('nblig : %s / nbcol : %s' % (nblig, nbcol)) for f in terrain: print(f) while j < nblig: if terrain[j][i] == '#': compteur = compteur + 1 print(terrain[j][0:i - 1] + 'X' + terrain[j][i + 1:nbcol - 1]) else: print(terrain[j][0:i - 1] + 'O' + terrain[j][i + 1:nbcol - 1]) i = (i + 3) % nbcol j = j + 1 print(compteur)
dicionario_sites = {"Diego": "diegomariano.com"} print(dicionario_sites['Diego']) dicionario_sites = {"Diego": "diegomariano.com", "Google": "google.com", "Udemy": "udemy.com", "Luiz Carlin" : "luizcarlin.com.br"} print ("-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=") for chave in dicionario_sites: print (chave + " -:- " +dicionario_sites[chave]) print(dicionario_sites[chave]) print ("-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=") for i in dicionario_sites.items(): print(i) print ("-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=") for i in dicionario_sites.values(): print(i) print ("-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=") for i in dicionario_sites.keys(): print(i)
dicionario_sites = {'Diego': 'diegomariano.com'} print(dicionario_sites['Diego']) dicionario_sites = {'Diego': 'diegomariano.com', 'Google': 'google.com', 'Udemy': 'udemy.com', 'Luiz Carlin': 'luizcarlin.com.br'} print('-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=') for chave in dicionario_sites: print(chave + ' -:- ' + dicionario_sites[chave]) print(dicionario_sites[chave]) print('-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=') for i in dicionario_sites.items(): print(i) print('-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=') for i in dicionario_sites.values(): print(i) print('-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=-=+=') for i in dicionario_sites.keys(): print(i)
# -*- coding: utf-8 -*- # Author: Tonio Teran <[email protected]> # Copyright: Stateoftheart AI PBC 2021. '''RLlib's library wrapper.''' SOURCE_METADATA = { 'name': 'rllib', 'original_name': 'RLlib', 'url': 'https://docs.ray.io/en/master/rllib.html' } MODELS = { 'discrete': [ 'A2C', 'A3C', 'ARS', 'BC', 'ES', 'DQN', 'Rainbow', 'APEX-DQN', 'IMPALA', 'MARWIL', 'PG', 'PPO', 'APPO', 'R2D2', 'SAC', 'SlateQ', 'LinUCB', 'LinTS', 'AlphaZero', 'QMIX', 'MADDPG', 'Curiosity' ], 'continuous': [ 'A2C', 'A3C', 'ARS', 'BC', 'CQL', 'ES', # 'DDPG', 'TD3', 'APEX-DDPG', 'Dreamer', 'IMPALA', 'MAML', 'MARWIL', 'MBMPO', 'PG', 'PPO', 'APPO', 'SAC', 'MADDPG' ], 'multi-agent': [ 'A2C', 'A3C', 'BC', # 'DDPG', 'TD3', 'APEX-DDPG', 'DQN', 'Rainbow', 'APEX-DQN', 'IMPALA', 'MARWIL', 'PG', 'PPO', 'APPO', 'R2D2', 'SAC', 'LinUCB', 'LinTS', 'QMIX', 'MADDPG', 'Curiosity' ], 'unknown': [ 'ParameterSharing', 'FullyIndependentLearning', 'SharedCriticMethods' ], } def load_model(name: str) -> dict: return {'name': name, 'source': 'rllib'}
"""RLlib's library wrapper.""" source_metadata = {'name': 'rllib', 'original_name': 'RLlib', 'url': 'https://docs.ray.io/en/master/rllib.html'} models = {'discrete': ['A2C', 'A3C', 'ARS', 'BC', 'ES', 'DQN', 'Rainbow', 'APEX-DQN', 'IMPALA', 'MARWIL', 'PG', 'PPO', 'APPO', 'R2D2', 'SAC', 'SlateQ', 'LinUCB', 'LinTS', 'AlphaZero', 'QMIX', 'MADDPG', 'Curiosity'], 'continuous': ['A2C', 'A3C', 'ARS', 'BC', 'CQL', 'ES', 'TD3', 'APEX-DDPG', 'Dreamer', 'IMPALA', 'MAML', 'MARWIL', 'MBMPO', 'PG', 'PPO', 'APPO', 'SAC', 'MADDPG'], 'multi-agent': ['A2C', 'A3C', 'BC', 'TD3', 'APEX-DDPG', 'DQN', 'Rainbow', 'APEX-DQN', 'IMPALA', 'MARWIL', 'PG', 'PPO', 'APPO', 'R2D2', 'SAC', 'LinUCB', 'LinTS', 'QMIX', 'MADDPG', 'Curiosity'], 'unknown': ['ParameterSharing', 'FullyIndependentLearning', 'SharedCriticMethods']} def load_model(name: str) -> dict: return {'name': name, 'source': 'rllib'}
# Recursive, O(2^n) def LCS(X, Y, m, n): if m == 0 or n == 0: return 0 elif X[m - 1] == Y[n - 1]: return 1 + LCS(X, Y, m - 1, n - 1) else: return max(LCS(X, Y, m - 1, n), LCS(X, Y, m, n - 1)) X = "AGGTAB" Y = "GXTXAYB" print("Length of LCS is ", LCS(X, Y, len(X), len(Y))) # Overlapping Substructure, Tabulation, O(mn) def LCS(X, Y): m = len(X) n = len(Y) L = [[None] * (n + 1) for i in range(m + 1)] # build L[m+1][n+1] bottom up # L[i][j] contains length of LCS of X[0..i-1] # and Y[0..j-1] for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: L[i][j] = 0 elif X[i - 1] == Y[j - 1]: L[i][j] = L[i - 1][j - 1] + 1 else: L[i][j] = max(L[i - 1][j], L[i][j - 1]) # L[m][n] contains LCS of X[0..m-1] & Y[0..n-1] return L[m][n] X = "ABCDGH" Y = "AEDFHR" print("Length of LCS is ", LCS(X, Y)) X = "AGGTAB" Y = "GXTXAYB" print("Length of LCS is ", LCS(X, Y))
def lcs(X, Y, m, n): if m == 0 or n == 0: return 0 elif X[m - 1] == Y[n - 1]: return 1 + lcs(X, Y, m - 1, n - 1) else: return max(lcs(X, Y, m - 1, n), lcs(X, Y, m, n - 1)) x = 'AGGTAB' y = 'GXTXAYB' print('Length of LCS is ', lcs(X, Y, len(X), len(Y))) def lcs(X, Y): m = len(X) n = len(Y) l = [[None] * (n + 1) for i in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: L[i][j] = 0 elif X[i - 1] == Y[j - 1]: L[i][j] = L[i - 1][j - 1] + 1 else: L[i][j] = max(L[i - 1][j], L[i][j - 1]) return L[m][n] x = 'ABCDGH' y = 'AEDFHR' print('Length of LCS is ', lcs(X, Y)) x = 'AGGTAB' y = 'GXTXAYB' print('Length of LCS is ', lcs(X, Y))
class CalculoZ(): def calcular_z(self, n1, n2, x, y, ux, uy, ox, oy): arriba = (x-y)-(ux-uy) abajo = (((ox)**2/(n1))+((oy)**2/(n2)))**0.5 z = arriba/abajo return z
class Calculoz: def calcular_z(self, n1, n2, x, y, ux, uy, ox, oy): arriba = x - y - (ux - uy) abajo = (ox ** 2 / n1 + oy ** 2 / n2) ** 0.5 z = arriba / abajo return z
class Solution: def intToRoman(self, num: int) -> str: res = "" s = ['I', 'V', 'X', 'L', 'C', 'D', 'M'] index = 0 while num > 0: x = num % 10 if x < 5: if x == 4: temp = s[index] + s[index + 1] else: temp = "" while x > 0: temp += s[index] x -= 1 else: if x == 9: temp = s[index] + s[index + 2] else: temp = s[index + 1] while x > 5: temp += s[index] x -= 1 index += 2 res = temp + res num = num // 10 return res if __name__ == '__main__': print( Solution().intToRoman(3), "III", Solution().intToRoman(4), "IV", Solution().intToRoman(9), "IX", Solution().intToRoman(58), "LVIII", Solution().intToRoman(1994), "MCMXCIV", )
class Solution: def int_to_roman(self, num: int) -> str: res = '' s = ['I', 'V', 'X', 'L', 'C', 'D', 'M'] index = 0 while num > 0: x = num % 10 if x < 5: if x == 4: temp = s[index] + s[index + 1] else: temp = '' while x > 0: temp += s[index] x -= 1 elif x == 9: temp = s[index] + s[index + 2] else: temp = s[index + 1] while x > 5: temp += s[index] x -= 1 index += 2 res = temp + res num = num // 10 return res if __name__ == '__main__': print(solution().intToRoman(3), 'III', solution().intToRoman(4), 'IV', solution().intToRoman(9), 'IX', solution().intToRoman(58), 'LVIII', solution().intToRoman(1994), 'MCMXCIV')
class BasicScript(object): def __init__(self, parser): """ Initialize the class :param parser: ArgumentParser """ super(BasicScript, self).__init__() self._parser = parser def get_arguments(self): """ Get the arguments to configure current script, should be implementd in children classes :return: list """ raise StandardError('Implement get_arguments method') def run(self, args, injector): raise StandardError('Implement run method') def configure(self): """ Configure the component before running it :rtype: Class instance """ self.__set_arguments() return self def __set_arguments(self): parser = self._parser.add_parser(self.__class__.__name__.lower(), help=self.__class__.__doc__, conflict_handler='resolve') arguments = self.get_arguments() for argument in arguments: short = argument['short'] long = argument['long'] del argument['short'] del argument['long'] parser.add_argument(short, long, **argument) def get_wf_configuration(self, args, injector): object_configuration = injector.get('object_configuration') if 1 >= len(object_configuration): configuration_file = args.configuration_file if 'configuration_file' in args and None != args.configuration_file else injector.get( 'interactive_configuration_file').get(args.wf_dir) configuration = injector.get('wf_configuration').get_workflow_configuration(configuration_file) configuration['config_paths'] = configuration_file for key in configuration: object_configuration[key] = configuration[key] return object_configuration
class Basicscript(object): def __init__(self, parser): """ Initialize the class :param parser: ArgumentParser """ super(BasicScript, self).__init__() self._parser = parser def get_arguments(self): """ Get the arguments to configure current script, should be implementd in children classes :return: list """ raise standard_error('Implement get_arguments method') def run(self, args, injector): raise standard_error('Implement run method') def configure(self): """ Configure the component before running it :rtype: Class instance """ self.__set_arguments() return self def __set_arguments(self): parser = self._parser.add_parser(self.__class__.__name__.lower(), help=self.__class__.__doc__, conflict_handler='resolve') arguments = self.get_arguments() for argument in arguments: short = argument['short'] long = argument['long'] del argument['short'] del argument['long'] parser.add_argument(short, long, **argument) def get_wf_configuration(self, args, injector): object_configuration = injector.get('object_configuration') if 1 >= len(object_configuration): configuration_file = args.configuration_file if 'configuration_file' in args and None != args.configuration_file else injector.get('interactive_configuration_file').get(args.wf_dir) configuration = injector.get('wf_configuration').get_workflow_configuration(configuration_file) configuration['config_paths'] = configuration_file for key in configuration: object_configuration[key] = configuration[key] return object_configuration
class ApiError(Exception): """ Exception raised when user does not have appropriate credentials Used for 301 & 401 HTTP Status codes """ def __init__(self, response): if 'error_description' in response: self.message = response['error_description'] else: self.message = response['error']
class Apierror(Exception): """ Exception raised when user does not have appropriate credentials Used for 301 & 401 HTTP Status codes """ def __init__(self, response): if 'error_description' in response: self.message = response['error_description'] else: self.message = response['error']
N, X, T = map(int, input().split()) time = N // X if(N%X == 0): print(time * T) else: print((time+1) * T)
(n, x, t) = map(int, input().split()) time = N // X if N % X == 0: print(time * T) else: print((time + 1) * T)
class Token: __slots__ = ('start', 'end') def __init__(self, start: int=None, end: int=None): self.start = start self.end = end @property def type(self): "Type of current token" return self.__class__.__name__ def to_json(self): return dict([(k, self.__getattribute__(k)) for k in dir(self) if not k.startswith('__') and k != 'to_json']) class Chars: Hash = '#' Dollar = '$' Dash = '-' Dot = '.' Colon = ':' Comma = ',' Excl = '!' At = '@' Percent = '%' Underscore = '_' RoundBracketOpen = '(' RoundBracketClose = ')' CurlyBracketOpen = '{' CurlyBracketClose = '}' Sibling = '+' SingleQuote = "'" DoubleQuote = '"' Transparent = 't' class OperatorType: Sibling = '+' Important = '!' ArgumentDelimiter = ',' ValueDelimiter = '-' PropertyDelimiter = ':' class Operator(Token): __slots__ = ('operator',) def __init__(self, operator: OperatorType, *args): super(Operator, self).__init__(*args) self.operator = operator class Bracket(Token): __slots__ = ('open',) def __init__(self, is_open: bool, *args): super(Bracket, self).__init__(*args) self.open = is_open class Literal(Token): __slots__ = ('value',) def __init__(self, value: str, *args): super(Literal, self).__init__(*args) self.value = value class NumberValue(Token): __slots__ = ('value', 'raw_value', 'unit') def __init__(self, value: int, raw_value: str, unit='', *args): super(NumberValue, self).__init__(*args) self.value = value self.raw_value = raw_value self.unit = unit class ColorValue(Token): __slots__ = ('r', 'g', 'b', 'a', 'raw') def __init__(self, r=0, g=0, b=0, a=None, raw='', *args): super(ColorValue, self).__init__(*args) self.r = r self.g = g self.b = b self.a = a if a is not None else 1 self.raw = raw class StringValue(Token): __slots__ = ('value', 'quote') def __init__(self, value: str, quote='', *args): super(StringValue, self).__init__(*args) self.value = value self.quote = quote class Field(Token): __slots__ = ('name', 'index') def __init__(self, name: str, index: int=None, *args): super(Field, self).__init__(*args) self.index = index self.name = name class WhiteSpace(Token): pass
class Token: __slots__ = ('start', 'end') def __init__(self, start: int=None, end: int=None): self.start = start self.end = end @property def type(self): """Type of current token""" return self.__class__.__name__ def to_json(self): return dict([(k, self.__getattribute__(k)) for k in dir(self) if not k.startswith('__') and k != 'to_json']) class Chars: hash = '#' dollar = '$' dash = '-' dot = '.' colon = ':' comma = ',' excl = '!' at = '@' percent = '%' underscore = '_' round_bracket_open = '(' round_bracket_close = ')' curly_bracket_open = '{' curly_bracket_close = '}' sibling = '+' single_quote = "'" double_quote = '"' transparent = 't' class Operatortype: sibling = '+' important = '!' argument_delimiter = ',' value_delimiter = '-' property_delimiter = ':' class Operator(Token): __slots__ = ('operator',) def __init__(self, operator: OperatorType, *args): super(Operator, self).__init__(*args) self.operator = operator class Bracket(Token): __slots__ = ('open',) def __init__(self, is_open: bool, *args): super(Bracket, self).__init__(*args) self.open = is_open class Literal(Token): __slots__ = ('value',) def __init__(self, value: str, *args): super(Literal, self).__init__(*args) self.value = value class Numbervalue(Token): __slots__ = ('value', 'raw_value', 'unit') def __init__(self, value: int, raw_value: str, unit='', *args): super(NumberValue, self).__init__(*args) self.value = value self.raw_value = raw_value self.unit = unit class Colorvalue(Token): __slots__ = ('r', 'g', 'b', 'a', 'raw') def __init__(self, r=0, g=0, b=0, a=None, raw='', *args): super(ColorValue, self).__init__(*args) self.r = r self.g = g self.b = b self.a = a if a is not None else 1 self.raw = raw class Stringvalue(Token): __slots__ = ('value', 'quote') def __init__(self, value: str, quote='', *args): super(StringValue, self).__init__(*args) self.value = value self.quote = quote class Field(Token): __slots__ = ('name', 'index') def __init__(self, name: str, index: int=None, *args): super(Field, self).__init__(*args) self.index = index self.name = name class Whitespace(Token): pass
literals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,.?/:;{[]}-=_+~!@#$%^&*()" #obfuscated literals = "tJ;EM mKrFzQ_SOT?]B[U@$yqec~fhd{=is&alxPIbnuRkC%Z(jDw#G:/)L,*.V!pov+HNYA^g-}WX" key = 7 def shuffle(plaintext): shuffled = "" # shuffle plaintext for i in range(int(len(plaintext) / 3)): block = plaintext[i*3] + plaintext[i*3 + 1] + plaintext[i*3 + 2] old0 = block[0] old1 = block[1] old2 = block[2] block = old2 + old0 + old1 shuffled += block shuffled += plaintext[len(plaintext) - (len(plaintext) % 3):len(plaintext)] return shuffled def unshuffle(ciphertext): unshuffled = "" # unshuffle plaintext for i in range(int(len(ciphertext) / 3)): block = ciphertext[i*3] + ciphertext[i*3 + 1] + ciphertext[i*3 + 2] old0 = block[0] old1 = block[1] old2 = block[2] block = old1 + old2 + old0 unshuffled += block unshuffled += ciphertext[len(ciphertext) - (len(ciphertext) % 3):len(ciphertext)] return unshuffled def shift(plaintext): shifted = "" # Cipher shift tmp = [] for i in range(len(plaintext)): pos = literals.find(plaintext[i]) if pos >= 0: if pos + key > len(literals): pos = (pos + key) - len(literals) res = literals[pos + key] else: res = plaintext[i] tmp.append(res) # reconstruct ciphertext for i in range(len(tmp)): shifted += tmp[i] return shifted def unshift(ciphertext): unshifted = "" tmp = [] for i in range(len(ciphertext)): pos = literals.find(ciphertext[i]) if pos >= 0: if pos - key < 0: pos = (pos - key) + len(literals) res = literals[pos - key] else: res = ciphertext[i] tmp.append(res) #reconstruct ciphertext for i in range(len(tmp)): unshifted += tmp[i] return unshifted def encrypt(msg): msg = shuffle(msg) msg = shift(msg) return msg def decrypt(msg): #msg = unshuffle(msg) msg = unshift(msg) msg = unshuffle(msg) return msg def test(): test = "This is my plaintext" test = "\nThis is a long paragraph with lots of exciting things\nI could go on and on about all of this stuff.\nLove, Zach!" test = "abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ_!@#$%^&*()" print ("Testing: " + test) print ("Shuffle: " + shuffle(test)) print ("Shift: " + shift(shuffle(test))) print ("Unshift: " + unshift(shift(shuffle(test)))) print ("Unshuffle: " + unshuffle(unshift(shift(shuffle(test))))) print ("") print ("Encrypt: " + encrypt(test)) print ("Decrypt: " + decrypt(encrypt(test))) if __name__ == "__main__": test()
literals = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,.?/:;{[]}-=_+~!@#$%^&*()' literals = 'tJ;EM mKrFzQ_SOT?]B[U@$yqec~fhd{=is&alxPIbnuRkC%Z(jDw#G:/)L,*.V!pov+HNYA^g-}WX' key = 7 def shuffle(plaintext): shuffled = '' for i in range(int(len(plaintext) / 3)): block = plaintext[i * 3] + plaintext[i * 3 + 1] + plaintext[i * 3 + 2] old0 = block[0] old1 = block[1] old2 = block[2] block = old2 + old0 + old1 shuffled += block shuffled += plaintext[len(plaintext) - len(plaintext) % 3:len(plaintext)] return shuffled def unshuffle(ciphertext): unshuffled = '' for i in range(int(len(ciphertext) / 3)): block = ciphertext[i * 3] + ciphertext[i * 3 + 1] + ciphertext[i * 3 + 2] old0 = block[0] old1 = block[1] old2 = block[2] block = old1 + old2 + old0 unshuffled += block unshuffled += ciphertext[len(ciphertext) - len(ciphertext) % 3:len(ciphertext)] return unshuffled def shift(plaintext): shifted = '' tmp = [] for i in range(len(plaintext)): pos = literals.find(plaintext[i]) if pos >= 0: if pos + key > len(literals): pos = pos + key - len(literals) res = literals[pos + key] else: res = plaintext[i] tmp.append(res) for i in range(len(tmp)): shifted += tmp[i] return shifted def unshift(ciphertext): unshifted = '' tmp = [] for i in range(len(ciphertext)): pos = literals.find(ciphertext[i]) if pos >= 0: if pos - key < 0: pos = pos - key + len(literals) res = literals[pos - key] else: res = ciphertext[i] tmp.append(res) for i in range(len(tmp)): unshifted += tmp[i] return unshifted def encrypt(msg): msg = shuffle(msg) msg = shift(msg) return msg def decrypt(msg): msg = unshift(msg) msg = unshuffle(msg) return msg def test(): test = 'This is my plaintext' test = '\nThis is a long paragraph with lots of exciting things\nI could go on and on about all of this stuff.\nLove, Zach!' test = 'abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ_!@#$%^&*()' print('Testing: ' + test) print('Shuffle: ' + shuffle(test)) print('Shift: ' + shift(shuffle(test))) print('Unshift: ' + unshift(shift(shuffle(test)))) print('Unshuffle: ' + unshuffle(unshift(shift(shuffle(test))))) print('') print('Encrypt: ' + encrypt(test)) print('Decrypt: ' + decrypt(encrypt(test))) if __name__ == '__main__': test()
# apis_v1/documentation_source/organization_suggestion_tasks_doc.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- def organization_suggestion_tasks_doc_template_values(url_root): """ Show documentation about organizationSuggestionTask """ required_query_parameter_list = [ { 'name': 'voter_device_id', 'value': 'string', # boolean, integer, long, string 'description': 'An 88 character unique identifier linked to a voter record on the server', }, { 'name': 'api_key', 'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string 'description': 'The unique key provided to any organization using the WeVoteServer APIs', }, { 'name': 'kind_of_suggestion_task', 'value': 'string', # boolean, integer, long, string 'description': 'Default is UPDATE_SUGGESTIONS_FROM_TWITTER_IDS_I_FOLLOW. ' 'Other options include UPDATE_SUGGESTIONS_FROM_WHAT_FRIENDS_FOLLOW, ' 'UPDATE_SUGGESTIONS_FROM_WHAT_FRIENDS_FOLLOW_ON_TWITTER, ' 'UPDATE_SUGGESTIONS_FROM_WHAT_FRIEND_FOLLOWS, ' 'UPDATE_SUGGESTIONS_FROM_WHAT_FRIEND_FOLLOWS_ON_TWITTER or UPDATE_SUGGESTIONS_ALL', }, ] optional_query_parameter_list = [ { 'name': 'kind_of_follow_task', 'value': 'string', # boolean, integer, long, string 'description': 'Default is FOLLOW_SUGGESTIONS_FROM_TWITTER_IDS_I_FOLLOW. ' 'Other options include FOLLOW_SUGGESTIONS_FROM_FRIENDS, ' 'or FOLLOW_SUGGESTIONS_FROM_FRIENDS_ON_TWITTER, ', }, ] potential_status_codes_list = [ { 'code': 'VALID_VOTER_DEVICE_ID_MISSING', 'description': 'Cannot proceed. A valid voter_device_id parameter was not included.', }, { 'code': 'VALID_VOTER_ID_MISSING', 'description': 'Cannot proceed. A valid voter_id was not found.', }, ] try_now_link_variables_dict = { # 'organization_we_vote_id': 'wv85org1', } api_response = '{\n' \ ' "status": string,\n' \ ' "success": boolean,\n' \ ' "voter_device_id": string (88 characters long),\n' \ '}' template_values = { 'api_name': 'organizationSuggestionTasks', 'api_slug': 'organizationSuggestionTasks', 'api_introduction': "This will provide list of suggested endorsers to follow. " "These suggestions are generated from twitter ids i follow, or organization of my friends follow", 'try_now_link': 'apis_v1:organizationSuggestionTasksView', 'try_now_link_variables_dict': try_now_link_variables_dict, 'url_root': url_root, 'get_or_post': 'GET', 'required_query_parameter_list': required_query_parameter_list, 'optional_query_parameter_list': optional_query_parameter_list, 'api_response': api_response, 'api_response_notes': "", 'potential_status_codes_list': potential_status_codes_list, } return template_values
def organization_suggestion_tasks_doc_template_values(url_root): """ Show documentation about organizationSuggestionTask """ required_query_parameter_list = [{'name': 'voter_device_id', 'value': 'string', 'description': 'An 88 character unique identifier linked to a voter record on the server'}, {'name': 'api_key', 'value': 'string (from post, cookie, or get (in that order))', 'description': 'The unique key provided to any organization using the WeVoteServer APIs'}, {'name': 'kind_of_suggestion_task', 'value': 'string', 'description': 'Default is UPDATE_SUGGESTIONS_FROM_TWITTER_IDS_I_FOLLOW. Other options include UPDATE_SUGGESTIONS_FROM_WHAT_FRIENDS_FOLLOW, UPDATE_SUGGESTIONS_FROM_WHAT_FRIENDS_FOLLOW_ON_TWITTER, UPDATE_SUGGESTIONS_FROM_WHAT_FRIEND_FOLLOWS, UPDATE_SUGGESTIONS_FROM_WHAT_FRIEND_FOLLOWS_ON_TWITTER or UPDATE_SUGGESTIONS_ALL'}] optional_query_parameter_list = [{'name': 'kind_of_follow_task', 'value': 'string', 'description': 'Default is FOLLOW_SUGGESTIONS_FROM_TWITTER_IDS_I_FOLLOW. Other options include FOLLOW_SUGGESTIONS_FROM_FRIENDS, or FOLLOW_SUGGESTIONS_FROM_FRIENDS_ON_TWITTER, '}] potential_status_codes_list = [{'code': 'VALID_VOTER_DEVICE_ID_MISSING', 'description': 'Cannot proceed. A valid voter_device_id parameter was not included.'}, {'code': 'VALID_VOTER_ID_MISSING', 'description': 'Cannot proceed. A valid voter_id was not found.'}] try_now_link_variables_dict = {} api_response = '{\n "status": string,\n "success": boolean,\n "voter_device_id": string (88 characters long),\n}' template_values = {'api_name': 'organizationSuggestionTasks', 'api_slug': 'organizationSuggestionTasks', 'api_introduction': 'This will provide list of suggested endorsers to follow. These suggestions are generated from twitter ids i follow, or organization of my friends follow', 'try_now_link': 'apis_v1:organizationSuggestionTasksView', 'try_now_link_variables_dict': try_now_link_variables_dict, 'url_root': url_root, 'get_or_post': 'GET', 'required_query_parameter_list': required_query_parameter_list, 'optional_query_parameter_list': optional_query_parameter_list, 'api_response': api_response, 'api_response_notes': '', 'potential_status_codes_list': potential_status_codes_list} return template_values
#!/usr/bin/env python # -*- coding: UTF-8 -*- class ConstraintSyntaxError(SyntaxError): """A generic error indicating an improperly defined constraint.""" pass class ConstraintValueError(ValueError): """A generic error indicating a value violates a constraint.""" pass
class Constraintsyntaxerror(SyntaxError): """A generic error indicating an improperly defined constraint.""" pass class Constraintvalueerror(ValueError): """A generic error indicating a value violates a constraint.""" pass
curupira = int(input()) boitata = int(input()) boto = int(input()) mapinguari = int(input()) lara = int(input()) total = 225 + (curupira * 300) + (boitata *1500) + (boto * 600) + (mapinguari * 1000)+(lara*150) print(total)
curupira = int(input()) boitata = int(input()) boto = int(input()) mapinguari = int(input()) lara = int(input()) total = 225 + curupira * 300 + boitata * 1500 + boto * 600 + mapinguari * 1000 + lara * 150 print(total)
class Sibling: pass
class Sibling: pass
if True: foo = 42 else: foo = None
if True: foo = 42 else: foo = None
#!/usr/bin/python3 print("Sum of even-valued terms less than four million in the Fibonacci sequence:") a, b, sum = 1, 1, 0 while b < 4000000: sum += b if b % 2 == 0 else 0 a, b = b, a + b print(sum)
print('Sum of even-valued terms less than four million in the Fibonacci sequence:') (a, b, sum) = (1, 1, 0) while b < 4000000: sum += b if b % 2 == 0 else 0 (a, b) = (b, a + b) print(sum)
class Solution: def numFactoredBinaryTrees(self, A): """ :type A: List[int] :rtype: int """ A.sort() nums, res, trees, factors = set(A), 0, {}, collections.defaultdict(set) for i, num in enumerate(A): for n in A[:i]: if num % n == 0 and num // n in nums: factors[num].add(n) for root in A: trees[root] = 1 for fac in factors[root]: trees[root] += trees[fac] * trees[root // fac] return sum(trees.values()) % ((10 ** 9) + 7)
class Solution: def num_factored_binary_trees(self, A): """ :type A: List[int] :rtype: int """ A.sort() (nums, res, trees, factors) = (set(A), 0, {}, collections.defaultdict(set)) for (i, num) in enumerate(A): for n in A[:i]: if num % n == 0 and num // n in nums: factors[num].add(n) for root in A: trees[root] = 1 for fac in factors[root]: trees[root] += trees[fac] * trees[root // fac] return sum(trees.values()) % (10 ** 9 + 7)
#LeetCode problem 200: Number of Islands class Solution: def check(self,grid,nodesVisited,row,col,m,n): return (row>=0 and row<m and col>=0 and col<n and grid[row][col]=="1" and nodesVisited[row][col]==0) def dfs(self,grid,nodesVisited,row,col,m,n): a=[-1,1,0,0] b=[0,0,1,-1] nodesVisited[row][col]=1 for k in range(4): if self.check(grid,nodesVisited,row+a[k],col+b[k],m,n): self.dfs(grid,nodesVisited,row+a[k],col+b[k],m,n) def numIslands(self, grid: List[List[str]]) -> int: nodesVisited=[[0 for i in range(len(grid[0]))] for i in range(len(grid))] count=0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j]=="0": continue elif grid[i][j]=="1" and nodesVisited[i][j]==0: count+=1 self.dfs(grid,nodesVisited,i,j,len(grid),len(grid[0])) return count
class Solution: def check(self, grid, nodesVisited, row, col, m, n): return row >= 0 and row < m and (col >= 0) and (col < n) and (grid[row][col] == '1') and (nodesVisited[row][col] == 0) def dfs(self, grid, nodesVisited, row, col, m, n): a = [-1, 1, 0, 0] b = [0, 0, 1, -1] nodesVisited[row][col] = 1 for k in range(4): if self.check(grid, nodesVisited, row + a[k], col + b[k], m, n): self.dfs(grid, nodesVisited, row + a[k], col + b[k], m, n) def num_islands(self, grid: List[List[str]]) -> int: nodes_visited = [[0 for i in range(len(grid[0]))] for i in range(len(grid))] count = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == '0': continue elif grid[i][j] == '1' and nodesVisited[i][j] == 0: count += 1 self.dfs(grid, nodesVisited, i, j, len(grid), len(grid[0])) return count
''' ################ # 55. Jump Game ################ class Solution: def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ if not nums or (nums[0]==0 and len(nums)>1): return False if len(nums)==1: return True l = len(nums) max_ = 0 for i in range (l-1): if nums[i]+i>max_: max_ = nums[i] + i if max_>=l-1: return True if max_==i and nums[i]==0: return False return False # nums = [2,3,1,1,4] nums = [1,2,0,3,0] solu = Solution() print (solu.canJump(nums)) ''' ######################## # 56. Merge Intervals ######################## # Definition for an interval. class Interval: def __init__(self, s=0, e=0): self.start = s self.end = e class Solution: def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ if not intervals: return intervals out = [] for interval in sorted(intervals, key=lambda i: i.start): if out and interval.start<=out[-1].end: out[-1].end = max(interval.end, out[-1].end) else: out.append(interval) return out intervals = [Interval(2,3), Interval(8,10),Interval(1,6),Interval(15,18)] # intervals = [[2,3],[8,10],[1,6],[15,18]] solu = Solution() t = solu.merge(intervals) print (t[1].end) # print (sorted(intervals, key=lambda i: i.start))
''' ################ # 55. Jump Game ################ class Solution: def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ if not nums or (nums[0]==0 and len(nums)>1): return False if len(nums)==1: return True l = len(nums) max_ = 0 for i in range (l-1): if nums[i]+i>max_: max_ = nums[i] + i if max_>=l-1: return True if max_==i and nums[i]==0: return False return False # nums = [2,3,1,1,4] nums = [1,2,0,3,0] solu = Solution() print (solu.canJump(nums)) ''' class Interval: def __init__(self, s=0, e=0): self.start = s self.end = e class Solution: def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ if not intervals: return intervals out = [] for interval in sorted(intervals, key=lambda i: i.start): if out and interval.start <= out[-1].end: out[-1].end = max(interval.end, out[-1].end) else: out.append(interval) return out intervals = [interval(2, 3), interval(8, 10), interval(1, 6), interval(15, 18)] solu = solution() t = solu.merge(intervals) print(t[1].end)
''' Create exceptions based on your inputs. Please follow the tasks below. - Capture and handle system exceptions - Create custom user-based exceptions ''' class CustomInputError(Exception): def __init__(self, *args, **kwargs): print("Going through my own CustomInputError") # Exception.__init__(self, *args, **kwargs) class MyZeroDivisionException(ZeroDivisionError): def __init__(self): print("The data is not valid") class DataNotValidException(TypeError): def __init__(self): print("The data contains Strings. Only numbers are expected in the input data")
""" Create exceptions based on your inputs. Please follow the tasks below. - Capture and handle system exceptions - Create custom user-based exceptions """ class Custominputerror(Exception): def __init__(self, *args, **kwargs): print('Going through my own CustomInputError') class Myzerodivisionexception(ZeroDivisionError): def __init__(self): print('The data is not valid') class Datanotvalidexception(TypeError): def __init__(self): print('The data contains Strings. Only numbers are expected in the input data')
""" This folder contains help-functions to Bokeh visualizations in Python. There are functions that align 2nd-ary y-axis to primary y-axis as well as functions that align 3 y-axes. """ __credits__ = "ICOS Carbon Portal" __license__ = "GPL-3.0" __version__ = "0.1.0" __maintainer__ = "ICOS Carbon Portal, elaborated products team" __email__ = ['[email protected]', '[email protected]'] __date__ = "2020-10-15"
""" This folder contains help-functions to Bokeh visualizations in Python. There are functions that align 2nd-ary y-axis to primary y-axis as well as functions that align 3 y-axes. """ __credits__ = 'ICOS Carbon Portal' __license__ = 'GPL-3.0' __version__ = '0.1.0' __maintainer__ = 'ICOS Carbon Portal, elaborated products team' __email__ = ['[email protected]', '[email protected]'] __date__ = '2020-10-15'
"""Collection of all documented ADS constants. Only a small subset of these are used by code in this library. Source: http://infosys.beckhoff.com/english.php?content=../content/1033/tcplclibsystem/html/tcplclibsys_constants.htm&id= # nopep8 """ """Port numbers""" # Port number of the standard loggers. AMSPORT_LOGGER = 100 # Port number of the TwinCAT Eventloggers. AMSPORT_EVENTLOG = 110 # Port number of the TwinCAT Realtime Servers. AMSPORT_R0_RTIME = 200 # Port number of the TwinCAT I/O Servers. AMSPORT_R0_IO = 300 # Port number of the TwinCAT NC Servers. AMSPORT_R0_NC = 500 # Port number of the TwinCAT NC Servers (Task SAF). AMSPORT_R0_NCSAF = 501 # Port number of the TwinCAT NC Servers (Task SVB). AMSPORT_R0_NCSVB = 511 # internal AMSPORT_R0_ISG = 550 # Port number of the TwinCAT NC I Servers. AMSPORT_R0_CNC = 600 # internal AMSPORT_R0_LINE = 700 # Port number of the TwinCAT PLC Servers (only at the Buscontroller). AMSPORT_R0_PLC = 800 # Port number of the TwinCAT PLC Servers in the runtime 1. AMSPORT_R0_PLC_RTS1 = 801 # Port number of the TwinCAT PLC Servers in the runtime 2. AMSPORT_R0_PLC_RTS2 = 811 # Port number of the TwinCAT PLC Servers in the runtime 3. AMSPORT_R0_PLC_RTS3 = 821 # Port number of the TwinCAT PLC Servers in the runtime 4. AMSPORT_R0_PLC_RTS4 = 831 # Port number of the TwinCAT CAM Server. AMSPORT_R0_CAM = 900 # Port number of the TwinCAT CAMTOOL Server. AMSPORT_R0_CAMTOOL = 950 # Port number of the TwinCAT System Service. AMSPORT_R3_SYSSERV = 10000 # Port number of the TwinCAT Scope Servers (since Lib. V2.0.12) AMSPORT_R3_SCOPESERVER = 27110 """ADS States""" ADSSTATE_INVALID = 0 # ADS Status: invalid ADSSTATE_IDLE = 1 # ADS Status: idle ADSSTATE_RESET = 2 # ADS Status: reset. ADSSTATE_INIT = 3 # ADS Status: init ADSSTATE_START = 4 # ADS Status: start ADSSTATE_RUN = 5 # ADS Status: run ADSSTATE_STOP = 6 # ADS Status: stop ADSSTATE_SAVECFG = 7 # ADS Status: save configuration ADSSTATE_LOADCFG = 8 # ADS Status: load configuration ADSSTATE_POWERFAILURE = 9 # ADS Status: Power failure ADSSTATE_POWERGOOD = 10 # ADS Status: Power good ADSSTATE_ERROR = 11 # ADS Status: Error ADSSTATE_SHUTDOWN = 12 # ADS Status: Shutdown ADSSTATE_SUSPEND = 13 # ADS Status: Suspend ADSSTATE_RESUME = 14 # ADS Status: Resume ADSSTATE_CONFIG = 15 # ADS Status: Configuration ADSSTATE_RECONFIG = 16 # ADS Status: Reconfiguration ADSSTATE_MAXSTATES = 17 """Reserved Index Groups""" ADSIGRP_SYMTAB = 0xF000 ADSIGRP_SYMNAME = 0xF001 ADSIGRP_SYMVAL = 0xF002 ADSIGRP_SYM_HNDBYNAME = 0xF003 ADSIGRP_SYM_VALBYNAME = 0xF004 ADSIGRP_SYM_VALBYHND = 0xF005 ADSIGRP_SYM_RELEASEHND = 0xF006 ADSIGRP_SYM_INFOBYNAME = 0xF007 ADSIGRP_SYM_VERSION = 0xF008 ADSIGRP_SYM_INFOBYNAMEEX = 0xF009 ADSIGRP_SYM_DOWNLOAD = 0xF00A ADSIGRP_SYM_UPLOAD = 0xF00B ADSIGRP_SYM_UPLOADINFO = 0xF00C ADSIGRP_SYM_SUMREAD = 0xF080 ADSIGRP_SYM_SUMWRITE = 0xF081 ADSIGRP_SYM_SUMREADWRITE = 0xF082 ADSIGRP_SYMNOTE = 0xF010 ADSIGRP_IOIMAGE_RWIB = 0xF020 ADSIGRP_IOIMAGE_RWIX = 0xF021 ADSIGRP_IOIMAGE_RISIZE = 0xF025 ADSIGRP_IOIMAGE_RWOB = 0xF030 ADSIGRP_IOIMAGE_RWOX = 0xF031 ADSIGRP_IOIMAGE_RWOSIZE = 0xF035 ADSIGRP_IOIMAGE_CLEARI = 0xF040 ADSIGRP_IOIMAGE_CLEARO = 0xF050 ADSIGRP_IOIMAGE_RWIOB = 0xF060 ADSIGRP_DEVICE_DATA = 0xF100 ADSIOFFS_DEVDATA_ADSSTATE = 0x0000 ADSIOFFS_DEVDATA_DEVSTATE = 0x0002 """System Service Index Groups""" SYSTEMSERVICE_OPENCREATE = 100 SYSTEMSERVICE_OPENREAD = 101 SYSTEMSERVICE_OPENWRITE = 102 SYSTEMSERVICE_CREATEFILE = 110 SYSTEMSERVICE_CLOSEHANDLE = 111 SYSTEMSERVICE_FOPEN = 120 SYSTEMSERVICE_FCLOSE = 121 SYSTEMSERVICE_FREAD = 122 SYSTEMSERVICE_FWRITE = 123 SYSTEMSERVICE_FSEEK = 124 SYSTEMSERVICE_FTELL = 125 SYSTEMSERVICE_FGETS = 126 SYSTEMSERVICE_FPUTS = 127 SYSTEMSERVICE_FSCANF = 128 SYSTEMSERVICE_FPRINTF = 129 SYSTEMSERVICE_FEOF = 130 SYSTEMSERVICE_FDELETE = 131 SYSTEMSERVICE_FRENAME = 132 SYSTEMSERVICE_REG_HKEYLOCALMACHINE = 200 SYSTEMSERVICE_SENDEMAIL = 300 SYSTEMSERVICE_TIMESERVICES = 400 SYSTEMSERVICE_STARTPROCESS = 500 SYSTEMSERVICE_CHANGENETID = 600 """System Service Index Offsets (Timeservices)""" TIMESERVICE_DATEANDTIME = 1 TIMESERVICE_SYSTEMTIMES = 2 TIMESERVICE_RTCTIMEDIFF = 3 TIMESERVICE_ADJUSTTIMETORTC = 4 """Masks for Log output""" ADSLOG_MSGTYPE_HINT = 0x01 ADSLOG_MSGTYPE_WARN = 0x02 ADSLOG_MSGTYPE_ERROR = 0x04 ADSLOG_MSGTYPE_LOG = 0x10 ADSLOG_MSGTYPE_MSGBOX = 0x20 ADSLOG_MSGTYPE_RESOURCE = 0x40 ADSLOG_MSGTYPE_STRING = 0x80 """Masks for Bootdata-Flagsx""" BOOTDATAFLAGS_RETAIN_LOADED = 0x01 BOOTDATAFLAGS_RETAIN_INVALID = 0x02 BOOTDATAFLAGS_RETAIN_REQUESTED = 0x04 BOOTDATAFLAGS_PERSISTENT_LOADED = 0x10 BOOTDATAFLAGS_PERSISTENT_INVALID = 0x20 """Masks for BSOD-Flags""" SYSTEMSTATEFLAGS_BSOD = 0x01 # BSOD: Blue Screen of Death SYSTEMSTATEFLAGS_RTVIOLATION = 0x02 # Realtime violation, latency time overrun """Masks for File output""" # 'r': Opens file for reading FOPEN_MODEREAD = 0x0001 # 'w': Opens file for writing, (possible) existing files were overwritten. FOPEN_MODEWRITE = 0x0002 # 'a': Opens file for writing, is attached to (possible) exisiting files. If no # file exists, it will be created. FOPEN_MODEAPPEND = 0x0004 # '+': Opens a file for reading and writing. FOPEN_MODEPLUS = 0x0008 # 'b': Opens a file for binary reading and writing. FOPEN_MODEBINARY = 0x0010 # 't': Opens a file for textual reading and writing. FOPEN_MODETEXT = 0x0020 """Masks for Eventlogger Flags""" # Class and priority are defined by the formatter. TCEVENTFLAG_PRIOCLASS = 0x0010 # The formatting information comes with the event TCEVENTFLAG_FMTSELF = 0x0020 # Logg. TCEVENTFLAG_LOG = 0x0040 # Show message box . TCEVENTFLAG_MSGBOX = 0x0080 # Use Source-Id instead of Source name. TCEVENTFLAG_SRCID = 0x0100 """TwinCAT Eventlogger Status messages""" # Not valid, occurs also if the event was not reported. TCEVENTSTATE_INVALID = 0x0000 # Event is reported, but neither signed off nor acknowledged. TCEVENTSTATE_SIGNALED = 0x0001 # Event is signed off ('gone'). TCEVENTSTATE_RESET = 0x0002 # Event is acknowledged. TCEVENTSTATE_CONFIRMED = 0x0010 # Event is signed off and acknowledged. TCEVENTSTATE_RESETCON = 0x0012 """TwinCAT Eventlogger Status messages""" TCEVENT_SRCNAMESIZE = 15 # Max. Length for the Source name. TCEVENT_FMTPRGSIZE = 31 # Max. Length for the name of the formatters. """Other""" PI = 3.1415926535897932384626433832795 # Pi number DEFAULT_ADS_TIMEOUT = 5 # (seconds) Default ADS timeout MAX_STRING_LENGTH = 255 # The max. string length of T_MaxString data type
"""Collection of all documented ADS constants. Only a small subset of these are used by code in this library. Source: http://infosys.beckhoff.com/english.php?content=../content/1033/tcplclibsystem/html/tcplclibsys_constants.htm&id= # nopep8 """ 'Port numbers' amsport_logger = 100 amsport_eventlog = 110 amsport_r0_rtime = 200 amsport_r0_io = 300 amsport_r0_nc = 500 amsport_r0_ncsaf = 501 amsport_r0_ncsvb = 511 amsport_r0_isg = 550 amsport_r0_cnc = 600 amsport_r0_line = 700 amsport_r0_plc = 800 amsport_r0_plc_rts1 = 801 amsport_r0_plc_rts2 = 811 amsport_r0_plc_rts3 = 821 amsport_r0_plc_rts4 = 831 amsport_r0_cam = 900 amsport_r0_camtool = 950 amsport_r3_sysserv = 10000 amsport_r3_scopeserver = 27110 'ADS States' adsstate_invalid = 0 adsstate_idle = 1 adsstate_reset = 2 adsstate_init = 3 adsstate_start = 4 adsstate_run = 5 adsstate_stop = 6 adsstate_savecfg = 7 adsstate_loadcfg = 8 adsstate_powerfailure = 9 adsstate_powergood = 10 adsstate_error = 11 adsstate_shutdown = 12 adsstate_suspend = 13 adsstate_resume = 14 adsstate_config = 15 adsstate_reconfig = 16 adsstate_maxstates = 17 'Reserved Index Groups' adsigrp_symtab = 61440 adsigrp_symname = 61441 adsigrp_symval = 61442 adsigrp_sym_hndbyname = 61443 adsigrp_sym_valbyname = 61444 adsigrp_sym_valbyhnd = 61445 adsigrp_sym_releasehnd = 61446 adsigrp_sym_infobyname = 61447 adsigrp_sym_version = 61448 adsigrp_sym_infobynameex = 61449 adsigrp_sym_download = 61450 adsigrp_sym_upload = 61451 adsigrp_sym_uploadinfo = 61452 adsigrp_sym_sumread = 61568 adsigrp_sym_sumwrite = 61569 adsigrp_sym_sumreadwrite = 61570 adsigrp_symnote = 61456 adsigrp_ioimage_rwib = 61472 adsigrp_ioimage_rwix = 61473 adsigrp_ioimage_risize = 61477 adsigrp_ioimage_rwob = 61488 adsigrp_ioimage_rwox = 61489 adsigrp_ioimage_rwosize = 61493 adsigrp_ioimage_cleari = 61504 adsigrp_ioimage_clearo = 61520 adsigrp_ioimage_rwiob = 61536 adsigrp_device_data = 61696 adsioffs_devdata_adsstate = 0 adsioffs_devdata_devstate = 2 'System Service Index Groups' systemservice_opencreate = 100 systemservice_openread = 101 systemservice_openwrite = 102 systemservice_createfile = 110 systemservice_closehandle = 111 systemservice_fopen = 120 systemservice_fclose = 121 systemservice_fread = 122 systemservice_fwrite = 123 systemservice_fseek = 124 systemservice_ftell = 125 systemservice_fgets = 126 systemservice_fputs = 127 systemservice_fscanf = 128 systemservice_fprintf = 129 systemservice_feof = 130 systemservice_fdelete = 131 systemservice_frename = 132 systemservice_reg_hkeylocalmachine = 200 systemservice_sendemail = 300 systemservice_timeservices = 400 systemservice_startprocess = 500 systemservice_changenetid = 600 'System Service Index Offsets (Timeservices)' timeservice_dateandtime = 1 timeservice_systemtimes = 2 timeservice_rtctimediff = 3 timeservice_adjusttimetortc = 4 'Masks for Log output' adslog_msgtype_hint = 1 adslog_msgtype_warn = 2 adslog_msgtype_error = 4 adslog_msgtype_log = 16 adslog_msgtype_msgbox = 32 adslog_msgtype_resource = 64 adslog_msgtype_string = 128 'Masks for Bootdata-Flagsx' bootdataflags_retain_loaded = 1 bootdataflags_retain_invalid = 2 bootdataflags_retain_requested = 4 bootdataflags_persistent_loaded = 16 bootdataflags_persistent_invalid = 32 'Masks for BSOD-Flags' systemstateflags_bsod = 1 systemstateflags_rtviolation = 2 'Masks for File output' fopen_moderead = 1 fopen_modewrite = 2 fopen_modeappend = 4 fopen_modeplus = 8 fopen_modebinary = 16 fopen_modetext = 32 'Masks for Eventlogger Flags' tceventflag_prioclass = 16 tceventflag_fmtself = 32 tceventflag_log = 64 tceventflag_msgbox = 128 tceventflag_srcid = 256 'TwinCAT Eventlogger Status messages' tceventstate_invalid = 0 tceventstate_signaled = 1 tceventstate_reset = 2 tceventstate_confirmed = 16 tceventstate_resetcon = 18 'TwinCAT Eventlogger Status messages' tcevent_srcnamesize = 15 tcevent_fmtprgsize = 31 'Other' pi = 3.141592653589793 default_ads_timeout = 5 max_string_length = 255
# https://www.acmicpc.net/problem/8393 a = int(input()) result = 0 for i in range(a + 1): result = result + i print(result)
a = int(input()) result = 0 for i in range(a + 1): result = result + i print(result)
# conf.py/Open GoPro, Version 1.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro). # This copyright was auto-generated on Tue May 18 22:08:50 UTC 2021 project = "Open GoPro Python SDK" copyright = "2020, GoPro Inc." author = "Tim Camise" version = "0.5.8" release = "0.5.8" templates_path = ["_templates"] source_suffix = ".rst" master_doc = "index" pygments_style = "sphinx" html_static_path = ["_static"] extensions = [ "sphinx.ext.autodoc", "sphinxcontrib.napoleon", "sphinx_rtd_theme", "sphinx.ext.autosectionlabel", ] html_theme = "sphinx_rtd_theme" html_context = { "display_github": True, }
project = 'Open GoPro Python SDK' copyright = '2020, GoPro Inc.' author = 'Tim Camise' version = '0.5.8' release = '0.5.8' templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' pygments_style = 'sphinx' html_static_path = ['_static'] extensions = ['sphinx.ext.autodoc', 'sphinxcontrib.napoleon', 'sphinx_rtd_theme', 'sphinx.ext.autosectionlabel'] html_theme = 'sphinx_rtd_theme' html_context = {'display_github': True}
# Link --> https://www.hackerrank.com/challenges/maximum-element/problem # Code: def getMax(operations): maximum = 0 temp = [] answer = [] for i in operations: if i != '2' and i != '3': numbers = i.split() number = int(numbers[1]) temp.append(number) if number > maximum: maximum = number elif i == '2': temp.pop() if len(temp) != 0: maximum = max(temp) else: maximum = 0 else: answer.append(maximum) return answer
def get_max(operations): maximum = 0 temp = [] answer = [] for i in operations: if i != '2' and i != '3': numbers = i.split() number = int(numbers[1]) temp.append(number) if number > maximum: maximum = number elif i == '2': temp.pop() if len(temp) != 0: maximum = max(temp) else: maximum = 0 else: answer.append(maximum) return answer
# -*- coding: utf-8 -*- """ Created on Mon Aug 30 15:49:24 2021 @author: alann """ arr = [[1,1,0,1,0], [0,1,1,1,0], [1,1,1,1,0], [0,1,1,1,1]] def largestSquare(arr ) -> int: if len(arr) < 1 or len(arr[0]) < 1: return 0 largest = 0 cache = [[0 for i in range(len(arr[0]))] for j in range(len(arr))] for i, iVal in enumerate(arr): for j, jVal in enumerate(iVal): if jVal: if not i or not j: cache[i][j] = jVal else: currentMin = None currentMin = min(currentMin, cache[i-1][j]) if currentMin != None else cache[i-1][j] currentMin = min(currentMin, cache[i-1][j-1]) if currentMin != None else cache[i-1][j-1] currentMin = min(currentMin, cache[i][j-1]) if currentMin != None else cache[i][j-1] cache[i][j] = currentMin + 1 largest = max(largest, cache[i][j]) return largest largest = largestSquare(arr) print(largest) """ if we are allowed to modify original array we can do it in constant space """ arr = [[1,1,0,1,0], [0,1,1,1,0], [1,1,1,1,0], [0,1,1,1,1]] def largestSquare(arr ) -> int: if len(arr) < 1 or len(arr[0]) < 1: return 0 largest = 0 for i, iVal in enumerate(arr): for j, jVal in enumerate(iVal): if jVal: if not i or not j: arr[i][j] = jVal else: arr[i][j] = 1 + min(arr[i-1][j], arr[i-1][j-1],arr[i][j-1]) largest = max(largest, arr[i][j]) return largest largest = largestSquare(arr) print(largest)
""" Created on Mon Aug 30 15:49:24 2021 @author: alann """ arr = [[1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [0, 1, 1, 1, 1]] def largest_square(arr) -> int: if len(arr) < 1 or len(arr[0]) < 1: return 0 largest = 0 cache = [[0 for i in range(len(arr[0]))] for j in range(len(arr))] for (i, i_val) in enumerate(arr): for (j, j_val) in enumerate(iVal): if jVal: if not i or not j: cache[i][j] = jVal else: current_min = None current_min = min(currentMin, cache[i - 1][j]) if currentMin != None else cache[i - 1][j] current_min = min(currentMin, cache[i - 1][j - 1]) if currentMin != None else cache[i - 1][j - 1] current_min = min(currentMin, cache[i][j - 1]) if currentMin != None else cache[i][j - 1] cache[i][j] = currentMin + 1 largest = max(largest, cache[i][j]) return largest largest = largest_square(arr) print(largest) '\n if we are allowed to modify original array we can do it in constant space\n' arr = [[1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [0, 1, 1, 1, 1]] def largest_square(arr) -> int: if len(arr) < 1 or len(arr[0]) < 1: return 0 largest = 0 for (i, i_val) in enumerate(arr): for (j, j_val) in enumerate(iVal): if jVal: if not i or not j: arr[i][j] = jVal else: arr[i][j] = 1 + min(arr[i - 1][j], arr[i - 1][j - 1], arr[i][j - 1]) largest = max(largest, arr[i][j]) return largest largest = largest_square(arr) print(largest)
# -*- coding: utf-8 -*- """ Created on Sun May 12 19:10:03 2019 @author: DiPu """ shopping_list=[] print("enter items to add in list and type quit when you arew done") while True: ip=input("enter list") if ip=="QUIT": break elif ip.upper()=="SHOW": print(shopping_list) elif ip.upper()=="HELP": print("help1:if input is show then items in list will be displayed") print("help2:if input is QUIT then total items in list will be printed and user will not be able to add more items") else: shopping_list.append(ip) for count,item in enumerate(shopping_list,1): print(count,item) ip=input("enter add to ADDITION/REMOVE of item at some index:") if ip=="ADDITION": ip1=int(input("enter index:")) item=input("enter item:") shopping_list[ip1-1]=item elif ip=="REMOVE": ip1=int(input("enter index:")) shopping_list.pop(ip1-1) with open("shopping_list_miniprojectpy.py",'rt') as f1: with open("shopping.txt",'wt') as f: for lines in f1: f.write(lines) ip=open("shopping.txt") content=ip.readlines() print(content)
""" Created on Sun May 12 19:10:03 2019 @author: DiPu """ shopping_list = [] print('enter items to add in list and type quit when you arew done') while True: ip = input('enter list') if ip == 'QUIT': break elif ip.upper() == 'SHOW': print(shopping_list) elif ip.upper() == 'HELP': print('help1:if input is show then items in list will be displayed') print('help2:if input is QUIT then total items in list will be printed and user will not be able to add more items') else: shopping_list.append(ip) for (count, item) in enumerate(shopping_list, 1): print(count, item) ip = input('enter add to ADDITION/REMOVE of item at some index:') if ip == 'ADDITION': ip1 = int(input('enter index:')) item = input('enter item:') shopping_list[ip1 - 1] = item elif ip == 'REMOVE': ip1 = int(input('enter index:')) shopping_list.pop(ip1 - 1) with open('shopping_list_miniprojectpy.py', 'rt') as f1: with open('shopping.txt', 'wt') as f: for lines in f1: f.write(lines) ip = open('shopping.txt') content = ip.readlines() print(content)
#!/usr/bin/env python3 if __name__ == "__main__": N = int(input().strip()) stamps = set() for _ in range(N): stamp = input().strip() stamps.add(stamp) print(len(stamps))
if __name__ == '__main__': n = int(input().strip()) stamps = set() for _ in range(N): stamp = input().strip() stamps.add(stamp) print(len(stamps))
"""Provide a class for yWriter chapter representation. Copyright (c) 2021 Peter Triesberger For further information see https://github.com/peter88213/PyWriter Published under the MIT License (https://opensource.org/licenses/mit-license.php) """ class Chapter(): """yWriter chapter representation. # xml: <CHAPTERS><CHAPTER> """ chapterTitlePrefix = "Chapter " # str # Can be changed at runtime for non-English projects. def __init__(self): self.title = None # str # xml: <Title> self.desc = None # str # xml: <Desc> self.chLevel = None # int # xml: <SectionStart> # 0 = chapter level # 1 = section level ("this chapter begins a section") self.oldType = None # int # xml: <Type> # 0 = chapter type (marked "Chapter") # 1 = other type (marked "Other") self.chType = None # int # xml: <ChapterType> # 0 = Normal # 1 = Notes # 2 = Todo self.isUnused = None # bool # xml: <Unused> -1 self.suppressChapterTitle = None # bool # xml: <Fields><Field_SuppressChapterTitle> 1 # True: Chapter heading not to be displayed in written document. # False: Chapter heading to be displayed in written document. self.isTrash = None # bool # xml: <Fields><Field_IsTrash> 1 # True: This chapter is the yw7 project's "trash bin". # False: This chapter is not a "trash bin". self.suppressChapterBreak = None # bool # xml: <Fields><Field_SuppressChapterBreak> 0 self.srtScenes = [] # list of str # xml: <Scenes><ScID> # The chapter's scene IDs. The order of its elements # corresponds to the chapter's order of the scenes. def get_title(self): """Fix auto-chapter titles if necessary """ text = self.title if text: text = text.replace('Chapter ', self.chapterTitlePrefix) return text
"""Provide a class for yWriter chapter representation. Copyright (c) 2021 Peter Triesberger For further information see https://github.com/peter88213/PyWriter Published under the MIT License (https://opensource.org/licenses/mit-license.php) """ class Chapter: """yWriter chapter representation. # xml: <CHAPTERS><CHAPTER> """ chapter_title_prefix = 'Chapter ' def __init__(self): self.title = None self.desc = None self.chLevel = None self.oldType = None self.chType = None self.isUnused = None self.suppressChapterTitle = None self.isTrash = None self.suppressChapterBreak = None self.srtScenes = [] def get_title(self): """Fix auto-chapter titles if necessary """ text = self.title if text: text = text.replace('Chapter ', self.chapterTitlePrefix) return text
""" """ # TODO: make this list complete [exclude stuffs ending with 's'] conditionals = [ "cmp", "cmn", "tst", "teq" ] class CMP(object): def __init__(self, line_no, text): self.line_no = line_no self.text = text class Branch(object): def __init__(self, line_no, text, label=None): text = text.strip() self.line_no = line_no self.text = text # dealing with space self.label_text = getArgs(text)[0] self.label = label class Label(object): def __init__(self, line_no, text): self.line_no = line_no self.text = text.replace(":", "") class Loop(object): def __init__(self, label, branch, cmp): self.label = label self.branch = branch self.cmp = cmp self.enterNode = label.line_no self.exitNode = branch.line_no def getStart(self): return self.enterNode def getEnd(self): return self.exitNode def contains(self, i, j): if i > self.enterNode and j < self.exitNode: return True return False class If(object): def __init__(self, cmp, branch_to_end, end_label): self.cmp = cmp self.cmp_branch = branch_to_end self.branch_to_end = branch_to_end self.end_label = end_label self.block1_start_line = branch_to_end.line_no + 1 self.block1_end_line = end_label.line_no - 1 def contains(self, i, j): if i > self.block1_start_line and j <= self.block1_end_line: return True return False def getStart(self): return self.block1_start_line def getEnd(self): return self.block1_end_line class IfElse(object): def __init__(self, cmp, branch_to_2nd_block, branch_to_end, block2_label, end_label): self.cmp = cmp self.cmp_branch = branch_to_2nd_block self.branch_to_2nd_Block = branch_to_2nd_block self.block1_start_line = branch_to_2nd_block.line_no + 1 assert branch_to_end.line_no - 1 == block2_label.line_no - 2 self.block1_end_line = branch_to_end.line_no - 1 self.block2_start_line = block2_label.line_no + 1 self.block2_end_line = end_label.line_no - 1 self.block2_start_label = block2_label self.block2_label = block2_label self.block2_end_label = end_label self.end_label = end_label def isLabel(text): if text.strip().endswith(":"): return True def isConditional(text): text = getOpcode(text) # if text.endswith("s"): # return True # print(text) if text in conditionals: return True return False # TODO: make this more robust def isBranching(text): if text.startswith("b"): return True return False def removeSpaces(text): text = text.replace("\t"," ") text = text.strip(" ") text = text.strip("\n") i = 0 while(i != len(text)-1): if text[i] == " " and text[i+1] == " ": text = text[:i+1]+text[i+2:] continue i += 1 return text def getOpcode(text): text = removeSpaces(text) op = text.split(" ")[0] return op def getArgs(text): text = removeSpaces(text) op = ''.join(text.split(" ")[1:]) args = op.split(",") for i in range(len(args)): args[i].strip(" ") if args[i][0] == "#": args[i] = args[i][1:] return args def getComparison(cmp, branch): vars = getArgs(cmp) var1 = vars[0] var2 = vars[1] cond = getOpcode(branch)[1:] ans = "" if cond == "eq": ans = (str(var1) + " == " + str(var2)) elif cond == "lt": ans = (str(var1) + " < " + str(var2)) elif cond == "gt": ans = (str(var1) + " > " + str(var2)) elif cond == "ge": ans = (str(var1) + " >= " + str(var2)) elif cond == "le": ans = (str(var1) + " <= " + str(var2)) elif cond == "ne": ans = (str(var1) + " != " + str(var2)) return ans ''' def getOpDesc(text): text = text.upper() args = getArgs(text) opcode = getOpcode(text) if opcode == "add" or opcode == "vadd.f32" or opcode == "vadd.f64": print(str(args[0]) + " = " + str(args[1]) + " + " + str(args[2])) elif opcode == "sub": print(str(args[0]) + " = " + str(args[1]) + " - " + str(args[2])) elif opcode == "rsb": print(str(args[0]) + " = " + str(args[2]) + " - " + str(args[1])) elif opcode == "and": print(str(args[0]) + " = " + str(args[1]) + " && " + str(args[2])) elif opcode == "orr": print(str(args[0]) + " = " + str(args[1]) + " || " + str(args[2])) elif opcode == "mov" or opcode == "vmov.f32": print(str(args[0]) + " = " + str(args[1])) elif opcode == "str": print(str(args[1]) + " = " + str(args[0])) elif opcode == "ldr": print("int " + str(args[0]) + " = " + str(args[1])) elif opcode == "vldr.32": print("float " + str(args[0]) + " = " + str(args[1])) elif opcode == "vldr.64": print("double " + str(args[0]) + " = " + str(args[1])) elif opcode == "ldrb": print("char " + str(args[0]) + " = " + str(args[1])) '''
""" """ conditionals = ['cmp', 'cmn', 'tst', 'teq'] class Cmp(object): def __init__(self, line_no, text): self.line_no = line_no self.text = text class Branch(object): def __init__(self, line_no, text, label=None): text = text.strip() self.line_no = line_no self.text = text self.label_text = get_args(text)[0] self.label = label class Label(object): def __init__(self, line_no, text): self.line_no = line_no self.text = text.replace(':', '') class Loop(object): def __init__(self, label, branch, cmp): self.label = label self.branch = branch self.cmp = cmp self.enterNode = label.line_no self.exitNode = branch.line_no def get_start(self): return self.enterNode def get_end(self): return self.exitNode def contains(self, i, j): if i > self.enterNode and j < self.exitNode: return True return False class If(object): def __init__(self, cmp, branch_to_end, end_label): self.cmp = cmp self.cmp_branch = branch_to_end self.branch_to_end = branch_to_end self.end_label = end_label self.block1_start_line = branch_to_end.line_no + 1 self.block1_end_line = end_label.line_no - 1 def contains(self, i, j): if i > self.block1_start_line and j <= self.block1_end_line: return True return False def get_start(self): return self.block1_start_line def get_end(self): return self.block1_end_line class Ifelse(object): def __init__(self, cmp, branch_to_2nd_block, branch_to_end, block2_label, end_label): self.cmp = cmp self.cmp_branch = branch_to_2nd_block self.branch_to_2nd_Block = branch_to_2nd_block self.block1_start_line = branch_to_2nd_block.line_no + 1 assert branch_to_end.line_no - 1 == block2_label.line_no - 2 self.block1_end_line = branch_to_end.line_no - 1 self.block2_start_line = block2_label.line_no + 1 self.block2_end_line = end_label.line_no - 1 self.block2_start_label = block2_label self.block2_label = block2_label self.block2_end_label = end_label self.end_label = end_label def is_label(text): if text.strip().endswith(':'): return True def is_conditional(text): text = get_opcode(text) if text in conditionals: return True return False def is_branching(text): if text.startswith('b'): return True return False def remove_spaces(text): text = text.replace('\t', ' ') text = text.strip(' ') text = text.strip('\n') i = 0 while i != len(text) - 1: if text[i] == ' ' and text[i + 1] == ' ': text = text[:i + 1] + text[i + 2:] continue i += 1 return text def get_opcode(text): text = remove_spaces(text) op = text.split(' ')[0] return op def get_args(text): text = remove_spaces(text) op = ''.join(text.split(' ')[1:]) args = op.split(',') for i in range(len(args)): args[i].strip(' ') if args[i][0] == '#': args[i] = args[i][1:] return args def get_comparison(cmp, branch): vars = get_args(cmp) var1 = vars[0] var2 = vars[1] cond = get_opcode(branch)[1:] ans = '' if cond == 'eq': ans = str(var1) + ' == ' + str(var2) elif cond == 'lt': ans = str(var1) + ' < ' + str(var2) elif cond == 'gt': ans = str(var1) + ' > ' + str(var2) elif cond == 'ge': ans = str(var1) + ' >= ' + str(var2) elif cond == 'le': ans = str(var1) + ' <= ' + str(var2) elif cond == 'ne': ans = str(var1) + ' != ' + str(var2) return ans '\ndef getOpDesc(text):\n text = text.upper()\n args = getArgs(text)\n opcode = getOpcode(text)\n if opcode == "add" or opcode == "vadd.f32" or opcode == "vadd.f64":\n print(str(args[0]) + " = " + str(args[1]) + " + " + str(args[2]))\n elif opcode == "sub":\n print(str(args[0]) + " = " + str(args[1]) + " - " + str(args[2]))\n elif opcode == "rsb":\n print(str(args[0]) + " = " + str(args[2]) + " - " + str(args[1]))\n elif opcode == "and":\n print(str(args[0]) + " = " + str(args[1]) + " && " + str(args[2]))\n elif opcode == "orr":\n print(str(args[0]) + " = " + str(args[1]) + " || " + str(args[2]))\n elif opcode == "mov" or opcode == "vmov.f32":\n print(str(args[0]) + " = " + str(args[1]))\n elif opcode == "str":\n print(str(args[1]) + " = " + str(args[0]))\n elif opcode == "ldr":\n print("int " + str(args[0]) + " = " + str(args[1]))\n elif opcode == "vldr.32":\n print("float " + str(args[0]) + " = " + str(args[1]))\n elif opcode == "vldr.64":\n print("double " + str(args[0]) + " = " + str(args[1]))\n elif opcode == "ldrb":\n print("char " + str(args[0]) + " = " + str(args[1]))\n'
# coding: utf-8 """ Union-Find (Disjoint Set) https://en.wikipedia.org/wiki/Disjoint-set_data_structure """ class QuickFindUnionFind: def __init__(self, union_pairs=()): self.num_groups = 0 self.auto_increment_id = 1 self.element_groups = { # element: group_id, } for p, q in union_pairs: self.union(p, q) def __len__(self): return self.num_groups # O(1) def make_group(self, element): # Initially, every element is in its own group which contains only itself. group_id = self.element_groups.get(element) if group_id is None: # Group id could be arbitrary as long as each group has an unique one. group_id = self.auto_increment_id self.element_groups[element] = group_id self.num_groups += 1 self.auto_increment_id += 1 return group_id # O(1) def find(self, p): try: return self.element_groups[p] except KeyError: # We implicitly create a new group for the new element `p`. return self.make_group(p) # O(n) def union(self, p, q): p_group_id = self.find(p) q_group_id = self.find(q) if p_group_id != q_group_id: for element, group_id in self.element_groups.items(): # Merge p into q. if group_id == p_group_id: self.element_groups[element] = q_group_id self.num_groups -= 1 # O(1) def is_connected(self, p, q): return self.find(p) == self.find(q)
""" Union-Find (Disjoint Set) https://en.wikipedia.org/wiki/Disjoint-set_data_structure """ class Quickfindunionfind: def __init__(self, union_pairs=()): self.num_groups = 0 self.auto_increment_id = 1 self.element_groups = {} for (p, q) in union_pairs: self.union(p, q) def __len__(self): return self.num_groups def make_group(self, element): group_id = self.element_groups.get(element) if group_id is None: group_id = self.auto_increment_id self.element_groups[element] = group_id self.num_groups += 1 self.auto_increment_id += 1 return group_id def find(self, p): try: return self.element_groups[p] except KeyError: return self.make_group(p) def union(self, p, q): p_group_id = self.find(p) q_group_id = self.find(q) if p_group_id != q_group_id: for (element, group_id) in self.element_groups.items(): if group_id == p_group_id: self.element_groups[element] = q_group_id self.num_groups -= 1 def is_connected(self, p, q): return self.find(p) == self.find(q)
class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ if not nums: return None i = len(nums)-1 j = -1 # j is set to -1 for case `4321`, so need to reverse all in following step while i > 0: if nums[i-1] < nums[i]: # first one violates the trend j = i-1 break i-=1 for i in xrange(len(nums)-1, -1, -1): if nums[i] > nums[j]: # nums[i], nums[j] = nums[j], nums[i] # swap position nums[j+1:] = sorted(nums[j+1:]) # sort rest return
class Solution(object): def next_permutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ if not nums: return None i = len(nums) - 1 j = -1 while i > 0: if nums[i - 1] < nums[i]: j = i - 1 break i -= 1 for i in xrange(len(nums) - 1, -1, -1): if nums[i] > nums[j]: (nums[i], nums[j]) = (nums[j], nums[i]) nums[j + 1:] = sorted(nums[j + 1:]) return
def sort_data_by_cumulus(data): """ Sort data by submitted_by field, which holds the cumulus number (or id), Parameters: data (list): A list containing the report data. Returns: (dict): A dict containg the data sorted by the cumulus id. """ sorted_data = {} for d in data: if d["user"] not in sorted_data: sorted_data[d["user"]] = [] sorted_data[d["user"]].append(d) else: sorted_data[d["user"]].append(d) return sorted_data
def sort_data_by_cumulus(data): """ Sort data by submitted_by field, which holds the cumulus number (or id), Parameters: data (list): A list containing the report data. Returns: (dict): A dict containg the data sorted by the cumulus id. """ sorted_data = {} for d in data: if d['user'] not in sorted_data: sorted_data[d['user']] = [] sorted_data[d['user']].append(d) else: sorted_data[d['user']].append(d) return sorted_data
# -*- coding: utf-8 -*- # Copyright (C) 2017 Intel Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Group(object): def __init__(self, name): self.name = name self.__attributes = {} def equals(self, obj): return self.name == obj.get_name() def get_attribute(self, key): return self._attributes[key] def get_device_members(self): devices = [] all_devices = IAgentManager.getInstance().get_all_devices() for device in all_devices: if self.name in device.get_groups(): devices.append(device) return devices def get_name(self): return self.name def get_resource_members(self): resources = [] all_devices = IAgentManager.getInstance().get_all_devices() for device in all_devices: resources_device = device.get_resources() for resource in resource_device: if self.name in resource.get_groups: resources.append(resource) return resources def hash_code(self): return hash(self.name)
class Group(object): def __init__(self, name): self.name = name self.__attributes = {} def equals(self, obj): return self.name == obj.get_name() def get_attribute(self, key): return self._attributes[key] def get_device_members(self): devices = [] all_devices = IAgentManager.getInstance().get_all_devices() for device in all_devices: if self.name in device.get_groups(): devices.append(device) return devices def get_name(self): return self.name def get_resource_members(self): resources = [] all_devices = IAgentManager.getInstance().get_all_devices() for device in all_devices: resources_device = device.get_resources() for resource in resource_device: if self.name in resource.get_groups: resources.append(resource) return resources def hash_code(self): return hash(self.name)
""" Configuration file """ class Config: """ Base Configuration """ DEBUG = True SECRET_KEY = r'f\x13\xd9fM\xdc\x82\x01b\xdb\x03' SQLALCHEMY_POOL_SIZE = 5 SQLALCHEMY_POOL_TIMEOUT = 120 SQLALCHEMY_POOL_RECYCLE = 280 MAIL_SERVER = 'smtp.gmail.com' MAIL_PORT = 465 MAIL_USERNAME = r'[email protected]' MAIL_PASSWORD = r'Reset@123' MAIL_USE_TLS = False MAIL_USE_SSL = True FTP_SERVER = 'aigbusiness.in' FTP_USER = '[email protected]' FTP_PASSWORD = 'policy123' class DevelopmentConfig(Config): """ Local Development """ DEBUG = True SQLALCHEMY_DATABASE_URI = 'mysql://[email protected]/aig_docs' class ProductionConfig(Config): """ Production configurations """ DEBUG = False SQLALCHEMY_DATABASE_URI = 'mysql://root:maria@[email protected]/aig_docs' app_config = { 'development': DevelopmentConfig, 'production': ProductionConfig }
""" Configuration file """ class Config: """ Base Configuration """ debug = True secret_key = 'f\\x13\\xd9fM\\xdc\\x82\\x01b\\xdb\\x03' sqlalchemy_pool_size = 5 sqlalchemy_pool_timeout = 120 sqlalchemy_pool_recycle = 280 mail_server = 'smtp.gmail.com' mail_port = 465 mail_username = '[email protected]' mail_password = 'Reset@123' mail_use_tls = False mail_use_ssl = True ftp_server = 'aigbusiness.in' ftp_user = '[email protected]' ftp_password = 'policy123' class Developmentconfig(Config): """ Local Development """ debug = True sqlalchemy_database_uri = 'mysql://[email protected]/aig_docs' class Productionconfig(Config): """ Production configurations """ debug = False sqlalchemy_database_uri = 'mysql://root:maria@[email protected]/aig_docs' app_config = {'development': DevelopmentConfig, 'production': ProductionConfig}
# -*- coding:utf-8 -*- # https://leetcode.com/problems/permutation-sequence/description/ class Solution(object): def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ factorial = [1] for i in range(1, n): factorial.append(i * factorial[-1]) num = [i for i in range(1, n + 1)] ret = [] for i in range(n - 1, -1, -1): m = factorial[i] ret.append(num.pop((k - 1) / m)) k = ((k - 1) % m) + 1 return ''.join(map(str, ret))
class Solution(object): def get_permutation(self, n, k): """ :type n: int :type k: int :rtype: str """ factorial = [1] for i in range(1, n): factorial.append(i * factorial[-1]) num = [i for i in range(1, n + 1)] ret = [] for i in range(n - 1, -1, -1): m = factorial[i] ret.append(num.pop((k - 1) / m)) k = (k - 1) % m + 1 return ''.join(map(str, ret))
datasetDir = '../dataset/' model = '../model/lenet' modelDir = '../model/' epochs = 20 batchSize = 128 rate = 0.001 mu = 0 sigma = 0.1
dataset_dir = '../dataset/' model = '../model/lenet' model_dir = '../model/' epochs = 20 batch_size = 128 rate = 0.001 mu = 0 sigma = 0.1
"""A board is a list of list of str. For example, the board ANTT XSOB is represented as the list [['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']] A word list is a list of str. For example, the list of words ANT BOX SOB TO is represented as the list ['ANT', 'BOX', 'SOB', 'TO'] """ def is_valid_word(wordlist, word): """ (list of str, str) -> bool Return True if and only if word is an element of wordlist. >>> is_valid_word(['ANT', 'BOX', 'SOB', 'TO'], 'TO') True """ return word in wordlist def make_str_from_row(board, row_index): """ (list of list of str, int) -> str Return the characters from the row of the board with index row_index as a single string. >>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0) 'ANTT' """ str_row = '' i=0 for i in range(len(board[row_index])): str_row = str_row+board[row_index[i]] i = i+1 return str_row def make_str_from_column(board, column_index): """ (list of list of str, int) -> str Return the characters from the column of the board with index column_index as a single string. >>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 1) 'NS' """ str_col='' for strList in board: str_col += strList[column_index] return str_col def board_contains_word_in_row(board, word): """ (list of list of str, str) -> bool Return True if and only if one or more of the rows of the board contains word. Precondition: board has at least one row and one column, and word is a valid word. >>> board_contains_word_in_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'SOB') True """ for row_index in range(len(board)): if word in make_str_from_row(board, row_index): return True return False def board_contains_word_in_column(board, word): """ (list of list of str, str) -> bool Return True if and only if one or more of the columns of the board contains word. Precondition: board has at least one row and one column, and word is a valid word. >>> board_contains_word_in_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'NO') False """ for index in range(len(board)): myStr = make_str_from_column(board, index) if word in myStr: return True else: return False def board_contains_word(board, word): """ (list of list of str, str) -> bool Return True if and only if word appears in board. Precondition: board has at least one row and one column. >>> board_contains_word([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'ANT') True """ return (board_contains_word_in_row(board, word) or board_contains_word_in_column(board, word)) def word_score(word): """ (str) -> int Return the point value the word earns. Word length: < 3: 0 points 3-6: 1 point per character for all characters in word 7-9: 2 points per character for all characters in word 10+: 3 points per character for all characters in word >>> word_score('DRUDGERY') 16 """ if len(word) < 3: return 0 elif len(word) <7: return 1 elif len(word) < 10: return 2 else: return 3 def update_score(player_info, word): """ ([str, int] list, str) -> NoneType player_info is a list with the player's name and score. Update player_info by adding the point value word earns to the player's score. >>> update_score(['Jonathan', 4], 'ANT') """ player_info[1] += word_score(word) def num_words_on_board(board, words): """ (list of list of str, list of str) -> int Return how many words appear on board. >>> num_words_on_board([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], ['ANT', 'BOX', 'SOB', 'TO']) 3 """ count=0 for word in words: if board_contains_word(board, word): count +=1 return count def read_words(words_file): """ (file open for reading) -> list of str Return a list of all words (with newlines removed) from open file words_file. Precondition: Each line of the file contains a word in uppercase characters from the standard English alphabet. """ f = open(words_file) myList = [] for line in f.readlines(): myList.append(line[0:len(line)-1]) f.close() return myList def read_board(board_file): """ (file open for reading) -> list of list of str Return a board read from open file board_file. The board file will contain one row of the board per line. Newlines are not included in the board. """ f = open(board_file) myList = [] for word in f.readlines(): word = word[0:len(word) - 1] tempList = [] for letter in word: tempList.append(letter) myList.append(tempList) f.close() return myList
"""A board is a list of list of str. For example, the board ANTT XSOB is represented as the list [['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']] A word list is a list of str. For example, the list of words ANT BOX SOB TO is represented as the list ['ANT', 'BOX', 'SOB', 'TO'] """ def is_valid_word(wordlist, word): """ (list of str, str) -> bool Return True if and only if word is an element of wordlist. >>> is_valid_word(['ANT', 'BOX', 'SOB', 'TO'], 'TO') True """ return word in wordlist def make_str_from_row(board, row_index): """ (list of list of str, int) -> str Return the characters from the row of the board with index row_index as a single string. >>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0) 'ANTT' """ str_row = '' i = 0 for i in range(len(board[row_index])): str_row = str_row + board[row_index[i]] i = i + 1 return str_row def make_str_from_column(board, column_index): """ (list of list of str, int) -> str Return the characters from the column of the board with index column_index as a single string. >>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 1) 'NS' """ str_col = '' for str_list in board: str_col += strList[column_index] return str_col def board_contains_word_in_row(board, word): """ (list of list of str, str) -> bool Return True if and only if one or more of the rows of the board contains word. Precondition: board has at least one row and one column, and word is a valid word. >>> board_contains_word_in_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'SOB') True """ for row_index in range(len(board)): if word in make_str_from_row(board, row_index): return True return False def board_contains_word_in_column(board, word): """ (list of list of str, str) -> bool Return True if and only if one or more of the columns of the board contains word. Precondition: board has at least one row and one column, and word is a valid word. >>> board_contains_word_in_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'NO') False """ for index in range(len(board)): my_str = make_str_from_column(board, index) if word in myStr: return True else: return False def board_contains_word(board, word): """ (list of list of str, str) -> bool Return True if and only if word appears in board. Precondition: board has at least one row and one column. >>> board_contains_word([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'ANT') True """ return board_contains_word_in_row(board, word) or board_contains_word_in_column(board, word) def word_score(word): """ (str) -> int Return the point value the word earns. Word length: < 3: 0 points 3-6: 1 point per character for all characters in word 7-9: 2 points per character for all characters in word 10+: 3 points per character for all characters in word >>> word_score('DRUDGERY') 16 """ if len(word) < 3: return 0 elif len(word) < 7: return 1 elif len(word) < 10: return 2 else: return 3 def update_score(player_info, word): """ ([str, int] list, str) -> NoneType player_info is a list with the player's name and score. Update player_info by adding the point value word earns to the player's score. >>> update_score(['Jonathan', 4], 'ANT') """ player_info[1] += word_score(word) def num_words_on_board(board, words): """ (list of list of str, list of str) -> int Return how many words appear on board. >>> num_words_on_board([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], ['ANT', 'BOX', 'SOB', 'TO']) 3 """ count = 0 for word in words: if board_contains_word(board, word): count += 1 return count def read_words(words_file): """ (file open for reading) -> list of str Return a list of all words (with newlines removed) from open file words_file. Precondition: Each line of the file contains a word in uppercase characters from the standard English alphabet. """ f = open(words_file) my_list = [] for line in f.readlines(): myList.append(line[0:len(line) - 1]) f.close() return myList def read_board(board_file): """ (file open for reading) -> list of list of str Return a board read from open file board_file. The board file will contain one row of the board per line. Newlines are not included in the board. """ f = open(board_file) my_list = [] for word in f.readlines(): word = word[0:len(word) - 1] temp_list = [] for letter in word: tempList.append(letter) myList.append(tempList) f.close() return myList
# flake8: noqa _JULIA_V1 = { "$schema": "http://json-schema.org/draft-04/schema#", "title": "PythonRuntimeMetadata v1.0", "description": "PythonRuntimeMetadata runtime/metadata.json schema.", "type": "object", "properties": { "metadata_version": { "description": "The metadata version.", "type": "string" }, "implementation": { "description": "The implementation (e.g. cpython)", "type": "string" }, "version": { "description": "The implementation version, e.g. pypy 2.6.1 would report 2.6.1 as the 'upstream' part.", "type": "string" }, "abi": { "description": "The runtime's ABI, e.g. 'msvc2008' or 'gnu'.", "type": "string" }, "language_version": { "description": "This is the 'language' version, e.g. pypy 2.6.1 would report 2.7.10 here.", "type": "string" }, "platform": { "description": ("The platform string (as can be parsed by" "EPDPlatform.from_epd_string"), "type": "string" }, "build_revision": { "description": "Build revision (internal only).", "type": "string", }, "executable": { "description": "The full path to the actual runtime executable.", "type": "string", }, "paths": { "description": "The list of path to have access to this runtime.", "type": "array", "items": {"type": "string"}, }, "post_install": { "description": ("The command (as a list) to execute after " "installation."), "type": "array", "items": {"type": "string"}, }, }, "required": [ "metadata_version", "implementation", "version", "abi", "language_version", "platform", "build_revision", "executable", "paths", "post_install", ] } _PYTHON_V1 = { "$schema": "http://json-schema.org/draft-04/schema#", "title": "PythonRuntimeMetadata v1.0", "description": "PythonRuntimeMetadata runtime/metadata.json schema.", "type": "object", "properties": { "metadata_version": { "description": "The metadata version.", "type": "string" }, "implementation": { "description": "The implementation (e.g. cpython)", "type": "string" }, "version": { "description": "The implementation version, e.g. pypy 2.6.1 would report 2.6.1 as the 'upstream' part.", "type": "string" }, "abi": { "description": "The runtime's ABI, e.g. 'msvc2008' or 'gnu'.", "type": "string" }, "language_version": { "description": "This is the 'language' version, e.g. pypy 2.6.1 would report 2.7.10 here.", "type": "string" }, "platform": { "description": ("The platform string (as can be parsed by" "EPDPlatform.from_epd_string"), "type": "string" }, "build_revision": { "description": "Build revision (internal only).", "type": "string", }, "executable": { "description": "The full path to the actual runtime executable.", "type": "string", }, "paths": { "description": "The list of path to have access to this runtime.", "type": "array", "items": {"type": "string"}, }, "post_install": { "description": ("The command (as a list) to execute after " "installation."), "type": "array", "items": {"type": "string"}, }, "scriptsdir": { "description": "Full path to scripts directory.", "type": "string", }, "site_packages": { "description": "The full path to the python site packages.", "type": "string", }, "python_tag": { "description": "The python tag, as defined in PEP 425.", "type": "string", }, }, "required": [ "metadata_version", "implementation", "version", "abi", "language_version", "platform", "build_revision", "executable", "paths", "post_install", "scriptsdir", "site_packages", "python_tag", ] }
_julia_v1 = {'$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'PythonRuntimeMetadata v1.0', 'description': 'PythonRuntimeMetadata runtime/metadata.json schema.', 'type': 'object', 'properties': {'metadata_version': {'description': 'The metadata version.', 'type': 'string'}, 'implementation': {'description': 'The implementation (e.g. cpython)', 'type': 'string'}, 'version': {'description': "The implementation version, e.g. pypy 2.6.1 would report 2.6.1 as the 'upstream' part.", 'type': 'string'}, 'abi': {'description': "The runtime's ABI, e.g. 'msvc2008' or 'gnu'.", 'type': 'string'}, 'language_version': {'description': "This is the 'language' version, e.g. pypy 2.6.1 would report 2.7.10 here.", 'type': 'string'}, 'platform': {'description': 'The platform string (as can be parsed byEPDPlatform.from_epd_string', 'type': 'string'}, 'build_revision': {'description': 'Build revision (internal only).', 'type': 'string'}, 'executable': {'description': 'The full path to the actual runtime executable.', 'type': 'string'}, 'paths': {'description': 'The list of path to have access to this runtime.', 'type': 'array', 'items': {'type': 'string'}}, 'post_install': {'description': 'The command (as a list) to execute after installation.', 'type': 'array', 'items': {'type': 'string'}}}, 'required': ['metadata_version', 'implementation', 'version', 'abi', 'language_version', 'platform', 'build_revision', 'executable', 'paths', 'post_install']} _python_v1 = {'$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'PythonRuntimeMetadata v1.0', 'description': 'PythonRuntimeMetadata runtime/metadata.json schema.', 'type': 'object', 'properties': {'metadata_version': {'description': 'The metadata version.', 'type': 'string'}, 'implementation': {'description': 'The implementation (e.g. cpython)', 'type': 'string'}, 'version': {'description': "The implementation version, e.g. pypy 2.6.1 would report 2.6.1 as the 'upstream' part.", 'type': 'string'}, 'abi': {'description': "The runtime's ABI, e.g. 'msvc2008' or 'gnu'.", 'type': 'string'}, 'language_version': {'description': "This is the 'language' version, e.g. pypy 2.6.1 would report 2.7.10 here.", 'type': 'string'}, 'platform': {'description': 'The platform string (as can be parsed byEPDPlatform.from_epd_string', 'type': 'string'}, 'build_revision': {'description': 'Build revision (internal only).', 'type': 'string'}, 'executable': {'description': 'The full path to the actual runtime executable.', 'type': 'string'}, 'paths': {'description': 'The list of path to have access to this runtime.', 'type': 'array', 'items': {'type': 'string'}}, 'post_install': {'description': 'The command (as a list) to execute after installation.', 'type': 'array', 'items': {'type': 'string'}}, 'scriptsdir': {'description': 'Full path to scripts directory.', 'type': 'string'}, 'site_packages': {'description': 'The full path to the python site packages.', 'type': 'string'}, 'python_tag': {'description': 'The python tag, as defined in PEP 425.', 'type': 'string'}}, 'required': ['metadata_version', 'implementation', 'version', 'abi', 'language_version', 'platform', 'build_revision', 'executable', 'paths', 'post_install', 'scriptsdir', 'site_packages', 'python_tag']}
# Copyright 2009 Moyshe BenRabi # # 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. # # This is always generated file. Do not edit directyly. # Instead edit messagegen.pl and descr.txt class ProgramFragment(object): def __init__(self): self.max_program_name = 25 self.program_name = '' self.program_major_version = 0 self.program_minor_version = 0 self.protocol_major_version = 0 self.protocol_minor_version = 0 self.protocol_source_revision = 0 def clear(self): self.program_name = '' self.program_major_version = 0 self.program_minor_version = 0 self.protocol_major_version = 0 self.protocol_minor_version = 0 self.protocol_source_revision = 0 super(ProgramFragment,self).clear() def frame_data_size(self, frame_index): result = 0 result += 1 result += 1 result += 1 result += 1 result += 4 return result def serialize(self, writer): writer.writeRange(self.program_name,self.max_program_name,'chr') writer.write(self.program_major_version,'byte') writer.write(self.program_minor_version,'byte') writer.write(self.protocol_major_version,'byte') writer.write(self.protocol_minor_version,'byte') writer.write(self.protocol_source_revision,'uint') def deserialize(self, reader): (self.program_name, c) = reader.readRange(self.max_program_name,'chr',1) (self.program_major_version, c) = reader.read('byte') (self.program_minor_version, c) = reader.read('byte') (self.protocol_major_version, c) = reader.read('byte') (self.protocol_minor_version, c) = reader.read('byte') (self.protocol_source_revision, c) = reader.read('uint') def __str__(self): return 'ProgramFragment('+self.program_name \ + str(self.program_major_version) \ + str(self.program_minor_version) \ + str(self.protocol_major_version) \ + str(self.protocol_minor_version) \ + str(self.protocol_source_revision)+')' def __eq__(self,other): return True and \ (self.program_name == other.program_name) and \ self.program_major_version == other.program_major_version and \ self.program_minor_version == other.program_minor_version and \ self.protocol_major_version == other.protocol_major_version and \ self.protocol_minor_version == other.protocol_minor_version and \ self.protocol_source_revision == other.protocol_source_revision def __ne__(self,other): return True or \ (self.program_name != other.program_name) or \ self.program_major_version != other.program_major_version or \ self.program_minor_version != other.program_minor_version or \ self.protocol_major_version != other.protocol_major_version or \ self.protocol_minor_version != other.protocol_minor_version or \ self.protocol_source_revision != other.protocol_source_revision
class Programfragment(object): def __init__(self): self.max_program_name = 25 self.program_name = '' self.program_major_version = 0 self.program_minor_version = 0 self.protocol_major_version = 0 self.protocol_minor_version = 0 self.protocol_source_revision = 0 def clear(self): self.program_name = '' self.program_major_version = 0 self.program_minor_version = 0 self.protocol_major_version = 0 self.protocol_minor_version = 0 self.protocol_source_revision = 0 super(ProgramFragment, self).clear() def frame_data_size(self, frame_index): result = 0 result += 1 result += 1 result += 1 result += 1 result += 4 return result def serialize(self, writer): writer.writeRange(self.program_name, self.max_program_name, 'chr') writer.write(self.program_major_version, 'byte') writer.write(self.program_minor_version, 'byte') writer.write(self.protocol_major_version, 'byte') writer.write(self.protocol_minor_version, 'byte') writer.write(self.protocol_source_revision, 'uint') def deserialize(self, reader): (self.program_name, c) = reader.readRange(self.max_program_name, 'chr', 1) (self.program_major_version, c) = reader.read('byte') (self.program_minor_version, c) = reader.read('byte') (self.protocol_major_version, c) = reader.read('byte') (self.protocol_minor_version, c) = reader.read('byte') (self.protocol_source_revision, c) = reader.read('uint') def __str__(self): return 'ProgramFragment(' + self.program_name + str(self.program_major_version) + str(self.program_minor_version) + str(self.protocol_major_version) + str(self.protocol_minor_version) + str(self.protocol_source_revision) + ')' def __eq__(self, other): return True and self.program_name == other.program_name and (self.program_major_version == other.program_major_version) and (self.program_minor_version == other.program_minor_version) and (self.protocol_major_version == other.protocol_major_version) and (self.protocol_minor_version == other.protocol_minor_version) and (self.protocol_source_revision == other.protocol_source_revision) def __ne__(self, other): return True or self.program_name != other.program_name or self.program_major_version != other.program_major_version or (self.program_minor_version != other.program_minor_version) or (self.protocol_major_version != other.protocol_major_version) or (self.protocol_minor_version != other.protocol_minor_version) or (self.protocol_source_revision != other.protocol_source_revision)
class Singleton: __instance = None @classmethod def __get_instance(cls): return cls.__instance @classmethod def instance(cls, *args, **kargs): cls.__instance = cls(*args, **kargs) cls.instance = cls.__get_instance return cls.__instance """"" class MyClass(BaseClass, Singleton): pass c = MyClass.instance() """""
class Singleton: __instance = None @classmethod def __get_instance(cls): return cls.__instance @classmethod def instance(cls, *args, **kargs): cls.__instance = cls(*args, **kargs) cls.instance = cls.__get_instance return cls.__instance '""\nclass MyClass(BaseClass, Singleton):\n pass\n\nc = MyClass.instance()\n'
test_cases = int(input()) for t in range(1, test_cases + 1): nums = list(map(int, input().strip().split())) result = [] for i in range(0, 5): for j in range(i + 1, 6): for k in range(j + 1, 7): result.append(nums[i] + nums[j] + nums[k]) result = sorted(list(set(result)), reverse=True) print('#{} {}'.format(t, result[4]))
test_cases = int(input()) for t in range(1, test_cases + 1): nums = list(map(int, input().strip().split())) result = [] for i in range(0, 5): for j in range(i + 1, 6): for k in range(j + 1, 7): result.append(nums[i] + nums[j] + nums[k]) result = sorted(list(set(result)), reverse=True) print('#{} {}'.format(t, result[4]))
# atomic level def get_idx(list, key): for idx in range(len(list)): if key == list[idx][0]: return idx def ins(list, key, val): list.append([key, val]) return list def ret(list, key): idx = get_idx(list, key) return list[idx][1] def upd(list, key, val): new_item = [key.lower(), val] idx = get_idx(list, key) list[idx] = new_item return list def delete(list, key): idx = get_idx(list, key) list.remove(idx) return list # table level def ins_tab(db, table_name): return ins(db, table_name, []) def ret_tab(db, table_name): return ret(db, table_name) def upd_tab(db, table_name, table): return upd(db, table_name, table) def del_tab(db, table_name): return delete(db, table_name) # record level def is_member(record, kv, check_value): if len(kv) == 0: return True else: for item in record: if item[0] == kv[0]: if check_value: if item[1] == kv[1]: return True else: return True return False def kvs_in_rec(record, kv_list): # all kv's of kv_list_search are members of record for kv in kv_list: if not is_member(record, kv, True): return False return True def ins_rec(db, table_name, kv_list): table = ret(db, table_name) table.append(kv_list) return upd(db, table_name, table) def ret_recs(db, table_name, kv_list): list = [] table = ret(db, table_name) for record in table: if kvs_in_rec(record, kv_list): list.append(record) return list def ret_rec_idx(db, table_name, record_idx): table = ret(db, table_name) if len(table) >= record_idx: return table[record_idx] else: return None def upd_recs(db, table_name, kv_list_search, kv_list_upd): # updates all records identified by kv_list_search new_table = [] old_table = ret_tab(db, table_name) for old_rec in old_table: if kvs_in_rec(old_rec, kv_list_search): # matching record new_rec = old_rec for kv in kv_list_upd: # if kv is member of record, update value of kv, # otherwise insert entire kv key = kv[0] val = kv[1] if is_member(new_rec, kv, False): new_rec = upd(new_rec, key, val) else: new_rec = ins(new_rec, key, val) new_table.append(new_rec) else: new_table.append(old_rec) return upd(db, table_name, new_table) def del_recs(db, table_name, kv_list): new_table = [] old_table = ret_tab(db, table_name) for record in old_table: if not kvs_in_rec(record, kv_list): new_table.append(record) return upd(db, table_name, new_table) def del_all(db, table_name): table = [] return upd(db, table_name, table) # value level def ret_val(db, table_name, record_id_key, record_id_value, data_key): # assumes [record_id_key, record_id_value] identifies a single record records = ret_recs(db, table_name, [[record_id_key, record_id_value]]) if len(records) == 0: return None else: return ret(records[0], data_key) def ret_val_idx(db, table_name, record_idx, data_key): record = ret_rec_idx(db, table_name, record_idx) if record: return ret(record, data_key) else: return None def upd_val(db, table_name, record_id_key, record_id_val, data_key, data_val): # updates all records identified by [record_id_key, record_id_value] return upd_recs(db, table_name, [[record_id_key, record_id_val]], [[data_key, data_val]]) # summary def rec_cnt(db, table_name, kv_list): records = ret_recs(db, table_name, kv_list) return len(records) def rec_list(db, table_name, key): list = [] table = ret_tab(db, table_name) for record in table: for item in record: if item[0].lower() == key.lower(): if not item[1] in list: list.append(item[1]) return list
def get_idx(list, key): for idx in range(len(list)): if key == list[idx][0]: return idx def ins(list, key, val): list.append([key, val]) return list def ret(list, key): idx = get_idx(list, key) return list[idx][1] def upd(list, key, val): new_item = [key.lower(), val] idx = get_idx(list, key) list[idx] = new_item return list def delete(list, key): idx = get_idx(list, key) list.remove(idx) return list def ins_tab(db, table_name): return ins(db, table_name, []) def ret_tab(db, table_name): return ret(db, table_name) def upd_tab(db, table_name, table): return upd(db, table_name, table) def del_tab(db, table_name): return delete(db, table_name) def is_member(record, kv, check_value): if len(kv) == 0: return True else: for item in record: if item[0] == kv[0]: if check_value: if item[1] == kv[1]: return True else: return True return False def kvs_in_rec(record, kv_list): for kv in kv_list: if not is_member(record, kv, True): return False return True def ins_rec(db, table_name, kv_list): table = ret(db, table_name) table.append(kv_list) return upd(db, table_name, table) def ret_recs(db, table_name, kv_list): list = [] table = ret(db, table_name) for record in table: if kvs_in_rec(record, kv_list): list.append(record) return list def ret_rec_idx(db, table_name, record_idx): table = ret(db, table_name) if len(table) >= record_idx: return table[record_idx] else: return None def upd_recs(db, table_name, kv_list_search, kv_list_upd): new_table = [] old_table = ret_tab(db, table_name) for old_rec in old_table: if kvs_in_rec(old_rec, kv_list_search): new_rec = old_rec for kv in kv_list_upd: key = kv[0] val = kv[1] if is_member(new_rec, kv, False): new_rec = upd(new_rec, key, val) else: new_rec = ins(new_rec, key, val) new_table.append(new_rec) else: new_table.append(old_rec) return upd(db, table_name, new_table) def del_recs(db, table_name, kv_list): new_table = [] old_table = ret_tab(db, table_name) for record in old_table: if not kvs_in_rec(record, kv_list): new_table.append(record) return upd(db, table_name, new_table) def del_all(db, table_name): table = [] return upd(db, table_name, table) def ret_val(db, table_name, record_id_key, record_id_value, data_key): records = ret_recs(db, table_name, [[record_id_key, record_id_value]]) if len(records) == 0: return None else: return ret(records[0], data_key) def ret_val_idx(db, table_name, record_idx, data_key): record = ret_rec_idx(db, table_name, record_idx) if record: return ret(record, data_key) else: return None def upd_val(db, table_name, record_id_key, record_id_val, data_key, data_val): return upd_recs(db, table_name, [[record_id_key, record_id_val]], [[data_key, data_val]]) def rec_cnt(db, table_name, kv_list): records = ret_recs(db, table_name, kv_list) return len(records) def rec_list(db, table_name, key): list = [] table = ret_tab(db, table_name) for record in table: for item in record: if item[0].lower() == key.lower(): if not item[1] in list: list.append(item[1]) return list
class Example: def __init__(self): self.name = "" pass def greet(self, name): self.name = name print("hello " + name)
class Example: def __init__(self): self.name = '' pass def greet(self, name): self.name = name print('hello ' + name)
class Solution(object): def longestValidParentheses(self, s): """ :type s: str :rtype: int """ i = 0 maxlen = 0 self.longest = {} while i < len(s): if s[i] == ")": i = i + 1 continue else: l = self.find_longest(i, s) if l - i + 1 > maxlen: maxlen = l - i + 1 i = l + 1 return maxlen def find_longest(self, i, s): if i in self.longest: return self.longest[i] start = balance = i left = 0 right = 0 while True: if i >= len(s): self.longest[start] = balance return balance if s[i] == "(": left += 1 else: right += 1 if left < right: self.longest[start] = balance return balance if left == right: balance = i i = i + 1
class Solution(object): def longest_valid_parentheses(self, s): """ :type s: str :rtype: int """ i = 0 maxlen = 0 self.longest = {} while i < len(s): if s[i] == ')': i = i + 1 continue else: l = self.find_longest(i, s) if l - i + 1 > maxlen: maxlen = l - i + 1 i = l + 1 return maxlen def find_longest(self, i, s): if i in self.longest: return self.longest[i] start = balance = i left = 0 right = 0 while True: if i >= len(s): self.longest[start] = balance return balance if s[i] == '(': left += 1 else: right += 1 if left < right: self.longest[start] = balance return balance if left == right: balance = i i = i + 1
#!/usr/bin/env python3 visited = set() visited.add((0, 0)) turn = 0 # Santa = 0, Robo-Santa = 1 locations = [[0, 0], [0, 0]] with open('input.txt', 'r') as f: for line in f: for ch in line: pos = locations[turn] turn = (turn + 1) % 2 if ch == '^': pos[0] += 1 elif ch == 'v': pos[0] -= 1 elif ch == '<': pos[1] -= 1 elif ch == '>': pos[1] += 1 visited.add(tuple(pos)) print("Total houses", len(visited))
visited = set() visited.add((0, 0)) turn = 0 locations = [[0, 0], [0, 0]] with open('input.txt', 'r') as f: for line in f: for ch in line: pos = locations[turn] turn = (turn + 1) % 2 if ch == '^': pos[0] += 1 elif ch == 'v': pos[0] -= 1 elif ch == '<': pos[1] -= 1 elif ch == '>': pos[1] += 1 visited.add(tuple(pos)) print('Total houses', len(visited))
# import pytest class TestBaseReplacerMixin: def test_target(self): # synced assert True def test_write(self): # synced assert True def test_flush(self): # synced assert True def test_close(self): # synced assert True class TestStdOutReplacerMixin: def test_target(self): # synced assert True class TestStdErrReplacerMixin: def test_target(self): # synced assert True class TestStdOutFileRedirector: def test___str__(self): # synced assert True def test_write(self): # synced assert True class TestBaseStreamRedirector: def test___str__(self): # synced assert True def test_write(self): # synced assert True def test_flush(self): # synced assert True def test_close(self): # synced assert True class TestStdOutStreamRedirector: pass class TestStdErrStreamRedirector: pass class TestSupressor: def test_write(self): # synced assert True
class Testbasereplacermixin: def test_target(self): assert True def test_write(self): assert True def test_flush(self): assert True def test_close(self): assert True class Teststdoutreplacermixin: def test_target(self): assert True class Teststderrreplacermixin: def test_target(self): assert True class Teststdoutfileredirector: def test___str__(self): assert True def test_write(self): assert True class Testbasestreamredirector: def test___str__(self): assert True def test_write(self): assert True def test_flush(self): assert True def test_close(self): assert True class Teststdoutstreamredirector: pass class Teststderrstreamredirector: pass class Testsupressor: def test_write(self): assert True
# coding: utf8 db.define_table('post', Field('Email',requires=IS_EMAIL()), Field('filen','upload'), auth.signature)
db.define_table('post', field('Email', requires=is_email()), field('filen', 'upload'), auth.signature)
class Solution: def dfs(self,row_cnt:int, col_cnt:int, i:int, j:int, obs_arr:list, solve_dict:dict): if (i, j) in solve_dict: return solve_dict[(i,j)] right_cnt = 0 down_cnt = 0 #right if i + 1 < row_cnt and not obs_arr[i + 1][j]: if (i + 1, j) in solve_dict: right_cnt = solve_dict[(i + 1, j)] else: right_cnt = self.dfs(row_cnt, col_cnt,i + 1, j,obs_arr,solve_dict) #left if j + 1 < col_cnt and not obs_arr[i][j + 1]: if (i, j + 1) in solve_dict: down_cnt = solve_dict[(i, j + 1)] else: down_cnt = self.dfs(row_cnt, col_cnt, i, j + 1,obs_arr, solve_dict) res = right_cnt + down_cnt solve_dict[(i, j)] = res return res def uniquePathsWithObstacles(self, obstacleGrid: list) -> int: row = len(obstacleGrid) if not row: return 0 col = len(obstacleGrid[0]) if not col: return 0 if obstacleGrid[row - 1][col - 1]: return 0 if obstacleGrid[0][0]: return 0 res = self.dfs(row,col,0,0,obstacleGrid, {(row-1, col - 1):1}) return res t1 = [ [0,0,0], [0,1,0], [0,0,0] ] sl = Solution() res = sl.uniquePathsWithObstacles(t1) print(res)
class Solution: def dfs(self, row_cnt: int, col_cnt: int, i: int, j: int, obs_arr: list, solve_dict: dict): if (i, j) in solve_dict: return solve_dict[i, j] right_cnt = 0 down_cnt = 0 if i + 1 < row_cnt and (not obs_arr[i + 1][j]): if (i + 1, j) in solve_dict: right_cnt = solve_dict[i + 1, j] else: right_cnt = self.dfs(row_cnt, col_cnt, i + 1, j, obs_arr, solve_dict) if j + 1 < col_cnt and (not obs_arr[i][j + 1]): if (i, j + 1) in solve_dict: down_cnt = solve_dict[i, j + 1] else: down_cnt = self.dfs(row_cnt, col_cnt, i, j + 1, obs_arr, solve_dict) res = right_cnt + down_cnt solve_dict[i, j] = res return res def unique_paths_with_obstacles(self, obstacleGrid: list) -> int: row = len(obstacleGrid) if not row: return 0 col = len(obstacleGrid[0]) if not col: return 0 if obstacleGrid[row - 1][col - 1]: return 0 if obstacleGrid[0][0]: return 0 res = self.dfs(row, col, 0, 0, obstacleGrid, {(row - 1, col - 1): 1}) return res t1 = [[0, 0, 0], [0, 1, 0], [0, 0, 0]] sl = solution() res = sl.uniquePathsWithObstacles(t1) print(res)
class MkDocsTyperException(Exception): """ Generic exception class for mkdocs-typer errors. """
class Mkdocstyperexception(Exception): """ Generic exception class for mkdocs-typer errors. """
dataset_type = 'ShipRSImageNet_Level2' # data_root = 'data/Ship_ImageNet/' data_root = './data/ShipRSImageNet/' CLASSES = ('Other Ship', 'Other Warship', 'Submarine', 'Aircraft Carrier', 'Cruiser', 'Destroyer', 'Frigate', 'Patrol', 'Landing', 'Commander', 'Auxiliary Ships', 'Other Merchant', 'Container Ship', 'RoRo', 'Cargo', 'Barge', 'Tugboat', 'Ferry', 'Yacht', 'Sailboat', 'Fishing Vessel', 'Oil Tanker', 'Hovercraft', 'Motorboat', 'Dock',) img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=8, workers_per_gpu=2, train=dict( type=dataset_type, classes=CLASSES, ann_file=data_root + 'COCO_Format/ShipRSImageNet_bbox_train_level_2.json', img_prefix=data_root + 'VOC_Format/JPEGImages/', pipeline=train_pipeline), val=dict( type=dataset_type, classes=CLASSES, ann_file=data_root + 'COCO_Format/ShipRSImageNet_bbox_val_level_2.json', img_prefix=data_root + 'VOC_Format/JPEGImages/', pipeline=test_pipeline), test=dict( type=dataset_type, classes=CLASSES, ann_file=data_root + 'COCO_Format/ShipRSImageNet_bbox_val_level_2.json', img_prefix=data_root + 'VOC_Format/JPEGImages/', pipeline=test_pipeline)) evaluation = dict(interval=10, metric='bbox')
dataset_type = 'ShipRSImageNet_Level2' data_root = './data/ShipRSImageNet/' classes = ('Other Ship', 'Other Warship', 'Submarine', 'Aircraft Carrier', 'Cruiser', 'Destroyer', 'Frigate', 'Patrol', 'Landing', 'Commander', 'Auxiliary Ships', 'Other Merchant', 'Container Ship', 'RoRo', 'Cargo', 'Barge', 'Tugboat', 'Ferry', 'Yacht', 'Sailboat', 'Fishing Vessel', 'Oil Tanker', 'Hovercraft', 'Motorboat', 'Dock') img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels'])] test_pipeline = [dict(type='LoadImageFromFile'), dict(type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img'])])] data = dict(samples_per_gpu=8, workers_per_gpu=2, train=dict(type=dataset_type, classes=CLASSES, ann_file=data_root + 'COCO_Format/ShipRSImageNet_bbox_train_level_2.json', img_prefix=data_root + 'VOC_Format/JPEGImages/', pipeline=train_pipeline), val=dict(type=dataset_type, classes=CLASSES, ann_file=data_root + 'COCO_Format/ShipRSImageNet_bbox_val_level_2.json', img_prefix=data_root + 'VOC_Format/JPEGImages/', pipeline=test_pipeline), test=dict(type=dataset_type, classes=CLASSES, ann_file=data_root + 'COCO_Format/ShipRSImageNet_bbox_val_level_2.json', img_prefix=data_root + 'VOC_Format/JPEGImages/', pipeline=test_pipeline)) evaluation = dict(interval=10, metric='bbox')
def dbapi_subscription(dbsession, action, input_dict, action_filter={}, caller_area={}): _api_name = "dbapi_subscription" _api_entity = 'SUBSCRIPTION' _api_action = action _api_msgID = set_msgID(_api_name, _api_action, _api_entity) _process_identity_kwargs = {'type': 'api', 'module': module_id, 'name': _api_name, 'action': _api_action, 'entity': _api_entity, 'msgID': _api_msgID,} _process_adapters_kwargs = {'dbsession': dbsession} _process_log_kwargs = {'indent_method': 'AUTO', 'indent_level':None} _process_debug_level = get_debug_level(caller_area.get('debug_level'), **_process_identity_kwargs, **_process_adapters_kwargs) _process_debug_files = get_debug_files(_process_debug_level, **_process_identity_kwargs, **_process_adapters_kwargs) _process_debug_kwargs={'debug_level':_process_debug_level,'debug_files':_process_debug_files} _process_signature = build_process_signature(**_process_identity_kwargs, **_process_adapters_kwargs, **_process_debug_kwargs, **_process_log_kwargs) _process_call_area = build_process_call_area(_process_signature, caller_area) log_process_start(_api_msgID,**_process_call_area) log_process_input('', 'input_dict', input_dict,**_process_call_area) log_process_input('', 'action_filter', action_filter,**_process_call_area) log_process_input('', 'caller_area', caller_area,**_process_call_area) input_dict.update({'client_type': 'subscriber'}) if action.upper() in ('REGISTER','ADD','REFRESH'): action='REFRESH' action_result = dbsession.table_action(dbmodel.CLIENT, action, input_dict, action_filter, auto_commit=True, caller_area=_process_call_area) api_result = action_result thismsg=action_result.get('api_message') api_result.update({'api_action': _api_action, 'api_name': _api_name}) if not api_result.get('api_status') == 'success': # msg = f"subscription not registered" # api_result.update({'api_message':msg}) log_process_finish(_api_msgID, api_result, **_process_call_area) return api_result client = api_result.get('api_data') client_id = client.get('client_id') input_dict.update({'client_id': client_id}) elif action.upper() in ('CONFIRM', 'ACTIVATE', 'DEACTIVATE', 'DELETE'): subscription_dict = dbsession.get(dbmodel.SUBSCRIPTION, input_dict, 'DICT', caller_area=_process_call_area) if not subscription_dict: msg = f'subscription not found' action_status='error' api_result = {'api_status': action_status, 'api_message': msg, 'api_data': input_dict, 'api_action': _api_action.upper(), 'api_name': _api_name} log_process_finish(_api_msgID, api_result, **_process_call_area) return api_result client_dict=dbsession.get(dbmodel.CLIENT, subscription_dict,'DICT', caller_area=_process_call_area) if not client_dict: msg = f'client not found' action_status='error' api_result = {'api_status': action_status, 'api_message': msg, 'api_data': subscription_dict, 'api_action': _api_action.upper(), 'api_name': _api_name} log_process_finish(_api_msgID, api_result, **_process_call_area) return api_result #action='CONFIRM' action_result = dbsession.table_action(dbmodel.CLIENT, action, input_dict, action_filter, auto_commit=True, caller_area=_process_call_area) api_result = action_result api_result.update({'api_action': _api_action, 'api_name': _api_name}) thismsg=action_result.get('api_message') if not api_result.get('api_status') == 'success': # msg = f'client confirmation failed' # api_result.update({'api_message':msg}) log_process_finish(_api_msgID, api_result, **_process_call_area) return api_result subscription_dict = dbsession.get(dbmodel.SUBSCRIPTION, subscription_dict, 'DICT', caller_area=_process_call_area) status=subscription_dict.get('status') client_id=subscription_dict.get('client_id') # if not subscription_dict.get('status') == 'Active': # msg = f"service provider not confirmed. status={status}" # action_status='error' # api_result = {'api_status': action_status, 'api_message': msg, 'api_data': subscription_dict, 'messages': messages, 'rows_added': rows_added, 'rows_updated': rows_updated, 'api_action': _api_action.upper(), 'api_name': _api_name} # log_process_finish(_api_msgID, api_result, **_process_call_area) # return api_result input_dict.update({'status': status}) input_dict.update({'client_id': client_id}) action_result = dbsession.table_action(dbmodel.SUBSCRIPTION, action, input_dict, action_filter, auto_commit=True, caller_area=_process_call_area) api_result = action_result thismsg=thismsg.replace('CLIENT',_api_entity) api_result.update({'api_action': _api_action, 'api_name': _api_name,'api_message':thismsg}) log_process_finish(_api_msgID, api_result, **_process_call_area) return api_result
def dbapi_subscription(dbsession, action, input_dict, action_filter={}, caller_area={}): _api_name = 'dbapi_subscription' _api_entity = 'SUBSCRIPTION' _api_action = action _api_msg_id = set_msg_id(_api_name, _api_action, _api_entity) _process_identity_kwargs = {'type': 'api', 'module': module_id, 'name': _api_name, 'action': _api_action, 'entity': _api_entity, 'msgID': _api_msgID} _process_adapters_kwargs = {'dbsession': dbsession} _process_log_kwargs = {'indent_method': 'AUTO', 'indent_level': None} _process_debug_level = get_debug_level(caller_area.get('debug_level'), **_process_identity_kwargs, **_process_adapters_kwargs) _process_debug_files = get_debug_files(_process_debug_level, **_process_identity_kwargs, **_process_adapters_kwargs) _process_debug_kwargs = {'debug_level': _process_debug_level, 'debug_files': _process_debug_files} _process_signature = build_process_signature(**_process_identity_kwargs, **_process_adapters_kwargs, **_process_debug_kwargs, **_process_log_kwargs) _process_call_area = build_process_call_area(_process_signature, caller_area) log_process_start(_api_msgID, **_process_call_area) log_process_input('', 'input_dict', input_dict, **_process_call_area) log_process_input('', 'action_filter', action_filter, **_process_call_area) log_process_input('', 'caller_area', caller_area, **_process_call_area) input_dict.update({'client_type': 'subscriber'}) if action.upper() in ('REGISTER', 'ADD', 'REFRESH'): action = 'REFRESH' action_result = dbsession.table_action(dbmodel.CLIENT, action, input_dict, action_filter, auto_commit=True, caller_area=_process_call_area) api_result = action_result thismsg = action_result.get('api_message') api_result.update({'api_action': _api_action, 'api_name': _api_name}) if not api_result.get('api_status') == 'success': log_process_finish(_api_msgID, api_result, **_process_call_area) return api_result client = api_result.get('api_data') client_id = client.get('client_id') input_dict.update({'client_id': client_id}) elif action.upper() in ('CONFIRM', 'ACTIVATE', 'DEACTIVATE', 'DELETE'): subscription_dict = dbsession.get(dbmodel.SUBSCRIPTION, input_dict, 'DICT', caller_area=_process_call_area) if not subscription_dict: msg = f'subscription not found' action_status = 'error' api_result = {'api_status': action_status, 'api_message': msg, 'api_data': input_dict, 'api_action': _api_action.upper(), 'api_name': _api_name} log_process_finish(_api_msgID, api_result, **_process_call_area) return api_result client_dict = dbsession.get(dbmodel.CLIENT, subscription_dict, 'DICT', caller_area=_process_call_area) if not client_dict: msg = f'client not found' action_status = 'error' api_result = {'api_status': action_status, 'api_message': msg, 'api_data': subscription_dict, 'api_action': _api_action.upper(), 'api_name': _api_name} log_process_finish(_api_msgID, api_result, **_process_call_area) return api_result action_result = dbsession.table_action(dbmodel.CLIENT, action, input_dict, action_filter, auto_commit=True, caller_area=_process_call_area) api_result = action_result api_result.update({'api_action': _api_action, 'api_name': _api_name}) thismsg = action_result.get('api_message') if not api_result.get('api_status') == 'success': log_process_finish(_api_msgID, api_result, **_process_call_area) return api_result subscription_dict = dbsession.get(dbmodel.SUBSCRIPTION, subscription_dict, 'DICT', caller_area=_process_call_area) status = subscription_dict.get('status') client_id = subscription_dict.get('client_id') input_dict.update({'status': status}) input_dict.update({'client_id': client_id}) action_result = dbsession.table_action(dbmodel.SUBSCRIPTION, action, input_dict, action_filter, auto_commit=True, caller_area=_process_call_area) api_result = action_result thismsg = thismsg.replace('CLIENT', _api_entity) api_result.update({'api_action': _api_action, 'api_name': _api_name, 'api_message': thismsg}) log_process_finish(_api_msgID, api_result, **_process_call_area) return api_result
def recursiveCalc(n, counter=0, steps=''): if n<10: steps += 'Total Steps: ' + str(counter) + '.' return steps, counter counter+=1 result = calc(n) steps += str(result)+', ' return recursiveCalc(result, counter, steps) def calc(n): result = 1 while (n>0): mod = n % 10 result *= mod n -= mod n /= 10 return result def printNumber(n, steps): print (str(n) + ': ' + steps) max = -1 bestNumbers = [] for i in range(1000000): result = recursiveCalc(i) if(result[1] > max): max = result[1] printNumber(i, result[0]) bestNumbers.append(i) print (bestNumbers)
def recursive_calc(n, counter=0, steps=''): if n < 10: steps += 'Total Steps: ' + str(counter) + '.' return (steps, counter) counter += 1 result = calc(n) steps += str(result) + ', ' return recursive_calc(result, counter, steps) def calc(n): result = 1 while n > 0: mod = n % 10 result *= mod n -= mod n /= 10 return result def print_number(n, steps): print(str(n) + ': ' + steps) max = -1 best_numbers = [] for i in range(1000000): result = recursive_calc(i) if result[1] > max: max = result[1] print_number(i, result[0]) bestNumbers.append(i) print(bestNumbers)
def ifPossible(a): while a%2==0: a/=2 return a test=int(input()) while test: a,b = input().split() a=int(a) b=int(b) if a>b: n=b b=a a=n num=ifPossible(b) ans=0 if num!=ifPossible(a): print("-1") else: b/=a while b>=8: b/=8 ans+=1 if b>1: ans+=1 print(ans) test-=1
def if_possible(a): while a % 2 == 0: a /= 2 return a test = int(input()) while test: (a, b) = input().split() a = int(a) b = int(b) if a > b: n = b b = a a = n num = if_possible(b) ans = 0 if num != if_possible(a): print('-1') else: b /= a while b >= 8: b /= 8 ans += 1 if b > 1: ans += 1 print(ans) test -= 1
#!/usr/bin/python3 class Student(): """Student class with name and age""" def __init__(self, first_name, last_name, age): """initializes new instance of Student""" self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): """returns dict attributes of Student""" if attrs is None: obj_dict = self.__dict__ return obj_dict else: o_D = self.__dict__ D = dict(([k, v] for k, v in o_D.items() if k in attrs)) return D def reload_from_json(self, json): """reloads Student instance from input dictionary""" for k, v in json.items(): setattr(self, k, v)
class Student: """Student class with name and age""" def __init__(self, first_name, last_name, age): """initializes new instance of Student""" self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): """returns dict attributes of Student""" if attrs is None: obj_dict = self.__dict__ return obj_dict else: o_d = self.__dict__ d = dict(([k, v] for (k, v) in o_D.items() if k in attrs)) return D def reload_from_json(self, json): """reloads Student instance from input dictionary""" for (k, v) in json.items(): setattr(self, k, v)
def bubble_sort(arr): swapped = True while swapped: swapped = False for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] swapped = True def selection_sort(arr): for i in range(len(arr)): minpos = i for j in range(i + 1, len(arr)): if arr[j] < arr[minpos]: minpos = j arr[i], arr[minpos] = arr[minpos], arr[i] def insertion_sort(arr): for i in range(1, len(arr)): current = arr[i] j = i - 1 while j >= 0 and arr[j] > current: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = current def merge_sort(array): def _merge(left_arr, right_arr): _summary = [0] * (len(left_arr) + len(right_arr)) li = ri = n = 0 while li < len(left_arr) and ri < len(right_arr): if left_arr[li] <= right_arr[ri]: _summary[n] = left_arr[li] li += 1 n += 1 else: _summary[n] = right_arr[ri] ri += 1 n += 1 while li < len(left_arr): _summary[n] = left_arr[li] li += 1 n += 1 while ri < len(right_arr): _summary[n] = right_arr[ri] ri += 1 n += 1 return _summary if len(array) <= 1: return middle = len(array) // 2 left_array = [array[i] for i in range(0, middle)] right_array = [array[i] for i in range(middle, len(array))] merge_sort(left_array) merge_sort(right_array) summary = _merge(left_array, right_array) for i in range(len(array)): array[i] = summary[i] def quick_sort(array): if len(array) <= 1: return pivot = array[0] left_array = [] right_array = [] middle_array = [] for x in array: if x < pivot: left_array.append(x) elif x > pivot: right_array.append(x) else: middle_array.append(x) quick_sort(left_array) quick_sort(right_array) index = 0 for x in left_array + middle_array + right_array: array[index] = x index += 1
def bubble_sort(arr): swapped = True while swapped: swapped = False for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: (arr[i], arr[i + 1]) = (arr[i + 1], arr[i]) swapped = True def selection_sort(arr): for i in range(len(arr)): minpos = i for j in range(i + 1, len(arr)): if arr[j] < arr[minpos]: minpos = j (arr[i], arr[minpos]) = (arr[minpos], arr[i]) def insertion_sort(arr): for i in range(1, len(arr)): current = arr[i] j = i - 1 while j >= 0 and arr[j] > current: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = current def merge_sort(array): def _merge(left_arr, right_arr): _summary = [0] * (len(left_arr) + len(right_arr)) li = ri = n = 0 while li < len(left_arr) and ri < len(right_arr): if left_arr[li] <= right_arr[ri]: _summary[n] = left_arr[li] li += 1 n += 1 else: _summary[n] = right_arr[ri] ri += 1 n += 1 while li < len(left_arr): _summary[n] = left_arr[li] li += 1 n += 1 while ri < len(right_arr): _summary[n] = right_arr[ri] ri += 1 n += 1 return _summary if len(array) <= 1: return middle = len(array) // 2 left_array = [array[i] for i in range(0, middle)] right_array = [array[i] for i in range(middle, len(array))] merge_sort(left_array) merge_sort(right_array) summary = _merge(left_array, right_array) for i in range(len(array)): array[i] = summary[i] def quick_sort(array): if len(array) <= 1: return pivot = array[0] left_array = [] right_array = [] middle_array = [] for x in array: if x < pivot: left_array.append(x) elif x > pivot: right_array.append(x) else: middle_array.append(x) quick_sort(left_array) quick_sort(right_array) index = 0 for x in left_array + middle_array + right_array: array[index] = x index += 1
class Project(): def __init__(self, client, project_id=None): self.client = client self.project_id = project_id def get_details(self, project_id=None): """ Get information about a specific project http://developer.dribbble.com/v1/projects/#get-a-project """ project_id = project_id if project_id is not None else self.project_id project_details = self.client.GET("/projects/{}".format(project_id)) return project_details.json() def get_shots(self, project_id=None): """ Retrieves a list of all shots that are part of this project http://developer.dribbble.com/v1/projects/shots/#list-shots-for-a-project """ project_id = project_id if project_id is not None else self.project_id shots = self.client.GET("/projects/{}/shots".format(project_id)) return shots.json()
class Project: def __init__(self, client, project_id=None): self.client = client self.project_id = project_id def get_details(self, project_id=None): """ Get information about a specific project http://developer.dribbble.com/v1/projects/#get-a-project """ project_id = project_id if project_id is not None else self.project_id project_details = self.client.GET('/projects/{}'.format(project_id)) return project_details.json() def get_shots(self, project_id=None): """ Retrieves a list of all shots that are part of this project http://developer.dribbble.com/v1/projects/shots/#list-shots-for-a-project """ project_id = project_id if project_id is not None else self.project_id shots = self.client.GET('/projects/{}/shots'.format(project_id)) return shots.json()
class AllennlpReaderToDict: def __init__(self, **kwargs): self.kwargs = kwargs def __call__(self, *args_ignore, **kwargs_ignore): kwargs = self.kwargs reader = kwargs.get("reader") file_path = kwargs.get("file_path") n_samples = kwargs.get("n_samples") instances = reader._read(file_path) n_samples = n_samples or len(instances) d = dict() i = 0 for instance in instances: if n_samples and i >= n_samples: break d[i] = instance.fields i += 1 return d
class Allennlpreadertodict: def __init__(self, **kwargs): self.kwargs = kwargs def __call__(self, *args_ignore, **kwargs_ignore): kwargs = self.kwargs reader = kwargs.get('reader') file_path = kwargs.get('file_path') n_samples = kwargs.get('n_samples') instances = reader._read(file_path) n_samples = n_samples or len(instances) d = dict() i = 0 for instance in instances: if n_samples and i >= n_samples: break d[i] = instance.fields i += 1 return d
def one_hot_encode(_df, _col): _values = set(_df[_col].values) for v in _values: _df[_col + str(v)] = _df[_col].apply(lambda x : float(x == v) ) return _df
def one_hot_encode(_df, _col): _values = set(_df[_col].values) for v in _values: _df[_col + str(v)] = _df[_col].apply(lambda x: float(x == v)) return _df
class Solution(object): def sumOddLengthSubarrays(self, arr): """ :type arr: List[int] :rtype: int """ # Runtime: 32 ms # Memory: 13.4 MB prefix_sum = [] last_sum = 0 for item in arr: last_sum += item prefix_sum.append(last_sum) total = sum(arr) # Lengths of subarrays with length = 1 for subarr_size in range(3, len(arr) + 1, 2): for ptr in range(len(arr) - subarr_size + 1): total += prefix_sum[ptr + subarr_size - 1] if ptr != 0: total -= prefix_sum[ptr - 1] return total
class Solution(object): def sum_odd_length_subarrays(self, arr): """ :type arr: List[int] :rtype: int """ prefix_sum = [] last_sum = 0 for item in arr: last_sum += item prefix_sum.append(last_sum) total = sum(arr) for subarr_size in range(3, len(arr) + 1, 2): for ptr in range(len(arr) - subarr_size + 1): total += prefix_sum[ptr + subarr_size - 1] if ptr != 0: total -= prefix_sum[ptr - 1] return total
""" This code was written by JonECope Using Python 3035 in Processing 3.3.7 """ color_choice = color(0, 0, 0) circ = True instructions = "Press Mouse to draw, Right-click to erase, Q to exit, R, O, Y, G, B, V for colors. Press S for square brush or C for circle brush. Press Enter to save." def setup(): #size(800, 800) fullScreen() background(255) textSize(30) fill(0) text(instructions, 10, 100, width-20, 200) circ = True def draw(): global color_choice if mousePressed: if mouseButton == LEFT: fill(color_choice) stroke(color_choice) elif mouseButton == RIGHT: fill(255, 255, 255) stroke(255, 255, 255) else: fill(0, 0, 0, 0) stroke(0, 0, 0, 0) global circ if keyPressed: if key == "s" or key == "S": circ = False elif key == "c" or key == "C": circ = True if key == "q" or key == "Q": exit() elif key == ENTER: save("MyDrawing.png") background(255) fill(255, 0, 0) text("Your creation has been saved to the application's folder!", 10, 100, width-20, 200) elif keyCode == LEFT: color_choice = color(0) elif key == "r" or key == "R": color_choice = color(255, 0, 0) elif key == "o" or key == "O": color_choice = color(255, 156, 0) elif key == "y" or key == "Q": color_choice = color(255, 255, 0) elif key == "g" or key == "Q": color_choice = color(0, 255, 0) elif key == "b" or key == "Q": color_choice = color(0, 0, 255) elif key == "v" or key == "Q": color_choice = color(169, 0, 255) if circ: ellipse(mouseX, mouseY, 30, 30) else: rect(mouseX, mouseY, 30, 30)
""" This code was written by JonECope Using Python 3035 in Processing 3.3.7 """ color_choice = color(0, 0, 0) circ = True instructions = 'Press Mouse to draw, Right-click to erase, Q to exit, R, O, Y, G, B, V for colors. Press S for square brush or C for circle brush. Press Enter to save.' def setup(): full_screen() background(255) text_size(30) fill(0) text(instructions, 10, 100, width - 20, 200) circ = True def draw(): global color_choice if mousePressed: if mouseButton == LEFT: fill(color_choice) stroke(color_choice) elif mouseButton == RIGHT: fill(255, 255, 255) stroke(255, 255, 255) else: fill(0, 0, 0, 0) stroke(0, 0, 0, 0) global circ if keyPressed: if key == 's' or key == 'S': circ = False elif key == 'c' or key == 'C': circ = True if key == 'q' or key == 'Q': exit() elif key == ENTER: save('MyDrawing.png') background(255) fill(255, 0, 0) text("Your creation has been saved to the application's folder!", 10, 100, width - 20, 200) elif keyCode == LEFT: color_choice = color(0) elif key == 'r' or key == 'R': color_choice = color(255, 0, 0) elif key == 'o' or key == 'O': color_choice = color(255, 156, 0) elif key == 'y' or key == 'Q': color_choice = color(255, 255, 0) elif key == 'g' or key == 'Q': color_choice = color(0, 255, 0) elif key == 'b' or key == 'Q': color_choice = color(0, 0, 255) elif key == 'v' or key == 'Q': color_choice = color(169, 0, 255) if circ: ellipse(mouseX, mouseY, 30, 30) else: rect(mouseX, mouseY, 30, 30)
def differ(string_1, string_2): new_string = "" for i in range(len(string_1)): if string_1[i] == string_2[i]: new_string += string_1[i] return new_string def main(): f = [line.rstrip("\n") for line in open("Data.txt")] for i in range(len(f)): for j in range(i + 1, len(f)): if len(differ(f[i], f[j])) == len(f[i]) - 1: print(differ(f[i], f[j])) if __name__ == "__main__": main()
def differ(string_1, string_2): new_string = '' for i in range(len(string_1)): if string_1[i] == string_2[i]: new_string += string_1[i] return new_string def main(): f = [line.rstrip('\n') for line in open('Data.txt')] for i in range(len(f)): for j in range(i + 1, len(f)): if len(differ(f[i], f[j])) == len(f[i]) - 1: print(differ(f[i], f[j])) if __name__ == '__main__': main()
class Car(object): # setting some default values num_of_doors = 4 num_of_wheels = 4 def __init__(self, name='General', model='GM', car_type='saloon', speed=0): self.name = name self.model = model self.car_type = car_type self.speed = speed if self.name is 'Porshe' or self.name is 'Koenigsegg': self.num_of_doors = 2 elif self.car_type is 'trailer': self.num_of_wheels = 8 else: self def is_saloon(self): ''' Determine between saloon and trailer ''' if self.car_type is not 'trailer': return True return False def drive(self, speed): ''' Check the car type and return appropriate speed ''' if self.car_type is 'trailer': self.speed = speed * 11 else: self.speed = 10 ** speed return self
class Car(object): num_of_doors = 4 num_of_wheels = 4 def __init__(self, name='General', model='GM', car_type='saloon', speed=0): self.name = name self.model = model self.car_type = car_type self.speed = speed if self.name is 'Porshe' or self.name is 'Koenigsegg': self.num_of_doors = 2 elif self.car_type is 'trailer': self.num_of_wheels = 8 else: self def is_saloon(self): """ Determine between saloon and trailer """ if self.car_type is not 'trailer': return True return False def drive(self, speed): """ Check the car type and return appropriate speed """ if self.car_type is 'trailer': self.speed = speed * 11 else: self.speed = 10 ** speed return self