content stringlengths 7 1.05M |
|---|
km = float(input('Quantos km tem sua viagem? '))
if km <=200:
print('O valor da sua viagem é R${:.2f}'.format(km*0.50))
else:
print('o valor da sua viagem é R${:.2f}'.format(km*0.45))
|
class Building(object):
lock = MetalKey()
def unlock(self):
self.lock.attempt_unlock()
class KeyCardMixin(object):
lock = KeyCard()
class ExcellaHQ(KeyCardMixin, Building):
pass
|
def fibonacci(n):
if n == 0:
return 0
elif n==1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
def test():
for i in range(15):
print("fib[" + str(i) + "]: " + str(fibonacci(i)))
test()
|
instruct = [] # keeps the splitted version of the instructions
filename = input("Enter the filename: ") # gets the filename as the input
print("Reading...")
with open(filename) as f: # goes through the file line by line, and splits each line from the spaces, and adds them into instruct list
for line in f:
... |
"""A collection of definitions for generated benchmark scenarios.
Each generated scenario is defined by the a number of parameters that
control the size of the problem (see scenario.generator for more info):
There are also some parameters, where default values are used for all
scenarios, see DEFAULTS dict.
"""
# gen... |
# Faça um programa que leia a largura e a altura de uma parede em metros,
# calcule a sua área e a quantidade de tinta necessária para pintá-la,
# sabendo que cada litro de tinta pinta uma área de 2 metros quadrados.
width = float(input('Largura da parede: '))
height = float(input('Altura da parede: '))
area = width *... |
#
# PySNMP MIB module RBN-ALARM-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBN-ALARM-EXT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:43:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
"""``utils`` module of ``dataql``.
Provide some simple utilities.
"""
def class_repr(value):
"""Returns a representation of the value class.
Arguments
---------
value
A class or a class instance
Returns
-------
str
The "module.name" representation of the value class.
... |
#! /usr/bin/env python
class StateUpdate:
def __init__(
self,
position_update=None,
phase_update=None,
phase_level_update=None,
small_phase_update=None,
phase_correction_update=None,
velocity_update=None,
orientation_update=None,
angular_spee... |
#!/usr/bin/env python3
def ntchange( variant_frame ):
GC2CG = []
GC2TA = []
GC2AT = []
TA2AT = []
TA2GC = []
TA2CG = []
for ref, alt in zip(variant_frame['REF'], variant_frame['ALT']):
ref = ref.upper()
alt = alt.upper()
if (ref == 'G' an... |
roster = (('ipns adrres one', 'Name one'),
('ipns adrres two', 'Name two'),
('etc', 'etc'))
|
class Config(object):
pass
class ProdConfig(Config):
DEBUG = False
SQLALCHEMY_DATABASE_URI = (
"postgresql+psycopg2://test:password@postgres:5432/mex_polit_db"
)
SQLALCHEMY_TRACK_MODIFICATIONS = False
class DevConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = (
"post... |
def test_construction(sm_config):
assert True is sm_config.debug
viewservice_config = sm_config.serviceconfigs['viewservice']
assert 99 == viewservice_config.flag
|
# Module is an abstraction of a candle, which is the data structure returned when requesting price history
# data from the API. It also contains methods for analysis.
class Candle(object):
def __init__(self, json):
self.openPrice = json['open']
self.closePrice = json['close']
self.lowPrice = json['low']
se... |
# deliberatly not in file_dep, so a change to sizes doesn't force rerenders
def get_map_size(obj_name):
map_size = 512
# maybe let a custom attr raise this sometimes, or determine it from obj size?
if obj_name.startswith('gnd.'):
if obj_name != 'gnd.023':
return None, None
map_... |
def find2020(list):
for i in range(0, len(list)):
for j in range(i+1, len(list)):
for k in range(j+1, len(list)):
if list[i] + list[j] + list[k] == 2020:
print(list[i] * list[j] * list[k])
if __name__ == '__main__':
with open("test2.txt") as file:
... |
class MyHashMap:
def eval_hash(self, key):
return ((key*1031237) & (1<<20) - 1)>>5
def __init__(self):
self.arr = [[] for _ in range(1<<15)]
def put(self, key, value):
t = self.eval_hash(key)
for i,(k,v) in enumerate(self.arr[t]):
if k == key:
... |
numWords = 2
mostCommonWords = ["the","of","to","and","a","in","is","it","you","that"]
def addWord(d,group,word):
if d.get(group) == None:
d[group] = {word : 1}
else:
if d[group].get(word) == None:
d[group][word] = 1
else:
d[group][word] = d[group][word] + 1
def... |
# -*- encoding: utf-8 -*-
class Scene:
"""
Represents an abstract scene of the game.
A scene is a visible part of the game, like a loading screen
or an option menu. For creating a working scene the object
should be derived from this class.
"""
def __init__(self, director):
self.di... |
# Imprime uma linha contendo n + 2 caracteres #
def print_linha(n):
for i in range(n + 2):
print("#", end="")
print()
# Recebe uma string e imprime no formato
# #################
# valor da string
# #################
def print_cabecalho(s):
n = len(s)
print_linha(n)
print(" " + s)
prin... |
"""
MembershipTookit.com Downloader v1.0.0
======================================
Software (C) Copyright 2019 Gideon Tong
All rights reserved.
This piece of software is available to use as "free as in beer", but is
not for redistribution, resell, remixing, reusing, or any other type
of use other than for personal use... |
# Copyright (c) 2022 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
load(
"@daml//bazel_tools/client_server:client_server_test.bzl",
"client_server_test",
)
load("//bazel_tools:versions.bzl", "version_to_name", "versions")
def daml_script_dar... |
# An integer has sequential digits
# if and only if each digit in the number is one more than the previous digit.
# Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.
# Example 1:
# Input: low = 100, high = 300
# Output: [123,234]
# Example 2:
# Input: low = 1000... |
# encoding: utf-8
rivers = {
'nile': 'egypt',
'mississippi': 'united states',
'fraser': 'canada',
'kuskokwim': 'alaska',
'yangtze': 'china',
}
for river, country in rivers.items():
print("The " + river.title() + " flows through " + country.title() + ".")
# 打印该字典中每条河流的名字
print("\nThe follo... |
#!/usr/bin/python3
with open('05_input', 'r') as f:
lines = f.readlines()
lines = [r.strip() for r in lines]
def get_seat_id(code):
row_str = code[0:7]
col_str = code[7:10]
row_num = row_str.replace('F','0').replace('B','1')
col_num = col_str.replace('L','0').replace('R','1')
row = int(row_nu... |
# pseudo code taken from CLRS book
def lcs(X, Y):
c = {} # c[(i,j)] represents length of lcs of [x0, x1, ... , xi] and [y0, y1, ... , yj]
m = len(X)
n = len(Y)
for i in range(m):
c[(i, -1)] = 0
for j in range(n):
c[(-1, j)] = 0
for i in range(m):
for j in range(n):
... |
class TreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def insert(root, node):
if root is None:
root = node
else:
if root.data >= node.data:
if root.left == None:
root.left = node
else:
... |
## <hr>Dummy value.
#
# No texture, but the value to be used as 'texture semantic'
# (#aiMaterialProperty::mSemantic) for all material properties
# *not* related to textures.
#
aiTextureType_NONE = 0x0
## <hr>The texture is combined with the result of the diffuse
# lighting equation.
#
aiTextureType_DIFFUSE = 0x1
## ... |
# -*- coding: cp852 -*-
#en_EN Locale
class language():
VERSION='Version'
CREATING_BACKUP='Creating backup'
NO_PERM='No Permission'
COPYING_FILES='Copying files'
COULD_NOT_COPY='Could not copy files'
DONE='Done'
REWRITING_FLUXION_BASH='Rewriting fluxion bash'
RECONFIGURE_FLUXION_BASH='R... |
def sycl_library_path(name):
return "lib/lib{}.so".format(name)
def readlink_command():
return "readlink"
|
class Sources:
def __init__(self,id,name,description,language):
self.id = id
self.name = name
self.description = description
self.language = language
class Articles:
def __init__(self,author,title,description,url,publishedAt,urlToImage):
self.author = author
self... |
num_list = list(map(int, input().split()))
high=max(num_list)
low=min(num_list)
print(low,sum(num_list),high) |
def clock_degree(clock_time):
hour, minutes = (int(a) for a in clock_time.split(':'))
if not (24 > hour >= 0 and 60 > minutes >= 0):
return 'Check your time !'
return '{}:{}'.format((hour % 12) * 30 or 360, minutes * 6 or 360) |
# def quick_sort(the_list):
# # left index
# l = 0
# # pivot index
# p = len(the_list)
# # right index
# r = pivot - 1
# if l < r:
# # increment l till we have an appropriate value
# while the_list[l] <= the_list[p] && l < len(the_list):
# l += 1
# # d... |
class ProductionConfig():
DEBUG = False
MONGODB_HOST = 'localhost'
MONGODB_DBNAME = 'their_tweets'
MONGODB_SETTINGS = {
'host' : 'localhost',
'DB' : 'new',
'port' : 27017
}
SECRET_KEY = 'thisissecret'
MULTIPLE_AUTH_HEADERS = ['access_token', 'device']
PORT = 8... |
__author__ = ""
__version__ = "0.0.1"
__date__ = ""
__all__ = ["__author__", "__version__", "__date__"]
|
class C:
def __init__(self, x, y):
"""
Args:
x:
y:
"""
return None |
def analog_state(analog_input):
if analog_input.read():
return 'UP'
else:
return 'DOWN'
|
#
# -*- coding: utf-8 -*-
#
# Copyright 2015-2020 NETCAT (www.netcat.pl)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
def getRoot(config):
if not config.parent:
return config
return getRoot(config.parent)
root = getRoot(config)
if 'libdispatch' in root.available_features:
additional_cflags = ' -fblocks '
for index, (template, replacement) in enumerate(config.substitutions):
if template in ['%clang_tsan ', '%clangxx_t... |
user_modelling_units = {
'item_lookup_field': 'userModellingUnitId',
'item_url': 'regex("[\S]+")',
'item_title': 'league_table',
'resource_methods': ['GET', 'POST', 'DELETE'],
'item_methods': ['GET', 'PATCH', 'DELETE'],
'extra_response_fields': ['userModellingUnitId'],
'doc': {
... |
"""
0251. Flatten 2D Vector
Medium
Design and implement an iterator to flatten a 2d vector. It should support the following operations: next and hasNext.
Example:
Vector2D iterator = new Vector2D([[1,2],[3],[4]]);
iterator.next(); // return 1
iterator.next(); // return 2
iterator.next(); // return 3
iterator.has... |
"""
This file includes the Quip class. Quips are responses given by NPCs, when responding to a
DialogEvent.
Classes:
Quip
"""
class Quip:
"""
Attributes:
key: str
This is the name of the object when referenced internally by the game.
text: str
The text printed w... |
colleges = [
'National Institute of Technology, Kurukshetra' ,
'National Institute of Technology Raipur' ,
'National Institute of Technology, Rourkela' ,
'National Institute of Technology Calicut' ,
'Indian Institute of Engineering Science and Technology, Shibpur' ,
'National Institute of Technology Delhi' ,
'National... |
class Currency:
"""
Simple currency domain model, holds value as string
"""
s: str
def __init__(self, currency: str):
if currency == "":
raise TypeError("currency cannot be empty")
self.s = currency
def __str__(self):
return self.String()
def __eq__(se... |
"""
There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.
A province is a group of directly or indirectly connected cities and no other cities outside of the group.
... |
feature_funcs = set()
def feature(func):
""" Feature functions take a request as their single argument. """
feature_funcs.add(func)
return func
@feature
def requirejs(request):
return 'requirejs' in request.GET
@feature
def thread_new(request):
return True
@feature
def lazy_content(request):
... |
UNBOXED_PRIMITIVE_DEFAULT_EMPTY = "__prim_empty_slot"
UNBOXED_PRIMITIVE_DEFAULT_ZERO = "__prim_zero_slot"
IO_CLASS = "IO"
OBJECT_CLASS = "Object"
INTEGER_CLASS = "Int"
BOOLEAN_CLASS = "Bool"
STRING_CLASS = "String"
BUILT_IN_CLASSES = [
IO_CLASS,
OBJECT_CLASS,
INTEGER_CLASS,
BOOLEAN_CLASS,
STRING_CLAS... |
## gera novo arquivo sped a partir do banco de dados
def exec(filename,cursor):
arquivo = open("out/" + filename + '_r.txt', 'w')
for row in cursor.execute('SELECT * FROM principal order by r0'):
line = [i for i in row if i is not None]
line = '|' + '|'.join(line[1:]) + '|' + '\n'
arqu... |
def array123(nums):
# Note: iterate with length-2, so can use i+1 and i+2 in the loop
for i in range(len(nums)-2):
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
return True
return False
|
class Solution:
def findSwapValues(self,a, n, b, m):
summA = sum(a)
summB = sum(b)
diff = (summA - summB)
if diff % 2 != 0 :
return -1
diff = diff / 2
# We need to find num1 in a and num2 in b such that
# summA - num1 + num2 = summB - num2 + num1
... |
# Copyright (C) 2019 Project AGI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
_base_ = ['../../_base_/default_runtime.py']
# dataset settings
dataset_type = 'MOTChallengeDataset'
img_norm_cfg = dict(
mean=[0, 0, 0], std=[255, 255, 255], to_rgb=True)
train_pipeline = [
dict(type='LoadMultiImagesFromFile', to_float32=True),
dict(type='SeqLoadAnnotations', with_bbox=True, with_track=T... |
def calculate_best_trade(prices):
# Check if there are less than two prices in the list
# If so, the function cannot calculate max profit
# Else, there are at least two prices in the list and so run the function
if len(prices) < 2:
print("List of prices does not have at least two elements! Cann... |
#
# PySNMP MIB module Unisphere-Data-SONET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-SONET-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:25:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
"""
Tools to create and update EMA models.
"""
def create_ema_model(model):
""" Given a newly made network, detach all its parameters so its
parameters can serve as the EMA of another model. """
for param in model.parameters():
param.detach_()
return model
def update_ema_model(model, ema_mo... |
'''
It is often convenient to build a large DataFrame by parsing many files as DataFrames and concatenating them all at once. You'll do this here with three files, but, in principle, this approach can be used to combine data from dozens or hundreds of files.
Here, you'll work with DataFrames compiled from The Guardian... |
'''
Many-to-many data merge
The final merging scenario occurs when both DataFrames do not have unique keys for a merge. What happens here is that for each duplicated key, every pairwise combination will be created.
Two example DataFrames that share common key values have been pre-loaded: df1 and df2. Another DataFram... |
boxWidth = 50 # Width of square boxes inside grid
margin = 15 # Margin around grid
border = 2 # grid thickness
steps = 11 # no. of loki movement b/w two maze boxes in animation
# COLORS
grey = (67,67,67)
black = (0,0,0)
white = (255,255,255)
yellow = (50,226,249)
red = (1,23,182)
green = (0,114,1)
|
#!/usr/bin/env python
# encoding: utf-8
version_info = (0, 2, 1)
version = ".".join(map(str, version_info))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Administrator'
class Screen(object):
@property
def width(self):
return self._width
@width.setter
def width(self, value):
if not isinstance(value, int):
raise ValueError('width must be an integer!')
self.... |
liste = list()
liste2 = [1,2,3,4]
|
#
# Connection Transport
#
# Exception classes used by this module.
class ExceptionPxTransport(ExceptionPexpect):
'''Raised for pxtransport exceptions.
'''
class pxtransport(object):
'''The carrier of the info.'''
def __init__(self, hostname=None, info=None):
if hostname is None and info is N... |
while True:
nx, ny, w = input().split()
nx = int(nx)
ny = int(ny)
w = float(w)
if nx == ny and ny == w and w == 0:
break
xs = sorted(map(float, input().split()))
ys = sorted(map(float, input().split()))
xbroke = xs[0] - w / 2 > 0 or xs[-1] + w / 2 < 75
ybroke = ys[0] - w / ... |
class AttachableVolume:
"""
Base Mixin for requesting extra disk resources to k8s.
Sub classes should implement volume_spec specifiying a kubernetes PVC.
- size can be set by overriding volume_size_in_gb
- mount point can be set by overriding mount_location
"""
@property
def pvc_name(se... |
# -*- coding: utf-8 -*-
# For simplicity, these values are shared among both threads and comments.
MAX_THREADS = 1000
MAX_NAME = 50
MAX_DESCRIPTION = 3000
MAX_ADMINS = 2
# status
DEAD = 0
ALIVE = 1
STATUS = {
DEAD: 'dead',
ALIVE: 'alive',
}
BASE_SUBREDDITS = {'biology': ['biochemistry',
... |
# directory list
DATA_DIR = "./plugins/data/"
# cv window
MAIN_WINDOW_NAME = 'main'
MASK_WINDOW_NAME = 'mask'
KEY_WAIT_DURATION = 1
|
# Copyright 2014 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
def split_tag(tag):
if tag == 'O':
state = 'O'
label = None
elif tag == '-X-':
state = 'O'
label = None
else:
state, label = tag.split('-')
return state, label
def iob2bio(tags):
processed_tags = [] # should be bio format
prev_state = None
prev... |
# # Altere o programa anterior para mostrar no final a soma dos números.
# n1 = int(input("Digite um número inteiro: "))
# n2 = int(input("Digite um número inteiro: "))
# while n1 > n2:
# n1 = int(input("Digite um número inteiro (O primeiro número deve ser o maior): "))
# n2 = int(input("Digite um número inte... |
class OnTheFarmDivTwo:
def animals(self, heads, legs):
if legs < 2 * heads or legs > 4 * heads or legs % 2:
return tuple()
x = (legs - 2 * heads) / 2
return heads - x, x
|
"""
Welcome to the new format of the course! From now on, I'll be writing within
these Python files instead of in seperate .md files. This will let me write
code in this files and comment on them directly, because this is a .py file
that you can actually run!
To start, we're going to talk about how a computer st... |
#
# Copyright (c) 2010-2016, Fabric Software Inc. All rights reserved.
#
Direct = 0
Reference = 1
Pointer = 2
|
class GtExampleDependency:
def __init__(self,gt_example):
self.gt_example = gt_example
self.parent_dependencies = []
self.child_dependencies = []
def add_parent(self, parent_dependency):
self.parents().append(parent_dependency)
def add_child(self, child_dependency):
... |
n=int(input())
t=[[0]*n for i in range (n)]
i,j=0,0
for k in range(1, n*n+1):
t[i][j]=k
if k==n*n: break
if i<=j+1 and i+j<n-1: j+=1
elif i<j and i+j>=n-1: i+=1
elif i>=j and i+j>n-1: j-=1
elif i>j+1 and i+j<=n-1: i-=1
for i in range(n):
print(*t[i]) |
#use of the while loop to determine the number of digits of an integer n:
n = int(input())
length = 0
while n > 0:
n = n//10
length = length + 1
print("number of digits in the given number n =" , length)
#On each iteration we cut the last digit of the number using
# integer division by 10 (n //= 10). In the... |
class ShapeConfig():
def __init__(
self,
shape=[74, 74, 125, 125],
verbose=False
):
self.shape = shape
self._number_of_substrip = len(self.shape)
self._number_of_pixels = 0
for pixel_number in self.shape:
self._number_of_pixels += pixel_numbe... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
minn = float("inf")
profit = 0
for price in prices:
if minn > price : minn = price
if price - minn > profit : profit = price - minn
return profit |
'''https://practice.geeksforgeeks.org/problems/smallest-distant-window3132/1
Smallest distinct window
Medium Accuracy: 50.29% Submissions: 16273 Points: 4
Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.
For eg. A = “aabcbcdbca”... |
coordinates_E0E1E1 = ((125, 117),
(125, 120), (126, 96), (126, 117), (126, 119), (126, 127), (127, 94), (127, 97), (127, 109), (127, 118), (127, 119), (127, 127), (128, 93), (128, 98), (128, 108), (128, 109), (128, 118), (128, 119), (129, 92), (129, 94), (129, 96), (129, 100), (129, 101), (129, 103), (129, 107), (129... |
class EMA:
def __init__(self):
self.EMA_12 = []
self.EMA_20 = []
self.EMA_26 = []
self.EMA_50 = []
self.EMA_80 = []
self.EMA_85 = []
self.EMA_90 = []
self.EMA_95 = []
self.EMA_100 = []
self.EMA_160 = []
@staticmethod
def EMA(da... |
"""
装饰器:拓展被装饰函数功能的一种函数,在不改变原函数的的基础上为函数添加新的功能,满足对拓展是开放的,对修改是封闭的原则。
"""
# 通用装饰器
def wrapper(func): # 装饰器函数
def inner(*args, **kwargs): # 接受被装饰函数传参
print('inner')
return func(*args, **kwargs) # 执行被装饰函数
return inner # 闭包,外部函数返回值是内部函数
@wrapper
def test(): # 被装饰函数
print("test")
test(... |
# 链表中倒数第K个节点
# 输入一个链表,输出该链表中倒数第k个结点。
# 链表结构
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 打印链表
def printChain(head):
node = head
while node:
print(node.val)
node = node.next
class Solution:
def FindKthToTail(self, head, k):
if k <= 0 or... |
def solution(x):
s = 0
for i in range(x):
if i%3 == 0 or i%5 == 0:
s += i
return s |
class Iris:
def __init__(self, features, label):
self.features = features
self.label = label
def sum(self):
return sum(self.features)
for *features, label in DATA:
iris = Iris(features, label)
result[iris.label] = iris.sum()
|
# -*- coding: utf-8 -*-
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive licens... |
class CameraInterface:
def get_image(self):
raise NotImplementedError()
def get_depth(self):
raise NotImplementedError() |
class Usuario():
'''classe de usuários'''
def __init__(self, primeiro_nome, ultimo_nome, idade, altura, nacionalidade):
'''Inicializa os atributos teste e teste1.'''
self.primeiro_nome = primeiro_nome
self.ultimo_nome = ultimo_nome
self.idade = idade
self.altura = altura... |
class HTTPCache(ValueError):
pass
__all__ = ("HTTPCache",)
|
class AuthError(Exception):
pass
class BadExtentError(Exception):
pass
class InvalidEndpoint(Exception):
pass
class InvalidDatestring(Exception):
pass
class RequiredArgumentError(Exception):
pass
class Request429Error(Exception):
pass
class RequestsPerSecondLimitExceeded(Request429E... |
class Warning(StandardError):
pass
class Error(StandardError):
pass
class InterfaceError(Error):
pass
class DatabaseError(Error):
pass
class DataError(DatabaseError):
pass
class OperationalError(DatabaseError):
pass
class IntegrityError(DatabaseError):
pass
class InternalError(DatabaseError... |
# This makes this folder a package and can be left empty if you like.
# the __all__ special variable indicates what modules to load then the * star
# is used for importing.
__all__ = ['aCoolModule']
|
class DoubleKeyContainer(object):
def __init__(self):
self.id_map = dict() # maps ID to phone and name
self.phone_map = dict() # maps phone to ID
def add_contact(self, id, name, phone):
if id in self.id_map:
del self.phone_map[self.id_map[id][1]]
self.id_map[id] =... |
main_colors = ['red', 'yellow', 'blue']
secondary_colors = {
'orange': ('red', 'yellow'),
'purple': ('red', 'blue'),
'green': ('yellow', 'blue')
}
base_strings = input().split()
made_colors_all = []
made_colors_final = []
while base_strings:
first_string = base_strings.pop(0)
second_string = base_s... |
def inc(c, d):
return chr(ord(c) + d)
def dec(c, d):
return chr(ord(c) - d)
arg1 = ["+"] * 29
arg1[0x13] = '6'
arg1[0x10] = 'n'
arg1[0xd] = 'r'
arg1[0x14] = dec('%', -8)
arg1[0xf] = 'n'
arg1[10] = 'p'
arg1[0x10] = dec('u', 7)
arg1[3] = '{'
arg1[0x13] = '6'
arg1[0x15] = 'q'
arg1[2] = 'n'
arg1[0] = 's'
arg1[7]... |
class SequentialProcessor(object):
def process(self, vertice, executor):
results = []
for vertex in vertice:
result = executor.execute(executor.param(vertex))
results.append((vertex, result))
return results
|
#!/bin/env python
"""A file which contains only what is strictly necessary for completion of the is_even function"""
# Y combinator, used for recursion
Y = lambda f: (lambda x: x(x))(lambda y: f(lambda a: y(y)(a)))
# Church arithmetic
succ = lambda n: lambda f: lambda x: f(n(f)(x))
pred = lambda n: lambda f: lambda x... |
# from math import factorial
# n = int(input('Digite um número para calcular se Fatorial: '))
# f = factorial(n)
# print(f'O fatorial de {n} e {f}')
n = int(input('Digite um número para calcular se Fatorial: '))
c = n
f = 1
print(f'Calculando {n}! = ', end='')
while c > 0:
print(f'{c}', end='')
print(' x ' if ... |
n = input().split()
K=int(n[0])
N=int(n[1])
M=int(n[2])
need= K*N
if need>M:
print(need-M)
else:
print('0')
|
def aoc(data):
jolts = 0
ones = 0
threes = 1
for psu in sorted([int(i) for i in data.split()]):
if psu == jolts + 1:
ones += 1
if psu == jolts + 3:
threes += 1
jolts = psu
return ones * threes
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.