content
stringlengths
7
1.05M
def simple_moving_average(df, base, target, period): """ Function to compute Simple Moving Average (SMA) This is a lagging indicator df - the data frame base - on which the indicator has to be calculated eg Close target - column name to store output period - period of the sma """ df...
class Usuario: def __init__(self, nome) -> None: self.nome = nome self.id = None
_all__ = [ 'Auto' ] class Auto(object): pass
def add(number_one, number_two): return number_one + number_two def multiply(number_one, number_two): return number_one * number_two if __name__ == "__main__": print(add(3, 4)) print(multiply(5, 5))
# ElasticQuery # File: exception.py # Desc: ES query builder exceptions class QueryError(ValueError): pass class NoQueryError(QueryError): pass class NoAggregateError(QueryError): pass class NoSuggesterError(QueryError): pass class MissingArgError(ValueError): pass
#https://rszalski.github.io/magicmethods/ #__init__ é um metodo magico #Um design muito utilizado é o Singleton, ou seja, somente uma instacia para o projeto todo class A: def __new__(cls, *args, **kwargs): if not hasattr(cls,'_jaexiste'): cls._jaexiste = object.__new__(cls) ret...
#serie a,b,a,b,a,b.... limite = int(input("Digite las veces que se repetira: ")) interructor = True controlador = 0 letra = "" while controlador < limite: controlador = controlador + 1 if interructor: letra = "A" interructor = False else: letra = "B" interructor = True ...
# Longest Common Subsequence def lcs(X, Y, m, n): if m == 0 or n == 0: return 0 elif X[m - 1] == Y[n - 1]: return 1 + lcs(X, Y, m-1, n-1) else: return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n)) X = 'AGGTAB' Y = 'GXTXAYB' print('Length of LCS is ', lcs(X, Y, len(X),...
''' bd_username = 'ruslan' bd_password = '12345' def auth(tries: int): count = 0 while count < tries: username = input('введите имя пользователя: ') password = input('введите пароль: ') if username == bd_username and password == bd_password: print('добро пожаловать') ...
#!env python # # ACSL Intermediate Division - Number Transformation - 2019-2020 # Solution by Arul John # 2020-11-22 # # Function to do the number transformations def number_transformation(n, p): str_n = n n = int(n) p = int(p) if len(str_n) < p: return str_n_ans = '' # answer # index...
def fileNaming(names): for i in range(1, len(names)): temp = names[i] counter = 1 while temp in names[0:i]: temp = f"{names[i]}({counter})" counter += 1 names[i] = temp return names print(fileNaming(["doc", "doc", "image", "doc(1)", "doc"]))
helpline_numbers = { 'source':'https://www.mohfw.gov.in/pdf/coronvavirushelplinenumber.pdf', 'helpline_number':'+91-11-23978046', 'toll_free':'1075', 'helpline_email':'ncov2019@gov.in', 'contact_details':[ { 'state_or_UT':'Andhra Pradesh', 'helpline_number':'0866-2410978' }, { 'state_or_...
"""Takes a number of miles and converts it to a feet value.""" def main() -> None: """Convert the user input miles value to feet and display the result.""" print('Hike Calculator') miles: float = float(input('How many miles did you walk?: ')) print(f'You walked {to_feet(miles)} feet.') def to_...
#------------------------------------------------------------------------------- # # Project: EOxServer <http://eoxserver.org> # Authors: Fabian Schindler <fabian.schindler@eox.at> # Martin Paces <martin.paces@eox.at> # #------------------------------------------------------------------------------- # Copyrigh...
# Utility macros for Twister2 core files def twister2_core_files(): return twister2_core_conf_files() + twister2_core_lib_files() def twister2_core_conf_files(): return [ "//twister2/config/src/yaml:config-system-yaml", "//twister2/config/src/yaml:common-conf-yaml", ] def twister2_core_li...
class Exception: def __init__(self, message): self.message = message class TypeError(Exception): pass class AttributeError(Exception): pass class KeyError(Exception): pass class StopIteration(Exception): pass class NotImplementedError(Exception): pass class NotImplemente...
__version__ = '0.15.0.dev0' PROJECT_NAME = "pulsar" PROJECT_OWNER = PROJECT_USERAME = "galaxyproject" PROJECT_AUTHOR = 'Galaxy Project and Community' PROJECT_EMAIL = 'jmchilton@gmail.com' PROJECT_URL = "https://github.com/{}/{}".format(PROJECT_OWNER, PROJECT_NAME) RAW_CONTENT_URL = "https://raw.github.com/{}/{}/maste...
test = { 'name': 'Problem 5', 'points': 2, 'suites': [ { 'cases': [ { 'code': r""" >>> abs_diff = lambda w1, w2, limit: abs(len(w2) - len(w1)) >>> autocorrect("cul", ["culture", "cult", "cultivate"], abs_diff, 10) 'cult' >>> autocorrect("cul", ["...
# puzzle3a.py def main(): calc_slope(1, 1) calc_slope(3, 1) calc_slope(5, 1) calc_slope(7, 1) calc_slope(1, 2) def calc_slope(horiz_step = 3, vert_step = 1): tree_char = "#" horiz_pos = 0 trees = 0 input_file = open("input.txt", "r") lines = input_file.readlines() ...
"""Exceptions that pertain to Flashcards-level functionality.""" class FlashCardsError(Exception): """Base class for other Flashcards-level exceptions.""" def __init__(self, message: str) -> None: super().__init__(f"Flashcards Error: {message}") class InvalidConfiguration(FlashCardsError): """S...
# # PySNMP MIB module RADLAN-AGGREGATEVLAN-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-AGGREGATEVLAN-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:45:06 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7....
# Title : Url shortner # Author : Kiran Raj R. # Date : 07:11:2020 class URL_short: url_id = 0 url_dict = {} def url_shortner(self,orginal_url): if orginal_url in self.url_dict: url = self.url_dict[orginal_url] return f"{orginal_url} already has a shorten url: my_url.com/...
# Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra "A", # em que posição ela aparece a primeira vez e em que posição ela aparece a última vez. text = input('Digite uma frase:').strip().upper() print('Quantidade de letras "A":', text.count('A')) print('Primeira aparição:', text.fi...
""" Exceptions raised by cli-toolkit """ class ScriptError(Exception): """ Errors raise during script processing """
def snake_to_camel(s): """ >>> snake_to_camel('snake_to_camel') 'snakeToCamel' """ pass
# -*- coding: utf-8 -*- __title__ = 'gym_breakout_pygame' __description__ = 'Gym Breakout environment using Pygame' __url__ = 'https://github.com/whitemech/gym-breakout-pygame.git' __version__ = '0.1.1' __author__ = 'Marco Favorito, Luca Iocchi' __author_email__ = 'favorito@diag.uniroma1.it, iocchi@diag.uniroma1.it' _...
def numUniqueEmails(self, emails): """ :type emails: List[str] :rtype: int """ email_set = set() for i in emails: email = i.split("@") local = email[0].replace(".", "") locate_plus = local.find("+") if locate_plus != -1: email_set.add(local[...
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ l = len(nums) sum = (0 + l) * (l + 1) / 2 for n in nums: sum -= n return sum
class ContactList(list): def search(self, name): """Return all contacts that contain the search value in their name""" matching_contact = [] for contact in self: if name in contact.name: matching_contact.append(contact) return matching_contact
# MOOC-Python Task # takuron@github def lcm(n1,n2) : maxx = 0 if n1>=n2: maxx = n1 else: maxx = n2 i = 0 while 1 : i = i+1 if ((maxx+i)%n1==0) and ((maxx+i)%n2==0): return maxx+i num1=int(input("")) num2=int(input("")) print(lcm(num1,num2...
# The marketing team is spending way too much time typing in hashtags. # Let's help them with our own Hashtag Generator! # # Here's the deal: # # It must start with a hashtag (#). # All words must have their first letter capitalized. # If the final result is longer than 140 chars it must return false. # If the input or...
# # 1520. Maximum Number of Non-Overlapping Substrings # # Q: https://leetcode.com/problems/maximum-number-of-non-overlapping-substrings/ # A: https://leetcode.com/problems/maximum-number-of-non-overlapping-substrings/discuss/749421/Javascript-Python3-C%2B%2B-beginend-index-%2B-greedy-consumption # class Solution: ...
class Solution: def isPowerOfThree(self, n: int) -> bool: if n < 1: return False if n == 1: return True if sum(list(map(int, str(n)))) % 3 != 0: return False else: while n > 1: if n % 3 == 0: n /= 3 ...
"""Static Token And Credential Scanner CI integrations. SPDX-License-Identifier: BSD-3-Clause """ __title__ = "stacs-ci" __summary__ = "Static Token And Credential Scanner CI Integrations." __version__ = "0.1.6" __author__ = "Peter Adkins" __uri__ = "https://www.github.com/stacscan/stacs-integration/" __license__ = "...
def bubble_sort(items): for i in range(len(items)): for j in range(len(items)-1-i): if items[j] > items[j+1]: items[j], items[j+1] = items[j+1], items[j] def f(n): #bubble sort worst case bubble_sort(range(n,0,-1))
""" Global information to be used by the module. """ class Question: q_p_id: int q_id: str q_text: str q_answer: str q_a: str q_b: str q_c: str q_d: str def __init__( self, q_p_id, q_id, q_text, q_answer, q_a, q_b, q_...
a = 'C:\\Users\\Jason\\Documents\\GitHub\\chesspdftofen\\data\\out\\yasser\\WhiteQueen' l = [] for e in sorted(os.listdir(a)): i = cv2.imread(os.path.join(a, e), 0) h,w = i.shape # l.append([np.sum(i[h//4:h//4*3, w//4:w//4*3]), e]) l.append([np.sum(i), e]) l.sort() print(l) for i, k in enumerate(l): # aa = ...
''' Created on Sep 3, 2010 @author: ilg ''' class WriterBase(object): ''' classdocs ''' def __init__(self, sName): ''' Constructor ''' self.bVerbose = False self.sName = sName self.sLocalUrl = None pass def setVerbose(self, bVerbose): ...
def process_old_format(self, cg_resources_requirements): """ Old format is njs,request_cpu=1,request_memory=1,request_disk=1,request_color=blue Regex is assumed to be true :param cg_resources_requirements: :return: """ cg_res_req_split = cg_resources_requirements.split(",") # List # A...
""" Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account. Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email t...
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices: return 0 n = len(prices) if n == 1: return 0 dp = [0 for i in range(n + 1)] tmpmin = prices[0] fo...
class Solution: def calculateTime(self, keyboard: str, word: str) -> int: positions = {key : i for i, key in enumerate(keyboard)} n = len(word) ans = 0 for i in range(1, n): ans += abs(positions[word[i]] - positions[word[i - 1]]) return ans + positions[word[0]]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Utility functions. """ def _check_columns(df_to_check, cols) -> None: """Check that a list of required column names is in a data frame Args: df_to_check: A DataFrame to check columns on. cols (Iterable[str]): Required columns. Returns: ...
# -*- coding: utf-8 -*- """ neutrino_api This file was automatically generated for NeutrinoAPI by APIMATIC v2.0 ( https://apimatic.io ). """ class BrowserBotResponse(object): """Implementation of the 'Browser Bot Response' model. TODO: type model description here. Attributes: ...
# Exercício Python 056 # Leia nome, idade e sexo de quatro pessoas. Mostre: # média de idade, qual é o nome do homem mais velho, quantas mulheres tem menos de 20 anos maisvelho = '' maior = 0 somaIdade = 0 somaMulheres = 0 for c in range(0,4): nome = str(input('Nome: ')).strip idade = int(input('Idade: ')) ...
''' Nesse problema você deverá descobrir se um conjunto de diversas palavras é bom ou ruim. Por definição, um conjunto é bom quando nenhuma palavra desse conjunto é um prefixo de uma outra palavra. Caso contrário, este é considerado um conjunto ruim. Por exemplo, {abc, dae, abcde} é um conjunto ruim, pois abc é um pre...
numbers = [0, 1, 2, 3, 4] doubled_numbers = [] for num in numbers: doubled_numbers.append(num * 2) print(doubled_numbers) # -- List comprehension -- numbers = [0, 1, 2, 3, 4] # list(range(5)) is better doubled_numbers = [num * 2 for num in numbers] # [num * 2 for num in range(5)] would be even better. print(d...
# É possível digitar listas dentro de lista galera = [["João", 44], ["Ana", 18], ["Pedro", 29]] print(galera[1][0])
#!/usr/bin/env python # -*- coding: utf-8 -*- """ generator用到的工具函数 """ def get_trigger_event(s, is_delay=False): """ 获取触发事件 """ # 取第一个event term for t in s.terms: if t.left.type == 'event': if is_delay: new = t.left.event[:] new[-1] = new[-1] + ...
# internal library def ceil_pow2(n): x = 0 while((1 << x) < n): x += 1 return x # internal library end class segtree: def __init__(self, op, e, n=0, ary=[]): self.op = op self.e = e if n: ary = [e()] * n else: n = len(ary) self.n ...
class CompatibilityResult(object): def __init__(self, mergerule, incompatible_rule_class_names=[]): """ :param mergerule: MergeRule :param incompatible_rule_class_names: list of strings """ self._mergerule = mergerule self._incompatible_rule_class_names = incompatible...
class User: # Class Attribute active_users = 0 #class Methods @classmethod def display_active(cls): return f"Total Active users are {cls.active_users}" def __init__(self,first_name,last_name,age): # instance Attribute/Variable self.first_name = first_name se...
""" █▀▀ █▀▀ █▄░█ █▀▀ █▀ █ █▀   █░░ █▀▀ █▀ █▀ █▀█ █▄░█ █▀   █░█ █▀█ █░░ ░ ▄█ █▄█ ██▄ █░▀█ ██▄ ▄█ █ ▄█   █▄▄ ██▄ ▄█ ▄█ █▄█ █░▀█ ▄█   ▀▄▀ █▄█ █▄▄ ▄ ░█ Welcome to the genesis gir lesson tutorials Volume 1! Companion Cube is a program based on doing various tasks on guiding your companion cube to freedom and most importan...
class TextStats: def _calc_symbol_freqs(self): self.symbol_freq = {} for c in self.text: if c in self.symbol_freq: self.symbol_freq[c] += 1 else: self.symbol_freq[c] = 1 @staticmethod def _is_valid_bigram(a, b): """ 0nly count ...
test = { 'name': 'Problem 7', 'points': 3, 'suites': [ { 'cases': [ { 'code': r""" >>> big_limit = 10 >>> meowstake_matches("wird", "wiry", big_limit) 1 >>> meowstake_matches("wird", "bird", big_limit) 1 >>> meowstake_matches(...
# Notices we don't need to worry about ignore_notices = [ "already_banned", "already_emote_only_off", "already_emote_only_on", "already_r9k_off", "already_r9k_on", "already_subs_off", "already_subs_on", "bad_ban_admin", "bad_ban_anon", "bad_ban_broadcaster", "bad_ban_global_m...
class InvalidUsage(Exception): status_code = 404 message = 'Instance Not Found!' def __init__(self, message=None, status_code=None): Exception.__init__(self) if message is not None: self.message = message if status_code is not None: self.status_code = status_...
""" Here we create template function """ def function_file2(value=1): print(f"you have called function from file 2 level 1") return value + 1
def build_response(parameters): response = {} if("success" in parameters and parameters["success"] == True): response['success'] = True else: response['success'] = False if("response" in parameters): response["response"] = parameters["response"] if("error" in parameters): ...
f = open("Q20/testinputs.txt","r") #ques_input = [i.strip("\n") for i in f.readlines()] a,b = f.read().split("\n\n") b = "".join(b).split("\n") trans = [] for i in range(-1,2,1): for j in range(-1,2,1): trans += [(i,j)] # rowlength = len(b[0]) # top_row = [inf_symbol] * (rowlength+4) inf_symbol = "." fli...
COMPANY_SCALE_CHOICE = [ ('0-15', '少于 15 人'), ('15-50', '15 - 50 人'), ('50-150', '50 - 150 人'), ('150-500', '150 - 500 人'), ('500-2000', '500 - 2000 人'), ('2000-', '2000 人以上') ] COMPANY_FINANCING_CHOICE = [ ('none', '未融资'), ('angel', '天使轮'), ('a', 'A 轮'), ('b...
goal = int(input('Write a number: ')) epsilon = 0.01 low = 0.0 high = max(1.0, goal) answer = (high + low) / 2 while abs(answer**2 - goal) >= epsilon: if answer**2 < goal: low = answer else: high = answer answer = (high + low) / 2 print(f'The square root of {goal} is {answer}')
class CustomListIndexException(Exception): pass class CustomListTypeException(Exception): pass class CustomListSumException(Exception): pass
# len = 1001 tp_qtys = ( (0.0, 0.0, 0.0, 0.0, 1.0), (0.0, 0.0, 0.0, 0.1, 0.9), (0.0, 0.0, 0.0, 0.2, 0.8), (0.0, 0.0, 0.0, 0.3, 0.7), (0.0, 0.0, 0.0, 0.4, 0.6), (0.0, 0.0, 0.0, 0.5, 0.5), (0.0, 0.0, 0.0, 0.6, 0.4), (0.0, 0.0, 0.0, 0.7, 0.3), (0.0, 0.0, 0.0, 0.8, 0.2), (0.0, 0.0, 0...
def binary_prefix(value, binary=True): '''Return a tuple with a scaled down version of value and it's binary prefix Parameters: - `value`: numeric type to trim down - `binary`: use binary (ICE) or decimal (SI) prefix ''' SI =...
a, b, c = [int(x) for x in input().split()] if c >= a and c <= b: print("Yes") else: print("No")
""" All modules contained in frontend were written to be compiled bythe transpiler (transcrypt), they were not tested in Cpython. """
def lambda_handler(event, context): print("event ->", event) print("context ->", context) return {"statusCode": "200", "body" : "hello from user profile"}
# is.numeric() verifica se o conteúdo da string pode ser convertido para número num = '3' palavra = 'Olá' decimal = '5.2a' print(num.isnumeric()) print(palavra.isnumeric()) print(palavra.isalpha())
#coding=utf-8 ''' 删除设备:Dev_Del request: { "user_id":"1", #设备所属的用户 "dev_id":1, #模块的id } return: { "error":"SUCCESS", # } ''' def main(data): cip=data['client_ip'] par=data['params'] red=data['red'] dbconn=data['dbconn'] cur=data['dbcursor'] assert('dev_id' in par) cur.execute('''delete from...
class SDKConfig(object): """ The class to configure the SDK. """ def __init__(self, auto_refresh_fields=False, pick_list_validation=True, read_timeout=None, connect_timeout=None): """ Creates an instance of SDKConfig with the following parameters Parameters: auto_re...
#coding: UTF8 """ Module description. """
# Python Classes and Objects # Python is an Object-oriented Programming Language and almost everything in Python is an object with it properties and methods # A Python Class is like an object constructor or a blueprint for creating objects class Employee: # This "Employee" class contains one variable "age" ag...
def traverse_nested_dict(d): iters = [d.iteritems()] while iters: it = iters.pop() try: k, v = it.next() except StopIteration: continue iters.append(it) if isinstance(v, dict): iters.append(v.iteritems()) yield k, v def tra...
T = int(input()) for i in range(T): n_A = int(input()) A = set([int(j) for j in input().split(' ')]) n_B = int(input()) B = set([int(j) for j in input().split(' ')]) if not A.difference(B): print("True") else: print("False")
bad_char = {"," , "₹"} def Clean_price(price): for char in bad_char: price = price.replace(char,'') return float(price)
# Принадлежит ли точка квадрату - 1 def is_point_in_square(x, y): axis_x = -1 <= x <= 1 axis_y = -1 <= y <= 1 return axis_x and axis_y if __name__ == '__main__': x, y = float(input()), float(input()) if is_point_in_square(x, y): print("YES") else: print("NO")
for _ in range(int(input())): n=int(input()) if(n%4==0 or n%4==1): print((n//4)**2) else: print(((n//4)+1) * (n//4))
class TSTreeNode(object): def __init__(self, char, key, value, low, eq, high): self.char = char self.key = key self.low = low self.eq = eq self.high = high self.value = value def __repr__(self): return f"{self.key}:{self.value}<{self.low and self.low...
BASE_URL = 'https://imdb.com' URLS = { 'Top 250 movies': '/chart/top/', 'Most popular movies': '/chart/moviemeter/', 'Top 250 TV shows': '/chart/toptv/', 'Most popular TV shows': '/chart/tvmeter/', 'Lowest rated movies': '/chart/bottom/', } def get_url(url_key): if url_key in URLS: re...
#Array curso = " Curso de Python " print(curso.strip()) # remove os espaços print("Tamanho: " +str (len(curso)))
""" Useful base functionality for use internally by the operations modules """ class Operation(object): """ An abstract operation that represents some modification/action on this operations's image. Implementation of a particular operation can be created by subclassing this and then overidding the `ru...
while True: try: a = float(input('Number: ')) except ValueError: print('Please, numbers only.') continue break print('You entered a number: {}'.format(a))
class Solution: def maxProduct(self, nums: List[int]) -> int: ans , max_p, min_p = nums[0], 1, 1 for num in nums: max_p, min_p = max(num, min_p*num, max_p* num), min(num, min_p*num, max_p*num) ans = max(ans, max_p) return ans
# Exercício Python 086: Crie um programa que declare uma matriz de dimensão 3x3 e preencha com valores lidos pelo teclado. # No final, mostre a matriz na tela, com a formatação correta. #Inicializando com 0's. matrix = [[0,0,0], [0,0,0], [0,0,0]] for i in range(0,3): for j in range(0,3): matrix[i][j] = int(inpu...
class Solution: # @param n, an integer # @return an integer def reverseBits(self, n): t = bin(n)[2:] return int(((32 - len(t)) * "0" + t)[: : -1], 2)
'''Simple parsing using mxTextTools See the /doc subdirectory for introductory and general documentation. See license.txt for licensing information. (This is a BSD-licensed package). ''' __version__="2.1.1"
class Stack: def __init__(self): self.stack = [] def push(self, el): self.stack.append(el) def pop(self): return self.stack.pop() def peek(self): return self.stack[-1] def is_empty(self): return len(self.stack) == 0
class Student: def __init__(self, name, phy, chem, bio): self.name = name self.phy = phy self.chem = chem self.bio = bio def totalObtained(self): return(self.phy + self.chem + self.bio) def percentage(self): return((self.totalObtained() / 300) * 100)
local_var = "foo" class C: local_var = local_var #pass def foo(self): print(self.local_var) C().foo()
numero = int(input("\033[35mMe diga um número qualquer:\033[m ")) par = numero % 2 == 0 if par: print("\033[36mEsse número é PAR!\033[m") else: print("\033[36mEsse número é ÍMPAR!\033[m")
n = int(input()) lista = list(map(int,input().split(" "))) menor = lista[0] posicao = 0 for i in range(len(lista)): if menor > lista[i]: menor = lista[i] posicao = i print("Menor valor: {}".format(menor)) print("Posicao: {}".format(posicao))
a = list(map(int, input().split())) def mergesort(a): if len(a) > 1: mid = len(a) // 2 left = a[:mid] right = a[mid:] mergesort(left) mergesort(right) i = j = k = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: ...
# -*- coding: utf-8 -*- # # Figure 14-2 from page 284 class Item(object): def __init__(self, n, v, w): self._name = n self._value = v self._weight = w def get_name(self): return self._name def get_value(self): return self._value def get_weight(self): retu...
''' Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. A leaf is a node with no children. ''' # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right...
# # PySNMP MIB module AP64STATS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AP64STATS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:07:11 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/env python # encoding: utf-8 ''' @author: Jason Lee @license: (C) Copyright @ Jason Lee @contact: jiansenll@163.com @file: jianzhi_offer_65_1.py @time: 2019/4/25 15:29 @desc: ''' class Solution: def maxInWindows(self, num, size): if not num or size <= 0: return [] if ...
n=int(input("Enter the number : ")) sum=0 order=len(str(n)) copy_n=n while(n>0): digit=n%10 sum+=digit**order n=n//10 if(sum==copy_n): print(f"{copy_n} is an armstrong number") else: print(f"{copy_n} is not an armstrong number")
# Aula 15 - Interrompendo repetições while cont = soma = 0 while True: num = int(input('Digite um numero: ')) if num == 999: break soma += num cont += 1 print('FIM!') print(f'Os {cont} numeros somados deram = {soma}.')
a = True while a: if(not a): a = get() else: execute(b) a = execute(mogrify(a))