content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#!/usr/bin/env python3 for _ in range(int(input())): input() # don't need n try: print(input().index('1') // 2) except ValueError: print(-1)
for _ in range(int(input())): input() try: print(input().index('1') // 2) except ValueError: print(-1)
def assignments_yield_islice(n_clubs: int) -> Iterator[set]: # This is almost but not quite accurate # It's about 15% faster than non-islice, but I can't get the combinators to roll over right n_block_1 = n_clubs // 3 + ((n_clubs % 3) > 0) n_block_2 = n_clubs // 3 + ((n_clubs % 3) > 1) n1 = n_assi...
def assignments_yield_islice(n_clubs: int) -> Iterator[set]: n_block_1 = n_clubs // 3 + (n_clubs % 3 > 0) n_block_2 = n_clubs // 3 + (n_clubs % 3 > 1) n1 = n_assignments(n_clubs, True) c2 = c(n_clubs - n_block_1, n_block_2) - (n_clubs % 3 > 1) def _get_runs() -> Iterator[tuple]: if n_clubs ...
def reverse_vowel(s): vowels = "AEIOUaeiou" i, j = 0, len(s)-1 s = list(s) while i < j: while i < j and s[i] not in vowels: i += 1 while i < j and s[j] not in vowels: j -= 1 s[i], s[j] = s[j], s[i] i, j = i + 1, j - 1 return "".join(s)
def reverse_vowel(s): vowels = 'AEIOUaeiou' (i, j) = (0, len(s) - 1) s = list(s) while i < j: while i < j and s[i] not in vowels: i += 1 while i < j and s[j] not in vowels: j -= 1 (s[i], s[j]) = (s[j], s[i]) (i, j) = (i + 1, j - 1) return ''.jo...
ips = ["127.0.0.1", "255.0.0.1", "137.44.1.20", "48.8.9.72", ".".join(str(x) for x in range(256))] z_a = ord("z") - ord("a") # apparently I find it hard to remember az is 26 letters for ip in ips: sip = [] for byte in ip.split("."): b, s = int(byte), [] if b < ord("a"): b += ord("a") if b > ord...
ips = ['127.0.0.1', '255.0.0.1', '137.44.1.20', '48.8.9.72', '.'.join((str(x) for x in range(256)))] z_a = ord('z') - ord('a') for ip in ips: sip = [] for byte in ip.split('.'): (b, s) = (int(byte), []) if b < ord('a'): b += ord('a') if b > ord('z'): s.app...
class AI(): def __init__(self, grid): self.grid = grid def solve(self): covered = self.grid.grid.get_covered() try: cell = covered[0] except IndexError: print("Nothing more to do") return self.grid.press(*cell) print("Press",...
class Ai: def __init__(self, grid): self.grid = grid def solve(self): covered = self.grid.grid.get_covered() try: cell = covered[0] except IndexError: print('Nothing more to do') return self.grid.press(*cell) print('Press', ce...
def StringVersion( seq ): return '.'.join( ['%s'] * len( seq )) % tuple( seq ) def TupleVersion( str ): return map( int, str.split( '.' ))
def string_version(seq): return '.'.join(['%s'] * len(seq)) % tuple(seq) def tuple_version(str): return map(int, str.split('.'))
# responder-brute configuration file # Path to Responder.db RESPONDERDB = '../Responder.db' # Current hash file CURRENTHASHFILE = 'current.txt' # Poll for new hashes every N seconds POLLTIME = 5 # Use 'john' for John The Ripper or 'hashcat' for Hashcat. MODE = 'john' if MODE == 'john': # Command to run. Use "{...
responderdb = '../Responder.db' currenthashfile = 'current.txt' polltime = 5 mode = 'john' if MODE == 'john': command = 'john --format={hashtype} --wordlist=dictionary.dic {hash}' hashtype_ntl_mv1 = 'netntlm' hashtype_ntl_mv2 = 'netntlmv2' command_post = 'john --show {}' else: command = 'hashcat -m ...
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------- # CISCO-CDP-MIB # Compiled MIB # Do not modify this file directly # Run ./noc mib make_cmib instead # ---------------------------------------------------------------------- # Copyright (C) 2007-2018 The NOC Proj...
name = 'CISCO-CDP-MIB' last_updated = '2005-03-21' compiled = '2018-06-09' mib = {'CISCO-CDP-MIB::ciscoCdpMIB': '1.3.6.1.4.1.9.9.23', 'CISCO-CDP-MIB::ciscoCdpMIBObjects': '1.3.6.1.4.1.9.9.23.1', 'CISCO-CDP-MIB::cdpInterface': '1.3.6.1.4.1.9.9.23.1.1', 'CISCO-CDP-MIB::cdpInterfaceTable': '1.3.6.1.4.1.9.9.23.1.1.1', 'CIS...
class Simple(object): def __init__(self, lines): self.lines = lines def __enter__(self): return self def __exit__(self, *args): pass def path(self): return None def get_doc_ids(self): return list(range(len(self.lines))) def get_doc_text(self, line): ...
class Simple(object): def __init__(self, lines): self.lines = lines def __enter__(self): return self def __exit__(self, *args): pass def path(self): return None def get_doc_ids(self): return list(range(len(self.lines))) def get_doc_text(self, line): ...
''' igualad: a == b desigualad: a != b a menor que b: a < b a menor o igual b: a <= b a mayor que b: a > b a mayor o igual b: a >= b ''' # if basico en varias lineas a = 33 b = 200 if b > a: print("b es mayor a") # if anidado en varias lineas a = 33 b = 33 if b > a: print("b es mayor a") elif a == b: print(...
""" igualad: a == b desigualad: a != b a menor que b: a < b a menor o igual b: a <= b a mayor que b: a > b a mayor o igual b: a >= b """ a = 33 b = 200 if b > a: print('b es mayor a') a = 33 b = 33 if b > a: print('b es mayor a') elif a == b: print('a y b son iguales') if b > a: print('b es mayor a...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # class Solution: # def inorderTraversal(self, root: TreeNode) -> List[int]: # res = [] # if not root: # ...
class Solution: def inorder_traversal(self, root: TreeNode) -> List[int]: res = [] if not root: return res stack = [(False, root)] while stack: (visited, node) = stack.pop() if not node: continue if visited: ...
class Fifo(list): def __init__(self): self.back = [] self.append = self.back.append def pop(self): if not self: self.back.reverse() self[:] = self.back del self.back[:] return super(Fifo, self).pop()
class Fifo(list): def __init__(self): self.back = [] self.append = self.back.append def pop(self): if not self: self.back.reverse() self[:] = self.back del self.back[:] return super(Fifo, self).pop()
## Script (Python) "getPautasPautao" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters=data='', ##title=Retorna a lista de pautas do pautao ret = { 'manha': [], 'tarde': [], 'noite': [], 'nota':[], 'programas': [], 'semturno': [] } if...
ret = {'manha': [], 'tarde': [], 'noite': [], 'nota': [], 'programas': [], 'semturno': []} if not data: data = date_time().Date() pautas = context.portal_catalog.searchResults(portal_type='Pauta', getData=data, review_state='Pautao') programas = ['nbr-entrevista', 'documentacao', 'bomdiaministro', 'cenasdobrasil', ...
"""Hackerrank Problem: https://www.hackerrank.com/challenges/validate-list-of-email-address-with-filter/problem""" def fun(s): """Determine if the passed in email address is valid based on the following rules: It must have the username@websitename.extension format type. The username can only contain lett...
"""Hackerrank Problem: https://www.hackerrank.com/challenges/validate-list-of-email-address-with-filter/problem""" def fun(s): """Determine if the passed in email address is valid based on the following rules: It must have the username@websitename.extension format type. The username can only contain lette...
""" Dummy module to substitute missing dependencies, e.g.: >>> try: ... import termcolor ... except ImportError: ... import dummy as termcolor Now some functionality of missing modules can be used in form of dummy functions, i.e. it will make no real effect. E.g. `termcolor.colored` will return text without any ...
""" Dummy module to substitute missing dependencies, e.g.: >>> try: ... import termcolor ... except ImportError: ... import dummy as termcolor Now some functionality of missing modules can be used in form of dummy functions, i.e. it will make no real effect. E.g. `termcolor.colored` will return text without any ...
class BaseModule(object): def __init__(self, connector): self.connector = connector def setup(self): pass
class Basemodule(object): def __init__(self, connector): self.connector = connector def setup(self): pass
''' Created on 09.03.2019 @author: Nicco ''' class plan_base(object): ''' plan base is providing alle the methods to connect to act, perception and the simulator ''' def __init__(self, params): ''' Constructor '''
""" Created on 09.03.2019 @author: Nicco """ class Plan_Base(object): """ plan base is providing alle the methods to connect to act, perception and the simulator """ def __init__(self, params): """ Constructor """
even_set = set() odd_set = set() for row in range(int(input())): name = input() ascii_letters = [ord(letter) for letter in name] result = sum(ascii_letters) // (row+1) if result % 2 == 0: even_set.add(result) else: odd_set.add(result) if sum(even_set) == sum(odd_set):...
even_set = set() odd_set = set() for row in range(int(input())): name = input() ascii_letters = [ord(letter) for letter in name] result = sum(ascii_letters) // (row + 1) if result % 2 == 0: even_set.add(result) else: odd_set.add(result) if sum(even_set) == sum(odd_set): [odd_set....
_base_ = [ '../_base_/models/ocrnet_r50-d8.py', '../_base_/datasets/cityscapes_sccqq.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py' ] model = dict(pretrained='open-mmlab://resnet101_v1c', backbone=dict(depth=101)) optimizer = dict(lr=0.02) lr_config = dict(min_lr=2e-4) data = dict( ...
_base_ = ['../_base_/models/ocrnet_r50-d8.py', '../_base_/datasets/cityscapes_sccqq.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py'] model = dict(pretrained='open-mmlab://resnet101_v1c', backbone=dict(depth=101)) optimizer = dict(lr=0.02) lr_config = dict(min_lr=0.0002) data = dict(samples_pe...
# # PySNMP MIB module BAY-STACK-PIM-EXT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BAY-STACK-PIM-EXT-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:36:08 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_union, value_size_constraint, value_range_constraint, constraints_intersection) ...
# # PySNMP MIB module Nortel-Magellan-Passport-FrameRelayUniTraceMIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-FrameRelayUniTraceMIB # Produced by pysmi-0.3.4 at Wed May 1 14:27:22 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 ...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint) ...
with open("input.txt") as f: lines = f.readlines() split_lines = [x.split() for x in lines] horiz = map(lambda x: int(x[1]) if x[0][0] == 'f' else -int(x[1]) if x[0][0] == 'b' else 0, split_lines) vert = map(lambda x: int(x[1]) if x[0][0] == 'd' else -int(x[1]) if x[0][0] == 'u' else 0, split_lines) print(su...
with open('input.txt') as f: lines = f.readlines() split_lines = [x.split() for x in lines] horiz = map(lambda x: int(x[1]) if x[0][0] == 'f' else -int(x[1]) if x[0][0] == 'b' else 0, split_lines) vert = map(lambda x: int(x[1]) if x[0][0] == 'd' else -int(x[1]) if x[0][0] == 'u' else 0, split_lines) print(sum(horiz...
''' Use this folder for the development of any products. All data should be saved to S3. '''
""" Use this folder for the development of any products. All data should be saved to S3. """
nums = [12, 34, 5, 7, 8] iter_nums = iter(nums) # def sum_numbers(nums): # for n in nums: # n += sum_numbers(nums) # return n # print(sum_numbers(iter_nums)) def sum_list(list_to_sum, index): if len(list_to_sum) == 0: return 0 if index == 0: return list_to_...
nums = [12, 34, 5, 7, 8] iter_nums = iter(nums) def sum_list(list_to_sum, index): if len(list_to_sum) == 0: return 0 if index == 0: return list_to_sum[0] return list_to_sum[index] + sum_list(list_to_sum, index - 1) string = '123' def recursive_sum_string(list, index): if len(list) == 0...
def hello(): return "Hello, pobby!" def main(): s = hello() print(s) """hahahahahah sdjfkadsjflksdjfkldsajfklsda fjdaslkfjdsakl""" if __name__ == '__main__': main()
def hello(): return 'Hello, pobby!' def main(): s = hello() print(s) 'hahahahahah\n sdjfkadsjflksdjfkldsajfklsda\n fjdaslkfjdsakl' if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """Tests dict input objects for `cookiecutter.operator.aws.ec2_meta` module.""" # import os # from cookiecutter.main import cookiecutter # TODO: Need to be able test pyinquirer # def test_operator_terraform(monkeypatch, tmpdir): # """Verify the operator call works successfully.""" # m...
"""Tests dict input objects for `cookiecutter.operator.aws.ec2_meta` module."""
""" https://docs.python.org/3/tutorial/controlflow.html """ def parrot(voltage, state='a stiff', action='voom'): print("-- This parrot wouldn't", action, end=' ') print("if you put", voltage, "volts through it.", end=' ') print("E's", state, "!") d = {"voltage": "four million", "state": "bleedin' d...
""" https://docs.python.org/3/tutorial/controlflow.html """ def parrot(voltage, state='a stiff', action='voom'): print("-- This parrot wouldn't", action, end=' ') print('if you put', voltage, 'volts through it.', end=' ') print("E's", state, '!') d = {'voltage': 'four million', 'state': "bleedin' demised",...
class SnapshotView(object): """ A view into some subset of a snapshot instance. The attributes of the view depend on the snapshot from which it was derived, and the kind of view requested. All available attributes from the snapshot are available via the fields property, which returns a tuple. ...
class Snapshotview(object): """ A view into some subset of a snapshot instance. The attributes of the view depend on the snapshot from which it was derived, and the kind of view requested. All available attributes from the snapshot are available via the fields property, which returns a tuple. ...
class Solution(object): def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ if not matrix: return [] M = matrix[:] # duplicate matrix m = len(M) # get m n = len(M[0]) # get n i, j = 0, 0 # set coordinate ...
class Solution(object): def spiral_order(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ if not matrix: return [] m = matrix[:] m = len(M) n = len(M[0]) (i, j) = (0, 0) l = m * n k = 0 ...
# Author: OMKAR PATHAK # A Python generator is a function which returns a generator iterator (just an object we can iterate over) # by calling yield def simpleGenerator(numbers): i = 0 while True: check = input('Wanna generate a number? (If yes, press y else n): ') if check in ('Y', 'y') and l...
def simple_generator(numbers): i = 0 while True: check = input('Wanna generate a number? (If yes, press y else n): ') if check in ('Y', 'y') and len(numbers) > i: yield numbers[i] i += 1 else: print('Bye!') break for number in simple_genera...
def _configure_features( ctx, cuda_toolchain, requested_features=[], unsupported_features=[] ): features = cuda_toolchain.features enabled_features = {} # Enable compilation mode feature compilation_mode = ctx.var["COMPILATION_MODE"] if compilation_mode in features: enabled_...
def _configure_features(ctx, cuda_toolchain, requested_features=[], unsupported_features=[]): features = cuda_toolchain.features enabled_features = {} compilation_mode = ctx.var['COMPILATION_MODE'] if compilation_mode in features: enabled_features[compilation_mode] = features[compilation_mode] ...
"""Test mobile app device tracker.""" async def test_sending_location(hass, create_registrations, webhook_client): """Test sending a location via a webhook.""" resp = await webhook_client.post( "/api/webhook/{}".format(create_registrations[1]["webhook_id"]), json={ "type": "update_...
"""Test mobile app device tracker.""" async def test_sending_location(hass, create_registrations, webhook_client): """Test sending a location via a webhook.""" resp = await webhook_client.post('/api/webhook/{}'.format(create_registrations[1]['webhook_id']), json={'type': 'update_location', 'data': {'gps': [10,...
""" A row measuring seven units in length has red blocks with a minimum length of three units placed on it, such that any two red blocks (which are allowed to be different lengths) are separated by at least one grey square. There are exactly seventeen ways of doing this. p114.png How many ways can a row measuring fift...
""" A row measuring seven units in length has red blocks with a minimum length of three units placed on it, such that any two red blocks (which are allowed to be different lengths) are separated by at least one grey square. There are exactly seventeen ways of doing this. p114.png How many ways can a row measuring fift...
class Node: def __init__(self,data): self.left=None self.right=None self.data=data def PrintTree(self): if self.left: self.left.PrintTree() print(self.data) if self.right: self.right.PrintTree() def insert(self,data): i...
class Node: def __init__(self, data): self.left = None self.right = None self.data = data def print_tree(self): if self.left: self.left.PrintTree() print(self.data) if self.right: self.right.PrintTree() def insert(self, data): ...
# 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 # d...
class Portforwardingpayload(object): """Payload for port-forwarding-related callback registry notifications.""" def __init__(self, context, current_pf=None, original_pf=None): self.context = context self.current_pf = current_pf self.original_pf = original_pf def __eq__(self, other)...
names = ['Simon', 'Sophie', 2] print (names[0] + ' loves ' + names[1] + ' for ' + str(names[2]) + ' years') for name in names : print (name)
names = ['Simon', 'Sophie', 2] print(names[0] + ' loves ' + names[1] + ' for ' + str(names[2]) + ' years') for name in names: print(name)
''' Using sieve of Eratosthenes, primes(x) returns list of all primes less than x Modification: We don't need to check all even numbers, we can make the sieve excluding even numbers and adding 2 to the primes list by default. We are going to make an array of: x / 2 - 1 if number is even, else x / 2 (The -1 with even...
""" Using sieve of Eratosthenes, primes(x) returns list of all primes less than x Modification: We don't need to check all even numbers, we can make the sieve excluding even numbers and adding 2 to the primes list by default. We are going to make an array of: x / 2 - 1 if number is even, else x / 2 (The -1 with even...
# Space: O(1) # Time: O(n) class Solution: def singleNumber(self, nums): res = [] length = len(nums) nums.sort() status = 0 for i in range(length): if i == 0: if nums[i] != nums[i + 1]: res.append(nums[i]) ...
class Solution: def single_number(self, nums): res = [] length = len(nums) nums.sort() status = 0 for i in range(length): if i == 0: if nums[i] != nums[i + 1]: res.append(nums[i]) status += 1 eli...
numbers_list = input().split(', ') new_list = [] for digit in numbers_list: digits = digit.split(', ') current_digit = int(digits[0]) if current_digit == 0: numbers_list.remove('0') numbers_list.append('0') new_list = list(map(int, numbers_list)) print(new_list)
numbers_list = input().split(', ') new_list = [] for digit in numbers_list: digits = digit.split(', ') current_digit = int(digits[0]) if current_digit == 0: numbers_list.remove('0') numbers_list.append('0') new_list = list(map(int, numbers_list)) print(new_list)
# Copyright 2018 The GraphNets Authors. 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 applicabl...
def cr_inputs_reference(): reference__range = {'C-reactive protein': {'Male': {'min': '0', 'max': '5'}, 'Female': {'min': '0', 'max': '5'}, 'Unknown': {'min': '0', 'max': '5'}, 'Unspecified': {'min': '0', 'max': '5'}}} input_node_fields = ['C-reactive protein'] return (Reference_Range, input_node_fields)
class Error(Exception): """ Base exception for all exceptions that indicate a failed request """ class DecodeError(Error): """" Raised when the request cannot be decoded by the server. """ class NoFreeOTAAddresses(Error): """" Raised when the OTA request cannot be completed due to no ...
class Error(Exception): """ Base exception for all exceptions that indicate a failed request """ class Decodeerror(Error): """" Raised when the request cannot be decoded by the server. """ class Nofreeotaaddresses(Error): """" Raised when the OTA request cannot be completed due to no f...
wt3_3_10 = {'192.168.122.110': [8.5425, 9.6589, 8.3878, 8.9764, 8.5553, 8.1619, 8.5832, 8.1742, 7.8747, 7.6304, 7.6131, 7.5381, 7.3988, 7.2547, 7.2352, 7.1954, 7.0925, 6.9968, 7.8112, 7.7524, 7.6389, 7.5302, 7.4983, 7.4729, 7.4327, 7.3494, 7.2848, 7.2741, 7.2099, 7.1539, 7.2822, 7.2477, 7.3613, 7.315, 7.2783, 7.1005, ...
wt3_3_10 = {'192.168.122.110': [8.5425, 9.6589, 8.3878, 8.9764, 8.5553, 8.1619, 8.5832, 8.1742, 7.8747, 7.6304, 7.6131, 7.5381, 7.3988, 7.2547, 7.2352, 7.1954, 7.0925, 6.9968, 7.8112, 7.7524, 7.6389, 7.5302, 7.4983, 7.4729, 7.4327, 7.3494, 7.2848, 7.2741, 7.2099, 7.1539, 7.2822, 7.2477, 7.3613, 7.315, 7.2783, 7.1005, 7...
""" ==CHANGELOG== * support UTF8 ==CHANGELOG== """ sqdgfhsqgfksqfkjgsqfkqsgdkfsqkgfqsdf sqgjdfjsqdhfqgskdgfkqgsdjfsqdfggdsqjf sqdgfhsqgfksqfkjgsqfkqsgdkfsqkgfqsdf sqgjdfjsqdhfqgskdgfkqgsdjfsqdfggdsqjf sqdgfhsqgfksqfkjgsqfkqsgdkfsqkgfqsdf sqgjdfjsqdhfqgskdgfkqgsdjfsqdfggdsqjf sqdgfhsqgfksqfkjgsqfkqsgdkfsqkgfqsdf sqgjdf...
""" ==CHANGELOG== * support UTF8 ==CHANGELOG== """ sqdgfhsqgfksqfkjgsqfkqsgdkfsqkgfqsdf sqgjdfjsqdhfqgskdgfkqgsdjfsqdfggdsqjf sqdgfhsqgfksqfkjgsqfkqsgdkfsqkgfqsdf sqgjdfjsqdhfqgskdgfkqgsdjfsqdfggdsqjf sqdgfhsqgfksqfkjgsqfkqsgdkfsqkgfqsdf sqgjdfjsqdhfqgskdgfkqgsdjfsqdfggdsqjf sqdgfhsqgfksqfkjgsqfkqsgdkfsqkgfqsdf sqgjdfj...
names = ['David','Herry','Army'] message1 = "hello " + names[0] print(message1) message1 = "hello " + names[1] print(message1) message1 = "hello " + names[2] print(message1)
names = ['David', 'Herry', 'Army'] message1 = 'hello ' + names[0] print(message1) message1 = 'hello ' + names[1] print(message1) message1 = 'hello ' + names[2] print(message1)
hu = "haha" age = 22 name = "Cat"
hu = 'haha' age = 22 name = 'Cat'
def calculateStats(numbers): val = len(numbers) result = {"max": float('NaN'), "min": float('NaN'), "avg": float('NaN')} if val == 0: return result else: result["max"] = max(numbers) result["min"] = min(numbers) result["avg"] = sum(numbers) / val return result ...
def calculate_stats(numbers): val = len(numbers) result = {'max': float('NaN'), 'min': float('NaN'), 'avg': float('NaN')} if val == 0: return result else: result['max'] = max(numbers) result['min'] = min(numbers) result['avg'] = sum(numbers) / val return result c...
lst = [ ["https://bit.ly/DataStructC", "9:00", "9:58"], ["https://bit.ly/AeroStructures", "11:10", "12:08"], ["https://zoom.us/j/8143311495?pwd=e-space", "12:10", "13:00"] ["https://bit.ly/engMaterials", "13:50", "14:50"] ]
lst = [['https://bit.ly/DataStructC', '9:00', '9:58'], ['https://bit.ly/AeroStructures', '11:10', '12:08'], ['https://zoom.us/j/8143311495?pwd=e-space', '12:10', '13:00']['https://bit.ly/engMaterials', '13:50', '14:50']]
host='localhost' user='root' password='wowilosttwosis$' db='fin_man_db' charset='utf8mb4'
host = 'localhost' user = 'root' password = 'wowilosttwosis$' db = 'fin_man_db' charset = 'utf8mb4'
cx, cy, cd = input().split() cx = float(cx); cy = float(cy); cd = float(cd); r = cd; n = int(input()); coef = input().split(); z = float(input()); for i in range(n+1): coef[i] = float(coef[i]) def f_eval(x): ans = 0 for i in range(0, n+1): ans += coef[i]*(x**(n-i)) return ans lo = cx - r - 10 hi = cx + r + 10 ...
(cx, cy, cd) = input().split() cx = float(cx) cy = float(cy) cd = float(cd) r = cd n = int(input()) coef = input().split() z = float(input()) for i in range(n + 1): coef[i] = float(coef[i]) def f_eval(x): ans = 0 for i in range(0, n + 1): ans += coef[i] * x ** (n - i) return ans lo = cx - r - 1...
"""Load dependencies needed to depend on the remote-apis-sdks repo.""" load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies", "go_repository") def _maybe(repo_rule, name, **kwargs): if name not in native.existing_rules(): repo_rule(name = name, **kwargs) def remote_apis_sdks_go_deps(): """Load dep...
"""Load dependencies needed to depend on the remote-apis-sdks repo.""" load('@bazel_gazelle//:deps.bzl', 'gazelle_dependencies', 'go_repository') def _maybe(repo_rule, name, **kwargs): if name not in native.existing_rules(): repo_rule(name=name, **kwargs) def remote_apis_sdks_go_deps(): """Load depend...
# Copyright 2016 The Closure Rules Authors. 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 appli...
"""Utilities for compiling Closure Templates to Java. """ load('@rules_java//java:defs.bzl', 'java_library') _soy_compiler_bin = '@com_google_template_soy//:SoyParseInfoGenerator' _soy_library = '@com_google_template_soy//:com_google_template_soy' def closure_java_template_library(name, java_package=None, srcs=[], dep...
class Process: def __init__(self, id, arrvl_time, exec_time): self.id = id self.arrvl_time = arrvl_time self.exec_time = exec_time self.compl_time = 0 self.timeLeft = exec_time def execute(self, quantum): #self.timeLeft = self.timeLeft - quantum if self.timeLeft ...
class Process: def __init__(self, id, arrvl_time, exec_time): self.id = id self.arrvl_time = arrvl_time self.exec_time = exec_time self.compl_time = 0 self.timeLeft = exec_time def execute(self, quantum): if self.timeLeft > quantum: self.timeLeft = s...
# DATABASE db_username = 'root' db_password = 'toor' db_name = 'fscaffold' db_hostname = 'localhost' DEBUG = True PORT = 5000 HOST = "0.0.0.0" SQLALCHEMY_ECHO = False SECRET_KEY = "SOME SECRET" # PostgreSQL # SQLALCHEMY_DATABASE_URI = "postgresql://{DB_USER}:{DB_PASS}@{DB_ADDR}/{DB_NAME}".format( # DB_USER=db_use...
db_username = 'root' db_password = 'toor' db_name = 'fscaffold' db_hostname = 'localhost' debug = True port = 5000 host = '0.0.0.0' sqlalchemy_echo = False secret_key = 'SOME SECRET' sqlalchemy_database_uri = 'mysql+pymysql://{DB_USER}:{DB_PASS}@{DB_ADDR}/{DB_NAME}'.format(DB_USER=db_username, DB_PASS=db_password, DB_A...
# Time: O(n) ~ O(n^2) # Space: O(n) class Solution(object): def canCross(self, stones): """ :type stones: List[int] :rtype: bool """ if stones[1] != 1: return False last_jump_units = {s: set() for s in stones} last_jump_units[1].add(1) f...
class Solution(object): def can_cross(self, stones): """ :type stones: List[int] :rtype: bool """ if stones[1] != 1: return False last_jump_units = {s: set() for s in stones} last_jump_units[1].add(1) for s in stones[:-1]: for ...
words = "Life is short" upper_word_list = ["LIFE", "IS", "SHORT", "USE", "PYTHON"] word_generator = ( lower_w for w in upper_word_list if (lower_w := w.lower()) in words.lower() ) for w in word_generator: print(w, end=" ") # word_generator is StopIteration now
words = 'Life is short' upper_word_list = ['LIFE', 'IS', 'SHORT', 'USE', 'PYTHON'] word_generator = (lower_w for w in upper_word_list if (lower_w := w.lower()) in words.lower()) for w in word_generator: print(w, end=' ')
# overall function that recursively splits an input array in half, and # uses the helper function "merge" to compare items in each half against each # other to sort them def mergeSort(list): # Determine whether the list is broken into # individual pieces. if len(list) < 2: return list # Find th...
def merge_sort(list): if len(list) < 2: return list middle = len(list) // 2 left = merge_sort(list[:middle]) right = merge_sort(list[middle:]) print('Left side: ', left) print('Right side: ', right) merged = merge(left, right) print('Merged ', merged) return merged def merge...
class DockerComposeEntity: def __init__(self): self.sinks = list() def build_state(self): result = dict() services = dict() sink_count = 0 for sink in self.sinks: services[f"sink_{sink_count}"] = sink.__dict__ sink_count += 1 result["ver...
class Dockercomposeentity: def __init__(self): self.sinks = list() def build_state(self): result = dict() services = dict() sink_count = 0 for sink in self.sinks: services[f'sink_{sink_count}'] = sink.__dict__ sink_count += 1 result['vers...
a = input() if len(a) == 1 and 'a' in a: ans = -1 else: ans = 'a' print(ans)
a = input() if len(a) == 1 and 'a' in a: ans = -1 else: ans = 'a' print(ans)
LocalValueDim = 18446744073709551613 dataTypes = { -1: 'unknown', 0: 'byte', 1: 'short', 2: 'integer', 4: 'long', 50: 'unsigned_byte', 51: 'unsigned_short', 52: 'unsigned_integer', 54: 'unsigned_long', 5: 'real', 6: 'double', 7: 'long_double', 9: 'string', 10...
local_value_dim = 18446744073709551613 data_types = {-1: 'unknown', 0: 'byte', 1: 'short', 2: 'integer', 4: 'long', 50: 'unsigned_byte', 51: 'unsigned_short', 52: 'unsigned_integer', 54: 'unsigned_long', 5: 'real', 6: 'double', 7: 'long_double', 9: 'string', 10: 'complex', 11: 'double_complex', 12: 'string_array', 55: ...
list1 = [3, 4, 51, 90.1, False, 'Amresh', 7] # index = 0 # for i in list1: # print (f'index: {index}, Value: {i}') # index += 1 for index, item in enumerate(list1): print (f'index: {index}, Value: {item}')
list1 = [3, 4, 51, 90.1, False, 'Amresh', 7] for (index, item) in enumerate(list1): print(f'index: {index}, Value: {item}')
class Params(object): def __init__(self , data_path='faces/dataset/' , artifacts_path='faces/artifacts/' , models_path='/User/mlrun/demos/faces/notebooks/functions/models.py' , frames_url='framesd:8081' , token='set_token' ...
class Params(object): def __init__(self, data_path='faces/dataset/', artifacts_path='faces/artifacts/', models_path='/User/mlrun/demos/faces/notebooks/functions/models.py', frames_url='framesd:8081', token='set_token', encodings_path='faces/encodings/', container='users'): self.data_path = data_path ...
''' Created on 15.02.2017 @author: emillokal ''' measure0=0 measure1=0
""" Created on 15.02.2017 @author: emillokal """ measure0 = 0 measure1 = 0
# Link to the problem: https://www.codechef.com/MARCH18B/problems/MIXCOLOR def main(): T = int(input()) while T: T -= 1 _ = int(input()) occr = {} colors = list(map(int, input().split())) for i in colors: occr[i] = 0 for val in colors: oc...
def main(): t = int(input()) while T: t -= 1 _ = int(input()) occr = {} colors = list(map(int, input().split())) for i in colors: occr[i] = 0 for val in colors: occr[val] += 1 ans = 0 for (_, v) in occr.items(): ...
# File where I wrote functions that helped parse and make changes to multiple lines of code def read_source_file(name: str)->str: f = open(name) s = f.read() f.close() return s def save_as_new(text: str): f = open('./new.py', mode='w') f.write(text) f.close() def find_brace_close_posit...
def read_source_file(name: str) -> str: f = open(name) s = f.read() f.close() return s def save_as_new(text: str): f = open('./new.py', mode='w') f.write(text) f.close() def find_brace_close_position(text: str, brace_start: int) -> int: scope_level = 1 position = brace_start + 1 ...
# # 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 # ...
def check_c_count(expected_count): test.assertEqual(expected_count, len(reality.resources_by_logical_name('C'))) example_template = template({'A': rsrc_def({'a': 'initial'}, []), 'B': rsrc_def({}, []), 'C': rsrc_def({'!a': get_att('A', 'a')}, ['B']), 'D': rsrc_def({'c': get_res('C')}, []), 'E': rsrc_def({'ca': get_...
class Immutable(type): def __new__(msc, name, bases, nmspc): new_class = type(name, bases, nmspc) original_initialization = new_class.__init__ def set_attribute(self, key, value): raise AttributeError("Attributes are immutable") def wrapper(self, *args, **kwargs): ...
class Immutable(type): def __new__(msc, name, bases, nmspc): new_class = type(name, bases, nmspc) original_initialization = new_class.__init__ def set_attribute(self, key, value): raise attribute_error('Attributes are immutable') def wrapper(self, *args, **kwargs): ...
MAX_MEMBER_REPR_LENGTH = 1000 class Repr: """Convencience class to automatically add standard ``__repr__()`` and ``__str__()`` functions to class. Uses ``__dict__`` property. """ def __repr__(self): members = ', '.join(f'{k}={str(v)[:MAX_MEMBER_REPR_LENGTH]}' for k, v in self.__dict__.items...
max_member_repr_length = 1000 class Repr: """Convencience class to automatically add standard ``__repr__()`` and ``__str__()`` functions to class. Uses ``__dict__`` property. """ def __repr__(self): members = ', '.join((f'{k}={str(v)[:MAX_MEMBER_REPR_LENGTH]}' for (k, v) in self.__dict__.item...
class CleanPhoneNumber(object): def __init__(self, phone_number): self.phone_number = phone_number def sanitize_phone_number(self): phone_number = self.phone_number phone = list(phone_number) prefix = phone[0] length = len(phone_number) if prefix == '+' and leng...
class Cleanphonenumber(object): def __init__(self, phone_number): self.phone_number = phone_number def sanitize_phone_number(self): phone_number = self.phone_number phone = list(phone_number) prefix = phone[0] length = len(phone_number) if prefix == '+' and leng...
""" Some convenience methods to manipulate sequence objects (ex: list, range, set, string) """ def chunks(l, n): """ Yield successive n-sized chunks from list l. Example: l = [1,2,3,4,5,6,7,8,9,10] c = list(chunks(l, 3)) # c will be equal "[ [1,2,3], [4,5,6], [7,8,9], [10]] """ f...
""" Some convenience methods to manipulate sequence objects (ex: list, range, set, string) """ def chunks(l, n): """ Yield successive n-sized chunks from list l. Example: l = [1,2,3,4,5,6,7,8,9,10] c = list(chunks(l, 3)) # c will be equal "[ [1,2,3], [4,5,6], [7,8,9], [10]] """ ...
# List of guide files to search guides = ['analytics_guide.md','angular_guide.md','api_guide.md','authentication_guide.md','cache_guide.md','hub_guide.md','i18n_guide.md','interactions_guide.md','logger_guide.md','pub_sub_guide.md','push_notifications_setup.md','service_workers_guide.md','storage_guide.md'] # Start of...
guides = ['analytics_guide.md', 'angular_guide.md', 'api_guide.md', 'authentication_guide.md', 'cache_guide.md', 'hub_guide.md', 'i18n_guide.md', 'interactions_guide.md', 'logger_guide.md', 'pub_sub_guide.md', 'push_notifications_setup.md', 'service_workers_guide.md', 'storage_guide.md'] filestart = '../docs/media/' sn...
x = 9 y = 3 # Arithmetic Operators print(x+y) #Addition print(x-y) #Subtraction print(x*y) #Multiplication print(x/y) #Division print(x%y) #Modulus print(x**y) #Exponantiation x = 9.191823 print(x//y) #Floor Division #Assignment Operators x = 9 # set x = 9 x += 3 # x = x + 3 print(x) x = 9 x -= 3 # x = x - 3 ...
x = 9 y = 3 print(x + y) print(x - y) print(x * y) print(x / y) print(x % y) print(x ** y) x = 9.191823 print(x // y) x = 9 x += 3 print(x) x = 9 x -= 3 print(x) x *= 3 print(x) x /= 3 print(x) x **= 3 print(x) x = 9 y = 3 print(x == y) print(x != y) print(x > y) print(x < y) print(x >= y) print(x <= y)
#!/usr/bin/env python # -*- coding: utf-8 -*- # # File Name: Problem_3.py # Project Name: WebLearn # Author: Benjamin Zhang # Created Time: 2019-01-12 21:45 # Version: 0.0.1.20190112 # # Copyright (c) Benjamin Zhang 2019 # All rights reserved. # name = ["Adam", "Seth", "Enosh", "Ke...
name = ['Adam', 'Seth', 'Enosh', 'Kenan', 'Mahalalel', 'Jared', 'Enoch', 'Methuselah', 'Lamech', 'Noah', 'Shem', 'Ham', 'Japheth'] age = [930, 912, 905, 910, 895, 962, 365, 969, 777, 0, 0, 0, 0] def find_seniority(string): for i in range(0, len(age)): if name[i] == string: return 10 if i > 9 el...
infile = open("./local_models/time-all.normalized","r") outfile = open("./clustering/initial.dat","w") listoflists = [] for line in infile: listoflists.append(line.strip().split()) numtopics = len(listoflists[0])-1 numwords = len(listoflists) for topic in range(1,numtopics+1): #fancy indexing because words are st...
infile = open('./local_models/time-all.normalized', 'r') outfile = open('./clustering/initial.dat', 'w') listoflists = [] for line in infile: listoflists.append(line.strip().split()) numtopics = len(listoflists[0]) - 1 numwords = len(listoflists) for topic in range(1, numtopics + 1): outfile.write(str(topic) + ...
def spam(): global eggs eggs = 'spam' def bacon(): eggs = 'bacon' def ham(): print(eggs) eggs = 12 spam() print(eggs) """ spam """
def spam(): global eggs eggs = 'spam' def bacon(): eggs = 'bacon' def ham(): print(eggs) eggs = 12 spam() print(eggs) '\nspam\n'
def check_ip_byte(string, i, chars_left, ip, dot='exist'): index, result = i + 1, 'fail' if len(string) - i >= chars_left: n = string[i] if n.isdigit(): i += 1 while n.isdigit(): if i < len(string): if string[i].isdigit(): ...
def check_ip_byte(string, i, chars_left, ip, dot='exist'): (index, result) = (i + 1, 'fail') if len(string) - i >= chars_left: n = string[i] if n.isdigit(): i += 1 while n.isdigit(): if i < len(string): if string[i].isdigit(): ...
class Solution: def findJudge(self, N: int, trust) -> int: helper = [set() for i in range(N)] for i, n in enumerate(trust): helper[n[0] - 1].add(n[1]) for i in range(N): if len(helper[i]) != 0: continue is_major = True for j, n...
class Solution: def find_judge(self, N: int, trust) -> int: helper = [set() for i in range(N)] for (i, n) in enumerate(trust): helper[n[0] - 1].add(n[1]) for i in range(N): if len(helper[i]) != 0: continue is_major = True for (...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. load("//antlir/bzl:oss_shim.bzl", "buck_genrule") def _get_build_info(): return struct( package_name = native.read_config("build_...
load('//antlir/bzl:oss_shim.bzl', 'buck_genrule') def _get_build_info(): return struct(package_name=native.read_config('build_info', 'package_name'), package_version=native.read_config('build_info', 'package_version'), revision=native.read_config('build_info', 'revision')) def initrd_release(name): info = _ge...
i = 0 for i in range(0, 100): if i % 2 == 0: print(i) i+= i
i = 0 for i in range(0, 100): if i % 2 == 0: print(i) i += i
"""\ Front-to-back rapid web development =================================== TurboGears brings together four major pieces to create an easy to install, easy to use web mega-framework. It covers everything from front end (MochiKit JavaScript for the browser, Genshi / Kid / Mako / Cheetah for templates in Python) to the...
"""Front-to-back rapid web development =================================== TurboGears brings together four major pieces to create an easy to install, easy to use web mega-framework. It covers everything from front end (MochiKit JavaScript for the browser, Genshi / Kid / Mako / Cheetah for templates in Python) to the c...
input = """jmp +336 jmp +593 jmp +121 acc -8 nop +459 jmp +451 acc -6 acc +23 acc +23 acc -2 jmp +113 acc -11 acc +25 jmp +529 acc +0 jmp +1 jmp +313 acc +30 nop +235 jmp +45 nop +195 acc -11 jmp +491 acc +6 nop +425 nop +68 acc +9 jmp -25 jmp +507 jmp +456 acc -1 acc +49 acc +5 jmp +31 acc +30 nop +513 jmp +499 nop +5...
input = 'jmp +336\njmp +593\njmp +121\nacc -8\nnop +459\njmp +451\nacc -6\nacc +23\nacc +23\nacc -2\njmp +113\nacc -11\nacc +25\njmp +529\nacc +0\njmp +1\njmp +313\nacc +30\nnop +235\njmp +45\nnop +195\nacc -11\njmp +491\nacc +6\nnop +425\nnop +68\nacc +9\njmp -25\njmp +507\njmp +456\nacc -1\nacc +49\nacc +5\njmp +31\n...
class componente: def equip(self): pass class CharacterConcreteComponent(componente): def __init__(self, name: str): self.name = name self.p1 = '' def e2(x): def a2(self): return f"{self.name} equipment:"+ x(self) return a2 @e2 def equip(self): ...
class Componente: def equip(self): pass class Characterconcretecomponent(componente): def __init__(self, name: str): self.name = name self.p1 = '' def e2(x): def a2(self): return f'{self.name} equipment:' + x(self) return a2 @e2 def equip(sel...
class PaymentAPIError(Exception): """ Raised when a payment related action fails. """ pass
class Paymentapierror(Exception): """ Raised when a payment related action fails. """ pass
class Meta(dict): def __getattr__(self, name): try: return self[name] except KeyError: raise AttributeError(name) def __setattr__(self, name, value): self[name] = value def bind(self, name, func): setattr(self.__class__, name, func)
class Meta(dict): def __getattr__(self, name): try: return self[name] except KeyError: raise attribute_error(name) def __setattr__(self, name, value): self[name] = value def bind(self, name, func): setattr(self.__class__, name, func)
# Rain_Water_Trapping def trappedWater(a, size) : # left[i] stores height of tallest bar to the to left of it including itself left = [0] * size # Right [i] stores height of tallest bar to the to right of it including itself right = [0] * size # Initialize result waterVolume = 0 ...
def trapped_water(a, size): left = [0] * size right = [0] * size water_volume = 0 left[0] = a[0] for i in range(1, size): left[i] = max(left[i - 1], a[i]) right[size - 1] = a[size - 1] for i in range(size - 2, -1, -1): right[i] = max(right[i + 1], a[i]) for i in range(0, ...
# -*- coding: utf-8 -*- BOT_NAME = 'spider' SPIDER_MODULES = ['spiders'] NEWSPIDER_MODULE = 'spiders' ROBOTSTXT_OBEY = False # change cookie to yours #DEFAULT_REQUEST_HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36', # '...
bot_name = 'spider' spider_modules = ['spiders'] newspider_module = 'spiders' robotstxt_obey = False default_request_headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0', 'Cookie': 'SUB=_2A25MjPT-DeRhGeNM6VcX-SrJzjuIHXVvjpy2rDV6PUJbkdCOLXXzkW1NTiDEuD0Z5qOTeRYpEH6...
# -*- coding: utf-8 -*- # Copyright (2018) Hewlett Packard Enterprise Development LP # # 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...
""" Dict of schemas version used by application. """ schemas = {'ServiceRoot': 'ServiceRoot.v1_3_1.json', 'ChassisCollection': 'ChassisCollection.json', 'Chassis': 'Chassis.v1_7_0.json', 'CollectionCapabilities': 'CollectionCapabilities.v1_0_0.json', 'CompositionService': 'CompositionService.v1_0_1.json', 'ComputerSyst...
#Function to remove a given word from a list and strip it at the same time. def remove_and_split(string, word): newStr = string.replace(word, "") return newStr.strip() this = " Root is a Computer " n = remove_and_split(this, "Root") print(n)
def remove_and_split(string, word): new_str = string.replace(word, '') return newStr.strip() this = ' Root is a Computer ' n = remove_and_split(this, 'Root') print(n)
tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] def printTable(table): colWidth = [0] * len(table) #List of rjust values to be used for i in range(len(table)): #iterates through the 3 lists ...
table_data = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] def print_table(table): col_width = [0] * len(table) for i in range(len(table)): rjustlength = 0 for j in table[i]: if len(j) > rjustlength: ...
N = int(input()) M = int(input()) S = int(input()) for num in range(M, N - 1, - 1): if num % 2 == 0 and num % 3 == 0: if num == S: break print(num, end=" ")
n = int(input()) m = int(input()) s = int(input()) for num in range(M, N - 1, -1): if num % 2 == 0 and num % 3 == 0: if num == S: break print(num, end=' ')
f=open('demo1.txt','a') a=int(input('enter number ')) f.write('hello hi\n') f.write('world') f.write(str(a)) f.close()
f = open('demo1.txt', 'a') a = int(input('enter number ')) f.write('hello hi\n') f.write('world') f.write(str(a)) f.close()
ALIEN = {'.----': '1', '..---': '2', '...--': '3', '....-': '4', '.....': '5', '-....': '6', '--...': '7', '---..': '8', '----.': '9', '-----': '0'} def morse_converter(s): return int(''.join(ALIEN[s[a:a + 5]] for a in xrange(0, len(s), 5)))
alien = {'.----': '1', '..---': '2', '...--': '3', '....-': '4', '.....': '5', '-....': '6', '--...': '7', '---..': '8', '----.': '9', '-----': '0'} def morse_converter(s): return int(''.join((ALIEN[s[a:a + 5]] for a in xrange(0, len(s), 5))))
def calculateAverageAge(students): add_age = 0 for thing in students.values(): age = thing['age'] add_age = add_age + age return(add_age / len(students.keys())) students = { "Peter": {"age": 10, "address": "Lisbon"}, "Isabel": {"age": 11, "address": "Sesimbra"}, "Ann...
def calculate_average_age(students): add_age = 0 for thing in students.values(): age = thing['age'] add_age = add_age + age return add_age / len(students.keys()) students = {'Peter': {'age': 10, 'address': 'Lisbon'}, 'Isabel': {'age': 11, 'address': 'Sesimbra'}, 'Anna': {'age': 9, 'address':...
# very old file that isn't very useful but it works with things so I'm keeping it for now class Rectangle: current_id = 0 tolerable_distance_to_combine_rectangles = 0.00005 # buildings need to be this (lat/long degrees) away to merge def __init__(self, init_points, to_id=True): self.points = init_...
class Rectangle: current_id = 0 tolerable_distance_to_combine_rectangles = 5e-05 def __init__(self, init_points, to_id=True): self.points = init_points self.deleted_rect_ids = [] if to_id: Rectangle.current_id += 1 self.id = Rectangle.current_id def merg...
class Solution: def restoreString(self, s: str, indices: List[int]) -> str: res = [0] * len(indices) for i, j in zip(s, indices) : res[j] = i return "".join(res)
class Solution: def restore_string(self, s: str, indices: List[int]) -> str: res = [0] * len(indices) for (i, j) in zip(s, indices): res[j] = i return ''.join(res)
class Move: def __init__(self, dest_rank_id, from_rank_id): self.dest_rank_id = dest_rank_id self.from_rank_id = from_rank_id def output(self): out_str = '' out_str += str(self.from_rank_id) out_str += ' -> ' out_str += str(self.dest_rank_id) print(out_str)
class Move: def __init__(self, dest_rank_id, from_rank_id): self.dest_rank_id = dest_rank_id self.from_rank_id = from_rank_id def output(self): out_str = '' out_str += str(self.from_rank_id) out_str += ' -> ' out_str += str(self.dest_rank_id) print(out_s...
# MatchJoin takes a list of matchers and joins them, to essentially # make a conjunctive matcher class MatchJoin: # @matchers A list of matchers to join into a single match for example # [ # LiteralMatch("hello ") # LiteralMatch("world") # ] def __init__(self, matchers : list): self....
class Matchjoin: def __init__(self, matchers: list): self.to_string_call_count = None self.matchers = matchers def parser(self, body: str, hard_fail=True): result = [] head = 0 for matcher in self.matchers: sub_body = body[head:] out = matcher.pa...
# Finds the optmial cost def find_opt_cost(data): min_cost = data[data.A == -1]['cost'].values[0] return min_cost # Finds the energy corresponding to optimal route def find_opt_energy(data): opt_energy = data[data.A == -1]['energy'].values[0] return opt_energy # Returns true if optimal route is obs...
def find_opt_cost(data): min_cost = data[data.A == -1]['cost'].values[0] return min_cost def find_opt_energy(data): opt_energy = data[data.A == -1]['energy'].values[0] return opt_energy def opt_found(data): min_cost = find_opt_cost(data) data_d = data[(data.cost == min_cost) & (data.valid == T...
class LayeredStreamReaderBase: __slots__ = {'upstream'} def __init__(self, upstream): self.upstream = upstream async def read(self, n): return await self.upstream.read(n) async def readexactly(self, n): return await self.upstream.readexactly(n)
class Layeredstreamreaderbase: __slots__ = {'upstream'} def __init__(self, upstream): self.upstream = upstream async def read(self, n): return await self.upstream.read(n) async def readexactly(self, n): return await self.upstream.readexactly(n)
# class class_name: # def __init__(self): # # def function_name(self): # return class Athlete: def __init__(self, value='Jane'): self.inner_value = value print(self.inner_value) def getInnerValue(self): return self.inner_value class InheritanceClass(Athlete): def _...
class Athlete: def __init__(self, value='Jane'): self.inner_value = value print(self.inner_value) def get_inner_value(self): return self.inner_value class Inheritanceclass(Athlete): def __init__(self): super().__init__() def set_value(self, first_value): self...
Import("env") # # Add -m32 to the linker (since PlatformIo is not capable directly!) # (and since we are at it, make everyting statically linked ;-) # env.Append( LINKFLAGS=[ "-m32", "-static-libgcc", "-static-libstdc++" ] )
import('env') env.Append(LINKFLAGS=['-m32', '-static-libgcc', '-static-libstdc++'])