content
stringlengths
7
1.05M
class Digraph: def __init__(self, v): self.v = v self.e = 0 self.adj = [[] for _ in range(v)] def init_from(self, file_name): with open(file_name) as f: self.v = int(f.readline()) self.e = int(f.readline()) self.adj = [[] for _ in range(self...
# -*- coding: utf-8 -*- try: print('enter a number') num = int (input()) print('enter a denom') denom = int (input()) print(str(num/denom)) #you can raise the exceptions as follows #raise ZeroDivisionError except ZeroDivisionError: #except IOError: print('Canno...
# 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. num = int(input('Digite um número entre 0 e 20: ')) escolha = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 's...
class Journal: def __init__(self, article_title, journal_title, year_published, page_start, page_end, volume, issue, doi_or_website): self.article_title = article_title self.journal_title = journal_title self.year_published = year_published self.page_start = page_sta...
#!/usr/bin/env python3 """ Pythonic implementation of Adverse Outcome Pathways """ class AdverseOutcomePathway(object): """Adverse Outcome Pathway---A framework for conceptualizing how toxic exposures result in downstream adverse phenotypic effects, especially in humans. AOPs basically constitute th...
vogais = ('Aprender', 'Programar', 'Linguagem', 'Python', 'Curso', 'Gratis', 'Estudar', 'Praticar', 'Trabalhar', 'Mercado', 'Programador') for c in range(0, len(vogais)): print(f'\nNa palavra {vogais[c].upper()} temos: ', end=' ') for letra in vogais[c]: if letra.lower() in 'aeiou': print(l...
#!/usr/bin/env python3 def responses(input_text): user_message = str(input_text).lower() if user_message in ("yes","sure","ok"): return "Great! Let's start. First I need to know where you were born." if user_message in ("no","naw","no thanks"): return "That's alright, maybe another t...
''' Este snipet es para crear un generador que me permita contar hasta 100. ''' # Retorna la lsita con todos los valores def count_to(): yield [n for n in range(0,101) if n%2 ==0] if __name__ == '__main__': i = count_to() print(next(i)) # Lista print(next(i)) # Error StopIteration
largura_parede = float(input('Qual a largura da sua parede?:')) altura_parede = float(input('Qual a altura da sua parede?:')) area_parede = largura_parede * altura_parede quantidade_de_tinta = a / 2 print('A área da sua parede é de {} é necessário {} litros de tinta para pintala!'.format(area_parede, quantidade_de_tint...
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: low = 0 high = len(numbers)-1 while low < high: s = numbers[low] + numbers[high] if s == target: return [low+1, high+1] if s > target: high -= ...
#============================================================================== # exceptions.py # exception handler for Exosite HTTP JSON RPC API library (man, alphabet soup) #============================================================================== ## ## Tested with python 2.6 ## ## Copyright (c) 2010, Exosite LL...
num1 = int(input('Enter First number: ')) num2 = int(input('Enter Second number ')) add = num1 + num2 dif = num1 - num2 mul = num1 * num2 div = num1 / num2 floor_div = num1 // num2 power = num1 ** num2 modulus = num1 % num2 print('Sum of ',num1 ,'and' ,num2 ,'is :',add) print('Difference of ',num1 ,'and' ,num2 ,'is :',...
#!/usr/bin/env python3 c = 100 k = int(input()) i = 0 while c<k: c = int(c*1.01) i += 1 print(i)
def parse(data): kernel, img = data.split("\n\n") i = set() for y, r in enumerate(img.split()): for x, c in enumerate(r): if c == "#": i.add((x, y)) return [c == "#" for c in kernel], i def enhance(kernel, i, inverted): inverting = kernel[0] and not inverted ...
print(a) print(b) c = a + b print(c)
class Solution(object): def countSubstrings(self, s): def manacher(s): s = '^#' + '#'.join(s) + '#$' P = [0] * len(s) C, R = 0, 0 for i in xrange(1, len(s) - 1): i_mirror = 2 * C - i if R > i: P[i] = min(R-i,...
""" Given an array, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i. More formally, G[i] for an element A[i] = an element A[j] such that j is maximum possible AND j < i AND A[j] < A[i] Elements for which no smaller element exist, ...
FG = "\033[38;5;{}m" BG = "\033[48;5;{}m" RST = "\033[0m" def print_256_color_lookup_table_for(x): if x == "foreground" or x == "fg": x = FG elif x == "background" or x == "bg": x = BG else: raise ValueError("Unrecognized value for argument.") for n in range(16): # Sta...
demo_list = [1, 'hello', 1.34, True, [1, 2, 3]] colors = ['red', 'green', 'blue'] numbers_list = list((1, 2, 3, 4)) print(numbers_list) r = list(range(1, 100)) print(r) print(len(colors)) print(colors[1]) print('green' in colors) print(colors) colors[1] = 'yellow' print(colors) colors.append('violet')...
# Leetcode Problem Link: # https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: '...
''' I=1 J=7 I=1 J=6 I=1 J=5 ''' i = 1 j = 7 while i < 10: print("I={} J={}".format(i, j)) if j == 5: i = i + 2 j = 7 else: j = j - 1
# MIT License # # Copyright (c) 2020-2021 Markus Prasser # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify,...
# Time: O(n * l^2), n is length of string s, l is maxLen of words in dict; # slice to get substring s[i-l:i] takes l time # Space: O(n) # 139 # Given a string s and a dictionary of words dict, # determine if s can be segmented into a space-separated sequence of one or more dictionary words. # # Fo...
def max_heapify(A,k): l = left(k) m = middle(k) r = right(k) largest = k if l < len(A) and A[l] > A[k]: largest = l else: largest = k if r < len(A) and A[r] > A[largest]: largest = r if m < len(A) and A[m] > A[largest]: largest = m if largest != k: ...
""" CCC '20 J3 - Art Find this problem at: https://dmoj.ca/problem/ccc20j3 """ # Unzip the input into separate lists of x & y coordinates xs, ys = [], [] for i in range(int(input())): x, y = map(int, input().split(',')) xs.append(x) ys.append(y) # The smallest x & y coordinates and minus one (because of f...
nome = input('Olá, como se chama?') print(f'Muito prazer em conhece-o(a), {nome}!')
n = int(input('Digite um número: ')) antecessor = n - 1 sucessor = n + 1 print('O antecessor de {} é {}'.format(n, antecessor)) print('O sucessor de {} é {}'.format(n, sucessor))
class Node: def __init__(self, value=None, next=None): self.value = value self.next = next def remove_from_list(value, listHead): curr = listHead prev = None while curr: if curr.value > value: if prev: prev.next = curr.next else: ...
# recursive approach to find the number of set # bits in binary representation of positive integer n def count_set_bits(n): if (n == 0): return 0 else: return (n & 1) + count_set_bits(n >> 1) # Get value from user n = 41 # Function calling print(count_set_bits(n...
APPLICATION_GOOD_BODY = { 'information': { 'first_name': 'Andrew James', 'last_name': 'McLeod', 'date_of_birth': '1987-03-04', 'addresses': [ { 'address': '3023 BODEGA ROAD', 'city': 'VICTORIA', 'province_state': 'BC', ...
ENCRYPTION_FILE_CHUNK_SIZE = 64 * 1024 # 64K ENCRYPTION_KEY_DERIVATION_ITERATIONS = 100000 ENCRYPTION_KEY_SIZE = 32 ZIP_CHUNK_SIZE = 64 * 1024 # 64K ZIP_MEMBER_FILENAME = 'mayan_file'
'''lst=[x for x in range(2,21,2)] print(lst)''' lst=[x for x in range(1,21) if x%2==0] print(lst)
#multiple if statements (IBM Digital Nation Africa) num = 72.5 if num > 0 : print ("The Number is positive") if num > 20 : print("The Number is greater than 20")
# The Project # Master Ticket TICKET_PRICE = 10 tickets_remaining = 100 # Notify the user that the tickets are sold out if the tickets remaining is 0 if tickets_remaining == 0: print("I'm sorry we are sold out!") # Run this code continuously until we run out of tickets while tickets_remaining >= 1: # Output how...
del_items(0x80116458) SetType(0x80116458, "int NumOfMonsterListLevels") del_items(0x800A375C) SetType(0x800A375C, "struct MonstLevel AllLevels[16]") del_items(0x80116174) SetType(0x80116174, "unsigned char NumsLEV1M1A[4]") del_items(0x80116178) SetType(0x80116178, "unsigned char NumsLEV1M1B[4]") del_items(0x8011617C) S...
# Programar em Python #12 - Ciclo for organizacao = 'Caffeine Algorithm'; cores = ['Azul', 'Verde', 'Amarelo', 'Vermelho', 'Laranja']; ''' for carater in organizacao: print('Carater:', carater); for cor in cores: print('Cor:', cor); ''' for numero in range(1, 11): print('Número:', numero);
# ------------------------------------ # CODE BOOLA 2015 PYTHON WORKSHOP # Mike Wu, Jonathan Chang, Kevin Tan # Puzzle Challenges Number 4 # ------------------------------------ # Wow! You are doing this way faster # than I thought you would. Slooooow # doooowwwwwnnn... # ------------------------------------ # IN...
# import pytest class TestTranslator: def test___call__(self): # synced assert True def test_translate(self): # synced assert True def test_translate_recursively(self): # synced assert True def test_translate_json(self): # synced assert True class TestTranslata...
class RBTreeNode: def __init__(self, val, parent=None): self.val = val self.black = True self.left = None self.right = None self.parent = parent class RBTree: def __init__(self): self.root = None def get_root(self): return self.root def insert(...
__all__ = ['gmrt_raw_toguppi'] class GUPPIINJ: def __init__(self, guppifile) -> None: self.header = self.header_dict() self.guppifile = guppifile # def bbinj(self,d):# samples_per_frame=960, pktsize=1024,npol=2, nchan=4): # hdr = {k: self.header[k] for k in self.header if self.h...
#ticTacToe.py #Written by Jesse Gallarzo gameGrid = [[' ' for i in range(3)] for j in range(3)] gameOver = False answer = str() def gameRules(): print('Whoever matches three of a kind in a row or column wins! Place either an X or an O within the grid') def printGrid(): print('|'+gameGrid[0][0]+'|'+gameGrid[0...
# terrascript/data/bgpat/dnsimple.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:15:28 UTC) __all__ = []
INFO = { "name": "hi", "description": "Membalas dengan hello", "visibility": "public", "authority": "all" } async def execute(client, message): message_chat = message.chat await client.send_message( message_chat.id, "Hello" )
class Connection(object): def open(self): pass def close(self): pass
# # PySNMP MIB module XEDIA-DVMRP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XEDIA-DVMRP-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:42:43 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
""" Atributos - podem ser públicos ou privados, representam caracteristicas dos objetos. Tem atributos de instancia, classe e dinamicos. Atributos de instancia sao declarados dentro do construtor e cada instancia da classe tem os seus atributos, ou seja cada instancia terá atributos diferentes. Atributos privados são...
class Error(Exception): """Base class for exceptions in this module.""" pass class SnipeITErrorHandler(object): """Handles SnipeIT Exceptions""" def __init__(self,request): self.fault=request.json() if self.fault.get('status')=='error': if self.fault.get('messages') == 'Unau...
# https://www.codewars.com/kata/52597aa56021e91c93000cb0/train/python def move_zeros(array: list) -> list: return [x for x in array if x != 0] + [0] * array.count(0) # ----------------------------------------------------------------------------- tests = [ { 'assertion': move_zeros([1, 2, 0, 1, 0, 1, ...
__author__ = 'slaviann' TEMPLATES = ( "ddos.list", "domains.list", "domains_ssl.list", "suspend.list" )
NEEDLESS_ATTRS = ['op', 'desc', 'id', 'swap', 'trainable', 'ctx', 'event', 'inplace', 'lazy_execution', 'on_cpu', 'on_gpu', 'compute', 'middle_result', 'gpu_buffer', ] ONNX_DOMAIN = "" AI_ONNX_ML_DOMAIN = "ai.onnx.ml"
class InvalidAPIKey(Exception): pass class GatewayError(Exception): pass class TooManyRequests(Exception): pass
def db_field(**options): def _exec(client, *args, **kwargs): pass return _exec
# -*- coding: utf-8 -*- # mathtoolspy # ----------- # A fast, efficient Python library for mathematically operations, like # integration, solver, distributions and other useful functions. # # Author: sonntagsgesicht, based on a fork of Deutsche Postbank [pbrisk] # Version: 0.3, copyright Wednesday, 18 September 20...
print('=*=SEQUÊNCIA DE FIBONACHII =*=') termos = int(input('Digite quantos termos você quer: ')) t1 = 0 t2 = 1 t3 = 0 print(t1, ' =>', t2, ' =>', end='') for i in range(1, termos+1): t3 = t2 + t1 print(t3, end=' => ') t1 = t2 t2 = t3 print('...') print('Fim do Programa')
''' Given n friends, each one can remain single or can be paired up with some other friend. Each friend can be paired only once. Find out the total number of ways in which friends can remain single or can be paired up. Input : n = 3 Output : 4 Explanation {1}, {2}, {3} : all single {1}, {2, 3} : 2 and 3 paired but 1 ...
""" Definition of ListNode """ class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next class Solution: """ @param head: the head @param G: an array @return: the number of connected components in G """ def numComponents(self, head, G): ...
def insert_shift_array(l,b): middle = len(l) // 2 if len(l) % 2 == 0: return l[:middle] + [b] + l[middle:] else: return l[:middle + 1] + [b] + l[middle +1:]
def problem059(): """ Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107. A modern encryption method is to take a text fil...
boxes = [ ] c = 0 for line in open( 'input.txt', 'r' ): line = line.strip( ) if c == 0: boxes.append( line ) c += 1 continue for old_line in boxes: diffs = 0 for i in range( len( old_line ) ): if old_line[ i ] != line[ i ]: diffs += 1 same_char = old_line[ i ] #print( ---\n{0}\n{1}\n{2...
# https://www.youtube.com/watch?v=-VpH54mhSu4&list=PL5TJqBvpXQv6TtedyS_a_pJK2uVrksh7D&index=3 def solve(A): # [-2, 1, 2, 3, 5, -4] min, max = 0, 0 # min, max = A[0], A[0] Other way to start beginning from the first position for value in A: if value <= min: min = value if v...
''' Exercício 2 - Invertendo sequência Como pedido na primeira video-aula desta semana, escreva um programa que recebe uma sequência de números inteiros terminados por 0 e imprima todos os valores em ordem inversa. Note que 0 (ZERO) não deve fazer parte da sequência. ''' numero = -1 lista = [] while numero != 0: ...
__version__ = "0.2.0" __description__ = "Download data from Refinitiv Tick History and compute some market microstructure measures." __author__ = "Mingze Gao" __author_email__ = "mingze.gao@sydney.edu.au" # __github_url__ = "https://github.com/mgao6767/mktstructure"
class Graph: def __init__(self, v): self.v = v self.e = 0 self.adj = [[] for _ in range(v)] def add_edge(self, v, w): self.adj[v].append(w) self.adj[w].append(v) self.e += 1 def get_v(self): return self.v def det_e(self): return self.e ...
def detect_os(rctx): """ Detects the host operating system. Args: rctx: repository_ctx Returns: One of the targets in @platforms//os:*. """ os_name = rctx.os.name.lower() if os_name.startswith("mac os"): return "darwin" elif os_name == "linux": return "l...
# ------------------------------------------------------------ # MC911 - Compiler construction laboratory. # IC - UNICAMP # # RA094139 - Marcelo Mingatos de Toledo # RA093175 - Victor Fernando Pompeo Barbosa # # ------------------------------------------------------------ class LyaColor: HEADER = '\033[95m' O...
def print_tasks(): print("The available tasks are:") for t in list_of_tasks: print(display_full_task(t)) ''' for x in range(0, num_tasks): n = input("\ninput name: \n") #Customize Questions t = input("input time: \n") c = input("input category: \n") task=task_list(n,t,c) ...
# Given a singly linked list and an integer k, remove the kth last element from # the list. k is guaranteed to be smaller than the length of the list. # The list is very long, so making more than one pass is prohibitively expensive. class Node: def __init__(self, value): self.value = value ...
def test_Dataset(mocker): pass
real = float(input('quantos reais voce tem:')) dolar = float(real/5.20) euro = float(real/6.20) print('com {} reais voce consegue comprar {:.2f} dolares e {:.2f} euros.'.format(real, dolar, euro)) '''real = float(input('quantos reais voce tem na carteira?')) dolar = real / 5.17 euro = real / 6.10 print('{} voçe co...
''' @Author Alper Meriç ''' class Experience(object): def __init__(self, company_name,title,start_date,finish_date,descriptions): self.company_name=company_name self.title=title self.start_date =start_date self.finish_date=finish_date self.descriptions=descriptions
f = str(input('Diite uma frase: ')).strip().upper() print('A letra A apareceu {} vezes na frase.'.format(f.count('A'))) print('Primeira posição {}'.format(f.find('A')+1)) print('Última posição {}'.format(f.rfind('A')+1))
n = float(input('Digite um número em metros:\n')) print(f'{n}m em centimetros é: {n*100:.2f}.') print(f'E em milimetros é: {n*1000:.2f}.')
# Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. # Example 1: # Input: [2,3,-2,4] # Output: 6 # Explanation: [2,3] has the largest product 6. # Example 2: # Input: [-2,0,-1] # Output: 0 # Explanation: The result cannot be 2, ...
# Fibonacci series # 0,1,1,2,3,5,8,13,21... try: term_number = int(input('Enter Term Number : ')) except: print('Please Enter A Valid Integer') quit() n1, n2 = 0, 1 count = 0 if term_number <= 0: print('Please enter a positive integer') elif term_number == 1: print('Fibonacci Series') print(n1...
""" Created on 04/06/2012 @author: victor """ class Analysis(object): def __init__(self, name, analysis_function, other_params = None): """ Creates one analysis object. It uses an 'analysis_function' which has at least a clustering as parameter and returns a string without any tab c...
#!/usr/bin/env python # -*- coding: utf-8 -*- nota1 = float(input("Digite a primeira nota: ")) nota2 = float(input("Digite a segunda nota: ")) nota3 = float(input("Digite a terceira nota: ")) media = (nota1 + nota2 + nota3) / 3 if media > 6: print("Sua média é: {0:.2f}. Aluno aprovado." .format(media)) else: print...
def floyd(num_vertice, graph): distance = graph #to keep the distances of the graph for target in range(num_vertice): #going thro all vertices for i in range(num_vertice): #go thro row for j in range(num_vertice):#go thro column distance[i][j] = min(distance[i][j], distance[i...
class NoSuchListenerError(Exception): pass class NoSuchEventError(Exception): pass class InvalidHandlerError(Exception): pass
def packbits(myarray, axis=None): # TODO(beam2d): Implement it raise NotImplementedError def unpackbits(myarray, axis=None): # TODO(beam2d): Implement it raise NotImplementedError
""" by Denexapp """ sound_files = { 1: "legacy/1_allakh_akbar.mp3", 2: "legacy/2_assalam_alleykum.mp3", 3: "legacy/3_ver_i_vse_poluchitsya.mp3", 4: "legacy/4_vnesi_dengi_i_zagadai_zhelanie.mp3", 5: "legacy/5_vnesi_platu_i_zagadai_svoye_zhelanie.mp3", 6: "legacy/6_vnesi_platu_i_sosredotochsya.m...
upper_code = '' lower_code = '' currentBlock = True f = open('code.slice','r') p = f.read().splitlines() for i in p: if i == '[upper]': currentBlock = True continue if i == '[end]': continue if i == '[lower]': currentBlock = False continue if i == '[endFile]':...
def listify(obj): if obj is None: return [] if isinstance(obj, (list, tuple)): return obj return [obj]
renterData = { 'Topshop': { 'totalSqm': 2400, 'term': 120, # month 'isGuaranteed': False, 'initialRent': 2000000, # in euro 'initialRentPerSqm': 833, 'annualIncrease': 0.025, 'abatement': 0, # in month 'TI': 200, # TI per sqm 'equityMultiple': ...
class CreateUserController: def __init__(self, create_user_use_case): self.create_user_use_case = create_user_use_case def route(self, body): if body is not None: print("controller", body) name = body["name"] if "name" in body else None role = body["role"] ...
"""try to implement a conjugate gradient method following following: https://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf """ def CG(A, b, x0, eps=0.01, imax=50): """Solve linear system Ax = b, starting from x0. The iterative process stops when the residue falls below eps. Eq. 45 - 49. ...
''' This module is home to the IOManager class, which manages the various input and output formats (specifically, FASTA, FASTQ, CLUSTAL alignments, and GFF files, currently). ''' class IOManager(object): ''' A class used by the `IOBase` class to manage the various input and output methods for the differen...
class URLOpener(object): def __init__(self, x): self.x = x def urlopen(self): return file(self.x)
print('Olá,Mundo!') number_one = int(input("Digite um Número: ")) number_two = int(input('Digite outro Número:')) print(f"A soma de {number_one} e {number_two} é: {number_one + number_two}")
class Photo(object): """ Database object for a photo to allow single uid calculation per full path """ def __init__(self, **kwargs): self.name = kwargs.get("name", "") self.full_path = kwargs.get("full_path", "") self.date_taken = kwargs.get("date_taken", "") self.ui...
class Repository: def __init__(self, RepositoryAffiliation, user, data): self.__userLogin = user.loginUser self.__userId = user.id self.__repositoryAffiliation = RepositoryAffiliation self.__url = data['url'] self.__isFork = data['isFork'] self.__pushedAt = data['push...
# Copyright 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License is located at # # http://aws.amazon.com/apache2.0 # # or in the "license" file accompa...
def minesweeper(matrix): x_axis, y_axis = len(matrix[0]), len(matrix) new_matrix = [] for y in range(y_axis): line = [] for x in range(x_axis): neighbour = [] if x > 0: neighbour.append(matrix[y][x-1]) if y > 0: neig...
class Calculators(): def __init__(self): pass def dca(self, all_buys: list) -> tuple: """ Calculates the DCA entry, total quote invested and total coins purchased :param all_buys: All fully filled buys marked in database for symbol :return: Average DCA entry, total dolla...
# 如果执行这个命令: python index.py # 上面的命令会自动 __name__='__main__' # 如果有其它的文件如 1.py 2.py lib/3.py # __name__ 1 2 3 lib.3 def f1(): pass def f2(): pass if(__name__ == '__main__'): f1() # 对于python,一切都是对象,对象基于类创建 name ='alex' arr = [11, 22, 33] array=list #查看什么类型 print(...
#!/usr/bin/python3 class PetriNet: """ Simplest basic code structure implementing the Petri net functionality. The class PetriNet is used here as namespace only. The code pattern demonstrated here can not be used for running multiple instances of the same model with different states of their ma...
# get user email email = input("What is your email address?:").strip() # slice out user name user = email[:email.index("@")] # slice out domain name domain = email[email.index("@")+1:] # format message output = "Your username is {} and you domain name is {}".format(user,domain) # display output message print(o...
# Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média. n1 = float(input('Digite sua primeira nota: ')) n2 = float(input('Digite sua segunda nota: ')) print('A sua média é: {:.1f}'.format(((n1 + n2) / 2)))
class Computer: def __init__(self): self.name = "Shihab" self.age = 18 def compare(self, other): return self.age == other.age c1 = Computer() c1.age = 30 c2 = Computer() c1.name = "Rashi" if c1.compare(c2): print("They are same") else: print("They are not same")
class points: user = [] points = [] def addUser(self, user, points): try: index = self.getIndex(user) except: index = -1 if index < 0: self.user.append(user) self.points.append(points) return 'User ' + user + ...
#!/usr/bin/python # splitting.py nums = "1,5,6,8,2,3,1,9" k = nums.split(",") print (k) l = nums.split(",", 5) print (l) m = nums.rsplit(",", 3) print (m)