content
stringlengths
7
1.05M
""" Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained. Examples "This is an example!" ==> "sihT si na !elpmaxe" "double spaces" ==> "elbuod secaps" """ def reverse_words(text): str_list = [] for word in text.split(' '): ...
# Creating a program that uses the min() without using the min() function. Without knowing the user inputted values of num1 and num2, create a program that outputs the lower value without using the min() num1 = int(input('Enter a value: ')) num2 = int(input('Enter a value: ')) if num1 <= num2: print(num1) else: ...
# Faça um algoritmo que leia o salário de um # funcionário e mostre seu novo salário com 15% de aumento. s = float(input('Digite o valor do seu salário: ')) a = (15 / 100) * s print('O seu novo salário é: {}.'.format(a + s)) print('\n' * 2) print('O seu novo salário é: {}.'.format((15 / 100) * s + s))
class NodeIndexer: def __init__(self, walker): self.walker = walker self.__nodes = [] def __walk(self): next_node = next(self.walker) self.__nodes.append(next_node) return next_node def index(self, node): result = self.__find_from_loaded(node) if res...
def bfs(graph, start): """Visits all the nodes of a graph using BFS Args: graph (dict): Search space represented by a graph start (str): Starting state Returns: explored (list): List of the explored nodes """ # list to keep track of all visited nodes explored = [] ...
for _ in range(int(input())): n,k=map(int,input().split()) a=list(map(int,input().split())) s=sum(a) c=0 for i in range(n): if(a[i]+k>s-a[i]): #print([i]) c+=1 print(c)
class color(object): GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' RESET_ALL = '\033[0m'
# -*- coding: utf-8 -*- # Copyright (c) 2019-2020 shmilee class RawLoader(object): path = 'test/rawlodaer' filenames = [ 'g.out', 'eq.out', 's0.out', 's2.out', 's4.out', 'p/s0_t0.out', 'p/s0_t1.out', 'p/s0_t2.out', 'p/s2_t0.out', 'p/s2_t1.out', 'p/s2_t2.out', ] class PckLoader(o...
def minTime(machines, goal): # make a modest guess of what the days may be, and use it as a starting point efficiency = [1.0/x for x in machines] lower_bound = int(goal / sum(efficiency)) - 1 upper_bound = lower_bound + max(machines) + 1 while lower_bound < upper_bound -1: days ...
# write program reading an integer from standard input - a # printing sum of all numbers indivisible by 3, smaller than a # for example, for a=10, result = 1 + 2 + 4 + 5 + 7 + 8 = 27 a = int(input("pass a - ")) element = 1 result = 0 while element < a: if element % 3 != 0 : result = result + element element = el...
N, K = map(int, input().split()) if N % 2 == 0: print(min(K + 1, N // 2)) else: print(min(K + 1, N))
def format_sexpr_flat(node): if not isinstance(node, (list, tuple)): return str(node) else: return '(' + ' '.join(format_sexpr_flat(x) for x in node) + ')' def format_sexpr(node, indent_level=0, max_width=80): if not isinstance(node, (list, tuple)): return str(node) if len(node)...
#-*- coding:utf-8 -*- class UnknownComponent: def build(self, c): pass def start(self, c): pass def stop(self, c): pass def __str__(self): return 'unknown'
class Rectangle: def __init__(self, l, w): # Aqui estamos llamando a los setters (ver abajo) self.length = l self.width = w @property def area(self): return self._length*self._width @property def perimeter(self): return self._length * 2 + se...
# danh sách các class nhận điện được từ ảnh pineappleClasses = open("./model_data/pineapple_classes.txt", 'r').read() pineappleClasses = pineappleClasses.split('\n') # danh sách các class phân chia theo mode modeClasses = { 0: {'full baby pineapple', 'body baby pineapple'}, 1: {'full green pineapple', 'body gr...
# -*- encoding: utf-8 -*- def differ(a,b): return a-b
class SchoolMember(object): def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex def tell(self): pass class School(object): def __init__(self, name, addr): self.name = name self.addr = addr self.teachers = list() ...
# -*- coding: UTF-8 -*- VENDOR_GROUP = 1 CUSTOMER_GROUP = 2 RETAILER_GROUP = 3 SUPER_ADMIN = 4
# -*- coding: utf-8 -*- class BaseApiException(Exception): status_code = None message = None detail = None def to_dict(self): _output = { 'code': self.status_code, 'message': self.message } if self.detail: _output.update({'detail': self.deta...
TEMPLATE = """ {name} ==== README """ def get_readme_template(name: str) -> str: return TEMPLATE.format(name=name)
# outer loop for i in range (65,70): # inner loop for j in range(65,i+1): print(chr(j),end="") print()
# 定义函数 def sandwich_ingredients(*toppings): """打印一条消息,对顾客点的三明治进行概述""" print("\nMaking a sandwich with the following toppings:") for topping in toppings: print(f"- {topping}") # 调用函数 sandwich_ingredients('Toast', 'Six eggs') sandwich_ingredients('Tomato slices', 'Lettuce leaves') sandwich_ingredient...
# Copyright (C) [2015-2017] [Thomson Reuters LLC] # Copyright (C) [2015-2017] [Panos Kittenis] # 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...
# -*- coding: utf-8 -*- """ server settings """ # The address which the server runs on. # The server supports both INET4 and UNIX sockets. # For INET sockets, set to (addr: str, port: int), # For UNIX sockets, set to the path of the socket. server_addr = '/tmp/gulag.sock' # The max amount of concurrent # connections ...
def print_table(table, max_char): if table: if len(table) > 0: if len(table[0]) > 0: #find length/height col = len(table) row = len(table[0]) maxlen = [] output = [] #find l...
class Day1: @staticmethod def count(depths: str): lines = depths.splitlines() current_ine = 9999999 increased = 0 for line in lines: int_line = int(line) if current_ine < int_line: increased += 1 current_ine = int_line r...
''' Sample code to test PythonSyntaxHighlighter. ''' # Comments: # - Words like TODO, BUG, FIXME, HACK, NOTE, and XXX are highlighted. # - Escapes like \n and \t are not. # Integers: i = 0_000_000 + 0o_000 + 0o123 + 0x1_2abc_CAFE + 0b_1011_0110 + 1_2_3_4_5 # Floats: f = [3.14, 10., .001, 1e100, 3.14e-10, 0e0, 3.14_1...
# Curso Introdução a Linguagem Python - MIT MISTI Brazil–Unicamp # Ana Luísa Fogarin - 02/02/2021 # a193948@dac.unicamp.br # SET 0 - Problema 1 Parte 2 - Distâncias px = 1 py = 2 a = 3 b = 4 c = 5 out = abs(a * px + b * py + c) / (a** 2 + b ** 2) ** 0.5 print(out)
# Refaça o desafio 35 dos triângulos acrescentando o recurso de mostrar que tipo de triângulo será formado: # Equilátero # Escaleno # Isósceles l1 = float(input('Lado 1: ')) l2 = float(input('Lado 2: ')) l3 = float(input('Lado 3: ')) if l1 < l2 + l3 and l2 < l3 + l1 and l3 < l1 + l2: print('Essas medidas podem fo...
""" Auteur: Frédéric Castel Date : Mars 2020 Projet : MOOC Python 3 - France Université Numérique Objectif: Écrire un programme qui, si temperature (entier lu sur input correspondant à la température maximale prévue pour aujourd’hui) est strictement supérieur à 0, teste si temperature est inférieur ou égal...
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ a,b,c=map(int,input().split()) print(0--(a*c)//b-c)
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"core_fn": "00_core.ipynb", "Apple": "00a_apple.ipynb", "core_text_fn": "10_text_core.ipynb", "text_util_fn": "10a_text_utils.ipynb"} modules = ["core.py", "apple.py", ...
# -*- coding: utf-8 -*- """2.Lista. Declaração Acessando elementos Adicionando elementos Removendo elementos """ # Declarando uma lista. lista = ['João', 'Pedro', 'Antonio', 'Carlos',] # Acessando elementos individualmente. print(lista[0]) print(lista[1]) print(lista[2]) print(lista[3]) # Acessando elementos atra...
def interlock(word1, word2, word3): if (not word1) or (not word2) or (not word3): return False interlocked = "" for i in range(len(min([word1, word2], key=len))): interlocked += (word1[i] + word2[i]) if word3 == (interlocked + max([word1, word2], key=len)[len(min([word1, word2], key=l...
# -*- coding: utf-8 -*- class Solution: def isMagicSquareCenteredHere(self, grid, i, j): all_nine_numbers = sorted([ grid[i - 1][j - 1], grid[i - 1][j], grid[i - 1][j + 1], grid[i][j - 1], grid[i][j], grid[i][j + 1], grid[i + 1][j - 1], grid[i + 1][j], grid[i + 1][j + 1...
# Do not edit this file directly. # It was auto-generated by: code/programs/reflexivity/reflexive_refresh load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def sfml(): http_archive( name="sfml" , build_file="//bazel/deps/sfml:build.BUILD" , sha256="6b013624aa9a916da2d37...
class Solution: """ @param s: a string @param k: an integer @return: all unique substring """ def uniqueSubstring(self, s, k): records = set() for i in range(len(s) - k + 1): word = s[i: i + k] records.add(word) return sorted(records)
ADMIN = 1 USER = 0 ROLE = { ADMIN: 'admin', USER: 'user', } # Post status PRIVATE = 1 PUBLIC = 0 STATUS = { PRIVATE: 'Private', PUBLIC: 'Public' } #User friend ISFRIEND = 1 NOTISFRIEND = 0 STATUS = { ISFRIEND: 'Is Friend', NOTISFRIEND: 'Not is Friend' } PROCESSED = 1 NOPROCESSED = 0 STATUS = ...
class Solution: def plusOne(self, digits: [int]) -> [int]: if digits[-1] < 9: digits[-1] += 1 return digits temp = '' for value in digits: temp += str(value) temp = str(int(temp) + 1) result = [] for value in temp: res...
#-*- encoding: utf-8 -*- # 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 # # 示例: # # 输入: [0,1,0,3,12] # 输出: [1,3,12,0,0] # # 说明: # # # 必须在原数组上操作,不能拷贝额外的数组。 # 尽量减少操作次数。 # # Related Topics 数组 双指针 # leetcode submit region begin(Prohibit modification and deletion) # class Solution(object): # def moveZeroes(self, n...
''' Exceptions/codes ________________ Organized error codes for reporting errors and exceptions. :copyright: (c) 2015 The Regents of the University of California. :license: GNU GPL, see licenses/GNU GPLv3.txt for more details. ''' CODES = { "000": ("Cannot find file%(-s)s in row%(-s)s {0}." ...
def add(num1:int,num2:int): return num1 + num2 class InsufficientFunds(Exception): pass class BankAccount(): def __init__(self,starting_balance=0): self.balance = starting_balance def deposit(self,amount): self.balance += amount def withdraw(self,amount): if amount > self...
{ "variables": { "libwebm_root%": "", }, "targets": [ { "target_name": "audio", "sources": [ "audio-napi.cc", "webvtt/vttreader.cc", "webvtt/webvttparser.cc", "webm_muxer.cc", "sample_muxer_metadata.cc" ], "conditions": [ ['OS=="mac"', { 'defines': [ '__MACOSX_CORE_...
# 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. { 'variables': { 'errorprone_script_path': '<(PRODUCT_DIR)/bin.java/chromium_errorprone', }, 'targets': [ { # GN: //third_party/errorpron...
n=int(input()) i=0 x=0 while (i<n): b=set(input()) if("+" in b): x+=1 else: x+=(-1) i+=1 else: print(x)
class InputError(Exception): """Exception raised for errors in the input. Attributes: expression -- input expression in which the error occurred message -- explanation of the error """ def __init__(self, expression, options): self.expression = expression self.message = ...
#!python3 # 4. Пользователь вводит целое положительное число. # Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции. num = int(input("input num {num > 0} = ")) max = 0 while(num > 0): if max < num % 10: max = num % 10 num //= 10 print(max)
n = int(input()) total_sum = 0 for x in range(1, n + 1): ascii_code = input() total_sum += ord(ascii_code) print(f"The sum equals: {total_sum}")
def soma(x1, y1): res = x1 + y1 print('O resultado da soma e {}'.format(res)) x = int(input('Digite um valor!')) y = int(input('Digite um outro valor!')) soma(x, y)
# Excreva um programa que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: # -1 para binário # -2 para octal # -3 para hexadecimal numero = int(input('Digite um número inteiro: ')) print('''Escolha uma das bases para conversão: [ 1 ] converter para BINÁRIO [ 2 ] coverter par...
casa = float(input('qual o valor da casa? ')) sal = float(input('qual o salario? ')) anos = float(input('em quantos anos vai pagar? ')) mensalidade = casa/(anos*12) if mensalidade < sal * 0.30: print(f'\033[1;32mEMPRESTIMO APROVADO!\033[m\n' f'o valor da mensalidade será {mensalidade:.2f} reais') ...
# double quote, backslash, and newlines are forbidden ok_chars = " !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~" ok_chars = frozenset(ok_chars) # these characters cannot use unicode escape codes due to the way Java escaping works late_escape = {u'\u0009':r'\t', u'\u000a...
# OpenWeatherMap API Key weather_api_key = "68524e14c88fa47aab3ac62f9461f6d5" # Google API Key g_key = "AIzaSyAMvlEJHc05Plk9V6VOFt-ezMHPgo6BZSo"
def fib(n): if n <= 1: return n return fib(n - 1) + fib(n - 2) if __name__ == "__main__": assert fib(3) == 2 assert fib(6) == 8
# global variables for common header types ETHER_DETECT = False IPv4_DETECT = False IPv6_DETECT = False TCP_DETECT = False UDP_DETECT = False DEBUG = False # Maximum possible headers within a packet, hyperparameter with default value as 10 MAX_PATH_LENGTH = 10
class Solution: def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int: if not timeSeries: return 0 ans = 0 start = timeSeries[0] end = timeSeries[0] + duration for t in timeSeries[1:]: if t < end: ...
#!/usr/bin/python # encoding: utf-8 """ @author: xuk1 @license: (C) Copyright 2013-2017 @contact: kai.a.xu@intel.com @file: test.py @time: 8/15/2017 10:38 @desc: """
# This file is generated by ./Setup.py class LocalConfig: @staticmethod def initialized(): pass @staticmethod def get_db_name(): return 'universe_db' @staticmethod def get_db_user(): return 'postgres' @staticmethod def get_db_host(): return '127.0.0.1'...
""" Given an array arr of N integers. Find the contiguous sub-array with maximum sum. Input: The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the size of array. The second l...
matriz = [[], [], []] soma = stc = maior = 0 print('-' * 50) for l in range(3): for v in range(3): num = int(input(f'Digite O Valor Da Posição [{l},{v}]: ')) matriz[l].append(num) for n in matriz: for v in n: if v % 2 == 0: soma += v for tc in range(0, 3): stc...
top_three([2, 3, 5, 6, 8, 4, 2, 1]) # [8, 6, 5] top_three([1, 2]) # [2, 1] top_three(['cat', 'dog', 'python', 'cuttlefish']) # ['python', 'dog', 'cuttlefish']
class GameEnd(Exception): pass class Tie(GameEnd): pass class Checkmated(GameEnd): pass class RunOutOfTime(GameEnd): pass class MoveError(Exception): pass class CheckAfterMove(MoveError): pass class SquareNotInValidMoves(MoveError): pass class TeamDoesntGotTurn(MoveError): ...
interfaces = [None] * 26 interfaces[0] = "kitchen_a" interfaces[1] = "kitchen_b" interfaces[2] = "kitchen_c" interfaces[3] = "kitchen_d" interfaces[4] = "kitchen_e" interfaces[5] = "kitchen_f" interfaces[6] = "kitchen_g" interfaces[7] = "kitchen_h" interfaces[8] = "kitchen_i" interfaces[9] = "kitchen_j" interfaces[10] ...
ROOT = '' BASE_DIR = ROOT+'' WRITABLE_FOLDER = ROOT+'writable/' DATABASES = {'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/path/to/database', } } ADMINS = (('name', 'name@example.com')) #Influences which template and...
#1. Basic - Print all integers from 0 to 150. for x in range(151): print(x) #2. Multiples of Five - Print all the multiples of 5 from 5 to 1,000 for x in range(1001): if (x % 5 == 0): print(x) """3. Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead. If divisi...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # %FFILE% # # Created by %USER% on %YEAR%/%MONTH%/%DAY%. # Copyright (c) %YEAR%年 %USER% All rights reserved. # """ %HERE% """ if __name__ == '__main__': pass
def merge_sort(lst): # print("list=",lst) n=len(lst) if n>1: mid=n//2 # print("mid=",mid) left=lst[0:mid] # print("left:",left) right=lst[mid:] # print("right:",right) # print("-"*50) merge_sort(left) merge_sort(right) Merge(left,right,lst) return lst def Merge(left,r...
''' Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. Example 1: Input: [1,4,3,2] Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + m...
# O(n) def find_in_sorted_matrix(matrix, val): i = 0 j = len(matrix[0]) - 1 while ( i < len(matrix) and j >= 0 ): if (matrix[i][j] == val ): return (i,j) if (matrix[i][j] > val ): j -= 1 else: i += 1 return None
# idea: the setup sounds complicated but actually reduces to a trivial problem. If the strings are not identical, the longer of the two strings can't be a subsequence of the other (or either one if they are the same length but not identical), and if they are identical, there is no uncommon subsequence class Solution: ...
""" Exceptions thrown by pyxll_notebook. """ class KernelStartError(RuntimeError): pass class ExecuteRequestError(RuntimeError): def __init__(self, evalue=None, traceback=None, **kwargs): if evalue is None: evalue = str(kwargs) super().__init__(evalue) class AuthenticationError...
flag = False N = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0'] inp = raw_input("Input Rule:") prod = inp[(inp.index("->")+2):] print(prod) for i in range(len(prod)): if prod[i] == inp[0]: flag = True ...
response = natural_language_understanding.analyze( url="https://en.wikipedia.org/wiki/SpaceX", features=Features( categories=CategoriesOptions(limit=4), concepts=ConceptsOptions(limit=10)), clean=False ).get_result()
def fibgen(): a, b = 1, 1 while True: yield b a, b = b, a + b n = int(input('n= ')) fg = fibgen() print('Числа Фібоначчі (next)') for i in range(n): print(i+1, next(fg))
#!/usr/bin/env python3 def f(h,l,p): #print(h,p,l) nc = len(l) for i in range(nc): l[i] -= p[1][i] if l[i]<0: return ['NO'] v2s = [0]*(nc-1) #quota of small v2b = [0]*(nc-1) #quota of big for i in range(nc-1): v2s[i] = l[i] #use all small left! p[2][i...
""" syntax.py: contains syntax for common languages """ syntax = { "py": { "keywords": ['False', 'await', 'else', 'import', 'pass', 'None', 'break', 'except', 'in', 'raise', 'True', 'class', 'finally', 'is', 'return', 'and', 'continue', 'for', ...
class Solution: def climbStairs(self, n): """ :type n: int :rtype: int """ a, b = 1, 1 for _ in range(n): a, b = b, a + b return a
class PlayerHand: # player's hand def __init__(self): self.__hand = [] def deal(self, card): # receive a card self.__hand.append(card) def gethand(self): return self.__hand def burnhand(self): self.__hand = []
# -*- coding: utf-8 -*- # @Author : jjxu # @time: 2019/01/14 14:42 DEBUG = True HOST = "0.0.0.0"
input = "1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,6,19,2,19,6,23,1,23,5,27,1,9,27,31,1,31,10,35,2,35,9,39,1,5,39,43,2,43,9,47,1,5,47,51,2,51,13,55,1,55,10,59,1,59,10,63,2,9,63,67,1,67,5,71,2,13,71,75,1,75,10,79,1,79,6,83,2,13,83,87,1,87,6,91,1,6,91,95,1,10,95,99,2,99,6,103,1,103,5,107,2,6,107,111,1,10,111,115,1,115,5,119,2,...
"""684. Redundant Connection""" class Solution(object): def findRedundantConnection(self, edges): """ :type edges: List[List[int]] :rtype: List[int] """ # union find: 1. Union 2. Find """OOD""" self.parent = [x for x in range(len(edges)+1)] for x, y i...
class Solution: def maxSubArray(self, nums: list[int]) -> int: maxItem, arraySum, maxSum = nums[0], 0, 0 for i in nums: maxItem = max(maxItem, i) if i >= 0: arraySum += i maxSum = max(arraySum, maxSum) elif arraySum+i >= 0: ...
# First Last _ custid _ username _ password _ rank # change list of dictionaries into dictionary of dictionaries def user_dict(user_l): """ list(dict) -> dict """ id_user = {} for u in user_l: id_user[u['custID']] = u return id_user # change string to dictionary of info def read_user(str): ...
#!/usr/bin/env python3 google_api_key='' google_cx_id=''
# # PySNMP MIB module LANCOM-1711-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LANCOM-1711-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:05:22 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
def find_132(array): queue = [] minVal = array[0] for v in array[1:]: while queue and v >= queue[-1][0]: queue.pop() if queue and v < queue[-1][1]: return True queue.append((v, minVal)) minVal = min(minVal, v) return False print(find_132([1,0,1,-4...
mail_data = [ { "sender": "Winnie Mandela", "email": "winniee.mandela@gmail.com", "read_status": "unread", "content": "Dear Sir/Madam,<br/> I am Winnie Mandela. I am the second wife of Nelson Mandela the former South African president. How are you today? I am in p...
_TEST_DATA = """939 7,13,x,x,59,x,31,19""" with open("inputs/day13.txt") as f: lines = f.read().splitlines() # lines = _TEST_DATA.splitlines() time = int(lines[0]) bus_ids = [(i, int(bus)) for i, bus in enumerate(lines[1].split(",")) if bus != "x"] def part_a() -> int: closest = min(((i, a...
# coding: utf-8 # Aluno: Misael Augusto # Matrícula: 117110525 # Problema: Analytics Assembleia def conta_votos(votacoes, id_votacao): votos = [0, 0] for i in range(len(votacoes)): dados = votacoes[i].split(",") if int(dados[2]) == id_votacao: if dados[1] == "sim": votos[0] += 1 else: votos[1] += 1...
BASS = "Bass" TENOR = "Tenor" ALTO = "Alto" SOPRANO = "Soprano" class Voice: """Represents the type of voice. Attributes ---------- note : int The note of the voice. """ def __init__(self, note): """Constructor method. Parameters ---------- note : int...
class Router(object): """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Attempts to read auth models go to rolodex. """ if model._meta.app_label == 'rolodex': return...
config = { 'HOST': '0.0.0.0', 'PORT': 4242 }
b = 'Corinthians', 'Palmeiras', 'Santos', 'Grêmio', 'Cruzeiro', 'Flamengo', 'Vasco da Gama', 'Chapecoense', 'Atlético Mineiro', 'Botafogo', 'Atlético Paranaense', 'Bahia', 'São Paulo', 'Fluminense', 'Sport', 'Vitória', 'Coritiba', 'Avaí', 'Ponte Preta', 'Atlético Goianiense' print(30*'-=') print(f'Classificação do Bras...
#Faça um programa que leia um número inteiro e diga #se ele é ou não um número primo tot = 0 num = int(input("digite um número inteiro: ")) for c in range(1, num + 1): if num % c == 0: print('\033[33m', end='') tot += 1 else: print('\033[31m', end='') print(f'{c} ', end='') print(f'\...
class Solution(object): def flipAndInvertImage(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ return [[1-element for element in nested_array][::-1] for nested_array in A]
def _longest_common_subsequence(s1: str, s2: str) -> int: """ Let m and n be the lengths of two strings. Build L[m+1][n+1] from the bottom up. Note: L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] Runtime: O(mn) Space Complexity: O(mn) """ m, n = len(s1), len(s2) L = [[0] ...
class Leapx_org(): pass L_obj1 = Leapx_org() L_obj2 = Leapx_org() print (L_obj1) print (L_obj2)
my_name = '孙帅比' my_age = 23 my_weight = 70 #kg my_height = 173 #cm my_eyes = 'Black' my_teeth = 'White' my_hair = 'Black' print ("Let talk about %s" % my_name) print ("He is %d kg weight." % my_weight) print ("He is %d cm tall." % my_height) print ("Actually that's not too heavy.") print ("He has got %s eyes and %s...
# While loop - body is true, expresses condition # For loop is an iterator - executes each item in the sequence # While loop should have a statement that will result in true to close the loop secret = "swordfish" pw = '' while pw != secret: pw = input("what's the secret word ? ") # Continue (Testing condition ...
# 3. Сума от числа # Напишете програма, която чете цяло число от конзолата и на всеки следващ ред цели числа, докато тяхната сума стане # по-голяма или равна на първоначалното число. След приключване на четенето да се отпечата сумата на въведените числа. number = int(input()) sum_numbers = 0 while sum_numbers < numb...