content stringlengths 7 1.05M |
|---|
# -*- encoding:utf-8 -*-
# index rule:
# 3 ------6------- 2
#
# 7 ------ ------- 5
#
# 0 ------4------- 1
# Stores the triangle values
raw_trigs = [
[],
[(0,7,4)],
[(4,5,1)],
[(0,5,1),(0,7,5)],
[(5,6,2)],
[(0,7,4), (4,7,5), (7,6,5), (5,6,2)],
[(1,4,6), (1,6,2)],
[(1,0,7), (1,7,6), (1,6,2)],
[(7,3,6)],
[(0... |
def mininum_temperature(arr_temp):
min_val = arr_temp[0]
i = 1
while i < len(arr_temp):
if (i < min_val):
min_val = arr_temp[i]
i += 1
return min_val
def maximum_temperature(arr_temp):
max_val = arr_temp[0]
i = 1
while i < len(arr_temp):
if (i > max_val):
max_val = arr_temp[i]
i += 1
return max... |
class TypeNode:
def __init__(self,className,parent="Object"):
self.name = className
self.attrlist = [Attribute("self",className)]
self.methodlist = {}
self.default = "void"
self.parent = parent
self.children = []
# def GetAttribute(self,attrName):
# attr... |
"""
Python package to help with daily work on heusler materials.
"""
name = "heuslertools"
|
make = "Ford"
model = "Everest"
def start_engine():
print (f'{make} {model} engine started')
|
# KATA MODULO 08
# EJERCICIO 01 Crear y modificar un diccionario de Python
# Agrega el código para crear un nuevo diccionario denominado 'planet'. Rellena con la siguiente información:
# name: Mars
# moons: 2
# Crea un diccionario llamado planet con los datos propuestos
# Para recuperar valores, puede utiliza... |
class Resource():
def __init__(self, path):
self.path = path
def __str__(self):
return '-i {}'.format(self.path)
class Resources(list):
def add(self, path):
self.append(Resource(path))
def append(self, resource):
resource.number = len(self)
super().append(r... |
# Python - 3.6.0
Test.describe('Basic tests')
names = ['john', 'matt', 'alex', 'cam']
ages = [16, 25, 57, 39]
for name, age in zip(names, ages):
person = Person(name, age)
Test.it(f'Testing for {name} and {age}')
Test.assert_equals(person.info, f'{name}s age is {age}')
|
aluno = {
}
aluno['nome'] = str(input('Nome: ').title())
aluno['média'] = float(input(f'Média de {aluno["nome"]} é: '))
print('-='*20)
if aluno['média'] >= 7:
aluno['situação'] = 'Aprovado!'
elif aluno ['média'] < 5:
aluno['situação'] = 'Reprovado!'
else:
aluno['situação']='Recuperação!'
pr... |
#Floating loop
first_list = list(range(10))
for i in first_list:
first_list[i] = float(first_list[i])
print(first_list)
|
def read_file(filename):
"""
Read input file and save the lines into a list.
:param filename: input file
:return: grid of octopuses
"""
grid = []
with open(filename, 'r', encoding='UTF-8') as file:
for line in file:
grid.append([int(s) for s in list(line.strip())])
re... |
# compat3.py
# Copyright (c) 2013-2019 Pablo Acosta-Serafini
# See LICENSE for details
# pylint: disable=C0111,W0122,W0613
###
# Functions
###
def _readlines(fname, fpointer1=open, fpointer2=open):
"""Read all lines from file."""
# fpointer1, fpointer2 arguments to ease testing
try: # pragma: no cover
... |
## Adicionando Cores
##\033[formatação:corTexto:corFundom
print('\033[0;30;41mOlá mundo!')
print('\033[4;33;44mOlá mundo!')
print('\033[1;35;43mOlá mundo!')
print('\033[30;42mOlá mundo!\033[0;0;0m')
print('\033[mOlá mundo!')
print('\033[7;33;44mOlá mundo!')
## Verifica quantidade de caracteres em uma string
s='Prova... |
class Fibonacci:
"""Implementations of the Fibonacci number."""
@staticmethod
def fib_iterative(index):
"""
Iterative algorithm for calculating the Fibonacci number.
:param index: Index of a number in the Fibonacci sequence.
:return: Fibonacci number.
"""
lower = 0
higher = 1
for i in range(1, index... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"win": "game.ipynb",
"lose": "game.ipynb"}
modules = ["game.py"]
doc_url = "https://thecharlieblake.github.io/solitairenet/"
git_url = "https://github.com/thecharlieblake/solitairenet/tree/master/... |
# Crie um programa que leia um número inteiro e mostre na tela se ele é PAR ou ÍMPAR.
num = int(input('Digite um valor qualquer:'))
resultado = num % 2 #resultado da divisão
#Todo valor impar dá 1
#Todo valor par dá 0
if resultado == 0:
print('{} é PAR'.format(num))
else:
print('{} é Impar'.format(num)) |
""" Helper routines for generating gpu kernels for nvcc.
"""
def nvcc_kernel(name, params, body):
"""Return the c code of a kernel function.
:param params: the parameters to the function as one or more strings
:param body: the [nested] list of statements for the body of the function. These will be
se... |
def smooth(dataset):
dataset_length = len(dataset)
dataset_extra_weights = [ItemWeight(*x) for x in dataset]
def get_next():
if dataset_length == 0:
return None
if dataset_length == 1:
return dataset[0][0]
total_weight = 0
result = None
for e... |
# O(nlogn) time | O(n) space
def mergeSort(array):
if len(array) <= 1:
return array
subarray = array[:]
mergeSortHelper(array, 0, len(array)-1)
return array
def mergeSortHelper(array, l, r):
if l == r:
return
m = (l + r) // 2
mergeSortHelper(array, l, m)
mergeSortHelper... |
# This is the custom function interface.
# You should not implement it, or speculate about its implementation
class CustomFunction:
# Returns f(x, y) for any given positive integers x and y.
# Note that f(x, y) is increasing with respect to both x and y.
# i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)
... |
#!/usr/bin/env python
class SulException(Exception):
"""
"""
class ConfigurationException(SulException):
pass
class ServerException(SulException):
pass
class DirectoryNotFoundException(SulException):
pass
class IntegrityException(SulException):
pass
|
class UndergroundSystem:
def __init__(self):
self.count = defaultdict(int)
self.time = defaultdict(int)
self.traveling = dict()
def checkIn(self, id: int, stationName: str, t: int) -> None:
self.traveling[id] = (stationName, t)
def checkOut(self, id: int, stationNa... |
class Patcher(object):
""" A dumb class to allow a mock.patch object to be used as a decorator and
a context manager
Typical usage::
import mock
import sys
my_mock = Patcher(mock.patch("sys.platform", "win32"))
@my_mock
def func1():
print(sys.platform)... |
def test_clear_images(client, seeder, app, utils):
user_id, admin_unit_id = seeder.setup_base()
image_id = seeder.upsert_default_image()
url = utils.get_image_url_for_id(image_id)
utils.get_ok(url)
runner = app.test_cli_runner()
result = runner.invoke(args=["cache", "clear-images"])
assert... |
def binary_slow(n):
assert n>=0
bits = []
while n:
bits.append('01'[n&1])
n >>= 1
bits.reverse()
return ''.join(bits) or '0'
|
# Containers for txid sequences start with this string.
CONTAINER_PREFIX = 'txids'
# Transaction ID sequence nodes start with this string.
COUNTER_NODE_PREFIX = 'tx'
# ZooKeeper stores the sequence counter as a signed 32-bit integer.
MAX_SEQUENCE_COUNTER = 2 ** 31 - 1
# The name of the node used for manually setting... |
# 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 ... |
# Solution 1 - recursion
# O(log(n)) time / O(log(n)) space
def binarySearch1(array, target):
return binarySearchHelper1(array, target, 0, len(array) - 1)
def binarySearchHelper1(array, target, left, right):
if left > right:
return -1
middle = (left + right) // 2
potentialMatch = array[middle... |
def levenshtein(source: str, target: str) -> int:
"""Computes the Levenshtein
(https://en.wikipedia.org/wiki/Levenshtein_distance)
and restricted Damerau-Levenshtein
(https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)
distances between two Unicode strings with given lengths using th... |
"""
pymatrices Package :-
- A Python 3.x Package to implement Matrices and its properties...
"""
class matrix:
"""Creates a Matrix using a 2-D list"""
def __init__(self, matrix):
self.__rows = len(matrix)
self.__cols = len(matrix[0])
for rows in matrix:
if len(rows) != self.__cols:
raise TypeError("I... |
# Uebungsblatt 2
# Uebung 1
i = 28
f = 28.0
print(i, id(i), type(i))
print(f, id(f), type(f))
# Uebung 2
i = 28.0
f = 28.0
print(i, id(i), type(i))
print(f, id(f), type(f))
# Uebung 3
s = "Hello"
s2 = s
print(s, id(s), s2, id(s2))
s += " World"
print(s, id(s), s2, id(s2))
# Uebung 4
m = ['a', 'b', 'd', 'e', 'f']
... |
n, m = map(int, input().split())
f = list(int(i) for i in input().split())
f.sort()
# formula -> f[i+n-1] - f[i]
ans = 10**9
for i in range(m-n+1):
ans = min(ans, f[i+n-1] - f[i])
print(ans) |
ENDPOINT_PATH = 'foobar'
BOOTSTRAP_SERVERS = 'localhost:9092'
TOPIC_RAW_REQUESTS = 'test.raw_requests'
TOPIC_PARSED_DATA = 'test.parsed_data'
USERNAME = None
PASSWORD = None
SASL_MECHANISM = None
SECURITY_PROTOCOL = 'PLAINTEXT'
# Use these when trying with FVH servers
# SASL_MECHANISM = "PLAIN"
# SECURITY_PROTOCOL = "... |
"""
Analyser of the relation.
@author: Minchiuan Gao <minchiuan.gao@gmail.com>
Build Date: 2015-Nov-25 Wed
"""
class RelationValue(object):
def __init__(self, title, weight, abbr, level):
self.title = title
self.weight = weight
self.abbr = abbr
self.level = level
class Analyse(o... |
iSay = input('Введите фразу: ')
print('Введите 2 слова из этой фразы')
iFind1 = input('Первое: ')
iFind2 = input('Второе: ')
word1 = iSay.find(iFind1)
word2 = iSay.find(iFind2)
if (word1 < word2):
print('ДА')
else:
print('НЕТ')
|
# input
print('What is my favourite food?')
input_guess = input("Guess? ")
# response
while input_guess != 'electricity':
print("Not even close.")
input_guess = input("Guess? ")
print("You guessed it! Buzzzz")
|
"""Crie um programa que leia nome e peso de várias pessoas, guardando tudo em uma lista. No final, mostre:
A) Quantas pessoas foram cadastradas:
B) Uma listagem com as pessoas mais pesadas:
C) Uma listagem com as pessoas mais leves:"""
temp = []
princ = []
mai = men = 0
while True:
temp.append(str(input('Nome: ')))... |
# Use enumerate() and other skills to return the count of the number of items in
# the list whose value equals its index.
def count_match_index(numbers):
return len([number for index, number in enumerate(numbers) if index == number])
result = count_match_index([0, 2, 2, 1, 5, 5, 6, 10])
print(result)
|
__title__ = 'elasticsearch-cli'
__version__ = '0.0.1'
__author__ = 'nevercaution'
__license__ = 'Apache v2'
|
## Largest 5 digit number in a series
## 7 kyu
## https://www.codewars.com/kata/51675d17e0c1bed195000001
def solution(digits):
biggest = 0
for index in range(len(digits) - 4):
if int(digits[index:index+5]) > biggest:
biggest = int(digits[index:index+5])
return biggest |
def candidates():
candidatesDictionary = {
#Initials : [First_name, Last_name, Club, Last_seen, 'TV_station', Total_time, Last_screenshot]
'AD': ['Andrzej', 'Duda', 'Bezpartyjny', 'b/d', 'b/d', 'b/d', 'https://upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Prezydent_Rzeczypospolitej_Polskiej_Andr... |
"""
Quantum Probability
===================
"""
class QuantumProbability(
int,
):
def __init__(
self,
probability: int,
):
super().__new__(
int,
probability,
)
|
# Databricks notebook source
## Enter your group specific information here...
GROUP='group05' # CHANGE TO YOUR GROUP NAME
# COMMAND ----------
"""
Enter any project wide configuration here...
- paths
- table names
- constants
- etc
"""
# Some configuration of the cluster
spark.conf.set("spark.sql.shuffle.partitio... |
"""
A simple script.
This file shows why we use print.
Author: Walker M. White (wmw2)
Date: July 31, 2018
"""
x = 1+2 # I am a comment
x = 3*x
print(x) |
"""
В генеалогическом древе у каждого человека, кроме родоначальника, есть ровно один родитель. Каждом элементу дерева
сопоставляется целое неотрицательное число, называемое высотой. У родоначальника высота равна 0, у любого другого
элемента высота на 1 больше, чем у его родителя.Вам дано генеалогическое древо, определ... |
sal = float(input('Qual é o salario do funcionario? R$ '))
if sal > 1250:
alm = sal + (sal * 10 / 100)
if sal <= 1250:
alm = sal + (sal * 15 /100)
print('Quem ganhava R$ {:.2f} passa a ganhar R$ {:.2f} agora.'.format(sal, alm))
|
{
"targets": [
{
"target_name": "game",
"sources": [ "game.cpp" ]
}
]
} |
class Stack:
def __init__(self,max_size=4):
self.max_size = max_size
self.stk = [None]*max_size
self.last_pos = -1
def pop(self):
if self.last_pos < 0:
raise IndexError()
temp = self.stk[self.last_pos]
self.stk[self.last_pos]=None
if self.last... |
#!/usr/bin/env python3
"""Peter Rasmussen, Programming Assignment 1, utils.py
This module provides miscellaneous utility functions for this package.
"""
def compute_factorial(n: int) -> int:
"""
Compute n-factorial.
:param n: Number to compute factorial for
:return: n-factorial
"""
if (not i... |
# Cambiar valor de la semilla aca
seed = 1
# Cambiar cantidad de iteraciones aca
cantidadIteraciones = 10
# Devuelve un número aleatorio entre 0 y 1
def random():
global seed
a = 16807
m = 2147483647
q = 127773
r = 2836
hi = seed // q
lo = seed % q
test = a*lo - r*hi
if (test > 0):
seed = test
... |
DEFAULT_SERVER_HOST = "localhost"
DEFAULT_SERVER_PORT = 11211
DEFAULT_POOL_MINSIZE = 2
DEFAULT_POOL_MAXSIZE = 5
DEFAULT_TIMEOUT = 1
DEFAULT_MAX_KEY_LENGTH = 250
DEFAULT_MAX_VALUE_LENGTH = 1024 * 1024 # 1 megabyte
STORED = b"STORED\r\n"
NOT_STORED = b"NOT_STORED\r\n"
EXISTS = b"EXISTS\r\n"
NOT_FOUND = b"NOT_FOUND\r\n"... |
def median(pool):
copy = sorted(pool)
size = len(copy)
if size % 2 == 1:
return int(copy[int((size-1) / 2)])
else:
return (int(copy[int((size) / 2)-1]) + int(copy[int(size / 2)])) / 2
|
# Python program to calculate C(n, k)
# Returns value of Binomial Coefficient
# C(n, k)
def binomialCoefficient(n, k):
# since C(n, k) = C(n, n - k)
if(k > n - k):
k = n - k
# initialize result
res = 1
# Calculate value of
# [n * (n-1) *---* (n-k + 1)] / [k * (k-1) *----* 1]... |
#does array have duplicate entries
a=[1,2,3,4,5,1,7]
i=1
j=1
for num in a:
for ab in range(len(a)):
if num==a[i]:
print("duplicate found! ",num,"is = a[",i,"]")
else:
print(num,"is not = a[",i,"]" )
if i>4:
break
else:
i=i+1
i=0
... |
{
'name': 'To-Do Kanban board',
'description': 'Kanban board to manage to-do tasks.',
'author': 'Daniel Reis',
'depends': ['todo_ui'],
'data': ['views/todo_view.xml'],
}
|
# play sound
file = "HappyBirthday.mp3"
print('playing sound using native player')
os.system("afplay " + file) |
class SkiffKernel(object):
"""SkiffKernel"""
def __init__(self, options=None, **kwargs):
super(SkiffKernel, self).__init__()
if not options:
options = kwargs
self._json = options
self.__dict__.update(options)
def __repr__(self):
return '<%s (#%s) %s>' ... |
class Solution(object):
def splitIntoFibonacci(self, S):
"""
:type S: str
:rtype: List[int]
"""
Solution.res= []
self.backtrack(0, 0, 0, [],S)
return Solution.res
def backtrack(self, start, last1, last2, intList, string):
for i in range(start,len(... |
v = 18
_v = 56
def f():
pass
def _f():
pass
class MyClass(object):
pass
class _MyClass(object):
pass
|
# Değişkenlerin tanımlanması.
adet = 20
x = 0
buyuk = 0
kucuk = 0
i = 0
p = 0
j = 0
ort = 0
p_ort = 0
# İlk “x” değerinin döngüye girmeden girilmesi
x = int(input())
buyuk = x
kucuk = x
# Değişkenlere koşullar kontrol edilerek değer atanması
if (x > 0):
p_ort = p_ort + x
p += 1
if (x > 100 and x < 200) :
... |
# -*- coding: utf-8 -*-
# Service key from www.data.go.kr
ServiceKey = "Ej9BN7hUDaYUbYCEde4crW5llAbmNvkMXsLimF3up9FBCO4nkGilDfzfHQe33kIhgXBt%2Bl%2BPbnivoQn%2BTMmLWg%3D%3D"
MobileOS = "ETC"
MobileApp = "Test"
Languages = [
{"code": "Kor", "name": "한국"},
{"code": "Eng", "name": "English"},
{"code": "Jpn", "name":... |
def solve_single_lin(opt_x_s):
'''
solve one opt_x[s]
'''
opt_x_s.solve(solver='MOSEK', verbose = True)
return opt_x_s |
pkgname = "xsetroot"
pkgver = "1.1.2"
pkgrel = 0
build_style = "gnu_configure"
hostmakedepends = ["pkgconf"]
makedepends = [
"xbitmaps", "libxmu-devel", "libxrender-devel",
"libxfixes-devel", "libxcursor-devel"
]
pkgdesc = "X root window parameter setting utility"
maintainer = "q66 <q66@chimera-linux.org>"
lice... |
def is_num(in_value):
"""Checks if a value is a valid number.
Parameters
----------
in_value
A variable of any type that we want to check is a number.
Returns
-------
bool
True/False depending on whether it was a number.
Examples
--------
>>> is_num(1)
True... |
class Item:
def __init__(self, block_id, count, damage, data):
self.block_id = block_id
self.count = count
self.damage = damage
self.data = data
def __str__(self):
return 'block: {:3d}, count: {:2d}, damage: {}'.format(self.block_id, self.count, self.damage)
|
"""
103. Binary Tree Zigzag Level Order Traversal
Given a binary tree,
return the zigzag level order traversal of its nodes' values.
(ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
r... |
BAZEL_VERSION_SHA256S = {
"0.14.1": "7b14e4fc76bf85c4abf805833e99f560f124a3b96d56e0712c693e94e19d1376",
"0.15.0": "7f6748b48a7ea6bdf00b0e1967909ce2181ebe6f377638aa454a7d09a0e3ea7b",
"0.15.2": "13eae0f09565cf17fc1c9ce1053b9eac14c11e726a2215a79ebaf5bdbf435241",
"0.16.1": "17ab70344645359fd4178002f367885e9... |
def censor(text, word):
bigstring = text.split()
print (bigstring)
words = ""
" ".join(bigstring)
return bigstring
print (censor("hello hi hey", "hi")) |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 5 18:30:18 2020
@author: MarcoSilva
"""
def general_poly (L):
""" L, a list of numbers (n0, n1, n2, ... nk)
Returns a function, which when applied to a value x, returns the value
n0 * x^k + n1 * x^(k-1) + ... nk * x^0 """
def f(x):
total = 0
... |
config = {
'api_root': 'https://library.cca.edu/api/v1',
'client_id': 'abcedfg-123445678',
'client_secret': 'abcedfg-123445678',
}
|
"""
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?
"""
exponent = 1000
def initial_func(exponent):
return sum(int(digit) for digit in f'{2 ** exponent}')
def improved_func(exponent):
pass
# 1366
print(initial_func(ex... |
# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## Customize your APP title, subtitle and menus here
#########################################################################
response.logo... |
def bubble_sort(elements: list):
"""Sort the list inplace using bubble sort.
Args:
--
elements (list): list of elements
"""
size = len(elements)
for i in range(size - 1):
# if list is already sorted track it using swapped variable
swapped = False
for j in range... |
# filter().py
def func(a):
if a <100:
return True
else:
return False
print(list(filter(func,[10,56,101,500])))
# 返回True所对应的值
def f(x):
x = 100
print(x)
a = 1
f(a)
print(a)
|
# game model list base class for all object collections in game
class GameModelList():
def __init__(
self,
game,
game_models=[],
collidable=False,
block_color=None
):
self.game = game
self.game_models = game_models
self.collidable = collidable
self.block_color = block_color
for model in self.g... |
# Author: Ian Burke
# Module: Emerging Technologies
# Date: September, 2017
# Problem Sheet: https://emerging-technologies.github.io/problems/python-fundamentals.html
# create a function to reverse a string
def reverse():
word = input("Enter a string: ") #user enters a string and store it in word
word = word[... |
# GENERATED VERSION FILE
# TIME: Tue Oct 26 14:07:11 2021
__version__ = '0.3.0+dc45206'
short_version = '0.3.0'
|
class Cuenta:
def __init__(self, nombre, numero, saldo):
self.nombre = nombre
self.numero= numero
self.saldo = saldo
def depositar(self, a):
self.saldo=self.saldo+a
return self.saldo
def retirar(self, a):
self.saldo=self.saldo-a
return self... |
# coding: utf-8
def convert(word):
word = word.replace('vv','1')
word = word.replace('ll','2')
word = word.replace('ss','3')
word = word.replace('gg','4')
word = word.replace('rr','5')
word = word.replace('ng','6')
word = word.replace('μ','7')
word = word.replace('+','8')
word = word.replace('TMg','9')
word =... |
temp=n=int(input("Enter a number: "))
sum1 = 0
while(n > 0):
sum1=sum1+n
n=n-1
print(f"natural numbers in series {sum1}+{n}")
print(f"The sum of first {temp} natural numbers is: {sum1}") |
n = str(input('Digite seu nome : ')).strip()
print('Muito prazer em te conhecer ! ')
nome = n.split()
print('O seu primeiro nome é: {}'.format(nome[0]))
print('O seu último nome é: {}'.format(nome[len(nome)-1]))
#n = str(input('Digite seu nome completo : ')).strip()
#print('Olá! Prazer em te conhecer ! ')
#nome = n.s... |
# red_black_node.py
class Node:
"""
A class used to represent a Node in a red-black search tree.
Attributes:
key: The key is the value the node shall be sorted on. The key can be an integer,
float, string, anything capable of being sorted.
instances (int): The number o... |
def get_max_profit(stock_prices):
# initialize the lowest_price to the first stock price
lowest_price = stock_prices[0]
# initialize the max_profit to the
# difference between the first and the second stock price
max_profit = stock_prices[1] - stock_prices[0]
# loop through every price in stock... |
# Given an integer n, return the number of trailing zeroes in n!.
# Example 1:
# Input: 3
# Output: 0
# Explanation: 3! = 6, no trailing zero.
# Example 2:
# Input: 5
# Output: 1
# Explanation: 5! = 120, one trailing zero.
class Solution:
def trailingZeroes(self, n):
"""
:type n: int
... |
class EventMongoRepository:
database_address = "localhost"
def __init__(self):
self.client = "Opens a connection with mongo"
def add_event(self, event):
pass
def remove_event(self, event):
pass
def update_event(self, event):
pass
|
class SuperList(list):
def __len__(self):
return 1000
super_list1 = SuperList()
print(len(super_list1))
super_list1.append(5)
print(super_list1[0])
print(issubclass(list, object)) |
# Python Developer
# 3.1. Практика
#
# 1. У вас есть массив чисел. Напишите три функции, которые вычисляют сумму этих чисел:
# с for-циклом,
# a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# i = 0
# b = 0
# for i in a:
# b = b + i
# print(b)
# с while -циклом, с * рекурсией.
# a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# # b = 0... |
"""
link: https://leetcode-cn.com/problems/longest-increasing-path-in-a-matrix
problem: 求给定矩阵的最大严格递增路径长度
solution: DP。从小到大排序所有元素,因为路径只能从低向高长,g[i][j] 记录当检查到 matrix[i][j] 时,以 matrix[i][j] 为终点的最大路径长度。
因为做了排序,时间复杂度O(nm(log_nm))
solution-fix: 拓扑排序。思路同上,不做排序,遍历一次记录每个点附近比其小的点数量作为入度,用拓扑序遍历,时间复杂度可以压到 O(nm)
"""
cl... |
class Finding:
def __init__(self, filename, secret_type, secret_value, line_number=None, link=None):
self._filename = filename
self._secret_type = secret_type
self._secret_value = secret_value
self._line_number = line_number
self._link = link
@property
def filename(s... |
"""
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
示例:
输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
提示:
3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum... |
PATH_ROOT = "/sra/sra-instant/reads/ByExp/sra/SRX/SRX{}/{}/"
def read_srx_list(file):
srxs = set()
with open(file, "r") as fh:
next(fh)
for line in fh:
if line.startswith("SRX"):
srxs.add(line.rstrip())
return list(srxs)
def read_srr_file(srr_file):
srr_d... |
# Exercício Python 051
# Leia o primeiro termo e a razão de uma progressão aritmética
# Mostre os 10 primeiros termos dessa progressão
n = int(input('Digite o primeiro termo: '))
p = int(input('Digite a constante de progressão: '))
for c in range(n,10,p):
print('{}·'.format(c),end='')
print('FIM')
# Professor
n = i... |
styles = {
"alignment": {
"color": "black",
"linestyle": "-",
"linewidth": 1.0,
"alpha": 0.2,
"label": "raw alignment"
},
"despiked": {
"color": "blue",
"linestyle": "-",
"linewidth": 1.4,
"alpha": 1.0,
"label": "de-spiked align... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 21 18:24:11 2021
@author: User
"""
# Objetos, pilas y colas
class Rectangulo():
def __init__(self, x, y):
self.x = x
self.y = y
def base(self):
return
def altura(self):
return
def area(self):
return
... |
# Faça um programa que leia o peso de cinco pessoas.
# No final, mostre qual foi o maior e o menor peso lidos.
menor_peso = 999
maior_peso = -1
for i in range(1, 6):
peso = float(input(f'Peso {i}: '))
if peso > maior_peso:
maior_peso = peso
elif peso < menor_peso:
menor_peso = peso
print(... |
# encoding: utf-8
# module errno
# from (built-in)
# by generator 1.147
"""
This module makes available standard errno system symbols.
The value of each symbol is the corresponding integer value,
e.g., on most systems, errno.ENOENT equals the integer 2.
The dictionary errno.errorcode maps numeric codes to symbol name... |
'''
'''
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
length = len(nums)
if length <= 2:
return length
left = 0
cur = 0
while cur < length - 1:
sums = 1
while cur < length - 1 and nums[cur] == nums[cur + 1]:
... |
# Problem description: http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/
def make_change(money, coins):
if money < 0:
return 0
elif money == 0:
return 1
elif not coins:
return 0
else:
return make_change(money - coins[-1], coins) + make_change(money, coi... |
_notes_dict_array_hz = {
'C': [8.176, 16.352, 32.703, 65.406, 130.81, 261.63, 523.25, 1046.5, 2093.0, 4186.0, 8372.0],
'C#': [8.662, 17.324, 34.648, 69.296, 138.59, 277.18, 554.37, 1108.7, 2217.5, 4434.9, 8869.8],
'Df': [8.662, 17.324, 34.648, 69.296, 138.59, 277.18, 554.37, 1108.7, 2217.5, 4434.9, 8869.8],... |
def funct(l1, l2):
s = len(set(l1+l2))
return s
for t in range(int(input())):
n = int(input())
l = input().split()
a = {}
for i in l:
p = i[1:]
if p in a:
a[p].append(i[0])
else:
a[p] = [i[0]]
b = list(a.keys())
s = 0
for i in range(l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.