content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
''' Have the function SimpleMode(arr) take the array of numbers stored in arr and return the number that appears most frequently (the mode). For example: if arr contains [10, 4, 5, 2, 4] the output should be 4. If there is more than one mode return the one that appeared in the array first (ie. [5, 10, 10, 6, 5] sh...
""" Have the function SimpleMode(arr) take the array of numbers stored in arr and return the number that appears most frequently (the mode). For example: if arr contains [10, 4, 5, 2, 4] the output should be 4. If there is more than one mode return the one that appeared in the array first (ie. [5, 10, 10, 6, 5] shoul...
class Solution: """ @param nums: A list of integers @param k: An integer @return: The median of the element inside the window at each moving """ def medianSlidingWindow(self, nums, k): # write your code here pass
class Solution: """ @param nums: A list of integers @param k: An integer @return: The median of the element inside the window at each moving """ def median_sliding_window(self, nums, k): pass
class Pipe(object): def __init__(self, *args): self.functions = args self.state = {'error': '', 'result': None} def __call__(self, value): if not value: raise "Not any value for running" self.state['result'] = self.data_pipe(value) return self.state def ...
class Pipe(object): def __init__(self, *args): self.functions = args self.state = {'error': '', 'result': None} def __call__(self, value): if not value: raise 'Not any value for running' self.state['result'] = self.data_pipe(value) return self.state def...
#code class Node : def __init__(self,data): self.data = data self.next = None class LinkedList : def __init__(self): self.head = None def Push(self,new_data): if(self.head== None): self.head = Node(new_data) else: new_node = Node(new_data) ...
class Node: def __init__(self, data): self.data = data self.next = None class Linkedlist: def __init__(self): self.head = None def push(self, new_data): if self.head == None: self.head = node(new_data) else: new_node = node(new_data) ...
NONE = 0 HALT = 1 << 0 FAULT = 1 << 1 BREAK = 1 << 2
none = 0 halt = 1 << 0 fault = 1 << 1 break = 1 << 2
""" check if 2 strings are anagrams """ def anagrams(string1, string2): if sorted(string1) == sorted(string2): return True else: return False
""" check if 2 strings are anagrams """ def anagrams(string1, string2): if sorted(string1) == sorted(string2): return True else: return False
# Pascal's Triangle # @author unobatbayar # Input website link and download to a directory # @author unobatbayar just for comments not whole code this time # @program 10 # date 27-10-2018 print("Welcome to Pascal's Triangle!" + "\n") row = int(input('Please input a row number to which you want to see the triangle ...
print("Welcome to Pascal's Triangle!" + '\n') row = int(input('Please input a row number to which you want to see the triangle to' + '\n')) a = [] for i in range(row): a.append([]) a[i].append(1) for j in range(1, i): a[i].append(a[i - 1][j - 1] + a[i - 1][j]) if row != 0: a[i].append(1)...
class StorageDriverError(Exception): pass class ObjectDoesNotExistError(StorageDriverError): def __init__(self, driver, bucket, object_name): super().__init__( f"Bucket {bucket} does not contain {object_name} (driver={driver})" ) class AssetsManagerError(Exception): pass cl...
class Storagedrivererror(Exception): pass class Objectdoesnotexisterror(StorageDriverError): def __init__(self, driver, bucket, object_name): super().__init__(f'Bucket {bucket} does not contain {object_name} (driver={driver})') class Assetsmanagererror(Exception): pass class Assetalreadyexistser...
class Solution: def maximizeSweetness(self, sweetness: List[int], K: int) -> int: low, high = 1, sum(sweetness) // (K + 1) while low < high: mid = (low + high + 1) // 2 count = curr = 0 for s in sweetness: curr += s if curr >= mid: ...
class Solution: def maximize_sweetness(self, sweetness: List[int], K: int) -> int: (low, high) = (1, sum(sweetness) // (K + 1)) while low < high: mid = (low + high + 1) // 2 count = curr = 0 for s in sweetness: curr += s if curr >=...
""" good explanation from discussion my solution is like this: using two pointers, one of them one step at a time. Another pointer each take two steps. Suppose the first meet at step k,the length of the Cycle is r. so..2k-k=nr,k=nr Now, the distance between the start node of list and the start node of c...
""" good explanation from discussion my solution is like this: using two pointers, one of them one step at a time. Another pointer each take two steps. Suppose the first meet at step k,the length of the Cycle is r. so..2k-k=nr,k=nr Now, the distance between the start node of list and the start node of c...
taggable_resources = [ # API Gateway "aws_api_gateway_stage", # ACM "aws_acm_certificate", "aws_acmpca_certificate_authority", # CloudFront "aws_cloudfront_distribution", # CloudTrail "aws_cloudtrail", # AppSync "aws_appsync_graphql_api", # Backup "aws_backup_plan", ...
taggable_resources = ['aws_api_gateway_stage', 'aws_acm_certificate', 'aws_acmpca_certificate_authority', 'aws_cloudfront_distribution', 'aws_cloudtrail', 'aws_appsync_graphql_api', 'aws_backup_plan', 'aws_backup_vault', 'aws_cloudformation_stack', 'aws_cloudformation_stack_set', 'aws_batch_compute_environment', 'aws_c...
CREATE_VENV__CMD = b'UkVNIE5lY2Vzc2FyeSBGaWxlczoNClJFTSAtIHByZV9zZXR1cF9zY3JpcHRzLnR4dA0KUkVNIC0gcmVxdWlyZWRfcGVyc29uYWxfcGFja2FnZXMudHh0DQpSRU0gLSByZXF1aXJlZF9taXNjLnR4dA0KUkVNIC0gcmVxdWlyZWRfUXQudHh0DQpSRU0gLSByZXF1aXJlZF9mcm9tX2dpdGh1Yi50eHQNClJFTSAtIHJlcXVpcmVkX3Rlc3QudHh0DQpSRU0gLSByZXF1aXJlZF9kZXYudHh0DQpSRU0gLSB...
create_venv__cmd = b'UkVNIE5lY2Vzc2FyeSBGaWxlczoNClJFTSAtIHByZV9zZXR1cF9zY3JpcHRzLnR4dA0KUkVNIC0gcmVxdWlyZWRfcGVyc29uYWxfcGFja2FnZXMudHh0DQpSRU0gLSByZXF1aXJlZF9taXNjLnR4dA0KUkVNIC0gcmVxdWlyZWRfUXQudHh0DQpSRU0gLSByZXF1aXJlZF9mcm9tX2dpdGh1Yi50eHQNClJFTSAtIHJlcXVpcmVkX3Rlc3QudHh0DQpSRU0gLSByZXF1aXJlZF9kZXYudHh0DQpSRU0gLSB...
""" SOURCE: TODO; link github code snippet """ class meta: length = 0 # def __init__(self): # print self.process("schmidt") def isSlavoGermanic(self, str): for each in ["W", "K", "CZ", "WITZ"]: if (each in str): return 1; return 0; def isVowel(self, wo...
""" SOURCE: TODO; link github code snippet """ class Meta: length = 0 def is_slavo_germanic(self, str): for each in ['W', 'K', 'CZ', 'WITZ']: if each in str: return 1 return 0 def is_vowel(self, word, start): return self.sub(word, start, 1, ['A', 'E', '...
n = int(input()) def sum_input(): _sum = 0 for i in range(n): _sum += int(input()) return _sum left_sum = sum_input() right_sum = sum_input() if left_sum == right_sum: print("Yes, sum =", left_sum) else: print("No, diff =", abs(left_sum - right_sum))
n = int(input()) def sum_input(): _sum = 0 for i in range(n): _sum += int(input()) return _sum left_sum = sum_input() right_sum = sum_input() if left_sum == right_sum: print('Yes, sum =', left_sum) else: print('No, diff =', abs(left_sum - right_sum))
a = int(input()) while(a): counti = 0 counte = 0 b = input() for i in b: if(i=='1'): counti+=1 elif(i=='2'): counte+=1 elif(i=='0'): counte+=1 counti+=1 if(counti>counte): print("INDIA") elif(counte>counti): ...
a = int(input()) while a: counti = 0 counte = 0 b = input() for i in b: if i == '1': counti += 1 elif i == '2': counte += 1 elif i == '0': counte += 1 counti += 1 if counti > counte: print('INDIA') elif counte > coun...
text = input('Enter the text:\n') if ('make a lot of money' in text): spam = True elif ('buy now' in text): spam = True elif ('watch this' in text): spam = True elif ('click this' in text): spam = True elif ('subscribe this' in text): spam = True else: spam = False if (spam): ...
text = input('Enter the text:\n') if 'make a lot of money' in text: spam = True elif 'buy now' in text: spam = True elif 'watch this' in text: spam = True elif 'click this' in text: spam = True elif 'subscribe this' in text: spam = True else: spam = False if spam: print('This text is spam.')...
a=input() b=int(len(a)) for i in range(b): print(a[i])
a = input() b = int(len(a)) for i in range(b): print(a[i])
""" @author: karthikrao Test the Polish Expression for its Balloting and Normalized properties. """ def test_ballot(exp, index): """ Parameters ---------- exp : list Polish Expression to be tested for its balloting property. index : int End point of the Polish Expression to be t...
""" @author: karthikrao Test the Polish Expression for its Balloting and Normalized properties. """ def test_ballot(exp, index): """ Parameters ---------- exp : list Polish Expression to be tested for its balloting property. index : int End point of the Polish Expression to be t...
def second_largest(mylist): largest = None second_largest = None for num in mylist: if largest is None: largest = num elif num > largest: second_largest = largest largest = num elif second_largest is None: second_largest = num elif num > second_largest: second_largest = num return second_la...
def second_largest(mylist): largest = None second_largest = None for num in mylist: if largest is None: largest = num elif num > largest: second_largest = largest largest = num elif second_largest is None: second_largest = num e...
# =========== # BoE # =========== class HP_IMDB_BOE: batch_size = 64 learning_rate = 1e-3 learning_rate_dpsgd = 1e-3 patience = 5 tgt_class = 1 sequence_length = 512 class HP_DBPedia_BOE: batch_size = 256 learning_rate = 1e-3 learning_rate_dpsgd = 1e-3 patience = 2 tgt_cla...
class Hp_Imdb_Boe: batch_size = 64 learning_rate = 0.001 learning_rate_dpsgd = 0.001 patience = 5 tgt_class = 1 sequence_length = 512 class Hp_Dbpedia_Boe: batch_size = 256 learning_rate = 0.001 learning_rate_dpsgd = 0.001 patience = 2 tgt_class = 1 sequence_length = 256...
def get_azure_config(provider_config): config_dict = {} azure_storage_type = provider_config.get("azure_cloud_storage", {}).get("azure.storage.type") if azure_storage_type: config_dict["AZURE_STORAGE_TYPE"] = azure_storage_type azure_storage_account = provider_config.get("azure_cloud_storage",...
def get_azure_config(provider_config): config_dict = {} azure_storage_type = provider_config.get('azure_cloud_storage', {}).get('azure.storage.type') if azure_storage_type: config_dict['AZURE_STORAGE_TYPE'] = azure_storage_type azure_storage_account = provider_config.get('azure_cloud_storage', {...
""" Blog app for the CDH website. Similar to the built-in grappelli blog, but allows multiple authors (other than the current user) to be associated with a post. """ default_app_config = "cdhweb.blog.apps.BlogConfig"
""" Blog app for the CDH website. Similar to the built-in grappelli blog, but allows multiple authors (other than the current user) to be associated with a post. """ default_app_config = 'cdhweb.blog.apps.BlogConfig'
backslashes_test_text_001 = ''' string = 'string' ''' backslashes_test_text_002 = ''' string = 'string_start \\ string end' ''' backslashes_test_text_003 = ''' if arg_one is not None \\ and arg_two is None: pass ''' backslashes_test_text_004 = ''' string = \'\'\' text \\\\ text \'\'\' '''
backslashes_test_text_001 = "\nstring = 'string'\n" backslashes_test_text_002 = "\nstring = 'string_start \\\n string end'\n" backslashes_test_text_003 = '\nif arg_one is not None \\\n and arg_two is None:\n pass\n' backslashes_test_text_004 = "\nstring = '''\n text \\\\\n text\n'''\n"
# 1 def front_two_back_two(input_string): return '' if len(input_string) < 2 else input_string[:2] + input_string[-2:] # 2 def kelvin_to_celsius(k): return k - 273.15 # 2 def kelvin_to_fahrenheit(k): return kelvin_to_celsius(k) * 9.0 / 5.0 + 32.0 # 4 def min_max_sum(input_list): return [min(input_...
def front_two_back_two(input_string): return '' if len(input_string) < 2 else input_string[:2] + input_string[-2:] def kelvin_to_celsius(k): return k - 273.15 def kelvin_to_fahrenheit(k): return kelvin_to_celsius(k) * 9.0 / 5.0 + 32.0 def min_max_sum(input_list): return [min(input_list), max(input_li...
class Data: def __init__(self, dia, mes, ano): self.dia = dia self.mes = mes self.ano = ano print(self) @classmethod def de_string(cls, data_string): dia, mes, ano = map(int, data_string.split('-')) data = cls(dia, mes, ano) return data @staticmethod def is_date_valid(data_string): dia, mes, an...
class Data: def __init__(self, dia, mes, ano): self.dia = dia self.mes = mes self.ano = ano print(self) @classmethod def de_string(cls, data_string): (dia, mes, ano) = map(int, data_string.split('-')) data = cls(dia, mes, ano) return data @stati...
# author: Fei Gao # # Evaluate Reverse Polish Notation # # Evaluate the value of an arithmetic expression in Reverse Polish Notation. # Valid operators are +, -, *, /. Each operand may be an integer or another expression. # Some examples: # ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 # ["4", "13", "5", "/", "+"] ->...
class Solution: def eval_rpn(self, tokens): if not tokens: return None op = {'+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '/': lambda x, y: int(float(x) / y)} queue = list() for val in tokens: if isinstance(val, list): ...
ROUTE_MIDDLEWARE = { 'test': 'app.http.middleware.MiddlewareTest.MiddlewareTest', 'middleware.test': [ 'app.http.middleware.MiddlewareTest.MiddlewareTest', 'app.http.middleware.AddAttributeMiddleware.AddAttributeMiddleware' ] }
route_middleware = {'test': 'app.http.middleware.MiddlewareTest.MiddlewareTest', 'middleware.test': ['app.http.middleware.MiddlewareTest.MiddlewareTest', 'app.http.middleware.AddAttributeMiddleware.AddAttributeMiddleware']}
""" * how to use: to be used you must declare how many parity bits (sizePari) you want to include in the message. it is desired (for test purposes) to select a bit to be set as an error. This serves to check whether the code is working correctly. Lastly,...
""" * how to use: to be used you must declare how many parity bits (sizePari) you want to include in the message. it is desired (for test purposes) to select a bit to be set as an error. This serves to check whether the code is working correctly. Lastly, the v...
# file creation myfile1 = open("truncate.txt", "w") # writing data to the file myfile1.write("Python is a user-friendly language for beginners") # file truncating to 30 bytes myfile1.truncate(30) # file is getting closed myfile1.close() # file reading and displaying the text myfile2 = open("truncate.tx...
myfile1 = open('truncate.txt', 'w') myfile1.write('Python is a user-friendly language for beginners') myfile1.truncate(30) myfile1.close() myfile2 = open('truncate.txt', 'r') print(myfile2.read()) myfile2.close()
"""Load dependencies needed to compile the protobuf library as a 3rd-party consumer.""" load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def protobuf_deps(): """Loads common dependencies needed to compile the protobuf library.""" if not native.existing_rule("zlib"): http_archive( ...
"""Load dependencies needed to compile the protobuf library as a 3rd-party consumer.""" load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') def protobuf_deps(): """Loads common dependencies needed to compile the protobuf library.""" if not native.existing_rule('zlib'): http_archive(nam...
# Copyright 2013 - Mirantis, Inc. # Copyright 2015 - StackStorm, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
class Mistralerror(Exception): """Mistral specific error. Reserved for situations that can't automatically handled. When it occurs it signals that there is a major environmental problem like invalid startup configuration or implementation problem (e.g. some code doesn't take care of certain corner ...
class Solution: def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ if numRows == 0: return [] ret = [[1]] for i in range(1, numRows): tmp = [] for j in range(i + 1): if j == 0: ...
class Solution: def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ if numRows == 0: return [] ret = [[1]] for i in range(1, numRows): tmp = [] for j in range(i + 1): if j == 0: ...
class NamingUtils(object): ''' Utilities related to object naming ''' @classmethod def createUniqueMnemonic(cls, mnem, unitMap): """ If mnemonic exists in dict appends a _x where x is an int """ result = mnem if mnem in unitMap: suffix = 1 while (mn...
class Namingutils(object): """ Utilities related to object naming """ @classmethod def create_unique_mnemonic(cls, mnem, unitMap): """ If mnemonic exists in dict appends a _x where x is an int """ result = mnem if mnem in unitMap: suffix = 1 while mne...
a = {'C', 'C++', 'Java'} b = {'C++', 'Java', 'Python'} c = {'java', 'Python', 'C', 'pascal'} # who known all three subject u = a.union(b).union(c) print("Union", u) # find subject known to A and not to B i = a.intersection(b) print("Intersection", i) diff1 = a.difference(b) print(a, b, "C-F", diff1) #find a subjec...
a = {'C', 'C++', 'Java'} b = {'C++', 'Java', 'Python'} c = {'java', 'Python', 'C', 'pascal'} u = a.union(b).union(c) print('Union', u) i = a.intersection(b) print('Intersection', i) diff1 = a.difference(b) print(a, b, 'C-F', diff1) studentswhoknowonlypascal = [] if 'pascal ' in a: studentswhoknowonlypascal.append('...
nk = input().split() n = int(nk[0]) k = int(nk[1]) r = int(input()) c = int(input()) o = [] z=0 for _ in range(k): o.append(list(map(int, input().rstrip().split()))) l=[] p=[] a=[] for i in range(n): l=l+[0] for i in range(n): l[i]=[0]*n l[r-1][c-1]=1 for i in range(len(o)): l[o[i][0]-...
nk = input().split() n = int(nk[0]) k = int(nk[1]) r = int(input()) c = int(input()) o = [] z = 0 for _ in range(k): o.append(list(map(int, input().rstrip().split()))) l = [] p = [] a = [] for i in range(n): l = l + [0] for i in range(n): l[i] = [0] * n l[r - 1][c - 1] = 1 for i in range(len(o)): l[o[i]...
name = "generators" """ The generators module """
name = 'generators' '\nThe generators module\n'
def eig(a): # TODO(beam2d): Implement it raise NotImplementedError def eigh(a, UPLO='L'): # TODO(beam2d): Implement it raise NotImplementedError def eigvals(a): # TODO(beam2d): Implement it raise NotImplementedError def eigvalsh(a, UPLO='L'): # TODO(beam2d): Implement it raise NotI...
def eig(a): raise NotImplementedError def eigh(a, UPLO='L'): raise NotImplementedError def eigvals(a): raise NotImplementedError def eigvalsh(a, UPLO='L'): raise NotImplementedError
# ex1116 Dividindo x por y n = int(input()) for c in range(1, n + 1): x, y = map(float, input().split()) if x > y and y != 0: divisao = x / y print('{:.1f}'.format(divisao)) elif x > y and y == 0: print('divisao impossivel') if x < y and y != 0: divisao = x / y p...
n = int(input()) for c in range(1, n + 1): (x, y) = map(float, input().split()) if x > y and y != 0: divisao = x / y print('{:.1f}'.format(divisao)) elif x > y and y == 0: print('divisao impossivel') if x < y and y != 0: divisao = x / y print('{:.1f}'.format(divis...
# https://leetcode.com/problems/valid-perfect-square class Solution: def isPerfectSquare(self, num): if num == 1: return True l, r = 1, num while l <= r: mid = (l + r) // 2 if mid ** 2 == num: return True elif mid ** 2 < num: ...
class Solution: def is_perfect_square(self, num): if num == 1: return True (l, r) = (1, num) while l <= r: mid = (l + r) // 2 if mid ** 2 == num: return True elif mid ** 2 < num: l = mid + 1 else: ...
''' Color Pallette ''' # Generic Stuff BLACK = ( 0, 0, 0) WHITE = (255, 255, 255) # Pane Colors PANE1 = (236, 236, 236) PANE2 = (255, 255, 255) PANE3 = (236, 236, 236) # Player Color PLAYER_COLOR = BLACK # Reds RED_POMEGRANATE = (242, 38, 19) RED_THUNDERBIRD = (217, 30, 24) RED_FLAMINGO = (239, 72, 54...
""" Color Pallette """ black = (0, 0, 0) white = (255, 255, 255) pane1 = (236, 236, 236) pane2 = (255, 255, 255) pane3 = (236, 236, 236) player_color = BLACK red_pomegranate = (242, 38, 19) red_thunderbird = (217, 30, 24) red_flamingo = (239, 72, 54) red_razzmatazz = (219, 10, 91) red_radicalred = (246, 36, 89) red_ecs...
lista = list() vezesInput = 0 while vezesInput < 6: valor = float(input()) if valor > 0: lista.append(valor) vezesInput += 1 print(f'{len(lista)} valores positivos')
lista = list() vezes_input = 0 while vezesInput < 6: valor = float(input()) if valor > 0: lista.append(valor) vezes_input += 1 print(f'{len(lista)} valores positivos')
# -*- coding: utf-8 -*- # This file is generated from NI Switch Executive API metadata version 19.1.0d1 enums = { 'ExpandAction': { 'values': [ { 'documentation': { 'description': 'Expand to routes' }, 'name': 'NISE_VAL_EXPAND_T...
enums = {'ExpandAction': {'values': [{'documentation': {'description': 'Expand to routes'}, 'name': 'NISE_VAL_EXPAND_TO_ROUTES', 'value': 0}, {'documentation': {'description': 'Expand to paths'}, 'name': 'NISE_VAL_EXPAND_TO_PATHS', 'value': 1}]}, 'MulticonnectMode': {'values': [{'documentation': {'description': 'Defaul...
"""Utility functions.""" def generate_query_string(query_params): """Generate a query string given kwargs dictionary.""" query_frags = [ str(key) + "=" + str(value) for key, value in query_params.items() ] query_str = "&".join(query_frags) return query_str
"""Utility functions.""" def generate_query_string(query_params): """Generate a query string given kwargs dictionary.""" query_frags = [str(key) + '=' + str(value) for (key, value) in query_params.items()] query_str = '&'.join(query_frags) return query_str
# Click trackpad of first controller by "C" key alvr.buttons[0][alvr.Id("trackpad_click")] = keyboard.getKeyDown(Key.C) alvr.buttons[0][alvr.Id("trackpad_touch")] = keyboard.getKeyDown(Key.C) # Move trackpad position by arrow keys if keyboard.getKeyDown(Key.LeftArrow): alvr.trackpad[0][0] = -1.0 alvr.trackpad[0][1...
alvr.buttons[0][alvr.Id('trackpad_click')] = keyboard.getKeyDown(Key.C) alvr.buttons[0][alvr.Id('trackpad_touch')] = keyboard.getKeyDown(Key.C) if keyboard.getKeyDown(Key.LeftArrow): alvr.trackpad[0][0] = -1.0 alvr.trackpad[0][1] = 0.0 elif keyboard.getKeyDown(Key.UpArrow): alvr.trackpad[0][0] = 0.0 alv...
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def flatten(root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ if not root: ...
class Treenode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def flatten(root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ if not root: return stack = [root] pre = N...
""" In Python, there are three different numeric types. These are "int", "float" and "complex". Documentation - https://www.w3schools.com/python/python_numbers.asp Below we will look at all three different types. """ """ "int", or integer, is a whole number, positive or negative, without decimals and has an unlimite...
""" In Python, there are three different numeric types. These are "int", "float" and "complex". Documentation - https://www.w3schools.com/python/python_numbers.asp Below we will look at all three different types. """ '\n"int", or integer, is a whole number, positive or negative, without decimals\nand has an unlimited...
class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: ''' T: O(n2 * n1 log n1); can be reduced to O(n2 * n1) by using char counter S: O(n1); can be reduced to O(26) = O(1) by using character counting array ''' n1, n2 = len(s1), len(s2) s1 = sorted(s1) ...
class Solution: def check_inclusion(self, s1: str, s2: str) -> bool: """ T: O(n2 * n1 log n1); can be reduced to O(n2 * n1) by using char counter S: O(n1); can be reduced to O(26) = O(1) by using character counting array """ (n1, n2) = (len(s1), len(s2)) s1 = sorted(...
#!/usr/bin/env python3 # MIT License # Copyright (c) 2020 pixelbubble # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, ...
def generate_accounts(): first_name = input('First name: ').lower() last_name = input('Last name: ').lower() year_of_birth = input('Year of birth: ') pseudo = input('Username (optional): ').lower() zip_code = input('Zip code (optional): ') results_list = [] results_list.append(firstName + la...
# MYSQL_CONFIG = { # 'host': '10.70.14.244', # 'port': 33044, # 'user': 'view', # 'password': '!@View123', # 'database': 'yjyg' # } MYSQL_CONFIG = { 'host': '127.0.0.1', 'port': 33004, 'user': 'root', 'password': 'q1w2e3r4', 'database': 'yjyg' }
mysql_config = {'host': '127.0.0.1', 'port': 33004, 'user': 'root', 'password': 'q1w2e3r4', 'database': 'yjyg'}
"""iCE entities.""" # # Base entity class # class Entity(object): """Generic entity. :type id: str :type created: datetime.datetime :type update: datetime.datetime :type etag: str """ def __init__(self, **kwargs): # MongoDB stuff self.id = kwargs.get('_id', None) ...
"""iCE entities.""" class Entity(object): """Generic entity. :type id: str :type created: datetime.datetime :type update: datetime.datetime :type etag: str """ def __init__(self, **kwargs): self.id = kwargs.get('_id', None) self.created = kwargs.get('_created', None) ...
def cheapest_flour(input1,output1): a=[] b=[] with open(input1,"r") as input_file: number1=0 for i in input_file.readlines(): a.append(i.split()) b.append(int(a[number1][0])/int(a[number1][1])) number1+=1 b=sorted(b,reverse=True) with...
def cheapest_flour(input1, output1): a = [] b = [] with open(input1, 'r') as input_file: number1 = 0 for i in input_file.readlines(): a.append(i.split()) b.append(int(a[number1][0]) / int(a[number1][1])) number1 += 1 b = sorted(b, reverse=True) ...
""" Cross-validation sampling ------------------------- This module contains the functions used to crete a a cross validation division for the data. TODO ---- Create a class structure to create samplings Create a class which is able to create a cv object """ class Categorical_Sampler: def __init__(self, point...
""" Cross-validation sampling ------------------------- This module contains the functions used to crete a a cross validation division for the data. TODO ---- Create a class structure to create samplings Create a class which is able to create a cv object """ class Categorical_Sampler: def __init__(self, points_...
__author__ = "Dimi Balaouras" __copyright__ = "Copyright 2016, Stek.io" __license__ = "Apache License 2.0, see LICENSE for more details." # Do not modify the following __default_feature_name__ = "DO_NOT_MODIFY" class AppContext(object): """ App Context based on Service Locator Pattern """ def __init...
__author__ = 'Dimi Balaouras' __copyright__ = 'Copyright 2016, Stek.io' __license__ = 'Apache License 2.0, see LICENSE for more details.' __default_feature_name__ = 'DO_NOT_MODIFY' class Appcontext(object): """ App Context based on Service Locator Pattern """ def __init__(self, allow_replace=False): ...
# config.py SEED = 42 EXTENSION = ".png" IMAGE_H = 28 IMAGE_W = 28 CHANNELS = 3 BATCH_SIZE = 30 EPOCHS = 400 LEARNING_RATE = 0.001 CIRCLES = "../input/shapes/circles/" SQUARES = "../input/shapes/squares/" TRIANGLES = "../input/shapes/triangles/" INPUT_FOLD = "../input/" OUTPUT_FOLD = "../output/" TRAIN_DATA = "../i...
seed = 42 extension = '.png' image_h = 28 image_w = 28 channels = 3 batch_size = 30 epochs = 400 learning_rate = 0.001 circles = '../input/shapes/circles/' squares = '../input/shapes/squares/' triangles = '../input/shapes/triangles/' input_fold = '../input/' output_fold = '../output/' train_data = '../input/train_datas...
# In one of the Chinese provinces, it was decided to build a series of machines to protect the # population against the coronavirus. The province can be visualized as an array of values 1 and 0, # which arr[i] = 1 means that in city [i] it is possible to build a machine and value 0 that it can't. # There is also a numb...
def machines_saving_people(T, k): count = 0 distance = -1 protected = distance + k while distance + k < len(T): if protected > len(T) - 1: protected = len(T) - 1 while T[protected] == 0 and protected >= distance + 1: protected -= 1 if protected == distance...
m = 5 n = 0.000001 # rule-id: use-float-numbers assert(1.0000 == 1.000000) # rule-id: use-float-numbers assert(1.0000 == m) # rule-id: use-float-numbers assert(m == 1.0000) # rule-id: use-float-numbers assert(m == n)
m = 5 n = 1e-06 assert 1.0 == 1.0 assert 1.0 == m assert m == 1.0 assert m == n
while True: password = input("Password") print(password) if password == "stop": break print("the while loop has stopped")
while True: password = input('Password') print(password) if password == 'stop': break print('the while loop has stopped')
# wczytanie slow i szyfrow with open('../dane/sz.txt') as f: cyphers = [] for word in f.readlines(): cyphers.append(word[:-1]) with open('../dane/klucze2.txt') as f: keys = [] for word in f.readlines(): keys.append(word[:-1]) # zbior odszyfrowanych slow words = [] # przejscie po slowac...
with open('../dane/sz.txt') as f: cyphers = [] for word in f.readlines(): cyphers.append(word[:-1]) with open('../dane/klucze2.txt') as f: keys = [] for word in f.readlines(): keys.append(word[:-1]) words = [] for (cypher, key) in zip(cyphers, keys): word = '' for (i, char) in en...
def graph_pred_vs_actual(actual,pred,data_type): plt.scatter(actual,pred,alpha=.3) plt.plot(np.linspace(int(min(pred)),int(max(pred)),int(max(pred))), np.linspace(int(min(pred)),int(max(pred)),int(max(pred)))) plt.title('Actual vs Pred ({} Data)'.format(data_type)) plt.xlabel('Actual') ...
def graph_pred_vs_actual(actual, pred, data_type): plt.scatter(actual, pred, alpha=0.3) plt.plot(np.linspace(int(min(pred)), int(max(pred)), int(max(pred))), np.linspace(int(min(pred)), int(max(pred)), int(max(pred)))) plt.title('Actual vs Pred ({} Data)'.format(data_type)) plt.xlabel('Actual') plt....
# https://www.hackerrank.com/challenges/insert-a-node-at-the-tail-of-a-linked-list # Python """ Insert Node at the end of a linked list head pointer input could be None as well for empty list Node is defined as class Node(object): def __init__(self, data=None, next_node=None): self.data = data s...
""" Insert Node at the end of a linked list head pointer input could be None as well for empty list Node is defined as class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node return back the head of the linked list in the below method """ def i...
# # PySNMP MIB module DC-OPT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DC-OPT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:21:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, value_range_constraint, constraints_union, constraints_intersection) ...
# # PySNMP MIB module DGS-6600-STP-EXT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DGS-6600-STP-EXT-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:45:14 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, value_size_constraint, single_value_constraint, constraints_intersection, constraints_union) ...
def arithmetic_arranger(problems,calc = False): if 5 < len(problems): return "Error: Too many problems." sOperand1 = sOperand2 = sDashes = sResults = "" separator = " " for i in range(len(problems)): words = problems[i].split() if(not (words[1] == "+" or words[1] =="-")): return "E...
def arithmetic_arranger(problems, calc=False): if 5 < len(problems): return 'Error: Too many problems.' s_operand1 = s_operand2 = s_dashes = s_results = '' separator = ' ' for i in range(len(problems)): words = problems[i].split() if not (words[1] == '+' or words[1] == '-'): ...
# # PySNMP MIB module MITEL-ERN (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MITEL-ERN # Produced by pysmi-0.3.4 at Wed May 1 14:13:10 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, value_range_constraint, constraints_intersection, single_value_constraint, constraints_union) ...
def oneaway(x,y): # INSERT x = list(x) y = list(y) if (len(x)+1) == len(y): for k in x: if k in y: continue else: return "1 FUCK" # REMOVAL if (len(x)-1) == len(y): for k in y: if k in x: continu...
def oneaway(x, y): x = list(x) y = list(y) if len(x) + 1 == len(y): for k in x: if k in y: continue else: return '1 FUCK' if len(x) - 1 == len(y): for k in y: if k in x: continue else: ...
""" State machine data structure with one start state and one stop state. Source: http://www.python-course.eu/finite_state_machine.php """ class InitializationError(ValueError): pass class InputError(ValueError): pass ############################################################################### class Stat...
""" State machine data structure with one start state and one stop state. Source: http://www.python-course.eu/finite_state_machine.php """ class Initializationerror(ValueError): pass class Inputerror(ValueError): pass class Statemachine: def __init__(self): self.handlers = {} se...
"""Find the smallest integer in the array, Kata in Codewars.""" def smallest(alist): """Return the smallest integer in the list. input: a list of integers output: a single integer ex: [34, 15, 88, 2] should return 34 ex: [34, -345, -1, 100] should return -345 """ res = [alist[0]] for ...
"""Find the smallest integer in the array, Kata in Codewars.""" def smallest(alist): """Return the smallest integer in the list. input: a list of integers output: a single integer ex: [34, 15, 88, 2] should return 34 ex: [34, -345, -1, 100] should return -345 """ res = [alist[0]] for n...
# Python - 3.6.0 test.describe('Example Tests') tests = ( ('John', 'Hello, John!'), ('aLIce', 'Hello, Alice!'), ('', 'Hello, World!') ) for inp, exp in tests: test.assert_equals(hello(inp), exp) test.assert_equals(hello(), 'Hello, World!')
test.describe('Example Tests') tests = (('John', 'Hello, John!'), ('aLIce', 'Hello, Alice!'), ('', 'Hello, World!')) for (inp, exp) in tests: test.assert_equals(hello(inp), exp) test.assert_equals(hello(), 'Hello, World!')
''' Author: Ajay Mahar Lang: python3 Github: https://www.github.com/ajaymahar YT: https://www.youtube.com/ajaymaharyt ''' class Node: def __init__(self, data): """TODO: Docstring for __init__. :returns: TODO """ self.data = data self.next = None class St...
""" Author: Ajay Mahar Lang: python3 Github: https://www.github.com/ajaymahar YT: https://www.youtube.com/ajaymaharyt """ class Node: def __init__(self, data): """TODO: Docstring for __init__. :returns: TODO """ self.data = data self.next = None class Sta...
'''PROGRAM TO, FOR A GIVEN LIST OF TUPLES, WHERE EACH TUPLE TAKES PATTERN (NAME,MARKS) OF A STUDENT, DISPLAY ONLY NAMES.''' #Given list scores = [("akash", 85), ("arind", 80), ("asha",95), ('bhavana',90), ('bhavik',87)] #Seperaing names and marks sep = list(zip(*scores)) names = sep[0] #Displaying names print('\nN...
"""PROGRAM TO, FOR A GIVEN LIST OF TUPLES, WHERE EACH TUPLE TAKES PATTERN (NAME,MARKS) OF A STUDENT, DISPLAY ONLY NAMES.""" scores = [('akash', 85), ('arind', 80), ('asha', 95), ('bhavana', 90), ('bhavik', 87)] sep = list(zip(*scores)) names = sep[0] print('\nNames of students:') for x in names: print(x.title()) pr...
"""Sorts GO IDs or user-provided sections containing GO IDs.""" __copyright__ = "Copyright (C) 2016-2019, DV Klopfenstein, H Tang, All rights reserved." __author__ = "DV Klopfenstein" class SorterNts(object): """Handles GO IDs in user-created sections. * Get a 2-D list of sections: sections ...
"""Sorts GO IDs or user-provided sections containing GO IDs.""" __copyright__ = 'Copyright (C) 2016-2019, DV Klopfenstein, H Tang, All rights reserved.' __author__ = 'DV Klopfenstein' class Sorternts(object): """Handles GO IDs in user-created sections. * Get a 2-D list of sections: sections = ...
# https://binarysearch.com/problems/Largest-Anagram-Group class Solution: def solve(self, words): anagrams = {} for i in range(len(words)): words[i] = "".join(sorted(list(words[i]))) if words[i] in anagrams: anagrams[words[i]]+=1 else: ...
class Solution: def solve(self, words): anagrams = {} for i in range(len(words)): words[i] = ''.join(sorted(list(words[i]))) if words[i] in anagrams: anagrams[words[i]] += 1 else: anagrams[words[i]] = 1 return max(anagrams....
class Solution: def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: paraList = re.split('\W', paragraph.lower()) paraListAlpha = [] for item in paraList: item = ''.join([i for i in item if i.isalpha()]) paraListAlpha.append(item) countParaList ...
class Solution: def most_common_word(self, paragraph: str, banned: List[str]) -> str: para_list = re.split('\\W', paragraph.lower()) para_list_alpha = [] for item in paraList: item = ''.join([i for i in item if i.isalpha()]) paraListAlpha.append(item) count_p...
with open("a.txt",'r') as ifile: with open("b.txt","w") as ofile: char = ifile.read(1) while char: if char==".": ofile.write(char) ofile.write("\n") char = ifile.read(1) else: ofile.write(char) ch...
with open('a.txt', 'r') as ifile: with open('b.txt', 'w') as ofile: char = ifile.read(1) while char: if char == '.': ofile.write(char) ofile.write('\n') char = ifile.read(1) else: ofile.write(char) ...
L, R = map(int, input().split()) ll = list(map(int, input().split())) rl = list(map(int, input().split())) lsize = [0]*41 rsize = [0]*41 for l in ll: lsize[l] += 1 for r in rl: rsize[r] += 1 ans = 0 for i in range(10, 41): ans += min(lsize[i], rsize[i]) print(ans)
(l, r) = map(int, input().split()) ll = list(map(int, input().split())) rl = list(map(int, input().split())) lsize = [0] * 41 rsize = [0] * 41 for l in ll: lsize[l] += 1 for r in rl: rsize[r] += 1 ans = 0 for i in range(10, 41): ans += min(lsize[i], rsize[i]) print(ans)
SIZE = 32 class Tile(): def __init__(self, collision=False, image=None, action_index=None): self.collision = collision self.image = image self.action_index = action_index
size = 32 class Tile: def __init__(self, collision=False, image=None, action_index=None): self.collision = collision self.image = image self.action_index = action_index
A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] B = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] C = [21, 22, 23, 24, 25, 26, 27, 28, 29, 30] intercalada = [] contador = 0 for i in range(10): intercalada.append(A[contador]) intercalada.append(B[contador]) intercalada.append(C[contador]) contador += 1 print(in...
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] b = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] c = [21, 22, 23, 24, 25, 26, 27, 28, 29, 30] intercalada = [] contador = 0 for i in range(10): intercalada.append(A[contador]) intercalada.append(B[contador]) intercalada.append(C[contador]) contador += 1 print(intercalada)
# Python program to demonstrate working of # Set in Python # Creating two sets set1 = set() set2 = set() # Adding elements to set1 for i in range(1, 6): set1.add(i) # Adding elements to set2 for i in range(3, 8): set2.add(i) set1.add(1) print("Set1 = ", set1) print("Set2 = ", set2) print("\n") #...
set1 = set() set2 = set() for i in range(1, 6): set1.add(i) for i in range(3, 8): set2.add(i) set1.add(1) print('Set1 = ', set1) print('Set2 = ', set2) print('\n') my_set = {1, 3, 4, 5, 6} print(my_set) my_set.discard(4) print(my_set) my_set.remove(6) print(my_set) my_set.discard(2) print(my_set) my_set = set('...
''' Copyright 2011 Acknack Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dis...
""" Copyright 2011 Acknack Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dis...
# This is your Application's Configuration File. # Make sure not to upload this file! # Flask App Secret. Used for "session". flaskSecret = "<generateKey>" # Register your V1 app at https://portal.azure.com. # Sign-On URL as <domain>/customer/login/authorized i.e. http://localhost:5000/customer/login/authorized # Mak...
flask_secret = '<generateKey>' client_id = '<GUID>' client_secret = '<SECRET>' aad_endpoint = 'https://login.microsoftonline.com/' resource_arm = 'https://management.azure.com/' resource_graph = 'https://graph.windows.net/' api_version_graph = '1.6'
""" This package contains definitions for the geometric primitives in use in ``phantomas``. """ __all__ = ['fiber', 'models', 'utils', 'rois']
""" This package contains definitions for the geometric primitives in use in ``phantomas``. """ __all__ = ['fiber', 'models', 'utils', 'rois']
def min4(*args): min_ = args[0] for item in args: if item < min_: min_ = item return min_ a, b, c, d = int(input()), int(input()), int(input()), int(input()) print(min4(a, b, c, d))
def min4(*args): min_ = args[0] for item in args: if item < min_: min_ = item return min_ (a, b, c, d) = (int(input()), int(input()), int(input()), int(input())) print(min4(a, b, c, d))
class Contender: def __init__(self, names, values): self.names = names self.values = values def __repr__(self): strings = tuple(str(v.id()) for v in self.values) return str(strings) + " contender" def __lt__(self, other): return self.values < other.values def ...
class Contender: def __init__(self, names, values): self.names = names self.values = values def __repr__(self): strings = tuple((str(v.id()) for v in self.values)) return str(strings) + ' contender' def __lt__(self, other): return self.values < other.values de...
def non_repeat(line): ls = [line[i:j] for i in range(len(line)) for j in range(i+1, len(line)+1) if len(set(line[i:j])) == j - i] return max(ls, key=len, default='')
def non_repeat(line): ls = [line[i:j] for i in range(len(line)) for j in range(i + 1, len(line) + 1) if len(set(line[i:j])) == j - i] return max(ls, key=len, default='')
first_number = int(input("Enter the first number(divisor): ")) second_number = int(input("Enter the second number(boundary): ")) for number in range(second_number, 0, -1): if number % first_number == 0: print(number) break
first_number = int(input('Enter the first number(divisor): ')) second_number = int(input('Enter the second number(boundary): ')) for number in range(second_number, 0, -1): if number % first_number == 0: print(number) break
n = int(input()) last = 1 lastlast = 0 print('0 1 ', end="") for i in range(n-2): now = last+lastlast if i == n-3: print('{}'.format(now)) else: print('{} '.format(now), end="") lastlast = last last = now
n = int(input()) last = 1 lastlast = 0 print('0 1 ', end='') for i in range(n - 2): now = last + lastlast if i == n - 3: print('{}'.format(now)) else: print('{} '.format(now), end='') lastlast = last last = now
# -*- coding: utf-8 -*- def main(): n = int(input()) dishes = list() ans = 0 # See: # https://poporix.hatenablog.com/entry/2019/01/28/222905 # https://misteer.hatenablog.com/entry/NIKKEI2019qual?_ga=2.121425408.962332021.1548821392-1201012407.1527836447 for i in range(n): ...
def main(): n = int(input()) dishes = list() ans = 0 for i in range(n): (ai, bi) = map(int, input().split()) dishes.append((ai, bi)) for (index, dish) in enumerate(sorted(dishes, key=lambda x: x[0] + x[1], reverse=True)): if index % 2 == 0: ans += dish[0] ...
class Cell: def __init__(self, x, y, entity = None, agent = None, dirty = False): self.x = x self.y = y self.entity = entity self.agent = agent self.dirty = dirty def set_entity(self, entity): self.entity = entity self.entity.x = self.x self.entit...
class Cell: def __init__(self, x, y, entity=None, agent=None, dirty=False): self.x = x self.y = y self.entity = entity self.agent = agent self.dirty = dirty def set_entity(self, entity): self.entity = entity self.entity.x = self.x self.entity.y =...
# Ann watched a TV program about health and learned that it is # recommended to sleep at least A hours per day, but # oversleeping is also not healthy, and you should not sleep more # than B hours. Now Ann sleeps H hours per day. If Ann's sleep # schedule complies with the requirements of that TV program - # print "Nor...
(a, b, h) = (int(input()), int(input()), int(input())) if h < a: print('Deficiency') elif h > b: print('Excess') else: print('Normal')
def menu(): simulation_name = "listWithOptionsOptimized" use_existing = True save_results = False print("This project is made to train agents to fight each other\nThere is three types of agents\n-dummy : don't do anything\n-runner : just moving\n-killer : move and shoot\nWe are only using dummies and runners ...
def menu(): simulation_name = 'listWithOptionsOptimized' use_existing = True save_results = False print("This project is made to train agents to fight each other\nThere is three types of agents\n-dummy : don't do anything\n-runner : just moving\n-killer : move and shoot\nWe are only using dummies and ru...
my_set = {4, 2, 8, 5, 10, 11, 10} # seturile sunt neordonate my_set2 = {9, 5, 77, 22, 98, 11, 10} print(my_set) # print(my_set[0:]) #nu se poate lst = (11, 12, 12, 14, 15, 13, 14) print(set(lst)) #eliminam duplicatele din lista prin transformarea in set print(my_set.difference(my_set2)) print(my_set.intersection(my_...
my_set = {4, 2, 8, 5, 10, 11, 10} my_set2 = {9, 5, 77, 22, 98, 11, 10} print(my_set) lst = (11, 12, 12, 14, 15, 13, 14) print(set(lst)) print(my_set.difference(my_set2)) print(my_set.intersection(my_set2))
def make_weights_for_balanced_classes(images, nclasses): count = [0] * nclasses for item in images: count[item[1]] += 1 ...
def make_weights_for_balanced_classes(images, nclasses): count = [0] * nclasses for item in images: count[item[1]] += 1 weight_per_class = [0.0] * nclasses n = float(sum(count)) for i in range(nclasses): weight_per_class[i] = N / float(count[i]) weight = [0] * len(images) for...
''' You own a Goal Parser that can interpret a string command. The command consists of an alphabet of "G", "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G", "()" as the string "o", and "(al)" as the string "al". The interpreted strings are then concaten...
""" You own a Goal Parser that can interpret a string command. The command consists of an alphabet of "G", "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G", "()" as the string "o", and "(al)" as the string "al". The interpreted strings are then concaten...
def sequencia(): i = 0 j = 1 while i <= 2: for aux in range(3): if int(i) == i: print(f'I={int(i)} J={int(j)}') else: print(f'I={i:.1f} J={j:.1f}') j += 1 j = round(j - 3 + 0.2, 1) i = round(i + 0.2, 1) sequencia()...
def sequencia(): i = 0 j = 1 while i <= 2: for aux in range(3): if int(i) == i: print(f'I={int(i)} J={int(j)}') else: print(f'I={i:.1f} J={j:.1f}') j += 1 j = round(j - 3 + 0.2, 1) i = round(i + 0.2, 1) sequencia()
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: longest = 0 """ @param root: the root of binary tree @return: the length of the longest consecutive sequence path """ def longestConse...
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: longest = 0 '\n @param root: the root of binary tree\n @return: the length of the longest consecutive sequence path\n ' def longest_consec...
def twoSum( nums, target: int): #Vaule = {}.fromkeys for i in range(len(nums)): a = target - nums[i] for j in range(i+1,len(nums),1): if a == nums[j]: return [i,j] findSum = twoSum(nums = [1,2,3,4,5,6,8],target=14) print(findSum)
def two_sum(nums, target: int): for i in range(len(nums)): a = target - nums[i] for j in range(i + 1, len(nums), 1): if a == nums[j]: return [i, j] find_sum = two_sum(nums=[1, 2, 3, 4, 5, 6, 8], target=14) print(findSum)
#!/usr/bin/python # -*- coding: utf-8 -*- """ MIT License Copyright (c) 2013-2016 Frantisek Uhrecky Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, includ...
""" MIT License Copyright (c) 2013-2016 Frantisek Uhrecky Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to u...
# Events for actors to send __all__ = [ "NodeEvent", "AuthPingEvent", "TagEvent", "UntagEvent", "DetagEvent", "RawMsgEvent", "PingEvent", "GoodNodeEvent", "RecoverEvent", "SetupEvent", ] class NodeEvent: pass class AuthPingEvent(NodeEvent): """ Superclass for tag...
__all__ = ['NodeEvent', 'AuthPingEvent', 'TagEvent', 'UntagEvent', 'DetagEvent', 'RawMsgEvent', 'PingEvent', 'GoodNodeEvent', 'RecoverEvent', 'SetupEvent'] class Nodeevent: pass class Authpingevent(NodeEvent): """ Superclass for tag and ping: must arrive within :meth:`cycle_time_max` seconds of each other...
# Tot's reward lv 50 sm.completeQuest(5522) # Lv. 50 Equipment box sm.giveItem(2430450, 1) sm.dispose()
sm.completeQuest(5522) sm.giveItem(2430450, 1) sm.dispose()
""" Inner module for card utilities. """ def is_location(card): """ Return true if `card` is a location card, false otherwise. """ return card.kind is not None and card.color is not None def is_door(card): """ Return true if `card` is a door card, false otherwise. """ return card.kind...
""" Inner module for card utilities. """ def is_location(card): """ Return true if `card` is a location card, false otherwise. """ return card.kind is not None and card.color is not None def is_door(card): """ Return true if `card` is a door card, false otherwise. """ return card.kind ...