content
stringlengths
7
1.05M
class Lamp: def __init__(self, color): self.color=color self.on=False def state(self): return "The lamp is off." if not self.on else "The lamp is on." def toggle_switch(self): self.on=not self.on
def test_add(): class Number: def __add__(self, other): return 4 + other def __radd__(self, other): return other + 4 a = Number() assert 3 + a == 7 assert a + 3 == 7 def test_inheritance(): class Node(object): def __init__(self, a, b, c): ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def diameterOfBinaryTree(self, root: TreeNode) -> int: _, res = self.max_depth(root) return res def max_depth(self, ...
# Copyright 2016 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # for use with servo INA adapter board. If measuring via servo V1 this can just # be ignored. clobber_ok added if user wishes to include servo_loc.xml #...
response = sm.sendAskYesNo("Would you like to go back to Victoria Island?") if response: if sm.hasQuest(38030): sm.setQRValue(38030, "clear", False) sm.warp(100000000, 23) sm.dispose() sm.warp(104020000, 0)
# Write your solutions for 1.5 here! class superheros: def __init__(self, name, superpower, strength): self.name = name self.superpower = superpower self.strength = strength def gaya(self): print(self.name)
#Algoritmos Computacionais e Estruturas de Dados #Lista Simplesmente Encadeada em Python #Prof.: Laercio Brito #Dia: 07/02/2022 #Turma 2BINFO #Alunos: #Dora Tezulino Santos #Guilherme de Almeida Torrão #Mauro Campos Pahoor #Victor Kauã Martins Nunes #Victor Pinheiro Palmeira #Lucas Lima #Criar o método apagarLSE() que ...
# 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 kthSmallest(self, root: Optional[TreeNode], k: int) -> int: ordered_list = [] def inor...
TYPE_MAP = { 0: 'bit', 1: 'u32', 2: 's32', 3: 'float', 'bit': 0, 'u32': 1, 's32': 2, 'float': 3, } class HalType(object): bit = 0 u32 = 1 s32 = 2 float = 3 @classmethod def toString(self, typ): return TYPE_MAP[typ]
# Welcome to the interactive tutorial for PBUnit! Please read the # descriptions and follow the instructions for each example. # # Let's start with writing unit tests and using Projection Boxes: # # 1. Edit the unit test below to use your name and initials. # 2. Click your mouse on each line of code in the function to ...
# --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- MMS_WORKSPACE_API_VERSION = '2018-11-19' MMS_ROUTE_API_VERSION = 'v1.0' MMS_SYNC_TIMEOUT_SECONDS = 80 MMS_SERVICE_VALIDATE_OPERATION...
class LinkedListTreeTraversal: def __init__(self, data): self.tree = data # bfsTraversal is a recursive version of bfs traversal def bfsTraversal(self): root = self.tree queue = [] path = [] if self.tree == None: return [] queue.append(root) ...
# # 258. Add Digits # # Q: https://leetcode.com/problems/add-digits/ # A: https://leetcode.com/problems/add-digits/discuss/756944/Javascript-Python3-C%2B%2B-1-Liners # # using reduce() to accumulate the digits of x class Solution: def addDigits(self, x: int) -> int: return x if x < 10 else self.addDigits(r...
#!/usr/bin/env python3 class Cavern: def __init__(self, mapstring): self.mapstring = mapstring self.initialize(mapstring) def initialize(self, mapstring, elf_attack = 3): self.walls = set() self.units = {} self.elf_initial = 0 for y, line in enumerate(ma...
ROLE_METHODS = { 'google.iam.admin.v1.CreateRole', 'google.iam.admin.v1.DeleteRole', 'google.iam.admin.v1.UpdateRole' } def rule(event): return (event['resource'].get('type') == 'iam_role' and event['protoPayload'].get('methodName') in ROLE_METHODS) def dedup(event): return event['resour...
# -*- coding: utf-8 -*- # Common constants for submit SUBMIT_RESPONSE_ERROR = 'CERR' SUBMIT_RESPONSE_OK = 'OK' SUBMIT_RESPONSE_PROTOCOL_CORRUPTED = 'PROTCOR'
class DateTime(object,IComparable,IFormattable,IConvertible,ISerializable,IComparable[DateTime],IEquatable[DateTime]): """ Represents an instant in time,typically expressed as a date and time of day. DateTime(ticks: Int64) DateTime(ticks: Int64,kind: DateTimeKind) DateTime(year: int,month: int,day:...
text = 'shakespeare.txt' output = 'output_file.txt' f = open(output, 'r') o = open(text, 'w') for line in f: o.write(line) f.close() o.close()
{ "targets": [ { "target_name": "scsSDKTelemetry", "sources": [ "scsSDKTelemetry.cc" ], "cflags": ["-fexceptions"], "cflags_cc": ["-fexceptions"] } ] }
""" cargo-raze crate workspace functions DO NOT EDIT! Replaced on runs of cargo-raze """ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository") def _new_http_archive(name, **kwargs): if not native.existing_rule(name): ...
""" SII RTC/RPETC ============= Concepts and acronyms used interchangeably: * "Registro Transferencia de Crédito" (RTC) * "Registro Público Electrónico de Transferencia de Crédito" (RPETC) * "Registro Electrónico de Cesión de Créditos" """
# Flags quiet_mode = False no_log = False no_cleanup = False all_containers = False no_confirm = False no_backup = False # intern Flags keep_maintenance_mode = False def set_flags(flags=list): global no_confirm global all_containers global quiet_mode global no_log global no_cleanup global no_...
class Solution: def solve(self, n): # Write your code here l = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K' , 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ] s = "" while n > 26: j = n%26 ...
# coding: utf8 # intente algo como def index(): return dict(message="hello from configmenu.py") def articulos(): formulario =SQLFORM.smartgrid(db.articulo) return locals() def usuarios(): formulario =SQLFORM.grid(db.auth_user) return locals() def enviaCorreo(): #mail.send('oulloa@televida.biz', # 'As...
class Base: base_url = "https://localhost" def __init__(self, *args, **kwargs): pass
def reward_function(params): distance_from_center = params['distance_from_center'] progress = params['progress'] on_track = params["all_wheels_on_track"] ''' Example that penalizes slow driving. This create a non-linear reward function so it may take longer to learn. ''' # Calculate 3 marks...
test_list = [-2, 1, 3, -6] print(f'before', test_list) test_list.sort(key=abs) print(f'before', test_list)
############################################################################################### # 题目较难,直接看了官方答案,官方采用动态规划的方法,以空间换时间,学习后给出完整注释 ########### # 时间复杂度:O(m*n²*target),共四个循环,导致了主要的时间复杂度 # 空间复杂度:O(m*n*target),即三维动态规划所需要的空间(里面包含状态数量) ###########################################################################...
class Request: def __init__(self, req_id: int, emp_id: int, req_amount: float, req_desc: str, req_date: str, approved: bool, mgr_message: str, reviewed: bool): self.req_id = req_id self.emp_id = emp_id self.req_amount = req_amount self.req_desc = req_desc sel...
class OpenTokException(Exception): """Defines exceptions thrown by the OpenTok SDK. """ pass class RequestError(OpenTokException): """Indicates an error during the request. Most likely an error connecting to the OpenTok API servers. (HTTP 500 error). """ pass class AuthError(OpenTokExcep...
def test_count_by_time_categorical(total_spent): labels = range(2) total_spent = total_spent.bin(2, labels=labels) ax = total_spent.plot.count_by_time() assert ax.get_title() == 'Label Count vs. Cutoff Times' def test_count_by_time_continuous(total_spent): ax = total_spent.plot.count_by_time() ...
# Provides numerous # examples of different options for exception handling def my_function(x, y): """ A simple function to divide x by y """ print('my_function in') solution = x / y print('my_function out') return solution print('Starting') print(my_function(6, 0)) try: print('Bef...
DATABASES_PATH="../tmp/storage" CREDENTIALS_PATH_BUCKETS="../credentials/tynr/engine/bucketAccess.json" CREDENTIALS_PATH_FIRESTORE = '../credentials/tynr/engine/firestoreServiceAccount.json' INGESTION_COLLECTION = "tyns" INGESTION_BATCH_LIMIT = 1000
MAIN_WINDOW_STYLE = """ QMainWindow { background: white; } """ BUTTON_STYLE = """ QPushButton { background-color: transparent; border-style:none; } QPushButton:hover{ background-color: qradialgradient(cx:0, cy:0, radius: 1, fx:1, fy:1, stop:0 #c0c5ce, stop:1 #a7adba); border-style:none; } """
__all__ = ['EXPERIMENTS'] EXPERIMENTS = ','.join([ 'ig_android_sticker_search_explorations', 'android_ig_camera_ar_asset_manager_improvements_universe', 'ig_android_stories_seen_state_serialization', 'ig_stories_photo_time_duration_universe', 'ig_android_bitmap_cache_executor_size', 'ig_androi...
# Copyright 2004 Roman Yakovenko. # Distributed under the Boost Software License, Version 1.0. (See # accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) """ defines types visitor class interface """ class type_visitor_t(object): """ types visitor interface All functi...
""" Copyright 2022 Searis AS 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 dist...
"jq_eval rule" load("@bazel_skylib//lib:collections.bzl", "collections") load("@bazel_skylib//lib:shell.bzl", "shell") _DOC = "Defines a jq eval execution." _ATTRS = { "srcs": attr.label_list( doc = "Files to apply filter to.", allow_files = True, ), "filter": attr.string( doc = "...
#!/usr/bin/env python3 """Codon/Amino Acid table conversion""" codon_table = """ Isoleucine ATT ATC ATA Leucine CTT CTC CTA CTG TTA TTG Valine GTT GTC GTA GTG Phenylalanine TTT TTC Methionine ATG Cysteine TGT TGC Alanine GCT GCC GCA GCG Glycine GGT GGC GGA GGG Proline ...
""" Code for computing the mean. Using a list of tuples. """ def mean(l): s=0 for i in t: s = s +(i[0] * i[1]) return s t = [] x= (0,0.2) t.append(x) t.append((137,0.55)) t.append((170,0.25)) print(t) print(mean(t))
# encoding: utf-8 # Copyright 2008 California Institute of Technology. ALL RIGHTS # RESERVED. U.S. Government Sponsorship acknowledged. ''' Unit, functional, and other tests. '''
#function to get a string made of its first three characters of a specified string. # If the length of the string is less than 3 then return the original string. def first_three(str): return str[:3] if len(str) > 3 else str print(first_three('ipy')) print(first_three('python')) print(first_three('py'))
#!/usr/bin/env python """ Description: Fractional Backpack args: goods:[(price, weight)...] capacity: the total capacity of bag return: num_goods: the number of each goods val: total value of the bag """ def fractional_backpack(goods: list(tuple), capacity: int) -> (list, int | float): # initiali...
def factorial_digit_sum(num): fact_total = 1 while num != 1: fact_total *= num num -= 1 fact_total_str = str(fact_total) total_list = [] sum_total = 0 for i in fact_total_str: total_list.append(i) for i in total_list: sum_total += int(i) ...
# This is an input class. Do not edit. class LinkedList: def __init__(self, value): self.value = value self.next = None # O(n) time | O(n) space - where n is the number of nodes in the Linked List def nodeSwap(head): if head is None or head.next is None: return head ...
arrow_array = [ [[0,1,0], [1,1,1], [0,1,0], [0,1,0], [0,1,0]] ] print(arrow_array[0][0][0])
TREE = "#" def hit_test(map_, y, x, width) -> bool: while x >= width: x -= width return map_[y][x] == TREE def hit_test_map(map_, vy, vx) -> int: height, width = len(map_), len(map_[0]) r = 0 for x, y in enumerate(range(0, height, vy)): r += hit_test(map_, y, x * vx, width) r...
''' Vibrator ======= The :class:`Vibrator` provides access to public methods to use vibrator of your device. .. note:: On Android your app needs the VIBRATE permission to access the vibrator. Simple Examples --------------- To vibrate your device:: >>> from plyer import vibrator >>> time=2 >>> ...
# # PySNMP MIB module ONEACCESS-SYS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ONEACCESS-SYS-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:34:42 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
# all test parameters are declared here delay = 5 #no of seconds to wait before deciding to exit chrome_driver_path = '/home/apalya/browsers/chromedriver2.46' website = 'http://www.sunnxt.com' signin_text = 'Sign In' profile_icon_xpath = '//span[@class="icomoon icon-icn_profile"]' signin_link_xpath = '//ul[@class="sig...
male = [ 'Bence', 'Máté', 'Levente', 'Noel', 'Ádám', 'Marcell', 'Dominik', 'Dávid', 'Dániel', 'Milán', 'Botond', 'Zalán', 'Áron', 'Olivér', 'Balázs', 'Kristóf', 'Péter', 'Tamás', 'Zsombor', 'Márk', 'László', 'Gergő', 'Bálint', ...
num_usernames = int(input()) usernames = set() for _ in range(num_usernames): username = input() usernames.add(username) [print(name) for name in usernames]
"""Do not import this package. This file is required by pylint and this docstring is required by pydocstyle. """
num = int(input()) words = [] for i in range(num): words.append(input()) words.sort() for word in words: print(word)
# def make_table(): # colors_distance = { # 'black': {'black': 0, 'brown': 0, 'beige': 0, 'gray': 0, 'white': 0, 'blue': 0, # 'petrol': 0, 'turquoise': 0, 'green': 0, # 'olive': 0, 'yellow': 0, 'orange': 0, 'red': 0, 'pink': 0, 'purple': 0}, # 'brown': {'black': 0...
digits = { "0": "۰", "1": "۱", "2": "۲", "3": "۳", "4": "۴", "5": "۵", "6": "۶", "7": "۷", "8": "۸", "9": "۹", } def convert_digits(x: str) -> str: """ Convert english digits to persian digits. :param x: string with english digits :return: string with persian di...
""" Client (App) Agent singleton More description - TBD """ # # Author: Eric Gustafson <eg-git@elfwerks.org> (29 Aug 2015) # # ############################################################ # import statement def init_agent(**kwargs): # opportunity for pre/post hooks. return Agent(**kwargs) class Agent: ...
# Faça um programa que leia nome e média de um aluno, guardando também a situação em um dicionário. No final, mostre o conteúdo da estrutura na tela. aluno = {} aluno['Nome'] = input('Nome do aluno(a): ') aluno['Média'] = float(input(f'Média do aluno {aluno["Nome"]}: ')) if aluno['Média'] >= 7: aluno['Situação'] = ...
cpgf._import(None, "builtin.core"); KeyIsDown = []; def makeMyEventReceiver(receiver) : for i in range(irr.KEY_KEY_CODES_COUNT) : KeyIsDown.append(False); def OnEvent(me, event) : if event.EventType == irr.EET_KEY_INPUT_EVENT : KeyIsDown[event.KeyInput.Key + 1] = event.KeyInput.PressedDown; ret...
class AttemptResults(list): def __init__(self, tries): return super(AttemptResults, self).extend(['ND'] * tries)
lucky_numbers = [2, 4, 8, 1, 7, 15, 27, 25, 10] friends = ["yacubu", "rolan", "anatol", "patrick", "jony", "bel"] friends.extend(lucky_numbers)## take friend and value of lucky num in it print(friends) friends.append("toby") friends.insert(1, "rolax")## add value at index value and all other value get push back p...
# pylint: disable=missing-function-docstring, missing-module-docstring/ ai = (1,4,5) ai[0] = 2 bi = ai[0] ci = 2 * ai[0] di = 2 * ai[0] + 3 * ai[1] ei = 2 * ai[0] + bi * ai[1] fi = ai gi = (0,)*2 gi[:] = ai[1:] ad = (1.,4.,5.) ad[0] = 2. bd = ad[0] cd = 2. * ad[0] dd = 2. * ad[0] + 3. * ad[1] ed = 2. * ad[0] + bd * ad...
class IntegrationFeatureRegistry: def __init__(self): self.features = [] def register(self, integration_feature): self.features.append(integration_feature) self.features.sort(key=lambda f: f.order) def run_pre_scan(self): for integration in self.features: if ...
names = ['Dani', 'Ale', 'E. Jose'] message = f'Hey {names[0]}, Thanks for your friendship' print(message) message = f'Hey {names[1]}, Thanks for your friendship' print(message) message = f'Hey {names[2]}, Thanks for your friendship' print(message)
# -*- coding: utf-8 -*- # !/usr/bin/python3 """ ------------------------------------------------- File Name: strings.py Author : Carl Author_email: xingkong906@outlook.com date: strings.py Description : ------------------------------------------------- # If this run wrong, don't as...
infilename = input() outfilename = input() print(infilename,outfilename)
class ShrinkwrapConstraint: distance = None project_axis = None project_axis_space = None project_limit = None shrinkwrap_type = None target = None
""" In this bite you learn to catch/raise exceptions. Write a simple division function meeting the following requirements: when denominator is 0 catch the corresponding exception and return 0. when numerator or denominator are not of the right type reraise the corresponding exception. if the result of the division (...
'''Faça um programa que calcule a soma entre todos os números ímpares que são múltiplos de três e que se encontram no intervalo de 1 até 500.''' soma=0 for cont in range(0,500): if(cont%3==0 and cont%2!=0): print(cont) soma+=cont print('A soma é: {}'.format(soma))
# Let's say it's a wedding day, and two happy people are getting # married. # we have a dictionary first_family, which contains the names # of the wife's family members. For example: first_family = {"wife": "Janet", "wife's mother": "Katie", "wife's father": "George"} # And a similar dictionary second_family for the...
class BaseBoa: NUM_REGRESSION_MODELS_SUPPORTED = 5 reg_model_index = {0: 'dtree', 1: 'knn', 2: 'linreg', 3: 'adaboost', 4: 'rforest', } def __repr__(self): return type(...
# Copyright (c) 2007 The Hewlett-Packard Development Company # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implemen...
T = int(input()) for x in range(1, T + 1): N = int(input()) names = [input() for index in range(N)] y = 0 previous = names[0] for name in names[1:]: if name < previous: y += 1 else: previous = name print(f"Case #{x}: {y}", flush = True)
def zero(*args): arguments = str(args) current_number = 0 if '+' in arguments: for elem in args: number = current_number if elem == '+None': result = number + current_number return result number_2 = int(elem) result = nu...
class ApiError(Exception): """An error status code was returned when querying the HTTP API""" pass class AuthError(ApiError): """An 401 Unauthorized status code was returned when querying the API""" pass class NonUniqueIdentifier(ApiError): pass class ObjectNotFound(ApiError): pass
#Pizza #Burger #Fries - > Peri Peri mala # > normal order ="" #initialization print("-----Crunch n Munch-------") while order!="exit" : order = input("Enter your order - ") if order == "pizza" or order == "burger" : print ("Your order is "+order+" Preparation in progress...") ...
""" Parameter retrieval exceptions """ class GetParameterError(Exception): """When a provider raises an exception on parameter retrieval""" class TransformParameterError(Exception): """When a provider fails to transform a parameter value"""
#Entrada y Salida Estándar #Autor: Javier Arturo Hernández Sosa #Fecha: 3/Sep/2017 #Descripcion: Curso Python FES Acatlán #Entrada y Salida Estándar #Salida x="Paco" print("Hola ",x) #print puede tener varios valores separados por coma print("Hola",x,"¿Cómo estas?") print(f"Hola, {x}. ¿Cómo estas?") #Notacó...
# Spec: https://docs.python.org/2/library/types.html print(None) # TypeType # print(True) # LOAD_NAME??? print(1) # print(1L) # Long print(1.1) # ComplexType print("abc") # print(u"abc") # Structural below print((1, 2)) # Tuple can be any length, but fixed after declared x = (1,2) print(x[0]) # Tuple can be any length,...
n = int(input()) v = list(map(int, input().split())) c = list(map(int, input().split())) ans = 0 for i in range(n): xy = v[i] - c[i] if xy > 0: ans += xy print(ans)
# Hello World # My first python git repo if __name__ == "__main__": print("Hello World")
class Motor: """ doctest para motor >>> # testando motor >>> motor=Motor() >>> motor.acelerar() >>> motor.velocidade 1 >>> motor.frear() >>> motor.velocidade 0 """ def __init__(self, velocidade=0): self.velocidade = velocidade def acelerar(self): sel...
# -*- coding: utf-8 -*- ''' File name: code\building_a_tower\sol_324.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #324 :: Building a tower # # For more information see: # https://projecteuler.net/problem=324 # Problem Statement ''' L...
""" faça um programa que peça os 3 lados de um triângulo. O programa deverá informar se os valores podem ser um triangulo. Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isóceles ou escaleno.""" # três lados formam um triângulo quando a soma de quaisquer dois lados for maior que o terceiro # Eq...
def bingo(array): ctr = 0 for i in [2, 9, 14, 7, 15]: if i in list(set(array)): ctr += 1 if ctr == 5: return "WIN" else: return "LOSE"
colors = { "100 Mph":0xc93f38, "18th Century Green":0xa59344, "1975 Earth Red":0x7b463b, "1989 Miami Hotline":0xdd3366, "20000 Leagues Under the Sea":0x191970, "24 Karat":0xab7f46, "3AM in Shibuya":0x225577, "3am Latte":0xc0a98e, "400XT Film":0xd2d2c0, "5-Masted Preußen":0x9bafad, "8 Bit Eggplant":0x990066, "90% Cocoa"...
# Bit Manipulation # Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. # # Note: # The given integer is guaranteed to fit within the range of a 32-bit signed integer. # You could assume no leading zero bit in the integer’s binary represent...
# F. Палиндром # ID успешной посылки 65285610 def is_palindrome(line: str) -> bool: rem_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' ', '!', '"', '#', '$', '%', '&', '\', ''', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', ...
# # PySNMP MIB module CISCO-PSM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-PSM-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:39: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...
#!/usr/bin/python # -*- coding: utf-8 -*- # author arrti SQLALCHEMY_DATABASE_URI = "mysql+pymysql://ss" \ ":" \ "shadowsocks" \ "@" \ "localhost/" \ "shadowsocks" \ ...
# Given a year, determine whether it is a leap year. If it is a leap year, # return the Boolean True, otherwise return False. # Note that the code stub provided reads from STDIN and # passes arguments to the is_leap function. It is only necessary to complete the is_leap function. def is_leap(year): leap = False ...
''' Суммы двух На вход программе подается натуральное число n≥2, а затем n целых чисел. Напишите программу, которая создает из указанных чисел список, состоящий из сумм соседних чисел (0 и 1, 1 и 2, 2 и 3 и т.д.). Формат входных данных На вход программе подаются натуральное число n, а затем n целых чисел, каждое на от...
def media(n1=int(input("introduce la nota ")),n2=int(input("introduce la nota ")), n3=int(input("introduce la nota ")),n4=int(input("introduce la nota "))): notaMedia=(n1+n2+n3+n4)/4 if notaMedia>15: return print("Alumno con talento") elif notaMedia>=12 and notaMedia<=15: return print("C...
# indent = int(input()) # indent = 1 # indent = 14 # str1 = input() # str1 = 'bwfusvfupdbftbs' # str1 = 'fsfftsfufksttskskt' ''' str1 = '0123456789' for i in str1: print(chr((ord(i) + indent) % 26), end='') ''' indent = 14 # str1 = '0123456789' str1 = 'abcdefghijklmnopqrstuvwxyz' str2 = '' str3 = '' str5_coded = 'f...
check = 'Coderbunker whatever' bool(check.find('Coderbunker')) print(bool(check)) if check == 'Coderbunker whatever': print('what')
add_pointer_input = { "type": "object", "additionalProperties": False, "properties": {"pointer": {"type": "string"}, "weight": {"type": "integer"}, "key": {"type": "string"}}, "required": ["pointer", "weight"], } remove_pointer_input = { "type": "object", "additionalProperties": False, "prop...
# 415. Add Strings # Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. # # Note: # # The length of both num1 and num2 is < 5100. # Both num1 and num2 contains only digits 0-9. # Both num1 and num2 does not contain any leading zero. # You must not use ...
# Finding peak element 1D of array of int def findPeakRec(arr,low,high,n): mid = low + (low + high) / 2 mid = int(mid) if ((mid == 0 or arr[mid - 1] <= arr[mid]) and (mid == n - 1 or arr[mid + 1] <= arr[mid])): return arr[mid] elif arr[mid] < arr[mid-1]: #find left retur...
"""Decoder for the NEC infrared transmission protocol Implemented according to this specification: https://techdocs.altium.com/display/FPGA/NEC+Infrared+Transmission+Protocol """ _TOLERANCE = 0.25 class _UnexpectedPulse(Exception): pass class _Pulse(object): def __init__(self, durationms): duratio...
def Length(L): C = 0 for _ in L: C+=1 return C N = int(input('\nEnter number of elements in list to be entered: ')) L = [] for i in range(0,N): L.append(input('Enter an element: ')) print('\nLength of list:',Length(L))