content
stringlengths
7
1.05M
class TrieNode(object): def __init__(self, char): self.char = char self.children = [] self.words_count = 0 self.is_word = False def get_child(self, char): for child in self.children: if child.char == char: return child return None cl...
# -*- coding: utf-8 -*- """Document __init__.py here. Copyright (C) 2020, Auto Trader UK Created 15. Dec 2020 14:31 """
""" Автор: Моисеенко Павел, группа № 1, подгруппа № 2. Задание: разработайте программу, которая выводит на экран с помощью ASCII-графики таблицу истинности на основе переданных ей на вход аргументов (логическое выражение, аргументы, результат вычисления выражения). """ values = ((0, 0), (0, 1), (...
# Expressing a percentage points = 19 total = 22 print('Correct answers: {:.2%}'.format(points/total))
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: illuz <iilluzen[at]gmail.com> # File: AC_dfs_n.py # Create Date: 2015-03-03 14:53:53 # Usage: AC_dfs_n.py # Descripton: # Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None...
# checking if condition for i in range (1,101): if(((i % 3) == 0) and ((i % 5) == 0)): print('FuzzBuzz') elif ((i % 3) == 0): print('Fuzz') elif ((i % 5) == 0): print('Buzz') else: print(i)
## Function libs ## @author: Gil Miranda ## @email: gilsmneto@gmail.com ## @github: mirandagil ## @page: www.gilmiranda.me ## @class of functions: METHODS FOR INTEGRATION ## @last update: 22/10/2018 ## -- Computação Cientifica 2018.2 @ UFRJ -- ### - TRAPEZOIDAL - ### ### - BASIC TRAPEZOIDAL STEPPER - ### ### ...
{ "target_defaults": { "default_configuration": "Release", "configurations": { "Debug" : { "defines": ["_DEBUG"] }, "Release": { "defines": ["NDEBUG"] } }, "conditions": [ ["OS=='linux' or OS=='mac'", { "cflags": ["-fvisibility=hidden"] }] ] }, "targets": [{ ...
REQUEST_STATUS_CHOICES = ( ('Pending', 'Pending'), ('Accepted', 'Accepted'), ('Rejected', 'Rejected'), ('Blocked', 'Blocked'), ) CAUSE_CATEGORY_CHOICES = ( ('Animals', 'Animals'), ('Environment', 'Environment'), ('Humans', 'Humans'), )
__all__ = ( 'WumpyException', 'ExtensionFailure' ) class WumpyException(Exception): """Base exception that all other exceptions from the library subclass.""" pass class ConnectionClosed(WumpyException): """Exception raised when the WebSocket to the Discord gateway was closed.""" pass class Com...
lista = [] par = [] impar = [] while True: lista.append(int(input('Digite um número: '))) while True: continua = str(input('Quer continuar? [S/N] ')).strip().upper()[0] if continua in 'SN': break if continua == 'N': break for c in range(0, len(lista)): if lista[c] % 2...
class C: def __init__(self, x): self.x = x def m1(self): return f"calling m1 from C, x = {self.x}" def m2(self): return f"calling m2 from C, x = {self.x}" class Proxy(object): def __init__(self, prototype): self.prototype = prototype def m2(self): self.x = 10 retur...
class Discount: def __init__(self, price, quantity): self.price = price self.quantity = quantity def calculate_for(self, quantity): return quantity // self.quantity * self.price class PricePolicy: def __init__(self, original_price, discounts=None): self.original_price = or...
coordinates_E0E1E1 = ((125, 112), (126, 112), (126, 115), (126, 129), (127, 112), (127, 116), (127, 129), (127, 130), (128, 113), (128, 115), (128, 117), (128, 129), (128, 130), (129, 114), (129, 117), (129, 129), (129, 130), (130, 115), (130, 117), (130, 120), (130, 129), (131, 105), (131, 107), (131, 116), (131, 11...
def solution(participant=None, completion=None): answer = '' if not isinstance(participant, list) or not isinstance(completion, list): return answer participant.sort() completion.sort() for i, j in zip(participant, completion): if i != j: return i answer = participan...
# -*- coding: utf-8 -*- """ ontraportlib.models.sort_dir_enum This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ) on 11/14/2017 """ class SortDirEnum(object): """Implementation of the 'SortDir' enum. TODO: type enum description here. Attributes: ...
no_mutation = { 'soc_lower': 0, 'soc_upper': 0, 'charge_price_lower': 0, 'charge_price_upper': 0, 'discharge_price_lower': 0, 'discharge_price_upper': 0 } aggressive_mutation = { 'charge_price_lower': -5, 'charge_price_upper': 0, 'discharge_price_lower': 0, 'discharge_price_uppe...
# -*- coding: utf-8 -*- class firstInFirstOut: def processData(self, listOfNumbers): #takes only the first element of each tuple n = 0 arrivalTimeList = [x[n] for x in listOfNumbers] #takes only the second element of each tuple n = 1 burstTimeList = [x[n] for x in l...
#Crie um programa que leia vários valores inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles. numero = int(input('Informe um número [999 para parar]: ')) quantidade = 0 soma = 0 wh...
#(C) Copyright [2022] American Megatrends International LLC # #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 ...
#Crie um algoritimo que leia um número e mostre o seu dobro, triplo e raiz quadrada. n = int(input('Digite um número para ver seu dobro, triplo e raiz quadrada: ')) dobro = n * 2 triplo = n * 3 raiz = n ** (1/2) print('O dobro de {} equivale a {};'.format(n, dobro)) print('O triplo de {} equivale a {};'.format(n, trip...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def recoverTree(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. ...
def string_format_s(arg1): return 'this is %s' % arg1 def string_format(arg1): return 'this is {}'.format(arg1) def string_format_f(arg1): return f'this is {arg1}' def string_format_f_multiple(arg1, arg2, arg3): return f'{arg2} this is {arg1}! {arg3}' def string_format_multiple(arg1, arg2, arg3)...
# coding=utf-8 """ 克隆一个二叉树 思路: 用 dfs """ """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree @return: root of new tree """ def cloneTree(self, roo...
''' The MIT License (MIT) Copyright (c) 2016 WavyCloud Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, p...
# Vinicius Alves Loures França 20.1.1039 def primo(x): soma = 0 for c in range(1, x + 1): if x % c == 0: soma += 1 if soma == 2: return True else: return False def check_primo(x, y): lista_primo = [] for c in range(x, y + 1): if primo(c): ...
""" Copyright 2013 Rackspace 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...
''' It's Magic Sussutu is a world-renowned magician. And recently, he was blessed with the power to remove EXACTLY ONE element from an array. Given, an array A (index starting from 0) with N elements. Now, Sussutu CAN remove only that element which makes the sum of ALL the remaining elements exactly divisible by 7. Th...
nome = 'Patrícia' for c in nome: #if c == 'a' or c == 'í' or c == 'i': #if c in('a', 'í', 'i'): if c in 'aíi': print(c.upper()) elif c == 'c': print('@') else: print(c)
class Duck: def quack(self): return 'quack!' def swim(self): return 'I can swim!' def display(self): return 'I am a duck!' class MallardDuck(Duck): def display(self): return 'I am a mallard duck ^^' class RedheadDuck(Duck): def display(self): return 'I am a redhead duck @_@' class ...
class Scene: def __init__(self, display): self._entities = [] self._display = display def addEntity(self, entity): self._entities.append(entity) def update(self, events, delta): for entity in self._entities: entity.update(delta) def draw(self, screen): for entity in self._entities: e...
# https://leetcode.com/problems/two-sum/ # Given an array of integers, return indices of the two numbers such # that they add up to a specific target. # You may assume that each input would have exactly one solution, and # you may not use the same element twice. # Example: # Given nums = [2, 7, 11, 15], target = 9,...
# House Robber III 337 # ttungl@gmail.com # The thief has found himself a new place for his thievery again. # There is only one entrance to this area, called the "root." # Besides the root, each house has one and only one parent house. # After a tour, the smart thief realized that # "all houses in this place forms ...
# uninhm # https://atcoder.jp/contests/abc162/tasks/abc162_b # simulation ans = 0 for i in range(int(input())+1): if not (i%3 == 0 or i%5 == 0): ans += i print(ans)
BOARDING_TRANS = str.maketrans({"F": "0", "B": "1", "L": "0", "R": "1"}) def boarding_pass_to_seat_id(boarding_pass: str) -> int: return int(boarding_pass.translate(BOARDING_TRANS), 2) def find_hole_in_list(numbers: list) -> int: expected_sum = 0.5 * (len(numbers) + 1) * (min(numbers) + max(numbers)) retu...
# import math # import os # import random # import re # import sys # # Complete the 'gradingStudents' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts INTEGER_ARRAY grades as parameter. # def gradingStudents(grades): aut_list = [] for grade in grades: if...
def key_value_help(): print("Hello !") print("Let's Dive Deep and see the Features of this App - \n\n") print("--help or -h - For help") print("set - For Setting Key Value Pair") print("get - For Getting Key Value Pair") print("Thanks\nArchit Kumar Dwevedi") def key_value_invalid(): print...
""" The function sum_positive_numbers should return the sum of all positive numbers between the number n received and 1. For example, when n is 3 it should return 1+2+3=6, and when n is 5 it should return 1+2+3+4+5=15. Let's make this work """ # Remeber to define Base case! def sum_positive_numbers(n): #The base ...
nome_do_arquivo = input('Digite o nome do arquivo de entrada: ') # nome_do_arquivo = 'entrada.txt' conjunto_palavras_caracteres_repetidos = set() with open(nome_do_arquivo, 'r', encoding='utf8') as arquivo: for linha in arquivo: linha = linha.strip() palavras = linha.split() for palavra in p...
n, m = map(int, input().split()) graph = [] for i in range(n): graph.append(list(map(int, input())))
# # This is an example configuration. # Add your own keys and rename it to `slackbot_settings.py`. # DEFAULT_REPLY = "Hi! :wave: If you want me to do something, you should tell me what to do." ERRORS_TO = "your_slack_username_goes_here" # Don't put an @ sign. PLUGINS = [ 'slackbot.plugins' ] API_AI_KEY = "api...
""" https://programmers.co.kr/learn/courses/30/lessons/42577 """ def solution(phone_book): phone_book.sort() for i in range(len(phone_book)-1): if phone_book[i] == phone_book[i+1][:len(phone_book[i])]: return False return True
# Ejercicio 4 # Localiza el error en el siguiente bloque de código. # Crea una excepción para evitar que el programa se bloquee y además explica en un mensaje al usuario la causa y/o solución: # resultado = 15 + "20" try: resultado = 15 + "20" print(resultado) except TypeError: print("No se pueden operar u...
def main(): myList = [i for i in range(1, 101) if i%4 == 0] return print(myList) if __name__=="__main__": main()
10 (0, 0) 100 (7, 17) 1000 (70, 325) 10000 (703, 4858) 100000 (7026, 64741) 1000000 (70229, 808950) 10000000 (702309, 9706567)
a=4 b=5 c=a+b print("the value of a+b is : ",c)
# 1. uzdevums # temp = float(input("Cik Jums šobrīd ir temperatūra? ")) if temp < 35: print("Vai nav par aukstu?") elif temp > 37: print("Iespējams drudzis!") else: # 35 to 37 inclusive print("Viss kārtībā!")
"""PRINT BIG: Write a function that takes in a single letter, and returns a 5x5 representation of that letter print_big('a') out: * * * ***** * * * * HINT: Consider making a dictionary of possible patterns, and mapping the alphabet to specific 5-line combinations of patterns. For purpose...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeElements(self, head, val): if not head: return None p = head while p.next: ...
# 1) swapcase = Convert uppercase characters to lowercase and lowercase characters to uppercase x="python" print(x.swapcase()) # 2) casefold = Convert in lowercase print(x.casefold()) # 3) capitalize = More specifically, make the first character have upper case and the rest lower case print(x.capitalize()) # 4) t...
class Solution: def minMalwareSpread(self, matrix: List[List[int]], initial: List[int]) -> int: graph = collections.defaultdict(list) for i, row in enumerate(matrix): for j, val in enumerate(row): if val == 1: graph[i].append(j) inf_relations =...
description = 'Dilatometer' group = 'optional' includes = ['alias_T'] tango_base = 'tango://stressictrl.stressi.frm2:10000/stressi/dilato/' devices = { 'Ts_dil': device('nicos.devices.tango.Sensor', description = 'The sample temperature', tangodevice = tango_base + 'temp', pollinterval =...
class ApiConfig: """class that store Api configuration added in ApiConfig instance Store Configs passed to ApiConfig and provide a search class method to retrieve configs by 'name' Exception: NotImplementedError: Call the '__init__' special method is not allowed it r...
def triangle_star(row): for x in range(1,row+1): for k in range(x): print("*",end=" ") print("") x = input("How many rows : ") try : x = int(x) triangle_star(x) except ValueError: print("Please enter number only")
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def min_diff_in_BST(self, root: TreeNode) -> int: left = float('inf') right = float('inf') if root.left: left = min(abs(root.val - self.max(root.le...
def possible_player_pairs(array) : lenArr = len(array) if (lenArr <= 0): return [] if (lenArr == 1): return array results = [] for i in range(0, lenArr - 1): for j in range(i + 1, lenArr): results.append(array[i] + array[j]) return results def count_player_pairs(n) : if (n <= 0):...
class APIError(Exception): error_code = 1000 log_message = "API Error" send_to_sentry = False request_id = None def __init__(self, request_id=None, message=None): if message is not None: self.log_message = message self.request_id = request_id def __str__(self): ...
class InvalidRequestObject(object): def __init__(self): self.errors = list() def __nonzero__(self): return False __bool__ = __nonzero__ def add_error(self, parameter, value): self.errors.append({'parameter': parameter, 'message': value}) def has_errors(self): retu...
def A(): return ValueError try: raise ValueError() # breaks except A(): pass
entrada_1 = input().split() entrada_2 = input().split() x1, y1 = entrada_1 x2, y2 = entrada_2 distancia = (((float(x2) - float(x1)) ** 2) + ((float(y2) - float(y1)) ** 2)) saida = distancia ** (1/2) print(f"{saida:.4f}")
description = 'Multi tomo setup with four motors in Experimental Chamber 1, currently only 3 motors implemented' group = 'optional' tango_base = 'tango://antareshw.antares.frm2.tum.de:10000/antares/' devices = dict( sry_multi_1 = device('nicos.devices.entangle.Motor', description = 'Multitomo sample rota...
print('git ni lai a') def hello(): print('git真好玩') a = 10 b = a * 10 print(b)
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: # dp[i] means fewest coins needed to reach amount i # dp[i] = min(dp[i-coins[p1]] + 1,...dp[i-coins[pn]]+1) dp = [None for _ in range(amount + 1)] for coin in coins: if coin < len(dp): ...
class Solution: def jump(self, nums: List[int]) -> int: if not nums or len(nums) == 0: return 0 n = len(nums) dp = [float('inf') for _ in range(n)] dp[0] = 0 for i in range(1, n): for j in range(i): if nums[j]...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: p = dummy = ListNode(-1) p.next = head for _ in range(m - 1): p = p...
class Role(object): vistor = 1 # 游客,无登录态 user = 2 # 用户 manager = 3 # 管理员 class RoleBuilder(object): def __init__(self): self.role = [] def append_vistor(self): self.role.append(Role.vistor) return self def append_user(self): self.role.append(Role.user) ...
class Solution: def isHappy(self, n: int) -> bool: """ 方法1:辅助循环链表,典型的数学证明题,需要证明,他不会无线扩大,要么到1,要么在其他的数上循环 快乐数:每个位置的平方和=1 :param n: :return: 是否快乐数 """ # 关键确定Set集合,判断是否出现了重复数字 numset = set() while n != 1 and n not in numset: numset.add...
# numeros impares que são multiplos de 3 (divisiveis por 3) soma = 0 for c in range(1, 500): print('.', end='') if c % 2 != 0 and c % 3 == 0: print(c, end='') soma= soma + c print('\nA soma de todos os valores impar é igual a {} '.format(soma))
# Eve IDs EVE_CATEGORY_ID_SHIP = 6 EVE_CATEGORY_ID_STRUCTURE = 65 EVE_CATEGORY_ID_FIGHTER = 87 EVE_GROUP_MINING_DRONE = 101 EVE_GROUP_ORBITAL_INFRASTRUCTURE = 1025
""" train,val pose 안불러오고 Identity로 불러오는 원래 코드 """ # import numpy as np # import os,sys,time # import torch # import torch.nn.functional as torch_F # import torchvision # import torchvision.transforms.functional as torchvision_F # import PIL # import imageio # from easydict import EasyDict as edict # import json # imp...
img_width, img_height = 299, 299 num_channels = 3 train_data = 'data/train' valid_data = 'data/valid' num_classes = 80 num_train_samples = 53879 num_valid_samples = 7120 verbose = 1 batch_size = 32 num_epochs = 1000 patience = 50 best_model = 'model.11-0.6262.hdf5'
# # PySNMP MIB module TAILF-ALARM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TAILF-ALARM-MIB # Produced by pysmi-0.3.4 at Wed Aug 7 20:00:11 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.7.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
def triangleArea(side, height): return side * height / 2 side = float(input()) height = float(input()) print(triangleArea(side, height))
# a. merge full = pd.merge(pop, prices_long, on=['date','municipality'], how='left') full.sort_values(['municipality','date'], inplace=True) # b. take logs full['log_population'] = np.log(full['population']) full['log_price'] = np.log(full['price']) # c. figur 1: log differences ax = full.groupby('municipality').di...
def _topic_str(topic_d): type_ = topic_d.get("type") or topic_d.get("type_str", "topic") type_str = f', {type_}' if type_ != 'topic' else '' return f'{topic_d["name"]} ({topic_d["id"]}{type_str})' def created_connection(plugin, parameters): return ( f"Created fdbk DB connection of type '{plugi...
class Dictionary: def get_sub_dictionary(self): return Dictionary pass
""" Implicit chaining -> Occurs when an exception is raised incidentally during processing of another. -> The original exception is stored on the __context__ attribute of the second. """
# -*- coding: utf-8 -*- # simple set, constructed by a list, will auto remove duplicated values s = {1, 1, 2, 3} print(s) # duplicated values will not be added s.add(1) s.add(4) print(s) # remove key s.remove(4) print(s) # set operation s2 = {2, 3, 4} print(s2.intersection(s)) print(s2 & s) # shortcut print(s2.dif...
def collatz(num): length = 1 while num != 1: if num % 2 == 0: num //= 2 else: num = 3 * num + 1 length += 1 return length def solution(num): max_length = 1 value = 1 for i in range(1, num): chain_length = collatz(i) if chain_length...
# -*- coding: utf-8 -*- """ Created on Mon Jan 27 19:51:12 2020 @author: Administrator """ """ 给定一个由n-1个整数组成的未排序的数组序列,其元素都是1到n中的不同的整数.请写出一个寻找数组序列中缺失整数的线性时间算法. """ def FindMissValue(array , N): # find the missing value in the array sumv = 0 for item in array: sumv += item missv...
#Creación de la función def multiplication_exponent_table(): name = input("\tWhats is your name?:\t").title() number = float(input("\tWhat number would you like to work with?:\t").title()) print(f"""\n\tMultiplication table for {number}\n \t\t1.0*{number} = {round(1*number,4)} \t\t2.0*{numb...
# coding: utf8 def memory_reallocation_v1(s): """memory reallocation.""" cycles = 0 banks = s[:] ll = len(banks) seen = [] uk = ''.join(list(map(str, banks))) while uk not in seen: seen.append(uk) key_chosen = banks.index(max(banks)) value_chosen = banks[key_chosen...
class SignifyError(Exception): """Base class for all errors generated by Signify""" pass class ParseError(SignifyError): pass class SignedPEParseError(ParseError): pass class SignerInfoParseError(ParseError): pass class AuthenticodeParseError(ParseError): """Raised when any exception r...
PIXIV_IOS_USER_AGENT = 'PixivIOSApp/4.13.3 (iOS 14.6; iPhone13,2)' PIXIV_ANDROID_USER_AGENT = "PixivAndroidApp/5.0.234 (Android 11; Pixel 5)" PIXIV_REQUEST_HEADERS = { 'APP-OS': 'ios', 'APP-OS-Version': '12.6', 'Accept-Language': 'zh-CH;zh;q=0.9;en;q=0.8', }
__all__ = ['make_site'] def make_site(rep): if isinstance(rep, Site): return rep elif rep is None or isinstance(rep, tuple): return GridSite(rep) else: return Site(rep) class Site: def __init__(self, location, placed=True): self.location = location self.place...
# See bazel/README.md for details on how this system works. EXTENSIONS = { "envoy.filters.http.router": "//source/extensions/filters/http/router:config", "envoy.filters.network.direct_response": "//source/extensions/filters/network/direct_response:config", "envoy.filters.network.http_connection_manager": "/...
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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 applicab...
class Solution(object): def solve(self, board): # Handle base case if len(board) == 0 or len(board[0]) == 0: return board # Get Mark all Os on the edge and their connected Os for i in range(len(board)): for j in range(len(board[0])): if i == ...
""" The main entry point for player-wearable armor. This module gives a main entry point for all armor. Currently, this is all inside one file, but could be split into more. The class :class:`Armor` is the main entry point of all armor, being the one to define generic stats. While all armor classes can have more than...
# bug collector bugs_total = 0.0 for day in range(5): print("Enter the collected bugs for day", day + 1, end='') bugs = int(input(": ")) # add bugs to accumulator bugs_total += bugs print() print("The total bugs collected: ", bugs_total)
mult_3_5 = lambda x: x%3==0 or x%5==0 print(mult_3_5(3)) print(mult_3_5(4)) print(mult_3_5(5)) def add1(): return lambda x: x + 1 f = add1() print(f(2))
""" Root module for the fixtest tool. Copyright (c) 2014 Kenn Takara See LICENSE for details """
rpc_server_url = None # địa chỉ rpc_server db_url = None #địa chỉ của MetricDB check_timeout = 3 upload_timeout = None # timeout of sending result to DB check_interval = 5 # option which APScheduler need enable_plugin = [ { 'name': 'Ping', 'path': 'check_plugins.ping' } ]
def pattern(): for i in range(len(name)): # A if name[i] == "A": print_A = [[" " for i in range(6)] for j in range(7)] for row in range(7): for col in range(6): if ((col == 0 or col == 3) and (row > 0)) or ((row == 0 or row == 3) and (col =...
""" Este programa tiene como propósito evidenciar el uso de las estructuras while. Lo que hace es que recibe un valor que deseo calcular y eleva al cuadrado el número dado, lo hace hasta que la condición LIMITE deje de ser verdadera. En este caso operara hasta que encuentre la potencia de mi numero que es menor a 1000...
#!/usr/bin/env python # coding: utf-8 # In[2]: list1 = [5, 8, 10] #for loops list2 = ["Ravi", "EMC", "IBM", "Sogeti"] for i in list1: print(i) for j in list2: print(j) # In[5]: print(range(0,10)) for k in range(0,5): print(k) # In[9]: sum = 0 for n in range(1,11): sum += n print(sum) prin...
# test waiting within async with enter/exit functions # uPy allows normal generators to be awaitables. # CircuitPython does not. # In CircuitPython you need to have an __await__ method on an awaitable like in CPython; # and like in CPython, generators do not have __await__. class Awaitable: def __init__(self, x)...
class Constant(object): """ Constant Class This class contains all variable constants. All variables with a variable value will call this class. """ # Weight first patch w_first_patch = 5 # Weight second patch w_second_patch = 5 # Weight number of inputs w_number_inputs = 1 ...
func_count_dic = {} userA = {} userB = {} def check_fn_docs(): ''' A function check_fn_docs is defined to check whether the input function has doctring length should be 50 characters. Input : function name Output : return nested function. ''' char_count = 50 def len_docs_...
# Segments are comprised of 2 main components: Transport and DataProcessingGroup (DPG) # The Transport represents an mechanism for input objects to be sent to the DPG. The DPG # is a cluster of different DataProcessor objects each created with a work function. The transport # does not need to be homogenous as the type ...