content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
""" Stworz klase Ulamek reprezentujaca liczby ulamkowe. Kazdy obiekt typu Ulamek powinien miec dwa atrybuty: self.licznik oraz self.mianownik. Glownym celem zadania jest dorobienie imlementacji, dzieki ktorej mozliwe stanie sie dodawanie, mnozenie, dzielenie i odejmowanie od siebie dwoch obiektow ty...
""" Stworz klase Ulamek reprezentujaca liczby ulamkowe. Kazdy obiekt typu Ulamek powinien miec dwa atrybuty: self.licznik oraz self.mianownik. Glownym celem zadania jest dorobienie imlementacji, dzieki ktorej mozliwe stanie sie dodawanie, mnozenie, dzielenie i odejmowanie od siebie dwoch obiektow typu U...
''' You all have seen how to write loops in python. Now is the time to implement what you have learned. Given an array A of N numbers (integers), you have to write a program which prints the sum of the elements of array A with the corresponding elements of the reverse of array A. If array A has elements [1,2,3], then ...
""" You all have seen how to write loops in python. Now is the time to implement what you have learned. Given an array A of N numbers (integers), you have to write a program which prints the sum of the elements of array A with the corresponding elements of the reverse of array A. If array A has elements [1,2,3], then ...
# # PySNMP MIB module ELTEX-MES-IpRouter (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-MES-IpRouter # Produced by pysmi-0.3.4 at Mon Apr 29 18:47:07 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') (constraints_intersection, constraints_union, single_value_constraint, value_range_constraint, value_size_constraint) ...
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def __repr__(self): if self: return "{} -> {} -> {}".format(self.val,self.left, self.right) class Trim: def tr...
class Treenode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def __repr__(self): if self: return '{} -> {} -> {}'.format(self.val, self.left, self.right) class Trim: def trim_bst(self, root: TreeNode, low...
# The setup function is run once at the beginning def setup(): # Create a canvas of size 800 x 800 size(800, 500) # Set the background color to white background(255, 255, 255) # Color the shapes black fill(0) # No shape outline noStroke() # The draw function is run every frame of animat...
def setup(): size(800, 500) background(255, 255, 255) fill(0) no_stroke() def draw(): ellipse(mouseX, mouseY, 10, 10) def key_pressed(): if key == 'r': fill(255, 0, 0) elif key == 'g': fill(0, 255, 0) elif key == 'b': fill(0, 0, 255) elif key == 'c': ...
class Solution: def rotateTheBox(self, box: list[list[str]]) -> list[list[str]]: if len(box) == 0: return box rows = len(box) cols = len(box[0]) ROCK, OBSTACLE, EMPTY = '#', '*', '.' for row in box: nearest_obstacle = cols for index, cell...
class Solution: def rotate_the_box(self, box: list[list[str]]) -> list[list[str]]: if len(box) == 0: return box rows = len(box) cols = len(box[0]) (rock, obstacle, empty) = ('#', '*', '.') for row in box: nearest_obstacle = cols for (index...
""" Module version ============== Just the version of the ASE2SPRKKR package. """ #: Version number of the ASE2SPRKKR package __version__ = "1.0.5"
""" Module version ============== Just the version of the ASE2SPRKKR package. """ __version__ = '1.0.5'
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any lat...
class Group(object): """ a group of ansible hosts """ __slots__ = ['name', 'hosts', 'vars', 'child_groups', 'parent_groups', 'depth'] def __init__(self, name=None): self.depth = 0 self.name = name self.hosts = [] self.vars = {} self.child_groups = [] self.par...
def test_counter_ip_dscp(api, b2b_raw_config, utils): """ Configure a raw IPv4 flow with, - all Dscp values Validate, - Fetch the IPv4 header config via restpy and validate against expected """ f = b2b_raw_config.flows[0] f.packet.ethernet().ipv4() ipv4 = f.packet[1] phb =...
def test_counter_ip_dscp(api, b2b_raw_config, utils): """ Configure a raw IPv4 flow with, - all Dscp values Validate, - Fetch the IPv4 header config via restpy and validate against expected """ f = b2b_raw_config.flows[0] f.packet.ethernet().ipv4() ipv4 = f.packet[1] phb =...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"ls": "01_utils.ipynb", "Path.ls": "00_dup_finder.ipynb", "Path.lf": "00_dup_finder.ipynb", "Path.ld": "00_dup_finder.ipynb", "ls_print": "01_utils.ipynb"} modules = ["dup...
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'ls': '01_utils.ipynb', 'Path.ls': '00_dup_finder.ipynb', 'Path.lf': '00_dup_finder.ipynb', 'Path.ld': '00_dup_finder.ipynb', 'ls_print': '01_utils.ipynb'} modules = ['dup_finder.py', 'utils.py'] doc_url = 'https://ayasyrev.github.io/dup_finder/' gi...
def tsearch (l, r, f): while (r-l > 0.01): # precision en x m1 = (r+2*l)/3 m2 = (2*r+l)/3 if f(m1)>f(m2): # maximo r = m2 else: l = m1 return l def bsearch (l, r, v, f): while (r-l > 0.01): # precision en x med = (l+r)/2 ...
def tsearch(l, r, f): while r - l > 0.01: m1 = (r + 2 * l) / 3 m2 = (2 * r + l) / 3 if f(m1) > f(m2): r = m2 else: l = m1 return l def bsearch(l, r, v, f): while r - l > 0.01: med = (l + r) / 2 if f(med, v): r = med ...
def print_birthdays(people): """print names of people in birthdays dictionary The birthdays dictionary contains names as keys and birthdays as values. When the function is invoked, it returns the names of the people in the dictionary built in the program :return: None :rtype: Boolean """ ...
def print_birthdays(people): """print names of people in birthdays dictionary The birthdays dictionary contains names as keys and birthdays as values. When the function is invoked, it returns the names of the people in the dictionary built in the program :return: None :rtype: Boolean """ ...
class Solution: def XXX(self, root: TreeNode) -> int: if root is None: return 0 st = list() res = 0 while st or root: while root: st.append(root) root = root.left if root.left else root.right res = max(res, len(st)) ...
class Solution: def xxx(self, root: TreeNode) -> int: if root is None: return 0 st = list() res = 0 while st or root: while root: st.append(root) root = root.left if root.left else root.right res = max(res, len(st))...
#!/usr/bin/env python3 num_inputs = 16 print(f""" -------------------------------------------------------------------------------- -- Block: avg{num_inputs} -- Description: -- This block implements a big adder with {num_inputs} inputs. -- There are several add stages to improve timing. -- ----------------------------...
num_inputs = 16 print(f'\n--------------------------------------------------------------------------------\n-- Block: avg{num_inputs}\n-- Description:\n-- This block implements a big adder with {num_inputs} inputs.\n-- There are several add stages to improve timing.\n--\n------------------------------------------------...
class Solution: def calculate(self, s: str) -> int: res, num, sign, stack = 0, 0, 1, [] for c in s: if c.isdigit(): num = 10 * num + int(c) elif c == "+" or c == "-": res += sign * num num = 0 sign = 1 if c == "+...
class Solution: def calculate(self, s: str) -> int: (res, num, sign, stack) = (0, 0, 1, []) for c in s: if c.isdigit(): num = 10 * num + int(c) elif c == '+' or c == '-': res += sign * num num = 0 sign = 1 if c ...
class BadHTTPResponse(Exception): def __init__(self, code): msg = f"The bridge returned HTTP response code {code}" class BadResponse(Exception): def __init__(self, text): msg= f"The bridge returned an unrecognized response {text}" class InvalidColorSpec(Exception): def __init__(self, colorspec): msg = "Inval...
class Badhttpresponse(Exception): def __init__(self, code): msg = f'The bridge returned HTTP response code {code}' class Badresponse(Exception): def __init__(self, text): msg = f'The bridge returned an unrecognized response {text}' class Invalidcolorspec(Exception): def __init__(self, c...
def add_zeros(element): """This changes the format of postcodes to string with the needed zeros Args: element: individual row from apply codes Returns: parameter postcode value with zeros """ #postinumeroihin etunollat jos on ollut integer elem...
def add_zeros(element): """This changes the format of postcodes to string with the needed zeros Args: element: individual row from apply codes Returns: parameter postcode value with zeros """ element = str(element) if len(element) == 3: element = '00' + elem...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: de...
class Solution: def is_sub_path(self, head: ListNode, root: TreeNode) -> bool: def check(root, head): if head is None: return True if root is None: return False if root.val != head.val: return False return chec...
class BaseExporter(object): """ The base class of all exporters. """ def __init__(self, document): self.document = document def export(self): raise NotImplementedError def as_text(self): return "\n".join(list(self.export())) class ExporterError(Exception): pass
class Baseexporter(object): """ The base class of all exporters. """ def __init__(self, document): self.document = document def export(self): raise NotImplementedError def as_text(self): return '\n'.join(list(self.export())) class Exportererror(Exception): pass
task = {i + 1: 0 for i in range(12)} for i in range(int(input())): task[int(input())] += 1 for i in sorted(filter(lambda key: task[key] != 0, task)): print(i, task[i])
task = {i + 1: 0 for i in range(12)} for i in range(int(input())): task[int(input())] += 1 for i in sorted(filter(lambda key: task[key] != 0, task)): print(i, task[i])
def remote_field(field): # remote_field is new in Django 1.9 return field.remote_field if hasattr(field, 'remote_field') else getattr(field, 'rel', None) def remote_model(field): # remote_field is new in Django 1.9 return field.remote_field.model if hasattr(field, 'remote_field') else field.rel.to d...
def remote_field(field): return field.remote_field if hasattr(field, 'remote_field') else getattr(field, 'rel', None) def remote_model(field): return field.remote_field.model if hasattr(field, 'remote_field') else field.rel.to def cached_field_value(instance, attr): try: field = instance._meta.get...
def f(): i: i32 i = 4 print(i // 0) f()
def f(): i: i32 i = 4 print(i // 0) f()
MAX = 1000000 def breakSum(n): dp = [0] * (n + 1) dp[0] = 0 dp[1] = 1 for i in range(2, n + 1): dp[i] = max(dp[int(i / 2)] + dp[int(i / 3)] + dp[int(i / 4)], i); return dp[n] n = 24 print(breakSum(n))
max = 1000000 def break_sum(n): dp = [0] * (n + 1) dp[0] = 0 dp[1] = 1 for i in range(2, n + 1): dp[i] = max(dp[int(i / 2)] + dp[int(i / 3)] + dp[int(i / 4)], i) return dp[n] n = 24 print(break_sum(n))
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: dictIndex = {} for i in range(len(nums)): n = target - nums[i] if n in dictIndex: return [dictIndex[n], i] dictIndex[nums[i]] = i return [-1, -1]
class Solution: def two_sum(self, nums: List[int], target: int) -> List[int]: dict_index = {} for i in range(len(nums)): n = target - nums[i] if n in dictIndex: return [dictIndex[n], i] dictIndex[nums[i]] = i return [-1, -1]
"""comprehensions - do more with less!""" print("===== Intermediate =====") nested = [ [x * y for y in range(1, 11)] for x in range(1, 11) ] print("nested:", nested) multiple_ifs = [ f"{char}{num}" for char in "AbCDe" for num in range(26) if char.isupper() if not num % 5 ] print("multiple_ifs:", m...
"""comprehensions - do more with less!""" print('===== Intermediate =====') nested = [[x * y for y in range(1, 11)] for x in range(1, 11)] print('nested:', nested) multiple_ifs = [f'{char}{num}' for char in 'AbCDe' for num in range(26) if char.isupper() if not num % 5] print('multiple_ifs:', multiple_ifs) inline_if = {...
class Solution: # 1st brute-froce solution # def maxProfit(self, prices: List[int]) -> int: # d = len(prices) # lst = [0] # for i in range(d): # for j in range(i + 1, d): # profit = prices[j] - prices[i] # if profit > 0: # l...
class Solution: def max_profit(self, prices: List[int]) -> int: low = prices[0] max_profit = 0 for price in prices: if price < low: low = price if price - low > maxProfit: max_profit = price - low return maxProfit
# String # Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. # # Each letter in the magazine string can only be used once in your ransom n...
class Solution: def can_construct(self, ransomNote, magazine): """ :type ransomNote: str :type magazine: str :rtype: bool """ mag_list = list(magazine) for x in ransomNote: if x in magList: magList.remove(x) else: ...
#Integers Come In All Sizes #https://www.hackerrank.com/challenges/python-integers-come-in-all-sizes/problem a = int(input()) b = int(input()) c = int(input()) d = int(input()) print(a**b + c**d)
a = int(input()) b = int(input()) c = int(input()) d = int(input()) print(a ** b + c ** d)
class Dummy: """ Implements a dummy class that is completely inert. """ def __init__(self, *args, **kwargs): pass def __getattr__(self, item): return self.dummy_function def __setattr__(self, key, value): pass def dummy_function(*args, **kwargs): pass
class Dummy: """ Implements a dummy class that is completely inert. """ def __init__(self, *args, **kwargs): pass def __getattr__(self, item): return self.dummy_function def __setattr__(self, key, value): pass def dummy_function(*args, **kwargs): pass
############################# # www.adventofcode.com/2021 # # Challenge: Day 4 # ############################# def main_01(): with open('input_demo.txt', 'r') as f: data = f.read().splitlines() # Get the bingo numbers from the input and convert them to integers bingoNumbers = data[0].spli...
def main_01(): with open('input_demo.txt', 'r') as f: data = f.read().splitlines() bingo_numbers = data[0].split(',') bingo_numbers = [int(x) for x in bingoNumbers] del data[0] data = [x.split() for x in data] bingo_boards = data[:] delete = [] for i in range(len(bingoBoards)): ...
L=[] for i in range(1,9): L.append((i,int(input()))) L=sorted(sorted(L,key=lambda x:x[1],reverse=True)[:5],key=lambda x:x[0]) print(sum(i[1] for i in L)) for i in L: print(i[0],end=' ')
l = [] for i in range(1, 9): L.append((i, int(input()))) l = sorted(sorted(L, key=lambda x: x[1], reverse=True)[:5], key=lambda x: x[0]) print(sum((i[1] for i in L))) for i in L: print(i[0], end=' ')
# # PySNMP MIB module ELTEX-TAU8 (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-TAU8 # Produced by pysmi-0.3.4 at Wed May 1 13:02:27 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, constraints_union, single_value_constraint, value_size_constraint, value_range_constraint) ...
class DatabaseConfig: def __init__(self, driver: str = None, host: str = None, database: str = None, username: str = None, password: str = None, ): self.driver = driver self.host = host self...
class Databaseconfig: def __init__(self, driver: str=None, host: str=None, database: str=None, username: str=None, password: str=None): self.driver = driver self.host = host self.database = database self.username = username self.password = password
names = ['wangfan','wagfan1','wangfan2'] for name in names: print(name) for value in range(1,5): print(value) numbers = list(range(1,6)) print(numbers) even_number = list(range(2,11,2)) print(even_number) squers = [] for value in range(1,11): squers.append(value ** 2) print(squers) print(min(squers)) ...
names = ['wangfan', 'wagfan1', 'wangfan2'] for name in names: print(name) for value in range(1, 5): print(value) numbers = list(range(1, 6)) print(numbers) even_number = list(range(2, 11, 2)) print(even_number) squers = [] for value in range(1, 11): squers.append(value ** 2) print(squers) print(min(squers))...
class CalibrationProcess: def __init__(self, calibrator_factory): if calibrator_factory is None: raise TypeError('calibrator_factory') self._calibrator_factory = calibrator_factory def calibrate(self): calibrate_another = True while calibrate_another: while True: ready = input('Is the device conne...
class Calibrationprocess: def __init__(self, calibrator_factory): if calibrator_factory is None: raise type_error('calibrator_factory') self._calibrator_factory = calibrator_factory def calibrate(self): calibrate_another = True while calibrate_another: w...
level = 3 name = 'Soreang' capital = 'Soreang' area = 25.51
level = 3 name = 'Soreang' capital = 'Soreang' area = 25.51
class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: # https://leetcode.com/problems/max-consecutive-ones/ maxLength = 0 curLength = 0 for n in nums: if n == 1: curLength = curLength + 1 else: ...
class Solution: def find_max_consecutive_ones(self, nums: List[int]) -> int: max_length = 0 cur_length = 0 for n in nums: if n == 1: cur_length = curLength + 1 else: cur_length = 0 max_length = max(curLength, maxLength) ...
def get_book_by_osis_id(id): """ Retrieves book meta data :param id: the osis book id :return: """ sort = find_key(id, osis_ids) return get_book_by_sort(sort) def get_book_by_sort(sort): """ Retrieves book metadata :param sort: the sort order of the book to look up :return: ...
def get_book_by_osis_id(id): """ Retrieves book meta data :param id: the osis book id :return: """ sort = find_key(id, osis_ids) return get_book_by_sort(sort) def get_book_by_sort(sort): """ Retrieves book metadata :param sort: the sort order of the book to look up :return: ...
try: age = int(input("Enter your age: ")) if (age > -1 and age < 101): if (age >= 18): print("Eligible for voting!") else: print("Not Eligible for Voting") else: print("Invalid Age!") except: print("You've entered invalid age") ...
try: age = int(input('Enter your age: ')) if age > -1 and age < 101: if age >= 18: print('Eligible for voting!') else: print('Not Eligible for Voting') else: print('Invalid Age!') except: print("You've entered invalid age")
# pysam versioning information __version__ = "0.16.0.1" __samtools_version__ = "1.10" __bcftools_version__ = "1.10.2" __htslib_version__ = "1.10.2"
__version__ = '0.16.0.1' __samtools_version__ = '1.10' __bcftools_version__ = '1.10.2' __htslib_version__ = '1.10.2'
load("@rules_python//python:defs.bzl", "py_binary", "py_library") def envoy_py_test(name, package, visibility, envoy_prefix = "@envoy"): filepath = "$(location %s//tools/testing:base_pytest_runner.py)" % envoy_prefix output = "$(@D)/pytest_%s.py" % name native.genrule( name = "generate_pytest_" + ...
load('@rules_python//python:defs.bzl', 'py_binary', 'py_library') def envoy_py_test(name, package, visibility, envoy_prefix='@envoy'): filepath = '$(location %s//tools/testing:base_pytest_runner.py)' % envoy_prefix output = '$(@D)/pytest_%s.py' % name native.genrule(name='generate_pytest_' + name, cmd='sed...
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/lzh/racecar_ws/src/lslidar_ws/src/lslidar_c16/lslidar_c16_msgs/msg/LslidarC16Layer.msg;/home/lzh/racecar_ws/src/lslidar_ws/src/lslidar_c16/lslidar_c16_msgs/msg/LslidarC16Packet.msg;/home/lzh/racecar_ws/src/lslidar_ws/src/lslidar_c16/lslidar_c16_...
messages_str = '/home/lzh/racecar_ws/src/lslidar_ws/src/lslidar_c16/lslidar_c16_msgs/msg/LslidarC16Layer.msg;/home/lzh/racecar_ws/src/lslidar_ws/src/lslidar_c16/lslidar_c16_msgs/msg/LslidarC16Packet.msg;/home/lzh/racecar_ws/src/lslidar_ws/src/lslidar_c16/lslidar_c16_msgs/msg/LslidarC16Point.msg;/home/lzh/racecar_ws/src...
""" Example .csv file contents that should be parsable as a mapping, or should fail Used in test_mapping. """ BASIC_MAPPING = r""" ## DESCRIPTION ##,,, some comment by some person,,, ,,,, ## OPTIONS ##,,, destination_path,\\someserver\share\folder1,, pims_key,555,, ## MAPPING ##,,, source,patient_id,patient_name,descr...
""" Example .csv file contents that should be parsable as a mapping, or should fail Used in test_mapping. """ basic_mapping = '\n## DESCRIPTION ##,,,\nsome comment by some person,,,\n,,,,\n## OPTIONS ##,,,\ndestination_path,\\\\someserver\\share\\folder1,,\npims_key,555,,\n## MAPPING ##,,,\nsource,patient_id,patient_na...
# __init__.py/Open GoPro, Version 2.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro). # This copyright was auto-generated on Wed, Sep 1, 2021 5:05:55 PM # Open GoPro API Versions to test versions = ["1.0", "2.0"] # Cameras to test. This assumes that a camera with the given name is advertising. # TODO m...
versions = ['1.0', '2.0'] cameras = {'HERO9': 'GoPro 0456', 'HERO10': 'GoPro 0480'}
class ResponseQueue: RESULT_SUCCESS = "success" RESULT_FAILURE = "failure" RESULT_CANCEL = "canceled" CANCEL_RESULT_CANCELLING = "cancelling" CANCEL_RESULT_FAILURE = RESULT_FAILURE CANCEL_RESULT_FINISHED = "finished" def __init__(self, queue): self.queue = queue def ack(self, ...
class Responsequeue: result_success = 'success' result_failure = 'failure' result_cancel = 'canceled' cancel_result_cancelling = 'cancelling' cancel_result_failure = RESULT_FAILURE cancel_result_finished = 'finished' def __init__(self, queue): self.queue = queue def ack(self, p...
#coding: utf-8 BASE = '' routes_in = ( (BASE + '/index', BASE + '/kolaborativa/default/index'), (BASE + '/principal', BASE + '/kolaborativa/default/principal'), (BASE + '/user/$anything', BASE + '/kolaborativa/default/user/$anything'), (BASE + '/user_info/$anything', BASE + '/kolaborativa/default/user_...
base = '' routes_in = ((BASE + '/index', BASE + '/kolaborativa/default/index'), (BASE + '/principal', BASE + '/kolaborativa/default/principal'), (BASE + '/user/$anything', BASE + '/kolaborativa/default/user/$anything'), (BASE + '/user_info/$anything', BASE + '/kolaborativa/default/user_info/$anything'), (BASE + '/proje...
x = int(input()) y = int(input()) range_xy = range(x+1, y) if (x > y): range_xy = range(y+1, x) sum_xy = 0 for i in range_xy: if i % 2 != 0: sum_xy = sum_xy + i print(sum_xy)
x = int(input()) y = int(input()) range_xy = range(x + 1, y) if x > y: range_xy = range(y + 1, x) sum_xy = 0 for i in range_xy: if i % 2 != 0: sum_xy = sum_xy + i print(sum_xy)
"""Types used in configuration module for Spark's performance tests.""" class OptionSet(object): """Represents an option and a set of values for it to sweep over.""" def __init__(self, name, vals, can_scale=False): self.name = name self.vals = vals self.can_scale = can_scale def sc...
"""Types used in configuration module for Spark's performance tests.""" class Optionset(object): """Represents an option and a set of values for it to sweep over.""" def __init__(self, name, vals, can_scale=False): self.name = name self.vals = vals self.can_scale = can_scale def s...
'''input 5 3 10000 9000 48000 2 3 10000 9000 20000 ''' # -*- coding: utf-8 -*- # AtCoder Beginner Contest # Problem A if __name__ == '__main__': n = int(input()) k = int(input()) x = int(input()) y = int(input()) diff = n - k if diff > 0: print((k * x) + diff * y) else: ...
"""input 5 3 10000 9000 48000 2 3 10000 9000 20000 """ if __name__ == '__main__': n = int(input()) k = int(input()) x = int(input()) y = int(input()) diff = n - k if diff > 0: print(k * x + diff * y) else: print(n * x)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): # p.left = parent.right # parent.right = p.right # p.right = parent # parent = p.left # p = left def ...
class Solution(object): def upside_down_binary_tree(self, root): """ :type root: TreeNode :rtype: TreeNode """ (node, parent, parent_right) = (root, None, None) while node is not None: left = node.left node.left = parentRight paren...
def intInput(prompt,default): try: return int(input(prompt)) except: return default age = intInput("How old is your car? ",0) print("Your car is",age,"years old")
def int_input(prompt, default): try: return int(input(prompt)) except: return default age = int_input('How old is your car? ', 0) print('Your car is', age, 'years old')
class Employee: raise_amount = 1.04 num_of_emps = 0 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' Employee.num_of_emps += 1 def fullname(self): return "{} {}".for...
class Employee: raise_amount = 1.04 num_of_emps = 0 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' Employee.num_of_emps += 1 def fullname(self): return '{} {}'.for...
def solve_part_1(sequence): sequence = sequence.split("\t") historic = [sequence[:]] block_redistribution = 0 sequence_size = len(sequence) for i in range(sequence_size): sequence[i] = int(sequence[i]) while True: maximum = -1 index = -1 for i in range(seque...
def solve_part_1(sequence): sequence = sequence.split('\t') historic = [sequence[:]] block_redistribution = 0 sequence_size = len(sequence) for i in range(sequence_size): sequence[i] = int(sequence[i]) while True: maximum = -1 index = -1 for i in range(sequence_si...
# Instruction: Replace the character H with a J. txt = "Hello World" # Solution: txt = txt.replace("H", "J") print(txt) # Read More Here: https://www.w3schools.com/python/python_strings.asp
txt = 'Hello World' txt = txt.replace('H', 'J') print(txt)
#!/usr/bin/env python3 """ A Befunge-93 interpreter written in Python. Spec can be found at https://en.wikipedia.org/wiki/Befunge. """ class Pointer: def __init__(self): self.x = 0 self.y = 0
""" A Befunge-93 interpreter written in Python. Spec can be found at https://en.wikipedia.org/wiki/Befunge. """ class Pointer: def __init__(self): self.x = 0 self.y = 0
# q1 def select_second(L): """Return the second element of the given list. If the list has no second element, return None. """ if len(L) < 2: return None return L[1] # q2 def losing_team_captain(teams): """Given a list of teams, where each team is a list of names, return the 2nd player ...
def select_second(L): """Return the second element of the given list. If the list has no second element, return None. """ if len(L) < 2: return None return L[1] def losing_team_captain(teams): """Given a list of teams, where each team is a list of names, return the 2nd player (captain) ...
N, M = map(int, input().split()) P = [] for _ in range(N): a, b = map(int, input().split()) P.append((a, b)) P2 = [] for _ in range(M): a, b = map(int, input().split()) P2.append((a, b)) for i, (x, y) in enumerate(P): dis = 1e10 ans = 1 for j, (x2, y2) in enumerate(P2): new_dis = ab...
(n, m) = map(int, input().split()) p = [] for _ in range(N): (a, b) = map(int, input().split()) P.append((a, b)) p2 = [] for _ in range(M): (a, b) = map(int, input().split()) P2.append((a, b)) for (i, (x, y)) in enumerate(P): dis = 10000000000.0 ans = 1 for (j, (x2, y2)) in enumerate(P2): ...
"""The code template to supply to the front end. This is what the user will be asked to complete and submit for grading. Do not include any imports. This is not a REPL environment so include explicit 'print' statements for any outputs you want to be displayed back to the user. Use triple single q...
"""The code template to supply to the front end. This is what the user will be asked to complete and submit for grading. Do not include any imports. This is not a REPL environment so include explicit 'print' statements for any outputs you want to be displayed back to the user. Use triple single q...
class NoTokenError(Exception): def __init__(self, *a, **kw): super().__init__(*a, **kw) class GetContentError(Exception): def __init__(self, *a, **kw): super().__init__(*a, **kw)
class Notokenerror(Exception): def __init__(self, *a, **kw): super().__init__(*a, **kw) class Getcontenterror(Exception): def __init__(self, *a, **kw): super().__init__(*a, **kw)
class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: n = len(nums) res = [1] * (n) fwd = [1] * (n) bwd = [1] * (n) fwd[0] = 1 bwd[n-1] = 1 for i in range(1,n): fwd[i] = fwd[i-1] * nums[i-1] for i in range(n-2,...
class Solution: def product_except_self(self, nums: List[int]) -> List[int]: n = len(nums) res = [1] * n fwd = [1] * n bwd = [1] * n fwd[0] = 1 bwd[n - 1] = 1 for i in range(1, n): fwd[i] = fwd[i - 1] * nums[i - 1] for i in range(n - 2, -1...
1 1_0 -1 0x1 0xff 0xf_f 0o123 0o12_3 10j 1_0j 1-2j
1 10 -1 1 255 255 83 83 10j 10j 1 - 2j
""" 538. Convert BST to Greater Tree Input: The root of a Binary Search Tree like this: 5 / \ 2 13 Output: The root of a Greater Tree like this: 18 / \ 20 13 """ """" 5 / \ 2 13 r = ...
""" 538. Convert BST to Greater Tree Input: The root of a Binary Search Tree like this: 5 / 2 13 Output: The root of a Greater Tree like this: 18 / 20 13 """ '"\n 5 \n / \\ \n 2 13 r = 16, node 13, \n / ...
"""A bcftools modules. Author: Shujia Huang Date: 2020-04-28 20:29:09 """ def concat(config, input_vcfs, output_vcf): tabix = config["tabix"] bcftools = config["bcftools"]["bcftools"] concat_options = "%s" % " ".join(config["bcftools"]["concat_options"]).replace("-O z", "") \ if "concat_options"...
"""A bcftools modules. Author: Shujia Huang Date: 2020-04-28 20:29:09 """ def concat(config, input_vcfs, output_vcf): tabix = config['tabix'] bcftools = config['bcftools']['bcftools'] concat_options = '%s' % ' '.join(config['bcftools']['concat_options']).replace('-O z', '') if 'concat_options' in config['...
class Solution: def maxSubArray(self, nums): sm, mn, mx = 0, 0, -float("inf") for num in nums: sm += num mx, mn = max(mx, sm - mn), min(mn, sm) return mx
class Solution: def max_sub_array(self, nums): (sm, mn, mx) = (0, 0, -float('inf')) for num in nums: sm += num (mx, mn) = (max(mx, sm - mn), min(mn, sm)) return mx
# expr # : AWAIT? atom trailer* # | <assoc=right> expr op=POWER expr # | op=(ADD | MINUS | NOT_OP) expr # | expr op=(STAR | DIV | MOD | IDIV | AT) expr # | expr op=(ADD | MINUS) expr # | expr op=(LEFT_SHIFT | RIGHT_SHIFT) expr # | expr op=AND_OP expr # | expr op=XOR expr # | expr op=...
"""123""" await 5 '1231'.lower() '1231'.lower().upper() await '1231'.lower().upper() 2 ** 2 ** 3 +6 -6 ~6 6 * 7 6 / 7 6 % 8 6 // 7 6 @ 2 6 + 1 7 - 9 8 << 9 4 >> 1 4 & 6 4 ^ 7 7 | 1
LOCS__ABCDE = list('abcde') LOCS__A_TO_Z = list('abcdefghijklmnopqrstuvwxyz') SRCS_TGTS__ONE_SHOT__ABCDE = [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')] SRCS_TGTS__FORWARD_BACK__ABCDE = [ ('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'c'), ('c', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e') ]
locs__abcde = list('abcde') locs__a_to_z = list('abcdefghijklmnopqrstuvwxyz') srcs_tgts__one_shot__abcde = [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')] srcs_tgts__forward_back__abcde = [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'c'), ('c', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')]
def interpret(data, soc): '''takes foot movements and converts to chess moves''' row = '' column = '' if len(data) != 2 and len(data) != 4: print("ERROR: command len is " + str(len(data))) soc.send(bytes("FF", encoding='utf8')) return -1 column = data[0] row = str(ord(d...
def interpret(data, soc): """takes foot movements and converts to chess moves""" row = '' column = '' if len(data) != 2 and len(data) != 4: print('ERROR: command len is ' + str(len(data))) soc.send(bytes('FF', encoding='utf8')) return -1 column = data[0] row = str(ord(dat...
#!/usr/bin/env python3 # --- general ------------------------------------------------------------------ project = "Ethereum Classic Technical Reference" author = "Christian Seberino" copyright = "2018 " + author version = "0.1" release = version master_doc = "index" source_suffix = ".r...
project = 'Ethereum Classic Technical Reference' author = 'Christian Seberino' copyright = '2018 ' + author version = '0.1' release = version master_doc = 'index' source_suffix = '.rst' extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx....
# # PySNMP MIB module NSC-TCP-EXCEL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NSC-TCP-EXCEL-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:15:20 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, value_size_constraint, constraints_intersection, constraints_union) ...
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate...
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthres...
withdraw,balance = map(float,input().split()) #withdraw,balance = [float(item) for item in read] if (withdraw%5 != 0) : print (balance) elif (balance < withdraw +0.5) : print (balance) else : print(balance-(withdraw+0.5))
(withdraw, balance) = map(float, input().split()) if withdraw % 5 != 0: print(balance) elif balance < withdraw + 0.5: print(balance) else: print(balance - (withdraw + 0.5))
""" let's reset the array by it's min value start out from (0,0) in another words, after reset grid[i][j]'s value will be the min value start out from (0,0) if we are at (i,j), we will be either from (i-1,j) or (i,j-1) we call them s1 and s2, let's assume they are both in range grid[i][j] will be grid[i][j]+min(s1, s2...
""" let's reset the array by it's min value start out from (0,0) in another words, after reset grid[i][j]'s value will be the min value start out from (0,0) if we are at (i,j), we will be either from (i-1,j) or (i,j-1) we call them s1 and s2, let's assume they are both in range grid[i][j] will be grid[i][j]+min(s1, s2...
s1=input() s2=input() s3=input() print(s1+s2+s3) print(s2+s3+s1) print(s3+s1+s2) print('%s%s%s'%(s1[:10], s2[:10], s3[:10]))
s1 = input() s2 = input() s3 = input() print(s1 + s2 + s3) print(s2 + s3 + s1) print(s3 + s1 + s2) print('%s%s%s' % (s1[:10], s2[:10], s3[:10]))
class Board: def __init__(self, settings): self.number_of_players = settings.number_of_players self.number_to_pass = settings.number_to_pass self.missions = settings.missions self.spy_score = 0 self.antifa_score = 0 self.current_mission = 0 self.stall_counte...
class Board: def __init__(self, settings): self.number_of_players = settings.number_of_players self.number_to_pass = settings.number_to_pass self.missions = settings.missions self.spy_score = 0 self.antifa_score = 0 self.current_mission = 0 self.stall_counter...
# Copyright 2018-present Open Networking Foundation # SPDX-License-Identifier: Apache-2.0 # This Starlark rule imports the BF SDE shared libraries and headers. The # SDE_INSTALL environment variable needs to be set, otherwise the Stratum # rules for barefoot platforms cannot be built. def _impl(repository_ctx): i...
def _impl(repository_ctx): if 'SDE_INSTALL' not in repository_ctx.os.environ: repository_ctx.file('BUILD', '') return bf_sde_path = repository_ctx.os.environ['SDE_INSTALL'] repository_ctx.symlink(bf_sde_path, 'barefoot-bin') repository_ctx.symlink(label('@//bazel:external/bfsde.BUILD'), ...
MOCK_SALE = [{ "id": 1, "title": "Demix Magus M", "description": "Lightweight and flexible Demix Magus training sneakers. Special grooves on the sole, located in places of the anatomical fold of the foot, allow you to move naturally. Ultra-lightweight knitwear with a special weave provides air circulation a...
mock_sale = [{'id': 1, 'title': 'Demix Magus M', 'description': 'Lightweight and flexible Demix Magus training sneakers. Special grooves on the sole, located in places of the anatomical fold of the foot, allow you to move naturally. Ultra-lightweight knitwear with a special weave provides air circulation and also effec...
#!/usr/bin/env python #_*_coding:utf-8_*_ __all__ = [ 'readCode', 'saveCluster', 'kmeans', 'hcluster', 'apc', 'meanshift', 'dbscan', 'tsne', 'pca' ]
__all__ = ['readCode', 'saveCluster', 'kmeans', 'hcluster', 'apc', 'meanshift', 'dbscan', 'tsne', 'pca']
# tombstone __author__ = "N. Laughton" __copyright__ = "Copyright 2018, N. Laughton" __credits__ = ["N. Laughton"] __license__ = "MIT" __version__ = "0.1.0dev" __maintainer__ = "N. Laughton" __status__ = "development"
__author__ = 'N. Laughton' __copyright__ = 'Copyright 2018, N. Laughton' __credits__ = ['N. Laughton'] __license__ = 'MIT' __version__ = '0.1.0dev' __maintainer__ = 'N. Laughton' __status__ = 'development'
lista= [] for x in range (5): lista.append(input("Ingrese un numero")) menor=lista[0] posicion_x=0 for x in range(1,5): if lista[x] < menor: menor= lista[x] posicion_x= x print("El valor es: ", menor, " y la posicion es: ", posicion_x)
lista = [] for x in range(5): lista.append(input('Ingrese un numero')) menor = lista[0] posicion_x = 0 for x in range(1, 5): if lista[x] < menor: menor = lista[x] posicion_x = x print('El valor es: ', menor, ' y la posicion es: ', posicion_x)
# This file is intended to be used with the HDLMAKE tool for HDL generator. If # you don't use it, please ignore files = [ "ahb3lite_to_wb.v", "wb_to_ahb3lite.v", ]
files = ['ahb3lite_to_wb.v', 'wb_to_ahb3lite.v']
""" Good morning! Here's your coding interview problem for today. This problem was asked by Facebook. There is an N by M matrix of zeroes. Given N and M, write a function to count the number of ways of starting at the top-left corner and getting to the bottom-right corner. You can only move right or down. For exampl...
""" Good morning! Here's your coding interview problem for today. This problem was asked by Facebook. There is an N by M matrix of zeroes. Given N and M, write a function to count the number of ways of starting at the top-left corner and getting to the bottom-right corner. You can only move right or down. For exampl...
""" Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? Extras: If the number is a multiple of 4, print out a different message. Ask the user for two numbers: one number to ...
""" Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? Extras: If the number is a multiple of 4, print out a different message. Ask the user for two numbers: one number to ...
class _NFA: pass class NFA(_NFA): STATE_ID = -1 def __init__(self, final_states=None, name=""): if final_states is None: final_states = set() NFA.STATE_ID += 1 self.id = NFA.STATE_ID self.final_states = final_states self.transitions = {} self....
class _Nfa: pass class Nfa(_NFA): state_id = -1 def __init__(self, final_states=None, name=''): if final_states is None: final_states = set() NFA.STATE_ID += 1 self.id = NFA.STATE_ID self.final_states = final_states self.transitions = {} self.nam...
class NumArray: def __init__(self, nums: List[int]): self.NumArray = nums self.sum_mat = [0]*(len(nums)+1) for i in range(len(nums)): self.sum_mat[i+1] = nums[i] + self.sum_mat[i] def sumRange(self, left: int, right: int) -> int: #Approach 1 ...
class Numarray: def __init__(self, nums: List[int]): self.NumArray = nums self.sum_mat = [0] * (len(nums) + 1) for i in range(len(nums)): self.sum_mat[i + 1] = nums[i] + self.sum_mat[i] def sum_range(self, left: int, right: int) -> int: return self.sum_mat[right + 1...
def primes(N): f = [] i = 1 while N > 1: i = i + 1 k = 1 check = True while k < i - 1: k = k + 1 check = check and (i % k != 0) if check: c = 0 while N >= 1 and N % i == 0: c = c + 1 N = ...
def primes(N): f = [] i = 1 while N > 1: i = i + 1 k = 1 check = True while k < i - 1: k = k + 1 check = check and i % k != 0 if check: c = 0 while N >= 1 and N % i == 0: c = c + 1 n = N /...
#program to delete all the repetitive character in a list c=0; lis=[1,2,3,4,5,1,2,3,4,5,1]; lis1=[]; k=0 for i in range(0,len(lis)): for j in range(0,i+1): if(lis[j]==lis[i]): c=c+1; if(c>1): break; if(c==1): lis1.append(lis[i]); k+=1; c=0; print(lis1);
c = 0 lis = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1] lis1 = [] k = 0 for i in range(0, len(lis)): for j in range(0, i + 1): if lis[j] == lis[i]: c = c + 1 if c > 1: break if c == 1: lis1.append(lis[i]) k += 1 c = 0 print(lis1)
test = { 'name': 'q1_12_0', 'points': 0, 'suites': [ { 'cases': [ {'code': '>>> pop_for_year(1972) == 3345978384\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> pop_for_year(1989) == 4567880153\nTrue', 'hidden': False, 'locked': False}, ...
test = {'name': 'q1_12_0', 'points': 0, 'suites': [{'cases': [{'code': '>>> pop_for_year(1972) == 3345978384\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> pop_for_year(1989) == 4567880153\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> pop_for_year(2002) == 5501335945\nTrue', 'hidden': False, 'locke...
# This program calculates the area of rectangle # input for length length = float(input('Enter the length: ')) # input for breadth breadth = float(input('Enter the breadth: ')) # calculate area area = length * breadth # calculate perimeter perimeter = 2 * (length + breadth) print(f"Area is {area} and perimeter is ...
length = float(input('Enter the length: ')) breadth = float(input('Enter the breadth: ')) area = length * breadth perimeter = 2 * (length + breadth) print(f'Area is {area} and perimeter is {perimeter}')
# 3.2: Stack Min # Runtime: O(1) - Space: O(1) class Node: def __init__(self, value): self.value = value self.next = None self.minimum = None class Stack: def __init__(self): self.top = None self.minimum = None def push(self, value): new_top = Node(value) ...
class Node: def __init__(self, value): self.value = value self.next = None self.minimum = None class Stack: def __init__(self): self.top = None self.minimum = None def push(self, value): new_top = node(value) new_top.next = self.top self.to...
def test_configuration_session(eos_conn): eos_conn.register_configuration_session(session_name="scrapli_test_session1") result = eos_conn.send_configs( configs=["interface ethernet 1", "show configuration sessions"], privilege_level="scrapli_test_session1", ) eos_conn.close() # pop t...
def test_configuration_session(eos_conn): eos_conn.register_configuration_session(session_name='scrapli_test_session1') result = eos_conn.send_configs(configs=['interface ethernet 1', 'show configuration sessions'], privilege_level='scrapli_test_session1') eos_conn.close() eos_conn.privilege_levels.pop(...
def print_left_triangle(b): for i in range(1,b+1): print ("*"*i) print ("%"*i) print_left_triangle(20)
def print_left_triangle(b): for i in range(1, b + 1): print('*' * i) print('%' * i) print_left_triangle(20)
# -*- coding: utf-8 -*- """ Spyder Editor @auther: syenpark Python Version: 3.6 """ class WeightedEdge(Edge): """ make a gragh weighted """ def __init__(self, src, dest, weight): self.src = src self.dest = dest self.weight = weight def getWeight(self): retur...
""" Spyder Editor @auther: syenpark Python Version: 3.6 """ class Weightededge(Edge): """ make a gragh weighted """ def __init__(self, src, dest, weight): self.src = src self.dest = dest self.weight = weight def get_weight(self): return self.weight def __str_...
def getModels(self): if self._isFalse(self._root): return list([]) if self._isTrue(self._root): models = list([]) else: models = self._getModels(self._root) if self._varFullCount != len(self._varMap): scope1 = self._nodes[self._root].scope scope2 = self._vtreeMan.getScope(self._vtreeMan.getRoot()) mis...
def get_models(self): if self._isFalse(self._root): return list([]) if self._isTrue(self._root): models = list([]) else: models = self._getModels(self._root) if self._varFullCount != len(self._varMap): scope1 = self._nodes[self._root].scope scope2 = self._vtreeMan...
def Corpus_bello(): return 'Corpus' def actionMan(s): return 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFU'
def corpus_bello(): return 'Corpus' def action_man(s): return 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFU'
# coding=utf-8 """ @author: conan @date: 2018/6/25 """ if __name__ == '__main__': empty_list = list() print(empty_list) str1 = 'I love you!' print(str1) fac = (1, 1, 2, 3, 5, 8, 13, 21, 34) fac_list = list(fac) print(fac_list) print(len(empty_list)) print(len(st...
""" @author: conan @date: 2018/6/25 """ if __name__ == '__main__': empty_list = list() print(empty_list) str1 = 'I love you!' print(str1) fac = (1, 1, 2, 3, 5, 8, 13, 21, 34) fac_list = list(fac) print(fac_list) print(len(empty_list)) print(len(str1)) print(max(1, 2, 3, 4, 5)) ...
""" https://leetcode.com/problems/duplicate-zeros/ Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place, do not ret...
""" https://leetcode.com/problems/duplicate-zeros/ Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place, do not ret...
# encoding: utf8 owner = 'module2' def show_owner(): print(owner)
owner = 'module2' def show_owner(): print(owner)
# Constants for first year, last year, date of march, and special years FIRST_YEAR = 1900 LAST_YEAR = 2099 DATE_OF_MARCH = 31 SPECIAL_YEARS = [1954, 1981, 2049, 2076] # Prompt and return year def get_year(): valid = False # Enter year until valid year is entered while not valid: year = int(in...
first_year = 1900 last_year = 2099 date_of_march = 31 special_years = [1954, 1981, 2049, 2076] def get_year(): valid = False while not valid: year = int(input('Enter a year between 1900 to 2099, or 0 to finish: ')) if year == 0 or year in range(FIRST_YEAR, LAST_YEAR + 1): valid = Tr...
def parser(l, r): if all(S[i].isdigit() for i in range(l, r + 1)): return int(S[l:r + 1]) // 2 + 1 ret = [] cnt = 0 start = 0 for i in range(l, r + 1): if S[i] == '[': cnt += 1 if cnt == 1: start = i elif S[i] == ']': if cnt...
def parser(l, r): if all((S[i].isdigit() for i in range(l, r + 1))): return int(S[l:r + 1]) // 2 + 1 ret = [] cnt = 0 start = 0 for i in range(l, r + 1): if S[i] == '[': cnt += 1 if cnt == 1: start = i elif S[i] == ']': if c...
# Print out an error message when DIV by zero occurs # # %rdi := the line of the binary expression # error_div_by_zero_code = """__error_div_by_zero: pushq %rbx movq %rdi, %rbx movq $1, %rax movq $2, %rdi movq $_div_error, %rsi movq $47, %rdx syscall movq %rbx, %rdi call __write_stderr movq $1, %rax...
error_div_by_zero_code = '__error_div_by_zero:\n\t\tpushq\t%rbx\n\t\tmovq\t%rdi, %rbx\n\t\tmovq\t$1, %rax\n\t\tmovq\t$2, %rdi\n\t\tmovq\t$_div_error, %rsi\n\t\tmovq\t$47, %rdx\n\t\tsyscall\n\t\tmovq\t%rbx, %rdi\n\t\tcall\t__write_stderr\n\t\tmovq\t$1, %rax\n\t\tmovq\t$2, %rdi\n\t\tmovq\t$_zero_end, %rsi\n\t\tmovq\t$20,...