content stringlengths 7 1.05M |
|---|
#Given an array nums and a value val, remove all instances of that value in-place and return the new length.
#Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
#The order of elements can be changed. It doesn't matter what you leave beyond the... |
class Button():
LEFT = 0
CENTER = 1
RIGHT = 2
class Key():
""" Key codes for InputEmulation.Keyboard object.
Can be entered directly or concatenated with an existing string, e.g. ``type(Key.TAB)`` """
ENTER = "{ENTER}"
ESC = "{ESC}"
BACKSPACE = "{BACKSPACE}"
DELETE = "{DELET... |
#!/bin/env/python
infileList = []
keyList = []
cList = (
"GBR",
"FIN",
"CHS",
"PUR",
"CLM",
"IBS",
"CEU",
"YRI",
"CHB",
"JPT",
"LWK",
"ASW",
"MXL",
"TSI",
)
for i in range(17,23):
infileList.app... |
n = int(input())
sumI = 0
for i in range(n):
sumI = sumI + int(input())
o = int(input())
for i in range(o):
sumI = sumI + int(input())
print('{:.3f}'.format((round(sumI*1000/(n+i+1)))/1000))
|
nome = str(input('Digite seu nome: ')).strip()
print('Seu nome em letras maiúsculas: {}'.format(nome.upper()))
print('Seu nome em letras minúsculas: {}'.format(nome.lower()))
print('Seu nome sem espaços: {}'.format(len(nome.replace(' ', ''))))
print('Seu primeiro nome tem: {} caracteres'.format(len(nome.split()[0])))
|
#-*- codeing = utf-8 -*-
#@Time : 2021-01-14 19:41
#@Author : 苏苏
#@File : 第五课作业二.py
#@Software : PyCharm
#用递归实现阶乘函数factorial(n),对于任意的整数n都能返回其对应的阶乘。
def factorial(n):
if n == 0:
return 1
else:
return n*factorial(n-1)
|
class HeapError(Exception):
pass
class Heap(object):
def __init__(self, iterable=()):
self._heap = []
for value in iterable:
self.push(value)
def _get(self, node):
if not self._heap:
raise HeapError("empty heap")
if node is None:
retur... |
# Sum of numbers 3
def get_sum(x, y):
s = 0
if x > y:
for index in range(y, x + 1):
s = s + index
return s
elif x < y:
for index in range(x, y + 1):
s = s + index
return s
else:
return x
print(get_sum(2, 1))
print(get_sum(0, -1))
|
# EMPTY = "L"
# OCCUPIED = "#"
# FIXED = "."
EMPTY = 0
OCCUPIED = 1
FIXED = -1
def read_input(file_name):
seats = []
with open(file_name) as input_file:
for line in input_file:
line = line.strip()
seats.append( list(map(map_input, line) ))
return seats
# Failed attempt to... |
# When user enters 'exit', exit program
while (True):
inp = raw_input('> ')
if inp.lower() == 'exit':
break
else:
print(inp)
|
"""
Constants for the CLI.
"""
WELCOME_MESSAGE = "Welcome to [bold green]{{cookiecutter.project_slug}}!![/bold green] Your CLI is working!"
|
"""Constants for ThermiaGenesis integration."""
KEY_ATTRIBUTES = 'attributes'
KEY_ADDRESS = 'address'
KEY_RANGES = 'ranges'
KEY_SCALE = 'scale'
KEY_REG_TYPE = 'register_type'
KEY_BITS = 'bits'
KEY_DATATYPE = 'datatype'
TYPE_BIT = 'bit'
TYPE_INT = 'int'
TYPE_UINT = 'uint'
TYPE_LONG = 'long'
TYPE_STATUS = 'status'
REG_... |
# https://leetcode.com/problems/bulls-and-cows
class Solution:
def getHint(self, secret, guess):
s_used, g_used = set(), set()
bull = 0
for idx, (s_char, g_char) in enumerate(zip(secret, guess)):
if s_char == g_char:
bull += 1
s_used.add(idx)
... |
__version__ = '0.2.2'
default_app_config = 'cid.apps.CidAppConfig'
|
# -*- coding: utf-8 -*-
"""FamilySearch Discovery submodule"""
# Python imports
# Magic
class Discovery(object):
"""https://familysearch.org/developers/docs/api/tree/FamilySearch_Collections_resource"""
def __init__(self):
"""https://familysearch.org/developers/docs/api/resources#disc... |
#
# PySNMP MIB module HH3C-IDS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-IDS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:27:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... |
class ServerNotRespondingException(BaseException):
"""
Exception raised when the requested server is not responding.
"""
def __init__(self, url):
self.url = url
def __str__(self):
return "Url '%s' is not responding." % self.url
class ExceededRequestsLimitException(BaseException):... |
temperaturaFahrenheit = input("Digite uma temperatura em Fahrenheit: ")
temperaturaCelsius = (float(temperaturaFahrenheit) -32) * 5/9
print("A temperatura em celsius é",temperaturaCelsius) |
def listens_to_mentions(regex):
"""
Decorator to add function and rule to routing table
Returns Line that triggered the function.
"""
def decorator(func):
func.route_rule = ('mentions', regex)
return func
return decorator
def listens_to_all(regex):
"""
Decorator to add... |
class TrieNode():
def __init__(self, letter=''):
self.children = {}
self.is_word = False
def lookup_letter(self, c):
if c in self.children:
return True, self.children[c].is_word
else:
return False, False
class Trie():
def __init__(self):
se... |
"""
São duas constantes, VERDADEIRO ou FALSO
TRUE: Verdadeiro
FALSE: Falso
OBS.: Sempre começa com Maiuscula
OPERAÇÕES BASICAS
#NEGAÇÃO (not): Sé verdadeiro é falso e se falso é verdadeiro. SEMPRE AO CONTRARIO
Ex.: usr=True
print(not usr) -> False
#(or): Operação binária... |
def calcula_fatorial(n):
resultado = 1
for i in range(1, n+1):
resultado = resultado * i
return resultado
def imprime_numeros(n):
imprimir = ""
for i in range(n, 0, -1):
imprimir += "%d . " %(i)
return imprimir[:len(imprimir) - 3]
numero = int(input("Digite um numero: "))
... |
class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
rooms = 0
if not intervals:
return 0
endp = 0
starts = sorted([i[0] for i in intervals])
ends = sorted([i[1] for i in intervals])
for i in ran... |
# -*- coding: utf-8 -*-
# --------------------------------------------------------
# Licensed under the terms of the BSD 3-Clause License
# (see LICENSE for details).
# Copyright © 2018-2021, A.A Suvorov
# All rights reserved.
# --------------------------------------------------------
class IteratorBase:
"""Base ... |
# Copyright (C) 2021 Intel Corporation
#
# SPDX-License-Identifier: MIT
class PointCloudPath:
BASE_DIR = 'ds0'
ANNNOTATION_DIR = 'ann'
DEFAULT_IMAGE_EXT = '.jpg'
POINT_CLOUD_DIR = 'pointcloud'
RELATED_IMAGES_DIR = 'related_images'
KEY_ID_FILE = 'key_id_map.json'
META_FILE = 'meta.json'
... |
VIDEO_ELEMENT = 'videoRenderer'
CHANNEL_ELEMENT = 'channelRenderer'
PLAYLIST_ELEMENT = 'playlistRenderer'
SHELF_ELEMENT = 'shelfRenderer'
class ResultMode:
json = 0
dict = 1
class SearchMode:
videos = 'EgIQAQ%3D%3D'
channels = 'EgIQAg%3D%3D'
playlists = 'EgIQAw%3D%3D'
class VideoU... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright SAS Institute
#
# 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... |
# This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.
DOUBAN_COOKIE = {
"__gads": "ID=2421173a5ca57aed-228b4c29c5c800c1:T=1621494084:RT=1621494084:S=ALNI_MaJlRkH7cibeVPuRhGgoy4NehQdpw",
"__utma": "8137958... |
class Mail:
def __init__(self, prot, *argv):
self.prot = prot(*argv)
def login(self, account, passwd):
self.prot.login(account, passwd)
def send(self, frm, to, subject, content):
self.prot.send(frm, to, subject, content)
def quit(self):
self.prot.quit()
|
class BaseError(Exception):
error_id = ""
error_msg = ""
def __repr__(self):
return "<{err_id}>: {err_msg}".format(
err_id=self.error_id,
err_msg=self.error_msg,
)
def render(self):
return dict(
error_id=self.error_id,
error_msg=s... |
TOTAL_BUDGET_AUTHORITY = 8361447130497.72
TOTAL_OBLIGATIONS_INCURRED = 4690484214947.31
WEBSITE_AWARD_BINS = {
"<1M": {"lower": None, "upper": 1000000},
"1M..25M": {"lower": 1000000, "upper": 25000000},
"25M..100M": {"lower": 25000000, "upper": 100000000},
"100M..500M": {"lower": 100000000, "upper": 500... |
class NotificationData(object):
"""
Class used to represent notification data.
Attributes:
veh_id (int): The vehicle ID.
req_id (int): The request ID.
waiting_duration (str): The waiting duration.
assigned (bool): True if assigned, false if not.
"""
def __init__(self... |
def f():
x: list[list[i32]]
x = [[1, 2, 3]]
y: list[list[str]]
y = [['a', 'b']]
x = y
|
permissions = {
"on_permissions": {
"all": "0",
"uids": [],
"badges": {
"broadcaster": "1"
},
"forbid": {
"all": "0",
"uids": [],
"badges": {}
}
},
"on_channel": {
"all": "0",
"uids": [],
... |
pinoy_jokes = {
1: {'dialect': 'bisaya',
'joke': ['Teban: Dok, ngano gasakit man akong dughan kada inum nakug '
'tuba, pero kung libre gani dili mosakit??',
'Doktor: Ah kabalo nako ana, nipis imong BAGA, pero BAGA IMONG '
'NAWONG']},
2: {'dialect': 'bisaya',
'jok... |
a = 0
def fun1():
print("fun1: a=", a)
def fun2():
a = 10 # By default, the assignment statement creates variables in the local scope
print("fun2: a=", a)
def fun3():
global a # refer global variable
a = 5
print("fun3: a=", a)
fun1()
fun2()
fun1()
fun3()
fun1()
|
# -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:36 ms, 在所有 Python3 提交中击败了91.91% 的用户
内存消耗:13.8 MB, 在所有 Python3 提交中击败了5.59% 的用户
解题思路:
深度优先搜索
然后进行翻转
"""
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
record = {}
def dfs(root, d): # 深度优先,使用字典记录每层的节点值
... |
seq = []
n = 1
while n:
n = int(input(print("Digite um número: ")))
if n != 0:
seq.append(n)
print(seq)
print(seq[:-1])
|
def reverse_string(string):
reversed_letters = list()
index = 1
for letter in string:
reversed_letters.append(string[ len(string) - index ])
index += 1
return "".join(reversed_letters)
word_input = str(input("Input a word: "))
print(f"INPUT: {word_input}")
print("OUTPUT: %s (%d char... |
def conta_a(palavra):
c = 0
for letra in palavra:
if letra == 'a':
c += 1
return c
s = 'Insper'
r = s[::-2]
print(r)
|
#String functions
myStr = 'Hello world!'
#Capitalize
print(myStr.capitalize())
#Swap case
print(myStr.swapcase())
#Get length
print(len(myStr))
#Replace
print(myStr.replace('world', 'everyone'))
#Count
sub = 'l'
print(myStr.count(sub))
#Startswith
print(myStr.startswith('Hello'))
#Endswith
print(myStr.endswith(... |
# Faça um mini-sistema que utilize o Interactive Help do Python. O usuário vai digitar o comando e o manual vai aparecer.
# Quando o usuário digitar a palavra 'FIM', o programa se encerrará. Importante: use cores.
c = ('\033[m','\033[1;32m','\033[1;31m','\033[7:30m')
cores = {'limpa':'\033[m',
'bverde... |
#!/usr/bin/env python
DESCRIPTION = "Variant of djb2 hash in use by Nokoyawa ransomware"
# Type can be either 'unsigned_int' (32bit) or 'unsigned_long' (64bit)
TYPE = 'unsigned_int'
# Test must match the exact has of the string 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
TEST_1 = 3792689168
def ... |
'''
Faça um programa que leia a largura e a altura de uma parede
em metros, calcule a sua área e a quantidada de tinta
necessária para pintá-la. Sabendo que cada litro de
tinta, pinta uma área de 2m quadrados.
'''
l = float(input('Digite o valor da largura: '))
h = float(input('Digite o valor da altura: '))
a = l * ... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"Scraper": "00_scraper.ipynb",
"Scraper.get_facebook_posts": "00_scraper.ipynb",
"print_something": "00_scraper.ipynb"}
modules = ["scraper.py"]
doc_url = "https://devacto.github.io/talk_l... |
class Solution:
def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
FI_A = list()
for row in A:
row = [0 if i else 1 for i in row[::-1]]
FI_A.append(row)
return FI_A
|
{{AUTO_GENERATED_NOTICE}}
load("@{{REPO_NAME}}//:rules.bzl", "rescript_compiler")
rescript_compiler(
name = "darwin",
bsc = ":darwin/bsc.exe",
bsb_helper = ":darwin/bsb_helper.exe",
visibility = ["//visibility:public"],
)
rescript_compiler(
name = "linux",
bsc = ":linux/bsc.exe",
bsb_helpe... |
def myFunction():
print('The value of __name__ is ' + __name__)
def main():
myFunction()
if __name__ == '__main__':
main() |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 2 10:39:47 2019
@author: ldh
"""
# __init__.py |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Yue-Wen FANG'
__maintainer__ = "Yue-Wen FANG"
__email__ = 'fyuewen@gmail.com'
__license__ = 'Apache License 2.0'
__creation_date__= 'Dec. 26, 2018'
"""
single inheritance
"""
class Person:
"""
define a CLASS Person with three methods
"""
de... |
tokens = {
'ID': r'[A-Za-z][A-Za-z_0-9]*',
'FLOATNUM': r'(([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)([Ee][+-]?[0-9]+)?|[0-9]+[Ee][+-]?[0-9]+)',
'INTNUM': r'[0-9]+',
# Multi-character operators
'==': r'==',
'<=': r'<=',
'>=': r'>=',
'<>': r'<>',
'::': r'::',
}
special_characters = '<>+-*/=(){}... |
# DFS: Depth First Search, 从最左侧由根向下遍历,对象有未被遍历的叶时继续往下遍历,无未被遍历叶时向上返回,返回到根时退出。
nums = [2, 0, 3, 1, 3, 4]
pst = 3
def dfs(nums, p, t=0, nb=set()):
step = nums[p]
if p - step < 0 and p + step > len(nums):
return False
if nums[p - step] == t or nums[p + step] == t:
return p - step or p + step
... |
"""
Range
range(stop)
range(start, stop)
range(start, stop, step)
default start = 0
default step = 1
"""
r = range(5, 10, 2)
print(r.start)
print(r.stop)
print(r.step)
print(type(r))
|
count = 0
maximum = (-10) ** 9
for _ in range(4):
x = int(input())
if x % 2 == 1:
count += 1
if x > maximum:
maximum = x
if count > 0:
print(count)
print(maximum)
else:
print('NO')
|
# Neon number --> If the sum of digits of the squared numbers are equal to the orignal number , the number is said to be Neon number. Example 9
ch=int(input("Enter 1 to do it with loop and 2 without loop :\n"))
n= int(input("Enter the number :\n"))
def number(n):
sq= n**2
digisum=0
while sq>0:
r... |
class Solution(object):
def partition(self, s):
self.isPalindrome = lambda s : s == s[::-1]
res = []
self.backtrack(s, res, [])
return res
def backtrack(self, s, res, path):
print(path)
if not s: #如果是空字符串 ''
res.append(path)
return... |
# [[1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]]
#
# print(((1-4) ** 2 + (4-4) ** 2 + (7-4) ** 2)/3)
def constroi_matriz(n, m):
mat = []
for i in range(n):
linha = []
for j in range(m):
linha.append(0)
mat.append(linha)
return mat
def popula_matriz(mat):
for i in range(l... |
# Desafio 43 - Aula 12 : Programa que calcule o IMC e apresente a tabela:
# A/ Abaixo de 18.5 - ABAIXO DO PESO.
# B/ Entre 18.5 e 25 - PESO IDEAL.
# C/ De 25 até 30 - SOBREPESO.
# D/ 30 até 50 - OBESIDADE.
# E/ Acima de 40 - OBESIDADE MORBIDA.
# FORMULA - ALTURA² / PESO
print('='*50)
nome = 'IMC (INDICE DE MASSA CORP... |
raio = int(input('Raio: '))
format(r,'.2f')
pi = 3.14159
volume = (4/3)*pi*raio**3
print("Volume = ", format(volume,'.3f'))
#Para o URI:
R = float(input())
format(R,'.2f')
pi = 3.14159
v = (4/3)*pi*R**3
print("VOLUME = "+format(v,'.3f')) |
# -*- coding: utf-8 -*-
# @Time: 2020/7/16 11:38
# @Author: GraceKoo
# @File: interview_8.py
# @Desc: https://www.nowcoder.com/practice/8c82a5b80378478f9484d87d1c5f12a4?tpId=13&rp=1&ru=%2Fta%2Fcoding-interviews&qr
# u=%2Fta%2Fcoding-interviews%2Fquestion-ranking
class Solution:
def climbStairs(self, n: int) -> in... |
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
def BackTrack(m, per: list):
if m == n:
if per not in permutation:
permutation.append(per)
return per
for i in range(n):
if not visited[i]:... |
def f(*args):
summ = 0
for i in args:
if isinstance(i, list):
for s in i:
summ += f(s)
elif isinstance(i, tuple):
for s in i:
summ += s
else:
summ += i
return summ
a = [[1, 2, [3]], [1], 3]
b = (1, 2, 3, 4... |
EMPTY_WORDS_PATH = "./palabrasvacias.txt"
# "palabrasvacias.txt"
# "emptywords.txt"
# None
DIRPATH = "/home/agustin/Desktop/Recuperacion/colecciones/RI-tknz-data/"
# "/home/agustin/Desktop/Recuperacion/colecciones/RI-tknz-data/"
# "/home/agustin/Desktop/Recuperacion/colecciones/wiki-small/"
# "/home/agustin/Desktop/Re... |
# 12 Tendo como dados de entrada a altura de uma pessoa, construa um algoritmo que calcule seu peso ideal, usando a seguinte fórmula: (72.7*altura) - 58
Altura = float(input("Digite sua altura: "));
PesoIdeal = ( 72.7 * Altura ) - 58;
print("Seu peso ideal é {:.2f}".format(PesoIdeal));
|
# loop3
userinput = input("Enter a letter in the range A - C : ")
while (userinput != "A") and (userinput != "a") and (userinput != "B") and (userinput != "b") and (userinput != "C") and (userinput != "c"):
userinput = input("Enter a letter in the range A-C : ")
|
class Song:
"""
@brief A Song object, used along with the Songs data source.
This is a convenience class provided for users who wish to use this
data source as part of their application. It provides an API that makes
it easy to access the attributes of this data set.
This object is generally... |
COLOR = {
'ORANGE': (255, 121, 0),
'LIGHT_YELLOW': (255, 230, 130),
'YELLOW': (255, 204, 0),
'LIGHT_BLUE': (148, 228, 228),
'BLUE': (51, 204, 204),
'LIGHT_RED': (255, 136, 106),
'RED': (255, 51, 0),
'LIGHT_GREEN': (206, 255, 60),
'GREEN': (153, 204, 0),
'CYAN': (0, 159, 218),
... |
# -*- coding: utf-8 -*-
class Solution:
def minDeletionSize(self, A):
return len([col for col in zip(*A) if col != tuple(sorted(col))])
if __name__ == '__main__':
solution = Solution()
assert 1 == solution.minDeletionSize(['cba', 'daf', 'ghi'])
assert 0 == solution.minDeletionSize(['a', 'b'... |
# https://leetcode.com/problems/simplify-path/
class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
for d in path.split('/'):
if d == '..':
if len(stack) > 0:
stack.pop()
elif d == '.' or d == '':
continue
... |
class ReplyAgreeState():
def update(self, req):
# TODO 入力
msg = ""
# 分岐
if msg == 'start':
return ['Game']
else:
raise ValueError("Unexpected condition")
|
# Guess password and output the score
chocolate = 2
playerlives = 1
playername = "Aung"
# this loop clears the screen
for i in range(1, 35):
print()
bonus = 0
numbercorrect = 0
# the player must try to guess the password
print("Now you must ener each letter that you remember ")
print("You will be given 3 times")... |
#!/usr/bin/env python3
def best_stock(data):
return sorted(data.items(), key=lambda x: x[1])[-1][0]
if __name__ == '__main__':
print(best_stock({ "CAL": 42.0, "GOG": 190.5, "DAG": 32.2 }))
assert best_stock({ "CAL": 42.0, "GOG": 190.5, "DAG": 32.2 }) == "GOG"
assert best_stock({ "CAL": 31.4, "GOG": 3... |
def find_position(matrix, size, symbol):
positions = []
for row in range(size):
for col in range(size):
if matrix[row][col] == symbol:
positions.append([row, col])
return positions
def is_position_valid(row, col, size):
return 0 <= row < size and 0 <= col < size
d... |
items = {key: {} for key in input().split(", ")}
n = int(input())
for _ in range(n):
line = input().split(" - ")
category, item = line[0], line[1]
items_count = line[2].split(";")
quantity = int(items_count[0].split(":")[1])
quality = int(items_count[1].split(":")[1])
items[category][item] = (... |
cnt = int(input())
for i in range(cnt):
s=input()
a=s.lower()
g=a.count('g')
b=a.count('b')
print(s,"is",end=" ")
if g == b:
print("NEUTRAL")
elif g>b:
print("GOOD")
else:
print("A BADDY") |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Fenwick tree
jill-jenn vie et christoph durr - 2014-2018
"""
# snip{
class Fenwick:
"""maintains a tree to allow quick updates and queries
"""
def __init__(self, t):
"""stores a table t and allows updates and queries
of prefix sums in log... |
print("Enter a character:\n")
ch=input()
while(len(ch)!=1):
print("\nShould Enter single Character...RETRY!")
ch=input()
print(ord(ch))
|
class Solution:
def parseTernary(self, expression: str) -> str:
c, values = expression.split('?', 1)
cnt = 0
p = 0
for i in range(len(values)):
if values[i] == ':':
if cnt > 0:
cnt -= 1
else:
p = i
... |
lista = []
for c in range(0, 5):
lista.append(int(input(f'Digite um valor para a posição {c}: ')))
print('=-=' * 10)
print(f'Você digitou os valores {lista}')
print(f'O maior valor digitado é o {max(lista)} e ele está na posição {lista.index(max(lista))}')
print(f'O menor valor digitado é o {min(lista)} e ele está... |
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
# just use a sliding window
np, ns = len(p), len(s)
res = []
if np > ns: return []
map_ = [0] * 26
for i,x in enumerate(p):
map_[ord(x) - 97] -= 1
map_[ord(s[i])-97]... |
'''
An N x N board contains only 0s and 1s. In each move, you can swap any 2 rows with each other, or any 2 columns with each other.
What is the minimum number of moves to transform the board into a "chessboard" - a board where no 0s and no 1s are 4-directionally
adjacent? If the task is impossible, return -1.
Examp... |
memMap = {}
def fibonacci (n):
if (n not in memMap):
if n <= 0:
print("Invalid input")
elif n == 1:
memMap[n] = 0
elif n == 2:
memMap[n] = 1
else:
memMap[n] = fibonacci (n-1) + fibonacci (n-2)
return memMap[n]
def fibonacciSlow (n):
if n <= 0:
print("Invalid inpu... |
class Hashtable:
def __init__(self):
"""
Create an array(self.my dict) w/ a bucket size - derived from load factor.
Load factor --> a measure that decides when to increase the Hashmap capacity to maintain the get() and put() operator complexity of o(1).
Default load factor of hashmap... |
def embarque(motorista:str, passageiro:str, saida:dict):
fortwo = {'motorista': motorista, 'passageiro': passageiro}
saida['pessoas'].remove(motorista)
print(f"{fortwo['motorista']} embarcou como motorista")
if passageiro != '':
saida['pessoas'].remove(passageiro)
print(f"{fortwo['passa... |
class UnfoldingResult:
def __init__(self, solution, error):
self.solution = solution
self.error = error
|
# input number of testcases
test=int(input())
for i in range(test):
# input the number of predicted prices for WOT
n=int(input())
# input array of predicted stock price
a=list(map(int,input().split()))
c=0
i=len(a)-1
while(i>=0):
d=a[i]
l=i
p=0
while(a[i]<=d a... |
class node:
def __init__(self,value):
self.data=value
self.next=None
self.prev=None
class DoubleLinkedList:
def __init__(self):
self.head=None
def insertAtBeg(self,value):
newnode = node(value)
if self.head==None:
self.head=newnode
else:
... |
#!usr/bin/python
class Enviroment:
sets = []
banned = [] |
'''
udata-schema-gouvfr
Integration with schema.data.gouv.fr
'''
__version__ = '1.3.3.dev'
__description__ = 'Integration with schema.data.gouv.fr'
|
#
# PySNMP MIB module WIENER-CRATE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///home/tin/Dev/mibs.snmplabs.com/asn1/WIENER-CRATE-MIB
# Produced by pysmi-0.3.4 at Fri Jan 31 21:36:11 2020
# On host bier platform Linux version 5.4.0-3-amd64 by user tin
# Using Python version 3.7.6 (default, Jan 19 2020, 22:34:5... |
class Queue:
def __init__(self) :
self.__max = 10
self.__first = 0
self.__last = 0
self.__structure = {}
def is_full(self):
"""
Verifica se a Queue está cheia
"""
result = (self.__last - self.__first) == self.__max
return result
de... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Source code meta data
__author__ = 'Dalwar Hossain'
__email__ = 'dalwar.hossain@protonmail.com'
# Version
__version__ = '1.1'
__release__ = '1.1'
|
__version__ = '0.12.1'
__prog_name__ = 'DOLfYN'
__version_date__ = 'May-07-2020'
def ver2tuple(ver):
if isinstance(ver, tuple):
return ver
# ### Previously used FLOATS for 'save-format' versioning.
# Version 1.0: underscore ('_') handled inconsistently.
# Version 1.1: '_' and '#' handled consi... |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... |
"""
@Author: huuuuusy
@GitHub: https://github.com/huuuuusy
系统: Ubuntu 18.04
IDE: VS Code 1.36
工具: python == 3.7.3
"""
"""
思路:
直接将每个数字从0开始到自己的和存入target数组中
最后返回两个数字在target数组的差值即为结果
参考链接:
https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/dong-tai-gui-hua-er-fen-cha-zhao-tan-xin-suan-f... |
def find_deletions(friends_file_path, new_friends_list):
deleted = ""
f1 = open(friends_file_path, "r")
data2 = new_friends_list
for line in f1:
if data2.find(line) == -1:
print ("--" +line),
deleted += line
f1.close()
return deleted
def find_additions(friends_file_path, new_friends_list):
added = "... |
# Copyright 2013 Daniel Stokes, Mitchell Stokes
#
# 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 ... |
def sort(list_):
"""
This function is a selection sort algorithm. It will put a list in numerical order.
:param list_: a list
:return: a list ordered by numerial order.
"""
for minimum in range(0, len(list_)):
for c in range(minimum + 1, len(list_)):
if list_[c] < list_[mini... |
noun_suffix = ['াই', 'াটা', 'াটাই', 'াটাও', 'াটাকে', 'াটাকেও', 'াটি', 'ামি', 'িক', 'িকা', 'ের', 'েরই', 'েরও', 'েরা',
'েরাও', 'েরে', 'ও', 'আবলি', 'আলা', 'এরা', 'এরে', 'কারী', 'কুলের', 'কে', 'কেই', 'কেও', 'খানা', 'খানি',
'গণ', 'গণে', 'গন', 'গাছা', 'গাছি', 'গিরি', 'গুচ্ছ', 'গুলা', 'গুলি', 'গু... |
__title__ = 'pinecone-backend'
__summary__ = 'Domain.'
__version__ = '0.0.1-dev'
__license__ = 'All rights reserved.'
__uri__ = 'http://vigotech.org/'
__author__ = 'VigoTech'
__email__ = 'alliance@vigotech.org'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.