content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
__author__ = 'Jeffrey Seifried' __description__ = 'Scraping tools for getting me a damn Nintendo Switch' __email__ = 'jeffrey.seifried@gmail.com' __program__ = 'switch' __url__ = 'http://github.com/jeffseif/{}'.format(__program__) __version__ = '1.0.0' __year__ = '2017' HEADERS = { 'Accept': '*/*', 'Accept-En...
__author__ = 'Jeffrey Seifried' __description__ = 'Scraping tools for getting me a damn Nintendo Switch' __email__ = 'jeffrey.seifried@gmail.com' __program__ = 'switch' __url__ = 'http://github.com/jeffseif/{}'.format(__program__) __version__ = '1.0.0' __year__ = '2017' headers = {'Accept': '*/*', 'Accept-Encoding': 'g...
class FibonacciImpl: arr = [0,1,1] def calculate(self, num: int): if num < len(self.arr): return self.arr[num] else: for i in range(len(self.arr)-1, num): new_fib = self.arr[i-1] + self.arr[i] self.arr.append(new_fib) return se...
class Fibonacciimpl: arr = [0, 1, 1] def calculate(self, num: int): if num < len(self.arr): return self.arr[num] else: for i in range(len(self.arr) - 1, num): new_fib = self.arr[i - 1] + self.arr[i] self.arr.append(new_fib) ret...
class Color(object): def __init__(self, rgb_value, name): self.rgb_value = rgb_value self.name = name if __name__ == "__main__": c = Color("#ff0000", "bright_red") print(c.name) c.name = "red"
class Color(object): def __init__(self, rgb_value, name): self.rgb_value = rgb_value self.name = name if __name__ == '__main__': c = color('#ff0000', 'bright_red') print(c.name) c.name = 'red'
def balanced_brackets(inp): # if odd number, can't be balanced if len(inp) % 2 is not 0: return False # opening brackets opening = set('[{(') s = [] # functions as a stack (last in, first out) for c in inp: # if no items in stack, add first character if len(s) is 0: s.append(c) else: # if ...
def balanced_brackets(inp): if len(inp) % 2 is not 0: return False opening = set('[{(') s = [] for c in inp: if len(s) is 0: s.append(c) elif s[-1] == '[' and c == ']' or (s[-1] == '{' and c == '}') or (s[-1] == '(' and c == ')'): s.pop() elif c in...
class Solution: def pathSum(self, root: TreeNode, sum: int) -> int: if not root: return 0 def dfs(root: TreeNode, sum: int) -> int: if not root: return 0 return (sum == root.val) + \ dfs(root.left, sum - root.val) + \ dfs(root.right, sum - root.val) return d...
class Solution: def path_sum(self, root: TreeNode, sum: int) -> int: if not root: return 0 def dfs(root: TreeNode, sum: int) -> int: if not root: return 0 return (sum == root.val) + dfs(root.left, sum - root.val) + dfs(root.right, sum - root.val)...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # @author JourWon # @date 2022/1/7 # @file ListNode.py def __init__(self, x): self.val = x self.next = None
def __init__(self, x): self.val = x self.next = None
#!/usr/bin/env python def main(): print("Start training") x_array = [1.0, 2.0, 3.0, 4.0, 5.0] # y = 2x + 3 y_array = [5.0, 7.0, 9.0, 11.0, 13.0] instance_number = len(x_array) learning_rate = 0.01 epoch_number = 100 w = 1.0 b = 1.0 for epoch_index in range(epoch_number): w_grad = 0.0 ...
def main(): print('Start training') x_array = [1.0, 2.0, 3.0, 4.0, 5.0] y_array = [5.0, 7.0, 9.0, 11.0, 13.0] instance_number = len(x_array) learning_rate = 0.01 epoch_number = 100 w = 1.0 b = 1.0 for epoch_index in range(epoch_number): w_grad = 0.0 b_grad = 0.0 ...
def chunks(messageLength, chunkSize): chunkValues = [] for i in range(0, len(messageLength), chunkSize): chunkValues.append(messageLength[i:i+chunkSize]) return chunkValues def leftRotate(chunk, rotateLength): return ((chunk << rotateLength) | (chunk >> (32 - rotateLength))) & ...
def chunks(messageLength, chunkSize): chunk_values = [] for i in range(0, len(messageLength), chunkSize): chunkValues.append(messageLength[i:i + chunkSize]) return chunkValues def left_rotate(chunk, rotateLength): return (chunk << rotateLength | chunk >> 32 - rotateLength) & 4294967295 def sha...
''' - Leetcode problem: 937 - Difficulty: Easy - Brief problem description: You have an array of logs. Each log is a space delimited string of words. For each log, the first word in each log is an alphanumeric identifier. Then, either: Each word after the identifier will consist only of lowercase letters, or; Ea...
""" - Leetcode problem: 937 - Difficulty: Easy - Brief problem description: You have an array of logs. Each log is a space delimited string of words. For each log, the first word in each log is an alphanumeric identifier. Then, either: Each word after the identifier will consist only of lowercase letters, or; Ea...
n, k = map(int, input().split()) participants = list(map(int, input().split())) target_score = participants[k - 1] total = 0 for participant in participants: if participant >= target_score and participant > 0: total += 1 print(total)
(n, k) = map(int, input().split()) participants = list(map(int, input().split())) target_score = participants[k - 1] total = 0 for participant in participants: if participant >= target_score and participant > 0: total += 1 print(total)
a,b,c,d = map(int, input().split()) if b > c and d > a and (c+d) > (a+b) and c > 0 and d > 0 and a%2 == 0: print("Valores aceitos") else: print("Valores nao aceitos")
(a, b, c, d) = map(int, input().split()) if b > c and d > a and (c + d > a + b) and (c > 0) and (d > 0) and (a % 2 == 0): print('Valores aceitos') else: print('Valores nao aceitos')
def get_all_directions_values(row, col, board): total = 0 total += int(board[0][col]) total += int(board[-1][col]) total += int(board[row][0]) total += int(board[row][-1]) return total def outside_board(shoot): row, col = shoot return 0 > row or row > 6 or 0 > col or col > 6 def bu...
def get_all_directions_values(row, col, board): total = 0 total += int(board[0][col]) total += int(board[-1][col]) total += int(board[row][0]) total += int(board[row][-1]) return total def outside_board(shoot): (row, col) = shoot return 0 > row or row > 6 or 0 > col or (col > 6) def bu...
bridgelist = [] with open('input.txt') as infile: for line in infile.readlines(): i, o = line.strip().split('/') i, o = int(i), int(o) bridgelist.append((i,o,)) def build_bridge(bridgelist, already_used=None, current_value=0, connector_used=0): if already_used == None: already_u...
bridgelist = [] with open('input.txt') as infile: for line in infile.readlines(): (i, o) = line.strip().split('/') (i, o) = (int(i), int(o)) bridgelist.append((i, o)) def build_bridge(bridgelist, already_used=None, current_value=0, connector_used=0): if already_used == None: alr...
# https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/727/ class Solution: def removeDuplicates(self, nums: list[int]) -> int: length = 0 curNum = None for idx in range(len(nums)): if nums[idx] != curNum: curNum = nums[idx] ...
class Solution: def remove_duplicates(self, nums: list[int]) -> int: length = 0 cur_num = None for idx in range(len(nums)): if nums[idx] != curNum: cur_num = nums[idx] nums[length] = curNum length += 1 return (length, nums)...
class workspaceApiPara: getWorkspace_POST_request = {"ad_group_list": {"type": list, "default": []}} setWorkspace_POST_request = {}, updateWorkspace_POST_request = {}, getWorkspace_GET_response = {}, setWorkspace_POST_response = {} updateWorkspace_POST_response = {}
class Workspaceapipara: get_workspace_post_request = {'ad_group_list': {'type': list, 'default': []}} set_workspace_post_request = ({},) update_workspace_post_request = ({},) get_workspace_get_response = ({},) set_workspace_post_response = {} update_workspace_post_response = {}
expected_output = { "interfaces": { "Port-channel1": { "name": "Port-channel1", "protocol": "lacp", "members": { "GigabitEthernet2": { "interface": "GigabitEthernet2", "oper_key": 1, "admin_key": ...
expected_output = {'interfaces': {'Port-channel1': {'name': 'Port-channel1', 'protocol': 'lacp', 'members': {'GigabitEthernet2': {'interface': 'GigabitEthernet2', 'oper_key': 1, 'admin_key': 1, 'port_num': 1, 'lacp_port_priority': 32768, 'flags': 'SA', 'activity': 'auto', 'state': 'bndl', 'bundled': True, 'port_state':...
# # PySNMP MIB module CONTIVITY-INFO-V1-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CONTIVITY-INFO-V1-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:26:50 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_intersection, constraints_union, single_value_constraint, value_range_constraint) ...
def domain_name(url): st = url.replace("http://", "") tt = st.replace("https://","") ut = tt.replace("www.","") s = ut.split(".") return s[0] print(domain_name("http://github.com/carbonfive/raygun"))
def domain_name(url): st = url.replace('http://', '') tt = st.replace('https://', '') ut = tt.replace('www.', '') s = ut.split('.') return s[0] print(domain_name('http://github.com/carbonfive/raygun'))
fullSWOF2DPath='../FullSWOF_2D' def getFullSWOF2DPath(): return fullSWOF2DPath
full_swof2_d_path = '../FullSWOF_2D' def get_full_swof2_d_path(): return fullSWOF2DPath
# INSTRUCTIONS # ------------ # Create ```config.py``` in this folder, take this file as reference. # ```config.py``` will not be committed to Git, added in .gitignore # Add project settings and API_KEYS here... NEWS_API_KEY = ""
news_api_key = ''
# -*- coding: utf-8 -*- ''' File name: code\maximum_path_sum_ii\sol_67.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #67 :: Maximum path sum II # # For more information see: # https://projecteuler.net/problem=67 # Problem Statement ''...
""" File name: code\\maximum_path_sum_ii\\sol_67.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x """ "\nBy starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.\n37 4\n2 4 6\n8 5 9 3\nThat is, 3 + 7 +...
# # PySNMP MIB module DIFF-SERV-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DIFF-SERV-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:23:07 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_range_constraint, constraints_intersection, constraints_union, value_size_constraint) ...
# 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 class Solution: def hasPathSum(self, root: TreeNode, targetSum: int) -> bool: # return true, if adding up values alo...
class Solution: def has_path_sum(self, root: TreeNode, targetSum: int) -> bool: if not root: return False target_sum -= root.val if not root.left and (not root.right) and (targetSum == 0): return True return self.hasPathSum(root.left, targetSum) or self.hasPa...
USERNAME = 'super.user.1' PASSWORD = 'X!16a99a4e' CONSUMER_KEY = 'f3haancaj0vm4lkx2erk3uwdzy2elz00of513u5w' TOKEN = 'eyJhbGciOiJIUzI1NiJ9.eyIiOiIifQ.Qjz0-kry1Yb7PH0Pw1PbRWrgaqsFYPbac3RHQ-eykk4' # API server URL BASE_URL = "https://openlab.openbankproject.com" API_VERSION = "v3.0.0" CONTENT_JSON =...
username = 'super.user.1' password = 'X!16a99a4e' consumer_key = 'f3haancaj0vm4lkx2erk3uwdzy2elz00of513u5w' token = 'eyJhbGciOiJIUzI1NiJ9.eyIiOiIifQ.Qjz0-kry1Yb7PH0Pw1PbRWrgaqsFYPbac3RHQ-eykk4' base_url = 'https://openlab.openbankproject.com' api_version = 'v3.0.0' content_json = {'content-type': 'application/json'} dl...
class Alerts: def _init_ (self,Alert_Id, Alert_Name, Alert_Code): self.Alert_Id= AlertId self.Alert_Name = Alert_Name self.Alert_Code = Alert_Code
class Alerts: def _init_(self, Alert_Id, Alert_Name, Alert_Code): self.Alert_Id = AlertId self.Alert_Name = Alert_Name self.Alert_Code = Alert_Code
n = int(input('me diga um numero: ')) s = n + 1 a = n - 1 print ('o sucessor de {} e {}'. format(n, s)) print ('o antecessor de {} e {}'.format(n, a))
n = int(input('me diga um numero: ')) s = n + 1 a = n - 1 print('o sucessor de {} e {}'.format(n, s)) print('o antecessor de {} e {}'.format(n, a))
def main(): a = 0 while True: a += 1 if a % 1000 == 0: print(a) if __name__ == "__main__": main()
def main(): a = 0 while True: a += 1 if a % 1000 == 0: print(a) if __name__ == '__main__': main()
def get_words(wordlist, resume=None): with open(wordlist) as f: raw_words = f.read() found_resume = False words = list() for word in raw_words.split(): if resume is not None: if found_resume: words.append(word) else: if word == re...
def get_words(wordlist, resume=None): with open(wordlist) as f: raw_words = f.read() found_resume = False words = list() for word in raw_words.split(): if resume is not None: if found_resume: words.append(word) elif word == resume: ...
def fact(x): if x == 1: return 1 return x * fact(x-1) if __name__=='__main__': print("fact(5) = %s" % fact(5))
def fact(x): if x == 1: return 1 return x * fact(x - 1) if __name__ == '__main__': print('fact(5) = %s' % fact(5))
def extraerDatos(dato): palo = dato[0:1] # Se extrae el primer caracter correspondiente a un palo aux = dato.split(palo) valor = int(aux[1]) # Se extra el valor del caracter if (valor >= 10): # En el envido las cartas de 10 para arriba suman cero valor = 0 r...
def extraer_datos(dato): palo = dato[0:1] aux = dato.split(palo) valor = int(aux[1]) if valor >= 10: valor = 0 return (palo, valor) def contar_envido(carta1, carta2, carta3): (palo1, aux1) = extraer_datos(carta1) (palo2, aux2) = extraer_datos(carta2) (palo3, aux3) = extraer_dato...
class Life: def __init__(self, width, height): self.width = width self.height = height self.frame = [[0 for x in range(width)] for y in range(height)] def import_frame(self, fname): with open(fname, 'r') as f: lines = f.readlines() for i, line in enumerate(l...
class Life: def __init__(self, width, height): self.width = width self.height = height self.frame = [[0 for x in range(width)] for y in range(height)] def import_frame(self, fname): with open(fname, 'r') as f: lines = f.readlines() for (i, line) in enumerate...
class Estadistica: def __init__(self): self.bodega_saladillo = [] self.bodega_saladillo_hora = [] self.bodega_andina = [] self.bodega_andina_hora = [] self.camiones_t2 = [] self.error_bodega = 0 self.barcos_puerto = [] self.ocupacion_trenes = [] ...
class Estadistica: def __init__(self): self.bodega_saladillo = [] self.bodega_saladillo_hora = [] self.bodega_andina = [] self.bodega_andina_hora = [] self.camiones_t2 = [] self.error_bodega = 0 self.barcos_puerto = [] self.ocupacion_trenes = [] ...
# Write a program that reads in three strings and sorts them lexicographically. # Enter a string: Charlie # Enter a string: Able # Enter a string: Baker # Able # Baker # Charlie string1 = str(input("Enter a string: ")) string2 = str(input("Enter a string: ")) string3 = str(input("Enter a string...
string1 = str(input('Enter a string: ')) string2 = str(input('Enter a string: ')) string3 = str(input('Enter a string: ')) if string1 < string2 and string1 < string3: print(string1) if string2 < string3: print(string2) print(string3) else: print(string3) print(string2) elif s...
#!/usr/bin/env python #coding: utf-8 class Solution: # @return a boolean def isValid(self, s): stack = [] for x in s: if x == '(' or x == '{' or x == '[': stack.append(x) else: if not stack: return False y = stack.pop() ...
class Solution: def is_valid(self, s): stack = [] for x in s: if x == '(' or x == '{' or x == '[': stack.append(x) else: if not stack: return False y = stack.pop() if x == ')' and y != '(': ...
def doSubtraction(): a=30 b=20 print(a-b) doSubtraction() #This is Code for Subtraction
def do_subtraction(): a = 30 b = 20 print(a - b) do_subtraction()
o = int(input()) c = -1 for i in range(1000000000000): i = str(i) t = 0 for j in range(len(i)): k = abs(int(i[j - 1]) - int(i[j])) if k > 1: t = 1 break if t: continue c += 1 if c == o: print(i) break
o = int(input()) c = -1 for i in range(1000000000000): i = str(i) t = 0 for j in range(len(i)): k = abs(int(i[j - 1]) - int(i[j])) if k > 1: t = 1 break if t: continue c += 1 if c == o: print(i) break
print('hello world') for item in [1,2,3,4,5,6,'foo','bar','baz']: print('eh') class MyCustomClass(object): arg = None def __init__(arg): self.arg = arg def my_method(self): return self.arg + 1 def more_python(self): return 1 + 1 + 2 def new_method(): return self.arg * arg ...
print('hello world') for item in [1, 2, 3, 4, 5, 6, 'foo', 'bar', 'baz']: print('eh') class Mycustomclass(object): arg = None def __init__(arg): self.arg = arg def my_method(self): return self.arg + 1 def more_python(self): return 1 + 1 + 2 def new_method(): ...
class DocumentDocstring: def __init__(self, expression): self._exp = expression self._docstring = expression.value.s def title(self): return self._docstring.split('\n')[0] def body(self): b = [] skipped_lines = 1 for s in self._docstring.split('\n'): ...
class Documentdocstring: def __init__(self, expression): self._exp = expression self._docstring = expression.value.s def title(self): return self._docstring.split('\n')[0] def body(self): b = [] skipped_lines = 1 for s in self._docstring.split('\n'): ...
class Solution: def romanToInt(self, s: str) -> int: res = 0 last = None for d in s: if d == 'M': res += 800 if last == 'C' else 1000 elif d == 'D': res += 300 if last == 'C' else 500 elif d == 'C': res += 80...
class Solution: def roman_to_int(self, s: str) -> int: res = 0 last = None for d in s: if d == 'M': res += 800 if last == 'C' else 1000 elif d == 'D': res += 300 if last == 'C' else 500 elif d == 'C': res +=...
s = 1 valor = soma = 0 for c in range(2, 101): valor = s / c soma += valor print(f'{soma+1:.2f}')
s = 1 valor = soma = 0 for c in range(2, 101): valor = s / c soma += valor print(f'{soma + 1:.2f}')
a = 18 b = 13 print(a-b) # Answer should be 5
a = 18 b = 13 print(a - b)
# Question: https://projecteuler.net/problem=115 M = 50 T = 10**6 DP1 = [] DP2 = [] for i in range(M): DP1.append(1) DP2.append(0) while DP1[-1] + DP2[-1] <= T: DP1_i = DP1[-1] + DP2[-1] DP2_i = DP1[-M] + DP2[-1] DP1.append(DP1_i) DP2.append(DP2_i) print(len(DP1) - 1) # --- # Even better r...
m = 50 t = 10 ** 6 dp1 = [] dp2 = [] for i in range(M): DP1.append(1) DP2.append(0) while DP1[-1] + DP2[-1] <= T: dp1_i = DP1[-1] + DP2[-1] dp2_i = DP1[-M] + DP2[-1] DP1.append(DP1_i) DP2.append(DP2_i) print(len(DP1) - 1) dp = [] for i in range(M): DP.append(1) DP.append(2) while DP[-1] <= T...
expected_output = { 'event_num': { 2: { 'event_name': '_wdtimer', 'value': '180' }, } }
expected_output = {'event_num': {2: {'event_name': '_wdtimer', 'value': '180'}}}
d = {}; print(len(d)) d = {'k1':'v1', 'k2':'v2'}; print(len(d)) print(iter(d)) for i in iter(d): print(i)
d = {} print(len(d)) d = {'k1': 'v1', 'k2': 'v2'} print(len(d)) print(iter(d)) for i in iter(d): print(i)
print('===== \033[31mDESAFIO 02\033[m =====') dia = input('Dia = ') mes = input('Mes = ') ano = input('Ano = ') print('Voce nasceu no dia \033[33m{}\033[m de \033[33m{}\033[m de \033[33m{}\033[m. Correto?'.format(dia, mes, ano))
print('===== \x1b[31mDESAFIO 02\x1b[m =====') dia = input('Dia = ') mes = input('Mes = ') ano = input('Ano = ') print('Voce nasceu no dia \x1b[33m{}\x1b[m de \x1b[33m{}\x1b[m de \x1b[33m{}\x1b[m. Correto?'.format(dia, mes, ano))
# # PySNMP MIB module ENVIRONMENT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENVIRONMENT-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:05:02 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_intersection, value_range_constraint, single_value_constraint, constraints_union) ...
# def combine_all(input): # check1 = False # check2 = False # check3 = False # if len(input) > 0: # if input[0] == 'a': # check1 = True # # main_s = [] # tmp_dict = {} # for item in input: # tmp_dict[item] = "0" # if item not in ['a', 'b']: # r...
def longest_palidrom_substr(input_str): l = 0 r = len(input_str) counter = 0 while counter < r: if input_str[counter:r] == input_str[counter:r][::-1]: return input_str[counter:r] counter = counter + 1 counter = len(input_str) while counter > l: if input_str[l:...
myApp = App("chrome.app") if not myApp.window(): # chrome not open App.open("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe") wait(10) myApp.focus() wait(1) wait("1392883544404.png", FOREVER) click("1392883741646.png") type("http://10.112.18.28/testcases/symbol/BoxMarkerSymbol.html\n") w...
my_app = app('chrome.app') if not myApp.window(): App.open('C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe') wait(10) myApp.focus() wait(1) wait('1392883544404.png', FOREVER) click('1392883741646.png') type('http://10.112.18.28/testcases/symbol/BoxMarkerSymbol.html\n') wait('1392884154681.png'...
#!/usr/bin/env python appd_auth = { 'controller': '', 'account': '', 'user': '', 'password': '' } APPD_APP = '' APPD_TIER = ''
appd_auth = {'controller': '', 'account': '', 'user': '', 'password': ''} appd_app = '' appd_tier = ''
print("Hello World!") print ("Hello Again") print("I like typing this.") print("This is fun.") print('Yay! Printing.') print("I'd much rather you 'not'.") print('I "said" do not touch this.') print('this command will print one line') print('this\n command\n will\n print\n multiple\n lines') # print('nevermind') # --O...
print('Hello World!') print('Hello Again') print('I like typing this.') print('This is fun.') print('Yay! Printing.') print("I'd much rather you 'not'.") print('I "said" do not touch this.') print('this command will print one line') print('this\n command\n will\n print\n multiple\n lines')
# Not runnable end_point = "team/frc254" url = f"https://www.thebluealliance.com/api/v3/{end_point}" "https://www.thebluealliance.com/api/v3/team/frc254"
end_point = 'team/frc254' url = f'https://www.thebluealliance.com/api/v3/{end_point}' 'https://www.thebluealliance.com/api/v3/team/frc254'
class DoublyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None self.prev = None def to_str(head): data = [] while head: data.append(str(head.data)) head = head.next return ', '.join(data) def reverse_recursive(head): if h...
class Doublylinkedlistnode: def __init__(self, node_data): self.data = node_data self.next = None self.prev = None def to_str(head): data = [] while head: data.append(str(head.data)) head = head.next return ', '.join(data) def reverse_recursive(head): if he...
class Piece: def __init__(self, index: int, piece_hash: bytes, piece_length: int, block_length: int): self.index = index self.hash = piece_hash self.piece_length = piece_length self.block_length = block_length self.blocks = [Block(i, i*block_length, block_le...
class Piece: def __init__(self, index: int, piece_hash: bytes, piece_length: int, block_length: int): self.index = index self.hash = piece_hash self.piece_length = piece_length self.block_length = block_length self.blocks = [block(i, i * block_length, block_length) for i in ...
a = list1[0] list1[0] = "def" list1.remove ( 3 ) list1.append ( 4 ) print ( list1 ) del list1[1:2] print ( list1 )
a = list1[0] list1[0] = 'def' list1.remove(3) list1.append(4) print(list1) del list1[1:2] print(list1)
n = int(input()) v = [] trocas = 0 for i in range (n): for j in range (5): #para coletar os elementos do vetor v.append(int(input())) for j in range (5): #para ordenar o vetor for k in range (4): if v[k] > v[k+1]: t = v[k] v[k] = v[k+1] ...
n = int(input()) v = [] trocas = 0 for i in range(n): for j in range(5): v.append(int(input())) for j in range(5): for k in range(4): if v[k] > v[k + 1]: t = v[k] v[k] = v[k + 1] v[k + 1] = t trocas = trocas + 1 prin...
junk_drawer = [3, 4] # Using the list provided, add a pen, a scrap paper, a 7.3 and a True element ____ # ____ # ____ # ____ # What's the length of the list now? # Save it in an object named drawer_length # ____ = ____ # Slice the junk_drawer object to include the element 4 to scrap paper # Save this in an ob...
junk_drawer = [3, 4] ____
# dictionary = {key: value for element in iterable} fruits = ['apple', 'kiwi', 'banana', 'orange', 'apricot'] fruit_dict = {element: len(element) for element in fruits if len(element) > 5} print('\n'.join("{} {}".format(element, leng) for (element, leng) in fruit_dict.items()))
fruits = ['apple', 'kiwi', 'banana', 'orange', 'apricot'] fruit_dict = {element: len(element) for element in fruits if len(element) > 5} print('\n'.join(('{} {}'.format(element, leng) for (element, leng) in fruit_dict.items())))
class QueryOperatorProcessor(object): def __init__(self, dispatcher): self.dispatcher = dispatcher def process(self, child_nodes): raise NotImplementedError() def _process_node(self, node): return self.dispatcher.dispatch(node) def _process_all_nodes(self, nodes): ...
class Queryoperatorprocessor(object): def __init__(self, dispatcher): self.dispatcher = dispatcher def process(self, child_nodes): raise not_implemented_error() def _process_node(self, node): return self.dispatcher.dispatch(node) def _process_all_nodes(self, nodes): r...
# SPDX-License-Identifier: MIT # Copyright (c) 2021 Akumatic # # https://adventofcode.com/2021/day/17 def read_file(filename: str = "input.txt") -> list: with open(f"{__file__.rstrip('code.py')}{filename}", "r") as f: lines = [s[2:].split("..") for s in f.read().strip().replace("target area: ", "").split("...
def read_file(filename: str='input.txt') -> list: with open(f"{__file__.rstrip('code.py')}{filename}", 'r') as f: lines = [s[2:].split('..') for s in f.read().strip().replace('target area: ', '').split(', ')] return [(int(lines[0][0]), int(lines[0][1])), (int(lines[1][0]), int(lines[1][1]))] def fire_p...
x = 0; for i in range(1000000): x = x + 1;
x = 0 for i in range(1000000): x = x + 1
N = int(input()) a = list(map(int, input().split())) t = [] for i in range(N): t.append([a[i], i]) t.sort(key=lambda x: x[0]) for i in t[::-1]: print(i[1] + 1)
n = int(input()) a = list(map(int, input().split())) t = [] for i in range(N): t.append([a[i], i]) t.sort(key=lambda x: x[0]) for i in t[::-1]: print(i[1] + 1)
#retomando clase pasada #Estructura de datos ################################# #listas otra_lista = [1, 2, 3, 4 , 5, 6] #Accediendo a los elementos de una lista print(otra_lista[0]) print(otra_lista[-1]) #Slicing print(otra_lista[0:3]) print(otra_lista[3:]) copia_lista = otra_lista copia_lista.append(7) print(o...
otra_lista = [1, 2, 3, 4, 5, 6] print(otra_lista[0]) print(otra_lista[-1]) print(otra_lista[0:3]) print(otra_lista[3:]) copia_lista = otra_lista copia_lista.append(7) print(otra_lista) print(copia_lista) if True: print('Es verdad') semaforo = 'rojo' if semaforo == 'rojo': print('detenido') elif semaforo == 'ver...
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: dp = [1]*len(nums) for i in range(1,len(nums)): for j in range(i): if nums[i] > nums[j]: dp[i] = max( dp[i], dp[j]+1 ) return max(dp) class S...
class Solution: def length_of_lis(self, nums: List[int]) -> int: dp = [1] * len(nums) for i in range(1, len(nums)): for j in range(i): if nums[i] > nums[j]: dp[i] = max(dp[i], dp[j] + 1) return max(dp) class Solutionii: def length_of_lis...
def can_make_arithmetic_progression(arr): arr = sorted(arr) prev_diff = arr[1] - arr[0] for i in range(1, len(arr)): difference = arr[i] - arr[i - 1] if not difference == prev_diff: return False prev_diff = difference return True print(can_make_arithmetic_progre...
def can_make_arithmetic_progression(arr): arr = sorted(arr) prev_diff = arr[1] - arr[0] for i in range(1, len(arr)): difference = arr[i] - arr[i - 1] if not difference == prev_diff: return False prev_diff = difference return True print(can_make_arithmetic_progression(...
model_status = [ { 'code': 0, 'description': 'Model uploaded'}, { 'code': 1, 'description': 'File csv uploaded'}, { 'code': 2, 'description': 'Send to elm'}, { 'code': 3, 'description': 'Training', 'perc': 0}, { 'code': 4, 'description': 'Done'} ]
model_status = [{'code': 0, 'description': 'Model uploaded'}, {'code': 1, 'description': 'File csv uploaded'}, {'code': 2, 'description': 'Send to elm'}, {'code': 3, 'description': 'Training', 'perc': 0}, {'code': 4, 'description': 'Done'}]
class CmfParseError(Exception): def __init__(self, parseinfo, msg): self.message = '({}:{}) Error: {}'.format( parseinfo.line + 1, parseinfo.pos, msg) def __str__(self): return self.message
class Cmfparseerror(Exception): def __init__(self, parseinfo, msg): self.message = '({}:{}) Error: {}'.format(parseinfo.line + 1, parseinfo.pos, msg) def __str__(self): return self.message
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. def Watermelon(i): w =i result = "YES" if w%2 == 0 and w > 2 else "NO" print(result + " " + str(i))...
def watermelon(i): w = i result = 'YES' if w % 2 == 0 and w > 2 else 'NO' print(result + ' ' + str(i)) watermelon(int(input()))
matrix = ["1.1 2.2 3.3", "4.4 5.5 6.6", "7.7 8.8 9.9"] def transpose(matrix): return [" ".join(row.split()[i] for row in matrix) for i in range(len(matrix))] print(transpose(matrix))
matrix = ['1.1 2.2 3.3', '4.4 5.5 6.6', '7.7 8.8 9.9'] def transpose(matrix): return [' '.join((row.split()[i] for row in matrix)) for i in range(len(matrix))] print(transpose(matrix))
print('Meta definition') class Meta(type): def __new__(mcs, name, bases, namespace): print('Meta __new__:', mcs, name, namespace) ret = type.__new__(mcs, name, bases, namespace) # class creation print('Meta __new__ ret:', ret) return ret def __init__(cls, name, bases=None, na...
print('Meta definition') class Meta(type): def __new__(mcs, name, bases, namespace): print('Meta __new__:', mcs, name, namespace) ret = type.__new__(mcs, name, bases, namespace) print('Meta __new__ ret:', ret) return ret def __init__(cls, name, bases=None, namespace=None): ...
print("Input: ",end="") a, b, t = 2020, 2021, int(input()) for i in range(t): n = int(input("\n")) def sum(x, a, b, check, n): if x > n: return if check[x]: return check[x] = True sum(x + a, a, b, check, n) sum(x + b, a, b, check, n) def...
print('Input: ', end='') (a, b, t) = (2020, 2021, int(input())) for i in range(t): n = int(input('\n')) def sum(x, a, b, check, n): if x > n: return if check[x]: return check[x] = True sum(x + a, a, b, check, n) sum(x + b, a, b, check, n) def...
class PROJECT(object): NAME = "leafytracker" DESC = "A set of tools to aggregate Leafy Games' developer posts for PULSAR: Lost Colony." URL = "https://github.com/TomRichter/leafytracker" VERSION = "0.0.0"
class Project(object): name = 'leafytracker' desc = "A set of tools to aggregate Leafy Games' developer posts for PULSAR: Lost Colony." url = 'https://github.com/TomRichter/leafytracker' version = '0.0.0'
a=input().split(" ") b=input().split(" ") A=0 B=0 for i in range(len(a)): num1=int(a[i]) num2=int(b[i]) if(num1>num2): A+=1 elif(num1<num2): B+=1 print(A, B)
a = input().split(' ') b = input().split(' ') a = 0 b = 0 for i in range(len(a)): num1 = int(a[i]) num2 = int(b[i]) if num1 > num2: a += 1 elif num1 < num2: b += 1 print(A, B)
# app config APP_CONFIG=dict( SECRET_KEY="SECRET", WTF_CSRF_SECRET_KEY="SECRET", # Webservice config WS_URL="http://localhost:5058", # ws del modello in locale DATASET_REQ = "/dataset", OPERATIVE_CENTERS_REQ = "/operative-centers", OC_DATE_REQ = "/oc-date", OC_DATA_REQ = "/oc-data", PREDICT_REQ = "/p...
app_config = dict(SECRET_KEY='SECRET', WTF_CSRF_SECRET_KEY='SECRET', WS_URL='http://localhost:5058', DATASET_REQ='/dataset', OPERATIVE_CENTERS_REQ='/operative-centers', OC_DATE_REQ='/oc-date', OC_DATA_REQ='/oc-data', PREDICT_REQ='/predict', OPERATORS_RANK_REQ='/ops-rank/', SEND_REAL_Y_REQ='/store-real-y/', SEND_LOGIN_R...
#encoding:utf-8 subreddit = 'mildlyvagina' t_channel = '@r_mildlyvagina' def send_post(submission, r2t): return r2t.send_simple(submission)
subreddit = 'mildlyvagina' t_channel = '@r_mildlyvagina' def send_post(submission, r2t): return r2t.send_simple(submission)
num1, num2 = list(map(int, input().split())) if num1 < num2: print(num1, num2) else: print(num2, num1)
(num1, num2) = list(map(int, input().split())) if num1 < num2: print(num1, num2) else: print(num2, num1)
def main(): print('Hola, mundo') if __name__ =='__main__': main()
def main(): print('Hola, mundo') if __name__ == '__main__': main()
env = None pg = None surface = None width = None height = None # __pragma__ ('opov') def init(environ): global env, pg, surface, width, height env = environ pg = env['pg'] surface = env['surface'] width = env['width'] height = env['height'] tests = [test_transform_rotate, te...
env = None pg = None surface = None width = None height = None def init(environ): global env, pg, surface, width, height env = environ pg = env['pg'] surface = env['surface'] width = env['width'] height = env['height'] tests = [test_transform_rotate, test_transform_rotozoom, test_transform_...
__author__ = 'vcaen' class Item(object): def __init__(self, title, short_desc, desc, picture): self.title = title self.short_desc = short_desc self.desc = desc self.picture = picture class Work(Item): def __init__(self, title, short_desc, desc, date_begin, date_end, company...
__author__ = 'vcaen' class Item(object): def __init__(self, title, short_desc, desc, picture): self.title = title self.short_desc = short_desc self.desc = desc self.picture = picture class Work(Item): def __init__(self, title, short_desc, desc, date_begin, date_end, company, ...
# https://leetcode.com/problems/counting-words-with-a-given-prefix/ class Solution: def prefixCount(self, words: List[str], pref: str) -> int: res = 0 for each in words: if len(each) >= len(pref): if each[:len(pref)] == pref: res += ...
class Solution: def prefix_count(self, words: List[str], pref: str) -> int: res = 0 for each in words: if len(each) >= len(pref): if each[:len(pref)] == pref: res += 1 return res
class RollingHash: def __init__(self, text, pattern_size): self.text = text self.pattern_size = pattern_size self.hash = RollingHash.hash_text(text, pattern_size) self.start = 0 self.end = pattern_size self.alphabet = 26 def move_window(self): if self.end...
class Rollinghash: def __init__(self, text, pattern_size): self.text = text self.pattern_size = pattern_size self.hash = RollingHash.hash_text(text, pattern_size) self.start = 0 self.end = pattern_size self.alphabet = 26 def move_window(self): if self.en...
class ImageAdapter: @staticmethod def to_network_input(dataset): return (dataset - 127.5) / 127.5 @staticmethod def to_image(normalized_images): images = normalized_images * 127.5 + 127.5 return images.astype(int)
class Imageadapter: @staticmethod def to_network_input(dataset): return (dataset - 127.5) / 127.5 @staticmethod def to_image(normalized_images): images = normalized_images * 127.5 + 127.5 return images.astype(int)
BULBASAUR = 0x01 IVYSAUR = 0x02 VENUSAUR = 0x03 CHARMANDER = 0x04 CHARMELEON = 0x05 CHARIZARD = 0x06 SQUIRTLE = 0x07 WARTORTLE = 0x08 BLASTOISE = 0x09 CATERPIE = 0x0a METAPOD = 0x0b BUTTERFREE = 0x0c WEEDLE = 0x0d KAKUNA = 0x0e BEEDRILL = 0x0f PIDGEY = 0x10 PIDGEOTTO = 0x11 PIDGEOT = 0...
bulbasaur = 1 ivysaur = 2 venusaur = 3 charmander = 4 charmeleon = 5 charizard = 6 squirtle = 7 wartortle = 8 blastoise = 9 caterpie = 10 metapod = 11 butterfree = 12 weedle = 13 kakuna = 14 beedrill = 15 pidgey = 16 pidgeotto = 17 pidgeot = 18 rattata = 19 raticate = 20 spearow = 21 fearow = 22 ekans = 23 arbok = 24 p...
input() A = {int(param) for param in input().split()} B = {int(param) for param in input().split()} print(len(A-B)) for i in sorted(A-B): print(i, end = ' ')
input() a = {int(param) for param in input().split()} b = {int(param) for param in input().split()} print(len(A - B)) for i in sorted(A - B): print(i, end=' ')
languages = ['Chamorro', 'Tagalog', 'English', 'russian'] print(languages) languages.append('Spanish') print(languages) languages.insert(0, 'Finish') print(languages) del languages[0] print(languages) popped_language = languages.pop(0) print(languages) print(popped_language) popped_language = languages.pop(0) prin...
languages = ['Chamorro', 'Tagalog', 'English', 'russian'] print(languages) languages.append('Spanish') print(languages) languages.insert(0, 'Finish') print(languages) del languages[0] print(languages) popped_language = languages.pop(0) print(languages) print(popped_language) popped_language = languages.pop(0) print(lan...
''' Created on Oct 5, 2011 @author: IslamM '''
""" Created on Oct 5, 2011 @author: IslamM """
SOURCES = { "activity.task.error.generic": "CommCareAndroid", "app.handled.error.explanation": "CommCareAndroid", "app.handled.error.title": "CommCareAndroid", "app.key.request.deny": "CommCareAndroid", "app.key.request.grant": "CommCareAndroid", "app.key.request.message": "CommCareAndroid", ...
sources = {'activity.task.error.generic': 'CommCareAndroid', 'app.handled.error.explanation': 'CommCareAndroid', 'app.handled.error.title': 'CommCareAndroid', 'app.key.request.deny': 'CommCareAndroid', 'app.key.request.grant': 'CommCareAndroid', 'app.key.request.message': 'CommCareAndroid', 'app.menu.display.cond.bad.x...
class Solution: def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool: if root is None: return False targetSum -= root.val if targetSum == 0: if (root.left is None) and (root.right is None): return True return self.has...
class Solution: def has_path_sum(self, root: Optional[TreeNode], targetSum: int) -> bool: if root is None: return False target_sum -= root.val if targetSum == 0: if root.left is None and root.right is None: return True return self.hasPathSum(r...
# -*- coding: utf-8 -*- # @Author: jpch89 # @Email: jpch89@outlook.com # @Date: 2018-06-27 23:59:30 # @Last Modified by: jpch89 # @Last Modified time: 2018-06-28 00:02:38 formatter = '{} {} {} {}' print(formatter.format(1, 2, 3, 4)) print(formatter.format("one", "two", "three", "four")) print(formatter.format(Tru...
formatter = '{} {} {} {}' print(formatter.format(1, 2, 3, 4)) print(formatter.format('one', 'two', 'three', 'four')) print(formatter.format(True, False, False, True)) print(formatter.format(formatter, formatter, formatter, formatter)) print(formatter.format('Try your', 'Own text here', 'Maybe a peom', 'Or a song about ...
'''2. Write a Python program to compute the similarity between two lists. Sample data: ["red", "orange", "green", "blue", "white"], ["black", "yellow", "green", "blue"] Expected Output: Color1-Color2: ['white', 'orange', 'red'] Color2-Color1: ['black', 'yellow'] ''' def find_similiarity(list1, list2): list3 = lis...
"""2. Write a Python program to compute the similarity between two lists. Sample data: ["red", "orange", "green", "blue", "white"], ["black", "yellow", "green", "blue"] Expected Output: Color1-Color2: ['white', 'orange', 'red'] Color2-Color1: ['black', 'yellow'] """ def find_similiarity(list1, list2): list3 = lis...
def get_client_ip(request): client_ip = request.META.get('REMOTE_ADDR', '') return client_ip
def get_client_ip(request): client_ip = request.META.get('REMOTE_ADDR', '') return client_ip
url = "https://customerportal.supermicro.com/Customer/ContentPages/CustOrders.aspx" orderType = "//select[@id='ContentPlaceHolder1_ddlSearchType']" fromDate = "//input[@id='ContentPlaceHolder1_txtFrom']" customerId = "//select[@id='ContentPlaceHolder1_ddlCustomerID']" searchIcon = "//a[@id='linkSearch']" orderTable = "...
url = 'https://customerportal.supermicro.com/Customer/ContentPages/CustOrders.aspx' order_type = "//select[@id='ContentPlaceHolder1_ddlSearchType']" from_date = "//input[@id='ContentPlaceHolder1_txtFrom']" customer_id = "//select[@id='ContentPlaceHolder1_ddlCustomerID']" search_icon = "//a[@id='linkSearch']" order_tabl...
class Solution: def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: dp = [0]*n for i,j,k in bookings: dp[i-1]+=k if j!=n: dp[j]-=k for i in range(1,n): dp[i]+=dp[i-1] return dp
class Solution: def corp_flight_bookings(self, bookings: List[List[int]], n: int) -> List[int]: dp = [0] * n for (i, j, k) in bookings: dp[i - 1] += k if j != n: dp[j] -= k for i in range(1, n): dp[i] += dp[i - 1] return dp
def buildFibonacciSequence(items): actual = 0 next = 1 sequence = [] for index in range(items): sequence.append(actual) actual, next = next, actual+next return sequence
def build_fibonacci_sequence(items): actual = 0 next = 1 sequence = [] for index in range(items): sequence.append(actual) (actual, next) = (next, actual + next) return sequence
class Animation: def __init__(self, sprites, time_interval): self.sprites = tuple(sprites) self.time_interval = time_interval self.index = 0 self.time = 0 def restart_at(self, index): self.time = 0 self.index = index % len(self.sprites) def update(self, dt)...
class Animation: def __init__(self, sprites, time_interval): self.sprites = tuple(sprites) self.time_interval = time_interval self.index = 0 self.time = 0 def restart_at(self, index): self.time = 0 self.index = index % len(self.sprites) def update(self, dt)...
NoOfLines=int(input()) for Row in range(0,NoOfLines): for Column in range(0,NoOfLines): if(Row%2==0 and Column+1==NoOfLines)or(Row%2==1 and Column==0): print("%2d"%(Row+2),end=" ") else: print("%2d"%(Row+1),end=" ") else: print(end="\n") #second code N...
no_of_lines = int(input()) for row in range(0, NoOfLines): for column in range(0, NoOfLines): if Row % 2 == 0 and Column + 1 == NoOfLines or (Row % 2 == 1 and Column == 0): print('%2d' % (Row + 2), end=' ') else: print('%2d' % (Row + 1), end=' ') else: print(end='...
# --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- def get_workspace_dependent_resource_location(location): if location == "centraluseuap": return "eastus" return lo...
def get_workspace_dependent_resource_location(location): if location == 'centraluseuap': return 'eastus' return location
# 1.5 One Away # There are three types of edits that can be performed on strings: # insert a character, remove a character, or replace a character. # Given two strings, write a function to check if they are one edit (or zero edits) away. def one_away(string_1, string_2): if string_1 == string_2: return ...
def one_away(string_1, string_2): if string_1 == string_2: return True if one_insert_away(string_1, string_2): return True if one_removal_away(string_1, string_2): return True if one_replacement_away(string_1, string_2): return True return False def one_insert_away(s...
def permune(orignal, chosen): if not orignal: print(chosen) else: for i in range(len(orignal)): c=orignal[i] chosen+=c lt=list(orignal) lt.pop(i) orignal=''.join(lt) permune(orignal,chosen) orignal=orignal[:i]+c+orignal[i:] chosen=chosen[:len(chosen)-1] permune('lit','')
def permune(orignal, chosen): if not orignal: print(chosen) else: for i in range(len(orignal)): c = orignal[i] chosen += c lt = list(orignal) lt.pop(i) orignal = ''.join(lt) permune(orignal, chosen) orignal = ori...
entity_id = 'sensor.next_train_to_wim' attributes = hass.states.get(entity_id).attributes my_early_train_current_status = hass.states.get('sensor.my_early_train').state scheduled = False # Check if train scheduled for train in attributes['next_trains']: if train['scheduled'] == '07:15': scheduled = Tru...
entity_id = 'sensor.next_train_to_wim' attributes = hass.states.get(entity_id).attributes my_early_train_current_status = hass.states.get('sensor.my_early_train').state scheduled = False for train in attributes['next_trains']: if train['scheduled'] == '07:15': scheduled = True if train['status'] != ...
class Node: def __init__(self,key=None,val=None,nxt=None,prev=None): self.key = key self.val = val self.nxt = nxt self.prev = prev class DLL: def __init__(self): self.head = Node() self.tail = Node() self.head.nxt = self.tail self.tail.prev = self...
class Node: def __init__(self, key=None, val=None, nxt=None, prev=None): self.key = key self.val = val self.nxt = nxt self.prev = prev class Dll: def __init__(self): self.head = node() self.tail = node() self.head.nxt = self.tail self.tail.prev ...