content
stringlengths
7
1.05M
""" Test init module ================================== Author: Casokaks (https://github.com/Casokaks/) Created on: Aug 15th 2021 """
""" 1065. Index Pairs of a String Easy Given a text string and words (a list of strings), return all index pairs [i, j] so that the substring text[i]...text[j] is in the list of words. Example 1: Input: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"] Output: [[3,7],[9,13],[10,17]] Example 2: ...
class Point: def __init__(self, x, y): self.x = x self.y = y self.dist = math.sqrt(x ** 2 + y ** 2) class Solution: """ Quick Select algo: Time best -> O(N) Time worst -> O(N^2) """ def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: ...
def is_odd(n): return n % 2 == 1 def not_empty(s): return s and s.strip() a = list(filter(is_odd, [1, 2, 4, 5, 6, 7, 8])) a = list(filter(lambda n : n % 2 == 1, [1, 2, 4, 5, 6, 7, 8, 9])) b = list(filter(not_empty, ['A', '' , 'B', None, 'C', ' '])) # filter 函数返回的是一个Iterator, 也就是一个惰性序列 print(a, b) def _odd_iter():...
Candies = [int(x) for x in input("Enter the numbers with space: ").split()] extraCandies=int(input("Enter the number of extra candies: ")) Output=[ ] i=0 while(i<len(Candies)): if(Candies[i]+extraCandies>=max(Candies)): Output.append("True") else: Output.append("False") i+=1 print(Output)
class MotionSensor: """Get 9Dof data by using MotionSensor. See [MatrixMotionSensor](https://matrix-robotics.github.io/MatrixMotionSensor/) for more details. Parameters ---------- i2c_port : int i2c_port is corresponding with I2C1, I2C2 ... sockets on board. _dev : class Matrix...
def separador(): print("-="*30) """ Considerando duas listas de inteiros ou floats (lista A e lista B) Some os valores nas listas retornando uma nova lista com os valores somados: Se uma lista for maior que a outra, a soma só vai considerar o tamanho da menor. Exemplo: lista_a = [1, 2, 3, 4, 5, 6, 7] lista_b ...
class MicromagneticModell: def __init__(self, name, Ms, calc): self.name = name self.Ms = Ms self.field = None self.calc = calc def __str__(self): return "AbstractMicromagneticModell(name={})".format(self.name) def relax(self): self.calc.relax(self) def...
# eventually we will have a proper config ANONYMIZATION_THRESHOLD = 10 WAREHOUSE_URI = 'postgres://localhost' WAGE_RECORD_URI = 'postgres://localhost'
""" Дефинирайте фуннкция `is_even`, която приема число и върща `True` ако числото е четно и `False` в противен случай. >>> is_even(4) True >>> is_even(5) False """ def is_even(number): raise Exception('Not implemented')
""" Example module """ def java_maker(*args, **kwargs): """ Make you a java """ java_library(*args, **kwargs)
N = int(input().strip()) names = [] for _ in range(N): name,email = input().strip().split(' ') name,email = [str(name),str(email)] if email.endswith("@gmail.com"): names.append(name) names.sort() for n in names: print(n)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' def upper_print(f): def wrapper(*args, **kwargs): f(*[i.upper() if hasattr(i, 'upper') else i for i in args], **kwargs) return wrapper if __name__ == '__main__': text = 'hello world!' print(text) # hello world! ol...
if __name__ == '__main__': # Check correct price prediction price_input_path = 'tests/data/Price_Simple.csv' price_input = open(price_input_path, 'r').read().splitlines()[0].split(';') price_prediction = open('price_prediction.csv', 'r').read().splitlines()[0].split(';') assert price_input == price_...
print('===== DESAFIO 041 =====') nascimento = int(input('Digite o ano q vc nasceu: ')) idade = 2021 - nascimento print(f'vc tem {idade} anos') if idade <= 9: print('vc é um nadador mirim') elif idade > 9 and idade <= 14: print('vc é um nadador infantil') elif idade > 14 and idade <= 19: print('vc é um na...
#coding: utf-8 #date: 2018/7/30 19:07 #author: zhou_le # 求1000以下3和5的倍数之和 print(sum([i for i in range(1000) if i % 3 == 0 or i % 5 == 0]))
rows = [] try: while True: rows.append(int(input())) except EOFError: pass rows.sort() goal = 2020 l = 0 r = len(rows) - 1 while rows[l] + rows[r] != goal and l < r: if rows[l] + rows[r] < goal: l += 1 else: r -= 1 if rows[l] + rows[r] == goal: print(rows[l] * rows[r]) e...
def mostrar(n='', g=''): if n == '': n = '<desconhecido>' if not g.isnumeric(): g = 0 return f'O jogador {n} fez {g} gol(s) no campeonato' # Main nome = input('Nome do Jogador: ').title() gols = input('Número de Gols: ') print(mostrar(nome, gols))
class Telecom: def __init__(self, contact_db_id, system, value, use, rank, period): self.contact_db_id = contact_db_id self.system = system self.value = value self.use = use self.rank = rank self.period = period def get_contact_db_id(self): return self.contact_db_id def get_system(self): return se...
# kasutaja sisestab 3 numbrit number1 = int(input("Sisesta esimene arv: ")) number2 = int(input("Sisesta teine arv: ")) number3 = int(input("Sisesta kolmas arv: ")) # funktsioon, mis tagastab kolmes sisestatud arvust suurima def largest(number1, number2, number3): biggest = 0 if number1 > biggest: big...
#Tuplas numeros = [1,2,4,5,6,7,8,9] #lista usuario = {'Nome':'Mateus' , 'senha':123456789 } #dicionario pessoa = ('Mateus' , 'Alves' , 16 , 14 , 90) #tupla print(numeros) print(usuario) print(pessoa) numeros[1] = 8 usuario['senha'] = 4545343
def lin(): print('-' * 35) # Principal program lin() print(' IAN STIGLIANO SILVA ') lin() lin() print(' CURSO EM VÍDEO ') lin() lin() print(' GUSTAVO GUANABARA ') lin()
# @Title: 重排链表 (Reorder List) # @Author: 18015528893 # @Date: 2021-02-12 16:05:36 # @Runtime: 100 ms # @Memory: 23.9 MB # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reorderList(self, head:...
"""Stores constants used as numbers for readability that are used across all apps""" class AdminRoles: """ """ JCRTREASURER = 1 SENIORTREASURER = 2 BURSARY = 3 ASSISTANTBURSAR = 4 CHOICES = ( (JCRTREASURER, 'JCR Treasurer'), (SENIORTREASURER, 'Senior Treasurer'), (BURSA...
def _check_inplace(trace): """Checks that all PythonOps that were not translated into JIT format are out of place. Should be run after the ONNX pass. """ graph = trace.graph() for node in graph.nodes(): if node.kind() == 'PythonOp': if node.i('inplace'): raise R...
# @Title: 旋转数组 (Rotate Array) # @Author: KivenC # @Date: 2019-03-14 16:57:56 # @Runtime: 124 ms # @Memory: 13.4 MB class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ ''' k = k % len(nums) ...
def test1(): arr = [["我", "你好"], ["你在干嘛", "你干啥呢"], ["吃饭呢", "打球呢", "看电视呢"]] new_arr = [] for i in arr[0]: print(i) for j in arr[1]: new_arr.append(i + j) print(new_arr) # # def test(): # while True: # test1(arr) test1()
############################################################################### # Utils functions for language models. # # NOTE: source from https://github.com/litian96/FedProx ############################################################################### ALL_LETTERS = "\n !\"&'(),-.0123456789:;>?ABCDEFGHIJKLMNOPQRST...
a = str(input()) b = {'0': 0, '1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0, '9': 0} for i in a: b[i] = b[i] + 1 for i in range(len(b)): if b[str(i)] == 0: continue print(str(i) + ':' + str(b[str(i)]))
class ModeIndicator: LENGTH = 4 TERMINATOR_VALUE = 0x0 NUMERIC_VALUE = 0x1 ALPHANUMERIC_VALUE = 0x2 STRUCTURED_APPEND_VALUE = 0x3 BYTE_VALUE = 0x4 KANJI_VALUE = 0x8
# 11/03/21 # What does this code do? # This code introduces a new idea, Dictionaries. The codes purpose is to take an input, and convert it into the numbers you'd need to press # on an alphanumeric keypad, as shown in the picture. # How do Dictionaries work? # To use our dictionary, we first need to initial...
# # PySNMP MIB module Juniper-V35-CONF (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-V35-CONF # Produced by pysmi-0.3.4 at Wed May 1 14:04:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
def maior_numero(lista): a = lista[0] for i in range(len(lista)): if lista[i] > a: a = lista[i] return a def remove_divisores_do_maior(lista): maiornumero=maior_numero(lista) for i in range(len(lista)-1,-1,-1): if (maiornumero%lista[i])==0: lista.pop(i) re...
# sample\core.py def run_core(): print("In pycharm run_core")
l = float(input('Digite a largura da parede em metros: ')) al = float(input('Digite a altura da parede em metros: ')) #Um litro de tinta pinta 2m², largura * altura da parede obtemos a área dela em m² e dividimos por dois para obter a quantidade de tinta necessária. lt = (l * al) / 2 print(f'Com uma parede {l}x{al}, ...
raise NotImplementedError("Getting an NPE trying to parse this code") class KeyValue: def __init__(self, key, value): self.key = key self.value = value def __repr__(self): return f"{self.key}->{self.value}" class MinHeap: def __init__(self, start_size): self.heap = [None]...
n = int(input()) c = [0]*n for i in range(n): l = int(input()) S = input() for j in range(l): if (S[j]=='0'): continue for k in range(j,l): if (S[k]=='1'): c[i] = c[i]+1 for i in range(n): print(c[i])
# # PySNMP MIB module CHECKPOINT-TRAP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CHECKPOINT-TRAP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:31:16 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
colors_per_chi = {2: 'green', 3: 'orange', 4: 'purple', 5: 'pink', 6: 'red'} style_per_chi = {2: '-', 3: '-.', 4: 'dotted'} markers_per_reason = {'converged': 'o', 'progress': 'x', 'ressources': 'v'} linewidth = 5.31596
def get_failed_ids(txt_file): id = [] fh = open(txt_file, 'r') for row in fh: id.append(row.split('/')[1].split('.')[0]) return(id)
""" Implementation of Linked List reversal. """ # Author: Nikhil Xavier <nikhilxavier@yahoo.com> # License: BSD 3 clause class Node: """Node class for Singly Linked List.""" def __init__(self, value): self.value = value self.next_node = None def reverse_linked_list(head): """Reverse li...
d=int(input("enter d")) n='' max='' for i in range(d): if i==0: n=n+str(1) else : n=n+str(0) max=max+str(9) n=int(n)+1 #smallest odd no. with d digits if d>1 or 2 if d==1 max=int(max) #largest no. with d digits def check_prime(m_odd): #returns truth value of an odd no. or of 2 being prime if m_odd==2:return T...
class Boolable: def __bool__(self): return False class DescriptiveTrue(Boolable): def __init__(self, description): self.description = description def __bool__(self): return True def __str__(self): return f"{self.description}" def __repr__(self): return f"...
def fuel_required(weight: int) -> int: return weight // 3 - 2 def fuel_required_accurate(weight: int) -> int: fuel = 0 while weight > 0: weight = max(0, weight // 3 - 2) fuel += weight return fuel def test_fuel_required() -> None: cases = [(12, 2), (14, 2), (1969, 654), (100756, ...
""" Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu PREÇO NORMAL e CONDIÇÃO DE PAGAMENTO: - À vista dinheiro/cheque: 10% de desconto - À vista no cartão: 5% de desconto - Em até 2x no cartão: Preço normal - 3x ou mais no cartão: 20% de JUROS """ preco = float(input('Qual o valor d...
class Node: def __init__(self, value, index, next, previous): self.value = value self.next_value = value self.index = index self.next = next self.previous = previous def main(): input_data = read_input() initial_row = input_data.pop(0) # Extract the initial state...
# David Hickox # Jan 12 17 # HickoxProject2 # Displayes name and classes # prints my name and classes in columns and waits for the user to hit enter to end the program print("David Hickox") print() print("1st Band") print("2nd Programming") print("3rd Ap Pysics C") print("4th Lunch") print("5th Ap Lang...
class Node(): def __init__(self, value): self.value = value self.adjacentlist = [] self.visited = False class Graph(): def DFS(self, node, traversal): node.visited = True traversal.append(node.value) for element in node.adjacentlist: if element...
# https://www.hackerrank.com/challenges/utopian-tree def tree_height(tree, N, start): if not N: return tree if start == 'spring': for i in range(N // 2): tree = tree * 2 + 1 if N % 2: return tree * 2 else: return tree elif start == 'summer...
### Maximum Number of Coins You Can Get - Solution class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort() max_coin, n = 0, len(piles) for i in range(n//3, n, 2): max_coin += piles[i] return max_coin
#Antonio Karlo Mijares #ICS4U-01 #November 24 2016 #1D_2D_arrays.py #Creates 1D arrays, for the variables to be placed in characteristics = [] num = [] #Creates a percentage value for the numbers to be calculated with base = 20 percentage = 100 #2d Arrays #Ugly Arrays ugly_one_D = [] ugly_one_D_two = [] ugly_two_D ...
kamus = {"elephant" : "gajah", "zebra" : "zebra", "dog" : "anjing", "camel" : "unta"} kata = input("Masukan kata berbahasa inggris : ") if kata in kamus: print("Terjemahan dari " + kata + " adalah " + kamus[kata]) else: print("Kata tersebt belum ada di kamus")
# -*- coding: utf-8 -*- ''' nbpkg defspec ''' NBPKG_MAGIC_NUMBER = b'\x1f\x8b' NBPKG_HEADER_MAGIC_NUMBER = '\037\213' NBPKGINFO_MIN_NUMBER = 1000 NBPKGINFO_MAX_NUMBER = 1146 # data types definition NBPKG_DATA_TYPE_NULL = 0 NBPKG_DATA_TYPE_CHAR = 1 NBPKG_DATA_TYPE_INT8 = 2 NBPKG_DATA_TYPE_INT16 = 3 NBPKG_DATA_TYPE_IN...
#Write a program which can compute the factorial of a given numbers. #The results should be printed in a comma-separated sequence on a single line number=int(input("Please Enter factorial Number: ")) j=1 fact = 1 for i in range(number,0,-1): fact =fact*i print(fact)
"""Defines the version number and details of ``qusetta``.""" __all__ = ( '__version__', '__author__', '__authoremail__', '__license__', '__sourceurl__', '__description__' ) __version__ = "0.0.0" __author__ = "Joseph T. Iosue" __authoremail__ = "joe.iosue@qcware.com" __license__ = "MIT License" __sourceurl__ ...
##Write a program to input from the input file a familiar greeting of any length, each word on a line. Output the greeting file you just received on a single line, the words separated by a space #Mo file voi mode='r' de doc file with open('05_ip.txt', 'r') as fileInp: #Dung ham read() doc toan bo du lieu tu file F...
def fuel_required_single_module(mass): fuel = int(mass / 3) - 2 return fuel if fuel > 0 else 0 def fuel_required_multiple_modules(masses): total_fuel = 0 for mass in masses: total_fuel += fuel_required_single_module(mass) return total_fuel def recursive_fuel_required_single_module(mass):...
str_xdigits = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", ] def convert_digit(value: int, base: int) -> str: return str_xdigits[value % base] def convert_to_val(value: int, base: int) -> str: if value == No...
class SimpleOpt(): def __init__(self): self.method = 'cpgan' self.max_epochs = 100 self.graph_type = 'ENZYMES' self.data_dir = './data/facebook.graphs' self.gpu = '2' self.lr = 0.003 self.encode_size = 16 self.decode_size = 16 self.pool_size = ...
# What will the gender ratio be after every family stops having children after # after they have a girl and not until then. def birth_ratio(): # Everytime a child is born, there is a 0.5 chance of the baby being male # and 0.5 chance of the baby being a girl. So the ratio is 1:1. return 1
# You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are(i, 0) and (i, height[i]). # Find two lines that together with the x-axis form a container, such that the container contains the most water. # Return the maximum amount of water a conta...
# 最小差值 #   给定n个数,请找出其中相差(差的绝对值)最小的两个数,输出它们的差值的绝对值。 def st171201(): n= int(input()) numbers = list(map(int, input().split())) numbers.sort() # print(numbers) before=numbers[1] temp = abs(before-numbers[0]) for i in numbers[2:]: # print(temp,before,i,abs(i-before)) if abs(i-bef...
# server backend server = 'cherrypy' # debug error messages debug = False # auto-reload reloader = False # database url db_url = 'postgresql://user:pass@localhost/dbname' # echo database engine messages db_echo = False
#decorators def decorator(myfunc): def wrapper(*args): return myfunc(*args) return wrapper @decorator def display(): print('display function') @decorator def info(name, age): print('name is {} and age is {}'.format(name,age)) info('john', 23) #hi = decorator(display) #hi() display()
def connected_tree(n, edge_list): current_edges = len(edge_list) edges_needed = (n-1) - current_edges return edges_needed def main(): with open('datasets/rosalind_tree.txt') as input_file: input_data = input_file.read().strip().split('\n') n = int(input_data.pop(0)) edge_l...
#============================================================================= # # JDI Unit Tests # #============================================================================= """ JDI Unit Tests ============== Run all unit tests from project's root directory. python -m unittest discover python3 -m unittes...
#Задача 3. Вариант 1. #Напишите программу, которая выводит имя "Иво Ливи", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире. name=input('Герой нашей сегодняшней программы - Иво Ливи. \nПод каким же именем мы знаем этого человека?...
# 魔术师 def show_magicians(magicians): for magician in magicians: print('magician\'s name is ' + magician) def make_great(magicians): i = 0 for item in magicians: magicians[i] = 'The Great ' + item i = i + 1 magicians = ['singi', 'sunjun'] make_great(magicians) show_magicians(ma...
# # Author    : Manuel Bernal Llinares # Project   : trackhub-creator # Timestamp : 11-09-2017 11:10 # --- # © 2017 Manuel Bernal Llinares <mbdebian@gmail.com> # All rights reserved. # """ Configuration Manager for this HPC Module """ if __name__ == '__main__': print("ERROR: This script is part of a pipeline co...
# Released under the MIT License. See LICENSE for details. # # This file was automatically generated from "rampage.ma" # pylint: disable=all points = {} # noinspection PyDictCreation boxes = {} boxes['area_of_interest_bounds'] = (0.3544110667, 5.616383286, -4.066055072) + (0.0, 0.0,...
# -*- coding: utf-8 -*- # see LICENSE.rst """Basic Astronomy Functions. .. todo:: change this to C / pyx. whatever astropy's preferred C thing is. """ __author__ = "" # __copyright__ = "Copyright 2018, " # __credits__ = [""] # __license__ = "" # __version__ = "0.0.0" # __maintainer__ = "" # __email__ = "" # __...
"""The bias-variance tradeoff Often, researchers use the terms "bias" and "variance" or "bias- variance tradeoff" to describe the performance of a model—that is, you may stumble upon talks, books, or articles where people say that a model has a "high variance" or "high bias." So, what does that mea...
# # PySNMP MIB module HPN-ICF-8021PAE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-8021PAE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:24:57 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
# 44. Wildcard Matching # # Implement wildcard pattern matching with support for '?' and '*'. # # '?' Matches any single character. # '*' Matches any sequence of characters (including the empty sequence). # # The matching should cover the entire input string (not partial). # # The function prototype should be: # bool i...
class SchemaError(Exception): def __init__(self, schema, code): self.schema = schema self.code = code msg = schema.errors[code].format(**schema.__dict__) super().__init__(msg) class NoCurrentApp(Exception): pass class ConfigurationError(Exception): pass
__author__ = "Wild Print" __maintainer__ = __author__ __email__ = "telegram_coin_bot@rambler.ru" __license__ = "MIT" __version__ = "0.0.1" __all__ = ( "__author__", "__email__", "__license__", "__maintainer__", "__version__", )
TT_INT = 'INT' # int TT_FLOAT = 'FLOAT' # float TT_STRING = 'STRING' # string TT_IDENTIFIER = 'IDENTIFIER' # 变量 TT_KEYWORD = 'KEYWORD' # 关键字 TT_PLUS = 'PLUS' # + TT_MINUS = 'MINUS' # - TT_MUL = 'MUL' # * TT_DIV = 'DIV' # / TT_POW = 'POW' # ^ TT_EQ = 'EQ' # = TT_LPAREN = 'LPAREN' # ( TT_RPAREN = 'RPAREN' # ...
''' Created on Oct 10, 2012 @author: Brian Jimenez-Garcia @contact: brian.jimenez@bsc.es ''' class Color: def __init__(self, red=0., green=0., blue=0., alpha=1.0): self.__red = red self.__green = green self.__blue = blue self.__alpha = alpha def get_rgba(self): ...
__COL_GOOD = '\033[32m' __COL_FAIL = '\033[31m' __COL_INFO = '\033[34m' __COL_BOLD = '\033[1m' __COL_ULIN = '\033[4m' __COL_ENDC = '\033[0m' def __TEST__(status, msg, color, args): args = ", ".join([str(key)+'='+str(args[key]) for key in args.keys()]) if args: args = "(" + args + ")" return "[{colo...
""" Funções (def) - *args **kwargs """ # def func(a1, a2, a3, a4, a5, nome=None, a6=None): # print(a1, a2, a3, a4, a5, nome, a6) def func(*args, **kwargs): print(args, kwargs) lista = [1, 2, 3, 4, 5] func(*lista, nome='João')
class Contract: """ Model class representing a Cisco ACI Contract """ def __init__(self, uid, name, dn): self.uid = uid self.name = name self.dn = dn def equals(self, con): return self.dn == con.dn
"""Routes and URIs.""" def includeme(config): """Add routes and their URIs.""" config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('about', '/about') config.add_route('details', '/journal/{id:\d+}') config.add_route('create', '/journal/...
def find_metric_transformation_by_name(metric_transformations, metric_name): for metric in metric_transformations: if metric["metricName"] == metric_name: return metric def find_metric_transformation_by_namespace(metric_transformations, metric_namespace): for metric in metric_transformatio...
# (C) Datadog, Inc. 2020-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) # metrics namespaced under 'scylla' SCYLLA_ALIEN = { 'scylla_alien_receive_batch_queue_length': 'alien.receive_batch_queue_length', 'scylla_alien_total_received_messages': 'alien.total_received_me...
#Среднее гармоническое #!/usr/bin/env python3 # -*- coding: utf-8 -*- def harmid(*args): if args and 0 not in args: a = 0 for item in args: a += 1 / item return len(args) / a else: return None if __name__ == "__main__": print(harmid()) print(harmi...
# List of tables that should be routed to this app. # Note that this is not intended to be a complete list of the available tables. TABLE_NAMES = ( 'lemma', 'inflection', 'aspect_pair', )
[ { 'date': '2014-01-01', 'description': 'Yılbaşı', 'locale': 'tr-TR', 'notes': '', 'region': '', 'type': 'NF' }, { 'date': '2014-04-23', 'description': 'Ulusal Egemenlik ve Çocuk Bayramı', 'locale': 'tr-TR', 'notes': '', ...
nome = [] temp = [] pesoMaior = pesoMenor = 0 count = 1 while True: temp.append(str(input('Nome: '))) temp.append(float(input('Peso: '))) if count == 1: pesoMaior = pesoMenor = temp[1] else: if temp[1] >= pesoMaior: pesoMaior = temp[1] elif temp[1] <= pesoMenor: ...
# Necro(ネクロ) # sidmishra94540@gmail.com def binaryGenerator(n): pad = [0]*n res = [] for _ in range(2**n): num = list(map(int, bin(_)[2:])) num = pad[:n-len(num)]+num res.append(num) return res if __name__ == '__main__': print(binaryGenerator(int(input())))
""" Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина). Значения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными. Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна. Использовать формулу...
tcase = int(input()) while(tcase): str= input() [::-1] print(int(str)) tcase -= 1
class FixtureException(Exception): pass class FixtureUploadError(FixtureException): pass class DuplicateFixtureTagException(FixtureUploadError): pass class ExcelMalformatException(FixtureUploadError): pass class FixtureAPIException(Exception): pass class FixtureTypeCheckError(Exception): ...
#!/usr/bin/env python3 # tuples is a type of list. # tuples is immutable. # the structure of a tuple: (1, "nice work", 2.3, [1,2,"hey"]) my_tuple = ("hey", 1, 2, "hey ho!", "hey", "hey") print("My tuple:", my_tuple) # to get a tuple value use it's index print("Second item in my_tuple:", my_tuple[1]) # to count how ...
def possibleHeights(parent): edges = [[] for i in range(len(parent))] height = [0 for i in range(len(parent))] isPossibleHeight = [False for i in range(len(parent))] def initGraph(parent): for i in range(1, len(parent)): edges[parent[i]].append(i) def calcHeight(v): fo...
expected_output = { 'instance': { 'isp': { 'address_family': { 'IPv4 Unicast': { 'spf_log': { 1: { 'type': 'FSPF', 'time_ms': 1, 'level': 1, ...
b = "r n b q k b n r p p p p p p p p".split(" ") + ['.']*32 + "p p p p p p p p r n b q k b n r".upper().split(" ") def newBoard(): b = "r n b q k b n r p p p p p p p p".split(" ") + ['.']*32 + "p p p p p p p p r n b q k b n r".upper().split(" ") def display(): #white side view c , k= 1 ...
#!/usr/bin/env python3 print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """)
tree_count, tree_hinput, tree_chosen = int(input()), input().split(), 0 tree_height = [int(x) for x in tree_hinput] for each_tree in range(tree_count): if each_tree==0 and tree_height[0]>tree_height[1]:tree_chosen+=1 elif each_tree==tree_count-1 and tree_height[each_tree]>tree_height[each_tree-1]:tree_chose...
# Create the DMatrix: housing_dmatrix housing_dmatrix = xgb.DMatrix(data=X, label=y) # Create the parameter dictionary: params params = {'objective':'reg:linear', 'max_depth':4} # Train the model: xg_reg xg_reg = xgb.train(dtrain=housing_dmatrix, params=params, num_boost_round=10) # Plot the feature importances xgb....
# -*- encoding:utf-8 -*- impar = lambda n : 2 * n - 1 header = """ Demostrar que es cierto: 1 + 3 + 5 + ... + (2*n)-1 = n ^ 2 Luego con este programa se busca probar dicha afirmacion. """ def suma_impares(n): suma = 0 for i in range(1, n+1): suma += impar(i) return suma def main(): print(header) num ...