content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def greeting(name="Default"): print(f"Hello {name}") def goodbye(name="Default"): print(f"Goodbye {name}") person1 = { 'name' : 'Ali', 'age' : 25, 'country' : 'Germany' }
def greeting(name='Default'): print(f'Hello {name}') def goodbye(name='Default'): print(f'Goodbye {name}') person1 = {'name': 'Ali', 'age': 25, 'country': 'Germany'}
def foo1(x=(h1 := 1)): pass print(h1) def foo2(x: int = (h2 := 2)): pass print(h2) def foo3(x: (h3 := int)): pass print(h3) def foo4(x: (h4 := float) = 1.1): pass print(h4) def foo5(x=1) -> (h5 := complex): return x * 1j print(h5)
def foo1(x=(h1 := 1)): pass print(h1) def foo2(x: int=(h2 := 2)): pass print(h2) def foo3(x: (h3 := int)): pass print(h3) def foo4(x: (h4 := float)=1.1): pass print(h4) def foo5(x=1) -> (h5 := complex): return x * 1j print(h5)
def solution(A): # write your code in Python 3.6 A.sort() return max(A[0]*A[1]*A[-1],A[-1]*A[-2]*A[-3])
def solution(A): A.sort() return max(A[0] * A[1] * A[-1], A[-1] * A[-2] * A[-3])
class Heap: def __init__(self, array: list) -> None: self.array = array self.heapsize = None def parent(self, i) -> int: return i // 2 def left(self, i) -> int: return 2 * i + 1 def right(self, i) -> int: return 2 * i + 2 def build(self): self.heap...
class Heap: def __init__(self, array: list) -> None: self.array = array self.heapsize = None def parent(self, i) -> int: return i // 2 def left(self, i) -> int: return 2 * i + 1 def right(self, i) -> int: return 2 * i + 2 def build(self): self.hea...
# -*- encoding: utf-8 -*- if __name__ == "__main__": # Computing our magic number... # I wonder why it is taking so long! max_limit = 12345678987654320 linear_sum = max_limit * (max_limit + 1) / 2 max_limit /= 5 squared_sum = max_limit * (max_limit + 1) * (max_limit *...
if __name__ == '__main__': max_limit = 12345678987654320 linear_sum = max_limit * (max_limit + 1) / 2 max_limit /= 5 squared_sum = max_limit * (max_limit + 1) * (max_limit * 2 + 1) / 6 max_limit = max_limit * 5 * 20 cubic_sum = max_limit * max_limit * (max_limit + 1) * (max_limit + 1) * 2 pr...
#!/usr/bin/env python # -*- coding: utf-8 -*- # bot.py # Necessary information Host = "irc.twitch.tv" # The Twitch IRC server Port = 6667 # Always use port 6667! Nickname = "" # The username of your bo...
host = 'irc.twitch.tv' port = 6667 nickname = '' bot_token = '' user_token = '' channel = '#' client_id = '' stream_link_location = 'C:\\Program/Files\\Streamlink\\bin\\streamlink.exe' vlc_location = 'C:\\Program/Files\\VLC\\vlc.exe' webhook_url = 'https://discord.com/api/webhooks/123456/23224gh3if51tyu23gfy5ufyuofiu'
class Default: DEBUG = False ENV = 'production' MONGODB_HOST = 'mongodb://127.0.0.1:27017/urlshortener' SECRET_KEY = 'default secret key' SERVER_NAME = '127.0.0.1:5000' SESSION_COOKIE_DOMAIN = '127.0.0.1:5000' SSL = True class Test: DEBUG = True ENV = 'test' MONGODB_HOST = 'm...
class Default: debug = False env = 'production' mongodb_host = 'mongodb://127.0.0.1:27017/urlshortener' secret_key = 'default secret key' server_name = '127.0.0.1:5000' session_cookie_domain = '127.0.0.1:5000' ssl = True class Test: debug = True env = 'test' mongodb_host = 'mong...
#list #tuple #set #random #loop #checking #add #update #len #remove #discard #pop() #clear objects = {"daivd", "table", "laptop", "phone", "Mike"} # ramdom for x in objects: print(x) if "daivd" in objects: print("Yes, It has david") objects.add("Guna1") objects.update(["Guna", "Rakulan", "Gunarakulan"]) prin...
objects = {'daivd', 'table', 'laptop', 'phone', 'Mike'} for x in objects: print(x) if 'daivd' in objects: print('Yes, It has david') objects.add('Guna1') objects.update(['Guna', 'Rakulan', 'Gunarakulan']) print(objects) print(len(objects)) objects.remove('Rakulan') objects.discard('Guna1') objects.pop() objects...
def fix_shape(x, y): if x.shape < y.shape: y = y[-x.shape[0]:] elif x.shape > y.shape: x = x[-y.shape[0]:] return x, y
def fix_shape(x, y): if x.shape < y.shape: y = y[-x.shape[0]:] elif x.shape > y.shape: x = x[-y.shape[0]:] return (x, y)
#!/usr/bin/env python # coding: utf-8 # In[1]: s="Arsh Saxena" s[0] # In[2]: s[4] # In[3]: s[-1] # In[7]: s[-6] # In[8]: s[0:11] #[start:end]>end point is excluded # In[9]: s[:] # In[19]: s[::2] # In[21]: s[::-1] # In[23]: s[5:1:-1]
s = 'Arsh Saxena' s[0] s[4] s[-1] s[-6] s[0:11] s[:] s[::2] s[::-1] s[5:1:-1]
def commafy(lst): if len(lst) == 0: return "" elif len(lst) == 1: return str(lst[0]) elif len(lst) == 2: return str(lst[0]) + " and " + str(lst[1]) else: lastItem = ", and " + str(lst.pop()) return ", ".join([str(item) for item in lst]) + lastItem empty = [] bac...
def commafy(lst): if len(lst) == 0: return '' elif len(lst) == 1: return str(lst[0]) elif len(lst) == 2: return str(lst[0]) + ' and ' + str(lst[1]) else: last_item = ', and ' + str(lst.pop()) return ', '.join([str(item) for item in lst]) + lastItem empty = [] baco...
Import("env") # access to global construction environment # <SCons.Script.SConscript.SConsEnvironment> # print(env.Dump()) def before_build_littlefs(source, target, env): env.Execute("yarn && yarn build --pioEnv=" + env["PIOENV"]) # # Custom actions for specific files/objects # env.AddPreAction("$BUILD_DIR/littlef...
import('env') def before_build_littlefs(source, target, env): env.Execute('yarn && yarn build --pioEnv=' + env['PIOENV']) env.AddPreAction('$BUILD_DIR/littlefs.bin', before_build_littlefs)
''' Copyright [2020] [Anoop Bhat] 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 d...
""" Copyright [2020] [Anoop Bhat] 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 di...
class IniPair: Name = "" Value = None def __init__(self): self.Name = "" self.Value = None def IsNull(self): return self.Name == "" or self.Value is None or self.Value == ""
class Inipair: name = '' value = None def __init__(self): self.Name = '' self.Value = None def is_null(self): return self.Name == '' or self.Value is None or self.Value == ''
## ocaml/_rules/impl_common.bzl tmpdir = "__obazl/" dsorder = "postorder" opam_lib_prefix = "external/ocaml/_lib" module_sep = "__" resolver_suffix = module_sep + "0Resolver"
tmpdir = '__obazl/' dsorder = 'postorder' opam_lib_prefix = 'external/ocaml/_lib' module_sep = '__' resolver_suffix = module_sep + '0Resolver'
class Vocab: def __init__(self, name): self.name = name self.word_index = {} self.word_count = {} self.index_word = {0: "SOS", 1: "EOS"} self.num_words = 2 def add_sentence(self, sentence): for word in sentence.split(' '): self.add_word(word) def add_word(self, word): if word not in self.word_inde...
class Vocab: def __init__(self, name): self.name = name self.word_index = {} self.word_count = {} self.index_word = {0: 'SOS', 1: 'EOS'} self.num_words = 2 def add_sentence(self, sentence): for word in sentence.split(' '): self.add_word(word) de...
count = 0 for i in range(0,5): x = int(input()) if x % 2 == 0: count += 1 print('{} valores pares'.format(count))
count = 0 for i in range(0, 5): x = int(input()) if x % 2 == 0: count += 1 print('{} valores pares'.format(count))
#!/usr/bin/env python3 alpha = 0.125 sentTimes = [0.026477, 0.041737, 0.054026, 0.054690, 0.077405, 0.078157] recvTimes = [0.053937, 0.077294, 0.124805, 0.169118, 0.217299, 0.267802] SampleRTT = recvTimes[0]-sentTimes[0] EstimatedRTT = SampleRTT if len(sentTimes) == len(recvTimes): i = 0 while i < len(sentTi...
alpha = 0.125 sent_times = [0.026477, 0.041737, 0.054026, 0.05469, 0.077405, 0.078157] recv_times = [0.053937, 0.077294, 0.124805, 0.169118, 0.217299, 0.267802] sample_rtt = recvTimes[0] - sentTimes[0] estimated_rtt = SampleRTT if len(sentTimes) == len(recvTimes): i = 0 while i < len(sentTimes): estimat...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Unordered collections with unique elements. my_set = set() # Initialize with iterable object like list or tuple. # 'Set' operations. my_set.add(1) my_set.add(2) print(my_set) my_set.add(1) # Adding 1 again to be duplicate. This throws no error nither add. p...
my_set = set() my_set.add(1) my_set.add(2) print(my_set) my_set.add(1) print(my_set) l = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5] my_set = set(l) print(my_set) str_set = set('Mississippi') print(str_set)
#!/usr/bin/env python number = int(input('Type a number to create a Fibonacci sequence of it: ')) f1 = -1 f2 = 1 counter = 0 while counter <= number: f = f1 + f2 print("%d" % f) f1 = f2 f2 = f counter += 1
number = int(input('Type a number to create a Fibonacci sequence of it: ')) f1 = -1 f2 = 1 counter = 0 while counter <= number: f = f1 + f2 print('%d' % f) f1 = f2 f2 = f counter += 1
deposit=int(input("Enter the deposit amount :")) if deposit > 100: print("you will get a free toast") print("Have a nice day")
deposit = int(input('Enter the deposit amount :')) if deposit > 100: print('you will get a free toast') print('Have a nice day')
# Specialization: Google IT Automation with Python # Course 01: Crash Course with Python # Week 4 Module Part 2 Exercise 03 # Student: Shawn Solomon # Learning Platform: Coursera.org # Let's use tuples to store information about a file: its name, its type and its size in bytes. # Fill in the gaps in this code ...
def file_size(file_info): (na, ty, si) = file_info return '{:.2f}'.format(si / 1024) print(file_size(('Class Assignment', 'docx', 17875))) print(file_size(('Notes', 'txt', 496))) print(file_size(('Program', 'py', 1239)))
# # PySNMP MIB module CISCO-ISNS-IP-NW-DISCOVERY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ISNS-IP-NW-DISCOVERY-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:46:00 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python ...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint) ...
AWR_CONFIGS = { "Ant-v2": { "actor_net_layers": [128, 64], "actor_stepsize": 0.00005, "actor_momentum": 0.9, "actor_init_output_scale": 0.01, "actor_batch_size": 256, "actor_steps": 1000, "action_std": 0.2, "critic_net_layers": [128, 64], ...
awr_configs = {'Ant-v2': {'actor_net_layers': [128, 64], 'actor_stepsize': 5e-05, 'actor_momentum': 0.9, 'actor_init_output_scale': 0.01, 'actor_batch_size': 256, 'actor_steps': 1000, 'action_std': 0.2, 'critic_net_layers': [128, 64], 'critic_stepsize': 0.01, 'critic_momentum': 0.9, 'critic_batch_size': 256, 'critic_st...
def make_param_entries(model_name, prepend, feat_dict, cfg): if(model_name in cfg): for i, param in enumerate(cfg[model_name]): param_key = param.keys()[0] feat_dict[prepend + '__' + param_key] = \ cfg[model_name][i][param_key] return feat_dict
def make_param_entries(model_name, prepend, feat_dict, cfg): if model_name in cfg: for (i, param) in enumerate(cfg[model_name]): param_key = param.keys()[0] feat_dict[prepend + '__' + param_key] = cfg[model_name][i][param_key] return feat_dict
proxy = '''proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_http_version 1.1; proxy_read_timeout 900; proxy_send_timeout 120; #proxy_ssl_server_name on; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $host; p...
proxy = 'proxy_set_header Upgrade $http_upgrade;\nproxy_set_header Connection $connection_upgrade;\nproxy_http_version 1.1;\nproxy_read_timeout 900;\nproxy_send_timeout 120;\n\n#proxy_ssl_server_name on;\nproxy_set_header X-Real-IP $remote_addr;\nproxy_set_header X-Forwarded-For $remote_addr;\nproxy_set_header Host $h...
class QueryError(Exception): def __init__(self, code, message): self.code = code self.message = message super().__init__(f"{message} (error code {code})") class GatewayError(QueryError): pass class ComponentError(Exception): pass
class Queryerror(Exception): def __init__(self, code, message): self.code = code self.message = message super().__init__(f'{message} (error code {code})') class Gatewayerror(QueryError): pass class Componenterror(Exception): pass
# this one is like your scripts with argv def print_two(*args): arg1, arg2 = args print(f"arg1: {arg1}, arg2: {arg2}") # oK, that *args is actually pointless, we can just do this def print_two_again(arg1, arg2): print(f"arg1: {arg1}, arg2: {arg2}") # this just take one argument def print_one(arg): pri...
def print_two(*args): (arg1, arg2) = args print(f'arg1: {arg1}, arg2: {arg2}') def print_two_again(arg1, arg2): print(f'arg1: {arg1}, arg2: {arg2}') def print_one(arg): print(f'arg: {arg}') def print_none(): print('I got nothin...:(') print_two('Min', 'Kyoz') print_two_again('One', 'Two') print_o...
class Solution: def nextPermutation(self, nums: List[int]) -> None: l = len(nums) for i in range(l - 1, 0, -1): if nums[i - 1] >= nums[i]: continue nums[i:] = nums[:i-l-1:-1] for j in range(i, l): if nums[j] > nums[i - 1]: ...
class Solution: def next_permutation(self, nums: List[int]) -> None: l = len(nums) for i in range(l - 1, 0, -1): if nums[i - 1] >= nums[i]: continue nums[i:] = nums[:i - l - 1:-1] for j in range(i, l): if nums[j] > nums[i - 1]: ...
# len() List = [1, 2, 3, 4, 5, 6] print(len(List)) print(List.__len__())
list = [1, 2, 3, 4, 5, 6] print(len(List)) print(List.__len__())
class Solution: def longestPrefix(self, s): pre, suf, ans, mod, tmp = 0, 0, 0, 10 ** 9 + 7, 1 for i in range(len(s) - 1): pre = (pre * 64 + ord(s[i])) % mod suf = (ord(s[~i]) * tmp + suf) % mod tmp = (tmp * 64) % mod if pre == suf: ans = i + 1 ...
class Solution: def longest_prefix(self, s): (pre, suf, ans, mod, tmp) = (0, 0, 0, 10 ** 9 + 7, 1) for i in range(len(s) - 1): pre = (pre * 64 + ord(s[i])) % mod suf = (ord(s[~i]) * tmp + suf) % mod tmp = tmp * 64 % mod if pre == suf: ...
# Autor: Abdel G. Martinez L. # Hacer un programa que lea 5 numeros # y los ordene de forma descendente num1 = int(input("Numero 1: ")) mx = num1 num2 = int(input("Numero 2: ")) if num2 > mx: mx = num2 md = num1 else: md = num2 num3 = int(input("Numero 3: ")) if num3 > mx: mn = md md = mx mx = ...
num1 = int(input('Numero 1: ')) mx = num1 num2 = int(input('Numero 2: ')) if num2 > mx: mx = num2 md = num1 else: md = num2 num3 = int(input('Numero 3: ')) if num3 > mx: mn = md md = mx mx = num3 elif num3 > md: mn = md md = num3 else: mn = num3 print(mx, md, mn)
# How many passwords are valid according to their policies? with open('input.txt') as f: lines = f.read().splitlines() print(lines) valid_passwords = 0 for (_range, letter, password) in [line.split() for line in lines]: _letter = letter[0] index_1, index_2 = _range.split("-") ch...
with open('input.txt') as f: lines = f.read().splitlines() print(lines) valid_passwords = 0 for (_range, letter, password) in [line.split() for line in lines]: _letter = letter[0] (index_1, index_2) = _range.split('-') (char_1, char_2) = (password[int(index_1) - 1], password[int(...
# This program demonstrates passes two strings as # keyword arguments to a function. def main(): first_name = input('Enter your first name: ') last_name = input('Enter your last name: ') print('Your name reversed is') reverse_name(last=last_name, first=first_name) def reverse_name(first, last): pr...
def main(): first_name = input('Enter your first name: ') last_name = input('Enter your last name: ') print('Your name reversed is') reverse_name(last=last_name, first=first_name) def reverse_name(first, last): print(last, first) main()
''' Created on May 26, 2019 @author: ballance ''' dpi_c = ''' /**************************************************************************** * SystemVerilog DPI Launcher ****************************************************************************/ #include <stdint.h> #include <stdio.h> #include "Python.h" #ifdef __...
""" Created on May 26, 2019 @author: ballance """ dpi_c = '\n/****************************************************************************\n * SystemVerilog DPI Launcher\n ****************************************************************************/\n#include <stdint.h>\n#include <stdio.h>\n#include "Python.h"\n\n#ifd...
__author__ = 'Will Dampier' __email__ = 'judowill@gmail.com' __version__ = '0.1.0' #from fig2pptx import utils #from fig2pptx.fig2pptx import PowerPointSlide, PowerPointBox
__author__ = 'Will Dampier' __email__ = 'judowill@gmail.com' __version__ = '0.1.0'
class DiscordAPIError(Exception): ... class InvalidData(Exception): ... class InvalidIntents(Exception): ... class ShardingRequired(Exception): ... class InvalidToken(Exception): ... class UnhandledException(Exception): ... class DisallowedIntents(Exception): ...
class Discordapierror(Exception): ... class Invaliddata(Exception): ... class Invalidintents(Exception): ... class Shardingrequired(Exception): ... class Invalidtoken(Exception): ... class Unhandledexception(Exception): ... class Disallowedintents(Exception): ... class Badrequest400(E...
n = int(input()) a = 100 d = 100 for i in range(n): x, y = map(int, input().split()) if x > y: d -= x elif y > x: a -= y print(a) print(d)
n = int(input()) a = 100 d = 100 for i in range(n): (x, y) = map(int, input().split()) if x > y: d -= x elif y > x: a -= y print(a) print(d)
# Errors NSERR_SESSION_EXPIRED = 0x1BC NSERR_AUTHTIMEOUT = 0x403 NSERR_NOUSER = 0x162 MAX_LOGIN_RETRIES_ALLOWED = 3
nserr_session_expired = 444 nserr_authtimeout = 1027 nserr_nouser = 354 max_login_retries_allowed = 3
# -*- coding: utf-8 -*- __all__ = ('get_input_function', ) def get_input_function(): try: input_function = raw_input except NameError: input_function = input return input_function
__all__ = ('get_input_function',) def get_input_function(): try: input_function = raw_input except NameError: input_function = input return input_function
def partition(arr): p = arr[0] s = 0 for i in range(1, len(arr)): if (arr[i] < p): s += 1 temp = arr[s] arr[s] = arr[i] arr[i] = temp temp = arr[s] arr[s] = arr[0] arr[0] = temp return arr,s print(partition([4,7,2,1,3,8,9]))
def partition(arr): p = arr[0] s = 0 for i in range(1, len(arr)): if arr[i] < p: s += 1 temp = arr[s] arr[s] = arr[i] arr[i] = temp temp = arr[s] arr[s] = arr[0] arr[0] = temp return (arr, s) print(partition([4, 7, 2, 1, 3, 8, 9]))
def linear_search_dictionary(the_dict, target): for k, v in the_dict.items(): if v == target: print(f"Found at key {k}") return k print("Target is not in the dictionary") return None my_dictionary = {"red": 5, "blue": 3, "yellow": 12, "green": 7} linear_search_dictionary(...
def linear_search_dictionary(the_dict, target): for (k, v) in the_dict.items(): if v == target: print(f'Found at key {k}') return k print('Target is not in the dictionary') return None my_dictionary = {'red': 5, 'blue': 3, 'yellow': 12, 'green': 7} linear_search_dictionary(my...
# Method 1 rows = int(input("Enter the rows : ")) cols = int(input("Enter the cols : ")) arr = [[0]*rows]*cols print(arr) # Method 2 rows1 = int(input("Enter rows1 : ")) cols1 = int(input("Enter cols1 : ")) arr = [[0 for i in range(cols1)] for j in range(rows1)] print(arr) # Method 3 rows = int(input("Enter the rows2...
rows = int(input('Enter the rows : ')) cols = int(input('Enter the cols : ')) arr = [[0] * rows] * cols print(arr) rows1 = int(input('Enter rows1 : ')) cols1 = int(input('Enter cols1 : ')) arr = [[0 for i in range(cols1)] for j in range(rows1)] print(arr) rows = int(input('Enter the rows2 : ')) cols = int(input('Enter ...
def bead_sort(obj): if all([type(x) == int and x >= 0 for x in obj]): ref = [range(x) for x in obj] #for reference else: raise ValueError("All elements must be positive integers") inter = [] #for intermediate ind = 0 #for index prev = sum([1 for x in ref if len(x) > ind]) #prev f...
def bead_sort(obj): if all([type(x) == int and x >= 0 for x in obj]): ref = [range(x) for x in obj] else: raise value_error('All elements must be positive integers') inter = [] ind = 0 prev = sum([1 for x in ref if len(x) > ind]) while prev: inter.append(range(prev)) ...
'''module containing helper functions for logging This module just contains a couple of decorators. This is useful when you want to wrap your function into a decorator. The decorators will automatically inject the right decorator into your module withoput you having to worry about the decorator. '''
"""module containing helper functions for logging This module just contains a couple of decorators. This is useful when you want to wrap your function into a decorator. The decorators will automatically inject the right decorator into your module withoput you having to worry about the decorator. """
# TC: O(m+n) | SC: O(1) def solution_1(m): # last index of a row one_start_index = len(m[0])-1 # track row with max 1s. row = -1 # search for row with max 1s. for i in range(0, len(m)): # each row move backwards to hold starting index of 1. while m[i][one_start_index-1] and one_...
def solution_1(m): one_start_index = len(m[0]) - 1 row = -1 for i in range(0, len(m)): while m[i][one_start_index - 1] and one_start_index > 0: one_start_index -= 1 row = i return row if __name__ == '__main__': m = [[0, 0, 0, 1], [0, 1, 1, 1], [1, 1, 1, 1], [0, 0, 0, ...
color_list_1 = set(["White", "Black", "Red"]) color_list_2 = set(["Red", "Green"]) output = color_list_1 - color_list_2 print(output)
color_list_1 = set(['White', 'Black', 'Red']) color_list_2 = set(['Red', 'Green']) output = color_list_1 - color_list_2 print(output)
def count_to(num, arr): iterator = zip(range(num), arr) for i, elem in iterator: yield elem test_arr = [f'elem{i}' for i in range(10)] for i in count_to(3, test_arr): print(i)
def count_to(num, arr): iterator = zip(range(num), arr) for (i, elem) in iterator: yield elem test_arr = [f'elem{i}' for i in range(10)] for i in count_to(3, test_arr): print(i)
mem=[0 for _ in range(0x10000)] mem[1]=ord(input("Please input a char: ")) mem[2]=ord(input("Please input a char: ")) mem[3]=ord(input("Please input a char: ")) mem[4]=ord(input("Please input a char: ")) mem[5]=ord(input("Please input a char: ")) mem[6]=ord(input("Please input a char: ")) while mem[1]!=0: mem[1]=(m...
mem = [0 for _ in range(65536)] mem[1] = ord(input('Please input a char: ')) mem[2] = ord(input('Please input a char: ')) mem[3] = ord(input('Please input a char: ')) mem[4] = ord(input('Please input a char: ')) mem[5] = ord(input('Please input a char: ')) mem[6] = ord(input('Please input a char: ')) while mem[1] != 0:...
s = 'I am a string' print(type(s)) #Boolean yes = True no = False print(type(no)) #List, ordered and changeable alpha_list = ['a','b','c'] print(type(alpha_list)) print(type(alpha_list[0])) alpha_list.append('d') print(alpha_list) #Tuple, ordered and unchangeable alpha_tuple = ('a','b','c') print(type(alpha_tuple...
s = 'I am a string' print(type(s)) yes = True no = False print(type(no)) alpha_list = ['a', 'b', 'c'] print(type(alpha_list)) print(type(alpha_list[0])) alpha_list.append('d') print(alpha_list) alpha_tuple = ('a', 'b', 'c') print(type(alpha_tuple)) try: alpha_tuple[2] = 'd' except TypeError: print('We cant add ...
{ 'targets': [ { 'target_name': 'catboost-node', 'sources': [ 'src/api_helpers.cpp', 'src/api_module.cpp', 'src/model.cpp', ], 'include_dirs': [ "<!@(node -p \"require('node-addon-api').i...
{'targets': [{'target_name': 'catboost-node', 'sources': ['src/api_helpers.cpp', 'src/api_module.cpp', 'src/model.cpp'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")', '<!@(node -p "process.env[\'CATBOOST_SRC_PATH\'] || \'../..\'")', '<!@(node -p "process.env[\'CATBOOST_SRC_PATH\'] || \'../..\'"...
class SeaIceError(Exception): pass class SeaIceBadSeason(SeaIceError): pass
class Seaiceerror(Exception): pass class Seaicebadseason(SeaIceError): pass
EMAIL_IS_NOT_VERIFIED_USERS = 'EMAIL_IS_NOT_VERIFIED' USERS = 'USER' GROUPS = (EMAIL_IS_NOT_VERIFIED_USERS, USERS)
email_is_not_verified_users = 'EMAIL_IS_NOT_VERIFIED' users = 'USER' groups = (EMAIL_IS_NOT_VERIFIED_USERS, USERS)
def format_residential_address(address_parts): # use this function to format an address with commas # e.g: 1 Foo street, Bar Town # We store Residential Addresses in this format because we show # them in a list/drop down (i.e: in a single line format) address = ", ".join([part for part in address_pa...
def format_residential_address(address_parts): address = ', '.join([part for part in address_parts if part.strip()]) return address def format_polling_station_address(address_parts): address = '\n'.join([part for part in address_parts if part.strip()]) return address
class nft: # class has properties inside it x=5 y=7 bored_ape=nft() print(nft.x) print(nft.y) print(bored_ape.x)
class Nft: x = 5 y = 7 bored_ape = nft() print(nft.x) print(nft.y) print(bored_ape.x)
height= float(input("Please Enter your height :")) weight = int(input("Please Enter your weight :")) BMI = weight / height ** 2 BMI = round(BMI, 2) if BMI <18.5 : print(f"your BMI is {BMI} and you are underweight") elif BMI <25: print(f"your BMI is {BMI} and you are normalweight") elif BMI <30: print(f"you...
height = float(input('Please Enter your height :')) weight = int(input('Please Enter your weight :')) bmi = weight / height ** 2 bmi = round(BMI, 2) if BMI < 18.5: print(f'your BMI is {BMI} and you are underweight') elif BMI < 25: print(f'your BMI is {BMI} and you are normalweight') elif BMI < 30: print(f'y...
#Nick Pandelakis, Ann Beimers, Grace De Benetti print('Hello World') #hello world works #grace's push goes through
print('Hello World')
def test_attr(*args): def decorator(func): for i in args: setattr(func, 'test', i) return func return decorator
def test_attr(*args): def decorator(func): for i in args: setattr(func, 'test', i) return func return decorator
class Solution: def minReorder(self, n: int, connections: List[List[int]]) -> int: visited = set() connection = {} inverse = {} self.ans = 0 def dfs(node): visited.add(node) if node in connection: for neighbour in connection[node]: ...
class Solution: def min_reorder(self, n: int, connections: List[List[int]]) -> int: visited = set() connection = {} inverse = {} self.ans = 0 def dfs(node): visited.add(node) if node in connection: for neighbour in connection[node]: ...
# # PySNMP MIB module HPN-ICF-LswMix-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-LswMix-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:27:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_intersection, constraints_union, value_size_constraint, value_range_constraint) ...
class Solution: def thirdMax(self, nums: List[int]) -> int: # my initial solution, not quite get there b/c time is O(nlogn) nums = sorted(list(set(nums))) try: return nums[-3] except: return nums[-1] # https://leetcode.com/problems/third-maxi...
class Solution: def third_max(self, nums: List[int]) -> int: nums = sorted(list(set(nums))) try: return nums[-3] except: return nums[-1] def third_max(self, nums: List[int]) -> int: lst = [-float('inf'), -float('inf'), -float('inf')] for n in num...
# noinspection PyPep8Naming def solution(A): counter = len(A) freq = [0] * (len(A) + 1) for a in A: if a > len(A): return 0 counter -= 1 freq[a] += 1 if freq[a] > 1: return 0 return int(counter == 0) assert solution([4, 1, 3, 2]) == 1 assert solu...
def solution(A): counter = len(A) freq = [0] * (len(A) + 1) for a in A: if a > len(A): return 0 counter -= 1 freq[a] += 1 if freq[a] > 1: return 0 return int(counter == 0) assert solution([4, 1, 3, 2]) == 1 assert solution([4, 1, 3]) == 0
''' Created on June 14, 2020 @author: karel.blavka@gmail.com ''' class Moving_Average: def __init__(self, n): self._n = n self._head = 0 self._sum = 0 self._counter = 0 self._samples = [0] * n def feed(self, value): self._sum -= self._samples[self._head] ...
""" Created on June 14, 2020 @author: karel.blavka@gmail.com """ class Moving_Average: def __init__(self, n): self._n = n self._head = 0 self._sum = 0 self._counter = 0 self._samples = [0] * n def feed(self, value): self._sum -= self._samples[self._head] ...
#!/usr/bin/env python3 def setbufcalc(): buf = b"" buf += b"\xb8\x7a\xaf\xec\xe5\xdb\xc9\xd9\x74\x24\xf4\x5e\x31" buf += b"\xc9\xb1\x30\x31\x46\x13\x03\x46\x13\x83\xc6\x7e\x4d" buf += b"\x19\x19\x96\x13\xe2\xe2\x66\x74\x6a\x07\x57\xb4\x08" buf += b"\x43\xc7\x04\x5a\x01\xeb\xef\x0e\xb2\x78\x9d\x86\...
def setbufcalc(): buf = b'' buf += b'\xb8z\xaf\xec\xe5\xdb\xc9\xd9t$\xf4^1' buf += b'\xc9\xb101F\x13\x03F\x13\x83\xc6~M' buf += b'\x19\x19\x96\x13\xe2\xe2ftj\x07W\xb4\x08' buf += b'C\xc7\x04Z\x01\xeb\xef\x0e\xb2x\x9d\x86\xb5' buf += b'\xc9(\xf1\xf8\xca\x01\xc1\x9bHX\x16|q' buf += b'\x93k}\xb...
def getHeaders(solved): tmp, i = [], 0 # Store text of strong tags(section headings) for text in solved.find_all('strong'): tmp.append(text.get_text()) # Printing section headings print("Sections available to download:") for heading in tmp: print(f"{(i+1)}. {heading[0:-1]}") ...
def get_headers(solved): (tmp, i) = ([], 0) for text in solved.find_all('strong'): tmp.append(text.get_text()) print('Sections available to download:') for heading in tmp: print(f'{i + 1}. {heading[0:-1]}') i += 1 return tmp def get_solutions(solved, section): tmp = [] ...
#!/usr/bin/env python3 ################################################################################# # # # Program purpose: Compute the digit number of sum of two given numbers. # # Program Author : Happi Yvan <ivensteinpok...
if __name__ == '__main__': int_a = 0 int_b = 0 cont = True while cont: try: int_a = int(input('Enter first integer: ')) cont = False except ValueError as ve: print('Invalid input. Try again.') cont = True while cont: try: in...
class LostInternetConnection(Exception): def __init__(self, message): super().__init__(message) class UnexpectedVariable(Exception): def __init__(self, message): super().__init__(message) class DatabaseWrongDataForm(Exception): def __init__(self, message): super().__init__(messa...
class Lostinternetconnection(Exception): def __init__(self, message): super().__init__(message) class Unexpectedvariable(Exception): def __init__(self, message): super().__init__(message) class Databasewrongdataform(Exception): def __init__(self, message): super().__init__(messa...
start = [0,0] end = [7,7] taken = [ [1,0], [1,1], [1,2], [1,3] ] queue = [] queue.append([start[0],start[1],-1]) visited = [] maze = [] for i in range(8): maze.append(['.','.','.','.','.','.','.','.']) visited.append([0,0,0,0,0,0,0,0]) maze[start[0]][start[1]] = 'S' maze[end[0]][end[1]] = 'E' for i in taken: m...
start = [0, 0] end = [7, 7] taken = [[1, 0], [1, 1], [1, 2], [1, 3]] queue = [] queue.append([start[0], start[1], -1]) visited = [] maze = [] for i in range(8): maze.append(['.', '.', '.', '.', '.', '.', '.', '.']) visited.append([0, 0, 0, 0, 0, 0, 0, 0]) maze[start[0]][start[1]] = 'S' maze[end[0]][end[1]] = 'E...
final = ["Andaman & Nicobar", "Andhra Pradesh", "Arunachal Pradesh", "Assam", "Bihar", "Chandigarh", "Chhattisgarh", "Dadra & Nagar Haveli", "Daman & Diu", "Delhi", "Goa", "Gujarat", "Haryana", "Himachal Pradesh", "Jammu & Kashmir", "Jharkhand", "Karnataka", "Kerala", "Lakshadweep", "Madhya Pradesh", "Maharash...
final = ['Andaman & Nicobar', 'Andhra Pradesh', 'Arunachal Pradesh', 'Assam', 'Bihar', 'Chandigarh', 'Chhattisgarh', 'Dadra & Nagar Haveli', 'Daman & Diu', 'Delhi', 'Goa', 'Gujarat', 'Haryana', 'Himachal Pradesh', 'Jammu & Kashmir', 'Jharkhand', 'Karnataka', 'Kerala', 'Lakshadweep', 'Madhya Pradesh', 'Maharashtra', 'Ma...
#find leaders l1= [16,17,4,3,5,2] def leaders(l1): res = [ ] maxval = None for i in range(1, len(l1)+1): val = l1[-i] if maxval is None: res.append(val) maxval = val else: if maxval <val: res.append(val) ...
l1 = [16, 17, 4, 3, 5, 2] def leaders(l1): res = [] maxval = None for i in range(1, len(l1) + 1): val = l1[-i] if maxval is None: res.append(val) maxval = val elif maxval < val: res.append(val) maxval = val return res print(leaders...
# Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) fun(a, kw=1, *c, **d) fun(a, *c, kw=1, **d) fun(a, kw=1, *c) fun(a, *c, kw=1) fun(a, *c) # Introduced in Python3.5, not supported yet #fun(*c, a)
fun(a, *c, kw=1, **d) fun(a, *c, kw=1, **d) fun(a, *c, kw=1) fun(a, *c, kw=1) fun(a, *c)
#A program to determine your reading speed #This program is a precursor for a future program to investigate a correlation #between reading speed and book format #Python3 syntax #declare variables introduction = " " book_format = " " book_name = " " pages_read = 0.0 reading_time = 0.0 #get input introduction = input("...
introduction = ' ' book_format = ' ' book_name = ' ' pages_read = 0.0 reading_time = 0.0 introduction = input('Hello! Please answer the following questions to the best of your ability. (Press enter to continue)') book_format = input("What format is the book you're reading?") book_name = input('Which book have you just ...
def find_common_characters(msg1, msg2): msg3 = msg1.replace(" ", "") msg4 = msg2.replace(" ", "") l = [] for alpha in msg3: if alpha in msg4: l.append(alpha) if len(l) != 0: return "".join(l) else: return -1 # Provide different values for msg1,msg2 and test ...
def find_common_characters(msg1, msg2): msg3 = msg1.replace(' ', '') msg4 = msg2.replace(' ', '') l = [] for alpha in msg3: if alpha in msg4: l.append(alpha) if len(l) != 0: return ''.join(l) else: return -1 msg1 = 'I like Python' msg2 = 'Java is a very popula...
# O(n log n) Solution class Solution1: # @param A : list of integers # @return a list of integers def wave(self, A): A.sort() for i in range(0, len(A) - 1, 2): A[i], A[i + 1] = A[i + 1], A[i] return A # O(n) Solution class Solution2: # @param A : list of integers ...
class Solution1: def wave(self, A): A.sort() for i in range(0, len(A) - 1, 2): (A[i], A[i + 1]) = (A[i + 1], A[i]) return A class Solution2: def wave(self, A): n = len(A) for i in range(0, n, 2): if i > 0 and A[i] < A[i - 1]: (A[...
bicycles = ['trek', 'cannondale', 'redline', 'specialize'] print(bicycles) print(bicycles[0]) print(bicycles[0].title())
bicycles = ['trek', 'cannondale', 'redline', 'specialize'] print(bicycles) print(bicycles[0]) print(bicycles[0].title())
expected_output = { 'interfaces': { 'GigabitEthernet0/0/0/0': { 'interface': 'GigabitEthernet0/0/0/0', 'neighbors': { '2001:db8:8548:1::1': { 'age': '82', 'ip': '2001:db8:8548:1::1', 'link_layer_address': '...
expected_output = {'interfaces': {'GigabitEthernet0/0/0/0': {'interface': 'GigabitEthernet0/0/0/0', 'neighbors': {'2001:db8:8548:1::1': {'age': '82', 'ip': '2001:db8:8548:1::1', 'link_layer_address': 'fa16.3eff.c4d3', 'neighbor_state': 'REACH', 'location': '0/0/CPU0', 'static': '-', 'dynamic': 'Y', 'sync': '-', 'serg_f...
##Bubble Sort def bubbleSort(arr): n = len(arr) for i in range(n-1): for j in range(0, n-i-1): if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] arr= [50,11,213,1235,151,484,989,1,35,78,45] bubbleSort(arr) print ("Sorted array is:") f...
def bubble_sort(arr): n = len(arr) for i in range(n - 1): for j in range(0, n - i - 1): if arr[j] > arr[j + 1]: (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]) arr = [50, 11, 213, 1235, 151, 484, 989, 1, 35, 78, 45] bubble_sort(arr) print('Sorted array is:') for i in range(len(ar...
class MercadolibreTransformer: def transform_item(self, raw_item): title = raw_item.find('h2', class_='ui-search-item__title') price = raw_item.find('span', class_='price-tag-fraction') image = raw_item.find('img', class_='ui-search-result-image__element') return { 'ti...
class Mercadolibretransformer: def transform_item(self, raw_item): title = raw_item.find('h2', class_='ui-search-item__title') price = raw_item.find('span', class_='price-tag-fraction') image = raw_item.find('img', class_='ui-search-result-image__element') return {'title': title.tex...
# This file was generated from a template with the following substitutions: # # - REPOSITORY_NAME: {REPOSITORY_NAME} '''Defines a helper macro to register the GraalVM toolchains provided by this repository, "@{REPOSITORY_NAME}". ''' def register_graalvm_toolchains(): native.register_toolchains( "@{REPOSIT...
"""Defines a helper macro to register the GraalVM toolchains provided by this repository, "@{REPOSITORY_NAME}". """ def register_graalvm_toolchains(): native.register_toolchains('@{REPOSITORY_NAME}//graalvm:graalvm_native_image_toolchain')
class Smartphone(): def set_price(self, price): self.smartphone_price = price def get_price(self): return self.smartphone_price x = Smartphone() x.set_price(11000) y = x.get_price() print(y)
class Smartphone: def set_price(self, price): self.smartphone_price = price def get_price(self): return self.smartphone_price x = smartphone() x.set_price(11000) y = x.get_price() print(y)
def setup_test_config(configuration): configuration.reset() configuration.set('database-path', '') configuration.set('debug', True) configuration.set('debug-db-reset', True) configuration.set('oidc_client_id', 'test-app') configuration.set('oidc_client_secret_file', '../oidc_secret.txt') con...
def setup_test_config(configuration): configuration.reset() configuration.set('database-path', '') configuration.set('debug', True) configuration.set('debug-db-reset', True) configuration.set('oidc_client_id', 'test-app') configuration.set('oidc_client_secret_file', '../oidc_secret.txt') con...
class Code: def __init__(self, data: dir): self.json = data self.code = 0 @property def Code(self): self.code = self.json.get("code") return self class BootData: def __init__(self, data: dir): self.json = data self.is_viral_tab_disabled = None ...
class Code: def __init__(self, data: dir): self.json = data self.code = 0 @property def code(self): self.code = self.json.get('code') return self class Bootdata: def __init__(self, data: dir): self.json = data self.is_viral_tab_disabled = None ...
# # PySNMP MIB module CISCO-HSRP-CAPABILITY (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-HSRP-CAPABILITY # Produced by pysmi-0.3.4 at Wed May 1 11:59:47 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, single_value_constraint, constraints_union, value_size_constraint, value_range_constraint) ...
# # This file contains the Python code from Program 14.1 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm14_01.txt # class Solution(Obj...
class Solution(Object): def __init__(self): super(Solution, self).__init__() def get_is_feasible(self): pass get_is_feasible = abstractmethod(getIsFeasible) is_feasible = property(fget=lambda self: self.getIsFeasible()) def get_is_complete(self): pass get_is_complete =...
def get_urls(*args, **kwargs): return { 'https://raw.githubusercontent.com/ionelmc/python-lazy-object-proxy/master/CHANGELOG.rst' }, set()
def get_urls(*args, **kwargs): return ({'https://raw.githubusercontent.com/ionelmc/python-lazy-object-proxy/master/CHANGELOG.rst'}, set())
class NotInHandError(Exception): def __init__(self, card: str): self.card = card self.message = f"Card '{card}' not found in player hand!" super().__init__(self.message)
class Notinhanderror(Exception): def __init__(self, card: str): self.card = card self.message = f"Card '{card}' not found in player hand!" super().__init__(self.message)
# firmware errors LCE_NO_ERROR = 0x00 LCE_USB_EP5_TX_WHILE_INBUF_WRITTEN = 0x01 LCE_USB_EP0_SENT_STALL = 0x04 LCE_USB_EP5_OUT_WHILE_OUTBUF_WRITTEN = 0x05 LCE_USB_EP5_LEN_TOO_BIG = 0x06 LCE_USB_EP5_GOT_CRAP = 0x07 LCE_USB_EP5_STALL ...
lce_no_error = 0 lce_usb_ep5_tx_while_inbuf_written = 1 lce_usb_ep0_sent_stall = 4 lce_usb_ep5_out_while_outbuf_written = 5 lce_usb_ep5_len_too_big = 6 lce_usb_ep5_got_crap = 7 lce_usb_ep5_stall = 8 lce_usb_data_leftover_flags = 9 lce_rf_rxovf = 16 lce_rf_txunf = 17 lce_dropped_packet = 18 lce_rftx_never_tx = 19 lce_rf...
''' Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Example 1: Input: s = "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome. Example 2: Input: s = "race a car" Output: false Explanation: "raceacar" is no...
""" Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Example 1: Input: s = "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome. Example 2: Input: s = "race a car" Output: false Explanation: "raceacar" is no...
DEFAULT_ARGS_ORDER = ( 'code', 'network_name', 'subnet_name', 'tx', 'block', 'magic_header', 'default_port', 'dns_bootstrap', 'ui', 'extras' ) class Network(object): def __init__(self, *args, **kwargs): for arg, name in zip(args, DEFAULT_ARGS_ORDER): kwargs[name] = arg ...
default_args_order = ('code', 'network_name', 'subnet_name', 'tx', 'block', 'magic_header', 'default_port', 'dns_bootstrap', 'ui', 'extras') class Network(object): def __init__(self, *args, **kwargs): for (arg, name) in zip(args, DEFAULT_ARGS_ORDER): kwargs[name] = arg for (k, v) in kw...
# [LINK]documentation: http://www.eso.org/projects/alma/develop/acs/OnlineDocs/ACS_Supported_BACI_Types.pdf # section 3.3 monitors; page 16 # dict holding all the possible properties props = dict() GLOBAL_FREQ = 10000000 QUEUE_FREQ = 10000000 # ------------------------------------------------------------------ # proper...
props = dict() global_freq = 10000000 queue_freq = 10000000 props['doubleRWProp:TEST_JAVA_T1'] = {'Polling': {'polling_command': '.doubleRWProp.get_sync()[0]', 'additional_parameters': {'polling_interval': 10000000}}, 'Monitor': {'monitoring_command': '.doubleRWProp', 'additional_parameters': {'timer_trigger_interval':...
class Flutes: error = None actual = None def __init__(self, error, actual): self.error = error self.actual = actual def get_error(self): return self.error def get_actual(self): return self.actual
class Flutes: error = None actual = None def __init__(self, error, actual): self.error = error self.actual = actual def get_error(self): return self.error def get_actual(self): return self.actual
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( s ) : if ( len ( s ) >= 10 ) : return True for i in range ( 1 , len ( s ) ) : for j in rang...
def f_gold(s): if len(s) >= 10: return True for i in range(1, len(s)): for j in range(i + 1, len(s)): for k in range(j + 1, len(s)): s1 = s[0:i] s2 = s[i:j - i] s3 = s[j:k - j] s4 = s[k:len(s) - k] if s1 ...
# # 1437. Check If All 1's Are at Least Length K Places Away # # Q: https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/ # A: https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/613577/Kt-Js-Py3-Cpp-Last-Seen-Index # class Solution: def kLengthApart(s...
class Solution: def k_length_apart(self, A: List[int], K: int, last=-100000.0) -> bool: for i in range(len(A)): if not A[i]: continue ok = K < i - last last = i if not ok: return False return True
valid_campaigns = [ "mightybear", "dancingdragon", "sillysand", "pretentiouspanda" ] def get_scoring_dict(): return { "unattrib" : { "score" : 1, "list" : [ "unattrib", "misc" ] }, "named" : { "score" : 5, "list" : valid_campaigns }, "top_campaign" : { "score" :...
valid_campaigns = ['mightybear', 'dancingdragon', 'sillysand', 'pretentiouspanda'] def get_scoring_dict(): return {'unattrib': {'score': 1, 'list': ['unattrib', 'misc']}, 'named': {'score': 5, 'list': valid_campaigns}, 'top_campaign': {'score': 7, 'list': ['dancingdragon', 'pretentiouspanda']}, 'specific_malz': {'...
dataset_info = dict( dataset_name='pp', paper_info=dict( ), keypoint_info={ 0: dict(name='products_far_left_top', id=0, color=[51, 153, 255], type='upper', swap='products_far_right_top'), 1: dict( name='products_far_left_bottom', id=1, ...
dataset_info = dict(dataset_name='pp', paper_info=dict(), keypoint_info={0: dict(name='products_far_left_top', id=0, color=[51, 153, 255], type='upper', swap='products_far_right_top'), 1: dict(name='products_far_left_bottom', id=1, color=[51, 153, 255], type='upper', swap='products_far_right_bottom'), 2: dict(name='pro...
# DESCRIPTION # In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge. # If the town judge exists, then: # The town judge trusts nobody. # Everybody (except for the town judge) trusts the town judge. # There is exactly one person that satisfies prope...
class Solution: """ Time: O(N+T), where N is the num of people and T is the size of the trust array Space: O(N), array to see who has the N-1 trust """ def find_judge(self, N: int, trust: List[List[int]]) -> int: town_trust = [0] * (N + 1) for (trustee, trusted) in trust: ...
#Newton - Raphson Method #Equation - f(x) = t - (Summation of(di/(si+c))) #f'(x) = summation of di(si+c)^2 #xj = xi - f(xi)/f'(xi) #Inputs xi=0 n=4 t=10 d = [5,2,3,3] s = [3,2,6,1] #Equation def f(d, s, x): summation = 0 for d, s in zip(d,s): summation += d/(s+x) return summation #Derivative of...
xi = 0 n = 4 t = 10 d = [5, 2, 3, 3] s = [3, 2, 6, 1] def f(d, s, x): summation = 0 for (d, s) in zip(d, s): summation += d / (s + x) return summation def df(d, s, x): summation = 0 for (d, s) in zip(d, s): summation += d / (s + x) ** 2 return summation while True: xj = xi ...
class Sources: ''' Sources class to define sources objects ''' def __init__(self,id,name,description,url,category,language,country): self.id = id self.name = name self.description = description self.url = url self.category = category self.language = langua...
class Sources: """ Sources class to define sources objects """ def __init__(self, id, name, description, url, category, language, country): self.id = id self.name = name self.description = description self.url = url self.category = category self.language ...
class Path: # sfx sfx_click = "assets/sounds/SFX_ButtonUp.wav" sfx_move = "assets/sounds/SFX_PieceMoveLR.wav" sfx_drop = "assets/sounds/SFX_PieceHardDrop.wav" sfx_single = "assets/sounds/SFX_SpecialLineClearSingle.wav" sfx_double = "assets/sounds/SFX_SpecialLineClearDouble.wav" sfx_triple = ...
class Path: sfx_click = 'assets/sounds/SFX_ButtonUp.wav' sfx_move = 'assets/sounds/SFX_PieceMoveLR.wav' sfx_drop = 'assets/sounds/SFX_PieceHardDrop.wav' sfx_single = 'assets/sounds/SFX_SpecialLineClearSingle.wav' sfx_double = 'assets/sounds/SFX_SpecialLineClearDouble.wav' sfx_triple = 'assets/so...
def find_distance_value(arr1, arr2, d): count = 0 for i in range(len(arr1)): for j in range(len(arr2)): dis = abs(arr1[i] - arr2[j]) if dis <= d: break else: count += 1 return count print(find_distance_value(arr1=[4, 5, 8], arr2=[10, 9,...
def find_distance_value(arr1, arr2, d): count = 0 for i in range(len(arr1)): for j in range(len(arr2)): dis = abs(arr1[i] - arr2[j]) if dis <= d: break else: count += 1 return count print(find_distance_value(arr1=[4, 5, 8], arr2=[10, 9, 1, ...