content stringlengths 7 1.05M |
|---|
# person = dict(first_name="Bob", last_name="Smith")
person = {
"first_name": "Bob",
"last_name": "Smith",
"age": 34,
"jobs": {
"programmer": "Sr. Developer",
"crochet": "Magazine Editor for Crocheting"
}
}
# person["jobs"]["programmer"]
# person = dict([
# ("first_name", "B... |
# Personalizando a representação string de uma classe
class MinhasCores():
def __init__(self):
self.red = 50
self.green = 75
self.blue = 100
# TODO: Use getattr para retornar um valor de forma dinâmica
# TODO: Use setattr para retornar um valor de forma dinâmica
# TODO: Use ... |
"""
Faça um programa que leia uma frase pelo teclado
quantas vezes aparece letra A
em que posição aparece primeiro
em que posição aparece pela última vez
"""
frase = input('Digite uma frase: ')
fraseLower = frase.lower()
print('A letra A aparece {} vez(es).'.format(fraseLower.count('a')))
print('A letra A inicia a a... |
k, q = map(int, input().split())
dp = [[0.0 for i in range(k + 1)] for j in range(10000)]
dp[0][0] = 1.0
for i in range(1, 10000):
for j in range(1, k + 1):
dp[i][j] = dp[i - 1][j] * j / k + dp[i - 1][j - 1] * (k - j + 1) / k
for t in range(q):
p = int(input())
for i in range(10000):
... |
def readlist(file="day_05/input.txt"):
with open(file, "r") as f:
return [int(char) for char in f.readline().split(",")]
def parse_instruction(instruction):
sint = str(instruction).zfill(5)
parm3 = bool(int(sint[0]))
parm2 = bool(int(sint[1]))
parm1 = bool(int(sint[2]))
op = int(sint[-... |
#Bases Númericas - Conversão
num = int(input('Digite um numero inteiro: '))
conversao = int(input( 'Selecione a base de conversão: \n 1.Binário \n 2.Octal \n 3.Hexadecimal\nDigite sua opção: '))
if conversao == 1:
print('O numero convertido para binario : {}'.format(bin(num)[2:]))
elif conversao == 2:
print('O... |
# https://projecteuler.net/problem=63
"""
The reason i have choosen 25 is because any number which when is raised to the power of 25 gradually increases from
8 digits of 2^25 linearly(at first with a diffrence of 4(that is num_of_digit in 2^25 is 8 and 3^25 id 12) which starts
halfening) ,hence all the sollution must ... |
def cantApariciones(letra, cadena):
cant=0
for i in range(len(cadena)):
if (letra==cadena[i]):
cant+=1
return (cant)
def imprimeCantApariciones(cadena):
listaAparecidos=[]
for i in range(len(cadena)):
letra=cadena[i]
if (cantApariciones(letra,listaAp... |
'''Desenvolva um programa que leia o primeiro termo e a razão de uma PA.
No final, mostre os 10 primeiros termos dessa progressão.'''
primeiroTermo = int(input("Qual o primeiro Termo da PA: "))
razao = int(input("Qual a razão dessa PA: "))
decimo = primeiroTermo + (10 - 1) * razao
for c in range(primeiroTermo,decimo + ... |
"""
2 If-Abfragen (Tag 1)
2.4 Überprüfe, ob ein vorher festgelegtes Jahr ein Schaltjahr ist.
Hinweise:
- Jahreszahl nicht durch 4 teilbar: kein Schaltjahr
- Jahreszahl durch 4 teilbar: Schaltjahr
- Jahreszahl durch 100 teilbar: kein Schaltjahr
- Jahreszahl durch 400 teilbar: Schaltjahr
Beispiele:
... |
# *****************************************************************
# Copyright 2015 MIT Lincoln Laboratory
# Project: SPAR
# Authors: SY
# Description: IBM TA2 batch class
#
# Modifications:
# Date Name Modification
# ---- ---- ------------... |
# _*_ coding: utf-8 _*_
#
# Package: bookstore.src.core.repository.databases
__all__ = ["book_repository", "db_repository", "mysql_repository"]
|
mock_history_data = {
"coord": [50.0, 50.0],
"list": [
{
"main": {"aqi": 2},
"components": {
"co": 270.367,
"no": 5.867,
"no2": 43.184,
"o3": 4.783,
"so2": 14.544,
"pm2_5": 13.448,
... |
class Matrix:
"""
Square matrix
"""
def __init__(self, matrix):
assert len(matrix) == len(matrix[0]), "expected a square matrix"
self.container = matrix
def __mul__(self, other):
if not isinstance(other, Matrix): return TypeError
assert len(self.container) == len(oth... |
#! /usr/bin/env python
"""Module with a dictionary and variables for storing constant parameters.
Usage
-----
from param import VLT_NACO
VLT_NACO['diam']
"""
VLT_SPHERE = {
'latitude' : -24.627,
'longitude' : -70.404,
'plsc' : 0.01225, # plate scale [arcsec]/px
'diam': 8.2, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Filename: ClimbingStairs.py
# @Author: olenji - lionhe0119@hotmail.com
# @Description:
# @Create: 2019-07-23 11:58
# @Last Modified: 2019-07-23 11:58
class Solution:
def climbStairs(self, n: int) -> int:
if n == 1:
return 1
a = 1
... |
word = 'banana'
count = 0
for letter in word:
if letter == 'n':
count = count + 1
print(count) |
"""
1704. Determine if String Halves Are Alike
Easy
151
10
Add to List
Share
You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.
Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A',... |
class Solution(object):
def findRestaurant(self, list1, list2):
"""
:type list1: List[str]
:type list2: List[str]
:rtype: List[str]
"""
lookup = {}
for i, s in enumerate(list1):
lookup[s] = i
result = []
min_sum = float("inf")
... |
n = int(input())
left_dp = [1] * (n + 1)
right_dp = [1] * (n + 1)
arr = list(map(int, input().split()))
for i in range(1, n):
for j in range(i):
if arr[j] < arr[i]:
left_dp[i] = max(left_dp[i], left_dp[j] + 1)
for i in range(n - 2, -1, -1):
for j in range(n - 1, i, -1):
if arr[j]... |
#encoding:utf-8
subreddit = 'ani_bm'
t_channel = '@cahaf_avir'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
class Computer:
def __init__(self,name,size):
self.brand = name
self.size = size
class Laptop(Computer):
def __init__(self,name,size,model):
super().__init__(name,size)
self.model = model
if __name__ == "__main__":
abc = Laptop('MSI','15.6','GL Series')
print("... |
def div_elem_list(list, divider):
try:
return [i /divider for i in list]
except ZeroDivisionError as e:
print(e, '- this is the error.')
return list
list = list(range(10))
divider = 0
print(div_elem_list(list, divider))
# que permiten que tu no vas a tener errores dentro
# ... |
# Object change log actions
OBJECT_CHANGE_ACTION_CREATE = 1
OBJECT_CHANGE_ACTION_UPDATE = 2
OBJECT_CHANGE_ACTION_DELETE = 3
OBJECT_CHANGE_ACTION_CHOICES = (
(OBJECT_CHANGE_ACTION_CREATE, "Created"),
(OBJECT_CHANGE_ACTION_UPDATE, "Updated"),
(OBJECT_CHANGE_ACTION_DELETE, "Deleted"),
)
# User Actions Constan... |
class FileStructureHelper:
def __init__(self, run_settings):
self.run_settings = run_settings
def get_project_directory(self):
return self.run_settings.app_directory + '/projects/' + self.run_settings.project
def get_config_file_path(self):
return self.get_project_directory() + "/... |
"""
Copyright (c) 2019-2020, the Decred developers
See LICENSE for details
"""
class DecredError(Exception):
pass
|
# The usual way
numbers = [1, 2, 3, 4, 5, 6]
new_numbers = []
for f in numbers:
new_num = f + 1
new_numbers.append(new_num)
print(new_numbers)
# 6 lines!!
# With list comperhension
numbers = [1, 2, 3, 4, 5, 6]
new_numbers = [n + 1 for n in numbers]
print(new_numbers)
# 3 lines!!
# Using list comperhension wit... |
"""
Given a list, rotate the list to the right by k places, where k is non-negative.
Example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class So... |
def sum_numbers(num1, num2):
return num1 + num2
def multiply_numbers(num1, num2):
return num1 * num2
def func_executor(*args):
results = []
for arg in args:
func, nums = arg
results.append(func(*nums))
return results
print(func_executor((sum_numbers, (1, 2)), (multiply_number... |
# -*- coding: utf-8 -*-
#############################################################################
# Copyright Vlad Popovici <popovici@bioxlab.org>
#
# Licensed under the MIT License. See LICENSE file in root folder.
#############################################################################
__author__ = "Vlad P... |
# def changeName(n):
# n = 'ada'
# name = 'yiğit'
# changeName(name)
# print(name)
# def change(n):
# n[0] = 'istanbul'
# sehirler = ['ankara','izmir']
# change(sehirler[:])
# print(sehirler)
def add(*params): # tuple kullanırken * tek yıldız kullanılır
print(type(params))
sum ... |
class Solution:
def matrixBlockSum(self, mat: List[List[int]], K: int) -> List[List[int]]:
if not mat: return []
m = len(mat)
n = len(mat[0])
get = lambda i, j: mat[i][j] if 0 <= i < m and 0 <= j < n else 0
row = lambda i, j: sum([get(i, y) for y in range(j - K, j + K + 1)]... |
'''Starlark rule for packaging Python 3 Google Cloud Functions.'''
SRC_ZIP_EXTENSION = 'zip'
SRC_PY_EXTENSION = 'py'
MEMORY_VALUES = [
128, 256, 512, 1024, 2048, 4096,
]
MAX_TIMEOUT = 540
DEPLOY_SCRIPT_TEMPLATE = '''#!/usr/bin/env fish
set gcf_archive (status --current-filename | sed 's/\.fish$/\.zip/' | xargs real... |
#!/usr/bin/python3
#Every instance of this class, represents a single word found in a message.
class Word:
def __init__(self, word):
#The word itself.
self.word = word
#The number of times the word was found in a collection of ham messages.
self.inHam = 0
#The number of ... |
URL_LIST_ARTICLES = "../../../data/nytimes_news_articles.txt"
URL_BASE_ARTICLE = "../../../data/articles/nytimes"
URL_SPLIT_WORDS = "../../../data/split_words.json"
URL_SORT = "../../../data/sort.json"
URL_LIST_DICT = "../../../data/list_dict.json"
URL_LIST_DOCID = "../../../data/list_doc_id.json"
N_ARTICLE = 1000
|
# 914000220
if not "cmd=o" in sm.getQRValue(21002):
sm.showFieldEffect("aran/tutorialGuide3")
sm.systemMessage("You can use a Command Attack by pressing both the arrow key and the attack key after a Consecutive Attack.")
sm.addQRValue(21002, "cmd=o") |
class Curry:
def __init__(self, f, params=[], length=None):
self.f = f
self.len = f.__code__.co_argcount if length is None else length
self.params = params
def __call__(self, *a):
p = [*self.params, *a]
return self.f(*p) if len(p) >= self.len else Curry(self.f, p, self.... |
# -*- coding: utf-8 -*-
# This file is generated from NI-DCPower API metadata version 19.6.0d2
functions = {
'Abort': {
'documentation': {
'description': '\nTransitions the NI-DCPower session from the Running state to the\nCommitted state. If a sequence is running, it is stopped. Any\nconfigurat... |
'''
#basic data types
a = int(input())
b = float(input())
c = "I'm a boy"
print(c)
#casting------converting one datatype to another type
a = 1.22222
print(int(a))
#flowchartXXXX----conditionals----if/else
x = 'Ronaldo is better than Messi'
try:
print('Ronaldo' in s)
except:
print('sorry--not execute')
''... |
# 此处可 import 模块
"""
@param string line 为单行测试数据
@return string 处理后的结果
"""
def solution(line):
# 缩进请使用 4 个空格,遵循 PEP8 规范
# please write your code here
# return 'your_answer'
while 'mi' in line:
line = line.replace('mi', '')
return line
aa = solution('fwfddqhmpcmmmiiiijfrmiimmmmmirwbte')
... |
#Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..len(str)-1 inclusive).
#missing_char('kitten', 1) → 'ktten'
#missing_char('kitten', 0) → 'itten'
#missing_char('k... |
#!/usr/bin/env python
# _*_coding:utf-8 _*_
#@Time :2019/4/24 0024 下午 10:06
#@Author :喜欢二福的沧月君(necydcy@gmail.com)
#@FileName: Climbing_ladder.py
#@Software: PyCharm
"""
(八)、爬楼梯
【题目描述】
假设一段楼梯共n(n>1)个台阶,小朋友一步最多能上3个台阶,那么小朋友上这段楼梯一共有多少种方法。
"""
def climb(num):
if num==1:
return 1
if num... |
class SubsystemA(object):
def operation_a1(self):
print("Operation a1")
def operation_a2(self):
print("Operation a2")
class SubsystemB(object):
def operation_b1(self):
print("Operation b1")
def operation_b2(self):
print("Operation b2")
class SubsystemC(object):
de... |
# Copyright 2004-2009 Joe Wreschnig, Michael Urman, Steven Robertson
# 2011,2013 Nick Boultbee
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation
def decode(s, charset="utf-8... |
class Cashier:
def __init__(self, n, discount, products, prices):
self.n = n
self.now = n
self.dc = discount
self.pds = products
self.pcs = prices
def getBill(self, product, amount):
money = 0
for i in range(len(product)):
money += self.pcs[s... |
s = b'abcdefgabc'
print(s)
print('c:', s.rindex(b'c'))
print('c:', s.index(b'c'))
#print('z:', s.rindex(b'z'))#ValueError: subsection not found
s = bytearray(b'abcdefgabc')
print(s)
print('c:', s.rindex(bytearray(b'c')))
print('c:', s.index(bytearray(b'c')))
#print('z:', s.rindex(bytearray(b'z')))#ValueError: subsecti... |
def bubblesort(vals):
changed = True
while changed:
changed = False
for i in range(len(vals) - 1):
if vals[i] > vals[i + 1]:
changed = True
vals[i], vals[i + 1] = vals[i + 1], vals[i]
# Yield gives the "state"
yield vals... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This script contains functions that don't belong to a specific category.
# The buffer_size function computes a buffer around the input ee.Element
# whilst the get_metrics function returns the accuracy metrics of the input
# classifier and test set.
#
# Author: Davide Lom... |
r = '\033[31m' # red
b = '\033[34m' # blue
g = '\033[32m' # green
y = '\033[33m' # yellow
f = '\33[m'
bb = '\033[44m' # backgournd blue
def tela(mensagem, colunatxt=5):
espaco = bb + ' ' + f
mensagem = bb + y + mensagem
for i in range(12):
print('')
if i == 5:
... |
"""This package contains components for working with switches."""
__all__ = (
"momentary_switch",
"momentary_switch_component",
"switch",
"switch_state",
"switch_state_change_event",
"toggle_switch",
"toggle_switch_component"
)
|
tst = int(input())
ids = [ int(w) for w in input().split(',') if w != 'x' ]
def wait_time(bus_id):
return (bus_id - tst % bus_id, bus_id)
min_id = min(map(wait_time, ids))
print(f"{min_id=}")
|
# Aiden Baker
# 2/12/2021
# DoNow103
print(2*3*5)
print("abc")
print("abc"+"bde") |
name = "ServerName"
user = "mongo"
japd = None
host = "hostname"
port = 27017
auth = False
auth_db = "admin"
use_arg = True
use_uri = False
repset = "ReplicaSet"
repset_hosts = ["host1:27017", "host2:27017"]
|
def solution(xs):
"""Returns integer representing maximum power output of solar panel array
Args:
xs: List of integers representing power output of
each of the solar panels in a given array
"""
negatives = []
smallest_negative = None
positives = []
contains_panel_with_zero_p... |
class GlobalConfig:
def __init__(self):
self.logger_name = "ecom"
self.log_level = "INFO"
self.vocab_filename = "products.vocab"
self.labels_filename = "labels.vocab"
self.model_filename = "classifier.mdl"
gconf = GlobalConfig()
|
def fact(n):
if n > 0:
return (n*fact(n - 1))
else:
return 1
print(fact(5))
|
"""
Maria acabou de iniciar seu curso de graduação na faculdade de medicina e precisa de sua ajuda para organizar os experimentos de um laboratório o qual ela é responsável. Ela quer saber no final do ano, quantas cobaias foram utilizadas no laboratório e o percentual de cada tipo de cobaia utilizada.
Este laboratório... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 3 14:39:32 2020
@author: zo
"""
def tokenizer_and_model_config_mismatch(config, tokenizer):
"""
Check for tokenizer and model config miss match.
Args:
config:
model config.
tokenizer:
tokenizer... |
def est_positif(n: int) -> bool:
"""
Description:
Vérifie si un nombre est positif.
Paramètres:
n: {int} -- Nombre à vérifier
Retourne:
{bool} -- True si positif, false sinon
Exemple:
>>> est_positif(1)
True
>>> est_positif(-1)
Fals... |
#!/usr/bin/env python3
class Service:
def __init__(self, kube_connector, resource):
self.__resource = resource
self.__kube_connector = kube_connector
self.__extract_meta()
def __extract_meta(self):
self.namespace = self.__resource.metadata.namespace
self.name = self._... |
BOT_NAME = 'AmazonHeadSetScraping'
SPIDER_MODULES = ['AmazonHeadSetScraping.spiders']
NEWSPIDER_MODULE = 'AmazonHeadSetScraping.spiders'
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0'
DOWNLOAD_DELAY = 3
DOWNLOAD_TIMEOUT = 30
RANDOMIZE_DOWNLOAD_DELAY = True
REACTOR_THRE... |
#!/usr/bin/python
DIR = "data_tmp/"
FILES = {}
FILES['20_avg'] = []
FILES['40_avg'] = []
FILES['50_avg'] = []
FILES['60_avg'] = []
FILES['80_avg'] = []
FILES['20_opt'] = []
FILES['40_opt'] = []
FILES['50_opt'] = []
FILES['60_opt'] = []
FILES['80_opt'] = []
FILES['20_avg'].append("04_attk2_avg20_20_test")
FILES['20_a... |
class Int32CollectionConverter(TypeConverter):
"""
Converts an System.Windows.Media.Int32Collection to and from other data types.
Int32CollectionConverter()
"""
def CanConvertFrom(self,*__args):
"""
CanConvertFrom(self: Int32CollectionConverter,context: ITypeDescriptorContext,sourceType: Type) -> b... |
def list_of_lists(l, n):
q = len(l) // n
r = len(l) % n
if r == 0:
return [l[i * n:(i + 1) * n] for i in range(q)]
else:
return [l[i * n:(i + 1) * n] if i <= q else l[i * n:i * n + r] for i in range(q + 1)]
|
"""Type stubs for gi.repository.GLib."""
class Error(Exception):
"""Horrific GLib Error God Object."""
@property
def message(self) -> str: ...
class MainLoop:
def run(self) -> None: ...
def quit(self) -> None: ... |
class PrefixList:
""" The PrefixList holds the data received from routing registries and
the validation results of this data. """
def __init__(self, name):
self.name = name
self.members = {}
def __iter__(self):
for asn in self.members:
yield self.members[asn]
... |
def find_common_number(*args):
result = args[0]
for arr in args:
result = insect_array(result, arr)
return result
def union_array(arr1, arr2):
return list(set.union(arr1, arr2))
def insect_array(arr1, arr2):
return list(set(arr1) & set(arr2))
arr1 = [1,5,10,20,40,80]
arr2 = [6,27,20,80,100]
arr3 = [... |
# Question 2
# Convert all units of time into seconds.
day = float(input("Enter number of days: "))
hour = float(input("Enter number of hours: "))
minute = float(input("Enter number of minutes: "))
second = float(input("Enter number of seconds: "))
day = day * 3600 * 24
hour *= 3600
minute *= 60
second = day + hour + ... |
""" An administrator is a special kind of user. Write a class called
Admin that inherits from the User class you wrote in Exercise 9-3 (page 166)
or Exercise 9-5 (page 171). Add an attribute, privileges, that stores a list
of strings like "can add post", "can delete post", "can ban user", and so on.
Write a method call... |
text = """
ar-EG* Female "Microsoft Server Speech Text to Speech Voice (ar-EG, Hoda)"
ar-SA Male "Microsoft Server Speech Text to Speech Voice (ar-SA, Naayf)"
ca-ES Female "Microsoft Server Speech Text to Speech Voice (ca-ES, HerenaRUS)"
cs-CZ Male "Microsoft Server Speech Text to Speech Voice (cs-CZ, Vit)"
da-... |
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
"""
0 1 2. 3
[[1,2],[3],[3],[]]
^
paths = [[0, 1, 3], [0,2,3]]
path =
"""
end = len(graph)-1
@lru_cache(maxsize=... |
class QueueMember:
def __init__(self, number):
self.number = number
self.next = self
self.prev = self
def set_next(self, next):
self.next = next
def get_next(self):
return self.next
def set_prev(self, prev):
self.prev = prev
def get_prev(self):
... |
class AgedPeer:
def __init__(self, address, age=0):
self.address = address
self.age = age
def __eq__(self, other):
if isinstance(other, AgedPeer):
return self.address == other.address
return False
@staticmethod
def from_json(json_object):
return AgedPeer(json_object['address'], json_object['age']) |
# (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
EVENT_SOURCE = 'DatadogTest'
EVENT_ID = 9000
EVENT_CATEGORY = 42
INSTANCE = {
'legacy_mode': False,
'timeout': 2,
'path': 'Application',
'filters': {'source': [EVENT_SOURCE]},
}
|
"""
Entradas
Sueldo_bruto-->float-->sa
Salidas
Categoria-->int-->c
Sueldo_neto-->float-->sn
"""
sa=float(input("Digite el salario bruto: "))
sn=0.0#float
if(sa>=5_000_000):
sn=(sa*0.10)+sa
c=1
elif(sa<5_000_000 and sa>=4_300_000):
sn=(sa*0.15)+sa
c=2
elif(sa<4_300_000 and sa>=3_600_000):
sn=(sa*0.20)+sa
c=3... |
# 3/15
num_of_pages = int(input()) # < 10000
visited = set()
shortest_path = 0
instructions = [list(map(int, input().split()))[1:] for _ in range(num_of_pages)]
def choose_paths(page, history):
if page not in visited:
visited.add(page)
if not len(instructions[page - 1]): # if this page doesn't n... |
conn_info = {'host': 'vertica.server.ip.address',
'port': 5433,
'user': 'readonlyuser',
'password': 'XXXXXX',
'database': '',
# 10 minutes timeout on queries
'read_timeout': 600,
# default throw error on invalid UTF-8 results
... |
class DoubleLinklist:
class _node:
__slots__ = ['val', 'next', 'prev']
def __init__(self, val: int, next, prev):
self.val = val
self.next = next
self.prev = prev
def __init__(self):
self.head = None
self.size = 0
def insert(self, x: int... |
# Created by MechAviv
# Quest ID :: 25562
# Fostering the Dark
sm.setSpeakerID(0)
sm.flipDialoguePlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendNext("Dark magic is so much easier than light...")
sm.setSpeakerID(0)
sm.flipDialoguePlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendSay("But I do not fully understand it. With... |
num = cont = soma = 0
num = int(input('Digite um número: '))
while num != 999:
soma += num
cont += 1
num = int(input('Digite um número: '))
print('O total de números digitados foi {} que somados é igual a {}.'.format(cont, soma))
|
# (n, k) represent nCk
# (N+M-1, N-1)-(N+M-1, N) = (N-M)/(N+M) * (N+M, N)
def solution():
T = int(input())
for i in range(T):
N, M = map(float, input().split(' '))
print('Case #%d: %f' % (i+1, (N-M)/(N+M)))
solution()
|
class HttpException(Exception):
"""
A base exception designed to support all API error handling.
All exceptions should inherit from this or a subclass of it (depending on the usage),
this will allow all apps and libraries to maintain a common exception chain
"""
def __init__(self, message, debug... |
# Find len of ll. k = k%l. Then mode l-k-1 steps and break the ll. Add the remaining part of the LL in the front.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: ListN... |
MY_MAC = ""
MY_IP = ""
IFACE = ""
GATEWAY_MAC = ""
_SRC_DST = {}
PROTO = ""
CMD = ""
STOP_SNIFF = False |
"""Top-level package for Image to LaTeX."""
__author__ = """Oscar Arbelaez"""
__email__ = 'odarbelaeze@gmail.com'
__version__ = '0.2.1'
|
# Convert the temperature from Fahrenheit to Celsius in the
# function below. You can use this formula:
# C = (F - 32) * 5/9
# Round the returned result to 3 decimal places.
# You don't have to handle input, just implement the function
# below.
# Also, make sure your function returns the value. Please do NOT
# pr... |
task = '''
Реализовать базовый класс Worker (работник), в котором определить атрибуты:
name, surname, position (должность), income (доход). Последний атрибут должен
быть защищенным и ссылаться на словарь, содержащий элементы: оклад и премия,
например, {"wage": wage, "bonus": bonus}. Создать класс Position (должность)
н... |
"""
Sponge Knowledge Base
Action metadata Record type - sub-arguments
"""
def createBookRecordType(name):
return RecordType(name, [
IntegerType("id").withNullable().withLabel("Identifier").withFeature("visible", False),
StringType("author").withLabel("Author"),
StringType("title").withLabel... |
def zero(f=lambda a: a):
return f(0)
def one(f=lambda a: a):
return f(1)
def two(f=lambda a: a):
return f(2)
def three(f=lambda a: a):
return f(3)
def four(f=lambda a: a):
return f(4)
def five(f=lambda a: a):
return f(5)
def six(f=lambda a: a):
return f(6)
def seven(f=lambda a: a):
return f(7)
def eight(f=lambd... |
"""
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
"""
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
list_a = [int(i) for i in a[::-1]]
list_b ... |
# coding=utf-8
"""Hive: microservice powering social networks on the dPay blockchain.
Hive is a "consensus interpretation" layer for the dPay blockchain,
maintaining the state of social features such as post feeds, follows,
and communities. Written in Python, it synchronizes an SQL database
with chain state, providin... |
print("Nombre del alumno; Sharlene Miorzlava Cervantes Vazquez")
print("lugar de residencia: El refugio de Agua zarca")
print("Fecha de Nacimiento: 24 de enero del año 2002")
print("Color favorito: Verde")
print("Animal Favorito: Panda")
print("¿Que es un Programa? Es una serie de instruccionespreviamente codificadas, ... |
def ChangeText(s):
print('ChangeText() received:', s)
decoded = s.decode("utf-16-le")
print('Decoded:', decoded)
returned = None
if decoded == 'hello':
returned = 'world'
if returned is None:
return None
else:
b = returned.encode("utf-16-le")... |
print("""interface GigabitEthernet0/3.100\nvlan 100\nnameif wireless_user-v100\nsecurity-level 75\nip addr 10.1.100.1 255.255.255.0
interface GigabitEthernet0/3.101\nvlan 101\nnameif wireless_user-v101\nsecurity-level 75\nip addr 10.1.101.1 255.255.255.0
interface GigabitEthernet0/3.102\nvlan 102\nnameif wireless_use... |
#! /usr/bin/env python3
# coding:utf-8
def main():
#answer = [(a, b, c) for a in range(21) for b in range(34) for c in range(101-a-b)
# if a*5 + b*3 +c/3 == 100 and a+b+c == 100]
#print(answer)
for a in range(21):
for b in range(34):
c = 100-a-b
if a*5 + b*3 +c... |
name = "qt"
version = "4.8.7"
description = \
"""
Qt
"""
build_requires = [
"python-2.7"
]
def commands():
# export CMAKE_MODULE_PATH=$CMAKE_MODULE_PATH:!ROOT!/cmake
# export QTDIR=!ROOT!
# export QT_INCLUDE_DIR=!ROOT!/include
# export QT_LIB_DIR=!ROOT!/lib
# export LD_LIBRARY_PA... |
def getCommonLetters(word1, word2):
return ''.join(sorted(set(word1).intersection(set(word2))))
print(getCommonLetters('apple', 'strw'))
print(getCommonLetters('sing', 'song'))
|
class ParseFailure(Exception):
def __init__(self, message, offset=None, column=None, row=None, text=None):
self.message = message
self.offset = offset
self.column = column
self.row = row
self.text = text
super(ParseFailure, self).__init__(
self.message,
... |
#
# @lc app=leetcode id=71 lang=python3
#
# [71] Simplify Path
#
# @lc code=start
class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
for token in path.split('/'):
if token in ('', '.'):
pass
elif token == '..':
if stack:
... |
"""
Dada 2 listas numéricas ("a" e "b") de tamanho 3, retorne uma nova contendo os
seus elementos do meio.
"""
def middle_way(a, b):
return a[int(len(a)/2):int(len(a)/2)+1] + b[int(len(b)/2):int(len(b)/2)+1]
print(middle_way([1, 2, 3], [4, 5, 6]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.