content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def duplicate(iterat, word): ans = '' if iterat == 0: return '' for i in range(len(word)): if word[i] != ' ' and word[i] != ',' and word[i] != '!' and word[i] != '?' and word[i] != '(' and word[i] != ')' and word[i] != ";" and word[i] != ":" and word[i] != '[' and word[i] != ']' and wor...
def duplicate(iterat, word): ans = '' if iterat == 0: return '' for i in range(len(word)): if word[i] != ' ' and word[i] != ',' and (word[i] != '!') and (word[i] != '?') and (word[i] != '(') and (word[i] != ')') and (word[i] != ';') and (word[i] != ':') and (word[i] != '[') and (word[i] != '...
# Create linked list from the array # used to be imported to another file # class ListNode(): def __init__(self, val=0, next=None): self.val = val self.next = next def create_linkedList(self, data): list_head = ListNode() prev = list_head for i in data: a = ...
class Listnode: def __init__(self, val=0, next=None): self.val = val self.next = next def create_linked_list(self, data): list_head = list_node() prev = list_head for i in data: a = list_node(i) prev.next = a prev = prev.next ...
# example of using dict ---------------------------------------- # Declare a dict student = {'name': 'John', 'age': 14} # Get a value age = student['age'] # age is 14 # Update a value student['age'] = 15 # student becomes {'name': 'John', 'age': 15} # Insert a key-value pair student['score'] = 'A' # student becomes {'n...
student = {'name': 'John', 'age': 14} age = student['age'] student['age'] = 15 student['score'] = 'A' d1 = {'a': 1, 'b': 2} d2 = {'c': 3, 'd': 4} d2a = {'a': 10, 'c': 3, 'd': 4} d3 = {'a': 1, 'b': 2, 'c': 3, 'd': 4} d3 = d1.copy() d3.update(d2) print(d3) d3 = d1.copy() d3.update(d2a) print(d3) d3 = d2a.copy() d3.update...
def partition(A, b, e): x = A[e] i = b - 1 for j in range(b, e): if A[j] <= x: i = i + 1 t = A[i] A[i] = A[j] A[j] = t i = i + 1 t = A[i] A[i] = A[e] A[e] = t return i def quick_sort(A, b, e): if b < e: m = partition(...
def partition(A, b, e): x = A[e] i = b - 1 for j in range(b, e): if A[j] <= x: i = i + 1 t = A[i] A[i] = A[j] A[j] = t i = i + 1 t = A[i] A[i] = A[e] A[e] = t return i def quick_sort(A, b, e): if b < e: m = partition(A,...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 8 21:45:52 2018 @author: joy """ message = "Hello Python world!" print(message)
""" Created on Mon Jan 8 21:45:52 2018 @author: joy """ message = 'Hello Python world!' print(message)
name = 'Marko' while name != "Adrian": if name != 'Adrian': print('name is not true, write your true name, Adrian') name=input() if name == 'Adrian': print('Well done!') elif name == 'Marko': print('Fuck off bozzo!') break else: print('You act...
name = 'Marko' while name != 'Adrian': if name != 'Adrian': print('name is not true, write your true name, Adrian') name = input() if name == 'Adrian': print('Well done!') elif name == 'Marko': print('Fuck off bozzo!') break else: print('You actually typed...
# $Id$ # # Copyright (C) 2001-2006 greg Landrum and Rational Discovery LLC # # @@ All Rights Reserved @@ # This file is part of the RDKit. # The contents are covered by the terms of the BSD license # which is included in the file license.txt, found at the root # of the RDKit source tree. # """ periodic table data...
""" periodic table data, **obsolete** now that the C++ code exposes an interface to the internal PT stuff, this data is mostly obsolete """ periodic_data = '\n0\tX\t0.0\t0.0\t0.0\t0\t0.000\t0\n1\tH\t0.230\t0.330\t1.200\t1\t1.008\t1\n2\tHe\t0.930\t0.700\t1.400\t0\t4.003\t2\n3\tLi\t0.680\t1.230\t1.820\t1\t6.941\t1\...
# Get Webex token here: https://developer.webex.com/ URL = "https://sandboxapicdc.cisco.com" USERNAME = "admin" PASSWORD = "ciscopsdt" WEBEX_ROOM_NAME = " " WEBEX_EMAIL_ADDRESS = " " WEBEX_TEAMS_ACCESS_TOKEN = " "
url = 'https://sandboxapicdc.cisco.com' username = 'admin' password = 'ciscopsdt' webex_room_name = ' ' webex_email_address = ' ' webex_teams_access_token = ' '
my_name='Zed A.Shaw' my_age=35 #not a lie my_height=74#inches my_weight=180#lbs my_eyes='Blue' my_hair='Brown' my_teeth='White' print ("Let's talk about %s." %my_name) print ("He's %d inches tall." %my_height) print ("He's %d pounds heavy." %my_weight) print ("Actually that's not too heavy") print ("He's got %s eyes a...
my_name = 'Zed A.Shaw' my_age = 35 my_height = 74 my_weight = 180 my_eyes = 'Blue' my_hair = 'Brown' my_teeth = 'White' print("Let's talk about %s." % my_name) print("He's %d inches tall." % my_height) print("He's %d pounds heavy." % my_weight) print("Actually that's not too heavy") print("He's got %s eyes and %s hair....
class Variable(): def __init__(self, name, type): # Informacoes da variavel self.__name = name # Nome da variavel self.__type = type # Tipo da variavel self.__used = False # Indica se a variavel ja foi utilizada def getName(self): return self.__name ...
class Variable: def __init__(self, name, type): self.__name = name self.__type = type self.__used = False def get_name(self): return self.__name def set_name(self, name): self.__name = name def get_type(self): return self.__type def get_used(self)...
# see https://www.codewars.com/kata/53573877d5493b4d6e00050c/solutions/python def capital(capitals): arr = [] for d in capitals: if 'country' in d: arr.append(f"The capital of {d['country']} is {d['capital']}") else: arr.append(f"The capital of {d['state']} is {d['capita...
def capital(capitals): arr = [] for d in capitals: if 'country' in d: arr.append(f"The capital of {d['country']} is {d['capital']}") else: arr.append(f"The capital of {d['state']} is {d['capital']}") return arr state_capitals = [{'state': 'Maine', 'capital': 'Augusta'...
""" ScalyMUCK has several base exceptions for the ScalyMUCK core and ScalyMUCK modifications that may be loaded into the MUCK server. This software is licensed under the MIT license. Please refer to LICENSE.txt for more information. """ class ModApplicationError(Exception): """ Generic exception for Sc...
""" ScalyMUCK has several base exceptions for the ScalyMUCK core and ScalyMUCK modifications that may be loaded into the MUCK server. This software is licensed under the MIT license. Please refer to LICENSE.txt for more information. """ class Modapplicationerror(Exception): """ Generic exception for ScalyMUC...
""" We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. For example if routes[0] = [1, 5, 7], this means that the first bus (0-th indexed) travels in the sequence 1->5->7->1->5->7->1->... forever. We start at bus stop S (initially not on a bus), and we want t...
""" We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. For example if routes[0] = [1, 5, 7], this means that the first bus (0-th indexed) travels in the sequence 1->5->7->1->5->7->1->... forever. We start at bus stop S (initially not on a bus), and we want t...
DEVELOPMENT = True # # email credentials MAIL_USERNAME ='' MAIL_PASSWORD = '' MAIL_DEFAULT_SENDER ='' SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY ='sdasiodaifqcXvLHzs6uAEfcFAEdzrwdaifqcXvLHzs6uAEfcFAEdzrwdjafqcXvLHzs6uAEfcFAEdzrwoidsj' SECURITY_PASSWORD_SALT = 'cXvLHzs6uAEfcFAEdzrwdjafqcXvLHzs6uAcXvLHzs6uAEfcFA...
development = True mail_username = '' mail_password = '' mail_default_sender = '' sqlalchemy_track_modifications = False secret_key = 'sdasiodaifqcXvLHzs6uAEfcFAEdzrwdaifqcXvLHzs6uAEfcFAEdzrwdjafqcXvLHzs6uAEfcFAEdzrwoidsj' security_password_salt = 'cXvLHzs6uAEfcFAEdzrwdjafqcXvLHzs6uAcXvLHzs6uAEfcFAEdzrwdjafqcXvLHzs6uAc...
class CompoundStructureError(Enum,IComparable,IFormattable,IConvertible): """ When CompoundStructure::isValid() returns false,it uses these values to indicate precise nature of defect. enum CompoundStructureError,values: BadShellOrder (0),BadShellsStructure (5),CoreTooThin (1),DeckCantBoundAbove (12),DeckCan...
class Compoundstructureerror(Enum, IComparable, IFormattable, IConvertible): """ When CompoundStructure::isValid() returns false,it uses these values to indicate precise nature of defect. enum CompoundStructureError,values: BadShellOrder (0),BadShellsStructure (5),CoreTooThin (1),DeckCantBoundAbove (12),DeckC...
class Queries: def __init__(self, file_path: str) -> None: self.__file_path = file_path @staticmethod def read_sql_file(file_path: str): file = open(file_path, 'r') sql = file.read().split(';') file.close() return sql @property def get(self): return self.read_sql_file(self._...
class Queries: def __init__(self, file_path: str) -> None: self.__file_path = file_path @staticmethod def read_sql_file(file_path: str): file = open(file_path, 'r') sql = file.read().split(';') file.close() return sql @property def get(self): return...
# Addition of numbers def add(num1, num2): return num1 + num2 # subtraction of numbers def subtract(num1, num2): return num1 - num2 # multiplication of numbers def multiply(num1, num2): return num1 * num2 # Division of numbers def divide(num1, num2): return num1 / num2 p...
def add(num1, num2): return num1 + num2 def subtract(num1, num2): return num1 - num2 def multiply(num1, num2): return num1 * num2 def divide(num1, num2): return num1 / num2 print('Select operation:') print('1.Add') print('2.Subtract') print('3.Multiply') print('4.Divide') select = int(input('Select o...
class Solution: def minMeetingRooms(self, intervals: List[List[int]]) -> int: # first sorting start time and end time # two pointers, one is point to start time list, another point to end time, this means pointer to the first available room starttime = sorted(x[0] for x i...
class Solution: def min_meeting_rooms(self, intervals: List[List[int]]) -> int: starttime = sorted((x[0] for x in intervals)) endtime = sorted((x[1] for x in intervals)) e = 0 roomnum = 0 for i in range(len(starttime)): if starttime[i] < endtime[e]: ...
def simulate(self, gameState, preState, level, R_s, Q_s_a): curAction = gameState.getAgentState(self.index).configuration.direction rev = Directions.REVERSE[curAction] legalActions = gameState.getLegalActions(self.index) legalActions.remove(Directions.STOP) legalActions.remove(rev) #...
def simulate(self, gameState, preState, level, R_s, Q_s_a): cur_action = gameState.getAgentState(self.index).configuration.direction rev = Directions.REVERSE[curAction] legal_actions = gameState.getLegalActions(self.index) legalActions.remove(Directions.STOP) legalActions.remove(rev) suc = self....
nome = str(input('digite seu nome completo :')).strip() n = nome.split() print('prazer em te conhecer!! {}'.format(nome.split()[0].capitalize())) print('seu primeiro nome e {}'.format(nome.split()[0].capitalize())) print('seu ultimo nome e {}'.format(n[len(n) - 1].capitalize())) #eu colei so um pouco na ultima
nome = str(input('digite seu nome completo :')).strip() n = nome.split() print('prazer em te conhecer!! {}'.format(nome.split()[0].capitalize())) print('seu primeiro nome e {}'.format(nome.split()[0].capitalize())) print('seu ultimo nome e {}'.format(n[len(n) - 1].capitalize()))
class AirdropWindowRule: def __init__(self, title, rule): self._title = title self._rule = rule def to_dict(self): return { "airdrop_window_eligibility_title": self._title, "airdrop_window_eligibility_rule": self._rule, }
class Airdropwindowrule: def __init__(self, title, rule): self._title = title self._rule = rule def to_dict(self): return {'airdrop_window_eligibility_title': self._title, 'airdrop_window_eligibility_rule': self._rule}
def setup_tpu(): # Detect hardware, return appropriate distribution strategy try: # TPU detection. No parameters necessary if TPU_NAME environment variable is # set: this is always the case on Kaggle. tpu = tf.distribute.cluster_resolver.TPUClusterResolver() print('Running on TPU...
def setup_tpu(): try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() print('Running on TPU ', tpu.master()) except ValueError: tpu = None if tpu: tf.config.experimental_connect_to_cluster(tpu) tf.tpu.experimental.initialize_tpu_system(tpu) strategy ...
# Classification # This project asks a series of Yes/No questions in order to work out what type of phone the person owns. # Pawel Zabinski class Node: def __init__(self, type, data, yes=None, no=None): # Type may be 'Q' or 'A' ('Q' is for Question, 'A' is for Answer) self.type = type # Data is the que...
class Node: def __init__(self, type, data, yes=None, no=None): self.type = type self.data = data self.yes = yes self.no = no def execute(self): if not self.type == 'Q': return answer = input(f'{self.data} [Yes/No]: ').lower() if answer in ('y...
class MySingleton(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(MySingleton, cls).__new__(cls) cls.number = 10 return cls._instance x = MySingleton() print(x.number) x.number = 20 y = MySingleton() y.number = 3...
class Mysingleton(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(MySingleton, cls).__new__(cls) cls.number = 10 return cls._instance x = my_singleton() print(x.number) x.number = 20 y = my_singleton() y.number = 3...
# BUILTINS # # Write a function named "filter_small_lists" that accepts an iterable # containing lists and returns a list of the lists that have more than two # elements in them. # # Use the "filter" method to do this. # # Test data is at the bottom. # WRITE YOUR CODE HERE # TEST DATA print(filter_small_lists([[1], ...
print(filter_small_lists([[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]])) print(filter_small_lists([]))
__author__ = 'olga.ostapenko' class SessionHelper: def __init__(self, app): self.app = app def login(self, username, password): wd = self.app.wd self.app.open_home_page() wd.find_element_by_id("public_site_login").click() wd.find_element_by_id("login_login").click() ...
__author__ = 'olga.ostapenko' class Sessionhelper: def __init__(self, app): self.app = app def login(self, username, password): wd = self.app.wd self.app.open_home_page() wd.find_element_by_id('public_site_login').click() wd.find_element_by_id('login_login').click() ...
def main(values, key): """ step 1: loop through the list (outer loop) step 2: loop through the list again (inner loop) step 3: check if value in outer loop matches second value in inner loop (don't add number to itself) step 4: if values from different indices add to key, return True step ...
def main(values, key): """ step 1: loop through the list (outer loop) step 2: loop through the list again (inner loop) step 3: check if value in outer loop matches second value in inner loop (don't add number to itself) step 4: if values from different indices add to key, return True step 5...
# -*- coding: utf-8 -*- # # Copyright (C) 2020 CERN. # Copyright (C) 2020 Northwestern University. # # Invenio-Drafts-Resources is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see LICENSE file for more # details. """Invenio-Drafts-Resources Configuration.""" DRAFTS_RES...
"""Invenio-Drafts-Resources Configuration.""" drafts_resources_link_urls = {'record': '{base}/records/{pid}', 'records': '{base}/records/', 'draft': '{base}/records/{pid}/draft/'}
class Solution: def islandPerimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ M, N = len(grid), len(grid[0]) counts = 0 neighbors = 0 for i in range(M): for j in range(N): if grid[i][j] == 1: ...
class Solution: def island_perimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ (m, n) = (len(grid), len(grid[0])) counts = 0 neighbors = 0 for i in range(M): for j in range(N): if grid[i][j] == 1: ...
# Time: O(size(tree)) # Space: O(size(tree)), for recursion stack # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: return self.uti...
class Solution: def is_symmetric(self, root: TreeNode) -> bool: return self.util(root, root) def util(self, root1, root2): if not root1 and (not root2): return True elif root1 and (not root2) or (root2 and (not root1)) or root1.val != root2.val: return False ...
class Node(object): """A node in the suffix tree. suffix_node the index of a node with a matching suffix, representing a suffix link. -1 indicates this node has no suffix link. """ def __init__(self): self.suffix_node = -1 def __repr__(self): return "Node(su...
class Node(object): """A node in the suffix tree. suffix_node the index of a node with a matching suffix, representing a suffix link. -1 indicates this node has no suffix link. """ def __init__(self): self.suffix_node = -1 def __repr__(self): return 'Node(suff...
"""All exceptions for Simple Salesforce""" class SalesforceError(Exception): """Base Salesforce API exception""" message = "Unknown error occurred for {url}. Response content: {content}" def __init__(self, url, status, resource_name, content): """Initialize the SalesforceError exception ...
"""All exceptions for Simple Salesforce""" class Salesforceerror(Exception): """Base Salesforce API exception""" message = 'Unknown error occurred for {url}. Response content: {content}' def __init__(self, url, status, resource_name, content): """Initialize the SalesforceError exception S...
# Question # 36. Write a program to sort a list of integers using bubble sort. # Code a = input("List of integers sep with commas:\n") ints = [int(i.strip()) for i in a.split(",")] # Bubble sorting while True: swaps = False for x in range(len(ints)-1): if ints[x] > ints[x+1]: a, b = ints[x...
a = input('List of integers sep with commas:\n') ints = [int(i.strip()) for i in a.split(',')] while True: swaps = False for x in range(len(ints) - 1): if ints[x] > ints[x + 1]: (a, b) = (ints[x], ints[x + 1]) del ints[x], ints[x] ints.insert(x, b) ints.in...
def rreplace(string, old_str_part, new_str_part, occurrence): split_str = string.rsplit(old_str_part, occurrence) return new_str_part.join(split_str) def rremove(string, str_part, occurrence): split_str = string.rsplit(str_part, occurrence) return split_str[0]
def rreplace(string, old_str_part, new_str_part, occurrence): split_str = string.rsplit(old_str_part, occurrence) return new_str_part.join(split_str) def rremove(string, str_part, occurrence): split_str = string.rsplit(str_part, occurrence) return split_str[0]
# location of local authentication logs to insert to db (update these paths if needed) auth_raw_files = [ '../../dataset/auth_C1DOM1.txt', '../../dataset/auth_C2DOM1.txt', '../../dataset/auth_C3DOM1.txt', '../../dataset/auth_C4DOM1.txt', '../../dataset/auth_C5DOM1.txt', '../../dataset/auth_C6DOM...
auth_raw_files = ['../../dataset/auth_C1DOM1.txt', '../../dataset/auth_C2DOM1.txt', '../../dataset/auth_C3DOM1.txt', '../../dataset/auth_C4DOM1.txt', '../../dataset/auth_C5DOM1.txt', '../../dataset/auth_C6DOM1.txt', '../../dataset/auth_C7DOM1.txt', '../../dataset/auth_ANONYMOUS-LOGONC5828.txt', '../../dataset/auth_ANON...
pkgname = "libmicrodns" pkgver = "0.2.0" pkgrel = 0 build_style = "meson" hostmakedepends = ["meson", "pkgconf"] pkgdesc = "Minimal mDNS resolver library" maintainer = "q66 <q66@chimera-linux.org>" license = "LGPL-2.1-or-later" url = "https://github.com/videolabs/libmicrodns" source = f"{url}/archive/{pkgver}.tar.gz" s...
pkgname = 'libmicrodns' pkgver = '0.2.0' pkgrel = 0 build_style = 'meson' hostmakedepends = ['meson', 'pkgconf'] pkgdesc = 'Minimal mDNS resolver library' maintainer = 'q66 <q66@chimera-linux.org>' license = 'LGPL-2.1-or-later' url = 'https://github.com/videolabs/libmicrodns' source = f'{url}/archive/{pkgver}.tar.gz' s...
class Solution: def countGoodSubstrings(self, s: str) -> int: count = 0 for i in range(len(s)-2): word = s[i:i+3] if(len(set(word))== len(word)): count+=1 return count
class Solution: def count_good_substrings(self, s: str) -> int: count = 0 for i in range(len(s) - 2): word = s[i:i + 3] if len(set(word)) == len(word): count += 1 return count
def get_files(test_name, MAIN_AMB=""): tests = { "swap_endianness_x2": "add", "add_to_swapped": "swap_endianness", "extract": ["#ALL", "#EXCEPT:"+MAIN_AMB], "extract_swapped": "extract", "add_from_dir": "add", "edge_extracted": ["#ALL", "#EXCEPT:files.amb_extracted*"...
def get_files(test_name, MAIN_AMB=''): tests = {'swap_endianness_x2': 'add', 'add_to_swapped': 'swap_endianness', 'extract': ['#ALL', '#EXCEPT:' + MAIN_AMB], 'extract_swapped': 'extract', 'add_from_dir': 'add', 'edge_extracted': ['#ALL', '#EXCEPT:files.amb_extracted*'], 'ml_empty': ['#ALL', '#EXCEPT:mods*'], 'ml_si...
""" Given an array of integers, return True or False if the array has two numbers that add up to a specific target. You may assume that each input would have exactly one solution. Input: [-2, 1, 2, 4, 7, 11], target=13 Output: True (2, 11) """ # Using two pointers (first and last index), assuming array is sorted # Ti...
""" Given an array of integers, return True or False if the array has two numbers that add up to a specific target. You may assume that each input would have exactly one solution. Input: [-2, 1, 2, 4, 7, 11], target=13 Output: True (2, 11) """ def two_sum_subset(nums, target): (i, j) = (0, len(nums) - 1) whil...
def calculate_age(year_of_birth, current_year): delta = current_year - year_of_birth if delta == 0: return "You were born this very year!" year_s = "year" if abs(delta) == 1 else "years" if delta > 0: return "You are {} {} old.".format(delta, year_s) else: return "You...
def calculate_age(year_of_birth, current_year): delta = current_year - year_of_birth if delta == 0: return 'You were born this very year!' year_s = 'year' if abs(delta) == 1 else 'years' if delta > 0: return 'You are {} {} old.'.format(delta, year_s) else: return 'You will be...
# # PySNMP MIB module ACMEPACKET-TC (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ACMEPACKET-TC # Produced by pysmi-0.3.4 at Mon Apr 29 16:57:55 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
(acmepacket,) = mibBuilder.importSymbols('ACMEPACKET-SMI', 'acmepacket') (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_union, v...
## Adding special methods to the student class # We first added the __str__() special method to get a string # representation of our student object, we also added the __len__() # and __repr__() methods, you can code out the __str__() method # to see the __repr__() method in action # The class looked like below at the ...
class Student: def __init__(self, first, last, courses=None): self.first_name = first self.last_name = last if courses == None: self.courses = [] else: self.courses = courses def add_course(self, course): if course not in self.courses: ...
egui_keys = [ "ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp", "Escape", "Tab", "Backspace", "Enter", "Space", "Insert", "Delete", "Home", "End", "PageUp", "PageDown", "Num0", "Num1", "Num2", "Num3", "Num4", "Num5", "Num6", ...
egui_keys = ['ArrowDown', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'Escape', 'Tab', 'Backspace', 'Enter', 'Space', 'Insert', 'Delete', 'Home', 'End', 'PageUp', 'PageDown', 'Num0', 'Num1', 'Num2', 'Num3', 'Num4', 'Num5', 'Num6', 'Num7', 'Num8', 'Num9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', '...
class CustomResponse: """ Defines an object to handle a response from a custom or unknown endpoint. This response class is intended to provide support handling newer endpoints that may not yet be included in the production release of the library. Since this object will built on the fly, a...
class Customresponse: """ Defines an object to handle a response from a custom or unknown endpoint. This response class is intended to provide support handling newer endpoints that may not yet be included in the production release of the library. Since this object will built on the fly, aut...
# V0 class Solution: def tree2str(self, t): if not t: return '' if not t.left and not t.right: return str(t.val) ### NOTICE HERE if not t.left: return str(t.val) + '()' + '(' + self.tree2str(t.right) + ')' ### NOTICE HERE if not t.r...
class Solution: def tree2str(self, t): if not t: return '' if not t.left and (not t.right): return str(t.val) if not t.left: return str(t.val) + '()' + '(' + self.tree2str(t.right) + ')' if not t.right: return str(t.val) + '(' + self.t...
def oldjsonSite(site): return { 'National ID' : site[0].national_id, 'Site Name' : site[0].site_name, 'Agency ID' : site[0].agency_id, 'latitude' : site[0].latitude, 'longitude' : site[0].longitude, 'Agency Name': site[1].name, 'Offe...
def oldjson_site(site): return {'National ID': site[0].national_id, 'Site Name': site[0].site_name, 'Agency ID': site[0].agency_id, 'latitude': site[0].latitude, 'longitude': site[0].longitude, 'Agency Name': site[1].name, 'Offering': site[2].domain_name} def json_site(sites): out = [] for s in sites: ...
var1 = 15 print("Enter a number") var2 = int(input()) if var2>var1: print("Greater") elif var2==var1: print("Equal") else: print("Lesser") # Quiz print("Enter age") age = int(input()) if age>18: print("You can drive") elif age==18: print("We will think about it") else: print("You cannot dri...
var1 = 15 print('Enter a number') var2 = int(input()) if var2 > var1: print('Greater') elif var2 == var1: print('Equal') else: print('Lesser') print('Enter age') age = int(input()) if age > 18: print('You can drive') elif age == 18: print('We will think about it') else: print('You cannot drive')
""" 4C """ def inp(): """ For taking integer inputs. """ return(int(input())) def get_n_strings(n): """ For taking List inputs. """ result = [] i = 0 while i < n: val = input().rstrip("\n") result.append(str(val)) i += 1 return result def problem(n...
""" 4C """ def inp(): """ For taking integer inputs. """ return int(input()) def get_n_strings(n): """ For taking List inputs. """ result = [] i = 0 while i < n: val = input().rstrip('\n') result.append(str(val)) i += 1 return result def problem(n, ...
class Solution: def modifyString(self, s: str) -> str: alphabet = 'abcdefghijklmnopqrstuvwxyz' ret = list('0' + s + '0') for i in range(1, len(ret)-1): if ret[i] == '?': for j in range(26): if alphabet[j] not in {ret[i-1], ret[i+1]}: ret[i] = alphabet[j] bre...
class Solution: def modify_string(self, s: str) -> str: alphabet = 'abcdefghijklmnopqrstuvwxyz' ret = list('0' + s + '0') for i in range(1, len(ret) - 1): if ret[i] == '?': for j in range(26): if alphabet[j] not in {ret[i - 1], ret[i + 1]}: ...
class FightActions: def fight(self, defender): if self.power_level > defender.power_level: defender.hits_point -= self.power_level - defender.power_level elif self.power_level == defender.power_level: print("They are equal in strength!") else: self.hit_poi...
class Fightactions: def fight(self, defender): if self.power_level > defender.power_level: defender.hits_point -= self.power_level - defender.power_level elif self.power_level == defender.power_level: print('They are equal in strength!') else: self.hit_po...
Posts= [{'File': 'images\\0.jpg', 'Title': 'Jose the "bully" #Mourinho #MUFC'}, {'File': 'images\\1.jpg', 'Title': "Former Southampton coach Jason Dodd about Luke Shaw's situation. " '#Shaw #MUFC'}]
posts = [{'File': 'images\\0.jpg', 'Title': 'Jose the "bully" #Mourinho #MUFC'}, {'File': 'images\\1.jpg', 'Title': "Former Southampton coach Jason Dodd about Luke Shaw's situation. #Shaw #MUFC"}]
input = """ 8 2 2 3 0 0 8 2 4 5 0 0 1 1 1 1 4 6 0 1 0 4 1 0 4 c 3 b 2 a 5 d 0 B+ 0 B- 1 0 1 """ output = """ COST 1@1 """
input = '\n8 2 2 3 0 0\n8 2 4 5 0 0\n1 1 1 1 4\n6 0 1 0 4 1\n0\n4 c\n3 b\n2 a\n5 d\n0\nB+\n0\nB-\n1\n0\n1\n' output = '\nCOST 1@1\n'
class Fields: """ Contains the fields that would be validated in the forms when a user is created or updated It also contains if the field can be empty and the functions to be run in order to validate it In case an error occurs, it also contains the error message to be displayed """ field = { ...
class Fields: """ Contains the fields that would be validated in the forms when a user is created or updated It also contains if the field can be empty and the functions to be run in order to validate it In case an error occurs, it also contains the error message to be displayed """ field = {'na...
# LoRa test channel _def_thingspeak_channel_key='SGSH52UGPVAUYG3S' #Note how we can indicate a device source addr that are allowed to use the script #Use decimal between 2-255 and use 4-byte hex format for LoRaWAN devAddr #leave empty to allow all devices #source_list=["6", "7", "01020304"] source_list=[] key_associa...
_def_thingspeak_channel_key = 'SGSH52UGPVAUYG3S' source_list = [] key_association = [] field_association = [] nomenclature_association = []
"""Possible triggers for reading data from a gyroscopes.""" READ_NOT_TRIGGERED = 0 """The read will not be triggered.""" GET_ANGLE_TRIGGER_READ = 1 """Trigger the device read when requesting the angle.""" GET_ANGULAR_VELOCITY_TRIGGER_READ = 2 """Trigger the device read when requesting angular velocity.""" GET_RAW_...
"""Possible triggers for reading data from a gyroscopes.""" read_not_triggered = 0 'The read will not be triggered.' get_angle_trigger_read = 1 'Trigger the device read when requesting the angle.' get_angular_velocity_trigger_read = 2 'Trigger the device read when requesting angular velocity.' get_raw_value_trigger_rea...
#Basic Linear Search # Defines function that searches through array def linearsearch(arr, x): # Passes in target as x, and the array for i in range(len(arr)): # Creates an index for length of array if arr[i] == x: # Compares array value to searched value return i # Returns index return -1 arr = [...
def linearsearch(arr, x): for i in range(len(arr)): if arr[i] == x: return i return -1 arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] x = int(input('Enter a number between 1 and 10: ')) print('element found at index ' + str(linearsearch(arr, x)))
class Solution: # @param {integer[]} nums # @return {integer} def singleNumber(self, nums): ans = 0 for each in nums: ans = ans ^ each; return ans
class Solution: def single_number(self, nums): ans = 0 for each in nums: ans = ans ^ each return ans
x = [12, 15, 14, 5] sum = 0 for i in x: sum += i print(sum)
x = [12, 15, 14, 5] sum = 0 for i in x: sum += i print(sum)
# How to open a file an read the file out file_read = open('../data/text_file_handler.txt', 'r') # Now loop through the file for line in file_read: print(line.strip()) # Close the file otherwise the file is blocked file_read.close() # Now write content in a file file_write = open('../data/write_file_handler.txt'...
file_read = open('../data/text_file_handler.txt', 'r') for line in file_read: print(line.strip()) file_read.close() file_write = open('../data/write_file_handler.txt', 'w') file_write.write('Lorem ipsum dolor sit amet') file_write.close() with open('../data/write_file_handler.txt', 'r') as file: for l in file: ...
TC02_PER_TC = 3.67 TC_PER_TBM = 0.5 TC_PER_TBM_IPCC = {'AGB': 0.47, 'BGB': 0.47, 'dead_wood': 0.47, 'litter': 0.37} SQM_PER_HA = 10000 R = 6.371e6 EMISSIONS_FACTORS = { 'savanna_fire': 1.613, 'tropical_forest_fire': 1.580, 'extratropical_forest_fire': 1.569, }
tc02_per_tc = 3.67 tc_per_tbm = 0.5 tc_per_tbm_ipcc = {'AGB': 0.47, 'BGB': 0.47, 'dead_wood': 0.47, 'litter': 0.37} sqm_per_ha = 10000 r = 6371000.0 emissions_factors = {'savanna_fire': 1.613, 'tropical_forest_fire': 1.58, 'extratropical_forest_fire': 1.569}
def dec_to_bin(num): #my original method was not as nice as this one if num<2: return str(num) else: return dec_to_bin(num//2) + dec_to_bin(num%2) print(dec_to_bin(100000)) #if n gets really big a while loop may be better something along the lines of this # def dec_to_bin(number): # binary = '...
def dec_to_bin(num): if num < 2: return str(num) else: return dec_to_bin(num // 2) + dec_to_bin(num % 2) print(dec_to_bin(100000))
actors = { '002' : 'USA', '020' : 'CAD', '040' : 'CUB', '041' : 'HAI', '042' : 'DOM', '051' : 'JAA', '052' : 'TRI', '070' : 'MEX', '090' : 'GUA', '091' : 'HON', '092' : 'ELS', '093' : 'NIC', '094' : 'COS', '095' : 'PAA', '100' : 'COL', '101' : 'VEN', '...
actors = {'002': 'USA', '020': 'CAD', '040': 'CUB', '041': 'HAI', '042': 'DOM', '051': 'JAA', '052': 'TRI', '070': 'MEX', '090': 'GUA', '091': 'HON', '092': 'ELS', '093': 'NIC', '094': 'COS', '095': 'PAA', '100': 'COL', '101': 'VEN', '110': 'GUY', '130': 'ECU', '135': 'PER', '140': 'BRA', '145': 'BOL', '150': 'PAR', '1...
""" Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). Example 1: Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1. Example 2: Input: [1, 2] Output: 2 Explanation: The third maximum ...
""" Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). Example 1: Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1. Example 2: Input: [1, 2] Output: 2 Explanation: The third maximum ...
""" Given an unsorted integer array, find the first missing positive integer. Example: Given [1,2,0] return 3, [3,4,-1,1] return 2, [-8, -7, -6] returns 1 Your algorithm should run in O(n) time and use constant space. """ class Solution: # @param A : list of integers # @return an integer def firstMis...
""" Given an unsorted integer array, find the first missing positive integer. Example: Given [1,2,0] return 3, [3,4,-1,1] return 2, [-8, -7, -6] returns 1 Your algorithm should run in O(n) time and use constant space. """ class Solution: def first_missing_positive(self, A): temp = [] for i in...
# by Kami Bigdely # Extract class class Person: """Define fields and methods for a person.""" def __init__(self, first_name, last_name, birth_year, movies, email): self.first_name = first_name self.last_name = last_name self.birth_yr = birth_year self.movies = movies s...
class Person: """Define fields and methods for a person.""" def __init__(self, first_name, last_name, birth_year, movies, email): self.first_name = first_name self.last_name = last_name self.birth_yr = birth_year self.movies = movies self.email = email first_names = ['el...
class Solution: def checkPalindromeFormation(self, a: str, b: str) -> bool: """ As long as a prefix == rev(bsuffix) keep forming the split do this (a, b) and (b, a) if any of them are palindromes, then it's true """ i = 0 j = len(a) - 1 while i < j an...
class Solution: def check_palindrome_formation(self, a: str, b: str) -> bool: """ As long as a prefix == rev(bsuffix) keep forming the split do this (a, b) and (b, a) if any of them are palindromes, then it's true """ i = 0 j = len(a) - 1 while i < j ...
def convert(fileInfo): arrays = [] with open(fileInfo["file"]) as file: linecounter = 0 for line in file: arraywidth = 0 linecounter += 1 arr = [] for bit in line: if (bit != "\n"): arr.append(int(bit)) ...
def convert(fileInfo): arrays = [] with open(fileInfo['file']) as file: linecounter = 0 for line in file: arraywidth = 0 linecounter += 1 arr = [] for bit in line: if bit != '\n': arr.append(int(bit)) ...
# -*- coding: utf-8 -*- def int2base(x, b, alphabet='0123456789abcdefghijklmnopqrstuvwxyz'): 'convert an integer to its string representation in a given base' if b < 2 or b > len(alphabet): if b == 64: # assume base64 rather than raise error alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi...
def int2base(x, b, alphabet='0123456789abcdefghijklmnopqrstuvwxyz'): """convert an integer to its string representation in a given base""" if b < 2 or b > len(alphabet): if b == 64: alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' else: raise ...
t = int(input()) for _ in range(t): n, a, b = map(int, input().split()) s = input() total = s.count('0') * a + s.count('1') * b print(total)
t = int(input()) for _ in range(t): (n, a, b) = map(int, input().split()) s = input() total = s.count('0') * a + s.count('1') * b print(total)
# http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_instances # This makes sure there are multiple reservations per simulated page, and # multiple instances in each reservation, and multiple pages. boto3_describe_instances_paginator_one_field = [ { 'Reservations': [ ...
boto3_describe_instances_paginator_one_field = [{'Reservations': [{'Instances': [{'InstanceId': 'instance1'}, {'InstanceId': 'instance2'}]}, {'Instances': [{'InstanceId': 'instance3'}, {'InstanceId': 'instance4'}]}]}, {'Reservations': [{'Instances': [{'InstanceId': 'instance5'}, {'InstanceId': 'instance6'}]}, {'Instanc...
""" Login and password generators """ # WeConnectResources with open('res/pass.dic') as f_pass: content = f_pass.read() password_list = content.split('\n') with open('res/usr.dic') as f_usr: content = f_usr.read() login_list = content.split('\n') def generate_popular_passwords(state): """ We ...
""" Login and password generators """ with open('res/pass.dic') as f_pass: content = f_pass.read() password_list = content.split('\n') with open('res/usr.dic') as f_usr: content = f_usr.read() login_list = content.split('\n') def generate_popular_passwords(state): """ We get the following passw...
def uglify(text): answer = '' even = True for index in range(len(text)): if even: answer += text[index].lower() else: answer += text[index].upper() even = not even return answer if __name__ == '__main__': text = 'Some random text to uglify' prin...
def uglify(text): answer = '' even = True for index in range(len(text)): if even: answer += text[index].lower() else: answer += text[index].upper() even = not even return answer if __name__ == '__main__': text = 'Some random text to uglify' print(u...
class Solution: def isMatch(self, s: 'str', p: 'str') -> 'bool': ls, lp = len(s), len(p) if p == '*' or ls == 0 and lp == 0: return True elif ls == 0 or lp == 0: return False dp = [[False] * (lp + 1) for _ in range(ls + 1)] dp[0][0] = True for ...
class Solution: def is_match(self, s: 'str', p: 'str') -> 'bool': (ls, lp) = (len(s), len(p)) if p == '*' or (ls == 0 and lp == 0): return True elif ls == 0 or lp == 0: return False dp = [[False] * (lp + 1) for _ in range(ls + 1)] dp[0][0] = True ...
conf_l3_agent_ini = """[DEFAULT] # Show debugging output in log (sets DEBUG log level output) # debug = False verbose = True # L3 requires that an interface driver be set. Choose the one that best # matches your plugin. interface_driver = neutron.agent.linux.interface.BridgeInterfaceDriver external_network_bridge = #...
conf_l3_agent_ini = "[DEFAULT]\n# Show debugging output in log (sets DEBUG log level output)\n# debug = False\nverbose = True\n\n# L3 requires that an interface driver be set. Choose the one that best\n# matches your plugin.\ninterface_driver = neutron.agent.linux.interface.BridgeInterfaceDriver\nexternal_network_bridg...
""" Utlity functions to run Ploomber tests. This is not a public module """ def assert_no_extra_attributes_in_class(abstract_class, concrete_class, allowed=None): """ Ploomber makes heavy use of abstract classes to provide a unifo...
""" Utlity functions to run Ploomber tests. This is not a public module """ def assert_no_extra_attributes_in_class(abstract_class, concrete_class, allowed=None): """ Ploomber makes heavy use of abstract classes to provide a uniform API for tasks, products, metadata, etc. When defining abstract classes, th...
# Get inputs a = int(input()) b = int(input()) # Calculate and print result print(a//b) print(a/b)
a = int(input()) b = int(input()) print(a // b) print(a / b)
transprop_perms = \ [ ( 'contact.customer.firstname' , [] ) , ( 'contact.customer.function' , [] ) , ( 'contact.customer.lastname' , [] ) , ( 'contact.customer.lookalike_firstname' , [] ) , ( 'contact.customer.lookalike_function' , [] ) ...
transprop_perms = [('contact.customer.firstname', []), ('contact.customer.function', []), ('contact.customer.lastname', []), ('contact.customer.lookalike_firstname', []), ('contact.customer.lookalike_function', []), ('contact.customer.lookalike_lastname', []), ('issue.composed_of.id', ['admin', 'dom-user-edit-facility'...
class WIM: def __init__(self, output_dict) -> None: for k, v in output_dict.items(): setattr(self, k.replace(' ', '_'), v) def __repr__(self): return '{' + self.Name + ', ' + self.Architecture + ', ' + self.Languages + '}' def __str__(self) -> str: return self.Name ...
class Wim: def __init__(self, output_dict) -> None: for (k, v) in output_dict.items(): setattr(self, k.replace(' ', '_'), v) def __repr__(self): return '{' + self.Name + ', ' + self.Architecture + ', ' + self.Languages + '}' def __str__(self) -> str: return self.Name +...
class BaseDataLoader(): def __init__(self): pass def load_data(): return None def initialize(self, opt): self.opt = opt
class Basedataloader: def __init__(self): pass def load_data(): return None def initialize(self, opt): self.opt = opt
''' lab 7 while loop ''' #3.1 i = 0 while i <=5: if i !=3: print(i) i = i +1 #3.2 i = 1 result =1 while i <=5: result = result *i i + i +1 print(result) #3.3 i = 1 result =0 while i <=5: result = result +i i + i +1 print(result) #3.4 i = 3 result =1 while i <=8: result = resu...
""" lab 7 while loop """ i = 0 while i <= 5: if i != 3: print(i) i = i + 1 i = 1 result = 1 while i <= 5: result = result * i i + i + 1 print(result) i = 1 result = 0 while i <= 5: result = result + i i + i + 1 print(result) i = 3 result = 1 while i <= 8: result = result * i i + ...
""" Today we are gonna learn about tuples and what are the things that we can do about it. A tuple is a ordered sequence of elements, can contain anything elements. AKA. ARRAY? Immutable. You can also go into the tuple by t = (2, 3, 4) t + (6, 8) t[1:2] You can reverse tuple swap variables. (x, y) = (y, x) ""...
""" Today we are gonna learn about tuples and what are the things that we can do about it. A tuple is a ordered sequence of elements, can contain anything elements. AKA. ARRAY? Immutable. You can also go into the tuple by t = (2, 3, 4) t + (6, 8) t[1:2] You can reverse tuple swap variables. (x, y) = (y, x) ""...
#flake8:noqa #PYX START """ // These are cython style comments for maintaining python compatibility cimport numpy as np ctypedef np.float64_t FLOAT64 """ #PYX MAP FLOAT_2D np.ndarray[FLOAT64, ndim=2] #PYX MAP FLOAT_1D np.ndarray[FLOAT64, ndim=1] #PYX END #--- # -------------------------------- # TODO: This is one of t...
""" // These are cython style comments for maintaining python compatibility cimport numpy as np ctypedef np.float64_t FLOAT64 """ @profile def affine_inliers(x1_m, y1_m, invV1_m, fx1_m, x2_m, y2_m, invV2_m, xy_thresh_sqrd, max_scale, min_scale): """Estimates inliers deterministically using elliptical shapes 1_...
POST = "POST" ROOT = "root" SPEC_VERSION = "specVersion" XML_VERSION = "<?xml version=\"1.0\"?>" XML_VERSION_PREFIX = "<?xml version=\"1.0\"" FAULT = "{http://schemas.xmlsoap.org/soap/envelope/}Fault" ENVELOPE = "{http://schemas.xmlsoap.org/soap/envelope/}Envelope" BODY = "{http://schemas.xmlsoap.org/soap/envelope/}Bod...
post = 'POST' root = 'root' spec_version = 'specVersion' xml_version = '<?xml version="1.0"?>' xml_version_prefix = '<?xml version="1.0"' fault = '{http://schemas.xmlsoap.org/soap/envelope/}Fault' envelope = '{http://schemas.xmlsoap.org/soap/envelope/}Envelope' body = '{http://schemas.xmlsoap.org/soap/envelope/}Body' c...
""" Module: 'machine' on M5 FlowUI v1.4.0-beta """ # MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module with ESP32') # Stubber: 1.3.1 class ADC: '' ATTN_0DB = 0 ATTN_11DB = 3 ATTN_2_5DB = 1 ATTN_6DB = 2 HALL = 8 WID...
""" Module: 'machine' on M5 FlowUI v1.4.0-beta """ class Adc: """""" attn_0_db = 0 attn_11_db = 3 attn_2_5_db = 1 attn_6_db = 2 hall = 8 width_10_bit = 1 width_11_bit = 2 width_12_bit = 3 width_9_bit = 0 def atten(): pass def collect(): pass def co...
class DefaultConfigs(object): input_size = 224 lr = 0.01 batch_size = 64 workers = 8 iter_step = 5 gamma = 0.3 train_ratio = 0.2 model = "resnet50" dataset = "sd-198" class_num = 198 epochs = 50 step_size = 40 add_ratios = [0.5, 0.75, 0.9, 1.0, 1.0] config = Default...
class Defaultconfigs(object): input_size = 224 lr = 0.01 batch_size = 64 workers = 8 iter_step = 5 gamma = 0.3 train_ratio = 0.2 model = 'resnet50' dataset = 'sd-198' class_num = 198 epochs = 50 step_size = 40 add_ratios = [0.5, 0.75, 0.9, 1.0, 1.0] config = default_c...
def read_article(file_name): file = open(file_name, "r") file_data = file.readlines() article = file_data[0].split(". ") sentences = [] for sentence in article: print(sentence) sentences.append(sentence.replace("[^a-zA-Z]", " ").split(" ")) sentences.pop() return sentences
def read_article(file_name): file = open(file_name, 'r') file_data = file.readlines() article = file_data[0].split('. ') sentences = [] for sentence in article: print(sentence) sentences.append(sentence.replace('[^a-zA-Z]', ' ').split(' ')) sentences.pop() return sentences
#!/usr/bin/env python3 def merge_dicts(base, update, values=False): merged = dict(base, **update) return list(merged.values()) if values else merged
def merge_dicts(base, update, values=False): merged = dict(base, **update) return list(merged.values()) if values else merged
inicio = 97 for i in range(inicio, inicio + 26): print(str(i) + ' e ' + str(chr(i)))
inicio = 97 for i in range(inicio, inicio + 26): print(str(i) + ' e ' + str(chr(i)))
expected_output = { "binding_table_configuration": { "max/box": "no limit", "max/port": "no limit", "max/vlan": "no limit", "max/mac": "no limit", }, "binding_table_count": { "dynamic": 0, "local": 0, "total": 2, }, "binding_table_state_count":...
expected_output = {'binding_table_configuration': {'max/box': 'no limit', 'max/port': 'no limit', 'max/vlan': 'no limit', 'max/mac': 'no limit'}, 'binding_table_count': {'dynamic': 0, 'local': 0, 'total': 2}, 'binding_table_state_count': {'reachable': 2, 'total': 2}, 'entry_count': 2, 'vlan_id': 38, 'dynamic_count': 0,...
# Define a split_in_two function that accepts a list and a number. # If the number is even, return the list elements from the third element to the end of the list. # If the number is odd, return the list elements from index 0 (inclusive) to 2 (exclusive) # # EXAMPLE: # values = ["a", "b", "c", "d", "e", "f"] # split_in...
values = ['a', 'b', 'c', 'd', 'e', 'f'] def split_in_two(array, number): if number % 2 == 0: return array[2:] return array[:2] print(split_in_two(values, 4)) print(split_in_two(values, 13))
"""Key-Value store server. The request takes "key=" and "value=" URL parameters. The key must be UUID generated by token(). - When only the "key=" is specified, serves a 200 response whose body contains the stored value specified by the key. If the stored value doesn't exist, serves a 200 response with an empty b...
"""Key-Value store server. The request takes "key=" and "value=" URL parameters. The key must be UUID generated by token(). - When only the "key=" is specified, serves a 200 response whose body contains the stored value specified by the key. If the stored value doesn't exist, serves a 200 response with an empty b...
# Problem Name: # Problem Description: #################################### # Sample Input: # Sample Output: #################################### """ Explain the solution: ################## Detailed explanation of the Solution: """ #################################### def solution(self): pass print(solution...
""" Explain the solution: ################## Detailed explanation of the Solution: """ def solution(self): pass print(solution())
{ 'targets': [ { 'target_name': 'build_all', 'type': 'none', 'dependencies': [ 'cppsrc/ImageRankerWrapper/binding.gyp:*', ] } ] }
{'targets': [{'target_name': 'build_all', 'type': 'none', 'dependencies': ['cppsrc/ImageRankerWrapper/binding.gyp:*']}]}
class Solution: def uniquePaths(self, A: int, B: int) -> int: if A==1 or B==1: return 1 if A==2 or B==2: return max(A,B) ans = 1 for i in range(max(A,B), A+B-1): ans *= i ans //= (i-max(A,B)+1) return ans # LC 62 Medium
class Solution: def unique_paths(self, A: int, B: int) -> int: if A == 1 or B == 1: return 1 if A == 2 or B == 2: return max(A, B) ans = 1 for i in range(max(A, B), A + B - 1): ans *= i ans //= i - max(A, B) + 1 return ans
# # [328] Odd Even Linked List # # https://leetcode.com/problems/odd-even-linked-list/description/ # # algorithms # Medium (45.01%) # Total Accepted: 96.2K # Total Submissions: 213.8K # Testcase Example: '[1,2,3,4,5]' # # Given a singly linked list, group all odd nodes together followed by the even # nodes. Please ...
class Solution: def odd_even_list(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head cur = head count = 1 even_head = None odd = None even = None while cur: ...
# Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. # The same number may be chosen from candidates an unlimited number of times. Two combinations are u...
class Solution(object): def combination_sum(self, candidates, target): result = [] unique = {} candidates = list(set(candidates)) self.solve(candidates, target, result, unique) return result def solve(self, candidates, target, result, unique, i=0, current=[]): i...
s=[] def sum_digits(f): s=0 c=str(f) for i in c: s+=int(i) return s for i in range(100): for j in range(100): s.append(sum_digits(i**j)) x=max(s) print("Max is ",x)
s = [] def sum_digits(f): s = 0 c = str(f) for i in c: s += int(i) return s for i in range(100): for j in range(100): s.append(sum_digits(i ** j)) x = max(s) print('Max is ', x)
# 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 # Using Recursion class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: levels = [] ...
class Solution: def level_order_bottom(self, root: TreeNode) -> List[List[int]]: levels = [] if not root: return levels def helper(node, level): if len(levels) == level: levels.append([]) levels[level].append(node.val) if node...
class Settings(): """Game settings class. Sets up in-game parameters and the screen attributes. """ def __init__(self): # Screen parameters: self.screen_width, self.screen_height = 800, 600 self.bg_color = 200, 200, 200 self.scoreboard_height = 50 s...
class Settings: """Game settings class. Sets up in-game parameters and the screen attributes. """ def __init__(self): (self.screen_width, self.screen_height) = (800, 600) self.bg_color = (200, 200, 200) self.scoreboard_height = 50 (self.button_width, self.button_height)...
class NoTradeError(RuntimeError): """ Exception class to raise if no trades are yielded. """ class NotRunError(ValueError): """ Exception class to raise if strategy is not run. """
class Notradeerror(RuntimeError): """ Exception class to raise if no trades are yielded. """ class Notrunerror(ValueError): """ Exception class to raise if strategy is not run. """