content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def func(*args): print(args) print(*args) a = [1, 2, 3] # here "a" is passed as tuple of list: ([1, 2, 3],) func(a) # print(args) -> ([1, 2, 3],) # print(*args) -> [1, 2, 3] # here "a" is passed as tuple of integers: (1, 2, 3) func(*a) # print(args) -> (1, 2, 3) # print(*args) -> 1 2 3
def func(*args): print(args) print(*args) a = [1, 2, 3] func(a) func(*a)
def main(): while True: n,m = map(int, input().split()) if n==0 and m==0: break D = [9] * n H = [0] * m for d in range(n): D[d] = int(input()) for k in range(m): H[k] = int(input()) D.sort() #...
def main(): while True: (n, m) = map(int, input().split()) if n == 0 and m == 0: break d = [9] * n h = [0] * m for d in range(n): D[d] = int(input()) for k in range(m): H[k] = int(input()) D.sort() H.sort() g...
# Default Configurations DEFAULT_PYTHON_PATH = '/usr/bin/python' DEFAULT_STD_OUT_LOG_LOC = '/usr/local/bin/log/env_var_manager.log' DEFAULT_STSD_ERR_LOG_LOC = '/usr/local/bin/log/env_var_manager.log' DEFAULT_START_INTERVAL = 120
default_python_path = '/usr/bin/python' default_std_out_log_loc = '/usr/local/bin/log/env_var_manager.log' default_stsd_err_log_loc = '/usr/local/bin/log/env_var_manager.log' default_start_interval = 120
n=int(input()) students={} for k in range(0,n): name = input() grade=float(input()) if not name in students: students[name]=[grade] else: students[name].append(grade) for j in students: gradesCount=len(students[j]); gradesSum=0 for k in range(0,len(students[j])): ...
n = int(input()) students = {} for k in range(0, n): name = input() grade = float(input()) if not name in students: students[name] = [grade] else: students[name].append(grade) for j in students: grades_count = len(students[j]) grades_sum = 0 for k in range(0, len(students[j])...
def problem_2(): "By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms." sequence = [1] total, sequence_next = 0, 0 # While the next term in the Fibonacci sequence is under 4000000... while(sequence_next < 4000000): ...
def problem_2(): """By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.""" sequence = [1] (total, sequence_next) = (0, 0) while sequence_next < 4000000: sequence_next = sequence[len(sequence) - 1] + sequence[len(seque...
# # PySNMP MIB module HUAWEI-VPLS-TNL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-VPLS-TNL-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:49:40 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, constraints_union, value_size_constraint, single_value_constraint, value_range_constraint) ...
print('a sequence from 0 to 2') for i in range(3): print(i) print('----------------------') print('a sequence from 2 to 4') for i in range(2, 5): print(i) print('----------------------') print('a sequence from 2 to 8 with a step of 2') for i in range(2, 9, 2): print(i) ''' Output: a seque...
print('a sequence from 0 to 2') for i in range(3): print(i) print('----------------------') print('a sequence from 2 to 4') for i in range(2, 5): print(i) print('----------------------') print('a sequence from 2 to 8 with a step of 2') for i in range(2, 9, 2): print(i) '\nOutput:\na sequence from 0 to 2\n0\...
class MockResponse: def __init__(self, status_code, data): self.status_code = status_code self.data = data def json(self): return self.data class AuthenticationMock: def get_token(self): pass def get_headers(self): return {"Authorization": "Bearer token"}...
class Mockresponse: def __init__(self, status_code, data): self.status_code = status_code self.data = data def json(self): return self.data class Authenticationmock: def get_token(self): pass def get_headers(self): return {'Authorization': 'Bearer token'} de...
#Creating a Tuple newtuple = 'a','b','c','d' print(newtuple) # Tuple with 1 element tupple = 'a', print(tupple) newtuple1 = tuple('abcd') print(newtuple1) print("------------------") #Accessing Tuples newtuple = 'a','b','c','d' print(newtuple[1]) print(newtuple[-1]) #Traversing a Tuple for i in newtuple: print(...
newtuple = ('a', 'b', 'c', 'd') print(newtuple) tupple = ('a',) print(tupple) newtuple1 = tuple('abcd') print(newtuple1) print('------------------') newtuple = ('a', 'b', 'c', 'd') print(newtuple[1]) print(newtuple[-1]) for i in newtuple: print(i) print('------------------') print('b' in newtuple)
my_favorite_things = {'food': ['burgers', 'pho', 'mangoes'], 'basketball': ['dribbling', 'passing', 'shooting']} # A list uses square brackets while a dictionary uses curly braces. my_favorite_things['movies'] = ['Avengers', 'Star Wars'] # my_favorite_things of movies is value # A square bracket after a variable allows...
my_favorite_things = {'food': ['burgers', 'pho', 'mangoes'], 'basketball': ['dribbling', 'passing', 'shooting']} my_favorite_things['movies'] = ['Avengers', 'Star Wars'] print(my_favorite_things['food']) appliances = ['lamp', 'toaster', 'microwave'] print(appliances[1]) appliances[1] = 'blender' print(appliances) my_fa...
def get_words_indexes(words_indexes_dictionary, review): words = review.split(' ') words_indexes = set() for word in words: if word in words_indexes_dictionary: word_index = words_indexes_dictionary[word] words_indexes.add(word_index) return words_indexe...
def get_words_indexes(words_indexes_dictionary, review): words = review.split(' ') words_indexes = set() for word in words: if word in words_indexes_dictionary: word_index = words_indexes_dictionary[word] words_indexes.add(word_index) return words_indexes
bool_expected_methods = [ '__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__ge...
bool_expected_methods = ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subcl...
#the program calculates the average of numbers whose input is in the form of a string def average(): numbers = str(input("Enter a string of numbers: ")) numbers = numbers.split() numbers2 = [] total = 0 for number in numbers: number = int(number) total += number ...
def average(): numbers = str(input('Enter a string of numbers: ')) numbers = numbers.split() numbers2 = [] total = 0 for number in numbers: number = int(number) total += number numbers2.append(number) avg = total // len(numbers2) print(avg) average()
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: num_dict = {} for i, num in enumerate(nums): n = target - num if n not in num_dict: num_dict[num] = i else: return [num_dict[n], i]
class Solution: def two_sum(self, nums: List[int], target: int) -> List[int]: num_dict = {} for (i, num) in enumerate(nums): n = target - num if n not in num_dict: num_dict[num] = i else: return [num_dict[n], i]
def pick_arr(arr, b): nums = arr[:b] idxsum = sum(nums) maxsum = idxsum for i in range(b): remove = nums.pop() add = arr.pop() idxsum = idxsum - remove + add maxsum = max(maxsum, idxsum) return maxsum print(pick_arr([5,-2,3,1,2], 3))
def pick_arr(arr, b): nums = arr[:b] idxsum = sum(nums) maxsum = idxsum for i in range(b): remove = nums.pop() add = arr.pop() idxsum = idxsum - remove + add maxsum = max(maxsum, idxsum) return maxsum print(pick_arr([5, -2, 3, 1, 2], 3))
#!/usr/bin/env python # encoding: utf-8 class HashInterface(object): @staticmethod def hash(*arg): pass
class Hashinterface(object): @staticmethod def hash(*arg): pass
class Solution: def solve(self, nums): ans = [-1]*len(nums) unmatched = [] for i in range(len(nums)): while unmatched and unmatched[0][0] < nums[i]: ans[heappop(unmatched)[1]] = nums[i] heappush(unmatched, [nums[i], i]) for i in range(len(nu...
class Solution: def solve(self, nums): ans = [-1] * len(nums) unmatched = [] for i in range(len(nums)): while unmatched and unmatched[0][0] < nums[i]: ans[heappop(unmatched)[1]] = nums[i] heappush(unmatched, [nums[i], i]) for i in range(len(nu...
''' Created on Aug 30, 2012 @author: philipkershaw '''
""" Created on Aug 30, 2012 @author: philipkershaw """
SETTINGS = { 'gee': { 'service_account': None, 'privatekey_file': None, } }
settings = {'gee': {'service_account': None, 'privatekey_file': None}}
# Fried Chicken Damage Skin success = sm.addDamageSkin(2435960) if success: sm.chat("The Fried Chicken Damage Skin has been added to your account's damage skin collection.") # sm.consumeItem(2435960)
success = sm.addDamageSkin(2435960) if success: sm.chat("The Fried Chicken Damage Skin has been added to your account's damage skin collection.")
# -*- coding: utf-8 -*- BADREQUEST = 400 UNAUTHORIZED = 401 FORBIDDEN = 403 GONE = 410 TOOMANYREQUESTS = 412 class DnsdbException(Exception): def __init__(self, message, errcode=500, detail=None, msg_ch=u''): self.message = message self.errcode = errcode self.detail = detail self....
badrequest = 400 unauthorized = 401 forbidden = 403 gone = 410 toomanyrequests = 412 class Dnsdbexception(Exception): def __init__(self, message, errcode=500, detail=None, msg_ch=u''): self.message = message self.errcode = errcode self.detail = detail self.msg_ch = msg_ch s...
#create class class Event: #create class variables def __init__(self , eventId , eventType , themeColor , location): self.eventId = eventId self.eventType = eventType self.themeColor = themeColor self.location = location #define class functions def displayEventDetails(se...
class Event: def __init__(self, eventId, eventType, themeColor, location): self.eventId = eventId self.eventType = eventType self.themeColor = themeColor self.location = location def display_event_details(self): print() print('Event Type = ' + self.eventType) ...
class Piece: def __init__(self, row, col): self.clicked = False self.numAround = -1 self.flagged = False self.row, self.col = row, col def setNeighbors(self, neighbors): self.neighbors = neighbors def getNumFlaggedAround(self): num = 0 for n in self...
class Piece: def __init__(self, row, col): self.clicked = False self.numAround = -1 self.flagged = False (self.row, self.col) = (row, col) def set_neighbors(self, neighbors): self.neighbors = neighbors def get_num_flagged_around(self): num = 0 for n...
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @AUTHOR:Joselyn Zhao @CONTACT:zhaojing17@foxmail.com @HOME_PAGE:joselynzhao.top @SOFTWERE:PyCharm @FILE:del.py @TIME:2020/4/29 19:57 @DES: ''' dict = {'shuxue':99,'yuwen':99,'yingyu':99} print('shuxue:',dict['shuxue']) print('yuwen:',dict['yuwen']) print('yingyu:',dict['yin...
""" @AUTHOR:Joselyn Zhao @CONTACT:zhaojing17@foxmail.com @HOME_PAGE:joselynzhao.top @SOFTWERE:PyCharm @FILE:del.py @TIME:2020/4/29 19:57 @DES: """ dict = {'shuxue': 99, 'yuwen': 99, 'yingyu': 99} print('shuxue:', dict['shuxue']) print('yuwen:', dict['yuwen']) print('yingyu:', dict['yingyu']) dict['wuli'] = 100 dict['hu...
# Input is square matrix A whose rows are sorted lists. # Returns a list B by merging all rows into a single list. # # Goal: O(n^2 log n) # Actually O(n^2 log(n^2)) but since log(n^2) == 2log(n) and constant factors can be ignored => O(2log(n)) can be relaxed to O(log(n)) def mergesort(Sublists): sublists_count=l...
def mergesort(Sublists): sublists_count = len(Sublists) if sublists_count is 0: return Sublists elif sublists_count is 1: return Sublists[0] k = sublists_count // 2 first_half = mergesort(Sublists[:k]) second_half = mergesort(Sublists[k:]) return merge(first_half, second_half...
def non_contiguous_motif(str1, dna_list): index = -1 num = 0 for i in str1: for j in dna_list: index+= 1 if i == j: num = index return num
def non_contiguous_motif(str1, dna_list): index = -1 num = 0 for i in str1: for j in dna_list: index += 1 if i == j: num = index return num
#!/usr/bin/env python NAME = 'Microsoft ISA Server' def is_waf(self): detected = False r = self.invalid_host() if r is None: return if r.reason in self.isaservermatch: detected = True return detected
name = 'Microsoft ISA Server' def is_waf(self): detected = False r = self.invalid_host() if r is None: return if r.reason in self.isaservermatch: detected = True return detected
# # PySNMP MIB module Unisphere-Data-L2F-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-L2F-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:24:37 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint) ...
enu = 3 zenn = 0 for ai in range(enu, -1, -1): zenn += ai*ai*ai print(zenn)
enu = 3 zenn = 0 for ai in range(enu, -1, -1): zenn += ai * ai * ai print(zenn)
deck = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace'] value = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] deck_values = dict(zip(deck, value)) hand = [input() for _ in range(6)] hand_values = [deck_values.get(card) for card in hand] print(sum(hand_values) / 6)
deck = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace'] value = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] deck_values = dict(zip(deck, value)) hand = [input() for _ in range(6)] hand_values = [deck_values.get(card) for card in hand] print(sum(hand_values) / 6)
# -*- coding: utf-8 -*- class RedirectError(Exception): def __init__(self, response): self.response = response class NotLoggedInError(Exception): pass class SessionNotFreshError(Exception): pass
class Redirecterror(Exception): def __init__(self, response): self.response = response class Notloggedinerror(Exception): pass class Sessionnotfresherror(Exception): pass
class Cell(object): def __init__(self): self.neighbours = [None for _ in range(8)] self.current_state = False self.next_state = False self.fixed = False def count_neighbours(self) -> int: count = 0 for n in self.neighbours: if n.current_state: ...
class Cell(object): def __init__(self): self.neighbours = [None for _ in range(8)] self.current_state = False self.next_state = False self.fixed = False def count_neighbours(self) -> int: count = 0 for n in self.neighbours: if n.current_state: ...
# automatically generated by the FlatBuffers compiler, do not modify # namespace: aghast_generated class DimensionOrder(object): c_order = 0 fortran_order = 1
class Dimensionorder(object): c_order = 0 fortran_order = 1
def specialPolynomial(x, n): s = 1 k = 0 while s <= n: k += 1 s += x**k return k-1 if __name__ == '__main__': input0 = [2, 10, 1, 3] input1 = [5, 111111110, 100, 140] expectedOutput = [1, 7, 99, 4] assert len(input0) == len(expectedOutput), '# input0 = {}, # expectedOutput = {}'.format(len(input0), len(exp...
def special_polynomial(x, n): s = 1 k = 0 while s <= n: k += 1 s += x ** k return k - 1 if __name__ == '__main__': input0 = [2, 10, 1, 3] input1 = [5, 111111110, 100, 140] expected_output = [1, 7, 99, 4] assert len(input0) == len(expectedOutput), '# input0 = {}, # expecte...
__all__ = [ "deployment_pb2", "repository_pb2", "status_pb2", "yatai_service_pb2_grpc", "yatai_service_pb2", ]
__all__ = ['deployment_pb2', 'repository_pb2', 'status_pb2', 'yatai_service_pb2_grpc', 'yatai_service_pb2']
def solve(): N = int(input()) V = list(map(int, input().split())) V1 = sorted(V[::2]) V2 = sorted(V[1::2]) flag = -1 for i in range(1, N): i_ = i // 2 # if i&1: print('Check {} {}'.format(V1[i_], V2[i_])) # if i&1==0: print('Check {} {}'.format(V2[i_-1], V1[i_])) ...
def solve(): n = int(input()) v = list(map(int, input().split())) v1 = sorted(V[::2]) v2 = sorted(V[1::2]) flag = -1 for i in range(1, N): i_ = i // 2 if i & 1 and V1[i_] > V2[i_] or (i & 1 == 0 and V2[i_ - 1] > V1[i_]): flag = i - 1 break print('OK') ...
def target(x0, sink): print(f'input: {x0}') while True: task = yield x0 = task(x0) sink.send(x0) def sink(): try: while True: x = yield except GeneratorExit: print(f'final output: {x}')
def target(x0, sink): print(f'input: {x0}') while True: task = (yield) x0 = task(x0) sink.send(x0) def sink(): try: while True: x = (yield) except GeneratorExit: print(f'final output: {x}')
def data_cart(request): total_cart=0 total_items=0 if request.user.is_authenticated and request.session.__contains__('cart'): for key, value in request.session['cart'].items(): if not key == "is_modify" and not key == 'id_update': total_cart = total_...
def data_cart(request): total_cart = 0 total_items = 0 if request.user.is_authenticated and request.session.__contains__('cart'): for (key, value) in request.session['cart'].items(): if not key == 'is_modify' and (not key == 'id_update'): total_cart = total_cart + float(v...
# int: Minimum number of n-grams occurence to be retained # All Ngrams that occur less than n times are removed # default value: 0 ngram_min_to_be_retained = 0 # real: Minimum ratio n-grams to skip # (will be chosen among the ones that occur rarely) # expressed as a ratio of the cumulated histogram # default value: 0...
ngram_min_to_be_retained = 0 ngram_min_rejected_ratio = 0 gram_size = 3 files_path = '/u/lisa/db/babyAI/textual_v2' file_name_train_amat = 'BABYAI_gray_4obj_64x64.train.img' file_name_valid_amat = 'BABYAI_gray_4obj_64x64.valid.img' file_name_test_amat = 'BABYAI_gray_4obj_64x64.test.img' image_size = 32 * 32 file_name_t...
customcb = {'_smps_flo': ["#000000", "#000002", "#000004", "#000007", "#000009", "#00000b", "#00000d", "#000010", "#000012", "#000014", "#000016", "#000019", "#00001b", "#00001d", "#00001f", "#000021", "#000024", "#000026", "#000028", "#00002a"...
customcb = {'_smps_flo': ['#000000', '#000002', '#000004', '#000007', '#000009', '#00000b', '#00000d', '#000010', '#000012', '#000014', '#000016', '#000019', '#00001b', '#00001d', '#00001f', '#000021', '#000024', '#000026', '#000028', '#00002a', '#00002d', '#00002f', '#000031', '#000033', '#000036', '#000038', '#00003a...
class ModelSingleton(object): # https://stackoverflow.com/a/6798042 _instances = {} def __new__(class_, *args, **kwargs): if class_ not in class_._instances: class_._instances[class_] = super(ModelSingleton, class_).__new__(class_, *args, **kwargs) return class_._instances[class...
class Modelsingleton(object): _instances = {} def __new__(class_, *args, **kwargs): if class_ not in class_._instances: class_._instances[class_] = super(ModelSingleton, class_).__new__(class_, *args, **kwargs) return class_._instances[class_] class Sharedmodel(ModelSingleton): ...
tabuleiro_easy_1 = [ [4, 0, 1, 8, 3, 9, 5, 2, 0], [3, 0, 9, 2, 7, 5, 1, 4, 6], [5, 2, 7, 6, 0, 1, 9, 8, 0], [0, 5, 8, 1, 0, 7, 3, 9, 4], [0, 7, 3, 9, 8, 4, 2, 5, 0], [9, 1, 4, 5, 2, 3, 6, 7, 8], [7, 4, 0, 3, 0, 6, 8, 1, 2], [8, 0, 6, 4, 1, 2, 7, 3, 5], [1, 3, 2, 7, 5, 8, 4, 0, 9...
tabuleiro_easy_1 = [[4, 0, 1, 8, 3, 9, 5, 2, 0], [3, 0, 9, 2, 7, 5, 1, 4, 6], [5, 2, 7, 6, 0, 1, 9, 8, 0], [0, 5, 8, 1, 0, 7, 3, 9, 4], [0, 7, 3, 9, 8, 4, 2, 5, 0], [9, 1, 4, 5, 2, 3, 6, 7, 8], [7, 4, 0, 3, 0, 6, 8, 1, 2], [8, 0, 6, 4, 1, 2, 7, 3, 5], [1, 3, 2, 7, 5, 8, 4, 0, 9]] tabuleiro_easy_2 = [[0, 6, 1, 8, 0, 0, ...
class Config(object): def __init__(self, vocab_size, max_length): self.vocab_size = vocab_size self.embedding_size = 300 self.hidden_size = 200 self.filters = [3, 4, 5] self.num_filters = 256 self.num_classes = 10 self.max_length = max_length self.num_...
class Config(object): def __init__(self, vocab_size, max_length): self.vocab_size = vocab_size self.embedding_size = 300 self.hidden_size = 200 self.filters = [3, 4, 5] self.num_filters = 256 self.num_classes = 10 self.max_length = max_length self.num...
#Mayor de edad mayor=int(input("edad: ")) if(mayor >=18): print("es mator de edad") else: print("es menor de edad")
mayor = int(input('edad: ')) if mayor >= 18: print('es mator de edad') else: print('es menor de edad')
def getBASIC(): list = [] n = input() while True: line = n if n.endswith('END'): list.append(line) return list else: list.append(line) newN = input() n = newN
def get_basic(): list = [] n = input() while True: line = n if n.endswith('END'): list.append(line) return list else: list.append(line) new_n = input() n = newN
type_of_flowers = input() count = int(input()) budget = int(input()) prices = { "Roses": 5.00, "Dahlias": 3.80, "Tulips": 2.80, "Narcissus": 3.00, "Gladiolus": 2.50 } price = count * prices[type_of_flowers] if type_of_flowers == "Roses" and count > 80: price -= 0.10 * price elif type_of_flowe...
type_of_flowers = input() count = int(input()) budget = int(input()) prices = {'Roses': 5.0, 'Dahlias': 3.8, 'Tulips': 2.8, 'Narcissus': 3.0, 'Gladiolus': 2.5} price = count * prices[type_of_flowers] if type_of_flowers == 'Roses' and count > 80: price -= 0.1 * price elif type_of_flowers == 'Dahlias' and count > 90:...
#170 # Time: O(n) # Space: O(n) # Design and implement a TwoSum class. It should support the following operations: add and find. # # add - Add the number to an internal data structure. # find - Find if there exists any pair of numbers which sum is equal to the value. # # For example, # add(1); add(3); add(5); # ...
class Twosumiii: def __init__(self): self.num_count = {} def add(self, val): if val in self.num_count: self.num_count[val] += 1 else: self.num_count[val] = 1 def find(self, target): for num in self.num_count: if target - num in self.num_...
def flatten(d: dict, new_d, path=''): for key, value in d.items(): if not isinstance(value, dict): new_d[path + key] = value else: path += f'{key}.' return flatten(d[key], new_d, path=path) return new_d if __name__ == "__main__": d = {"foo": 42, ...
def flatten(d: dict, new_d, path=''): for (key, value) in d.items(): if not isinstance(value, dict): new_d[path + key] = value else: path += f'{key}.' return flatten(d[key], new_d, path=path) return new_d if __name__ == '__main__': d = {'foo': 42, 'bar': '...
class BotovodException(Exception): pass class AgentException(BotovodException): pass class AgentNotExistException(BotovodException): def __init__(self, name: str): super().__init__(f"Botovod have not '{name}' agent") self.name = name class HandlerNotPassed(BotovodException): def __...
class Botovodexception(Exception): pass class Agentexception(BotovodException): pass class Agentnotexistexception(BotovodException): def __init__(self, name: str): super().__init__(f"Botovod have not '{name}' agent") self.name = name class Handlernotpassed(BotovodException): def __i...
class Solution: def carPooling(self, trips: List[List[int]], capacity: int) -> bool: tripOccupancy = [0] * 1002 for trip in trips: tripOccupancy[trip[1]] += trip[0] tripOccupancy[trip[2]] -= trip[0] occupancy = 0 for occupancyDelta in tripOccupancy: ...
class Solution: def car_pooling(self, trips: List[List[int]], capacity: int) -> bool: trip_occupancy = [0] * 1002 for trip in trips: tripOccupancy[trip[1]] += trip[0] tripOccupancy[trip[2]] -= trip[0] occupancy = 0 for occupancy_delta in tripOccupancy: ...
class Result: def __init__(self, value=None, error=None): self._value = value self._error = error def is_ok(self) -> bool: return self._error is None def is_error(self) -> bool: return self._error is not None @property def value(self): return self._value ...
class Result: def __init__(self, value=None, error=None): self._value = value self._error = error def is_ok(self) -> bool: return self._error is None def is_error(self) -> bool: return self._error is not None @property def value(self): return self._value ...
cv_results = cross_validate( model, X, y, cv=cv, return_estimator=True, return_train_score=True, n_jobs=-1, ) cv_results = pd.DataFrame(cv_results)
cv_results = cross_validate(model, X, y, cv=cv, return_estimator=True, return_train_score=True, n_jobs=-1) cv_results = pd.DataFrame(cv_results)
class Usercredentials: ''' class to generate new instances of usercredentials ''' user_credential_list = [] #empty list for user creddential def __init__(self,site_name,password): ''' method to define properties of the object ''' self.site_name = site_name ...
class Usercredentials: """ class to generate new instances of usercredentials """ user_credential_list = [] def __init__(self, site_name, password): """ method to define properties of the object """ self.site_name = site_name self.password = password def...
def GetParent(node, parent): if node == parent[node]: return node parent[node] = GetParent(parent[node], parent) return parent[node] def union(u, v, parent, rank): u = GetParent(u, parent) v = GetParent(v, parent) if rank[u] < rank[v]: parent[u] = v elif rank[u] > rank[...
def get_parent(node, parent): if node == parent[node]: return node parent[node] = get_parent(parent[node], parent) return parent[node] def union(u, v, parent, rank): u = get_parent(u, parent) v = get_parent(v, parent) if rank[u] < rank[v]: parent[u] = v elif rank[u] > rank[v...
#!/usr/bin/env python3 n, *h = map(int, open(0).read().split()) dp = [0] * n dp[0] = 0 a = abs for i in range(1, n): dp[i] = min(dp[i], dp[i-1] + a(h[i] - h[i-1])) dp[i+1] = min(dp[i+1], dp[i-1] + a(h[i] - h[i-2])) print(dp[n-1])
(n, *h) = map(int, open(0).read().split()) dp = [0] * n dp[0] = 0 a = abs for i in range(1, n): dp[i] = min(dp[i], dp[i - 1] + a(h[i] - h[i - 1])) dp[i + 1] = min(dp[i + 1], dp[i - 1] + a(h[i] - h[i - 2])) print(dp[n - 1])
# User input minutes = float(input("Enter the time in minutes: ")) # Program operation hours = minutes/60 # Computer output print("The time in hours is: " + str(hours))
minutes = float(input('Enter the time in minutes: ')) hours = minutes / 60 print('The time in hours is: ' + str(hours))
x = 12 y = 3 print(x > y) # True x = "12" y = "3" print(x > y) # ! False / Why it's false ? print(x < y) # ! True # x = 12 # y = "3" # print(x > y) x2 = "45" y2 = "321" print(x2 > y2) # True x2 = "45" y2 = "621" X2_Length = len(x2) Y2_Length = len(y2) print(X2_Length < Y2_Length) # True print( ord('4') ) # 52...
x = 12 y = 3 print(x > y) x = '12' y = '3' print(x > y) print(x < y) x2 = '45' y2 = '321' print(x2 > y2) x2 = '45' y2 = '621' x2__length = len(x2) y2__length = len(y2) print(X2_Length < Y2_Length) print(ord('4')) print(ord('5')) print(ord('6')) print(ord('2')) print(ord('1'))
''' For 35 points, answer the following questions. Create a new folder named file_io and create a new Python file in the folder. Run this 4 line program. Then look in the folder. 1) What did the program do? ''' f = open('workfile.txt', 'w') f.write('Bazarr 10 points\n') f.write('Iko 3 points') f.close() '''Run this ...
""" For 35 points, answer the following questions. Create a new folder named file_io and create a new Python file in the folder. Run this 4 line program. Then look in the folder. 1) What did the program do? """ f = open('workfile.txt', 'w') f.write('Bazarr 10 points\n') f.write('Iko 3 points') f.close() 'Run this shor...
# -*- coding: utf-8 -*- def main(): n = int(input()) a = [int(input()) for _ in range(n)][::-1] ans = 0 for i in range(n): p, q = divmod(a[i], 2) ans += p if q == 1: if (i + 1 <= n - 1) and (a[i + 1] >= 1): ans += 1 a...
def main(): n = int(input()) a = [int(input()) for _ in range(n)][::-1] ans = 0 for i in range(n): (p, q) = divmod(a[i], 2) ans += p if q == 1: if i + 1 <= n - 1 and a[i + 1] >= 1: ans += 1 a[i + 1] -= 1 print(ans) if __name__ == '_...
''' escreva num arquivo texto.txt o conteudo de uma lista de uma vez ''' arquivo = open('texto.txt', 'a') frases = list() frases.append('TreinaWeb \n') frases.append('Python \n') frases.append('Arquivos \n') frases.append('Django \n') arquivo.writelines(frases)
""" escreva num arquivo texto.txt o conteudo de uma lista de uma vez """ arquivo = open('texto.txt', 'a') frases = list() frases.append('TreinaWeb \n') frases.append('Python \n') frases.append('Arquivos \n') frases.append('Django \n') arquivo.writelines(frases)
'''Exceptions for my orm''' class ObjectNotInitializedError(Exception): pass class ObjectNotFoundError(Exception): pass
"""Exceptions for my orm""" class Objectnotinitializederror(Exception): pass class Objectnotfounderror(Exception): pass
def download_file(my_socket): print("[+] Downloading file") filename = my_socket.receive_data() my_socket.receive_file(filename)
def download_file(my_socket): print('[+] Downloading file') filename = my_socket.receive_data() my_socket.receive_file(filename)
# # @lc app=leetcode id=223 lang=python3 # # [223] Rectangle Area # # @lc code=start class Solution: def computeArea(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int: overlap = max(min(C, G) - max(A, E), 0) * max(min(D, H) - max(B, F), 0) total = (A - C) * (B - D) + (E...
class Solution: def compute_area(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int: overlap = max(min(C, G) - max(A, E), 0) * max(min(D, H) - max(B, F), 0) total = (A - C) * (B - D) + (E - G) * (F - H) return total - overlap
gameList = [ 'Riverraid-v0', 'SpaceInvaders-v0', 'StarGunner-v0', 'Pitfall-v0', 'Centipede-v0' ]
game_list = ['Riverraid-v0', 'SpaceInvaders-v0', 'StarGunner-v0', 'Pitfall-v0', 'Centipede-v0']
class Solution: def boxDelivering(self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int: n = len(boxes) # dp[i] := min trips to deliver boxes[0..i) and return to the storage dp = [0] * (n + 1) trips = 2 weight = 0 l = 0 for r in range(n): weight += box...
class Solution: def box_delivering(self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int: n = len(boxes) dp = [0] * (n + 1) trips = 2 weight = 0 l = 0 for r in range(n): weight += boxes[r][1] if r > 0 and boxes[r...
# https://leetcode.com/explore/featured/card/fun-with-arrays/521/introduction/3238/ class Solution: def findMaxConsecutiveOnes(self, nums): left = 0 prev = 0 while left < len(nums): counter = 0 if nums[left] == 1: right = left while rig...
class Solution: def find_max_consecutive_ones(self, nums): left = 0 prev = 0 while left < len(nums): counter = 0 if nums[left] == 1: right = left while right < len(nums): if nums[right] == 1: ...
# # PySNMP MIB module Nortel-Magellan-Passport-FrameRelayNniTraceMIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-FrameRelayNniTraceMIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:17:48 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 ...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, constraints_intersection, constraints_union, value_size_constraint) ...
RSS_PERF_NAME = "rss" FLT_PERF_NAME = "flt" CPU_CLOCK_PERF_NAME = "cpu_clock" TSK_CLOCK_PERF_NAME = "task_clock" SIZE_PERF_NAME = "file_size" EXEC_OVER_HEAD_KEY = 'exec' MEM_USE_OVER_HEAD_KEY = 'mem' FILE_SIZE_OVER_HEAD_KEY = 'size'
rss_perf_name = 'rss' flt_perf_name = 'flt' cpu_clock_perf_name = 'cpu_clock' tsk_clock_perf_name = 'task_clock' size_perf_name = 'file_size' exec_over_head_key = 'exec' mem_use_over_head_key = 'mem' file_size_over_head_key = 'size'
LINE_LEN = 25 while True: try: n = int(input()) if n == 0: break surface = [] max_len = 0 for i in range(n): line = str(input()) line = line.strip() l_space = line.find(' ') if l_space == -1: max_len = LINE_LEN else: r_space = line.rfind(' ') ...
line_len = 25 while True: try: n = int(input()) if n == 0: break surface = [] max_len = 0 for i in range(n): line = str(input()) line = line.strip() l_space = line.find(' ') if l_space == -1: max_len ...
class Solution: def findMin(self, nums: List[int]) -> int: # solution 1 # return min(nums) # solution 2 left = 0 right = len(nums)-1 while left < right: mid = int((left + right)/2) if nums[mid] < nums[right]: right = mid ...
class Solution: def find_min(self, nums: List[int]) -> int: left = 0 right = len(nums) - 1 while left < right: mid = int((left + right) / 2) if nums[mid] < nums[right]: right = mid elif nums[mid] == nums[right]: right = rig...
def cyclicQ(ll): da_node = ll sentient = ll poop = ll poop = poop.next.next ll = ll.next while poop != ll and poop is not None and poop.next is not None: poop = poop.next.next ll = ll.next if poop is None or poop.next is None: return None node_in_cycle =...
def cyclic_q(ll): da_node = ll sentient = ll poop = ll poop = poop.next.next ll = ll.next while poop != ll and poop is not None and (poop.next is not None): poop = poop.next.next ll = ll.next if poop is None or poop.next is None: return None node_in_cycle = ll ...
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 class Trace: '''An object that can cause a trace entry''' def trace(self) -> str: '''Return a representation of the entry for tracing This is use...
class Trace: """An object that can cause a trace entry""" def trace(self) -> str: """Return a representation of the entry for tracing This is used by things like the standalone ISS with -v """ raise not_implemented_error() class Tracepc(Trace): def __init__(self, pc: int...
WAGTAILSEARCH_BACKENDS = { "default": {"BACKEND": "wagtail.contrib.postgres_search.backend"} }
wagtailsearch_backends = {'default': {'BACKEND': 'wagtail.contrib.postgres_search.backend'}}
# https://www.codingame.com/training/easy/1d-spreadsheet def add_dependency(cell, arg_cell, in_deps, out_deps): if cell not in out_deps: out_deps[cell] = set() out_deps[cell].add(arg_cell) if arg_cell not in in_deps: in_deps[arg_cell] = set() in_deps[arg_cell].add(cell) def remove_dependency(cell, ...
def add_dependency(cell, arg_cell, in_deps, out_deps): if cell not in out_deps: out_deps[cell] = set() out_deps[cell].add(arg_cell) if arg_cell not in in_deps: in_deps[arg_cell] = set() in_deps[arg_cell].add(cell) def remove_dependency(cell, in_deps, out_deps): rc = [] if cell n...
#!/usr/bin/env python # -*- coding: utf-8 -*- class Word: def __init__(self, id, name, image, category=None): self.id = id self.name = name self.image = image self.category = category
class Word: def __init__(self, id, name, image, category=None): self.id = id self.name = name self.image = image self.category = category
def optimal_order(predecessors_map, weight_map): vertices = frozenset(predecessors_map.keys()) # print(vertices) memo_map = {frozenset(): (0, [])} # print(memo_map) return optimal_order_helper(predecessors_map, weight_map, vertices, memo_map) def optimal_order_helper(predecessors_map, weight_map, ...
def optimal_order(predecessors_map, weight_map): vertices = frozenset(predecessors_map.keys()) memo_map = {frozenset(): (0, [])} return optimal_order_helper(predecessors_map, weight_map, vertices, memo_map) def optimal_order_helper(predecessors_map, weight_map, vertices, memo_map): if vertices in memo_...
# Program to implement First Come First Served CPU scheduling algorithm print("First Come First Served scheduling Algorithm") print("============================================\n") headers = ['Processes','Arrival Time','Burst Time','Waiting Time' ,'Turn-Around Time','Completion Time'] # Dictionary to st...
print('First Come First Served scheduling Algorithm') print('============================================\n') headers = ['Processes', 'Arrival Time', 'Burst Time', 'Waiting Time', 'Turn-Around Time', 'Completion Time'] out = dict() n = int(input('Number of processes : ')) (a, b) = (0, 0) for i in range(0, N): k = f...
# -*- coding: utf-8 -*- __author__ = 'Sinval Vieira Mendes Neto' __email__ = 'sinvalneto01@gmail.com' __version__ = '0.1.0'
__author__ = 'Sinval Vieira Mendes Neto' __email__ = 'sinvalneto01@gmail.com' __version__ = '0.1.0'
# Tuples in python def swap(m, n, k): temp = m m = n n = k k = temp return m, n, k def main(): a = (1, "iPhone 12 Pro Max", 1.8, 1) print(a) print(a[1]) print(a.index(1.8)) print(a.count(1)) b = a + (999, 888) print(b) m = 1 n = 2 k = 3 m, n, k = swap(...
def swap(m, n, k): temp = m m = n n = k k = temp return (m, n, k) def main(): a = (1, 'iPhone 12 Pro Max', 1.8, 1) print(a) print(a[1]) print(a.index(1.8)) print(a.count(1)) b = a + (999, 888) print(b) m = 1 n = 2 k = 3 (m, n, k) = swap(m, n, k) print...
# O programa le um valor em metros e o exibe convertido em centimetros e milimetros metros = float(input('Entre com a distancia em metros: ')) centimetros = metros * 100 milimetros = metros * 1000 kilometros = metros / 1000.0 print('{} metros e {:.0f} centimetros'.format(metros, centimetros)) print('{} metros e {} m...
metros = float(input('Entre com a distancia em metros: ')) centimetros = metros * 100 milimetros = metros * 1000 kilometros = metros / 1000.0 print('{} metros e {:.0f} centimetros'.format(metros, centimetros)) print('{} metros e {} milimetros'.format(metros, milimetros)) print('{} metros e {} kilometros'.format(metros,...
train_datagen = ImageDataGenerator(rescale=1./255) # rescaling on the fly # Updated to do image augmentation train_datagen = ImageDataGenerator( rescale = 1./255, # recaling rotation_range = 40, # randomly rotate b/w 0 and 40 degrees width_shift_range = 0.2, # shifting the images height_shift_rang...
train_datagen = image_data_generator(rescale=1.0 / 255) train_datagen = image_data_generator(rescale=1.0 / 255, rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest')
#!/usr/bin/env python ## # Print a heading. # # @var string text # @return string ## def heading(text): return '-----> ' + text; ## # Print a single line. # # @var string text # @return string ## def line(text): return ' ' + text; ## # Print a single new line. # # @return string ## def nl(): return...
def heading(text): return '-----> ' + text def line(text): return ' ' + text def nl(): return line('')
print('Laboratory work 1.1 measurements of the R-load.') measurements = [] measurements_count = int(input('Enter number of measurements : ')) for cur_measurement_number in range(1, measurements_count+1): print(f'Enter value for measurement {cur_measurement_number} -> ', end='') measurement = float(input()) ...
print('Laboratory work 1.1 measurements of the R-load.') measurements = [] measurements_count = int(input('Enter number of measurements : ')) for cur_measurement_number in range(1, measurements_count + 1): print(f'Enter value for measurement {cur_measurement_number} -> ', end='') measurement = float(input()) ...
#tests: depend_extra depend_extra=('pelle',) def synthesis(): pass
depend_extra = ('pelle',) def synthesis(): pass
def _capnp_toolchain_gen_impl(ctx): ctx.template( "toolchain/BUILD.bazel", ctx.attr._build_tpl, substitutions = { "{capnp_tool}": str(ctx.attr.capnp_tool), }, ) capnp_toolchain_gen = repository_rule( implementation = _capnp_toolchain_gen_impl, attrs = { ...
def _capnp_toolchain_gen_impl(ctx): ctx.template('toolchain/BUILD.bazel', ctx.attr._build_tpl, substitutions={'{capnp_tool}': str(ctx.attr.capnp_tool)}) capnp_toolchain_gen = repository_rule(implementation=_capnp_toolchain_gen_impl, attrs={'capnp_tool': attr.label(allow_single_file=True, cfg='host', executable=True...
expected_output = { 'steering_entries': { 'sgt': { 2057: { 'entry_last_refresh': '10:32:00', 'entry_state': 'COMPLETE', 'peer_name': 'Unknown-2057', 'peer_sgt': '2057-01', 'policy_rbacl_src_list': { ...
expected_output = {'steering_entries': {'sgt': {2057: {'entry_last_refresh': '10:32:00', 'entry_state': 'COMPLETE', 'peer_name': 'Unknown-2057', 'peer_sgt': '2057-01', 'policy_rbacl_src_list': {'entry_status': 'UNKNOWN', 'installed_elements': '0x00000C80', 'installed_peer_policy': {'peer_policy': '0x7F3ADDAFEA08', 'pol...
__author__ = 'Stormpath, Inc.' __copyright__ = 'Copyright 2012-2014 Stormpath, Inc.' __version_info__ = ('1', '3', '1') __version__ = '.'.join(__version_info__) __short_version__ = '.'.join(__version_info__)
__author__ = 'Stormpath, Inc.' __copyright__ = 'Copyright 2012-2014 Stormpath, Inc.' __version_info__ = ('1', '3', '1') __version__ = '.'.join(__version_info__) __short_version__ = '.'.join(__version_info__)
J # welcoming the user name = input("What is your name? ") print("Hello, " + name, "It is time to play hangman!") print("Start guessing...") # here we set the secret word = "secret" # creates a variable with an empty value guesses = '' # determine the number of turns turns = 10 while turns > 0: failed = 0 ...
J name = input('What is your name? ') print('Hello, ' + name, 'It is time to play hangman!') print('Start guessing...') word = 'secret' guesses = '' turns = 10 while turns > 0: failed = 0 for char in word: if char in guesses: print(char) else: print('_') faile...
conductores = { 'azambrano': ('Andres Zambrano', 5.6, ('Hyundai', 'Elantra')), 'jojeda': ('Juan Ojeda', 1.1, ('Hyundai', 'Accent')), # ... } def agrega_conductor(conductores, nuevo_conductor): username, nombre, puntaje, (marca, modelo) = nuevo_conductor if username in conductores: ...
conductores = {'azambrano': ('Andres Zambrano', 5.6, ('Hyundai', 'Elantra')), 'jojeda': ('Juan Ojeda', 1.1, ('Hyundai', 'Accent'))} def agrega_conductor(conductores, nuevo_conductor): (username, nombre, puntaje, (marca, modelo)) = nuevo_conductor if username in conductores: return False conductores...
#calculator def add(n1,n2): return n1 +n2 def substract(n1,n2): return n1-n2 def multiply(n1,n2): return n1 * n2 def devide(n1,n2): return n1/n2 operator = { "+": add, "-": substract, "*": multiply, "/": devide, } num1 = float(input("Enter number: ")) op_simbol = input("enter +...
def add(n1, n2): return n1 + n2 def substract(n1, n2): return n1 - n2 def multiply(n1, n2): return n1 * n2 def devide(n1, n2): return n1 / n2 operator = {'+': add, '-': substract, '*': multiply, '/': devide} num1 = float(input('Enter number: ')) op_simbol = input('enter + - * / ') num2 = float(input(...
# https://www.codechef.com/problems/SUMPOS for T in range(int(input())): l=sorted(list(map(int,input().split()))) print("NO") if(l[2]!=l[1]+l[0]) else print("YES")
for t in range(int(input())): l = sorted(list(map(int, input().split()))) print('NO') if l[2] != l[1] + l[0] else print('YES')
class LoggerTemplate(): def __init__(self, *args, **kwargs): raise NotImplementedError def update_loss(self, phase, value, step): raise NotImplementedError def update_metric(self, phase, metric, value, step): raise NotImplementedError
class Loggertemplate: def __init__(self, *args, **kwargs): raise NotImplementedError def update_loss(self, phase, value, step): raise NotImplementedError def update_metric(self, phase, metric, value, step): raise NotImplementedError
var={"car":"volvo", "fruit":"apple"} print(var["fruit"]) for f in var: print("key: " + f + " value: " + var[f]) print() print() var1={"donut":["chocolate","glazed","sprinkled"]} print(var1["donut"][0]) print("My favorite donut flavors are:", end= " ") for f in var1["donut"]: print(f, end=" ") print() print() #Usin...
var = {'car': 'volvo', 'fruit': 'apple'} print(var['fruit']) for f in var: print('key: ' + f + ' value: ' + var[f]) print() print() var1 = {'donut': ['chocolate', 'glazed', 'sprinkled']} print(var1['donut'][0]) print('My favorite donut flavors are:', end=' ') for f in var1['donut']: print(f, end=' ') print() pr...
#Challenge 4: Take a binary tree and reverse it #I decided to create two classes. One to hold the node, and one to act as the Binary Tree. #Node class #Only contains the information for the node. Val is the value of the node, left is the left most value, and right is the right value class Node: def __init__(self, ...
class Node: def __init__(self, val): self.left = None self.right = None self.val = val class Binarytree: def __init__(self): self.root = None def get_root(self): return self.root def add(self, val): if self.root is None: self.root = node(v...
DAOLIPROXY_VENDOR = "OpenStack Foundation" DAOLIPROXY_PRODUCT = "DaoliProxy" DAOLIPROXY_PACKAGE = None # OS distro package version suffix loaded = False class VersionInfo(object): release = "1.el7.centos" version = "2015.1.21" def version_string(self): return self.version def release_string(...
daoliproxy_vendor = 'OpenStack Foundation' daoliproxy_product = 'DaoliProxy' daoliproxy_package = None loaded = False class Versioninfo(object): release = '1.el7.centos' version = '2015.1.21' def version_string(self): return self.version def release_string(self): return self.release v...
# Space: O(n) # Time: O(n) class Solution: def findUnsortedSubarray(self, nums): length = len(nums) if length <= 1: return 0 stack = [] left, right = length - 1, 0 for i in range(length): while stack and nums[stack[-1]] > nums[i]: left = min(lef...
class Solution: def find_unsorted_subarray(self, nums): length = len(nums) if length <= 1: return 0 stack = [] (left, right) = (length - 1, 0) for i in range(length): while stack and nums[stack[-1]] > nums[i]: left = min(left, stack.po...
# encoding: utf-8 # module Autodesk.AutoCAD.DatabaseServices # from D:\Python\ironpython-stubs\release\stubs\Autodesk\AutoCAD\DatabaseServices\__init__.py # by generator 1.145 # no doc # no imports # no functions # no classes # variables with complex values __path__ = [ 'D:\\Python\\ironpython-stubs\\release\\stu...
__path__ = ['D:\\Python\\ironpython-stubs\\release\\stubs\\Autodesk\\AutoCAD\\DatabaseServices']
# Basic - Print all integers from 0 to 150. y = 0 while y <= 150: print(y) y = y + 1 # Multiples of Five - Print all the multiples of 5 from 5 to 1,000 x = 5 while x < 1001: print(x) x = x + 5 # Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead. If divisible ...
y = 0 while y <= 150: print(y) y = y + 1 x = 5 while x < 1001: print(x) x = x + 5 j = 0 txt = 'Coding' while j < 101: if j % 10 == 0: print(txt + 'Dojo') elif j % 5 == 0: print(txt) else: print(j) j += 1 z = 0 sum = 0 while z < 500000: if z % 2 != 0: s...
##write a function that takes a nested list as an argument ##and returns a normal list ##show that the result is equal to flattened_list nested_list = ['a', [2, 3], [4, 'b', [0, -2, ['c', 'e', '0f']]]] flattened_list = ['a', 2, 3, 4, 'b', 0, -2, 'c', 'e', '0f'] def flat_list(nest_list): flat = list() ...
nested_list = ['a', [2, 3], [4, 'b', [0, -2, ['c', 'e', '0f']]]] flattened_list = ['a', 2, 3, 4, 'b', 0, -2, 'c', 'e', '0f'] def flat_list(nest_list): flat = list() for elem in nest_list: if type(elem) is list: flat += flat_list(elem) else: flat.append(elem) return f...
''' Program to count each character's frequency Example: Input: banana Output: a3b1n2 ''' def frequency(input1): l = list(input1) x= list(set(l)) x.sort() result="" for i in range(0,len(x)): count=0 for j in range(0,len(l)): if x[i]==l[j]: count +=1 ...
""" Program to count each character's frequency Example: Input: banana Output: a3b1n2 """ def frequency(input1): l = list(input1) x = list(set(l)) x.sort() result = '' for i in range(0, len(x)): count = 0 for j in range(0, len(l)): if x[i] == l[j]: count ...