content stringlengths 7 1.05M |
|---|
def route_login_required():
"""
Decorates a function to indicate the requirement for a logged-in session.
:return: The decorated function.
"""
def decorator(fn):
fn.route_login_required = True
return fn
return decorator
def is_route_login_required(fn):
"""
Determine i... |
#
# @lc app=leetcode id=741 lang=python3
#
# [741] Cherry Pickup
#
# @lc code=start
class Solution:
def cherryPickup(self, grid: List[List[int]]) -> int:
if grid[-1][-1] == -1: return 0
# set up cache
self.grid = grid
self.memo = {}
self.N = len(grid)
... |
class BaseDatasetFactory:
def get_dataset(self, data, postprocessors=None, **kwargs):
raise NotImplementedError
def get_label_mapper(self, data=None, postprocessors=None, **kwargs):
raise NotImplementedError
def get_scorers(self):
raise NotImplementedError
|
def main():
# input
N = int(input())
# compute
l_0, l_1 = 2, 1
if N == 1:
print(l_1)
else:
for _ in range(N-1):
l_i = l_0 + l_1
l_0, l_1 = l_1, l_i
print(l_i)
# output
if __name__ == '__main__':
main()
|
{
"id": "ac256b",
"title": "Some Small Useful Features of GitHub Actions",
"date": "2021-05-18",
"tags": ['github', 'QuTiP'],
}
|
USA = [
'%b %d %Y',
'%b %-d %Y',
'%b %d, %Y',
'%b %-d, %Y',
'%B %d, %Y',
'%B %-d, %Y',
'%B %d %Y',
'%B %-d %Y',
'%m/%d/%Y',
'%m/%-d/%Y',
'%m/%d/%y',
'%m/%-d/%y',
'%o of %B, %Y',
'%B %o, %Y'
]
EU = [
'%b %d %Y',
'%b %-d %Y',
'%b %d, %Y',
'%b %-d, %... |
def count_inversions(arr):
start_index = 0
end_index = len(arr) - 1
output = inversion_count_func(arr, start_index, end_index)
return output
def inversion_count_func(arr, start_index, end_index):
if start_index >= end_index:
return 0
mid_index = start_index + (end_index - start_index)... |
# -*- coding: utf-8 -*-
"""
Vendored versions of required libraries.
"""
|
# 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 writing, software
# distributed under the... |
print('Vamos analisar três números inteiros de sua preferência!')
n1 = int(input('1º número: '))
n2 = int(input('2º número: '))
n3 = int(input('3º número: '))
lista = [n1, n2, n3]
lista.sort()
print('O menor número digitado foi {}, enquanto o maior foi {}.'.format(lista[0], lista[2]))
|
"""convert pretrained models"""
def key_transformation(old_key):
# print(old_key)
if '.' in old_key:
a, b = old_key.split('.', 1)
if a == "cnn":
return f"body.{b}"
return old_key
# body.0.weight", "cnn.1.weight
rename_state_dict_keys(e['NoRoIPoolModel'].path/'models'/'bestm... |
# string = str(input())
# str1 = str(input())
# str2 = str(input())
# print(string.replace(str1,str2))
#num = int(input())
row =1;ct=1
for ctr in range(int(input())):
for ctr1 in range(row):
print(ct,end=' ')
ct +=1
row +=1
print("\n")
|
filename = "ch10\programming.txt"
with open(filename, 'w') as file_object:
file_object.write("I love programming.\n")
file_object.write("I want to be a great programmer.\n")
#Concatenando novas informações (append)
with open(filename, 'a') as file_object:
file_object.write("May i construct some career and... |
def MakeClass(impF: dict):
class X:
RawFunctions = impF
GeneratedFunctions = dict()
def __init__(self):
self.x = 1
return
def cc(self, name) -> callable:
if name in X.GeneratedFunctions:
return X.GeneratedFunctions[name]
... |
# Auto-generated file (see get_api_items.py)
def get_mapped_items():
mapped_wiki_inline_code = dict()
mapped_wiki_inline_code['*emscripten_get_preloaded_image_data'] = ':c:func:`*emscripten_get_preloaded_image_data`'
mapped_wiki_inline_code['*emscripten_get_preloaded_image_data()'] = ':c:func:`*emscripten... |
# 模拟请求头
HEADERS = {'Host': 'wx.qq.com', 'Referer': 'https://wx.qq.com/?&lang=zh_CN', 'Origin': 'https://wx.qq.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3534.4 Safari/537.36'}
UUID_URL = 'https://login.wx.qq.com/jslogin?appid=wx782c26e4c19acf... |
# strings
message = 'hi, how are you?'
# integer
# number = 776765757
# print(number)
# print(type(number))
a = 'hello'
# print(type(a))
# print(a)
# floating
pi = 3.14
e = 2.71828
a = 10.0
# print(type(a))
# print(a)
# boolean (1/0 True/False)
isBooked = False
has_passed_exam = True
print(has_passed_exam)
print(t... |
class my_Pow_Three:
def __init__(self, mymax = 0):
self.mymax = mymax
def __iter__(self):
self.num = 0
return self
def __next__(self):
if self.num > self.mymax:
raise StopIteration
myresult = 3 ** self.num
self.num += 1
ret... |
x,y=map(int,input().split())
a=[];r=''
for _ in range(x):
a.append(list(input()))
for k in range(y):
for _ in range(x):
for i in range(x-1):
t=a[i][k];z=a[i+1][k]
if t=='o' and z=='.':
a[i][k]=z
a[i+1][k]=t
for i in range(x):
for j in range(y):... |
EXTERNAL_DATA_FILE = "../data/external/basketball.sqlite"
RAW_DATA_OUTPUT = "../data/raw/"
RAW_DATA_FILE = "../data/raw/plays_total.csv"
INTERIM_DATA_OUTPUT = "../data/interim/"
PROCESSED_DATA_OUTPUT = "../data/processed/"
TRAINING_FILE = "../data/processed/train_proc_labeled_folds.csv"
TESTING_FILE = "../data/pr... |
gb = GearsBuilder("StreamReader")
gb.foreach(
lambda x: execute("HMSET", x["id"], *sum([[k, v] for k, v in x.items()], []))
) # write to Redis Hash
gb.register("mystream")
|
device = "cpu"
teacher_forcing_ratio = 1.0
clip = 50.0
learning_rate = 0.0001
decoder_learning_ratio = 5.0
n_iteration = 5000
print_every = 1
save_every = 500
model_name = 'cb_model'
hidden_size = 500
encoder_n_layers = 2
decoder_n_layers = 2
dropout = 0.1
batch_size = 64
|
# print(1)
# print(2)
# print(3)
# print(4)
# print(5)
# contador = 1
# print(contador)
# while contador < 1000:
# contador = contador + 1
# contador += 1 # con esta linea estamos diciendo que contador es igual a contador + 1, igual a la linea que tenemos arriba
# print(contador)
# a = list(range(1000... |
# Question 7
# Level 2
#
# Question:
# Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j.
# Example
# Suppose the following inputs are given to the program:
# 3,5
# Then, the output of the program should b... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
... |
# Databricks notebook source
# MAGIC %md-sandbox
# MAGIC
# MAGIC <div style="text-align: center; line-height: 0; padding-top: 9px;">
# MAGIC <img src="https://databricks.com/wp-content/uploads/2018/03/db-academy-rgb-1200px.png" alt="Databricks Learning" style="width: 600px">
# MAGIC </div>
# COMMAND ----------
# M... |
'''
Basic operation with Python
Pierre Baudin
2018-10-16
'''
# define list
student_names = ['James', 'Kat', 'Jess', 'Mark', 'Bort', 'Frank Grimes', 'Max Power', 'Homer']
for name in student_names:
if name == 'Bort':
print("Found him!\n" + name)
break
print("Currently testing " + name)
# Dict... |
class Nikola:
__Nikola = "Николай"
def __init__(self, name, age):
self.age = age
if not name.upper() == "НИКОЛАЙ":
self.name = f"Я не {name}, я - Император и самодержец Всеройскийский Николай II"
else:
self.name = "Николай"
Petya = Nikola("Петя", 19)
print(Petya... |
# 1295. Find Numbers with Even Number of Digits
def findNumbers(self, nums):
"""
:type nums: List[int]
:rtype: int
61% fast
46% less mem
"""
count = 0
for num in nums:
if(len(str(num))%2 == 0):
count +=1
... |
"""
Function get_list()
Takes a list of dictionaries as an argument and returns a list of all the unique dictionaries in the input list.
"""
def get_list(dictionary_list):
unique_list = []
for dictionary in dictionary_list:
if dictionary not in unique_list:
unique_list.append(dictionary)
... |
name = "br_loterias"
__version__ = "0.0.1"
|
'''
Probem Task : This program will find volume of inner sphere
Problem Link : https://edabit.com/challenge/iBqJcagS56wmDpe4x
'''
def vol_shell(r1, r2): # function for finding volume
pi = 3.1415926536
if r1 < r2: # Checking is r1 is greater than r2, if r1 is less than r2, if case works
r1, r2 ... |
'''
Created on 17 Jul 2015
@author: philipkershaw
'''
def keyword_parser(obj, prefix='', **kw):
'''Parse config items delimited by dots into corresponding objects and
members variables
'''
for param_name, val in list(kw.items()):
if prefix:
_param_name = param_name.rsplit(prefix)[-... |
T = int(input())
for t in range(T):
skipBlank = input()
N = int(input())
sum = 0
for n in range(N):
sum+= int(input())
if (sum % N == 0):
print("YES")
else:
print("NO") |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 ... |
class StatisticsCollector:
def __init__(self, collectors: list, report_interval):
self.collectors = collectors
self.report_interval = report_interval
def add_result(self, server_time, client_time, bytes_received):
for collector in self.collectors:
collector.add_result(server... |
#
# Este arquivo é parte do programa multi_agenda
#
# Esta obra está licenciada com uma
# Licença Creative Commons Atribuição 4.0 Internacional.
# (CC BY 4.0 Internacional)
#
# Para ver uma cópia da licença, visite
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# WELLINGTON SAMPAIO - wsampaio@yahoo.com
#... |
n = int(input())
for i in range(n):
print('+___', end=' ')
print()
for i in range(n):
print(f'|{i + 1} /', end=' ')
print()
for i in range(n):
print('|__\\', end=' ')
print()
for i in range(n):
print('| ', end=' ')
print()
|
# write your solution here
sentence = input("Write text: ")
check_list = []
with open("wordlist.txt") as new_file:
for line in new_file:
line = line.replace("\n", "")
check_list.append(line)
text = ""
word_list = sentence.split()
#print(word_list)
for word in word_list:
lcs_word = wo... |
def convert(base_10_number, new_base):
convert_string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if base_10_number < new_base:
return convert_string[base_10_number]
else:
return convert(base_10_number // new_base, new_base) + convert_string[base_10_number % new_base]
print(convert(10... |
x = 10 > 15
y = 15 > 10
print(x and y)
print(x or y)
print(not (x and y))
|
# -*- coding: utf-8 -*-
"""
pyltsv.benchmark.ltsv
~~~~~~~~~~~~~~~~~~~~~
Python script implementation.
:copyright: (c) 2013 Shinya Ohyanagi, All rights reserved.
:license: BSD, see LICENSE for more details.
"""
def parse_line(string):
line = string.decode('utf-8').rstrip()
return dict([x... |
class Featurizer():
"""Class used to extract features from objects."""
def extract_raw_features(self, astronomical_object):
"""Extract raw features from an object
Featurizing is slow, so the idea here is to extract a lot of different
things, and then in `select_features` these features ... |
def if_none_this(list, index, substitute):
"""Return *substitute* if *list* is None else returns *list[index]*
(NVL type function)"""
if list is None:
return substitute
else:
return list[index] |
############################################################################
#
# Copyright (c) Mamba Developers. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
############################################################################
class Em... |
#!/usr/bin/python3
age = int(input("请输入你家狗狗的年龄: "))
print("")
if age < 0:
print("傻逼,不对")
elif age == 1:
print("相当于12岁的人")
elif age == 2:
print("aaaa")
elif age > 2:
human = 22 + (age - 2) * 5
print("对应人类",human)
else:
print("adadfa")
### 退出提示
input("点击 enter 键退出")
##!/usr/bin/python3
#
#age = int(in... |
# -*- coding: utf-8 -*-
class Calculator(object):
"""
四則演算を行う。
"""
@staticmethod
def addition(x, y):
"""
加算を行う。
:param x: 左辺
:param y: 右辺
:return: 計算結果
"""
result = x + y
return result
@staticmethod
def subtraction(x, y):
... |
"""
35. Encontrar números primos é uma tarefa difícil. Faça um programa que gera uma
lista dos números primos existentes entre 1 e um número inteiro informado pelo
usuário.
"""
numero = int(input("Informe um número: "))
tot = 0
div = 0
for j in range(1, numero + 1):
tot = 0
div = 0
for c in range(1, nu... |
'''
Description:
Given a balanced parentheses string S, compute the score of the string based on the following rule:
() has score 1
AB has score A + B, where A and B are balanced parentheses strings.
(A) has score 2 * A, where A is a balanced parentheses string.
Example 1:
Input: "()"
Output: 1
Example 2:
In... |
owlfile = open("blob.owl")
parsed_owlfile = open("a.owl","w")
weinclass=0
for line in owlfile:
parsed_owlfile.write(line)
if line.strip()[0:10]=="<owl:Class":
weinclass=1
if line.strip()[6:11]=="label" and weinclass==1:
parsed_owlfile.write(' <oboInOwl:inSubset rdf:resour... |
def pars2dict(init_file):
""" It reads parameters `init_file` and returns a dictionary """
init_dict = {}
with open(init_file) as f:
lines = f.readlines()
for line in lines:
# if the line start with #, it is a comment
if line[0] == "#":
continue
... |
def part_one(input):
return sum([max_difference(line) for line in parse(input)])
def max_difference(numbers):
return max(numbers) - min(numbers)
def parse(input):
return [to_number_list(line) for line in input.splitlines()]
def to_number_list(string):
return list(map(int, string.split()))
def pa... |
'''
Extracted from ZED-F9P - Interface Description, section 3
'''
UBX_CLASS = {
b"\x01": "NAV", # Navigation solution messages
b"\x02": "RXM", # Status from the receiver manager
b"\x27": "SEC", # Security features of the receiver
} |
# 3.13 Convert the following code to an if-elif-else statement:
number = 4
if number == 1:
print('One')
else:
if number == 2:
print('Two')
else:
if number == 3:
print('Three')
else:
print('Unkown')
# ANSWER
if number == 1:
print('One')
elif number == 2:
... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.13.7
# kernelspec:
# display_name: Python [conda env:idp_bandit]
# language: python
# name: conda-env-idp_... |
'''
Problem
Someone just won the Code Jam lottery, and we owe them N jamcoins! However, when we tried to print out an oversized check, we encountered a problem. The value of N, which is an integer, includes at least one digit that is a 4... and the 4 key on the keyboard of our oversized check printer is broken.
Fortun... |
seller_name = str(input())
salary = float(input())
sales_made = float(input())
bonus = sales_made * 15 / 100
total_salary = salary + bonus
print("TOTAL = R$ {:.2f}".format(total_salary))
|
class Solution:
def reverse(self, x: int) -> int:
MAX = 2 ** 31 - 1
MIN = -(2 ** 31)
rev = 0
abs_x = abs(x)
while abs_x != 0:
pop = abs_x % 10
abs_x //= 10
if rev > MAX / 10 or rev < MIN / 10:
return 0
rev = rev ... |
# Copyright 2019 Erik Maciejewski
#
# 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 write_ts(ts,fname,dateformat="%Y-%m-%d %H:%M",fmt="%.2f",header=None,sep=','):
""" Estimate missing values within a time series by interpolation.
Parameters
----------
ts: :class:`~vtools.data.timeseries.TimeSeries`
The time series to be stored
fname: string
Output file name ... |
def getProtocol(url):
ret = url.split("://")
return ret[0]
def getDomain(url):
ret = url.split("://")
ret2 = ret[1].split("/")
full_domain = ret2[0]
sub_domain = getSubD(url)
if sub_domain is None:
return full_domain
else:
return full_domain.replace(sub_domain + ".", ""... |
"""
Simhash
Source: http://bibliographie-trac.ub.rub.de/browser/simhash.py
"""
# Implementation of Charikar simhashes in Python
# See: http://dsrg.mff.cuni.cz/~holub/sw/shash/#a1
class Simhash():
def __init__(self, tokens='', hashbits=128):
self.hashbits = hashbits
self.hash = self.simh... |
async def is_document_exists(collection, id):
"""Determine if a document with a specific id exist in a collection or not"""
return await collection.count_documents({'_id': id}, limit=1)
async def get_guild(guilds_collection, guild_id):
"""Get a guild from db."""
return await guilds_collection.find_one... |
D = DiGraph({
0: [1, 10, 19], 1: [8, 2], 2: [3, 6], 3: [19, 4],
4: [17, 5], 5: [6, 15], 6: [7], 7: [8, 14], 8: [9],
9: [10, 13], 10: [11], 11: [12, 18], 12: [16, 13],
13: [14], 14: [15], 15: [16], 16: [17], 17: [18],
18: [19], 19: []})
for u, v, l in D.edges():
D.set_edge_label(u, v, f'({u},{v})... |
URL = 'https://dogsearch.moag.gov.il/#/pages/pets'
ELEMENT_LIST = ['name', 'gender', 'breed', 'birthDate', 'owner', 'address', 'city', 'phone1', 'phone2',
'neutering', 'rabies-vaccine', 'rabies-vaccine-date', 'vet', 'viewReport', 'license',
'license-date-start', 'domain', 'license-latest... |
'''
Creating A function to group the sample based on the accession
split the sample name based on '-' and store it into variable called 'accession_group'
'''
def string_split (dataframe) :
column_name = list(dataframe)
sample_ID = column_name[0]
accession_group = []
for word in dataframe[sam... |
def solution(X, Y, A):
N = len(A)
result = -1
v = 0
k = 0
nX = 0
nY = 0
for i in range(N):
if A[i] == X:
nX += 1
if A[i] == Y:
nY += 1
#if nX == nY > 1:
#result = i
if nX == nY :
#v += 1
k = i
#return result
print(k... |
class Solution:
def isHappy(self, n: 'int') -> 'bool':
happies = set()
def powers(n):
result = 0
while n:
result += (n % 10) ** 2
n //= 10
return result
power = n
while True:
power = powers(power)
... |
megabytesMonthly = int(input())
megabyteCount = 0
months = int(input())
monthlyUsage = []
for every in range(months):
megabyteCount += megabytesMonthly
megabyteCount -= int(input())
print(megabyteCount + megabytesMonthly)
|
numero = int(input('Número: '))
print(f'{numero} x {1} = {numero * 1}')
print(f'{numero} x {2} = {numero * 2}')
print(f'{numero} x {3} = {numero * 3}')
print(f'{numero} x {4} = {numero * 4}')
print(f'{numero} x {5} = {numero * 5}')
print(f'{numero} x {6} = {numero * 6}')
print(f'{numero} x {7} = {numero * 7}')
print(f'... |
def safedivide(
numerator: float, denominator: float, valueonfailure: float = float("nan")
) -> float:
try:
return numerator / denominator
except ZeroDivisionError:
return valueonfailure
|
number = int(input("Enter number: "))
for num in range(1111, 9999 + 1):
is_special = True
for digit in str(num):
digit = int(digit)
if (digit == 0) or (number % digit !=0):
is_special = False
break
if is_special:
print(num) |
#!/usr/bin/python3
def shift(text):
return text[1:] + text[0]
t = input()
s = input()
found = False
for i in range(len(s)):
if t.find(s) != -1:
found = True
break
s = shift(s)
if found == True: print("yes")
else: print("no")
|
def grep(pattern):
print("Start coroutine")
try:
while True:
line = yield
if pattern in line:
print(line)
except GeneratorExit:
print("Stop coroutine")
def grep_python():
g = grep("Python")
yield from g
g = grep_python() # generator
next(g... |
""" Symlet 7 wavelet """
class Symlet7:
"""
Properties
----------
near symmetric, orthogonal, biorthogonal
All values are from http://wavelets.pybytes.com/wavelet/sym7/
"""
__name__ = "Symlet Wavelet 7"
__motherWaveletLength__ = 14 # length of the mother wavelet
__transformWavel... |
class Solution(object):
self.prev = None
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
if not root: return None
self.flatten(root.right)
self.flatten(root.left)
root.righ... |
class A:
def foo(self):
pass
async def bar(self):
pass
|
def clamp(floatnum, floatmin, floatmax):
if floatnum < floatmin:
floatnum = floatmin
if floatnum > floatmax:
floatnum = floatmax
return floatnum
def smootherstep(edge0, edge1, x):
# Scale, bias and saturate x to 0..1 range
x = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0)
# Ev... |
ar = [float(i) for i in input().split()]
ar_sq = []
for i in range(len(ar)):
ar_sq.append(ar[i]**2)
ar_sq = sorted(ar_sq)
print(ar_sq[0], end = ' ')
for i in range(1, len(ar_sq)):
if ar_sq[i] != ar_sq[i-1]:
print(ar_sq[i], end = ' ')
|
# https://docs.python.org/3/library/functions.html#open
# Obs: 'w+' cria um arquivo do zero
# Obs: 'a+' vai add mais coisas ao arquivo
# Obs: 'r' vai ler o arquivo
# Começo do codigo
# file = open('abc.txt', 'w+')
# file.write('linha 1\n')
# file.write('linha 2\n')
# file.write('linha 3\n')
#
# file.seek(0, 0) # Mos... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
################################################################################
# Copyright (c) 2019 University of Utah Student Computing Labs.
# All Rights Reserved.
#
# Author: Thackery Archuletta
# Creation Date: Oct 2018
# Last Updated: March 2019
#
# Permission to use, c... |
#
# PySNMP MIB module DISMAN-EXPRESSION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DISMAN-EXPRESSION-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:47:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
def floatToBin(valor):
f = str(valor)
inteira, deci = f.split(".")
print(inteira, deci)
bint = bin(int(inteira))
deci = list(deci)
deci.insert(0,'.')
print(bint)
print(deci)
# inteira
print('parte inteira')
if inteira.startswith("-"):
print('negativo')
if no... |
times_dict = {
"A": 51,
"B": 23,
"C": 67,
"D": 83,
"E": 77,
}
directions = {
0: "north",
1: "west",
2: "south",
3: "east",
}
for name in times_dict:
times = times_dict[name]
circles = times // 4
direction_index = times % 4
direction = directions[direction_index]
... |
def bstutil(root,min_v,max_v):
if root is None:
return True
if root.data>=min_v and root.data<max_v and bstutil(root.left,min_v,root.data) and bstutil(root.right,root.data,max_v):
return True
return False
def isBST(root):
return bstutil(root,-float("inf"),float("inf"))
|
class KMP(object):
def __init__(self, keyword):
'''
KMP 알고리즘 이니셜 함수로 string match에 사용될 keyword를 입력받고 Pi 배열을 생성
:param keyword: 패턴으로 사용될 키워드
'''
self.keyword = keyword
self.pi = self._generate_pi(keyword)
def __call__(self, text):
'''
String match를... |
class Scene(object):
MAIN = None
setup = False
destroyed = False
handles = []
handleFunc = {}
def __init__(self, MainObj):
self.MAIN = MainObj
self.createHandleFunctions()
def createHandleFunctions(self):
pass
def setUp(self):
self.setup = True
... |
class Solution:
def checkNeedle(self, h: str, n: str) -> bool:
if len(h) < len(n):
return False
for idx, hc in enumerate(h):
if hc != n[idx]:
return False
else:
if len(n) == idx + 1:
return True
... |
d = '\033[34mDesconsiderando o fleg\033[31m'
print(f'\033[31m{d:=^60}\033[31m')
s = i = 0
while True:
n = int(input('Digite um número [999 pra parar]: '))
if n == 999:
break
i += 1
s += n
print(f'\033[34mA soma dos {i} valores foi {s}!')
|
"""
@author: yuhao.he
@contact: <hawl.yuhao.he@gmail.com>
@version: 0.0.1
@file: __init__.py.py
@time: 2021/10/27 14:11
"""
|
__author__ = 'Michel Llorens'
__email__ = "mllorens@dcc.uchile.cl"
class Stack:
def __init__(self, delta):
self.stack = list()
self.DELTA = delta
return
def push(self, face):
self.stack.append(face)
return
def pop(self):
if not self.empty():
ret... |
def build_chrome_options():
chrome_options = webdriver.ChromeOptions()
chrome_options.accept_untrusted_certs = True
chrome_options.assume_untrusted_cert_issuer = True
# chrome configuration
# More: https://github.com/SeleniumHQ/docker-selenium/issues/89
# And: https://github.com/SeleniumHQ/docke... |
myset = {1,2,3,4,5,6}
print(myset)
myset = {1,1,1,2,3,4,5,5}
print(myset)
myset = set([1,2,3,4,5,5])
myset2 = set('hello')
print(myset)
print(myset2)
myset = {}
myset2 = set()
print(type(myset))
print(type(myset2))
myset2.add(1)
print(myset2)
myset2.add(1)
print(myset2)
myset2.add(2)
print(myset2)
myset2.add(3)
mys... |
CONFIG = {
'log': {
'level': 'DEBUG', # 与log库的level一致,包括DEBUG, INFO, ERROR
# DEBUG - Enable stdout, file, mail (如果在dest中启用)
# INFO - Enable file, mail (如果在dest中启用)
# ERROR - Enable mail (... |
# Reading files
# Example 1 - Open and closing files.
nerd_file = open("nerd_names.txt")
nerd_file.close()
# Example 2 - Is the file readable?
nerd_file = open("nerd_names.txt")
print(nerd_file.readable())
nerd_file.close()
# Example 3 - Read the file, with readlines()
nerd_file = open("nerd_names.txt")
print(nerd_f... |
# creates or updates a file with the given text
def write_file(file_path,text_to_write):
with open(file_path,'w') as f:
f.write(text_to_write)
return
|
class Card:
"""Standard playing card.
Attributes:
suit: string spades,hearts,diamonds,clubs
rank: string 1-10,jack,queen,king
"""
def __init__(self, rank, suit):
"""Initializes the object Card"""
self.rank = rank
self.suit = suit
def __repr__(self):
... |
""" 26 - Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra 'A', em que posição
ela aparece da primeira vez e em que posição ela aparece da última vez. """
frase = str(input('Digite uma frase a sua escolha: ')).strip().upper()
print(f"A letra A aparece {frase.count('A')} vezes na f... |
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
res = [[1 for j in range(i + 1)] for i in range(rowIndex + 1)]
for i in range(2, rowIndex + 1):
for j in range(1, i):
res[i][j] = res[i - 1][j... |
# caso queira testar os programas separadamente, adicione
# comentários de apóstofos simples ''' e ''' ENTRE um programa e outro.
# Exemplo abaixo:
'''
print('Programa X')
código
'''
print('Programa 01\n')
remedio = 'Dorflex'
dosagem = 5
duracao = 4.5
instrucoes = '{} - Tome {} ML pela boca a cada {} horas'.format... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.