content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Solution(object): def countSubstrings(self, s): def manacher(s): s = '^#' + '#'.join(s) + '#$' P = [0] * len(s) C, R = 0, 0 for i in xrange(1, len(s) - 1): i_mirror = 2 * C - i if R > i: P[i] = min(R-i,...
class Solution(object): def count_substrings(self, s): def manacher(s): s = '^#' + '#'.join(s) + '#$' p = [0] * len(s) (c, r) = (0, 0) for i in xrange(1, len(s) - 1): i_mirror = 2 * C - i if R > i: P[i] = m...
""" Given an array, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i. More formally, G[i] for an element A[i] = an element A[j] such that j is maximum possible AND j < i AND A[j] < A[i] Elements for which no smaller element exist, ...
""" Given an array, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i. More formally, G[i] for an element A[i] = an element A[j] such that j is maximum possible AND j < i AND A[j] < A[i] Elements for which no smaller element exist, ...
FG = "\033[38;5;{}m" BG = "\033[48;5;{}m" RST = "\033[0m" def print_256_color_lookup_table_for(x): if x == "foreground" or x == "fg": x = FG elif x == "background" or x == "bg": x = BG else: raise ValueError("Unrecognized value for argument.") for n in range(16): # Sta...
fg = '\x1b[38;5;{}m' bg = '\x1b[48;5;{}m' rst = '\x1b[0m' def print_256_color_lookup_table_for(x): if x == 'foreground' or x == 'fg': x = FG elif x == 'background' or x == 'bg': x = BG else: raise value_error('Unrecognized value for argument.') for n in range(16): print(...
demo_list = [1, 'hello', 1.34, True, [1, 2, 3]] colors = ['red', 'green', 'blue'] numbers_list = list((1, 2, 3, 4)) print(numbers_list) r = list(range(1, 100)) print(r) print(len(colors)) print(colors[1]) print('green' in colors) print(colors) colors[1] = 'yellow' print(colors) colors.append('violet')...
demo_list = [1, 'hello', 1.34, True, [1, 2, 3]] colors = ['red', 'green', 'blue'] numbers_list = list((1, 2, 3, 4)) print(numbers_list) r = list(range(1, 100)) print(r) print(len(colors)) print(colors[1]) print('green' in colors) print(colors) colors[1] = 'yellow' print(colors) colors.append('violet') colors.extend(['v...
# Leetcode Problem Link: # https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: '...
class Solution: def lowest_common_ancestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if root == None or root == p or root == q: return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) if...
''' I=1 J=7 I=1 J=6 I=1 J=5 ''' i = 1 j = 7 while i < 10: print("I={} J={}".format(i, j)) if j == 5: i = i + 2 j = 7 else: j = j - 1
""" I=1 J=7 I=1 J=6 I=1 J=5 """ i = 1 j = 7 while i < 10: print('I={} J={}'.format(i, j)) if j == 5: i = i + 2 j = 7 else: j = j - 1
# MIT License # # Copyright (c) 2020-2021 Markus Prasser # # 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 Biblebookstable: bible_books = ('Genesis', 'Exodus', 'Leviticus', 'Numbers', 'Deuteronomy', 'Joshua', 'Judges', 'Ruth', '1 Samuel', '2 Samuel', '1 Kings', '2 Kings', '1 Chronicles', '2 Chronicles', 'Ezra', 'Nehemiah', 'Esther', 'Job', 'Psalms', 'Proverbs', 'Ecclesiastes', 'Song of Solomon', 'Isaiah', 'Jeremia...
# Time: O(n * l^2), n is length of string s, l is maxLen of words in dict; # slice to get substring s[i-l:i] takes l time # Space: O(n) # 139 # Given a string s and a dictionary of words dict, # determine if s can be segmented into a space-separated sequence of one or more dictionary words. # # Fo...
class Solution(object): def word_break(self, s, wordDict): """ :type s: str :type wordDict: Set[str] :rtype: bool """ if not wordDict: return False (n, dset) = (len(s), set(wordDict)) max_len = max((len(w) for w in dset)) dp = [Fal...
def max_heapify(A,k): l = left(k) m = middle(k) r = right(k) largest = k if l < len(A) and A[l] > A[k]: largest = l else: largest = k if r < len(A) and A[r] > A[largest]: largest = r if m < len(A) and A[m] > A[largest]: largest = m if largest != k: ...
def max_heapify(A, k): l = left(k) m = middle(k) r = right(k) largest = k if l < len(A) and A[l] > A[k]: largest = l else: largest = k if r < len(A) and A[r] > A[largest]: largest = r if m < len(A) and A[m] > A[largest]: largest = m if largest != k: ...
""" CCC '20 J3 - Art Find this problem at: https://dmoj.ca/problem/ccc20j3 """ # Unzip the input into separate lists of x & y coordinates xs, ys = [], [] for i in range(int(input())): x, y = map(int, input().split(',')) xs.append(x) ys.append(y) # The smallest x & y coordinates and minus one (because of f...
""" CCC '20 J3 - Art Find this problem at: https://dmoj.ca/problem/ccc20j3 """ (xs, ys) = ([], []) for i in range(int(input())): (x, y) = map(int, input().split(',')) xs.append(x) ys.append(y) print(f'{min(xs) - 1},{min(ys) - 1}') print(f'{max(xs) + 1},{max(ys) + 1}')
class Node: def __init__(self, value=None, next=None): self.value = value self.next = next def remove_from_list(value, listHead): curr = listHead prev = None while curr: if curr.value > value: if prev: prev.next = curr.next else: ...
class Node: def __init__(self, value=None, next=None): self.value = value self.next = next def remove_from_list(value, listHead): curr = listHead prev = None while curr: if curr.value > value: if prev: prev.next = curr.next else: ...
# recursive approach to find the number of set # bits in binary representation of positive integer n def count_set_bits(n): if (n == 0): return 0 else: return (n & 1) + count_set_bits(n >> 1) # Get value from user n = 41 # Function calling print(count_set_bits(n...
def count_set_bits(n): if n == 0: return 0 else: return (n & 1) + count_set_bits(n >> 1) n = 41 print(count_set_bits(n))
APPLICATION_GOOD_BODY = { 'information': { 'first_name': 'Andrew James', 'last_name': 'McLeod', 'date_of_birth': '1987-03-04', 'addresses': [ { 'address': '3023 BODEGA ROAD', 'city': 'VICTORIA', 'province_state': 'BC', ...
application_good_body = {'information': {'first_name': 'Andrew James', 'last_name': 'McLeod', 'date_of_birth': '1987-03-04', 'addresses': [{'address': '3023 BODEGA ROAD', 'city': 'VICTORIA', 'province_state': 'BC', 'country': 'CA'}]}} auth_response = {'token': 'e5e4c777acb3c2a4e4234a282a8ac507c0be24708e6dfe121de563dda3...
ENCRYPTION_FILE_CHUNK_SIZE = 64 * 1024 # 64K ENCRYPTION_KEY_DERIVATION_ITERATIONS = 100000 ENCRYPTION_KEY_SIZE = 32 ZIP_CHUNK_SIZE = 64 * 1024 # 64K ZIP_MEMBER_FILENAME = 'mayan_file'
encryption_file_chunk_size = 64 * 1024 encryption_key_derivation_iterations = 100000 encryption_key_size = 32 zip_chunk_size = 64 * 1024 zip_member_filename = 'mayan_file'
'''lst=[x for x in range(2,21,2)] print(lst)''' lst=[x for x in range(1,21) if x%2==0] print(lst)
"""lst=[x for x in range(2,21,2)] print(lst)""" lst = [x for x in range(1, 21) if x % 2 == 0] print(lst)
#multiple if statements (IBM Digital Nation Africa) num = 72.5 if num > 0 : print ("The Number is positive") if num > 20 : print("The Number is greater than 20")
num = 72.5 if num > 0: print('The Number is positive') if num > 20: print('The Number is greater than 20')
# The Project # Master Ticket TICKET_PRICE = 10 tickets_remaining = 100 # Notify the user that the tickets are sold out if the tickets remaining is 0 if tickets_remaining == 0: print("I'm sorry we are sold out!") # Run this code continuously until we run out of tickets while tickets_remaining >= 1: # Output how...
ticket_price = 10 tickets_remaining = 100 if tickets_remaining == 0: print("I'm sorry we are sold out!") while tickets_remaining >= 1: print('There are {} tickets remaining.'.format(tickets_remaining)) user_name = input('What is your name? ') tickets_requested = input('How many tickets would you like...
del_items(0x80116458) SetType(0x80116458, "int NumOfMonsterListLevels") del_items(0x800A375C) SetType(0x800A375C, "struct MonstLevel AllLevels[16]") del_items(0x80116174) SetType(0x80116174, "unsigned char NumsLEV1M1A[4]") del_items(0x80116178) SetType(0x80116178, "unsigned char NumsLEV1M1B[4]") del_items(0x8011617C) S...
del_items(2148623448) set_type(2148623448, 'int NumOfMonsterListLevels') del_items(2148153180) set_type(2148153180, 'struct MonstLevel AllLevels[16]') del_items(2148622708) set_type(2148622708, 'unsigned char NumsLEV1M1A[4]') del_items(2148622712) set_type(2148622712, 'unsigned char NumsLEV1M1B[4]') del_items(214862271...
# ------------------------------------ # CODE BOOLA 2015 PYTHON WORKSHOP # Mike Wu, Jonathan Chang, Kevin Tan # Puzzle Challenges Number 4 # ------------------------------------ # Wow! You are doing this way faster # than I thought you would. Slooooow # doooowwwwwnnn... # ------------------------------------ # IN...
def reverse(s): pass
# import pytest class TestTranslator: def test___call__(self): # synced assert True def test_translate(self): # synced assert True def test_translate_recursively(self): # synced assert True def test_translate_json(self): # synced assert True class TestTranslata...
class Testtranslator: def test___call__(self): assert True def test_translate(self): assert True def test_translate_recursively(self): assert True def test_translate_json(self): assert True class Testtranslatablemeta: pass class Testdonottranslatemeta: pass
class RBTreeNode: def __init__(self, val, parent=None): self.val = val self.black = True self.left = None self.right = None self.parent = parent class RBTree: def __init__(self): self.root = None def get_root(self): return self.root def insert(...
class Rbtreenode: def __init__(self, val, parent=None): self.val = val self.black = True self.left = None self.right = None self.parent = parent class Rbtree: def __init__(self): self.root = None def get_root(self): return self.root def insert...
__all__ = ['gmrt_raw_toguppi'] class GUPPIINJ: def __init__(self, guppifile) -> None: self.header = self.header_dict() self.guppifile = guppifile # def bbinj(self,d):# samples_per_frame=960, pktsize=1024,npol=2, nchan=4): # hdr = {k: self.header[k] for k in self.header if self.h...
__all__ = ['gmrt_raw_toguppi'] class Guppiinj: def __init__(self, guppifile) -> None: self.header = self.header_dict() self.guppifile = guppifile @classmethod def header_dict(cls, par=None): cls._header = header() _dict = cls._header.__dict__ att = attr_dict() ...
#ticTacToe.py #Written by Jesse Gallarzo gameGrid = [[' ' for i in range(3)] for j in range(3)] gameOver = False answer = str() def gameRules(): print('Whoever matches three of a kind in a row or column wins! Place either an X or an O within the grid') def printGrid(): print('|'+gameGrid[0][0]+'|'+gameGrid[0...
game_grid = [[' ' for i in range(3)] for j in range(3)] game_over = False answer = str() def game_rules(): print('Whoever matches three of a kind in a row or column wins! Place either an X or an O within the grid') def print_grid(): print('|' + gameGrid[0][0] + '|' + gameGrid[0][1] + '|' + gameGrid[0][2] + '|...
# terrascript/data/bgpat/dnsimple.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:15:28 UTC) __all__ = []
__all__ = []
INFO = { "name": "hi", "description": "Membalas dengan hello", "visibility": "public", "authority": "all" } async def execute(client, message): message_chat = message.chat await client.send_message( message_chat.id, "Hello" )
info = {'name': 'hi', 'description': 'Membalas dengan hello', 'visibility': 'public', 'authority': 'all'} async def execute(client, message): message_chat = message.chat await client.send_message(message_chat.id, 'Hello')
class Connection(object): def open(self): pass def close(self): pass
class Connection(object): def open(self): pass def close(self): pass
# # PySNMP MIB module XEDIA-DVMRP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XEDIA-DVMRP-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:42: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, constraints_union, value_size_constraint, constraints_intersection, value_range_constraint) ...
class Error(Exception): """Base class for exceptions in this module.""" pass class SnipeITErrorHandler(object): """Handles SnipeIT Exceptions""" def __init__(self,request): self.fault=request.json() if self.fault.get('status')=='error': if self.fault.get('messages') == 'Unau...
class Error(Exception): """Base class for exceptions in this module.""" pass class Snipeiterrorhandler(object): """Handles SnipeIT Exceptions""" def __init__(self, request): self.fault = request.json() if self.fault.get('status') == 'error': if self.fault.get('messages') ==...
# https://www.codewars.com/kata/52597aa56021e91c93000cb0/train/python def move_zeros(array: list) -> list: return [x for x in array if x != 0] + [0] * array.count(0) # ----------------------------------------------------------------------------- tests = [ { 'assertion': move_zeros([1, 2, 0, 1, 0, 1, ...
def move_zeros(array: list) -> list: return [x for x in array if x != 0] + [0] * array.count(0) tests = [{'assertion': move_zeros([1, 2, 0, 1, 0, 1, 0, 3, 0, 1]), 'expected': [1, 2, 1, 1, 3, 1, 0, 0, 0, 0]}, {'assertion': move_zeros([9, 0, 0, 9, 1, 2, 0, 1, 0, 1, 0, 3, 0, 1, 9, 0, 0, 0, 0, 9]), 'expected': [9, 9, 1...
__author__ = 'slaviann' TEMPLATES = ( "ddos.list", "domains.list", "domains_ssl.list", "suspend.list" )
__author__ = 'slaviann' templates = ('ddos.list', 'domains.list', 'domains_ssl.list', 'suspend.list')
NEEDLESS_ATTRS = ['op', 'desc', 'id', 'swap', 'trainable', 'ctx', 'event', 'inplace', 'lazy_execution', 'on_cpu', 'on_gpu', 'compute', 'middle_result', 'gpu_buffer', ] ONNX_DOMAIN = "" AI_ONNX_ML_DOMAIN = "ai.onnx.ml"
needless_attrs = ['op', 'desc', 'id', 'swap', 'trainable', 'ctx', 'event', 'inplace', 'lazy_execution', 'on_cpu', 'on_gpu', 'compute', 'middle_result', 'gpu_buffer'] onnx_domain = '' ai_onnx_ml_domain = 'ai.onnx.ml'
class InvalidAPIKey(Exception): pass class GatewayError(Exception): pass class TooManyRequests(Exception): pass
class Invalidapikey(Exception): pass class Gatewayerror(Exception): pass class Toomanyrequests(Exception): pass
def db_field(**options): def _exec(client, *args, **kwargs): pass return _exec
def db_field(**options): def _exec(client, *args, **kwargs): pass return _exec
# -*- coding: utf-8 -*- # mathtoolspy # ----------- # A fast, efficient Python library for mathematically operations, like # integration, solver, distributions and other useful functions. # # Author: sonntagsgesicht, based on a fork of Deutsche Postbank [pbrisk] # Version: 0.3, copyright Wednesday, 18 September 20...
class Simplexintegrator: def log_none(self, x): pass def __init__(self, steps=100, log_info=None): self.nsteps = steps if log_info == None: self.log_info = self.logNone else: self.log_info = log_info def integrate(self, function, lower_bound, upper_...
''' Given n friends, each one can remain single or can be paired up with some other friend. Each friend can be paired only once. Find out the total number of ways in which friends can remain single or can be paired up. Input : n = 3 Output : 4 Explanation {1}, {2}, {3} : all single {1}, {2, 3} : 2 and 3 paired but 1 ...
""" Given n friends, each one can remain single or can be paired up with some other friend. Each friend can be paired only once. Find out the total number of ways in which friends can remain single or can be paired up. Input : n = 3 Output : 4 Explanation {1}, {2}, {3} : all single {1}, {2, 3} : 2 and 3 paired but 1 ...
""" Definition of ListNode """ class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next class Solution: """ @param head: the head @param G: an array @return: the number of connected components in G """ def numComponents(self, head, G): ...
""" Definition of ListNode """ class Listnode(object): def __init__(self, val, next=None): self.val = val self.next = next class Solution: """ @param head: the head @param G: an array @return: the number of connected components in G """ def num_components(self, head, G): ...
def insert_shift_array(l,b): middle = len(l) // 2 if len(l) % 2 == 0: return l[:middle] + [b] + l[middle:] else: return l[:middle + 1] + [b] + l[middle +1:]
def insert_shift_array(l, b): middle = len(l) // 2 if len(l) % 2 == 0: return l[:middle] + [b] + l[middle:] else: return l[:middle + 1] + [b] + l[middle + 1:]
def problem059(): """ Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107. A modern encryption method is to take a text fil...
def problem059(): """ Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107. A modern encryption method is to take a text fil...
boxes = [ ] c = 0 for line in open( 'input.txt', 'r' ): line = line.strip( ) if c == 0: boxes.append( line ) c += 1 continue for old_line in boxes: diffs = 0 for i in range( len( old_line ) ): if old_line[ i ] != line[ i ]: diffs += 1 same_char = old_line[ i ] #print( ---\n{0}\n{1}\n{2...
boxes = [] c = 0 for line in open('input.txt', 'r'): line = line.strip() if c == 0: boxes.append(line) c += 1 continue for old_line in boxes: diffs = 0 for i in range(len(old_line)): if old_line[i] != line[i]: diffs += 1 sam...
# https://www.youtube.com/watch?v=-VpH54mhSu4&list=PL5TJqBvpXQv6TtedyS_a_pJK2uVrksh7D&index=3 def solve(A): # [-2, 1, 2, 3, 5, -4] min, max = 0, 0 # min, max = A[0], A[0] Other way to start beginning from the first position for value in A: if value <= min: min = value if v...
def solve(A): (min, max) = (0, 0) for value in A: if value <= min: min = value if value >= max: max = value return min + max a = [-2, 1, 2, 3, 5, -4] b = [-4, -2, 1, 5, 10, 20, -15] print(solve(A)) print(solve(B))
__version__ = "0.2.0" __description__ = "Download data from Refinitiv Tick History and compute some market microstructure measures." __author__ = "Mingze Gao" __author_email__ = "mingze.gao@sydney.edu.au" # __github_url__ = "https://github.com/mgao6767/mktstructure"
__version__ = '0.2.0' __description__ = 'Download data from Refinitiv Tick History and compute some market microstructure measures.' __author__ = 'Mingze Gao' __author_email__ = 'mingze.gao@sydney.edu.au'
class Graph: def __init__(self, v): self.v = v self.e = 0 self.adj = [[] for _ in range(v)] def add_edge(self, v, w): self.adj[v].append(w) self.adj[w].append(v) self.e += 1 def get_v(self): return self.v def det_e(self): return self.e ...
class Graph: def __init__(self, v): self.v = v self.e = 0 self.adj = [[] for _ in range(v)] def add_edge(self, v, w): self.adj[v].append(w) self.adj[w].append(v) self.e += 1 def get_v(self): return self.v def det_e(self): return self.e ...
def detect_os(rctx): """ Detects the host operating system. Args: rctx: repository_ctx Returns: One of the targets in @platforms//os:*. """ os_name = rctx.os.name.lower() if os_name.startswith("mac os"): return "darwin" elif os_name == "linux": return "l...
def detect_os(rctx): """ Detects the host operating system. Args: rctx: repository_ctx Returns: One of the targets in @platforms//os:*. """ os_name = rctx.os.name.lower() if os_name.startswith('mac os'): return 'darwin' elif os_name == 'linux': return 'l...
# ------------------------------------------------------------ # MC911 - Compiler construction laboratory. # IC - UNICAMP # # RA094139 - Marcelo Mingatos de Toledo # RA093175 - Victor Fernando Pompeo Barbosa # # ------------------------------------------------------------ class LyaColor: HEADER = '\033[95m' O...
class Lyacolor: header = '\x1b[95m' okblue = '\x1b[94m' okgreen = '\x1b[92m' warning = '\x1b[93m' fail = '\x1b[91m' endc = '\x1b[0m' bold = '\x1b[1m' underline = '\x1b[4m'
def print_tasks(): print("The available tasks are:") for t in list_of_tasks: print(display_full_task(t)) ''' for x in range(0, num_tasks): n = input("\ninput name: \n") #Customize Questions t = input("input time: \n") c = input("input category: \n") task=task_list(n,t,c) ...
def print_tasks(): print('The available tasks are:') for t in list_of_tasks: print(display_full_task(t)) '\nfor x in range(0, num_tasks):\n n = input("\ninput name: \n") #Customize Questions\n t = input("input time: \n")\n c = input("input category: \n")\n\n task=task_list(n,t,c)\n\n list...
# Given a singly linked list and an integer k, remove the kth last element from # the list. k is guaranteed to be smaller than the length of the list. # The list is very long, so making more than one pass is prohibitively expensive. class Node: def __init__(self, value): self.value = value ...
class Node: def __init__(self, value): self.value = value self.next = None class Linklist: def __init__(self, values): self.length = 0 self.head = None if values: current = self.head = node(values[0]) self.length += 1 for v in values...
def test_Dataset(mocker): pass
def test__dataset(mocker): pass
# Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. # Example 1: # Input: [2,3,-2,4] # Output: 6 # Explanation: [2,3] has the largest product 6. # Example 2: # Input: [-2,0,-1] # Output: 0 # Explanation: The result cannot be 2, ...
class Solution(object): def max_product(self, nums): """ :type nums: List[int] :rtype: int """ if not nums or len(nums) == 0: return 0 else: (res1, res2) = ([0 for i in range(len(nums))], [0 for i in range(len(nums))]) (res1[0], re...
# Fibonacci series # 0,1,1,2,3,5,8,13,21... try: term_number = int(input('Enter Term Number : ')) except: print('Please Enter A Valid Integer') quit() n1, n2 = 0, 1 count = 0 if term_number <= 0: print('Please enter a positive integer') elif term_number == 1: print('Fibonacci Series') print(n1...
try: term_number = int(input('Enter Term Number : ')) except: print('Please Enter A Valid Integer') quit() (n1, n2) = (0, 1) count = 0 if term_number <= 0: print('Please enter a positive integer') elif term_number == 1: print('Fibonacci Series') print(n1) else: print('Fibonacci Series') ...
""" Created on 04/06/2012 @author: victor """ class Analysis(object): def __init__(self, name, analysis_function, other_params = None): """ Creates one analysis object. It uses an 'analysis_function' which has at least a clustering as parameter and returns a string without any tab c...
""" Created on 04/06/2012 @author: victor """ class Analysis(object): def __init__(self, name, analysis_function, other_params=None): """ Creates one analysis object. It uses an 'analysis_function' which has at least a clustering as parameter and returns a string without any tab c...
def floyd(num_vertice, graph): distance = graph #to keep the distances of the graph for target in range(num_vertice): #going thro all vertices for i in range(num_vertice): #go thro row for j in range(num_vertice):#go thro column distance[i][j] = min(distance[i][j], distance[i...
def floyd(num_vertice, graph): distance = graph for target in range(num_vertice): for i in range(num_vertice): for j in range(num_vertice): distance[i][j] = min(distance[i][j], distance[i][target] + distance[target][i])
class NoSuchListenerError(Exception): pass class NoSuchEventError(Exception): pass class InvalidHandlerError(Exception): pass
class Nosuchlistenererror(Exception): pass class Nosucheventerror(Exception): pass class Invalidhandlererror(Exception): pass
def packbits(myarray, axis=None): # TODO(beam2d): Implement it raise NotImplementedError def unpackbits(myarray, axis=None): # TODO(beam2d): Implement it raise NotImplementedError
def packbits(myarray, axis=None): raise NotImplementedError def unpackbits(myarray, axis=None): raise NotImplementedError
""" by Denexapp """ sound_files = { 1: "legacy/1_allakh_akbar.mp3", 2: "legacy/2_assalam_alleykum.mp3", 3: "legacy/3_ver_i_vse_poluchitsya.mp3", 4: "legacy/4_vnesi_dengi_i_zagadai_zhelanie.mp3", 5: "legacy/5_vnesi_platu_i_zagadai_svoye_zhelanie.mp3", 6: "legacy/6_vnesi_platu_i_sosredotochsya.m...
""" by Denexapp """ sound_files = {1: 'legacy/1_allakh_akbar.mp3', 2: 'legacy/2_assalam_alleykum.mp3', 3: 'legacy/3_ver_i_vse_poluchitsya.mp3', 4: 'legacy/4_vnesi_dengi_i_zagadai_zhelanie.mp3', 5: 'legacy/5_vnesi_platu_i_zagadai_svoye_zhelanie.mp3', 6: 'legacy/6_vnesi_platu_i_sosredotochsya.mp3', 7: 'legacy/7_vremya_o...
upper_code = '' lower_code = '' currentBlock = True f = open('code.slice','r') p = f.read().splitlines() for i in p: if i == '[upper]': currentBlock = True continue if i == '[end]': continue if i == '[lower]': currentBlock = False continue if i == '[endFile]':...
upper_code = '' lower_code = '' current_block = True f = open('code.slice', 'r') p = f.read().splitlines() for i in p: if i == '[upper]': current_block = True continue if i == '[end]': continue if i == '[lower]': current_block = False continue if i == '[endFile]':...
def listify(obj): if obj is None: return [] if isinstance(obj, (list, tuple)): return obj return [obj]
def listify(obj): if obj is None: return [] if isinstance(obj, (list, tuple)): return obj return [obj]
renterData = { 'Topshop': { 'totalSqm': 2400, 'term': 120, # month 'isGuaranteed': False, 'initialRent': 2000000, # in euro 'initialRentPerSqm': 833, 'annualIncrease': 0.025, 'abatement': 0, # in month 'TI': 200, # TI per sqm 'equityMultiple': ...
renter_data = {'Topshop': {'totalSqm': 2400, 'term': 120, 'isGuaranteed': False, 'initialRent': 2000000, 'initialRentPerSqm': 833, 'annualIncrease': 0.025, 'abatement': 0, 'TI': 200, 'equityMultiple': {'unleveraged': 2.92, 'lenderA': 2.11, 'lenderB': 2.52}, 'IRR': {'unleveraged': 0.51, 'lenderA': 0.66, 'lenderB': 0.49}...
"""try to implement a conjugate gradient method following following: https://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf """ def CG(A, b, x0, eps=0.01, imax=50): """Solve linear system Ax = b, starting from x0. The iterative process stops when the residue falls below eps. Eq. 45 - 49. ...
"""try to implement a conjugate gradient method following following: https://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf """ def cg(A, b, x0, eps=0.01, imax=50): """Solve linear system Ax = b, starting from x0. The iterative process stops when the residue falls below eps. Eq. 45 - 49. ...
''' This module is home to the IOManager class, which manages the various input and output formats (specifically, FASTA, FASTQ, CLUSTAL alignments, and GFF files, currently). ''' class IOManager(object): ''' A class used by the `IOBase` class to manage the various input and output methods for the differen...
""" This module is home to the IOManager class, which manages the various input and output formats (specifically, FASTA, FASTQ, CLUSTAL alignments, and GFF files, currently). """ class Iomanager(object): """ A class used by the `IOBase` class to manage the various input and output methods for the different...
class URLOpener(object): def __init__(self, x): self.x = x def urlopen(self): return file(self.x)
class Urlopener(object): def __init__(self, x): self.x = x def urlopen(self): return file(self.x)
class Photo(object): """ Database object for a photo to allow single uid calculation per full path """ def __init__(self, **kwargs): self.name = kwargs.get("name", "") self.full_path = kwargs.get("full_path", "") self.date_taken = kwargs.get("date_taken", "") self.ui...
class Photo(object): """ Database object for a photo to allow single uid calculation per full path """ def __init__(self, **kwargs): self.name = kwargs.get('name', '') self.full_path = kwargs.get('full_path', '') self.date_taken = kwargs.get('date_taken', '') self.ui...
class Repository: def __init__(self, RepositoryAffiliation, user, data): self.__userLogin = user.loginUser self.__userId = user.id self.__repositoryAffiliation = RepositoryAffiliation self.__url = data['url'] self.__isFork = data['isFork'] self.__pushedAt = data['push...
class Repository: def __init__(self, RepositoryAffiliation, user, data): self.__userLogin = user.loginUser self.__userId = user.id self.__repositoryAffiliation = RepositoryAffiliation self.__url = data['url'] self.__isFork = data['isFork'] self.__pushedAt = data['pus...
# Copyright 2013 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://aws.amazon.com/apache2.0 # # or in the "license" file accompa...
class Eventbase(object): def __init__(self, event_id, datetime, attributes): """ :param event_id: event id :type event_id: int :param datetime: datetime of event :type datetime: datetime.datetime :param attributes: event attributes :type attributes: dict ...
def minesweeper(matrix): x_axis, y_axis = len(matrix[0]), len(matrix) new_matrix = [] for y in range(y_axis): line = [] for x in range(x_axis): neighbour = [] if x > 0: neighbour.append(matrix[y][x-1]) if y > 0: neig...
def minesweeper(matrix): (x_axis, y_axis) = (len(matrix[0]), len(matrix)) new_matrix = [] for y in range(y_axis): line = [] for x in range(x_axis): neighbour = [] if x > 0: neighbour.append(matrix[y][x - 1]) if y > 0: ...
class Calculators(): def __init__(self): pass def dca(self, all_buys: list) -> tuple: """ Calculates the DCA entry, total quote invested and total coins purchased :param all_buys: All fully filled buys marked in database for symbol :return: Average DCA entry, total dolla...
class Calculators: def __init__(self): pass def dca(self, all_buys: list) -> tuple: """ Calculates the DCA entry, total quote invested and total coins purchased :param all_buys: All fully filled buys marked in database for symbol :return: Average DCA entry, total dollar...
# get user email email = input("What is your email address?:").strip() # slice out user name user = email[:email.index("@")] # slice out domain name domain = email[email.index("@")+1:] # format message output = "Your username is {} and you domain name is {}".format(user,domain) # display output message print(o...
email = input('What is your email address?:').strip() user = email[:email.index('@')] domain = email[email.index('@') + 1:] output = 'Your username is {} and you domain name is {}'.format(user, domain) print(output)
class Computer: def __init__(self): self.name = "Shihab" self.age = 18 def compare(self, other): return self.age == other.age c1 = Computer() c1.age = 30 c2 = Computer() c1.name = "Rashi" if c1.compare(c2): print("They are same") else: print("They are not same")
class Computer: def __init__(self): self.name = 'Shihab' self.age = 18 def compare(self, other): return self.age == other.age c1 = computer() c1.age = 30 c2 = computer() c1.name = 'Rashi' if c1.compare(c2): print('They are same') else: print('They are not same')
class points: user = [] points = [] def addUser(self, user, points): try: index = self.getIndex(user) except: index = -1 if index < 0: self.user.append(user) self.points.append(points) return 'User ' + user + ...
class Points: user = [] points = [] def add_user(self, user, points): try: index = self.getIndex(user) except: index = -1 if index < 0: self.user.append(user) self.points.append(points) return 'User ' + user + ' added with ...
#!/usr/bin/python # splitting.py nums = "1,5,6,8,2,3,1,9" k = nums.split(",") print (k) l = nums.split(",", 5) print (l) m = nums.rsplit(",", 3) print (m)
nums = '1,5,6,8,2,3,1,9' k = nums.split(',') print(k) l = nums.split(',', 5) print(l) m = nums.rsplit(',', 3) print(m)
##!FAIL: UnsupportedNodeError[Return]@5:4 def f(x): """ int -> NoneType """ return
def f(x): """ int -> NoneType """ return
#Defining a hash function """def get_hash(key): h=0 for char in key: h += ord(char) return h%100 print(get_hash("hirwa")) """ #Creating a hash Table class class Hashtable: def __init__(self): self.MAX=100 self.arr=[None for i in range(self.MAX)] def get_hash(self,key): ...
"""def get_hash(key): h=0 for char in key: h += ord(char) return h%100 print(get_hash("hirwa")) """ class Hashtable: def __init__(self): self.MAX = 100 self.arr = [None for i in range(self.MAX)] def get_hash(self, key): h = 0 for char in key: h ...
# Name, Variables, Functions def print_two(*args): arg1, arg2 = args print(f"arg1: {arg1}, arg2: {arg2}") print(f"Type1: {type(arg1)}. Type2: {type(arg2)}") def print_take_2(one, two): print(f"Value1: {one}, Value2: {two}") def print_take_1(one): print(f"Value: {one}") def print_none(): ...
def print_two(*args): (arg1, arg2) = args print(f'arg1: {arg1}, arg2: {arg2}') print(f'Type1: {type(arg1)}. Type2: {type(arg2)}') def print_take_2(one, two): print(f'Value1: {one}, Value2: {two}') def print_take_1(one): print(f'Value: {one}') def print_none(): print('I got nothing') print_two...
COL_WITH_NAN_SIGNIFICATION = ["BsmtQual", "BsmtCond", "BsmtExposure", "BsmtFinType1", "BsmtFinType2", "GarageType", "GarageFinish", "GarageQual", "GarageCond", "PoolQC", "Fence", "MiscFeature", "Alley"] CONTINUOUS_COL = ["LotFron...
col_with_nan_signification = ['BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2', 'GarageType', 'GarageFinish', 'GarageQual', 'GarageCond', 'PoolQC', 'Fence', 'MiscFeature', 'Alley'] continuous_col = ['LotFrontage', 'LotArea', 'MasVnrArea', 'BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF', '1s...
def dec2bin(x): cache = [] res = '' while x: num = x % 2 x = x // 2 cache.append(num) while cache: res += str(cache.pop()) return res print(dec2bin(10),bin(10))
def dec2bin(x): cache = [] res = '' while x: num = x % 2 x = x // 2 cache.append(num) while cache: res += str(cache.pop()) return res print(dec2bin(10), bin(10))
_config = {} def Get(key): global _config return _config[key] def Set(key, value): global _config _config[key] = value
_config = {} def get(key): global _config return _config[key] def set(key, value): global _config _config[key] = value
class Case: def __init__(self, number: str, status: str, title: str, body: str): self.number = number self.status = status self.title = title self.body = body
class Case: def __init__(self, number: str, status: str, title: str, body: str): self.number = number self.status = status self.title = title self.body = body
def update_transition_matrix(self, opponent_move): global POSSIBLE_MOVES if len(self.moves) <= len(LAST_POSSIBLE_MOVES[0]): return None for i in range(len(self.transition_sum_matrix[self.last_moves])): self.transition_sum_matrix[self.last_moves][i] *= self.decay self.transition_sum_matri...
def update_transition_matrix(self, opponent_move): global POSSIBLE_MOVES if len(self.moves) <= len(LAST_POSSIBLE_MOVES[0]): return None for i in range(len(self.transition_sum_matrix[self.last_moves])): self.transition_sum_matrix[self.last_moves][i] *= self.decay self.transition_sum_matri...
class Vertex: def __init__(self, name): self.name = name class Graph: vertices = {} edges = [] edge_indices = {} def add_vertex(self, vertex): if isinstance(vertex, Vertex) and vertex.name not in self.vertices: self.vertices[vertex.name] = vertex for row ...
class Vertex: def __init__(self, name): self.name = name class Graph: vertices = {} edges = [] edge_indices = {} def add_vertex(self, vertex): if isinstance(vertex, Vertex) and vertex.name not in self.vertices: self.vertices[vertex.name] = vertex for row in...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def sortList(self, head: ListNode) -> ListNode: if not head: return if head.next == None: return head def find_mid(h...
class Solution: def sort_list(self, head: ListNode) -> ListNode: if not head: return if head.next == None: return head def find_mid(head): if not head: return None (slow, fast) = (head, head) while fast.next and fa...
def parse(input_file): with open(input_file, 'r') as f: return f.read().split('\n\n') def clean_input(answers): return [a.replace('\n', '') for a in answers] def get_uniques(answers): return [set(a) for a in answers] def get_unique_count(answers): return [len(a) for a in answers] def get_agr...
def parse(input_file): with open(input_file, 'r') as f: return f.read().split('\n\n') def clean_input(answers): return [a.replace('\n', '') for a in answers] def get_uniques(answers): return [set(a) for a in answers] def get_unique_count(answers): return [len(a) for a in answers] def get_agr...
fib_num= lambda n:fib_num(n-1)+fib_num(n-2) if n>2 else 1 print(fib_num(6)) def test1_fib_num(): assert (fib_num(6)==8) def test2_fib_num(): assert (fib_num(5)==5) def test3_fib_num(): n = 10 assert (fib_num(2*n)==fib_num(n+1)**2 - fib_num(n-1)**2)
fib_num = lambda n: fib_num(n - 1) + fib_num(n - 2) if n > 2 else 1 print(fib_num(6)) def test1_fib_num(): assert fib_num(6) == 8 def test2_fib_num(): assert fib_num(5) == 5 def test3_fib_num(): n = 10 assert fib_num(2 * n) == fib_num(n + 1) ** 2 - fib_num(n - 1) ** 2
# cohort.migrations # Cohort app database migrations. # # Author: Benjamin Bengfort <benjamin@bengfort.com> # Created: Thu Dec 26 15:06:39 2019 -0600 # # Copyright (C) 2019 Georgetown University # For license information, see LICENSE.txt # # ID: __init__.py [] benjamin@bengfort.com $ """ Cohort app database migrati...
""" Cohort app database migrations. """
people = ['Jonas', 'Julio', 'Mike', 'Mez'] ages = [25, 30, 31, 39] for person, age in zip(people, ages): print(person, age)
people = ['Jonas', 'Julio', 'Mike', 'Mez'] ages = [25, 30, 31, 39] for (person, age) in zip(people, ages): print(person, age)
def main() -> None: n = int(input()) s = [list(map(lambda x: int(x) - 1, input())) for _ in range(n)] time = [[-1] * 10 for _ in range(n)] for i in range(n): for j in range(10): time[i][s[i][j]] = j mn = 1 << 60 for d in range(10): count = [0] * 10 ...
def main() -> None: n = int(input()) s = [list(map(lambda x: int(x) - 1, input())) for _ in range(n)] time = [[-1] * 10 for _ in range(n)] for i in range(n): for j in range(10): time[i][s[i][j]] = j mn = 1 << 60 for d in range(10): count = [0] * 10 mx = 0 ...
# encoding: utf-8 print("I will now count my chickens:") print("Hens", 25 + 30 / 6) print("Roosters", 100 - 25 * 3 % 4) print("Now I will count the eggs:") print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) print("Is it true that 3 + 2 < 5 - 7?") print(3 + 2 < 5 - 7) print("What is 3 + 2?", 3 + 2) print("What is 5 - 7?", ...
print('I will now count my chickens:') print('Hens', 25 + 30 / 6) print('Roosters', 100 - 25 * 3 % 4) print('Now I will count the eggs:') print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) print('Is it true that 3 + 2 < 5 - 7?') print(3 + 2 < 5 - 7) print('What is 3 + 2?', 3 + 2) print('What is 5 - 7?', 5 - 7) print("Oh, that's ...
''' 1) Create a Clusterfile 2) Add metadata to created Clusterfile 3) Create a bunch of Datasets - Add them to created Clusterfile '''
""" 1) Create a Clusterfile 2) Add metadata to created Clusterfile 3) Create a bunch of Datasets - Add them to created Clusterfile """
class EurecomDataset(Dataset): def __init__(self,domain,variation,training_dir=None,transform=None): self.transform = transform self.training_dir = training_dir # For each variant keep a list self.thermal_illu = [] self.thermal_exp = [] self.thermal_pose = [] ...
class Eurecomdataset(Dataset): def __init__(self, domain, variation, training_dir=None, transform=None): self.transform = transform self.training_dir = training_dir self.thermal_illu = [] self.thermal_exp = [] self.thermal_pose = [] self.thermal_occ = [] self...
#!/usr/bin/env python3 # ex31: Making Decisions print("You enter a dark room with two doors. Do you go through door #1 or door #2?") door = input("> ") if door == "1": print("There's a giant bear here eating a cheese cake. What do you do?") print("1. Take the cake.") print("2. Scream at the bear.") ...
print('You enter a dark room with two doors. Do you go through door #1 or door #2?') door = input('> ') if door == '1': print("There's a giant bear here eating a cheese cake. What do you do?") print('1. Take the cake.') print('2. Scream at the bear.') bear = input('> ') if bear == '1': print...
"""This problem was asked by Facebook. Suppose you are given two lists of n points, one list p1, p2, ..., pn on the line y = 0 and the other list q1, q2, ..., qn on the line y = 1. Imagine a set of n line segments connecting each point pi to qi. Write an algorithm to determine how many pairs of the line segments in...
"""This problem was asked by Facebook. Suppose you are given two lists of n points, one list p1, p2, ..., pn on the line y = 0 and the other list q1, q2, ..., qn on the line y = 1. Imagine a set of n line segments connecting each point pi to qi. Write an algorithm to determine how many pairs of the line segments in...
class item: def __init__(self, name, cap, dur, flav, text, cal): self.name = name self.cap = cap self.dur = dur self.fla = flav self.tex = text self.cal = cal return it = [item('Frosting', 4, -2, 0, 0, 5), item('Candy', 0, 5, -1, 0, 8), item('Butterscotch', -1, 0, 5, 0, 6), ...
class Item: def __init__(self, name, cap, dur, flav, text, cal): self.name = name self.cap = cap self.dur = dur self.fla = flav self.tex = text self.cal = cal return it = [item('Frosting', 4, -2, 0, 0, 5), item('Candy', 0, 5, -1, 0, 8), item('Butterscotch', -...
t = int(input()) for _ in range(t): n = int(input()) s = input() s = list(s) index = 0 while index < n - 1: s[index], s[index + 1] = s[index + 1], s[index] index += 2 for i in range(n): s[i] = chr(ord('z') - (ord(s[i]) - ord('a'))) print("".join(s))
t = int(input()) for _ in range(t): n = int(input()) s = input() s = list(s) index = 0 while index < n - 1: (s[index], s[index + 1]) = (s[index + 1], s[index]) index += 2 for i in range(n): s[i] = chr(ord('z') - (ord(s[i]) - ord('a'))) print(''.join(s))
# -*- coding: utf-8 -*- """ sub_analysis_proxy.py generated by WhatsOpt. """
""" sub_analysis_proxy.py generated by WhatsOpt. """
""" James Haywood, Unit 4.01 This unit was pretty good, especially the logic lab. That was fun, if a bit OCD-inducing with the wire layout (you know what I mean.) Assignment 3 seemed almost too easy though, so I'd make that tougher. """
""" James Haywood, Unit 4.01 This unit was pretty good, especially the logic lab. That was fun, if a bit OCD-inducing with the wire layout (you know what I mean.) Assignment 3 seemed almost too easy though, so I'd make that tougher. """
# -*- coding: utf-8 -*- # Author: Jiajun Ren <jiajunren0522@gmail.com> electron = "e" electrons = "es" phonon = "ph" class EphTable(tuple): @classmethod def all_phonon(cls, site_num): return cls([phonon] * site_num) @classmethod def from_mol_list(cls, mol_list, scheme): eph_list = ...
electron = 'e' electrons = 'es' phonon = 'ph' class Ephtable(tuple): @classmethod def all_phonon(cls, site_num): return cls([phonon] * site_num) @classmethod def from_mol_list(cls, mol_list, scheme): eph_list = [] if scheme < 4: for mol in mol_list: ...
sentence = 'This awesome spaghetti is awesome' better_sentence = sentence.replace('awesome', 'fabulous') print(better_sentence) date = '12/01/2035' print(date.replace('/', '-'))
sentence = 'This awesome spaghetti is awesome' better_sentence = sentence.replace('awesome', 'fabulous') print(better_sentence) date = '12/01/2035' print(date.replace('/', '-'))
# if you have a list = [], or a string = '', it will evaluate as a False value our_list = [] our_string = '' if our_list: print('This list has something in it.') if our_string: print('This string is not empty.') teams = ['knicks', 'kings', 'heat', 'pacers', 'celtics', 'pelicans'] for team in teams: if team.star...
our_list = [] our_string = '' if our_list: print('This list has something in it.') if our_string: print('This string is not empty.') teams = ['knicks', 'kings', 'heat', 'pacers', 'celtics', 'pelicans'] for team in teams: if team.startswith('k'): print('The ' + team.title() + ' could win the NBA cham...
class Node: def __init__(self, key, value): self.key = key self.val = value self.next = self.pre = None self.pre = None class LRUCache: def remove(self, node): node.pre.next, node.next.pre = node.next, node.pre self.dic.pop(node.key) def add(self, nod...
class Node: def __init__(self, key, value): self.key = key self.val = value self.next = self.pre = None self.pre = None class Lrucache: def remove(self, node): (node.pre.next, node.next.pre) = (node.next, node.pre) self.dic.pop(node.key) def add(self, node...
TOKENIZE_TEXT_INPUT_SCHEMA = { "type": "object", "properties": { "text": {"type": "string"}, }, "required": ["text"], "additionalProperties": False } TOKENIZE_TEXT_OUTPUT_SCHEMA = { "type": "array", "items": { "type": "array", "items": { "type": "array", ...
tokenize_text_input_schema = {'type': 'object', 'properties': {'text': {'type': 'string'}}, 'required': ['text'], 'additionalProperties': False} tokenize_text_output_schema = {'type': 'array', 'items': {'type': 'array', 'items': {'type': 'array', 'items': {'type': 'string'}}}}
class Solution: def convertToTitle(self, n: int) -> str: return self.solution1(n) def solution1(self, n: int) -> str: ans = [] while n > 0: n, r = divmod(n-1, 26) ans.append(chr(r + ord('A'))) return ''.join(ans[::-1]) # time limit exceeded def s...
class Solution: def convert_to_title(self, n: int) -> str: return self.solution1(n) def solution1(self, n: int) -> str: ans = [] while n > 0: (n, r) = divmod(n - 1, 26) ans.append(chr(r + ord('A'))) return ''.join(ans[::-1]) def solution2(self, n: i...
"""Prediction of Optimal Price based on Listing Properties""" def get_optimal_pricing(**listing): ''' Just return 100 for now - will call out to a proper predictive model later''' print(listing) price = listing.get('price', 0) price = price+10 if price else 100 return price
"""Prediction of Optimal Price based on Listing Properties""" def get_optimal_pricing(**listing): """ Just return 100 for now - will call out to a proper predictive model later""" print(listing) price = listing.get('price', 0) price = price + 10 if price else 100 return price