content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
############################################################################# # Copyright 2016 Mass KonFuzion # # 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/l...
class Collisiongeomtype: aabb = 0
class Virus(object): '''Properties and attributes of the virus used in Simulation.''' def __init__(self, name, repro_rate, mortality_rate): self.name = name self.repro_rate = repro_rate self.mortality_rate = mortality_rate def test_virus_instantiation(): #TODO: Create your own tes...
class Virus(object): """Properties and attributes of the virus used in Simulation.""" def __init__(self, name, repro_rate, mortality_rate): self.name = name self.repro_rate = repro_rate self.mortality_rate = mortality_rate def test_virus_instantiation(): """Check to make sure that ...
def getInnerBlocks(string, begin, end, sep = [","]): ret_list = [] if not isinstance(string, str): return None # read a name until depth 1. Store until depth 0, and append it along with # the contents. # at depth 0, ignore separators cname = "" depth = 0 last_name = "" cstr = "" clist = [] for char in ...
def get_inner_blocks(string, begin, end, sep=[',']): ret_list = [] if not isinstance(string, str): return None cname = '' depth = 0 last_name = '' cstr = '' clist = [] for char in string: if char == end: depth -= 1 if depth == 0: cl...
def solve(n): a = [] for _ in range(n): name, h = input().split() h = float(h) a.append((name, h)) a.sort(key = lambda t: t[1], reverse=True) m = a[0][1] for n, h in a: if h != m: break print(n, end = " ") print() while True: n = int(input()) if ...
def solve(n): a = [] for _ in range(n): (name, h) = input().split() h = float(h) a.append((name, h)) a.sort(key=lambda t: t[1], reverse=True) m = a[0][1] for (n, h) in a: if h != m: break print(n, end=' ') print() while True: n = int(input(...
# IDLE (Python 3.8.0) # module_for_lists_of_terms def termal_generator(lict): length_of_termal_generator = 16 padding = length_of_termal_generator - len(lict) count = padding while count != 0: lict.append(['']) count = count - 1 termal_lict = [] for first_inner in lict[0]: ...
def termal_generator(lict): length_of_termal_generator = 16 padding = length_of_termal_generator - len(lict) count = padding while count != 0: lict.append(['']) count = count - 1 termal_lict = [] for first_inner in lict[0]: for second_inner in lict[1]: for thi...
# ------------------------------ # 331. Verify Preorder Serialization of a Binary Tree # # Description: # One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #. # # _9_ # ...
class Solution: def is_valid_serialization(self, preorder: str) -> bool: nodes = preorder.split(',') diff = 1 for n in nodes: diff -= 1 if diff < 0: return False if n != '#': diff += 2 return diff == 0 if __name__ =...
class HsvFilter: def __init__(self, hMin=None, sMin=None, vMin=None, hMax=None, sMax=None, vMax=None, sAdd=None, sSub=None, vAdd=None, vSub=None): self.hMin = hMin self.sMin = sMin self.vMin = vMin self.hMax = hMax self.sMax = sMax self.vMax = vM...
class Hsvfilter: def __init__(self, hMin=None, sMin=None, vMin=None, hMax=None, sMax=None, vMax=None, sAdd=None, sSub=None, vAdd=None, vSub=None): self.hMin = hMin self.sMin = sMin self.vMin = vMin self.hMax = hMax self.sMax = sMax self.vMax = vMax self.sAdd ...
class Solution: def isHappy(self, n: int) -> bool: def squaredSum(n: int) -> bool: sum = 0 while n: sum += pow(n % 10, 2) n //= 10 return sum slow = squaredSum(n) fast = squaredSum(squaredSum(n)) while slow != fast: slow = squaredSum(slow) fast = squar...
class Solution: def is_happy(self, n: int) -> bool: def squared_sum(n: int) -> bool: sum = 0 while n: sum += pow(n % 10, 2) n //= 10 return sum slow = squared_sum(n) fast = squared_sum(squared_sum(n)) while slow !=...
def safeDict(elem, array_of_keys, default=""): try: for key in array_of_keys: elem = elem[key] return elem except Exception as e: return default
def safe_dict(elem, array_of_keys, default=''): try: for key in array_of_keys: elem = elem[key] return elem except Exception as e: return default
# Those constants are used from the library only BASE_PAL_URL = "https://pal-{}.adyen.com/pal/servlet" PAL_LIVE_ENDPOINT_URL_TEMPLATE = "https://{}-pal-live" \ ".adyenpayments.com/pal/servlet" BASE_HPP_URL = "https://{}.adyen.com/hpp" ENDPOINT_CHECKOUT_TEST = "https://checkout-test.adye...
base_pal_url = 'https://pal-{}.adyen.com/pal/servlet' pal_live_endpoint_url_template = 'https://{}-pal-live.adyenpayments.com/pal/servlet' base_hpp_url = 'https://{}.adyen.com/hpp' endpoint_checkout_test = 'https://checkout-test.adyen.com' endpoint_checkout_live_suffix = 'https://{}-checkout-live.adyenpayments.com/chec...
__all__ = ['VERSION'] YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" VIDEO = 'youtube#video' YOUTUBE_VIDEO_URL = 'https://www.youtube.com/watch?v=' VERSION = '4.0.0'
__all__ = ['VERSION'] youtube_api_service_name = 'youtube' youtube_api_version = 'v3' video = 'youtube#video' youtube_video_url = 'https://www.youtube.com/watch?v=' version = '4.0.0'
# mailbox_or_url_parsetab.py # This file is automatically generated. Do not edit. _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'mailbox_or_urlFWSP AT DOT COMMA SEMICOLON LANGLE RANGLE ATOM DOT_ATOM LBRACKET RBRACKET DTEXT DQUOTE QTEXT QPAIR LPAREN RPAREN CTEXT URLmailbox_or_url_list : mailbox_or_url_list...
_tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'mailbox_or_urlFWSP AT DOT COMMA SEMICOLON LANGLE RANGLE ATOM DOT_ATOM LBRACKET RBRACKET DTEXT DQUOTE QTEXT QPAIR LPAREN RPAREN CTEXT URLmailbox_or_url_list : mailbox_or_url_list delim mailbox_or_url\n | mailbox_or_url_list delim\n ...
print(add(5, 3)) def add(x, y): return x+y
print(add(5, 3)) def add(x, y): return x + y
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def kthLargest(self, root: TreeNode, k: int) -> int: def dfs(root): if root: dfs(root.left) nu...
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def kth_largest(self, root: TreeNode, k: int) -> int: def dfs(root): if root: dfs(root.left) nums.append(root.val) ...
class Solution: # O(n) time | O(1) space - where n is the length of the input list def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: maxDuration, startTime, slowestKey = 0, 0, '' for i in range(len(releaseTimes)): pressTime = releaseTimes[i] - startTime ...
class Solution: def slowest_key(self, releaseTimes: List[int], keysPressed: str) -> str: (max_duration, start_time, slowest_key) = (0, 0, '') for i in range(len(releaseTimes)): press_time = releaseTimes[i] - startTime if pressTime > maxDuration: max_duration ...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"run_params": "000_exp_02_pretrained.ipynb", "experiment": "000_exp_02_pretrained.ipynb", "DatasetBuilder": "01_dataset_builder.ipynb", "StatementClassifier": "02_statement_classife...
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'run_params': '000_exp_02_pretrained.ipynb', 'experiment': '000_exp_02_pretrained.ipynb', 'DatasetBuilder': '01_dataset_builder.ipynb', 'StatementClassifier': '02_statement_classifer.ipynb', 'Experiment': '03_experiment.ipynb', 'RunParams': '04_run_...
A, B = map(int, input().split()) S = str(input()) flag = True if not S[:A].isdecimal(): flag = False elif S[A] != '-': flag = False elif not S[-B:].isdecimal(): flag = False if flag: print('Yes') else: print('No')
(a, b) = map(int, input().split()) s = str(input()) flag = True if not S[:A].isdecimal(): flag = False elif S[A] != '-': flag = False elif not S[-B:].isdecimal(): flag = False if flag: print('Yes') else: print('No')
def configure_tx_chains(txChains, streamNum, mcsIdx): txChains = txChains.lower() RATE_MCS_ANT_A_MSK = 0x04000 RATE_MCS_ANT_B_MSK = 0x08000 RATE_MCS_ANT_C_MSK = 0x10000 RATE_MCS_HT_MSK = 0x00100 mask = 0x0 usedAntNum = 0 if "a" in txChains: mask |= RATE_MCS_ANT_A_MSK ...
def configure_tx_chains(txChains, streamNum, mcsIdx): tx_chains = txChains.lower() rate_mcs_ant_a_msk = 16384 rate_mcs_ant_b_msk = 32768 rate_mcs_ant_c_msk = 65536 rate_mcs_ht_msk = 256 mask = 0 used_ant_num = 0 if 'a' in txChains: mask |= RATE_MCS_ANT_A_MSK used_ant_num ...
# 19. Remove Nth Node From End of List # Time: O(n) # Space: O(1) # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: slow = head fast ...
class Solution: def remove_nth_from_end(self, head: ListNode, n: int) -> ListNode: slow = head fast = head for i in range(n): fast = fast.next while fast: prev = slow slow = slow.next fast = fast.next if slow == head: ...
''' URL: https://leetcode.com/problems/find-lucky-integer-in-an-array/ Difficulty: Easy Description: Find Lucky Integer in an Array Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value. Return a lucky integer in the array. If there are multiple lucky in...
""" URL: https://leetcode.com/problems/find-lucky-integer-in-an-array/ Difficulty: Easy Description: Find Lucky Integer in an Array Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value. Return a lucky integer in the array. If there are multiple lucky in...
#string.py str1 = "Hello" str2 = 'John' print(type(str1)) print("\"Good\\Job\"") greet = "Hello John" print(greet[1]) print(greet[-4]) print(greet[0:3]) print("bad" + "apple") print("wt" + "d" * 5) print(len("pine")) print(type(str(123)))
str1 = 'Hello' str2 = 'John' print(type(str1)) print('"Good\\Job"') greet = 'Hello John' print(greet[1]) print(greet[-4]) print(greet[0:3]) print('bad' + 'apple') print('wt' + 'd' * 5) print(len('pine')) print(type(str(123)))
#!/usr/bin/env python NAME = 'Reblaze (Reblaze)' def is_waf(self): if self.matchcookie(r'^rbzid='): return True if self.matchheader(('Server', 'Reblaze Secure Web Gateway')): return True # Now going for attack phase for attack in self.attacks: r = attack(self) if r is...
name = 'Reblaze (Reblaze)' def is_waf(self): if self.matchcookie('^rbzid='): return True if self.matchheader(('Server', 'Reblaze Secure Web Gateway')): return True for attack in self.attacks: r = attack(self) if r is None: return (_, page) = r if ...
# # PySNMP MIB module TIME-AGGREGATE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIME-AGGREGATE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:09:20 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, single_value_constraint, constraints_union, value_range_constraint, constraints_intersection) ...
class ExtendedTextAttributes(object): def __init__( self, text, matched_text, canonical_url, description, title, jpeg_thumbnail, context_info ): self._text = text self._matched_text = matched_text self._canonical_url = canonical_url self._description = des...
class Extendedtextattributes(object): def __init__(self, text, matched_text, canonical_url, description, title, jpeg_thumbnail, context_info): self._text = text self._matched_text = matched_text self._canonical_url = canonical_url self._description = description self._title ...
_V = {} # Stages: game, rounds # State: probability, probability of co-operating # Action: # V(t,p) gives maximum expected value from starting game t with probability p of cooperating def V(game, probability): if game is 10: return 0, 0 else: if (game, probability) not in _V: coope...
_v = {} def v(game, probability): if game is 10: return (0, 0) elif (game, probability) not in _V: cooperate = probability * (3 + v(game + 1, min(1, probability + 0.1))[0]) + (1 - probability) * (0 + v(game + 1, min(1, probability + 0.1))[0]) defect = probability * (5 + v(game + 1, max(...
BASE_DIR = './' environ = { 'KPK_DATA': '/home/kpk/data', 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' } KPK_DATA = environ.get('KPK_DATA') # print(KPK_DATA) # _KPK_DATA = environ['KPK_DATA'] # print(_KPK_DATA) # os.environ.get('KPK_DATA') or BASE_DIR # # os.environ.get('KPK_DATA') ...
base_dir = './' environ = {'KPK_DATA': '/home/kpk/data', 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'} kpk_data = environ.get('KPK_DATA') pass if KPK_DATA: root = KPK_DATA else: root = BASE_DIR print(ROOT) pass root = KPK_DATA if KPK_DATA else BASE_DIR print(ROOT) pass root = KPK_DATA ...
class Reference: def __init__(self, id, campaign_id, name, details, created, modified): self.id = id self.campaign_id = campaign_id self.name = name self.details = details self.created = created self.modified = modified
class Reference: def __init__(self, id, campaign_id, name, details, created, modified): self.id = id self.campaign_id = campaign_id self.name = name self.details = details self.created = created self.modified = modified
NONE = 0x000000000 # Posting Permissions CREATE_POST = 0x000000001 EDIT_POST = 0x000000002 DELETE_POST = 0x000000004 # Documents Permissions UPLOAD_DOCUMENT = 0x000000008 EDIT_DOCUMENT = 0x000000010 DELETE_DOCUMENT = 0x000000020 # User Account Permissions CREATE_USER = 0x000000040 EDIT_USER = 0x000000080 DELETE_USER...
none = 0 create_post = 1 edit_post = 2 delete_post = 4 upload_document = 8 edit_document = 16 delete_document = 32 create_user = 64 edit_user = 128 delete_user = 256
class Car: wheels = 4 # Class (Static) Variables before __init__ def __init__(self): self.com = "BMW" # Instance Variables inside __init__ self.mil = "10" c1 = Car() c2 = Car() Car.wheels = 5 # The value of all ...
class Car: wheels = 4 def __init__(self): self.com = 'BMW' self.mil = '10' c1 = car() c2 = car() Car.wheels = 5 print(c1.com, c1.mil, c1.wheels) print(c2.com, c2.mil, c2.wheels)
''' Discuss structure: Getting input from user Formatting the input (multiply by 100 then convert to integer) Getting total amount of change (amount paid minus bill) Getting dollars of change (divide by 100 then convert to integer) Getting the amount of change leftover (either change minus dollars times 100 or ch...
""" Discuss structure: Getting input from user Formatting the input (multiply by 100 then convert to integer) Getting total amount of change (amount paid minus bill) Getting dollars of change (divide by 100 then convert to integer) Getting the amount of change leftover (either change minus dollars times 100 or cha...
class AzureCloudProviderResourceModel(object): def __init__(self): self.azure_application_id = '' # type: str self.azure_mgmt_network_d = '' # type: str self.azure_mgmt_nsg_id = '' # type: str self.azure_application_key = '' # type: str self.region = '' # type: str ...
class Azurecloudproviderresourcemodel(object): def __init__(self): self.azure_application_id = '' self.azure_mgmt_network_d = '' self.azure_mgmt_nsg_id = '' self.azure_application_key = '' self.region = '' self.vm_size = '' self.keypairs_location = '' ...
# Given a binary matrix representing an image, we want to flip the image horizontally, then invert it. # To flip an image horizontally means that each row of the image is reversed. # For example, flipping [0, 1, 1] horizontally results in [1, 1, 0]. # To invert an image means that each 0 is replaced by 1, and each 1 ...
def flip_invert_image(matrix): m = len(matrix) n = len(matrix[0]) for i in range(m): for j in range((n + 1) // 2): (matrix[i][j], matrix[i][n - j - 1]) = (matrix[i][n - j - 1] ^ 1, matrix[i][j] ^ 1) return matrix print(flip_invert_image([[1, 0, 1], [1, 1, 1], [0, 1, 1]])) print(flip_...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** _SNAKE_TO_CAMEL_CASE_TABLE = { "availability_zones": "availabilityZones", "backend_services": "backendServices", "beanstalk...
_snake_to_camel_case_table = {'availability_zones': 'availabilityZones', 'backend_services': 'backendServices', 'beanstalk_environment_name': 'beanstalkEnvironmentName', 'block_devices_mode': 'blockDevicesMode', 'capacity_unit': 'capacityUnit', 'cluster_id': 'clusterId', 'cluster_zone_name': 'clusterZoneName', 'control...
# guess file size : https://softwareengineering.stackexchange.com/q/204417 # https://stackoverflow.com/a/1094933 def sizeof_fmt(num, suffix='B'): for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 ...
def sizeof_fmt(num, suffix='B'): for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return '%3.1f%s%s' % (num, unit, suffix) num /= 1024.0 return '%.1f%s%s' % (num, 'Yi', suffix)
# Source : https://leetcode.com/problems/rectangle-overlap/ # Author : foxfromworld # Date : 07/04/2021 # Second attempt class Solution: def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool: if rec1[0] == rec1[2] or rec2[0] == rec2[2] or\ rec2[1] == rec2[3] or rec1[1] == rec1[3]: ...
class Solution: def is_rectangle_overlap(self, rec1: List[int], rec2: List[int]) -> bool: if rec1[0] == rec1[2] or rec2[0] == rec2[2] or rec2[1] == rec2[3] or (rec1[1] == rec1[3]): return False up_bound = min(rec1[3], rec2[3]) lo_bound = max(rec1[1], rec2[1]) rt_bound = ...
class Project(): def __init__(self, id_project, name, session_counter, token): self.id_project = id_project self.name = name self.session_counter = session_counter self.token = token class Session(): def __init__(self, id_session, index, dt_start, dt_end, is_active, is_favorite,...
class Project: def __init__(self, id_project, name, session_counter, token): self.id_project = id_project self.name = name self.session_counter = session_counter self.token = token class Session: def __init__(self, id_session, index, dt_start, dt_end, is_active, is_favorite, h...
#======================================================================= # Author: Isai Damier # Title: Selection Sort # Project: geekviewpoint # Package: algorithm.sorting # # Statement: # Given a disordered list of integers (or any other items), # rearrange the integers in natural order. # # Sample Input: [18...
def selectionsort(aList): for i in range(len(aList)): least = i for k in range(i + 1, len(aList)): if aList[k] < aList[least]: least = k swap(aList, least, i) def swap(A, x, y): tmp = A[x] A[x] = A[y] A[y] = tmp
#!/usr/bin/env python3 # -*- coding: utf-8 -*- a = 3 if a > 2: print("H") else: print("L")
a = 3 if a > 2: print('H') else: print('L')
# Enter your code here. Read input from STDIN. Print output to STDOUT m = float(raw_input()); t = m * input() /100; x = m * input() /100; totalCost = round(m + x + t); print ('The total meal cost is' " " + str(int(totalCost)) + " " 'dollars.')
m = float(raw_input()) t = m * input() / 100 x = m * input() / 100 total_cost = round(m + x + t) print('The total meal cost is ' + str(int(totalCost)) + ' dollars.')
# program to match key values in two dictionaries. x = {'key1': 1, 'key2': 3, 'key3': 2} y = {'key1': 1, 'key2': 2} for (key, value) in set(x.items()) & set(y.items()): print('%s: %s is present in both x and y' % (key, value))
x = {'key1': 1, 'key2': 3, 'key3': 2} y = {'key1': 1, 'key2': 2} for (key, value) in set(x.items()) & set(y.items()): print('%s: %s is present in both x and y' % (key, value))
class Number(object): def __init__(self, value): if value % 2 != 0: self.even = self._odds_even else: self.even = self._even def _even(self): print("even") return True def _odds_even(self): print("not odd") return False a = Number...
class Number(object): def __init__(self, value): if value % 2 != 0: self.even = self._odds_even else: self.even = self._even def _even(self): print('even') return True def _odds_even(self): print('not odd') return False a = number(2)...
WIDTH = 87 HEIGHT = 87 FIRST = 0x20 LAST = 0x7f _font =\ b'\x00\x4a\x5a\x02\x44\x60\x44\x52\x60\x52\x02\x44\x60\x44\x60'\ b'\x60\x44\x02\x52\x52\x52\x3e\x52\x66\x02\x44\x60\x44\x44\x60'\ b'\x60\x02\x44\x60\x44\x52\x60\x52\x02\x46\x5e\x46\x59\x5e\x4b'\ b'\x02\x4b\x59\x4b\x5e\x59\x46\x02\x52\x52\x52\x44\x52\x60\x02'\ b'...
width = 87 height = 87 first = 32 last = 127 _font = b'\x00JZ\x02D`DR`R\x02D`D``D\x02RRR>Rf\x02D`DD``\x02D`DR`R\x02F^FY^K\x02KYK^YF\x02RRRDR`\x02KYKFY^\x02F^FK^Y\x02KYKRYR\x02MWMWWM\x02RRRKRY\x02MWMMWW\x07GRRGPGMHJJHMGPGR\x07GRGRGTHWJZM\\P]R]\x07R]R]T]W\\ZZ\\W]T]R\x07R]]R]P\\MZJWHTGRG\x08D`DOGQKSPTTTYS]Q`O\x08PUUDSGQKP...
#!/usr/bin/python ## Ejercicio 1 reverse Polish Notation ## Autor: Fabiola Tapara Quispe ## Description: Mediante el siguiente metodo recibe un string con datos y signos con operaciones basicas (+, -, *, /) usando una Pila como estructura. ## * Date: 15/11/21 def sum (a, b): return a + b def resta (a, b): ...
def sum(a, b): return a + b def resta(a, b): return a - b def multipli(a, b): return a * b def division(a, b): return a // b def polish_reverse(input): operadores = '+-*/' string = [] listado = input.split(' ') for i in listado: if i in operadores: num2 = string.p...
def return_category_with_more_spending(transactions): category_transactions = transactions.groupby(by=["column_category"])[ "column_installment_value" ].sum() return category_transactions.idxmax(), category_transactions.max()
def return_category_with_more_spending(transactions): category_transactions = transactions.groupby(by=['column_category'])['column_installment_value'].sum() return (category_transactions.idxmax(), category_transactions.max())
def is_palindrome(n: int) -> bool: s = str(n) h = int(len(s) / 2) s1 = s[:h] s2 = s[h:][::-1] is_palindrome = True for i in range(h): if s1[i] != s2[i]: is_palindrome = False return is_palindrome def solution() -> int: largest_palindrome = 0 for i in range(100, ...
def is_palindrome(n: int) -> bool: s = str(n) h = int(len(s) / 2) s1 = s[:h] s2 = s[h:][::-1] is_palindrome = True for i in range(h): if s1[i] != s2[i]: is_palindrome = False return is_palindrome def solution() -> int: largest_palindrome = 0 for i in range(100, 1...
''' Check valid age Write a program that takes age fro the user and then decide whether the age is between 18 to 24. If so, then it will display the message "You can apply for youth festival program". Otherwise, display the message "Sorry, you cannot apply". If age >= 18 and age <= 24 # Not correct If age = 18 and ...
""" Check valid age Write a program that takes age fro the user and then decide whether the age is between 18 to 24. If so, then it will display the message "You can apply for youth festival program". Otherwise, display the message "Sorry, you cannot apply". If age >= 18 and age <= 24 # Not correct If age = 18 and ...
#Algorithm Case Study def naive(a,b): x=a; y=b z =0 while(x > 0): z = z+y x = x-1 return z def testnaive(): i=0 while(i < 10): j=0 while(j < 10): print(i,j) print(naive(i,j)) j += 1 i += 1 ...
def naive(a, b): x = a y = b z = 0 while x > 0: z = z + y x = x - 1 return z def testnaive(): i = 0 while i < 10: j = 0 while j < 10: print(i, j) print(naive(i, j)) j += 1 i += 1 if __name__ == '__main__': testn...
capacity = int(input()) income = 0 command = input() while command != "Movie time!": group_count = int(command) if group_count > capacity: print("The cinema is full.") print(f"Cinema income - {income} lv.") exit() capacity -= group_count group_tax = group_count * 5 if gro...
capacity = int(input()) income = 0 command = input() while command != 'Movie time!': group_count = int(command) if group_count > capacity: print('The cinema is full.') print(f'Cinema income - {income} lv.') exit() capacity -= group_count group_tax = group_count * 5 if group_c...
#pretty print method def indent(elem, level=0): i = "\n" + level*" " j = "\n" + (level-1)*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): elem.tail = i for subelem in elem: ...
def indent(elem, level=0): i = '\n' + level * ' ' j = '\n' + (level - 1) * ' ' if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + ' ' if not elem.tail or not elem.tail.strip(): elem.tail = i for subelem in elem: indent(sube...
# -*- coding: utf-8 -*- # This work is licensed under the MIT License. # To view a copy of this license, visit https://www.gnu.org/licenses/ # Written by Taher Abbasi # Email: abbasi.taher@gmail.com class WrongSide(Exception): pass
class Wrongside(Exception): pass
skywater_metal1 = {"layer": 68, "datatype": 20 } skywater_metal2 = {"layer": 69, "datatype": 20 } skywater_metal3 = {"layer": 70, "datatype": 20 } skywater_metal4 = {"layer": 71, "datatype": 20 } skywater_metal5 = {"layer": 72, "datatype": 20 }
skywater_metal1 = {'layer': 68, 'datatype': 20} skywater_metal2 = {'layer': 69, 'datatype': 20} skywater_metal3 = {'layer': 70, 'datatype': 20} skywater_metal4 = {'layer': 71, 'datatype': 20} skywater_metal5 = {'layer': 72, 'datatype': 20}
rc = 0 def setup(): size(600, 600) smooth() background(0) font = loadFont("Gadugi-Bold-48.vlw") textFont(font, 48) def draw(): global rc translate(width/2, height/2) pushMatrix() rotate(rc) fill(255) text("Black", mouseX - width/4, mouseY - height/4) popMa...
rc = 0 def setup(): size(600, 600) smooth() background(0) font = load_font('Gadugi-Bold-48.vlw') text_font(font, 48) def draw(): global rc translate(width / 2, height / 2) push_matrix() rotate(rc) fill(255) text('Black', mouseX - width / 4, mouseY - height / 4) pop_matr...
class MessagesSerializer: fields = ['id', 'topic', 'payload', 'attributes', 'bulk'] def serialize(self, messages): return [self._serialize_fields(message) for message in messages] def _serialize_fields(self, message): return {field: getattr(message, field, None) for field in self.fields}
class Messagesserializer: fields = ['id', 'topic', 'payload', 'attributes', 'bulk'] def serialize(self, messages): return [self._serialize_fields(message) for message in messages] def _serialize_fields(self, message): return {field: getattr(message, field, None) for field in self.fields}
# -*- coding: utf-8 -*- # @Author: Anderson # @Date: 2018-09-01 22:04:38 # @Last Modified by: Anderson # @Last Modified time: 2018-09-14 15:55:53 class DS(object): def __init__(self, N): self.__id = list(range(0, N)) def is_connected(self, parent, child): pid = ord(parent) - ord('A') ...
class Ds(object): def __init__(self, N): self.__id = list(range(0, N)) def is_connected(self, parent, child): pid = ord(parent) - ord('A') cid = ord(child) - ord('A') connected = False generation_count = 0 while not connected: generation_count += 1 ...
# # PySNMP MIB module Juniper-IPV6-PROFILE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-IPV6-PROFILE-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:03:09 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7....
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_range_constraint, constraints_union, value_size_constraint, single_value_constraint) ...
print("My name is Jessica Bonnie Ayomide") print("JJJJJJJJJJJJJ BBBBBBBBBB A") print(" J B B A A") print(" J B B A A") print(" J B B A A") print(" J B B A A") print(" J BB...
print('My name is Jessica Bonnie Ayomide') print('JJJJJJJJJJJJJ BBBBBBBBBB A') print(' J B B A A') print(' J B B A A') print(' J B B A A') print(' J B B A A') print(' J BBBBBBBB...
#!/usr/bin/env python3 def main(): arr = [] fname = sys.argv[1] with open(fname, 'r') as f: for line in f: arr.append(int(line.rstrip('\r\n'))) quicksort(arr, start=0, end=len(arr)-1) print('Sorted list is: ', arr) return def quicksort(arr, start, end): if end - start <...
def main(): arr = [] fname = sys.argv[1] with open(fname, 'r') as f: for line in f: arr.append(int(line.rstrip('\r\n'))) quicksort(arr, start=0, end=len(arr) - 1) print('Sorted list is: ', arr) return def quicksort(arr, start, end): if end - start < 1: return 0 ...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"test_eq": "00_core.ipynb", "listify": "00_core.ipynb", "test_in": "00_core.ipynb", "test_err": "00_core.ipynb", "configure_logging": "00_core.ipynb", "setup_dataf...
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'test_eq': '00_core.ipynb', 'listify': '00_core.ipynb', 'test_in': '00_core.ipynb', 'test_err': '00_core.ipynb', 'configure_logging': '00_core.ipynb', 'setup_dataframe_copy_logging': '00_core.ipynb', 'n_total_series': '00_core.ipynb', 'n_days_total'...
# code '''python''' class Solution(object): def lengthOfLastWord(self, s): self.s=s string = self.s.strip().split(' ')[-1] return len(string)
"""python""" class Solution(object): def length_of_last_word(self, s): self.s = s string = self.s.strip().split(' ')[-1] return len(string)
def clean_sentence(output, data_loader): start_word = data_loader.dataset.vocab.start_word end_word = data_loader.dataset.vocab.end_word unk_word = data_loader.dataset.vocab.unk_word words = [] for i in range(len(output)): word_idx = output[i] word = data_loader.dataset.vocab.idx2wo...
def clean_sentence(output, data_loader): start_word = data_loader.dataset.vocab.start_word end_word = data_loader.dataset.vocab.end_word unk_word = data_loader.dataset.vocab.unk_word words = [] for i in range(len(output)): word_idx = output[i] word = data_loader.dataset.vocab.idx2wor...
# # PySNMP MIB module TPLINK-SSH-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-SSH-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:25:53 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, value_range_constraint, constraints_union, constraints_intersection, single_value_constraint) ...
REGULAR_MARGIN_REQUIREMENT = 0.25 LEVERAGED_MARGIN_REQUIREMENT = 0.75 def max_margin(leveraged_value, regular_value, percentage_of_leveraged_drop, percentage_of_regular_drop, current_loan): leveraged_value_after_drop = leveraged_value * (1 - percentage_of_leveraged_drop) regular_value_after_dro...
regular_margin_requirement = 0.25 leveraged_margin_requirement = 0.75 def max_margin(leveraged_value, regular_value, percentage_of_leveraged_drop, percentage_of_regular_drop, current_loan): leveraged_value_after_drop = leveraged_value * (1 - percentage_of_leveraged_drop) regular_value_after_drop = regular_valu...
class Solution: def __init__(self): pass # o(mn) def print_lcs(self, str1, str2): m = len(str1) n = len(str2) if n == 0 or m == 0: return 0 # declare an two dimension array store calculated dp value of lcs(str1[i] R = [[None] * (n + 1) for i in xr...
class Solution: def __init__(self): pass def print_lcs(self, str1, str2): m = len(str1) n = len(str2) if n == 0 or m == 0: return 0 r = [[None] * (n + 1) for i in xrange(m + 1)] for i in range(m + 1): for j in range(n + 1): ...
lines = None with open('day07/input.txt') as f: lines = f.readlines() line = lines[0] arr = list(map(lambda s: int(s), line.split(","))) cost = [] prev = 0 q = 0 for i in range(2000): cost.append(prev + q) prev = prev + q q += 1 min = 99999999999999 for pos in range(1500): sum = 0 for x in ar...
lines = None with open('day07/input.txt') as f: lines = f.readlines() line = lines[0] arr = list(map(lambda s: int(s), line.split(','))) cost = [] prev = 0 q = 0 for i in range(2000): cost.append(prev + q) prev = prev + q q += 1 min = 99999999999999 for pos in range(1500): sum = 0 for x in arr: ...
target = "xilinx" action = "synthesis" syn_device = "xc7k325t" syn_grade = "-2" syn_package = "ffg900" syn_top = "cm0_busy_wait_top" syn_project = "cm0_busy_wait_top" syn_tool = "vivado" modules = { "local" : [ "../../../top/kc705_busy_wait/verilog" ], }
target = 'xilinx' action = 'synthesis' syn_device = 'xc7k325t' syn_grade = '-2' syn_package = 'ffg900' syn_top = 'cm0_busy_wait_top' syn_project = 'cm0_busy_wait_top' syn_tool = 'vivado' modules = {'local': ['../../../top/kc705_busy_wait/verilog']}
class DataObject: def __init__(self, read_data=True): if read_data: self._run_methods('read') self._run_methods('parse') def _run_methods(self, method_type): for method in [m for m in dir(self) if m.startswith('_{}_'.format(method_type))]: getattr(self, me...
class Dataobject: def __init__(self, read_data=True): if read_data: self._run_methods('read') self._run_methods('parse') def _run_methods(self, method_type): for method in [m for m in dir(self) if m.startswith('_{}_'.format(method_type))]: getattr(self, meth...
def sumUpNumbers(inputString): numbers = [] curr = "" for i in inputString: try: x = int(i) curr += i except: if curr != "": numbers.append(curr) curr = "" if curr != "": numbers.append(curr) return sum([in...
def sum_up_numbers(inputString): numbers = [] curr = '' for i in inputString: try: x = int(i) curr += i except: if curr != '': numbers.append(curr) curr = '' if curr != '': numbers.append(curr) return sum([in...
#!/usr/bin/python3 def recsum(n): return n if n<=1 else n+recsum(n-1) n = int(input("Enter your number\t")) if n < 0: print("Enter a positive number") else: print("The sum is",recsum(n))
def recsum(n): return n if n <= 1 else n + recsum(n - 1) n = int(input('Enter your number\t')) if n < 0: print('Enter a positive number') else: print('The sum is', recsum(n))
raio = float(input()) pi = 3.14159 VOLUME = (4 / 3) * pi * (raio**3) print("VOLUME = {:.3f}".format(VOLUME))
raio = float(input()) pi = 3.14159 volume = 4 / 3 * pi * raio ** 3 print('VOLUME = {:.3f}'.format(VOLUME))
# automatically generated by the FlatBuffers compiler, do not modify # namespace: proto class AuthMethod(object): ANONYMOUS = 0 COOKIE = 1 TLS = 2 TICKET = 3 CRA = 4 SCRAM = 5 CRYPTOSIGN = 6
class Authmethod(object): anonymous = 0 cookie = 1 tls = 2 ticket = 3 cra = 4 scram = 5 cryptosign = 6
def for_e(): for row in range(6): for col in range(4): if row==2 or row==1 and col%3!=0 or row==4 and col>0 or col==0 and row==3: print("*",end=" ") else: print(" ",end=" ") print() def while_e(): row=0 while row<6: ...
def for_e(): for row in range(6): for col in range(4): if row == 2 or (row == 1 and col % 3 != 0) or (row == 4 and col > 0) or (col == 0 and row == 3): print('*', end=' ') else: print(' ', end=' ') print() def while_e(): row = 0 while ...
def selection_sort(elements): for i in range(len(elements) - 1): min_index = i for j in range(i + 1, len(elements)): if elements[min_index] > elements[j]: min_index = j elements[i], elements[min_index] = elements[min_index], elements[i] return elements ele =...
def selection_sort(elements): for i in range(len(elements) - 1): min_index = i for j in range(i + 1, len(elements)): if elements[min_index] > elements[j]: min_index = j (elements[i], elements[min_index]) = (elements[min_index], elements[i]) return elements ele...
tab = 1 while tab <= 10: print("Tabuada do", tab, ":", end="\t") i = 1 while i <= 10: print(tab*i, end = "\t") i = i + 1 print() tab = tab + 1
tab = 1 while tab <= 10: print('Tabuada do', tab, ':', end='\t') i = 1 while i <= 10: print(tab * i, end='\t') i = i + 1 print() tab = tab + 1
def chk_p5m(n): if n%5==0: return 0 elif n==1: return n for i in range(2,n): if n%i==0: return n return 0 def fab(n): f=[0,1] return [chk_p5m((f:=[f[-1],f[-1]+f[-2]])[0]) for i in range(n)] #i know it's little confusing most won't understand... but tried to do somethin...
def chk_p5m(n): if n % 5 == 0: return 0 elif n == 1: return n for i in range(2, n): if n % i == 0: return n return 0 def fab(n): f = [0, 1] return [chk_p5m((f := [f[-1], f[-1] + f[-2]])[0]) for i in range(n)] print(*fab(int(input())))
class Solution: def largestValsFromLabels(self, values, labels, num_wanted, use_limit): zipped = list(zip(values, labels)) _dict = {x: 0 for x in set(labels)} ans = 0 for v, l in reversed(sorted(zipped)): if num_wanted == 0: return ans if _dic...
class Solution: def largest_vals_from_labels(self, values, labels, num_wanted, use_limit): zipped = list(zip(values, labels)) _dict = {x: 0 for x in set(labels)} ans = 0 for (v, l) in reversed(sorted(zipped)): if num_wanted == 0: return ans if...
class Human(): sum = 0 def __init__(self, name, age): self.name = name self.age = age def get_name(self): print(self.name) def do_homework(self): print('parent method')
class Human: sum = 0 def __init__(self, name, age): self.name = name self.age = age def get_name(self): print(self.name) def do_homework(self): print('parent method')
d = { "no": "yes" } class CustomError: def __init__(self, fun): self.fun = fun def __call__(self, *args, **kwargs): try: return self.fun(*args, **kwargs) except Exception as e: print(e) raise Exception(d.get(str(e))) @CustomError def a(): ...
d = {'no': 'yes'} class Customerror: def __init__(self, fun): self.fun = fun def __call__(self, *args, **kwargs): try: return self.fun(*args, **kwargs) except Exception as e: print(e) raise exception(d.get(str(e))) @CustomError def a(): raise e...
# Databricks notebook source # MAGIC %md # MAGIC <img src="https://github.com/billkellett/flight-school-resources/blob/master/images/databricks icon.png?raw=true" width=100/> # MAGIC <img src="/files/flight/Megacorp.png?raw=true" width=200/> # MAGIC # Democratizing MegaCorp's Data # MAGIC # MAGIC ## MegaCorp's current...
dbutils.widgets.text('team_name', "Enter your team's name") team_name = dbutils.widgets.get('team_name') setup_responses = dbutils.notebook.run('./includes/flight_school_assignment_1_setup', 0, {'team_name': team_name}).split() local_data_path = setup_responses[0] dbfs_data_path = setup_responses[1] database_name = set...
#Longest Collatz Sequence #Solving for Project Euler.Net Problem 14. #Given n -> n/2 (n is even) # n -> 3n + 1 (n is odd) # #Which starting number, under one million, produces the longest chain? # #By Alex Murshak def collatz(n): count = 0 while n>1: if n%2==0: n= n/2 else: ...
def collatz(n): count = 0 while n > 1: if n % 2 == 0: n = n / 2 else: n = 3 * n + 1 count += 1 return count c_large = 0 i_large = 0 for i in range(1, 1000000, 1): c = collatz(i) if C > C_large: c_large = C i_large = i print(I_large)
class Solution: def romanToInt(self, s: str) -> int: translations = { "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000 } number = 0 s = s.replace("IV", "IIII").replace("IX", "V...
class Solution: def roman_to_int(self, s: str) -> int: translations = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} number = 0 s = s.replace('IV', 'IIII').replace('IX', 'VIIII') s = s.replace('XL', 'XXXX').replace('XC', 'LXXXX') s = s.replace('CD', 'CCCC'...
budget = float(input()) price_1kg_flour = float(input()) colored_eggs = 0 price_1pack_eggs = price_1kg_flour * 0.75 price_250ml_milk = (price_1kg_flour + (price_1kg_flour * 0.25)) / 4 price_1_bread = price_1pack_eggs + price_1kg_flour + price_250ml_milk count_breads = int(budget // price_1_bread) for current_bread...
budget = float(input()) price_1kg_flour = float(input()) colored_eggs = 0 price_1pack_eggs = price_1kg_flour * 0.75 price_250ml_milk = (price_1kg_flour + price_1kg_flour * 0.25) / 4 price_1_bread = price_1pack_eggs + price_1kg_flour + price_250ml_milk count_breads = int(budget // price_1_bread) for current_bread in ran...
# O(n) time | O(h) space - where n is the number of nodes in the Binary Tree # and h is the height of the Binary Tree def nodeDepths(root, depth = 0): if root is None: return 0 return depth + nodeDepths(root.left, depth + 1) + nodeDepths(root.right, depth + 1) # This is the class of the input binary tree. clas...
def node_depths(root, depth=0): if root is None: return 0 return depth + node_depths(root.left, depth + 1) + node_depths(root.right, depth + 1) class Binarytree: def __init__(self, value): self.value = value self.left = None self.right = None
# Lesson 1 - Hello world and entry points # # All languages have an "entry point" # An entry point is where the program begins execution # "Main" is a common keyword used to specify the entry point # # Common C style entry points: # int main() # { # return 0; # } # or # void main() # { # } # Hello World is a common ...
def hello_world(): print('Hello World') if __name__ == '__main__': hello_world()
PASSWD = '12345' def password_required(func): def wrapper(): password = input('Cual es el passwd ? ') if password == PASSWD: return func() else: print('error') return wrapper def p_decorate(func): def func_wrapper(name): return "<p>{0}</p>".format(fu...
passwd = '12345' def password_required(func): def wrapper(): password = input('Cual es el passwd ? ') if password == PASSWD: return func() else: print('error') return wrapper def p_decorate(func): def func_wrapper(name): return '<p>{0}</p>'.format...
def euclid(n, m): if n > m: r = m m = n n = r r = m % n while r != 0: m = n n = r r = m % n return n
def euclid(n, m): if n > m: r = m m = n n = r r = m % n while r != 0: m = n n = r r = m % n return n
def bisection_search(arr: list, n: int) -> bool: mid = len(arr) // 2 if len(arr) < 2: if arr[mid] == n: return True else: return False else: if arr[mid] == n: return True else: return bisection_search(arr[:mid], n) if arr[mid] >...
def bisection_search(arr: list, n: int) -> bool: mid = len(arr) // 2 if len(arr) < 2: if arr[mid] == n: return True else: return False elif arr[mid] == n: return True else: return bisection_search(arr[:mid], n) if arr[mid] > n else bisection_search...
l1 = int(input('Digite o lado 1 ')) l2 = int(input('Digite o lado 2 ')) l3 = int(input('Digite o lado 3 ')) if l1+l2>l3 and l1+l3>l2 and l2+l3>l1: print(f'O triangulo PODE ser formado') else: print(f'O triangulo NAO PODE ser formado')
l1 = int(input('Digite o lado 1 ')) l2 = int(input('Digite o lado 2 ')) l3 = int(input('Digite o lado 3 ')) if l1 + l2 > l3 and l1 + l3 > l2 and (l2 + l3 > l1): print(f'O triangulo PODE ser formado') else: print(f'O triangulo NAO PODE ser formado')
''' 02 - Creating two-factor Let's continue looking at the student_data dataset of students in secondary school. Here, we want to answer the following question: does a student's first semester grade ("G1") tend to correlate with their final grade ("G3")? There are many aspects of a student's life that could ...
""" 02 - Creating two-factor Let's continue looking at the student_data dataset of students in secondary school. Here, we want to answer the following question: does a student's first semester grade ("G1") tend to correlate with their final grade ("G3")? There are many aspects of a student's life that could ...
# # PySNMP MIB module CISCO-VOICE-DNIS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VOICE-DNIS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:03:03 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, constraints_union, single_value_constraint, value_size_constraint, value_range_constraint) ...
# acronymsBuilder.py # A program to build acronyms from a phrase # by Tung Nguyen def main(): # declare program function: print("This program builds acronyms.") print() # prompt user to input the sentence: sentence = input("Enter a phrase: ") # split the sentence into a list that con...
def main(): print('This program builds acronyms.') print() sentence = input('Enter a phrase: ') list_word = sentence.split() acronym = '' for x in listWord: acronym += x[0].upper() print('The acronym is ' + acronym) main()
# x y x y #r1 = [[0, 0], [5, 5]] r1 = [[-5, -5], [-2, -2]] r2 = [[7, 1], [1, 8]] r3 = [[-1.2, 4], [3.7, 1.1]] def rect_intersection_area(r1, r2, r3): area = 0 r1_p1, r1_p2 = r1 r2_p1, r2_p2 = r2 r3_p1, r3_p2 = r3 right_x_p = 0 left_x_p = 0 top_y_p ...
r1 = [[-5, -5], [-2, -2]] r2 = [[7, 1], [1, 8]] r3 = [[-1.2, 4], [3.7, 1.1]] def rect_intersection_area(r1, r2, r3): area = 0 (r1_p1, r1_p2) = r1 (r2_p1, r2_p2) = r2 (r3_p1, r3_p2) = r3 right_x_p = 0 left_x_p = 0 top_y_p = 0 bottom_y_p = 0 left_x_p = max(min(r2_p1[0], r2_p2[0]), min...
# https://atcoder.jp/contests/abs/tasks/practice_1 def resolve(): a = int(input()) b, c = list(map(int, input().split())) d = input() print("{} {}".format(a + b + c, d))
def resolve(): a = int(input()) (b, c) = list(map(int, input().split())) d = input() print('{} {}'.format(a + b + c, d))
class IpConfiguration: options: object def __init__(self, options): self.options = options
class Ipconfiguration: options: object def __init__(self, options): self.options = options
#!/usr/bin/env python3 # Compares two lexicon files providing several stats # @author Cristian TG # @since 2021/04/15 # Please change the value of these variables: LEXICON_1 = 'lexicon1.txt' LEXICON_2 = 'lexicon2.txt' SHOW_DETAILS = True DISAMBIGUATION_SYMBOL = '#' #################################################...
lexicon_1 = 'lexicon1.txt' lexicon_2 = 'lexicon2.txt' show_details = True disambiguation_symbol = '#' def get_lexicon(lexicon, path): with open(path) as lexi: for line in lexi: aux = line.split('\t') lexicon[aux[0]] = aux[1].replace('\n', '').split(' ') return lexicon def get_w...
def three_word(a, b, c): title = a if title == '\"\"': title = "\'\'" else: title = "\'{0}\'".format(title) tag = b if tag == '\"\"': tag = "\'\'" else: tag = "\'{0}\'".format(tag) description = c if description == '\"\"': description = "\'\'" ...
def three_word(a, b, c): title = a if title == '""': title = "''" else: title = "'{0}'".format(title) tag = b if tag == '""': tag = "''" else: tag = "'{0}'".format(tag) description = c if description == '""': description = "''" else: de...
# [Skill] Cygnus Constellation (20899) echo = 10001005 cygnusConstellation = 1142597 cygnus = 1101000 if sm.canHold(cygnusConstellation): sm.setSpeakerID(cygnus) sm.sendNext("You have exceeded all our expectations. Please take this as a symbol of your heroism.\r\n" "#s" + str(echo) + "# #q" + str(echo) +...
echo = 10001005 cygnus_constellation = 1142597 cygnus = 1101000 if sm.canHold(cygnusConstellation): sm.setSpeakerID(cygnus) sm.sendNext('You have exceeded all our expectations. Please take this as a symbol of your heroism.\r\n#s' + str(echo) + '# #q' + str(echo) + '#\r\n#i' + str(cygnusConstellation) + '# #z' +...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: ans = str(int(self.combine(l1)) + int(self.combine(l2))) return self...
class Solution: def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode: ans = str(int(self.combine(l1)) + int(self.combine(l2))) return self.separate(ans, len(ans) - 1) def combine(self, lst): if lst.next: return self.combine(lst.next) + str(lst.val) else...
def http_exception(response): raise HTTPException(response) class HTTPException(Exception): def __init__(self, response): self._response = response def __str__(self): return self._response.message @property def is_redirect(self): return self._response.is_redirect @p...
def http_exception(response): raise http_exception(response) class Httpexception(Exception): def __init__(self, response): self._response = response def __str__(self): return self._response.message @property def is_redirect(self): return self._response.is_redirect @p...
coins = [ 100, 50, 25, 5, 1 ] total = 0 change = 130 for i in range(len(coins)): numCoins = change // coins[i] change -= numCoins * coins[i] total += numCoins print(total) ''' numCoins = 75 // 100 = 0 change = change - 0 * 100 change = change '''
coins = [100, 50, 25, 5, 1] total = 0 change = 130 for i in range(len(coins)): num_coins = change // coins[i] change -= numCoins * coins[i] total += numCoins print(total) '\nnumCoins = 75 // 100 = 0\nchange = change - 0 * 100\nchange = change \n'
#!/usr/bin/env python # -*- coding: utf-8 -*- DELIMITER = "\r\n" def encode(*args): "Pack a series of arguments into a value Redis command" result = [] result.append("*") result.append(str(len(args))) result.append(DELIMITER) for arg in args: result.append("$") result.append(st...
delimiter = '\r\n' def encode(*args): """Pack a series of arguments into a value Redis command""" result = [] result.append('*') result.append(str(len(args))) result.append(DELIMITER) for arg in args: result.append('$') result.append(str(len(arg))) result.append(DELIMITE...