content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#lab1 ex2 print('Please insert Your name, surname and year of birth:') a = input() b = a.split() name = b[0] surname = b[1] year_of_birth = b[2] print(surname, year_of_birth, name)
print('Please insert Your name, surname and year of birth:') a = input() b = a.split() name = b[0] surname = b[1] year_of_birth = b[2] print(surname, year_of_birth, name)
class HTML_Icon(): HTML_Icon_Color_Default_Display='inline' HTML_Icon_Color_Default_Show='blue' HTML_Icon_Color_Default_Hide='grey' HTML_Icon_Size_Default=0 HTML_Icon_Sizes=[ '', 'fa-lg', 'fa-2x', 'fa-xs','fa-sm', 'fa-3x','fa-5x','fa-7x','fa-10x', ...
class Html_Icon: html__icon__color__default__display = 'inline' html__icon__color__default__show = 'blue' html__icon__color__default__hide = 'grey' html__icon__size__default = 0 html__icon__sizes = ['', 'fa-lg', 'fa-2x', 'fa-xs', 'fa-sm', 'fa-3x', 'fa-5x', 'fa-7x', 'fa-10x'] def html__icon(self...
''' A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null. Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding ori...
""" A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null. Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding ori...
# logic: # a function which would accept a number #the number would be tried agains all the positive numbers less than itself excpet 0 wo see if it is a prime number #the result would be returned def prime(number): divi=[ i for i in range(1,number) if number%i==0] if number==1: return print('the number...
def prime(number): divi = [i for i in range(1, number) if number % i == 0] if number == 1: return print('the number is not prime') if divi.__len__() > 2: print('the number is not prime') else: print('the number is prime') prime(1381)
def stop(): pass class Load(): def __init__(self, chan): self.channel = chan.channel self.all_channels = chan.owner.channels self.botnick = chan.botnick self.sendmsg = chan.sendmsg self.name = "broadcast" def run(self, ircmsg): if ircmsg.lowe...
def stop(): pass class Load: def __init__(self, chan): self.channel = chan.channel self.all_channels = chan.owner.channels self.botnick = chan.botnick self.sendmsg = chan.sendmsg self.name = 'broadcast' def run(self, ircmsg): if ircmsg.lower().find(self.cha...
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: longest, current = "", "" for j in range(len(s)): i = current.find(s[j]) if i >= 0: current = current[i + 1:] current += s[j] if len(longest) < len(current): ...
class Solution: def length_of_longest_substring(self, s: str) -> int: (longest, current) = ('', '') for j in range(len(s)): i = current.find(s[j]) if i >= 0: current = current[i + 1:] current += s[j] if len(longest) < len(current): ...
"""ex097 - Um print especial Faca um programa que tenha uma funcao chamada escreva(), que receba um texto qualquer como parametro e mostre uma mensagem com tamanho adaptavel. Ex: escreva("Ola, Mundo!") saida: ~~~~~~~~~~~~~~ Ola, Mundo! ~~~~~~~~~~~~~~""" def escreva(msg): tam = len(msg) + 4 print("~" * tam) ...
"""ex097 - Um print especial Faca um programa que tenha uma funcao chamada escreva(), que receba um texto qualquer como parametro e mostre uma mensagem com tamanho adaptavel. Ex: escreva("Ola, Mundo!") saida: ~~~~~~~~~~~~~~ Ola, Mundo! ~~~~~~~~~~~~~~""" def escreva(msg): tam = len(msg) + 4 print('~' * tam) ...
''' .. _snippets-pythonapi-metadata: Python API: Managing Metadata ============================= This is the tested source code for the snippets used in :ref:`pythonapi-metadata`. The config file we're using in this example can be downloaded :download:`here <../../examples/snippets/resources/datafs_mongo.yml>`. Se...
""" .. _snippets-pythonapi-metadata: Python API: Managing Metadata ============================= This is the tested source code for the snippets used in :ref:`pythonapi-metadata`. The config file we're using in this example can be downloaded :download:`here <../../examples/snippets/resources/datafs_mongo.yml>`. Se...
#!/usr/bin/env python # 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 agreed to in writing, software...
def debian_package_install(packages): """Jinja utility method for building debian-based package install command apt-get is not capable of installing .deb files from a URL and the template logic to construct a series of steps to install regular packages from apt repos as well as .deb files that need to ...
"""Constants used by yggdrasil.""" # ====================================================== # Do not edit this file past this point as the following # is generated by yggdrasil.schema.update_constants # ====================================================== LANG2EXT = { 'R': '.R', 'c': '.c', 'c++': '.cpp...
"""Constants used by yggdrasil.""" lang2_ext = {'R': '.R', 'c': '.c', 'c++': '.cpp', 'cpp': '.cpp', 'cxx': '.cpp', 'executable': '.exe', 'fortran': '.f90', 'lpy': '.lpy', 'matlab': '.m', 'osr': '.xml', 'python': '.py', 'r': '.R', 'sbml': '.xml', 'yaml': '.yml'} ext2_lang = {v: k for (k, v) in LANG2EXT.items()} language...
# # PySNMP MIB module NV-ATKK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NV-ATKK-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:25:52 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 0...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, constraints_union, single_value_constraint, value_range_constraint, value_size_constraint) ...
# https://www.codewars.com/kata/521c2db8ddc89b9b7a0000c1/ ''' Instructions : Snail Sort Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise. array = [[1,2,3], [4,5,6], [7,8,9]] snail(array) #=> [1,2,3,6,9,8,7,4,5] For better u...
""" Instructions : Snail Sort Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise. array = [[1,2,3], [4,5,6], [7,8,9]] snail(array) #=> [1,2,3,6,9,8,7,4,5] For better understanding, please follow the numbers of the next array c...
command = '/home/slunk/code/racks_project/env/bin/gunicorn' pythonpath = '/home/slunk/code/racks_project/racks' bind = '127.0.0.1:8001' workers = 5 user = 'slunk' limit_request_fields = 32000 limit_request_field_size = 0 raw_enw = 'DJANGO_SETTINGS_MODULE=racks.settings'
command = '/home/slunk/code/racks_project/env/bin/gunicorn' pythonpath = '/home/slunk/code/racks_project/racks' bind = '127.0.0.1:8001' workers = 5 user = 'slunk' limit_request_fields = 32000 limit_request_field_size = 0 raw_enw = 'DJANGO_SETTINGS_MODULE=racks.settings'
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...
def calculate_max_profit(prices): '''Calculates the maximum profit given a list of prices of a stock by buying and selling exactly once. >>> calculate_max_profit([9, 11, 8, 5, 7, 10]) 5 >>> calculate_max_profit([10, 9, 8, 5, 2]) 0 ''' smallest_element_so_far = float('inf'...
def calculate_max_profit(prices): """Calculates the maximum profit given a list of prices of a stock by buying and selling exactly once. >>> calculate_max_profit([9, 11, 8, 5, 7, 10]) 5 >>> calculate_max_profit([10, 9, 8, 5, 2]) 0 """ smallest_element_so_far = float('inf'...
class FailedRequestingEcoCounterError(Exception): pass class PublishError(Exception): pass
class Failedrequestingecocountererror(Exception): pass class Publisherror(Exception): pass
fname = input('Enter file: ') try: fhandle = open(fname, 'r') except: print('No such file.') quit() hrs = dict() for line in fhandle: if not line.startswith('From '): continue tmp = line.find(':') hour = line[tmp-2:tmp] hrs[hour] = hrs.get(hour, 0) + 1 for (k, v) in sorted(hrs.it...
fname = input('Enter file: ') try: fhandle = open(fname, 'r') except: print('No such file.') quit() hrs = dict() for line in fhandle: if not line.startswith('From '): continue tmp = line.find(':') hour = line[tmp - 2:tmp] hrs[hour] = hrs.get(hour, 0) + 1 for (k, v) in sorted(hrs.item...
sides = {} data = input() while not data == "Lumpawaroo": keep_it = True idk = False if "|" in data: side, name = data.split(" | ") if side in sides: for person in sides[side]: if name in person: idk = True break ...
sides = {} data = input() while not data == 'Lumpawaroo': keep_it = True idk = False if '|' in data: (side, name) = data.split(' | ') if side in sides: for person in sides[side]: if name in person: idk = True break ...
class Customer: #function to update the details of the customer def __init__(self,name,email): self.name = name self.email = email self.purchases = [] #function to have a customer make a purchase def purchase(self,inventory, product): inventory_dict = inventory.i...
class Customer: def __init__(self, name, email): self.name = name self.email = email self.purchases = [] def purchase(self, inventory, product): inventory_dict = inventory.inventory if product in inventory_dict: if inventory_dict[product] > 1: ...
""" Copyright (c) 2020, Souvik Ghosh. Distributed under the terms of the MIT License. The full license is in the file LICENSE, distributed with this software. Created on Mar 15, 2020 @author """ def Solve(): m = [] for j in range(1, i): if i % j == 0: m.append(j) yiel...
""" Copyright (c) 2020, Souvik Ghosh. Distributed under the terms of the MIT License. The full license is in the file LICENSE, distributed with this software. Created on Mar 15, 2020 @author """ def solve(): m = [] for j in range(1, i): if i % j == 0: m.append(j) yield sum(m) e = in...
samples = [ { "input": { "array": [5, 1, 22, 25, 6, -1, 8, 10], }, "output": [1, 6, -1, 10], }, ]
samples = [{'input': {'array': [5, 1, 22, 25, 6, -1, 8, 10]}, 'output': [1, 6, -1, 10]}]
def process_flags(all_flags): """ Argument: Return: list of """ fixed_map = {'fixed': True, 'param': False} flags = [Flags(name, fixed_map[flag_type]) for name, flag_type in all_flags.items()] return flags def process_hparams(all_hparams): """ Argument: Return: ""...
def process_flags(all_flags): """ Argument: Return: list of """ fixed_map = {'fixed': True, 'param': False} flags = [flags(name, fixed_map[flag_type]) for (name, flag_type) in all_flags.items()] return flags def process_hparams(all_hparams): """ Argument: Return: """...
def doNothing(rawSolutions): #TODO - accept some sort of number QoI from somewhere number_qoi = 1 list_of_qoi = [] for _ in range(number_qoi): qoi_values = [] for raw_solution in rawSolutions: qoi_values.append(raw_solution) list_of_qoi.append(qoi_values) return...
def do_nothing(rawSolutions): number_qoi = 1 list_of_qoi = [] for _ in range(number_qoi): qoi_values = [] for raw_solution in rawSolutions: qoi_values.append(raw_solution) list_of_qoi.append(qoi_values) return list_of_qoi
class SaleorAppError(Exception): """Generic Saleor App Error, all framework errros inherit from this""" class InstallAppError(SaleorAppError): """Install App error""" class ConfigurationError(SaleorAppError): """App is misconfigured"""
class Saleorapperror(Exception): """Generic Saleor App Error, all framework errros inherit from this""" class Installapperror(SaleorAppError): """Install App error""" class Configurationerror(SaleorAppError): """App is misconfigured"""
class Plan: def __init__(self): self.tasks = [] def add_task(self, task): assert task.task_id is None self.tasks.append(task) def take_tasks(self): tasks = self.tasks self.tasks = [] return tasks
class Plan: def __init__(self): self.tasks = [] def add_task(self, task): assert task.task_id is None self.tasks.append(task) def take_tasks(self): tasks = self.tasks self.tasks = [] return tasks
# Program : Linear search in an array. # Input : size = 5, array = [1, 3, 5, 2, 4], target = 5 # Output : 2 # Explanation : The index of the element 5 is 2. # Language : Python3 # O(n) time | O(1) space def linear_search(size, array, target): # Do for each element in the array. for i in range(size): #...
def linear_search(size, array, target): for i in range(size): current_element = array[i] if current_element == target: return i return -1 if __name__ == '__main__': size = 5 array = [1, 3, 5, 2, 4] target = 5 answer = linear_search(size, array, target) print(answe...
# -*- coding: utf-8 -*- """ Used to space/separate choices group """ class Separator: line = '-' * 15 def __init__(self, line=None): if line: self.line = line def __str__(self): return self.line
""" Used to space/separate choices group """ class Separator: line = '-' * 15 def __init__(self, line=None): if line: self.line = line def __str__(self): return self.line
def pego_correndo(speed, is_birthday): retorno = 0 if is_birthday == True: if speed <= 65: retorno = 0 elif 65 < speed <= 85 : retorno = 1 elif speed > 85 : retorno = 2 elif is_birthday == False: if speed <= 60 : retorno = 0 elif 60 < speed <= 80 : retorno = 1 elif speed > 80 : retorno ...
def pego_correndo(speed, is_birthday): retorno = 0 if is_birthday == True: if speed <= 65: retorno = 0 elif 65 < speed <= 85: retorno = 1 elif speed > 85: retorno = 2 elif is_birthday == False: if speed <= 60: retorno = 0 ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @created: 11.01.21 @author: felix """
""" @created: 11.01.21 @author: felix """
class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: s1_len = len(s1) s2_len = len(s2) flag = False for i,v in enumerate(s2): for k in s1: if k != v: flag = False break; else: ...
class Solution: def check_inclusion(self, s1: str, s2: str) -> bool: s1_len = len(s1) s2_len = len(s2) flag = False for (i, v) in enumerate(s2): for k in s1: if k != v: flag = False break else: ...
my_list = ["one", 2, "three"] print(my_list) print(type(my_list)) l = [] # an empty list
my_list = ['one', 2, 'three'] print(my_list) print(type(my_list)) l = []
class Solution: def minimumDeviation(self, nums: List[int]) -> int: # since heapq is a min-heap # we use negative of the numbers to mimic a max-heap evens = [] minimum = inf for num in nums: if num % 2 == 0: evens.append(-num) minim...
class Solution: def minimum_deviation(self, nums: List[int]) -> int: evens = [] minimum = inf for num in nums: if num % 2 == 0: evens.append(-num) minimum = min(minimum, num) else: evens.append(-num * 2) ...
def scanstring(s, end, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match): """Scan the string s for a JSON string. End is the index of the character in s after the quote that started the JSON string. Unescapes all valid JSON string escape sequences and raises ValueError on attempt to decode an invalid string. If stri...
def scanstring(s, end, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match): """Scan the string s for a JSON string. End is the index of the character in s after the quote that started the JSON string. Unescapes all valid JSON string escape sequences and raises ValueError on attempt to decode an invalid string. If s...
# # PySNMP MIB module HPN-ICF-TE-TUNNEL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-TE-TUNNEL-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:41:36 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, constraints_intersection, value_range_constraint, single_value_constraint, value_size_constraint) ...
class Solution: def swapNodes(self, head: ListNode, k: int) -> ListNode: n1, n2, p = None, None, head while p: k -= 1 if n2: n2 = n2.next if k == 0: n1 = p n2 = head p = p.next n1.val, n2.val = n...
class Solution: def swap_nodes(self, head: ListNode, k: int) -> ListNode: (n1, n2, p) = (None, None, head) while p: k -= 1 if n2: n2 = n2.next if k == 0: n1 = p n2 = head p = p.next (n1.val, n2.v...
# # Define a generator # def test(): # print("phase one") # yield 5 # print("phase two") # yield 10 # # call and return the generator # gen=test() # # print(gen) #"only print the object of generator" # # work with for-loop # for data in gen: # print(data) def generateEven(maxNumber): number ...
def generate_even(maxNumber): number = 0 while number < maxNumber: yield number number += 2 even_generator = generate_even(10) for data in evenGenerator: print(data)
c, r = 'ABCDEFGH', '12345678' cell = input("Which chess square? ") cc, cr = c.index(cell[0]), r.index(cell[1]) print("black") if (int(cc)+int(cr)) % 2 == 0 else print("white")
(c, r) = ('ABCDEFGH', '12345678') cell = input('Which chess square? ') (cc, cr) = (c.index(cell[0]), r.index(cell[1])) print('black') if (int(cc) + int(cr)) % 2 == 0 else print('white')
#!/usr/bin/env python3 def encrypt(text, s): result = "" # transverse the plain text for i in range(len(text)): char = text[i] # Encrypt uppercase characters in plain text if (char.isupper()): result += chr((ord(char) + s-65) % 26 + 65) # Encrypt lowercase charac...
def encrypt(text, s): result = '' for i in range(len(text)): char = text[i] if char.isupper(): result += chr((ord(char) + s - 65) % 26 + 65) else: result += chr((ord(char) + s - 97) % 26 + 97) return result text = 'ATTACKATONCE' s = 4 print('Plain Text : ' + t...
# explicit conversion a="32" b=str(32) print(a+b) a=int(a) b=int(b) print(a+b) # python does not convert implicitly in these cases
a = '32' b = str(32) print(a + b) a = int(a) b = int(b) print(a + b)
def part_1(data): return sum(int(line) for line in data) def part_2(data): cumulative = 0 reached = {0} while True: for line in data: cumulative += int(line) if cumulative in reached: return cumulative reached.add(cumulative) if __name__ ==...
def part_1(data): return sum((int(line) for line in data)) def part_2(data): cumulative = 0 reached = {0} while True: for line in data: cumulative += int(line) if cumulative in reached: return cumulative reached.add(cumulative) if __name__ == ...
class Resistor: def __init__(self, p, R): self.type = 'R' self.p = p self.p1 = p.split('-')[0] self.p2 = p.split('-')[1] self.R = R self.Y = 1/R self.v = [] self.ic = [] def resolveInitialConditions(self): # self.v.append(0) # se...
class Resistor: def __init__(self, p, R): self.type = 'R' self.p = p self.p1 = p.split('-')[0] self.p2 = p.split('-')[1] self.R = R self.Y = 1 / R self.v = [] self.ic = [] def resolve_initial_conditions(self): pass def resolve_ih(sel...
def read_file(file_path): with open(file_path) as file: return file.read().split("|") def parser_list(questions): return [question.strip() for question in questions if question.strip()]
def read_file(file_path): with open(file_path) as file: return file.read().split('|') def parser_list(questions): return [question.strip() for question in questions if question.strip()]
def main(): phrase = input("Choose a phrase: ") # Write your code here main()
def main(): phrase = input('Choose a phrase: ') main()
COMPONENTS_BANNER_DOMESTIC = 'eu-exit-banner-domestic' COMPONENTS_BANNER_INTERNATIONAL = 'eu-exit-banner-international' EUEXIT_DOMESTIC_NEWS = 'eu-exit-news' EUEXIT_INTERNATIONAL_NEWS = 'international-eu-exit-news' EUEXIT_DOMESTIC_FORM = 'eu-exit-domestic' EUEXIT_FORM_SUCCESS = 'eu-exit-form-success' EUEXIT_INTERNATIO...
components_banner_domestic = 'eu-exit-banner-domestic' components_banner_international = 'eu-exit-banner-international' euexit_domestic_news = 'eu-exit-news' euexit_international_news = 'international-eu-exit-news' euexit_domestic_form = 'eu-exit-domestic' euexit_form_success = 'eu-exit-form-success' euexit_internation...
class APIException(Exception): """General exception thrown by an API view, contains a message for the JSON response.""" def __init__(self, message, status_code=400) -> None: super().__init__(self) self.message: str = message self.status_code: int = status_code def __repr__(self) ->...
class Apiexception(Exception): """General exception thrown by an API view, contains a message for the JSON response.""" def __init__(self, message, status_code=400) -> None: super().__init__(self) self.message: str = message self.status_code: int = status_code def __repr__(self) ->...
def extractFujitranslationWordpressCom(item): ''' Parser for 'fujitranslation.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('My Wife is a Martial Alliance Head', ...
def extract_fujitranslation_wordpress_com(item): """ Parser for 'fujitranslation.wordpress.com' """ (vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None tagmap = [('My Wife is a Martial Alliance H...
class Solution: def subarraySum(self, nums: List[int], k: int) -> int: # We will construct an additional dictionary to keep the sum of # all the elements before the index, for example # given nums = [1, 4, 0, 3, 2] # the element sum list: sum_list = [0, 1, 5, 5, 8, 10] # Then...
class Solution: def subarray_sum(self, nums: List[int], k: int) -> int: sum_dict = {0: 1} count = s = 0 for n in nums: s += n count += sum_dict.get(s - k, 0) if s in sum_dict: sum_dict[s] += 1 else: sum_dict[s] ...
# -*- coding: utf-8 -*- """SF-TOOLS PACKAGE INFO This module provides some basic information about the sf_tools package. :Author: Samuel Farrens <samuel.farrens@cea.fr> :Version: 2.0.4 """ # Package Version version_info = (2, 0, 4) __version__ = '.'.join(str(c) for c in version_info) __about__ = ('sf_tools \n\n ...
"""SF-TOOLS PACKAGE INFO This module provides some basic information about the sf_tools package. :Author: Samuel Farrens <samuel.farrens@cea.fr> :Version: 2.0.4 """ version_info = (2, 0, 4) __version__ = '.'.join((str(c) for c in version_info)) __about__ = 'sf_tools \n\n Author: Samuel Farrens \n Year: 2018 \n Emai...
"""Hershey Vector Font. See http://paulbourke.net/dataformats/hershey/ """ # print(hershey.simplex[0]) simplex = [ [0,16, # Ascii 32 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,...
"""Hershey Vector Font. See http://paulbourke.net/dataformats/hershey/ """ simplex = [[0, 16, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1...
chars_to_remove = [',', '.', '!', ':', ';', '-', ' ', '?'] def get_longest_palendromes(text): if not text: return [] if len(text) <= 2: return [text] palendromes = [] for window_size in range(len(text), 1, -1): num_shifts = len(text) - window_size for start_index in range(0, num_shif...
chars_to_remove = [',', '.', '!', ':', ';', '-', ' ', '?'] def get_longest_palendromes(text): if not text: return [] if len(text) <= 2: return [text] palendromes = [] for window_size in range(len(text), 1, -1): num_shifts = len(text) - window_size for start_index in rang...
"""Problem 30 of https://projecteuler.net""" def problem_30(): """Solution to problem 30.""" count = 0 # No solution can exist above 9^5 * 6. for number in range(2, (9 ** 5) * 6): digit_sum = sum([int(x) ** 5 for x in str(number)]) if number == digit_sum: count += number ...
"""Problem 30 of https://projecteuler.net""" def problem_30(): """Solution to problem 30.""" count = 0 for number in range(2, 9 ** 5 * 6): digit_sum = sum([int(x) ** 5 for x in str(number)]) if number == digit_sum: count += number answer = count return answer
# %% ####################################### # THIS IS NOT THE SAME AS: my_pcap.getlayer(TCP) def scapyget_tcp(packet_list: scapy.plist.PacketList): result_list = [ pckt for pckt in packet_list if pckt.haslayer('TCP')] return PacketList(result_list)
def scapyget_tcp(packet_list: scapy.plist.PacketList): result_list = [pckt for pckt in packet_list if pckt.haslayer('TCP')] return packet_list(result_list)
# SPDX-License-Identifier: MIT # Copyright (C) 2020-2021 Mobica Limited """Provide error handling helpers""" NO_ERROR = 0 CONFIGURATION_ERROR = 1 REQUEST_ERROR = 2 FILESYSTEM_ERROR = 3 INTEGRATION_ERROR = 4 # Indicates that some assumption about how the Jira works seems to be false INVALID_ARGUMENT_ERROR = 5 INPUT_DA...
"""Provide error handling helpers""" no_error = 0 configuration_error = 1 request_error = 2 filesystem_error = 3 integration_error = 4 invalid_argument_error = 5 input_data_error = 6 jira_data_error = 7 class Cjmerror(Exception): """Exception to be raised by cjm library functions and by cjm-* and sm-* scripts""" ...
def change_variation(change: float) -> float: """Helper to convert change variation Parameters ---------- change: float percentage change Returns ------- float: converted value """ return (100 + change) / 100 def calculate_hold_value(changeA: float, changeB: float...
def change_variation(change: float) -> float: """Helper to convert change variation Parameters ---------- change: float percentage change Returns ------- float: converted value """ return (100 + change) / 100 def calculate_hold_value(changeA: float, changeB: float,...
# -*- coding: utf-8 -*- def formatter(name=None): def decorate(func): func._formatter = name return func return decorate
def formatter(name=None): def decorate(func): func._formatter = name return func return decorate
_UNSET = object() class PyErr: def __init__(self, type=_UNSET, value=_UNSET, traceback=_UNSET): if not(type is _UNSET): self.type = type if not(value is _UNSET): self.value = value if not(traceback is _UNSET): self.traceback = traceback
_unset = object() class Pyerr: def __init__(self, type=_UNSET, value=_UNSET, traceback=_UNSET): if not type is _UNSET: self.type = type if not value is _UNSET: self.value = value if not traceback is _UNSET: self.traceback = traceback
def repeat_string(string, times): return string * times text = input() number = int(input()) result = repeat_string(text, number) print(result)
def repeat_string(string, times): return string * times text = input() number = int(input()) result = repeat_string(text, number) print(result)
#Ask the user for a string and print out whether this string is a palindrome or not. # (A palindrome is a string that reads the same forwards and backwards.) str = input("Let's have a string, shall we?") palindrome = str[::-1]==str if palindrome: print(str,"is a palindrome") else: print(str, "is not a palindr...
str = input("Let's have a string, shall we?") palindrome = str[::-1] == str if palindrome: print(str, 'is a palindrome') else: print(str, 'is not a palindrome')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 12 14:43:23 2017 @author: Nadiar """ def deep_reverse(L): """ assumes L is a list of lists whose elements are ints Mutates L such that it reverses its elements and also reverses the order of the int elements in every element of L. ...
""" Created on Sun Feb 12 14:43:23 2017 @author: Nadiar """ def deep_reverse(L): """ assumes L is a list of lists whose elements are ints Mutates L such that it reverses its elements and also reverses the order of the int elements in every element of L. It does not return anything. """ for l...
# Problem URL: https://leetcode.com/problems/reverse-integer/ class Solution: def reverse(self, x: int) -> int: # Handling Negative Input neg_flag = 0 if x<0: neg_flag = 1 string = [i for i in str(x)] if neg_flag == 1: string = string[1:] ...
class Solution: def reverse(self, x: int) -> int: neg_flag = 0 if x < 0: neg_flag = 1 string = [i for i in str(x)] if neg_flag == 1: string = string[1:] reversed_string = string[::-1] final_string = '' for i in reversed_string: ...
def binaryToDecimal(arr): arr = str(arr) arr = arr[::-1] length = len(arr)-1 if int(arr[length]) != 1: length -= 1 count = 0 for i in range(length,-1,-1): count += int(arr[i])*(2**i) return count def binaryToDecimal2(value): return int(str(value),2) def binaryToDeci...
def binary_to_decimal(arr): arr = str(arr) arr = arr[::-1] length = len(arr) - 1 if int(arr[length]) != 1: length -= 1 count = 0 for i in range(length, -1, -1): count += int(arr[i]) * 2 ** i return count def binary_to_decimal2(value): return int(str(value), 2) def binar...
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ n,k=map(int,input().split()) a=[] for _ in[0]*n: x,y=map(int,input().split()) a+=[51*(100-x)+y] a=sorted(a) r=i=l=0 while i<n and (a[i]==l or i<k): if a[i]!=l:r=0 r+=1 l=a[i] i+=1 print(r)
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ (n, k) = map(int, input().split()) a = [] for _ in [0] * n: (x, y) = map(int, input().split()) a += [51 * (100 - x) + y] a = sorted(a) r = i = l = 0 while i < n and (a[i] == l or i < k): if a[i] != l: r = 0 ...
#/ <reference path="./testBlocks/mb.ts" /> item = images.createBigImage(""" . . . . . . . . . . . . . . . . # # # . . # # # . . # # # . . # . # . . # . # . . # . # . . # # # . . # # # . . # # # . . . . . . . . . . . . . . . . """) z = images.createBigImage(""" . . . ...
item = images.createBigImage('\n . . . . . . . . . . . . . . .\n . # # # . . # # # . . # # # .\n . # . # . . # . # . . # . # .\n . # # # . . # # # . . # # # .\n . . . . . . . . . . . . . . .\n ') z = images.createBigImage('\n . .\n . #\n . #\n . #\n . .\n ')
""" Sort method works only for lists Sorted functions works for any iterable you can specify the params reverse in both of then and you can also specify a key IMPORTANT functions never modify args """ list = ["abacate", "kiwi", "caju", "damasco", "coco"] s = sorted(list, reverse=True) print(s)
""" Sort method works only for lists Sorted functions works for any iterable you can specify the params reverse in both of then and you can also specify a key IMPORTANT functions never modify args """ list = ['abacate', 'kiwi', 'caju', 'damasco', 'coco'] s = sorted(list, reverse=True) print(s)
# coding=utf-8 class DijkstraAlgorithm: def find_min_cost_vertice(self, costs: dict, processed: set): """ Find the minimum cost and not processed vertice in costs.""" not_processed_vertice_costs = { vertice: cost for vertice, cost in costs.items() if vertice not in processe...
class Dijkstraalgorithm: def find_min_cost_vertice(self, costs: dict, processed: set): """ Find the minimum cost and not processed vertice in costs.""" not_processed_vertice_costs = {vertice: cost for (vertice, cost) in costs.items() if vertice not in processed} return min(not_processed_ver...
print("********** BIENVENIDO AL MENU INTERACTIVO ********** ") print("Que opcion desea Seleccionar? ") print("1)Saludar") print("2)Sumar dos numeros") print("3)Salir del sistema") Opcion = int( input() ) while Opcion<=3: if (Opcion==1): nombre = input("Enter your name : ") print("Hola, mucho gusto...
print('********** BIENVENIDO AL MENU INTERACTIVO ********** ') print('Que opcion desea Seleccionar? ') print('1)Saludar') print('2)Sumar dos numeros') print('3)Salir del sistema') opcion = int(input()) while Opcion <= 3: if Opcion == 1: nombre = input('Enter your name : ') print('Hola, mucho gusto '...
def bicepup(): i01.setArmSpeed("right", 1.0, 1.0, 1.0, 1.0) i01.rightArm.bicep.attach() i01.rightArm.bicep.moveTo(180) sleep(1) i01.rightArm.bicep.detach()
def bicepup(): i01.setArmSpeed('right', 1.0, 1.0, 1.0, 1.0) i01.rightArm.bicep.attach() i01.rightArm.bicep.moveTo(180) sleep(1) i01.rightArm.bicep.detach()
class Car: def __init__(self, maker, model): carManufacturer = maker carModel = model carModel = "" carManufacturer = "" carYear = 0 def setModel(self, model): self.carModel = model def setManufacturer(self, manufacturer): self.carManufacturer = manufacturer...
class Car: def __init__(self, maker, model): car_manufacturer = maker car_model = model car_model = '' car_manufacturer = '' car_year = 0 def set_model(self, model): self.carModel = model def set_manufacturer(self, manufacturer): self.carManufacturer = manufact...
""" Character Picture Grid. Makes a heart. """ grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.'...
""" Character Picture Grid. Makes a heart. """ grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.'...
def hash_key(string): multiplication = 1 for i in string: multiplication *= ord(i) return (multiplication % 97) for i in range(int(input())): str1, str2 = input().split() str1_key = hash_key(str1) str2_key = hash_key(str2) if str1_key == str2_key: print("YES") else: ...
def hash_key(string): multiplication = 1 for i in string: multiplication *= ord(i) return multiplication % 97 for i in range(int(input())): (str1, str2) = input().split() str1_key = hash_key(str1) str2_key = hash_key(str2) if str1_key == str2_key: print('YES') else: ...
#!/usr/bin/env python """Tests for `oops_fhir` package.""" def test_test(): """Sample pytest test function with the pytest fixture as an argument.""" assert True
"""Tests for `oops_fhir` package.""" def test_test(): """Sample pytest test function with the pytest fixture as an argument.""" assert True
def sim_shift(ref, ref_center, ref_length, shift=0, rec=None, padding=False): """ :param ref: Reference signal. :param ref_center: Where to center the simulated signal set. :param ref_length: The length of the signal equidistant around center. :param shift: How much shift should be added to the sim...
def sim_shift(ref, ref_center, ref_length, shift=0, rec=None, padding=False): """ :param ref: Reference signal. :param ref_center: Where to center the simulated signal set. :param ref_length: The length of the signal equidistant around center. :param shift: How much shift should be added to the sim...
{ "targets": [{ "target_name": "opendkim", "sources": [ "src/opendkim_body_async.cc", "src/opendkim_chunk_async.cc", "src/opendkim_chunk_end_async.cc", "src/opendkim_eoh_async.cc", "src/opendkim_eom_async.cc", "src/opendkim_flus...
{'targets': [{'target_name': 'opendkim', 'sources': ['src/opendkim_body_async.cc', 'src/opendkim_chunk_async.cc', 'src/opendkim_chunk_end_async.cc', 'src/opendkim_eoh_async.cc', 'src/opendkim_eom_async.cc', 'src/opendkim_flush_cache_async.cc', 'src/opendkim_header_async.cc', 'src/opendkim_sign_async.cc', 'src/opendkim_...
# Objective # Today, we're delving into Inheritance. Check out the attached tutorial for learning materials and an instructional video. # Task # You are given two classes, Person and Student, where Person is the base class and Student is the derived class. Completed code for Person and a declaration for Student are pr...
class Person: def __init__(self, firstName, lastName, idNumber): self.firstName = firstName self.lastName = lastName self.idNumber = idNumber def print_person(self): print('Name:', self.lastName + ',', self.firstName) print('ID:', self.idNumber) class Student(Person): ...
class ChannelDoesNotExist(Exception): pass class LevelDoesNotExist(Exception): pass class HandlerError(Exception): pass
class Channeldoesnotexist(Exception): pass class Leveldoesnotexist(Exception): pass class Handlererror(Exception): pass
# -*- coding: utf-8 -*- ################################################ # # URL: # ===== # https://leetcode.com/problems/PROBLEM_TITLE/ # # DESC: # ===== # PROBLEM DESCRIPTION ################################################ class Solution: def method(self) -> int: return 0
class Solution: def method(self) -> int: return 0
"""Checks view access for Permissions""" METHODS = ( 'GET', 'POST', ) # pylint: disable=too-few-public-methods class CheckAcess: """ Checks the permissions for Request. """ def __init__(self, request, permissions): self.request = request self.permissions = permissions def ...
"""Checks view access for Permissions""" methods = ('GET', 'POST') class Checkacess: """ Checks the permissions for Request. """ def __init__(self, request, permissions): self.request = request self.permissions = permissions def have_view_access(self): """ Checks i...
# -*- coding: utf-8 -*- class _CommitOnSuccess(object): def __init__(self, session): self.session = session def __enter__(self): self.transaction = self.session.begin_nested() def __exit__(self, exc_type, exc_value, traceback): try: if exc_value is not None: ...
class _Commitonsuccess(object): def __init__(self, session): self.session = session def __enter__(self): self.transaction = self.session.begin_nested() def __exit__(self, exc_type, exc_value, traceback): try: if exc_value is not None: self.transaction.r...
# # PySNMP MIB module IEEE8021-EVB-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IEEE8021-EVB-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:52:20 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint) ...
c,b=map(int,input().split()) x=[*map(int,input().split())] oioi=set() ans=0 oioi.add(0) for i in x: tmp=[] for j in oioi: tmp.append(i+j) if i+j<=c: ans=max(ans,i+j) for j in tmp: oioi.add(j) print(ans)
(c, b) = map(int, input().split()) x = [*map(int, input().split())] oioi = set() ans = 0 oioi.add(0) for i in x: tmp = [] for j in oioi: tmp.append(i + j) if i + j <= c: ans = max(ans, i + j) for j in tmp: oioi.add(j) print(ans)
#!/usr/bin/env python NAME = 'Naxsi' def is_waf(self): # Sometimes naxsi waf returns 'x-data-origin: naxsi/waf' if self.matchheader(('X-Data-Origin', '^naxsi(.*)?')): return True # Found samples returning 'server: naxsi/2.0' if self.matchheader(('server', 'naxsi(.*)?')): return True for att...
name = 'Naxsi' def is_waf(self): if self.matchheader(('X-Data-Origin', '^naxsi(.*)?')): return True if self.matchheader(('server', 'naxsi(.*)?')): return True for attack in self.attacks: r = attack(self) if r is None: return (_, responsebody) = r ...
consumer_key = 'v5bb7HD9PmYTvXuCBgCwa44qZ' consumer_secret = 'tlONgznY4y9S0E4D9JkDVABGGT8ACVgOySt3CPpsKUxU9IE2RS' twitter_token = '2888299528-05kwbmRfd82mneeJg2EMGhcMXXlFci6yaBWjxCA' twitter_token_secret = 'h0WLEeq7PNkC1Rd56eyM1oxi1KL4S9sXP8kigYxEB527B'
consumer_key = 'v5bb7HD9PmYTvXuCBgCwa44qZ' consumer_secret = 'tlONgznY4y9S0E4D9JkDVABGGT8ACVgOySt3CPpsKUxU9IE2RS' twitter_token = '2888299528-05kwbmRfd82mneeJg2EMGhcMXXlFci6yaBWjxCA' twitter_token_secret = 'h0WLEeq7PNkC1Rd56eyM1oxi1KL4S9sXP8kigYxEB527B'
def ip_to_int32(ip): temp="" ip=ip.split(".") for i in ip: temp+="{0:08b}".format(int(i)) return int(temp,2)
def ip_to_int32(ip): temp = '' ip = ip.split('.') for i in ip: temp += '{0:08b}'.format(int(i)) return int(temp, 2)
array = [] with open('input-p22.txt') as f: array = f.readlines() array = array[0].split(',') array.sort() print(array) asciA = ord('A') print("ascii A:", asciA) answer = 0 for i in range(0, len(array)): sum = 0 for letter in array[i]: if letter == '"': continue print(letter, ...
array = [] with open('input-p22.txt') as f: array = f.readlines() array = array[0].split(',') array.sort() print(array) asci_a = ord('A') print('ascii A:', asciA) answer = 0 for i in range(0, len(array)): sum = 0 for letter in array[i]: if letter == '"': continue print(letter, or...
# Do not edit this file directly. # It was auto-generated by: code/programs/reflexivity/reflexive_refresh load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def bigIntegerCpp(): http_archive( name="big_integer_cpp" , build_file="//bazel/deps/big_integer_cpp:build.BUILD" , ...
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') def big_integer_cpp(): http_archive(name='big_integer_cpp', build_file='//bazel/deps/big_integer_cpp:build.BUILD', sha256='1c9505406accb1216947ca60299ed70726eade7c9458c7c7f94ca2aea68d288e', strip_prefix='BigIntegerCPP-79e7b023bf5157c0f8d308d3791c...
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'file', 'isolated', 'json', 'path', 'runtime', 'step', ] def RunSteps(api): # Inspect the associated isolated server. ...
deps = ['file', 'isolated', 'json', 'path', 'runtime', 'step'] def run_steps(api): api.isolated.isolate_server temp = api.path.mkdtemp('isolated-example') api.step('touch a', ['touch', temp.join('a')]) api.step('touch b', ['touch', temp.join('b')]) api.step('touch c', ['touch', temp.join('c')]) ...
#!-*- encoding=utf-8 class MegNoriBaseException(Exception): pass class NoAvaliableVolumeError(MegNoriBaseException): pass class PutFileException(MegNoriBaseException): pass class GetFileException(MegNoriBaseException): pass
class Megnoribaseexception(Exception): pass class Noavaliablevolumeerror(MegNoriBaseException): pass class Putfileexception(MegNoriBaseException): pass class Getfileexception(MegNoriBaseException): pass
{ 'target_defaults': { 'conditions': [ ['OS != "win"', { 'defines': [ '_GNU_SOURCE', ], 'conditions': [ ['OS=="solaris"', { 'cflags': ['-pthreads'], 'ldlags': ['-pthreads'], }, { 'cflags': ['-pthread'], 'ld...
{'target_defaults': {'conditions': [['OS != "win"', {'defines': ['_GNU_SOURCE'], 'conditions': [['OS=="solaris"', {'cflags': ['-pthreads'], 'ldlags': ['-pthreads']}, {'cflags': ['-pthread'], 'ldlags': ['-pthread']}]]}]]}, 'targets': [{'target_name': 'lring', 'type': '<(library)', 'include_dirs': ['include/', 'src/'], '...
# # PySNMP MIB module CHEETAH-TRAP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CHEETAH-TRAP-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:48:47 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
(slb_cur_cfg_real_server_index, flt_cur_cfg_indx, slb_cur_cfg_virt_service_real_port, flt_cur_cfg_port_indx, slb_cur_cfg_real_server_name, slb_cur_cfg_real_server_ip_addr, flt_cur_cfg_src_ip) = mibBuilder.importSymbols('ALTEON-CHEETAH-LAYER4-MIB', 'slbCurCfgRealServerIndex', 'fltCurCfgIndx', 'slbCurCfgVirtServiceRealPo...
def imagecreate(): image = open("theimage.ppm", "w") image.write("P3\n") image.write("500 500\n") image.write("255\n\n") for i in range(500): curline = "" for j in range(500): if i > 250: i = 250 - (i % 250) if j > 250: j = 250 ...
def imagecreate(): image = open('theimage.ppm', 'w') image.write('P3\n') image.write('500 500\n') image.write('255\n\n') for i in range(500): curline = '' for j in range(500): if i > 250: i = 250 - i % 250 if j > 250: j = 250 - ...
def calculate_pi(n_terms: int) -> float: numerator: float = 4.0 denominator: float = 1.0 operation: float = 1.0 pi: float = 0.0 for _ in range(n_terms): pi += operation *(numerator/denominator) denominator += 2.0 operation *= -1.0 return pi if __name__ == "__main__": print(calculate_pi(100000)...
def calculate_pi(n_terms: int) -> float: numerator: float = 4.0 denominator: float = 1.0 operation: float = 1.0 pi: float = 0.0 for _ in range(n_terms): pi += operation * (numerator / denominator) denominator += 2.0 operation *= -1.0 return pi if __name__ == '__main__': ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author: Anne Philipp (University of Vienna) @Date: March 2018 @License: (C) Copyright 2014 UIO. This software is licensed under the terms of the Apache Licence Version 2.0 which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. """
""" @Author: Anne Philipp (University of Vienna) @Date: March 2018 @License: (C) Copyright 2014 UIO. This software is licensed under the terms of the Apache Licence Version 2.0 which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. """
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1, l2): # create a Answer node and mark it's start node StartAns = Answer = ListNode(0) carry = 0 ...
class Solution: def add_two_numbers(self, l1, l2): start_ans = answer = list_node(0) carry = 0 while l1 and l2: (carry, sumval) = divmod(l1.val + l2.val + carry, 10) Answer.next = list_node(sumval) l1 = l1.next l2 = l2.next answer ...
class Node: def __init__(self, data): self.data = data self.next = None self.prev = None def deleteNode(head_ref, del_): if (head_ref == None or del_ == None): return if (head_ref == del_): head_ref = del_.next if (del_.next != None): del_.next.prev = del_.prev if (del_.prev != None): del_.prev.next...
class Node: def __init__(self, data): self.data = data self.next = None self.prev = None def delete_node(head_ref, del_): if head_ref == None or del_ == None: return if head_ref == del_: head_ref = del_.next if del_.next != None: del_.next.prev = del_.pr...
# Windows functions with NLP data # A. Load the data # 1. Load the dataframe df = spark.read.load('sherlock_sentences.parquet') # Filter and show the first 5 rows df.where('id > 70').show(5, truncate=False) # 2. Split and explode text # Split the clause column into a column called words split_df = clauses_df.select...
df = spark.read.load('sherlock_sentences.parquet') df.where('id > 70').show(5, truncate=False) split_df = clauses_df.select(split('clause', ' ').alias('words')) split_df.show(5, truncate=False) exploded_df = split_df.select(explode('words').alias('word')) exploded_df.show(10) print('\nNumber of rows: ', exploded_df.cou...
''' The MIT License (MIT) Copyright (c) 2016 WavyCloud Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, p...
""" The MIT License (MIT) Copyright (c) 2016 WavyCloud Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, p...
"""This problem was asked by Apple. Gray code is a binary code where each successive value differ in only one bit, as well as when wrapping around. Gray code is common in hardware so that we don't see temporary spurious values during transitions. Given a number of bits n, generate a possible gray code for it. For exa...
"""This problem was asked by Apple. Gray code is a binary code where each successive value differ in only one bit, as well as when wrapping around. Gray code is common in hardware so that we don't see temporary spurious values during transitions. Given a number of bits n, generate a possible gray code for it. For exa...
""" Contains code no longer used but kept for review/further reuse --- imports need to be re-added --- """ def determine_disjuct_modules_alternative(src_rep): """ Potentially get rid of determine_added_modules and get_modules_lst() """ findimports_output = subprocess.check_output(['findimports', src_rep]) findim...
""" Contains code no longer used but kept for review/further reuse --- imports need to be re-added --- """ def determine_disjuct_modules_alternative(src_rep): """ Potentially get rid of determine_added_modules and get_modules_lst() """ findimports_output = subprocess.check_output(['findimports', src_rep]) ...
class Endereco: def __init__(self, rua="", bairro="", numero="", cidade="", estado="", cep=""): self.rua = rua self.bairro = bairro self.numero = numero self.cidade = cidade self.estado = estado self.cep = cep
class Endereco: def __init__(self, rua='', bairro='', numero='', cidade='', estado='', cep=''): self.rua = rua self.bairro = bairro self.numero = numero self.cidade = cidade self.estado = estado self.cep = cep
""" --- Day 6: Memory Reallocation --- A debugger program here is having an issue: it is trying to repair a memory reallocation routine, but it keeps getting stuck in an infinite loop. In this area, there are sixteen memory banks; each memory bank can hold any number of blocks. The goal of the reallocation routine is...
""" --- Day 6: Memory Reallocation --- A debugger program here is having an issue: it is trying to repair a memory reallocation routine, but it keeps getting stuck in an infinite loop. In this area, there are sixteen memory banks; each memory bank can hold any number of blocks. The goal of the reallocation routine is...