content
stringlengths
7
1.05M
#------------------------------------------------------------------------------- # elftools: elf/constants.py # # Constants and flags, placed into classes for namespacing # # Eli Bendersky (eliben@gmail.com) # This code is in the public domain #---------------------------------------------------------------------------...
''' Created on 1.12.2016 @author: Darren '''''' Given an array of integers, every element appears three times except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? " '''
class Vector: size = 0 capacity = 0 data = [] def _init__(self, size=0): self.size = size if size: self.data = [None] * size print('Vector initialized!!') def __str__(self): return "Size = {} \nCapacity = {} \nData = {}\n".format( self.size, ...
class Solution: def numJewelsInStones(self, J: str, S: str) -> int: count = 0 for char in S: if char in J: count +=1 return count if __name__ == '__main__': J = "aA" S = "aAAbbbb" instance = Solution() solution = instance.numJewelsInStones(J,S) ...
class Account(): def __init__(self,ownername,balance): self.ownername=ownername self.balance=balance def _str_(self): return 'Account owner:{ownername}\nAccount balance:${balance}'.format(ownername=self.owner,balance=self.balance) def deposit(self,dp_money): self.balan...
# -*- coding: utf-8 -*- DESC = "ecm-2019-07-19" INFO = { "ResetInstancesMaxBandwidth": { "params": [ { "name": "InstanceIdSet", "desc": "待重置带宽上限的实例ID列表。在单次请求的过程中,单个region下的请求实例数上限为100。" }, { "name": "MaxBandwidthOut", "desc": "修改后的最大带宽上限。" } ], "desc...
#MP03 by Jake Hayes def rail4Encrypt(plainText): firstChars="" secondChars="" thirdChars="" fourthChars="" for i in range(len(plainText)): if i%4==0: fourthChars=fourthChars+plainText[i] elif (i-1)%4==0: thirdChars=thirdChars+plainText[i] elif i%2==0: ...
# Python - 3.6.0 test.assert_equals(warn_the_sheep(['sheep', 'sheep', 'sheep', 'sheep', 'sheep', 'wolf', 'sheep', 'sheep']), 'Oi! Sheep number 2! You are about to be eaten by a wolf!') test.assert_equals(warn_the_sheep(['sheep', 'wolf', 'sheep', 'sheep', 'sheep', 'sheep', 'sheep']), 'Oi! Sheep number 5! You are about ...
def _sum_compose(losses): loss = sum(v[0] for v in losses) loss_value = sum(v[1] for v in losses) loss_dict = {} [loss_dict.update(v[2]) for v in losses] return loss, loss_value, loss_dict class MultiScaleLossComposer: def __init__(self, compose_fn, single_scale_loss_composers): self.s...
#!/usr/bin/python3 """ All constants for Jupyter Notebook testing """ DEFAULT_WAIT_PERIOD = 10 START_SERVER_WAIT_PERIOD = 60 DATAHUB_DEV_URL = "http://datahub-dev.berkeley.edu" NBPULLER_ROUTE = "/interact" JPY_USER_ROUTE = "/user/peterkangveerman" TEST_1_PARAMS = "repo=data8assets&path=materials/sp17/lab/lab02" TEST_1...
file = open('text', 'r', encoding='UTF-8') text = file.read() #1) методами строк очистить текст от знаков препинания; #2) сформировать list со словами (split); punctuation = ['.',',',';',':','"','(',')','?','!','!','»','..','-','«','«'] wordList = text.split() for q in range(5): i = 0 for word in wordList: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # def build_column_names_from_list_of_column_name_with_type(list_of_column_name_with_type): # column_names = [] # # for column_name_with_type in list_of_column_name_with_type: # # if the column is a geometry, so transform the geom to text # if "geo...
# -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. class SqlOptionsEnum(object): """Implementation of the 'SqlOptions' enum. Specifies the sql options to update the Restore Task with. Specifies the action type of multi stage SQL restore. 'kCreate' specifies the create action for a restore. 'k...
wid = 0 hei = 0 dots = [] folds = [] grid = [] def loadFile(): global wid global hei #load dots f = open("Day13\\Input.txt", "r") for x in f: if x=="\n": break x = x.strip() dot = [int(y) for y in x.split(',')] if(dot[0]>=wid): ...
# -*- coding: utf-8 -*- class Solution(object): def lengthOfLongestSubstring(self, s): """ 最长不重复的子字符串长度 输入: "pwwkew" 输出: 3(wke) :type s: str :rtype: int """ if not s: return None char_dict, res, st = dict(), 0, 0 for i,...
class NullBotAPIException(Exception): def __init__( self, error: int, description: str = "" ): self.error = error self.description = description def __repr__(self): return f"<NullBotAPIException:code={self.error}, msg={self.description}>" ...
#!/usr/bin/env python # -*-coding:utf-8-*- # File Name : f.py # Description : # Author : # Creation Date : 2021-11-30 # Last Modified : 2021年11月30日 星期二 07时22分43秒 # Created By : lsl # 选一道菜的考虑 # 选二道菜的考虑 def f(nums): nums.sort(reverse=True) ans,presum = 0,0 for i in nums: if presu...
q_001 = ''' PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> PREFIX mds: <http://www.angelocarbone.com/ontologies/MoDelS#> ...
# 1492. The kth Factor of n # User Accepted:4524 # User Tried:4554 # Total Accepted:4600 # Total Submissions:6166 # Difficulty:Medium # Given two positive integers n and k. # A factor of an integer n is defined as an integer i where n % i == 0. # Consider a list of all factors of n sorted in ascending order, # return ...
# -*- coding: utf-8 -*- day1 = int(input().split()[1]) hour1, minute1, second1 = map(int, input().split(" : ")) day2 = int(input().split()[1]) hour2, minute2, second2 = map(int, input().split(" : ")) totalSeconds1 = hour1 * 3600 + minute1 * 60 + second1 totalSeconds2 = hour2 * 3600 + minute2 * 60 + second2 days = d...
# complex expressions # from def renderBanner(self): if ( (self.platform.toUpperCase().indexOf("MAC") > -1) and (self.browser.toUpperCase().indexOf("IE") > -1) and self.wasInitialized() and (self.resize > 0) ): # do something pass # to def renderBanner(self): ...
#!/usr/bin/python # -*- coding: utf-8 -*- # 该脚本主要用于自动生成中断处理程序 # trap which has error number trap_with_errno = [8, 10, 11, 12, 13, 14, 17] print("# generated by vectors.py, please do not edit!") print("# trap handler vectors!\n") print(".code32") print(".section .text") print(".global trap_handlers") for i in range(2...
def userInput(): # takes user input for number of sides and lenght of sides year = int(input('Please enter the 4 digit year: ')) month = int(input('Please enter the month: ')) return year, month def leapYear(year): if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: ...
class ClimateMonitor: def __init__(self, get_climate_data, low_to_high_threshold, high_to_low_threshold, low_is_normal=True): self.low_is_normal = low_is_normal # Assume that climate data is in its normal state at first if self.low_is_normal: self.climate_data_is_high = False ...
""" mbed CMSIS-DAP debugger Copyright (c) 2015 ARM Limited 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...
def ccw(A, B, C): """Tests whether the line formed by A, B, and C is ccw""" return (B.x - A.x) * (C.y - A.y) < (B.y - A.y) * (C.x - A.x) class PathFinder: def __init__(self): pass ''' Implementation of the funnel algorithm for path finding ''' def find_path_funnel(self, point_dict ...
def climbingLeaderboard(scores, alice): unique_scores = list(reversed(sorted(set(scores)))) i = len(alice)-1 j = 0 ans = [] while i >= 0: if j >= len(unique_scores) or unique_scores[j] <= alice[i]: ans.append(j+1) i -= 1 else: j += 1 return ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def add(staff): # Запросить данные о работнике. point1 = input("Откуда? ") point2 = input("Куда? ") routeNumber = int(input("Номер маршрута? ")) route = { 'point1': point1, 'point2': point2, 'routeNumber': routeNumber, } ...
maior = 0 menu = 0 n1 = float(input('Digite um valor: ')) n2 = float(input('Digite outro valor: ')) while menu != 5: print('[1] Somar\n[2] Multiplicar\n[3] Maior\n[4] Novos números\n[5] Sair do programa') menu = int(input('Digite a opção desejada: ')) if menu == 1: s = n1 + n2 print(f'{n1}...
#Ler 10 números inteiros e identificar o maior n=0 m=0 x=0 while(x<10): n=int(input ("entre com o número")) x=x+1 if (n>m): m=n print ("O maior número é: ", m)
class Solution: def XXX(self, nums: List[int]) -> List[List[int]]: result = [] if len(nums)==1: return [nums[:]] for i in range(len(nums)): num = nums.pop(0) # 对剩下的元素找可能的排列 perms = self.XXX(nums) for perm in perms: #...
def numPointsInSpans(spans): """ ARC112B >>> numPointsInSpans([(1, 3)]) 3 >>> numPointsInSpans([(1, 3), (5, 7)]) 6 >>> numPointsInSpans([(1, 3), (3, 5)]) 5 >>> numPointsInSpans([(1, 3), (2, 5)]) 5 """ timeline = [] for start, end in spans: assert start <= end ...
# @dependency 001-main/002-createrepository.py with repository.workcopy() as work: review = Review(work, "alice", "200-json/008-batches") review.addFile(first="200-json/008-batches/first.txt", second="200-json/008-batches/second.txt", third="200-json/008-batches/third.txt"...
# * # * * # * * * # * * * * for row in range(0,4): for column in (0,row+1): # range is not there hence weired output print(column,end=' ') print("") #end is very important, by default it is \n which is new line, # it needs to remove for pattern programs and can be replace woth #empty string or sp...
# material definition table: artdeco # artdeco = [\ [ # 0 [[0.0706087, 0.0212897, 0.0336154, 1.0]], # ambient [[0.282435, 0.0851587, 0.134462, 1.0]], # diffuse [[0.0, 0.0, 0.0, 1.0]], # emission [[0.276305, 0.11431, 0.139857, 1.0]], # specular [0.127273], # shini...
# 126. Word Ladder II # ttungl@gmail.com # Given two words (beginWord and endWord), and a dictionary's word list, # find all shortest transformation sequence(s) from beginWord to endWord, such that: # Only one letter can be changed at a time # Each transformed word must exist in the word list. Note that beginWord is ...
th_prime_number_being_searched = 10001 arbitrary_size = 1000000 prime_numbers = [True] * arbitrary_size prime_numbers[1] = False counter_prime_numbers = 0 i = 1 continue_search = True while (i < arbitrary_size - 1 and continue_search): i += 1 if (prime_numbers[i]): counter_prime_numbers += 1 if...
class EditorBrowsableState(Enum, IComparable, IFormattable, IConvertible): """ Specifies the browsable state of a property or method from within an editor. enum EditorBrowsableState,values: Advanced (2),Always (0),Never (1) """ def __eq__(self, *args): """ x.__eq__(y) <==> x==yx.__eq__...
def my_handler(event, context): return 'new hello world'
# -*- coding: utf-8 -*- __author__ = 'Andrew Stretton' __email__ = 'andrew.stretton@sgc.ox.ac.uk' __version__ = '0.1.0'
# built-int list1.sort() sorted(list1) can be used def partition(arr, i, j, p): left = i right = j while(left < right): while(arr[left] < p): left += 1 while(arr[right] > p): right -= 1 if left < right: arr[left], arr[right] = arr[righ...
a = "I am not tainted" while b: send_mail_jinja(a) a = ContactMailForm() + get_query_string() execute(a)
""" upload data related constants """ INSTRUCTIONS_1 = """You can upload your data using an ```Excel file (.xlsx)``` which should at least have the following columns: * **Date.** it is advised to use reversed order (**YYYY/MM/DD**). * **Amount.** the values for **incomes** should be **positive** while **expenses*...
class Penalty: def __init__(self, stats): self.player_penalty = stats.playing_players self.cpu_penalty = 1.05 ** (100 * stats.system_load) * 10 - 10 self.null_frame_penalty = 0 self.deficit_frame_penalty = 0 if stats.frames_nulled is not -1: self.null_frame_penal...
class Solution: def countArrangement(self, N: int) -> int: def getValid(i, usedValues): if i > N: return 1 count = 0 for val in range(1, N+1): if not usedValues[val] and (val%i==0 or i%val == 0): usedValues[...
class Solution: def longestPalindrome(self, s: str) -> str: dp = [[0 for _ in range(len(s) + 1)] for _ in range(len(s) + 1)] for i in range(len(s)): dp[i][i] = 1 for i in range(len(s) - 1, -1, -1): for j in range(i + 1, len(s)): if(s...
''' Lab 7 Implementação do Método de Newton Gabriel Tardochi Salles , TIA = 41822730 ''' # Metodo de Newton, recebe p0, funcao f, derivada fd de f, tolerancia tol, e N máximo de iteracoes permitidas ao algoritmo def Newton(p0, f, fd, tol, n): k = 1 pa = p0 while(k<=n): p = pa - (f(pa)/fd(pa)) ...
class Node: def __init__(self, key, val, left=None, right=None, n=0): self.key = key self.val = val self.left = left self.right = right self.n = n class BinarySearchTree: def __init__(self): self.root = None def size(self, node): if not node: ...
#048_Soma_impares_multiplos_de_3.py i = int(input("Início: ")) f = int(input("Fim: ")) s = int(input("Passo: ")) soma = 0 for c in range(i, f+1, s): if (c % 2 == 1 and c % 3 == 0): print(c) soma += c print(soma)
counter = {chr(val): 0 for val in range(97, 124)} str1 = input("enter the string: ") for char in str1: if not char == " ": counter[char] += 1 for char in str1: if not char == " ": print(char, counter[char], end=",")
# Question: https://projecteuler.net/problem=44 N = 10000 pentagon_nums = [i*(3*i-1) for i in range(1, N+1)] pentagon_num_set = set(pentagon_nums) best_diff = N * (3*N - 1) for i, a in enumerate(pentagon_nums): for b in pentagon_nums[i:]: if b - a > best_diff: break if (b - a) in pe...
def findsd(n): d = n - 1 s = 0 while d % 2 == 0: d >>= 1 s += 1 return (s, d) # Is composite? def MillerRabin(n, a, s, d): if pow(a, d, n) == 1: return False #might be prime for r in range(0, s, 1): if pow(a, 2**r*d, n) == n-1: return False #might be prime return True #definitely not prime # Is n ...
x=input() count=0 m=x.split(".") print(len(m))
a = [int(i) for i in input().split()] b = 0 for i in range(1, len(a) - 1): if a[i - 1] < a[i] > a[i + 1]: b += 1 print(b)
session_numbers = [] lower_bound = 0.0 upper_bound = 0.0 while True: # Set the minimum and maximum values try: lower_bound = float(input("Please enter the minimum value allowed for this instance of the program: ")) upper_bound = float(input("Please enter the maximum value allowed: ")) if ...
@app.errorhandler(403) # Trying to access without permission @login_required def page_not_allowed(e): return render_template('403.html'), 403 @app.errorhandler(404) # Trying to access page that does not exist. @login_required def page_not_found(e): return render_template('404.html'), 404 @app.errorhandler(500...
def numpaths(m , n): if m == 1 or n == 1: return 1 return numpaths(m -1 , n) + numpaths(m, n-1) m = int(input("M: ")) n = int(input("N: ")) print(numpaths(m , n))
class Logger: """ Class that provides methods to log warnings and errors. """ @staticmethod def warning(message): print("[Warning] {}".format(message)) @staticmethod def error(message): print("[Error] {}".format(message))
# Given some integer, find the maximal number you can obtain by deleting exactly one digit of the given number. # # Example # # For n = 152, the output should be # deleteDigit(n) = 52; # For n = 1001, the output should be # deleteDigit(n) = 101. def deleteDigit(n): num = 0 s = str(n) for i in range(len(s...
print("Hello!, Welcome to Python") print("*" * 40) print("Please Enter your name ") name = input() print("Your name is, " + name) # Hello!,Welcome to Python # **************************************** # Please Enter your name # Leo # Your name is, Leo
# # Copyright (C) 2019 The Android Open Source Project # # 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 la...
def dataset(state, event): del state, event # unused return "the_fabulous_cifar10_dataset" def register(mf): mf.register_helpers({ "num_data": 24 }) mf.register_event("dataset", dataset, unique=True)
# -*- coding: utf-8 -*- # Scrapy settings for europython project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'europython' SPIDER_MODULES = ['europython.spide...
def find_substring(string, substring, count_start=0, count_stop=0): """ find substring with unknown start/finish index and return metadata of said string :param string: full string (str) :param substring: str :param count_start: starting index for the search after substring :param count_stop: ...
name = "Kalob" def myfunc(name): # name = "New name" return name print(myfunc()) print(name)
n = int(input()) a, b = [], [] for i in range(n): a.append(input()) for i in range(n): b.append(input()) count = 0 for i in range(n): if a[i] == b[i]: count += 1 print(count)
def binary_search(input_array, value): """Your code goes here.""" # mid = len(input_array)//2 # if input_array[mid] < value: # return binary_search(input_array[mid+1:],value) # elif input_array[mid] > value: # return binary_search(input_array[:mid],value) # elif input_array[mid] == ...
print(u'\xA9')
# encoding: utf-8 # usando python 3 # Metades de cadeia - Implemente um programa que lê uma cadeia de caracteres de tamanho até # 255 e mostra na tela as metades da cadeia. [Dica: basear os cálculos no tamanho da cadeia] frase = input("Digite uma frase com até 255 caracteres: ") tamanho=len(frase) metade = int(taman...
# ---------------------------- print('# 1. Цикл for:') i = 1 for color in 'red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'violet': print('#', i, ' color of rainbow is ', color, sep='') # print('#', i, ' color of rainbow is ', color, sep = '**') i += 1 for i in 1, 2, 3, 'one', 'two', 'three': print...
# Via http://www.fabiocrameri.ch/colourmaps.php ACTON = ( (46, 33, 77), (47, 34, 77), (48, 35, 78), (49, 36, 79), (50, 37, 80), (51, 38, 81), (52, 38, 82), (53, 39, 83), (54, 40, 84), (55, 41, 85), (56, 42, 86), (57, 43, 87), (58, 44, 88), (59, 45, 88), (60, ...
#!/usr/bin/env python3.8 def starred_return(): my_list = ["value2", "value3"] return "value1", *my_list def starred_yield(): my_list = ["value2", "value3"] yield "value1", *my_list # all right hand side expressions allowed in regular assignments are now also allowed in # annotated assignments a : ...
# -*- coding: utf-8 -*- """ Created on Mon Sep 21 22:46:14 2020 @author: sl7516 """ def write_MacroCoor(pwd, geometry_name, job_name): fr = open('Macro_ExtractCoor.py', 'w') fr.write('# -*- coding: mbcs -*-\n') fr.write('# Do not delete the following import lines\n') fr.write('from abaqus imp...
a=float(input("Informe a altura:")) c=float(input("Informe o comprimento:")) t=((a*2)+(c*2)) d=(t/(3.6*3)) p=(d*107) print("O total da parede dá {:.1f} e o total de lata a ser pago vai ser{:.2f}".format(t,p))
path1 = "/Users/traviskochel/Desktop/temp/Kablammo-8-21-d.pdf" path2 = "/Users/traviskochel/Desktop/temp/Kablammo-8-24-b.pdf" exportPath = "/Users/traviskochel/Desktop/temp/Kablammo-8-21-8-24.pdf" # rgba color1 = (1,0,0,1) color2 = (0,0,1,1) # PDF exports in raster, so raise this if it's too pixellated. Lower for ...
# List of ipymd cells expected for this example. output = [ {'cell_type': 'markdown', 'source': '# Test notebook'}, {'cell_type': 'markdown', 'source': 'This is a text notebook. Here *are* some **rich text**, ' '`code`, $\\pi\\simeq 3.1415$ equations.'}, {'cell_type': 'markdown',...
i = 0 while i < 5: i = i + 1 if i > 3: break print(i)
class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: g.sort() s.sort() i = j = 0 for cookie in s: if i >= len(g): return i if cookie >= g[i]: i += 1 return i
# Write your count_first_letter function here: def count_first_letter(names): letters = {} for key in names: first_letter = key[0] if first_letter not in letters: letters[first_letter] = 0 letters[first_letter] += len(names[key]) return letters # Uncomment these function calls to test your fun...
US_TIMEZONE_CHOICES = ( ('America/Anchorage', 'US/Alaska', ), ('America/Adak', 'US/Aleutian', ), ('America/Phoenix', 'US/Arizona', ), ('America/Chicago', 'US/Central', ), ('America/Indiana/Indianapolis', 'US/East-Indiana', ), ('America/New_York', 'US/Eastern', ), ('Pacific/Honolulu', 'US/Haw...
""" 1. Clarification 2. Possible solutions - Long division 3. Coding 4. Tests """ # T=O(n), S=O(n) class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: if numerator == 0: return "0" fraction = list() if (numerator < 0) ^ (denominator < 0): ...
# https://www.codewars.com/kata/5d5a7525207a674b71aa25b5 def odd_row(row): base = row * (row - 1) return [base + n * 2 + 1 for n in range(row)]
# -*- coding: utf-8 -*- # Copyright 2017-TODAY LasLabs Inc. # License MIT (https://opensource.org/licenses/MIT). class HelpScoutException(Exception): """Base exception for HelpScout library errors.""" def __init__(self, message): self.message = message def __str__(self): return str(self....
apple_price = 200 apple_count = 8 # apple_priceとapple_countを掛けた結果を、変数total_priceに代入してください total_price = apple_price * apple_count # total_priceの値を出力してください print(total_price)
# Copyright 2012 Loris Corazza, Sakis Christakidis # # 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...
# # Copyright (C) 2018 The Android Open Source Project # # 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 la...
obis_codes = { "1.8.0": "Positive active energy (A+) total [kWh]", "1.8.1": "Positive active energy (A+) in tariff T1 [kWh]", "1.8.2": "Positive active energy (A+) in tariff T2 [kWh]", "1.8.3": "Positive active energy (A+) in tariff T3 [kWh]", "1.8.4": "Positive active energy (A+) in tariff T4 [kWh]...
""" RFID =============== """ # from .rfid import RFID
n = int(input()) for i in range(n): c = False k = int(input()) name = input() items = [input() for _ in range(k)] if 'pea soup' in items and 'pancakes' in items: print(name) c = True break if not c: print('Anywhere is fine I guess')
# Пример класса по определению расстояния до указанных координат на плоскости начиная с пересечения осей x и y (0) #----------------------------------------------------------------------------------------------------------------- # по соглашению программистов, имена классов пишутся с Большой буквы class Point2D: # ...
class Continent: def __init__(self, name, id = None): self.name = name self.id = id
class AbstractWeightsLearning(object): def __init__(self, num_data, num_treatment, data_model): self.num_data = num_data self.num_treatment = num_treatment self.data_model = data_model self.policy = None def update_policy(self, policy): # policy is function mapping x v...
# 209. Minimum Size Subarray Sum # Time: O(len(nums)) # Space: O(1) class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: min_range = 1<<32 cur_sum = 0 start = 0 for index,num in enumerate(nums): cur_sum+=num while cur_sum>=s: ...
# Lucia Saura 24/03/2018 # factorial # source of information https://www.youtube.com/watch?v=D6qpjk48U6U def factorial3 (num): #first a name is given to the function and a name to the value that we will be calling at the end (when calling the function) #in the video source they are doing that asking a number on the sh...
# Space: O(n) # Time: O(n) class Solution: def findPaths(self, m, n, maxMove, startRow, startColumn): self.mod = 1000000007 self.board = [[[-1 for _ in range(n)] for _ in range(m)] for _ in range(maxMove + 1)] return self.dfs(m, n, startRow, startColumn, maxMove) % self.mod def dfs...
# Doubly LinkedList ''' head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | o-------->| 3 | null | | | o<--------| | o<--------|...
class BaseMic(object): def __init__(self, *args, **kwargs): pass def set(self): pass def tune(self): pass def listen(self): pass def reset(self): pass def record(self): pass
class setu: def __init__( self, url='', type=2, info={}, pic_file='' ): self.url=url self.type=type self.info=info self.pic_file=pic_file
def generate_test_payment_method_code(number): return "stub-" + number VisaPaymentMethodCode = generate_test_payment_method_code("4111111111111111") InvalidPaymentMethodCode = generate_test_payment_method_code("invalid-payment-method-code") Session = "stub-session" InvalidSession = "stub-invalid-session"
name, age = "Sreelakshmi", 19 username = "Sreelakshmi-M.py" print ('Hello!') print("Name: {}\nAge: {}\nUsername: {}".format(name, age, username))