content stringlengths 7 1.05M |
|---|
# Time: O(nlogn)
# Space: O(n)
class Solution(object):
def relativeSortArray(self, arr1, arr2):
"""
:type arr1: List[int]
:type arr2: List[int]
:rtype: List[int]
"""
lookup = {v: i for i, v in enumerate(arr2)}
return sorted(arr1, key=lambda i: lookup.get(i, ... |
# Objetivo do algorítimo:
# Desenvolver uma lógica que leia a altura e o peso de uma pessoa
# calcule seu imc e mostre seu status de acordo com a tabela:
# Abaixo de 18.5: Abaixo do peso.
# Entre 18.5 e 25: Peso ideal.
# 25 até 30: Sobrepeso.
# 30 até 40: Obesidade
# Acima de 40 obesidade mórbida
# Exercicio pensado po... |
"""
https://parzibyte.me/blog
"""
print("Hola. Elimina esto y haz que diga 'Mi nombre es Luis'")
print("Hola. Me llamo cambia esto para que diga tu nombre, sin borrar el final. Tengo 23 años")
# Eleva el 2 a la potencia 3, no a la 50
pow(2, 50) |
"""
Criando sua própria versão de loop
"""
for num in range(1, 6):
print(num, end=', ')
print()
def meu_for(iteravel):
it = iter(iteravel)
while True:
try:
print(next(it))
except StopIteration:
break
numeros = range(1, 6)
meu_for(numeros)
|
"""
17263. Sort 마스터 배지훈
작성자: xCrypt0r
언어: Python 3
사용 메모리: 70,552 KB
소요 시간: 204 ms
해결 날짜: 2020년 9월 16일
"""
def main():
input()
print(max(map(int, input().split())))
if __name__ == '__main__':
main()
|
#Horas-minutos e Segundos
valor = int(input())
horas = 0
minutos = 0
segundos = 0
valorA = valor
contador = segundos
while(contador <= valorA):
if contador > 0:
segundos += 1
if segundos >= 60:
minutos += 1
segundos = 0
if minutos >= 60:
horas += 1
minutos = 0
c... |
#!/usr/bin/env python
# Author: Omid Mashayekhi <omidm@stanford.edu>
# ssh -i ~/.ssh/omidm-sing-key-pair-us-west-2.pem -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ubuntu@<ip>
# US West (Northern California) Region
# EC2_LOCATION = 'us-west-1'
# NIMBUS_AMI = 'ami-50201815'
# UBUNTU_AMI = 'ami-660c3023... |
# SPDX-FileCopyrightText: Aresys S.r.l. <info@aresys.it>
# SPDX-License-Identifier: MIT
"""
Constants module
----------------
Example of usage:
.. code-block:: python
import arepytools.constants as cst
print(cst.LIGHT_SPEED)
"""
# Speed of light
LIGHT_SPEED = 299792458.0
"""
Speed of light in vacuum (m/s).... |
a = float(input('Primeiro segmento: '))
b = float(input('Segundo segmento: '))
c = float(input('Terceiro segmento: '))
# print(a, b, c)
if (a < b + c) and (b < a + c) and (c < a + b):
triangulo = True
parte1 = 'Os segmentos acima PODEM FORMAR um triângulo '
else:
triangulo = False
parte1 = 'Os segmentos... |
# Copyright: 2006 Marien Zwart <marienz@gentoo.org>
# License: BSD/GPL2
#base class
__all__ = ("PackageError", "InvalidPackageName", "MetadataException", "InvalidDependency",
"ChksumBase", "MissingChksum", "ParseChksumError")
class PackageError(ValueError):
pass
class InvalidPackageName(PackageError):
p... |
#
# PySNMP MIB module CISCO-ENTITY-ASSET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ENTITY-ASSET-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:56:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
def egcd(a, b):
if a==0:
return b, 0, 1
else:
gcd, x, y = egcd(b%a, a)
return gcd, y-(b//a)*x, x
if __name__ == '__main__':
a = int(input('Enter a: '))
b = int(input('Enter b: '))
gcd, x, y = egcd(a, b)
print(egcd(a,b))
if gcd!=1:
print("M.I. doe... |
class Engine(object):
"""Engine"""
def __init__(self, rest):
self.rest = rest
def list(self, params=None):
return self.rest.get('engines', params)
def create(self, data=None):
return self.rest.post('engines', data)
def get(self, name):
return self.rest.get('engin... |
def app(environ, start_response):
s = ""
for i in environ['QUERY_STRING'].split("&"):
s = s + i + "\r\n"
start_response("200 OK", [
("Content-Type", "text/plain"),
("Content-Length", str(len(s)))
])
return [bytes(s, 'utf-8')]
|
# -*- coding: utf-8 -*-
'''
File name: code\integer_angled_quadrilaterals\sol_177.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #177 :: Integer angled Quadrilaterals
#
# For more information see:
# https://projecteuler.net/problem=177
... |
deck_test = {
"kategori 1": ["kartuA", "kartuB", "kartuC", "kartuD"],
"kategori 2": ["kartuE", "kartuF", "kartuG", "kartuH"],
"kategori 3": ["kartuI", "kartuJ", "kartuK", "kartuL"],
# "kategori 4": ["kartuM", "kartuN", "kartuO", "kartuP"],
# "kategori 5": ["kartuQ", "kartuR", "kartuS", "kartuT"],
}
... |
data = [int(input()), input()]
if 10 <= data[0] <= 15 and data[1] == "f":
print("YES")
else:
print("NO")
|
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
res = cnt = 0
for i in nums:
if i:
cnt += 1
else:
if cnt:
res = max(res, cnt)
cnt = 0
return max(res, cnt) |
n = int(input())
while True:
s,z =0,n
while z>0:
s+=z%10
z//=10
if n%s==0:
print(n)
break
n+=1 |
n = int(input())
k = n >> 1
ans = 1
for i in range(n-k+1,n+1):
ans *= i
for i in range(1,k+1):
ans //= i
print (ans)
|
#
# PySNMP MIB module DVMRP-STD-MIB-UNI (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DVMRP-STD-MIB-UNI
# Produced by pysmi-0.3.4 at Mon Apr 29 18:40:19 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
mesh_meshes_begin = 0
mesh_mp_score_a = 1
mesh_mp_score_b = 2
mesh_load_window = 3
mesh_checkbox_off = 4
mesh_checkbox_on = 5
mesh_white_plane = 6
mesh_white_dot = 7
mesh_player_dot = 8
mesh_flag_infantry = 9
mesh_flag_archers = 10
mesh_flag_cavalry = 11
mesh_inv_slot = 12
mesh_mp_ingame_menu = 13
mesh_mp_inventory_lef... |
# hanoi: int -> int
# calcula el numero de movimientos necesarios aara mover
# una torre de n discos de una vara a otra
# usando 3 varas y siguiendo las restricciones del puzzle hanoi
# ejemplo: hanoi(0) debe dar 0, hanoi(1) debe dar 1, hanoi(2) debe dar 3
def hanoi(n):
if n < 2:
return n
else:
... |
class Solution(object):
def alienOrder(self, words):
"""
:type words: List[str]
:rtype: str
"""
|
# BUG Can live for several minutes after decapitation
# Either change death-time or remove need for head entirely
"""
TODO BAK-AAAW
# BUG If you read me as a seperate code-tag you are a dumb, dumb, dumb crawler.
''' TODO Include me with bak-aaaw too! '''
""" |
date = input("enter the date: ").split()
dd = int(date[0])
yyyy = int(date[2])
mm = date[1]
l = []
l.append(yyyy)
l.append(mm)
l.append(dd)
t = tuple(l)
print(t)
|
menu_item=0
namelist = []
while menu_item != 9:
print("----------------------------")
print("1. Mencetak List")
print("2. Menambahkan nama ke dalam list")
print("3. Menghapus nama dari list")
print("4. Mengubah data dari dalam list")
print("9. Keluar")
menu_item= int(input("Pilih menu: "))
if men... |
#
# baseparser.py
#
# Base class for Modbus message parser
#
class ModbusBaseParser:
"""Base class for Modbus message parsing.
"""
def __init__(self):
pass
def msgs_from_bytes(self, b):
"""Parse messages from a byte string
"""
|
"""
Write a function:
def missing_integer(A):
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [−1, −... |
a, b = input().split()
a = int(a)
b = int(b)
if a > b:
print(">")
elif a < b:
print("<")
else:
print("==")
|
n = int(input("Enter a number: "))
for i in range(1, n+1):
count = 0
for j in range(1, n+1):
if i%j==0:
count= count+1
if count==2:
print(i)
|
#what is python
#added by @Dima
print("What is Data Types?")
print("_______________________________________________________")
print("Collections of data put together like array ")
print("________________________________________________________")
print("there are four data types in the Python ")
print("_________... |
# V2
"""
02. both_ends
Dada uma string s, retorne uma string feita com os dois primeiros
e os dois ultimos caracteres da string original.
Exemplo: 'spring' retorna 'spng'. Entretanto, se o tamanho da string
for menor que 2, retorne uma string vazia.
"""
def both_ends(string: str) -> str:
# +++ SUA SOLUÇÃO +++
... |
format = "%(asctime)s - %(levelname)s - %(name)s - %(message)s"
minimal_format = "%(message)s"
def _get_formatter_and_handler(use_minimal_format: bool = False):
logging_dict = {
"version": 1,
"disable_existing_loggers": True,
"formatters": {
"colored": {
"()": "... |
#!/bin/python3
# Set .union() Operation
# https://www.hackerrank.com/challenges/py-set-union/problem
if __name__ == '__main__':
n = int(input())
students_n = set(map(int, input().split()))
b = int(input())
students_b = set(map(int, input().split()))
print(len(students_n | students_b)) |
'''
Сортировка
'''
n = int(input())
a = [int(j) for j in input().split()]
a.sort()
print(*a)
|
def ddd():
for i in 'fasdffghdfghjhfgj':
yield i
a = ddd()
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
|
# Customer States
C_CALLING = 0
C_WAITING = 1
C_IN_VEHICLE = 2
C_ARRIVED = 3
C_DISAPPEARED = 4
# Vehicle States
V_IDLE = 0
V_CRUISING = 1
V_OCCUPIED = 2
V_ASSIGNED = 3
V_OFF_DUTY = 4 |
# app seettings
EC2_ACCESS_ID = 'A***Q'
EC2_ACCESS_KEY = 'R***I'
YCSB_SIZE =0
MCROUTER_NOISE = 0
MEMCACHED_OD_SIZE = 1
MEMCACHED_SPOT_SIZE = 0
G_M_MIN = 7.5*1024
G_M_MAX = 7.5*1024
G_C_MIN = 2
G_C_MAX = 2
M_DEFAULT = 7.5*1024
C_DEFAULT = 2
G_M_MIN_2 = 7.5*1024
G_M_MAX_2 = 7.5*1024
G_C_MIN_2 = 2
G_C_MAX_2 = 2
M_... |
def avg_grade(name, *args):
if args:
avg = sum(args) / len(args)
print(f'{name}, your average grade is: {avg}')
else:
print(f'No grades available for {name}')
avg_grade('Joe')
avg_grade('Doe', 90, 95, 100)
|
# B_R_R
# M_S_A_W
"""
Coding Problem on Iterators and Generators:
First, using Iterators, we will write a code that pass in a sentence and print out all words in the sentence in line.
Then, we will do the same thing with generators.
"""
class Sentence:
def __init__(self, sentence):
self.sentence=senten... |
def read_input():
n = int(input())
return (
[input() for _ in range(n)],
input()
)
def find_position(matrix, symbol):
for i in range(len(matrix)):
line = matrix[i]
if symbol in line:
return (i, line.index(symbol))
return None
(matrix, symbol) = read_in... |
# (c) Copyright 2018 Palantir Technologies Inc. All rights reserved.
#
# 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 ... |
numero = int(input('Digite um número: '))
base = int(input('Entre as opções: '
'\n[1] Binário'
'\n[2] Octal'
'\n[3] Hexadecimal'
'\nQual a base de conversão? '))
if base == 1:
print(f'> {numero} convertido em BINÁRIO = {bin(numero)[2:]}.')
elif bas... |
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
rows = [set() for _ in range(9)]
cols = [set() for _ in range(9)]
subboxes = [set() for _ in range(9)]
for i, row in enumerate(board):
... |
#string: temperatura
Gc = float(input("Digite grados Centigrados: "))
Gk = (Gc + 273.15)
print("el valor de los grados kelvin es el siguiente: ",Gk)
|
class Triangular:
### Constructor ###
def __init__(self, init, end, center=None, peak=1, floor=0):
# initialize attributes
self._init = init
self._end = end
if center:
#using property to test if its bewtween init and end
self.center = center
else:
... |
current = [0, 1]
someList = []
while True:
for n in range(0, 2):
current[n] += 1
print(current)
someList.append(current[:]) #aqui faz uma cópia da lista e usa referêwncia para esta cópia, não a original
if current == [2, 3]:
break
print(someList)
#https://pt.stackoverflow.com/q/425908/1... |
# Python - 3.6.0
test.describe('Fixed tests')
test.assert_equals(whatday(1), 'Sunday')
test.assert_equals(whatday(2), 'Monday')
test.assert_equals(whatday(3), 'Tuesday')
test.assert_equals(whatday(8), 'Wrong, please enter a number between 1 and 7')
test.assert_equals(whatday(20), 'Wrong, please enter a number between ... |
def last_vowel(s):
"""(str) -> str
Return the last vowel in s if one exists; otherwise, return None.
>>> last_vowel("cauliflower")
"e"
>>> last_vowel("pfft")
None
"""
i = len(s) - 1
while i >= 0:
if s[i] in 'aeiouAEIOU':
return s[i]
i = i - 1
return No... |
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
list
'''
print("==========list=============")
students = ["jack", "tony", "john"]
students.append("kevin")
students.insert(1, "lisa")
students.pop()
students.pop(0)
print(students)
print(len(students))
print(students[0])
print(students[-1])
'''
tuple
'''
prin... |
#
# PySNMP MIB module TPLINK-PORTMIRROR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-PORTMIRROR-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:25:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
File = open("File PROTEK/Data2.txt", "w")
while True:
nim = input('Masukan NIM:')
nama = input('Masukan Nama:')
alamat = input('Masukan Alamat:')
print('')
File.write(nim + '|' + nama + '|' + alamat + '\n')
repeat = input('Apakah ingin memasukan data lagi?(y/n):')
print('')
... |
# 看了Topics知道这个是用栈来解决的题目。看了别人的解答才明白怎么回事。
#
# 使用一个栈作为辅助,遍历数字字符串,当当前的字符比栈最后的字符小的时候,说明要把栈的最后的这个字符删除掉。为什么呢?你想,把栈最后的字符删除掉,然后用现在的字符进行替换,是不是数字比以前的那种情况更小了?所以同样的道理,做一个while循环!这个很重要,可是我没有想到。在每一个数字处理的时候,都要做一个循环,使得栈里面最后的数字比当前数字大的都弹出去。
#
# 最后,如果K还没用完,那要删除哪里的字符呢?毋庸置疑肯定是最后的字符,因为前面的字符都是小字符。
class Solution:
def removeKdigits(self, n... |
# Lv-677_Ivan_Vaulin
# Task2. Write a script that checks the login that the user enters.
# If the login is "First", then greet the users. If the login is different, send an error message.
# (need to use loop while)
user_name = input('Hello, please input your Log in:')
while user_name != 'First':
user_name = inpu... |
n = input('Digite algo:\n')
print('O tipo primitivo do que foi digitado é:', type(n))
print('Só tem epaços?', (n.isspace()))
print('Só tem números?', (n.isnumeric()))
print(n.isalpha())
print(n.isalnum())
print(n.isupper())
print(n.islower())
print(n.istitle())
|
# 读取data.txt文件中 数据如下:
# 小张 13888888888
# 小李 13999999999
# 小赵 13777777777
# 写程序读取数据,打印出姓名和电话号码
try:
f = open('data.txt', 'rt', encoding='utf-8') # 设置编码
while True:
s = f.readline()
if not s:
break
s = s.rstrip().lstrip() # 去掉左右的空格、制表符、换行符等
info = s.split(' ')
... |
"""
1272. Remove Interval
Medium
Given a sorted list of disjoint intervals, each interval intervals[i] = [a, b] represents the set of real numbers x such that a <= x < b.
We remove the intersections between any interval in intervals and the interval toBeRemoved.
Return a sorted list of intervals after all such remov... |
# -*- coding: UTF-8 -*-
# Copyright 2013 Felix Friedrich, Felix Schwarz
# Copyright 2015, 2019 Felix Schwarz
# The source code in this file is licensed under the MIT license.
# SPDX-License-Identifier: MIT
__all__ = ['Result']
class Result(object):
def __init__(self, value, **data):
self.value = value
... |
#
# Runtime: 44 ms, faster than 96.86% of Python3 online submissions for Flatten Binary Tree to Linked List.
# Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Flatten Binary Tree to Linked List.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# sel... |
"""
Refaça o Exercício 009, mostrando a tabuada de um número que o usuário
escolher, só que agora utilizando um laço for.
"""
n = int(input('Digite um número inteiro: '))
print('='*20)
print('> Tabuada do {}'.format(n))
for c in range(1, 11):
print('\t{} X {} = {}'.format(n, c, n * c))
print('='*20)
|
# Test that systemctl will accept service names both with or without suffix.
def test_dot_service(sysvenv):
service = sysvenv.create_service("foo")
service.will_do("status", 3)
service.direct_enable()
out, err, status = sysvenv.systemctl("status", "foo.service")
assert status == 3
assert service... |
#!/usr/bin/python3
# 9x9 values in a sudoku
COUNT_NUMBERS = int(9)
"""
a sudoku of indices, columns and rows
colum 0 1 2 3 4 5 6 7 8 | row
________________________________________________|_____
sudoku = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, | 0
9, 10, 11, 12, 13, 14, 15, 16, 17,... |
num_list = []
num_list.append(1)
num_list.append(2)
num_list.append(3)
print(num_list[1]) |
class BaseModule:
"""
Base module class to be extended by feature modules.
"""
command_char = ''
# To be updated in subclasses
module_name = ''
module_description = ''
commands = []
def __init__(self, user_cmd_char):
"""
Sets command prefix while initializing.
... |
#!/usr/bin/env python
# Paths
VIDEOS_PATH = '~/Desktop/Downloaded Youtube Videos'
VIDEOS_PATH_WIN = '/mnt/e/Alex/Videos/Youtube'
|
# Variables that contain the user credentials to access Twitter API
ACCESS_TOKEN ="< Enter your Twitter Access Token >"
ACCESS_TOKEN_SECRET ="< Enter your Access Token Secret >"
CONSUMER_KEY = "< Enter Consumer Key >"
CONSUMER_SECRET = "< Enter Consumer Key Secret >" |
""" https://adventofcode.com/2018/day/4 """
def readFile():
with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
l = [line[:-1] for line in f.readlines()]
l.sort()
return l
class Guard:
def __init__(self, id):
self.id = int(id)
self.idStr = id
self.timeAsleep ... |
RESPONSE_MOCK = [
{
"request_id": "REQUEST_UUID",
"results": [
{
"company_id": "COMPANY_UUID",
"companies": [
{
"cnpj": "CNPJ DA EMPRESA",
"company_name": "Razão Social",
... |
ft_name = 'points'
featuretype_api = datastore_api.featuretype(name=ft_name, data={
"featureType": {
"circularArcPresent": False,
"enabled": True,
"forcedDecimal": False,
"maxFeatures": 0,
"name": ft_name,
"nativeName": ft_name,
"numDecimals": 0,
"over... |
# Time: O(k * n^2)
# Space: O(n^2)
class Solution(object):
def knightProbability(self, N, K, r, c):
"""
:type N: int
:type K: int
:type r: int
:type c: int
:rtype: float
"""
directions = \
[[ 1, 2], [ 1, -2], [ 2, 1], [ 2, -1], \
... |
class Solution:
def spiralMatrixIII(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:
step = sign = 1
result = [[r0, c0]]
r, c = r0, c0
while len(result) < R*C:
for _ in range(step):
c += sign
if 0 <= r < R and 0 <= c < C:
... |
# -*- coding: utf-8 -*-
def includeme(config):
config.register_service_factory('.services.user.rename_user_factory', name='rename_user')
config.include('.views')
config.add_route('admin_index', '/')
config.add_route('admin_admins', '/admins')
config.add_route('admin_badge', '/badge')
config.... |
## Iterative approach - BFS - Using Queue
# 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 invertTree(self, root: TreeNode) -> TreeNode:
... |
"""
Given the root of a binary tree, return the sum of every tree node's tilt.
The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0. The ru... |
class ExtractJSON:
@staticmethod
def get_json(path:str) -> str:
"""
Return an extract JSON from a file
"""
try:
return open(path, "r").readlines()[0]
except ValueError:
print("ERROR: file not found.")
exit(-1)
return None |
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
motorcycles.append('honda')
print(motorcycles)
motorcycles = []
motorcycles.append('suzuki')
motorcycles.append('honda')
motorcycles.append('bmw')
print(motorcycles)
motorcycles.insert(0, 'ducati')
print(mot... |
# -*- coding: utf-8 -*-
class StaticBase(object):
"""
Base class for StaticModel framework class.
.. todo::
KDJ: What is the reason this class exists? Can it be merged with
StaticModel?
"""
def __init__(self):
if self.__class__ is StaticBase:
raise NotImplementedError
self.inIniti... |
#
# PySNMP MIB module HP-ICF-LAYER3VLAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-LAYER3VLAN-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:21:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
class BaseClient(object):
def __init__(self, username, password, randsalt):
## password = {MD5(pwrd) for old clients, SHA256(pwrd + salt) for new clients}
## randsalt = {"" for old clients, random 16-byte binary string for new clients}
## (here "old" means user was registered over an unencrypted link, without sa... |
# %% [696. *Count Binary Substrings](https://leetcode.com/problems/count-binary-substrings/)
# 問題:正規表現'(0+1+|1+0+)'にマッチする個数を返せ。ただし0と1は同数とする
# 解法:itertools.groupbyを用いる
class Solution:
def countBinarySubstrings(self, s: str) -> int:
lst = [len(list(g)) for _, g in itertools.groupby(s)]
return sum(min(... |
TITLE = "Metadata extractor"
SAVE = "Save"
OPEN = "Open"
EXTRACT = "Extract"
DELETE = "Delete"
META_TITLE = "title"
META_NAMES = "names"
META_CONTENT = "content"
META_LOCATIONS = "locations"
META_KEYWORD = "keyword"
META_REF = "reference"
TYPE_TXT = "txt"
TYPE_ISO19115v2 = "iso19115v2"
TYPE_FGDC = "fgdc"
LABLE_NAME... |
# ORDENANDO UMA LISTA DE FORMA PERMANENTE COM O MÉTODO sort()
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
# ORDENANDO UMA LISTA EM ORDEM ALFABÉTICA INVERSA
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)
# ORDENANDO UMA LISTA TEMPORARIAMENTE COM O MÉTODO sorted()
... |
class SpaceAge(object):
def __init__(self, seconds):
self.seconds = seconds
def on_earth(self):
return round(self.seconds / 31557600, 2)
def on_mercury(self):
earth = self.on_earth()
return round(earth / 0.2408467, 2)
def on_venus(self):
return round(self.s... |
class Tester(object):
def __init__(self):
self.results = dict()
self.params = dict()
self.problem_data = dict()
def set_params(self, params):
self.params = params |
"""
Forçando tipos de dados com decoradores
-> Função zip()
a = (1, 3, 5)
b = (2, 4, 6)
c = zip(a, b)
(1, 2), (3, 4), (5, 6)
"""
def forca_tipo(*tipos):
def decorador(funcao):
def converte(*args, **kwargs):
novo_args = []
for (valor, tipo) in zip(args, tipos):
... |
class Solution(object):
def find132pattern(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
stack = []
s3 = -float("inf")
for n in nums[::-1]:
if n < s3: return True
while stack and stack[-1] < n: s3 = stack.pop()
sta... |
class SlackResponseTool:
@classmethod
def response2is_ok(cls, response):
return response["ok"] is True
@classmethod
def response2j_resopnse(cls, response):
return response.data
|
#!/usr/bin/env python
NAME = 'Cloudflare (Cloudflare Inc.)'
def is_waf(self):
# This should be given first priority (most reliable)
if self.matchcookie('__cfduid'):
return True
# Not all servers return cloudflare-nginx, only nginx ones
if self.matchheader(('server', 'cloudflare-nginx')) or s... |
s = input()
K = int(input())
n = len(s)
substr = set()
for i in range(n):
for j in range(i + 1, i + 1 + K):
if j <= n:
substr.add(s[i:j])
substr = sorted(list(substr))
print(substr[K - 1])
|
def exc():
a=10
b=0
try:
c=a/b
except(ZeroDivisionError ):
print("Divide by zero")
exc()
|
"""
More list manipulations
"""
def split(in_list, index):
"""
Parameters
----------
in_list: list
index: int
Returns
----------
Two lists, splitting in_list by 'index'
Examples
----------
>>> split(['a', 'b', 'c', 'd'], 3)
(['a', 'b', 'c'], ['d'])
""... |
__version__ = "0.3.43"
def doc_version():
"""Use this number in the documentation to avoid triggering updates
of the whole documentation each time the last part of the version is
changed."""
parts = __version__.split(".")
return parts[0] + "." + parts[1]
|
"""
Bars Module
"""
def starbar(num):
print('*' * num)
def hashbar(num):
print('#' * num)
def simplebar(num):
print('-' * num)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def is_odd(num):
return num % 2 == 1
def not_empty(s):
return s and s.strip()
print(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])))
print(list(filter(not_empty, ['A', '', 'B', None, 'C', ' '])))
# 生成从3开始的奇数
def ge_num():
n = 1
while True:
n = n + 2
yield n
#... |
A, B, K = map(int, input().split())
for i, num in enumerate(range(A, B + 1)):
if i + 1 > K:
break
print(num)
x = []
for i, num in enumerate(range(B, A-1, -1)):
if i + 1 > K:
break
x.append(num)
x.sort()
k = B - A +1
for i in x:
if k < 2 * K:
k += 1
else:
print(i... |
s = sum(range(1, 101)) ** 2
ss = sum(list(map(lambda x: x ** 2, range(1, 101))))
print(s - ss)
|
#-*- coding: utf-8 -*-
class SQLForge:
"""
SQLForge
This class is in charge of providing methods to craft SQL queries. Basically,
the methods already implemented fit with most of the DBMS.
"""
def __init__(self, context):
""" Constructor
context: context to associate the for... |
class Solution(object):
def generateParenthesis(self, n):
# corner case
if n == 0:
return []
# level: tree level
# openCount: open bracket count
def dfs(level, n1, n2, n, stack, ret, openCount):
if level == 2 * n:
ret.append("".join(... |
def find(n: int):
for i in range(1, 1000001):
total = 0
for j in str(i):
total += int(j)
total += i
if total == n:
print(i)
return
print(0)
find(int(input()))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.