content stringlengths 7 1.05M |
|---|
"""
'Pruning' as shown in Marcos Lopez de Prado "Advances in Financial Machine Learning" Chapter 7
For cases when the test set is not the most recent one in time, such as cross validation, another technique
shown in that chapter, that the author calls 'Embargo', would also be useful. It would help, at least, to preve... |
x = f"There are {10} types of people."
binary = 'binary'
do_not = "don't"
y = "Those who know {binary} adn those who {do_not}."
print(x)
print(y)
print('I said: {x}.')
print('I also said: {y}')
hilarious = False
joke_evaluation = f"Isn't that joke so funny?! {hilarious}"
print(joke_evaluation)
w = ... |
def romanToInt(s):
roman_val = {'I' : 1, 'V': 5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
int_val = 0
for i in range(len(s)):
print(s, i, s[i], roman_val[s[i]], roman_val[s[i - 1]])
if i > 0 and roman_val[s[i]] > roman_val[s[i - 1]]:
int_val += roman_val[s[i]] - 2 * roma... |
class Loan:
'Base class for all loans.'
LoanCount = 0
def __init__(self, m, y, v, r, score, term):
LoanCount += 1
self.PolicyNumber = LoanCount
self.OriginMonth = m
self.OriginYear = y
self.OriginValue = v
self.PrincipalValue = v
self.Balance = v
... |
# 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 isSymmetric(self, root: TreeNode) -> bool:
def find(r,l):
if(r == None and ... |
def pattern_elevan(strings):
'''Pattern elevan
K A T H M A N D U
A T H M A N D U
T H M A N D U
H M A N D U
M A N D U
A N D U
N D U
D U
U
'''
if not str(strings).isalpha():
strings = str(strings) # If provided i... |
# Created by Egor Kostan.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
class EpidemicTestData:
def __init__(self, tm, n, s0, i0, b, a, expected):
self.__tm = tm
self.__n = n
self.__s0 = s0
self.__i0 = i0
self.__b = b
self.__a = a
self.__expected = expect... |
s = int(input('Digite a distância que deseja percorrer (em Km): '))
'''if s <= 200:
print('Sua viajem então custará R${:.2f}'.format(0.5 * s))
else:
print('Sua viajem irá custar R${:.2f}'.format(0.45 * s))
print('-Boa Viajem!-' * 5)'''
preço = s * 0.5 if s <= 200 else s * 0.45
print('Sua viajem vai custar R${:.... |
class Solution:
def solve(self, lst1, lst2):
lst1.sort()
lst2.sort()
n = len(lst1)-1
m = len(lst2)-1
i = 0
j = 0
ans = float('inf')
while i <= n and j <= m:
ans = min(abs(lst1[i]-lst2[j]),ans)
if lst1[i] < lst2[j]:
... |
n = int(input())
arr = list(map(int, input().split()))
b=max(arr)
while max(arr)==b:
arr.remove(max(arr))
print(max(arr))
|
class GraphQlVariable(object):
"""A GraphQL variable definition.
Public attributes:
object default_value - A Python object indicating the default value
of the variable, if any.
basestring name - The name of the variable.
GraphQlType variable_type - The type of the variable.
"""
de... |
# https://docs.python.org/3/library/__main__.html
if __name__ == "__main__":
pass
|
print('Enter the three sides of the triangle')
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('Area of the triangle = %0.3f' %area) |
def transform_test_oa18_to_oa11_kinetics(oa18_test_stacks, oa11_kinetics_test_stacks):
cls_to_new_class = {2:1, 3:2, 4:3,
5:4, 7:5, 9:6,
11:7, 13:8, 15:9,
17:10, 18:11}
lines = []
with open(oa18_test_stacks) as fr:
for line in... |
n, l = map(int, input().split())
list = [str(input()) for i in range(n)]
list.sort()
s = ''.join(list)
print(s)
|
def lcs(s1,s2):
l1 = len(s1)
l2 = len(s2)
memo = [[-1] * (l1+1) for x in range(l2+1)]
sol = [[None for x in range(l1+1)] for x in range(l2+1)]
for i in range(l1):
for j in range(l2):
if i == 0 or j == 0:
q = 0
memo[i][j] = 0
sol[i]... |
while True:
valor = int(input('INFORME O VALOR DO SAQUE: R$ '))
while valor < 1:
valor = int(input('VALOR INVÁLIDO! DIIGTE NOVAMENTE: R$ '))
a = valor % 50
cinquenta = (valor - a) / 50
b = a % 20
vinte = (a - b) / 20
c = b % 10
dez = (b - c) / 10
d = c % 1
um = (c - d) / ... |
class Tile:
def __init__(self, tile_type):
self.tyle_type = tile_type
|
'''
Below, we have provided a list of lists. Use indexing to assign the element ‘horse’ to the variable name idx1.
'''
animals = [['cat', 'dog', 'mouse'], ['horse', 'cow', 'goat'], ['cheetah', 'giraffe', 'rhino']]
idx1 = animals[1][0]
'''
Using indexing, retrieve the string ‘willow’ from the list and assign that to ... |
# Copyright (c) 2021.
# The copyright lies with Timo Hirsch-Hoffmann, the further use is only permitted with reference to source
class ChampionMastery:
champion_id: int
champion_level: int
champion_points: int
last_play_time: int
champion_points_since_last_level: int
champion_points_until_nex... |
def mode():
tally = {}
M = nums[0]
for x in nums:
tally[x] = tally.get(x, 0) + 1
if tally[x] > tally[M]:
M = x
return M
def max(nums):
M = nums[0]
for x in nums:
if x > M:
M = x
return M
def min(nums):
M = nums[0]
for x in nums:
if x < M:
M =x
return M
def mean(nums):
if len(nums) == 0:
... |
NODE_SIGNING_KEY = NotImplemented
SENTRY_DSN = None
SENTRY_EVENT_LEVEL = 'WARNING'
NODE_NETWORK_ADDRESSES: list[str] = []
NODE_PORT = 8555
APPEND_AUTO_DETECTED_NETWORK_ADDRESS = True
NODE_FEE = 4
IN_DOCKER = False
NODE_LIST_JSON_PATH = None
SYNC_BATCH_SIZE = 10
SCHEDULE_CAPACITY = 20
SUPPRESS_WARNINGS_TB = True
LO... |
# # DESCRIPTION
# Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
# You may assume that the array is non-empty and the majority element always exist in the array.
# EXAMPLE 1:
# Input: [3,2,3]
# Output: 3
# EXAMPLE 2:
# Input: [2,2,1,1,1,2... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
#Approach :
'''
Put Node2.next which is n3->n4->...nn into Node1.next
Now put entire Node1 which is n1-n3-n4... into Node2.next . with this step n1 and n2 are swapped.... |
for t in range(int(input())):
wordList=(" ".join(input())).split(" ")
numOfHy=int(input())
locOfHy=list(map(int,input().split()))
numOfHyEachLoc=[0 for i in range(len(wordList)+1)]
for i in locOfHy:
numOfHyEachLoc[i]+=1
print(f"#{t+1}",numOfHyEachLoc[0]*"-",end="")
for i in range(len... |
"""
for i in range(size):
c = buf[i]
enc += table[(c // 10) * 16 + c % 10]
"""
with open("babyrev.exe", "rb") as f:
f.seek(0x8fb0)
table = f.read(0x100)
with open("enc.txt", "rb") as f:
cipher = f.read()
flag = ""
for i, c in enumerate(cipher):
for x in range(0x100):
if table[(x // 10)... |
# -*- coding: utf-8 -*-
class NotRecognizeCommandException(Exception):
pass
class NotRecognizeProtocolException(Exception):
pass
|
# MENU
# DIFERENCA EXERCICIO MENU x EXERCICIO LISTA
# Exercício do Banco
# Crie um menu no qual:
# 1) faz um deposito de um valor a ser colocado pelo cliente, se o usuario entrar com 1
# 2) faz um saque de um valor a ser colocado pelo cliente se opção for 2
# 3) faz uma transferencia para um valor a ser colocado pelo ... |
#
# @lc app=leetcode id=765 lang=python3
#
# [765] Couples Holding Hands
#
# @lc code=start
class Solution:
def minSwapsCouples(self, row: List[int]) -> int:
d, swap={}, 0
for i, x in enumerate(row):
d[x]=i
for i in range(0, len(row), 2):
partner=row[i]+1 if row[i]%2... |
# -*- coding: utf-8 -*-
'''package requirements are checked at runtime and installation time'''
#-----------------------------------------------------------------------------
# Copyright (c) 2013-2020, NeXpy Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the ... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# pylint:disable=bad-whitespace
# pylint:disable=line-too-long
# pylint:disable=too-many-lines
# pylint:disable=invalid-name
# #########################################################
#
# ************** !! WARNING !! ***************
# ******* THIS FILE WAS A... |
# multiple.py
def fail(exception_cls):
raise exception_cls("Ooops")
try:
fail(ValueError)
except Exception as exc:
print("Can catch ValueError as Exception.")
print(exc.__class__)
except ValueError as exc:
print("Can catch ValueError as ValueError.")
print(exc.__class__)
try:
fail(Value... |
#!/usr/bin/env python
"""
Fraunhofer IML
Department Automation and Embedded Systems
Tabsize : 4
Charset : UTF-8
"""
__author__ = "Dennis Luensch"
__maintainer__ = "Dennis Luensch"
__email__ = "dennis.luensch@iml.fraunhofer.de"
TP_EXCEPTION_PATH_ALREADY_EXISTS = "Path to vertex alreay ... |
# https://www.hackerrank.com/challenges/python-string-formatting/problem
def print_formatted(number):
for i in range(1, number + 1):
pad = number.bit_length()
print(f"{i:{pad}d} {i:{pad}o} {i:{pad}X} {i:{pad}b}")
|
numero = int(input("inserisci muvt"))
if numero % 2 == 0 :
print("il numero è pari")
else:
print("il numero è dispari") |
# Generic
CPREF_COMPONENT = "([0-9A-Z-]|%2F|%23)+"
NUMERIC_COMPONENT = "(0|[1-9]\d*)"
GS3A3_CHAR = "((%[0-9a-fA-F])|([a-zA-Z0-9!'()*+,-.:;=_]))"
GS3A3_COMPONENT = f"{GS3A3_CHAR}+"
PADDED_NUMERIC_COMPONENT = "\d+"
PADDED_NUMERIC_COMPONENT_OR_EMPTY = "\d*"
VERIFY_GS3A3_CHARS = "[a-zA-Z0-9!'()*+,-.:;=_\"%&/<>?]+"
GS1_ELEM... |
#Code to check a string has unique charecters
#using hash_map
def is_unique(inp_str):
c_dict = {}
for c in inp_str:
if c in inp_str:
return False
else:
c_dict[c]=1
return True
#no data structure , bruteforce
def is_unique_bf(inp_str):
for i in range(len(inp_str)-1):
for j in range(i+1,len(inp_str))... |
string = 'afassdfasdfa'
start = maxLength = 0
mydict = {}
for i, c in enumerate(string):
if c in mydict and start <= mydict[c]:
start = mydict[c] + 1
else:
maxLength = max(maxLength, i-start+1)
mydict[c] = i
print(mydict)
print(maxLength, mydict )
|
{
"targets": [
{
"target_name": "addon",
"sources": [
"SensorFusion_Addon.cpp", "SensorFusion.cpp", "Vector3D.cpp"
],
"include_dirs": [
"/usr/include/upm/","/usr/include/mraa/"
],
"libraries": [
"/usr/lib/libupm-lsm9ds0.so"
],
"cflags": [ "-... |
def update_session_credentials(config, session_credentials, profile):
if not config.has_section(profile):
config.add_section(profile)
config.set(profile, "aws_access_key_id", session_credentials.access_key)
config.set(profile, "aws_secret_access_key", session_credentials.secret_key)
config.set... |
student = {
"Name": "Shantanu",
"Age": 21,
"feedback": None
}
student["lastName"] = "Kamath"
try:
lastName = student["lastName"]
new_var = 3 + student["lastName"]
except KeyError:
print("Error finding last name")
except TypeError as error:
print("Cant add these two together... |
nome = str(input('Qual é seu nome completo? ').strip())
print('Seu nome todo em maisculas é {}'.format(nome.upper()))
print('Seu nome todo em minusculas é {}'.format(nome.lower()))
print('Seu nome tem ao todo {} letras'.format(len(nome) - nome.count(' ')))
print('Seu primeiro nome tem {} letras'.format(nome.find(' ')))... |
#PRIME OR NOT
num=int(input('Enter a number'))
if num<=1:
print('Please enter a valid number')
for i in range(2,num):
if(num % i == 0):
print("The number is not prime number")
break
else:
print('The number is a prime number') |
def serialize_suggestions_values_response(result):
try:
field_values = result["aggregations"]["values"]["buckets"]
except KeyError:
field_values = []
return field_values
def serialize_mappings(mappings):
result = []
for field in mappings:
result.append({"name": field.name, ... |
with open('02.txt', 'r') as f:
data = f.read()
player_1_data, player_2_data = data.split('\n\n')
player_1_cards = list(map(int, player_1_data.split(':')[1].split()))
player_2_cards = list(map(int, player_2_data.split(':')[1].split()))
while player_1_cards and player_2_cards:
card_1 = player_1_cards.pop(0)
... |
PA=80000
PB=200000
tca=0.03
tcb=0.015
a=0
while PA<PB:
PA+=PA*tca
PB+=PB*tcb
a+=1
print("o tempo necessario para que a população se iguale é %d anos" % a)
|
# -*- coding: utf-8 -*-
# file: TextProcessor.py
# date: 2022-03-08
class TextProcessor(object):
def __init__(self):
pass
|
class Solution:
# @param s, a string
# @param wordDict, a set<string>
# @return a boolean
def wordBreak(self, s, wordDict):
dym = [True]
for i in range(1, len(s)+1):
dym.append(False)
for word in wordDict:
l = len(word)
if l <= i an... |
__author__ = "Alex Laird"
__copyright__ = "Copyright 2020, Alex Laird"
__version__ = "4.1.0"
class PyngrokError(Exception):
"""
Raised when a general ``pyngrok`` error has occurred.
"""
pass
class PyngrokSecurityError(PyngrokError):
"""
Raised when a ``pyngrok`` security error has occurred.
... |
def detail(a, b, c, D):
if b == 0 and c == 0:
print("\nFor finding the solutions of the equation we must resolve:")
print("\n\t",a,"x^2 = 0")
elif b == 0:
if (a > 0 and c > 0) or (a < 0 and c < 0):
print('\n\tThe equation has no solutions..')
else:
... |
"""Тесты прямоугольника"""
def test_rectangle_area(rectangle):
assert rectangle.get_area() == 35
def test_triangle_perimeter(rectangle):
assert rectangle.get_perimeter() == 24
def test_add_area_rectangle(rectangle, square):
assert rectangle.add_area(square) == 71
def test_is_instance_not_figure(rect... |
# En este script hacemos operaciones basicas
# 13 de sept 2021
suma = 5 + 2
resta = suma - 8.5
m1 = 32
m2 = 64
multiplicacion = m1 * m2
print("Este programa acaba de hacer algunas operaciones")
print('la suma dio como resultado: ')
print(suma)
print('la resta dio como resultado: ', resta) # la resta dio como resultado:... |
'''
This is the binary search tree implementation.
'''
class BinSearchTree():
class Node():
def __init__(self, key, parent, data, left_child, right_child):
self.key = key
self.parent = parent
self.data = data
self.left = left_child
self.right = ... |
#// AUTHOR: Guruprasanna
#// Python3 Concept: sha384(hashing)
#// GITHUB: https://github.com/Guruprasanna02
#// Add your python3 concept below
#SHA384 hashing implementation manaually.
def rightrotate_64(i, j):
i &= 0xFFFFFFFFFFFFFFFF
return ((i >> j) | (i << (64 - j))) & 0xFFFFFFFFFFFFFFFF
def leftrotate... |
# Start of Lesson 3
bubbles = [1,2,3,4,5,6]
n = 9
def find(n,array):
'''
This function looks for n in a list
'''
for item in array:
if item == n:
return True
return False
print(find(n,bubbles))
'''
index = 0
isFound = False
while isFound == False:
item = bubbl... |
class Deque:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def add_front(self, item):
self.items.insert(0, item)
def add_rear(self, item):
self.items.append(item)
def remove_front(self):
return self.items.pop(0)
def ... |
#
# PySNMP MIB module ASCEND-MIBATMSIG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBATMSIG-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:26:38 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
# Copyright 2020 StreamSets Inc.
#
# 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... |
def main():
pass
# wip
|
# Dictionary
# : is used to specify the key
data = {1: "pvd", 2: "vsd", 3: "rhd"}
print(data)
# fetching a particular value
print(data[2])
# functions can be used
print(data.get(3))
print(data.get(4, "Not found"))
# dictionary with lists
keys = ["pvd", "vsd", "rhd"]
val = ["c", "php", "c++"]
data = dict(
zip(ke... |
# 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 rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def iter(node):
... |
"""Module contains utilities to improve the interface with benchling."""
def only_label_feature(part: "BasicPart") -> "BasicPart":
"""Return part with only the label feature.
Useful for getting rid of ApEinfo features following Benchling
exports.
Args:
part: object to simplify each feature i... |
class BST_node:
def __init__(self, root, key):
self.key = key
self.left = None
self.right = None
self.parent = root
self.max_height = 0
self.all = False
def falling_block(root, a, b, last_value):
if root.left is None and root.right is None:
return root.m... |
def toggle_batch_norm(config: dict, layer_id: int):
batch_norm = config['model']['conv_layers'][layer_id].get('batch_norm', False)
config['model']['conv_layers'][layer_id]['batch_norm'] = not batch_norm
def add_conv_layer(config: dict, num_filters: int, kernel_size: int, batch_norm: bool = False):
config[... |
class CommissionScheme:
def __init__(self,
scheme: str):
self.name = scheme
self.commission = 0
def calculate_commission(self,
quantity: float,
price: float) -> float:
# Avanza.se
if self.name == 'avanza_... |
f1 = 'psychoticism'
f2 = 'neuroticism'
f3 = 'extraversion'
f4 = 'lie'
factors_names = (f1,f2,f3,f4)
factors = {
1:{
22 :(f1,)
, 26 :(f1,)
, 30 :(f1,)
, 33 :(f1,)
, 43 :(f1,)
, 46 :(f1,)
, 50 :(f1,)
, 65 :(f1,)
, 67 :(f1,)
, 74 :(f1,)... |
HARI = (
("Senin","Senin"),
("Selasa","Selasa"),
("Rabu","Rabu"),
("Kamis","Kamis"),
("Jumat","Jumat"),
) |
def hamming_dist(s1, s2):
'''
returns:
pass in:
'''
if len(s1) != len(s2):
raise ValueError("Hamming dist undefined for two strings of unequal length")
return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))
|
#!/usr/bin/env python
#
# ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University of Chicago
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://ge... |
class ReverseProxied(object):
"""This middleware can be applied to add HTTP proxy support to an application
which access the WSGI environment directly.
It sets `REMOTE_ADDR`, `HTTP_HOST`, `wsgi.url_scheme` from `X-Forwarded` headers.
Also front-end server can be configured to quietly bind this to a URL ... |
# -*- coding: utf-8 -*-
'''Autor: Alessandra Souza
Data: 05/05/2017
Objetivo: Calculo de salario liquido.
ID Urionlinejudge: 1008.'''
NUMBER=int(input())
horast=int(input())
valhr=float(input())
SALARY = (valhr*horast)
print("NUMBER = %d" %NUMBER)
print("SALARY = U$ %.2f" %SALARY)
|
"""Merge and sort two arrays into one."""
def sort_array_buf(a, b):
if b == [] or a == []:
return None
i = len(a) - 1
j = len(b) - 1
k = i - j - 1
if k < 0:
return None
while i >= 0 and j >= 0 and k >= 0:
if a[k] >= b[j]:
a[i] = a[k]
k ... |
data = list(input().split())
counter = 0
for x in range(int(data[1])):
word = sorted(list(input()))
check = sorted(list(data[0]))
if word == check:
counter += 1
print(counter)
|
colors = [
'purple',
'blue',
'red',
] |
words = "Life is short"
upper_word_list = ["LIFE", "IS", "SHORT", "USE", "PYTHON"]
lower_word_list = [
lower_w for w in upper_word_list if (lower_w := w.lower()) in words.lower()
]
print(" ".join(lower_word_list))
|
def respuesta(cells, cell_data, phy_lin):
"""Extracts the nodes located at the physical line
phy_line
Parameters
----------
cell : dictionary
Dictionary created by meshio with cells information.
cell_data: dictionary
Dictionary created by meshio with ... |
class BibleVersionNotSupportedException(Exception):
code = 600
def __init__(self, message='Bible version was not supported'):
# Call the base class constructor with the parameters it needs
super().__init__(message)
# Now for your custom code...
self.error = {
'code'... |
""" import turtle as t
for x in range(4):
t.forward(100)
t.right(90)
"""
""" import turtle
# edit this line to control where window appears
turtle.setup(width=500, height=500, startx=-1, starty=0)
turtle.forward(100) """
""" from turtle import *
turtle = Turtle()
print(turtle.position())
turtle.forward(... |
def check(mark):
if mark > 100:
return None
elif mark >= 80:
return 4.00
elif mark >= 75:
return 3.75
elif mark >= 70:
return 3.50
elif mark >= 65:
return 3.25
elif mark >= 60:
return 3.00
elif mark >= 55:
return 2.75
elif mark >= 5... |
# -*- coding: utf-8 -*-
"""
@ Author: Sandip Dutta
--------------------------------------------------------------
Code for Modular Exponentiation
Modular Exponentiation is an algorithm for calculating
(a^b) % m fast.
a^b is useful for us but it's value may be large
and it might overflow. So we calculate (a^b... |
filenames = ['the-big-picture.md',
'inspecting.md',
'download-html.md',
'create-soup-and-search.md',
'scrape-data-from-tag.md',
'project1-basketball-data-from-nba.md',
'project2-game-data-from-steam.md',
'project3-movie-data-from-imdb.md',
'project4-product-data-from-amazon.md'
]
with open('book.md', 'w') as outfile:
... |
def fbx_template_def_texture_file(scene, settings, override_defaults=None, nbr_users=0):
# WIP...
# XXX Not sure about all names!
props = OrderedDict((
(b"TextureTypeUse", (0, "p_enum", False)), # Standard.
(b"AlphaSource", (2, "p_enum", False)), # Black (i.e. texture's alpha), XXX name gu... |
#!/usr/bin/python3.6
##### Sieve of Eratosthenes #####
""" Calculates prime numbers, Enter the upper range of Primes."""
def seiveoferatosthenes(num):
primes = [i for i in range(2, num+1)]
i = 0
while i < len(primes):
p = primes[i]
j = i + 1
while j < len(primes):
if p... |
expected_output = {
'status': 'enabled',
'ssh_port': '830',
'candidate_datastore_status': 'enabled'
}
|
def titulo(txt):
print('-=' * 30)
print(txt)
#programa principal
titulo(' APRENDENDO PYTHON ')
titulo(' PYTHON É MUITO BOM ! ')
titulo('Oi')
#-----------------------------------------------------------------------------------------------------------------------
def soma(* valores): #a função soma vai ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2016 Richard Hull
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including wit... |
# -*- coding: utf-8 -*-
class ModuleDocFragment(object):
# Git doc fragment
DOCUMENTATION = '''
options:
git_token:
description:
- Git token used for authentication
- Required if I(git_username=None)
- If not set, the value of the C(GIT_TOKEN) environment variab... |
"""A collection of functions for doing my project."""
def string_concatenator(string1, string2):
"""Combines strings together by adding them and returning the combination as an output.
Parameters
----------
string1 : string
String that will be added to another string.
str... |
#!/usr/bin/env python3
def unit_fraction(d):
n = 10
while True:
yield n//d, n%d
n = 10*(n%d)
def longest_chain(d):
encountered = []
for pair in unit_fraction(d):
if pair in encountered:
return len(encountered[encountered.index(pair):])
else:
enco... |
"""
Power digit sum
2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2**1000?
Answer: 1366
"""
def power_digit_sum(base, power):
"""Return the sum of the digtis in base**power"""
return sum([int(... |
class Decision(object):
def __init__(self, action=None):
self.action = action
def get_action(self):
return self.action
def decision(self):
action = self.get_action()
if action == 4:
return "open"
elif action == 6:
return "fold"
elif a... |
class Car:
def __init__(self, name, loss):
# loss [价格,油耗,公里数]
self.name = name
self.loss = loss
def get_name(self):
return self.name
def get_price(self):
# 获取汽车价格
return self.loss[0]
def get_loss(self):
# 获取汽车损耗值
return self.loss[1] * se... |
class Solution:
def permute(self, nums: [int]) -> [[int]]:
if len(nums) <= 1:
return [nums]
ans = []
perms = self.permute(nums[1:])
for perm in perms:
for i in range(0, len(perm) + 1):
p = perm[:i] + [nums[0]] + perm[i:]
ans.app... |
def get_summary(name = "Daisi user"):
text = '''
This Daisi is a simple endpoint to a *Hello World* function, with a straightforward
Streamlit app.
Call the `hello()` endpoint in Python with `pydaisi`:
```python
import pydaisi as pyd
print_hello_app = pyd.Daisi("Print Hello App")
gre... |
def image(request, id):
return HttpResponse(open(directory.settings.DIRNAME +
"/static/images/profile/" + id, "rb").read(),
mimetype = directory.models.Entity.objects.filter(id = int(id))[0].image_mimetype)
|
#
# @lc app=leetcode.cn id=120 lang=python3
#
# [120] 三角形最小路径和
#
# https://leetcode-cn.com/problems/triangle/description/
#
# algorithms
# Medium (67.13%)
# Likes: 692
# Dislikes: 0
# Total Accepted: 129.9K
# Total Submissions: 193.5K
# Testcase Example: '[[2],[3,4],[6,5,7],[4,1,8,3]]'
#
# 给定一个三角形 triangle ,找出自顶... |
#!/usr/bin/python3
"""defines a class Square"""
class Square:
"""Represents a square
Attributes:
__size (int): size of a side of the square
"""
def __init__(self, size=0):
"""initializes the square
Args:
size (int): size of a side of the square
Returns:
... |
def user_id_validator(source_function):
"""Function which can be used as a decorator to validate the user id"""
def function_wrapper(*args, **kwargs):
exe_res = source_function(*args, **kwargs)
return exe_res
return function_wrapper
@user_id_validator
def sample_function(arg1, arg2):
... |
def score_game(frames):
total = 0
for index, frame in enumerate(frames):
# frame => (10, 0) # 14, frame+1 => (2, 2) # 4
frame_total = sum(frame)
if frame[0] == 10:
total += sum(frames[index + 1])
# if frames[index + 2][0] == 10:
# total += frames... |
class LocalCommunicationService:
__hotword_file = "/home/pi/teddy-vision/hotword.txt"
__instance = None
@staticmethod
def getInstance():
if LocalCommunicationService.__instance == None:
LocalCommunicationService()
return LocalCommunicationService.__instance
def __init__... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.