content stringlengths 7 1.05M |
|---|
class Judge:
def __init__(self, trial, comparator):
self.trial = trial
self.comparator = comparator
def judge(self, inputs, default):
results = {input: self.trial(input) for input in inputs}
eligible = {input: result for input, result in results.items() if result is not None}
... |
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
elif len(nums) == 1:
return nums[0]
elif len(nums) == 2:
return max(nums[0], nums[1])
scores = [0] * len(nums)
scores[0] = nums[0]
scores[1] = n... |
a = 50
print('\033[32m_\033[m'*a)
print('\033[1;32m{:=^{}}\033[m'.format('SISTEMA DE IDENTIFICAÇÃO DE PESOS', a))
print('\033[32m-\033[m'*a)
listafinal = list()
listainit = list()
tamanho = 0
maiorp = menorp = 0
continuar = 's'
while True:
if 's' in continuar:
listainit.append(str(input('\033[36mNome: '))... |
#exercicio 93 curso de python
lista_de_tarefa = []
desfeito = []
menu_0 = '''
|_______________________|
| [1] - Adicionar tarefa|
| [2] - Listar tarefas |
| [3] - Desfazer tarefa |
| [4] - Refazer tarefa |
| [5] - Sair
|_______________________|
Digite uma opção: '''
def adici... |
class BinarySearchTree:
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def __init__(self):
self.root = None
def add(self, value):
if self.root:
self._add(value, self.root)
... |
# noinspection PyUnusedLocal
def fizz_buzz(number):
strings = []
numstring = str(number)
# fizz if divisible by 3 or has a 3 in it
if (number % 3 == 0) or ("3" in numstring):
strings.append("fizz")
# buzz if divisible by 5 or it has a 5 in it:
if (number % 5 == 0) or ("5" in numstring):
... |
# program to find whether it contains an additive sequence or not.
class Solution(object):
# DFS: iterative implement.
def is_additive_number(self, num):
length = len(num)
for i in range(1, int(length/2+1)):
for j in range(1, int((length-i)/2 + 1)):
first, second, others ... |
# -*- coding:UTF-8 -*-
# Author:Tiny Snow
# Date: Tue, 30 Mar 2021, 17:09
# Project Euler # 085 Counting rectangles
#=============================================================Solution
def get_rectangles(m, n):
return m * (m + 1) * n * (n + 1) // 4
diff = 10000
area = 0
for m in range(1, int(2 * (2 ** 0.5) * 10... |
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
s = []; t = []
for i in range(len(S)):
if S[i] == "#":
if len(s) > 0:
s.pop(-1)
else:
s.append(S[i])
for i in range(len(T)):
if T[i] == ... |
N = int(input())
before = input()
after = input()
if N % 2 == 0:
print("Deletion succeeded" if before == after else "Deletion failed")
else:
find = True
for i in range(len(before)):
if before[i] == after[i]:
find = False
break
print("Deletion succeeded" if find else "Del... |
class Actor:
def __init__(self, sess, learning_rate,action_dim,action_bound):
self.sess = sess
self.action_dim = action_dim
self.action_bound = action_bound
self.learning_rate = learning_rate
# input current state, output action to be taken
self.a = self.build_neural... |
"""
PlotPlayer Validators Subpackage contains various modules to support input and type validations.
Public Modules:
* type_validation - Contains methods to validating various types
"""
|
class ParserError(Exception):
pass
|
r = int(input())
w = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
m = [0]
for i in range(1, r + 1):
m.append(max([x[0] + m[i - x[1]] for x in zip(c, w) if x[1] <= i], default = 0))
print(m)
|
#
# オセロ(リバーシ) 6x6
#
N = 6 # 大きさ
EMPTY = 0 # 空
BLACK = 1 # 黒
WHITE = 2 # 白
STONE = ['□', '●', '○'] #石の文字
#
# board = [0] * (N*N)
#
def xy(p): # 1次元から2次元へ
return p % N, p // N #35の座標の出力(5,5)
def p(x, y): # 2次元から1次元へ
return x + y * N #35を出力
# リバーシの初期画面を生成する
def init_board():
board = [EMPTY]... |
# Greewald et al. 1998
Japanese_names = ["Hitaka", "Yokomichi", "Fukamachi", "Yamamoto", "Itsumatsu", "Yagimoto", "Kawabashi", "Tsukimoto", "Kushibashi", "Tanaka", "Kuzumaki", "Takasawa", "Fujimoto", "Sugimoto", "Fukuyama", "Samukawa", "Harashima", "Sakata", "Kamakura", "Namikawa", "Kitayama", "Nakamoto", "Minakami", "... |
'''"Template" day module for AoC 2015'''
def run(args):
print(f'day0: {args}')
|
'''
@Author: Hata
@Date: 2020-07-26 03:41:32
@LastEditors: Hata
@LastEditTime: 2020-07-28 21:31:17
@FilePath: \LeetCode\116.py
@Description: https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/
'''
class Solution:
def connect(self, root: 'Node') -> 'Node':
if root is None:
... |
#pegando numero
num = int(input('Digite um número qualquer: '))
numDob = num * 2
numTri = num * 3
numRaiz = num**(1/2) #Raiz quadrada é o mesmo que o numero elevado ao meio 1/2
print('O número digitado foi {}, seu dobro é {}, seu triplo é {}, e por fim sua raiz é {}'.format(num, numDob, numTri, numRaiz))
'''
A var... |
name = "boost"
version = "1.61.0"
authors = [
"Beman Dawes",
"David Abrahams"
]
description = \
"""
Boost is a set of libraries for the C++ programming language that provide support for tasks and structures such
as linear algebra, pseudorandom number generation, multithreading, image processing, ... |
class Solution:
# Iterative
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
stack = [root]
while len(stack) > 0:
currentNode = stack.pop()
currentNode.left, currentNode.right = currentNode.right,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
# A number n is called deficient if the sum... |
def returnHazards(map):
hazards = []
for x_index, x in enumerate(map):
for y_index, y in enumerate(x):
if y == 'x':
hazards.append({"x":x_index,"y":y_index})
return hazards |
'''
A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two.
You can pick any two different foods to make a good meal.
Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the ith item of food,
return th... |
# Codechef June2020
# PRICECON
# https://www.codechef.com/problems/PRICECON
# Chef and Price Control
"""
Chef has N items in his shop (numbered 1 through N); for each valid i, the price of the i-th item is Pi. Since Chef has very loyal customers, all N items are guaranteed to be sold regardless of their price.
Howe... |
chislo = input()
chislo_na_schote_drevnih_shizov = ""
cifri_scheta_drevnih_shizov = "ноль, целковый, чекушка, порнушка, пердушка, засирушка, жучок, мудачок, хуй на воротничок, дурачок, ВСЕ".split(", ")
for i in chislo: chislo_na_schote_drevnih_shizov+=cifri_scheta_drevnih_shizov[int(i)]
print(chislo_na_schote_drevnih_s... |
'''
Entrada de dados
'''
nome = input('qual o seu nome? ')
idade = input('qual a sua idade? ')
ano_nascimento = 2021-int(idade)
print()
print(f'{nome}, tem {idade} anos. '
f'{nome} nasceu em {ano_nascimento}.')
print(f'O usuário digitou {nome} e o tipo da variável é'
f' {type(nome)}')
|
# # set up logging
# from config import logging
# logger = logging.getLogger(__name__)
# import re
class Criterion:
"""A set of conditions for matching Actions against PRAW objects"""
def __init__(self, values):
# convert the dict to attributes
self.conditions = values
self.modifier... |
result = 0
boxIds = []
with open("input.txt", "r") as input:
for line in input:
line = line.strip()
boxIds.append(line)
count2 = 0
count3 = 0
for boxId in boxIds:
flag2 = True
flag3 = True
for c in set(boxId):
n = boxId.count(c)
if n == 2 and flag2:
count2 +... |
#!/usr/bin/env python3
"""I’ll Use My Scale module"""
def np_shape(matrix):
"""calculates the shape of a numpy.ndarray"""
return matrix.shape
|
class Solution(object):
def XXX(self, n):
g5=5**0.5
b=(((1+g5)/2)**(n+1)-((1-g5)/2)**(n+1))/g5
return int(round(b))
|
# -*- coding: utf-8 -*-
"""036 - Analisando Triângulo
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1oQmCX-HLeaqxWxaz9zsjj-5Na35XtNXM
"""
print('*' * 54)
print('------- Condição de existência de um triângulo -------'.upper())
print('*' * 54)
r1 = fl... |
"""Created by sgoswami on 7/18/17."""
"""Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be
segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not
contain duplicate words.
For example, given
s = ... |
names = []
addr = 0x148 + 0x4E4
while addr <= 0x148 + 0x7FC:
names.append('\t' + Name(Dword(addr)) + ' = ')
addr += 8
with open('names.txt', 'w') as f:
f.write('\n'.join(names))
|
# Defines sample_keymap_string and sample_keymap_bytes
# Python 2 type Python 3 type
# sample_keymap_string unicode str
# sample_keymap_bytes str bytes
# This sample keymap is the output of xkbcomp :0 [filename] on my
# system - it wasn't chosen for any other... |
prenom = input("Votre prenom svp ")
langue = input("Votre langue: ") # Langue devait etre "francais" ou "anglais"
if langue == "francais":
print("Bonjour %s" % prenom)
elif langue == "anglais":
print("Hello %s" % prenom)
else:
print("ERREUR")
|
"""
Day 1 Solutions
"""
def part1(input_lines):
"""
The captcha requires you to review a sequence of digits (your puzzle input) and find
the sum of all digits that match the next digit in the list. The list is circular,
so the digit after the last digit is the first digit in the list.
For example... |
"""Top-level package for deployer-fsm."""
__author__ = """Luke Smith"""
__email__ = 'lsmith@zenoscave.com'
__version__ = '0.1.5'
|
class Solution:
# @param A : list of list of integers
# @return an integer
def cnt(self, A, mid):
l = 0
r = len(A)-1
while l <= r:
m = (l+r)//2
if A[m] <= mid:
l = m+1
else:
r = m-1
return l
def findMed... |
# raider.io api configuration
RIO_MAX_PAGE = 5
# need to update in templates/stats_table.html
# need to update in templates/compositions.html
# need to update in templates/navbar.html
RIO_SEASON = "season-sl-3"
WCL_SEASON = 3
WCL_PARTITION = 1
# config
RAID_NAME = "Sepulcher of the First Ones"
# for heroic week,... |
__all__ = [
'plotting',
'misc',
'colors',
'tables',
'nodes',
'containers',
'values',
'basic',
'textures',
'drawing',
]
__version__ = '1.1.1'
|
'''
Q: Popular star patterns
Pattern 1:
*
**
***
****
*****
******
Pattern 2:
* * * * * *
* * * * *
* * * *
* * *
* *
*
Pattern 3:
*
***
*****
*******
*********
Pattern 4:
*
... |
# 27. Remove Element
# Python 3
# https://leetcode.com/problems/remove-element
def removeElement(nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
nums[:] = [num for num in nums if num != val]
return len(nums)
numbers, value = [3, 2, 2, 3], 3
print('Length: {} |... |
class Guild:
__slots__ = ('id', 'name', 'icon', 'owner', 'client_is_owner', 'permissions', 'region', 'afk_channel',
'afk_timeout', 'verification_level', 'roles', 'emojis', 'system_channel', 'features',
'mfa_level', 'created', 'large', 'member_count', 'voice_states', 'members', 'chann... |
q_data = [
{"question": "Japan was part of the Allied Powers during World War I.", "correct_answer": "True",
"incorrect_answers": ["False"]}, {"category": "History", "type": "boolean", "difficulty": "easy",
"question": "The Tiananmen Square protests of 1989 were held in H... |
# Python INTRO for TD Users
# Kike Ramírez
# May, 2018
# Understanding Tuples
# Tuples comparison
#case 1
a=(5,6)
b=(1,4)
if (a>b):print("a is bigger")
else: print("b is bigger")
#case 2
a=(5,6)
b=(5,4)
if (a>b):print("a is bigger")
else: print ("b is bigger")
#case 3
a=(5,6)
b=(6,4)
if (a>b):print("a is bigger")
... |
#GamePlay.py
#Richard Greenbaum, Karson Daecher, Max Melamed
"""This module contains the functions needed to support pentago gameplay.
A pentago gameboard is represented by a 6x6 2D array. Each location on the board is initialized to "" and is set
to 0 or 1 when the player or the AI respectively places a marble o... |
def func(s):
one = 0
zero = 0
for i in range(len(s)):
if i > 0 and s[i] == s[i-1] : continue
if s[i] == "1":
one += 1
else :
zero += 1
return min(one,zero)
s = input()
print(func(s))
|
# n points
def lerp_line(pt0, pt1, n):
pts = []
for i in range(n + 1):
t = i / float(n)
pt = pt0 * t + pt1 * (1.0 - t)
pts.append(pt)
return pts
def pole_to_lines(pt0, pt1, color=[0, 255, 0], n=20):
lines = []
pts = lerp_line(pt0, pt1, n)
for pt in pts:
lines.ap... |
class MetaData:
'''
convert to dynamically adding attributes by passing in **kwargs and
setting each key value pair
attention will need to be given for when this class is used in other processes
to make sure they know the attributes that exists with each class
however, not necessary just now
... |
# A non-empty zero-indexed array A consisting of N integers is given.
#
# A permutation is a sequence containing each element from 1 to N once, and
# only once.
#
# For example, array A such that:
# A = [4, 1, 3, 2]
# is a permutation, but array A such that:
# A = [4, 1, 3]
# is not a permutation, because value... |
while(True):
jars = [int(x) for x in input().split()]
if sum(jars) == 0:
break
if sum(jars) == 13:
print("Never speak again.")
elif jars[0] > jars[1]:
print("To the convention.")
elif jars[1] > jars[0]:
print("Left beehind.")
elif jars[1] == jars[0]:
print... |
DATE_PATTERNS = ["%d.%m.%Y", "%Y-%m-%d", "%y-%m-%d", "%Y-%m-%dT%H:%M:%S",
"%Y-%m-%d %H:%M:%S",
"%d.%m.%Y %H:%M"]
DEFAULT_DICT_SHARE = 70
SUPPORTED_FILE_TYPES = ['xls', 'xlsx', 'csv', 'xml', 'json', 'jsonl', 'yaml', 'tsv', 'sql', 'bson']
DEFAULT_OPTIONS = {'encoding' : 'utf8',
... |
#9. Elabore um programa para mostrar a sequência dos N primeiro números da série de Fibonacci:
#1 1 2 3 5 8 13 21 34 55 89 ....
#Sempre o próximo elemento é a soma dos dois anteriores, assim, no exemplo o próximo é 144.
ult = 0
num = 1
while num <= 144:
print(num)
ult, num = num, ult
num += ult
|
'''
This solution was submitted by Team: eyeCoders_UOP
during ACES Coders v8 2020
Team lead: Rusiru Thushara thusharakart@gmail.com
The solution runs in O(n)
'''
def getline():return [float(x) for x in input().strip().split(' ')]
c,e,n,s0 = getline()
arr, lst = [], []
m = c/s0
for i in range(int(n)):
x,s = ... |
# TODO: Make this a relative path
local_url = "/home/garrison/Code/blogengine/output"
remote_url = "http://www.example.com"
site_title = "My Vanilla Blog"
site_description = "The really cool blog in which I write about stuff"
copy_rst = False
disqus_shortname = "mydisqusshortname"
|
in_code = 'abcdefghijklmnopqrstuvwxyz'
out_code = '9128645!@#$%^&*()/.,;:~|[]'
code = str.maketrans(in_code, out_code)
print('this is encrypted!'.translate(code))
|
# Question:5
countNumber = input("Enter the string ")
print ("Original string is : " + countNumber)
res = len(countNumber.split())
print ("Number of words in string is : " + str(res))
|
class Solution:
def isValid(self, s: str) -> bool:
while '[]' in s or '()' in s or '{}' in s:
s = s.replace('[]','').replace('()','').replace('{}','')
return len(s) == 0
"""
time: 10 min
time: O(n)
space: O(n)
errors:
lower case values/keys
Have to use stack because 3 charactors open/c... |
class Solution:
def __init__(self):
self.result = None
def findMax(self, root):
if root == None:
return 0
# find max for left and right node
left = self.findMax(root.left)
right = self.findMax(root.right)
# can either go straight down i.e. from root... |
class DatasetVO:
def __init__(self):
self._id = None
self._name = ""
self._folder = ""
self._description = ""
self._data_type = ""
self._size = 0
self._count = 0
@property
def count(self):
return self._count
@count.setter
def count(se... |
valores = []
while True:
valores.append(int(input('Digite um valor: ')))
resp = str(input('Quer continuar? [S/N] '))
if resp in 'Nn':
break
print('-='*30)
print(f'Você digitou {len(valores)} elementos')
valores.sort(reverse=True)
print(f'Os valores em ordem decrescente são {valores} ')
if ... |
class TembaException(Exception):
def __str__(self):
return self.message
class TembaConnectionError(TembaException):
message = "Unable to connect to host"
class TembaBadRequestError(TembaException):
def __init__(self, errors):
self.errors = errors
def __str__(self):
msgs = []... |
DEFAULT_WINDOW_SIZE = 32
DEFAULT_THRESHOLD_MIN_BASIC = 45.39
DEFAULT_THRESHOLD_MAX_BASIC = 46.0
DEFAULT_THRESHOLD_MIN_ABS = 50.32
DEFAULT_THRESHOLD_MAX_ABS = 52.96
DEFAULT_THRESHOLD_MIN_WITHOUT_GC = 11.28
DEFAULT_THRESHOLD_MAX_WITHOUT_GC = 11.42
DEFAULT_MEAN_GC = 0.46354823199323626
DEFAULT_MAX_EVALUE = 0.00445
DEFAULT... |
# @desc Add a short description or instruction here. This will show up at the top of the exercise.
def function_name(parameter): # give your function a name and parameter(s)
# have it do stuff
return # what does it return? This will be what the user types when they predict the result.
def main():
... |
s = input()
g1 = {}
for i in range(1, len(s)):
g1[s[i-1: i+1]] = g1.get(s[i-1: i+1], 0) + 1
s = input()
g2 = set()
for i in range(1, len(s)):
g2.add(s[i-1: i+1])
print(sum([g1[g] for g in frozenset(g1.keys()) & g2]))
|
"""Defines LidarObject class.
----------------------------------------------------------------------------------------------------------
This file is part of Sim-ATAV project and licensed under MIT license.
Copyright (c) 2018 Cumhur Erkan Tuncali, Georgios Fainekos, Danil Prokhorov, Hisahiro Ito, James Kapinski.
For qu... |
# Code Demo for 13 Lecture
# Working with Python Strings
# CIS 135 - Code Demo File
# Lecture example showing string contatenation
firstName = "Peter"
lastName = "Parker"
print("\nString Contcatenation in Pyton uses the + operator")
print(f'First Name = {firstName}')
print(f'Last Name = {lastName}')
print(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/10/17 21:35
# @Author : jacson
# @FileName: file_from_pycharm.py
print("hello world!!!") |
def percentual(qtde, total):
return (100 * qtde) / total
n = int(input())
c = r = s = 0
for i in range(n):
val, tipo = input().split()
qtde = int(val)
if tipo == 'C':
c += qtde
if tipo == 'R':
r += qtde
if tipo == 'S':
s += qtde
total = c + r + s
print('Total: {} c... |
# See: http://django-suit.readthedocs.org/en/develop/
SUIT_CONFIG = {
# header
'ADMIN_NAME': 'Augeo',
# 'HEADER_DATE_FORMAT': 'l, j. F Y',
# 'HEADER_TIME_FORMAT': 'H:i',
} |
def convert(my_str):
my_list = list(my_str.split(' '))
return my_list
values = {}
times = {}
weights = {}
ids = []
f = open('crime_scene.txt')
my_lines = f.readlines()
stripped_lines = [line.strip() for line in my_lines]
f.close()
N = int(stripped_lines[1])
w = int(convert(stripped_lines[0])[0])... |
class Command:
def exec(self, ob):
met = getattr(self, "on"+type(ob).__name__)
return met(ob)
def onNode(self, a):
pass
def onConnection(self, a):
pass
def onGenome(self, a):
pass
|
__all__ = ['interpolation_slicing_default_param']
def interpolation_slicing_default_param(key):
""" Returns the default parameters with the specified key. """
if key in default_parameters:
return default_parameters[key]
else:
raise ValueError('The parameter with key : ' + str(key) +
... |
FILTER_ACTION_ON_CHOICES = (
('entry', 'On Entry'),
('exit', 'On Exit'),
)
FILTER_ACTION_TYPE_CHOICES = (
('eml', 'Send Email Notification'),
('sms', 'Send SMS Notification'),
('slk', 'Send Slack Notification'),
('cus', 'Custom Action'),
('drv', 'Derive Stream Action'),
('rpt', 'Report... |
# countup.py
# http://asu-compmethodsphysics-phy494.github.io/ASU-PHY494//2017/01/19/03_Introduction_to_Python_2/#the-while-loop
tmax = 10.
t, dt = 0, 2.
while t <= tmax:
print("time " + str(t))
t += dt
print("Finished")
|
wordList = ['quail']
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase str... |
def func1():
"""
## Create a QA Task
To reach the tasks and assignments repositories go to <a href="https://sdk-docs.dataloop.ai/en/latest/repositories.html#module-dtlpy.repositories.tasks" target="_blank">tasks</a> and <a href="https://sdk-docs.dataloop.ai/en/latest/repositories.html#module-dtlpy.reposito... |
# https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/
# Easy (47.22%)
# Total Accepted: 2,951
# Total Submissions: 6,250
# beats 100.0% of python submissions
class Solution(object):
def canThreePartsEqualSum(self, A):
"""
:type A: List[int]
:rtype: bool
... |
'''
Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Created on Apr 9, 2014
@author: dfleck
'''
class MessageCache(list):
'''
Holds a list of tuples (envelope, message)
'''
def __contains__(self, otherEnvelope):
#print("\... |
class Request:
def __init__(self):
self.timeout = 5000
def get_params(self):
return {}
def get_body(self):
return {}
|
a = ['a', 'b', 'c', 'd']
print("This is a list", a)
print("It is", len(a), "elements length.")
print("Let's check if element 'd' is in the list:", 'd' in a)
print("This should be the maximun value of the list", max(a))
print("This should be the minnimun value of the list", min(a))
print("This is a list, item ... |
# Verifica palíndromo
# Faça uma função que recebe uma string e retorna True se ela for um palíndromo (é a mesma de trás para frente), ou False caso contrário. Por exemplo, a string 'roma é amor' é um palíndromo.
# Use fatiamento.
# Desafio 1: dá para fazer essa função com apenas 2 linhas de código.
# Desafio 2: resolv... |
def soft_update_network(target, source, tau):
for target_param, source_param in zip(target.parameters(), source.parameters()):
target_param.data.copy_(
target_param.data * (1 - tau) + source_param.data * tau
)
def hard_update_network(target, source):
target.load_state_dict(source.... |
class PropertyError(Exception):
"""Represents game property error."""
pass
|
words = {
'i': 520,
'am': 100,
'batman': 20,
'hello': 100
}
# iterate over keys
# for key in words.keys():
# print(key)
# for key in words:
# print(key)
# iterate over values
# words_keys = words.keys()
# print(words_keys)
# words_values = words.values()
# print(words_values)
# for value i... |
SECRET = "very secret key"
DEBUG = False
LOG_FILE = "log"
LOG_FORMAT = '''
Message type: %(levelname)s
Location: %(pathname)s:%(lineno)d
Module: %(module)s
Function: %(funcName)s
Time: %(asctime)s
Message:
%(message)s
'''
SENDGRID_APIKEY = "BLAABLAA"
RECEIPTS_FOL... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
50个话题
9章
1.课程简介
2.数据结构相关话题
3.迭代器与生成器相关话题
4.字符串处理相关话题
5.文件I/O操作相关话题
6.数据编码与处理相关话题
7.类与对象相关话题
8.多线程与多进程相关话题
9.装饰器相关话题
"""
"""
第1章 课程简介
1-1 课程简介
1-2 在线编码工具WebIDE使用指南
第2章 数据结构与算法进阶训练
2-1 如何在列表, 字典, 集合中根据条件筛选数据
2-2 如何为元组中的每个元素命名, 提高程序可读性
2-3 如何统计序列中元... |
"""
Algoritmos de PCS3110 em Python
Módulo 3 - Análise de algoritmo e ordenação
"""
class MaxHeap:
""" Implementação de um max-heap.
"""
def __init__(self, lista = None):
if lista == None:
self.lista = []
else:
self.lista = lista
self.heap_size = len(self.lis... |
CONTAINERS_DISCOVERY_LOCK_KEY = 'containers_discovery.lock'
CONTAINERS_DISCOVERY_LAST_UPDATE_KEY = 'containers_discovery.last_update'
CONTAINERS_DISCOVERY_DATA_KEY = 'containers_discovery.data'
RESOURCES_DISCOVERY_LOCK_KEY = 'resources_discovery.lock'
RESOURCES_DISCOVERY_LAST_UPDATE_KEY = 'resources_discovery.last_upd... |
def assert_revision(revision, author=None, message=None):
"""Asserts values of the given fields in the provided revision.
:param revision: The revision to validate
:param author: that must be present in the ``revision``
:param message: message substring that must be present in ``revision``
"""
... |
class ScraperFactoryException(Exception):
pass
class SpiderNotFoundError(ScraperFactoryException):
pass
class InvalidUrlError(ScraperFactoryException):
pass
|
"""Functions for calculating biomass from TCH of canopy height models"""
def longo2016_acd(top_of_canopy_height: float) -> float:
"""
Convert `top_of_canopy_height` (tch) to biomass according to
the formula in Longo et al. 2016.
Source:
https://agupubs.onlinelibrary.wiley.com/action/downloadS... |
class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
sorted_score = sorted(score,reverse=True)
rankings = {}
for i in range(len(sorted_score)):
if i == 0: rankings[sorted_score[i]] = 'Gold Medal'
elif i == 1: rankings[sorted_score[i]] = 'Silver ... |
""" Utility routines for handling control file contents."""
def cfg_string_to_list(input_string):
""" Convert a string containing items separated by commas into a list."""
if "," in input_string:
output_list = input_string.split(",")
else:
output_list = [input_string]
return output_list |
for j in range(1, 9):
for i in range(1,j+1):
print("%d * %d = %d" % (i,j,i*j),end="\t")
print()
|
# Relationship instance name
JSON_RELATIONSHIP_INTERACT_WITH = "interaction"
JSON_RUN_TIME = "runtime"
JSON_DEPLOYMENT_TIME = "deploymenttime"
JSON_NODE_DATABASE = "datastore"
JSON_NODE_SERVICE= "service"
JSON_NODE_MESSAGE_BROKER = "messagebroker"
JSON_NODE_MESSAGE_ROUTER = "messagerouter"
JSON_NODE_MESSAGE_ROUTER_KS... |
""" Sorting algorithms """
def insert_sort(list_num):
""" Insertion sort
Start from second element
Save it alongside with it's index
Run from previous element to first one
While checking if value should be moved
In the end, put saved value after last moved index
... |
kilometer = float(input('Digite quantos KM você irá percorrer: '))
price_gas = float(input('Digite o preço da gasolina na sua região: R$'))
cars_consumption = [5, 6, 7, 8, 9, 10, 11, 12, 13]
for i in range(9):
total = (kilometer/cars_consumption[i])*price_gas
print(f'Se seu carro tem a autonomia de {cars_con... |
'''
06 - Binning data
When the data on the x axis is a continuous value, it can
be useful to break it into different bins in order to get
a better visualization of the changes in the data.
For this exercise, we will look at the relationship between
tuition and the Undergraduate population abbreviated as UG in ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.