content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# -*- coding: utf-8 - # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. version_info = (20, 0, 4, "custom") __version__ = ".".join([str(v) for v in version_info]) SERVER = "gunicorn" SERVER_SOFTWARE = "%s/%s" % (SERVER, __version__)
version_info = (20, 0, 4, 'custom') __version__ = '.'.join([str(v) for v in version_info]) server = 'gunicorn' server_software = '%s/%s' % (SERVER, __version__)
''' 03 - Creating histograms Histograms show the full distribution of a variable. In this exercise, we will display the distribution of weights of medalists in gymnastics and in rowing in the 2016 Olympic games for a comparison between them. You will have two DataFrames to use. The first is called mens_rowing and ...
""" 03 - Creating histograms Histograms show the full distribution of a variable. In this exercise, we will display the distribution of weights of medalists in gymnastics and in rowing in the 2016 Olympic games for a comparison between them. You will have two DataFrames to use. The first is called mens_rowing and ...
"""camera_settings.py Note: Currently not used. Proof of concept to show how to change camera settings in one file and have them applied to a camera from a different script. """ def apply_settings(camera): """Changes the settings of a camera.""" camera.clear_mode = 0 camera.exp_mode = "Internal T...
"""camera_settings.py Note: Currently not used. Proof of concept to show how to change camera settings in one file and have them applied to a camera from a different script. """ def apply_settings(camera): """Changes the settings of a camera.""" camera.clear_mode = 0 camera.exp_mode = 'Internal Trigger' ...
# model settings norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained=None, backbone=dict( type='MixVisionTransformer', in_channels=3, embed_dims=32, num_stages=4, num_layers=[2, 2, 2, 2], num_heads=[1, 2, 5, 8], ...
norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict(type='EncoderDecoder', pretrained=None, backbone=dict(type='MixVisionTransformer', in_channels=3, embed_dims=32, num_stages=4, num_layers=[2, 2, 2, 2], num_heads=[1, 2, 5, 8], patch_sizes=[7, 3, 3, 3], sr_ratios=[8, 4, 2, 1], out_indices=(0, 1, 2, 3), mlp_...
# how to create a function def greet(): print("Hello") print("welcome, Edgar") greet() # prints greet() # prints(2) greet() # prints(3) # arguments and parameters def greet(name): # name is a parameter print('hello') print('welcome, ', name) greet('Edgar') # Edgar is the argument # return def greet(n...
def greet(): print('Hello') print('welcome, Edgar') greet() greet() greet() def greet(name): print('hello') print('welcome, ', name) greet('Edgar') def greet(name): if name == 'Edgar': return else: print('hello') print('welcome, ', name) greet('Edgar') def greet(name):...
#! /usr/bin/env python3 """ constants.py - Contains all constants used by the device manager Author: - Nidesh Chitrakar (nideshchitrakar@bennington.edu) - Hoanh An (hoanhan@bennington.edu) Date: 12/07/2017 """ number_of_rows = 3 # total number rows of Index Servers number_of_li...
""" constants.py - Contains all constants used by the device manager Author: - Nidesh Chitrakar (nideshchitrakar@bennington.edu) - Hoanh An (hoanhan@bennington.edu) Date: 12/07/2017 """ number_of_rows = 3 number_of_links = 5 number_of_chunks = 5 number_of_comps = 10
def convert_date_string_to_period(timestamp) -> int: try: month = int(timestamp.month) except AttributeError: return -1 else: return month
def convert_date_string_to_period(timestamp) -> int: try: month = int(timestamp.month) except AttributeError: return -1 else: return month
exe = "tester.exe" toolchain = "msvc" # optional link_pool_depth = 1 # optional builddir = { "gnu" : "build" , "msvc" : "build" , "clang" : "build" } includes = { "gnu" : [ "-I." ] , "msvc" : [ "/I." ] , "clang" : [ "-I." ] } defines = { "gnu" : [ "-DEXAMPLE=1" ] , "msvc" : [ "/DEX...
exe = 'tester.exe' toolchain = 'msvc' link_pool_depth = 1 builddir = {'gnu': 'build', 'msvc': 'build', 'clang': 'build'} includes = {'gnu': ['-I.'], 'msvc': ['/I.'], 'clang': ['-I.']} defines = {'gnu': ['-DEXAMPLE=1'], 'msvc': ['/DEXAMPLE=1'], 'clang': ['-DEXAMPLE=1']} cflags = {'gnu': ['-O2', '-g'], 'msvc': ['/O2'], '...
# Problem: https://www.hackerrank.com/challenges/alphabet-rangoli/problem def print_rangoli(size): alorder = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' alorder = ''.join([i.lower() for i in alorder]) string, width , side_l, side_str = alorder[:size], (size-1)*4+1, [], '' # top half for i in range(size-1): ...
def print_rangoli(size): alorder = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' alorder = ''.join([i.lower() for i in alorder]) (string, width, side_l, side_str) = (alorder[:size], (size - 1) * 4 + 1, [], '') for i in range(size - 1): print((side_str + '-' + string[size - 1 - i] + '-' + side_str[::-1]).center(w...
# Cooling Settings cool_circuit = \ {'label': 'Activate Cooling:', 'value': True, 'sticky': ['NW', 'NWE'], 'sim_name': ['stack', 'cool_flow'], 'type': 'CheckButtonSet', 'specifier': 'checklist_activate_cooling', 'command': {'function': 'set_status', 'args': [[[1, 0], [1, 1], [1, 2],...
cool_circuit = {'label': 'Activate Cooling:', 'value': True, 'sticky': ['NW', 'NWE'], 'sim_name': ['stack', 'cool_flow'], 'type': 'CheckButtonSet', 'specifier': 'checklist_activate_cooling', 'command': {'function': 'set_status', 'args': [[[1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2], [3, 0], [3, 1], [3, 2], [4, 0], [...
class Solution: # @param {integer} n # @param {integer} k # @return {string} def getPermutation(self, n, k): nums = [i+1 for i in xrange(n)] facts = [0 for i in xrange(n)] facts[0] = 1 for i in range(1,n): facts[i] = i*facts[i-1] k = k-1 res = ...
class Solution: def get_permutation(self, n, k): nums = [i + 1 for i in xrange(n)] facts = [0 for i in xrange(n)] facts[0] = 1 for i in range(1, n): facts[i] = i * facts[i - 1] k = k - 1 res = [] for i in range(n, 0, -1): idx = k / fac...
# Python 3 compatibility (no longer includes `basestring`): try: basestring except NameError: basestring = str class Item(object): '''Common logic shared across all kinds of objects.''' class UnknownAttributeError(ValueError): def __init__(self, attributes): super(Item.UnknownAttr...
try: basestring except NameError: basestring = str class Item(object): """Common logic shared across all kinds of objects.""" class Unknownattributeerror(ValueError): def __init__(self, attributes): super(Item.UnknownAttributeError, self).__init__('Unknown attributes: {0}'.format(...
word = input().lower() ans = [] vowels = ('a', 'i', 'u', 'e', 'o', 'y') filtered_word = word for i in word: if i in vowels: filtered_word = filtered_word.replace(i, "") for i in filtered_word: ans.append('.') ans.append(i) print(''.join(ans))
word = input().lower() ans = [] vowels = ('a', 'i', 'u', 'e', 'o', 'y') filtered_word = word for i in word: if i in vowels: filtered_word = filtered_word.replace(i, '') for i in filtered_word: ans.append('.') ans.append(i) print(''.join(ans))
def ft_map(function_to_apply, list_of_inputs): return [function_to_apply(x) for x in list_of_inputs] c = [0,1,2,3,4,5] def add1(t): return t+1 print(list(map(lambda x: x+1,c))) print(ft_map(lambda x: x+1,c))
def ft_map(function_to_apply, list_of_inputs): return [function_to_apply(x) for x in list_of_inputs] c = [0, 1, 2, 3, 4, 5] def add1(t): return t + 1 print(list(map(lambda x: x + 1, c))) print(ft_map(lambda x: x + 1, c))
#!/bin/python2.7 #CLASS PARA VERIFICAR OS GRUPOS DE CONFLITO class ScdGrupoConflito(object): def __init__(self): self.in_port = False self.ip_src = False self.ip_dst = False self.dl_src = False self.dl_dst = False self.tp_src = False self.tp_dst = False ...
class Scdgrupoconflito(object): def __init__(self): self.in_port = False self.ip_src = False self.ip_dst = False self.dl_src = False self.dl_dst = False self.tp_src = False self.tp_dst = False self.dl_type = False self.solucao = str('') class...
def get_slice_length(path): for i in range(len(path)): if path[i].isalpha(): return i return -1
def get_slice_length(path): for i in range(len(path)): if path[i].isalpha(): return i return -1
entrada = int(input()) #resultado = entrada % 2 #comp = 10 % 2 i = 1 while i <= entrada: if i % 2 != 0: print(i) i+= 1
entrada = int(input()) i = 1 while i <= entrada: if i % 2 != 0: print(i) i += 1
""" # Supported expressions examples Test for `handsdown.ast_parser.analyzers.expression_analyzer.ExpressionAnalyzer` test. """ # string example STRING = "string" # bytes example BSTRING = b"string" # r-string example RSTRING = r"str\ing" # joined string example JOINED_STRING = "part1" "part2" # f-string example ...
""" # Supported expressions examples Test for `handsdown.ast_parser.analyzers.expression_analyzer.ExpressionAnalyzer` test. """ string = 'string' bstring = b'string' rstring = 'str\\ing' joined_string = 'part1part2' fstring = f'start{STRING}end' slice = STRING[1:4:-1] set = {1, 2, 3} list = [1, 2, 3] tuple = (1, 2, 3)...
class ModaError(Exception): pass class ModaTimeoutError(ModaError): pass class ModaCannotInteractError(ModaError): pass
class Modaerror(Exception): pass class Modatimeouterror(ModaError): pass class Modacannotinteracterror(ModaError): pass
def bubblesort(a_list: list) -> list: """ The Bubble sort algorithm is the most naive one that we can create. The idea around this algorithm is comparing each two elements on the list and swapping them in case one is bigger than the other. If any swap is executed, we need to rerun it, since these swapp...
def bubblesort(a_list: list) -> list: """ The Bubble sort algorithm is the most naive one that we can create. The idea around this algorithm is comparing each two elements on the list and swapping them in case one is bigger than the other. If any swap is executed, we need to rerun it, since these swappe...
def recurse(a,i): if i == len(a)-1: print(a[i]) return else: recurse(a,i+1) print(a[i]) recurse([1,2,3,4,5],0)
def recurse(a, i): if i == len(a) - 1: print(a[i]) return else: recurse(a, i + 1) print(a[i]) recurse([1, 2, 3, 4, 5], 0)
# https://www.hackerrank.com/challenges/30-running-time-and-complexity/problem # Trial division def is_prime(n): if n < 2: return False i = 2 while i * i <= n: if n % i == 0: return False i += 1 return True if __name__ == '__main__': n, nums = int(input()), [] ...
def is_prime(n): if n < 2: return False i = 2 while i * i <= n: if n % i == 0: return False i += 1 return True if __name__ == '__main__': (n, nums) = (int(input()), []) for i in range(n): nums.append(int(input())) for num in nums: print('Pr...
class Citation: """Basic citation class""" def __init__(self, data: dict): self.data = data @property def data_(self): return self.data def __str__(self): return str(self.data) def __repr(self): return str(self.data)
class Citation: """Basic citation class""" def __init__(self, data: dict): self.data = data @property def data_(self): return self.data def __str__(self): return str(self.data) def __repr(self): return str(self.data)
def encode1(Loan_Status): """ This function encodes a loan status to either 1 or 0. """ if Loan_Status == 'Y': return 1 else: return 0 def encode2(Gender): """ This function encodes a loan status to either 1 or 0. ...
def encode1(Loan_Status): """ This function encodes a loan status to either 1 or 0. """ if Loan_Status == 'Y': return 1 else: return 0 def encode2(Gender): """ This function encodes a loan status to either 1 or 0. """ if Gender == 'Male': retu...
bulan_pembelian = ('Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember') pertengahan_tahun = bulan_pembelian[4:8] print(pertengahan_tahun) awal_tahun = bulan_pembelian[:5] print(awal_tahun) akhir_tahun = bulan_pembelian[8:] print(akhir_tahun) print(bu...
bulan_pembelian = ('Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember') pertengahan_tahun = bulan_pembelian[4:8] print(pertengahan_tahun) awal_tahun = bulan_pembelian[:5] print(awal_tahun) akhir_tahun = bulan_pembelian[8:] print(akhir_tahun) print(bu...
def test_one(app): response = app.get('/api/services', status=200) response.json.should.be.is_instance(list) def test_two(app): response = app.get('/api/services/1', status=200) response.json.should.be.equal({'id': 9, 'name': 'Voice', 'slug': 'SERVICE_VOICE'})
def test_one(app): response = app.get('/api/services', status=200) response.json.should.be.is_instance(list) def test_two(app): response = app.get('/api/services/1', status=200) response.json.should.be.equal({'id': 9, 'name': 'Voice', 'slug': 'SERVICE_VOICE'})
def str_to_int(value, default=int(0)): stripped_value = value.strip() try: return int(stripped_value) except ValueError: return default def str_to_float(value, default=float(0)): stripped_value = value.strip() try: return float(stripped_value) except ValueError: ...
def str_to_int(value, default=int(0)): stripped_value = value.strip() try: return int(stripped_value) except ValueError: return default def str_to_float(value, default=float(0)): stripped_value = value.strip() try: return float(stripped_value) except ValueError: ...
k=1 suma=(k**2+1)/k cont=0 while cont<1000: cont+=suma print(k) k+=1 suma=(k**2+1)/k
k = 1 suma = (k ** 2 + 1) / k cont = 0 while cont < 1000: cont += suma print(k) k += 1 suma = (k ** 2 + 1) / k
# Copyright 2017-2021 object_database Authors # # 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 ...
class Sortwrapper: def __init__(self, x): self.x = x def __lt__(self, other): try: if type(self.x) in (int, float) and type(other.x) in (int, float): return self.x < other.x if type(self.x) is type(other.x): return self.x < other.x ...
class JSException(Exception): """Base exception for javascript engine wrapper.""" pass class ArgumentError(JSException): pass class JSFunctionNotExists(JSException): pass class JSRuntimeException(JSException): """Javascript runtime exception with a stacktrace.""" def __init__(self, msg, ...
class Jsexception(Exception): """Base exception for javascript engine wrapper.""" pass class Argumenterror(JSException): pass class Jsfunctionnotexists(JSException): pass class Jsruntimeexception(JSException): """Javascript runtime exception with a stacktrace.""" def __init__(self, msg, trac...
# encoding=utf8 # coding=UTF-8 #pastaArquivoCsv = "/home/00937325465/familiai/acompanhaig/arquivos/csv/" #pastaArquivoCsvProc = "/home/00937325465/familiai/acompanhaig/arquivos/csv/processados/" #pastaArquivoZip = "/home/00937325465/familiai/acompanhaig/arquivos/zip/" #pastaArquivoZipProc = "/home/00937325465/famili...
pasta_arquivo_csv = '/home/ubuntu/workspace/public/python/input/csv/' pasta_arquivo_csv_proc = '/home/ubuntu/workspace/public/python/input/csv/processados/' pasta_arquivo_zip = '/home/ubuntu/workspace/public/python/input/zip/' pasta_arquivo_zip_proc = '/home/ubuntu/workspace/public/python/input/zip/processados/' pasta_...
class Innovation: def __init__(self, innov, new_conn, fr=None, to=None, node_id=None): """Innovation details Args: innov (int): Innovation ID of the Innovation new_conn (bool): Is the new Innovation a innovation of a connection or a node fr (int, optional): Node ...
class Innovation: def __init__(self, innov, new_conn, fr=None, to=None, node_id=None): """Innovation details Args: innov (int): Innovation ID of the Innovation new_conn (bool): Is the new Innovation a innovation of a connection or a node fr (int, optional): Node...
def slices(number, n): initial, res = 0, [] if n > len(number) or n == 0: raise ValueError("Desired slices greater than number length") elif n == len(number): return [[int(x) for x in number]] elif n == 1: return [[int(x)] for x in number] else: while n <= len(number)...
def slices(number, n): (initial, res) = (0, []) if n > len(number) or n == 0: raise value_error('Desired slices greater than number length') elif n == len(number): return [[int(x) for x in number]] elif n == 1: return [[int(x)] for x in number] else: while n <= len(nu...
# # PySNMP MIB module HUAWEI-LswSMON-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-LswSMON-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:34:34 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, single_value_constraint, constraints_union, value_range_constraint, value_size_constraint) ...
""" Copyright 2015, Rob Shakir (rjs@jive.com, rjs@rob.sh) This project has been supported by: * Jive Communcations, Inc. * BT plc. 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 a...
""" Copyright 2015, Rob Shakir (rjs@jive.com, rjs@rob.sh) This project has been supported by: * Jive Communcations, Inc. * BT plc. 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 a...
INPUTS = [ ['Select', False], ['Signal Only', ''], ['Probe', 'motion.probe-input'], ['Digital In 0', 'motion.digital-in-00'], ['Digital In 1', 'motion.digital-in-01'], ['Digital In 2', 'motion.digital-in-02'], ['Digital In 3', 'motion.digital-in-03'], ] OUTPUTS = [ ['Select', False], ['Signal Only', ''], ['C...
inputs = [['Select', False], ['Signal Only', ''], ['Probe', 'motion.probe-input'], ['Digital In 0', 'motion.digital-in-00'], ['Digital In 1', 'motion.digital-in-01'], ['Digital In 2', 'motion.digital-in-02'], ['Digital In 3', 'motion.digital-in-03']] outputs = [['Select', False], ['Signal Only', ''], ['Coolant Flood', ...
n=int(input()) d=2 i = 0 while n>d : if n%d==0 : i+=1 print ("divisible by",d, "and count",i) else: print ("not divisible by this number",d) d+=1
n = int(input()) d = 2 i = 0 while n > d: if n % d == 0: i += 1 print('divisible by', d, 'and count', i) else: print('not divisible by this number', d) d += 1
# -*- encoding: utf-8 -*- EPILOG = 'Docker Hub in your terminal' DESCRIPTION = 'Access docker hub from your terminal' HELPMSGS = { 'method': 'The api method to query {%(choices)s}', 'orgname': 'Your orgname', 'reponame': 'The name of repository', 'username': 'The Docker Hub username', 'format': 'You can dispaly re...
epilog = 'Docker Hub in your terminal' description = 'Access docker hub from your terminal' helpmsgs = {'method': 'The api method to query {%(choices)s}', 'orgname': 'Your orgname', 'reponame': 'The name of repository', 'username': 'The Docker Hub username', 'format': 'You can dispaly results in %(choices)s formats', '...
adj = [[False for i in range(10)] for j in range(10)] result = [0] def findthepath(S, v): result[0] = v for i in range(1, len(S)): if (adj[v][ord(S[i]) - ord('A')] or adj[ord(S[i]) - ord('A')][v]): v = ord(S[i]) - ord('A') elif (adj[v][ord(S[i]) - ord('A') + 5] or ...
adj = [[False for i in range(10)] for j in range(10)] result = [0] def findthepath(S, v): result[0] = v for i in range(1, len(S)): if adj[v][ord(S[i]) - ord('A')] or adj[ord(S[i]) - ord('A')][v]: v = ord(S[i]) - ord('A') elif adj[v][ord(S[i]) - ord('A') + 5] or adj[ord(S[i]) - ord('...
# Create a program that reads a positive integer N as input and prints on the console a rhombus with size n: def generate_pyramid(size: int, inverted: bool = False) -> list: steps = [i for i in range(1, size + 1)] if inverted: steps.reverse() return [' ' * (size - i) + '* ' * i for i in steps] d...
def generate_pyramid(size: int, inverted: bool=False) -> list: steps = [i for i in range(1, size + 1)] if inverted: steps.reverse() return [' ' * (size - i) + '* ' * i for i in steps] def generate_rhombus(size: int) -> list: retval = generate_pyramid(size) retval.extend(generate_pyramid(siz...
# Copyright 2021 Denis Gavrilyuk. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
class Recoveryimageismissing(Exception): """Raised when a client passed an image id for recovery but the image associated with the id wasn't found in the database. """
#!/usr/bin/env python3 # ~*~ coding: utf-8 ~*~ # Write a program that has a user guess your name, but they only get 3 # chances to do so until the program quits. print("Try to guess my name!") count = 1 name = "guileherme" guess = input("What is my name? ") while count < 3 and guess.lower() != name: # . lower allows th...
print('Try to guess my name!') count = 1 name = 'guileherme' guess = input('What is my name? ') while count < 3 and guess.lower() != name: print('You are wrong!') guess = input('What is my name? ') count = count + 1 if guess.lower() != name: print('You are wrong!') print('You ran out of chances.') e...
def minimumDistances(a): min_distance = -1 length = len(a) for number in range(0, length-1): for another_number in range(number+1, length): if a[number] == a[another_number]: distance = another_number - number if min_distance == -1: min...
def minimum_distances(a): min_distance = -1 length = len(a) for number in range(0, length - 1): for another_number in range(number + 1, length): if a[number] == a[another_number]: distance = another_number - number if min_distance == -1: ...
class Parser: """ Parse string matrix and covert each entry to double value, skipping nan values""" def parse(self, matrix): result = [] for row in range(0, len(matrix)): result.append([]) rowLength = len(matrix[row]) for col in range(0, rowLength): ...
class Parser: """ Parse string matrix and covert each entry to double value, skipping nan values""" def parse(self, matrix): result = [] for row in range(0, len(matrix)): result.append([]) row_length = len(matrix[row]) for col in range(0, rowLength): ...
# -*- coding: utf-8 -*- # # ax_spines.py # # Copyright 2017 Sebastian Spreizer # The MIT License def set_default(ax): set_visible(ax, ['bottom', 'left']) def set_visible(ax, sides): all_sides = ax.spines.keys() for side in all_sides: ax.spines[side].set_visible(side in sides) def set_invisible(a...
def set_default(ax): set_visible(ax, ['bottom', 'left']) def set_visible(ax, sides): all_sides = ax.spines.keys() for side in all_sides: ax.spines[side].set_visible(side in sides) def set_invisible(ax, sides): all_sides = ax.spines.keys() for side in all_sides: ax.spines[side].set_...
""" Pre-generation tasks. This is executed before the project has been generated. """ def main() -> int: """ Validate parameters. """ status = 0 if not "{{ cookiecutter.plugin_name }}": print("ERROR: plugin_name cannot be blank") status = 1 if not "{{ cookiecutter.author_name }}":...
""" Pre-generation tasks. This is executed before the project has been generated. """ def main() -> int: """ Validate parameters. """ status = 0 if not '{{ cookiecutter.plugin_name }}': print('ERROR: plugin_name cannot be blank') status = 1 if not '{{ cookiecutter.author_name }}'...
''' https://www.codingame.com/training/easy/create-the-longest-sequence-of-1s ''' b = input() count = 0 buf = "0" zeros = [] ones = [] for i in range(len(b)): if b[i] == buf: count += 1 else: if buf == "0": zeros.append(count) else: ones.append(count) ...
""" https://www.codingame.com/training/easy/create-the-longest-sequence-of-1s """ b = input() count = 0 buf = '0' zeros = [] ones = [] for i in range(len(b)): if b[i] == buf: count += 1 else: if buf == '0': zeros.append(count) else: ones.append(count) co...
#This program calculates how many tiles you #need when tiling a floor (in m2) length = float(input("Enter room length:")) width = float(input("Enter room width:")) area = length * width needed = area * 1.05 print("You need", needed, "tiles in squared metres")
length = float(input('Enter room length:')) width = float(input('Enter room width:')) area = length * width needed = area * 1.05 print('You need', needed, 'tiles in squared metres')
# # PySNMP MIB module ZYXEL-CLUSTER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-CLUSTER-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:49:17 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint, constraints_union) ...
# import math # def squareRoot(a): # return round(math.sqrt(float(a)),9) def squareRoot(a): return round(float(a)**(1/2),8)
def square_root(a): return round(float(a) ** (1 / 2), 8)
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: if not head: return None ...
class Solution: def remove_elements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: if not head: return None dummy_head = current_node = list_node() dummyHead.next = head while currentNode.next: if currentNode.next.val == val: ...
alist = [10, 20, 23, 26, 27, 35, 38, 41, 46, 49, 54, 56, 64, 70, 81, 87, 88, 90, 92, 96, 98] temp = None def binary_search(left: int, right: int, key: int) -> int: global temp if len(alist) == 1: if alist[left] == key: return alist[left] else: return 0 else: ...
alist = [10, 20, 23, 26, 27, 35, 38, 41, 46, 49, 54, 56, 64, 70, 81, 87, 88, 90, 92, 96, 98] temp = None def binary_search(left: int, right: int, key: int) -> int: global temp if len(alist) == 1: if alist[left] == key: return alist[left] else: return 0 else: ...
class HTTPError(Exception): """Http Error Exception""" pass
class Httperror(Exception): """Http Error Exception""" pass
# 2021 April 16. Surrendered entirely. # 2-d dp. # text1 = "abcba", text2 = "abcbcba" # At any two positions i, j in t1 and t2, if 1) t1[i] == t2[j] # then the length of common subsequence count should increment by 1 and # we then check from t1[i+1] and t2[j+1]. If 2) t1[i] != t2[j], then we # should keep on finding...
class Solution: def longest_common_subsequence(self, text1: str, text2: str) -> int: (rows, cols) = (len(text1) + 1, len(text2) + 1) dp = [[0 for _ in range(COLS)] for _ in range(ROWS)] for row in range(ROWS - 2, -1, -1): for col in range(COLS - 2, -1, -1): if te...
class PxLoadBar(object): """ Visualizes system load in a horizontal bar. Inputs are: * System load * Number of physical cores * Number of logical cores * How many columns wide the horizontal bar should be The output is a horizontal bar string. Load below the number of physical cor...
class Pxloadbar(object): """ Visualizes system load in a horizontal bar. Inputs are: * System load * Number of physical cores * Number of logical cores * How many columns wide the horizontal bar should be The output is a horizontal bar string. Load below the number of physical cor...
""" FizzBuzz is a classical interview question. We will implement a modified version of it, however, you can also find the original version on the web if you are interested. Write a program that takes a number from the user. If this number is negative, print an error message if this number is a multiple of 3, print '...
""" FizzBuzz is a classical interview question. We will implement a modified version of it, however, you can also find the original version on the web if you are interested. Write a program that takes a number from the user. If this number is negative, print an error message if this number is a multiple of 3, print '...
class BaseSensor(): def __init__(self): self.null_value = 0 self.sensor = None self.measurements = [] self.upper_reasonable_bound = 200 self.lower_reasonable_bound = 0 def setup(self): self.sensor = None def read(self): return None def average(s...
class Basesensor: def __init__(self): self.null_value = 0 self.sensor = None self.measurements = [] self.upper_reasonable_bound = 200 self.lower_reasonable_bound = 0 def setup(self): self.sensor = None def read(self): return None def average(se...
def time_in_range(data, bg_range=(4.0, 7.0)): # data[0] is the time values - assume they are equally spaced, so we can ignore values = data[1] return 100.0 * sum([bg_range[0] <= v <= bg_range[1] for v in values]) / len(values) def mean(data): values = data[1] return float(sum(values)) / len(values...
def time_in_range(data, bg_range=(4.0, 7.0)): values = data[1] return 100.0 * sum([bg_range[0] <= v <= bg_range[1] for v in values]) / len(values) def mean(data): values = data[1] return float(sum(values)) / len(values) def estimated_hba1c(data): return hba1c_ngsp_to_ifcc((mean(data) + 2.59) / 1.5...
def maior_primo(x) -> object: for maior in reversed(range(1,x+1)): if all(maior%n!=0 for n in range(2,maior)): return maior
def maior_primo(x) -> object: for maior in reversed(range(1, x + 1)): if all((maior % n != 0 for n in range(2, maior))): return maior
USER_CREATED = "user_created" USER_ADDED = "user_added_to_request" USER_REMOVED = "user_removed_from_request" USER_PERM_CHANGED = "user_permissions_changed" USER_STATUS_CHANGED = "user_status_changed" # user, admin, super USER_INFO_EDITED = "user_information_edited" REQUESTER_INFO_EDITED = "requester_information_edite...
user_created = 'user_created' user_added = 'user_added_to_request' user_removed = 'user_removed_from_request' user_perm_changed = 'user_permissions_changed' user_status_changed = 'user_status_changed' user_info_edited = 'user_information_edited' requester_info_edited = 'requester_information_edited' req_created = 'requ...
# Find the sum of the numbers 8, 9, 10 # Var declarations num1 = 8 num2 = 9 num3 = 10 # Code sum = num1 + num2 + num3 # Result print(sum)
num1 = 8 num2 = 9 num3 = 10 sum = num1 + num2 + num3 print(sum)
# Write your make_spoonerism function here: def make_spoonerism(word1, word2): a = word1[0] b = word2[0] c = word1[0].replace(a,b) + word1[1:] d = word2[0].replace(b,a) + word2[1:] e = c + ' ' + d return e # Uncomment these function calls to test your function: print(make_spoonerism("Codecademy", "Learn"...
def make_spoonerism(word1, word2): a = word1[0] b = word2[0] c = word1[0].replace(a, b) + word1[1:] d = word2[0].replace(b, a) + word2[1:] e = c + ' ' + d return e print(make_spoonerism('Codecademy', 'Learn')) print(make_spoonerism('Hello', 'world!')) print(make_spoonerism('a', 'b'))
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"trace_log": "01_convert_time_log.ipynb", "format_value": "01_convert_time_log.ipynb", "strip_extra_EnmacClientTime_elements": "01_convert_time_log.ipynb", "unix_time_milliseconds":...
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'trace_log': '01_convert_time_log.ipynb', 'format_value': '01_convert_time_log.ipynb', 'strip_extra_EnmacClientTime_elements': '01_convert_time_log.ipynb', 'unix_time_milliseconds': '01_convert_time_log.ipynb', 'parse_dt': '01_convert_time_log.ipynb...
#Planetary database #Source for planetary data, and some of the data on #the moons, is http://nssdc.gsfc.nasa.gov/planetary/factsheet/ class Planet: ''' A Planet object contains basic planetary data. If P is a Planet object, the data are: P.name = Name of the planet P.a = Mean radius ...
class Planet: """ A Planet object contains basic planetary data. If P is a Planet object, the data are: P.name = Name of the planet P.a = Mean radius of planet (m) P.g = Surface gravitational acceleration (m/s**2) P.L = Annual mean solar constant (current) (W/m**2...
palavras = {} arquivo = open('words.txt', 'r') for p in arquivo.readlines(): palavra = p.split(' ') for l in palavra: try: palavras[l] += 1 except: palavras[l] = 1 arquivo.close() print(palavras)
palavras = {} arquivo = open('words.txt', 'r') for p in arquivo.readlines(): palavra = p.split(' ') for l in palavra: try: palavras[l] += 1 except: palavras[l] = 1 arquivo.close() print(palavras)
def getKey(dictionary, svalue): for key, value in dictionary.items(): if value == svalue: return key # def hasKey(dictionary, key): # if key in dictionary: # return True # return False
def get_key(dictionary, svalue): for (key, value) in dictionary.items(): if value == svalue: return key
# https://www.codewars.com/kata/529872bdd0f550a06b00026e/ ''' Instructions : Complete the greatestProduct method so that it'll find the greatest product of five consecutive digits in the given string of digits. For example: greatestProduct("123834539327238239583") // should return 3240 The input string always has...
""" Instructions : Complete the greatestProduct method so that it'll find the greatest product of five consecutive digits in the given string of digits. For example: greatestProduct("123834539327238239583") // should return 3240 The input string always has more than five digits. Adapted from Project Euler. """ ...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. def drop_view_if_exists(cr, viewname): cr.execute("DROP view IF EXISTS %s CASCADE" % (viewname,)) cr.commit() def escape_psql(to_escape): return to_escape.replace('\\', r'\\').replace('%', '\%').replace('_',...
def drop_view_if_exists(cr, viewname): cr.execute('DROP view IF EXISTS %s CASCADE' % (viewname,)) cr.commit() def escape_psql(to_escape): return to_escape.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_') def pg_varchar(size=0): """ Returns the VARCHAR declaration for the provided size: ...
""" You are given three inputs, all of which are instances of a class that have an "ancestor" property pointing to their youngest ancestor. The first input is the top ancestor in an ancestral tree(i.e. the only instance that has no ancestor), and the other two inputs are descendants in the ancestral tree. Write a funct...
""" You are given three inputs, all of which are instances of a class that have an "ancestor" property pointing to their youngest ancestor. The first input is the top ancestor in an ancestral tree(i.e. the only instance that has no ancestor), and the other two inputs are descendants in the ancestral tree. Write a funct...
@auth.route('/login', methods=['GET', 'POST']) # define login page path def login(): # define login page fucntion if request.method=='GET': # if the request is a GET we return the login page return render_template('login.html') else: # if the request is POST the we check if the user exist ...
@auth.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') else: email = request.form.get('email') password = request.form.get('password') remember = True if request.form.get('remember') else False user = U...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"get_norm_stats": "00_utils.ipynb", "draw_rect": "00_utils.ipynb", "convert_cords": "00_utils.ipynb", "resize": "00_utils.ipynb", "noise": "00_utils.ipynb", "get_p...
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'get_norm_stats': '00_utils.ipynb', 'draw_rect': '00_utils.ipynb', 'convert_cords': '00_utils.ipynb', 'resize': '00_utils.ipynb', 'noise': '00_utils.ipynb', 'get_prompt_points': '00_utils.ipynb', 'yolo_to_coco': '00_utils.ipynb', 'PTBDataset': '01_d...
class OutcomeInfo: '''Details for individual outcomes of a Market.''' def __init__(self, id, volume, price, description): self._id = id self._volume = volume self._price = price self._description = description @property def id(self): '''Market Outcome ID Returns int ''' return...
class Outcomeinfo: """Details for individual outcomes of a Market.""" def __init__(self, id, volume, price, description): self._id = id self._volume = volume self._price = price self._description = description @property def id(self): """Market Outcome ID Re...
''' @author: Jakob Prange (jakpra) @copyright: Copyright 2020, Jakob Prange @license: Apache 2.0 ''' LETTERS = '_YZWVUTS' def index_category(category, nargs, result_index=0, arg_index=1, self_index=0): attr_str = ''.join((f'[{a}]' for a in category.attr - {'conj'})) + ('[conj]' if 'conj' in category.attr else...
""" @author: Jakob Prange (jakpra) @copyright: Copyright 2020, Jakob Prange @license: Apache 2.0 """ letters = '_YZWVUTS' def index_category(category, nargs, result_index=0, arg_index=1, self_index=0): attr_str = ''.join((f'[{a}]' for a in category.attr - {'conj'})) + ('[conj]' if 'conj' in category.attr else '') ...
# One Gold Star # Question 1-star: Stirling and Bell Numbers # The number of ways of splitting n items in k non-empty sets is called # the Stirling number, S(n,k), of the second kind. For example, the group # of people Dave, Sarah, Peter and Andy could be split into two groups in # the following ways. # 1. Dave, Sa...
def stirling(n_items, k_sets): """ Takes as its inputs two positive integers of which the first is the number of items and the second is the number of sets into which those items will be split. Returns total number of k_sets created from n_items. """ if n_items < k_sets: return 0 ...
def cpu_bound(n): return sum(i * i for i in range(n)) if __name__ == "__main__": n = int(input()) res = cpu_bound(n) print(res)
def cpu_bound(n): return sum((i * i for i in range(n))) if __name__ == '__main__': n = int(input()) res = cpu_bound(n) print(res)
# Implement a queue using two stacks. Recall that a queue is a FIFO # (first-in, first-out) data structure with the following methods: enqueue, # which inserts an element into the queue, and dequeue, which removes it. class Queue: def __init__(self): self.ins = [] self.out = [] de...
class Queue: def __init__(self): self.ins = [] self.out = [] def enqueue(self, value): self.ins.append(value) def dequeue(self): if not self.out: while self.ins: self.out.append(self.ins.pop()) return self.out.pop() if __name__ == '__mai...
MOCK_DATA = [ { "symbol": "sy1", "companyName": "cn1", "exchange": "ex1", "industry": "in1", "website": "ws1", "description": "dc1", "CEO": "ceo1", "issueType": "is1", "sector": "sc1", }, { "symbol": "sy2", "companyName"...
mock_data = [{'symbol': 'sy1', 'companyName': 'cn1', 'exchange': 'ex1', 'industry': 'in1', 'website': 'ws1', 'description': 'dc1', 'CEO': 'ceo1', 'issueType': 'is1', 'sector': 'sc1'}, {'symbol': 'sy2', 'companyName': 'cn2', 'exchange': 'ex2', 'industry': 'in2', 'website': 'ws2', 'description': 'dc2', 'CEO': 'ceo2', 'is...
# Only used for PyTorch open source BUCK build # @lint-ignore-every BUCKRESTRICTEDSYNTAX def is_arvr_mode(): if read_config("pt", "is_oss", "0") == "0": fail("This file is for open source pytorch build. Do not use it in fbsource!") return False
def is_arvr_mode(): if read_config('pt', 'is_oss', '0') == '0': fail('This file is for open source pytorch build. Do not use it in fbsource!') return False
# a = "crazy_python" # print(id(a)) # print(id("crazy" + "_" + "python")) """ output: 41899952 41899952 """ a = 'crazy' b = 'crazy' c = 'crazy!!' d = 'crazy!!' e, f = "crazy!", "crazy!" print (a is b) print(c is d) print(e is f) """ output: True True True """ array_1 = [1,2,3,4] print(id(array_1)) g1 = (x for x in...
""" output: 41899952 41899952 """ a = 'crazy' b = 'crazy' c = 'crazy!!' d = 'crazy!!' (e, f) = ('crazy!', 'crazy!') print(a is b) print(c is d) print(e is f) '\noutput:\nTrue\nTrue\nTrue\n' array_1 = [1, 2, 3, 4] print(id(array_1)) g1 = (x for x in array_1) array_1 = [1, 2, 3, 4, 5] print(id(array_1)) '\noutput:\n41768...
class ValueParsingOptions(object,IDisposable): """ Options for parsing strings into numbers with units. ValueParsingOptions() """ def Dispose(self): """ Dispose(self: ValueParsingOptions) """ pass def GetFormatOptions(self): """ GetFormatOptions(self: ValueParsingOptions) -> FormatOptions...
class Valueparsingoptions(object, IDisposable): """ Options for parsing strings into numbers with units. ValueParsingOptions() """ def dispose(self): """ Dispose(self: ValueParsingOptions) """ pass def get_format_options(self): """ GetFormatOptions(self: ValueParsingOption...
"""Below Python Programme demonstrate lstrip functions in a string""" #Example: random_string = ' this is good ' # Leading whitepsace are removed print(random_string.lstrip()) # Argument doesn't contain space # No characters are removed. print(random_string.lstrip('sti')) print(random_string.lstrip('s ti'))
"""Below Python Programme demonstrate lstrip functions in a string""" random_string = ' this is good ' print(random_string.lstrip()) print(random_string.lstrip('sti')) print(random_string.lstrip('s ti'))
# Diffusion 2D nx = 20 # number of elements ny = nx # number of nodes mx = nx + 1 my = ny + 1 # initial values iv = {} for j in range(int(0.2*my), int(0.3*my)): for i in range(int(0.5*mx), int(0.8*mx)): index = j*mx + i iv[index] = 1.0 print("iv: ",iv) config = { "solverStructureDiagramFile": "so...
nx = 20 ny = nx mx = nx + 1 my = ny + 1 iv = {} for j in range(int(0.2 * my), int(0.3 * my)): for i in range(int(0.5 * mx), int(0.8 * mx)): index = j * mx + i iv[index] = 1.0 print('iv: ', iv) config = {'solverStructureDiagramFile': 'solver_structure.txt', 'logFormat': 'csv', 'scenarioName': 'diffus...
__title__ = 'lightwood' __package_name__ = 'mindsdb' __version__ = '0.14.1' __description__ = "Lightwood's goal is to make it very simple for developers to use the power of artificial neural networks in their projects." __email__ = "jorge@mindsdb.com" __author__ = 'MindsDB Inc' __github__ = 'https://github.com/mindsdb/...
__title__ = 'lightwood' __package_name__ = 'mindsdb' __version__ = '0.14.1' __description__ = "Lightwood's goal is to make it very simple for developers to use the power of artificial neural networks in their projects." __email__ = 'jorge@mindsdb.com' __author__ = 'MindsDB Inc' __github__ = 'https://github.com/mindsdb/...
# Problem: input: an unsorted array A[lo..hi]; | output: the (left) median of the given array # Source: SCU COEN279 DAA HW3 Q3 # Author: Shreyas Padhye # Algorithm: Decrease-Conquer class solution(): def left_median(self, A): if len(A) == 1 or len(A) == 2: return A[0] else: ...
class Solution: def left_median(self, A): if len(A) == 1 or len(A) == 2: return A[0] else: median = self.left_median(A[:-1]) if len(A[:-1]) % 2 == 0: if median > A[-1]: return median else: me...
""" This module provide all the functions or classes which help pre-processing data. For example, splitting paragraph into sentences """
""" This module provide all the functions or classes which help pre-processing data. For example, splitting paragraph into sentences """
""" Defines CPU Options for use in the CPU target """ class FastMathOptions(object): """ Options for controlling fast math optimization. """ def __init__(self, value): # https://releases.llvm.org/7.0.0/docs/LangRef.html#fast-math-flags valid_flags = { 'fast', '...
""" Defines CPU Options for use in the CPU target """ class Fastmathoptions(object): """ Options for controlling fast math optimization. """ def __init__(self, value): valid_flags = {'fast', 'nnan', 'ninf', 'nsz', 'arcp', 'contract', 'afn', 'reassoc'} if isinstance(value, FastMathOptio...
def get_belief(sent): if '<|belief|>' in sent: tmp = sent.strip(' ').split('<|belief|>')[-1].split('<|action|>')[0] else: return [] tmp = tmp.strip(' .,') tmp = tmp.replace('<|endofbelief|>', '') tmp = tmp.replace('<|endoftext|>', '') belief = tmp.split(',') new_belief = []...
def get_belief(sent): if '<|belief|>' in sent: tmp = sent.strip(' ').split('<|belief|>')[-1].split('<|action|>')[0] else: return [] tmp = tmp.strip(' .,') tmp = tmp.replace('<|endofbelief|>', '') tmp = tmp.replace('<|endoftext|>', '') belief = tmp.split(',') new_belief = [] ...
''' Created on 2016-01-13 @author: Wu Wenxiang (wuwenxiang.sh@gmail.com) ''' DEBUG = False
""" Created on 2016-01-13 @author: Wu Wenxiang (wuwenxiang.sh@gmail.com) """ debug = False
description = 'Helmholtz field coil' group = 'optional' includes = ['alias_B'] tango_base = 'tango://phys.kws1.frm2:10000/kws1/' devices = dict( I_helmholtz = device('nicos.devices.entangle.PowerSupply', description = 'Current in coils', tangodevice = tango_base + 'gesupply/ps2', unit = ...
description = 'Helmholtz field coil' group = 'optional' includes = ['alias_B'] tango_base = 'tango://phys.kws1.frm2:10000/kws1/' devices = dict(I_helmholtz=device('nicos.devices.entangle.PowerSupply', description='Current in coils', tangodevice=tango_base + 'gesupply/ps2', unit='A', fmtstr='%.2f'), B_helmholtz=device('...
# Test checked class SymbolTable(object): def __init__(self): self._symbols = \ { \ 'SP':0, 'LCL':1, 'ARG':2, 'THIS':3, 'THAT':4, \ 'R0':0, 'R1':1, 'R2':2, 'R3':3, 'R4':4, 'R5':5, 'R6':6, 'R7':7, \ 'R8':8, 'R9':9, 'R10':10, 'R11':11, 'R12':12, 'R13':13, 'R14'...
class Symboltable(object): def __init__(self): self._symbols = {'SP': 0, 'LCL': 1, 'ARG': 2, 'THIS': 3, 'THAT': 4, 'R0': 0, 'R1': 1, 'R2': 2, 'R3': 3, 'R4': 4, 'R5': 5, 'R6': 6, 'R7': 7, 'R8': 8, 'R9': 9, 'R10': 10, 'R11': 11, 'R12': 12, 'R13': 13, 'R14': 14, 'R15': 15, 'SCREEN': 16384, 'KBD': 24576} ...
''' This the demonstration of range function in python''' class Range: """A class that mimic's the built-in range class""" def __init__(self, start, stop=None, step=1): """Initialize a Range instance Semantic is similar to built-in range class """ if step == 0: raise ValueError('step cannot be 0') i...
""" This the demonstration of range function in python""" class Range: """A class that mimic's the built-in range class""" def __init__(self, start, stop=None, step=1): """Initialize a Range instance Semantic is similar to built-in range class """ if step == 0: raise value_e...
# File: question3.py # Author: David Lechner # Date: 11/19/2019 '''Ask some questions about goats''' # REVIEW: We write `NUM_GOATS` in all caps because it is a constant. We set it # once at the begining of the program and don't change after that. NUM_GOATS = 10 # This is how many goats I have # REVIEW: The input()...
"""Ask some questions about goats""" num_goats = 10 answer = int(input('How many goats do you see?')) if answer < NUM_GOATS: print('Some of your goats are missing!') if answer == NUM_GOATS: print('All of the goats are there.') if answer > NUM_GOATS: print('You have extra goats!')
# lec6.4-removeDups.py # edX MITx 6.00.1x # Introduction to Computer Science and Programming Using Python # Lecture 6, video 4 # Demonstrates performing operations on lists # Demonstrates how changing a list while iterating over it creates # unintended problems def removeDups(L1, L2): for e1 in L1: if e1 ...
def remove_dups(L1, L2): for e1 in L1: if e1 in L2: L1.remove(e1) l1 = [1, 2, 3, 4] l2 = [1, 2, 5, 6] remove_dups(L1, L2) print(L1) def remove_dups_better(L1, L2): l1_start = L1[:] for e1 in L1Start: if e1 in L2: L1.remove(e1) l1 = [1, 2, 3, 4] l2 = [1, 2, 5, 6] remo...
def compareTriplets(a, b): result = [] aliceScore =0 bobScore = 0 for Alice, Bob in zip(a, b): if Alice > Bob: aliceScore +=1 continue if Bob > Alice: bobScore +=1 continue if Alice == Bob: continue result....
def compare_triplets(a, b): result = [] alice_score = 0 bob_score = 0 for (alice, bob) in zip(a, b): if Alice > Bob: alice_score += 1 continue if Bob > Alice: bob_score += 1 continue if Alice == Bob: continue result....
#file extension '''n = input("enter file name with extension:") f_ext = n.split('.') x = f_ext[-1] print(x) #sum n = input("enter one number:") temp = n temp1 = temp+temp temp2 = temp+temp+temp val = int(n)+int(temp1)+int(temp2) print(val) #Multiline comment print("a string that you \"don\'t\" have to escape \n This...
"""n = input("enter file name with extension:") f_ext = n.split('.') x = f_ext[-1] print(x) #sum n = input("enter one number:") temp = n temp1 = temp+temp temp2 = temp+temp+temp val = int(n)+int(temp1)+int(temp2) print(val) #Multiline comment print("a string that you "don't" have to escape This is a ....... mult...
# Python - Object Oriented Programming # In here we will use special methods, also called as Magic methods. # Double underscore is called as dunder. We have seen dunder __init__ fuction # we will see __repr__ and __str__ in here. # we can also have custom dunder that we can create for performing certain # tasks as func...
class Employee: raise_amt = 1.04 def __init__(self, firstName, lastName, pay): self.firstName = firstName self.lastName = lastName self.pay = pay self.email = f'{firstName}.{lastName}@Company.com' def fullname(self): return f'{self.firstName} {self.lastName}' d...
# File: okta_consts.py # # Copyright (c) 2018-2022 Splunk Inc. # # 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 applic...
okta_base_url = 'base_url' okta_api_token = 'api_key' okta_paginated_actions_list = ['list_users', 'list_user_groups', 'list_providers', 'list_roles'] okta_reset_password_succ = 'Successfully created one-time token for user to reset password' okta_limit_invalid_msg_err = "Please provide a valid positive integer value f...
# """ Array addition Have the function ArrayAddition(arr) take the array of numbers stored in arr and return the string true if any combination of numbers in the array (excluding the largest number) can be added up to equal the largest number in the array, otherwise return the string false. For example: if arr cont...
""" Array addition Have the function ArrayAddition(arr) take the array of numbers stored in arr and return the string true if any combination of numbers in the array (excluding the largest number) can be added up to equal the largest number in the array, otherwise return the string false. For example: if arr contai...
""" 1. Make a table value -> [index]. 2. Make an empty set of the tuples (i, j, k) 3. For-loop through array. Pick two random elements. Test set for a third that completes the triplet (N^2) 4. Confirm i != j !=k, add to ret set. convert ret set to list and return it. """ class Solution: def threeSum(self, n...
""" 1. Make a table value -> [index]. 2. Make an empty set of the tuples (i, j, k) 3. For-loop through array. Pick two random elements. Test set for a third that completes the triplet (N^2) 4. Confirm i != j !=k, add to ret set. convert ret set to list and return it. """ class Solution: def three_sum(self...
class Node: def __init__(self, dataval = None): self.dataval = dataval self.next = None self.prev = None def __str__(self): return str(self.dataval) class MyList: def __init__(self): self.first = None self.last = None def add(self, dataval):...
class Node: def __init__(self, dataval=None): self.dataval = dataval self.next = None self.prev = None def __str__(self): return str(self.dataval) class Mylist: def __init__(self): self.first = None self.last = None def add(self, dataval): if ...