content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
''' In this module were implemented functions that check if the board is correctly built. >>> validate_board(["****4****","***21****"," 26****","* 5 2****",\ " 04 8 2 "," 7 65 4","12 34 "," 456 ***"," 1 3****"]) False ''' def rule2(lst:list)->bool: ''' Checks if there is no similar elements in lines...
""" In this module were implemented functions that check if the board is correctly built. >>> validate_board(["****4****","***21****"," 26****","* 5 2****"," 04 8 2 "," 7 65 4","12 34 "," 456 ***"," 1 3****"]) False """ def rule2(lst: list) -> bool: """ Checks if there is no similar elements in lines...
def main(): # input N, M = map(int, input().split()) ABs = [[*map(int, input().split())] for _ in range(M)] # compute adj = set(max(AB) for AB in ABs if min(AB) == 1) flag = any(min(AB) in adj for AB in ABs if max(AB) == N) # output if flag: print('POSSIBLE') else: ...
def main(): (n, m) = map(int, input().split()) a_bs = [[*map(int, input().split())] for _ in range(M)] adj = set((max(AB) for ab in ABs if min(AB) == 1)) flag = any((min(AB) in adj for ab in ABs if max(AB) == N)) if flag: print('POSSIBLE') else: print('IMPOSSIBLE') if __name__ ==...
def task1(): c = 0 while 1: try: x = int(input()) except EOFError: break c += x // 3 - 2 return c def task2(): c = 0 while 1: try: x = int(input()) except EOFError: break while x >= 6: ...
def task1(): c = 0 while 1: try: x = int(input()) except EOFError: break c += x // 3 - 2 return c def task2(): c = 0 while 1: try: x = int(input()) except EOFError: break while x >= 6: x = x ...
class getChannel: query = """ query($id: ID $login: String) { user(id: $id login: $login) { id login displayName description createdAt profileImageURL(width: 300) offlineImageURL roles { i...
class Getchannel: query = '\n query($id: ID $login: String) {\n user(id: $id login: $login) {\n id\n login\n displayName\n description\n createdAt\n profileImageURL(width: 300)\n offlineImageURL\n roles {\n ...
for t in range(int(input())): L=list(map(int,input().split())) totalMinute=(L[0]+L[2])*60+(L[1]+L[3]) if (totalMinute//60)%12==0: a=12 else : a=(totalMinute//60)%12 print(f"#{t+1} {a} {totalMinute%60}")
for t in range(int(input())): l = list(map(int, input().split())) total_minute = (L[0] + L[2]) * 60 + (L[1] + L[3]) if totalMinute // 60 % 12 == 0: a = 12 else: a = totalMinute // 60 % 12 print(f'#{t + 1} {a} {totalMinute % 60}')
# DO NOT LOOK AT THIS CODE # # Just go along.. # # Lokk at something pretty instead... ############################################ def process(uri: str): f = open(uri, 'r') programms = [] # Save all programms (with their children) into an array for line in f: prog = [] prog.append(li...
def process(uri: str): f = open(uri, 'r') programms = [] for line in f: prog = [] prog.append(line.split(' ')[0]) prog.append(line.split(' ')[1].replace('(', '').replace(')', '')) if '->' in line: prog.append(line.split('->')[1].replace(',', '').replace('\n', '')....
#Linkedlist implementation class Node: def __init__(self,key): self.key=key self.next=None head=Node(10) head.next=Node(20) head.next.next=Node(30) head.next.next.next=Node(20) #print(head) def print_Linkedlist(head): curr=head while curr!=None: print(curr.key) curr=curr.next #...
class Node: def __init__(self, key): self.key = key self.next = None head = node(10) head.next = node(20) head.next.next = node(30) head.next.next.next = node(20) def print__linkedlist(head): curr = head while curr != None: print(curr.key) curr = curr.next def insert_in_be...
_YEAST = { "use_tss": True, "window": (1000, 100), "tandem": 25 } _FLY = { "use_tss": True, "window": (50000, 2000), "tandem": 100 } _MOUSE = { "use_tss": True, "window": (50000, 2000), "tandem": 100 } _HUMAN = { "use_tss": True, "window": (50000, 2000), "tandem": 100 ...
_yeast = {'use_tss': True, 'window': (1000, 100), 'tandem': 25} _fly = {'use_tss': True, 'window': (50000, 2000), 'tandem': 100} _mouse = {'use_tss': True, 'window': (50000, 2000), 'tandem': 100} _human = {'use_tss': True, 'window': (50000, 2000), 'tandem': 100} species_map = {'yeast': _YEAST, 'saccharomyces cerevisiae...
class DeliveryRouter(object): app_label = 'delivery' db_name = 'delivery' def db_for_read(self, model, **hints): if self._is_delivery_method_model(model): return None if model._meta.app_label == self.app_label: return self.db_name return None def db...
class Deliveryrouter(object): app_label = 'delivery' db_name = 'delivery' def db_for_read(self, model, **hints): if self._is_delivery_method_model(model): return None if model._meta.app_label == self.app_label: return self.db_name return None def db_for_...
""" @author: Badita Marin-Georgian @email: geo.badita@gmail.com @date: 20.03.2020 00:48 """
""" @author: Badita Marin-Georgian @email: geo.badita@gmail.com @date: 20.03.2020 00:48 """
class Solution: def bitwiseComplement(self, N: int) -> int: binary = bin(N)[2:] ans = ['0'] * len(binary) for i in range(len(binary)): if binary[i] == '0': ans[i] = '1' else: ans[i] = '0' return int(''.join(ans), 2)
class Solution: def bitwise_complement(self, N: int) -> int: binary = bin(N)[2:] ans = ['0'] * len(binary) for i in range(len(binary)): if binary[i] == '0': ans[i] = '1' else: ans[i] = '0' return int(''.join(ans), 2)
""" 1.Question 1 In this programming problem and the next you'll code up the knapsack algorithm from lecture. Let's start with a warm-up. This file (knapsack1.txt) describes a knapsack instance, and it has the following format: [knapsack_size][number_of_items] [value_1] [weight_1] [value_2] [weight_2] ...
""" 1.Question 1 In this programming problem and the next you'll code up the knapsack algorithm from lecture. Let's start with a warm-up. This file (knapsack1.txt) describes a knapsack instance, and it has the following format: [knapsack_size][number_of_items] [value_1] [weight_1] [value_2] [weight_2] ... For ex...
# fig05_01.py """Displaying a bar chart""" numbers = [19, 3, 15, 7, 11] print('\nCreating a bar chart from numbers:') print(f'Index{"Value":>8} Bar') for index, value in enumerate(numbers): print(f'{index:>5}{value:>8} {"*" * value}') #********************************************************...
"""Displaying a bar chart""" numbers = [19, 3, 15, 7, 11] print('\nCreating a bar chart from numbers:') print(f"Index{'Value':>8} Bar") for (index, value) in enumerate(numbers): print(f"{index:>5}{value:>8} {'*' * value}")
# The predict_state function should take in a state # and a change in time, dt (ex. 3 for 3 seconds) # and it should output a new, predicted state # based on a constant motion model # This function also assumes that all units are in m, m/s, s, etc. def predict_state(state, dt): [position, velocity] = state re...
def predict_state(state, dt): [position, velocity] = state return [position + velocity * dt, velocity] test_state = [10, 3] test_dt = 5 test_output = predict_state(test_state, test_dt)
''' Author: jianzhnie Date: 2021-12-03 12:05:26 LastEditTime: 2021-12-03 12:05:27 LastEditors: jianzhnie Description: '''
""" Author: jianzhnie Date: 2021-12-03 12:05:26 LastEditTime: 2021-12-03 12:05:27 LastEditors: jianzhnie Description: """
# (Written into separate file for sharing with cloud code.) # Now let's define a helper function that limits variable length # sparse tensors to a maximum length and converts them to dense # tensors. We need to convert sparse tensors to dense tensors before # we can use them as input in the recurrent neural network. ...
def convert_sparse(sparse, max_len): """Converts batched sparse tensor to dense tensor with specified size. Args: sparse: tf.SparseTensor instance of shape=[n]. max_len: Truncates / zero-pads the dense tensor the specified max_len. """ dense = tf.sparse_to_dense(sparse.indices, sparse.d...
def move_zeroes(nums): """Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ # approach 01 zero_counter = 0 whi...
def move_zeroes(nums): """Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ zero_counter = 0 while 0 in nums: ...
def line_to_board_row(line): return [int(val) for val in line.strip().replace(' ', ' ').split(' ')] def play_board(board, number): played_board = [] for row in board: row = [x if x != number else -1 for x in row] played_board.append(row) return played_board def check_board(board): ...
def line_to_board_row(line): return [int(val) for val in line.strip().replace(' ', ' ').split(' ')] def play_board(board, number): played_board = [] for row in board: row = [x if x != number else -1 for x in row] played_board.append(row) return played_board def check_board(board): ...
def selecao_direta(lista): qntd_trocas = 0 fim = len(lista) for i in range(fim -1): pos_menor = i for j in range(i+1, fim): if lista[j] < lista[pos_menor]: pos_menor = j qntd_trocas += 1 lista[i], lista[pos_menor] = lista[pos_menor], lista[i] return qntd_trocas def ordenada(...
def selecao_direta(lista): qntd_trocas = 0 fim = len(lista) for i in range(fim - 1): pos_menor = i for j in range(i + 1, fim): if lista[j] < lista[pos_menor]: pos_menor = j qntd_trocas += 1 (lista[i], lista[pos_menor]) = (lista[pos_menor], ...
N = int(input()) xyh = [tuple(map(int, input().split())) for _ in range(N)] for e in xyh: if e[2] != 0: t = e candidates = [] for cy in range(101): for cx in range(101): candidates.append((cx, cy, t[2] + abs(t[0] - cx) + abs(t[1] - cy))) for e in xyh: nc = [] for c in candidates: ...
n = int(input()) xyh = [tuple(map(int, input().split())) for _ in range(N)] for e in xyh: if e[2] != 0: t = e candidates = [] for cy in range(101): for cx in range(101): candidates.append((cx, cy, t[2] + abs(t[0] - cx) + abs(t[1] - cy))) for e in xyh: nc = [] for c in candidates: ...
class Urls: url = { "base": "https://www.datpiff.com/", "album": "http://www.datpiff.com", "search": "https://www.datpiff.com/mixtapes-search", } category = { "hot": "http://www.datpiff.com/mixtapes/hot", "new": "http://www.datpiff.com/mixtapes", "top": "http...
class Urls: url = {'base': 'https://www.datpiff.com/', 'album': 'http://www.datpiff.com', 'search': 'https://www.datpiff.com/mixtapes-search'} category = {'hot': 'http://www.datpiff.com/mixtapes/hot', 'new': 'http://www.datpiff.com/mixtapes', 'top': 'http://www.datpiff.com/mixtapes-top', 'celebrated': 'http://w...
def extract_remainder_after_fragments(fragments, content): content = content.lower() for fragment in fragments: fragment = fragment.lower() try: idx = content.index(fragment) return content[idx + len(fragment) + 1:] except ValueError: continue # or pa...
def extract_remainder_after_fragments(fragments, content): content = content.lower() for fragment in fragments: fragment = fragment.lower() try: idx = content.index(fragment) return content[idx + len(fragment) + 1:] except ValueError: continue retu...
def mat_mult(x, y): # 2 by 2 array * 1 by 1 array if len(y) == 2: a = x[0]*y[0] + x[1]*y[1] b = x[2]*y[0] + x[3]*y[1] return [a, b] # 2 by 2 array * 2 by 2 array else: a = x[0]*y[0] + x[1]*y[2] b = x[0]*y[1] + x[1]*y[3] c = x[2]*y[0] + x[3]*y[2] ...
def mat_mult(x, y): if len(y) == 2: a = x[0] * y[0] + x[1] * y[1] b = x[2] * y[0] + x[3] * y[1] return [a, b] else: a = x[0] * y[0] + x[1] * y[2] b = x[0] * y[1] + x[1] * y[3] c = x[2] * y[0] + x[3] * y[2] d = x[2] * y[1] + x[3] * y[3] return [a % ...
expected_output = { 'isakmp_stats': { 'IPv4':{ 1:{ 'destination': '100.0.10.2', 'source': '100.13.220.2', 'session_state': 'QM_IDLE', 'conn_id': 29609, 'status': 'ACTIVE' ...
expected_output = {'isakmp_stats': {'IPv4': {1: {'destination': '100.0.10.2', 'source': '100.13.220.2', 'session_state': 'QM_IDLE', 'conn_id': 29609, 'status': 'ACTIVE'}, 2: {'destination': '100.0.10.2', 'source': '100.12.82.2', 'session_state': 'MM_NO_STATE', 'conn_id': 29188, 'status': 'ACTIVE', 'current_status': 'de...
"""Exercise 1: Country Roads Steps: 1. Fill out Cat.__init__() (line 17) 2. Fill out Cat.meow() (line 21) """ class Animal: def __init__(self, name, sound): self.name = name self.sound = sound def make_sound(self): print(self.sound) class Cat(Animal): def __init__(self, n...
"""Exercise 1: Country Roads Steps: 1. Fill out Cat.__init__() (line 17) 2. Fill out Cat.meow() (line 21) """ class Animal: def __init__(self, name, sound): self.name = name self.sound = sound def make_sound(self): print(self.sound) class Cat(Animal): def __init__(self,...
# OpenWeatherMap API Key weather_api_key = "redacted" # Google API Key g_key = "redacted"
weather_api_key = 'redacted' g_key = 'redacted'
# -*- coding: ISO-8859-1 -*- """Resource phongweights_frag (from file phongweights.frag)""" # written by resourcepackage: (1, 0, 0) source = 'phongweights.frag' package = 'OpenGLContext.resources' data = "vec3 phong_weightCalc( \012 in vec3 light_pos, // light posi\ tion/direction\012 in vec3 half_light, //...
"""Resource phongweights_frag (from file phongweights.frag)""" source = 'phongweights.frag' package = 'OpenGLContext.resources' data = 'vec3 phong_weightCalc( \n in vec3 light_pos, // light position/direction\n in vec3 half_light, // half-way vector between light and view\n in vec3 frag_normal, // geometry nor...
"""Decorator pattern Decorator is a structural design pattern. It is used to extend (decorate) the functionality of a certain object at run-time, independently of other instances of the same class. The decorator pattern is an alternative to subclassing. Subclassing adds behavior at compile time, and the change affects...
"""Decorator pattern Decorator is a structural design pattern. It is used to extend (decorate) the functionality of a certain object at run-time, independently of other instances of the same class. The decorator pattern is an alternative to subclassing. Subclassing adds behavior at compile time, and the change affects...
class UrlVerifyFail(Exception): def __init__(self, message): super().__init__(message) class FailToCreate(Exception): def __init__(self): super().__init__()
class Urlverifyfail(Exception): def __init__(self, message): super().__init__(message) class Failtocreate(Exception): def __init__(self): super().__init__()
class Expression: pass class Assign(Expression): def __init__(self, name, value): self.name = name self.value = value class Binary(Expression): def __init__(self, left, operator, right): self.left = left self.operator = operator self.right = right class Call(Exp...
class Expression: pass class Assign(Expression): def __init__(self, name, value): self.name = name self.value = value class Binary(Expression): def __init__(self, left, operator, right): self.left = left self.operator = operator self.right = right class Call(Expr...
#!/usr/bin/python def next_moves(board, cur_player): '''Returns an iterator with the possible moves that cur_player can make in this turn Each move will be represented by the squared played and the resulting board ''' directions = [(0,1),(0,-1),(1,0),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1)] for row...
def next_moves(board, cur_player): """Returns an iterator with the possible moves that cur_player can make in this turn Each move will be represented by the squared played and the resulting board """ directions = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)] for ro...
def faktor(x) : if x == 0 : return 0 elif x == 1 : return 1 return faktor(x-1)*x x = int(input('masukkan angka yang mau di factorial : ')) print(f'faktorial dari {x} : ',faktor(x))
def faktor(x): if x == 0: return 0 elif x == 1: return 1 return faktor(x - 1) * x x = int(input('masukkan angka yang mau di factorial : ')) print(f'faktorial dari {x} : ', faktor(x))
# -*- coding: utf-8 -*- """ pip_services3_messaging.queues.MessagingCapabilities ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Messaging capabilities implementation. :copyright: Conceptual Vision Consulting LLC 2018-2019, see AUTHORS for more details. :license: MIT, see LICENSE for more...
""" pip_services3_messaging.queues.MessagingCapabilities ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Messaging capabilities implementation. :copyright: Conceptual Vision Consulting LLC 2018-2019, see AUTHORS for more details. :license: MIT, see LICENSE for more details. """ class Mes...
# factorial def fact(num): if num == 0: return 1 else: return num*fact(num-1) print(fact(10)) factorial = 1 for i in range(1,11): factorial*=i # += print(factorial) # a^b def degree(a,b): if b == 0: return 1 else: return a* degree(a,b-1) print(degree(2,10)) deg...
def fact(num): if num == 0: return 1 else: return num * fact(num - 1) print(fact(10)) factorial = 1 for i in range(1, 11): factorial *= i print(factorial) def degree(a, b): if b == 0: return 1 else: return a * degree(a, b - 1) print(degree(2, 10)) deg = 1 for i in ra...
def z(f): return (lambda x: f(lambda y: x(x)(y))) (lambda x: f(lambda y: x(x)(y))) def c(g): return (lambda n: 1 if n == 0 else n * g(n - 1)) print(z(c)(5))
def z(f): return (lambda x: f(lambda y: x(x)(y)))(lambda x: f(lambda y: x(x)(y))) def c(g): return lambda n: 1 if n == 0 else n * g(n - 1) print(z(c)(5))
num1= float(input("Enter first number: ")) op= input("Enter operator: ") num2= float(input("Enter second number: ")) if op == "+": print(num1 + num2) elif op == "-": print(num1 - num2) elif op == "/": print(num1 / num2) elif op == "*": print(num1 * num2) elif op == "**": print(num1 ** ...
num1 = float(input('Enter first number: ')) op = input('Enter operator: ') num2 = float(input('Enter second number: ')) if op == '+': print(num1 + num2) elif op == '-': print(num1 - num2) elif op == '/': print(num1 / num2) elif op == '*': print(num1 * num2) elif op == '**': print(num1 ** num2) else:...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- def calc_Er_mom_bal(n, e_z, dp_dr, v_tor, v_pol, B_tor, B_pol): pres_term = -1.0 / (n * e_z) * dp_dr # pres_term_simp = -1.0 * (Lp * T.J) / e_z # alternative method using grad scale length. vxb_term = -1.0 * (v_pol * B_tor - v_tor * B_pol) E_r = pres_term...
def calc__er_mom_bal(n, e_z, dp_dr, v_tor, v_pol, B_tor, B_pol): pres_term = -1.0 / (n * e_z) * dp_dr vxb_term = -1.0 * (v_pol * B_tor - v_tor * B_pol) e_r = pres_term + vxb_term return (E_r, pres_term, vxb_term)
__author__ = 'eric'
__author__ = 'eric'
""" File name: extensions.py Author: Maciej Bedra File containing all supported extensions, assets names and other static informations. """ # Sublime Text 3 informations sublime_text = { "logo": "st3_logo", "header": "Sublime Text 3" } # Unknown file informations unknown = { "icon": "unknown_file", "header": "Un...
""" File name: extensions.py Author: Maciej Bedra File containing all supported extensions, assets names and other static informations. """ sublime_text = {'logo': 'st3_logo', 'header': 'Sublime Text 3'} unknown = {'icon': 'unknown_file', 'header': 'Unknown file'} supported = {'applescript': 'AppleScript', 'as': 'Acti...
while True: try: d = input() s = input() if s in d: print("Resistente") else: print("Nao resistente") except EOFError: break
while True: try: d = input() s = input() if s in d: print('Resistente') else: print('Nao resistente') except EOFError: break
class Solution(object): def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] >>> sln = Solution() >>> sln.combinationSum([1, 2, 3], 3) [[1, 1, 1], [1, 2], [3]] >>> sln.combinationSum([2...
class Solution(object): def combination_sum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] >>> sln = Solution() >>> sln.combinationSum([1, 2, 3], 3) [[1, 1, 1], [1, 2], [3]] >>> sln.combinationSum(...
class Plot(object): def __init__(self,name,array_func,event_weight_func,hist, dim=1, selection_func=None ): self.name = name self.array_func = array_func self.event_weight_func = event_weight_func self.hist = hist self.dim = dim sel...
class Plot(object): def __init__(self, name, array_func, event_weight_func, hist, dim=1, selection_func=None): self.name = name self.array_func = array_func self.event_weight_func = event_weight_func self.hist = hist self.dim = dim self.selection_func = selection_fun...
# Copyright 2012 Lemur Consulting 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 or agreed ...
"""Settings for the demo """ root_url = 'http://localhost:8080/static/index.html' taxonomy_path = 'data/tax' solr_url = 'http://localhost:8983/solr/collection1' http_cache = '/tmp/solr_cache' ner_host = 'localhost' ner_port = 9000
class english(): NORMAL_ORDERED_SUFFIX = "th" SPECIAL_ORDERED_SUFFIX = { "1":"st", "2":"nd", "3":"rd"} MONTHS = { "1": "January", "2": "February", "3": "March", "4": "April", "5...
class English: normal_ordered_suffix = 'th' special_ordered_suffix = {'1': 'st', '2': 'nd', '3': 'rd'} months = {'1': 'January', '2': 'February', '3': 'March', '4': 'April', '5': 'May', '6': 'June', '7': 'July', '8': 'August', '9': 'September', '10': 'October', '11': 'November', '12': 'December'} weekda...
with open("zad3.txt", "w+") as plik: plik.write(str(print("witaj"))) plik.write(str(print("hej"))) with open("zad3.txt", "r") as plik: for linia in plik: print(linia, end="")
with open('zad3.txt', 'w+') as plik: plik.write(str(print('witaj'))) plik.write(str(print('hej'))) with open('zad3.txt', 'r') as plik: for linia in plik: print(linia, end='')
LABELS = [ "PERCEPTION_LABEL_NOT_SET", "PERCEPTION_LABEL_UNKNOWN", "PERCEPTION_LABEL_DONTCARE", "PERCEPTION_LABEL_CAR", "PERCEPTION_LABEL_VAN", "PERCEPTION_LABEL_TRAM", "PERCEPTION_LABEL_BUS", "PERCEPTION_LABEL_TRUCK", "PERCEPTION_LABEL_EMERGENCY_VEHICLE", "PERCEPTION_LABEL_OTHER...
labels = ['PERCEPTION_LABEL_NOT_SET', 'PERCEPTION_LABEL_UNKNOWN', 'PERCEPTION_LABEL_DONTCARE', 'PERCEPTION_LABEL_CAR', 'PERCEPTION_LABEL_VAN', 'PERCEPTION_LABEL_TRAM', 'PERCEPTION_LABEL_BUS', 'PERCEPTION_LABEL_TRUCK', 'PERCEPTION_LABEL_EMERGENCY_VEHICLE', 'PERCEPTION_LABEL_OTHER_VEHICLE', 'PERCEPTION_LABEL_BICYCLE', 'P...
def countBits(n): num = n binary = '' while (num != 0): bit = num % 2 num = int(num/2) binary += str(bit) print(binary[::-1]) # [::-1] reverse the string return print(numSum(int(binary))) def numSum(n): num = n nSum = 0 for i in str(num): nSum += int(i) ...
def count_bits(n): num = n binary = '' while num != 0: bit = num % 2 num = int(num / 2) binary += str(bit) print(binary[::-1]) return print(num_sum(int(binary))) def num_sum(n): num = n n_sum = 0 for i in str(num): n_sum += int(i) num = num // 10 ...
for _ in range(int(input())): x,b,c=map(float,input().split()) d=((x/5.0)+((b*3.0)/10.0)+(c/2.0)) print("%.1f"%d)
for _ in range(int(input())): (x, b, c) = map(float, input().split()) d = x / 5.0 + b * 3.0 / 10.0 + c / 2.0 print('%.1f' % d)
a,m=map(int,input().split(' ')) for i in range(1, 10000): if a * i % m == 1: print(i) break
(a, m) = map(int, input().split(' ')) for i in range(1, 10000): if a * i % m == 1: print(i) break
def hello(message='Hello world!'): print(message) if __name__ == '__main__': hello() hello('Namaste PyCon!')
def hello(message='Hello world!'): print(message) if __name__ == '__main__': hello() hello('Namaste PyCon!')
"""Top-level package for Easy Forecast.""" __author__ = """Resul Akay""" __email__ = 'resulakay1@gmail.com' __version__ = '0.1.1' __all__ = ["arar", "utils", "arima"]
"""Top-level package for Easy Forecast.""" __author__ = 'Resul Akay' __email__ = 'resulakay1@gmail.com' __version__ = '0.1.1' __all__ = ['arar', 'utils', 'arima']
#Given a string (the input will be in the form of an array of characters), write a function that returns the reverse of the given string. def csReverseString(chars): start = 0 end = len(chars) - 1 while start < end: storage = chars[start] chars[start] = chars[end] chars[end] = s...
def cs_reverse_string(chars): start = 0 end = len(chars) - 1 while start < end: storage = chars[start] chars[start] = chars[end] chars[end] = storage start += 1 end -= 1 return chars def cs_check_palindrome(input_str): start = input_str[0] end = input_str...
"""Sphinx configuration.""" project = "Python Spikedetection" author = "Anthony Fong" copyright = "2022, Anthony Fong" extensions = [ "sphinx.ext.autodoc", "sphinx.ext.napoleon", "sphinx_click", "myst_parser", ] autodoc_typehints = "description" html_theme = "furo"
"""Sphinx configuration.""" project = 'Python Spikedetection' author = 'Anthony Fong' copyright = '2022, Anthony Fong' extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx_click', 'myst_parser'] autodoc_typehints = 'description' html_theme = 'furo'
#$Id$ class ChartOfAccount: """Create object for Chart of Accounts.""" def __init__(self): """Initialize parameters for Chart of accounts.""" self.account_id = '' self.account_name = '' self.is_active = None self.account_type = '' self.account_type_formatted = ''...
class Chartofaccount: """Create object for Chart of Accounts.""" def __init__(self): """Initialize parameters for Chart of accounts.""" self.account_id = '' self.account_name = '' self.is_active = None self.account_type = '' self.account_type_formatted = '' ...
#edit distance dynamic programming # java code https://github.com/mission-peace/interview/blob/master/src/com/interview/dynamic/EditDistance.java def bottom_up_dp(str1, str2): m = len(str1) + 1 n = len(str2) + 1 T = [[0 for x in range(n)] for x in range(m)] for i in range(n): T[0][i] = i ...
def bottom_up_dp(str1, str2): m = len(str1) + 1 n = len(str2) + 1 t = [[0 for x in range(n)] for x in range(m)] for i in range(n): T[0][i] = i for i in range(m): T[i][0] = i for i in range(1, m): for j in range(1, n): if str1[i - 1] == str2[j - 1]: ...
#!/usr/bin/env python3 """This file contains the health check functions used on a Konvoy bundle. """
"""This file contains the health check functions used on a Konvoy bundle. """
class Solution: def countSquares(self, matrix): if not matrix or not matrix[0]: return 0 m = len(matrix) n = len(matrix[0]) ans = 0 for i in range(m): for j in range(n): if matrix[i][j] == 1: if i and j: ...
class Solution: def count_squares(self, matrix): if not matrix or not matrix[0]: return 0 m = len(matrix) n = len(matrix[0]) ans = 0 for i in range(m): for j in range(n): if matrix[i][j] == 1: if i and j: ...
f = open('E:\\a.txt') print(f) print(f.read(5)) print(f.tell()) print(f.seek(45, 0)) print(f.readline()) print(list(f)) f.seek(0, 0) lines = list(f) for each_line in lines: print(each_line) f.seek(0, 0) for each_line in f: print(each_line) f = open('E:\\test.txt', 'w') f.write('I love fish') f.close()
f = open('E:\\a.txt') print(f) print(f.read(5)) print(f.tell()) print(f.seek(45, 0)) print(f.readline()) print(list(f)) f.seek(0, 0) lines = list(f) for each_line in lines: print(each_line) f.seek(0, 0) for each_line in f: print(each_line) f = open('E:\\test.txt', 'w') f.write('I love fish') f.close()
#interface to fetch data from the specified orm # all methods throw exceptions. DB_OPERATIONS = { 'CREATE' : 'CREATE', 'READ' : 'READ', 'UPDATE' : 'UPDATE', 'DELETE' : 'DELETE', 'READ_LIST' : 'READ_LIST' } class DataAdminister(object): def __init__(self, db_connection): if db_connecti...
db_operations = {'CREATE': 'CREATE', 'READ': 'READ', 'UPDATE': 'UPDATE', 'DELETE': 'DELETE', 'READ_LIST': 'READ_LIST'} class Dataadminister(object): def __init__(self, db_connection): if db_connection is None: raise not_implemented_error('need db connnection instance') self.db_conn = d...
# Change the value from "apple" to "kiwi", in the fruits list. fruits = ["apple", "banana", "cherry"] fruits[0] = "kiwi" print(fruits)
fruits = ['apple', 'banana', 'cherry'] fruits[0] = 'kiwi' print(fruits)
#Pembagian bandit = 2500 romeo = 43 kuePerAnak = bandit / romeo print("Setiap anak akan mendapatkan bagian kue sebanyak", kuePerAnak)
bandit = 2500 romeo = 43 kue_per_anak = bandit / romeo print('Setiap anak akan mendapatkan bagian kue sebanyak', kuePerAnak)
# -*- coding: UTF-8 -*- class IcvHttpResponse(object): content=None status_code = 200 error = None headers = {} def __init__(self, content=None,status_code=200): self.content = content self.status_code = status_code @property def ok(self): return self.status_code =...
class Icvhttpresponse(object): content = None status_code = 200 error = None headers = {} def __init__(self, content=None, status_code=200): self.content = content self.status_code = status_code @property def ok(self): return self.status_code == 200 def __repr_...
def is_prime(n): if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return False if n < 9: return True if n%3 == 0: return False r = int(n**0.5) f = 5 while f <= r: if n%f == 0: return False if n%(f+2) == 0: return False f +=6 return True def sum_for_list(lst): count = {} ...
def is_prime(n): if n == 2 or n == 3: return True if n < 2 or n % 2 == 0: return False if n < 9: return True if n % 3 == 0: return False r = int(n ** 0.5) f = 5 while f <= r: if n % f == 0: return False if n % (f + 2) == 0: ...
class Base: def __init__(self): self.a = 'a' def call_static(self): type(self).static_method() @staticmethod def static_method(): print('in the static method of Base') class Child(Base): def __init__(self): super(Child, self).__init__() def call_static(self):...
class Base: def __init__(self): self.a = 'a' def call_static(self): type(self).static_method() @staticmethod def static_method(): print('in the static method of Base') class Child(Base): def __init__(self): super(Child, self).__init__() def call_static(self)...
i = 0 if i == 0: pass while i != 0: pass for x in [0]: pass i = 0 if i == 0: pass while i != 0: pass for x in [0]: pass
i = 0 if i == 0: pass while i != 0: pass for x in [0]: pass i = 0 if i == 0: pass while i != 0: pass for x in [0]: pass
GET = 'GET' POST = 'POST' ID = 'id' VAL = "val" USERNAME = 'username' PASSWORD = 'password' USER = 'user' USER_ID = 'user_id' USER_VAL = 'user_val' SELECT = 'SELECT' # url_rule attributes RULE = "rule" ENDPOINT = "endpoint" VIEW_FUNC = "view_func" METHODS = "methods" class Tables: USER = 'user'
get = 'GET' post = 'POST' id = 'id' val = 'val' username = 'username' password = 'password' user = 'user' user_id = 'user_id' user_val = 'user_val' select = 'SELECT' rule = 'rule' endpoint = 'endpoint' view_func = 'view_func' methods = 'methods' class Tables: user = 'user'
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/kaiodt/kaio_ros_ws/devel/share/sensor_actuator/msg/RotationAction.msg;/home/kaiodt/kaio_ros_ws/devel/share/sensor_actuator/msg/RotationActionGoal.msg;/home/kaiodt/kaio_ros_ws/devel/share/sensor_actuator/msg/RotationActionResult.msg;/home/kaiodt/...
messages_str = '/home/kaiodt/kaio_ros_ws/devel/share/sensor_actuator/msg/RotationAction.msg;/home/kaiodt/kaio_ros_ws/devel/share/sensor_actuator/msg/RotationActionGoal.msg;/home/kaiodt/kaio_ros_ws/devel/share/sensor_actuator/msg/RotationActionResult.msg;/home/kaiodt/kaio_ros_ws/devel/share/sensor_actuator/msg/RotationA...
# building the conversation dataset from the directory # function to build the Q & A dataset def dataset_generator(dir): dataset = [] for __class__ in dir.keys(): for __list__ in dir[__class__]: for i in range(1, len(__list__)): # i = 0 has the question # ...
def dataset_generator(dir): dataset = [] for __class__ in dir.keys(): for __list__ in dir[__class__]: for i in range(1, len(__list__)): dataset.append([__list__[0], __list__[i]]) return dataset "\nTakes input of data directory with this structure:\n{\n 'POLITICS' :\n [\...
try: str except NameError: # Python 3 str = str = str class Key(str): def __getitem__(self, key): return Key("%s:%s" % (self, key))
try: str except NameError: str = str = str class Key(str): def __getitem__(self, key): return key('%s:%s' % (self, key))
string = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." #string = "http://www.pythonchallenge.com/pc/def/map.html" #print(string) output = "" # string.maketran...
string = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." output = '' def do_print(): print(string.translate(str.maketrans('abcdefghijklmnopqrstuvwxyz', 'cdef...
int(10.6) #10 float(100) #100.0 str(100) #'100' int('1001') #1001 int('1001s') # Error bool(1) # True bool(0) # False bool(-1) # True
int(10.6) float(100) str(100) int('1001') int('1001s') bool(1) bool(0) bool(-1)
__version__ = '0.3.1' __author__ = 'Bobson Lin' __email__ = 'bobson801104@gmail.com' __description__ = 'A Flask extension for recording requests and responses'
__version__ = '0.3.1' __author__ = 'Bobson Lin' __email__ = 'bobson801104@gmail.com' __description__ = 'A Flask extension for recording requests and responses'
s = 1 base = 2 for i in range(3, 40, 2): s = s + i / base base *= 2 print(f"{s:.2f}")
s = 1 base = 2 for i in range(3, 40, 2): s = s + i / base base *= 2 print(f'{s:.2f}')
# HEAD # DataType - List method - insert() # DESCRIPTION # Describes the insert method of lists # RESOURCES # # USAGE # .insert(index, item) # inserts an item in place of index in the list # self modification function lists = ['cat', 'dog', 'bat'] lists.insert(1, 'chicken') print(lists) lists.insert(-1, 'testsecondl...
lists = ['cat', 'dog', 'bat'] lists.insert(1, 'chicken') print(lists) lists.insert(-1, 'testsecondlastend') print(lists) lists.insert(len(lists), 'testend') print(lists)
''' lab 7 while loop ''' #3.1 i = 0 while i <=5: if i !=3: print(i) i=i+1 #3.2 i = 1 result=1 while i <=5: result=result*i print(i) i=i+1 print(result) #3.3 i = 1 result=0 while i <=5: result=result+i print(i) i=i+1 print(result) #3.4 i = 3 result=1 while i <...
""" lab 7 while loop """ i = 0 while i <= 5: if i != 3: print(i) i = i + 1 i = 1 result = 1 while i <= 5: result = result * i print(i) i = i + 1 print(result) i = 1 result = 0 while i <= 5: result = result + i print(i) i = i + 1 print(result) i = 3 result = 1 while i <= 8: r...
## Script (Python) "get_firstLevelFolder" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters=object ##title= ## try: while object: if getattr(object.aq_explicit, 'menu_root', 0) or getattr(object.aq_parent.aq_explicit, 'is_di...
try: while object: if getattr(object.aq_explicit, 'menu_root', 0) or getattr(object.aq_parent.aq_explicit, 'is_division', 0): return object object = object.aq_parent.aq_explicit except: return None
for i in range(int(input())): D,d,A,B,C=map(int, input().split()) #given input total_km= d*D #num of days*total distance per day prize=[] #stores prize for each category #condition 1 if(total_km<10): prize.append(0) #condition 2 if(total_km>=10 and total_km<21): ...
for i in range(int(input())): (d, d, a, b, c) = map(int, input().split()) total_km = d * D prize = [] if total_km < 10: prize.append(0) if total_km >= 10 and total_km < 21: prize.append(A) if total_km >= 21 and total_km < 42: prize.append(A) prize.append(B) if...
# content: explore writing to files ''' # open a file to write to it fout = open('ex.txt', 'w') fout.write('This is another line.') # close the open file fout.close() # create a data file containing numbers 1 through 10 each on a seprarate line # ask the user to type in a flie name name = input('Enter a file name:...
""" # open a file to write to it fout = open('ex.txt', 'w') fout.write('This is another line.') # close the open file fout.close() # create a data file containing numbers 1 through 10 each on a seprarate line # ask the user to type in a flie name name = input('Enter a file name:') # open the file to write to it f...
cfg = dict( true_strs=['yes', 'y', 'true'], false_strs=['no', 'n', 'false'], pass_substrs=['password', 'pass'], default_host='localhost', templ_dirs=[('isna', 'playbook_templates'), ], templ_ext=['yml', 'json'], default_ssh_port=22, ) _common_ansi_vars = dict( ansible_python_interpreter...
cfg = dict(true_strs=['yes', 'y', 'true'], false_strs=['no', 'n', 'false'], pass_substrs=['password', 'pass'], default_host='localhost', templ_dirs=[('isna', 'playbook_templates')], templ_ext=['yml', 'json'], default_ssh_port=22) _common_ansi_vars = dict(ansible_python_interpreter='/usr/bin/python2') cfg['common_ansi_v...
""" Kaggle Graph ============ This is the top level module, which includes a :code:`__main__` script to generate the Kaggle graph by loading the required environment variables (including the Kaggle credentials) using :py:mod:`kaggle_graph.action_inputs` and then composing the methods exposed in :py:mod:`kaggle_graph.p...
""" Kaggle Graph ============ This is the top level module, which includes a :code:`__main__` script to generate the Kaggle graph by loading the required environment variables (including the Kaggle credentials) using :py:mod:`kaggle_graph.action_inputs` and then composing the methods exposed in :py:mod:`kaggle_graph.p...
# # PySNMP MIB module WWP-LEOS-DHCP-CLIENT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-LEOS-DHCP-CLIENT-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:37:51 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7....
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint) ...
''' Let's use a map vimap from values to index positions. Initially, all the values will start at positions [n+1, ..., 2n]; every time we pop a value, it will be placed again at positions n, n-1, n-2, etc. We also use a fenwick tree. This data structure is kind of like a virtual array A that lets us do two things in ...
""" Let's use a map vimap from values to index positions. Initially, all the values will start at positions [n+1, ..., 2n]; every time we pop a value, it will be placed again at positions n, n-1, n-2, etc. We also use a fenwick tree. This data structure is kind of like a virtual array A that lets us do two things in ...
# class LLNode: # def __init__(self, val, next=None): # self.val = val # self.next = next class Solution: def solve(self, a, b, lo, hi): if not a: return b a_lo_prev = None if lo == 0 else a for i in range(lo-1): a_lo_prev = a_lo_prev.next a...
class Solution: def solve(self, a, b, lo, hi): if not a: return b a_lo_prev = None if lo == 0 else a for i in range(lo - 1): a_lo_prev = a_lo_prev.next a_hi_next = a for i in range(hi + 1): a_hi_next = a_hi_next.next b_end = b ...
def say_hello(): print ("------------> Hey Mr. hello <-----------") def main(): print ("Entry to the main call") say_hello() if __name__ == "__main__": main()
def say_hello(): print('------------> Hey Mr. hello <-----------') def main(): print('Entry to the main call') say_hello() if __name__ == '__main__': main()
def main(): fish = [int(s) for s in open("input.txt").readline().split(",")] fish_counts = dict( [(age, sum(1 for f in fish if f == age)) for age in range(9)] ) last_day = 256 for day_i in range(1000): if day_i == last_day: print(sum(fish_counts.values())) ...
def main(): fish = [int(s) for s in open('input.txt').readline().split(',')] fish_counts = dict([(age, sum((1 for f in fish if f == age))) for age in range(9)]) last_day = 256 for day_i in range(1000): if day_i == last_day: print(sum(fish_counts.values())) break n...
class EnasNode(object): def __init__(self): self.index = None def __str__(self): instance_string = "Index: {}".format(self.index) return instance_string def __repr__(self): return self.__str__() class EnasModel(object): def __init__(self): self.model_type = None self.nodes = [] de...
class Enasnode(object): def __init__(self): self.index = None def __str__(self): instance_string = 'Index: {}'.format(self.index) return instance_string def __repr__(self): return self.__str__() class Enasmodel(object): def __init__(self): self.model_type = N...
def test(): # Here we can either check objects created in the solution code, or the # string value of the solution, available as __solution__. A helper for # printing formatted messages is available as __msg__. See the testTemplate # in the meta.json for details. # If an assertion fails, the messag...
def test(): assert height_var == None, 'Does your function check the type?' assert 'assert' in __solution__, 'Did you use assert statement?' assert 'type(df)' in __solution__.replace(' ', ''), 'Do you check the type of degrees of freedom?' __msg__.good('Well done!')
Google='Google' BATS='BATS' BMASS='BMASS' def aslist(): return [BMASS, BATS, Google] def getpath(key, config, setting): if key == Google: return config['Google']['AllModes'] if key == BATS: return config['BATS']['AllModes'] elif key == BMASS: return config['BMASS'][setting] ...
google = 'Google' bats = 'BATS' bmass = 'BMASS' def aslist(): return [BMASS, BATS, Google] def getpath(key, config, setting): if key == Google: return config['Google']['AllModes'] if key == BATS: return config['BATS']['AllModes'] elif key == BMASS: return config['BMASS'][settin...
# https://codeforces.com/problemset/problem/1519/B # https://codeforces.com/problemset/submission/1519/118914154 if __name__ == '__main__': t = int(input()) while t>0: t-=1 (n,m,k) = map(int, input().split(' ')) print("YES" if m-1+(n-1)*m==k else "NO")
if __name__ == '__main__': t = int(input()) while t > 0: t -= 1 (n, m, k) = map(int, input().split(' ')) print('YES' if m - 1 + (n - 1) * m == k else 'NO')
# Merge two sorted linked lists and return it as a sorted list. # The list should be made by splicing together the # nodes of the first two lists. class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def mergeTwoLists(self, l1...
class Listnode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def merge_two_lists(self, l1, l2): node_head = node_tracker_current = list_node() while l1 and l2: if l1.val <= l2.val: nodeTracker...
def add(x,y): return x+y def multiply(x,y): return x*y def subtract(x,y): return x-y print("Hi")
def add(x, y): return x + y def multiply(x, y): return x * y def subtract(x, y): return x - y print('Hi')
''' 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, ...
""" 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, ...
__author__ = 'Yifei' class PacketListener(object): def on_packet_received(self, packets): raise NotImplementedError def on_packet_sent(self, packets): raise NotImplementedError class ConnectionListener(object): def on_connected(self, packets): raise NotImplementedError def ...
__author__ = 'Yifei' class Packetlistener(object): def on_packet_received(self, packets): raise NotImplementedError def on_packet_sent(self, packets): raise NotImplementedError class Connectionlistener(object): def on_connected(self, packets): raise NotImplementedError def ...
# -*- coding: utf-8 -*- """ greenbyteapi This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """ class TurbineType(object): """Implementation of the 'TurbineType' model. Turbine-specific type information. Attributes: turbine_type_id (int): TODO: type descri...
""" greenbyteapi This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """ class Turbinetype(object): """Implementation of the 'TurbineType' model. Turbine-specific type information. Attributes: turbine_type_id (int): TODO: type description here. title (...
# # PySNMP MIB module OpenROUTE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OpenROUTE-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:35:56 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...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, value_size_constraint, single_value_constraint, constraints_union, constraints_intersection) ...
class Player: def __init__(self, ID, name, health, items): self.ID = ID self.name = name self.health = health self.items = items def __str__(self): return "My ID: " + str(self.ID) + \ " \nMy Name: " + str(self.name) + \ " \nMy Health: " + str(sel...
class Player: def __init__(self, ID, name, health, items): self.ID = ID self.name = name self.health = health self.items = items def __str__(self): return 'My ID: ' + str(self.ID) + ' \nMy Name: ' + str(self.name) + ' \nMy Health: ' + str(self.health) + ' \nMy Items: ' ...
""" Django-hstore-flattenfields is an alternative for who want to have a Dynamic Scheme in Django without rely on a NoSQL database. Django-hstore-flattenfields add "dynamic fields" in Django Models, using the Hstore extension built in the PostgreSQL v9.1+. This way you can quickly add new fields in a Model, with some g...
""" Django-hstore-flattenfields is an alternative for who want to have a Dynamic Scheme in Django without rely on a NoSQL database. Django-hstore-flattenfields add "dynamic fields" in Django Models, using the Hstore extension built in the PostgreSQL v9.1+. This way you can quickly add new fields in a Model, with some g...
class Solution(object): def findClosestElements(self, arr, k, x): """ :type arr: List[int] :type k: int :type x: int :rtype: List[int] """ idx = bisect.bisect_left(arr, x) l, r = idx, idx # not include r while r - l < k: if l == 0: ...
class Solution(object): def find_closest_elements(self, arr, k, x): """ :type arr: List[int] :type k: int :type x: int :rtype: List[int] """ idx = bisect.bisect_left(arr, x) (l, r) = (idx, idx) while r - l < k: if l == 0: ...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Delivery HS Code', 'version': '1.0', 'category': 'Stock', 'description': """ Set back field hs_code on pruduct template. ============================================================== """, ...
{'name': 'Delivery HS Code', 'version': '1.0', 'category': 'Stock', 'description': '\nSet back field hs_code on pruduct template.\n==============================================================\n\n', 'depends': ['delivery'], 'data': ['views/product_template_view.xml'], 'installable': True, 'auto_install': True}
def chunks(l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n] def api_chunker(inputs,method,arg,n): """ For API calls with a list argument of max N, call the method looping over chunks of inputs of size N """ for ci in chunks(inp...
def chunks(l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n] def api_chunker(inputs, method, arg, n): """ For API calls with a list argument of max N, call the method looping over chunks of inputs of size N """ for ci in chunks(i...