content
stringlengths
7
1.05M
class Employee: raise_amount = 1.04 employee_Amount = 0 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@companyemail' Employee.employee_Amount += 1 def fullname(self): ...
class Editor(object): def __init__(self): self.color = '0 143 192' self.visgroupshown = 1 self.visgroupautoshown = 1 def __str__(self): out_str = 'editor\n\t\t{\n' out_str += f'\t\t\t\"color\" \"{self.color}\"\n' out_str += f'\t\t\t\"visgroupshown\" \"{self.visgr...
class SharpSpringException(Exception): pass
t = int(input()) for _ in range(t): n = int(input()) s = input() dic = {} for i in s: if i not in dic: dic[i] = 1 else: dic[i] += 1 is_yes = True for key in dic: if(dic[key] % 2 == 1): is_yes = False break if(i...
# Space: O(l) # Time: O(m * n * l) class Solution: def exist(self, board, word) -> bool: column_length = len(board) row_length = len(board[0]) word_length = len(word) def dfs(x, y, index): if index >= word_length: return True if (not 0 <= x < row_length) o...
class User: def __init__(self, login, password): self._login = login self._password = password @property def login(self): return self._login @property def password(self): return self._password class Operation: def __init__(self, a, func, b): self._a = ...
internCache = {} # XXX: upper bound on size somehow def intern(klass, vm, method, frame): string = frame.get_local(0) value = string._values['value'] if value in internCache: return internCache[value] internCache[value] = string return string
for _ in range(int(input())): s = input().split() for i in range(2, len(s)): print(s[i], end=' ') print(s[0]+' '+s[1])
""" return every upper case character from a text """ def only_upper(string): text = "" for char in string: if char.isupper(): text += char return text if __name__ == "__main__": # get cipher from file if unavailable cipher = input("paste the text here: ") ...
""" © https://sudipghimire.com.np Create 2 different classes Major and Subject create an instance of Major and add different subjects to the 'subject' attribute as a set of subjects Create another instance for Major and add subjects to the instance add operator overloading to add different methods so that we can cr...
# https://stepik.org/lesson/5047/step/5?unit=1086 # Sample Input 1: # 8 # 2 # 14 # Sample Output 1: # 14 # 2 # 8 # Sample Input 2: # 23 # 23 # 21 # Sample Output 2: # 23 # 21 # 23 max, min, other = a, b, c = int(input()), int(input()), int(input()) if b > max: max, min = b, a if c > max: max, min, other = c, a, b if ...
p=int(input("Enter the size of list : ")) l=p x=[] while(l): x.append(input("Enter elements : ")) l=l-1 print(x) while(True) : option= int(input("Do you want to :\n1.Pop\n2Remove\n3.Exit\n4.Insert\n5.Append\n6.Search\n7.Sort\n8.Reverse\n9.DecSort ?\n")) if(option == 1): #POP n=int(in...
''' Python Code Snippets - stevepython.wordpress.com 149-Convert KMH to MPH Source: https://www.pythonforbeginners.com/code-snippets-source-code/ python-code-convert-kmh-to-mph/ ''' kmh = int(input("Enter km/h: ")) mph = 0.6214 * kmh print ("Speed:", kmh, "KM/H = ", mph, "MPH")
#!/usr/bin/env python # -*- coding: utf-8 -*- opticalIsomers = 2 energy = { 'CBS-QB3': GaussianLog('TS07.log'), 'CCSD(T)-F12/cc-pVTZ-F12': MolproLog('TS07_f12.out'), #'CCSD(T)-F12/cc-pVTZ-F12': -382.96546696009017 } frequencies = GaussianLog('TS07freq.log') rotors = [HinderedRotor(scanLog=Sca...
class AdditionalInfoMeta(object): """Attributes that can enhance the discoverability of a resource.""" KEY = 'additionalInformation' VALUES_KEYS = ( 'categories', 'copyrightHolder', 'description', 'inLanguage', 'links', 'tags', 'updateFrequency', ...
def read_list(t): return [t(x) for x in input().split()] def read_line(t): return t(input()) def read_lines(t, N): return [t(input()) for _ in range(N)] for i in range(read_line(int)): N = read_line(int) print(min(read_list(int)) * (N-1))
""" Check IRIS SystemPerformance or Caché pButtons Extract useful details to create a performance report. Validate common OS and IRIS/Caché configuration settings and show pass, fail and suggested fixes. """ def system_check(input_file): sp_dict = {} with open(input_file, "r", encoding="ISO-8859-1") as fil...
#assert True == True def mean(num_list): try: mean = sum(num_list)/float(len(num_list)) if isinstance(mean, complex): return NotImplemented return mean except ZeroDivisionError as detail: msg = "\nCannot compute the mean value of an empty list." raise ZeroDiv...
# Сообщения пользователю ERROR_LOGGING = 'Update "%s" caused error "%s"' LOGGING = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' PASSED = 'Экзамен сдан! Количество правильных ответов: ' FAILED = 'Экзамен не сдан! Возможно тебе стоит потренироваться (/training)\n' \ 'Количество правильных ответов: ' EX...
def solution(clothes): style = dict() for i in clothes: if i[1] not in style: style[i[1]]=1 else : style[i[1]]+=1 print(style) answer =1 for i in style.values(): answer*=(i+1) return answer-1
# tunnels at level = 0 #https://www.openstreetmap.org/way/167952621 assert_has_feature( 18, 41903, 101298, "roads", {"kind": "highway", "highway": "motorway", "id": 167952621, "name": "Presidio Pkwy.", "is_tunnel": True, "sort_key": 331}) # http://www.openstreetmap.org/way/89912879 assert_has_feature( ...
''' Kattis - rijeci from fibo(0) = 0, fibo(1) = 1, output the x-1th and xth fibo numbers, x <= 45 Simply use a for loop. Time: O(x), Space: O(1) ''' x = int(input()) a = 1 b = 0 for i in range(x): a, b = b, a+b print(a, b)
""" Sujet: NSI DS1 - Partie C : Problème 1 Nom: Charrier Prénom: Max Date: 7/10/2021 """ def tiragePhotos(n): if n < 50: return 0.2 * n elif n >= 100 and n < 100: return 0.15 * n elif n >= 100: return 0.1 * n print(tiragePhotos(10))
"""This module contains class Task for represent single task entity, class TaskStatus""" class TaskStatus: OPENED = 'opened' SOLVED = 'solved' ACTIVATED = 'activated' FAILED = 'failed' class RelatedTaskType: """ This class defines constants which using in related tasks """ BLOCKER = ...
# 1st solution # O(1) time | O(1) space class Solution: def bitwiseComplement(self, n: int) -> int: k = 1 while k < n: k = (k << 1) | 1 return k - n
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2019 Lorenzo 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, ...
""" https://leetcode.com/problems/find-smallest-letter-greater-than-target/ Given a list of sorted characters letters containing only lowercase letters, and given a target letter target, find the smallest element in the list that is larger than the given target. Letters also wrap around. For example, if the target is ...
"""88. Lowest Common Ancestor of a Binary Tree Assume two nodes are exist in tree.""" """ 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 the binary search tree. @param:...
""" Configuration for defining the datastore. """ MAX_KEY_LEN = 32 # characters MAX_VALUE_SIZE = 16 * 1024 # 16 Kbytes MAX_LOCAL_STORAGE_SIZE = 1 * 1024 * 1024 * 1024 # 1 GB LOCAL_STORAGE_PREPEND_PATH = "/tmp" # this will be prepended to the file path provided
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] for n in range(1, 12, 1): n = int(input()) print(months[n - 1]) break
def add_mod(x: int, y: int, modulo: int = 32) -> int: """ Modular addition :param x: :param y: :param modulo: :return: """ return (x + y) & ((1 << modulo) - 1) def left_circ_shift(x: int, shift: int, n_bits: int) -> int: """ Does a left binary circular shift on the number x of ...
# Utility class used for string processing def HasText(line, values): retval = False found = 0 for data in values: if data in line: found += 1 if found == len(values): retval = True return retval def TextAfter(line, values): retval = "" if HasText...
class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ hash_table = {} longest_length = 0 for i in range(len(s)): if hash_table.get(s[i]): cur_length = len(hash_table.keys()) if cu...
# razbi n, ki je 5000 mestno stevilo na 100 50 mestnih stevilk in najdi prvih 10 stevk vsote teh 100-tih stevil sez = [37107287533902102798797998220837590246510135740250,46376937677490009712648124896970078050417018260538,74324986199524741059474233309513058123726617309629,91942213363574161572522430563301811072406154908...
""" Represents the domain of a variable, i.e. the possible values that each variable may assign. """ class Domain: # ================================================================== # Constructors # ================================================================== def __init__ ( self, valu...
# Crie um programa que mostre na tela todos os números pares que estão no intervalo entre 1 e 50. print('Os números PARES que estão no intervalo entre 1 e 50 são: ') for c in range(2, 51, 2): print('.', end='') print(c, end=' ') print('Acabou...')
""" approximations using histograms """ class Interval: def __init__(self, low, up): if low > up: raise Exception("Cannot create interval: low must be smaller or equal than up") self.low = low self.up = up def __len__(self): return self.up - self.low def conta...
async def run(plugin, ctx, channel): plugin.db.configs.update(ctx.guild.id, "message_logging", True) plugin.db.configs.update(ctx.guild.id, "message_log_channel", f"{channel.id}") await ctx.send(plugin.t(ctx.guild, "enabled_module_channel", _emote="YES", module="Message Logging", channel=channel.mention)...
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # 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 applicabl...
def exist(board, word): """ Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. :pa...
class TwoSum: def __init__(self): """ Initialize your data structure here. """ self.numberCount = defaultdict(int) def add(self, number: int) -> None: """ Add the number to an internal data structure.. """ self.numberCount[number] += 1 def f...
### --- ### --- ### --- ### #! While structure: #` 1. The while statement starts with the while keyword, followed bu a test condition, and ends with a colon (:). #` 2. The loop body contains the code that gets repeated at each step of the loop. Each line is indented four spaces. #$ Example: n = 10 while n < 20: ...
class Solution: def maxScore(self, s: str) -> int: """String. Running time: O(n) where n == len(s). """ res = 0 ones = 0 for i in s: if i == '1': ones += 1 z, o = 0, 0 for i in s[:-1]: if i == '0': ...
class EndpointSolver(object): def __init__(self, env, charms): self.env = env self.charms = charms # Relation endpoint match logic def solve(self, ep_a, ep_b): service_a, charm_a, endpoints_a = self._parse_endpoints(ep_a) service_b, charm_b, endpoints_b = self._parse_endpo...
# -*- encoding: utf-8 -*- def _single_action_str(self): return '/'.join(list(iter(self))) def _multi_action_str(_): cmd_actions = [ str(arg) for arg in [ RUN_OPT_NAME, STOP_OPT_NAME, ENABLE_OPTS_NAME, ENABLE_OPTS_NAME, ] ] return ', '.j...
''' Pomodoro Timer code There are six steps in the original technique: Decide on the task to be done. Set the pomodoro timer (traditionally to 25 minutes).[1] Work on the task. End work when the timer rings and put a checkmark on a piece of paper.[5] If you have fewer than four checkmarks, take a short break (3–5 minu...
# -------------------------------------------------------- # # Linguagens de Programação - Prof. Flavio Varejão - 2019-1 # Segundo trabalho de implementação # # Aluno: Rafael Belmock Pedruzzi # # trabIO.py: módulo responsável pelo tratamento de I/O dos arquivos: # entrada.txt, distancia.txt, result.txt e saida.txt #...
rosha = bet_log[-1] bet_log = []
# # PySNMP MIB module CISCO-LWAPP-REAP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LWAPP-REAP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:49:14 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
number = 15 while True: number += 1 last_digit = str(number)[-1:] if last_digit != '6': continue small = int(number / 10) large = int('6' + str(small)) if large % number == 0: print('--') print(str(number) + ' || ' + str(small) + ' : ' + str(large)) print...
fake_users_db = { "typo11": { "username": "typo11", "full_name": "Tammy Cacablanka", "email": "tammy@localhost.com", "disabled": False, "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW" }, "typo12": { "username": "typo12", ...
""" DSC20 WI22 HW05 Name: William Trang PID: A16679845 """ # begin helper methods def ceil(x): """ Simulation to math.ceil No doctest needed """ if int(x) != x: return int(x) + 1 return int(x) def log(x): """ Simulation to math.log with base e No doctests needed """ ...
# Aidan Conlon - 27 March 2019 # This is the solution to Problem 6 # Write a program that takes a user input string and outputs every second word. UserInput = input("Please enter a string of text:") # Print to screen the comment and take a value entered by the user. for i, word in enumerate(UserInput.split()): ...
# THIS IS STATIC WEEKDAYS = { 0: "Monday", 1: "Tuesday", 2: "Wednesday", 3: "Thursday", 4: "Friday", 5: "Saturday", 6: "Sunday" } CLASS_MAP = { 1: "Art", 2: "Geography", 3: "Science" } ENTRIES = { "Monday": { 1: { "class_name": CLASS_MAP[1], ...
# -*- coding: utf-8 -*- def test_search_all(slack_time): assert slack_time.search.all def test_search_files(slack_time): assert slack_time.search.files def test_search_messages(slack_time): assert slack_time.search.messages
class SegmentTreeNode: def __init__(self, start, end, max): self.start, self.end, self.max = start, end, max self.left, self.right = None, None class Solution: """ @param root: The root of segment tree. @param index: index. @param value: value @return: nothing """ def mo...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright © 2007, 2008 Torsten Bronger <bronger@physik.rwth-aachen.de> # # This file is part of the Bobcat program. # # Bobcat is free software; you can use it, redistribute it and/or modify it # under the terms of the MIT license. # # You should have rec...
#!/usr/bin/env python3 #Altere o programa de cálculo dos números primos, informando, caso o número não seja primo, por quais número ele é divisível. contador=0 divisores=[] numero=int(input("Digite o número: ")) if numero!=-1 and numero!=0 and numero!=1: for divisor in range(1,numero+1): if numero%divisor...
class RssItem: """A class used to represent an RSS post""" def __init__(self, title, description, link, pub_date): self.title = title self.description = description self.link = link self.pub_date = pub_date
# Copyright 2014 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. # Pre-caching steps used internally by the IDL compiler # # Design doc: http://www.chromium.org/developers/design-documents/idl-build { 'includes': [ ...
# automatically generated by the FlatBuffers compiler, do not modify # namespace: enums class DateGenerationRule(object): Backward = 0 CDS = 1 Forward = 2 OldCDS = 3 ThirdWednesday = 4 Twentieth = 5 TwentiethIMM = 6 Zero = 7
n=int(input("Enter a number:")) print("The number is",n) sum=0 while(n>0 or sum>9): if(n==0): n=sum sum=0 sum=sum+n%10 n=n//10 print(f"sum of the digits is:", sum) if(sum==1): print("it is a magic number") else: print("It is not a magic number")
# https://docs.python.org/3/library/exceptions.html class person: def __init__(self, age, name): if type(age)!=int: raise Exception("Invaild Age: {}".format(age)) if age<0: raise Exception("Invaild Age: {}".format(age)) if type(name)!=str: raise Exception...
#Exercise! #Display the image below to the right hand side where the 0 is going to be ' ', # and the 1 is going to be '*'. This will reveal an image! picture = [ [0,0,0,1,0,0,0], [0,0,1,1,1,0,0], [0,1,1,1,1,1,0], [1,1,1,1,1,1,1], [0,0,0,1,0,0,0], [0,0,0,1,0,0,0] ] #version 1 # for y_list in picture: # ...
f = open('rucsac.txt', 'r') n = int(f.readline()) v = [] for i in range(n): linie = f.readline().split() v.append((i+1, int(linie[0]), int(linie[1]))) G = int(f.readline()) cmax = [[0 for i in range(G+1)] for j in range(n+1)] for i in range(1, n+1): for j in range(1, G+1): if v[i-1][1] > j...
for _ in range(int(input())): a,b = map(str,input().split()) l1 = len(a) l2 = len(b) flag = True k = "" while l1>0 and l2>0: if a[-1]<=b[-1]: l1-=1 l2-=1 a1 = a[-1] b1 = b[-1] a = a[:-1] b = b[:-1] a1 = i...
BILL_TYPES = { 'hconres': 'House Concurrent Resolution', 'hjres': 'House Joint Resolution', 'hr': 'House Bill', 'hres': 'House Resolution', 'sconres': 'Senate Concurrent Resolution', 'sjres': 'Senate Joint Resolution', 's': 'Senate Bill', 'sres': 'Senate Resolution', }
def is_file_h5(item): output = False if type(item)==str: if item.endswith('.h5') or item.endswith('.hdf5'): output = True return output
class World: def __init__(self): self.children = [] def addChild(self, child): child.world = self self.children.append(child) def getChildByName(self, name): for child in self.children: if child.name == name: return name return None ...
class Solution(object): def findContentChildren(self, g, s): """ :type g: List[int] :type s: List[int] :rtype: int """ g = sorted(g) s = sorted(s) ans = 0 start = 0 for x in range(0, len(s)): for y in range(start, len(g)): ...
""" Enumerates results and states used by Go CD. """ ASSIGNED = 'Assigned' BUILDING = 'Building' CANCELLED = 'Cancelled' COMPLETED = 'Completed' COMPLETING = 'Completing' DISCONTINUED = 'Discontinued' FAILED = 'Failed' FAILING = 'Failing' PASSED = 'Passed' PAUSED = 'Paused' PREPARING = 'Preparing' RESCHEDULED = 'Resche...
# Taken from https://engineering.semantics3.com/a-simplified-guide-to-grpc-in-python-6c4e25f0c506 def message_to_send(x): if x=="hi": return 'hello, how can i help you' elif x=="good afternoon": return "good afternoon, how you doing" elif x== 'Do you think you can really help me?': return 'Yes, O...
''' URL: https://leetcode.com/problems/shortest-unsorted-continuous-subarray/description/ Time complexity: O(n) Space complexity: O(1) ''' class Solution(object): def findUnsortedSubarray(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 1: re...
dia = int(input("\033[1;31mDia\033[m = ")) mes = str(input("\033[1;32mMês\033[m = ")) ano = int(input("\033[1;36mAno\033[m = ")) print("Você nasceu no dia\033[1;36m", dia, "\033[mde \033[1;32m" + mes + "\033[m de\033[1;31m", ano, "\033[m. \033[4;37mCerto!?\033[m")
# Python program to implement graph deletion operation | delete node | using dictionary nodes = [] graph = {} # delete a node undirected and unweighted def delete_node(val): if val not in graph: print(val, "is not present in the graph") else: graph.pop(val) # pop the key with all valu...
with open('day14/input.txt') as f: lines = f.readlines() dic = {} for line in lines: a, b = line.strip().split(" -> ") dic[a] = b def grow(poly: str) -> str: result = "" for i in range(len(poly) - 1): q = poly[i:i+2] result += poly[i] +dic[q] result += poly[-1] return resul...
n, m = map(int, input().split()) notes = [list(map(int, input().split())) for _ in range(m)] if m == 1: d, h = notes[0] print(max(h+(d-1), h+(n-d))) exit(0) d0, h0 = notes[0] ans = h0+(d0-1) for i in range(m-1): d1, h1 = notes[i] d2, h2 = notes[i+1] if d2-d1 < abs(h1-h2): ans = -1 ...
t = int(input()) outs = [] for _ in range(t): n = input() a = list(map(int, input().split())) if a[0] != a[1]: correct = a[2] else: correct = a[0] for i in range(len(a)): if a[i] != correct: outs.append(i+1) break for out in outs: print(out)
#Escreva um programa que pergunte a quantidade de Km percorridos por um carro alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa 60 reais por dia, e 0,15 centavos por Km rodado. name = input('Olá, e bem vindo ao último challenge da aula, e mais uma vez, me fal...
d={ "Aligarh":"It is the city in UP ", "bharatpur":"it is the city in Rajasthan", "delhi ":"it is the capital of India", "Mumbai":"it is the city in Maharashtra" } print("enter the name which you want to search ") n1=input() print(d[n1])
class Persona: def __init__(self,nombre,apellidoPaterno,apellidoMaterno,sexo,edad,domicilio,telefono): self.nombre = nombre self.apellidoPaterno = apellidoPaterno self.apellidoMaterno = apellidoMaterno self.sexo = sexo self.edad = edad self.domicilio = domicilio ...
# 1. Write a Python class named Rectangle constructed by a length and width and a method which will # compute the area of a rectangle. class rectangle(): def __init__(self, width, length): self.width = width self.length = length def area(self): return self.width * self.length a = int...
CONNECTION_TAB_DEFAULT_TITLE = "Untitled" CONNECTION_STRING_SUPPORTED_DB_NAMES = ["SQLite"] CONNECTION_STRING_PLACEHOLDER = "Enter..." CONNECTION_STRING_DEFAULT = "demo.db" QUERY_EDITOR_DEFAULT_TEXT = "SELECT name FROM sqlite_master WHERE type='table'" QUERY_CONTROL_CONNECT_BUTTON_TEXT = "Connect" QUERY_CONTROL_EXECUTE...
# -*- coding: utf-8 -*- # Copyright 2015 Pietro Brunetti <pietro.brunetti@itb.cnr.it> # # 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 # Unle...
#!/usr/bin/python # This script simply generates a table of the voltage to expect # if I combine my photoresistors with some of my resitors from stock.. # As there is no strong sunlight at the moment here, I will have to # postpone the real life testing.. voltage=5. resistor=[59,180,220,453,750,1000,10000,20000] me...
# Calculates total acres based on square feet input # Declare variables sqftInOneAcre = 43560 # Prompt user for total square feet of parcel of land totalSqft = float(input('\nEnter total square feet of parcel of land: ')) # Calculate and display total acres totalAcres = totalSqft / sqftInOneAcre print('Total acres: ...
class ReportEntry: def __init__(self): self.medium = 'Book' self.title = None self.url = None self.classification = None self.length = None self.start_date = None self.stop_date = None self.distribution_percent = None
def rank_cal(rank_list, target_index): rank = 0. target_score = rank_list[target_index] for score in rank_list: if score >= target_score: rank += 1. return rank def reciprocal_rank(rank): return 1./rank def accuracy_at_k(rank, k): if rank <= k: return...
BELI = 'b' ČRNI = 'č' KMET = 'P' TRDNJAVA = 'R' KONJ = 'N' TEKAČ = 'B' KRALJICA = 'Q' KRALJ = 'K' ZMAGA = 'W' PORAZ = 'X' NAPAČNA_POTEZA = 'xx' ZAČETEK = 'S' # začetno stanje: začetna_polja = { (1, 1): (BELI, TRDNJAVA), (1, 2): (BELI, KONJ), (1, 3): (BELI, TEKAČ), (1, 4): (BELI, KRALJICA), (1, 5): (BELI, KRALJ), ...
''' Tratamento de erros. Exceções. Não são necessáriamente erros no código. NameError = Erro de nome, variável não iniciada. ValueError = Erro de valor, não foi digitado algo do mesmo tipo solicitado. ZeroDivisionError = Erro de divisão por zero. TypeErroor = Erro de tipo. IndexError = Erro de índice. ModuleNotFoundErr...
pos = 0 for k in range(6): if float(input()) > 2: pos += 1 print(pos, "valores positivos")
# Exercício Python 043 # LEIA O PESO E ALTURA DE UMA PESSOA, CALCULE IMC E MOSTRAR STATUS: # ABAIXO DE 18.5: ABAIXO DO PESO # ENTRE 18.5 E 25: PESO IDEAL # 25 ATE 30: SOBREPESO # 30 ATE 40: OBESIDADE # ACIMA DE 40: OBESIDADE MÓRBIDA p = float(input('Digite o peso (kg): ')) h = float(input('Digite a altura (cm): ')) imc...
# Escreva um programa que pergunte a quantidade de dias pelos quais ele foi alugado e a quantidade de Km percorridos por um carro alugado. Calcule o preço a pagar, sabendo que o carro custa R$60 por dia e R$0,15 por Km rodado. dias = float(input('Quantos dias o carro foi alugado? ')) km = float(input('Quantos km foram...
class NumMatrix: def __init__(self, matrix: List[List[int]]): if not any(matrix): return m, n = len(matrix), len(matrix[0]) self.tree = [[0] * (n + 1) for _ in range(m + 1)] self.R = m + 1 self.C = n + 1 for i in range(m): for j in range(n): ...
width = 800 height = 700 fps = 60 font_n = 'arial' sheetload = "spritesheet_jumper.png" mob_fq = 5000 player_acc = 0.5 player_friction = -0.12 player_gra = 0.8 player_jump = 21 platform_list = [(0,height-50),(width/2-50,height*3/4), (235,height-350),(350,200),(175,100)] white = (255,255,...
#Done by Carlos Amaral in 20/06/2020 """ At this point, you’re a more capable programmer than you were when you started this book. Now that you have a better sense of how real-world situations are modeled in programs, you might be thinking of some problems you could solve with your own programs. Record any new ideas y...
n = int(input()) ans = 0 number = 0 for i in range(n): a, b = map(int, input().split()) A = int(str(a)[::-1]) # reverse B = int(str(b)[::-1]) # reverse ans = A + B number = int(str(ans)[::-1]) # reverse print(number)
#***Library implementing the sorting algorithms*** def quick_sort(seq,less_than): if len(seq) < 1: return seq else: pivot=seq[0] left = quick_sort([x for x in seq[1:] if less_than(x,pivot)],less_than) right = quick_sort([x for x in seq[1:] if not less_than(x,pivot)],less_than) return left + [pivot] + right...
# -*- coding: utf-8 -*- """ Copyright (C) 2014 Netflix, Inc. Copyright (C) 2021 Stefano Gottardo (python porting) SSDP Server helper SPDX-License-Identifier: BSD-2-Clause See LICENSES/BSD-2-Clause-Netflix.md for more information. """ # IMPORTANT: Make sure to maintain the header structure with exac...
class LigneTexte: """Une ligne de texte dans un document. """ def __init__(self, texte): self.texte = texte