content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
""" secstill plugin Senerio This plugin will monitor camera view using motion tracking. When motion tracking is triggered, the camera will take an HD still image then stop and monitor for the next motion tracking event. There will be a delay in taking the image due to camera change from streaming mode therefore faster...
""" secstill plugin Senerio This plugin will monitor camera view using motion tracking. When motion tracking is triggered, the camera will take an HD still image then stop and monitor for the next motion tracking event. There will be a delay in taking the image due to camera change from streaming mode therefore faster...
#!/usr/bin/env python # -*- coding: utf-8 -*- def check(N,S): if S=='.': return N+1,False else: return N,True def main(): H,W,X,Y = map(int,input().split()) S = [list(map(str,input())) for i in range(H)] X -= 1 Y -= 1 ans = -3 for i in range(X,H,1): ans,flag = ...
def check(N, S): if S == '.': return (N + 1, False) else: return (N, True) def main(): (h, w, x, y) = map(int, input().split()) s = [list(map(str, input())) for i in range(H)] x -= 1 y -= 1 ans = -3 for i in range(X, H, 1): (ans, flag) = check(ans, S[i][Y]) ...
class Pet: def __init__(self, name, age): self.name = name self.age = age def show(self): print(f'Hello! I am {self.name} and I am {self.age} years old!') def speak(self): print('I dont know what I say!') class Cat(Pet): def __init__(self, name, age, color): su...
class Pet: def __init__(self, name, age): self.name = name self.age = age def show(self): print(f'Hello! I am {self.name} and I am {self.age} years old!') def speak(self): print('I dont know what I say!') class Cat(Pet): def __init__(self, name, age, color): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 31 02:08:01 2020 @author: mlampert """ """ USEFUL COMMANDS WHICH I NEED FROM TIME TO TIME """
""" Created on Sat Oct 31 02:08:01 2020 @author: mlampert """ '\nUSEFUL COMMANDS WHICH I NEED FROM TIME TO TIME\n'
# Python dictionary with keys having multiple inputs # First Example dict = {} x, y, z = 10, 20, 30 dict[x, y, z] = x + y - z x, y, z = 5, 2, 4 dict[x, y, z] = x + y - z print(dict) # Second Example places = {("19.07'53.2", "72.54'51.0"):"Mumbai", ("28.33'34.1", "77.06'16.6"):"Delhi"} print(places) lat = [] l...
dict = {} (x, y, z) = (10, 20, 30) dict[x, y, z] = x + y - z (x, y, z) = (5, 2, 4) dict[x, y, z] = x + y - z print(dict) places = {("19.07'53.2", "72.54'51.0"): 'Mumbai', ("28.33'34.1", "77.06'16.6"): 'Delhi'} print(places) lat = [] long = [] plc = [] for i in places: lat.append(i[0]) long.append(i[1]) plc....
# Warning: This is an example of how you should *not* # implement stimulus presentation in time-critical # experiments. # # Prepare canvas 1 and show it canvas1 = Canvas() canvas1 += Text('This is the first canvas') t1 = canvas1.show() # Sleep for 95 ms to get a 100 ms delay clock.sleep(95) # Prepare canvas 2 and show ...
canvas1 = canvas() canvas1 += text('This is the first canvas') t1 = canvas1.show() clock.sleep(95) canvas2 = canvas() canvas2 += text('This is the second canvas') t2 = canvas2.show() print('Actual delay: %s' % (t2 - t1))
#!/usr/bin/env python3 a = [] s = input() while s != "end": a.append(s) s = input() n = input() i = 0 while i < len(a): s = a[i] if s[0] == n: print(s) i = i + 1
a = [] s = input() while s != 'end': a.append(s) s = input() n = input() i = 0 while i < len(a): s = a[i] if s[0] == n: print(s) i = i + 1
# Scrapy settings for booksbot project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-middlewar...
bot_name = 'booksbot' spider_modules = ['booksbot.spiders'] newspider_module = 'booksbot.spiders' robotstxt_obey = True spider_middlewares = {'scrapy_autounit.AutounitMiddleware': 950} autounit_enabled = False
coordinates_7F0030 = ((151, 114), (151, 115), (151, 116), (151, 117), (151, 118), (151, 119), (151, 120), (151, 121), (151, 122), (151, 123), (151, 124), (151, 125), (151, 126), (151, 127), (151, 128), (151, 129), (151, 130), (151, 131), (151, 132), (151, 133), (151, 135), (152, 111), (152, 113), (152, 135), (153, 11...
coordinates_7_f0030 = ((151, 114), (151, 115), (151, 116), (151, 117), (151, 118), (151, 119), (151, 120), (151, 121), (151, 122), (151, 123), (151, 124), (151, 125), (151, 126), (151, 127), (151, 128), (151, 129), (151, 130), (151, 131), (151, 132), (151, 133), (151, 135), (152, 111), (152, 113), (152, 135), (153, 113...
x = getattr(None, '') # 0 <mixed> l = [] # 0 [<mixed>] l.extend(x) # 0 [<mixed>] # e 0 # TODO: test converting to top s = [ # 0 [(str, int)] ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('',...
x = getattr(None, '') l = [] l.extend(x) s = [('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('', 1), ('',...
# Algorithm: # This pattern is an observational one. For eg, if n = 3 # 3 3 3 3 3 # 3 2 2 2 3 # 3 2 1 2 3 # 3 2 2 2 3 # 3 3 3 3 3 # The no. of columns and rows are equal to (2 * n - 1). # The first (n - 1) and last (n - 1) rows can easily be printed using nested for loops # The mi...
n = int(input()) for i in range(1, n): temp = n for j in range(1, n): if j <= i and j != 1: temp -= 1 print(temp, end=' ') print(temp, end=' ') for j in range(1, n): if j >= n - i + 1: temp += 1 print(temp, end=' ') print('') temp = n for i in ...
############################### # Overview # # Without using built a math # library, calculate the square root # of a number. # # Assume number is not negative. # Comlex numbers out of scope. # square root 4 -> 2 ############################### # Using newton's method # y ^ (1/2) = x => # y = x^2 ...
def calc_squre_root(y): x_t = y tol = 1000000 while tol > 1e-06: fx = x_t ** 2 - y fprime = 2 * x_t x_t_1 = x_t - fx / fprime tol = x_t_1 - x_t if tol < 0: tol = -1 * tol x_t = x_t_1 return x_t_1 calc_squre_root(4) calc_squre_root(9) calc_squre...
class A: pass def foo(): pass class B: """""" pass def bar(): """""" pass class C: @property def x(self): return 42 @x.setter def x(self, value): pass @x.deleter def x(self): pass
class A: pass def foo(): pass class B: """""" pass def bar(): """""" pass class C: @property def x(self): return 42 @x.setter def x(self, value): pass @x.deleter def x(self): pass
def make_url_part(name, value, value_type): if value == None: return '' if type(value) != value_type: raise ValueError('{}={} must be {}'.format( name, value, value_type)) result = "&${}={}".format(name, value) return result
def make_url_part(name, value, value_type): if value == None: return '' if type(value) != value_type: raise value_error('{}={} must be {}'.format(name, value, value_type)) result = '&${}={}'.format(name, value) return result
# Copyright 2021 The Bazel 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 applicable la...
""" Definition of proto_common module. """ load(':common/proto/proto_semantics.bzl', 'semantics') load(':common/paths.bzl', 'paths') proto_info = _builtins.toplevel.ProtoInfo native_proto_common = _builtins.toplevel.proto_common def _join(*path): return '/'.join([p for p in path if p != '']) def _create_proto_inf...
__version__ = "1.4.0" __title__ = "ADLES" __summary__ = "Automated Deployment of Lab Environments System (ADLES)" __license__ = "Apache 2.0" __author__ = "Christopher Goes" __email__ = "goesc@acm.org" __url__ = "https://github.com/GhostofGoes/ADLES" __urls__ = { 'GitHub': __url__, 'Homepage': 'https://ghost...
__version__ = '1.4.0' __title__ = 'ADLES' __summary__ = 'Automated Deployment of Lab Environments System (ADLES)' __license__ = 'Apache 2.0' __author__ = 'Christopher Goes' __email__ = 'goesc@acm.org' __url__ = 'https://github.com/GhostofGoes/ADLES' __urls__ = {'GitHub': __url__, 'Homepage': 'https://ghostofgoes.github...
bin1=input("what kind of fruit do you want?") if bin1=="apples": print("apples in bin 1") elif bin1=="orenges": print("orenges in bin 2") elif bin1=="bananas": print("bananas in bin 3") else: print("Error! I dont recognize this fruit!")
bin1 = input('what kind of fruit do you want?') if bin1 == 'apples': print('apples in bin 1') elif bin1 == 'orenges': print('orenges in bin 2') elif bin1 == 'bananas': print('bananas in bin 3') else: print('Error! I dont recognize this fruit!')
# # PySNMP MIB module HP-ICF-IPCONFIG (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-IPCONFIG # Produced by pysmi-0.3.4 at Mon Apr 29 19:21:43 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, constraints_union, constraints_intersection, value_range_constraint) ...
# coding: utf8 '''This file contains all the DAta archetype structures needed for the portal ''' class UnitView(): '''represent an article object in the main content part <div class="unitview"> <div class="unitview-header"> <h1 class="unitview-title">Sample Post 1</h1...
"""This file contains all the DAta archetype structures needed for the portal """ class Unitview: """represent an article object in the main content part <div class="unitview"> <div class="unitview-header"> <h1 class="unitview-title">Sample Post 1</h1> <di...
message = "This is a test at replacing text" print(message) message = "Change of text" print(message)
message = 'This is a test at replacing text' print(message) message = 'Change of text' print(message)
class Node: def __init__(self, key=None, parent=None): self.key = key self.parent = parent self.left = None self.right = None class BinarySearchTree: def __init__(self, key=None): self.root = None if key is not None: self.root = Node(key) def pr...
class Node: def __init__(self, key=None, parent=None): self.key = key self.parent = parent self.left = None self.right = None class Binarysearchtree: def __init__(self, key=None): self.root = None if key is not None: self.root = node(key) def p...
if __name__ == '__main__': the_list = list() for _ in range(int(input())): command, *args = input().split() try: getattr(the_list, command)(*(int(arg) for arg in args)) except AttributeError: print(the_list)
if __name__ == '__main__': the_list = list() for _ in range(int(input())): (command, *args) = input().split() try: getattr(the_list, command)(*(int(arg) for arg in args)) except AttributeError: print(the_list)
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root: return root.right, root.left = root.left, root.right self.invertTr...
class Treenode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def invert_tree(self, root: TreeNode) -> TreeNode: if not root: return (root.right, root.left) = (root.left, root.right) ...
def config_list_to_dict(l): d = {} for kv in l: if kv.count("=") != 1: raise ValueError(f"invalid 'key=value' pair: {kv}") k, v = kv.split("=") if len(v) == 0: raise ValueError(f"invalid 'key=value' pair: {kv}") _dot_to_dict(d, k, v) return d def ...
def config_list_to_dict(l): d = {} for kv in l: if kv.count('=') != 1: raise value_error(f"invalid 'key=value' pair: {kv}") (k, v) = kv.split('=') if len(v) == 0: raise value_error(f"invalid 'key=value' pair: {kv}") _dot_to_dict(d, k, v) return d def ...
# Return the root of the modified BST after deleting the node with value X def inorderSuccessor(root,ans,key,parent,node): if root is None: return False currParent=parent[0] parent[0]=root if root.data == key : node[0]=root if root.right: curr=root.right w...
def inorder_successor(root, ans, key, parent, node): if root is None: return False curr_parent = parent[0] parent[0] = root if root.data == key: node[0] = root if root.right: curr = root.right while curr.left: parent[0] = curr ...
# 1021 valor = float(input()) notas = [100, 50, 20, 10, 5, 2] moedas = [1, 0.50, 0.25, 0.10, 0.05, 0.01] print("NOTAS:") for nota in notas: quantidade_nota = int(valor / nota) print("{} notas(s) de R$ {:.2f}".format(quantidade_nota, nota)) valor -= quantidade_nota * nota print("MOEDAS:") for moeda in mo...
valor = float(input()) notas = [100, 50, 20, 10, 5, 2] moedas = [1, 0.5, 0.25, 0.1, 0.05, 0.01] print('NOTAS:') for nota in notas: quantidade_nota = int(valor / nota) print('{} notas(s) de R$ {:.2f}'.format(quantidade_nota, nota)) valor -= quantidade_nota * nota print('MOEDAS:') for moeda in moedas: qua...
TIMER_READ = 1; # ms SILAB_IMAGE_SIZE = 16384 SILAB_IMAGE_TOTAL_SUBPART = 144 # size/114+1 SILAB_BOOTLOADER_SIZE = 9216 SILAB_BOOTLOADER_TOTAL_SUBPART = 81 # size/114+1 BT_IMAGE_SIZE = 124928 BT_IMAGE_TOTAL_SUBPART = 1952 # size/64 BT_BOOTLOADER_SIZE = 4096 BT_BOOTLOADER_TOTAL_SUBPART = 64 # size/64 RFID_...
timer_read = 1 silab_image_size = 16384 silab_image_total_subpart = 144 silab_bootloader_size = 9216 silab_bootloader_total_subpart = 81 bt_image_size = 124928 bt_image_total_subpart = 1952 bt_bootloader_size = 4096 bt_bootloader_total_subpart = 64 rfid_image_size = 203776 rfid_image_total_subpart = 6368 rfid_bootloade...
#Shape of capital A: def for_A(): """printing capital 'A' using for loop""" for row in range(6): for col in range(11): if row+col == 5 or col-row==5 or row==3 and col not in(0,1,9,10): print("*",end=" ") else: print(" ",end=" ") pr...
def for_a(): """printing capital 'A' using for loop""" for row in range(6): for col in range(11): if row + col == 5 or col - row == 5 or (row == 3 and col not in (0, 1, 9, 10)): print('*', end=' ') else: print(' ', end=' ') print() def whi...
def get_string(addr): out = "" while True: if Byte(addr) != 0: out += chr(Byte(addr)) else: break addr += 1 return out def get_string_at(addr): return get_string(addr - 0x12040 + 0x001fb5a0) def get_i32_at(addr): addr = addr - 0x12040 + 0x001fb5a0 ...
def get_string(addr): out = '' while True: if byte(addr) != 0: out += chr(byte(addr)) else: break addr += 1 return out def get_string_at(addr): return get_string(addr - 73792 + 2078112) def get_i32_at(addr): addr = addr - 73792 + 2078112 return b...
class Solution: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: n = len(arr) # initialize hashmap mapping = {p[0]: p for p in pieces} i = 0 while i < n: # find target piece if arr[i] not in mapping: return Fals...
class Solution: def can_form_array(self, arr: List[int], pieces: List[List[int]]) -> bool: n = len(arr) mapping = {p[0]: p for p in pieces} i = 0 while i < n: if arr[i] not in mapping: return False target_piece = mapping[arr[i]] fo...
APP_ERROR_SEND_NOTIFICATION = True APP_ERROR_RECIPIENT_EMAIL = ('dev@example.com',) APP_ERROR_EMAIL_SENDER = "server@example.com" APP_ERROR_SUBJECT_PREFIX = "" APP_ERROR_MASK_WITH = "**************" APP_ERROR_MASKED_KEY_HAS = ("password", "secret") APP_ERROR_URL_PREFIX = "/dev/error"
app_error_send_notification = True app_error_recipient_email = ('dev@example.com',) app_error_email_sender = 'server@example.com' app_error_subject_prefix = '' app_error_mask_with = '**************' app_error_masked_key_has = ('password', 'secret') app_error_url_prefix = '/dev/error'
#!/usr/bin/env python # Written against python 3.3.1 # Matasano Problem 21 # Implement the MT19937 Mersenne Twister RNG # generated from code on the wikipedia class MT19937: def __init__(self, seed): self.MT = [0] * 624; self.index = 0; self.seed = 0; self.initialize_gene...
class Mt19937: def __init__(self, seed): self.MT = [0] * 624 self.index = 0 self.seed = 0 self.initialize_generator(seed) def initialize_generator(self, seed): i = 0 self.MT[0] = seed for i in range(1, 624): self.MT[i] = 4294967295 & 18124332...
# https://codeforces.com/problemset/problem/96/A teams = input() + "-" count = 0 isOnes = True if teams[0] == "1" else False isDangerous = False for player in teams: if count == 7: isDangerous = True break if player == "1": if not(isOnes): count = 0 ...
teams = input() + '-' count = 0 is_ones = True if teams[0] == '1' else False is_dangerous = False for player in teams: if count == 7: is_dangerous = True break if player == '1': if not isOnes: count = 0 is_ones = True count += 1 elif player == '0': ...
#! /usr/bin/env python """ pyweek 22 entry 'You can't let him in here.""" __author__ = "Rex Allison" __copyright__ = "Copyright 2016, Rex Allison" __license__ = "MIT" nemesis = [ # nemesis 1 ' ' ,' ' ,' ' ,' X' ...
""" pyweek 22 entry 'You can't let him in here.""" __author__ = 'Rex Allison' __copyright__ = 'Copyright 2016, Rex Allison' __license__ = 'MIT' nemesis = [' ', ' ', ' ', ' X', ' XXXX', ' XXXXXX', ' XXXX', ' X', ' ', ' ', ' ', ' ', ' ', ' ...
def try_or_default(default_value, func): def wrap(*args, **kwargs): try: return func(*args, **kwargs) except: return default_value return wrap def try_or_false(func): return try_or_default(False, func) def try_or_true(func): return try_or_default(True, func)
def try_or_default(default_value, func): def wrap(*args, **kwargs): try: return func(*args, **kwargs) except: return default_value return wrap def try_or_false(func): return try_or_default(False, func) def try_or_true(func): return try_or_default(True, func)
{ 'variables': { 'target_arch': 'ia32', 'VERSION_FULL': '<!(python tools/version.py)', 'VERSION_MAJOR': '<!(python tools/version.py major)', 'VERSION_MINOR': '<!(python tools/version.py minor)', 'VERSION_PATCH': '<!(python tools/version.py patch)', 'VERSION_RELEASE': '<!(python tools/version.p...
{'variables': {'target_arch': 'ia32', 'VERSION_FULL': '<!(python tools/version.py)', 'VERSION_MAJOR': '<!(python tools/version.py major)', 'VERSION_MINOR': '<!(python tools/version.py minor)', 'VERSION_PATCH': '<!(python tools/version.py patch)', 'VERSION_RELEASE': '<!(python tools/version.py release)'}, 'targets': [{'...
class StorageResult: def __init__(self, result=None): if result is None: self.total = 0 self._hits = [] self.chunk = 0 else: self.total = result['hits']['total']['value'] self._hits = result['hits']['hits'] self.chunk = len(self...
class Storageresult: def __init__(self, result=None): if result is None: self.total = 0 self._hits = [] self.chunk = 0 else: self.total = result['hits']['total']['value'] self._hits = result['hits']['hits'] self.chunk = len(sel...
class Sortness: def getSortness(self, a): s = 0.0 for i, e in enumerate(a): s += len(filter(lambda j: j > e, a[:i])) s += len(filter(lambda j: j < e, a[i+1:])) return s / len(a)
class Sortness: def get_sortness(self, a): s = 0.0 for (i, e) in enumerate(a): s += len(filter(lambda j: j > e, a[:i])) s += len(filter(lambda j: j < e, a[i + 1:])) return s / len(a)
# This code has to be added to the corresponding __init__.py DRIVERS["lis3dh"] = ["LIS3DH"]
DRIVERS['lis3dh'] = ['LIS3DH']
def hello(name): return 'Hello, {}.'.format(name) def test_hello(): assert 'Hello, Fred.' == hello('Fred') if __name__ == '__main__': print(hello('Taro'))
def hello(name): return 'Hello, {}.'.format(name) def test_hello(): assert 'Hello, Fred.' == hello('Fred') if __name__ == '__main__': print(hello('Taro'))
# -*- coding: utf-8 -*- INSTALLED_APPS += ("ags2sld",) DATA_UPLOAD_MAX_MEMORY_SIZE = 1073741824 FILE_UPLOAD_MAX_MEMORY_SIZE = 1073741824 # maximum file upload 1GB
installed_apps += ('ags2sld',) data_upload_max_memory_size = 1073741824 file_upload_max_memory_size = 1073741824
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
"""A few bit hacks (from https://graphics.stanford.edu/~seander/bithacks.html). """ def next_power_of_two(i): """Returns the next highest power of two. Args: i: Is the number and should be a 32 bit integer. Returns: The next highest power of two. """ i -= 1 i |= i >> 1 i |...
h,m=map(int,input().split());m+=60*h-45 if m<0: m+=24*60 print(m//60,m%60)
(h, m) = map(int, input().split()) m += 60 * h - 45 if m < 0: m += 24 * 60 print(m // 60, m % 60)
## func def make_withdrawal(balance): def inner(withdraw): balance -= withdraw if balance <0: print("Error: withdraw amount is more than initial balance") else: return balance return inner ## Explain print("updating the balance inner function doesn't work. In the inner function block, variable balance's...
def make_withdrawal(balance): def inner(withdraw): balance -= withdraw if balance < 0: print('Error: withdraw amount is more than initial balance') else: return balance return inner print("updating the balance inner function doesn't work. In the inner function bl...
class LinkedListMode: def __init__(self, value): self.vale = value self.next = None def reverse(head_of_list): current = head_of_list previous = None next = None # until we have 'fallen off' the end of the list while current: # copy a pointer to the next element ...
class Linkedlistmode: def __init__(self, value): self.vale = value self.next = None def reverse(head_of_list): current = head_of_list previous = None next = None while current: next = current.next current.next = previous previous = current current = ...
# # @lc app=leetcode id=657 lang=python3 # # [657] Robot Return to Origin # # https://leetcode.com/problems/robot-return-to-origin/description/ # # algorithms # Easy (74.23%) # Total Accepted: 288.7K # Total Submissions: 388.7K # Testcase Example: '"UD"' # # There is a robot starting at position (0, 0), the origin,...
class Solution: def judge_circle(self, moves: str) -> bool: num_l = 0 num_r = 0 num_u = 0 num_d = 0 for s in moves: if s == 'L': num_l += 1 elif s == 'U': num_u += 1 elif s == 'R': num_r += 1...
def insertion_sort(arr): length = len(arr) for i in range(1, length): #Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position key = arr[i] j=i-1 while( j>=0 and arr[j]>key): arr[j+1] = arr[j] ...
def insertion_sort(arr): length = len(arr) for i in range(1, length): key = arr[i] j = i - 1 while j >= 0 and arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key return arr
task_dataset = "entry-small-1" # number of individuals for each population population_size = 40 # number of generations (rounds) generations = 1000 exitAfter = 250 # for controlling the time scheduling, in minutes block_size = 10 # in minutes (less than or equal 1 hour) # define the parents selection method for cro...
task_dataset = 'entry-small-1' population_size = 40 generations = 1000 exit_after = 250 block_size = 10 select_parents_method = 'roulette' mutation_rate = 5 use_pace = False use_pace_width = True pace_method = 1 use_employee_wage = True use_equipment_cost = True auto_adjust = True
t = """DrawBot is an powerful, free application for MacOSX that invites you to write simple Python scripts to generate two-dimensional graphics. The builtin graphics primitives support rectangles, ovals, (bezier) paths, polygons, text objects and transparency. DrawBot is an ideal tool to teach the basics of programmin...
t = 'DrawBot is an powerful, free application for MacOSX that invites you to write simple Python scripts to generate two-dimensional graphics. The builtin graphics primitives support rectangles, ovals, (bezier) paths, polygons, text objects and transparency. \nDrawBot is an ideal tool to teach the basics of programming...
class Solution: def gen(self, nums, target): for i, A in enumerate(nums, 0): for k, B in enumerate(nums[i + 1:], i + 1): if target - A == B: yield list((i, k)) def twoSum(self, nums: List[int], target: int) -> List[int]: for a ...
class Solution: def gen(self, nums, target): for (i, a) in enumerate(nums, 0): for (k, b) in enumerate(nums[i + 1:], i + 1): if target - A == B: yield list((i, k)) def two_sum(self, nums: List[int], target: int) -> List[int]: for a in self.gen(nu...
""" Holds all global app variables. """ SUPPLIER_DEFAULT_INVENTORY_INTERVAL = 86400 THK_VERSION_NUMBER = "2.0.0" THK_VERSION_NAME = "Arrakis" THK_CYCLE_PID = "ThunderhawkCycle" THK_CYCLE_LAST_POSITION = "thunderhawk cycle last position" """ Collections. """ MONGO_USERS_COLLECTION = "Users" MONGO_SUPPLIER_REGISTER_CO...
""" Holds all global app variables. """ supplier_default_inventory_interval = 86400 thk_version_number = '2.0.0' thk_version_name = 'Arrakis' thk_cycle_pid = 'ThunderhawkCycle' thk_cycle_last_position = 'thunderhawk cycle last position' '\nCollections.\n' mongo_users_collection = 'Users' mongo_supplier_register_collect...
class Solution: def fib(self, n: int) -> int: if (n == 0): return 0 if (n == 1): return 1 last = 1 lastlast = 0 for i in range(n-1): tmp = last last += lastlast lastlast = tmp return last
class Solution: def fib(self, n: int) -> int: if n == 0: return 0 if n == 1: return 1 last = 1 lastlast = 0 for i in range(n - 1): tmp = last last += lastlast lastlast = tmp return last
# heuristic monster types lists ONLY_RANGED_SLOW_MONSTERS = ['floating eye', 'blue jelly', 'brown mold', 'gas spore', 'acid blob'] EXPLODING_MONSTERS = ['yellow light', 'gas spore', 'flaming sphere', 'freezing sphere', 'shocking sphere'] INSECTS = ['giant ant', 'killer bee', 'soldier ant', 'fire ant', 'giant beetle', '...
only_ranged_slow_monsters = ['floating eye', 'blue jelly', 'brown mold', 'gas spore', 'acid blob'] exploding_monsters = ['yellow light', 'gas spore', 'flaming sphere', 'freezing sphere', 'shocking sphere'] insects = ['giant ant', 'killer bee', 'soldier ant', 'fire ant', 'giant beetle', 'queen bee'] weak_monsters = ['li...
Point = tuple([int, int]) class Field: """Placeholder object for a single field in the grid. It can empty, inaccessible, etc. Object should fully describe what's at `self.point`, but implement no mechanism for change.""" def __init__(self, point: Point): self.point = point self.p...
point = tuple([int, int]) class Field: """Placeholder object for a single field in the grid. It can empty, inaccessible, etc. Object should fully describe what's at `self.point`, but implement no mechanism for change.""" def __init__(self, point: Point): self.point = point self.pi...
''' For a non-negative integer X, the array-form of X is an array of its digits in left to right order. For example, if X = 1231, then the array form is [1,2,3,1]. Given the array-form A of a non-negative integer X, return the array-form of the integer X+K. Example 1: Input: A = [1,2,0,0], K = 34 Output: [1,2,3,...
""" For a non-negative integer X, the array-form of X is an array of its digits in left to right order. For example, if X = 1231, then the array form is [1,2,3,1]. Given the array-form A of a non-negative integer X, return the array-form of the integer X+K. Example 1: Input: A = [1,2,0,0], K = 34 Output: [1,2,3,...
class A: def __init__(self,a): self.a = a a=A(1) b=A(2) c=A(3) abc = [a,b,c] for i in abc[1:]: if i.a>2: i.a=0 abc.remove(i) for i in abc: print(i.a)
class A: def __init__(self, a): self.a = a a = a(1) b = a(2) c = a(3) abc = [a, b, c] for i in abc[1:]: if i.a > 2: i.a = 0 abc.remove(i) for i in abc: print(i.a)
# -*- coding: utf-8 -*- class TracimError(Exception): pass class RunTimeError(TracimError): pass class ContentRevisionUpdateError(RuntimeError): pass class ContentRevisionDeleteError(ContentRevisionUpdateError): pass class ConfigurationError(TracimError): pass class AlreadyExistError(Tra...
class Tracimerror(Exception): pass class Runtimeerror(TracimError): pass class Contentrevisionupdateerror(RuntimeError): pass class Contentrevisiondeleteerror(ContentRevisionUpdateError): pass class Configurationerror(TracimError): pass class Alreadyexisterror(TracimError): pass class Comm...
class Solution: """ @param x: the base number @param n: the power number @return: the result """ def myPow(self, x, n): negative = False if n < 0: negative = True n = -n ans = 1 while n > 0: times = 1 multiply = x ...
class Solution: """ @param x: the base number @param n: the power number @return: the result """ def my_pow(self, x, n): negative = False if n < 0: negative = True n = -n ans = 1 while n > 0: times = 1 multiply = x ...
# Video - https://youtu.be/PmW8NfctNpk def sum_of_digits(n): n = abs(n) digits = [] char_digits = list(str(n)) for char_digit in char_digits: digits.append(int(char_digit)) return sum(digits) tests = [ (1325132435356, 43), (123, 6), (6, 6), (-10, 1) ] for n, expected in...
def sum_of_digits(n): n = abs(n) digits = [] char_digits = list(str(n)) for char_digit in char_digits: digits.append(int(char_digit)) return sum(digits) tests = [(1325132435356, 43), (123, 6), (6, 6), (-10, 1)] for (n, expected) in tests: result = sum_of_digits(n) print(result == exp...
#!/usr/bin/env python3 class Armor: ARMOR = { "Festival T-Shirt":{"defense":2, "value":6, "itemClass":"newb", "desc":"+02 Defense"}, "Offshore Overalls":{"defense":5, "value":10, "itemClass":"hunter", "desc":"+05 Defense - Hunter Classes Only"}, "Cotton Affliction Shirt":{"defense":...
class Armor: armor = {'Festival T-Shirt': {'defense': 2, 'value': 6, 'itemClass': 'newb', 'desc': '+02 Defense'}, 'Offshore Overalls': {'defense': 5, 'value': 10, 'itemClass': 'hunter', 'desc': '+05 Defense - Hunter Classes Only'}, 'Cotton Affliction Shirt': {'defense': 3, 'value': 8, 'itemClass': 'voodoo', 'desc':...
class Get: def __init__(self,db): self.db = db def _get(self,key): try: return JsonObject(self.db, key, self.db[key]) except Exception as e: raise ValueError(f"No Key named {key} found.") def __call__(self,key): return self._get(key) class JsonObject(type({})): def __init__(self, db, key=N...
class Get: def __init__(self, db): self.db = db def _get(self, key): try: return json_object(self.db, key, self.db[key]) except Exception as e: raise value_error(f'No Key named {key} found.') def __call__(self, key): return self._get(key) class Jso...
#Ensure there is an exceptional edge from the following case def f2(): b, d = Base, Derived try: class MyNewClass(b, d): pass except: e2 def f3(): sequence_of_four = a_global try: a, b, c = sequence_of_four except: e3 #Always treat locals as no...
def f2(): (b, d) = (Base, Derived) try: class Mynewclass(b, d): pass except: e2 def f3(): sequence_of_four = a_global try: (a, b, c) = sequence_of_four except: e3 def f4(): if cond: local = 1 try: local except: e4...
for _ in range(int(input())): l,r,m=map(int,input().split()) ma=r-l for i in range(l,r+1): temp=m%i if temp<=ma and i<=m: print(i,l+temp,l) break elif i-temp<=ma: print(i,l,l+i-temp) break
for _ in range(int(input())): (l, r, m) = map(int, input().split()) ma = r - l for i in range(l, r + 1): temp = m % i if temp <= ma and i <= m: print(i, l + temp, l) break elif i - temp <= ma: print(i, l, l + i - temp) break
MOVING = "moving" SLEEPING = "sleeping" jobs: dict[str, str] = { "mine_foo": "Mining Foo", "mine_bar": "Mining Bar", "build_foobar": "Trying to build a Foobar", "sell_foobar": "Selling Foobar", "buy_robot": "Buying a robot", MOVING: "Moving", SLEEPING: "Sleeping", }
moving = 'moving' sleeping = 'sleeping' jobs: dict[str, str] = {'mine_foo': 'Mining Foo', 'mine_bar': 'Mining Bar', 'build_foobar': 'Trying to build a Foobar', 'sell_foobar': 'Selling Foobar', 'buy_robot': 'Buying a robot', MOVING: 'Moving', SLEEPING: 'Sleeping'}
class defaultdict(dict): """Poor man's implementation of defaultdict for Python 2.4 """ def __init__(self, default_factory=None, **kwargs): self.default_factory = default_factory super(defaultdict, self).__init__(**kwargs) def __getitem__(self, key): if self.default_factory is...
class Defaultdict(dict): """Poor man's implementation of defaultdict for Python 2.4 """ def __init__(self, default_factory=None, **kwargs): self.default_factory = default_factory super(defaultdict, self).__init__(**kwargs) def __getitem__(self, key): if self.default_factory is ...
#!/usr/bin/python3 hostname = input("What value should we set for hostname?") #hostname = "MTG" hostname = hostname.upper() if hostname == "MTG": print("The hostname was found to be mtg")
hostname = input('What value should we set for hostname?') hostname = hostname.upper() if hostname == 'MTG': print('The hostname was found to be mtg')
class EVBaseException(Exception): def __init__(self, msg): super(EVBaseException, self).__init__(msg) self._msg = msg # Exception.__init__(self, msg) def __str__(self): return self._msg class EVConnectionError(EVBaseException): def __init__(self, msg, exc_obj): supe...
class Evbaseexception(Exception): def __init__(self, msg): super(EVBaseException, self).__init__(msg) self._msg = msg def __str__(self): return self._msg class Evconnectionerror(EVBaseException): def __init__(self, msg, exc_obj): super(EVConnectionError, self).__init__(ms...
''' Author: Yurii Bielotsytsia Version: Easy-01 Name: Ideal BMI by Brok formula ''' sex = input('Enter you sex(m if you are a man, w if you are a woman): ') height = float(input('Enter you height in cm ')) if(sex == 'm'): result=(((height*4/2.54)-128)*0.453) print('You ideal BMI is {0:.2f}'.format(resu...
""" Author: Yurii Bielotsytsia Version: Easy-01 Name: Ideal BMI by Brok formula """ sex = input('Enter you sex(m if you are a man, w if you are a woman): ') height = float(input('Enter you height in cm ')) if sex == 'm': result = (height * 4 / 2.54 - 128) * 0.453 print('You ideal BMI is {0:.2f}'.format(result))...
# # PySNMP MIB module SW-PROJECTX-SRPRIMGMT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SW-PROJECTX-SRPRIMGMT-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:46:16 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3....
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, constraints_intersection, value_range_constraint, constraints_union) ...
material_iron = 'iron' material_titanium = 'titanium' material_naonite = 'naonite' material_trinium = 'trinium' material_xanion = 'xanion' material_ogonite = 'ogonite' material_avorion = 'avorion' block_armor = 'armor' block_engine = 'engine' block_cargo = 'cargo' block_quarters = 'quarters' block_thruster = 'thruster...
material_iron = 'iron' material_titanium = 'titanium' material_naonite = 'naonite' material_trinium = 'trinium' material_xanion = 'xanion' material_ogonite = 'ogonite' material_avorion = 'avorion' block_armor = 'armor' block_engine = 'engine' block_cargo = 'cargo' block_quarters = 'quarters' block_thruster = 'thruster'...
input = """ % run with option --depgraph % the component of a must be cyclic b(1). a(X, Y) :- a(X, X), b(Y). """ output = """ DEPGRAPH: (2 atoms, 2 components) cyclic hcf stratified not_tight 0 --> 1 1 --> 1 COMPONENT 0: cyclic hcf stratified { 1 } COMPONENT 1: acyclic hcf stratified { 0 } Predicate names ...
input = '\n% run with option --depgraph\n% the component of a must be cyclic\n\nb(1).\na(X, Y) :- a(X, X), b(Y).\n\n' output = '\nDEPGRAPH: (2 atoms, 2 components) cyclic hcf stratified not_tight\n\n0 --> 1\n1 --> 1\n\n\nCOMPONENT 0: cyclic hcf stratified\n{ 1 }\nCOMPONENT 1: acyclic hcf stratified\n{ 0 }\n\n\nPredicat...
def heapify(arr, n, i): largest = i l = 2*n +1 r = 2*n +2 if l<n and arr[largest] < arr[l]: largest = l if r<n and arr[largest] < arr[r]: largest = r if largest != i: arr[largest], arr[i] = arr[i], arr[largest] heapify(arr, n, largest) def hea...
def heapify(arr, n, i): largest = i l = 2 * n + 1 r = 2 * n + 2 if l < n and arr[largest] < arr[l]: largest = l if r < n and arr[largest] < arr[r]: largest = r if largest != i: (arr[largest], arr[i]) = (arr[i], arr[largest]) heapify(arr, n, largest) def heapsort(...
""" sorted Return a new sorted list from the items in iterable. """ nums = [6, 1, 8, 2] sorted(nums) # [1, 2, 6, 8] print(nums) # [6, 1, 8, 2] # for dictionaries, you have to pass in how they will be sorted. users = [ {"username": "samuel", "tweets": ["I love cake", "I love pie", "hello world!"]}, {"userna...
""" sorted Return a new sorted list from the items in iterable. """ nums = [6, 1, 8, 2] sorted(nums) print(nums) users = [{'username': 'samuel', 'tweets': ['I love cake', 'I love pie', 'hello world!']}, {'username': 'katie', 'tweets': ['I love my cat']}, {'username': 'jeff', 'tweets': []}, {'username': 'bob123', 'twee...
#!/usr/bin/env python """ MIT License Copyright (c) 2017 Raphael "rGunti" Guntersweiler Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the right...
""" MIT License Copyright (c) 2017 Raphael "rGunti" Guntersweiler Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify...
class Solution: def largestRectangleArea(self, heights: List[int]) -> int: n, heights, st, ans = len(heights), [0] + heights + [0], [], 0 for i in range(n + 2): while st and heights[st[-1]] > heights[i]: ans = max(ans, heights[st.pop(-1)] * (i - st[-1] - 1)) s...
class Solution: def largest_rectangle_area(self, heights: List[int]) -> int: (n, heights, st, ans) = (len(heights), [0] + heights + [0], [], 0) for i in range(n + 2): while st and heights[st[-1]] > heights[i]: ans = max(ans, heights[st.pop(-1)] * (i - st[-1] - 1)) ...
f = open("unicode/data/utf-8_1.txt") l = f.readline() print(l) print(len(l))
f = open('unicode/data/utf-8_1.txt') l = f.readline() print(l) print(len(l))
class TopoHelper: def get_neighbor(self, rank, nworker): rank = rank + 1 ret = [] if rank > 1: ret.append(rank // 2 - 1) if rank * 2 - 1 < nworker: ret.append(rank * 2 - 1) if rank * 2 < nworker: ret.append(rank * 2) return ret ...
class Topohelper: def get_neighbor(self, rank, nworker): rank = rank + 1 ret = [] if rank > 1: ret.append(rank // 2 - 1) if rank * 2 - 1 < nworker: ret.append(rank * 2 - 1) if rank * 2 < nworker: ret.append(rank * 2) return ret ...
''' *********************************************************************************************************************** * Configuration file for Solar estimation tool * * Created by P.Nezval ...
""" *********************************************************************************************************************** * Configuration file for Solar estimation tool * * Created by P.Nezval ...
kartyak = ['2383 8823 9423 1164'] for kartya in kartyak: kartyaCheck = [] for karakter in kartya: if karakter != ' ': kartyaCheck.append(karakter) print(kartyaCheck) for index, karakter in enumerate(kartyaCheck): if index%2 == 0: double = 2*int(karakter) if double >= 10: ...
kartyak = ['2383 8823 9423 1164'] for kartya in kartyak: kartya_check = [] for karakter in kartya: if karakter != ' ': kartyaCheck.append(karakter) print(kartyaCheck) for (index, karakter) in enumerate(kartyaCheck): if index % 2 == 0: double = 2 * int(karakter) ...
{ 'Datadog': [ 'host:dev-test', 'environment:test' ], 'Users': [ 'role:database' ] }
{'Datadog': ['host:dev-test', 'environment:test'], 'Users': ['role:database']}
# random.seed(1234) # np.random.seed(1234) # torch.manual_seed(1234) # torch.cuda.manual_seed_all(1234) # torch.backends.cudnn.deterministic = True class Transition(object): def __init__( self, FromCluster, ArriveCluster, Vehicle, State, StateQTable, Action, ...
class Transition(object): def __init__(self, FromCluster, ArriveCluster, Vehicle, State, StateQTable, Action, TotallyReward, PositiveReward, NegativeReward, NeighborNegativeReward, State_, State_QTable): self.FromCluster = FromCluster self.ArriveCluster = ArriveCluster self.Vehicle = Vehicl...
''' Part 1: Define a class named Circle which can be constructed by a radius. Compare two circles objects and return True if circles are equal. Return False if circles are not equal Take radius of these circles through Input Expected Input/Output 1: Enter Radius of Circle 1: 2 Enter Radius of circle 2: 4 Output: Fal...
""" Part 1: Define a class named Circle which can be constructed by a radius. Compare two circles objects and return True if circles are equal. Return False if circles are not equal Take radius of these circles through Input Expected Input/Output 1: Enter Radius of Circle 1: 2 Enter Radius of circle 2: 4 Output: Fal...
while True: text = input(">>>") if (text == "python"): break print(text) print("Python is Addictive")
while True: text = input('>>>') if text == 'python': break print(text) print('Python is Addictive')
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"binarize_mask": "00_mask_transform.ipynb", "data_loader": "00_mask_transform.ipynb", "data_saver": "00_mask_transform.ipynb", "outpath_from_inpath": "00_mask_transform.ipynb", ...
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'binarize_mask': '00_mask_transform.ipynb', 'data_loader': '00_mask_transform.ipynb', 'data_saver': '00_mask_transform.ipynb', 'outpath_from_inpath': '00_mask_transform.ipynb', 'check_outpath': '00_mask_transform.ipynb', 'create_outpath': '00_mask_t...
#!/usr/bin/env python3 cfg_overridden_precisions = { # Convolution: output value inaccuracy exceeds threshold for FP16 'vgg16-IR:opid42': ['FP32'], 'vgg16-IR:opid31': ['FP32'], 'yolo-v4-tf:opid227': ['FP32'], # FusedConvolution: output value inaccuracy exceeds threshold for FP16 '3d_unet-grap...
cfg_overridden_precisions = {'vgg16-IR:opid42': ['FP32'], 'vgg16-IR:opid31': ['FP32'], 'yolo-v4-tf:opid227': ['FP32'], '3d_unet-graph-transform-cuda:opid31': ['FP32']}
"""4.10 Check Subtree: Tl and T2 are two very large binary trees, with Tl much bigger than T2. Create an algorith m to determine if T2 is a subtree of Tl . A tree T2 is a subtree ofTi if there exists a node n in Ti such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees ...
"""4.10 Check Subtree: Tl and T2 are two very large binary trees, with Tl much bigger than T2. Create an algorith m to determine if T2 is a subtree of Tl . A tree T2 is a subtree ofTi if there exists a node n in Ti such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees ...
class Solution(object): def canPartition(self, nums): """ :type nums: List[int] :rtype: bool """ if sum(nums) % 2: return False dp = set() dp.add(0) target = sum(nums) // 2 for i in range(len(nums)-1, -1, -1): nextDP =...
class Solution(object): def can_partition(self, nums): """ :type nums: List[int] :rtype: bool """ if sum(nums) % 2: return False dp = set() dp.add(0) target = sum(nums) // 2 for i in range(len(nums) - 1, -1, -1): next_d...
def count_char(text, char): count = 0 for c in text: if c == char: count += 1 return count filename = input("Enter a filename: ") with open(filename) as f: text = f.read() for char in "abcdefghijklmnopqrstuvwxyz": perc = 100 * count_char(text, char) / len(text) print("{0} - {1}%".format(char, round(perc, 2...
def count_char(text, char): count = 0 for c in text: if c == char: count += 1 return count filename = input('Enter a filename: ') with open(filename) as f: text = f.read() for char in 'abcdefghijklmnopqrstuvwxyz': perc = 100 * count_char(text, char) / len(text) print('{0} - {...
def pytest_addoption(parser): parser.addoption("--runexamples", action="store_true", help="run examples") parser.addoption("--runbenchmarks", action="store_true", help="run benchmarks") parser.addoption("--all", action="store_true", help="run be...
def pytest_addoption(parser): parser.addoption('--runexamples', action='store_true', help='run examples') parser.addoption('--runbenchmarks', action='store_true', help='run benchmarks') parser.addoption('--all', action='store_true', help='run benchmarks')
""" [2016-03-23] Challenge #259 [Intermediate] Mahjong Hands https://www.reddit.com/r/dailyprogrammer/comments/4bmdwz/20160323_challenge_259_intermediate_mahjong_hands/ # Description You are the biggest, baddest mahjong player around. Your enemies tremble at your presence on the battlefield, and you can barely walk t...
""" [2016-03-23] Challenge #259 [Intermediate] Mahjong Hands https://www.reddit.com/r/dailyprogrammer/comments/4bmdwz/20160323_challenge_259_intermediate_mahjong_hands/ # Description You are the biggest, baddest mahjong player around. Your enemies tremble at your presence on the battlefield, and you can barely walk t...
input = """ % This is also interesting for the model generator, due to the strange contraint. b :- not c. c :- not b. a :- b. :- a, not a. """ output = """ {a, b} {c} """
input = '\n% This is also interesting for the model generator, due to the strange contraint.\n\nb :- not c.\nc :- not b.\n\na :- b.\n\n:- a, not a.\n' output = '\n{a, b}\n{c}\n'
list1 = [6, 8, 19, 20, 23, 41, 49, 53, 56, 87] def find_max(items): if (len(items) == 1): return items[0] item1 = items[0] print(f"Item1 = {item1}") item2 = find_max(items[1:]) print(f"Item2 = {item2}") if item1 > item2: return item1 else: return item2 print(fin...
list1 = [6, 8, 19, 20, 23, 41, 49, 53, 56, 87] def find_max(items): if len(items) == 1: return items[0] item1 = items[0] print(f'Item1 = {item1}') item2 = find_max(items[1:]) print(f'Item2 = {item2}') if item1 > item2: return item1 else: return item2 print(find_max(l...
def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ # Create a hash table (Python dictionary) htbl = {} for i, num in enumerate(nums): t = target - num if t in htbl.keys(): return [htbl[t], i] else: ...
def two_sum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ htbl = {} for (i, num) in enumerate(nums): t = target - num if t in htbl.keys(): return [htbl[t], i] else: htbl[num] = i return None if __name__ ==...
class InlineIfThen (Exception): pass
class Inlineifthen(Exception): pass
lines = [] file = "output.txt" with open(file, "r") as default_branch: lines = default_branch.readlines() repos = set(lines) sort_file = file[:-4] + "_sorted" + file[-4:] with open(sort_file, "w") as default_branch: default_branch.writelines(sorted(repos))
lines = [] file = 'output.txt' with open(file, 'r') as default_branch: lines = default_branch.readlines() repos = set(lines) sort_file = file[:-4] + '_sorted' + file[-4:] with open(sort_file, 'w') as default_branch: default_branch.writelines(sorted(repos))
#!/usr/bin/env python3 class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ d = {} for w in sorted(strs): k = tuple(sorted(w)) d[k] = d.get(k, []) + [w] return list(d.values()) if __name_...
class Solution: def group_anagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ d = {} for w in sorted(strs): k = tuple(sorted(w)) d[k] = d.get(k, []) + [w] return list(d.values()) if __name__ == '__main__': p...
#!/usr/bin/env python3 # Dictionaries are data structures(blueprint for big data, definition template) # used to map key:value pairs. # As if lists were dictionaries with integer keys at range. # Dictionaries can be indexed in the same way as lists, using [] containing keys. # {key:value} can be: {"String":int} {"Stri...
data = {'age': 25, 'car': 'red', 'char1': 'c'} print(data['age']) print(data['car']) print(data['char1']) data['new'] = 'value' print(data) print('new' in data) print(data.get('age')) print(data.get('char2', "Key 'char2' is not in list, que this message")) print(data.get('age') + data.get('age'))
class ConfusionMatrix(object): TP = TN = FP = FN = 0 def __str__(self): return "p\\t\tP\tN\nP\t{}\t{}\nN\t{}\t{}".format(self.TP, self.FP, self.FN, self.TN) def recall(self): return self.TP / float(self.TP + self.FN) def precision(self): return self.TP / floa...
class Confusionmatrix(object): tp = tn = fp = fn = 0 def __str__(self): return 'p\\t\tP\tN\nP\t{}\t{}\nN\t{}\t{}'.format(self.TP, self.FP, self.FN, self.TN) def recall(self): return self.TP / float(self.TP + self.FN) def precision(self): return self.TP / float(self.TP + self.F...
# Example of what a for loop does: nums = [1, 2, 3] i_nums = iter(nums) while True: try: item = next(i_nums) print(item) except StopIteration: break
nums = [1, 2, 3] i_nums = iter(nums) while True: try: item = next(i_nums) print(item) except StopIteration: break
# # PySNMP MIB module CXFrameRelayInterfaceModule-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXFrameRelayInterfaceModule-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:17:14 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Pytho...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_intersection, value_range_constraint, single_value_constraint, constraints_union) ...