content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def rob(self, root: TreeNode) -> int: def helper(root): if root...
class Treenode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def rob(self, root: TreeNode) -> int: def helper(root): if root is None: return [0, 0] x = helper(root....
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
{'name': 'Double Validation on Purchase Requisition', 'version': '0.1', 'category': 'Purchase Management', 'images': [], 'depends': ['purchase_requisition'], 'author': 'Ecosoft', 'description': '\nDouble-validation for purchase requisition.\n==========================================\n\nThe objective of this module is ...
# Made by Wallee#8314/Red-exe-Engineer # Thanks @Bigjango helping :p Block = { "Air": [0, 0], "Stone": [1, 0], "Grass": [2, 0], "Dirt": [3, 0], "Cobblestone": [4, 0], "Wooden Planks": [5, 0], "Saplin":[6, 0], "Oak Saplin": [6, 0], "Spruce Saplin": [6, 1], "Birch Saplin": [6, 2],...
block = {'Air': [0, 0], 'Stone': [1, 0], 'Grass': [2, 0], 'Dirt': [3, 0], 'Cobblestone': [4, 0], 'Wooden Planks': [5, 0], 'Saplin': [6, 0], 'Oak Saplin': [6, 0], 'Spruce Saplin': [6, 1], 'Birch Saplin': [6, 2], 'Bedrock': [7, 0], 'Water': [8, 0], 'Water Stationary': [9, 0], 'Lava': [10, 0], 'Lava Staionary': [11, 0], '...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jan 15 15:31:15 2017 @author: Nadiar """ # 1 a = 2 while (a <= 10): print(a) a += 2 print("Goodbye!") # 2 print("Hello!") a = 10 while(a >= 2): print(a) a -= 2 # 3 temp = 0 inc = 1 end = 21 while (end >= inc): temp += ...
""" Created on Sun Jan 15 15:31:15 2017 @author: Nadiar """ a = 2 while a <= 10: print(a) a += 2 print('Goodbye!') print('Hello!') a = 10 while a >= 2: print(a) a -= 2 temp = 0 inc = 1 end = 21 while end >= inc: temp += inc inc += 1 print(temp)
CONFIG_BINDIR="<CONFIG_BINDIR>" CONFIG_LIBDIR="<CONFIG_LIBDIR>" CONFIG_LOCALSTATEDIR="<CONFIG_LOCALSTATEDIR>" CONFIG_SYSCONFDIR="<CONFIG_SYSCONFDIR>" CONFIG_SYSCONFDIR_DSC="<CONFIG_SYSCONFDIR_DSC>" CONFIG_OAAS_CERTPATH="<OAAS_CERTPATH>" OMI_LIB_SCRIPTS="<OMI_LIB_SCRIPTS>" PYTHON_PID_DIR="<PYTHON_PID_DIR>" DSC_NAMESPACE...
config_bindir = '<CONFIG_BINDIR>' config_libdir = '<CONFIG_LIBDIR>' config_localstatedir = '<CONFIG_LOCALSTATEDIR>' config_sysconfdir = '<CONFIG_SYSCONFDIR>' config_sysconfdir_dsc = '<CONFIG_SYSCONFDIR_DSC>' config_oaas_certpath = '<OAAS_CERTPATH>' omi_lib_scripts = '<OMI_LIB_SCRIPTS>' python_pid_dir = '<PYTHON_PID_DIR...
h, m = map(int, input().split()) fullMin = (h * 60) + m hour = (fullMin - 45) // 60 minu = (fullMin - 45) % 60 if hour == -1: hour = 23 print(f'{hour} {minu}') else: print(f'{hour} {minu}')
(h, m) = map(int, input().split()) full_min = h * 60 + m hour = (fullMin - 45) // 60 minu = (fullMin - 45) % 60 if hour == -1: hour = 23 print(f'{hour} {minu}') else: print(f'{hour} {minu}')
def get_attribute_or_key(obj, name): if isinstance(obj, dict): return obj.get(name) return getattr(obj, name, None)
def get_attribute_or_key(obj, name): if isinstance(obj, dict): return obj.get(name) return getattr(obj, name, None)
# # PySNMP MIB module FASTPATH-QOS-AUTOVOIP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FASTPATH-QOS-AUTOVOIP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:58:28 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3....
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_union, value_range_constraint, value_size_constraint, constraints_intersection) ...
{ "midi_fname": "sample_music/effrhy_131.mid", "video_fname": "tests/test_out/start_size.mp4", "note_start_height": 0.0, # "note_end_height": 0.0, }
{'midi_fname': 'sample_music/effrhy_131.mid', 'video_fname': 'tests/test_out/start_size.mp4', 'note_start_height': 0.0}
par = list() impar = list() num = list() for i in range(1, 8): num.append(int(input(f'Digite o {i} numero: '))) for a in num: if a % 2 == 0: par.append(a) else: impar.append(a) print(num) print(par) print(impar)
par = list() impar = list() num = list() for i in range(1, 8): num.append(int(input(f'Digite o {i} numero: '))) for a in num: if a % 2 == 0: par.append(a) else: impar.append(a) print(num) print(par) print(impar)
class Solution: def scheduleCourse(self, courses: List[List[int]]) -> int: time = 0 maxHeap = [] for duration, lastDay in sorted(courses, key=lambda x: x[1]): heapq.heappush(maxHeap, -duration) time += duration # if current course could not be taken, check if it's able to swap with a ...
class Solution: def schedule_course(self, courses: List[List[int]]) -> int: time = 0 max_heap = [] for (duration, last_day) in sorted(courses, key=lambda x: x[1]): heapq.heappush(maxHeap, -duration) time += duration if time > lastDay: time...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"get_data": "01_core.ipynb", "Dataset": "01_core.ipynb", "DataBunch": "01_core.ipynb", "Learner": "01_core.ipynb", "get_dls": "01_core.ipynb", "get_model": "01_cor...
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'get_data': '01_core.ipynb', 'Dataset': '01_core.ipynb', 'DataBunch': '01_core.ipynb', 'Learner': '01_core.ipynb', 'get_dls': '01_core.ipynb', 'get_model': '01_core.ipynb', 'get_learner': '01_core.ipynb', 'accuracy': '01_core.ipynb', 'camel2snake': ...
#function that allows user to filter photos based on ranking def filterPhotos(photoAlbum, userchoice): if userchoice: #display photos in ascending order return; else: #display photos in descending order return; return;
def filter_photos(photoAlbum, userchoice): if userchoice: return else: return return
def test_about_should_return_200(client): rv = client.get('/about') assert rv.status_code == 200 assert rv.headers['Content-type'] == 'text/html; charset=utf-8'
def test_about_should_return_200(client): rv = client.get('/about') assert rv.status_code == 200 assert rv.headers['Content-type'] == 'text/html; charset=utf-8'
#-*- coding:utf-8 -*- title = """""" text = """""".replace("\n", r"\n") template = """\t*-*"title": "{}", "content": "{}"-*-""" complete_text = template.format(title, text).replace("*-*", "{").replace("-*-", "}") file = open("aktar.txt", "a", encoding="utf-8") file.write(complete_text+",\n") file.close()
title = '' text = ''.replace('\n', '\\n') template = '\t*-*"title": "{}", "content": "{}"-*-' complete_text = template.format(title, text).replace('*-*', '{').replace('-*-', '}') file = open('aktar.txt', 'a', encoding='utf-8') file.write(complete_text + ',\n') file.close()
# dfs class Solution: def numIslands(self, grid: 'List[List[str]]') -> 'int': if grid == []: return 0 def dfs(i, j, n, m): if i < 0 or j < 0 or i >= n or j >= m or grid[i][j] == "0" or grid[i][j] == "-1": return grid[i][j] = "-1" dfs(i + 1, j, n, m) d...
class Solution: def num_islands(self, grid: 'List[List[str]]') -> 'int': if grid == []: return 0 def dfs(i, j, n, m): if i < 0 or j < 0 or i >= n or (j >= m) or (grid[i][j] == '0') or (grid[i][j] == '-1'): return grid[i][j] = '-1' dfs...
# Relative path to the database text file DATABASE_PATH = "resources/anime.txt" def add_anime(anime_name, episodes, current_episode_=0): """ Function to add a new anime to the database /resources/anime.txt Args: anime_name (str): Name of the anime. episodes (int): Total episodes in the an...
database_path = 'resources/anime.txt' def add_anime(anime_name, episodes, current_episode_=0): """ Function to add a new anime to the database /resources/anime.txt Args: anime_name (str): Name of the anime. episodes (int): Total episodes in the anime. current_episode_ (int) : Curre...
# Definitions EXECUTING = 'executing' QUEUED = 'queued' PLEDGED = 'pledged' IGNORE = 'ignore' class Node(object): def __init__(self): self.children = [] def add_child(self, node): self.children.append(node) def get_leaves(self, leaves=[]): # If the node has no leaves, return th...
executing = 'executing' queued = 'queued' pledged = 'pledged' ignore = 'ignore' class Node(object): def __init__(self): self.children = [] def add_child(self, node): self.children.append(node) def get_leaves(self, leaves=[]): if not self.children: leaves.append(self) ...
# # Copyright (c) 2017 Joy Diamond. All rights reserved. # @gem('Topaz.Cache') def gem(): require_gem('Gem.Cache2') require_gem('Topaz.Core') require_gem('Topaz.CacheSupport') # # Specific instances # eight = conjure_number('eight', 8) five = conjure_number('five', 5) four ...
@gem('Topaz.Cache') def gem(): require_gem('Gem.Cache2') require_gem('Topaz.Core') require_gem('Topaz.CacheSupport') eight = conjure_number('eight', 8) five = conjure_number('five', 5) four = conjure_number('four', 4) nine = conjure_number('nine', 9) one = conjure_number('one', 1) se...
""" Author: Resul Emre AYGAN """ """ Project Description: Sum of positive You get an array of numbers, return the sum of all of the positives ones. Example [1,-4,7,12] => 1 + 7 + 12 = 20 Note: if there is nothing to sum, the sum is default to 0. """ def positive_sum(arr): return sum([i for i in arr if i > 0])...
""" Author: Resul Emre AYGAN """ '\nProject Description: Sum of positive\n\nYou get an array of numbers, return the sum of all of the positives ones.\n\nExample [1,-4,7,12] => 1 + 7 + 12 = 20\n\nNote: if there is nothing to sum, the sum is default to 0.\n' def positive_sum(arr): return sum([i for i in arr if i > 0...
# -*- coding: utf-8 -*- """ Created on Fri Jan 5 16:03:43 2018 @author: James Jiang """ all_lines = [line.rstrip('\n') for line in open('Data.txt')] del all_lines[-2] original_molecule = all_lines[-1] capital_letters = [i for i in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'] count_elements = 0 for letter in original_molecule: ...
""" Created on Fri Jan 5 16:03:43 2018 @author: James Jiang """ all_lines = [line.rstrip('\n') for line in open('Data.txt')] del all_lines[-2] original_molecule = all_lines[-1] capital_letters = [i for i in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'] count_elements = 0 for letter in original_molecule: if letter in capital_lett...
ENV = 'directory that defines e.g. the boxes' WORKSPACE = 'workspace directory' BEAD_REF = ''' bead to load data from - either an archive file name or a bead name ''' INPUT_NICK = ( 'name of input,' + ' its workspace relative location is "input/%(metavar)s"') BOX = 'Name of box to store bead'
env = 'directory that defines e.g. the boxes' workspace = 'workspace directory' bead_ref = '\n bead to load data from\n - either an archive file name or a bead name\n' input_nick = 'name of input,' + ' its workspace relative location is "input/%(metavar)s"' box = 'Name of box to store bead'
a = [] assert a[:] == [] assert a[:2**100] == [] assert a[-2**100:] == [] assert a[::2**100] == [] assert a[10:20] == [] assert a[-20:-10] == [] b = [1, 2] assert b[:] == [1, 2] assert b[:2**100] == [1, 2] assert b[-2**100:] == [1, 2] assert b[2**100:] == [] assert b[::2**100] == [1] assert b[-10:1] == [1] assert b[...
a = [] assert a[:] == [] assert a[:2 ** 100] == [] assert a[-2 ** 100:] == [] assert a[::2 ** 100] == [] assert a[10:20] == [] assert a[-20:-10] == [] b = [1, 2] assert b[:] == [1, 2] assert b[:2 ** 100] == [1, 2] assert b[-2 ** 100:] == [1, 2] assert b[2 ** 100:] == [] assert b[::2 ** 100] == [1] assert b[-10:1] == [1...
class Class: __students_count = 22 def __init__(self, name): self.name = name self.students = [] self.grades = [] def add_student(self, name, grade): if self.__students_count != 0: self.students.append(name) self.grades.append(float(grade)) ...
class Class: __students_count = 22 def __init__(self, name): self.name = name self.students = [] self.grades = [] def add_student(self, name, grade): if self.__students_count != 0: self.students.append(name) self.grades.append(float(grade)) ...
#!/usr/bin/env python3 #p3_180824_2354.py # Search synonym #2 # Format: # Number_of_lines # Key (space) Value # Key_word def main(): num = input() myDictionary = getDictionary(num) word = input() #wordToSearch = getKeySearchWord(myDictionary) checkDictionary(myDictionary, word) # Fill dictionary w...
def main(): num = input() my_dictionary = get_dictionary(num) word = input() check_dictionary(myDictionary, word) def get_dictionary(numberOfLines): my_dictionary = dict() list_temp = list() for i in range(int(numberOfLines)): listTemp.append(input().split(' ')) my_dictionary = ...
__title__ = 'cli_command_parser' __description__ = 'CLI Command Parser' __url__ = 'https://github.com/dskrypa/cli_command_parser' __version__ = '2022.06.06' __author__ = 'Doug Skrypa' __author_email__ = 'dskrypa@gmail.com' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2022 Doug Skrypa'
__title__ = 'cli_command_parser' __description__ = 'CLI Command Parser' __url__ = 'https://github.com/dskrypa/cli_command_parser' __version__ = '2022.06.06' __author__ = 'Doug Skrypa' __author_email__ = 'dskrypa@gmail.com' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2022 Doug Skrypa'
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2020 Evgenii sopov <mrseakg@gmail.com> # pylint: disable=relative-beyond-top-level,missing-function-docstring """cpplint list of errors""" def error_line_too_long(parsed_line): print("error(00001): Line too long {}:{}".format( parsed_line...
"""cpplint list of errors""" def error_line_too_long(parsed_line): print('error(00001): Line too long {}:{}'.format(parsed_line.get_filename(), parsed_line.get_number_of_line())) def error_whitespace_after_equal(parsed_line): print('error(00002): Expected whitespace after equal {}:{}'.format(parsed_line.get_f...
# Based and improved from https://github.com/piratecrew/rez-python name = "python" version = "2.7.16" authors = [ "Guido van Rossum" ] description = \ """ The Python programming language. """ requires = [ "cmake-3+", "gcc-6+" ] variants = [ ["platform-linux"] ] tools = [ "2to3", ...
name = 'python' version = '2.7.16' authors = ['Guido van Rossum'] description = '\n The Python programming language.\n ' requires = ['cmake-3+', 'gcc-6+'] variants = [['platform-linux']] tools = ['2to3', 'idle', 'pip', 'pip2.7', 'pip2', 'pydoc', 'python-config', 'python', 'python2-config', 'python2.7-config', 'py...
def sda_to_rgb(im_sda, I_0): """Transform input SDA image or matrix `im_sda` into RGB space. This is the inverse of `rgb_to_sda` with respect to the first parameter Parameters ---------- im_sda : array_like Image (MxNx3) or matrix (3xN) of pixels I_0 : float or array_like Back...
def sda_to_rgb(im_sda, I_0): """Transform input SDA image or matrix `im_sda` into RGB space. This is the inverse of `rgb_to_sda` with respect to the first parameter Parameters ---------- im_sda : array_like Image (MxNx3) or matrix (3xN) of pixels I_0 : float or array_like Back...
altitude=int(input("enter the current altitude : ")) if altitude<=1000: print(" SAFE to land") elif altitude>1000 and altitude<=5000: print("bring it down to 1000ft") else: print("turn around")
altitude = int(input('enter the current altitude : ')) if altitude <= 1000: print(' SAFE to land') elif altitude > 1000 and altitude <= 5000: print('bring it down to 1000ft') else: print('turn around')
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: cs = head cf = head if head == None: return False if cf.next == Non...
class Solution: def has_cycle(self, head: Optional[ListNode]) -> bool: cs = head cf = head if head == None: return False if cf.next == None: return False else: cf = cf.next while cf.next != None and cf != cs: cs = cs.ne...
# *************************************** # ******** Manual Configurations ******** # *************************************** # ---------------------------------------------------------------- # -------- Part 1, meta-network generation settings -----...
blast_results_path = 'C:/Users/Tokuriki Lab/Documents/Sync/Projects/MBL SSN 2020/mbl_cdhit50_all_by_all/' blast_results_files = None query_col = 0 subject_col = 1 bitscore_col = 3 filter_path = 'input/filters/' filter_files = [] output_label = 'mbl_full_cdhit50' output_dir = 'metaSSN_v4_test/' mapping_path = 'C:/Users/...
sbox0 = [ 0X3e, 0x72, 0x5b, 0x47, 0xca, 0xe0, 0x00, 0x33, 0x04, 0xd1, 0x54, 0x98, 0x09, 0xb9, 0x6d, 0xcb, 0X7b, 0x1b, 0xf9, 0x32, 0xaf, 0x9d, 0x6a, 0xa5, 0xb8, 0x2d, 0xfc, 0x1d, 0x08, 0x53, 0x03, 0x90, 0X4d, 0x4e, 0x84, 0x99, 0xe4, 0xce, 0xd9, 0x91, 0xdd, 0xb6, 0x85, 0x48, 0x8b, 0x29, 0x6e, 0xac, 0Xcd, ...
sbox0 = [62, 114, 91, 71, 202, 224, 0, 51, 4, 209, 84, 152, 9, 185, 109, 203, 123, 27, 249, 50, 175, 157, 106, 165, 184, 45, 252, 29, 8, 83, 3, 144, 77, 78, 132, 153, 228, 206, 217, 145, 221, 182, 133, 72, 139, 41, 110, 172, 205, 193, 248, 30, 115, 67, 105, 198, 181, 189, 253, 57, 99, 32, 212, 56, 118, 125, 178, 167, 2...
# Description: Raw Strings if __name__ == '__main__': # Escape characters are honoured a_string = "this is\na string split\t\tand tabbed" print(a_string) # Raw string is printed as it is without interpreting the escape characters. # This is used a lot in regular expressions raw_string = r"this...
if __name__ == '__main__': a_string = 'this is\na string split\t\tand tabbed' print(a_string) raw_string = 'this is\\na string split\\t\\tand tabbed' print(raw_string) b_string = 'this is' + chr(10) + 'a string split' + chr(9) + chr(9) + 'and tabbed' print(b_string) backslash_string = 'this ...
class BaseLangDetect: """ Container for what a language detection module should take as input and should return as output """ def get(self, text): """ Uses the language detection module to detect a language Parameters ---------- text : str The r...
class Baselangdetect: """ Container for what a language detection module should take as input and should return as output """ def get(self, text): """ Uses the language detection module to detect a language Parameters ---------- text : str The ra...
class Board(): def __init__(self, matrix): self.matrix = matrix self.cols = len(matrix) self.rows = len(matrix[0]) self.last = None self.matches = [] for i in range(self.rows): self.matches.append([False] * self.cols) def is_winner(self): for...
class Board: def __init__(self, matrix): self.matrix = matrix self.cols = len(matrix) self.rows = len(matrix[0]) self.last = None self.matches = [] for i in range(self.rows): self.matches.append([False] * self.cols) def is_winner(self): for r...
DATABASE_ENGINE = 'sqlite3' ROOT_URLCONF = 'tests.urls' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'tests.app', ]
database_engine = 'sqlite3' root_urlconf = 'tests.urls' installed_apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'tests.app']
# using return in functions def my_function(name,surname): full_name = name.title() + " " + surname.title() return full_name print(my_function('selim', 'mh'))
def my_function(name, surname): full_name = name.title() + ' ' + surname.title() return full_name print(my_function('selim', 'mh'))
class Solution: def reverseWords(self, s: str) -> str: q = [] raw_split = s.split(' ') for raw_w in raw_split: w = raw_w.strip() if w: q.append(w) return ' '.join(q[::-1])
class Solution: def reverse_words(self, s: str) -> str: q = [] raw_split = s.split(' ') for raw_w in raw_split: w = raw_w.strip() if w: q.append(w) return ' '.join(q[::-1])
class RaddarException(Exception): pass class FailedToCloneRepoException(RaddarException): pass class FailedToWriteRepoException(RaddarException): pass
class Raddarexception(Exception): pass class Failedtoclonerepoexception(RaddarException): pass class Failedtowriterepoexception(RaddarException): pass
QUERIES = {} QUERIES['1A'] = ''' SELECT count(distinct(cpims_ovc_id)) as dcount, gender as sex_id, agerange from vw_cpims_registration {ocbos} {oareas} {odate} group by gender, agerange ''' QUERIES['1B'] = ''' SELECT count(distinct(cpims_ovc_id)) as dcount, gender as sex_id, CASE exit_status WHEN 'ACTIVE' THEN 'Activ...
queries = {} QUERIES['1A'] = '\nSELECT count(distinct(cpims_ovc_id)) as dcount,\ngender as sex_id, agerange\nfrom vw_cpims_registration {ocbos} {oareas} {odate}\ngroup by gender, agerange\n' QUERIES['1B'] = "\nSELECT count(distinct(cpims_ovc_id)) as dcount,\ngender as sex_id,\nCASE exit_status WHEN 'ACTIVE' THEN 'Activ...
def countingSort(array, place): size = len(array) output = [0] * size count = [0] * 10 for i in range(0, size): index = array[i] // place count[index % 10] += 1 for i in range(1, 10): count[i] += count[i - 1] i = size - 1 while i >= 0: index = array...
def counting_sort(array, place): size = len(array) output = [0] * size count = [0] * 10 for i in range(0, size): index = array[i] // place count[index % 10] += 1 for i in range(1, 10): count[i] += count[i - 1] i = size - 1 while i >= 0: index = array[i] // pla...
''' Created on Dec 2, 2013 @author: daniel ''' class PharmacyController(object): def __init__(self, repository): self.__pRepo = repository # cart is used to keep track of all the products self.__cart = [] self.__cartTotal = 0 def addProductToCart(self, product, qty): ...
""" Created on Dec 2, 2013 @author: daniel """ class Pharmacycontroller(object): def __init__(self, repository): self.__pRepo = repository self.__cart = [] self.__cartTotal = 0 def add_product_to_cart(self, product, qty): """ Add a product to cart Input: ...
####################################################################################### # 2.1 # change what is stored in the variables to another types of data # if a variable stores a string, change it to an int, or a boolean, or a float some_var = "hi" some_var2 = 1 some_var3 = True some_var4 = 1.32 #############...
some_var = 'hi' some_var2 = 1 some_var3 = True some_var4 = 1.32 a = 10 b = 2 c = 3 d = 12
load("@build_bazel_integration_testing//tools:import.bzl", "bazel_external_dependency_archive") def bazel_external_dependencies(rules_scala_version, rules_scala_version_sha256): bazel_external_dependency_archive( name = "io_bazel_rules_scala_test", srcs = { rules_scala_version_sha256: [ ...
load('@build_bazel_integration_testing//tools:import.bzl', 'bazel_external_dependency_archive') def bazel_external_dependencies(rules_scala_version, rules_scala_version_sha256): bazel_external_dependency_archive(name='io_bazel_rules_scala_test', srcs={rules_scala_version_sha256: ['https://github.com/wix/rules_scal...
class Line: pic = None color = -1 def __init__(self, pic, color): self.pic = pic self.color = color def oct1(self, x0, y0, x1, y1): if (x0 > x1): x0, y0, x1, y1 = x1, y1, x0, y0 x = x0 y = y0 A = y1 - y0 B = x0 - x1 d = 2 * A...
class Line: pic = None color = -1 def __init__(self, pic, color): self.pic = pic self.color = color def oct1(self, x0, y0, x1, y1): if x0 > x1: (x0, y0, x1, y1) = (x1, y1, x0, y0) x = x0 y = y0 a = y1 - y0 b = x0 - x1 d = 2 * ...
def test_signal_url_total_length(ranker): rank = lambda url: ranker.client.get_signal_value_from_url("url_total_length", url) rank_long = rank("http://www.verrrryyyylongdomain.com/very-long-url-xxxxxxxxxxxxxx.html") rank_short = rank("https://en.wikipedia.org/wiki/Maceo_Parker") rank_min = rank("http://t.co")...
def test_signal_url_total_length(ranker): rank = lambda url: ranker.client.get_signal_value_from_url('url_total_length', url) rank_long = rank('http://www.verrrryyyylongdomain.com/very-long-url-xxxxxxxxxxxxxx.html') rank_short = rank('https://en.wikipedia.org/wiki/Maceo_Parker') rank_min = rank('http://...
terms=int(input("Enter the number of terms:")) a, b= 0, 1 count=0 if terms <= 0: print("Please enter a positive number") elif terms == 1: print("The fibonacci series upto",terms) print(a) else: print("The fabinocci series upto",terms,"terms is:") while count < terms: print(a, end=" ") ...
terms = int(input('Enter the number of terms:')) (a, b) = (0, 1) count = 0 if terms <= 0: print('Please enter a positive number') elif terms == 1: print('The fibonacci series upto', terms) print(a) else: print('The fabinocci series upto', terms, 'terms is:') while count < terms: print(a, end...
OV2640_JPEG_INIT = [ [ 0xff, 0x00 ], [ 0x2c, 0xff ], [ 0x2e, 0xdf ], [ 0xff, 0x01 ], [ 0x3c, 0x32 ], [ 0x11, 0x04 ], [ 0x09, 0x02 ], [ 0x04, 0x28 ], [ 0x13, 0xe5 ], [ 0x14, 0x48 ], [ 0x2c, 0x0c ], [ 0x33, 0x78 ], [ 0x3a, 0x33 ], [ 0x3b, 0xfB ], [ 0x3e, 0x00 ], [ 0x43, 0x11 ], [ 0x16,...
ov2640_jpeg_init = [[255, 0], [44, 255], [46, 223], [255, 1], [60, 50], [17, 4], [9, 2], [4, 40], [19, 229], [20, 72], [44, 12], [51, 120], [58, 51], [59, 251], [62, 0], [67, 17], [22, 16], [57, 146], [53, 218], [34, 26], [55, 195], [35, 0], [52, 192], [54, 26], [6, 136], [7, 192], [13, 135], [14, 65], [76, 0], [72, 0]...
class Parent: value1="This is value 1" value2="This is value 2" class Child(Parent): pass parent=Parent() child=Child() print(parent.value1) print(child.value2)
class Parent: value1 = 'This is value 1' value2 = 'This is value 2' class Child(Parent): pass parent = parent() child = child() print(parent.value1) print(child.value2)
begin_unit comment|'# Copyright (c) 2016 Intel, Inc.' nl|'\n' comment|'# Copyright (c) 2013 OpenStack Foundation' nl|'\n' comment|'# All Rights Reserved.' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in ...
begin_unit comment | '# Copyright (c) 2016 Intel, Inc.' nl | '\n' comment | '# Copyright (c) 2013 OpenStack Foundation' nl | '\n' comment | '# All Rights Reserved.' nl | '\n' comment | '#' nl | '\n' comment | '# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl | '\n' comment | '# not us...
class Frame: __slots__ = ("name", "class_name", "line_no", "file_path") def __init__(self, name, class_name=None, line_no=None, file_path=None): self.name = name self.class_name = class_name self.line_no = line_no self.file_path = file_path
class Frame: __slots__ = ('name', 'class_name', 'line_no', 'file_path') def __init__(self, name, class_name=None, line_no=None, file_path=None): self.name = name self.class_name = class_name self.line_no = line_no self.file_path = file_path
# 6.Input and Range # Given an integer n, write a program that generates a dictionary with # entries from 1 to n. For each key i, the corresponding value should # be i*i. def range_dict(_max): my_dict = {} for i in range(1, _max + 1): my_dict[i] = i ** 2 return my_dict # or with dictionary Comp...
def range_dict(_max): my_dict = {} for i in range(1, _max + 1): my_dict[i] = i ** 2 return my_dict def range_dict2(_max): return {i: i ** 2 for i in range(1, _max + 1)} print(range_dict(10)) print(range_dict2(10))
# Holds permission data for a private race room def get_permission_info(server, race_private_info): permission_info = PermissionInfo() for admin_name in race_private_info.admin_names: for role in server.roles: if role.name.lower() == admin_name.lower(): permission_info.admi...
def get_permission_info(server, race_private_info): permission_info = permission_info() for admin_name in race_private_info.admin_names: for role in server.roles: if role.name.lower() == admin_name.lower(): permission_info.admin_roles.append(role) for member in server...
WORDLIST =\ ('dna', 'vor', 'how', 'hot', 'yud', 'fir', 'fit', 'fix', 'dsc', 'ate', 'ira', 'cup', 'fre', 'fry', 'had', 'has', 'hat', 'hav', 'old', 'fou', 'for', 'fox', 'foe', 'fob', 'foi', 'soo', 'son', 'pet', 'veo', 'vel', 'jim', 'bla', 'one', 'san', 'sad', 'say', 'sap', 'saw', 'sat', 'cim', 'ivy', 'wpi', 'pop', 'act',...
wordlist = ('dna', 'vor', 'how', 'hot', 'yud', 'fir', 'fit', 'fix', 'dsc', 'ate', 'ira', 'cup', 'fre', 'fry', 'had', 'has', 'hat', 'hav', 'old', 'fou', 'for', 'fox', 'foe', 'fob', 'foi', 'soo', 'son', 'pet', 'veo', 'vel', 'jim', 'bla', 'one', 'san', 'sad', 'say', 'sap', 'saw', 'sat', 'cim', 'ivy', 'wpi', 'pop', 'act', ...
n1 = float(input("Type the first number: ")) n2 = float(input("Type the second number: ")) print("Are equals?", n1 == n2) print("Are different?", n1 != n2) print("First number is greater than Second number? =", n1 > n2) print("Second is greater or equal than First number ? =", n2 >= n1) strTest = input("Type a string:...
n1 = float(input('Type the first number: ')) n2 = float(input('Type the second number: ')) print('Are equals?', n1 == n2) print('Are different?', n1 != n2) print('First number is greater than Second number? =', n1 > n2) print('Second is greater or equal than First number ? =', n2 >= n1) str_test = input('Type a string:...
track = dict( author_username='ryanholbrook', course_name='Computer Vision', course_url='https://www.kaggle.com/ryanholbrook/computer-vision', course_forum_url='https://www.kaggle.com/learn-forum', ) TOPICS = [ 'The Convolutional Classifier', 'Convolution and ReLU', 'Maximum Pooling', '...
track = dict(author_username='ryanholbrook', course_name='Computer Vision', course_url='https://www.kaggle.com/ryanholbrook/computer-vision', course_forum_url='https://www.kaggle.com/learn-forum') topics = ['The Convolutional Classifier', 'Convolution and ReLU', 'Maximum Pooling', 'The Moving Window', 'Custom Convnets'...
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) Copyright IBM Corp. 2010, 2020. All Rights Reserved. """Contains a dict to validate the app configs""" VALIDATE_DICT = { "num_workers": { "required": False, "valid_condition": lambda c: True if c >= 1 and c <= 50 else False, "invalid_msg"...
"""Contains a dict to validate the app configs""" validate_dict = {'num_workers': {'required': False, 'valid_condition': lambda c: True if c >= 1 and c <= 50 else False, 'invalid_msg': 'num_workers must be in the range 1 <= 50'}}
''' PythonExercicios\from math import factorial number = int(input('Choose a number: ')) result = factorial(number) print('The factorial of {}! is = {}'.format(number, result)) ''' number = int(input('Choose a number: ')) control = number result = 1 print('Calculating {}! = '.format(number), end='') while control > 0: ...
""" PythonExercicios\x0crom math import factorial number = int(input('Choose a number: ')) result = factorial(number) print('The factorial of {}! is = {}'.format(number, result)) """ number = int(input('Choose a number: ')) control = number result = 1 print('Calculating {}! = '.format(number), end='') while control > 0...
exclusions = ['\bCHAPTER (\d*|M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3}))\.*\b', 'CHAPTER', '\bChapter \d*\b', '\d{2}:\d{2}:\d{2},\d{3}\s-->\s\d{2}:\d{2}:\d{2},\d{3}', '^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})\.?\n', '^[^\w...
exclusions = ['\x08CHAPTER (\\d*|M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3}))\\.*\x08', 'CHAPTER', '\x08Chapter \\d*\x08', '\\d{2}:\\d{2}:\\d{2},\\d{3}\\s-->\\s\\d{2}:\\d{2}:\\d{2},\\d{3}', '^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})\\.?\n', '^[^\\w\\d\\s]*\n', '^(CLOV|HAMM|NAGG|NELL)\\s\\([\\w\...
class Agent: def __init__(self, env, q_function, action_selector, logger): self.__env = env self.__q_function = q_function self.__action_selector = action_selector self.__logger = logger def train(self, steps, episodes, filepath, filename): episode_reward = 0 tot...
class Agent: def __init__(self, env, q_function, action_selector, logger): self.__env = env self.__q_function = q_function self.__action_selector = action_selector self.__logger = logger def train(self, steps, episodes, filepath, filename): episode_reward = 0 to...
student = {"name":"Rolf", "grades":(89,9,93,78,90)} def average(seq): return sum(seq)/len(seq) print(average(student["grades"])) class Student: def __init__(self,name,grades): self.name = name self.grades = grades def averageGrade(self): return sum(self.grades)/len(self.grades) ...
student = {'name': 'Rolf', 'grades': (89, 9, 93, 78, 90)} def average(seq): return sum(seq) / len(seq) print(average(student['grades'])) class Student: def __init__(self, name, grades): self.name = name self.grades = grades def average_grade(self): return sum(self.grades) / len(s...
VERSION = '2.0b9' DEFAULT_TIMEOUT = 60000 REQUEST_ID_HEADER = 'Cko-Request-Id' API_VERSION_HEADER = 'Cko-Version'
version = '2.0b9' default_timeout = 60000 request_id_header = 'Cko-Request-Id' api_version_header = 'Cko-Version'
#Leia um numero real e imprima a quinta parte deste numero n=float(input("Informe um numero real: ")) n=n/5 print(n)
n = float(input('Informe um numero real: ')) n = n / 5 print(n)
expected_output = { 'instance': { 'default': { 'vrf': { 'red': { 'address_family': { '': { 'prefixes': { '11.11.11.11/32': { 'avail...
expected_output = {'instance': {'default': {'vrf': {'red': {'address_family': {'': {'prefixes': {'11.11.11.11/32': {'available_path': '1', 'best_path': '1', 'index': {1: {'binding_sid': {'color': '7', 'sid': '22', 'state': 'UP'}, 'cluster_list': '8.8.8.9', 'ext_community': 'RT:2:2 Color:1 Color:2 Color:3 Color:4 Color:...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: if not headA or not headB: return None # compute th...
class Solution: def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNode: if not headA or not headB: return None len_a = len_b = 1 node_a = headA while nodeA.next: node_a = nodeA.next len_a += 1 node_b = headB ...
def list_users_in_account(request_ctx, account_id, search_term=None, include=None, per_page=None, **request_kwargs): """ Retrieve the list of users associated with this account. @example_request curl https://<canvas>/api/v1/accounts/self/users?search_term=<search value> \ ...
def list_users_in_account(request_ctx, account_id, search_term=None, include=None, per_page=None, **request_kwargs): """ Retrieve the list of users associated with this account. @example_request curl https://<canvas>/api/v1/accounts/self/users?search_term=<search value> -X GET -...
# Autogenerated file for HID Mouse # Add missing from ... import const _JD_SERVICE_CLASS_HID_MOUSE = const(0x1885dc1c) _JD_HID_MOUSE_BUTTON_LEFT = const(0x1) _JD_HID_MOUSE_BUTTON_RIGHT = const(0x2) _JD_HID_MOUSE_BUTTON_MIDDLE = const(0x4) _JD_HID_MOUSE_BUTTON_EVENT_UP = const(0x1) _JD_HID_MOUSE_BUTTON_EVENT_DOWN = cons...
_jd_service_class_hid_mouse = const(411425820) _jd_hid_mouse_button_left = const(1) _jd_hid_mouse_button_right = const(2) _jd_hid_mouse_button_middle = const(4) _jd_hid_mouse_button_event_up = const(1) _jd_hid_mouse_button_event_down = const(2) _jd_hid_mouse_button_event_click = const(3) _jd_hid_mouse_button_event_doub...
def is_substitution_cipher(s1, s2): dict1={} dict2={} for i,j in zip(s1, s2): dict1[i]=dict1.get(i, 0)+1 dict2[j]=dict2.get(j, 0)+1 if len(dict1)!=len(dict2): return False return True
def is_substitution_cipher(s1, s2): dict1 = {} dict2 = {} for (i, j) in zip(s1, s2): dict1[i] = dict1.get(i, 0) + 1 dict2[j] = dict2.get(j, 0) + 1 if len(dict1) != len(dict2): return False return True
"""properties.py module""" DEFAULT_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)" DEFAULT_FILE_NAME = ".secret.txt" DEFAULT_LENGTH_OF_SECRET_KEY = 50
"""properties.py module""" default_chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)' default_file_name = '.secret.txt' default_length_of_secret_key = 50
# A program to rearrange array in alternating positive & negative items with O(1) extra space class ArrayRearrange: def __init__(self, arr, n): self.arr = arr self.n = n def rearrange_array(self): arr = self.arr.copy() out_of_place = -1 for i in range(self.n): ...
class Arrayrearrange: def __init__(self, arr, n): self.arr = arr self.n = n def rearrange_array(self): arr = self.arr.copy() out_of_place = -1 for i in range(self.n): if out_of_place == -1: if arr[i] >= 0 and i % 2 == 0 or (arr[i] < 0 and i %...
expected_output = { 'pid': 'WS-C4507R', 'os': 'ios', 'platform': 'cat4k', 'version': '12.2(18)EW5', }
expected_output = {'pid': 'WS-C4507R', 'os': 'ios', 'platform': 'cat4k', 'version': '12.2(18)EW5'}
# -*- coding: utf-8 -*- """ Created on Wed Sep 22 17:22:59 2021 Default paths for the different folders. Should be changed priori to any computation. @author: amarmore """ # RWC path_data_persisted_rwc = "C:/Users/amarmore/Desktop/data_persisted" ## Path where pre-computed data on RWC Pop should be stored (spectrogra...
""" Created on Wed Sep 22 17:22:59 2021 Default paths for the different folders. Should be changed priori to any computation. @author: amarmore """ path_data_persisted_rwc = 'C:/Users/amarmore/Desktop/data_persisted' path_annotation_rwc = 'C:/Users/amarmore/Desktop/Audio samples/RWC Pop/annotations' path_entire_rwc =...
#!/usr/bin/env python # -*- coding: utf-8 -*- """http://www.testingperspective.com/wiki/doku.php/collaboration/chetan/designpatternsinpython/chain-of-responsibilitypattern""" class Handler: def __init__(self): self._successor = None def successor(self, successor): self._successor = succ...
"""http://www.testingperspective.com/wiki/doku.php/collaboration/chetan/designpatternsinpython/chain-of-responsibilitypattern""" class Handler: def __init__(self): self._successor = None def successor(self, successor): self._successor = successor def handle(self, request): raise ...
""" A block cipher is a method of encrypting text, in which a cryptographic key and algorithm are applied to a block of data (for example, 64 contiguous bits) at once as a group rather than to one bit at a time. A block cipher is a deterministic algorithm operating on fixed-length groups of bits, called a block, with ...
""" A block cipher is a method of encrypting text, in which a cryptographic key and algorithm are applied to a block of data (for example, 64 contiguous bits) at once as a group rather than to one bit at a time. A block cipher is a deterministic algorithm operating on fixed-length groups of bits, called a block, with ...
_MAJOR = 0 _MINOR = 6 _PATCH = 4 __version__ = str(_MAJOR) + '.' + str(_MINOR) + '.' + str(_PATCH) def version(): ''' Returns a string representation of the version ''' return __version__ def version_tuple(): ''' Returns a 3-tuple of ints that represent the version ''' return (_MAJO...
_major = 0 _minor = 6 _patch = 4 __version__ = str(_MAJOR) + '.' + str(_MINOR) + '.' + str(_PATCH) def version(): """ Returns a string representation of the version """ return __version__ def version_tuple(): """ Returns a 3-tuple of ints that represent the version """ return (_MAJOR, ...
#!/usr/bin/env python3 # https://www.hackerrank.com/challenges/python-lists/ if __name__ == '__main__': N = int(input()) lst = [] for i in range(N): cmd = input().rstrip().split() if(cmd[0] == 'insert'): lst.insert(int(cmd[1]), int(cmd[2])) elif(cmd[0] == 'print'): ...
if __name__ == '__main__': n = int(input()) lst = [] for i in range(N): cmd = input().rstrip().split() if cmd[0] == 'insert': lst.insert(int(cmd[1]), int(cmd[2])) elif cmd[0] == 'print': print(lst) elif cmd[0] == 'remove': lst.remove(int(cm...
class Solution: def minSwap(self, A: List[int], B: List[int]) -> int: n1, s1 = 0, 1 for i in range(1, len(A)): n2 = s2 = float("inf") if A[i - 1] < A[i] and B[i - 1] < B[i]: n2 = min(n2, n1) s2 = min(s2, s1 + 1) if A[i - 1] < B[i] a...
class Solution: def min_swap(self, A: List[int], B: List[int]) -> int: (n1, s1) = (0, 1) for i in range(1, len(A)): n2 = s2 = float('inf') if A[i - 1] < A[i] and B[i - 1] < B[i]: n2 = min(n2, n1) s2 = min(s2, s1 + 1) if A[i - 1] < ...
__author__ = 'xelhark' class ErrorWithList(ValueError): def __init__(self, message, errors_list=None): self.errors_list = errors_list super(ErrorWithList, self).__init__(message) class ModelValidationError(ErrorWithList): pass class InstanceValidationError(ErrorWithList): pass
__author__ = 'xelhark' class Errorwithlist(ValueError): def __init__(self, message, errors_list=None): self.errors_list = errors_list super(ErrorWithList, self).__init__(message) class Modelvalidationerror(ErrorWithList): pass class Instancevalidationerror(ErrorWithList): pass
config = { "username": "", "password": "", "phonename": "iPhone", "sms_csv": "" }
config = {'username': '', 'password': '', 'phonename': 'iPhone', 'sms_csv': ''}
class BitDocument: """Wrapper for Firestore document (https://firebase.google.com/docs/firestore/reference/rest/v1beta1/projects.databases.documents) """ def __init__(self, doc): self.id = doc['id']['stringValue'] self.title = self._get_field(doc, 'title', 'stringValue', '') self.co...
class Bitdocument: """Wrapper for Firestore document (https://firebase.google.com/docs/firestore/reference/rest/v1beta1/projects.databases.documents) """ def __init__(self, doc): self.id = doc['id']['stringValue'] self.title = self._get_field(doc, 'title', 'stringValue', '') self.co...
#This program takes in a postive integer and applies a calculation to it. # It then outputs a sequence that ends in 1 #creates a list called L mylist=[] #take the input for the user value = int(input("Please enter a positive integer: ")) # Adds the input to the list. # The append wouldnt work unless I made i an int ...
mylist = [] value = int(input('Please enter a positive integer: ')) mylist.append(int(value)) while value != 1: if value % 2 == 0: value /= 2 mylist.append(int(value)) else: value = value * 3 + 1 mylist.append(int(value)) print(mylist)
class Aritmatika: @staticmethod def tambah(a, b): return a + b @staticmethod def kurang(a, b): return a - b @staticmethod def bagi(a, b): return a / b @staticmethod def bagi_int(a, b): return a // b @staticmethod def pangkat(a, b): ret...
class Aritmatika: @staticmethod def tambah(a, b): return a + b @staticmethod def kurang(a, b): return a - b @staticmethod def bagi(a, b): return a / b @staticmethod def bagi_int(a, b): return a // b @staticmethod def pangkat(a, b): ret...
# Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. # A region is captured by flipping all 'O's into 'X's in that surrounded region. def solve(board): """ Do not return anything, modify board in-place instead. """ if not board: return board nrow = len(bo...
def solve(board): """ Do not return anything, modify board in-place instead. """ if not board: return board nrow = len(board) ncol = len(board[0]) if nrow <= 2 or ncol <= 2: return board for i in range(nrow): for j in range(ncol): if (i == 0 or i == nr...
def calculate_similarity(my, theirs, tags): similarity = {} for group in ('personal', 'hobbies'): all_names = {tag.code for tag in tags if tag.group == group} my_names = all_names & my their_names = all_names & theirs both = my_names | their_names same = my_names & their_...
def calculate_similarity(my, theirs, tags): similarity = {} for group in ('personal', 'hobbies'): all_names = {tag.code for tag in tags if tag.group == group} my_names = all_names & my their_names = all_names & theirs both = my_names | their_names same = my_names & their_...
""" :copyright: (c) 2020 Yotam Rechnitz :license: MIT, see LICENSE for more details """ class Average: def __init__(self, js: dict): self._allDamageDoneAvgPer10Min = js["allDamageDoneAvgPer10Min"] if "allDamageDoneAvgPer10Min" in js else 0 self._barrierDamageDoneAvgPer10Min = js[ "barr...
""" :copyright: (c) 2020 Yotam Rechnitz :license: MIT, see LICENSE for more details """ class Average: def __init__(self, js: dict): self._allDamageDoneAvgPer10Min = js['allDamageDoneAvgPer10Min'] if 'allDamageDoneAvgPer10Min' in js else 0 self._barrierDamageDoneAvgPer10Min = js['barrierDamageDone...
# Method 1: using index find the max first, and then process def validMountainArray(self, A): if len(A) < 3: return False index = A.index(max(A)) if index == 0 or index == len(A) -1: return False for i in range(1, len(A)): if i <= index: if A[i] <= A[i - 1]: return False els...
def valid_mountain_array(self, A): if len(A) < 3: return False index = A.index(max(A)) if index == 0 or index == len(A) - 1: return False for i in range(1, len(A)): if i <= index: if A[i] <= A[i - 1]: return False elif A[i] >= A[i - 1]: ...
# 69. Sqrt(x) Easy # Implement int sqrt(int x). # # Compute and return the square root of x, where x is guaranteed to be a non-negative integer. # # Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. # # Example 1: # # Input: 4 # Output: 2 # Exampl...
def my_sqrt(self, x: int) -> int: """ Runtime: 56 ms, faster than 54.11% of Python3 online submissions for Sqrt(x). Memory Usage: 13.1 MB, less than 79.16% of Python3 online submissions for Sqrt(x). """ if x == 1 or x == 0: return x max_range = max(1, x) min_range = 0 result = 0 ...
class Line(object): """Represents a line on the road, which consists of a list of coordinates. Attributes: line_id: an integer indicating which line this is. coordinates: a list of tuples indicating the coordinates on the line. """ def __init__(self, line_id, coordinates): """I...
class Line(object): """Represents a line on the road, which consists of a list of coordinates. Attributes: line_id: an integer indicating which line this is. coordinates: a list of tuples indicating the coordinates on the line. """ def __init__(self, line_id, coordinates): """I...
class UncleEngineer: ''' test = UncleEngineer() test.art() ''' def __init__(self): self.name = 'Uncle Engineer' def art(self): asciiart = ''' Z Z .,., z ...
class Uncleengineer: """ test = UncleEngineer() test.art() """ def __init__(self): self.name = 'Uncle Engineer' def art(self): asciiart = '\n Z \n Z \n .,., z \n (((((()...
class Vscode(): def execute(self): print("code is compiling and code is running") class Pycharm(): def execute(self): print("code is compiling and code is running") class python(): def execute(self): print("python is using") class CPP(): def execute(self): print("C++ is usi...
class Vscode: def execute(self): print('code is compiling and code is running') class Pycharm: def execute(self): print('code is compiling and code is running') class Python: def execute(self): print('python is using') class Cpp: def execute(self): print('C++ is us...
#! /usr/bin/python __version__ = "0.1.0" __description__ = "Connection facilitator" __logo__ = """ ___ ____ ____ __ ____ __ __ ___ / __)(_ _)( _ \ /__\ (_ _)( )( )/ __) \__ \ )( ) / /(__)\ )( )(__)( \__ \\ (___/ (__) (_)\_)(__)(__)(__) (______)(___/ """ PORT = 5678 TIME_OUT = 20 BIND_TIME = 0....
__version__ = '0.1.0' __description__ = 'Connection facilitator' __logo__ = '\n ___ ____ ____ __ ____ __ __ ___\n/ __)(_ _)( _ \\ /__\\ (_ _)( )( )/ __)\n\\__ \\ )( ) / /(__)\\ )( )(__)( \\__ \\\n(___/ (__) (_)\\_)(__)(__)(__) (______)(___/\n' port = 5678 time_out = 20 bind_time = 0.1 all_client...
# -*- coding: utf-8 -*- """ Created on Wed Dec 4 10:28:28 2019 @author: Paul """ def generate_passwords(start, stop): """ Generates and returns a list strings of all possible passwords in the range start-stop, meeting the following requirements: - Passwords are six digit num...
""" Created on Wed Dec 4 10:28:28 2019 @author: Paul """ def generate_passwords(start, stop): """ Generates and returns a list strings of all possible passwords in the range start-stop, meeting the following requirements: - Passwords are six digit numbers - In each password two ...
nums = [2, 3, 4, 5, 7, 10, 12] for n in nums: print(n, end=", ") class CartItem: def __init__(self, name, price) -> None: self.price = price self.name = name def __repr__(self) -> str: return "({0}, ${1})".format(self.name, self.price) class ShoppingCart: def __init__(self) -> None: se...
nums = [2, 3, 4, 5, 7, 10, 12] for n in nums: print(n, end=', ') class Cartitem: def __init__(self, name, price) -> None: self.price = price self.name = name def __repr__(self) -> str: return '({0}, ${1})'.format(self.name, self.price) class Shoppingcart: def __init__(self) ...
highest_seat_id = 0 with open("input.txt", "r") as f: lines = [line.rstrip() for line in f.readlines()] for line in lines: rows = [0, 127] row = None columns = [0, 7] column = None for command in list(line): if command == "F": rows = [rows[0]...
highest_seat_id = 0 with open('input.txt', 'r') as f: lines = [line.rstrip() for line in f.readlines()] for line in lines: rows = [0, 127] row = None columns = [0, 7] column = None for command in list(line): if command == 'F': rows = [rows[0], ...
#! /usr/bin/env python """ Make a small MDV file containing a grid with X and Y axes in degrees. Partial grid is taken from full sized file 000000.mdv which is contained in the 200202.MASTER15.mdv.tar.gz file available online at: http://www2.mmm.ucar.edu/imagearchive/WSI/mdv/ """ # The MDV RLE decoding routine ends at...
""" Make a small MDV file containing a grid with X and Y axes in degrees. Partial grid is taken from full sized file 000000.mdv which is contained in the 200202.MASTER15.mdv.tar.gz file available online at: http://www2.mmm.ucar.edu/imagearchive/WSI/mdv/ """ infile = open('000000.mdv', 'rb') outfile = open('example_mdv...
class Vertex: def __init__(self, label: str = None, weight: int = float("inf"), key: int = None): self.label: str = label self.weight: int = weight self.key: int = key
class Vertex: def __init__(self, label: str=None, weight: int=float('inf'), key: int=None): self.label: str = label self.weight: int = weight self.key: int = key
class Solution: def dfs(self, s:str, n:int, pos:int, sub_res:list, total_res:list, left:int): if left == 0 and pos >= n: total_res.append(sub_res[:]) return if left == 0 and pos < n: return if pos < n and s[pos] == '0': sub_res.append(s[pos]) ...
class Solution: def dfs(self, s: str, n: int, pos: int, sub_res: list, total_res: list, left: int): if left == 0 and pos >= n: total_res.append(sub_res[:]) return if left == 0 and pos < n: return if pos < n and s[pos] == '0': sub_res.append(s[...
collection = ["gold", "silver", "bronze"] # list comprehension new_list = [item.upper for item in collection] # generator expression # it is similar to list comprehension, but use () round brackets my_gen = (item.upper for item in collection)
collection = ['gold', 'silver', 'bronze'] new_list = [item.upper for item in collection] my_gen = (item.upper for item in collection)
grader_tools = {} def tool(f): grader_tools[f.__name__] = f return f @tool def percentage(x, y): """ Convert x/y into a percentage. Useful for calculating success rate Args: x (int) y (int) Returns: str: percentage formatted into a string """ return '%.2f%%' %...
grader_tools = {} def tool(f): grader_tools[f.__name__] = f return f @tool def percentage(x, y): """ Convert x/y into a percentage. Useful for calculating success rate Args: x (int) y (int) Returns: str: percentage formatted into a string """ return '%.2f%%' %...