content
stringlengths
7
1.05M
#!/usr/bin/python3 def recsum(n): return n if n<=1 else n+recsum(n-1) n = int(input("Enter your number\t")) if n < 0: print("Enter a positive number") else: print("The sum is",recsum(n))
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ d = {} left = -1 right = 0 max = 0 if len(s) < 2: return len(s) while right < len(s)-1: d[s[right]] = right ...
# -*- coding: utf-8 -*- """ @Datetime: 2019/1/2 @Author: Zhang Yafei """
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'MiracleWong' # AOOP 之 多重继承 # 地址:https://www.liaoxuefeng.com/wiki/1016959663602400/1017502939956896 class Animal(object): pass # 大类: class Mammal(Animal): pass class Bird(Animal): pass class Runnable(object): def run(self): prin...
raio = float(input()) pi = 3.14159 VOLUME = (4 / 3) * pi * (raio**3) print("VOLUME = {:.3f}".format(VOLUME))
dias = float(input('Quantos dias o carro foi alugado? ')) km = float(input('Quantos Km rodados? ')) dias = dias * 60 # Da pra fazer melhor km = km * 0.15 print('O valor a pagar pelo aluguel é de {:.2f}'.format(dias + km))
# automatically generated by the FlatBuffers compiler, do not modify # namespace: proto class AuthMethod(object): ANONYMOUS = 0 COOKIE = 1 TLS = 2 TICKET = 3 CRA = 4 SCRAM = 5 CRYPTOSIGN = 6
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class BaseError(Exception): """Base error for all test runner errors.""" def __init__(self, message, is_infra_error=False): super(BaseError, self)....
km = int(input('Qual a distancia em Km para o destino?')) if km > 200: print('O preço da passagem é de R${}'.format(km * 0.45)) else: print('O preço da passagem é de R${}'.format(km * 0.50))
def for_e(): for row in range(6): for col in range(4): if row==2 or row==1 and col%3!=0 or row==4 and col>0 or col==0 and row==3: print("*",end=" ") else: print(" ",end=" ") print() def while_e(): row=0 while row<6: ...
""" Copyright 2017 ARM Limited 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 dis...
# //Faça um programa que leia um número inteiro qualquer e mostre na tela a sua tabuada. # //N = int(input('Digite um Nº para verificar sua tabuada: \n')) # //print('---------------') # //print(N, 'x 0 =', N*0) # //print(N, 'x 1 =', N*1) # //print(N, 'x 2 =', N*2) # //print(N, 'x 3 =', N*3) # //print(N, 'x 4 =', N...
def selection_sort(elements): for i in range(len(elements) - 1): min_index = i for j in range(i + 1, len(elements)): if elements[min_index] > elements[j]: min_index = j elements[i], elements[min_index] = elements[min_index], elements[i] return elements ele =...
def ValidaCpf(msg='Cadastro de Pessoa Física (CPF): ', pont=True): """ -> Função para validar um CPF :param msg: Mensagem exibida para usuário antes de ler o CPF. :param pont: Se True, retorna um CPF com pontuação (ex: xxx.xxx.xxx-xx). Se False, retorna um CPF sem pontuação (ex: xxxxxxxxxxx) ...
tab = 1 while tab <= 10: print("Tabuada do", tab, ":", end="\t") i = 1 while i <= 10: print(tab*i, end = "\t") i = i + 1 print() tab = tab + 1
# -*- coding: utf-8 -*- { 'name': 'GST Pos Order Line Menu', 'version': '12.0.0.4', 'sequence': 1, 'category': 'Sales', "author": "Guadaltech Soluciones tecnológicas S.L.", 'depends': ['point_of_sale', 'tis_catch_weight', 'tis_catch_weight_extension'], 'data':...
load("@bazel_skylib//lib:shell.bzl", "shell") def kubebuilder_manifests(name, srcs, config_root, **kwargs): native.genrule( name = name, srcs = srcs, outs = [name + ".yaml"], cmd = """ tmp=$$(mktemp --directory) cp -aL "%s/." "$$tmp" $(location @io_k8s_sigs_kustomize_kustomize_v4//:...
def chk_p5m(n): if n%5==0: return 0 elif n==1: return n for i in range(2,n): if n%i==0: return n return 0 def fab(n): f=[0,1] return [chk_p5m((f:=[f[-1],f[-1]+f[-2]])[0]) for i in range(n)] #i know it's little confusing most won't understand... but tried to do somethin...
'''Exercício Python 072: Crie um programa que tenha uma dupla totalmente preenchida com uma contagem por extenso, de zero até vinte. Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso.''' #---------------------------------------------------- tupla20 = ('zero','um', 'dois','três','quat...
'''2) Faça um programa, com uma função que necessite de um argumento. A função retorna o valor de caractere ‘P’, se seu argumento for positivo, e ‘N’, se seu argumento for zero ou negativo.''' def pn(x): if x < 0: return "N" elif x > 0: return "P" else: return "0" num...
n = int(input('Digite um numero :')) count = 0 for c in range(1, n + 1): if n % c == 0: print('\033[31m', end='') count = count+1 else: print('\033[m', end='') print('{}'.format(c), end=' ') print('\n \033[mo numero {} pode ser dividido {} vezes'.format(n, count)) if count == 2: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Environment Base Class __author__: Conor Heins, Alexander Tschantz, Brennan Klein """ class Env(object): def reset(self, state=None): raise NotImplementedError def step(self, action): raise NotImplementedError def render(self): ...
class Solution: def largestValsFromLabels(self, values, labels, num_wanted, use_limit): zipped = list(zip(values, labels)) _dict = {x: 0 for x in set(labels)} ans = 0 for v, l in reversed(sorted(zipped)): if num_wanted == 0: return ans if _dic...
# Тестируем функцию def res(a, b): r = a * b return r res(10, 10) def test_func_res(): assert res(10, 10) == 100
""" Package contains: Database Class Decoder Class Cleaner Class MyHTMLParser Class """
class Human(): sum = 0 def __init__(self, name, age): self.name = name self.age = age def get_name(self): print(self.name) def do_homework(self): print('parent method')
d = { "no": "yes" } class CustomError: def __init__(self, fun): self.fun = fun def __call__(self, *args, **kwargs): try: return self.fun(*args, **kwargs) except Exception as e: print(e) raise Exception(d.get(str(e))) @CustomError def a(): ...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Documentation', 'category': 'Website', 'summary': 'Forum, Documentation', 'description': """ Documentation based on question and pertinent answers of Forum """, 'depends': [ ...
# Databricks notebook source # MAGIC %md # MAGIC <img src="https://github.com/billkellett/flight-school-resources/blob/master/images/databricks icon.png?raw=true" width=100/> # MAGIC <img src="/files/flight/Megacorp.png?raw=true" width=200/> # MAGIC # Democratizing MegaCorp's Data # MAGIC # MAGIC ## MegaCorp's current...
# binary search def binary(srchlist,srch): """list needs to be in ascending order to search for element""" first = 0 last = len(srchlist)-1 while first <= last: mid = (first + last)/2 if srch > srchlist[mid]: first = mid+1 elif srch < srchlist[mid]: last = mid-1 else: return mid return -1
#Longest Collatz Sequence #Solving for Project Euler.Net Problem 14. #Given n -> n/2 (n is even) # n -> 3n + 1 (n is odd) # #Which starting number, under one million, produces the longest chain? # #By Alex Murshak def collatz(n): count = 0 while n>1: if n%2==0: n= n/2 else: ...
class Solution: def romanToInt(self, s: str) -> int: translations = { "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000 } number = 0 s = s.replace("IV", "IIII").replace("IX", "V...
budget = float(input()) price_1kg_flour = float(input()) colored_eggs = 0 price_1pack_eggs = price_1kg_flour * 0.75 price_250ml_milk = (price_1kg_flour + (price_1kg_flour * 0.25)) / 4 price_1_bread = price_1pack_eggs + price_1kg_flour + price_250ml_milk count_breads = int(budget // price_1_bread) for current_bread...
def min_value(gameState): """ Return the game state utility if the game is over, otherwise return the minimum value over all legal successors # HINT: Assume that the utility is ALWAYS calculated for player 1, NOT for the "active" player """ # TODO: finish this function! if gam...
#!/usr/bin/env python3 """ Exercise 20: Word Count Mimic the Un*x "wc" command to count lines, words, and characters. """ def wc(filename): lines = 0 words = 0 characters = 0 distinct_words = set() with open(filename) as f: for line in f: lines += 1 wor...
# O(n) time | O(h) space - where n is the number of nodes in the Binary Tree # and h is the height of the Binary Tree def nodeDepths(root, depth = 0): if root is None: return 0 return depth + nodeDepths(root.left, depth + 1) + nodeDepths(root.right, depth + 1) # This is the class of the input binary tree. clas...
class KeySpline(Freezable,ISealable,IFormattable): """ This class is used by a spline key frame to define animation progress. KeySpline(controlPoint1: Point,controlPoint2: Point) KeySpline() KeySpline(x1: float,y1: float,x2: float,y2: float) """ def CloneCore(self,*args): """ CloneCore(se...
# Lesson 1 - Hello world and entry points # # All languages have an "entry point" # An entry point is where the program begins execution # "Main" is a common keyword used to specify the entry point # # Common C style entry points: # int main() # { # return 0; # } # or # void main() # { # } # Hello World is a common ...
PASSWD = '12345' def password_required(func): def wrapper(): password = input('Cual es el passwd ? ') if password == PASSWD: return func() else: print('error') return wrapper def p_decorate(func): def func_wrapper(name): return "<p>{0}</p>".format(fu...
# In the first line, we are calling the print() function to display # an informational message. It is the same as printing like # we previously did in the hello world file print('Interest Calculator:') # These next three lines, we're using the following variables to store # the input provided by the user. The variab...
def euclid(n, m): if n > m: r = m m = n n = r r = m % n while r != 0: m = n n = r r = m % n return n
"""Loads the gflags library""" # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. def clean_dep(dep): return str(Label(dep)) def repo(): # gflags native.new_local_repository( name = "com_github_gflags_gflags", build_file = clean_dep("//third...
def bisection_search(arr: list, n: int) -> bool: mid = len(arr) // 2 if len(arr) < 2: if arr[mid] == n: return True else: return False else: if arr[mid] == n: return True else: return bisection_search(arr[:mid], n) if arr[mid] >...
def extractNetorutranslationsWordpressCom(item): ''' Parser for 'netorutranslations.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('pilgrimage', 'Netorare Pilgrimage of the ...
""" File: student_info_dict.py ------------------------------ This program puts data in a text file into a nested data structure where key is the name of each student, and the value is the dict that stores the student info """ # The file name of our target text file FILE = 'romeojuliet.txt' # Contains the chars we ...
# 迭代器对象:__iter__和__next__ # python中所有的迭代环境都会尝试先用__iter__方法,然后尝试__getitem__ # 从技术角度来讲迭代环境是通过调用内置函数iter去尝试寻找__iter__方法来实现的 # 这种方法应该返回一个迭代器对象,如果已经提供了Python就会重复调用这个迭代器对象的next # 对象知道发生StopIteration异常,如果没有找到这类__iter__就会改用__getitem__机制 # 定义迭代器类生成平方值 class Squares: def __init__(self, start, stop): self.value = star...
l1 = int(input('Digite o lado 1 ')) l2 = int(input('Digite o lado 2 ')) l3 = int(input('Digite o lado 3 ')) if l1+l2>l3 and l1+l3>l2 and l2+l3>l1: print(f'O triangulo PODE ser formado') else: print(f'O triangulo NAO PODE ser formado')
''' 02 - Creating two-factor Let's continue looking at the student_data dataset of students in secondary school. Here, we want to answer the following question: does a student's first semester grade ("G1") tend to correlate with their final grade ("G3")? There are many aspects of a student's life that could ...
def f(i): return i + 2 def g(i): return i > 1000 def applyF_filterG(L, f, g): """ Assumes L is a list of integers Assume functions f and g are defined for you. f takes in an integer, applies a function, returns another integer g takes in an integer, applies a Boolean function...
# # PySNMP MIB module CISCO-VOICE-DNIS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VOICE-DNIS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:03:03 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
""" oops """ print(0, 1 == 1, 0)
# acronymsBuilder.py # A program to build acronyms from a phrase # by Tung Nguyen def main(): # declare program function: print("This program builds acronyms.") print() # prompt user to input the sentence: sentence = input("Enter a phrase: ") # split the sentence into a list that con...
# x y x y #r1 = [[0, 0], [5, 5]] r1 = [[-5, -5], [-2, -2]] r2 = [[7, 1], [1, 8]] r3 = [[-1.2, 4], [3.7, 1.1]] def rect_intersection_area(r1, r2, r3): area = 0 r1_p1, r1_p2 = r1 r2_p1, r2_p2 = r2 r3_p1, r3_p2 = r3 right_x_p = 0 left_x_p = 0 top_y_p ...
# https://atcoder.jp/contests/abs/tasks/practice_1 def resolve(): a = int(input()) b, c = list(map(int, input().split())) d = input() print("{} {}".format(a + b + c, d))
class IpConfiguration: options: object def __init__(self, options): self.options = options
#!/usr/bin/env python3 # Compares two lexicon files providing several stats # @author Cristian TG # @since 2021/04/15 # Please change the value of these variables: LEXICON_1 = 'lexicon1.txt' LEXICON_2 = 'lexicon2.txt' SHOW_DETAILS = True DISAMBIGUATION_SYMBOL = '#' #################################################...
def three_word(a, b, c): title = a if title == '\"\"': title = "\'\'" else: title = "\'{0}\'".format(title) tag = b if tag == '\"\"': tag = "\'\'" else: tag = "\'{0}\'".format(tag) description = c if description == '\"\"': description = "\'\'" ...
# [Skill] Cygnus Constellation (20899) echo = 10001005 cygnusConstellation = 1142597 cygnus = 1101000 if sm.canHold(cygnusConstellation): sm.setSpeakerID(cygnus) sm.sendNext("You have exceeded all our expectations. Please take this as a symbol of your heroism.\r\n" "#s" + str(echo) + "# #q" + str(echo) +...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: ans = str(int(self.combine(l1)) + int(self.combine(l2))) return self...
def http_exception(response): raise HTTPException(response) class HTTPException(Exception): def __init__(self, response): self._response = response def __str__(self): return self._response.message @property def is_redirect(self): return self._response.is_redirect @p...
coins = [ 100, 50, 25, 5, 1 ] total = 0 change = 130 for i in range(len(coins)): numCoins = change // coins[i] change -= numCoins * coins[i] total += numCoins print(total) ''' numCoins = 75 // 100 = 0 change = change - 0 * 100 change = change '''
#!/usr/bin/env python # -*- coding: utf-8 -*- DELIMITER = "\r\n" def encode(*args): "Pack a series of arguments into a value Redis command" result = [] result.append("*") result.append(str(len(args))) result.append(DELIMITER) for arg in args: result.append("$") result.append(st...
#print hello with arguments def hello(name): print('hello ' + name) hello('bob') hello('alice')
n = int(input()) gerais = [e for e in input().split()] m = int(input()) proib = [e for e in input().split()] q = int(input()) arr = [e for e in input().split()] for i in range(q): key = arr[i] esq = 0 dir = m-1 achou = False while esq <= dir: meio = (esq + dir) // 2 if proi...
n = int(input()) calculadora = 1 for i in range(n): valor, operacao = input().split() valor = int(valor) if(operacao == '/'): calculadora = calculadora / valor else: calculadora = calculadora * valor print("{0:.0f}".format(calculadora))
BEHIND_PROXY = True SWAGGER_BASEPATH = "" DEFAULT_DATABASE = "dev" DATABASES = ["test"] ENV = "development" DEBUG = True
class Solution: def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int: ans = -math.inf maxHeap = [] # (y - x, x) for x, y in points: while maxHeap and x + maxHeap[0][1] > k: heapq.heappop(maxHeap) if maxHeap: ans = max(ans, x + y - maxHeap[0][0]) heap...
class Feature: def __init__(self, value, string, infix_string, size=0, fitness=1, original_variable=False): self.value = value self.fitness = fitness self.string = string self.infix_string = infix_string self.size = size self.original_variable = original_variable ...
def my_range(n): i = 0 while i <= n: yield i i += 1 yield 'there are no values left' gen = my_range(4) for i in range(7): print(next(gen))
""" pattern_stringHEAD_stringTAIL_list( "brianxxxcvbpythonvvvvvvvvvgghhbrianpppfgpython","brian","python") returns ["xxxcvb","pppfg"] pattern_stringHEAD_stringTAIL_list( "susanvenezuelastronggghhsusancanadastrong","susan","strong") returns ["venezuela","canada"] pattern_stringHEAD_stringTAIL_list( "boatxvmotorvvvmotorv...
def merge_values(original: dict, new_values: dict): """ if a value in a dictionary is also a dictionary we want to keep the old information inside it """ for key, value in new_values.items(): if isinstance(value, dict): original[key] = merge_values(original.get(key, dict()), value) else: origi...
# Advent of code Year 2021 Day 02 solution # Author = Anmol Gupta # Date = December 2021 input = list() with open("input.txt", "r") as input_file: input = input_file.readlines() def get_command(line): splitInput = line.strip().split() return (splitInput[0], int(splitInput[1])) input_commands = [get_com...
class nullcontext: """ A replacement for `contextlib.nullcontext` for python versions before 3.7 """ def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): pass
""" * Assignment: Sequence List Many * Required: yes * Complexity: easy * Lines of code: 3 lines * Time: 5 min English: 1. Create list `a` with data from row 1 2. Create list `b` with data from row 2 3. Create list `c` with data from row 3 4. Rewrite data manually: a. Do not automate by writing...
{ 'targets': [ { 'target_name': 'node_libtiepie', 'sources': [ 'src/libtiepie.cc' ], 'include_dirs': [ '<!(node -e "require(\'nan\')")' ], 'conditions': [ [ 'OS=="linux"', { 'libraries': ['-ltiepie'] ...
# Write a program that prompts the user for a measurement in meters and then con­ # verts it to miles, feet, and inches. measurementMeters = float(input("Enter the measurement in meters: ")) measurementMiles = measurementMeters * 0.000621371192 measurementFeet = measurementMeters * 3.2808399 measurementInches = measu...
def typist(s): cur=res=0 for i in s: next_val=int(i.isupper()) res+=1+int(next_val!=cur) cur=next_val return res
class ScopeCache(object): def __init__(self, name: str): """ :param name: human-readable name :param scoped_components: components managed by this scope """ self.name = name def handles_component(self, component: type) -> bool: raise NotImplementedError def...
n=int(input()) for i in range(n): a,b,c=[int(x) for x in input().split()] sum=a+b+c if sum==180: print("YES") else: print("NO")
beta = 9. gamma = 0.6 logLX = beta + gamma * logLUV scatter = 0.4 # 0.35 # LX: monochromatic at 2 keV # LUV: monochromatic at 2500 AA
class Solution: def isValid(self, s): if s == '': return True sList = list(s) stack = [] for chr in sList: if len(stack) == 0: stack.append(chr) else: stack.pop() if (chr == ')' and stack[-1] == '(') or (chr == ']' a...
#! /usr/bin/env python """ A singleton pattern implemented in python. Adapted from ActiveState Code Recipe 52558: The Singleton Pattern implemented with Python http://code.activestate.com/recipes/52558/ """ class Singleton(object): """ A python singleton """ class SingletonImplementation: ...
class SecretKey: """A wrapper class for representing secret key. Typical format of secret key data would be [p1. p2, p3...] where pi represents polynomials for each coefficient modulus. Elements of each polynomails is taken from {-1, 0, 1} represented in their respective modulus. Attributes: ...
# For loops are used ot iterate over all elements of an iterable # They use use the 'for variable in iterable' syntax for i in range(0, 3): # x is defined in the for loop and usable in this body of the for loop print(i) # prints 0, 1, 2 each on a new line for i in [10, "Hello", "World"]: # We call this it...
""" Lista em Python fatiamento append, insert, pop, del, clear, extend, min, max range """ secreto = 'Perfume' digitadas = [] chances = 3 while True: if chances <= 0: print('Você perdeu!!!') break letra = input('Digite uma letra: ') if len(letra) > 1: print('Ahhh isso não vale, di...
#!/usr/bin/env python #-*- coding: utf-8 -*- class Fitness: def __init__(self, criterion, *args, **kwargs): """ Simplest single criterion fitness object. :param criterion: Generic container to store the fitness criterion;. :type criterion: object """ self.criterion ...
weight = float(input("Please enter weight in kilograms: ")) height = float(input("Please enter height in meters: ")) bmi = weight/(height * height) print("BMI is: ",bmi)
#集合.py def n_gram(txt, n): result = [] for i in range(0, len(txt) - n + 1): result.append(txt[i:i + n]) return result #足し算、掛け算、引き算 # 集合 set_x = set(n_gram('paraparaparadise', 2)) print('X:' + str(set_x)) set_y = set(n_gram('paragraph', 2)) print('Y:' + str(set_y)) # 和 set_wa = s...
# -*-coding:Utf-8 -* # Copyright (c) 2010 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # l...
""" A package in which functionality specific to MAGIC H2020 project can be found The rest of the source code should not depend on MAGIC, being base on "plain" MuSIASEM and of course its evolution inside MAGIC project. """
_base_ = ['./pipelines/rand_aug.py'] # dataset settings dataset_type = 'ImageNet' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict( type='RandomResizedCrop', size=224, backend='pil...
# Ler os valores de quatro notas escolares bimestrais de um aluno representadas pelas variáveis N1, N2, N3 e N4.Calcular a média aritmética (variável MD1) desse aluno e apresentar a mensagem "Aprovado" se a média obtida for maior ou igual a 7; caso contrário, o programa deve solicitar a quinta nota (nota de exame, repr...
RELEVANT_EXTENSIONS = [ "java", "c", "cpp", "h", "py", "js", "xml", "go", "rb", "php", "sh", "scale", "lua", "m", "pl", "ts", "swift", "sql", "groovy", "erl", "swf", "vue", "bat", "s", "ejs", "yaml", "yml", "...
with open ('2gram_output_birkbeck.txt') as f: with open ('../data/birkbeck_correct.txt') as g: corrects = [] i = 0 for line in g: corrects.append(line.strip()) for line in f: try: A = line.split(' potential diatance_word:(') ...
def set_session_user_profile(request, profile=None): user_profile = { 'use_pop_article': True, 'theme': '', 'is_authenticated': request.user.is_authenticated } if profile: user_profile['use_pop_article'] = profile.use_pop_article user_profile['theme'] = profile.theme ...
class Solution(object): def readBinaryWatch(self, num): """ :type num: int :rtype: List[str] """ ans=[] for i in range(2**10): if(bin(i).count('1')==num): minute = i & 0b0000111111 hour = i>>6 if h...
# -*- coding: utf-8 -*- # Área de un círculo pi = 3.14159 area_circulo = lambda entRadio:pi*(entRadio**2) radio = 8 # 1ra forma print("El área del círculo es", area_circulo(radio)) # 2da forma print("El área del círculo es",(lambda entRadio:pi*(entRadio**2))(radio))
def squared(n): return n * n def cubed(n): return n * n * n def raise_power(n, power): total = 1 for t in range (power) : total = total * n return total def is_divisible(n, t): return n % t == 0 def is_even(n): return n % 2 == 0 def is_odd(n): return n % 2 != 0 p...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :rtype: ...
# HELP INTERACTIVE help(print) print(input.__doc__) # DOCSTRINGS def contador(i, f, p): """ -> Faz uma contagem e mostra na tela. :param i: início da contagem :param f: final da contagem :param p: passo da contagem :return: sem retorno """ c = i while c <= f: print(c, end='...