content
stringlengths
7
1.05M
class KeplerIOError(Exception): """A base exception for any IO error that might occur.""" def __init__(self, message): """Initializes a new KeplerIOError""" super().__init__(message) class MAST_IDNotFound(KeplerIOError): """The searched ID could not be found on MAST.""" def __init_...
class Solution: def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix: return False if not matrix[0]: return False left = up = 0 right = len(m...
def sum(a,b): return a + b def salario_descontado_imposto(salario,imposto=27.): return salario - (salario * imposto * 0.01) c = sum(1,3) print(c) salario_real = salario_descontado_imposto(5000) print(salario_real)
x = 50 while 50 <= x <= 100: print (x) x = x + 1
# Copyright (c) 2020 Geoffrey Huntley <ghuntley@ghuntley.com>. All rights reserved. # SPDX-License-Identifier: Proprietary # Sample Test passing with nose and pytest def test_pass(): assert True, "dummy sample test"
class InputReader: """Handles reading the input""" def __init__(self, mode, filename): self.filename = filename self.mode = mode def get_next_word(self) -> str: """ Returns one word at a time from the input document :return: The next word """ # The ...
""" Create a function that reverses a string. For example string 'Hi My name is Faisal' should be 'lasiaF si eman yM iH' """ # Function Definition # First attempt to reverse a string. def reverse_string(string_input): split_string = list(string_input) reversed_string = [] for i in reversed(range(len(spli...
#The Course:PROG8420 #Assignment No:2 #Create date:2020/09/25 #Name: Fei Yun location1=input('put the txt file with .py same folder and input file name: ') def wordCount(location): file=open(location,"r") wordcount={} #split word and lower all words Text=file.read().lower().split() #clean -,.\n special characater...
players = ['charles', 'martina', 'michael', 'florence', 'eli'] print (players) print (players[0:3]) print (players[1:4]) print (players[:4]) print (players[2:]) print ('\nHere are the first three players on my team:') for player in players[:3]: print (player.title())
# close func def CloseFunc(): print("CloseFunc") return False # an option def Option1(): print("Option1") return True # dictionary with all options_dict # your key : ("option name", function to call for that option), options_dict = { 0 : ("Close called", CloseFunc), 1 : ("Option1 function called", Option1), }...
##Create an empty string and assign it to the variable lett. Then using range, write code such that when your code is run, lett has 7 b’s ("bbbbbbb"). lett = "" for i in range(0, 7): lett = lett + "b" print(lett)
# Strings # split -> returns a list based on the delimiter # Sample String string_01 = "The quick brown fox jumps over the lazy dog." string_02 = "10/10/2019 01:02:35 CST|10.10.21.23|HTTP 200|Duration:5s|Timeout:30s" # Using split word_list = string_01.split() # Type & Print print(" Type ".center(44, "-")) print(ty...
magic_create_key = "TheQuickBrownFox" class Board: class Builder: def __init__(self, board, player): if len(board) == 0: raise InvalidBoardException("Board is empty") self.board = board self.player = player self.min_array_size = 5 # Min boar...
""" Author: CaptCorpMURICA Project: 100DaysPython File: module1_day13_continueBreak.py Creation Date: 6/2/2019, 8:55 AM Description: Learn about continue/break operations in python. """ # Print only consonants from a given text. motivation = "Over? Did you say 'over'? N...
def find_unique_and_common(line_1, line_2): print("\n".join(map(str, set(line_1) & set(line_2)))) line_1_count, line_2_count = map(int, input().split()) line_1 = [int(input()) for _ in range(line_1_count)] line_2 = [int(input()) for _ in range(line_2_count)] find_unique_and_common(line_1, line_2)
protos = { 0:"HOPOPT", 1:"ICMP", 2:"IGMP", 3:"GGP", 4:"IPv4", 5:"ST", 6:"TCP", 7:"CBT", 8:"EGP", 9:"IGP", 10:"BBN-RCC-MON", 11:"NVP-II", 12:"PUP", 13:"ARGUS", 14:"EMCON",...
print("-"*30) nome = input("Nome do Jogador: ").strip() gols = input("NUmero de gols: ").strip() def ficha(nome,gols): if gols.isnumeric(): if nome == '': return f'O jogador <desconhecido> fez {gols} gols(s) no campeaonato' else: return f'O jogador {nome} fez {gols} gol(s) no...
def change(fname, round): with open ("renamed_{}".format(fname), "w+") as new: with open(fname, "r") as old: for file in old: id = old.split("_")[0]
#Nilo soluction arquivo = open('mobydick.txt', 'r') texto = arquivo.readlines()[:] tam = len(texto) dicionario = dict() lista = list() clinha = 1 coluna = 1 for linha in texto: linha = linha.strip().lower() palavras = linha.split() for p in palavras: if p == '': coluna += 1 i...
#Write a program that accepts as input a sequence of integers (one by #one) and then incrementally builds, and displays, a Binary Search Tree #(BST). There is no need to balance the BST. class Node: def __init__(self, number = None): self.number = number self.left = None self.right = None ...
def catAndMouse(x, y, z): if abs(x - z) == abs(y - z): return "Mouse C" if abs(x - z) > abs(y - z): return "Cat B" return "Cat A"
def unboundedKnapsack(maxWeight, numberItems, value, weight): totValue = [0]*(maxWeight+1) for i in range(maxWeight + 1): for j in range(numberItems): if (weight[j] <= i): totValue[i] = max( totValue[i], totValue[i - weight[j]] + value[j]) # print(...
class OtypeFeature(object): def __init__(self, api, metaData, data): self.api = api self.meta = metaData self.data = data[0] self.maxSlot = data[1] self.maxNode = data[2] self.slotType = data[3] self.all = None def items(self): slotType = s...
""" 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """ def Euler005(n): """Solution of fifth Euler problem.""" found = True number = 0 while ...
''' This file contains the definitions of the DIAG chains used to load the microcode onto the various boards ''' ####################################################################### # Microcode is loaded by the 8051 on each board, by feeding a byte # at time to several serial-to-parallel registers. # The stru...
class NoDict(dict): def __getitem__(self, item): return None class ParamDefault: """ This is the base class for Parameter Defaults. Credit to khazhyk (github) for this idea. """ async def default(self, ctx): raise NotImplementedError("Must be subclassed.") class EmptyFlags(Pa...
l1 = [1] # 0 [<bool|int>] l2 = [''] # 0 [<bool|str>] l3 = l1 or l2 l3.append(True) l3 # 0 [<bool|int|str>]
class ModelAccessException(Exception): """Raise when user has no access to the model""" class ModelNotExistException(Exception): """Raise when model is None""" class AuthenticationFailedException(Exception): """Raise when authentication failed."""
# # PySNMP MIB module S412-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///home/tin/Dev/mibs.snmplabs.com/asn1/S412-MIB # Produced by pysmi-0.3.4 at Fri Jan 31 21:33:01 2020 # On host bier platform Linux version 5.4.0-3-amd64 by user tin # Using Python version 3.7.6 (default, Jan 19 2020, 22:34:52) # ObjectIden...
# TEE RATKAISUSI TÄHÄN: # Write your solution here: # Write your solution here: def order_by_price(item: dict): # Return the price, which is the second item within the tuple return item["rating"] def sort_by_ratings(items: list): return sorted(items, key=order_by_price, reverse=True) if __name__ == "__mai...
ajedrez=[[0,1,0,1,0,1,0,1],[1,0,1,0,1,0,1,0],[0,1,0,1,0,1,0,1],[1,0,1,0,1,0,1,0],[0,1,0,1,0,1,0,1],[1,0,1,0,1,0,1,0],[0,1,0,1,0,1,0,1],[1,0,1,0,1,0,1,0]] print(ajedrez[0][7]) c=0 for x in range(0,8): for y in range(0,8): if(ajedrez[x][y]==1): c+=1 print(c)
def avoidObstacles(inputArray): ''' You are given an array of integers representing coordinates of obstacles situated on a straight line. Assume that you are jumping from the point with coordinate 0 to the right. You are allowed only to make jumps of the same length represented by some integer...
N = int(input()) S = str(input()) for i,c in enumerate(S): if c == '1': if i % 2 == 0: print('Takahashi') else: print('Aoki') break
name = "EikoNet" __version__ = "1.0" __description__ = "EikoNet: A deep neural networking approach for seismic ray tracing" __license__ = "GPL v3.0" __author__ = "Jonathan Smith, Kamyar Azizzadenesheli, Zachary E. Ross" __email__ = "jdsmith@caltech.edu"
''' Successor with delete. Given a set of n integers S={0,1,...,n−1} and a sequence of requests of the following form: Remove x from S Find the successor of x: the smallest y in S such that y≥x. design a data type so that all operations (except construction) take logarithmic time or better in the worst case. ''...
companies = {} while True: command = input() if command == "End": break spl_command = command.split(" -> ") name = spl_command[0] id = spl_command[1] if name not in companies: companies[name] = [] companies[name].append(id) else: if id in companies[name]: ...
print('Please.') i = int(input('Type a natural number: ')) a = float(input('Type a real number: ')) b = float(input('Type a real number: ')) c = float(input('Type a real number: ')) if i <= 0: print('Please, first, type a natural number!') else: # Hopefully you remember that this is the solution of the problem...
class Pessoa: olhos = 2 #atributo de classe , criado quando é um valor padrão, igual para todos os objetos que serão criados def __init__(self,*filhos, nome=None, idade=35, altura=1.70): #atributo de instancia ou do objeto,os valores sã...
# set declaration myfruits = {"Apple", "Banana", "Grapes", "Litchi", "Mango"} mynums = {1, 2, 3, 4, 5} # Set printing before removing print("Before pop() method...") print("fruits: ", myfruits) print("numbers: ", mynums) # Elements getting popped from the set elerem = myfruits.pop() print(elerem, "is removed from fru...
# # PySNMP MIB module PDN-VLAN-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PDN-VLAN-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:39:52 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
#ex31: Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 parta viagens mais longas. distancia = float(input('Qual é a distância da viagem? ')) preco200km = 0.50 * distancia if distancia <= 200: print('O preço...
# -*- coding: utf-8 -*- config = dict( age_config={ "feature_name": "age", "feature_data_type": "int", "default_value": "PositiveSignedTypeDefault", "json_path_list": [("age", "$..content.age", "f_assert_not_null->f_assert_must_digit_or_float")], "f_map_and_filter_chain": "m...
students = [] second_grades = [] for _ in range(int(input())): name = input() score = float(input()) student = [] student.append(name) student.append(score) students.append(student) my_min = float('Inf') for student in students: if student[1] <= my_min: my_min = student[1] for stude...
# Write a function that takes an integer as an input and returns the sum of all numbers from the input down to 0. def sum_to_zero(n): # print base case if n == 0: return n # if we are not at the base case - if n is not yet zero, then print("This is a recursive function with input {0}".format(n)...
input = "((((()(()(((((((()))(((()((((()())(())()(((()((((((()((()(()(((()(()((())))()((()()())))))))))()((((((())((()))(((((()(((((((((()()))((()(())()((())((()(()))((()))()))()(((((()(((()()))()())((()((((())()())()((((())()(()(()(((()(())(()(())(((((((())()()(((())(()(()(()(())))(()((((())((()))(((()(()()(((((()()((...
"""Top-level package for Takes.""" __author__ = """Chris Lawlor""" __email__ = "chris@pymetrics.com" __version__ = "0.2.0"
menu = ix.application.get_main_menu() menu.add_command("Layout>") menu.add_show_callback("Layout>", "./_show.py") menu.add_command("Layout>Presets>") menu.add_show_callback("Layout>", "./presets_show.py") menu.add_command("Layout>Presets>separator") menu.add_command("Layout>Presets>Store...", "./presets_store.py") me...
#!/usr/bin/env python FIRST_VALUE = 20151125 INPUT_COLUMN = 3083 INPUT_ROW = 2978 MAGIC_MULTIPLIER = 252533 MAGIC_MOD = 33554393 def sequence_number(row, column): return sum(range(row + column - 1)) + column def next_code(code): return (code * MAGIC_MULTIPLIER) % MAGIC_MOD if __name__ == '__main__': cod...
class NoSessionError(Exception): """Raised when a model from :mod:`.models` wants to ``create``/``update`` but it doesn't have an :class:`atomx.Atomx` session yet. """ pass class InvalidCredentials(Exception): """Raised when trying to login with the wrong e-mail or password.""" pass class APIE...
class Solution: def dfs(self,row_cnt:int, col_cnt:int, i:int, j:int, solve_dict:dict): if (i, j) in solve_dict: return solve_dict[(i,j)] right_cnt = 0 down_cnt = 0 #right if i + 1 < row_cnt: if (i + 1, j) in solve_dict: right_cnt = sol...
''' Kept for python2.7 compatibility. ''' __all__ = []
""" stringjumble.py Author: johari Credit: megsnyder, https://www.geeksforgeeks.org/reverse-string-python-5-different-ways/https://www.geeksforgeeks.org/reverse-string-python-5-different-ways/ https://stackoverflow.com/questions/529424/traverse-a-list-in-reverse-order-in-python https://stackoverflow.com/questions/44817...
STATE_NOT_STARTED = "NOT_STARTED" STATE_COIN_FLIPPED = "COIN_FLIPPED" STATE_DRAFT_COMPLETE = "COMPLETE" STATE_BANNING = "BANNING" STATE_PICKING = "PICKING" USER_READABLE_STATE_MAP = { STATE_NOT_STARTED: "Not started", STATE_BANNING: "{} Ban", STATE_PICKING: "{} Pick", STATE_DRAFT_COMPLETE: "Draft compl...
class SearchProvider: def search(self) -> list: """ Searches a remote data source """ return []
class StringUtils: @staticmethod def is_empty(text: str) -> bool: """ 判断这个字符串是否为空 :param text: :return: """ if text is None: return True c = text.strip() if len(c) == 0: return True return False
#!/usr/bin/env python3 try: # try the following code print(a) # won't work since we have not defined a except: # if there is ANY error print('a is not defined!') # print this try: ...
n, k = map(int, input().split()) coin = sorted([int(input()) for _ in range(n)]) lst = [[0]*(k+1)]*n+[[1]*(k+1)] lst[0] = [1 if j%coin[0]==0 else 0 for j in range(0,k+1)] for i in range(0, len(coin)): lst[i] = [sum([lst[i-1][j - (k * coin[i])] for k in range((j//coin[i])+1)]) for j in range(k+1)] print(lst[n-1][k])
"""Top-level package for oda-ops.""" __author__ = """Volodymyr Savchenko""" __email__ = 'Volodymyr.Savchenko@unige.ch' __version__ = '0.1.0'
class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): class_name = cls.__name__ if class_name not in cls._instances: cls._instances[class_name] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[class_name]
{ "targets": [ { "target_name": "samplerproxy", "sources": [ "src/node_sampler_proxy.cpp" ], "include_dirs": [ # Path to hopper root ], "libraries": [ # Path to hopper framework library # Path to hopper histogram library ], "cflags" : [ "-std=c++11...
class Solution: def judgeCircle(self, moves: str) -> bool: M = { 'U': (0, -1), 'D': (0, 1), 'R': (1, 0), 'L': (-1, 0) } x, y = 0, 0 for move in moves: dx, dy = M[move] x += dx y += dy retur...
class Animal(object): def run(self): print('Animal is running...') class Dog(Animal): def run(self): print('Dog is running...') class Cat(Animal): pass dog = Dog() dog.run() cat = Cat() cat.run()
__author__ = "Piotr Gawlowicz, Anatolij Zubow" __copyright__ = "Copyright (c) 2015, Technische Universitat Berlin" __version__ = "0.1.0" __email__ = "{gawlowicz, zubow}@tkn.tu-berlin.de" class NetDevice(object): ''' Base Class for all Network Devices, i.e. wired/wireless This basic functionality should be...
x=9 y=3 #Im only gonna comment here but i'll separate all the operater by new lines #Same progression as the slides print(x+y) print(x-y) print(x*y) print(x/y) print(x%y) print(x**y) x=9.919555555 print(x//y) x=9 x+=3 print(x) x=9 x-=3 print(x) x*=3 print(x) x/=3 print(x) x ** 3 pri...
# Configuration # Flask DEBUG = True UPLOAD_FOLDER = "/tmp/uploads" MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # 16MB ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) # Flask-SQLAlchemy SQLALCHEMY_DATABASE_URI = "sqlite:////tmp/db.sqlite"
# Created by MechAviv # Quest ID :: 34925 # Not coded yet sm.setSpeakerID(3001508) sm.setSpeakerType(3) sm.flipDialogue() sm.setBoxChat() sm.boxChatPlayerAsSpeaker() sm.setBoxOverrideSpeaker() sm.flipBoxChat() sm.flipBoxChatPlayerAsSpeaker() sm.setColor(1) sm.sendNext("#face0#We've got to find it. Looks like we've got...
class user: """ Class that generates new instances of user identify for creating an account in the app """ listUser = [] def __init__(self, firstName, lastName, userName, passWord): self.fname = firstName self.lname = lastName self.uname = userName self.pword = pas...
# https: // leetcode.com/problems/middle-of-the-linked-list/description/ # # algorithms # Easy (69.1%) # Total Accepted: 6.1k # Total Submissions: 8.8k # beats 9.07% of python submissions # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # sel...
n = int(input()) a = [int(input()) for _ in range(n)] pushed = [False] * n cnt = 0 index = 0 while not (pushed[index]): cnt += 1 pushed[index] = True if index == 1: cnt -= 1 print(cnt) exit() index = a[index] - 1 print(-1)
single_port_ram = """module SinglePortRam # ( parameter DATA_WIDTH = 8, parameter ADDR_WIDTH = 4, parameter RAM_DEPTH = 1 << ADDR_WIDTH ) ( input clk, input rst, input [ADDR_WIDTH-1:0] ram_addr, input [DATA_WIDTH-1:0] ram_d, input ram_we, output [DATA_WIDTH-1:0] ram_q ); reg [DATA_WIDTH-1:0] mem [0...
# Source: https://leetcode.com/problems/add-digits/description/ # Author: Paulo Lemus # Date : 2017-11-16 # Info : #258, Easy, 92 ms, 92.50% # Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. # # For example: # # Given num = 38, the process is like: 3 + 8 = 11, 1 +...
# -*- coding: utf-8 -*- """Top-level package for Twith Chat File Reader.""" __author__ = """Yann-Sebastien Tremblay-Johnston""" __email__ = 'yanns.tremblay@gmail.com' __version__ = '0.1.0'
def neural_control (output): lat_stick = (output[0] - output[1]) * 21.5 pull = (output[2] - output[3]) * 25 control = [1.0, pull, lat_stick, 0.0] return control
a = input("Geef een waarde (geen 0) ") try: a = int(a) b = 100 / a print(b) except: print("Ik zei nog zo: geen 0") finally: print("Bedankt voor het meedoen")
title = """ __ \ ___| | | | | | __ \ _` | _ \ _ \ __ \ | __| _` | \ \ \ / | _ \ __| | | | | | | ( | __/ ( | | | | | ( | \ \ \ / | __/ | ____/ \_...
# # @lc app=leetcode id=43 lang=python # # [43] Multiply Strings # # https://leetcode.com/problems/multiply-strings/description/ # # algorithms # Medium (29.99%) # Total Accepted: 185.2K # Total Submissions: 617.4K # Testcase Example: '"2"\n"3"' # # Given two non-negative integers num1 and num2 represented as strin...
#https://www.acmicpc.net/problem/2475 n = map(int, input().split()) sum = 0 for i in n: sum += (i**2) print(sum%10)
__author__ = 'mcxiaoke' class Bird(object): feather=True class Chicken(Bird): fly=False def __init__(self,age): self.age=age ck=Chicken(2) print(Bird.__dict__) print(Chicken.__dict__) print(ck.__dict__)
t=int(input()) l=list(map(int,input().split())) l=sorted(l) ans=0 c=0 for i in l: if i>=c: ans+=1 c+=i print(ans)
names = ["shiva", "sai", "azim", "mathews", "philips", "samule"] items = [name.capitalize() for name in names] print(items) items = [len(name) for name in names] print(items) def get_list_comprehensions(lambda_expression, value): return [lambda_expression(x) for x in range(value)] data = get_list_comprehensions...
numero = int(input('Digite um numero:')) sucessor = numero + 1 antecessor = numero - 1 print(f'Analisando o numero {numero}, seu sucessor é {sucessor} e seu antecessor é {antecessor}.')
TILESIZE = 29 PLAYER_LAYER = 4 ENEMY_LAYER = 3 BLOCK_LAYER = 2 GROUND_LAYER = 1 PLAYER_SPEED = 3 player_speed = 0 WHITE = (255, 255, 255) BLUE = (0, 0, 255) RED = (255, 0, 0) BLACK = (0, 0, 0) tilemap = [ 'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB', 'B...............................
""" Cryptocurrency network definitions """ class Network: """ Represents a cryptocurrency network (e.g. Bitcoin Mainnet) """ def __init__(self, description, version_priv, version_pub, pub_key_hash, wif): self.description = description self.version_priv = version_priv ...
class VentilationTrapInstanceError(Exception): """Raised when a Ventilation Trap parameter is not int or float""" pass class TrapezeBuildGeometryError(Exception): """raised when the parameter have not good type""" pass
def fatorial(num=1): f = 1 for c in range(num,0,-1): f *= c return f def main(): ''' n = int(input(' Digite um número: ')) print(fatorial(n))''' f1 = fatorial(4) f2 = fatorial(5) f3 = fatorial() print('Os resultados são: ',f1,f2,f3) main()
#!/usr/bin/env python # -*- coding: UTF-8 -*- # python的set和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. # 集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric difference(对称差集)等数学运算. # sets 支持 x in set, len(set)和 for x in set. 作为一个无序的集合, sets不记录元素位置或者插入点. # 因此, sets不支持 indexing, slicing, 或其它类序列(sequence-like)的操作. # ...
def moveDisk(poles, disk, pole): # move disk to pole if(disk == 0): # base case of recursive algorithm return 0, poles # find the pole the disk is currently on diskIsOn = 0 if disk in poles[1]: diskIsOn = 1 if disk in poles[2]: diskIsOn = 2 # make list of al...
# -*- coding: utf-8 -*- """ Éditeur de Spyder Ceci est un script temporaire. """ print('bonjour')
TOKEN_URL = 'https://discordapp.com/api/oauth2/token' GROUP_DM_URL = 'https://discordapp.com/api/users/@me/channels' RPC_TOKEN_URL_FRAGMENT = '/rpc' RPC_HOSTNAME = 'ws://127.0.0.1:' RPC_QUERYSTRING = '?v=1&encoding=json&client_id=' CLIENT_ID = '' CLIENT_SECRET = '' REDIRECT_URI = '' RPC_ORIGIN = '' BOT_TOKEN = ''
## Automatically adapted for numpy Apr 14, 2006 by convertcode.py ARCSECTORAD = float('4.8481368110953599358991410235794797595635330237270e-6') RADTOARCSEC = float('206264.80624709635515647335733077861319665970087963') SECTORAD = float('7.2722052166430399038487115353692196393452995355905e-5') RADTOSEC = float('1...
CONTENT_TYPE_CHOICES = ( ('Company', 'Company'), ('Job', 'Job'), ('Topic', 'Topic'), )
class AnimalNode: def __init__(self, question, yes_child, no_child): self.question = question self.yes_child = yes_child self.no_child = no_child def name(self): """ Return the animal's name with an appropriate "a" or "an" in front. This only works for l...
# Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. # No final do programa, mostre: # -> A média de idade do grupo; # -> Qual o nome do homem mais velho; # -> Quantas mulheres têm menos de 20 anos. somaidade = 0 médiaidade = 0 maioridadehomem = 0 nomehomem = '' totmulher = 0 for c in range(1, 5): p...
class Solution(object): def angleClock(self, hour, minutes): """ :type hour: int :type minutes: int :rtype: float """ m = minutes * (360/60) if hour == 12: h = minutes * (360.0/12/60) else: h = hour * (360/12) + minutes * (360.0...
""" Figure parameters class """ class FigureParameters: """ Class contains figure and text sizes """ def __init__(self): self.scale = 1.25*1080/8 self.figure_size_x = int(1920/self.scale) self.figure_size_y = int(1080/self.scale) self.text_size = int(2.9*1080/self.sca...
class Solution: def summaryRanges(self, nums): summary = [] i = 0 for j in range(len(nums)): if j + 1 < len(nums) and nums[j + 1] == nums[j] + 1: continue if i == j: summary.append(str(nums[i])) else: summar...
# import copy class Solution: def numIslands(self, grid: List[List[str]]) -> int: if not grid: return 0 # copyGrid = copy.deepcopy(grid) copyGrid = grid m = len(grid) n = len(grid[0]) res = 0 for i in range(m): for j in range(n): ...
BAD_CREDENTIALS = "Unauthorized: The credentials were provided incorrectly or did not match any existing,\ active credentials." PAYMENT_REQUIRED = "Payment Required: There is no active subscription\ for the account associated with the credentials submitted with the request." FORBIDDEN = "Because the international s...
#!/usr/bin/env python3 # coding: utf-8 def foreachcsv(filename, callback): with open(filename, 'rb') as f: while True: line = f.readline().strip() if not line: break callback(line) def fdata2list(filename): with open(filename, 'r') as f: da...
class Person: def __init__(self, name): self.name = name def display1(self): print('End of the Statement') class Student(Person): def __init__(self, name, usn, branch): super().__init__(name) self.name = name self.usn = usn self.branch = branch def dis...