content
stringlengths
7
1.05M
# Unneeded charting code that was removed from a jupyter notebook. Stored here as an example for later # Draws a chart with the total area of multiple protin receptors at each time step tmpdf = totals65.loc[(totals65['Receptor'].isin(['M1', 'M5', 'M7', 'M22', 'M26'])) & (totals65['Experiment Step...
whitespace = " \t\n\r\v\f" ascii_lowercase = "abcdefghijklmnopqrstuvwxyz" ascii_uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ascii_letters = ascii_lowercase + ascii_uppercase digits = "0123456789" hexdigitx = digits + "abcdef" + "ABCDEF" octdigits = "01234567" punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" p...
with open("pattern.txt") as file: inputs = file.readlines() BUFFER = 10 ITERATIONS = 50_000_000_000 state = '.' * BUFFER + "..##.#######...##.###...#..#.#.#..#.##.#.##....####..........#..#.######..####.#.#..###.##..##..#..#" + '.' * 102 gives_empty = {line[:5] for line in inputs if line[-2] == '.'} pattern_ite...
all_sales = dict() try: with open(".\\.\\sales.csv") as file: for line in file: string_args = line.split() string_date = string_args[0] string_price = string_args[1].split(",") price = all_sales[string_date] all_sales[string_date] = price + string...
# Copyright (c) 2017, 2018 Jae-jun Kang # See the file LICENSE for details. class Config(object): heartbeat_interval = 5 # in seconds class Coroutine(object): default_timeout = 60 # in seconds
__all__ = ( "__title__", "__summary__", "__uri__", "__download_url__", "__version__", "__author__", "__email__", "__license__",) __title__ = "gpxconverter" __summary__ = ("gpx to csv converter. it supports waypoint elements except " "extensions. Values in extensions will be ignored.") __ur...
def count(s, t, loc, lst): return sum([(loc + dist) >= s and (loc + dist) <= t for dist in lst]) def countApplesAndOranges(s, t, a, b, apples, oranges): print(count(s, t, a, apples)) print(count(s, t, b, oranges))
""" This module provides utility functions that are used within socket-py """ def get_packet_request(content_name): message = struct.pack('>I', 1) + struct.pack(len(content_name)) message = message + content_name message = struct.pack('>I', len(message)) + message def get_packet_reply(content_name, conte...
# Ticket numbers usually consist of an even number of digits. # A ticket number is considered lucky if the sum of the first # half of the digits is equal to the sum of the second half. # # Given a ticket number n, determine if it's lucky or not. # # Example # # For n = 1230, the output should be # isLucky(n) = true; # ...
f = open('input.txt') data = [int(num) for num in f.read().split("\n")[:-1]] for i, num1 in enumerate(data): for num2 in data[i+1:]: if num1 + num2 == 2020: print(num1 * num2)
print("Welcome to Alexander's Tic-Tac-Toe Game", "\n") board = [" "for i in range(9)] def cls(): print('\n'*20) def printBoard(): row1 = "|{}|{}|{}|".format(board[0], board[1], board[2]) row2 = "|{}|{}|{}|".format(board[3], board[4], board[5]) row3 = "|{}|{}|{}|".format(board[6], board[7], board[8]...
""" Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the l...
# We want to make a row of bricks that is goal inches long. We have a number # of small bricks (1 inch each) and big bricks (5 inches each). Return True # if it is possible to make the goal by choosing from the given bricks. # This is a little harder than it looks and can be done without any loops. # make_bricks(3, 1...
burgers=[] quan=[] def PrintHead(): print(" ABC Burgers") print(" Pakistan Road,Karachi") print("=====================================") # Data Entry: rates = {"cheese": 110, "zinger": 160, "abc special": 250, "chicken": 120} # Front-End: def TakeInputs(): b = input("Burger Type:")....
cql = { "and": [ {"lte": [{"property": "eo:cloud_cover"}, "10"]}, {"gte": [{"property": "datetime"}, "2021-04-08T04:39:23Z"]}, { "or": [ {"eq": [{"property": "collection"}, "landsat"]}, {"lte": [{"property": "gsd"}, "10"]}, ] },...
def combinationSum(candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ #Firstly we sort the candidates so we can keep track of our progression candidates = sorted(candidates) def backTrack(left, curre...
""" Holds lists of different types of events """ # pylint: disable=line-too-long def get(ids = False): """holds different stack events""" cases = [{ "name": "new_stack_create_failed", "success": False, "StackEvents": [ { "StackId": "arn:aws:cloudformation:us-...
''' A boomerang is a set of 3 points that are all distinct and not in a straight line. Given a list of three points in the plane, return whether these points are a boomerang. Example 1: Input: [[1,1],[2,3],[3,2]] Output: true Example 2: Input: [[1,1],[2,2],[3,3]] Output: false Note: points.length == 3 points...
def definition(): """View of component groups, with fields additional to the cgroup object.""" sql = """ SELECT c.cgroup_id, c.description, c.strand, c.notes, c.curriculum_id, s.description as strand_name, c.cgroup_id id, c.description as short_name, ISNULL(conf.child_count,0) as child_count...
''' Author : MiKueen Level : Medium Problem Statement : Majority Element II Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. Note: The algorithm should run in linear time and in O(1) space. Example 1: Input: [3,2,3] Output: [3] Example 2: Input: [1,1,1,3,3,2,2,2] Output: [1,2]...
class AnnotaVO: def __init__(self): self._entry = None self._label = None self._points = None self._kind = None @property def points(self): return self._points @points.setter def points(self, value): self._points = value @property def entry(...
# Accounts USER_DOES_NOT_EXIST = 1000 INCORRECT_PASSWORD = 1001 USER_INACTIVE = 1002 INVALID_SIGN_UP_CODE = 1030 SOCIAL_DOES_NOT_EXIST = 1100 INCORRECT_TOKEN = 1101 TOKEN_ALREADY_IN_USE = 1102 SAME_PASSWORD = 1200 # Common FORM_ERROR = 9000
class Sigmoid(Node): """ Represents a node that performs the sigmoid activation function. """ def __init__(self, node): # The base class constructor. Node.__init__(self, [node]) def _sigmoid(self, x): """ This method is separate from `forward` because it will...
names = ["kara", "jackie", "Theophilus"] for name in names: print(names) print("\n") for index in range(len(names)): print(names[index])
''' Python name attribute Every module in Python has a special variable called name. The value of the nsme attribute is set '''
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Python implementation of permute utility with Numpy backend from the MATLAB Tensor Toolbox [1]. References ======================================== [1] General software, latest release: Brett W. Bader, Tamara G. Kolda and others, Tensor Toolbox for MATLAB, Version 3.2...
# -*- coding: utf-8 -*- """ Created on Thu May 16 19:37:39 2019 @author: Parikshith.H """ str="hello" if str=="hi": print("true") else: print("false") # ============================================================================= # #output: # false # ==========================================================...
people = [ ('Alice', 32), # one tuple ('Bob', 51), # another tuple ('Carol', 15), ('Dylan', 5), ('Erin', 25), ('Frank', 48) ] i= 0 yuanzu = (' ', 999) while i < len(people): if people[i][1] <= yuanzu[1]: yuanzu = people[i] i += 1 print('Youngest person: {}, {} years old. '.format(yuanzu[0], yuanzu[1])) ...
#!/usr/bin/env python ''' Description: these are the default parameters to use for processing secrets data Author: Rachel Kalmar ''' # ------------------------------------ # # Set defaults for parameters to be used in secretReaderPollyVoices datapath_base = '/Users/kalmar/Documents/code/secrets/secrets_data/' # Whe...
a = "0,0,0,0,0,0" b = "0,-1,-2,0" c = "-1,-3,-4,-1,-2" d = "qwerty" e = ",,3,,4" f = "1,2,v,b,3" g = "0,7,0,2,-12,3,0,2" h = "1,3,-2,1,2" def sum_earnings(str_earn): next_value = 0 total = 0 neg_sum = 0 if any(char.isalpha() for char in str_earn): return 0 for s in str_earn.split(','...
def main(): n, k = map(int, input().split()) l = [] for i in range(n): a, b = map(int, input().split()) l.append((a, b)) l.sort() prev = 0 for i in range(n): prev += l[i][1] if k <= prev: print(l[i][0]) break if __name__ == '__mai...
class Solution: def minimumLength(self, s: str) -> int: if len(s)==1: return 1 i=0 j=len(s)-1 while i<j: if s[i]!=s[j]: break temp = s[i] while i<=j and s[i]==temp: i+=1 while j>=i and s[j]==t...
""" Created by akiselev on 2019-07-18 In this challenge, the task is to debug the existing code to successfully execute all provided test files. Consider that vowels in the alphabet are a, e, i, o, u and y. Function score_words takes a list of lowercase words as an argument and returns a score as follows: The s...
"""Exemplo do dublê Fake.""" class Pedido: def __init__(self, valor, frete, usuario): self.valor = valor self.frete = frete self.usuario = usuario @property def resumo(self): """Informações gerais sobre o pedido.""" return f''' Pedido por: {self.usuario.nom...
# -*- coding: utf-8 -*- """The modules manager.""" class ModulesManager(object): """The modules manager.""" _module_classes = {} @classmethod def GetModuleObjects(cls, module_filter_expression=None): excludes, includes = cls.SplitExpression(cls, expression = module_filter_expression) ...
# set declaration myfruits = {"Apple", "Banana", "Grapes", "Litchi", "Mango"} mynums = {1, 2, 3, 4, 5} # Set printing before removing print("Before remove() method...") print("fruits: ", myfruits) print("numbers: ", mynums) # Removing the elements from the sets elerem = myfruits.remove('Apple') elerem = myfruits.remo...
# CPU: 0.05 s amounts = list(map(int, input().split())) ratios = list(map(int, input().split())) n = min(amounts[x] / ratios[x] for x in range(3)) for amount, ratio in zip(amounts, ratios): print(amount - ratio * n, end=" ")
COUNTRIES = [ "US", "IL", "IN", "UA", "CA", "AR", "SG", "TW", "GB", "AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "GR", "HU", "IE", "IT", "LK", "LV", "LT", "LU", "MT", "NL", "P...
# coding:UTF-8 # 2018-10-4 - 2018-10-6 # 决策树(CART) # python 机器学习算法 # https://blog.csdn.net/gamer_gyt/article/details/51372309 class node(object): def __init__(self, fea = -1, value = None, results = None, right = None, left = None): self.fea = fea self.value = value self.results = results self.right = right ...
_DE_NUMBERS = { 'null': 0, 'ein': 1, 'eins': 1, 'eine': 1, 'einer': 1, 'einem': 1, 'einen': 1, 'eines': 1, 'zwei': 2, 'drei': 3, 'vier': 4, 'fünf': 5, 'sechs': 6, 'sieben': 7, 'acht': 8, 'neun': 9, 'zehn': 10, 'elf': 11, 'zwölf': 12, 'dreiz...
x = 1 y = 10 # Checks if one value is equal to another if x == 1: print("x is equal to 1") # Checks if one value is NOT equal to another if y != 1: print("y is not equal to 1") # Checks if one value is less than another if x < y: print("x is less than y") # Checks if one value is greater ...
# general configuration LOCAL_OTP_PORT = 8088 # port for OTP to use, HTTPS will be served on +1 TEMP_DIRECTORY = "mara-ptm-temp" PROGRESS_WATCHER_INTERVAL = 5 * 60 * 1000 # milliseconds JVM_PARAMETERS = "-Xmx8G" # 6-8GB of RAM is good for bigger graphs # itinerary filter parameters CAR_KMH = 50 CAR_TRAVEL_FACTOR = ...
class Solution: # @param s, a string # @param dict, a set of string # @return a boolean def wordBreak(self, s, dict): if not dict: return False n = len(s) res = [False] * n for i in xrange(0, n): if s[:i+1] in dict: res[i] = True ...
diccionario= {91: 95} a=91 if a==91: a=diccionario.get(91) print(a)
arquivo = open('linguagens.txt', 'r') num = int(input("Numero de linguagens: ")) count=0 for linha in arquivo: if count<num: print(linha.rstrip('\n')) count += 1 else: break arquivo.close()
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------- # @File : ProcessError.py # @Created : 2020/10/23 6:05 下午 # @Software : PyCharm # # @Author : Liu.Qi # @Contact : liuqi_0725@aliyun.com # # @Desc : 处理中的异常 # -------------------------------------------...
class Solution: def myPow(self, x: float, n: int) -> float: # 如果是c系语言,就要考虑输出值的类型,以防止溢出,python应该没有这个问题? if x == 0 and n == 0: return "undefined" elif n ==0: return 1 y = n if n>0 else -n res = 1 # 当输入值为0.00001 2147483647时,出现了超时错误……以下方法不高效 ...
#!/usr/bin/env python3 # coding:utf-8 class Solution: def StrToInt(self, s): if s == '': return 0 string = s.strip() num = 0 start = 0 symbol = 1 if string[0] == '+': start += 1 elif string[0] == '-': start += 1 ...
def roman(num): """ Function to convert an integer to roman numeral. :type num: int :rtype: str """ if type(num) is not int: raise TypeError("Invalid input.") if num <= 0: raise ValueError("Roman numbers can only be positive. " + "Please enter a po...
fit2_lm = sm.ols(formula="y ~ age + np.power(age, 2) + np.power(age, 3)",data=diab).fit() poly_predictions = fit2_lm.get_prediction(predict_df).summary_frame() poly_predictions.head()
''' 1)Fill in the blanks of this code to print out the numbers 1 through 7. ''' '''number = 1 while number <= 7: print(number, end=" ") number+=1 ''' ''' 2) The show_letters function should print out each letter of a word on a separate line. Fill in the blanks to make that happen. ''' '''def show_letters(word...
class Solution: # def countAndSay(self, n): # """ # :type n: int # :rtype: str # """ # s = '1' # for _ in range(n - 1): # s = ''.join(str(len(list(group))) + digit for digit, group in itertools.groupby(s)) # return s def countAndSay(self, ...
""" Desafio 73. Crie um tupla com a colocação do brasileirão. Depois mostre: a) os 5 primeiros colocados; b) os últimos 4 colocados da tabela; c) lista com os times em ordem alfabética d) em que lugar está a Chapecoense. """ brasileirao = ("Flamengo", "Palmeiras", "São Paulo", "Grêmio", "Cruzeiro", "Atlético-MG", "Cor...
""" Given a square matrix, write a function that rotates the matrix 90 degrees clockwise. For example: 1 2 3 7 4 1 4 5 6 ---> 8 5 6 7 8 9 9 6 3 1 2 3 4 13 9 5 1 5 6 7 8 ---> 14 10 6 2 9 10 11 12 15 11 7 3 13 14 15 16 16 12 8 4 """ def rotate_square_arr...
""" The rotor class replicates the physical rotor in an Enigma. """ class Rotor: alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" amountOfRotations = 0 def __init__(self, permutation, rotation): """ :param permutation: string, mono-alphabetic permutation of the alphabet in string form with corres...
scores = [("Rodney Dangerfield", -1), ("Marlon Brando", 1), ("You", 100)] # list of tuples for person in scores: name = person[0] score = person[1] print("Hello {}. Your score is {}.".format(name, score)) origPrice = float(input('Enter the original price: $')) discount = float(input('Enter discount perce...
def find_loop(root): S = root F = root # set up first meeting while True: # if there is no loop, we will detect it if S is None or F is None: return None # advance slow and fast pointers S = S.next_node F = F.next_node.next_node if S is F: ...
''' Assume that two variables, varA and varB, are assigned values, either numbers or strings. Write a piece of Python code that evaluates varA and varB, and then prints out one of the following messages: "string involved" if either varA or varB are strings "bigger" if varA is larger than varB "equal" if varA is equ...
def __create_snap_entry(marker, entry_no, l): # use parse_roll() to create search entry node = [] x = [] for i in range(len(l)-1): if len(l) == 2 and abs(l[i] - l[i+1]) == 2: # if only two balls on the row x += [[l[i], 1]] elif abs(l[i] - l[i+1]) > 1: ...
""" Exceptions for EventBus. """ class EventDoesntExist(Exception): """ Raised when trying remove an event that doesn't exist. """ pass
ls = list() for _ in range(5): ls.append(input()) res = list() for i in range(len(ls)): if 'FBI' in ls[i]: res.append(str(i + 1)) if len(res) == 0: print('HE GOT AWAY!') else: print(' '.join(res))
# 3. Crie uma função para retornar a quantidade de CPF cadastrados def cadastro (): cpfs = [] continuar = '' while continuar != 'não' or 'Não' or 'n' or 'N': print('Digite o seu nome: ') nome = input() print('Digite o seu cpf: ') cpf = input() cpfs.append(cpf) ...
matriz = [[], [], []] for c in range(0, 3): linha0 = matriz[0].append(int(input(f'Digite um valor para [0, {c}]: '))) for c in range(0, 3): linha1 = matriz[1].append(int(input(f'Digite um valor para [1, {c}]: '))) for c in range(0, 3): linha2 = matriz[2]. append(int(input(f'Digite um valor para [2, {c}]: ')...
class NCSBase: def train(self, X, y): pass def scores(self, X, y, cp): pass def score(self, x, labels): pass class NCSBaseRegressor: def train(self, X, y): pass def coeffs(self, X, y, cp): pass def coeffs_n(self, x): pass
# Conditionals # Allows for decision making based on the values of our variables def main(): x = 1000 y = 10 if (x < y): st = " x is less than y" elif (x == y): st = " x is the same as y" else: st = "x is greater than y" print(st) print("\nAlternatively:...") ...
#!/usr/bin/env python # # Class implementing a serial (console) user interface for the Manchester Baby (SSEM) # #------------------------------------------------------------------------------ # # Class construction. # #----------------------------------------------------------------------------...
a,b=map(str,input().split()) z=[] x,c="","" if a[0].islower(): x=x+a[0].upper() if b[0].islower(): c=c+b[0].upper() for i in range(1,len(a)): if a[i].isupper() or a[i].islower(): x=x+a[i].lower() for i in range(1,len(b)): if b[i].isupper() or b[i].islower(): c=c+b[i].lower(...
#tutorials 3: Execute the below instructions in the interpreter #execute the below command "Hello World!" print("Hello World!") #execute using single quote 'Hello World!' print('Hello World!') #use \' to escape single quote 'can\'t' print('can\'t') #or use double quotes "can't" print("can't") #more examples 1-...
k = int(input("k: ")) array = [10,2,3,6,18] fulfilled = False i = 0 while i < len(array): if k-array[i] in array: fulfilled = True i += 1 if fulfilled == True: print("True") else: print("False")
# https://www.codewars.com/kata/570ac43a1618ef634000087f/train/python ''' Instructions: Nova polynomial add This kata is from a series on polynomial handling. ( #1 #2 #3 #4 ) Consider a polynomial in a list where each element in the list element corresponds to a factor. The factor order is the position in the list. ...
#!/usr/bin/env python # encoding: utf-8 """ @author: Alfons @contact: alfons_xh@163.com @file: 4.Floyd.py @time: 18-6-18 下午10:41 @version: v1.0 """ # 最短路径----弗洛伊德算法 # 设 $D_{i,j,k}$为从$i$到$j$的只以 $(1..k)$集合中的节点为中间节点的最短路径的长度。 # # - 若最短路径经过点k,则 $D_{i,j,k} = D_{i,k,k-1} + D_{k,j,k-1}$; # - 若最短路径不经过点k,则 $D_{i,j,k}=D_{i,j,...
# https://leetcode.com/problems/simplify-path/ class Solution: def simplifyPath(self, path: str) -> str: directories = path.split('/') directory_stack = list() for directory in directories: if not directory == '' and not directory == '.': if not directory == '..'...
#------------------------------------------------------------------------------- # Name: misc_python # Purpose: misc python utilities # # Author: matthewl9 # # Version: 1.0 # # Contains: write to file, quicksort, import_list # # Created: 21/02/2018 # Copyright: (c) matthewl9 2018 # Licence:...
NONE = 0 HALT = 1 << 0 FAULT = 1 << 1 BREAK = 1 << 2 def VMStateStr(_VMState): if _VMState == NONE: return "NONE" state = [] if _VMState & HALT: state.append("HALT") if _VMState & FAULT: state.append("FAULT") if _VMState & BREAK: state.append("BREAK") return ...
#!python def linear_search(array, item): """return the first index of item in array or None if item is not found""" # implement linear_search_iterative and linear_search_recursive below, then # change this to call your implementation to verify it passes all tests return linear_search_iterative(array, i...
# Copyright 2016 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. { 'targets': [ # { # 'target_name': 'byte_reader', # 'includes': ['../../../../compile_js2.gypi'], # }, # { # 'target_name': 'conten...
''' Insira aqui as respectivas variáveis mencionadas no README.md ''' TELEGRAM_TOKEN = 'TOKEN' CHAT_ID = '-123456789'
# DESAFIO 022: nome = input("Escreva seu nome completo:") n_ok = nome.strip() letras = len(n_ok) - n_ok.count(" ") nomeSplitado = n_ok.split() print(f"Nome todo em maiúsculo: ", n_ok.upper()) print(f"Nome todo em minúsculo: ", n_ok.lower()) print(f"Seu nome completo tem {letras} letras.") print(f"Seu primeiro nome tem ...
pessoas = [] person = {} masc = [] fem = [] som = 0 while True: person.clear() person['nome'] = str(input('Nome: ')) while True: person['sexo'] = str(input('Sexo:[M/F] ')).upper() if person['sexo'] in 'MF': break print('ERRO! Digite apenas M ou F!') person['idade'] = ...
#!/usr/bin/env python3 ''' lib/subl/constants.py Constants for use in sublime apis, including plugin-specific settings. ''' ''' Settings file name. This name is passed to sublime when loading the settings. ''' # pylint: disable=pointless-string-statement SUBLIME_SETTINGS_FILENAME = 'sublime-ycmd.sublime-setting...
class Method: BEGIN = 'calling.begin' ANSWER = 'calling.answer' END = 'calling.end' CONNECT = 'calling.connect' DISCONNECT = 'calling.disconnect' PLAY = 'calling.play' RECORD = 'calling.record' RECEIVE_FAX = 'calling.receive_fax' SEND_FAX = 'calling.send_fax' SEND_DIGITS = 'calling.send_digits' TA...
SCHEMA = """\ CREATE TABLE gene ( id INTEGER PRIMARY KEY, name TEXT, start_pos INTEGER, end_pos INTEGER, strand INTEGER, translation TEXT, scaffold TEXT, organism TEXT );\ """ QUERY = """\ SELECT id, name, star...
construction = ['Owner Authorization', 'Bidding & Contract Documents', 'Plans', 'Spedifications', 'Addenda', 'Submittals', 'Shop Drawings', 'Bonds', 'Insurance Certificates', 'Design Clarifications', 'Baseline Schedule', 'Schedule Revisions', 'Permits', 'Meeting Minutes', 'Payment Requests', 'Correspondence', 'Progres...
""" All that is open must be closed... http://www.codewars.com/kata/55679d644c58e2df2a00009c/train/python """ def is_balanced(source, caps): count = {} stack = [] for c in source: if c in caps: i = caps.index(c) if i % 2 == 0: if caps[i] == caps[i + 1]: ...
#python program to display odd numbers print("Odd numbers are as follows") for i in range(1,100,2): print(i) print("End of the program")
#!/usr/bin/python3 def img_splitter(img): img_lines = img.splitlines() longest = 0 for ind, line in enumerate(img_lines): if line == "": img_lines.pop(ind) if len(line) > longest: longest = len(line) for line in img_lines: if len(line) < longest: ...
class BinaryMatrix(object): def __init__(self, mat): self.mat = mat def get(self, x: int, y: int) -> int: return self.mat[x][y] def dimensions(self): n = len(self.mat) m = len(self.mat[0]) return n, m class Solution: def leftMostColumnWithOne(self, binaryMatri...
USER_AGENTS = [ ( "Mozilla/5.0 (X11; Linux x86_64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/57.0.2987.110 " "Safari/537.36" ), # chrome ( "Mozilla/5.0 (X11; Linux x86_64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/61.0.3163.79 " ...
# Block No 99997 # Block Bits 453281356 # Difficulty 14,484.16 _bits = input("* block's BITS ? : "); hexBits = hex(int(_bits)); _hexHead = hexBits[:4]; _hexTail = '0x'+hexBits[4:]; print("- BITS in hexadecimal : ", hexBits); print(" ", _hexHead); print(" ", _...
class BaseConfig: SECRET_KEY = None class DevelopmentConfig(BaseConfig): FLASK_ENV="development" class ProductionConfig(BaseConfig): FLASK_ENV="production"
class Analyzer(): ''' Analyzer holds image data, hooks to pre-processed and intermediate data and the methods to analyze and output visualizations start: 2017-05-27, Nathan Ing ''' def __init__(self): pass
""" The Elves think their skill will improve after making a few recipes. However, that could take ages; you can speed this up considerably by identifying the scores of the ten recipes after that. What are the scores of the ten recipes immediately after the number of recipes in your puzzle input? """ class Scoreboar...
# bubble sort function def bubble_sort(arr): n = len(arr) # Repeat loop N times # equivalent to: for(i = 0; i < n-1; i++) for i in range(0, n-1): # Repeat internal loop for (N-i)th largest element for j in range(0, n-i-1): # if jth value is greater than (j+1) value ...
arr = [] for i in range(5): dum = list(map(int, input().split())) arr.append(dum) def sol(arr): for i in range(5): for j in range(5): if arr[i][j] == 1: return abs(2-i) + abs(2-j) print(sol(arr))
""" *args A special operator we can pass to functions. Gathers remaining arguments as a tuple. """ def sum_all_nums(num1, num2, num3): return num1 + num2 + num3 print(sum_all_nums(4, 6, 9)) # 19 print(sum_all_nums(4, 6)) # Error: no value for argument num3 def sum_with_args(*args): total = 0 f...
# coding: utf-8 # This example is the python implementation of nowait.1.f from OpenMP 4.5 examples n = 100 m = 100 a = zeros(n, double) b = zeros(n, double) y = zeros(m, double) z = zeros(m, double) #$ omp parallel #$ omp do schedule(runtime) for i in range(0, m): z[i] = i*1.0 #$ omp end do nowait #$ omp do fo...
#!/usr/bin/env python3v ## create file object in "r"ead mode filename = input("Name of file: ") with open(f"{filename}", "r") as configfile: ## readlines() creates a list by reading target ## file line by line configlist = configfile.readlines() ## file was just auto closed (no more indenting) ## each i...
class Solution: def preorderTraversal(self, root): ret = [] s = [root] while s: cur = s.pop() if not cur: continue ret.append(cur.val) if cur.right: s.append(cur.right) if cur.left: ...
execfile('ex-3.02.py') assert dtype.size == MPI.DOUBLE.size + MPI.CHAR.size assert dtype.extent >= dtype.size dtype.Free()
""" --- Day 6: Custom Customs --- As your flight approaches the regional airport where you'll switch to a much larger plane, customs declaration forms are distributed to the passengers. The form asks a series of 26 yes-or-no questions marked a through z. All you need to do is identify the questions for which anyone...