content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#!/usr/bin/env python3 # coding:utf-8 class Solution: def GetNumberOfK(self, data, k): if data == [] or k > data[-1]: return 0 left = 0 right = len(data) - 1 while left < right: mid = left + (right - left) // 2 if data[mid] < k: ...
class Solution: def get_number_of_k(self, data, k): if data == [] or k > data[-1]: return 0 left = 0 right = len(data) - 1 while left < right: mid = left + (right - left) // 2 if data[mid] < k: left = mid + 1 else: ...
class FeedFormatter(object): def __init__(self): pass def format(self, contents): # To be overwritten by derived classes pass class PPrintFormatter(FeedFormatter): def __init__(self): super(PPrintFormatter, self).__init__() def format(self, contents): result =...
class Feedformatter(object): def __init__(self): pass def format(self, contents): pass class Pprintformatter(FeedFormatter): def __init__(self): super(PPrintFormatter, self).__init__() def format(self, contents): result = '' for content in contents: ...
class MissingSignerError(Exception): """Raised when the ``signer`` attribute has not been set on an :class:`~flask_pyjwt.manager.AuthManager` object. """ class MissingConfigError(Exception): """Raised when a config value is missing from an :class:`~flask_pyjwt.manager.AuthManager` object. Arg...
class Missingsignererror(Exception): """Raised when the ``signer`` attribute has not been set on an :class:`~flask_pyjwt.manager.AuthManager` object. """ class Missingconfigerror(Exception): """Raised when a config value is missing from an :class:`~flask_pyjwt.manager.AuthManager` object. Args...
class Root(object): @property def greetings(self): return [ Greeting('mundo'), Greeting('world') ] class Greeting(object): def __init__(self, person): self.person = person
class Root(object): @property def greetings(self): return [greeting('mundo'), greeting('world')] class Greeting(object): def __init__(self, person): self.person = person
def _rec(origin, l1, target, l2): if not l1: return l2 elif not l2: return l1 a1 = _rec(origin, l1-1, target, l2) + 1 a2 = _rec(origin, l1, target, l2-1) + 1 a3 = _rec(origin, l1-1, target, l2-1) + \ (origin[l1 - 1] != target[l2 - 1]) return min(a1, a2, a3) ...
def _rec(origin, l1, target, l2): if not l1: return l2 elif not l2: return l1 a1 = _rec(origin, l1 - 1, target, l2) + 1 a2 = _rec(origin, l1, target, l2 - 1) + 1 a3 = _rec(origin, l1 - 1, target, l2 - 1) + (origin[l1 - 1] != target[l2 - 1]) return min(a1, a2, a3) def levenstein_...
fichier = open("Rosetta/main/source/src/apps.src.settings","r") commands = fichier.readlines() fichier.close() commands = commands[:-1] + [" 'cifparse',\n"] + [commands[-1]] fichier = open("Rosetta/main/source/src/apps.src.settings","w") fichier.writelines(commands) fichier.close()
fichier = open('Rosetta/main/source/src/apps.src.settings', 'r') commands = fichier.readlines() fichier.close() commands = commands[:-1] + ["\t'cifparse',\n"] + [commands[-1]] fichier = open('Rosetta/main/source/src/apps.src.settings', 'w') fichier.writelines(commands) fichier.close()
project = "Textstat" master_doc = 'index' extensions = ['releases'] releases_github_path = 'shivam5992/textstat' releases_unstable_prehistory = True html_theme = 'alabaster' templates_path = [ '_templates', ] html_sidebars = { '**': [ 'about.html', 'navigation.html', 'relations.htm...
project = 'Textstat' master_doc = 'index' extensions = ['releases'] releases_github_path = 'shivam5992/textstat' releases_unstable_prehistory = True html_theme = 'alabaster' templates_path = ['_templates'] html_sidebars = {'**': ['about.html', 'navigation.html', 'relations.html', 'searchbox.html', 'contribute.html']} h...
"""week 8 warmup exercises and videos """ iso = {1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat', 7: 'Sun'} counts = {} for key in iso: counts[iso[key]] = 0 print(counts) def who_has_s(d, s): for keys in d.keys(): for values in s.values(): if 's' in values:...
"""week 8 warmup exercises and videos """ iso = {1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat', 7: 'Sun'} counts = {} for key in iso: counts[iso[key]] = 0 print(counts) def who_has_s(d, s): for keys in d.keys(): for values in s.values(): if 's' in values: return...
# # PySNMP MIB module ROHC-RTP-MIB (http://pysnmp.sf.net) # ASN.1 source http://mibs.snmplabs.com:80/asn1/ROHC-RTP-MIB # Produced by pysmi-0.0.7 at Sun Feb 14 00:27:06 2016 # On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose # Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52) # ( Ob...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, constraints_intersection, value_size_constraint, constraints_union) ...
name = 'help' cmdhelp = 'Display help' ### def init_parser(parser): return def main(cnsapp, args): '''Stub that actually does nothing''' pass
name = 'help' cmdhelp = 'Display help' def init_parser(parser): return def main(cnsapp, args): """Stub that actually does nothing""" pass
config = {} def process_adapter_message(message): type = message.get("type", None) if type == "initialize": return __initialize__() elif type == "set_state": return __set_state__(message) return { "type": "exception.not_supported", "origin_type": type } def __in...
config = {} def process_adapter_message(message): type = message.get('type', None) if type == 'initialize': return __initialize__() elif type == 'set_state': return __set_state__(message) return {'type': 'exception.not_supported', 'origin_type': type} def __initialize__(): return {...
def exposify(cls): # cls.__dict__ does not include inherited members, so we can't use that. for key in dir(cls): val = getattr(cls, key) if callable(val) and not key.startswith("_"): setattr(cls, "exposed_%s" % (key,), val) return cls class Singleton: """ A non-thread-safe helper class to ease implementi...
def exposify(cls): for key in dir(cls): val = getattr(cls, key) if callable(val) and (not key.startswith('_')): setattr(cls, 'exposed_%s' % (key,), val) return cls class Singleton: """ A non-thread-safe helper class to ease implementing singletons. This should be used as a dec...
""" Space : O(1) Time : O(n) """ class Solution: def maxDepth(self, s: str) -> int: n = len(s) if n == 0: return 0 max_dep, dep = 0, 0 for i in range(n): if s[i] == '(': dep += 1 max_dep = max(max_dep, dep) ...
""" Space : O(1) Time : O(n) """ class Solution: def max_depth(self, s: str) -> int: n = len(s) if n == 0: return 0 (max_dep, dep) = (0, 0) for i in range(n): if s[i] == '(': dep += 1 max_dep = max(max_dep, dep) ...
# Where You Came From [Kaiser] (25808) recoveredMemory = 7081 sm.flipDialoguePlayerAsSpeaker() sm.sendNext("Memories... Memories from when? When I became Kaiser?") sm.sendSay("No, that's not good enough. Tear... Velderoth... " "We were young and naive, but we believed. That was my beginning. " "That was when I learne...
recovered_memory = 7081 sm.flipDialoguePlayerAsSpeaker() sm.sendNext('Memories... Memories from when? When I became Kaiser?') sm.sendSay("No, that's not good enough. Tear... Velderoth... We were young and naive, but we believed. That was my beginning. That was when I learned to fight for what I loved.") sm.sendSay("May...
# use functions to break down the code def create_matrix(rows): result = [] for _ in range(rows): result.append(input().split()) return result def in_range(indices, rows_range, columns_range): is_in_range = True r_1, c_1, r_2, c_2 = indices if not r_1 in rows_range or not r_2 in rows_ra...
def create_matrix(rows): result = [] for _ in range(rows): result.append(input().split()) return result def in_range(indices, rows_range, columns_range): is_in_range = True (r_1, c_1, r_2, c_2) = indices if not r_1 in rows_range or not r_2 in rows_range: is_in_range = False ...
# # file: power_of_ten.py # # Report if the input is a power of ten and, if so, its exponent. # # Pipe the output of primes10.frac to this program to see the progression # of 10**prime. # # RTK, 05-Apr-2021 # Last update: 05-Apr-2021 # ################################################################ def isPo...
def is_power_of_ten(d): s = str(d) z = s.count('0') p = len(s) - 1 return (s[0] == '1' and z == p, p) while True: try: d = int(input()) except: exit(0) (ok, p) = is_power_of_ten(d) if ok: print('10**%d' % (p,), flush=True)
def binary_search(arr, val): min = 0 max = len(arr) - 1 while True: if max < min: return -1 mid = (min + max) // 2 if arr[mid] < val: min = mid + 1 elif arr[mid] > val: max = mid - 1 else: return mid
def binary_search(arr, val): min = 0 max = len(arr) - 1 while True: if max < min: return -1 mid = (min + max) // 2 if arr[mid] < val: min = mid + 1 elif arr[mid] > val: max = mid - 1 else: return mid
# Copyright 2018 Minds.ai, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
class Driveapiexception(Exception): def __init__(self, name: str, reason: str): """Initializes object for containing information about an exception or error with the Google Drive API or its defined interface. :param name: Name of the error. :param reason: Reason for error. """ supe...
MAX_SIZE = 71 MAX_NUMBER = 2**32 matrix = [[0 for _ in range(MAX_SIZE)] for _ in range(MAX_SIZE)] for i in range(MAX_SIZE): matrix[i][0] = 1 matrix[1][i] = 1 for i in range(2, MAX_SIZE): for j in range(1, MAX_SIZE): sum = matrix[i][j-1] + matrix[i-1][j] matrix[i][j] = sum if sum < MAX_NUM...
max_size = 71 max_number = 2 ** 32 matrix = [[0 for _ in range(MAX_SIZE)] for _ in range(MAX_SIZE)] for i in range(MAX_SIZE): matrix[i][0] = 1 matrix[1][i] = 1 for i in range(2, MAX_SIZE): for j in range(1, MAX_SIZE): sum = matrix[i][j - 1] + matrix[i - 1][j] matrix[i][j] = sum if sum < MAX_...
class Control(object): def __init__(self, states, start_state): states = {str(x): x for x in states} self.done = False self.states = states self.state_name = start_state self.state = self.states[self.state_name] self.state.startup() def update(self): if s...
class Control(object): def __init__(self, states, start_state): states = {str(x): x for x in states} self.done = False self.states = states self.state_name = start_state self.state = self.states[self.state_name] self.state.startup() def update(self): if ...
# Copyright (C) 2005 Michael Urman # # This program is free software; you can redistribute it and/or modify # it under the terms of version 2 of the GNU General Public License as # published by the Free Software Foundation. class Metadata(object): """An abstract dict-like object. Metadata is the base class ...
class Metadata(object): """An abstract dict-like object. Metadata is the base class for many of the tag objects in Mutagen. """ __module__ = 'mutagen' def __init__(self, *args, **kwargs): if args or kwargs: self.load(*args, **kwargs) def load(self, *args, **kwargs): ...
class DLinkedList: def __init__(self, def_value='B'): self.default_val = def_value self.curr = Node(val=self.default_val) @property def data(self): return self.curr.value @data.setter def data(self, val): self.curr.value = val def get_to_left_end(self): ...
class Dlinkedlist: def __init__(self, def_value='B'): self.default_val = def_value self.curr = node(val=self.default_val) @property def data(self): return self.curr.value @data.setter def data(self, val): self.curr.value = val def get_to_left_end(self): ...
class APIKeyMiddleware(object): """ A simple middleware to pull the users API key from the headers and attach it to the request. It should be compatible with both old and new style middleware. """ def __init__(self, get_response=None): self.get_response = get_response ...
class Apikeymiddleware(object): """ A simple middleware to pull the users API key from the headers and attach it to the request. It should be compatible with both old and new style middleware. """ def __init__(self, get_response=None): self.get_response = get_response ...
# coding=utf-8 """ ValueRef and LogicalBase classes """ class ValueRef(object): """ ValueRef abstract class """ def prepare_to_store(self, storage): """ Will be implemented :param storage: """ pass @staticmethod def referent_to_string(referent): ...
""" ValueRef and LogicalBase classes """ class Valueref(object): """ ValueRef abstract class """ def prepare_to_store(self, storage): """ Will be implemented :param storage: """ pass @staticmethod def referent_to_string(referent): """ Si...
def heapify(array, current, heap_size): left = 2 * current + 1 right = 2 * current + 2 if left <= heap_size and array[left] > array[current]: largest = left else: largest = current if right <= heap_size and array[right] > array[largest]: largest = right if largest != cu...
def heapify(array, current, heap_size): left = 2 * current + 1 right = 2 * current + 2 if left <= heap_size and array[left] > array[current]: largest = left else: largest = current if right <= heap_size and array[right] > array[largest]: largest = right if largest != curr...
global variables, localspace if str(variables.get("DOCKER_ENABLED")).lower() == 'true': # Be aware, that the prefix command is internally split by spaces. So paths with spaces won't work. # Prepare Docker parameters containerName = variables.get("DOCKER_IMAGE") dockerRunCommand = 'docker run ' dock...
global variables, localspace if str(variables.get('DOCKER_ENABLED')).lower() == 'true': container_name = variables.get('DOCKER_IMAGE') docker_run_command = 'docker run ' docker_parameters = '--rm ' pa_home_host = variables.get('PA_SCHEDULER_HOME') pa_home_container = variables.get('PA_SCHEDULER_HOME...
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate...
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthres...
class Cart: turn_list = ["<", "|", ">"] directions = {"left":"<", "right":">", "upp":"^", "down":"v"} def __init__(self, x, y, direction): self.x = x self.y = y self.direction = direction self.cross_count = 0 self.crashed = False def __lt__(self, other): ...
class Cart: turn_list = ['<', '|', '>'] directions = {'left': '<', 'right': '>', 'upp': '^', 'down': 'v'} def __init__(self, x, y, direction): self.x = x self.y = y self.direction = direction self.cross_count = 0 self.crashed = False def __lt__(self, other): ...
try: with open('input.txt', 'r') as myinputfile: print('how about here?') for line in myinputfile: print(line) except FileNotFoundError: print('That file does not exist') print('Execution never gets here')
try: with open('input.txt', 'r') as myinputfile: print('how about here?') for line in myinputfile: print(line) except FileNotFoundError: print('That file does not exist') print('Execution never gets here')
class SearchaniseException(Exception): def __init__(self, message): super(SearchaniseException, self).__init__(message) class PSAWException(Exception): def __init__(self, message): super(PSAWException, self).__init__(message)
class Searchaniseexception(Exception): def __init__(self, message): super(SearchaniseException, self).__init__(message) class Psawexception(Exception): def __init__(self, message): super(PSAWException, self).__init__(message)
# Copyright (C) 2019 GreenWaves Technologies # All rights reserved. # This software may be modified and distributed under the terms # of the BSD license. See the LICENSE file for details. quote = lambda s: '"'+s+'"' class CodeBlock(): def __init__(self, starting_indent=0, indent_char=" "): self._inde...
quote = lambda s: '"' + s + '"' class Codeblock: def __init__(self, starting_indent=0, indent_char=' '): self._indent = starting_indent self._indent_char = indent_char self._lines = [] def indent(self): self._indent += 1 return self def deindent(self): ...
class Solution(object): def computeArea(self, A, B, C, D, E, F, G, H): """ :type A: int :type B: int :type C: int :type D: int :type E: int :type F: int :type G: int :type H: int :rtype: int """ overlap = max(min(C, G) -...
class Solution(object): def compute_area(self, A, B, C, D, E, F, G, H): """ :type A: int :type B: int :type C: int :type D: int :type E: int :type F: int :type G: int :type H: int :rtype: int """ overlap = max(min(C, G)...
# # def minRemoveToMakeValid(s): """ :type s: str :rtype: str """ opens, closes = [], [] for i in range(len(s)): c = s[i] if c == '(': opens.append(i) elif c == ')': if len(opens) == 0: closes.append(i) else: ...
def min_remove_to_make_valid(s): """ :type s: str :rtype: str """ (opens, closes) = ([], []) for i in range(len(s)): c = s[i] if c == '(': opens.append(i) elif c == ')': if len(opens) == 0: closes.append(i) else: ...
def minSwaps(arr): count = 0 for i in range(len(arr)): val = arr[i] if val == i + 1: continue for j in range(i + 1, len(arr)): if arr[j] != i+1: continue arr[i] = arr[j] arr[j] = val count += 1 return count
def min_swaps(arr): count = 0 for i in range(len(arr)): val = arr[i] if val == i + 1: continue for j in range(i + 1, len(arr)): if arr[j] != i + 1: continue arr[i] = arr[j] arr[j] = val count += 1 return coun...
def log(parser,logic,logging,args=0): if args: options = args.keys() if "freq" in options: try: sec = int(args["freq"][0]) logging.freq = sec except: parser.print("-freq: "+str(args["freq"][0])+" could not cast to integer") ...
def log(parser, logic, logging, args=0): if args: options = args.keys() if 'freq' in options: try: sec = int(args['freq'][0]) logging.freq = sec except: parser.print('-freq: ' + str(args['freq'][0]) + ' could not cast to integer...
''' Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left ...
""" Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left ...
#!/usr/bin/env python # -*- coding:utf-8 -*- def binary_search(mylist, item): low = 0 high = len(mylist) - 1 while low <= high: mid = int((low + high) / 2) guess = mylist[mid] if guess == item: return mid if guess > item: high = mid - 1 else...
def binary_search(mylist, item): low = 0 high = len(mylist) - 1 while low <= high: mid = int((low + high) / 2) guess = mylist[mid] if guess == item: return mid if guess > item: high = mid - 1 else: low = mid + 1 return None myli...
number = 1024 # using map() to separate each element and store it in a list digit_list = list(map(int, str(number))) print(digit_list) # Using list comprehension digit_list2 = [int(a) for a in str(number)] print(digit_list2) # Simplest approach digit_list3 = list(str(number)) print(digit_list3)
number = 1024 digit_list = list(map(int, str(number))) print(digit_list) digit_list2 = [int(a) for a in str(number)] print(digit_list2) digit_list3 = list(str(number)) print(digit_list3)
#quiz2 print("convercion de monedad") """ Dolar: 1USD EUR: 1USD =0.8965 EUR YEN: 1USD =101.5744 YEN BP: 1USD = 0.7702 BP MXN: 1USD = 19.7843 """ print("Introduce la cantidad de monedas que deseas convertir ") i= int(input("valor monetario en centavos:")) Dolar= i/100 print(str(Dolar) + "dolares") EUR= Dolar*0.8965 p...
print('convercion de monedad') '\nDolar: 1USD\nEUR: 1USD =0.8965 EUR\nYEN: 1USD =101.5744 YEN\nBP: 1USD = 0.7702 BP\nMXN: 1USD = 19.7843\n' print('Introduce la cantidad de monedas que deseas convertir ') i = int(input('valor monetario en centavos:')) dolar = i / 100 print(str(Dolar) + 'dolares') eur = Dolar * 0.8965 pr...
# -*- coding: utf-8 -*- myName = input("Please enter your name: ") myAge = input("What about your age: ") print ("Hello World, my name is", myName, "and I am", myAge, "years old.") print ('''Hello World. My name is James and I am 20 years old.''')
my_name = input('Please enter your name: ') my_age = input('What about your age: ') print('Hello World, my name is', myName, 'and I am', myAge, 'years old.') print('Hello World.\nMy name is James and\nI am 20 years old.')
# -*- coding: utf-8 -*- """ Created on Mon Feb 1 14:22:58 2021 @author: NOTEBOOK """ class BankAccount(): #The __init__ method accepts an arguement for the account's balance. #It is assigned to the__balance attribute. def __init__(self, bal): self.__balance = bal #The deposit ,m...
""" Created on Mon Feb 1 14:22:58 2021 @author: NOTEBOOK """ class Bankaccount: def __init__(self, bal): self.__balance = bal def deposit(self, amount): self.__balance += amount def withdraw(self, amount): if self.__balance >= amount: self.__balance -= amount ...
# coding=utf-8 class Thumb(object): _engine = None def __init__(self, url='', key=None, fullpath=None): self.url = url self.key = key self.fullpath = fullpath def __nonzero__(self): return bool(self.url) def __bool__(self): return bool(self.url) def as_...
class Thumb(object): _engine = None def __init__(self, url='', key=None, fullpath=None): self.url = url self.key = key self.fullpath = fullpath def __nonzero__(self): return bool(self.url) def __bool__(self): return bool(self.url) def as_dict(self): ...
"""This problem was asked by Google. Implement a PrefixMapSum class with the following methods: insert(key: str, value: int): Set a given key's value in the map. If the key already exists, overwrite the value. sum(prefix: str): Return the sum of all values of keys that begin with a given prefix. For example, you s...
"""This problem was asked by Google. Implement a PrefixMapSum class with the following methods: insert(key: str, value: int): Set a given key's value in the map. If the key already exists, overwrite the value. sum(prefix: str): Return the sum of all values of keys that begin with a given prefix. For example, you s...
def lengthOfLongestSubstring(s: str) -> int: left = length = 0 visited = dict() for pos, char in enumerate(s): if char in visited and visited[char] >= left: left = visited[char] + 1 else: length = max(length, pos - left + 1) visited[char] = pos retur...
def length_of_longest_substring(s: str) -> int: left = length = 0 visited = dict() for (pos, char) in enumerate(s): if char in visited and visited[char] >= left: left = visited[char] + 1 else: length = max(length, pos - left + 1) visited[char] = pos return...
# 1. Greeting print("Welcome to Jeon's blind auction program!") print( "&& Rule: In the blind auction, if there are identical bid with one item, the winner is the first person who input his/her bid!" ) # 2. Ask name bid_log_dictionary = {} # 2-1. Creat function that checks if it is a valid name def name_check(na...
print("Welcome to Jeon's blind auction program!") print('&& Rule: In the blind auction, if there are identical bid with one item, the winner is the first person who input his/her bid!') bid_log_dictionary = {} def name_check(name): name_check = list(name) while '.' in name_check: name_check.remove('.')...
# # PySNMP MIB module DIAL-CONTROL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DIAL-CONTROL-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 16:52:54 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_union, single_value_constraint, value_size_constraint, constraints_intersection) ...
# This file is responsible for validating if a action is valid def how_may_of(dices): # Find out how many values there are for a number out = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0} for dice in dices: out[dice.value] += 1 return out def check(dices, settings): dices = sorted(dices, key=lamb...
def how_may_of(dices): out = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0} for dice in dices: out[dice.value] += 1 return out def check(dices, settings): dices = sorted(dices, key=lambda dice: dice.value) amount_of = how_may_of(dices) validation = {'aces': None, 'twos': None, 'threes': None, 'fo...
# -*- coding: utf-8 -*- """ Created on Mon Jan 18 08:52:57 2016 @author: Stella """
""" Created on Mon Jan 18 08:52:57 2016 @author: Stella """
class User: userList = [] def __init__(self, fname, lname, username, pwd): """ _init_ methods that help us define properties for our new user object Args: fname: New user first name lname: New user last name username: new Username pwd: New user password ...
class User: user_list = [] def __init__(self, fname, lname, username, pwd): """ _init_ methods that help us define properties for our new user object Args: fname: New user first name lname: New user last name username: new Username pwd: New user pass...
# -*- coding: utf-8 -*- def index(): redirect(URL(c='default', f='index')) def show_products(): if request.vars.category: product_list = db(db.product.default_category == request.vars.categor...
def index(): redirect(url(c='default', f='index')) def show_products(): if request.vars.category: product_list = db(db.product.default_category == request.vars.category).select(limitby=(0, 20), orderby=db.product.name) else: product_list = db(db.product).select(limitby=(0, 20), orderby=~db....
def to_range(s): a, b = s.split("-") a, b = int(a), int(b) return lambda x: x >= a and x <= b def parse_rule(line): key, values = line.split(":") rules = list(map(to_range, values.split("or"))) return ( key.strip(), lambda foo: any(map(lambda rule: rule(foo), rules)), ) d...
def to_range(s): (a, b) = s.split('-') (a, b) = (int(a), int(b)) return lambda x: x >= a and x <= b def parse_rule(line): (key, values) = line.split(':') rules = list(map(to_range, values.split('or'))) return (key.strip(), lambda foo: any(map(lambda rule: rule(foo), rules))) def parse_ticket(l...
#!/usr/bin/env python3 print(50 + 50) # add print (50 - 50) # subtract print(50 * 50) # multiply print( 50 / 50) #divide print (50 + 50 - 50 * 50 / 50) # PEMDAS print (50 ** 2) #raising to power. exponents print (50 % 6) #modulo, get remainder print( 50 // 6) # divides w/ no remainder
print(50 + 50) print(50 - 50) print(50 * 50) print(50 / 50) print(50 + 50 - 50 * 50 / 50) print(50 ** 2) print(50 % 6) print(50 // 6)
""" Macros for defining toolchains. See https://docs.bazel.build/versions/master/skylark/deploying.html#registering-toolchains """ load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kotlin_repositories", "kt_register_toolchains") load("@rules_java//java:repositories.bzl", "remote_jdk11_repos") load("@rules_jvm_externa...
""" Macros for defining toolchains. See https://docs.bazel.build/versions/master/skylark/deploying.html#registering-toolchains """ load('@io_bazel_rules_kotlin//kotlin:kotlin.bzl', 'kotlin_repositories', 'kt_register_toolchains') load('@rules_java//java:repositories.bzl', 'remote_jdk11_repos') load('@rules_jvm_external...
""" TRACK 3 Ask a user to write a short bio about themselves. Sanitize the input making sure that there are no extra spaces at the beginning and at the end of the string. Sanitize further the string, making sure that all the words are single spaced from one another using `.split()` and `.join()`. Use `.count()` to det...
""" TRACK 3 Ask a user to write a short bio about themselves. Sanitize the input making sure that there are no extra spaces at the beginning and at the end of the string. Sanitize further the string, making sure that all the words are single spaced from one another using `.split()` and `.join()`. Use `.count()` to det...
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
""" Define the command 'print_struct_c99' for gdb, useful for creating a literal for a nested runtime struct. Example use: (gdb) source source/tools/utils/gdb_struct_repr_c99.py (gdb) print_struct_c99 scene->toolsettings """ class Printstructc99(gdb.Command): def __init__(self): super(PrintStructC...
def convert_to_numeric(score): """ Convert the score to a numerical type. """ converted_score = float(score) return converted_score def sum_of_middle_three(score1, score2, score3, score4, score5): """ Return sum of 3 middle scores """ min_score = min(score1, score2, score3, score4, ...
def convert_to_numeric(score): """ Convert the score to a numerical type. """ converted_score = float(score) return converted_score def sum_of_middle_three(score1, score2, score3, score4, score5): """ Return sum of 3 middle scores """ min_score = min(score1, score2, score3, score4, ...
example = """ start-A start-b A-c A-b b-d A-end b-end """.strip() f = open("input/12.input") text = f.read().strip() def parse(t): graph = {} for line in t.split("\n"): left, right = line.split('-') if left not in graph: graph[left] = set() if right not in graph: ...
example = '\nstart-A\nstart-b\nA-c\nA-b\nb-d\nA-end\nb-end\n'.strip() f = open('input/12.input') text = f.read().strip() def parse(t): graph = {} for line in t.split('\n'): (left, right) = line.split('-') if left not in graph: graph[left] = set() if right not in graph: ...
# -*- coding: utf-8 -*- def get_config(): """Get default configuration credentials.""" return { "firewall": { "interface": "", "inbound_IPRule": { "action": "0", "ip_inbound": "" }, "outbound_IPRule": { "action": "0", "ip_outbound": "" }, "p...
def get_config(): """Get default configuration credentials.""" return {'firewall': {'interface': '', 'inbound_IPRule': {'action': '0', 'ip_inbound': ''}, 'outbound_IPRule': {'action': '0', 'ip_outbound': ''}, 'protocolRule': {'action': '0', 'protocols': 'ICMP'}, 'scanLoad': {'action': '0', 'extensions': '.exe'}...
# # @lc app=leetcode.cn id=1283 lang=python3 # # [1283] reformat-date # None # @lc code=end
None
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( n ) : count = 0 ; curr = 19 ; while ( True ) : sum = 0 ; x = curr ; while ( x >...
def f_gold(n): count = 0 curr = 19 while True: sum = 0 x = curr while x > 0: sum = sum + x % 10 x = int(x / 10) if sum == 10: count += 1 if count == n: return curr curr += 9 return -1 if __name__ == '__main__...
types = { "_car_way": "motorway|motorway_link|primary|primary_link|secondary|secondary_link|tertiary|tertiary_link|residential|living_street|service_road|unclassified", "_pedestrian_way": "footway|steps|path|track|pedestrian_street", "address_housenumber": '["addr:housenumber"]', "address_street": '["ad...
types = {'_car_way': 'motorway|motorway_link|primary|primary_link|secondary|secondary_link|tertiary|tertiary_link|residential|living_street|service_road|unclassified', '_pedestrian_way': 'footway|steps|path|track|pedestrian_street', 'address_housenumber': '["addr:housenumber"]', 'address_street': '["addr:street"]', 'at...
class Solution: def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int: modulo = 10 ** 9 + 7 # (efficiency, speed) metrics = zip(efficiency, speed) metrics = sorted(metrics, key=lambda t:t[0], reverse=True) speed_heap = [] speed_sum...
class Solution: def max_performance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int: modulo = 10 ** 9 + 7 metrics = zip(efficiency, speed) metrics = sorted(metrics, key=lambda t: t[0], reverse=True) speed_heap = [] (speed_sum, perf) = (0, 0) for...
point_dict = {} class face_c: def __init__(self, data_string) -> None: # data string is in format "p1,p2,p3" data = data_string.split(",") self.points = [point_dict[p] for p in data] def __repr__(self) -> str: result = "\nfacet normal 0 0 0\n\touter loop" for point in ...
point_dict = {} class Face_C: def __init__(self, data_string) -> None: data = data_string.split(',') self.points = [point_dict[p] for p in data] def __repr__(self) -> str: result = '\nfacet normal 0 0 0\n\touter loop' for point in self.points: result += f'\n\t\tver...
# # PySNMP MIB module VMWARE-CIMOM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VMWARE-CIMOM-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:34:48 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, constraints_intersection, value_range_constraint, constraints_union) ...
class Solution: def smallestRangeI(self, nums: List[int], k: int) -> int: a = min(nums) b = max(nums) return max(b - a - 2 * k, 0)
class Solution: def smallest_range_i(self, nums: List[int], k: int) -> int: a = min(nums) b = max(nums) return max(b - a - 2 * k, 0)
# Number Spiral diagonals def indexed_odd_number(num): counter = 0 while num != 1: num -= 2 counter += 1 return counter spiral_dimension = 1001 sum_diagonals = 1 temp_num = 1 for i in range(indexed_odd_number(spiral_dimension)): for j in range(4): temp_num += ...
def indexed_odd_number(num): counter = 0 while num != 1: num -= 2 counter += 1 return counter spiral_dimension = 1001 sum_diagonals = 1 temp_num = 1 for i in range(indexed_odd_number(spiral_dimension)): for j in range(4): temp_num += 2 * (i + 1) sum_diagonals += temp_num ...
''' Created on Jun 6, 2019 @author: Winterberger ''' class Menu: def __init__(self, name, items, start_time, end_time): ''' print(name + " is served from %d to %d." % (start_time, end_time)) ''' self.name = name self.items = items self.start_time = start_...
""" Created on Jun 6, 2019 @author: Winterberger """ class Menu: def __init__(self, name, items, start_time, end_time): """ print(name + " is served from %d to %d." % (start_time, end_time)) """ self.name = name self.items = items self.start_time = start_time ...
""" 0059. Spiral Matrix II Medium Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. Example 1: Input: n = 3 Output: [[1,2,3],[8,9,4],[7,6,5]] Example 2: Input: n = 1 Output: [[1]] Constraints: 1 <= n <= 20 """ class Solution: def generateMatrix(self, n:...
""" 0059. Spiral Matrix II Medium Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. Example 1: Input: n = 3 Output: [[1,2,3],[8,9,4],[7,6,5]] Example 2: Input: n = 1 Output: [[1]] Constraints: 1 <= n <= 20 """ class Solution: def generate_matrix(self,...
# # PySNMP MIB module HUAWEI-MC-TRUNK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-MC-TRUNK-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:34:48 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint) ...
class MyHashSet: def __init__(self): """ Initialize your data structure here. """ self.set = [0] * 1000001 def add(self, key: int) -> None: """Running time: O(1) """ self.set[key] = 1 def remove(self, key: int) -> None: """...
class Myhashset: def __init__(self): """ Initialize your data structure here. """ self.set = [0] * 1000001 def add(self, key: int) -> None: """Running time: O(1) """ self.set[key] = 1 def remove(self, key: int) -> None: """Running time: O(1)...
_base_ = [ '../_base_/datasets/kitti.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_cos20x.py' ] model = dict( type = 'Adabins', # model training and testing settings max_val=80, train_cfg=dict(), test_cfg=dict(mode='whole')) find_unused_parameters=True
_base_ = ['../_base_/datasets/kitti.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_cos20x.py'] model = dict(type='Adabins', max_val=80, train_cfg=dict(), test_cfg=dict(mode='whole')) find_unused_parameters = True
class Communicator: def __init__(self, nid, n_delay, in_lim, out_lim, out_conns): self.ins =set() # self.ordered_outs = out_conns self.outs = set(out_conns) self.id = nid self.node_delay = n_delay self.in_lim = in_lim self.out_lim = out_lim ...
class Communicator: def __init__(self, nid, n_delay, in_lim, out_lim, out_conns): self.ins = set() self.outs = set(out_conns) self.id = nid self.node_delay = n_delay self.in_lim = in_lim self.out_lim = out_lim def get_peers(self): return self.outs | self...
class User: user_list =[] ''' class that defines user blueprint ''' def __init__(self,username,password,email): self.username = username self.password = password self.email = email def save_user(self): ''' function that saves new user objects ''' User.user_list.append(self) ...
class User: user_list = [] '\n class that defines user blueprint\n ' def __init__(self, username, password, email): self.username = username self.password = password self.email = email def save_user(self): """ function that saves new user objects """ U...
#!/usr/bin/env python head_joints = [ 'head_sidetilt_joint', 'head_pan_joint', 'head_tilt_joint', ] right_arm_joints = [ 'right_arm_shoulder_rotate_joint', 'right_arm_shoulder_lift_joint', 'right_arm_elbow_rotate_joint', 'right_arm_elbow_bend_joint', 'right_arm_wrist_bend_joint', ...
head_joints = ['head_sidetilt_joint', 'head_pan_joint', 'head_tilt_joint'] right_arm_joints = ['right_arm_shoulder_rotate_joint', 'right_arm_shoulder_lift_joint', 'right_arm_elbow_rotate_joint', 'right_arm_elbow_bend_joint', 'right_arm_wrist_bend_joint', 'right_arm_wrist_rotate_joint', 'right_arm_gripper_finger_joint']...
class ConfigException(Exception): """Handles the Exceptions concerning the Configuration file such as : - absence of the file - absence of one of the necessary fields """ def __init__(self, error_message=None): if not error_message: error_message = 'The config file is mi...
class Configexception(Exception): """Handles the Exceptions concerning the Configuration file such as : - absence of the file - absence of one of the necessary fields """ def __init__(self, error_message=None): if not error_message: error_message = 'The config file is mi...
#lamex1------Lambda Function big=lambda a,b: a if a>b else b #Main Program num1 = int(input("Enter First number:")) num2 = int(input("Enter Second number:")) print("{0} is bigger".format(big(num1,num2)))
big = lambda a, b: a if a > b else b num1 = int(input('Enter First number:')) num2 = int(input('Enter Second number:')) print('{0} is bigger'.format(big(num1, num2)))
load("@bazel_skylib//rules:write_file.bzl", "write_file") def update_doc(doc_provs, doc_path = "doc"): """Defines an executable target that copies the documentation from the output directory to the workspace directory. Args: doc_provs: A `list` of document provider `struct` values as returned ...
load('@bazel_skylib//rules:write_file.bzl', 'write_file') def update_doc(doc_provs, doc_path='doc'): """Defines an executable target that copies the documentation from the output directory to the workspace directory. Args: doc_provs: A `list` of document provider `struct` values as returned ...
stmttype=''' typedef enum EStmtType { sstunknown,sstinvalid,sstselect,sstdelete,sstupdate, sstinsert,sstcreatetable,sstcreateview,sstsqlpluscmd, sstcreatesequence, sstdropsequencestmt,sstdroptypestmt,sstplsql_packages,sstplsql_objecttype,sstcreate_plsql_procedure, sstcreate_plsql_funct...
stmttype = '\ntypedef enum EStmtType {\n sstunknown,sstinvalid,sstselect,sstdelete,sstupdate,\n sstinsert,sstcreatetable,sstcreateview,sstsqlpluscmd, sstcreatesequence,\n sstdropsequencestmt,sstdroptypestmt,sstplsql_packages,sstplsql_objecttype,sstcreate_plsql_procedure,\n sstcreate_plsql_fu...
def bool_or_str(value: str): if value == 'True': return True if value == 'False': return False return value def clean_line(line: str) -> str: """Split/tokenize a line with keywords and parameters. TODO: rewrite using grammar or lexer? """ pieces = [''] quote = '' p...
def bool_or_str(value: str): if value == 'True': return True if value == 'False': return False return value def clean_line(line: str) -> str: """Split/tokenize a line with keywords and parameters. TODO: rewrite using grammar or lexer? """ pieces = [''] quote = '' pr...
linha1 = input().split(" ") linha2 = input().split(" ") c1, n1, v1 = linha1 c2, n2, v2 = linha2 valor_pago = (int(n1) * float(v1)) + (int(n2) * float(v2)) print("VALOR A PAGAR: R$ {:.2f}".format(valor_pago))
linha1 = input().split(' ') linha2 = input().split(' ') (c1, n1, v1) = linha1 (c2, n2, v2) = linha2 valor_pago = int(n1) * float(v1) + int(n2) * float(v2) print('VALOR A PAGAR: R$ {:.2f}'.format(valor_pago))
CryptoCurrencyCodes = [ 'ADA', 'BCH', 'BTC', 'DASH', 'EOS', 'ETC', 'ETH', 'LTC', 'NEO', 'XLM', 'XMR', 'XRP', 'ZEC', ] def is_CryptoCurrencyCode(text): return text.upper() in CryptoCurrencyCodes
crypto_currency_codes = ['ADA', 'BCH', 'BTC', 'DASH', 'EOS', 'ETC', 'ETH', 'LTC', 'NEO', 'XLM', 'XMR', 'XRP', 'ZEC'] def is__crypto_currency_code(text): return text.upper() in CryptoCurrencyCodes
class ExceptionHandler: def __init__(self, application, driver_config=None): self.application = application self.drivers = {} self.driver_config = driver_config or {} self.options = {} def set_options(self, options): self.options = options return self def ad...
class Exceptionhandler: def __init__(self, application, driver_config=None): self.application = application self.drivers = {} self.driver_config = driver_config or {} self.options = {} def set_options(self, options): self.options = options return self def a...
def perform_tsne(X, y, perplexity=100, learning_rate=200, n_components=2): tsne = TSNE(n_components=n_components, init='random', random_state=None, perplexity=perplexity, verbose=1) result = tsne.fit_transform(X) result = pd.DataFrame(result) result = result.join(y) result.c...
def perform_tsne(X, y, perplexity=100, learning_rate=200, n_components=2): tsne = tsne(n_components=n_components, init='random', random_state=None, perplexity=perplexity, verbose=1) result = tsne.fit_transform(X) result = pd.DataFrame(result) result = result.join(y) result.columns = ['x0', 'x1', 'y'...
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None # solution 1 # class Solution(object): # def swapPairs(self, head): # """ # :type head: ListNode # :rtype: ListNode # """ # if head == None:...
class Listnode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def swap_pairs(self, head): """ :type head: ListNode :rtype: ListNode """ (pre, pre.next) = (list_node(0), head) while pre.next and pre.next.nex...
top_twenty = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] def num_digi...
top_twenty = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] def num_digits(n): ...
""" Example: Design an algorithm to print all permutations of a string. For simplicity, assume all characters are unique. abcd abdc acbd acdb adbc adcb """ def fac(iteration): if iteration <= 1: return 1 else: return iteration * fac(iteration-1) def perm(remainder, parsed): if not remai...
""" Example: Design an algorithm to print all permutations of a string. For simplicity, assume all characters are unique. abcd abdc acbd acdb adbc adcb """ def fac(iteration): if iteration <= 1: return 1 else: return iteration * fac(iteration - 1) def perm(remainder, parsed): if not rema...
get_market_book_success = { 'data': { 'getMarketBook': { 'dynamicPriceExpiry': 1612756694, 'orders': { 'edges': [ { 'cursor': 'MQ', 'node': { 'coinAmount': '0.00963874', ...
get_market_book_success = {'data': {'getMarketBook': {'dynamicPriceExpiry': 1612756694, 'orders': {'edges': [{'cursor': 'MQ', 'node': {'coinAmount': '0.00963874', 'createdAt': 1612716031, 'cryptocurrency': 'bitcoin', 'dynamicExchangeRate': None, 'id': 'UG9zdE9yZGVyLThjMzRjZThiLTNlM2MtNDI4My04Yzg4LWVhYzE4MGRkNjQ4Mw==', ...
def Draw(w, h, gridscale, ox, oy): stroke(0) strokeWeight(1) line(ox, 0, ox, h) line(0, oy, w, oy) stroke(175, 175, 175) strokeWeight(1) for x in range(w / gridscale / 2): gx = (x + 1) * gridscale line(ox + gx, 0, ox + gx, h) line(ox - gx, 0, ox - gx, h) for y...
def draw(w, h, gridscale, ox, oy): stroke(0) stroke_weight(1) line(ox, 0, ox, h) line(0, oy, w, oy) stroke(175, 175, 175) stroke_weight(1) for x in range(w / gridscale / 2): gx = (x + 1) * gridscale line(ox + gx, 0, ox + gx, h) line(ox - gx, 0, ox - gx, h) for y i...
n, m = map(int, input().split()) matrix = [] for row in range(n): for col in range(m): first_and_last = chr(ord("a") + row) middle = chr(ord("a") + row + col) print(f"{first_and_last}{middle}{first_and_last}", end=" ") print()
(n, m) = map(int, input().split()) matrix = [] for row in range(n): for col in range(m): first_and_last = chr(ord('a') + row) middle = chr(ord('a') + row + col) print(f'{first_and_last}{middle}{first_and_last}', end=' ') print()
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: token = 0 for i in nums: temp = i**2 nums[token] = temp token += 1 nums = sorted(nums, reverse=False) return nums # return sorted(x*x for x in nums)
class Solution: def sorted_squares(self, nums: List[int]) -> List[int]: token = 0 for i in nums: temp = i ** 2 nums[token] = temp token += 1 nums = sorted(nums, reverse=False) return nums
def verify_browser_exists(browser): raise RuntimeError('Browser detection and automatic selenium updates are not yet available for Linux distributions!\nPlease update your selenium driver manually.') def get_browser_version(browser): raise RuntimeError('Browser version detection and automatic selenium updates are not...
def verify_browser_exists(browser): raise runtime_error('Browser detection and automatic selenium updates are not yet available for Linux distributions!\nPlease update your selenium driver manually.') def get_browser_version(browser): raise runtime_error('Browser version detection and automatic selenium update...
n = int(input('Enter A Number:')) i = 1 a = 2 while i <= n: j = 1 while j <= i: print(j*2, end=' ') j += 1 i += 1 print()
n = int(input('Enter A Number:')) i = 1 a = 2 while i <= n: j = 1 while j <= i: print(j * 2, end=' ') j += 1 i += 1 print()
# String matching algorithms word = "axascass" pattern = "ssaafasdasdcasaxqwdwdascassaxascassawdqwxascassaxascassaxascassaxascass" def find_match(word, pattern): j = 0; if(len(word) > len(pattern)): return -1 for i in range(0, len(pattern)): if(word[j] == pattern[i]): j+=1 else: j = 0 if(j == len(wor...
word = 'axascass' pattern = 'ssaafasdasdcasaxqwdwdascassaxascassawdqwxascassaxascassaxascassaxascass' def find_match(word, pattern): j = 0 if len(word) > len(pattern): return -1 for i in range(0, len(pattern)): if word[j] == pattern[i]: j += 1 else: j = 0 ...
# Copyright 2020 Board of Trustees of the University of Illinois. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
class Contact: def __init__(self): self.name = None self.email = None self.phone = None self.organization = None self.officialAddress = None def set_name(self, name): self.name = name def get_name(self): return self.name def set_email(self, ema...
emqx_bills_hour_aggr_sql = """ INSERT INTO emqx_bills_hour("countTime", "msgType", "msgCount", "msgSize", "tenantID") SELECT date_trunc('hour', current_timestamp - INTERVAL '1 hour') AS "countTime", emqx_bills."msgType" AS "msgType", COUNT(*...
emqx_bills_hour_aggr_sql = '\nINSERT INTO emqx_bills_hour("countTime",\n "msgType", "msgCount", "msgSize", "tenantID")\nSELECT date_trunc(\'hour\', current_timestamp - INTERVAL \'1 hour\') AS "countTime",\n emqx_bills."msgType" AS "msgType",\n ...
num_l = num_o = num_v = num_e = 0 for i in input()[::-1]: if i == "e": num_e += 1 elif i == "v": num_v += num_e elif i == "o": num_o += num_v elif i == "l": num_l += num_o print(num_l)
num_l = num_o = num_v = num_e = 0 for i in input()[::-1]: if i == 'e': num_e += 1 elif i == 'v': num_v += num_e elif i == 'o': num_o += num_v elif i == 'l': num_l += num_o print(num_l)
pkgname = "libxpm" pkgver = "3.5.13" pkgrel = 0 build_style = "gnu_configure" hostmakedepends = ["pkgconf", "gettext-tiny"] makedepends = ["xorgproto", "libsm-devel", "libxext-devel", "libxt-devel"] pkgdesc = "X PixMap library" maintainer = "q66 <q66@chimera-linux.org>" license = "MIT" url = "https://xorg.freedesktop.o...
pkgname = 'libxpm' pkgver = '3.5.13' pkgrel = 0 build_style = 'gnu_configure' hostmakedepends = ['pkgconf', 'gettext-tiny'] makedepends = ['xorgproto', 'libsm-devel', 'libxext-devel', 'libxt-devel'] pkgdesc = 'X PixMap library' maintainer = 'q66 <q66@chimera-linux.org>' license = 'MIT' url = 'https://xorg.freedesktop.o...
# We can check the divisibility by 3 by taking the sum of digits. # If remainder is 0, we consider it as it is. If remainder is 1 or 2 we can combine them greedily. # We can then combine 3 numbers each with remainder 1 or 2. def sum_of(n): s = 0 num = n while(num>0): s+=num%10 num = num//10 return s for i in r...
def sum_of(n): s = 0 num = n while num > 0: s += num % 10 num = num // 10 return s for i in range(int(input())): n = int(input()) l = list(map(int, input().split())) x_0 = 0 x_1 = 0 x_2 = 0 for i in range(n): temp = sum_of(l[i]) if temp % 3 == 0: ...
class Solution: def subsets(self, nums): """O(n^2) | not sure""" self.result = [[]] def helper(start, nums, prev_set): for i in range(start, len(nums)): if nums[i] not in prev_set: new_set = set(prev_set) new_set.add(nums[i]...
class Solution: def subsets(self, nums): """O(n^2) | not sure""" self.result = [[]] def helper(start, nums, prev_set): for i in range(start, len(nums)): if nums[i] not in prev_set: new_set = set(prev_set) new_set.add(nums[...
""" The new "Avengers" movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 dollar bill. An "Avengers" ticket costs 25 dollars. Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this li...
""" The new "Avengers" movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 dollar bill. An "Avengers" ticket costs 25 dollars. Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this li...