content
stringlengths
7
1.05M
# Execute o programa 4.4 e experimente alguns valores. Verifique se os resultados foram os mesmos do programa 4.2. # Abaixo cópia do programa 4.4. idade = int(input('Digite a idade do seu carro: ')) if idade <= 3: print('O seu carro é novo!') else: print('O seu carro é velho!')
def diameter_of_binary_tree(root): return diameter_of_binary_tree_func(root)[1] def diameter_of_binary_tree_func(root): """ Diameter for a particular BinaryTree Node will be: 1. Either diameter of left subtree 2. Or diameter of a right subtree 3. Sum of left-height and right-hei...
#Aula 12 #Condição Aninhada nome = str(input('Olá, qual é o seu nome? ')) print ('Seja Bem-Vindo {}!'.format(nome)) nota1 = int(input('{}, Qual foi 1º nota da sua Ac1? '.format(nome))) nota2 = int(input('E da Ac2? ')) nota3 = int(input('E da Ac3? ')) nota4 = int(input('E da Ac4? ')) resultado = ((nota1 + nota2 + n...
debian_os = ['debian', 'ubuntu'] rhel_os = ['redhat', 'centos'] def test_repo_file(host): f = None if host.system_info.distribution.lower() in debian_os: f = host.file('/etc/apt/sources.list.d/powerdns-rec-42.list') if host.system_info.distribution.lower() in rhel_os: f = host.file('/etc/...
class Empty(object): def __bool__(self): return False def __nonzero__(self): return False empty = Empty()
# -*- coding: utf-8 -*- """Provides all the data related to text.""" SAFE_COLORS = [ "#1abc9c", "#16a085", "#2ecc71", "#27ae60", "#3498db", "#2980b9", "#9b59b6", "#8e44ad", "#34495e", "#2c3e50", "#f1c40f", "#f39c12", "#e67e22", "#d35400", "#e74c3c", "#c0...
""" Pipeline defines all steps required by an algorithm to obtain predictions. Pipelines are typically a chain of sklearn compatible transformers and end with an sklearn compatible estimator. """
# Network parameters IMAGE_WIDTH = 84 IMAGE_HEIGHT = 84 NUM_CHANNELS = 4 # dqn inputs 4 image at same time as state
class MyCircularDeque: def __init__(self, k: int): """ Initialize your data structure here. Set the size of the deque to be k. """ self.nums = [0] * k self.k = k self.size = 0 self.front = -1 self.back = 0 def insertFront(self, value: in...
""" Name: Josh Hickman Pawprint: hickmanjv Assignment: Challenge: Cipher Date: 04/17/20 """ # Cipher based on assignment requirements CIPHER = {'a' : '0', 'b' : '1', 'c' : '2', 'd' : '3', 'e' : '4', 'f' : '5', 'g' : '6', 'h' : '7', 'i' : '8', 'j' : '9', 'k' : '!', 'l' : '@', 'm' : '#', 'n' : '$', 'o' : '%', 'p' ...
def parse_input(raw_input): return [ # strip multiline strings when testing [line.strip() for line in group.split('\n')] for group in raw_input.split('\n\n') ] with open('inputs/input6.txt') as file: input6 = parse_input(file.read()) def count_any_yeses(groups): return sum( ...
game_name = input("The name of the game:") num_timesteps = input("The num of timesteps:") total_gpu_num = 3 gpu_use_index = 0 print('conda activate openaivezen; cd baselines; ' + 'CUDA_VISIBLE_DEVICES={} '.format(gpu_use_index) + 'python -m baselines.run --alg=deepq ' + '--env={}NoFrameskip-v4 --num...
# Crie um programa que leia o nome e o preço de vários produtos. O programa devera perguntar # se o utilizador vai continuar. No final, mostre: # # a) Qual é o total gasto na compra # b) Quantos produtos custam mais de 1000 reais # c) Qual é o nome do produto mais barato nome_barato = ' ' cont_produtos = preço_barato =...
print(" Calculator \n") print(" ") num1 = float(input("Please enter your first number: ")) op = input("Please enter your o...
class PrimesBelow: def __init__(self, bound): self.candidate_numbers = list(range(2,bound)) def __iter__(self): return self def __next__(self): if len(self.candidate_numbers) == 0: raise StopIteration next_prime = self.candidate_numbers...
# -*- coding: utf-8 -*- def Mag_V_L(I, RL, Ro, w, C): return I * (1/(1/RL + 1/Ro)) / (1 + (w * (1/(1/RL + 1/Ro)) * C)**2)**.5 def Mag_I_L(I, RL, Ro, w, C): I_L = 1 / RL * I / (1 / Ro + 1 / RL + 1j * w * C) return abs(I_L) def Z_o_from_VLa_VLb(RLa, RLb, VLa, VLb): Z_o = (RLa * RLb * (VLb - VLa)) / (VLa * RL...
# Sage version information for Python scripts # This file is auto-generated by the sage-update-version script, do not edit! version = '9.6.beta6' date = '2022-03-27' banner = 'SageMath version 9.6.beta6, Release Date: 2022-03-27'
w_dic = {'example': 'eg', 'Example': 'eg', 'important': 'imp', 'Important': 'Imp', 'mathematics': 'math', 'Mathematics': 'Math', 'algorithm': 'algo', 'Algorithm': 'Algo', 'frequency': 'freq', 'Frequency': 'Freq', 'input': 'i/p', 'Input': 'i/p', 'output': 'o/p', 'Output': 'o/p',...
# -*- coding: utf-8 -*- """ meraki_sdk This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ). """ class UpdateOrganizationBrandingPoliciesPrioritiesModel(object): """Implementation of the 'updateOrganizationBrandingPoliciesPriorities' model. TODO: t...
class Edge: def __init__(self, dest, capa): self.dest = dest self.capa = capa self.rmng = capa class Node: def __init__(self, name, level=0, edges=None): self.name = name self.level = level if edges is None: self.edges = [] def add_edge(self, de...
def insertion_sort(lst): """Returns a sorted array. A provided list will be sorted out of place. Returns a new list sorted smallest to largest.""" for i in range (1, len(lst)): current_idx = i temp_vlaue = lst[i] while current_idx > 0 and lst[current_idx - 1] > temp_vlaue: ...
src = Split(''' cli.c dumpsys.c ''') component = aos_component('cli', src) component.add_component_dependencis('kernel/hal') component.add_global_macro('HAVE_NOT_ADVANCED_FORMATE') component.add_global_macro('CONFIG_AOS_CLI') component.add_global_includes('include')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 16 10:32:58 2019 @author: allen """
# USITTAsciiParser # # by Claude Heintz # copyright 2014 by Claude Heintz Design # # see license included with this distribution or # https://www.claudeheintzdesign.com/lx/opensource.html ##### This is an abstract class for parsing strings to extract # data formatted as specified in: # # ASCII Text Represen...
SUCCESS_RESPONSE_CODE = 'Success' METHOD_NOT_ALLOWED = 'Failure' UNAUTHORIZED = 'Warning' SUCCESS_RESPONSE_CREATED = 'Success' PAGE_NOT_FOUND = 'Error' INTERNAL_SERVER_ERROR = 'Error' BAD_REQUEST_CODE = 'Error' SUCCESS_MESSAGE = 'Success' FAILURE_MESSAGE = 'Failure'
class Stream(MarshalByRefObject): """ Provides a generic view of a sequence of bytes. """ def ZZZ(self): """hardcoded/mock instance of the class""" return Stream() instance=ZZZ() """hardcoded/returns an instance of the class""" def BeginRead(self,buffer,offset,count,callback,state): """ BeginRead(...
class Solution(object): def intToRoman(self, num): """ :type num: int :rtype: str """ roman = {1: 'I', 5: 'V', 10: 'X', 50: 'L', 100: 'C', 500: 'D', 1000: 'M', 5000: ''} ret = '' for i, s in enumerate(str(num)[::-1]): if s in ['4', '9']: ...
#!/usr/bin/env python """Docstring""" __author__ = "Petar Stoyanov" def main(): """Docstring""" text = input().lower() search_term = input().lower() counter = 0 index = 0 while True: if text.find(search_term, index) == -1: break else: counter += 1 ...
"""Test data files.""" def test(): pass
#!/usr/bin/env python """ https://leetcode.com/problems/implement-strstr/description/ Created on 2018-11-13 @author: 'Jiezhi.G@gmail.com' Reference: """ class Solution: def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ ...
def phonehome(): relax() sleep(1) i01.setHeadSpeed(1.0,1.0,1.0,1.0,1.0) i01.setArmSpeed("left",1.0,1.0,1.0,1.0) i01.setArmSpeed("right",1.0,1.0,1.0,1.0) i01.setHandSpeed("left",1.0,1.0,1.0,1.0,1.0,1.0) i01.setHandSpeed("right",1.0,1.0,1.0,1.0,1.0,1.0) i01.setTorsoSpeed(1.0,1.0,1.0) i01.moveHead(160,68...
class Script(object): START_MSG = """<b>Hy {},എന്റെ പേര് Carla ◢ ◤! 🤭 എന്നെ നിർമിച്ചിരിക്കുന്നത് മൂവി ക്ലബ്‌ ഗ്രൂപ്പിലേക്ക് ആണ്. എന്തായാലും സ്റ്റാർട്ട് അടിച്ചതല്ലെ ഇനി ആ താഴെ കാണുന്ന നമ്മുടെ ഒഫീഷ്യൽ ചന്നെൽ കൂടി Subscribe ചെയ്തിട്ട് പൊക്കോ...🤣🤣</b> """ HELP_MSG = """ <b>നീ ഏതാ..... ഒന്ന് പോടെയ് അവൻ help ...
n1 = int(input('Digite um Valor: ')) n2 = int(input('Digite outro valor: ')) n = n1 + n2 print('A soma entre {} e {} resulta em: {} !'.format(n1,n2,n)) print(type(n1))
class JUMP_GE: def __init__(self, stack): self.phase = 0 self.ip = 0 self.stack = stack self.a = 0 def exec(self, ip, data): if (self.phase == 0): self.ip = ip + 1 self.a = self.stack.pop() self.phase = 1 return False ...
class TriggerListener(object): def __init__(self, state_machine, **kwargs): self._state_machine = state_machine def __call__(self, msg): self._state_machine.trigger(msg.data)
# 78. Subsets # Runtime: 32 ms, faster than 85.43% of Python3 online submissions for Subsets. # Memory Usage: 14.3 MB, less than 78.59% of Python3 online submissions for Subsets. class Solution: # Cascading def subsets(self, nums: list[int]) -> list[list[int]]: res = [[]] for n in nums: ...
def on_enter(event_data): """ """ pocs = event_data.model # Clear any current observation pocs.observatory.current_observation = None pocs.observatory.current_offset_info = None pocs.next_state = 'parked' if pocs.observatory.has_dome: pocs.say('Closing dome') if not pocs.o...
""" Nothing, but in a friendly way. Good for filling in for objects you want to hide. If $form.f1 is a RecursiveNull object, then $form.f1.anything["you"].might("use") will resolve to the empty string. This module was contributed by Ian Bicking. """ class RecursiveNull(object): def __getattr__(self, attr): ...
class BitVector(object): """docstring for BitVector""" """infinite array of bits is present in bitvector""" def __init__(self): self.BitNum=0 self.length=0 def set(self,i): self.BitNum=self.BitNum | 1 << i self.length=self.BitNum.bit_length() def reset(self,i): resetValue=1<<i self.BitNum=self.BitNum ...
class Constand_Hs: HEADERSIZE=1024 Dangkyvantay=str('FDK') Dangkythetu=str('CDK') Van_tay_mo_tu_F=str('Fopen\n') Van_tay_dong_tu_F=str('Fclose\n') Van_Tay_Su_Dung_Tu=str('Fused\n') The_Tu_Su_Dung_Tu=str('Cused\n') Van_tay_mo_tu_C=str('Copen') Van_tay_dong_tu_C=str('Cclose') Serve...
'''Задание 25 № 27422 Напишите программу, которая ищет среди целых чисел, принадлежащих числовому отрезку [174457; 174505], числа, имеющие ровно два различных натуральных делителя, не считая единицы и самого числа. Для каждого найденного числа запишите эти два делителя в две соседних столбца на экране с новой строки в...
list1 = ['phisics','chemistry',1997,2000] print("Value available at index 2 is ", list1[2]) list1[2] = 2003 print("New Value available at index 2 is ", list1[2])
expected_output = { 'mst_instances': { 6: { 'bridge_address': '5897.bdff.3b3a', 'bridge_priority': 20486, 'interfaces': { 'GigabitEthernet1/7': { 'cost': 20000, 'counters': { 'bpdu_received': ...
#It is highly recommended that you check your code first in IDLE first for syntax errors and then Test it here. #If your code has syntax errors ,Open-Palm will freeze. You have to restart it in that case def check_even(n): if n%2 == 0: return True else: return False
def expand(maze, fill): length=len(maze) res=[[fill]*(length*2) for i in range(length*2)] for i in range(length//2, length//2+length): for j in range(length//2, length//2+length): res[i][j]=maze[i-length//2][j-length//2] return res
# -*- coding: utf-8 -*- """ Branca plugins -------------- Add different objects/effects in a branca webpage. """ __all__ = []
def print_id(**kwarg): return ' '.join(kwarg.values()) print(print_id(name=input('Введите своё имя '), surname=input('Введите свою фамилию '), date=input('Введите свой год рождения '), city=input('Введите свой город проживания '), email=input('Введите свой email '), number=input('Введите свой н...
number = int(input()) if any(number % int(i) for i in input().split()): print('not divisible by all') else: print('divisible by all')
num = [] imp = [] par = [] while True: num.append(int(input('Digite um número: '))) r = input('Você quer continuar? [S/N]: ') .strip().upper()[0] if r in 'N': break print(f'Todos os números digitados: {num}') for c in num: if c % 2 == 0: par.append(c) else: imp.append(c) pri...
# # PySNMP MIB module ALTIGA-MULTILINK-STATS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALTIGA-MULTILINK-STATS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:05:49 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
class Solution: def isPalindrome(self, s: str) -> bool: l,r = 0, len(s)-1 while l<r: if not s[l].isalnum(): l+=1 elif not s[r].isalnum(): r-=1 elif s[l].lower() == s[r].lower(): l+=1 ...
""" Entrez is an API that provides access to many databases, with most databases dealing with the biomedical and molecular fields. In this project we are concerned with the PubMed and the PubMed Central databases that hold biomedical literature. See: - Links to API documentation & examples: https://www.ncbi.nlm.nih.g...
class Solution: def rankTeams(self, votes: List[str]) -> str: # Create 2D data structure A : 0, 0, 0, 'A', C: 0, 0, 0, 'B' rnk = {v:[0] * len(votes[0]) + [v] for v in votes[0]} # Tally votes in reverse because sort defaults ascending for v in votes: for i, c in enumerate...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def findMode(self, root: TreeNode) -> List[int]: if not root: return dic = {} def record(node): ...
# # PySNMP MIB module TPT-DDOS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPT-DDOS-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:26:17 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
# # PySNMP MIB module CNT251-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CNT251-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:09:31 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:...
# Time: O(n) # Space: O(h) # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def btreeGameWinningMove(self, root, n, x): """ :type root: TreeNode :type n:...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def sumNumbers(self, root): """ :type root: TreeNode :rtype: int ...
""" Open511 Orlando """ # List of attribute keys which correspond to event descriptions DESC = ('Closure', 'Location') mapping = ( ('event_type', 'type'), ('geometry', 'geometry') ) class Event(object): def __init__(self, data, source: str = 'cityoforlando.net'): self.data = data self.so...
def sanitize(time_string): if '-' in time_string: splitter = '-' elif ':' in time_string: splitter = ':' else: return(time_string) (mins, secs) = time_string.split(splitter) return(mins + '.' + secs) with open('james.txt') as jaf: data = jaf.readline() james = data.stri...
# -*- coding: utf-8 -*- """ Created on Wed Feb 12 19:36:03 2020 @author: Administrator """ """ 有一个由大小写字母组成的字符串,请对它进行重新组合,使得其中的所有小写字母排在大写字母的前面 (大写字母或小写字母之间不要求保持原来的次序) """ def SortStr(s): i = 0 ; j = len(s) - 1 while i < j: if s[i].isupper(): pass else: ...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
def top3(products, amounts, prices): revenue_index_product = [ (amo*pri,-idx,pro) for (pro,amo,pri,idx) in zip(products,amounts,prices,range(len(prices))) ] revenue_index_product = sorted(revenue_index_product, reverse=True ) return [ pro for (rev,idx,pro) in revenue_index_product[0:3] ]
__all__ = [ 'XDict' ] class XDict(dict): __slots__ = () __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ __getitem__ = dict.get __getattr__ = dict.get __getnewargs__ = lambda self: getattr(dict,self).__getnewargs__(self) __repr__ = lambda self: '<XDict %s>' % dict.__repr__(sel...
class Node: def __init__(self, data = None, next = None): self.data = data self.next = next def setNext(self,next): self.next=next def setData(self, data): self.data=data class LinkedList: def __init__(self): self.head = None def add(self, data): if ...
class cached_property(object): """ Decorator that creates converts a method with a single self argument into a property cached on the instance. """ def __init__(self, func): self.func = func self.__doc__ = getattr(func, '__doc__') def __get__(self, instance, type): res =...
AddrSize = 8 Out = open("Template.txt", "w") Out.write(">->+\n[>\n" + ">" * AddrSize + "+" + "<" * AddrSize + "\n\n") def Mark(C, L): if C == L: Out.write("\t" * 0 + "[-\n") Out.write("\t" * 0 + "#\n") Out.write("\t" * 0 + "]\n") return Out.write("\t" * 0 + "[>\n") Ma...
length = int(input()) width = int(input()) height = int(input()) occupied = float(input()) occupied_percent = occupied / 100 full_capacity = length * width * height occupied_total = occupied_percent * full_capacity remaining = full_capacity - occupied_total capacity_in_dm = remaining / 1000 water = capacity_in_dm print...
module_id = 'gl' report_name = 'tb_bf_maj' table_name = 'gl_totals' report_type = 'bf_cf' groups = [] groups.append([ 'code', # dim ['code_maj', []], # grp_name, filter ]) include_zeros = True # allow_select_loc_fun = True expand_subledg = True columns = [ ['op_date', 'op_date', 'Op date', 'DTE', 8...
""" class TestNewOffsets(unittest.TestCase): def test_yearoffset(self): off = lib.YearOffset(dayoffset=0, biz=0, anchor=datetime(2002,1,1)) for i in range(500): t = lib.Timestamp(off.ts) self.assert_(t.day == 1) self.assert_(t.month == 1) self.asse...
class Calculator: def __init__(self): self.result = 0 def adder(self, num): self.result += num return self.result cal1 = Calculator() cal2 = Calculator() print(cal1.adder(3)) # 3 print(cal1.adder(5)) # 8 print(cal2.adder(3)) # 3 print(cal2.adder(7)) # 10 # Empty ...
# !/usr/bin/env python3 # Author: C.K # Email: theck17@163.com # DateTime:2021-09-03 16:21:08 # Description: class Solution: def cloneGraph(self, node: 'Node') -> 'Node': if not node: return node m = {node: Node(node.val)} stack = [node] while stack: n = sta...
N=int(input()) A=[int(input()) for i in range(N)] B={a:i for (i,a) in enumerate(sorted(set(A)))} for a in A: print(B[a])
# List of strings/words words = input().split() word_one = words[0] word_two = words[1] total_sum = 0 shorter_word_length = min(len(word_one), len(word_two)) # Process shorter string for i in range(shorter_word_length): word_one_current = word_one[i] word_two_current = word_two[i] ch_multiplication = ord...
class SomeClass: pass def simple_read_write(): x = SomeClass() # $tracked=foo x.foo = tracked # $tracked tracked=foo y = x.foo # $tracked=foo tracked do_stuff(y) # $tracked def foo(): x = SomeClass() # $tracked=attr bar(x) # $tracked=attr x.attr = tracked # $tracked=attr tracked ba...
def solution(n: int): answer = 0 i = 1 while i * i < n + 1: if n % i == 0: if i == n // i: answer += i else: answer += i + n // i i += 1 return answer if __name__ == "__main__": i = 25 print(solution(i))
""" Entradas Horas trabajadas-->float-->ht Pago por hora-->float-->ph Salidas Pago junto con la horas-->float-->pa=ht*ph Descuento por los impuestos-->float-->des1=pa*0.20 y des2=pa-des1 """ ht=float(input("Digite las horas que ha trabajado: ")) ph=float(input("Digite el pago por hora: ")) pa=ht*ph des1=pa*0.20 des2=p...
qst_deliver_message = 0 qst_deliver_message_to_enemy_lord = 1 qst_raise_troops = 2 qst_escort_lady = 3 qst_deal_with_bandits_at_lords_village = 4 qst_collect_taxes = 5 qst_hunt_down_fugitive = 6 qst_kill_local_merchant = 7 qst_bring_back_runaway_serfs = 8 qst_follow_spy = 9 qst_capture_enemy_hero = 10 qst_lend_companio...
class Chair: """Create a chair Parameters ---------- chair_name : str The name of the chair professor: str The name of the professor employees : {array-like of shape (n,), []}, default=[] List of all employees of the chair See A...
# Aluguel de carros k= (float(input('Total kilometragem percorrida: '))) a= (int(input('Total de dias alugado: '))) kr= (float(input('Valor por kilometro rodado: R$ '))) ad = (float(input('Valor do dia de aluguel: R$ '))) tk = k*kr # total de kilometros rodados ta = a * ad # total dias de aluguel total = tk + ta prin...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"dimension": "00_core.ipynb", "reshaped": "00_core.ipynb", "show": "00_core.ipynb", "makeThreatenedSquares": "00_core.ipynb", "defence": "00_core.ipynb", "attack":...
# This file was generated by the "capture_real_responses.py" script. # On Wed, 20 Nov 2019 19:34:18 +0000. # # To update it run: # python -m tests.providers.capture_real_responses captured_responses = [ { "request": { "full_url": "https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService...
class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ l = 0 r = len(s)-1 while l<r: s[l],s[r]=s[r],s[l] l+=1 r-=1
def check(params): "Check input parameters" attrs = [] for attr in attrs: if attr not in params: raise Exception('key {} not in {}'.format(attr, json.dumps(params))) def execute(cur, stmt, bindings, verbose=None): "Helper function to execute statement" if verbose: print(...
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: left, right = 0, len(numbers) - 1 while left < right: curSum = numbers[left] + numbers[right] if curSum == target: return[left + 1, right + 1] if curSum > target: ...
''' A collection of optional backends. You must manually select and install the backend you want. If the backend is not installed, then trying to import the module for that backend will cause an :class:`ImportError`. See :ref:`Choose a hashing backend` for more. ''' SUPPORTED_BACKENDS = [ 'pycryptodomex', # pref...
class linkedList(object): """ custom implementation of a linked list We need a custom implementation because in the tableMethod class we need to refere to individual items in the linked list to quickly remove and update them. """ first = None last = None lenght = 0 def...
""" from sys import argv script, input_file = argv def print_all(f): print f.read() def rewind(f): f.seek(0) def print_a_line(line_count, f): print line_count, f.readline() print "line = %d " % line_count current_file = open(input_file) print "First let's print the whole file: " print_all(current_file) #print...
class BSTIterator: def __init__(self, root: Optional[TreeNode]): self.stack = [] self.pushLeftsUntilNull_(root) def next(self) -> int: root = self.stack.pop() self.pushLeftsUntilNull_(root.right) return root.val def hasNext(self) -> bool: return self.stack def pushLeftsUntilNull_(self...
class Cache: def __init__(self, function, limit=1000): self.function = function self.limit = limit self.purge() def get(self, key): value = self.store.get(key) if value is None: value = self.function(key) self.set(key, value) return value ...
'''10. Write a Python program to use double quotes to display strings.''' def double_quote_string(string): ans = f"\"{string}\"" return ans print(double_quote_string('This is working already'))
# noqa class CustomSerializer: """Custom serializer implementation to test the injection of different serialization strategies to an input.""" @property def extension(self) -> str: # noqa return "ext" def serialize(self, value: str) -> bytes: # noqa return b"serialized" def de...
#カプセル化について """用語 カプセル化: プログラムの外部からの操作を制御、独立性を保つ仕組み ユーザーが使える機能を制限することでプログラムの干渉を抑えられる メンバ: クラス内で使用する変数. つまりインスタンス変数もクラス変数もメンバ プライベート変数: 特定の方法でのみアクセスできる変数. 不慮の事故を防げる """ #例 class Planet: description = '惑星について' #publicなクラス変数を宣言 def __init__(self): #コンストラクタ self.__name = 'Earth' #インスタンスの初期化 priv...
# Quem é o culpado perguntas = [] ct = 0 pt = 0 quest = input("Você telefonou a vitima: ") perguntas.append(quest) quest = input("Vocẽ esteve no local do crime: ") perguntas.append(quest) quest = input("Você mora perto da vitima? ") perguntas.append(quest) quest = input("Devia para a vitima? ") perguntas.append(ques...
""" .. module:: __init__ :synopsis: finvizfinance package general information .. moduleauthor:: Tianning Li <ltianningli@gmail.com> """ __version__ = "0.10" __author__ = "Tianning Li"
# URI Online Judge 1176 N = 62 n1 = 0 n2 = 1 string = '0 1' for i in range(N-2): new = n1 + n2 string += (' ') + str(new) n1 = n2 n2 = new fib = [int(item) for item in string.split()] T = -1 while (T<0) or (T>60): T = int(input()) for t in range(T): entrada = int(input())...
class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: res = ListNode(None) output = res while list1 and list2: if list1.val <= list2.val: output.next = list1 list1 = list1.next...
line = input().split('\\') line_length = len(line) -1 splitted = line[line_length].split('.') file_name = splitted[0] ext = splitted[1] print(f'File name: {file_name}') print(f'File extension: {ext}')
# # PySNMP MIB module Wellfleet-CCT-NAME-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-CCT-NAME-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:32:56 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
word_size = 9 num_words = 256 words_per_row = 4 local_array_size = 15 output_extended_config = True output_datasheet_info = True netlist_only = True nominal_corner_only = True