content stringlengths 7 1.05M |
|---|
#author SANKALP SAXENA
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
arr = list(arr)
arr.sort()
#print(arr)
l = -1
i = 0
e = 0
f = 0
flag = False
while(True) :
e = arr.pop(-1)
if(len(arr) == 1):
flag = True
... |
"""Given n names and phones numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each namequeried, print the associated entry from your phone book on a new line in the form name = phoneNumber.
If an... |
class CaesarCipher:
def encrypt(self, plain, n):
rst = [None] * len(plain)
for i in range(len(plain)):
rst[i] = chr((ord(plain[i]) - ord('A') + n) % 26 + ord('A'))
return ''.join(rst)
def decrypt(self, encrypted, n):
rst = [None] * len(encrypted)
f... |
class LotteryPlayer:
def __init__(self, name):
self.name = name
self.number = (1, 34, 56, 90)
def __str__(self):
return f"Person {self.name} year old"
def __repr__(self):
return f"<LotteryPlayer({self.name})>"
def total(self):
return sum(self.number)
player... |
def vert_mirror(strng):
arr = strng.split("\n")
res = []
for word in arr:
w = word[::-1]
res.append(w)
return '\n'.join(res)
def hor_mirror(strng):
# arr = splint("\n")
arr = strng.split("\n")
# revirse every element in arr
res = arr[::-1]
# return join arr ("\n")
... |
"""
Idempotency errors
"""
class IdempotencyItemAlreadyExistsError(Exception):
"""
Item attempting to be inserted into persistence store already exists and is not expired
"""
class IdempotencyItemNotFoundError(Exception):
"""
Item does not exist in persistence store
"""
class IdempotencyAl... |
display = [['.' for i in range(50)] for j in range(6)]
instructions = []
while True:
try:
instructions.append(input())
except:
break
for instruction in instructions:
if instruction[:4] == 'rect':
i, j = instruction.find(' '), instruction.find('x')
width = int(instruction[i ... |
one = int(input("Enter the number no 1: "))
two = int(input("Enter the number no 2: "))
three = int(input("Enter the number no 3: "))
four = int(input("Enter the number no 4: "))
one += two
three += four
dell = one / three
print("Answer %.2f" % dell)
|
# https://www.hackerrank.com/challenges/counting-valleys/problem
def countingValleys(steps, path):
# Write your code here
valley = 0
mountain = 0
state = 0
up = 0
down = 0
before_present_state = 0
for step in range(steps):
if path[step] == 'D':
down += 1
elif ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Purpose:
connections methods
'''
__author__ = 'Matt Joyce'
__email__ = 'matt@joyce.nyc'
__copyright__ = 'Copyright 2016, Symphony Communication Services LLC'
class Connections(object):
def __init__(self, *args, **kwargs):
super(Connections, ... |
def findOutlier(integers):
ofound = 0
efound = 0
ocnt = 0
ecnt = 0
for el in integers:
if (el % 2 == 1):
ofound = el
ocnt += 1
else:
efound = el
ecnt += 1
return(efound if ocnt > ecnt else ofound)
print("The outlier is %s" % findO... |
testList = [1, -4, 8, -9]
def applyToEach(L, f):
for i in range(len(L)):
L[i] = f(L[i])
def turnToPositive(n):
if(n<0):
n*=-1
return n
applyToEach(testList, turnToPositive)
def sumOne(n):
n+=1
return n
applyToEach(testList, sumOne)
def square(n):
n**=2
return n
applyTo... |
n=500
primeno=[2,3]
i=5
flag=0
diff=2
while i<=500:
print(i)
flag_p=1
for j in primeno:
if i%j== 0:
flag_p = 0
break
if flag_p==1:
primeno.append(i)
i += diff
if flag == 0:
diff=4
flag=1
continue
if flag == 1:
diff=2
... |
'''
desc:尝试定义一种新的数据类型
等差数列
'''
class ArithemeticSequence:
def __init__(self, start=0, step=1):
print('Call function __init__')
self.start = start
self.step = step
self.myData = {}
# 定义获取值的方法
def __getitem__(self, key):
print('Call function __getitem__'... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class AnalyseJarArg(object):
"""Implementation of the 'AnalyseJarArg' model.
API to analyse a JAR file. This JAR may contain multiple mappers/reducers.
Jar will be analysed and list of all mappers/reducers found in the jar
will be returned.
... |
print("Throughout this program please use consistent units of measure.")
unitOfMeasure = input("Please enter your unit of measure: ").strip()
print("You do not need to enter the units of measure when asked for measurements.")
try:
width = float(input("Width of Pool: "))
except ValueError:
print("That is not ... |
# file classtools.py(new)
"Assorted class utilities and tools"
class AttrDisplay:
"""
Provides an inheritable display overload method that show instances with
their class name and a name=value pair for each attribute stored on the
instance itself(but not attributes inherited from its classes). Can be
... |
#Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média.
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
m = (n1 + n2)/2
print('A primeira nota foi {} \n A segunda nota foi {}. \n Portanto, a média obtida foi {:.1f}.'.format(n1, n2, m)) |
#! /usr/bin/env python3
def neighbors(board, x, y) -> int :
minx, maxx = x - 1, x + 1
miny, maxy = y - 1, y + 1
if miny < 0 : miny = 0
if maxy >= len(board[0]) : maxy = len(board[0]) - 1
if minx < 0 : minx = 0
if maxx >= len(board) : maxx = len(board) - 1
count = 0
for i in range(min... |
"""
"""
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
def setup_immer(name):
git_repository(
name = name,
remote = "https://github.com/arximboldi/immer",
commit = "2eea2202b5b71b58d18cc4672a5d995397a9797b",
shallow_since = "1633428364 +0200"
)
|
class Container:
def __init__(self, processor, processes):
self._processor = processor
self._processes = processes
def run(self):
for process in self._processes:
process.run(self._processor)
|
def test_registering_new_filter_with_no_args(rpc_client, rpc_call_emitter):
filter_id = rpc_client(
method='eth_newFilter',
params=[{}]
)
changes = rpc_client(
method='eth_getFilterChanges',
params=[filter_id],
)
assert not changes
def test_registering_new_filter_w... |
data = []
# zbieranie danych z pliku do listy
with open('../dane/sygnaly.txt') as f:
for x in f:
data.append(x[:-1])
# funkcja sprawdzajaca czy string spelnia warunek z zadania
def is_valid(s):
# parowanie kazdej litery z kazda litera zeby sprawdzic
# czy ich kody ASCII sa wystarczajaco blisko si... |
__author__ = 'Eric SHI'
__author_email__ = 'longwosion@gmail.com'
__url__ = 'https://github.com/Longwosion/parrot'
__license__ = 'BSD'
version = __version__ = '0.1.0'
|
def steam(received):
# substitute spaces for url space character
response = "https://store.steampowered.com/search/?term=" + received.replace(' ', "%20")
return response
|
# coding=utf-8
__author__ = 'Rodrigo Agerri <rodrigo.agerri@ehu.es>'
stop_words = set(( 'unas', 'una', 'unos', 'un', 'del', 'al', 'el', 'la', 'los', 'lo', 'las', 'de', 'en', 'sobre', 'por', 'dentro', 'hacia', 'desde', 'fuera', 'como', 'así', 'tal', 'o', 'y', 'esos', 'esas', 'este', 'esta', 'aquellas', 'aquellos', 'e... |
while True:
contrasena=int(input("Inserte una contraseña Valida "))
if contrasena==2002:
print("Acesso Permitido ")
break
else:
print("senha invalida ")
contrasena=int(input("Inserte una contraseña Valida"))
|
# -*- coding: utf-8 -*-
"""Django password hasher using a fast PBKDF2 implementation (fastpbkdf2)."""
VERSION = (0, 0, 1)
__version__ = '.'.join([str(x) for x in VERSION])
|
# Atividade 04
# Proposta =>
# Leia a idade de um nadador e exiba sua categoria segundo as regras:
# A (5 até 7), B (8 até 10), C (11 até 13), D (14 até 18)
# E (idade > 18)
# Captura a idade inserido e armazena na variável.
idade = int(input("Informe sua idade: "))
# Faz as validações para definir a Categoria
if id... |
#Calculadora de média de 4 notas
n1 = float(input("Digite sua nota 1: "))
n2 = float(input("Digite sua nota 2: "))
n3 = float(input("Digite sua nota 3: "))
n4 = float(input("Digite sua nota 4: "))
media = (n1+n2+n3+n4) / 4
print(f"Sua média é: ", media) |
#encoding:utf-8
subreddit = 'desigentlemanboners'
t_channel = '@r_dgb'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
# 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.
{
'includes': [
'app_remoting_webapp_build.gypi',
],
'targets': [
{
'target_name': 'ar_sample_app',
'app_id': 'ljacajndfccfgnfohlg... |
n , dm = map(int,input().split())
li = list(map(int, input().split()))
x = -1
for i in range(n):
if int(li[i]) <= dm:
x = i
print("It hadn't snowed this early in %d years!"%x)
break
else:
print("It had never snowed this early!") |
class BasePSError:
def __init__(self, start_position, end_position, error_type, error_message, context):
self.start_position = start_position
self.end_position = end_position
self.error_type = error_type
self.error_message = error_message
self.context = context
def gener... |
msg_template = """Hello {name},
Thank you for joining {website}. We are very
happy to have you with us.
""" # .format(name="Justin", website='cfe.sh') without using the function
def format_msg(my_name="Dev tez", my_website="t&tinc.org"):
my_msg = msg_template.format(name=my_name, website=my_website)
return my_... |
class Solution:
def sequenceReconstruction(self, org: List[int], seqs: List[List[int]]) -> bool:
children = collections.defaultdict(set)
parents = collections.defaultdict(set)
nodes = set()
for s in seqs:
for i in range(len(s)):
nodes.add(s[i])
... |
def parse_vars(vars):
res = set()
for var in vars.split(" "):
var = var.split("<")[0]
res.add(chr(int(var[2:], 16)))
return res
|
n,m=map(int,input().split())
l=[]
for i in range(n):
new=list(map(int,input().split()))
l.append(new)
ans=[]
for i in range(n):
ans.append([0]*m)
for i in range(n):
for j in range(m):
if (i+j)%2==1:
ans[i][j]=720720 #lcm of first 16 numbers
else:
ans[i][j]=720720+... |
# -*- coding: utf-8 -*-
# @Author: 1uci3n
# @Date: 2021-03-10 16:02:41
# @Last Modified by: 1uci3n
# @Last Modified time: 2021-03-10 16:03:13
class Solution:
def calculate(self, s: str) -> int:
i = 0
kuohao = []
temp_sums = []
temp_sum = 0
temp_str = '0'
while i <... |
print('='*8,'Aumentos Multiplos','='*8)
s = float(input('Qual o valor do salario atual do funcionario? R$'))
if s<=1250.00:
ns = s*1.15
print('O novo salario do funcionario devera ser de R${:.2f}.'.format(ns))
else:
ns = s*1.10
print('O novo salario do funcionario devera ser de R${:.2f}.'.format(ns))
|
X = int(input())
azuke = 100
ans = 0
while True:
azuke = int(azuke*1.01)
ans += 1
if azuke >= X:
print(ans)
exit(0)
|
text = "hello world"
for c in text:
if c ==" ":
break
print(c) #will print every single fro mthe beginning of text but will stop a first space
|
# Write a program that ask the user car speed.If exceed 80km/h, show one message saying that the user has been fined.In this case, show the fine price, charging $5 per km over the limit of 80km/h
speed=int(input("What is your car speed(in km/h): "))
if speed>80:
fine=(speed-80)*5
print(f"You has been fined in $... |
TEAM_DATA = {
"nba": {
"1": [
"atl",
"hawks",
"atlanta hawks",
"<:hawks:935782369212895232>"
],
"2": [
"bos",
"celtics",
"boston celtics",
"<:celtics:935742825377718302>"
],
"3": [
... |
"""
Verifying an Alien Dictionary
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order.
The order of the alphabet is some permutation of lowercase letters.
Given a sequence of words written in the alien language, and the order of the alphabet,
return true i... |
class MSContentDrawView(object):
@property
def frame(self):
"""
Returns a CGRect of the current view
"""
pass
def zoomIn(self):
"""
Zooms in by 2x.
"""
# Not implemented
pass
def zoomOut(self):
"""
Zooms out by the... |
frutas = open('frutas.txt', 'r')
numeros = open('numeros.txt', 'r')
def informacion_lista(lista:list)->list:
auxiliar=[]
for i in lista:
print(len(lista))
return auxiliar
"""
if __name__ == "__main__":
lista_fruta_nueva=eliminar_un_caracter_de_toda_la_lista(lista_frutas,"\n")
print(lista_fruta_nueva)
li... |
class Solution(object):
# @return an integer
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
m=len(word1)+1; n=len(word2)+1
dp = [[0 for i in range(n)] for j in range(m)]
for i in range(n):
dp... |
def zmode(list) -> float:
"""Finds mode of given list
:param list: list of values
:return: int, float, None if no mode, or list if multiple modes"""
# mode = 0
# mode_count = 0
for i in list:
mode_count = 0
mode = 0
# index = 0
for i in list:
if list.c... |
class Solution:
def findSmallestSetOfVertices(self, n: int, edges):
in_degrees = {}
res = []
for u, v in edges:
in_degrees[v] = in_degrees.get(v, 0)+1
for i in range(n):
if in_degrees.get(i, 0) < 1:
res.append(i)
return res
"""
Succes... |
"""
U6 Dictionaries
@author: Gerhard Kling
"""
#=========================================================================================================
#Dictionaries
#=========================================================================================================
#Comma-separated list of key:value... |
# Array
# Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
#
# Example 1:
#
# Input:
# [
# [ 1, 2, 3 ],
# [ 4, 5, 6 ],
# [ 7, 8, 9 ]
# ]
# Output: [1,2,3,6,9,8,7,4,5]
# Example 2:
#
# Input:
# [
# [1, 2, 3, 4],
# [5, 6, 7, 8],
# [9,10,11,12]
# ]
# Output... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# TIOJ 1006.py
# @Author : ()
# @Link :
# @Date : 2019/10/5
a = input()
b = input()
a = int(a)
b = int(b)
print(a//b) |
days = input().split("|")
energy = 100
coins = 100
bakery_is_closed = False
for current_day in days:
current_day = current_day.split("-")
to_do = current_day[0]
number = int(current_day[1])
if to_do == "rest":
needed_energy = 100 - energy
gained_energy = min(number, needed_energy)
... |
"""細かな処理"""
class StateMachineHelperV13:
@classmethod
def is_verbose(clazz):
return False
@classmethod
def lookup_next_state_path_v13(clazz, transition_data, state_path, edge_name):
"""state_path に従って transition_data の階層を下りていきましょう"""
if clazz.is_verbose():
print(f... |
lista = []
par = []
impar = []
while True:
n = int(input('Digite o valor: '))
opcao = input('Deseja continuar?[S/N]').upper()
lista.append(n)
if n % 2 == 0:
par.append(n)
else:
impar.append(n)
if opcao == 'S':
print('Continuando...')
if opcao == 'N':
print(f'A... |
MODULE_NAME = 'Gigamon ThreatINSIGHT ConfTokenTest'
INTEGRATION_NAME = 'Gigamon ThreatINSIGHT'
GIGAMON_URL = 'https://portal.icebrg.io'
CONFIDENCE = SEVERITY = ('High', 'Medium', 'Low')
RELATIONS_TYPES = (
'Connected_To', 'Sent_From', 'Sent_To',
'Resolved_To', 'Hosted_On', 'Queried_For',
'Downloaded_To', 'D... |
def get_subindicator(metric):
subindicators = metric.indicator.subindicators
idx = metric.subindicator if metric.subindicator is not None else 0
return subindicators[idx]
def get_sum(data, group=None, subindicator=None):
if (group is not None and subindicator is not None):
return sum([float(row... |
mt = float(input('Insira valor em metros: '))
km = mt / 1000
hm = mt / 100
dam = mt / 10
dm = mt * 10
cm = mt * 100
mm = mt * 1000
print()
print('Valor em kilometros..: {:>20}'.format(km))
print('Valor em hectômetros.: {:>20}'.format(hm))
print('Valor em decâmetros..: {:>20}'.format(dam))
print('Valor em decímetros..: ... |
# -*- coding: utf-8 -*-
__all__ = ('__version__',)
__version__ = '0.39.0+dev'
def includeme(config):
config.include('pyramid_services')
# This must be included first so it can set up the model base class if
# need be.
config.include('memex.models')
config.include('memex.links')
|
description = 'setup for the NICOS watchdog'
group = 'special'
# The entries in this list are dictionaries. Possible keys:
#
# 'setup' -- setup that must be loaded (default '' to mean all setups)
# 'condition' -- condition for warning (a Python expression where cache keys
# can be used: t_value stands for t/value e... |
num = 0
cont = 0
soma = 0
while num != 999:
num = int(input('Digite um número [999 para parar]: '))
if num != 999:
cont +=1
soma += num
print(f'Ao todo foram digitados {cont} numeros e a soma entre eles é {soma}') |
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Point(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return Point(self... |
# Constants
PROD = "product"
LOCN = "location"
PRLO = "product_location"
PRMO = "product_movement"
names = [PROD, LOCN, PRLO, PRMO]
required_cols = {
PROD: ("product_id", "product_name"),
LOCN: ("location_id", "location_name"),
PRLO: ("product_id", "location_id", "qty"),
PRMO: ("movement_id", "transac... |
def main():
n_gnomes_orig, n_gnomes_remain = [int(x) for x in input().split()]
gnomes_remain = []
for _ in range(n_gnomes_remain):
gnomes_remain.append(int(input()))
gnomes_remain_tmp = set(gnomes_remain)
missing_gnomes = [g for g in range(1, n_gnomes_orig + 1) if g not in gnomes_remain_tm... |
print("*****************")
print("Guessing game")
print("*****************")
secret_number = 43
attempts_total = 3
for attempt in range(1, attempts_total + 1):
print("Attempt {} by {}".format(attempt, attempts_total))
user_number_str = input("Fill the number: ")
print("Your number was: " + user_number_st... |
[
[0.0, 1.3892930788974391, 0.8869425734660505, 1.402945620973322],
[0.0, 0.1903540333363253, 0.30894158244285624, 0.3994739596013725],
[0.0, 0.03761142927757482, 1.2682277741610029, 0.36476016345069556],
[0.0, -1.187392798652706, -1.0206496663686406, -1.35111583891054],
[0.0, -1.742783579889951, -2... |
_ = input() # number of test cases; we can ignore this since it has no significance
temps = map(int, input().split()) # all the temps stored to a list with type int
subercold = 0 # how many temps below 0 we got
for i in temps:
# for every temp we recorded if it's less than 0 add +1 to subercold
if i < 0:
... |
#!/usr/bin/python
# -*- utf-8 -*-
class Solution:
# @param A, a list of integer
# @return an integer
def singleNumber(self, A):
cache = {}
for a in A:
count = cache.get(a, 0) + 1
if count >= 3:
cache.pop(a)
else:
cache[a] =... |
# Criando arquivo 1 com 10 linhas
with open('arquivo1.txt', 'w') as arq1:
for line in range(1, 11):
arq1.write(f'Linha {line} do arquivo 1\n')
# Criando arquivo 2 com 10 linhas
with open('arquivo2.txt', 'w') as arq1:
for line in range(1, 11):
arq1.write(f'Linha {line} do arquivo 2\n')
# Lendo ... |
# https://www.codewars.com/kata/5432fd1c913a65b28f000342/train/python
'''
Instructions :
Create a function that accepts dimensions, of Rows x Columns, as parameters in order to create a multiplication table sized according to the given dimensions. **The return value of the function must be an array, and the numbers m... |
class Solution:
def reorderedPowerOf2(self, N: int) -> bool:
t=1
cands=set()
while t<=1000000000:
tt=sorted([ttt for ttt in str(t)])
cands.add(''.join(tt))
t*=2
print(cands)
tt=sorted([ttt for ttt in str(N)])
print(tt)
retur... |
# Lista de Preços com Tupla
mercadinho = (
'Sabão', 20.75,
'Televisão', 2400,
'Água Mineral', 5.30,
'Ventilador', 450,
'Geladeira', 1200,
'Guarda-roupa', 3600,
'Cama', 2100,
'Celular', 700,
'Computador', 9000,
'Fone de ouvido', 50
)
title = 'LISTA DE PRODUTOS'
print('=-=' * 15... |
#Meaning of Life?
answer = "42"
n = 1
i = 0
while i < 1:
x = input("What is the meaning of life? ")
if x != answer:
print("Incorrect.")
n = n + 1
if x == answer:
print("You got it in " + str(n) + " attempt(s)!")
break
|
#Create an empty set
s = set()
# Add elements to set
s.add(1)
s.add(2)
s.add(3)
s.add(4)
s.add(3)
s.remove(2)
print(s)
print(f"The set has {len(s)} elements.")
|
# /* Kattis: acm
# *
# * Topic: others
# *
# * Level: easy
# *
# * Brief problem description:
# *
# * branching summation
# *
# * Solution Summary:
# *
# * basic arithmetic
# *
# * Used Resources:
# *
# *
# *
# * I hereby certify that I have produced the following solution myself
# * using only t... |
def jmp_simple(n):
return 3 if n == 0 else 5
def jmp_short(n):
if n == 0:
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n += 1
n +... |
class Solution:
def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:
run = maxRun = 0
profit = maxProfit = 0
wait = 0
i = 0
while wait > 0 or i < len(customers):
if i < len(customers):
wait += customer... |
# Method 1
def reverse(str):
return str[::-1]
# Method 2
'''
def reverse(string):
result = ""
for letter in xrange(len(string), 0, -1):
result = result + string[letter-1]
return result
'''
if __name__=="__main__":
print("Enter a String: ",end="")
str = input()
print("Reverse of '",... |
config = {
# coinflex production api server
'rest_url': 'https://v2api.coinflex.com',
'rest_path': 'v2api.coinflex.com',
# local data filename
'coinflex_data_filename': 'coinflex_data.json',
# create an api key on coinflex.com and put it here
'api_key': "<your api key>",
'api_secret': "<your api secret>",
#... |
GUILD_ID = 391155528501559296
# ==== rewards ====
REWARDS_CHANNEL = 404753143172431873
DISCUSSION_CHANNEL = 556531902865997834
SCHEDULED_HOUR = 20 # 2000 GMT
ROLES_TO_PING = [
404055199054036993, # dm
631621534233919499, # planar dm
# 405499372592168960 # trial dm
]
# ==== onboarding ====
ROLLING_CHAN... |
class Movie():
# Initialize instance of class Movie
def __init__(self, movie_title, poster_image, trailer_youtube,
movie_storyline, movie_rating):
self.title = movie_title
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
... |
class Mammal:
mammal_population = 0
def __init__(self, name, age):
self.name = name
self.age = age
Mammal.mammal_population += 1
class Dog(Mammal):
dog_population = 0
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
... |
"""
===================
CanvasUserInterface
===================
Unsupported - this is a beta feature in Canvas, and does not translate to the
PPTX interface.
"""
class CanvasUserInterface(object):
"""
[NoInterfaceObject]
interface CanvasUserInterface {
void drawFocusIfNeeded(Element element);
... |
#Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros
metros = float(input('Digite o valor a ser convertido em metros: '))
cm = metros * 100
mm = metros * 1000
km = metros / 1000
hm = metros / 100
dam = metros / 10
dm = metros * 10
print('O valor em metros é {}m, em cm {:.0f... |
"""
Given two sorted linked lists, merge them together in ascending order and return a reference
to the merged list
"""
class ListNode:
def __init__(self, val=0, nextNode=None):
self.val = val
self.next = nextNode
class MergeLinkedList:
def printList(self, node: ListNode):
while nod... |
class WriteStreamClosedEventArgs(EventArgs):
""" WriteStreamClosedEventArgs() """
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return WriteStreamClosedEventArgs()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
Error=property(lambda self: object(),lambda self,v: None,lambda ... |
def apply_filters(sv_list, rmsk_track=None, segdup_track=None):
for sv in sv_list:
if sv.type == 'INS' or (sv.type == 'BND' and sv.bnd_ins > 0):
sv.filters.add('INSERTION')
def get_filter_string(sv, filter_criteria):
intersection = set(sv.filters).intersection(set(filter_criteria))
if ... |
huge = 999999999 # nothing but the largest number during calculation, just for convenience
cross_p = 0.8 # chromo cross probability
random_mutate_p = 0.1 # chromo random mutate probability
remove_mutate_p = 0.5 # remove the 'worst' route probability, opposite of it is direct restart probability
inter_change_p = 0.... |
brace = None
db = None
announcement = ""
templateLoader = None
templateEnv = None
datadog = None
datadogConfig = {} |
"""
Entrada
Metros-->float-->mtrs
Salida
Pulgafas-->float-->pul
Pie-->float-->pie
"""
mtrs=float(input("Digite los metros que quiera convertir: "))
pul=mtrs*39.37
pie=mtrs*3.281
print("Este valor en pies seria:", pie, "y en pulgadas es:",pul) |
def countWays(n):
a = 1
b = 2
c = 4
d = 0
if (n == 0 or n == 1 or n == 2):
return n
if (n == 3):
return c
for i in range(4, n + 1):
d = c + b + a
a = b
b = c
c = d
return d
n = 4
print(countWays(n))
|
class Solution:
def addNegabinary(self, arr1: 'List[int]', arr2: 'List[int]') -> 'List[int]':
n = max(len(arr1), len(arr2))
res = []
for i in range(-1, -n - 1, -1):
r = 0
if len(arr1) + i >= 0:
r += arr1[i]
if len(arr2) + i >= 0:
... |
#Função
def soma(a,b):
s = a + b
print(s)
def titulo(txt):
print('-' * 30)
print(txt)
print('-' * 30)
def contador(*num):
tam = len(num)
print(f'Recebi {num} números com o tamanho {tam}')
def dobra(lst):
pos = 0
while pos < len(lst):
lst[pos] *= 2
pos += 1
de... |
def logCommand(Command, Author, Date):
Message = f"[{str(Date)}] {Author}: {Command}\n"
with open('data/logs/commands.easy', 'a') as logFile:
logFile.write(Message)
logFile.close()
|
# https://atcoder.jp/contests/abc192/tasks/abc192_c
N, K = map(int, input().split())
ans = N
for _ in range(K):
str_N = str(ans)
g1 = int("".join(sorted(str_N, reverse=True)))
g2 = int("".join(sorted(str_N)))
ans = g1 - g2
print(ans)
|
class WeChatException(Exception):
DefaultMessage = '未知错误'
ErrorMessage = {
'-1': '系统繁忙,请稍后重试',
'0': '操作失败',
'1': '操作成功',
'10001': '图片上传失败,请重新上传',
'10002': '上传图片格式错误',
'20000': '微信响应签名错误',
'20001': '请求错误,请稍后重试',
'20002': '系统错误,请联系客服人员后重试', # 加密敏感信... |
# https://atcoder.jp/contests/abc002/tasks/abc002_3
ax, ay, bx, by, cx, cy = map(int, input().split())
ans = (ax * by + ay * cx + bx * cy - ay * bx - ax * cy - by * cx) * 0.5
print(abs(ans))
# ax ay 1 ax ay
# bx by 1 bx by
# cx cy 1 cx cy
# ax * by + ay * cx + bx * cy - ay * bx - ax * cy - by * cx
|
date = input("Inserisci una data in dd/mm (es: 22/10): ")
day = int(date[:2])
month = int(date[3:])
if month >= 1 and month <= 3:
stagione = "Winter"
elif month >= 4 and month <= 6:
stagione = "Spring"
elif month >= 7 and month <= 9:
stagione = "Summer"
elif month >= 10 and month <= 12:
stagione = "Fal... |
# separate file for keeping global constants
# right now need for LOGDIR_ROOT because this value is used in backend.py
# but is defined in backend.py descendants
LOGDIR_ROOT = None
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.