content stringlengths 7 1.05M |
|---|
'''
This problem was asked by Facebook.
Implement regular expression matching with the following special characters:
. (period) which matches any single character
* (asterisk) which matches zero or more of the preceding element
That is, implement a function that takes in a string and a valid regular
expression and r... |
def permutations_with_dups(string):
hash_table = {}
permutations = []
for character in string:
if character in hash_table:
hash_table[character] += 1
else:
hash_table[character] = 1
helper('', hash_table, permutations)
return permutations
def helper(string, ... |
"""
Sudoku solver script using a backtracking algorithm.
"""
def find_empty_location(grid):
"""
Looks for the coordinates of the next zero value on the grid,
starting on the upper left corner, from left to right and top to bottom.
Keyword Arguments:
grid {number matrix} -- The matrix to look f... |
#
# @lc app=leetcode id=1004 lang=python3
#
# [1004] Max Consecutive Ones III
#
# https://leetcode.com/problems/max-consecutive-ones-iii/description/
#
# algorithms
# Medium (61.32%)
# Likes: 2593
# Dislikes: 40
# Total Accepted: 123.4K
# Total Submissions: 202.1K
# Testcase Example: '[1,1,1,0,0,0,1,1,1,1,0]\n2'... |
SECRET_KEY = "fake-key"
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"rest_email_manager",
]
TEMPLATES = [
{
"BACKEND": "django.template.backends.djan... |
"""BaseMetric class."""
class BaseMetric:
"""Base class for all the metrics in SDMetrics.
Attributes:
name (str):
Name to use when reports about this metric are printed.
goal (sdmetrics.goal.Goal):
The goal of this metric.
min_value (Union[float, tuple[float]])... |
photos = Photo.objects.all()
captions = []
for idx, photo in enumerate(photos):
if idx > 2:
break
thumbnail_path = photo.thumbnail.url
with open("." + thumbnail_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
encoded_string = str(encoded_string)[2:-1]
resp_captions = requests.po... |
def quickSort(my_array):
qshelper(my_array, 0, len(my_array) - 1)
return my_array
def qshelper(my_array, start, end):
if start >= end:
return
pivot = start
left = start + 1
right = end
while right >= left:
if my_array[left] > my_array[pivot] and my_array[right] < ... |
#!/usr/bin/env python
"""
MULTPOTS Multiply potentials into a single potential
newpot = multpots(pots)
multiply potentials : pots is a cell of potentials
potentials with empty tables are ignored
if a table of type 'zero' is encountered, the result is a table of type
'zero' with table 0, and empty variables.
"""
def... |
class Category:
def __init__(self, name):
self.name = name
self.ledger = []
def __str__(self):
l = len(self.name)
n1 = 15-int(l/2)
n2 = 30-(n1+l)
title = "*"*n1+self.name+"*"*n2+"\n"
summary = ""
for item in self.ledger:
a= format(item[... |
#Max value from a list
numbers = []
lenght = int(input("Enter list lenght...\n"))
for i in range(lenght):
numbers.append(float(input("Enter an integer or decimal number...\n")))
print("The min value is: " + str(min(numbers)))
|
#----------------------------------------------------------------------------------------------------------
#
# AUTOMATICALLY GENERATED FILE TO BE USED BY W_HOTBOX
#
# NAME: Reconnect by Title
# COLOR: #6b4930
#
#----------------------------------------------------------------------------------------------------------
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
# def __init__(self):
# self.curr_head = None
#
# def isPalindrome(self, head):
# """
# :type head: ListNode
# ... |
# -*- coding:utf-8 -*-
# filename: units/__init__.py
# by スノル
__version__ = "0.2.0"
__all__ = []
|
class SisChkpointOpType(basestring):
"""
Checkpoint type
Possible values:
<ul>
<li> "scan" - Scanning volume for fingerprints,
<li> "start" - Starting a storage efficiency
operation,
<li> "check" - Checking for stale data in the
fingerprint database,
<li>... |
l = ["Camera", "Laptop", "Phone", "ipad", "Hard Disk", "Nvidia Graphic 3080 card"]
# sentence = "~~".join(l)
# sentence = "==".join(l)
sentence = "\n".join(l)
print(sentence)
print(type(sentence)) |
# Linked List, Two Pointers
# Given a singly linked list, determine if it is a palindrome.
#
# Example 1:
#
# Input: 1->2
# Output: false
# Example 2:
#
# Input: 1->2->2->1
# Output: true
# Follow up:
# Could you do it in O(n) time and O(1) space?
# Definition for singly-linked list.
# class ListNode(object):
# d... |
# Copyright 2021 Google LLC
#
# 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, s... |
"""
Module to handle universal/general constants used across files.
"""
################################################################################
# Constants #
################################################################################
# GENERAL CONSTANTS:
VERY_SMALL_NUMBER = 1e-31
INF = 1e20
_PAD_TOKEN... |
def test_catch_server__get(testdir):
testdir.makepyfile(
"""
import urllib.request
def test_get(catch_server):
url = "http://{cs.host}:{cs.port}/get_it".format(cs=catch_server)
request = urllib.request.Request(url, method="GET")
with urllib.request.urlop... |
# Roll the Dice #
# November 17, 2018
# By Robin Nash
n = int(input())
m = int(input())
if n > 10:
n = 9
if m > 10:
m = 9
ways = 0
for n in range (1,n+1):
for m in range(1,m+1):
if n + m == 10:
ways+=1
if ways == 1:
print("There is 1 way to get the sum 10.")
e... |
núm = (int(input('Digite um número: ')), \
int(input('Digite outro número: ')), \
int(input('Digite mais um número: ')),\
int(input('Digite o último número: ')))
print(f'Você digitou os valores {núm}')
print(f'O valor 9 apareceu {núm.count(9)} vezes!')
if 3 in núm:
print(f'O valor 3 ap... |
Carros = ['HRV', 'Polo', 'Jetta', 'Palio', 'Fusca']
itCarros = iter(Carros)
while itCarros:
try:
print(next(itCarros))
except StopIteration:
print('Fim da Lista.')
break |
def default_colors(n):
n = max(n, 8)
clist = ["#1b9e77", "#d95f02", "#7570b3", "#e7298a", "#66a61e", "#e6ab02",
"#a6761d", "#666666"]
return clist[:n]
|
def nth_fibonacci_using_recursion(n):
if n < 0:
raise ValueError("n should be a positive number or zero")
else:
if n == 1:
return 0
elif n == 2:
return 1
else:
return nth_fibonacci_using_recursion(n - 2) + nth_fibonacci_using_recursion(n - 1)
... |
class OpenInterest:
def __init__(self):
self.symbol = ""
self.openInterest = 0.0
@staticmethod
def json_parse(json_data):
result = OpenInterest()
result.symbol = json_data.get_string("symbol")
result.openInterest = json_data.get_float("openInterest")
... |
with open("input.txt") as input_file:
time = int(input_file.readline().strip())
busses = input_file.readline().strip().split(",")
def departures(bus):
multiplier = 0
while True:
multiplier += 1
yield multiplier * bus
def next_after(bus, time):
for departure in departures(bus):
... |
# -*- coding: utf-8 -*-
maior = -1
index_maior = -1
for i in range(1, 101):
n = int(input())
if n > maior:
maior = n
index_maior = i
print(maior)
print(index_maior)
|
# Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit.
t = float(input('Digite a temperatura em °C: '))
print('A temperatura {}ºC equivale a {}°F'.format(t,((( 9 / 5 ) * t) + 32)))
|
# This sample tests a particularly difficult set of dependent
# assignments that involve tuple packing and unpacking.
# pyright: strict
v1 = ""
v3 = ""
v2, _ = v1, v3
v4 = v2
for _ in range(1):
v1 = v4
v2, v3 = v1, ""
|
"""
1- Bir listeyi düzleştiren (flatten) fonksiyon yazın. Elemanları birden çok katmanlı listelerden ([[3],2] gibi) oluşabileceği gibi, non-scalar verilerden de oluşabilir. Örnek olarak:
input: [[1,'a',['cat'],2],[[[3]],'dog'],4,5]
output: [1,'a','cat',2,3,'dog',4,5]
2- Verilen listenin içindeki elemanları tersine d... |
nome = input('\033[1;31mOlá! Qual é o seu nome? ')
n1 = int(input(f'\033[1;31mMuito prazer, {nome}!\n\033[34mPor favor, poderia digitar um número? '))
n2 = int(input('\033[34mCerto! Digite outro número: '))
print('\033[32mHm... Deixe-me pensar...\033[m')
s = n1+n2
print('.')
print('.')
print('.')
print('.')
print('.')
... |
class DNABattleCell:
COMPONENT_CODE = 21
def __init__(self, width, height, pos):
self.width = width
self.height = height
self.pos = pos
def setWidth(self, width):
self.width = width
def setHeight(self, height):
self.height = height
def setWidthHeight(self,... |
def median(a):
a = sorted(a)
list_length = len(a)
num = list_length//2
if list_length % 2 == 0:
median_num = (a[num] + a[num + 1])/2
else:
median_num = a[num]
return median_num
|
class DeviceGroup:
def __init__(self, name):
self.name = name
self.devices = []
def addDevice(self, newDevice):
self.devices.append(newDevice)
# Just thinking through how I want the program to work.
# A diskgroup should be initialized once every time the service is started. ... |
def hed_setup(E_h, E_e):
"""
使用理解矩阵构建HEX图
:param E_h: H-edge-mat
:param E_e: E-edge-mat
:return: G
"""
|
#!/usr/bin/env python3
def read_text():
"""Reads a line of text, stripping whitespace."""
return input().strip()
def distance(s, t):
"""Wagner-Fischer algorithm"""
if len(s) < len(t):
s, t = t, s
pre = [None] * (len(t) + 1)
cur = list(range(len(pre)))
for i, sc in enumerate(s, ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 27 21:06:27 2021
@author: RGJG
"""
global A
global posicion
A=[]
posicion=0
def modos(archivo,identificador,modo,A,posicion):
A.append([archivo,identificador,modo,posicion,False])
return A
print("""dir → Muestra el directorio
open <arch> <modo> → Especifica que o... |
# -*- coding: utf-8 -*-
"""
665. Non-decreasing Array
Given an array nums with n integers, your task is to check if it could become non-decreasing
by modifying at most 1 element.
We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).
Constraints:
1 <=... |
"""
Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro e o último nome separadamente.
Ex: Ana Maria de Sousa
primeiro = Ana
último = Sousa
"""
valor_digitado = input('Digite seu nome completo: ')
transformar_valor_digitado_em_lista = valor_digitado.split()
primei... |
# -*- coding: utf-8 -*-
"""
Given a sorted array and a target value, return the index if the target is
found. If not, return the index where it would be if it were inserted in
order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
... |
# -*- coding: utf-8 -*-
USER_ROLE = {
'USER': 0,
'MODERATOR': 1,
'ADMINISTRATOR': 2,
} |
a = 1
print("a_module: Hi from my_package/" + __name__ + ".py!")
if __name__ == "__main__":
print("a_module: I was invoked from a script.")
else:
print("a_module: I was invoked from a Pyton module (probably using 'import').")
print("a_module: My name is =", __name__)
|
#
# PySNMP MIB module ZYXEL-MES2110-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-MES2110-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:50:49 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
userNum = int(input("Input a number: "))
out = ""
numeralArr = [(1000, "M"), (500, "D"), (100, "C"), (50, "L"), (10, "X"), (5, "V"), (1, "I"), (0, ""), (0, "")]
def convert(num, nums, iters, halfs):
global out
if n... |
d = {}
palavra = 'Felipe Schmaedecke'
for l in palavra:
if l in d:
d[l] = d[l] + 1
else:
d[l] = 1
print(d)
|
class ECA:
def __init__(self, id):
self.id = bin(id)[2:].zfill(8)
self.dict = {}
for i in range(8):
self.dict[bin(7 - i)[2:].zfill(3)] = self.id[i]
self.array = [0 for x in range(199)]
self.array[99] = 1
def step(self):
arr = [0 for x in range(len(s... |
expected_output = {
"service_instance": {
501: {
"interfaces": {
"TenGigabitEthernet0/3/0": {"state": "Up", "type": "Static"},
"TenGigabitEthernet0/1/0": {"state": "Up", "type": "Static"},
}
},
502: {
"interfaces": {"TenGiga... |
class KNNClassifier(object):
def __init__(self, k=3, distance=None):
self.k = k
self.distance = distance
def fit(self, x, y):
pass
def predict(self, x):
pass
def __decision_function(self):
pass
|
'''
Given a linked list, swap every two adjacent nodes and return its head.
You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# s... |
with open("Prob03.in.txt") as f:
content = f.readlines()
content = [x.strip() for x in content]
nola = content.pop(0)
for x in content:
x = x.strip(" ")
x = x.split()
add = int(x[0]) + int(x[1])
multi = int(x[0]) * int(x[1])
print( str(add) + " " + str(multi))
|
## Script (Python) "getFotoCapa"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=Retorna um nome de arquivo para ser usado como foto da capa
padrao = [ 'capa01.jpg','capa02.jpg','capa03.jpg','capa04.jpg','capa05.jpg', \
... |
numero = int(input('Digite um número: '))
a = numero - 1
s = numero + 1
print('Seu número é {} o antecessor é {} e o sucessor é {}'.format(numero, a, s))
|
'''
Escreva um programa que pergunte o salário de
um funcionário e calcule o valor do seu aumento
-> Para salários superiores a R$ 1250,00 calcule aumento de 10%
-> Para os inferiores ou iguais, o aumento é de 15%.
'''
salario = float(input("Digite o seu salário: "))
s = salario
if salario > 1250:
salario = sa... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
class DoubanPipeline(object):
# def __init__(self, server, port):
# pass
# @classmethod
# def from_craw... |
#
# PySNMP MIB module CISCO-LAG-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LAG-CAPABILITY
# Produced by pysmi-0.3.4 at Mon Apr 29 17:47:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
def test_epl_single_year_mtl(style_checker):
"""Style check test against epl_single_year.mtl
"""
style_checker.set_year(2017)
p = style_checker.run_style_checker('--config=module_config.yaml',
'whatever', 'epl_single_year.mtl')
style_checker.assertEqual(p.stat... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 14 07:44:37 2020
@author: ucobiz
"""
values = [] # initialize the list to be empty
userVal = 1 # give our loop variable a value
while userVal != 0:
userVal = int(input("Enter a number, 0 to stop: "))
if userVal != 0: # only append if it's v... |
mylist = ["banana", "apple", "pineapple"]
print(mylist)
item = mylist[2]
print(item)
if "banana" in mylist:
print("yes")
else:
print("no")
mylist.append("lemon")
print(mylist)
mylist.insert(2, "grapes")
print(mylist)
# /item = [0] * 5
# print(item)
|
# ------------------------------
# 787. Cheapest Flights Within K Stops
#
# Description:
# There are n cities connected by m flights. Each fight starts from city u and arrives at
# v with a price w.
#
# Now given all the cities and flights, together with starting city src and the destination
# dst, your task is to ... |
# These functions deal with displaying information in CLI
## Check Payment Display
def display_lessons(lessons):
print('displaying lesson payment info')
unpaid_lessons = []
paid_lessons = []
for lesson in lessons:
if lesson['paid'] == 'n':
unpaid_lessons.append(lesson)
elif... |
city = input("Enter city name = ")
sales = int(input("Enter sales volume = "))
cities = ["Sofia", "Varna", "Plovdiv"]
index = 4
#Discounts by cities
if 0 <= sales and sales <= 500:
comision = [0.05,0.045,0.055]
elif 500 < sales and sales <= 1000:
comision = [0.07,0.075,0.08]
elif 1000 < sales and sales <= 1000... |
#! /usr/bin/python3
# -*- coding: utf-8 -*-S
def crypt(line: str) -> str:
result = str()
for symbol in line:
result += chr(ord(symbol) + 1)
return result
print(crypt(input()))
|
class Solution:
# not my soln but its very cool
def threeSum(self, nums: List[int]) -> List[List[int]]:
triplets = set()
neg, pos, zeros = [], [], 0
for num in nums:
if num > 0:
pos.append(num)
elif num < 0:
neg.append(num)
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 4 09:38:16 2021
@author: gregoryvanbeek
"""
#%%INPUT
flag = 1040
verbose=True
#%%
def samflags(flag=0, verbose=True):
"""This script converts a decimal flag to binary and get the corresponding properties according to the sam-flag standard.
The code is based on... |
# -*- coding: utf-8 -*-
#
# Copyright 2016 Continuum Analytics, Inc.
# May be copied and distributed freely only as part of an Anaconda or
# Miniconda installation.
#
"""
Custom errors on Anaconda Navigator.
"""
class AnacondaNavigatorException(Exception):
pass
|
def change_return(amount,currency):
currency.sort(reverse = True)
counter = 0
amount_counter = [0]*len(currency)
while amount> 0:
amount_counter[counter] = int(amount/currency[counter])
amount -= amount_counter[counter]*currency[counter]
counter += 1
return [(currency[i],amou... |
# helpers.py, useful helper functions for wikipedia analysis
# We want to represent known symbols (starting with //) as words, the rest characters
def extract_tokens(tex):
'''walk through a LaTeX string, and grab chunks that correspond with known
identifiers, meaning anything that starts with \ and ends wit... |
# -*- coding: utf-8 -*-
# 0xCCCCCCCC
# Like Q153 but with possible duplicates.
def find_min(nums):
"""
:type nums: List[int]
:rtype: int
"""
l, r = 0, len(nums) - 1
while l < r and nums[l] >= nums[r]:
m = (l + r) // 2
if nums[m] > nums[r]:
l = m + 1
elif num... |
def seed_everything(seed=2020):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
tf.random.set_seed(seed)
seed_everything(42) |
#Faça um programa que leia nome e média de um aluno, guardando também a situação em um dicionário. No final,
# mostre o conteúdo da estrutura na tela.
aluno = dict()
aluno['nome'] = str(input('Nome:'))
aluno['média'] = float(input(f'Média de {aluno["nome"]}'))
if aluno['média'] >= 7:
aluno['situação'] = 'APROVADO'... |
"""Tabler."""
__title__ = "enigma"
__description__ = "Enigma emulator"
__url__ = ""
__version__ = "0.1"
__author__ = "Luke Shiner"
__author_email__ = "luke@lukeshiner.com"
__license__ = "MIT"
__copyright__ = "Copyright 2019 Luke Shiner"
|
class Solution:
def XXX(self, root: TreeNode) -> int:
if not root:
return 0
self.min_depth = float('inf')
def dfs(root, depth):
if not root:
return
if not root.left and not root.right:
self.min_depth = min(self.min_depth, d... |
#!/usr/bin/env python3
# Find the middle element in the list.
# Create a function called middle_element that has one parameter named lst.
# If there are an odd number of elements in lst, the function
# should return the middle element.
# If there are an even number of elements, the function should
# return the average... |
INPUT = """1919 2959 82 507 3219 239 3494 1440 3107 259 3544 683 207 562 276 2963
587 878 229 2465 2575 1367 2017 154 152 157 2420 2480 138 2512 2605 876
744 6916 1853 1044 2831 4797 213 4874 187 6051 6086 7768 5571 6203 247 285
1210 1207 1130 116 1141 563 1056 155 227 1085 697 735 192 1236 1065 156
682 883 187 307... |
class Microstate():
def __init__(self):
self.index = None
self.label = None
self.weight = 0.0
self.probability = 0.0
self.basin = None
self.coordinates = None
self.color = None
self.size = None
|
intraband_incharge = {
"WEIMIN": None,
"EBREAK": None,
"DEPER": None,
"TIME": None,
}
|
program_name = 'giraf'
program_desc = 'A command line utility to access imgur.com.'
|
def profile_likelihood_maximization(U, n_elbows, threshold):
"""
Inputs
U - An ordered or unordered list of eigenvalues
n - The number of elbows to return
Return
elbows - A numpy array containing elbows
"""
if type(U) == list: # cast to array for functionality later
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.