content stringlengths 7 1.05M |
|---|
people = int(input())
lift = [int(i) for i in input().split()]
available_space = 0
for index,cabin in enumerate(lift):
available_space = 4 - int(cabin)
if people < 4:
lift[index] += people
people -= available_space
break
lift[index] += available_space
people -= available_space... |
global_default = {
'general_poll_interval': 3
}
incoming_default = {
'require_arrival_monitor': False,
'control_file_extension': 'stager-ctrl-bss',
'receipt_file_extension': 'stager-rcpt-bss',
'thankyou_file_extension': 'stager-thanks-bss',
'stop_file': '.stop'
}
outgoing_default = {
'target_uses_arrival_monitor': F... |
"""
Given an unsorted array A of size N of non-negative integers, find a continuous sub-array which
adds to a given number.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases
follow. Each test case consists of two lines. The first line of each test case is N and... |
class WebOperationCollection:
def __init__(self):
self.id = None
self.opt_type = None
self.opt_name = None
self.opt_trans = None
self.opt_element = None
self.opt_data = None
self.opt_code = None
@staticmethod
def __parse(ui_data: dict, name):
... |
#Write a function that computes cosine or sine by taking the first n terms of the appropriate series expansion
#To evaluate the value of sin and cos, we can make use of MacLaurin's Theorem
#f(x) = f(0) + f'(0)x+ f''(0)/2! x^2 + f'''0/3! x^3 ...
def cos(n):
result = 0.0
for i in range(31): #Performs series fo... |
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
diff = -1
minValue = nums[0]+1
for i in range(len(nums)):
if nums[i] > minValue:
diff = max(diff, nums[i]- minValue)
minValue = min(minValue, nums[i]) #... |
filename='pi_digits.txt'
with open(filename) as file_object:
lines=file_object.readlines()
pi_string=''
for line in lines:
pi_string +=line.strip()
print(pi_string)
print(len(pi_string)) |
#Dylan Creaven - G00354442
#Graph Theory Project 2020
# =The Shunting Yard algoritm for regex
def shunt(infix):
"""Return infix regex as postfix"""
#convert input to a stack list
infix=list(infix)[::-1]
#operator stack and output list as empty lists
opers,postfix =[],[]
#operator precedence
... |
# shell sort
# 时间复杂度: 最优时间复杂度O(n^1.3)
# 最坏时间复杂度O(n^2)
# 平均时间复杂度O(nlogn) ~ O(n^2)
# 稳定性:不稳定
# 不需要额外空间 O(1)
def shell_sort(alist):
length = len(alist)
gap = length // 2
while gap > 0:
for i in range(gap, length):
j = i
while j ... |
"""
{{cookiecutter.module_name}}
{{cookiecutter.short_description}}
"""
__version__ = "{{cookiecutter.version}}"
|
#Collections, Lists and Tubles - colecao de dados
familia = ["Hugo", "Louyse", "Julieta"] #listas podem ser feitas com qualquer tipo de dado, bool, int, float, string
print(familia[0]) #primeiro dado
print(familia[-1]) #ultimo dado
print(familia[0:2]) #intervalo de dado, sem exclui o ultimo dado do vetor, neste caso ... |
#
# Unicode Mapping generated by uni2python.xsl
#
unicode_map = {
0x00100: r"\={A}", # LATIN CAPITAL LETTER A WITH MACRON
0x00101: r"\={a}", # LATIN SMALL LETTER A WITH MACRON
0x00102: r"\u{A}", # LATIN CAPITAL LETTER A WITH BREVE
0x00103: r"\u{a}", # LATIN SMALL LETTER A WITH BREVE
0x00104: r"\k{A}", # LATIN CAPITAL L... |
def main():
info('Jan unknown laser analysis')
#gosub('jan:PrepareForCO2Analysis')
if exp.analysis_type == 'blank':
info('is blank. not heating')
else:
info('move to position {}'.format(exp.position))
move_to_position(exp.position)
if exp.ramp_rate > 0:
'''... |
## Exercício 17 do livro Python 3 - Conceitos e Aplicações - Uma Abordagem Didática
""" Escreva um programa que leia um número inteiro do teclado e diga se esse número é positivo ou negativo."""
try:
num_x = int(input("Digite um número inteiro: "))
if num_x < 0:
print("O número digitado é negativo")
... |
"""
MailerSend Official Python DSK
@maintainer: Alexandros Orfanos (alexandros at remotecompany dot com)
"""
__version_info__ = ("0", "1", "3")
__version__ = ".".join(__version_info__)
|
c = float(input('Digite a temperatura em Celsius: '))
f = (c * 1.8) + 32
print(f'A temperatura de {c} Grau Celsius em fahrenheit equivale a {f}F')
|
# Copyright (c) 2012 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
class MCInvalidValue(object):
def __init__(self, name):
self.name = name
def __nonzero__(self):
return False
def __repr__(self):
return self.name
... |
"""
Represent classes found in European Medicines Agency (EMA) documents
"""
class SectionLeaflet:
"""
Class to represent individual section of a Package Leaflet
"""
def __init__(self, title, section_content, entity_recognition=None):
self.title = title
self.section_conten... |
# seleção simples
nome_carros = tuple(['Jetta Variant', 'Passat', 'Crossfox', 'DS5'])
print(nome_carros[0]) # selecionando indice 0
print(nome_carros[1]) # selecionando indice 1
print(nome_carros[-1]) # selecionando indice -1 (ultimo)
print(nome_carros[1:3]) # slice do indice 1 ao 3-1(2)
# seleção interna
nome_c... |
"""doc
# leanai.data.transformer
> A transformer converts the data from a general format into what the neural network needs.
"""
class Transformer():
def __init__(self):
"""
A transformer must implement `__call__`.
A transformer is a callable that gets the data (usually a tuple o... |
# Solution by Emma Neiss
L, N = map(int, input().split())
# initialisation
items = [0 for i in range(N)]
for i in range(N):
items[i] = int(input()) + 1 # ajout d'une personne fictive dans le groupe pour respecter les distances
# --- Implémentation du sac à dos classique sans répétition
# RQ : on fait +1 à la... |
# Longest Substring Without Repeating Characters
class Solution:
def lengthOfLongestSubstring(self, s):
longest = 0
start = 0
length = len(s)
while start < length - longest:
substr = s[start:start + longest + 1]
if len(set(substr)) == longest + 1:
... |
workers = 2
errorlog = "/demo/mysite.gunicorn.error"
accesslog = "/demo/mysite.gunicorn.access"
loglevel = "debug"
|
# https://www.codechef.com/problems/LOSTMAX
for T in range(int(input())):
l=list(map(int,input().split()))
l.remove(len(l)-1)
print(max(l)) |
BOARD_SIZE = 8
class Queen(object):
def __init__(self, x, y):
if (
x < 0 or x >= BOARD_SIZE or
y < 0 or y >= BOARD_SIZE
):
raise ValueError('invalid board position')
self.p = (x, y)
def __eq__(self, other):
return self.p == othe... |
numero = int(input('Insira um número: '))
unidade = numero // 1 % 10
dezena = numero // 10 % 10
centena = numero // 100 % 10
milhar = numero // 1000 % 10
print('O número analisado foi {}'.format(numero))
print('Unidade: {}'.format(unidade))
print('Dezena: {}'.format(dezena))
print('Centena: {}'.format(centena))
print... |
__name__ = "helpers"
def is_int(s):
""" return True if string is an int """
try:
int(s)
return True
except ValueError:
return False
def str2bool(s):
""" convert string to a python boolean """
return s.lower() in ("yes", "true", "t", "1")
def str2num(s):
""" convert str... |
def plug_in(symbol_values):
structure = symbol_values['structure']
factor = structure.composition.get_reduced_formula_and_factor()[1]
uc_cv = symbol_values.get("uc_cv")
uc_cp = symbol_values.get("uc_cp")
molar_cv = symbol_values.get("molar_cv")
molar_cp = symbol_values.get("molar_cp")
if uc_... |
class Solution:
# @param A : tuple of integers
# @return a list of integers
def repeatedNumber(self, A):
n = len(A)
f_sum = sum(A) #false sum
actual_sum = 0
actual_sum_squares = 0
f_sum_square = 0 #false sum squares
for i in range(1,n+1):
actual_su... |
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
cnt, pre = 0, 0
length = len(flowerbed)
flowers = flowerbed + [0]
for idx, _ in enumerate(flowerbed):
next_ = flowers[idx]
if not _:
print(cnt, idx, pre, flowers[i... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 15 11:59:54 2015
@author: ktritz
"""
def _postprocess(signal, data):
if signal._name in 'radius' and signal.units in 'cm':
data /= 100.
signal.units = 'm'
return data
|
# vim:tw=50
""""While" Loops
Recursion is powerful, but not always convenient
or efficient for processing sequences. That's why
Python has **loops**.
A _loop_ is just what it sounds like: you do
something, then you go round and do it again, like
a track: you run around, then you run around again.
Loops let you do ... |
"""Deserialization of incoming requests"""
class ASKRequest(dict):
"""Class to deserialize and access data for incoming requests
Allows access to request data via dot notation by dynamically
assigning attributes. Hopefully allows more graceful handling
of requests in the face of possible future reque... |
start = int(input())
end = int(input())
def is_divide(number):
return any(number % i == 0 for i in range(2, 11))
def get_divise_numbers(start, end):
return [s for s in range(start, end + 1) if is_divide(s)]
def print_result(numbers):
print(numbers)
numbers = get_divise_numbers(start, end)
print_resu... |
token = "1047594455:AAGGblu9FGRNgPkjMEcbX7I5BuwDHUBQqsI"
MODULE_NAME = "admin"
MESSAGE_AMOUNT = "People registered: "
MESSAGE_UNAUTHORIZED = "Unauthorized access attempt. Administrator was notified"
MESSAGE_SENT_EVERYBODY = "Message has been sent to everybody"
MESSAGE_SENT_PERSONAL = "Message has been sent"
MESSAGE_AB... |
class KikErrorException(Exception):
def __init__(self, xml_error, message=None):
self.message = message
self.xml_error = xml_error
def __str__(self):
return self.__repr__()
def __repr__(self):
if self.message is not None:
return self.message
else:
... |
class Solution(object):
def runningSum(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
for i in range(1, len(nums)):
nums[i] = nums[i] + nums[i-1]
return nums
if __name__ == '__main__':
nums = [1, 2, 3]
obj = Solution()
obj.runni... |
def getCourseList():
"""
Convert Dictionary list of course to a list
Returns:
list : a list for the types of courses in OSCAR
"""
courseDescription = []
for courseName, description in courseDict.items():
courseDescription.append(courseName + ": " + description)
return course... |
"name & description of constants"
MONGODB_LOCAL = "mongodb://localhost:27017/"
DATABASE_NAME = "danmaku_db"
SERVER_INFO_NAME = "server_db"
DANMAKU_THRESHORD = 250
ROOM_DANMAKU_THRESHOLD = 10
MAINDB = "until_200220"
"""
information of every interpretation danmaku (without message)
{
message:[String]
message_leng... |
"""ScriptRunner custom exceptions."""
class ScriptRunnerException(BaseException):
"""Base ScriptRunner exception."""
class FailuresException(ScriptRunnerException):
"""Failures parent exception."""
class StopKeywordFailures(FailuresException):
"""ScriptRunner `"stop"` keyword exception."""
class Unk... |
class Script(object):
START_MSG = """🌐[Share and Support](https://t.me/share/url?url=https://t.me/Tamil_RockersGroup)🌐
"""
HELP_MSG = """
NO GONNE HELP U BRO/SIS
"""
ABOUT_MSG = """⭕️<b>My Name : MT Unlimited Filter Bot</b>
⭕️<b>Creater :</b> <b>@geronimo1234</b>
⭕️<b>Language :</b> <code>Pytho... |
def anonymous_allowed(fn):
fn.authenticated = False
return fn
def authentication_required(fn):
fn.authenticated = True
return fn
|
class ansi: pass
ansi.red = '\x1b[41m'
ansi.orange = '\x1b[48;5;130m'
ansi.green = '\x1b[42m'
ansi.yellow = '\x1b[43m'
ansi.blue = '\x1b[44m'
ansi.magenta = '\x1b[45m'
ansi.cyan = '\x1b[46m'
ansi.white = '\x1b[47m'
ansi.reset = '\x1b[49m'
fill = {
'O': ansi.orange+' '+ansi.reset,
'G': ansi.green+' '+ansi.reset... |
class Pessoa:
# Atributos de classe/default
olhos = 2
def __init__(self, *filhos, nome = None, idade = 26):
# Atributos de instancia
self.nome = nome
self.idade = idade
self.filhos = list(filhos)
# Método da instância
def cumprimentar(self):
return f'Olá, me... |
# ----------------------------------------------------------------------
# TTSystem errors
# ----------------------------------------------------------------------
# Copyright (C) 2007-2020, The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
class TTErro... |
class MNIST_v4(torch.nn.Module):
training_losses = [] #for plotting purposes
validation_losses = [] #for plotting purposes
training_accuracy = [] #for plotting purposes
validation_accuracy = [] #for plotting purposes
criterion = None #for criterion check
optim ... |
input()
l = [*map(int, input().split())]
l.sort()
print(max(l[0]*l[1], l[0]*l[1]*l[-1], l[-1]*l[-2]*l[-3], l[-1]*l[-2]))
|
'''
MIT License
Copyright (c) 2020 Jimeno Fonseca
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, merge, publish... |
pkgname = "python-pyyaml"
pkgver = "6.0"
pkgrel = 0
build_style = "python_module"
hostmakedepends = ["python-setuptools", "python-cython"]
makedepends = ["libyaml-devel", "python-devel"]
pkgdesc = "YAML parser and emitter for Python"
maintainer = "q66 <q66@chimera-linux.org>"
license = "MIT"
url = "http://pyyaml.org/wi... |
# -*- coding: utf-8 -*-
class Root(object):
def __init__(self, request):
self.request = request
|
# https://codeforces.com/problemset/problem/510/A
n, m = [int(x) for x in input().split()]
counter = 0
for row in range(1, n + 1):
if row % 2 == 1:
print(m * '#')
else:
counter += 1
if counter % 2 == 1:
print((m - 1) * '.' + '#')
else:
print('#' + (m - ... |
def calc_bmi(x,y):
ans = y/(x*x)
return ans
x = 2
y = 80
if ans < 18:
print("痩せ気味")
elif 18 <= ans < 25:
print("普通")
elif ans >= 25:
print("太り気味")
|
roll = [1, 2, 3]
names = ['Ayush', 'Joe', 'Rob']
pair = zip(roll, names)
print(dict(pair))
bob2 = dict(zip(['names', 'job', 'age'], ['Bob', 'dev', 40]))
print(bob2)
# Nested dictionaties
record = {
'emp1' :
{ 'name' : {'first' : 'Ayush', 'last' : 'Dutta' },
'job' : 'Software Dev',
'age' : 17... |
# areas list
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
# Code the for loop
for areas in areas :
print(areas)
# areas list
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
# Change for loop to use enumerate() and update print()
for index, area in enumerate(areas) :
print("room " + str(index) + ": " + str... |
class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext
... |
# Arithmetic
# +, -, *, /, %, all work with numbers and variables holding numbers
# +=, -=, *=, /=, i.e x += 1 is the same as x = x + 1
x = 1 + 1 # assign 1 + 1 to x
y = 0
y += x # add x to y
|
def best_stock(data):
max = 0 # max price
best = '' # best stock
for s in data:
if data[s] > max:
max = data[s]
best = s
return best
if __name__ == '__main__':
print("Example:")
print(best_stock({
'CAC': 10.0,
'ATX': 390.2,
... |
#字符串
#字符串的驻留机制
a='hello'
b="hello"
c='''hello'''
print(a,id(a))
print(b,id(b))
print(c,id(c))#地址相同
#驻留,字符串只在编译时进行驻留,而非运行时
a="abc"
b="ab"+"c"
c="".join(["ab","c"])
print(a is b)
print(a is c)#is可以判断是否相等,严格相等id和值
print(id(a))
print(id(b))
print(id(c))#c的id与ab并不相同
#字符串的常用操作
s="hello,hello"
#正向索引
print(s.index("lo"))
pri... |
# This file is automatically generated during the release process
# Do not edit manually
"""Version module for github_actions_test."""
__version__ = "0.2.0"
|
# Adicionando listas dentro de listas
dados = []
dados.append('pedro')
dados.append('35')
pessoas = []
pessoas.append(dados[:]) #Observe a estrutura "[:]" , está gera uma cópia exata da lista, a ser adicionada.
#Exemplo de lista dentro de lista
pessoas = [['pedro',25],['maria',19],['joao',32]]
# Selecioando item dent... |
"""
Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
"""
"""Question 22
Level 3
Question:
Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
Suppos... |
class HTTPError(Exception):
def __init__(self, status_code, message=""):
"""
Raise this exception to return an http response indicating an error.
This is a boilerplate exception that was originally from Crane project.
:param status_code: HTTP status code. It's a good idea to get th... |
# https://leetcode.com/problems/sort-characters-by-frequency/
class Solution:
def frequencySort(self, s: str) -> str:
char_frequencies = dict()
for char in s:
char_frequencies[char] = char_frequencies.get(char, 0) + 1
char_frequencies = list(char_frequencies.items())
cha... |
def solution(nums):
n = len(nums)
dp = [1]*n
for i in range(n):
if i == 0:
dp[0] = nums[0]
else:
dp[i] = max(dp[i-1]*nums[i], nums[i])
return max(dp)
def main():
n = int(input())
nums = []
for _ in range(n):
nums.append(float(input()))
nu... |
n1 = int(input('Digite o preço do primeiro produto: '))
n2 = int(input('Digite o preço do segundo número: '))
desconto1= ((n1 * 8) / 100) - n1
desconto2= ((n2 * 11) / 100) - n2
total = (desconto1 + desconto2) *-1
print ('Com o desconto no primeiro produto de 8% e de 11% no segundo produt, o total vai ser de {}... |
#
# PySNMP MIB module Q-IN-Q-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Q-IN-Q-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:43:18 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, 09:... |
def handler(connection, event):
if event.arguments and event.arguments[0].startswith("!r"):
connection.privmsg(event.target, "\x02\x034 Rule one: \x035 No Banninating!")
connection.privmsg(event.target, "\x02\x034 Rule two: \x035 See rule one")
connection.privmsg(
event.targe... |
previous_scores = [0] * 301
def solve(num_stairs, points):
if num_stairs < 3:
print(previous_scores[num_stairs])
return
else:
return points[num_stairs - 1] + solve(num_stairs - 1)
if __name__ == '__main__':
num_stairs = int(input())
points = [int(input()) for _ in range(num_s... |
# AUTOGENERATED! DO NOT EDIT! File to edit: 21_multi_attributes.ipynb (unless otherwise specified).
__all__ = ['are_recurrent', 'get_summary_statistic', 'get_routine_scores', 'get_synchrony', 'get_sequence_frequencies']
# Cell
def are_recurrent(sequences):
"Returns true if any of the sequences in a given collecti... |
""" Various utility methods for `taskweb` """
def parse_undo(data):
""" Return a list of dictionaries representing the passed in
`taskwarrior` undo data.
"""
undo_list = []
for segment in data.split('---'):
parsed = {}
undo = [line for line in segment.splitlines() if line.strip... |
class Paginator:
"""Class hold Pagination for sqlalchemy query"""
def __init__(self, sqlalchemy_query, offset, limit):
"""
:param sqlalchemy_query: sqlalchemy query
:param offset: int offset of query
:param limit: int limit of query
"""
self.offset = offset if of... |
class Speed:
def __init__(self):
self._cache = {}
def get_value(self, entity):
value = 0
if entity in self._cache:
value = self._cache[entity]
return value
def update(self, entity, value):
self._cache[entity] = value
# speed.py
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
# Recursion ([left, mid, right])
'''
if root is None:
... |
def main():
for x in range(4):
if x == 5:
break
else:
print("Well of course that didn't happen")
for x in range(7):
if x == 5:
break
else:
print("H-hey wait!")
if __name__ == '__main__':
main()
|
lista = []
while True:
lista.append(int(input('Digite um valor:')))
cont = str(input('Quer continuar? S/N ')).upper()
if cont == 'N':
break
print(f'Você digitou {len(lista)} elementos')
lista.sort(reverse=True)
print(f'Os valores em ordem decrescentesão {lista}')
if 5 in lista:
print('O valor 5 ... |
class Sourcefile(Dashboard.Module):
"""Show the program source code, if available."""
def __init__(self):
self.file_name = None
def label(self):
return 'Sourcefile'
def lines(self, term_width, style_changed):
if self.output_path is None:
return []
# skip i... |
'''
@author: Sergio Rojas
@contact: rr.sergio@gmail.com
--------------------------
Contenido bajo
Atribución-NoComercial-CompartirIgual 3.0 Venezuela (CC BY-NC-SA 3.0 VE)
http://creativecommons.org/licenses/by-nc-sa/3.0/ve/
Creado en abril 21, 2016
'''
def f(x):
if (type(x)==int or type(x)==float or type(x)==co... |
FILENAMES = ("adjectives.txt", "adverbs.txt", "alliterations.txt",
"compoundwords.txt", "conjunctions.txt",# "duos.txt",
"interjections.txt", "nouns.txt", "occupations.txt",
"pronouns.txt", "verbs.txt")
def _extract_words_from_raw_data(filenames=FILENAMES):
""" usage: _extrac... |
# Section 5.3 snippets
# Creating Tuples
student_tuple = ()
student_tuple
len(student_tuple)
student_tuple = 'John', 'Green', 3.3
student_tuple
len(student_tuple)
another_student_tuple = ('Mary', 'Red', 3.3)
another_student_tuple
a_singleton_tuple = ('red',) # note the comma
a_singleton_tuple
# Accessing Tu... |
nome = input("Digite o nome do vendedor: ")
salario = float(input("Digite o salário fixo: "))
vendas = float(input("Digite o total de vendas:"))
comissao = salario * (15/100)
salario_final = salario + comissao
print(nome, " o seu salário fixo é de R$", salario, "e seu salário com a comissão é de R$" , salario_final) |
#Ejercicio 4
'''
Complejidad temporal/algorítmica: O(n^2)
'''
def find_needle(needle, haystack):
#Esta función recorrerá cada caracter del haystack para compararlo con el needle, 1er caracter
#Si hay equivalencia, se entra al 2do for para comparar con los caracteres de needle
if(len(needle) <= len(haystack)):
#V... |
# Plugin author
__author__ = 'John Maguire'
# Plugin homepage
__url__ = 'https://github.com/JohnMaguire2013/Cardinal/'
|
x = False
y = True
# a. Write an expression that produces True iff both variables are True.
print((x and not y) or (y and not x))
# b. Write an expression that produces True iff x is False.
print(not x)
# c. Write an expression that produces True iff at least one of the variables is True.
print(x or y) |
"""Group Model"""
class CBWGroup:
"""Group Model"""
def __init__(self,
id="", # pylint: disable=redefined-builtin
color="",
name="",
description="",
**kwargs): # pylint: disable=unused-argument
self.id = id # pylin... |
class Tokenizer(object):
"""The root class for tokenizers.
Args:
return_set (boolean): A flag to indicate whether to return a set of
tokens instead of a bag of tokens (defaults to False).
Attributes:
return_set (boolean): An att... |
n,m,a,x,r = [int(i) for i in input().split()]
s = input()
for i in range(m):
t = input()
for i in range(a):
p = input()
if(n<10**6 and r<=x):
print(1)
print(3,1,10**6-n)
else:
print(0)
|
def get_pk_type(schema, pk_field) -> type:
try:
return schema.__fields__[pk_field].type_
except KeyError:
return int
|
load("@bazel_skylib//lib:paths.bzl", "paths")
load("//:def.bzl", "project")
def _start_drone_runner_impl(ctx):
template_name = paths.basename(ctx.file._script_template.short_path)
script = ctx.actions.declare_file("rendered_{}".format(template_name))
ctx.actions.expand_template(
template = ctx.fil... |
table = {'1985': 'Test movie' , '1983': 'Test Movie2' , '2000': 'Test Movie 3'}
year = '1983'
movie = table[year]
print(movie)
for year in table:
print(year + '\t' + movie + '\t') |
km = float(input('Quantos Km foram percorridos? '))
dias = int(input('Quantos dias alugados? '))
print('O valor a pagar pelo aluguel de {} dias e {} Km percorridos é R${:0.2f}'.format(dias, km, (60*dias)+(0.15*km)))
|
"""
Test `rlmusician.utils` package.
Author: Nikolay Lysenko
"""
|
class Router:
def __init__(
self,
databricks_url: str,
routes: dict,
):
self.__databricks_url = databricks_url
self.__routes = routes
def generate_url(self, route_name: str, **kwargs):
if route_name not in self.__routes:
raise Exception(f"Route no... |
exception_messages = {
"InvalidSelectionStrategy": lambda selection_strategy, allowed_selection_strategies: f"{selection_strategy} is not a valid selection strategy. "
f"Available options are {', '.join(allowed_selection_strategies)}.",
"InvalidPopulationSize": "The population size must be larger than 2",
... |
x = 25
epsilon = 0.01
numGuesses = 0
low = 1.0
high = x
guess = (high + low ) / 2.0
while abs(guess**2 - x) >= epsilon:
print ('low = ' + str(low) + 'high =' + str(high) + 'Guess = ' + str(guess))
numGuesses += 1
if guess**2 < x:
low = guess
else:
high = guess
guess ... |
# programme to input student details and view them
# this is a modification of students.py but using a dict for choices/options
# helen o'shea
# 20210218
# function to show the menu - same as students.py
def show_menu():
print("What would you like to do? \n\
\t(a) Add new student\n\
\t(v) View students\n\
\t... |
'''cidades = ['Rio de Janeiro', 'sao paulo', 'salvador']
cidades[0] = 'brasilia'
cidades.append('santa catarina')
cidades.remove('salvador')
cidades.insert(1, 'salvador')
cidades.pop(1)
cidades.sort()
print(cidades)'''
'''numeros = [2, 3, 4, 5]
letras = ['a', 'b','c', 'd']
final = numeros + letras
print(final)
numer... |
def tomadas():
reguas = list(map(int, input().split()))
t1 = reguas[0]
t2 = reguas[1]
t3 = reguas[2]
t4 = reguas[3]
numeros_de_aparelhos = t1 + t2 + t3 - 3 + t4
print(numeros_de_aparelhos)
tomadas()
|
#!/usr/bin/env python3
"""Solves problem 021 from the Project Euler website"""
first_twenty_amicable_numbers = [(220, 284), (1184, 1210), (2620, 2924), (5020, 5564), (6232, 6368), (10744, 10856),
(12285, 14595), (17296, 18416), (63020, 76084), (66928, 66992), (67095, 71145),
... |
# Copyright (c) 2012 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': {
'chromium_code': 1,
},
'targets': [
{
# GN version: //cc
'target_name': 'cc',
'type': '<(component)',
... |
max_size = 10
print(
"(a)" + " " * (max_size) +
"(b)" + " " * (max_size) +
"(c)" + " " * (max_size) +
"(d)" + " " * (max_size)
)
for i in range(1, max_size + 1):
print("*" * i, end = " " * (max_size - i + 3))
print("*" * (max_size - i + 1), end = " " * (i - 1 + 3))
print(" " * (i - ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.