content
stringlengths
7
1.05M
class Item: def __init__(self, profit, weight): self.profit = profit self.weight = weight def zeroKnapsack(items, capacity, currentIndex): if capacity <= 0 or currentIndex < 0 or currentIndex>=len(items): return 0 elif items[currentIndex].weight <= capacity: profit1 = items[currentIndex].profit + zeroKnapsa...
# # PySNMP MIB module WL400-SNMPGEN-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WL400-SNMPGEN-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:36:41 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
__all__ = [ 'update_network_static_route_model', 'rule11_model', 'rule10_model', 'update_network_content_filtering_model', 'rule8_model', 'update_network_ssid_traffic_shaping_model', 'rule7_model', 'update_organization_snmp_model', 'move_network_sm_devices_model', 'lock_...
file = open('helloworld.txt', 'w+') file.write('file: helloworld.txt\n\n') for y in range(10): line = '' if y == 0: line = 'y | x\n' for x in range(10): if x == 0: line += f'{y} | ' line += x.__str__() + ' ' file.write(line + '\n') file.close()
# ------------------------------ # 139. Word Break # # Description: # Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. # Note: # The same word in the dictionary may be reused multi...
""" default configure for benchmark function """ class XtBenchmarkConf(object): """benchmark conf, user also can re-set it""" default_db_root = "/tmp/.xt_data/sqlite" # could set path by yourself default_id = "xt_default_benchmark" defalut_log_path = "/tmp/.xt_data/logs" default_tb_path = "/tmp/....
# # PySNMP MIB module CISCO-DMN-DSG-REMINDER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-DMN-DSG-REMINDER-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:55:08 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
""" Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. Note that after backspacing an empty text, the text will continue empty. Example 1: Input: S = "ab#c", T = "ad#c" Output: true Explanation: Both S and T become "ac". ...
PI = 3.14 r = 6 area = PI * r * r #print(area) #calulate the surface area of a circle. def findArea(r): PI = 3.14 return PI * (r*r); print('area of circle',findArea(6));
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
schema = { "transaction": { "attributes": ["category", "execution-date", "amount", "reference"], "key": "identifier", "representation": [ "execution-date", "reference", "account-of-receiver.account-number", "amount", ], }, "cont...
def function1(a): a[0] = 44 def main(): a = [1, 2, 3] b = a c = a.copy() # 값 변경 function1(a) print(a) print(b) print(c) print(a is b) print(a is c) if __name__=='__main__': main()
''' Get the name and the value of various products. The program should ask if the user wants to continue. In the end show the following: 1 - The total value. 2 - How many products costs more than R$1000. 3 - The name of cheaper product. ''' dlength = 20 division = '=-' * dlength print(f'{divis...
def countWordsFromFile(): fileName = input("Enter the file name:- ") numberOfWords = 0 file = open(fileName, 'r') for line in file: words = line.split() numberOfWords=numberOfWords+len(words) print("The number of words in this file are: ") print(numberOfWords) countWordsFro...
def rearrange(arr, n): # Auxiliary array to hold modified array temp = n*[None] # Indexes of smallest and largest elements # from remaining array. small,large =0,n-1 # To indicate whether we need to copy rmaining # largest or remaining smallest at next position flag = True ...
# def start_end_decorator(func): # def wrapper(number): # print("Start") # result = func(number) # print("End") # return result # return wrapper # @start_end_decorator # def func(number): # print("Inside func") # return number + 5 # result = func(5) # print(result) ...
# O(NlogM) / O(1) class Solution: def splitArray(self, nums: List[int], m: int) -> int: def count(d): ans, cur = 1, 0 for num in nums: cur += num if cur > d: ans += 1 cur = num return ans ...
def f(w : list, u : list, m : int) -> int: x = float(0) for i in range(m): x += (w[i]*u[i]) if x < 0.0: return 0 return 1 def perceptron(u : list, c : float): wt = [1.0 for _ in range(26)] t = 1 counter = 0 while counter < 5: zt = 1 if t % 5 < 3 else 0 ...
# calculo del perimetro del cuadrado print('calculo del perimetro cuadrado') lado = int(input('introduce el valor del lado que conoces del cuadrado: ')) lado *= 4 print('el perimetro del cuadrado es: ',lado)
def load(h): return ({'abbr': 'msl', 'code': 1, 'title': 'MSL Pressure reduced to MSL Pa'}, {'abbr': 't', 'code': 11, 'title': 'T Temperature Deg C'}, {'abbr': 'pt', 'code': 13, 'title': 'PT Potential temperature K'}, {'abbr': 'ws1', 'code': 28, 'title': 'WS1 Wave spectra (1) -'}...
# 9. Find the minimum element in an array of integers. # You can carry some extra information through method # arguments such as minimum value. def findmin(A, n): # if size = 0 means whole array # has been traversed if (n == 1): #if it's the last value just return it for comparison with ...
{ 'target_defaults': { 'variables': { 'deps': [ 'libchrome-<(libbase_ver)', ], }, }, 'targets': [ { 'target_name': 'touch_keyboard_handler', 'type': 'executable', 'sources': [ 'evdevsource.cc', 'fakekeyboard.cc', 'faketouchpad.cc', ...
def insertSort(arr): for i in range(1, len(arr)): val = arr[i] j = i-1 while j >=0 and val < arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = val arr = [67, 12, 1, 6, 9] insertSort(arr) print(arr)
''' 1. vagrant openstack docker 2. 架构 web application SOA micro service 2.1 不同服务tcp 语言的异构 2.2 数据接口api, 前端渲染,前后端渲染混合 2.3 自动弹性,容器,虚拟化,LaaS PaaS 3. 分布式 CAP猜想->CAP定理 C 一致性 A 可用性 P 网络分区的可容忍性 3.1. 小米 3.2. 电商 做秒杀 4. 后端现有架构图 5. jsonrpc ? xmlrpc? soap ? restful api? jsonrpc http json result['result'...
# this files contains basic metadata about the project. This data will be used # (by default) in the base.html and index.html PROJECT_METADATA = { 'title': 'Thunau', 'author': 'Peter Andorfer', 'subtitle': 'An Exavation Docu', 'description': 'A web application to manage and publish data gathered around...
def last_sqrt(x): n = 1 sqr = 0 while x>=sqr: sqr = sqr + ((2*n)-1) n+=1 return n-2 list = [] n = int(input("Enter the Number:")) for num in range(2,(n+1)): list.append(num) for ltsqrt in range(0,(last_sqrt(n)-1)): if list[ltsqrt]!=0: for nums in range((lts...
# parsetab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'leftPLUSMINUSleftTIMESDIVIDErightUMINUSDIVIDE EQUALS LPAREN MINUS NAME NUMBER PLUS RPAREN TIMESstatement : expressionexpression : expression PLUS expression\n ...
## Aim : ## You are given two strings, A and B. ## Find if there is a substring that appears in both A and B. # Input: # The first line of the input will contain a single integer , tthe number of test cases. # Then there will be t descriptions of the test cases. Each description contains two lines. # The first line ...
''' * @File: main.py * @Author: CSY * @Date: 2019/7/27 - 9:40 '''
# Copyright 2022 Tiernan8r # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
class LoopDetected(Exception): """ A loop has been detected while tracing a cable path. """ pass class CableTraceSplit(Exception): """ A cable trace cannot be completed because a RearPort maps to multiple FrontPorts and we don't know which one to follow. """ def __init__(self, term...
def show_free(cal_name, d, m, t1, t2): "String x Integer x String x String x String ->" day = new_day(d) mon = new_month(m) start = convert_time(t1) end = convert_time(t2) cal_day = calendar_day(day, calendar_month(mon, fetch_calendar(cal_name))) show_time_spans(free_spans(cal_day, start, ...
def list_comprehension(): matrix = [ [1 if row == 2 or column == 2 else 0 for column in range(5)] for row in range(5) ] print(matrix) # von Jonas(JoBo12) aus dem Discord def with_for(): matrix_1 = [] for item in range(5): matrix_1.append([]) for item2 in range(5): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: Zeyuan Shang # @Date: 2015-11-19 21:10:01 # @Last Modified by: Zeyuan Shang # @Last Modified time: 2015-11-19 21:10:09 class NumMatrix(object): def __init__(self, matrix): """ initialize your data structure here. :type matrix: List...
# dataset settings data_source_cfg = dict(type='CIFAR10', root='data/cifar10/') dataset_type = 'ExtractDataset' img_norm_cfg = dict(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_pipeline = [ dict( type='RandomResizedCrop', size=224, scale=(0.2, 1.0), interpolation=3), dict(type='RandomHo...
""" Sandbox for MicroPyDatabase A low-memory json-based databse for MicroPython. Data is stored in a folder structure in json for easy inspection. This file contains sample usage. """ #Database examples: db_object = Database.create("mydb2") db_object = Database.open("mydb") #Table examples: db_table = db_object.create...
travel_mode = {"1": "car", "2": "plane"} items = { "can opener", "fuel", "jumper", "knife", "matches", "razor blades", "razor", "scissors", "shampoo", "shaving cream", "shirts (3)", "shorts", "sleeping bag(s)", "soap", "socks (3 pairs)", "stove", "ten...
class Solution: def removeOuterParentheses(self, S: str) -> str: primitiveEndIndices = set([0]) count = 0 for i, char in enumerate(S): if char == '(': count += 1 elif char == ')': count -= 1 if count == 0: pr...
person = { "name": "Bernardo", "age": 21 } print(person) print(person.items()) print(person["name"]) person["wright"] = "78kg" print(person)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- BASE_CF_TEMPLATE = ''' AWSTemplateFormatVersion: 2010-09-09 Description: AWS CloudFormation template Parameters: EcsAmiId: Type: String Description: ECS AMI Id EcsInstanceType: Type: String Description: ECS EC2 instance type Default: t2.micro C...
STABLECOIN_SYMBOLS = ['USDC', 'DAI', 'USDT', 'BUSD', 'TUSD', 'PAX', 'VAI'] FREE_RPC_ENDPOINTS = ['https://api.mycryptoapi.com/eth', 'https://nodes.mewapi.io/rpc/eth', 'https://mainnet-nethermind.blockscout.com/', 'https://mainnet.eth.cloud.ava.do/', ...
# -*- coding: utf-8 -*- class SyncCommand(object): """ Helper class to call core sync """ def __init__(self, core): self.core = core def do(self): """ Do core sync """ self.core.sync()
# based on nuts_and_bolts.scad from MCAD library # https:# github.com/elmom/MCAD/ # Copyright 2010 D1plo1d # This library is dual licensed under the GPL 3.0 and the GNU Lesser General Public License as per http:# creativecommons.org/licenses/LGPL/2.1/ . MM = "mm" INCH = "inch" # Not yet supported # Based on: htt...
var = 77 def func(): global var var = 100 print(locals()) func() print(var)
def solution(xs): mn = -1000 count = 0 product = 0 for element in xs: if element != 0: if product != 0: product = product * element else: product = element count += 1 if element < 0 and element > mn: ...
first_num = 2 secord_num = 3 sum = first_num + secord_num print(sum)
# # PySNMP MIB module NOKIA-NTP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NOKIA-NTP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:13:54 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
""" .. module:: errors :platform: Unix, Windows :synopsis: Global error classes for gNMIP-API .. moduleauthor:: Greg Brown <gsb5067@gmail.com> """ class GNMIException(Exception): """ Exception for GNMI API Errors """ pass class ElasticSearchUploaderException(Exception): """ Exception for Elast...
#!/usr/bin/python #300 most common words according to google #Source: https://github.com/first20hours/google-10000-english #Some words that might refer to scientific information have been removed boringWords=set(['the','of','and','to','a','in','for','is','on','that','by','this','with','i','you','it','not','or','be','a...
{ 'targets': [ { 'target_name': 'publish', 'type':'none', 'dependencies': [ 'appjs' ], 'copies':[ { 'destination': '<(module_root_dir)/app/data/node_modules/appjs/', 'files': [ '<(module_root_dir)/README.md', '<(module_root_...
n, m = map(int, input().split()) ruins = [list(map(int, input().split())) for _ in range(n)] imos = [0] * (m+1) sum_s = 0 for i in range(n): l, r, s = ruins[i] l -= 1 imos[l] += s imos[r] -= s sum_s += s for i in range(m): imos[i+1] += imos[i] print(sum_s - min(imos[:-1]))
input = """ i(0). i(1). a(X) | -a(X) :- i(X). ok :- 0 < #count{X:a(X)}< 2. :- not ok. """ output = """ i(0). i(1). a(X) | -a(X) :- i(X). ok :- 0 < #count{X:a(X)}< 2. :- not ok. """
def check(s, t): v = 0 for i in range(len(t)): if t[i] == s[v]: v += 1 if v == len(s): return "Yes" return "No" while True: try: s, t = input().split() ans = check(s, t) print(ans) except: break
class _descriptor(object): def __get__(self, *_): raise RuntimeError("more like funtime error") class Methods(object): ok_method = "ok" err_method = _descriptor()
''' +Build Your Dream Python Project Discord Team Invite: https://dsc.gg/python_team 19 Feb 2021 @alexandros answer to @Subham https://discord.com/channels/794684213697052712/794684213697052718/812231193213796362 Sublist Yielder ''' lst = [[1, 3, 4], [2, 5, 7]] def f(lst): for sublst in lst: yield from s...
#----------* CHALLENGE 35 *---------- #Ask the user to enter their name and then display their name three times. name = input("Enter your name: ") for i in range (1,4): print(name+" ")
edibles = ["ham", "spam","eggs","nuts"] for food in edibles: if food == "spams": print("No more spam please!") break print("Great, delicious " + food) else: print("I am so glad: No " + food +"!") print("Finally, I finished stuffing myself")
domain = 'mycompany.local' user = 'automation@vsphere.local' pwd = 'somepassword'
game = "Hello world" #print(id(game)) def game_board(player=0, row=0, col=0, just_display=False): game = "Change !" #print(id(game)) print(game) print(game) game_board() print(game) #print(id(game))
def groupnames(name_iterable): name_dict = {} for name in name_iterable: key = _groupkeyfunc(name) name_dict.setdefault(key, []).append(name) for k, v in name_dict.iteritems(): aux = [(_sortkeyfunc(name), name) for name in v] aux.sort() name_dict[k] = tuple([ n for __...
class reverse_iter: def __init__(self, iterable) -> None: self.iterable = iterable self.start = len(iterable) def __iter__(self) -> iter: return self def __next__(self) -> int: if self.start > 0: self.start -= 1 return self.iterable[self.sta...
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def insertAtLast(self, data): node = Node(data) if self.head == None: self.head = node return ...
# __init__.py """[Module pys.conf] Parse .ini configuration of cmd -> build and cmd -> expand """ __all__ = ['mconf', 'mgroup']
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.incr = 0 def convertBST(self, root: TreeNode) -> TreeNode: def dfs(node): if not node: ...
#import necessary data df = pd.read_csv('~/lstm_test/input/nu_public_rep.csv', sep=';', parse_dates={'dt' : ['Date', 'Time']}, infer_datetime_format=True, low_memory=False, na_values=['nan','?'], index_col='dt') #fill nan with the means of the columns to handle missing databases dropi...
# # [463] Island Perimeter # # https://leetcode.com/problems/island-perimeter/description/ # # algorithms # Easy (58.21%) # Total Accepted: 84.4K # Total Submissions: 144.9K # Testcase Example: '[[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]' # # You are given a map in form of a two-dimensional integer grid where 1 # re...
'''Faça um programa que leia um ano qualquer e mostre se ele é bissexto''' ano=int(input('Digite um ano qualquer :')) if ano % 4==0: print('O ano {} é bissexto!!'.format(ano)) else: print('O ano {} não é bissexto!!'.format(ano))
#!/usr/bin/env python # coding: utf8 def writeResults(links, outfile): fw = open(outfile, "w") for link in links: fw.write(link)
# Imagine you're working at IMDb and your new task is to write a # program that will replace all the letters with ligatures and # diacritic marks with their equivalents from the Latin alphabet in # the celebrities' names. The list of replacements is the following: # é -> e # ë -> e # á -> a # å -> a # œ -> oe # æ -> a...
i = get_safe('id') username = "" if i != 0: username = get('username') username = escape_string(username) query = 'some query' it = execute(query + username)
''' file:except.py exceptions for piclock ''' class NoConfigError(Exception): ''' No Config Error Exception ''' class CharacterNotFound(Exception): ''' Character not found exception ''' class MatrixCharError(Exception): ''' Matrix Character Error ''' class NoMqttConfigSection...
# Objectives # # In this stage, you should write a program that: # # Reads matrix A A A from the input. # Reads matrix B B B from the input. # Outputs their sum if it is possible to add them. Otherwise, it should output the ERROR message. # # Each matrix in the input is given in the following way: the first...
"""Zorro's dependency injection framework Usage ===== Declare a class' dependencies:: @has_dependencies class Hello(object): world = dependency(World, 'universe') You must decorate class with ``@has_dependencies``. All dependencies has a type(class), which is ``World`` in this case, and a name, whi...
rows = 9 for i in range(rows): # nested loop for j in range(i): # display number print(i, end=' ') # new line after each row print('')
nu1 = int(input('Digite primeiro valor:')) nu2 = int(input('Digite o segundo valor:')) soma = nu1 + nu2 # print(f'A soma entre {nu1} e {nu2} é: {soma}') print('A soma dos numeros {} e {} é igual {}'.format(nu1, nu2, soma))
""" _ __ _ ___ ___ __ _| | ___ / _` |/ _ \ / _ \ / _` | |/ _ \ | (_| | (_) | (_) | (_| | | __/ \__, |\___/ \___/ \__, |_|\___| |___/ |___/ Author: Aaditya Chapagain version: 1.0.1 description: scripts which will make google API's easy in python. """
# Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. # Para salários superiores a R$1250,00, calcule um aumento de 10%. Para os inferiores ou iguais, # o aumento é de 15%. salário = float(input('Qual seu salário? R$')) if salário > 1250: salário = (salário * 10 / 100) el...
# OpenWeatherMap API Key weather_api_key = "ea45174aae3e4fc5de1af5d14f74cd81" # Google API Key g_key = "AIzaSyCiyVKYg3FYX0fAR2S2RGR1m-kUN947W9s"
def editDistance(str1, str2, m, n, ci=1,crm=1,crp=1): dp = [[0 for i in range(n + 1)] for j in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0: dp[i][j] = j elif j == 0: dp[i][j] = i ...
""" This problem was asked by Stripe. Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, the input [3, 4, -...
#!/usr/bin/env python # -*- coding: utf-8 -*- def funcion_generadora_print(): try: print("GENERADOR: Se va a generar un PRIMER dato") yield "valorGenerado1" print("GENERADOR: Se va a generar un SEGUNDO dato") yield "valorGenerado2" print("GENERADOR: Se va a generar un TER...
"""Provides classes for connecting to and controlling real and mock Spectrum digitiser cards and StarHubs.""" # Christian Baker, King's College London # Copyright (c) 2021 School of Biomedical Engineering & Imaging Sciences, King's College London # Licensed under the MIT. You may obtain a copy at https://opensource.or...
file_input="dump.seq_e10.mci.I12" num=1 output=open('assign_cluster_num.out','w') for i in open(file_input): i=i.replace('\n','') o=i.split() for j in o: output.write(j+'\t'+str(num)+'\n') num+=1 output.close()
t=int(input('Tabuada do : ')) r1 = t * 1 r2 = t * 2 r3 = t * 3 r4 = t * 4 r5 = t * 5 r6 = t * 6 r7 = t * 7 r8 = t * 8 r9 = t * 9 r10 = t * 10 print("RESUlTADO\n------------------------") print('{} x 1 = {}'.format(t,r1)) print('{} x 2 = {}'.format(t,r2)) print('{} x 3 = {}'.format(t,r3)) print('{} x 4 = {}'.format(t,...
class Palettes: # pylint: disable=too-few-public-methods """Color palettes applied to Map visualizations in the style helper methods. By default, each color helper method has its own default palette. More information at https://carto.com/carto-colors/ Example: Create color bins style with the ...
auditory = my_gaussian(x, mu_auditory, sigma_auditory) visual = my_gaussian(x, mu_visual, sigma_visual) posterior_pointwise = visual * auditory posterior_pointwise /= posterior_pointwise.sum() with plt.xkcd(): fig = plt.figure(figsize=(fig_w, fig_h)) my_plot(x, auditory, visual, posterior_pointwise) plt.ti...
def get_google_folder_id(service, folder_name): """Get folder id of a folder in Google Drive Arguments: service: in order to use any of this library, the user needs to first build the service class using google ServiceAccountCredentials. see https://pypi.org/project/google-api-v3-helper/ or https://github.com/...
""" 백준 16600번 : Contemporary Art """ a = int(input())**0.5 print(round(a*4, 8))
# Tutorial skipper snippet def skip_tutorial(): MAPLE_ADMINISTARTOR = 2007 quests_to_complete = [ 20820, # The City of Ereve 20821, # Knight's Orientation 20822, # The Path of Bravery 20823, # Question and Answer 20824, # Knight's Cavalier 20825, # Well-Behaved Student 20826, # Lesson 1 - Ereve History...
class ATM: def __init__(self,balance,bank_name): self.balance = balance self.bank_name = bank_name self.withdrawals_list = [] def show_withdrawals(self): for withdrawal in self.withdrawals_list: print("withdrawal: "+str(withdrawal)) def print_information(self): print("Welcome to "+ self.bank_nam...
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: # brute force ar = nums1 + nums2 ar.sort() n = len(ar) median = ar[n//2] if n%2 != 0: return median else: return (median + ...
defines = {} specials = {} defines.update(globals()["__builtins__"]) def define(fnc): defines[fnc.__name__] = fnc return fnc def rename(name): def deco(fnc): fnc.__name__ = name return define(fnc) return deco def special(fnc): specials[fnc.__name__] = fnc return fnc def ...
def insertion_sort(array): for i in range(1, len(array)): key = array[i] j = i - 1 while j >= 0 and array[i] < array[j]: array[i], array[j] = array[j], array[i] j -= 1 i -= 1 return array def test_insertion_sort_simple(): assert insertion_sort([4...
def generatorA(value, stop): i = 0 while i < stop: value = (value * 16807) % 2147483647 yield value i += 1 def generatorB(value, stop): i = 0 while i < stop: value = (value * 48271) % 2147483647 yield value i += 1 def generatorAPart2(value, stop): i...
# https://www.codechef.com/ELE32018/problems/JACKJILL t=int(input()) for _ in range(t): n,k,d=[int(x) for x in input().strip().split()] a=[int(x) for x in input().strip().split()] b=[int(x) for x in input().strip().split()] flag=0 res1=0 res2=0 for i in range(k): res1 += a[i] res2 += b[i] if(re...
# Copyright 2011 Google Inc. All Rights Reserved. """Specify the modules for which a Python 2.7 stub exists.""" # pylint: disable=undefined-all-variable __all__ = [ # These reside here. 'httplib', 'socket', 'subprocess', 'threading', 'urllib', ] MODULE_OVERRIDES = __all__
class Solution(object): def isValid(self, S): """ :type S: str :rtype: bool """ stack = [] for s in S: if s == 'c': valid = [s] for i in range(2): if not stack: return False ...
# Inicialização de variáveis totalClientes = totalAltura = numHomens = numMulheres = 0 maisAlto = maisBaixo = None while True: codCliente = input("\nDigite o código do cliente ou \"0\" para encerrar o programa: ") try: codCliente = int(codCliente) except: # Se a pessoa não inserir um número, retorna...
proipologismos = float(input('Δώσε ένα χρηματικό σκοπό που έχεις αποφασίσει ' 'να δαπανήσεις σε έναν μήνα: €')) print() eksoda = float(input('Δώσε τα έξοδά σου για αυτόν τον μήνα ' 'ή δώσε 0 για τερματισμό: €')) dapani = 0.0 print() while eksoda != 0: dapani...
class Solution(object): def findMaxConsecutiveOnes(self, nums): ans = 0 cnt = 0 for i in range(len(nums)): if nums[i] == 1: cnt += 1 ans = max(ans, cnt) else: cnt = 0 return ans