content
stringlengths
7
1.05M
def solution(value): print("Solution: {}".format(value))
latam_countries = """Argentina Bolivia Brazil Chile Colombia Ecuador French Guiana Guyana Paraguay Peru Suriname Uruguay Venezuela Belize Costa Rica El Salvador Guatemala Honduras Mexico Nicaragua Panama Antigua & Barbuda Aruba Bahamas Barbados Cayman Islands Cuba Dominica Dominican Republic Grenada Guadeloupe Haiti Ja...
# See LICENSE for licensing information. # # Copyright (c) 2021 Regents of the University of California and The Board # of Regents for the Oklahoma Agricultural and Mechanical College # (acting for and on behalf of Oklahoma State University) # All rights reserved. # class test_bench: """ Class to generate the ...
def test(): # Here we can either check objects created in the solution code, or the # string value of the solution, available as __solution__. A helper for # printing formatted messages is available as __msg__. See the testTemplate # in the meta.json for details. # If an assertion fails, the message...
n = int(input()) #ans = 0 def rec(currentValue, usedValue, counter): #global ans if currentValue > n: return if usedValue==7: #ans += 1 counter.append(1) rec(currentValue*10 + 7, usedValue|1<<0, counter) rec(currentValue*10 + 5, usedValue|1<<1, counter) rec(currentValue*...
class SimpleSpriteList: def __init__(self) -> None: self.sprites = list() def draw(self) -> None: for sprite in self.sprites: sprite.draw() def update(self) -> None: for sprite in self.sprites: sprite.update() def append(self, sprite) -> None: ...
resp = 's' cont = soma = 0 list = [] while resp == 's': num = int(input('digite um número: ')) cont += 1 soma += num list.append(num) resp = input('Deseja continuar? [s/n]').lower().strip() print(f'Você digitou {cont} números\n' f'A média deles é {soma/cont}\n' f'O maior número é o {max...
""" Problem: https://www.hackerrank.com/challenges/nested-list/problem Max Score: 10 Difficulty: Easy Author: Ric Date: Nov 13, 2019 """ def secondLow(classList): secondLowScore = sorted(set(m[1] for m in classList))[1] result = sorted([m[0] for m in classList if m[1] == secondLowScore]) return result n =...
numberLines = int(input()) while 0 < numberLines: number = int(input()) sum = 0 for i in range(number): if i%3 == 0 or i%5 == 0: sum = sum + i print(sum) numberLines = numberLines - 1
#!/usr/bin/env python3 #bpm to millisecond for compressor release def compressor_release(bpm, note_length): ''' Inputs: BPM, note length Output: compression release time Note: Function returns perfect compression release time for standard note lengths. Electronic music is not standard mus ic so t...
#Mock class for GPIO BOARD = 1 BCM = 2 OUT = 1 IN = 1 HIGH = 1 LOW = 0 def setmode(a): print ("setmode GPIO",a) def setup(a, b): print ("setup GPIO", a, b) def output(a, b): print ("output GPIO", a, b) def cleanup(): print ("cleanup GPIO", a, b) def setwarnings(flag): print ("setwarnings"...
__author__ = 'yinjun' class Solution: """ @param n: An integer @return: An integer """ def climbStairs(self, n): # write your code here if n<=2 : return n stairs = [0 for i in range(n)] stairs[0] = 1 stairs[1] = 2 for i in range(2, n):...
# Damage Skin - Violetta success = sm.addDamageSkin(2433197) if success: sm.chat("The Damage Skin - Violetta has been added to your account's damage skin collection.")
#!/usr/bin/env python3 formulas = [ "XNd perr", "PNd (PNd (call And (XNu exc)))", "PNd (han And (XNd (exc And (XBu call))))", "G (exc --> XBu call)", "T Ud exc", "PNd (PNd (T Ud exc))", "G ((call And pa And ((~ ret) Ud WRx)) --> XNu exc)", "PNd (PBu call)", "PNd (PNd (PNd (PBu call)...
numeros = [] for i in range(3): numeros.append(int(input(F'Digite o {i + 1}º número: '))) if len(numeros) == 1: maior = numeros[0] menor = numeros[0] if numeros[i] > maior: maior = numeros[i] elif numeros[i] < menor: menor = numeros[i] print(f'O maior número digitado foi:...
class Iterator(object): def __init__(self, iterable, looping: bool = False): self.iterable = iterable self.lastPos = 0 self.looping = looping def __next__(self): pos = self.lastPos self.lastPos += 1 if self.lastPos >= len(self.iterable): if self.looping: self.lastPos = 0 else: raise StopIt...
################################################################################## #### Runtime configuration ################################################################################## sampleCounter = 0 ################################################################################## #### General configurati...
# REPLACE EVERYTHING IN CURLY BRACKETS {}, INCLUDING THE BRACKETS THEMSELVES. # THEN RENAME THIS FILE TO constants.py AND MOVE IT INTO YOUR PROJECT'S ROOT CONNECT_BASE_URL = '{YOUR BASE URL}/api/xml?action=' CONNECT_LOGIN = '{YOUR LOGIN}' CONNECT_PWD = '{YOUR PASSWORD}' # USERS YOU WANT TO BE ABLE TO EXCLUDE FROM REP...
# -*- coding: utf-8 -*- def crearCombinaciones(abecedario): for d1 in abecedario: for d2 in abecedario: for d3 in abecedario: for d4 in abecedario: #print(d1 + '' + d2 + '' + d3 + '' + d4) f.write(d1 + '' + d2 + '' + d3 + '' + d4) ...
set_name(0x8009CFEC, "VID_OpenModule__Fv", SN_NOWARN) set_name(0x8009D0AC, "InitScreens__Fv", SN_NOWARN) set_name(0x8009D19C, "MEM_SetupMem__Fv", SN_NOWARN) set_name(0x8009D1C8, "SetupWorkRam__Fv", SN_NOWARN) set_name(0x8009D258, "SYSI_Init__Fv", SN_NOWARN) set_name(0x8009D364, "GM_Open__Fv", SN_NOWARN) set_name(0x8009...
class MusicTextView: """This class represents one instance of a view for the music maze. The purpose of this class is to represent the maze through text and also to create a basis on the methods needed to cover all of the view's expected features for sanity checking purposes."""
lr_scheduler = dict( name='poly_scheduler', epochs=30, power=0.9 )
size(800, 600) background(255) triangle(20, 20, 20, 50, 50, 20) triangle(200, 100, 200, 150, 300, 320) triangle(700, 500, 800, 550, 600, 600)
# 深度优先搜索 DFS def DFS(graph, start): """深度优先搜索,start为起点""" stack = [] stack.append(start) seen = set() seen.add(start) while len(stack) > 0: vertex = stack.pop() nodes = graph[vertex] for w in nodes: if w not in seen: stack.append(w) ...
def get_bit_mask(bit_num): """Returns as bit mask with bit_num set. :param bit_num: The bit number. :type bit_num: int :returns: int -- the bit mask :raises: RangeError >>> bin(pifacecommon.core.get_bit_mask(0)) 1 >>> pifacecommon.core.get_bit_mask(1) 2 >>> bin(pifacecommon.cor...
""" Module: 'lidar' on M5 FlowUI v1.4.0-beta """ # MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module with ESP32') # Stubber: 1.3.1 def deinit(): pass def distance(): pass def draw_map(): pass def get_distance(): pass def ge...
"""Functions for determining micrograph scaling. """ def determine_scaling(image, bar_length_um, bar_frac): r"""Determine um per pixels scaling for an image provided the bar length in um and the fraction of the image for which it occupies. Parameters ---------- image : ndarray Input image...
black = (0, 0, 0) red = (255, 0, 0) orange = (255, 152, 0) deep_orange = (255, 87, 34) brown = (121, 85, 72) green = (0, 128, 0) light_green = (139, 195, 74) teal = (0, 150, 136) blue = (33, 150, 136) purple = (156, 39, 176) pink = (234, 30, 99) deep_purple = (103, 58, 183) color_dict = { 0: black,...
#part 1 count = 0 expected_fields = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'} received_fields = set() with open("input.txt") as f: for line in f: if line != '\n': fields = {i[:3] for i in line.split(' ')} received_fields.update(fields) else: difference = e...
ACTION_CREATED = 'created' ACTION_UPDATED = 'updated' ACTION_DELETED = 'deleted' ACTION_OTHER = 'other' ACTION_CHOICES = ( (ACTION_CREATED, ACTION_CREATED), (ACTION_UPDATED, ACTION_UPDATED), (ACTION_DELETED, ACTION_DELETED), (ACTION_OTHER, ACTION_OTHER), ) LOG_LEVEL_CRITICAL = 'CRITICAL' LOG_LEVEL_ERRO...
""" A command line interface to the qcfractal. """ # from tornado.options import options, define # import tornado.ioloop # import tornado.web # define("port", default=8888, help="Run on the given port.", type=int) # define("mongod_ip", default="127.0.0.1", help="The Mongod instances IP.", type=str) # define("mongod_p...
def interest(n, principle_amount): def years(x): return principle_amount + (n * principle_amount * x) / 100 return years principle = 100000 home_loan = interest(7, principle) # percentage of 7 personal_loan = interest(11, principle) # percentage of 11 print(home_loan(20)) # for 20 years print(per...
class ProducerEvent: timestamp = 0 csvName = "" houseId = 0 deviceId = 0 id = 0 def __init__(self, timestamp, ids, csv_name): self.timestamp = int(timestamp) self.csvName = csv_name # ids_list = list(map(int, ids.replace("[", "").replace("]", "").replace("pv_producer", "...
# some mnemonics as specific to capstone CJMP_INS = ["je", "jne", "js", "jns", "jp", "jnp", "jo", "jno", "jl", "jle", "jg", "jge", "jb", "jbe", "ja", "jae", "jcxz", "jecxz", "jrcxz"] LOOP_INS = ["loop", "loopne", "loope"] JMP_INS = ["jmp", "ljmp"] CALL_INS = ["call", "lcall"] RET_INS = ["ret", "retn", "retf", "iret"] ...
def main(): # input N = int(input()) # compute N = int(1.08*N) # output if N < 206: print('Yay!') elif N == 206: print('so-so') else: print(':(') if __name__ == '__main__': main()
# -*- coding: utf-8 -*- strings = { 'test.fallback': 'A fallback string' }
def climb_stairs2(n: int) -> int: if n == 1 or n == 2: return n n1 = 1 n2 = 2 t = 0 for i in range(3, n + 1): t = n1 + n2 n1 = n2 n2 = t return t class StairClimber: # total variable needed for the recursive solution total = 0 # recursive, mathy w...
#!usr/bin/python # -*- coding:utf8 -*- def gen_func(): try: yield "http://projectesdu.com" except GeneratorExit: pass yield 2 yield 3 return "bobby" if __name__ == "__main__": gen = gen_func() next(gen) gen.close() next(gen)
""" ShellSort is mainly a variation of Insertion Sort. In insertion sort, we move elements only one position ahead. When an element has to be moved far ahead, many movements are involved. The idea of shellSort is to allow exchange of far items. In shellSort, we make the array h-sorted for a large value of h. We keep r...
list_images = [ ".jpeg",".jpg",".png",".gif",".webp",".tiff",".psd",".raw",".bmp",".heif",".indd",".svg",".ico" ] list_documents = [ ".doc",".txt",".pdf",".xlsx",".docx",".xls",".rtf",".md",".ods",".ppt",".pptx" ] list_videos = [ ".mp4",".m4v",".f4v",".f4a",".m4b",".m4r",".f4b",".mov",".3gp", "....
"""Aprimore o desafio anterior, mostrando no final: a) A soma de todos os valores pares digitados b) A soma dos valores da terceira coluna c) O maior valor da segunda linha""" matriz = list() linhas = list() for linha in range(0, 3): for coluna in range(0, 3): valor = int(input(f'Digite o da posição [{linha...
# Least Common Multiple (LCM) Calculator - Burak Karabey def LCM(x, y): if x > y: limit = x else: limit = y prime_numbers = [] # Start of Finding Prime Number if limit < 2: return prime_numbers.append(0) elif limit == 2: return prime_numbers.append(2) else: ...
# -*- coding: utf-8 -*- # See the "Code officiel géographique" on the INSEE website <www.insee.fr>. DEPARTMENT_CHOICES = ( # Metropolitan departments ('01', u'01 - Ain'), ('02', u'02 - Aisne'), ('03', u'03 - Allier'), ('04', u'04 - Alpes-de-Haute-Provence'), ('05', u'05 - Hautes-Alpes'), (...
# Dissecando uma Variável '''Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíveis sobre ela''' a = input('Digite algo: ') print('\033[1;30m''O tipo primitivo deste valor é', type(a)) print('Só tem espaços?', a.isspace()) print('É um número?', a.isnumeric())...
def is_prime(n): if n <= 1: return False elif n <= 3: return True elif n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True T = int(input()) for _ in range(T): if...
#!/usr/bin/env python3 sum=0 a=1 while a<=100: sum +=a a+=1 print(sum)
class PositionedObjectError(Exception): def __init__(self, *args): super().__init__(*args) class RelativePositionNotSettableError(PositionedObjectError): pass class RelativeXNotSettableError(RelativePositionNotSettableError): pass class RelativeYNotSettableError(RelativePositionNotSettableErro...
# Image types INTENSITY = 'intensity' LABEL = 'label' SAMPLING_MAP = 'sampling_map' # Keys for dataset samples PATH = 'path' TYPE = 'type' STEM = 'stem' DATA = 'data' AFFINE = 'affine' # For aggregator IMAGE = 'image' LOCATION = 'location' # In PyTorch convention CHANNELS_DIMENSION = 1 # Code repository REPO_URL = ...
#!/usr/local/bin/python3 # Copyright 2019 NineFx Inc. # Justin Baum # 3 June 2019 # Precis Code-Generator ReasonML # https://github.com/NineFX/smeagol/blob/master/spec/code_gen/precis_cp.txt fp = open('precis_cp.txt', 'r') ranges = [] line = fp.readline() code = "DISALLOWED" prev = "DISALLOWED" firstOccurence = 0 co...
"""Search filters for ExploreCourses queries""" # Term offered AUTUMN = "filter-term-Autumn" WINTER = "filter-term-Winter" SPRING = "filter-term-Spring" SUMMER = "filter-term-Summer" # Teaching presence INPERSON = "filter-instructionmode-INPERSON" ONLINEASYNC = "filter-instructionmode-ONLINEASYNC" ONLINESYNC = "filte...
# https://leetcode.com/problems/unique-morse-code-words/ class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: dictx = {"a": ".-", "b": "-...", "c": "-.-.", "d": "-..", "e": ".", "f": "..-.", "g": "--.", "h": "....", "i": "..", "j": ".---", "k": "-...
class BadBatchRequestException(Exception): def __init__(self, org, repo, message=None): super() self.org = org self.repo = repo self.message = message class UnknownBatchOperationException(Exception): def __init__(self, org, repo, operation, message=None): super() ...
# Faça um programa que leia algo e diga # seu tipo primitivo e diga todas as informações # possíveis dele do .is num = input('Digite algo:') print('='*40) print('O tipo primitivo do valor {} é {}'.format(num, type(num)))#vamos mandar o pc mostra o tipo primitivo print('*'*10) print('({}) é um número? {}'.format(n...
class Agent: def __init__(self, name): self.name = name def reset(self, state): # Completely resets the state of the Agent for a new game return def make_action(self, state): # Returns a valid move in (row, column) format where 0 <= row, column < board_len move = (0, 0) return move def u...
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ n=c=0;r=[] for x in map(int,[*open(0)][1].split()): if x<0: if n==2: r+=[c] n=1 c=0 else:n+=1 c+=1 r+=[c] print(len(r)) print(*r)
# # 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 Mon Apr 29 20:25:27 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
#!/usr/bin/env python # -*- coding: utf-8 -*- class GitCommandError(Exception): """ Exception which can be raised when git exits with a non-zero exit code. """ pass class InvalidUpgradePath(Exception): """ Exception which is thrown if an invalid upgrade path is detected. This is usually when...
TOKEN = b'd4r3d3v!l' def chall(): s = Sign() while True: choice = input("> ").rstrip() if choice == 'P': print("\nN : {}".format(hex(s.n))) print("\ne : {}".format(hex(s.e))) elif choice == 'S': try: msg = bytes.fromhex(input('msg to si...
# Python Class 2406 # Lesson 12 Problem 1 # Author: snowapple (471208) class Game: def __init__(self, n): '''__init__(n) -> Game creates an instance of the Game class''' if n% 2 == 0: #n has to be odd print('Please enter an odd n!') raise ValueError self.n ...
""" Challenge - Program Flow # TODO: Create a program that takes an IP address entered at the keyboard and prints out the number of segments it contains, and the length of each segment. An IP address consists of 4 numbers, separated from each other with a full stop. But your program should just count however many ar...
def BFS(graph,root,p1,max1): checked = [] visited=[] energy=[] level=[] l=[] l.append(root) level.append(l) checked.append(root) inienergy=14600 threshold=10 l1=0 flag=0 energy.append(inienergy) while(len(checked)>0): l1=l1+1 #print...
s="this this is a a cat cat cat ram ram jai it" l=[] count=[] i=0 #j=0 str="" for i in s: #print(i,end="") if i==" ": if str in l: for j in range(len(l)): if str == l[j]: count[j] += 1 str="" continue else: ...
class LRUCache: def __init__(self, capacity: int): self.db = dict() self.capacity = capacity self.time = 0 def get(self, key: int) -> int: if key in self.db: self.db[key][1] = self.time self.time += 1 return self.db[key][0] else: ...
# 2021.04.14 # Problem Statement: # https://leetcode.com/problems/majority-element/ class Solution: def majorityElement(self, nums: List[int]) -> int: # trivial question, no need to explain if len(nums) == 1: return nums[0] dict = {} for element in nums: if element not i...
def ParseGraphVertexEdge(file): with open(file, 'r') as fw: read_data = fw.read() res = read_data.splitlines(False) def ParseV(v_str): ''' @type v_str: string :param v_str: :return: ''' return [int(i) for i...
def kIsClicked(): print("Character moves right ") def hUsClikced(): print("Charater moves left") keepGoing = True #boolean = 뭐냐면 TRUE 또는 False냐의 변수 while True: userInput = input("which number do you want to choose? (1~9) type 9 ") if userInput == "k": kIsClicked() elif userI...
# -*- coding: utf-8 -*- """ Created on Sat Nov 3 13:54:22 2018 @author: David """ mainmenu = ["1:Add a new item ", "2:Move an item", "3:search an item", "4:view the inventory of a warehouse", "0: exit the system"] def menu(): # display a main menu for i in mainmenu: print(...
# @Title: 删除排序链表中的重复元素 II (Remove Duplicates from Sorted List II) # @Author: 18015528893 # @Date: 2021-02-12 21:18:52 # @Runtime: 56 ms # @Memory: 14.9 MB # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Soluti...
"""Tools to manage census tables.""" POSTGRES_COLUMN_NAME_LIMIT = 63 def _verified_column_name(column_name, limit=POSTGRES_COLUMN_NAME_LIMIT): if len(column_name) > limit: raise Exception('Column name {} is too long. Postgres limit is {}.'.format( column_name, limit)) return column_name ...
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: n = len(nums1) m = len(nums2) if (n > m): return self.findMedianSortedArrays(nums2, nums1) start = 0 end = n realmidinmergedarray = (n + m + 1) // 2 wh...
data_rows = [2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 22, 24, 25, 27] data_rows_cool = [2, 3, 4, 6, 7, 8, 10, 12, 14] hig_temp_techs = [2, 7, 8, 13, 14, 16, 18, 20, 22] med_temp_techs = [3, 4, 5, 9, 10, 11] low_temp_techs = [24, 25] no_imput_rows_color = [232, 232, 232]
def letter_counter(token, word): count = 0 for letter in word: if letter == token: count = count + 1 else: continue return count
class ExceptionBase(Exception): """Base exception.""" message: str def __init__(self, message: str) -> None: super().__init__(message) self.message = message class InvalidPduState(ExceptionBase): """Thrown during PDU self-validation.""" def __init__(self, message: str, pdu) -> N...
@React.command() async def redirect(ctx, *, url): await ctx.message.delete() try: embed = discord.Embed(color=int(json.load(open(f'./Themes/{json.load(open("config.json"))["theme"]}.json'))['embed_color'].replace('#', '0x'), 0), title='Redirect Checker') embed.set_thumbnail(url=json.load(open(f'...
arq_entrada = open("FORMAT.FLC", 'r') conjunto_entradas = \ {'SISTEMA FUZZY': '', 'CONJUNTO FUZZY': '', 'GRANULARIDADE': 3, 'OPERADOR COMPOSICAO': '', 'OPERADOR AGREGACAO': '', 'INFERENCIA': '', 'REGRA': False, 'DEFAULT': ''} for linha in arq_entrada.readlines(): #print(linha) variavel = linha.split(':')[0] ...
num = 1 num = 2 num = 3 num = 4 num = 5
# The MIT License (MIT) # # Copyright (c) 2016 Adam Schubert # # 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, mod...
class Parser: def __init__(self, file_path): self.dottedproductions = {'S\'': [['.', 'S']]} file_program = self.read_program(file_path) self.terminals = file_program[0] self.nonTerminals = file_program[1] self.productions = {} self.transactions = file_program[2:] ...
class instancemethod(object): def __init__(self, func): self._func = func def __get__(self, obj, type_=None): return lambda *args, **kwargs: self._func(obj, *args, **kwargs) class Func(object): def __init__(self): pass def __call__(self, *args, **kwargs): return self, args, kwargs class A(object): ...
#!/usr/bin/env python # https://adventofcode.com/2020/day/1 # Topic: Report repair my_list = [] with open("../data/1.puzzle.txt") as fp: Lines = fp.readlines() for line in Lines: my_list.append(int(line)) my_list.sort() num1 = 0 num2 = 0 for idx, x in enumerate(my_list): for y in range(0, len(my_list) - id...
class MasterConfig: def __init__(self, args): self.IP = args.ip self.PORT = args.port self.PERSISTENCE_DIR = args.persistence_dir self.SENDER_QUEUE_LENGTH = args.sender_queue_length self.SENDER_TIMEOUT = args.sender_timeout self.UI_PORT = args.ui_port self.CPU...
'''knot> pytest tests ''' def test_noting(): assert True
#!/usr/bin/env python3 ''' https://codeforces.com/group/H9K9zY8tcT/contest/297852 最长等差数列? 要用二分搜索? nl = [l[i]-l[i-1] for i in range(1,n)] n = len(nl) 实际是一个图的问题? 广度优先搜索? 看题解! [print(*l2[i*n:(i+1)*n]) for i in range(n)] l2 = ['-']*(n*n) #l2[i*n+j]=k so that v[k]=v[j]+(v[j]-v[i]), v[i]<v[j]<v[k] #57上面超内存! 内存和时间有点超! [...
#******************************************************************** # Filename: SingletonPattern_With.Metaclass.py # Author: Javier Montenegro (https://javiermontenegro.github.io/) # Copyright: # Details: This code is the implementation of the singleton pattern. #************************************************...
""" Purpose: File for holding custom exception types that will be generated by the kafka_helpers libraries """ ### # Consumer Exceptions ### class TopicNotFound(Exception): """ Purpose: The TopicNotFound will be raised when attempting to consume a topic that does not exis...
a = float(input('Valor da primeira reta: ')) b = float(input('Valor da segunda reta: ')) c = float(input('Valor da terceira reta: ')) if (b - c) < a < b + c and (a - c) < b < a + c and (a - b) < c < a + b: print('Com essas medidas o triangulo pode ser feito') if a == b == c: print('Este triangulo é EQU...
def junta_listas(listas): planarizada = [] for lista in listas: for e in lista: planarizada.append(e) return planarizada lista = [[1, 2, 3], [4, 5, 6], [7, 8], [9], [10]] print(junta_listas(lista))
S = input() n = S.count("N") s = S.count("S") e = S.count("E") w = S.count("W") home = False if n and s: if e and w: print("Yes") elif not e and not w: print("Yes") else: print("No") elif not n and not s: if e and w: print("Yes") elif not e and not w: print...
# lec5prob9-semordnilap.py # edX MITx 6.00.1x # Introduction to Computer Science and Programming Using Python # Lecture 5, problem 9 # A semordnilap is a word or a phrase that spells a different word when backwards # ("semordnilap" is a semordnilap of "palindromes"). Here are some examples: # # nametag / gateman # dog ...
""" Module docstring """ def _impl(_ctx): print("printing at debug level") my_rule = rule( attrs = { }, implementation = _impl, )
class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ if (n < 0): x = 1 / x n = -n if n == 0: return 1 half = self.myPow(x, n // 2) if(n % 2 == 0): retu...
class Auth: """ Base class for authentication schemes. """ def auth(self): ... def synchronous_auth(self): ... async def asynchronous_auth(self): ...
__title__ = 'fobi.contrib.plugins.form_elements.fields.' \ 'hidden_model_object.default' __author__ = 'Artur Barseghyan <artur.barseghyan@gmail.com>' __copyright__ = 'Copyright (c) 2014-2017 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('IGNORED_MODELS',) IGNORED_MODELS = []
# Exercício Python 064 # Leia varios numeros inteiros. Programa para quando digita 999 # No final, mostra quantos números foram digitados # A soma entre eles, desconsiderando o flag (999) soma = c = n = 0 while n != 999: soma = soma + n c = c + 1 n = int(input('Digite um número: ')) print('Você digitou {} n...
# Description: Sequence Built-in Methods # Sequence Methods word = 'Hello' print(len(word[1:3])) # 2 print(ord('A')) # 65 print(chr(65)) # A print(str(65)) # 65 # Looping Sequence # 1. The position index and corresponding value can be retrieved at the same time using the e...
__author__ = "Inada Naoki <songofacandy@gmail.com>" version_info = (1,4,2,'final',0) __version__ = "1.4.2"
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate...
""" A min priority queue implementation using a binary heap. @author Swapnil Trambake, trambake.swapnil@gmail.com """ class BinaryHeap(): """ Class implements binary heap using array """ def __init__(self) -> None: super().__init__() self.__heap = [] def print(self): """ ...
# tests.utils_tests # Tests for the Baleen utilities package. # # Author: Benjamin Bengfort <benjamin@bengfort.com> # Created: Sun Feb 21 15:31:55 2016 -0500 # # Copyright (C) 2016 Bengfort.com # For license information, see LICENSE.txt # # ID: __init__.py [] benjamin@bengfort.com $ """ Tests for the Baleen utiliti...
budget = float(input()) statists = int(input()) one_costume_price = float(input()) decor_price = 0.1 * budget costumes_price = statists * one_costume_price if statists >= 150: costumes_price -= 0.1 * costumes_price total_price = decor_price + costumes_price money_left = budget - total_price money_needed = total_...