content stringlengths 7 1.05M |
|---|
input = """
% Strategic Companies
%
% As we want to produce X, Y or Z must be strategic.
strategic(Y) v strategic(Z) :- produced_by(X,Y,Z).
% W is strategic, if it is controlled by strategic
% companies X, Y, and Z
strategic(W) :- controlled_by(W,X,Y,Z),
Strategic(X), Strategic(Y), Strategic(Z... |
# -*- coding: utf-8 -*-
NOTES = [100, 50, 20, 10, 5, 2]
COINS = [1, 0.50, 0.25, 0.10, 0.05, 0.01]
def main():
money = float(input())
print('NOTAS:')
for note in NOTES:
number_of_notes = money // note
print('%d nota(s) de R$ %.2f' % (number_of_notes, note))
money = money - (number_... |
def helloWorld(yourName):
print('Hello World'+ yourName)
helloWorld('Hackerobert')
|
class StorageNotFound(Exception):
pass
class StorageSettedError(Exception):
pass
class MismatchedVersionError(Exception):
pass
class InvalidPassword(Exception):
pass
|
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
t = int(input())
for _ in range(t):
n =... |
"""""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """''
======================================================================
Listas de Entidades BSMP
A posição da entidade na lista corresponde ao seu ID BSMP
=======================================================... |
def quickSort(array):
""" sort array by dividing and conquering
inplace"""
quickSortSplitter(array, 0, len(array)-1)
return array
def quickSortSplitter(array, start, end):
""" splits the array into subarrays"""
if start < end:
split_point = partition(array, start, end)
quickS... |
def kw_only_arg(*, kwo):
return kwo
def many_kw_only_args(*, first, second, third):
return first + second + third
def kw_only_arg_with_default(*, kwo='default', another='another'):
return '{}-{}'.format(kwo, another)
def mandatory_after_defaults(*, default1='xxx', mandatory, default2='zzz'):
retur... |
'''
n=2
m=3
print(n/m)
print(n/m + 1)
print('n/m + 1 =' , n/m + 1)
#print('n/m + 1 =' , n/m + 1, sep=' ' )
print('n/m + 1 =' ,'\n' , n/m + 1)
print('n/m + 1 =' , n/m + 1, sep='\n' )
print('n/m + 1 =' , n/m + 1, 125, sep='\n')
'''
#how to format my output
x = 2
y = 3
result = x/y
'''
print('result =', result)
# for... |
"""
String
1) Cover with
" " or ' ' or """ """ or ''' '''
2) Include ' or " with
"'" or '"' or \' or \"
3) Change line with
\n or ''' ''' or """ """
String Operation
1) Concatenate : str + str
2) Multiply : str * times
3) Get length : len(str)
4) Indexing : str[num]
... |
def add_prefix_un(word):
return "un" + word
def make_word_groups(vocab_words):
return(" :: " + vocab_words[0]).join(vocab_words)
def remove_suffix_ness(word):
base = word[:-4]
if base[-1] == 'i':
return base[:-1] + 'y'
return base
def noun_to_verb(sentenc... |
"""test misordered except
"""
__revision__ = 1
try:
__revision__ += 1
except Exception:
__revision__ = 0
except TypeError:
__revision__ = 0
try:
__revision__ += 1
except LookupError:
__revision__ = 0
except IndexError:
__revision__ = 0
try:
__revision__ += 1
except (LookupError, NameErro... |
def create_all(db):
db.Model.metadata.create_all(bind=db.engine)
def expose_psycopg2_connection(connection):
connection_proxy = connection.connection
psycopg2_connection = connection_proxy.connection
return psycopg2_connection
class create_connection:
def __init__(self, db, raw=False):
... |
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
num_active = len(iterables)
nexts = cycle(iter(it).__next__ for it in iterables)
while num_active:
try:
for next in nexts:
yield next()
except Sto... |
def palin_perm(str):
bitvec = [0] * 26
str = str.lower()
for char in str:
charCode = ord(char) - ord("a")
if charCode >= 0 and charCode < 26:
if bitvec[charCode] == 0:
bitvec[charCode] = 1
else:
bitvec[charCode] = 0
one = False
... |
################################################################################
# Define package composition
################################################################################
__all__ = ["root", "test", "message", "administration", "kb", "classifier", "note"]
# ZX: There's a better way to do this; see ... |
class RhinoDeselectAllObjectsEventArgs(EventArgs):
# no doc
Document=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Document(self: RhinoDeselectAllObjectsEventArgs) -> RhinoDoc
"""
ObjectCount=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get:... |
"""Top-level package for airmailer."""
__author__ = """Christopher Malek"""
__email__ = 'cmalek@caltech.edu'
__version__ = '0.1.2'
|
def progress(count: float, total: float):
bar_len = 60
filled_len = int(round(bar_len * count / float(total)))
percents = round(100.0 * count / float(total), 1)
bar = '=' * filled_len + '-' * (bar_len - filled_len)
print(f'\r[{bar}] {percents}%', end='') |
# -*- coding: utf-8 -*-
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx',
'sphinx.ext.todo', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Python Social Auth'
copyright = u'2012, Matías Aguirre'
exclude_patterns = ['_build']
pygm... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
~Gros
'''
config = {
"host": "localhost",
"task1": {
"port_alice": 10001,
"port_bob": 10002
},
"task2": {
"port_alice": 10001,
"port_bob": 10002
},
"task3": {
"port_alice": 30001,
"port_bob": 300... |
# Copyright 2017 Google LLC. 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 law or a... |
class TestCRUD:
def test_add_one(self, db):
result = db.add_one(
{'name': 'alice', 'url': 'alice.com', 'method': 'get'})
errors = result.get('errors')
success = result.get('success')
assert errors is None
assert success is True
def test_fetch_one(self, db, ... |
CONFIG={
'ppi_n':
{
'aggr': 'concat', 'arch': '1-0-1-0', 'dataset': 'ppi', 'dropout': 0, 'edge_budget': 4000, 'length': 2,
'log_dir': 'none', 'lr': 0.01, 'n_epochs': 50, 'n_hidden': 512, 'no_batch_norm': False, 'node_budget': 6000,
'num_subg': 50, 'num_roots': 3000, 'sampler': 'node', '... |
def stableMarriage(m, w):
m_id = sorted(w[0])
w_id = sorted(m[0])
m_num = 0
rank = 0
m_parner = []
wait = len(m)
tem_m_num = m_num
tem_rank = rank
tem_m_parner = []
for i in range(len(m)):
m_parner.append(-1)
while (wait):
if (m[m_num][rank] not in m_parner):
m_parner[m_num] = m[m_... |
def get_temp():
temp_c = float(input("Enter temp in Celsius: "))
return temp_c
def convert_to_fahr(c):
return c * 9 / 5 + 32
def display_results(c, f):
print(f"{c:.2f} C = {f:.2f} F")
def main():
temp_c = get_temp()
temp_f = convert_to_fahr(temp_c)
display_results(temp_c, temp_f)
main() |
while not done:
env.render()
step_counter += 1
action = agent.get_action(obs)
next_obs, reward, done, _ = env.step(action)
agent.store_env(obs, reward, next_obs, action, done)
obs = next_obs
if step_counter % train_freq == 0:
agent.learn(i + 1)
agent.target_network.load_state_dic... |
#!/usr/bin/env python
__version__ = '0.0.1'
__author__ = 'Fernandes Macedo'
__email__ = 'masedos@gmail.com'
print('''
*******************************************************************************
| | | |
_________|________________.=""_;=.___________... |
"""
This files contains some simple functions to be used in the main, there is no garbled circuit
logic here.
"""
ALICE_DATA_PATH = 'input/alice.txt'
BOB_DATA_PATH = 'input/bob.txt'
def read_input(path):
"""
It reads a file content
:param path: the path of the file to read.
:return: It returns the fi... |
class Carro:
def __init__(self, motor, direcao):
self.motor = motor
self.direcao = direcao
def calcular_velocidade(self):
return self.motor.velocidade
def acelerar(self):
self.motor.acelerar()
def frear(self):
self.motor.frear()
def calcula... |
# (C) Copyright 2019-2021 Hewlett Packard Enterprise Development LP.
# Apache License 2.0
class LoginError(Exception):
"""Exception raised for errors during login.
Attributes:
message -- explanation of the error
"""
def __init__(self, message, status_code=None):
self.message = message... |
def is_multichannel(samples):
"""
:param samples:
:return:
"""
return len(samples.shape) > 2
|
def sumTotal():
'''
Objective : To find the sum of list
User inputs : A list in which elements are space separated
Output : Sum of the list
'''
'''
approach : convert the user entered list to a integer list and loop through the list adding each element to sum variable.
'''
... |
# LISTA DE CHAMADA
# Lista de nomes
chamada = (
'Ana', 'Bianca', 'Gabriel', 'Helen', 'Kevin'
)
# Enumarate retorna, respectivamente, o índice e o valor da lista 'chamada'
for índice, valor in enumerate(chamada):
print(f'{índice + 1} - {valor}') |
def Try_Glossary(Item,Glossary,Header):
if Item in Glossary.keys():
return Header.append(Glossary[Item])
else:
print(Item)
return Header
def NFL_Shorthand_to_Headers(stats_type,Col_Cats,Col_Names):
Stats_Type = stats_type.upper()
Repeats = []
Header = []
... |
class Solution(object):
def maxTurbulenceSize(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
result = 1
start = 0
high = True
for i in range(1, len(arr)):
if arr[i-1] == arr[i]:
start = i
elif high ^ (arr... |
# -*- coding: UTF-8 -*-
class Perfil(object):
'CLasse padrão para perfils de usuários'
def __init__(self, nome, telefone, empresa):
if(len(nome) < 3):
raise ArgumentoInvalidoError('Nome deve ter pelo menos 3 caracteres')
self.nome = nome
self.telefone = telefone
self.empresa = empresa
self.__curtidas =... |
__version__ = "3.10.0"
# Version number of the Ansible collection we want to use
__edb_ansible_version__ = "3.10.0"
def to_num(version):
"""
Convert version number from 3 digits tuple to 1 integer.
(1, 2, 3) -> 100020003
"""
v = ''
for n in version:
v += '{0:04d}'.format(int(n))
ret... |
# NORMAL BINARY TREE DELETE OPERATION AND INSERTION U SING LEVEL ORDER TRAVERSAL.
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Inorder traversal of a binary tree
def inorder(temp):
if (not temp):
return
inorder(temp.left)
pr... |
class Solution:
def canConvert(self, s1: str, s2: str) -> bool:
if s1 == s2: return True
dp = {}
for i, j in zip(s1, s2):
if dp.setdefault(i, j) != j:
return False
return len(set(s2)) < 26 |
variavel = 'Valor'
def func():
print(variavel)
def func2():
# global variavel // nn é boa pratica de programação
variavel = 'Outro valor'
print(variavel)
func()
func2()
|
def train_model(x_train, x_test, y_train, y_test):
input_shape=(img_rows,img_cols,3)
model=create_model(input_shape,total_countries)
adams=optimizers.Adam(lr=1e-4)
model.compile(loss='categorical_crossentropy',
optimizer= adams,
metrics=['accuracy'])
model.fit(x = x_t... |
def get_bytewise_xor(text: bytes, key: int) -> bytes:
return bytes([byte ^ key for byte in text])
def get_character_frequency(ciphertext: bytes):
# Referenced from https://en.wikipedia.org/wiki/Letter_frequency
character_frequencies = {
'a': .08167, 'b': .01492, 'c': .02782, 'd': .04253... |
class LazySegTree:
X_unit = 0
A_unit = 0
@classmethod
def X_f(cls, x, y):
return max(x, y)
@classmethod
def A_f(cls, x, y):
return x + y
@classmethod
def operate(cls, x, a):
return x + a
def __init__(self, N):
self.N = N
self.X = [self.X_un... |
"""
============================================================================
Implementation Exercise: Singly Linked List
============================================================================
-------
Phase 1:
-------
1. Node and LinkedList initialization
2. Getting a node by its position
3. Adding a node to ... |
# as function:
def number(): return 10
def decimal(): return 2.3
def string(): return "Hello there." # ≡
def array(): return [2.3, 'Hello there.', [1, 2], {"a": 1, 'b': 2}]
def dictionary(): return {"number": 2.3, 'list': [1, 2], "values": {'a': 1, "b": 2}}
print(string()) # Hello there. ≡ |
DEBUG = True
HOST = '0.0.0.0'
PORT = 8000
SECRET_KEY = 'bunchofrandomfancylettersandstuff123094u-39u2'
DEFAULT_RATE = '2/hour'
GET_RATE = '10/hour' |
def _check_inputs(self, **kwargs):
# function used to check whether the required inputs have been specified
if 'sampling' not in kwargs:
raise AttributeError("sampling strategy not specified")
elif kwargs['sampling'] not in ['RNDM', 'EVEN']:
raise ValueError(f"{kwargs['sampling']} is not a... |
# Jeff Heaton's Kaggle Utilities
# Copyright 2019 by Jeff Heaton, Open Source, Released under the Apache License
# For more information: https://github.com/jeffheaton/jh-kaggle-util
#
# This file just holds all of the constant values used to configure other parts of the program.
FIT_TYPE_REGRESSION = "reg"
FIT_TYPE_... |
s = input()
n = int(input())
for i in range(n):
word = input()
if len(word) >= 4 and s[0] in word:
flag = True
for ch in word:
if ch not in s:
flag = False
break
if flag:
print(word)
|
# Calculo o enesimo termo
def calcula_termo(primeiro_termo, razao, posicao_termo):
return primeiro_termo * pow(razao, (posicao_termo - 1))
# Verifica se a serie converge
def verifica_convergencia(razao):
if abs(razao) < 1:
return True
else:
return False
# Calcula a soma infinita
def soma_i... |
# Binary Tree Zigzag Level Order Traversal
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
level = [root]
reverse = False
visited = []
# each lev... |
# -*- coding: utf-8 -*-
"""Top-level package for pyagetool."""
__author__ = """Marco Bellaccini"""
__version__ = '0.1.0'
|
# data used to calculate inflation
# source: https://www.minneapolisfed.org/community/financial-and-economic-education/cpi-calculator-information/consumer-price-index-and-inflation-rates-1913
data = {
1913:9.9,
1915:10.1,
1916:10.9,
1917:12.8,
1918:15.0,
1919:17.3,
1920:20.0,
1921:17.9,
1922:16.8,... |
def val(X):
if X<0:
return 1
else:
return 2
|
class TexTextError(RuntimeError):
""" Basic class of all TexText errors"""
pass
class TexTextNonFatalError(TexTextError):
""" TexText can continue execution properly """
pass
class TexTextCommandError(TexTextNonFatalError):
pass
class TexTextCommandNotFound(TexTextCommandError):
pass
cl... |
class BananoConversions():
# 1 BANANO = 10e29 RAW
RAW_PER_BAN = 10 ** 29
@classmethod
def raw_to_banano(self, raw_amt):
return raw_amt / self.RAW_PER_BAN
@staticmethod
def banano_to_raw(ban_amt):
expanded = float(ban_amt) * 100
return int(expanded) * (10 ** 27) |
n=int(input())
k=int(input())
sum=0
for i in range(n):
x=int(input())
if i<k:
sum+=x
print(sum) |
class CrunchyrollError(Exception):
pass
class LoginError(CrunchyrollError):
pass |
# -*- coding: utf-8 -*-
'''
File name: code\step_numbers\sol_178.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #178 :: Step Numbers
#
# For more information see:
# https://projecteuler.net/problem=178
# Problem Statement
'''
Consider ... |
if_list=['if','fi']
for_list=['for','fro','ofr','orf','rof','rfo']
elif_list=['elif', 'elfi', 'eilf', 'eifl', 'efil', 'efli', 'leif', 'lefi', 'lief', 'life', 'lfie', 'lfei', 'ilef', 'ilfe', 'ielf', 'iefl', 'ifel', 'ifle', 'flie', 'flei', 'file', 'fiel', 'feil', 'feli']
else_list=['else', 'eles', 'esle', 'esel', 'ees... |
"""FamilySearch Utilities submodule"""
# Python imports
# Magic
class Utilities:
"""https://familysearch.org/developers/docs/api/resources#utilities"""
def __init__(self):
"""https://familysearch.org/developers/docs/api/examples#utilities"""
pass
def pending_modifications(self)... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
# inorderMap = {... |
# Do the python implementation here !
def kolmogorov(histo1, histo2):
stat, p_value = 0,0
# TODO
return (stat, p_value)
def wasserstein(F1, F2, nbr_pixels, p):
total_area = 0
delta_D = 0
cosine_d = 0
quadratic_d = 0
for i in range(nbr_pixels):
if abs(F1[i] - F2[i]) > delta_D:... |
GIT_SSH_KEY = "/etc/opt/topology/github"
TOPOLOGY_DATA_DIR = "/data/webhook/topology"
CONTACT_DATA_DIR = "/data/webhook/contact"
WEBHOOK_STATE_DIR = "/data/webhook/state"
WEBHOOK_DATA_DIR = "/data/webhook/topology.git"
WEBHOOK_DATA_REPO = "https://github.com/opensciencegrid/topology"
WEBHOOK_DATA_BRANCH =... |
#!/usr/bin/env python
# Copyright Contributors to the Open Shading Language project.
# SPDX-License-Identifier: BSD-3-Clause
# https://github.com/imageworks/OpenShadingLanguage
# Set up a texture that is a gradient image with a distinct alpha gradient
# of 0.5 from left to right and 0.25 right to left, and no change ... |
"""
Another numerical technique for constructing a hash function is called the mid-square method.
We first square the item, and then extract some portion of the resulting digits.
For example, if the item were 44, we would first compute 44**2=1,936. By extracting the middle two digits, 93,
and performing the remainder ... |
def rotate(text, key):
def encode_single(char, key):
if char.isupper():
return chr((ord(char) - 65 + key) % 26 + 65)
elif char.islower():
return chr((ord(char) - 97 + key) % 26 + 97)
else:
return char
return ''.join(map(lambda c: encode_single(c, key)... |
class NoBoxHasPositiveArea(Exception):
def __init__(self):
Exception.__init__(self, 'No box has positive area.')
class NoBoxToKeep(Exception):
def __init__(self):
Exception.__init__(self, 'No box to keep in detection.')
|
# Criar uma função capaz de determinar qual valor é maior entre dois números determinados.
# Pseudo-Código
# 1. Defina n1 como sendo o primeiro número
# 2. Defina n2 como sendo o segundo número
# 3. Estabeleça a condição de que:
# 3.1. se n1 > n2, então n1 é maior que n2.
# 3.2. se n1 < n2, então n2 é maior que n1.
... |
class Node:
def __init__(self, value, next_value=None):
self.value = value
self.next = next_value
def getvalue(self):
return self.value
def getnext(self):
return self.next
def setnext(self,data):
self.next = data
def setvalue(self,data):
sel... |
class dotGetClipPlanes_t(object):
# no doc
aPlaneIDs=None
aUpX=None
aUpY=None
aUpZ=None
aX=None
aY=None
aZ=None
nPlanes=None
|
class VendingMachine():
def __init__(self, products=[], coins=[]):
self.products = products
self.coins = coins
self.isStopped = True
def computeMinimumChange(self, product, cashTendered):
"""Uses algorithm ScamCustomer to calculate minimum change"""
pass
de... |
def test_list_users(test_client):
response = test_client.user.list()
assert response
|
# This file is actually used to mock a module for the tests.
class Dinosaur:
def __init__(self):
self.name = "trex"
@staticmethod
def a(value):
return value
@classmethod
def b(cls, value):
return value
def hello(self):
return self.name
def roar():
"""
... |
n=int(input())
if n<=125:
print(4)
elif n<=211:
print(6)
else:
print(8)
|
T1 = [[1, 2], [3, 4]]
T2 = [[2, 3, 5], [7, 11, 13], [17, 19, 23]]
T3 = [[2, 5, 2, 5], [2, 5, 5, 2], [2, 5, 2, 2], [2, 5, 5, 5]]
T4 = [[43, 74, 53, 97], [80, 61, 61, 19], [61, 73, 89, 93], [42, 17, 89, 80]]
TESTS = [T1, T2, T3, T4]
def isok(T):
N = len(T)
for r in range(1, N):
for c in range(r):
... |
{('B', 'a'): {('E', 'a'): 0.9949479593949608,
('M', 'a'): 0.005052040605039197},
('B', 'ad'): {('E', 'ad'): 0.9992523782106919,
('M', 'ad'): 0.0007476217893081491},
('B', 'ag'): {},
('B', 'an'): {('E', 'an'): 1.0},
('B', 'b'): {('E', 'b'): 0.934691101357768, ('M', 'b'): 0.06530889864223... |
__version__ = '1.5.3'
__copyright__ = 'Copyright (c) 2009-2017, Kyle Fuller, Mariusz Felisiak'
__licence__ = 'BSD'
__author__ = [
'Kyle Fuller <kyle@fuller.li>',
'Jannis Leidel (jezdez)',
'krisje8 <krisje8@gmail.com>',
'Mariusz Felisiak <felisiak.mariusz@gmail.com>',
]
__URL__ = 'https://django-request.... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: virtual_account_sync
short_description: Manage VirtualAccountSync objects of DeviceOnboardingPnp
description:
- >... |
n = int(input())
l = sorted(map(int, input().split()))
ans = 10000
for i in range(n - 1):
if l[i + 1] - l[i] < ans:
ans = l[i + 1] - l[i]
print(ans)
|
# recursive function that replaces nodes with deeper one until no bypass is required
# the inputs are two set, the one of elements to bypass, the working one
def BypassedSet(Database, SetToBypass, WorkingSet):
for i in WorkingSet.intersection(SetToBypass):
# this pass consists into removing all bypass elem... |
load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
_proto_library_suffix = "proto"
_go_proto_library_suffix = "go_proto"
WELL_KNOWN_TYPE_PACKAGES = {
"any": ("github.com/golang/protobuf/ptypes/any", []),
"api": ("google.golang.org/genproto/protobuf/api", ["source_context", "type"]),
"compiler_p... |
# Puzzle Input
with open('Day15_Input.txt') as puzzle_input:
starting = puzzle_input.read().split('\n')
# Separate the integers (convert from CSV to python list)
for index, number_list in enumerate(starting):
starting[index] = number_list.split(',')
# Parameters
starting = list(map(int, starting[0])) # Allow... |
"""Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços.
Exemplos de palíndromos:"""
frase = str(input('Digite uma frase: ')).strip().upper().split()
juntas = ''.join(frase)
inverso = juntas[::-1]
if inverso == juntas:
print(f'{juntas} é um PALÍNDROMO "{inverso}"')... |
#!/usr/bin/env python3
print(len('Albert Einstein'))
print('Albert' + ' Einstein')
x = 'Albert'
y = ' '
z = 'Einstein'
print(x + y + z)
print('Albert' + y + z)
print('Four score and ' + str(7) + ' years ago')
print(4 * '-')
x = '-'
print(4 * x)
print('one\ntwo\nthree')
print('one\ttwo\nthree\tfour')
print('one','t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
PyRfid
Copyright (C) 2015 Philipp Meisberger <team@pm-codeworks.de>
All rights reserved.
@author: Philipp Meisberger <team@pm-codeworks.de>
"""
__version__ = '1.2'
|
# define the 'EXPECTED_BAKE_TIME' constant
EXPECTED_BAKE_TIME = 40
# consider defining the 'PREPARATION_TIME' constant
# equal to the time it takes to prepare a single layer
PREPARATION_TIME = 2
# define the 'bake_time_remaining()' function
def bake_time_remaining(elapsed_bake_time):
"""Calculate the bake t... |
class Solution(object):
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
res = []
tmp = []
wordlen = 0
for word in words:
if wordlen + len(word) + len(tmp) > maxWidth:
if len(tmp) == 1:
res.append(t... |
class Solution:
def XXX(self, x: int) -> int:
if x >=0 :
out_x = int(str(x)[::-1])
else:
out_x = -int(str(-x)[::-1])
if (out_x>-(2)**31) and (out_x<2**31-1):
return out_x
else:
return 0
|
class Road():
def __init__(self):
self.curves = []
self.curve_table = {} |
# coding=utf-8
"""
Make this module executable with python -m racetrax
"""
|
#!/usr/bin/env python3
#
# game_keyboard_mapping.py
# Include keyboard mappings for different games, i.e.
# converting bunch of button names into MultiDiscrete action
# lists
#
# Structure:
# game_name: [
# (possible_button_for_action1, another_possible_button_for_action1),
# (possible_button_for_action2),
# ...... |
n=int(input("enter a number\n"))
if n%7==0:
print("Divisible by 7")
else:
print("Not Divisible by 7")
|
# complex_function_grapher.py
class ComplexFunctionGrapher(object):
# Derivatives of this class can graph complex-valued functions
# of a complex variable in a variety of ways.
def __init__(self, window_min=None, window_max=None):
self.window_min = complex(real=-10.0, imag=-10.0) if window_min... |
"""
Arithmetic Functions
Arithmetic Functions are functions that work on individual numbers, lists, and arrays: in either symbolic or algebraic forms.
"""
|
def main():
# input
S = input()
# compute
# output
print(S[0].upper() + S[1:].lower())
if __name__ == '__main__':
main()
|
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
start, end = m, n
d... |
def test_verify_site(client):
content = client.get('/google11a50bcc62df11b5.html').content
assert '11a50bcc62df11b5' in str(content)
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sumNumbers(self, root, string=''):
"""
:type root: TreeNode
:rtype: int
"""
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.