content stringlengths 7 1.05M |
|---|
'''
This module defines the RentalException class, which handles all exception of the type RentalException.
it does not depend on any other module.
'''
class RentalException(Exception):
'''
RentalException class handles all thrown exceptions of the type RentalException. It inherits the Exception
... |
"""
handler.py
A two operands handler.
"""
class Handler():
def handle(self, expression):
operator = None
operand_1 = None
operand_2 = None
error = None
try:
tokens = expression.split(" ")
operator = tokens[1]
operand_1 = int(tokens[0])... |
def spd_pgs_limit_range(data, phi=None, theta=None, energy=None):
"""
Applies phi, theta, and energy limits to data structure(s) by
turning off the corresponding bin flags.
Input:
data: dict
Particle data structure
Parameters:
phi: np.ndarray
Minimum and ma... |
class Solution:
def XXX(self, x: int) -> int:
start = 0
end = x
while True:
mid = int((start + end) / 2)
if mid * mid <= x < (mid + 1) * (mid + 1):
return mid
if mid * mid > x: # 偏大
end = mid - 1
else:
... |
palavras = ('abacate', 'abacaxi', 'suco', 'melancia', 'limão', 'manga',
'pastel', 'pizza', 'chocolate', 'pao')
for i in palavras:
print(f'\nNa palavra {i.upper()} temos ', end='')
for letra in i:
if letra.lower() in 'aeiou':
print(letra, end=' ')
|
#O código a seguir percorre uma lista de nomes de carros em um laço e procura o valor 'bmw'. Sempre que o valor for 'bmw', ele será exibido com letras
#maiusculas, e não somente a inicial maiuscula.
requested_topping = ['mushrooms', 'extra cheese', 'green peppers']
if 'mushrooms' in requested_topping:
print('... |
class Loss(object):
def __init__(self):
self.output = 0
self.input = 0
def get_output(self, inp, target):
pass
def get_input_gradient(self, target):
pass
|
#Given two arrays, write a function to compute their intersection.
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
l=[]
for i in nums1:
if i in nums2:
l.append(i)
return list(set(l)) |
"""
Module for YamlTemplateFieldBuilder
"""
__author__ = 'DWI'
class TemplateReader(object):
"""
Class for reading complete Templates from files.
"""
def __init__(self, template_field_builder):
self.field_builder = template_field_builder
def read(self, file_name):
"""
Re... |
#!/user/bin/python
'''Compute the Edit Distance Between Two Strings
The edit-distance between two strings is the minimum number of operations
(insertions, deletions, and substitutions of symbols) to transform one string
into another
'''
# Uses python3
def edit_distance(s, t):
#D[i,0] = i
#D[0,j] = j
m ... |
class iron():
def __init__(self,name,kg):
self.kg = kg
self.name = name
def changeKg(self,newValue):
self.kg = newValue
def changeName(self,newName):
self.newName
|
def calculate_power(base, power):
if not power:
return 1
if not power % 2:
return calculate_power(base, power // 2) * calculate_power(base, power // 2)
else:
return calculate_power(base, power // 2) * calculate_power(base, power // 2) * base
if __name__ == "__main__":
a = int... |
class Node:
def __init__(self, data, nextNode=None):
self.data = data
self.next = nextNode
# find middle uses a slow pointer and fast pointer (1 ahead) to find the middle
# element of a singly linked list
def find_middle(self):
slow_pointer = self
fast_pointer = sel... |
def extract_cfg(cfg, prefix, sep='.'):
out = {}
for key,val in cfg.items():
if not key.startswith(prefix): continue
key = key[len(prefix)+len(sep):]
if sep in key or not key: continue
out[key] = val
return out
if __name__=="__main__":
cfg = {
'a.1':'aaa',
'a.2':'bbb',
'a.x.1':'ccc',
'a.x.2':'ddd',... |
'''
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
'''
# Definition for a binary ... |
# -*- coding: utf-8 -*-
def get_tokens(line):
"""tokenize an Epanet line (i.e. split words; stopping when ; encountered)"""
tokens=list()
words=line.split()
for word in words:
if word[:1] == ';':
break
else:
tokens.append(word)
return tokens
def read_epanet_file(fi... |
class SmMarket:
def __init__(self):
self.name = ""
self.product_dic = {}
def add_category(self, product):
self.product_dic[product.code] = product |
#project
print("welcome to the Band name generator")
city_name = input("Enter the city you were born: ")
pet_name = input("Enter your pet name: ")
print(f"your band name could be {city_name} {pet_name}")
#coding exercise(Print)
print("Day 1 - Python Print Function")
print("The function is declared like this:")... |
"""
signals we use to trigger regular batch jobs
"""
run_hourly_jobs = object()
run_daily_jobs = object()
run_weekly_jobs = object()
run_monthly_jobs = object()
|
num1=int(input("Enter first number :- "))
num2=int(input("Enter second number :- "))
print("Which opertation you want apply 1.add, 2.sub, 3.div")
op=input()
def add():
c=num1+num2
print("After Add",c)
def sub():
c=num1-num2
print("After sub",c)
def div():
c=num1/num2
print("After div",c)
def again... |
def get_odd_and_even_sets(n):
odd_nums = set()
even_nums = set()
for line in range(1, n + 1):
name = input()
name_ascii_sum = sum([ord(char) for char in name])
devised_num = name_ascii_sum // line
if devised_num % 2 == 0:
even_nums.add(devised_num)
else... |
# crie um algoritmo que leia um número e mostre
# o seu dobro, triplo e sua raiz quadrada.
num = int(input('Digite um número: '))
dobro = num * 2
triplo = num * 3
raizq = num ** (1/2)
print('O dobro de {} é igual a {}.'.format(num, dobro))
print('O triplo de {} é igual a {}.'.format(num, triplo))
print('A raiz quadra... |
class Debugger:
def __init__(self):
self.collectors = {}
def add_collector(self, collector):
self.collectors.update({collector.name: collector})
return self
def get_collector(self, name):
return self.collectors[name]
|
frutas = open('frutas.txt', 'r')
numeros = open('numeros.txt', 'r')
def copia_lista(lista:list)->list:
return lista.copy()
"""
if __name__ == "__main__":
lista_fruta_nueva=eliminar_un_caracter_de_toda_la_lista(lista_frutas,"\n")
print(lista_fruta_nueva)
""" |
users = [['896675','123','985'],['Gil','João', 'Maria']]
i = input('Digite sua senha: ')
while i not in users[0]:
i = str(input('Senha incorreta! \nDigite sua senha:'))
j = users[0].index(i)
name = users[1][j]
print('Acesso permitido. Bem-vindo %s' % (name))
|
# Only these modalities are available for query
ALLOWED_MODALITIES = ['bold', 'T1w', 'T2w']
STRUCTURAL_MODALITIES = ['T1w', 'T2w']
# Name of a subdirectory to hold fetched query results
FETCHED_DIR = 'fetched'
# Name of a subdirectory containing MRIQC group results used as inputs.
INPUTS_DIR = 'inputs'
# Name of the... |
"""
File IO
1.Create
-------------------
f = open('file_name.txt','w')
f.close()
-------------------
2.Write
-------------------
f = open('file_name.txt','w')
data = 'hi'
f.write(data)
f.close()
-------------------
3.Read
1) Readline
-------------------
f ... |
# Problem Statement: https://www.hackerrank.com/challenges/symmetric-difference/problem
_, M = int(input()), set(map(int, input().split()))
_, N = int(input()), set(map(int, input().split()))
print(*sorted(M ^ N), sep='\n') |
# The manage.py of the {{ project_name }} test project
# template context:
project_name = '{{ project_name }}'
project_directory = '{{ project_directory }}'
secret_key = '{{ secret_key }}'
|
class PaymentStrategy(object):
def get_payment_metadata(self,service_client):
pass
def get_price(self,service_client):
pass
|
#this program demonstrates several functions of the list class
x = [0.0, 3.0, 5.0, 2.5, 3.7]
print(type(x)) #prints datatype of x (list)
x.pop(2) #remove the 3rd element of x (5.0)
print(x)
x.remove(2.5) #remove the element 2.5 (index 2)
print(x)
x.append(1.2) #add a new element to the end (1.2... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 28 22:08:00 2017
@author: Roberto Piga
"""
s = 'azcbobobegghakl'
s = 'abcbcd'
subString = ""
maxString = ""
charval = ""
for char in s:
if char >= charval:
subString += char
elif char < charval:
subString = char
charval ... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
size = int(input())
nums = list(map(int, input().split()))
weights = list(map(int, input().split()))
weighted_sum = 0
for i in range(size):
weighted_sum += nums[i] * weights[i]
print(round(weighted_sum / sum(weights), 1))
|
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m = len(matrix)
n = len(matrix[0]) if m else 0
if m * n == 0:
return False
if target < matrix[0][0]... |
# Lower-level functionality for build config.
# The functions in this file might be referred by tensorflow.bzl. They have to
# be separate to avoid cyclic references.
WITH_XLA_SUPPORT = True
def tf_cuda_tests_tags():
return ["local"]
def tf_sycl_tests_tags():
return ["local"]
def tf_additional_plugin_deps():
... |
# Write a function that takes a string as input and reverse only the vowels of a string.
# Example 1:
# Input: "hello"
# Output: "holle"
# Example 2:
# Input: "leetcode"
# Output: "leotcede"
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
... |
def estimation(text,img_num):
len_text = len(text)
read_time = (len_text/1000) + img_num*0.2
if read_time < 1:
return 1
return round(read_time) |
numbers = [10, 20, 300, 40, 50]
# random indexing --> O(1) get items if we know the index !!!
print(numbers[4])
# it can store different data types
# numbers[1] = "Adam"
# iteration methods
# for i in range(len(numbers)):
# print(numbers[i])
# for num in numbers:
# print(num)
# remove last two items
print... |
''' Example of python control structures '''
a = 5
b = int(input("Enter an integer: "))
# If-then-else statment
if a < b:
print('{} is less than {}'.format(a,b))
elif a > b:
print('{} is greater than {}'.format(a,b))
else:
print('{} is equal to {}'.format(a,b))
# While loop
ii = 0
print("While loop:")
w... |
"""
Calculating the mean
"""
def calculate_mean(numbers):
s=sum(numbers)
N=len(numbers)
mean=s/N
return mean
def main():
donations=[100,60,70,900,100,200,500,500,503,600,1000,1200]
mean=calculate_mean(donations)
N=len(donations)
print("Mean donation over the last {0} days is {1}".forma... |
##############################################################################################################################################################################################
#
# ┌────────────────────────┐
# │ Experiment Memory Recovery v1.2 │
# │ Author: Christopher A Varnon ... |
'''
Created on Apr 2, 2021
@author: mballance
'''
class InitializeReq(object):
def __init__(self):
self.module = None
self.entry = None
def dump(self):
pass
@staticmethod
def load(msg) -> 'InitializeReq':
ret = InitializeReq()
if "module"... |
# 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 isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
ans = True
def tra... |
input = [
input(),
]
def ceil(number: int) -> int:
return int(number) + 1 if number % 2 else 0
def get_possible_ways_amount(board_width: int, board_height: int) -> int:
"""
Функция находит количество способов пройти через доску, из левой нижней клетки доски до правой верхней
:param board_width: ... |
'''Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:'''
x = y = z = "Orange"
print(x)
print(y)
print(z) |
sisend=input("Sisestage failinimi: ")
haali={}
parim={}
f=open(sisend, encoding="UTF-8")
f.readline()
for rida in f:
erakond, haaled, nr, nimi=rida.split(",")
if erakond not in haali or int(haaled)>haali[erakond]:
haali[erakond]=int(haaled)
parim[erakond]=nimi.strip()
f.close()
... |
#
# @lc app=leetcode id=795 lang=python3
#
# [795] Number of Subarrays with Bounded Maximum
#
# https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/description/
#
# algorithms
# Medium (48.43%)
# Likes: 1143
# Dislikes: 78
# Total Accepted: 40.2K
# Total Submissions: 77.7K
# Testcase Example: ... |
SYMBOLS = {',', '?', '!', ':', '\'', '"', '(', ')', ';', '@', '^', '^', '&', '&', '$', '$', '£',
'[', ']', '{', '}', '<', '>', '+', '-', "*", "#", "%", "=", "~", '/', "_"}
PREP = {'about', 'above', 'across', 'after', 'against', 'aka', 'along', 'and', 'anti', 'apart', 'around', 'as',
'astride', 'at'... |
class Human:
def __init__(self, xref_id):
self.xref_id = xref_id
self.name = None
self.father = None
self.mother = None
self.pos = None
def __repr__(self):
return "[ {} : {} - {} {} - {} ]".format(
self.xref_id,
self.name,
self... |
class Cell:
def __init__(self, row, col):
self.row = row
self.col = col
self.links = []
self.north = None
self.south = None
self.east = None
self.west = None
def neighbors(self):
n = []
self.north and n.append(self.north)
self.so... |
class Notifier(object):
def notify(self, title, message, retry_forever=False):
raise NotImplementedError()
def _resolve_params(self, title, message):
if callable(title):
title = title()
if callable(message):
message = message()
return title, message
|
n = int(input())
c=0
for _ in range(n):
p, q = list(map(int, input().split()))
if q-p >=2:
c= c+1
print(c)
|
class Solution:
def smallestRangeI(self, nums: List[int], k: int) -> int:
minNum,maxNum = min(nums),max(nums)
if maxNum-minNum>=2*k:
return maxNum-minNum-2*k
else:
return 0 |
class Base:
""" This is a class template. All the other classes will be made according to this templae """
def __init__(self) -> None:
""" constructor function """
pass
def enter(self, **param) -> None:
""" This function is called first when we change a group """
pa... |
# Q7: What is the time complexity of
# i = 1, 2, 4, 8, 16, ..., 2^k
# El bucle termina para: i >= n
# 2^k = n
# k = log_2(n)
# O(log_2(n))
# Algoritmo
# for (i = 1; i < n; i = i*2) {
# statement;
# }
i = 1
n = 10
while i < n:
print(i)
i = i*2 |
# https://www.programiz.com/python-programming/function-argument
# Python allows functions to be called using keyword arguments. When we call
# functions in this way, the order (position) of the arguments can be changed.
# As we can see, we can mix positional arguments with keyword arguments during
# a function call. ... |
"""
Topological Sort
"""
class Solution(object):
def alienOrder(self, words):
#return true if cycles are detected.
def dfs(c):
if c in path: return True
if c in visited: return False
path.add(c)
for nei in adj[c]:
if dfs(nei): return Tr... |
code_map = {
"YEAR": "year",
"MALE": "male population",
"FEMALE": "female population",
"M_MALE": "matable male population",
"M_FEMALE": "matable female population",
"C_PROB": "concieving probability",
"M_AGE_START": "starting age of mating",
"M_AGE_END": "ending age of mating",
"MX_A... |
txt = "I like bananas"
x = txt.replace("bananas", "mangoes")
print(x)
txt = "one one was a race horse and two two was one too."
x = txt.replace("one", "three")
print(x)
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three", 1)
print(x)
txt = "For only {price:.2f} dollars!"... |
def partition_labels(string):
#
"""
"""
indices = {}
for i, char in enumerate(string):
indices[char] = i
result = []
left, right = -1, -1
for i, char in enumerate(string):
right = max(right, indices[char])
if i == right:
result.append(right - le... |
class Solution(object):
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_index = -1
second_max_value = -1
for i in range(len(nums)):
if i == 0:
max_index = i
continue
value = n... |
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
# 0 -> 0 status = 0
# 1 -> 1 status = 1
# 1 -> 0 status = 2
# 0 -> 1 status = 3
m, n = len(board), len(board[0])
directions = [(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]
for x in... |
def calc(x,y,ops):
if ops not in "+-*/":
return "only +-*/!!!!!"
if ops=="+":
return (str(x) +""+ ops +str(y)+"="+str(x+y))
elif ops=="-":
return (str(x) +""+ ops +str(y)+"="+str(x-y))
elif ops == "*":
return (str(x) + "" + ops + str(y) + "=" + str(x * y))
elif ops ==... |
n = int(input())
length = 0
while True:
length += 1
n //= 10
if n == 0:
break
print('Length is', length)
|
''' '+' Plus Operator shows polymorphism. It is overloaded to perform multiple things, so we can call it polymorphic. '''
x = 10
y = 20
print(x+y)
s1 = 'Hello'
s2 = " How are you?"
print(s1+s2)
l1 = [1,2,3]
l2 = [4,5,6]
print(l1+l2)
|
# Exercício Python 38: Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, o programa deverá perguntar se o usuário quer ou não continuar. No final, mostre:
#A) quantas pessoas tem mais de 18 anos.
#B) quantos homens foram cadastrados.
#C) quantas mulheres tem menos de 20 anos.
prin... |
people = 50 #defines the people variable
cars = 10 #defines the cars variable
trucks = 35 #defines the trucks variable
if cars > people or trucks < cars: #sets up the first branch
print("We should take the cars.") #print that runs if the if above is true
elif cars < people: #sets up second branch that runs if the... |
DESEncryptParam = "key(16 Hex Chars), Number of rounds"
INITIAL_PERMUTATION = [58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, ... |
# pylint: disable-all
"""Test inputs for day 2"""
test_position: str = """forward 5
down 5
forward 8
up 3
down 8
forward 2"""
test_position_answer: int = 150
test_position_answer_day_two: int = 900
|
input = """
a :- b.
b | c.
d.
:- d, a.
"""
output = """
a :- b.
b | c.
d.
:- d, a.
"""
|
class WikipediaKnowledge:
@staticmethod
def all_wikipedia_language_codes_order_by_importance():
# list from https://meta.wikimedia.org/wiki/List_of_Wikipedias as of 2017-10-07
# ordered by article count except some for extreme bot spam
# should use https://stackoverflow.com/questions/336... |
# -*- coding:utf-8 -*-
# @Script: rotate_array.py
# @Author: Pradip Patil
# @Contact: @pradip__patil
# @Created: 2019-04-01 21:36:57
# @Last Modified By: Pradip Patil
# @Last Modified: 2019-04-01 22:44:02
# @Description: https://leetcode.com/problems/rotate-array/
'''
Given an array, rotate the array to the right by k... |
class TrainingConfig():
batch_size=64
lr=0.001
epoches=20
print_step=15
class BertMRCTrainingConfig(TrainingConfig):
batch_size=64
lr=1e-5
epoches=5
class TransformerConfig(TrainingConfig):
pass
class HBTTrainingConfig(TrainingConfig):
batch_size=32
lr=1e-5
epoch=20
|
# mouse
MOUSE_BEFORE_DELAY = 0.1
MOUSE_AFTER_DELAY = 0.1
MOUSE_PRESS_TIME = 0.2
MOUSE_INTERVAL = 0.2
# keyboard
KEYBOARD_BEFORE_DELAY = 0.05
KEYBOARD_AFTER_DELAY = 0.05
KEYBOARD_PRESS_TIME = 0.15
KEYBOARD_INTERVAL = 0.1
# clipbaord
CLIPBOARD_CHARSET = 'gbk'
# window
WINDOW_TITLE = 'Program Manager'
WINDOW_MANAGE_TI... |
class Student(object):
def __init__(self, name):
self.name = name
def __str__(self):
return 'Student object (name: %s)' % self.name
def __call__(self):
print('My name 111111111is %s.' % self.name)
print("-----------------------")
ffl = Student('ffl')
print("ffl-->", ffl)
print("f... |
LIMIT = 2000000;
def solve(limit):
a = 0
dam = limit
for i in range(2, 101):
for j in range(i, 101):
d = abs(i*(i + 1) * j*(j + 1)/4 - limit)
if d < dam:
a, dam = i * j, d
return a
if __name__ == "__main__":
print(solve(LIMIT))
|
class CajaFuerte:
def __init__(self, codigo):
self.codigo = codigo
self.caja_esta_abierta = False
self.objetos_guardados = []
def esta_abierta(self):
print(self.caja_esta_abierta)
def abrir(self, codigo):
if codigo != self.codigo:
raise Exception("La cla... |
for _ in range(int(input())):
l,r=map(int,input().split())
b=r
a=r//2+1
if a<l:
a=l
if a>r:
a=r
print(b%a) |
########################################################
# Copyright (c) 2015-2017 by European Commission. #
# All Rights Reserved. #
########################################################
extends("BaseKPI.py")
"""
Investment Analysis (euro)
---------------------------
Indexed ... |
print('Please think of a number between 0 and 100!')
x = 54
low = 0
high = 100
guessed = False
while not guessed:
guess = (low + high)/2
print('Is your secret number ' + str(guess)+'?')
s = raw_input("Enter 'h' to indicate the guess is too high.\
Enter 'l' to indicate the guess is too lo... |
# abcabc
# g_left = a, g_right = b
#
class Solution(object):
def __convert(self, x):
return ord(x) - ord('a') + 1
def distinctEchoSubstrings(self, text):
if len(text) == 1:
return 0
m = int(1e9 + 9)
p = 31
p_pow = 1
g_left = self.__convert(text... |
description = 'nGI backpack setup at ICON.'
display_order = 35
pvprefix = 'SQ:ICON:ngiB:'
includes = ['ngi_g0']
excludes = ['ngi_xingi_gratings']
devices = dict(
g1_rz = device('nicos_ess.devices.epics.motor.EpicsMotor',
epicstimeout = 3.0,
description = 'nGI Interferometer Grating Rotation G1 (... |
# -*- coding: utf-8 -*-
def roadbed_to_english(roadbed):
if roadbed in ['芝','0']:
roadbed_english='turf'
elif roadbed in ['ダ','1']:
roadbed_english='dirt'
else:
roadbed_english=roadbed
return roadbed_english
def roadbed_flg(roadbed):
if roadbed == '芝':
flg = '0'... |
# coding=utf-8
"""生产环境使用的配置
"""
DB_DEBUG = False
DB = 'attr_detect_ml3'
HOST = '192.168.178.19'
USER = 'db_ae3'
PASSWD = '632#ae931gld'
CONNECT_STRING = 'mysql://%s:%s@%s/%s?charset=utf8' % (USER, PASSWD, HOST, DB)
|
def powerLevelForCell(x, y, gridSerialNumber):
rackID = x + 11
powerLevel = rackID * (y + 1)
powerLevel += gridSerialNumber
powerLevel *= rackID
powerLevel //= 100
toSubtract = powerLevel // 10 * 10
powerLevel -= toSubtract
powerLevel -= 5
return powerLevel
"""
print(powerLevelForCell(2, 4, 8))
pri... |
# Input: Two strings, Pattern and Genome
# Output: A list containing all starting positions where Pattern appears as a substring of Genome
def PatternMatching(pattern, genome):
positions = [] # output variable
# your code here
for i in range(len(genome)-len(pattern)+1):
if genome[i:i+len(patt... |
def encodenum(num):
num = str(num)
line =""
for c in num:
line += chr(int(c) + ord('a'))
return line
def decodenum(line):
num = ""
for c in line:
num += str(ord(c)-ord('a'))
return num |
class exemplo():
def __init__(self):
pass
def thg_print(darkcode):
print(darkcode)
|
class Foo():
_myprop = 3
@property
def myprop(self):
return self.__class__._myprop
@myprop.setter
def myprop(self, val):
self.__class__._myprop = val
f = Foo()
g = Foo()
print(f.myprop, g.myprop)
f.myprop = 4
print(f.myprop, g.myprop)
|
#author: Lynijah
# date: 07-01-2021
def blank():
return print(" ")
# --------------- Section 1 --------------- #
# ---------- Integers and Floats ---------- #
# you may use floats or integers for these operations, it is at your discretion
# addition
# instructions
# 1 - create a print statement that pri... |
class RemoteError(Exception):
"""A base class for all remote's custom exception"""
class RemoteConnectionError(RemoteError):
"""Remote wasn't able to connect to remote host"""
class RemoteExecutionError(RemoteError):
"""A command executed remotely exited with non-zero status"""
class ConfigurationErro... |
#
# PySNMP MIB module CISCO-ENTITY-REDUNDANCY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ENTITY-REDUNDANCY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:39:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... |
# Escreva a função maior_primo que recebe um número inteiro maior ou igual a 2 como parâmetro e devolve o maior número primo menor ou igual ao número passado à função
def maior_primo(n):
""" Recebe um inteiro >= 2 como parâmetro e devolve o maior número primo <= ao número passado.
Ex:
>>> maior_primo(100)
... |
message = "This is a message!"
print(message)
message = "This is a new message!"
print(message) |
# author: Roy Kid
# contact: lijichen365@126.com
# date: 2021-09-20
# version: 0.0.1
def flat_kwargs(kwargs):
tmp = []
values = list(kwargs.values())
lenValue = len(values[0])
for v in values:
assert len(v) == lenValue, 'kwargs request aligned value'
for i in range(lenValue):
tmp.ap... |
# Feel free to add new properties and methods to the class.
"""
class MinMaxStack:
def __init__(self):
self.stack = []
self.min = float('inf')
self.max = float('-inf')
def _update_min(self, num, drop=False):
if drop and num == self.min:
self.min = min(self.stack or [... |
# Created by MechAviv
# Kinesis Introduction
# Map ID :: 331001120
# Hideout :: Training Room 2
KINESIS = 1531000
JAY = 1531001
if "1" not in sm.getQuestEx(22700, "E2"):
sm.setNpcOverrideBoxChat(KINESIS)
sm.sendNext("Jay, I feel so slow walking around like this. I'm going to switch to my speedier moves.")
... |
def do_something(x):
sq_x=x**2
return (sq_x) # this will make it much easier in future problems to see that something is actually happening
|
"""1143. Longest Common Subsequence"""
class Solution(object):
def longestCommonSubsequence(self, text1, text2):
"""
:type text1: str
:type text2: str
:rtype: int
"""
m = len(text1)
n = len(text2)
dp = [[0]*(n+1) for _ in range(m+1)]
for i, a... |
class Solution:
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype: bool
"""
return s in (s[1:] + s[:-1])
if __name__ == '__main__':
solution = Solution()
print(solution.repeatedSubstringPattern("abab"))
print(solution.repeatedSubstringPatter... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.