content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
description = 'GE detector setup PV values' group = 'configdata' EIGHT_PACKS = [ # ('ep01', 'GE-DD590C-EP'), # replaced 2015/10/29 ('ep01', 'GE-DD6D8C-EP'), ('ep02', 'GE-DD5FB3-EP'), ('ep03', 'GE-DDA871-EP'), ('ep04', 'GE-DD7D29-EP'), ('ep05', 'GE-DDBA8F-EP'), ('ep06', 'GE-DD5913-EP'), ...
description = 'GE detector setup PV values' group = 'configdata' eight_packs = [('ep01', 'GE-DD6D8C-EP'), ('ep02', 'GE-DD5FB3-EP'), ('ep03', 'GE-DDA871-EP'), ('ep04', 'GE-DD7D29-EP'), ('ep05', 'GE-DDBA8F-EP'), ('ep06', 'GE-DD5913-EP'), ('ep07', 'GE-DDC7CA-EP'), ('ep08', 'GE-DD6DEF-EP'), ('ep09', 'GE-DD5FB6-EP'), ('ep10...
# Write a program to print the pattern ''' * * * * * * * * * ''' n = int(input("Size: ")) s1 = 0 s2 = 2 * n - 3 i = 0 while (i < n): if (i < n-1): extra = "*" else : extra = "" print(" " * s1 + "*" + " " * s2 + extra) s1 += 1 s2 -= 2 i += 1 s1 -= 2 s2 += 4 i = 0 whi...
""" * * * * * * * * * """ n = int(input('Size: ')) s1 = 0 s2 = 2 * n - 3 i = 0 while i < n: if i < n - 1: extra = '*' else: extra = '' print(' ' * s1 + '*' + ' ' * s2 + extra) s1 += 1 s2 -= 2 i += 1 s1 -= 2 s2 += 4 i = 0 while i < n - 1: print(' ' * s1 + '*' + ' ' * ...
def empty_float(): """ >>> float() 0.0 >>> empty_float() 0.0 """ x = float() return x def float_conjugate(): """ >>> float_call_conjugate() 1.5 """ x = 1.5 .conjugate() return x def float_call_conjugate(): """ >>> float_call_conjugate() 1.5 ""...
def empty_float(): """ >>> float() 0.0 >>> empty_float() 0.0 """ x = float() return x def float_conjugate(): """ >>> float_call_conjugate() 1.5 """ x = 1.5.conjugate() return x def float_call_conjugate(): """ >>> float_call_conjugate() 1.5 """ ...
""" Exception module. """ __docformat__ = "restructuredtext en" ## Copyright (c) 2009 Emmanuel Goossaert ## ## This file is part of npy. ## ## npy 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 ver...
""" Exception module. """ __docformat__ = 'restructuredtext en' class Npyexception(Exception): """ Exception base class. The base Exception class is overridden, so that the __init__() function can be redefined. """ def __init__(self, msg): self.msg = msg def __str__(self): ...
# Write your solution here def double_items(numbers): double_numbers = [] for item in numbers: double_numbers.append(item*2) return double_numbers if __name__ == "__main__": numbers = [2, 4, 5, 3, 11, -4] numbers_doubled = double_items(numbers) print("original:", numbers) print("dou...
def double_items(numbers): double_numbers = [] for item in numbers: double_numbers.append(item * 2) return double_numbers if __name__ == '__main__': numbers = [2, 4, 5, 3, 11, -4] numbers_doubled = double_items(numbers) print('original:', numbers) print('doubled:', numbers_doubled)
class SIG_REVERIESH(object): KILL = 'SIG_REVERIESH_KILL'.encode() PROMPT = 'SIG_REVERIESH_PROMPT'.encode() class ascii_format: magenta = '\033[95m' blue = '\033[94m' green = '\033[92m' yellow = '\033[93m' red = '\033[91m' clear = '\033[0m' bold = '\033[1m' underline = '\033[4m'...
class Sig_Reveriesh(object): kill = 'SIG_REVERIESH_KILL'.encode() prompt = 'SIG_REVERIESH_PROMPT'.encode() class Ascii_Format: magenta = '\x1b[95m' blue = '\x1b[94m' green = '\x1b[92m' yellow = '\x1b[93m' red = '\x1b[91m' clear = '\x1b[0m' bold = '\x1b[1m' underline = '\x1b[4m' ...
#!/usr/bin/env python3 # Write a program that computes the running sum from 1..n # Also, have it compute the factorial of n while you're at it # No, you may not use math.factorial() # Use the same loop for both calculations n = 5 runsum = 0 factorial = 1 for i in range(1, n+1): runsum += i # computes the running su...
n = 5 runsum = 0 factorial = 1 for i in range(1, n + 1): runsum += i factorial *= i print(n, runsum, factorial) '\n5 15 120\n'
# -*- coding: utf-8 -*- TOILET_CHOICES = ( ('F', 'Flush'), ('PT', 'Pit toilet'), ('TPT', 'Traditional Pit toilet'), ('L', 'Latrine'), ('BF', 'Bush /Field'), ('R', 'River'), ('O', 'Others'), ) COOKING_FACILITIES = ( ('Electricity', 'Electricity'), ('Gas'...
toilet_choices = (('F', 'Flush'), ('PT', 'Pit toilet'), ('TPT', 'Traditional Pit toilet'), ('L', 'Latrine'), ('BF', 'Bush /Field'), ('R', 'River'), ('O', 'Others')) cooking_facilities = (('Electricity', 'Electricity'), ('Gas', 'Gas'), ('Biomass', 'Biomass'), ('Kerosene', 'Kerosene'), ('Coal', 'Coal'), ('Charcoal', 'Cha...
# # PySNMP MIB module ZHONE-COM-IP-ZEDGE-NAT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-COM-IP-ZEDGE-NAT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:41:01 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, constraints_intersection, value_range_constraint, single_value_constraint, value_size_constraint) ...
# Data paths DATA_BACKGROUND_FOLDER = "../data/background/" DATA_GENERATED_FOLDER = "../data/generated_data/" # General settings IMAGES_TO_GENERATE = 500 COIN_RESIZE_RATIO_MIN = 0.4 COIN_RESIZE_RATIO_MAX = 0.6 # Background settings BACKGROUND_RESIZE_RATIO = 400 BACKGROUND_MAX_N_COINS = 25 # Coin crop settings MAX_CO...
data_background_folder = '../data/background/' data_generated_folder = '../data/generated_data/' images_to_generate = 500 coin_resize_ratio_min = 0.4 coin_resize_ratio_max = 0.6 background_resize_ratio = 400 background_max_n_coins = 25 max_coin_overlap_percentage = 0.33 individual_coin_crop_noise = 0.05
""" This is the Blockchain Model class implementation """ class Blockchain: def __init__(self): self.current_transactions = [] self.chain = [] self.nodes = set() def __repr__(self): return '<Blockchain(chain={self.chain!r}, current_transactions={self.current_transactions!r})>'....
""" This is the Blockchain Model class implementation """ class Blockchain: def __init__(self): self.current_transactions = [] self.chain = [] self.nodes = set() def __repr__(self): return '<Blockchain(chain={self.chain!r}, current_transactions={self.current_transactions!r})>'...
#!/usr/bin/env python3 """Helper for finding threshold values for CO alarm.""" # The calculation is based of https://github.com/ElectronicCats/MICS4514-Croquette # and is not verified. LOAD_RESISTOR_OHM = 47000 VSUP = 3.3 VREF = 3.3 ADC_RESOLUTION_BITS = 10 def _main(): """Present the ppm value for each ADC raw ...
"""Helper for finding threshold values for CO alarm.""" load_resistor_ohm = 47000 vsup = 3.3 vref = 3.3 adc_resolution_bits = 10 def _main(): """Present the ppm value for each ADC raw value for the MiCS-4515.""" for adc in range(2 ** ADC_RESOLUTION_BITS): try: vco = VREF * adc / (2 ** ADC_R...
""" Given an array, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i. More formally, G[i] for an element A[i] = an element A[j] such that j is maximum possible AND j < i AND A[j] < A[i] Elements for which no smaller element exist, ...
""" Given an array, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i. More formally, G[i] for an element A[i] = an element A[j] such that j is maximum possible AND j < i AND A[j] < A[i] Elements for which no smaller element exist, ...
# Test values must be in the form [(text_input, expected_output), (text_input, expected_output), ...] test_values = [ ( "president", { "n": { "president", "presidentship", "presidencies", "presidency", "presi...
test_values = [('president', {'n': {'president', 'presidentship', 'presidencies', 'presidency', 'presidentships', 'presidents'}, 'r': {'presidentially'}, 'a': {'presidential'}, 'v': {'presiding', 'presides', 'preside', 'presided'}}), ('elect', {'n': {'elector', 'elects', 'electors', 'elective', 'electorates', 'elect', ...
def simulate_accuracy_vs_stoptime(sigma, stop_time_list, num_sample): """Calculate the average decision accuracy vs. stopping time by running repeated SPRT simulations for each stop time. Args: sigma (float): standard deviation for observation model stop_list_list (list-like object): a list of stoppi...
def simulate_accuracy_vs_stoptime(sigma, stop_time_list, num_sample): """Calculate the average decision accuracy vs. stopping time by running repeated SPRT simulations for each stop time. Args: sigma (float): standard deviation for observation model stop_list_list (list-like object): a list of stop...
def myfunc(str): print(str) nstr = str.lower() for i in range(len(str)): nstr[i+1].upper() return nstr print(myfunc("SlseJbKWdOEuhB"))
def myfunc(str): print(str) nstr = str.lower() for i in range(len(str)): nstr[i + 1].upper() return nstr print(myfunc('SlseJbKWdOEuhB'))
''' @Coded by TSG, 2021 Problem: FizzBuzz is a well known programming assignment, asked during interviews. The given code solves the FizzBuzz problem and uses the words "Solo" and "Learn" instead of "Fizz" and "Buzz". It takes an input n and outputs the numbers from 1 to n. For each multiple of 3, print "Solo" inst...
""" @Coded by TSG, 2021 Problem: FizzBuzz is a well known programming assignment, asked during interviews. The given code solves the FizzBuzz problem and uses the words "Solo" and "Learn" instead of "Fizz" and "Buzz". It takes an input n and outputs the numbers from 1 to n. For each multiple of 3, print "Solo" inst...
# # PySNMP MIB module HP-ICF-MLD-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-MLD-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:22:09 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint) ...
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard 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 3 of t...
__all__ = ['mainDB', 'cache']
class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ start = 0 end = len(height)-1 best = 0 while start < end: best = max(best, self.getArea(start,end,height)) if height[start] < height...
class Solution(object): def max_area(self, height): """ :type height: List[int] :rtype: int """ start = 0 end = len(height) - 1 best = 0 while start < end: best = max(best, self.getArea(start, end, height)) if height[start] < h...
def read_passphrases(): with open("day_04/input.txt", "r") as f: return [line.split() for line in f.readlines()] def part1(): return sum(len(phrase) == len(set(phrase)) for phrase in read_passphrases()) print(part1()) def anagram(passphrase): return len(passphrase) == len(set("".join(sorted(ph...
def read_passphrases(): with open('day_04/input.txt', 'r') as f: return [line.split() for line in f.readlines()] def part1(): return sum((len(phrase) == len(set(phrase)) for phrase in read_passphrases())) print(part1()) def anagram(passphrase): return len(passphrase) == len(set((''.join(sorted(phr...
autoref_rst=""" Math ==== .. index :: single: Math This is the reference documentation for the math modules. """ __all__ = ['kernel']
autoref_rst = '\nMath\n====\n.. index :: \n single: Math\n\nThis is the reference documentation for the math modules.\n' __all__ = ['kernel']
""" ID: IEV Title: Calculating Expected Offspring URL: http://rosalind.info/problems/iev/ """ # 1. P(AA-AA) = 1 (AA, AA, AA, AA) = 4/4 # 2. P(AA-Aa) = 1 (AA, AA, Aa, Aa) = 4/4 # 3. P(AA-aa) = 1 (Aa, Aa, Aa, Aa) = 4/4 # 4. P(Aa-Aa) = 0.75 (AA, Aa, Aa, aa) = 3/4 # 5. P(Aa-aa) = 0.5 (Aa, Aa, aa, aa) = 2/4 # 6. P(aa-aa) =...
""" ID: IEV Title: Calculating Expected Offspring URL: http://rosalind.info/problems/iev/ """ probabilities = [1, 1, 1, 0.75, 0.5, 0] def get_expected_offspring(couples_string): """ Calculates the expected number of offspring displaying the dominant phenotype in the next generation, under the assumption t...
def n_params(model): """Return the number of parameters in a pytorch model. Args: model (nn.Module): The model to analyze. Returns: int: The number of parameters in the model. """ pp = 0 for p in list(model.parameters()): nn = 1 for s in list(p.size()): ...
def n_params(model): """Return the number of parameters in a pytorch model. Args: model (nn.Module): The model to analyze. Returns: int: The number of parameters in the model. """ pp = 0 for p in list(model.parameters()): nn = 1 for s in list(p.size()): ...
n = int(input()) a = sorted(list(map(int, input().split()))) if n % 2 == 1 and a[0] != 0: print(0) exit() for i in range(n % 2, n, 2): if a[i] != a[i + 1] or a[i] != i + 1: print(0) exit() print(2 ** (n // 2) % (10 ** 9 + 7))
n = int(input()) a = sorted(list(map(int, input().split()))) if n % 2 == 1 and a[0] != 0: print(0) exit() for i in range(n % 2, n, 2): if a[i] != a[i + 1] or a[i] != i + 1: print(0) exit() print(2 ** (n // 2) % (10 ** 9 + 7))
#------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. #-------------------------------------------------------------------------- # This is a placeholder file. It is deployed with inference only wheel. pr...
print('An inference only version of ONNX Runtime is installed. Training functionalities are unavailable.')
# Copyright 2010-2012 Institut Mines-Telecom # # 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 agre...
""" Created on Jun 19, 2012 @author: Bilel Msekni @contact: bilel.msekni@telecom-sudparis.eu @author: Houssem Medhioub @contact: houssem.medhioub@it-sudparis.eu @organization: Institut Mines-Telecom - Telecom SudParis @license: Apache License, Version 2.0 """ kind = '{"kinds": [{"term": "compute",\n"scheme": "http://s...
''' Basic Info ''' __version__ = '0.1'
""" Basic Info """ __version__ = '0.1'
def maprange( a, b, s): (a1, a2), (b1, b2) = a, b return b1 + ((s - a1) * (b2 - b1) / (a2 - a1)) for s in range(11): print("%2g maps to %g" % (s, maprange( (0, 10), (-1, 0), s)))
def maprange(a, b, s): ((a1, a2), (b1, b2)) = (a, b) return b1 + (s - a1) * (b2 - b1) / (a2 - a1) for s in range(11): print('%2g maps to %g' % (s, maprange((0, 10), (-1, 0), s)))
strings = { 'str NaN': 'NaN', 'str none': 'None', 'str true': 'True', 'str false': 'False', 'str 0': '0', 'str -1': '-1', 'str -1.5': '-1.5', 'str 0.42': '0.42', 'str .42': '.42', 'str 1.2E+9': '1.2E+9', 'str 1.2e8': '1.2e8', 'str 0xFF': '0xFF', 'str Inf..': 'Infinity...
strings = {'str NaN': 'NaN', 'str none': 'None', 'str true': 'True', 'str false': 'False', 'str 0': '0', 'str -1': '-1', 'str -1.5': '-1.5', 'str 0.42': '0.42', 'str .42': '.42', 'str 1.2E+9': '1.2E+9', 'str 1.2e8': '1.2e8', 'str 0xFF': '0xFF', 'str Inf..': 'Infinity', 'str empty': '', 'str space': ' ', 'str [Ob]': '[o...
# coding: utf8 #!/usr/bin/python2 def directorymaker(): pass
def directorymaker(): pass
ZALORA_URLS = ['https://www.zalora.co.id/women/pakaian/atasan/?from=header'] def get_start_urls(): return ZALORA_URLS
zalora_urls = ['https://www.zalora.co.id/women/pakaian/atasan/?from=header'] def get_start_urls(): return ZALORA_URLS
name0_0_0_1_0_1_0 = None name0_0_0_1_0_1_1 = None name0_0_0_1_0_1_2 = None name0_0_0_1_0_1_3 = None name0_0_0_1_0_1_4 = None
name0_0_0_1_0_1_0 = None name0_0_0_1_0_1_1 = None name0_0_0_1_0_1_2 = None name0_0_0_1_0_1_3 = None name0_0_0_1_0_1_4 = None
# Copyright (C) 2019-2020, TomTom (http://tomtom.com). # # 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 o...
class Coordinate: """Class to hold information about a coordinate. A coordinate has a latitude, longitude, and an altitude. Attributes: latitude: Latitude in degrees. longitude: Longitude in degrees. altitude: Altitude in meters. """ latitude: float longitude: float ...
email_info = { 'recepient' : 'a.b@c.com', 'messages' : {'TOO_LOW' : 'Hi, the temperature is too low', 'TOO_HIGH' : 'Hi, the temperature is too high' } } def DefineCoolingtype_limits(coolingType): coolingtype_limits = { 'P...
email_info = {'recepient': 'a.b@c.com', 'messages': {'TOO_LOW': 'Hi, the temperature is too low', 'TOO_HIGH': 'Hi, the temperature is too high'}} def define_coolingtype_limits(coolingType): coolingtype_limits = {'PASSIVE_COOLING': {'lowerLimit': 0, 'upperLimit': 35}, 'HI_ACTIVE_COOLING': {'lowerLimit': 0, 'upperLi...
# -*- coding: utf-8 -*- # vim: set sw=4 ts=4 expandtab : class ArgError(Exception): def __init__(self, message): if message == None: self.message = 'node error' else: self.message = message
class Argerror(Exception): def __init__(self, message): if message == None: self.message = 'node error' else: self.message = message
@PixieApp class Test(): @route() def main_screen(self): return """ <button type="submit" pd_script="call_me()" pd_target="target{{prefix}}"> <pd_script> self.name="some value" print("This is a multi-line pd_script") </pd_script> Click me </button> ...
@PixieApp class Test: @route() def main_screen(self): return '\n <button type="submit" \npd_script="call_me()" \npd_target="target{{prefix}}">\n <pd_script>\nself.name="some value"\nprint("This is a multi-line pd_script")\n </pd_script>\n Click me\n </butt...
def formula_transform(formula): """ :param formula: dependent variable ~ covariant | fixed_effect |clusters' :type formula: str :return: Lists of out_col, consist_col, category_col, cluster_col, respectively. :rtype: (list[str], list[str], list[str], list[str]) """ phenotype = formula.repl...
def formula_transform(formula): """ :param formula: dependent variable ~ covariant | fixed_effect |clusters' :type formula: str :return: Lists of out_col, consist_col, category_col, cluster_col, respectively. :rtype: (list[str], list[str], list[str], list[str]) """ phenotype = formula.repl...
# encoding: utf-8 # module System.Custom calls itself Custom # from Wms.RemotingObjects,Version=1.23.1.0,Culture=neutral,PublicKeyToken=null # by generator 1.145 # no doc # no important # functions def Tuple(args,kwargs): # real signature unknown """ """ pass # no classes
def tuple(args, kwargs): """ """ pass
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if head is None: return head l = 1 tail = head while tail.next: ...
class Listnode: def __init__(self, x): self.val = x self.next = None class Solution: def rotate_right(self, head: ListNode, k: int) -> ListNode: if head is None: return head l = 1 tail = head while tail.next: tail = tail.next ...
"""VIC Emergency Incidents constants.""" ATTR_CATEGORY1 = "category1" ATTR_CATEGORY2 = "category2" ATTR_DESCRIPTION = "description" ATTR_ID = "id" ATTR_PUB_DATE = "updated" ATTR_SOURCE_TITLE = "sourceTitle" ATTR_SOURCE_ORG = "sourceOrg" ATTR_ESTA_ID = "estaid" ATTR_RESOURCES = "resources" ATTRIBUTION = "VICEmergency" ...
"""VIC Emergency Incidents constants.""" attr_category1 = 'category1' attr_category2 = 'category2' attr_description = 'description' attr_id = 'id' attr_pub_date = 'updated' attr_source_title = 'sourceTitle' attr_source_org = 'sourceOrg' attr_esta_id = 'estaid' attr_resources = 'resources' attribution = 'VICEmergency' a...
class ApiException(Exception): def __init__(self, response): if response.status_code == 404: self._rollbar_ignore = True message = response.text super(ApiException, self).__init__(message)
class Apiexception(Exception): def __init__(self, response): if response.status_code == 404: self._rollbar_ignore = True message = response.text super(ApiException, self).__init__(message)
__author__ = 'Chirag' x = {"Tom", 2.71, 36, 36} # is a set. REPETITION NOT ALLOWED y = ["Tom", 2.71, 36, 36] # is a list. MUTABLE print("x is a SET : ", x) print("y is a LIST : ", y) print() #=========================================== # CREATE sets s = {1,2,3,4,5} # direct declare print(s) s = set() for i i...
__author__ = 'Chirag' x = {'Tom', 2.71, 36, 36} y = ['Tom', 2.71, 36, 36] print('x is a SET : ', x) print('y is a LIST : ', y) print() s = {1, 2, 3, 4, 5} print(s) s = set() for i in range(1, 6): s.add(i) print(s) s = set([x for x in range(1, 6)]) print(s) print() list1 = [1, 1, 2, 2, 3, 4, 5, 6, 1, 1] print(f'l...
# Python3 program to Merge Two Binary Trees # Helper class that allocates a new node # with the given data and None left and # right pointers. class newNode: def __init__(self, data): self.data = data self.left = self.right = None # Given a binary tree, prints nodes # in inorder def inorder(node)...
class Newnode: def __init__(self, data): self.data = data self.left = self.right = None def inorder(node): if not node: return inorder(node.left) print(node.data, end=' ') inorder(node.right) def merge_trees(t1, t2): if not t1: return t2 if not t2: ...
def find_lis(a): T = [None]*len(a) prev = [None]*len(a) for i in range(len(a)): T[i] = 1 prev[i] = -1 for j in range(i): if a[j] <= a[i] and T[i]< T[j]+1: T[i] = T[j]+1 prev[i] = j longest =max(T) i = 0 for i in range( ...
def find_lis(a): t = [None] * len(a) prev = [None] * len(a) for i in range(len(a)): T[i] = 1 prev[i] = -1 for j in range(i): if a[j] <= a[i] and T[i] < T[j] + 1: T[i] = T[j] + 1 prev[i] = j longest = max(T) i = 0 for i in range(...
# -*- coding: utf-8 -*- """ Created on Mon Dec 6 23:56:31 2010 @author: Alexander Tsepkov """ """ This class wraps around ImageData HTML5 Canvas object and allows easier per-pixel access """ class ImageData: def __init__(self, imagedata): self.width = imagedata.width self.height = imagedata.heig...
""" Created on Mon Dec 6 23:56:31 2010 @author: Alexander Tsepkov """ '\nThis class wraps around ImageData HTML5 Canvas object and allows easier \nper-pixel access\n' class Imagedata: def __init__(self, imagedata): self.width = imagedata.width self.height = imagedata.height self.data = i...
# Problem 3 # Largest prime factor # The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? def is_prime(num): if num == 1: return False i = 2 while i*i <= num: if num % i == 0: return False i += 1 return True...
def is_prime(num): if num == 1: return False i = 2 while i * i <= num: if num % i == 0: return False i += 1 return True huge = 600851475143 for x in reversed(range(1, 10000)): if is_prime(x): if huge % x == 0: print(x)
# defines a mutable class class Mutable(): def __init__(self): self.layers = [] def getGen(self): gen = [] for layer in self.layers: gen += layer.getWeights() return gen def mutateWith(self, lover): genSelf = self.getGen() genLover = lover.getG...
class Mutable: def __init__(self): self.layers = [] def get_gen(self): gen = [] for layer in self.layers: gen += layer.getWeights() return gen def mutate_with(self, lover): gen_self = self.getGen() gen_lover = lover.getGen() self.setGen(...
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- __author__ = 'Florents Tselai' REDIS_URI = '127.0.0.1' REDIS_CAR_KEYSPACE = 'pycargr:car:{}' SEARCH_BASE_URL = 'https://www.car.gr/classifieds/cars/' CACHE_EXPIRE_IN = 24 * 3600
__author__ = 'Florents Tselai' redis_uri = '127.0.0.1' redis_car_keyspace = 'pycargr:car:{}' search_base_url = 'https://www.car.gr/classifieds/cars/' cache_expire_in = 24 * 3600
""" [2015-07-06] Challenge #222 [Easy] Balancing Words https://www.reddit.com/r/dailyprogrammer/comments/3c9a9h/20150706_challenge_222_easy_balancing_words/ # Description Today we're going to balance words on one of the letters in them. We'll use the position and letter itself to calculate the weight around the balan...
""" [2015-07-06] Challenge #222 [Easy] Balancing Words https://www.reddit.com/r/dailyprogrammer/comments/3c9a9h/20150706_challenge_222_easy_balancing_words/ # Description Today we're going to balance words on one of the letters in them. We'll use the position and letter itself to calculate the weight around the balan...
a = 28 b = 1.5 c = 'hello' d = True e = None print(a,b,c,d,e)
a = 28 b = 1.5 c = 'hello' d = True e = None print(a, b, c, d, e)
# -*- coding: utf-8 -*- class Fila: def __init__(self): self.element = list() def inserir(self,name): self.element.append(name) print(f'Inserindo o elemento {name}: ' + ' '.join(self.element)) def remover(self): self.element.pop(0) print(f'Removendo o primeiro elemento: ' + ' '.join(...
class Fila: def __init__(self): self.element = list() def inserir(self, name): self.element.append(name) print(f'Inserindo o elemento {name}: ' + ' '.join(self.element)) def remover(self): self.element.pop(0) print(f'Removendo o primeiro elemento: ' + ' '.join(self...
load("@bazel_skylib//lib:shell.bzl", "shell") load("@bazel_skylib//lib:paths.bzl", "paths") AsciidocInfo = provider( doc = "Information about the asciidoc-generated files.", fields = { "primary_output_path": "Path of the primary output file beneath {resource_dir}.", "resource_dir": "File for th...
load('@bazel_skylib//lib:shell.bzl', 'shell') load('@bazel_skylib//lib:paths.bzl', 'paths') asciidoc_info = provider(doc='Information about the asciidoc-generated files.', fields={'primary_output_path': 'Path of the primary output file beneath {resource_dir}.', 'resource_dir': 'File for the directory containing all of ...
# return the keys of a dictionary def keys(dictionary): return dictionary.keys() # return the values of a dictionary def values(dictionary): return dictionary.values() # return the string representation of a dictionary def dict_to_string(d): return str(d) # merge two dictionaries def merge(d1, d2): ...
def keys(dictionary): return dictionary.keys() def values(dictionary): return dictionary.values() def dict_to_string(d): return str(d) def merge(d1, d2): for (k, v) in d2.iteritems(): if k in d1.keys(): if type(v) is dict: if type(d1[k]) is dict: ...
def parse_line(line): splitted = line.strip().split() instruction, count = splitted[0], int(splitted[1]) return instruction, count def parse_input(filename): with open(filename) as file: lines = file.readlines() return [parse_line(l) for l in lines] def evaluate_til_repeat(instructions)...
def parse_line(line): splitted = line.strip().split() (instruction, count) = (splitted[0], int(splitted[1])) return (instruction, count) def parse_input(filename): with open(filename) as file: lines = file.readlines() return [parse_line(l) for l in lines] def evaluate_til_repeat(instructio...
def runonce(): # This is only ran when OSIRIS is restarted, unlike normal live updates return {} def depends(): # this is list of modules to import from app return ['testmodule', 'osirisd'] def reply(msg): """ code, header, and template are optional header is another json dict thing ...
def runonce(): return {} def depends(): return ['testmodule', 'osirisd'] def reply(msg): """ code, header, and template are optional header is another json dict thing template is another, but entries in the msg called (or in the file passed) {{ something }} will get replaced with the value ...
class Data: def __init__(self): self.__dia = 0 self.__mes = 0 self.__ano = 0 def le_data(self): self.dia = int(input('Digite o dia: ')) self.mes = int(input('Digite o mes: ')) self.ano = int(input('Digite o ano: ')) def formatada(self): print(f'{self...
class Data: def __init__(self): self.__dia = 0 self.__mes = 0 self.__ano = 0 def le_data(self): self.dia = int(input('Digite o dia: ')) self.mes = int(input('Digite o mes: ')) self.ano = int(input('Digite o ano: ')) def formatada(self): print(f'{sel...
""" Given two strings A and B, return whether or not A can be shifted some number of times to get B. For example, if A is abcde and B is cdeab, return true. If A is abc and B is acb, return false """ class Solution: def rotateString(self, A, B): N = len(A) if N != len(B): return False ...
""" Given two strings A and B, return whether or not A can be shifted some number of times to get B. For example, if A is abcde and B is cdeab, return true. If A is abc and B is acb, return false """ class Solution: def rotate_string(self, A, B): n = len(A) if N != len(B): return Fals...
#este es el ejercicio 3.1 def ejercicio01(): print ("Como saber si puedes votar por tu edad") mensaje="" #Ingreso de datos edadP=int(input("ingrese la edad que tiene:")) #Proceso if edadP>=18: mensaje="Usted tiene la edad necesaria para votar" else: mensaje="Usted no cumple con la edad minima para...
def ejercicio01(): print('Como saber si puedes votar por tu edad') mensaje = '' edad_p = int(input('ingrese la edad que tiene:')) if edadP >= 18: mensaje = 'Usted tiene la edad necesaria para votar' else: mensaje = 'Usted no cumple con la edad minima para votar' print(mensaje) ej...
spam = {'name': 'Pooka', 'age': 5} print("Before:") print(spam) #Traditional if 'color' not in spam: spam['color'] = 'black' print("After:") print(spam) #With setDefault() spam.setdefault("color", "white") print(spam) message = 'It was a bright cold day in April, and the clocks were striking thirteen.' count...
spam = {'name': 'Pooka', 'age': 5} print('Before:') print(spam) if 'color' not in spam: spam['color'] = 'black' print('After:') print(spam) spam.setdefault('color', 'white') print(spam) message = 'It was a bright cold day in April, and the clocks were striking thirteen.' count = {} for character in message: cou...
"""This solution uses addition repititively to find largest power n of 2 such that 2**n*b < a. Then you keep subtracting these multiples of b of the form 2**i*b for smaller powers until the remainder is smaller than b. Each time you subtract, take the previous quotient and multiply by two. If there is any remaining in ...
"""This solution uses addition repititively to find largest power n of 2 such that 2**n*b < a. Then you keep subtracting these multiples of b of the form 2**i*b for smaller powers until the remainder is smaller than b. Each time you subtract, take the previous quotient and multiply by two. If there is any remaining in ...
# Problem 2. # Write the function subStringMatchExact. This function takes two arguments: a target string, # and a key string. It should return a tuple of the starting points of matches of the key # string in the target string, when indexing starts at 0. Complete the definition for # # def subStringMatchExact(target,ke...
def sub_string_match_exact(target, key): position_list = [] begin_point = 0 temp_position = 0 while temp_position >= 0: temp_position = target.find(key, begin_point) if temp_position >= 0: begin_point = temp_position + 1 position_list.append(temp_position) pos...
''' Palindrome checker by python ''' #Palindrome check for String inputs. def palindrome (s): r=s[::-1] if(r==s): print("Yes It is a palindrome") else: print("No It is not a palindrome") s = input("Enter a String to check whether it is palindrome or not") palin...
""" Palindrome checker by python """ def palindrome(s): r = s[::-1] if r == s: print('Yes It is a palindrome') else: print('No It is not a palindrome') s = input('Enter a String to check whether it is palindrome or not') palindrome(s) num = int(input('Enter a n...
""" Number Data types Integers(int) Floating Point(float) Integer is a w """
""" Number Data types Integers(int) Floating Point(float) Integer is a w """
class BaseError(Exception): ... class InternalError(BaseError): _default = "An internal error has occurred." def __init__(self): super().__init__(self._default)
class Baseerror(Exception): ... class Internalerror(BaseError): _default = 'An internal error has occurred.' def __init__(self): super().__init__(self._default)
""" Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example: Given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6. For this problem, return the maximum sum. """ class Solution: # @param A : tuple of inte...
""" Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example: Given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6. For this problem, return the maximum sum. """ class Solution: def max_sub_array(self, A...
class Solution: def hammingDistance(self, x: int, y: int) -> int: dis = 0 while x != 0 or y !=0: x,resx = x //2, x%2 y,resy = y//2, y%2 if resx!= resy: dis +=1 return dis class Solution: def hammingDistance(self, x: int, y: int) -> int...
class Solution: def hamming_distance(self, x: int, y: int) -> int: dis = 0 while x != 0 or y != 0: (x, resx) = (x // 2, x % 2) (y, resy) = (y // 2, y % 2) if resx != resy: dis += 1 return dis class Solution: def hamming_distance(self...
QUERIES = { 'average_movies_per_user': ( 'select avg(movies_watched) ' 'from ( ' 'select count(movie_id) as movies_watched ' 'from views ' 'group by user_id ' ' ) as movies_count;' ), 'average_view_times': 'select avg(viewed_frame) from views;', 'top_20_...
queries = {'average_movies_per_user': 'select avg(movies_watched) from ( select count(movie_id) as movies_watched from views group by user_id ) as movies_count;', 'average_view_times': 'select avg(viewed_frame) from views;', 'top_20_users_by_total_view_time': 'select user_id, sum(viewed_frame) as view_time from view...
# Logic: Write a program that find the maximum positive integer from user input. # Algorithm: append all the numbers to a list and use the built-in method 'max()' to get the highest number in the list. num_int = int(input("Input a number: ")) num_list = [] while num_int >= 0: num_int = int(input("Input a number: ...
num_int = int(input('Input a number: ')) num_list = [] while num_int >= 0: num_int = int(input('Input a number: ')) num_list.append(num_int) print('The maximum is', max(num_list))
def _print_aspect_impl(target, ctx): # Make sure the rule has a srcs attribute. if hasattr(ctx.rule.attr, 'srcs'): # Iterate through the files that make up the sources and # print their paths. for src in ctx.rule.attr.srcs: for f in src.files.to_list(): print...
def _print_aspect_impl(target, ctx): if hasattr(ctx.rule.attr, 'srcs'): for src in ctx.rule.attr.srcs: for f in src.files.to_list(): print(f.path) return [] print_aspect = aspect(implementation=_print_aspect_impl, attr_aspects=['deps'])
for t in range(int(input())): n=int(input()) k = 3 + 5**(1/2) s = str(int(k**n)) if len(s) <3: s = "0"*(3-len(s)) +s print("Case #{}: {}".format(t+1,s[-3:]))
for t in range(int(input())): n = int(input()) k = 3 + 5 ** (1 / 2) s = str(int(k ** n)) if len(s) < 3: s = '0' * (3 - len(s)) + s print('Case #{}: {}'.format(t + 1, s[-3:]))
load( "@rules_scala3//rules:providers.bzl", _ScalaConfiguration = "ScalaConfiguration", _ScalaRulePhase = "ScalaRulePhase", ) def run_phases(ctx, phases): phase_providers = [ p[_ScalaRulePhase] for p in [ctx.attr.scala] + ctx.attr.plugins + ctx.attr._phase_providers if _ScalaRul...
load('@rules_scala3//rules:providers.bzl', _ScalaConfiguration='ScalaConfiguration', _ScalaRulePhase='ScalaRulePhase') def run_phases(ctx, phases): phase_providers = [p[_ScalaRulePhase] for p in [ctx.attr.scala] + ctx.attr.plugins + ctx.attr._phase_providers if _ScalaRulePhase in p] if phase_providers != []: ...
# Copyright 2017-2020 EPAM Systems, Inc. (https://www.epam.com/) # # 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 appli...
class Sharemountmodel(object): def __init__(self): self.identifier = None self.region_id = None self.mount_root = None self.mount_type = None self.mount_options = None @classmethod def load(cls, json): instance = share_mount_model() if not json: ...
X, Y, N = map(int, input().split()) grid = [] win = '' for i in range(X): grid.append([]) for j, val in enumerate(input().split()): grid[i].append({'R':0,'B':0, 'dir':'none'}) if val != 'O': grid[i][j][val] = 1 up, left, upleft, upright = 0, 0, 0, 0 ...
(x, y, n) = map(int, input().split()) grid = [] win = '' for i in range(X): grid.append([]) for (j, val) in enumerate(input().split()): grid[i].append({'R': 0, 'B': 0, 'dir': 'none'}) if val != 'O': grid[i][j][val] = 1 (up, left, upleft, upright) = (0, 0, 0, 0) ...
# Copied from https://rosettacode.org/wiki/Shortest_common_supersequence#Python # Use the Longest Common Subsequence algorithm def shortest_common_supersequence(a, b): lcs = longest_common_subsequence(a, b) scs = "" # Consume lcs while len(lcs) > 0: if a[0]==lcs[0] and b[0]==lcs[0]: # ...
def shortest_common_supersequence(a, b): lcs = longest_common_subsequence(a, b) scs = '' while len(lcs) > 0: if a[0] == lcs[0] and b[0] == lcs[0]: scs += lcs[0] lcs = lcs[1:] a = a[1:] b = b[1:] elif a[0] == lcs[0]: scs += b[0] ...
def extract_tib_only(csv_dump): lines = csv_dump.strip().split('\n') # cut dump in lines lines = [l.split(',')[1] for l in lines] # only keep the text lines = [lines[i] for i in range(0, len(lines), 2)] # only keep the tibetan return ''.join(lines) def extract_all(csv_dump): lines = csv_dump....
def extract_tib_only(csv_dump): lines = csv_dump.strip().split('\n') lines = [l.split(',')[1] for l in lines] lines = [lines[i] for i in range(0, len(lines), 2)] return ''.join(lines) def extract_all(csv_dump): lines = csv_dump.strip().split('\n') lines = [l.split(',')[1] for l in lines] re...
#! /usr/bin/env python3 description = """ Power digit sum Problem 16 215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? """ print(sum(int(x) for x in str(2**1000)))
description = '\nPower digit sum\nProblem 16\n215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.\n\nWhat is the sum of the digits of the number 21000?\n' print(sum((int(x) for x in str(2 ** 1000))))
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/7/31 17:52 # @Author : Leishichi # @File : 27.py # @Software: PyCharm # @Tag: class Solution: def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ if len(nums)...
class Solution: def remove_element(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ if len(nums) == 0: return 0 length = 0 for i in range(len(nums)): if val != nums[i]: nums[length] = n...
# 26.05.2019 # Tuples vs Lists # Tuples are read only # Tuples have ( ) brackets # Example with a List: awesomeList= ['hello', 45, 'Marc', 89.4] awesomeList[3] = 6 # List can be updated print(awesomeList) # now a tuple awesomeTuple = ('MarcTuple', 1, 213.2, 'Hello') print(awesomeTuple) print(awesomeTuple[2]) ...
awesome_list = ['hello', 45, 'Marc', 89.4] awesomeList[3] = 6 print(awesomeList) awesome_tuple = ('MarcTuple', 1, 213.2, 'Hello') print(awesomeTuple) print(awesomeTuple[2]) print(awesomeTuple[0][2:5]) var7 = awesomeTuple[0][2:5] var8 = awesomeTuple[2] print(var7 * 3) print(var8 * 3)
def dfCheckAvailability(df, baseTrackingMap): ##### # step number -- iStep bIStep = False if not ("iStep" in df.columns) else True print("scan step number (iStep) availability: %s \n--" % str(bIStep)) ##### # Unix time -- epoch bEpoch = False if not ("epoch" in df.columns) else True ...
def df_check_availability(df, baseTrackingMap): b_i_step = False if not 'iStep' in df.columns else True print('scan step number (iStep) availability: %s \n--' % str(bIStep)) b_epoch = False if not 'epoch' in df.columns else True print('Unix time (epoch) availability: %s \n--' % str(bEpoch)) ls_gonio...
# -*- coding: utf-8 -*- """ Created on Tue Jul 14 13:26:18 2020 @author: abhi0 """ class Solution: def isSubsequence(self, s: str, t: str) -> bool: for i in s: if i in t: tempIdx=t.index(i) t=t[tempIdx+1:] else: return Fal...
""" Created on Tue Jul 14 13:26:18 2020 @author: abhi0 """ class Solution: def is_subsequence(self, s: str, t: str) -> bool: for i in s: if i in t: temp_idx = t.index(i) t = t[tempIdx + 1:] else: return False return True
list1 = [1, 7, 16, 11, 14, 19, 20, 18] list2 = [85, 111, 117, 43, 104, 127, 117, 117, 33, 110, 99, 43, 72, 95, 85, 85, 94, 66, 120, 98, 79, 117, 68, 83, 64, 94, 39, 65, 73, 32, 65, 72, 51] ans = '' for i in range(len(list2)): ans += chr(list2[i] ^ list1[i % len(list1)]) print(ans)
list1 = [1, 7, 16, 11, 14, 19, 20, 18] list2 = [85, 111, 117, 43, 104, 127, 117, 117, 33, 110, 99, 43, 72, 95, 85, 85, 94, 66, 120, 98, 79, 117, 68, 83, 64, 94, 39, 65, 73, 32, 65, 72, 51] ans = '' for i in range(len(list2)): ans += chr(list2[i] ^ list1[i % len(list1)]) print(ans)
""" A nevelty COVID-19 Infections estimator function. """ def estimator(data): #calculations for the currentlyInfected property impact_ci = data['reportedCases']*10 severe_ci = data['reportedCases']*50 #calculations for the inFectedByRequestTime if data['periodType'] == 'days': impact_ibr...
""" A nevelty COVID-19 Infections estimator function. """ def estimator(data): impact_ci = data['reportedCases'] * 10 severe_ci = data['reportedCases'] * 50 if data['periodType'] == 'days': impact_ibrt = int(impact_ci * 2 ** int(data['timeToElapse'] / 3)) severe_ibrt = int(severe_ci * 2 ** ...
class Array(object): def __init__(self, capacity, fill_value=None): """Capacity is the static size of the array. fillValue is placed at each position.""" self._items = list() for count in range(capacity): self._items.append(fill_value) def __len__(self): """-...
class Array(object): def __init__(self, capacity, fill_value=None): """Capacity is the static size of the array. fillValue is placed at each position.""" self._items = list() for count in range(capacity): self._items.append(fill_value) def __len__(self): """...
f = open("Street_Centrelines.csv",'r') def tup(): for v in f: v = v.split(",") t = (v[2], v[4], v[6], v[7]) print(t) def maintenance(): h = dict() for f2 in f: f2 = f2.split(",") if f2[12] not in h: h[f2[12]] = 1 else: h[f[12]] += 1 print(h) ...
f = open('Street_Centrelines.csv', 'r') def tup(): for v in f: v = v.split(',') t = (v[2], v[4], v[6], v[7]) print(t) def maintenance(): h = dict() for f2 in f: f2 = f2.split(',') if f2[12] not in h: h[f2[12]] = 1 else: h[f[12]] += 1 ...
words = ['one', 'fish', 'two', 'fish', 'red', 'fish', 'blue', 'fish'] words2 = ['have', 'you', 'seen', 'a', 'blue', 'fish'] # what if we did the first example as a generator? def get_word_lengths(word_list): for word in word_list: yield len(word) for length in get_word_lengths(words): print(length) ...
words = ['one', 'fish', 'two', 'fish', 'red', 'fish', 'blue', 'fish'] words2 = ['have', 'you', 'seen', 'a', 'blue', 'fish'] def get_word_lengths(word_list): for word in word_list: yield len(word) for length in get_word_lengths(words): print(length) print('--------------------') for length in (len(word)...
# Time: O(n) # Space: O(1) # We are given two strings, A and B. # # A shift on A consists of taking string A and moving the leftmost character to the rightmost position. # For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True # if and only if A can become B after some number of shifts...
class Solution(object): def rotate_string(self, A, B): """ :type A: str :type B: str :rtype: bool Our approach comes down to quickly checking whether B is a substring of A2 = A+A. Specifically, check whether B = A2[0:N], or B = A2[1:N+1], or B = A2[2:N+2] and so on. ...
# Data processing with open('input') as f: in_data = [line.rstrip() for line in f] for i in range(25, len(in_data)): pre_i = in_data[i-25:i] summed_pair_found = False for a in pre_i: for b in pre_i: if a != b: if int(a)+int(b) == int(in_data[i]): ...
with open('input') as f: in_data = [line.rstrip() for line in f] for i in range(25, len(in_data)): pre_i = in_data[i - 25:i] summed_pair_found = False for a in pre_i: for b in pre_i: if a != b: if int(a) + int(b) == int(in_data[i]): summed_pair_fou...
#! python3 pessoas = [ {'nome': 'Pedro', 'idade': 11}, {'nome': 'Mariana', 'idade': 18}, {'nome': 'Arthur', 'idade': 26}, {'nome': 'Rebeca', 'idade': 6}, {'nome': 'Tiago', 'idade': 19}, {'nome': 'Gabriela', 'idade': 17}, ] menores = filter(lambda p: p['idade'] < 18, pessoas) print(list(menores...
pessoas = [{'nome': 'Pedro', 'idade': 11}, {'nome': 'Mariana', 'idade': 18}, {'nome': 'Arthur', 'idade': 26}, {'nome': 'Rebeca', 'idade': 6}, {'nome': 'Tiago', 'idade': 19}, {'nome': 'Gabriela', 'idade': 17}] menores = filter(lambda p: p['idade'] < 18, pessoas) print(list(menores)) nome_maiorede6caracteres = filter(lam...
class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ if x < 0: return -1 elif x == 0: return 0 start, end = 1, x while start + 1 < end: mid = start + (end - start) / 2 if mid**2 ...
class Solution(object): def my_sqrt(self, x): """ :type x: int :rtype: int """ if x < 0: return -1 elif x == 0: return 0 (start, end) = (1, x) while start + 1 < end: mid = start + (end - start) / 2 if mi...
line = input() a, b = line.split() a = int(a) b = int(b) print(a + b)
line = input() (a, b) = line.split() a = int(a) b = int(b) print(a + b)
def load(opt, splits): """ Load the TUF train dataset :return: """ return {"train": [], "val": []}
def load(opt, splits): """ Load the TUF train dataset :return: """ return {'train': [], 'val': []}
class Solution: def strStr(self, haystack: str, needle: str) -> int: """ Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. >>> Solution().strStr("asdf", "") 0 >>> Solution().strStr("h...
class Solution: def str_str(self, haystack: str, needle: str) -> int: """ Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. >>> Solution().strStr("asdf", "") 0 >>> Solution().strStr(...
class ContentTypeSerializer(object): """ A ContentTypeSerializer handles the conversion from a python data structure to a bytes object representing the content in a particular content type. """ def content_type(self): """ return back what a list of content types this ser...
class Contenttypeserializer(object): """ A ContentTypeSerializer handles the conversion from a python data structure to a bytes object representing the content in a particular content type. """ def content_type(self): """ return back what a list of content types this ser...
employees_happiness = [int(happiness) for happiness in input().split()] factor = int(input()) factored_employees_happiness = list(map(lambda h: h * factor, employees_happiness)) find_average_happiness = sum(factored_employees_happiness) / len(factored_employees_happiness) happy_employees = [e for e in factored_employe...
employees_happiness = [int(happiness) for happiness in input().split()] factor = int(input()) factored_employees_happiness = list(map(lambda h: h * factor, employees_happiness)) find_average_happiness = sum(factored_employees_happiness) / len(factored_employees_happiness) happy_employees = [e for e in factored_employee...
db_config = { 'user': 'user', 'password': 'password', 'host': 'host.com', 'port': 12345, 'database': 'db-name', "autocommit": True }
db_config = {'user': 'user', 'password': 'password', 'host': 'host.com', 'port': 12345, 'database': 'db-name', 'autocommit': True}
class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ ''' T: O(m * n) S: (m + n) ''' nrow = len(matrix) ncol = len(matrix[0]) rows, cols = set(), s...
class Solution: def set_zeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ '\n T: O(m * n)\n S: (m + n)\n ' nrow = len(matrix) ncol = len(matrix[0]) (rows, cols) = (set(), set())...
# encoding: utf-8 """ @version: v1.0 @author: Richard @license: Apache Licence @contact: billions.richard@qq.com @site: @software: PyCharm @time: 2019/9/8 9:37 """ def get_remove_len(node_pth: list) -> int: reversed_pth = list(reversed(node_pth)) pth_len = 0 lst_node = reversed_pth[0] for ...
""" @version: v1.0 @author: Richard @license: Apache Licence @contact: billions.richard@qq.com @site: @software: PyCharm @time: 2019/9/8 9:37 """ def get_remove_len(node_pth: list) -> int: reversed_pth = list(reversed(node_pth)) pth_len = 0 lst_node = reversed_pth[0] for node in reversed_pth[1...
VALUE_TYPES = { 'short', 'int', 'long', 'uchar', 'ushort', 'uint', 'ulong', 'bool', 'float', 'double', 'size_t', 'uint8', 'int8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64', } VALA_TYPES = VALUE_TYPES | { 'char', 'string', 'void*', 'void**', 'time_t', } VALA_ALIASES = { 'unsigne...
value_types = {'short', 'int', 'long', 'uchar', 'ushort', 'uint', 'ulong', 'bool', 'float', 'double', 'size_t', 'uint8', 'int8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'} vala_types = VALUE_TYPES | {'char', 'string', 'void*', 'void**', 'time_t'} vala_aliases = {'unsigned int': 'uint', 'short unsigned int...
num = float(input("Enter a Number: ")) if num > 0: print("This is a Positive Number") elif num == 0: print("Zero") else: print("This is a Negative Number")
num = float(input('Enter a Number: ')) if num > 0: print('This is a Positive Number') elif num == 0: print('Zero') else: print('This is a Negative Number')