content stringlengths 7 1.05M |
|---|
n=int(input())
while n:
n-=1
print(pow(*map(int,input().split()),10**9+7))
|
x = float(input('digite o segmento 1: '))
y = float(input('digite o segmento 2: '))
z = float(input('digite o segmento 3: '))
if x < y + z and y < x + z and z < x + y:
print(f'os segmentos {x, y, z} formam um Triangulo')
else:
print(f'os segmentos {x, y, z} NÃO formam um Triangulo')
|
# Wrapper class to make dealing with logs easier
class ChannelLog():
__channel = ""
__logs = []
unread = False
mentioned_in = False
# the index of where to start printing the messages
__index = 0
def __init__(self, channel, logs):
self.__channel = channel
self.__logs = list... |
l= int(input("Enter the size of array \n"))
a=input("Enter the integer inputs\n").split()
c=0
a[0]=int(a[0])
for i in range(1,l):
a[i]=int(a[i])
while a[i]<a[i-1]:
c+=1
a[i]+=1
print(c)
|
1 == 2
segfault()
class Dupe(object):
pass
class Dupe(Dupe):
pass
|
# General Errors
NO_ERROR = 0
USER_EXIT = 1
ERR_SUDO_PERMS = 100
ERR_FOUND = 101
ERR_PYTHON_PKG = 154
# Warnings
WARN_FILE_PERMS = 115
WARN_LOG_ERRS = 126
WARN_LOG_WARNS = 127
WARN_LARGE_FILES = 151
# Installation Errors
ERR_BITS = 102
ERR_OS_VER = 103
ERR_OS = 104
ERR_FINDING_OS = 105
ERR_FREE_SPACE = 106
ERR_PKG_MA... |
"{variable_name:format_description}"
print('{a:<10}|{a:^10}|{a:>10}'.format(a='test'))
print('{a:~<10}|{a:~^10}|{a:~>10}'.format(a='test'))
person = {"first":"Joran","last":"Beasley"}
print("{p[first]} {p[last]}".format(p=person))
data = range(100)
print("{d[0]}...{d[99]}".format(d=data))
print("normal:{num:d}".forma... |
def solution(A,B,K):
count = 0
for i in range(A,B):
if(i%K==0):
count += 1
#print(count)
return count
solution(6,11,2) |
# -*- coding: utf-8 -*-
class Solution:
def getLucky(self, s: str, k: int) -> int:
result = ''.join(str(ord(c) - ord('a') + 1) for c in s)
for _ in range(k):
result = sum(int(digit) for digit in str(result))
return result
if __name__ == '__main__':
solution = Solution()
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def getInput():
return input()
def testInput(a):
try:
val = int(a)
except ValueError:
return False
return True
def strToInt(a):
return int(a)
def printInt(a):
print(a)
if __name__ == '__main__':
a = getInput()
isInta... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 3 10:38:41 2018
@author: lenovo
"""
# =============================================================================
# 13. Roman to Integer
# Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
#
# Symbol Value
# I 1
# V ... |
def calc_average(case):
sum = 0
count = int(case[0])
for i in range(1, count + 1):
sum += int(case[i])
return sum / count
def count_average(case, average):
count = 0
count_num = int(case[0])
for i in range(1, count_num + 1):
if average < int(case[i]):
count += 1... |
"""
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
Constraints:
1 <= n <= 8
"""
class Solution:
def generateParenthesis(self, n: int... |
def decorator(func):
def wrapper():
print("Decoring")
func()
print("Done!")
return wrapper
@decorator
def say_hi():
print("Hi!")
if __name__ == "__main__":
say_hi()
|
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if (n < 3):
# Special cases
# 0 = 0:
# 1 = 1: 1
# 2 = 2: 2, 1 1
return n
else: # Fibonaci from here onward
... |
s = pd.Series(
data=np.random.randn(NUMBER),
index=pd.date_range('2000-01-01', freq='D', periods=NUMBER))
result = s['2000-02-14':'2000-02']
|
# https://edabit.com/challenge/Yx2a9B57vXRuPevGh
# Create a function that takes length and width and finds the perimeter of a rectangle.
def find_perimeter(x: int, y: int) -> int:
perimeter = (x * 2) + (y * 2)
return perimeter
print(find_perimeter(20, 10))
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
... |
"""
Chapter 02 - Problem 01 - remove duplicates - CTCI 6th Edition
Problem Statement:
Write code to remove duplicates from unsorted linked list
FOLLOW UP : How would you solve this problem if temporary buffer is not allowed.
"""
def remove_dups(head): # O(n) speed with O(n) space for hash table
hash_table = {hea... |
# -*- coding: utf-8 -*-
# This file is generated from NI Switch Executive API metadata version 21.0.0d1
config = {
'api_version': '21.0.0d1',
'c_function_prefix': 'niSE_',
'close_function': 'CloseSession',
'context_manager_name': {
},
'custom_types': [
],
'driver_name': 'NI Switch Execut... |
"""A utility module turning English into machine-readable data."""
def oxford_comma_text_to_list(phrase):
"""Examples:
- 'Eeeny, Meeny, Miney, and Moe' --> ['Eeeny', 'Meeny', 'Miney', 'Moe']
- 'Black and White' --> ['Black', 'White']
- 'San Francisco and Saint Francis' -->
['San Francisco', 'S... |
class DomainServiceBase:
def __init__(self, repository):
self.repository = repository
def update(self, obj, updated_data={}):
self.repository.update(obj, updated_data)
def delete(self, obj):
self.repository.delete(obj)
def create(self, obj):
obj = self.repository.creat... |
# score_manager.py
#Score Manager
ENEMY_SCORE = 300
RUPEE_SCORE = 500
scores = {
"ENEMY": ENEMY_SCORE,
"RUPEE": RUPEE_SCORE,
}
my_scores = {
"ENEMY": 300,
"MONEY": 1000,
"LASER": 1000,
"HP": 200,
"DEFENSE": 100
}
def calculate_score(score_type):
return my_scores[score_type]
|
'''
Created on Mar 1, 2016
@author: kashefy
'''
class Phase:
TRAIN = 'Train'
TEST = 'Test'
|
class Node:
#Initialize node oject
def __init__(self, data):
self.data = data #assign data
self.next = None #declare next as null
class LinkedList:
#Initialize head
def __init__(self):
self.head = None
#### Insert in the beginning
def push(self, content):
... |
# encoding = utf-8
__author__ = "Ang Li"
class Person:
age = 100
def __init__(self, name):
self.name = name
tom = Person('Tom')
print(tom.age) # tom 中没有定义age,访问的是类的,如果类中没有会接着访问上层的父类的
print(*tom.__dict__.items()) # 但是这种访问,是直接访问,tom实例并不会 并不会新增一个age属性。
|
"""
Lab 7 python file
"""
#
print("\n3.1")
current_number=-1
while current_number<6:
current_number +=1
if (current_number==3 or current_number==6):
continue
print(current_number)
#
print("\n3.2")
n=int(input("Enter a number:"))
factorial=1
while n>=1:
factorial=factorial*n
n=n-1
pr... |
class Solution:
# @param {character[][]} matrix
# @return {integer}
def maximalSquare(self, matrix):
if not matrix:
return 0
max_square = 0
self.visited = []
for line in matrix:
row = []
for c in line:
row.append(0)
... |
#!/usr/bin/python
#------------------------------------------------------------------------------
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
result = floa... |
class Sensores:
def __init__(self, ambiente, simboloCampoVazio, getTodasPecas):
self.IAmbiente = ambiente
self.ISimboloCampoVazio = simboloCampoVazio
self.IJogadorUmPeca, self.IJogadorDoisPeca = getTodasPecas
# retorna a posição do vetor que se jogada, ganha o jogo
def verificaSeGan... |
#! /usr/bin/python3.7
# soh cah toa
def sin():
o = float(input('What is the oppisite?: '))
h = float(input("What is the hypotnuse?: "))
s = o / h
print("sin = {}".format(s))
def cos():
a = float(input('What is the ajacent?: '))
h = float(input("What is the hypotnuse?: "))
c = a / h
print('cos = {}'.format(c))... |
# Scale Settings
# For 005.mp4
SCALE_WIDTH = 25
SCALE_HEIGHT = 50
# SCALE_WIDTH = 100
# SCALE_HEIGHT = 100
# Video Settings
DETECT_AFTER_N = 50
# NMS Settings
NMS_CONFIDENCE = 0.1
NMS_THRESHOLD = 0.1
# Detection Settings
DETECTION_CONFIDENCE = 0.9
# Tracker Settings
MAX_DISAPPEARED = 50 |
a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
c=int(input("Enter the third number:"))
if a<b in c>a:
min=a
elif a<b in c>b:
min=b
else:
min=c
print(min)
|
class setx:
def __init__(self, iterable=[]):
self.iterable = set(iterable)
self.size = len(self.iterable)
def __repr__(self):
return f"<{self.__class__.__name__.lower() !a}> {self.iterable}"
def add(self, element):
if element not in self.iterable:
self.iterable... |
def cycles_until_reseen(bins):
configs = set()
curr = bins
while tuple(curr) not in configs:
configs.add(tuple(curr))
min_idx = 0
for i in range(1, len(curr)):
if curr[i] > curr[min_idx]:
min_idx = i
redistribute = curr[min_idx]
curr[min_i... |
n = int(input())
count_2 = 0
count_5 = 0
for i in range(2,n+1):
num = i
while(1):
if num%2 == 0:
count_2 += 1
num //= 2
elif num%5 == 0:
count_5 += 1
num //= 5
else: break
print(min(count_2,count_5)) |
# Copyright 2016-2020 Blue Marble Analytics LLC. All rights reserved.
"""
**Relevant tables:**
+--------------------------------+----------------------------------------------+
|:code:`scenarios` table column |:code:`project_new_potential_scenario_id` |
+--------------------------------+------------------------... |
if 1:
N = int(input())
Q = int(input())
queries = []
for i in range(Q):
queries.append([int(x) for x in input().split()])
else:
N = 100000
queries = [
[2, 1, 2],
[4, 1, 2]
] * 10000
queries.append([4, 1, 2])
Q = len(queries)
isTransposed = False
xs = list(ra... |
# Location of the data.
reference_data_path = '/p/cscratch/acme/data/obs_for_acme_diags/'
test_data_path = '/p/cscratch/acme/data/test_model_data_for_acme_diags/'
# Name of the test model data, used to find the climo files.
test_name = '20161118.beta0.FC5COSP.ne30_ne30.edison'
# An optional, shorter name to be used ins... |
#
# Problem: Given an undirected graph with maximum degree, find a graph coloring using at most D+1 colors.
#
def color_graph_first_available(graph, colors):
"""
Solution: For each graph node, assign to it the first color not in the list of neighbor colors.
Complexity: (where n is # nodes, d is max degrees)
Time... |
file_name=str(input("Input the Filename:"))
if(file_name.split('.')[1]=='c'):
print('The extension of the file is C')
if(file_name.split('.')[1]=='cpp'):
print('The extension of the file is C++')
if(file_name.split('.')[1]=='java'):
print('The extension of the file is Java')
if(file_name.split('.')[1]=='py'):
p... |
#
# PySNMP MIB module INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INTELCORPORATION-MULTI-FLEX-SERVER-DRIVE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:54:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by u... |
def delUser(cur,con,loginid):
try:
query = "DELETE FROM USER WHERE Login_id='%s'" % (loginid)
#print(query)
cur.execute(query)
con.commit()
print("Deleted from Database")
except Exception as e:
con.rollback()
print("Failed to delete from database")
... |
# program to generate the combinations of n distinct objects taken from the elements of a given list.
def combination(n, n_list):
if n<=0:
yield []
return
for i in range(len(n_list)):
c_num = n_list[i:i+1]
for a_num in combination(n-1, n_list[i+1:]):
yield c_num + a_n... |
def install(job):
service = job.service
# create user if it doesn't exists
username = service.model.dbobj.name
password = service.model.data.password
email = service.model.data.email
provider = service.model.data.provider
username = "%s@%s" % (username, provider) if provider else username... |
if condition1:
...
elif condition2:
...
elif condition3:
...
elif condition4:
...
elif condition5:
...
elif condition6:
...
else:
...
|
MIN_DRIVING_AGE = 18
group = {'tim': 17, 'bob': 18, 'ana': 24}
def allowed_driving(name):
"""Print '{name} is allowed to drive' or '{name} is not allowed to drive'
checking the passed in age against the MIN_DRIVING_AGE constant
"""
is_found = False
if name in group:
if group[nam... |
# Python - 3.6.0
test.assert_equals(relatively_prime(8, [1, 2, 3, 4, 5, 6, 7]), [1, 3, 5, 7])
test.assert_equals(relatively_prime(15, [72, 27, 32, 61, 77, 11, 40]), [32, 61, 77, 11])
test.assert_equals(relatively_prime(210, [15, 100, 2222222, 6, 4, 12369, 99]), [])
|
def save_file(contents):
with open("path_to_save_the_file.wav", 'wb') as f:
f.write(contents)
return "path_to_save_the_file.wav"
|
expected_output = {
"main": {
"chassis": {
"ASR1002-X": {
"descr": "Cisco ASR1002-X Chassis",
"name": "Chassis",
"pid": "ASR1002-X",
"sn": "FOX1111P1M1",
"vid": "V07",
}
}
},
"slot": {
... |
input = """
c(1).
c(2).
c(3).
a(X) | -a(X) :- c(X).
minim(X) :- a(X), #min{ D : a(D) } = X.
"""
output = """
c(1).
c(2).
c(3).
a(X) | -a(X) :- c(X).
minim(X) :- a(X), #min{ D : a(D) } = X.
"""
|
A = 1
connection= {
A : ['B'],
'B' : ['A', 'B', 'D'],
'C' : ['A'],
'D' : ['E','A'],
'E' : ['B']
}
for f in connection:
print(connection['B'])
print(connection[id])
|
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
class AugmentedTaskDTO(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the... |
#entre com 2 notas e calcule a media
n1 = int(input('Entre com a primeira nota : '))
n2 = int(input('Entre com a segun da nota : '))
m = (n1 + n2) / 2
print('A média das notas é: {}'.format(m))
|
"""
EDX_DATABASES = {
'think_101x': {'dbname': 'UQx_Think101x_1T2014', 'mongoname': 'UQx/Think101x/1T2014', 'discussiontable': 'UQx-HYPERS301x-1T2014-prod', 'icon': 'fa-heart'},
'hypers_301x': {'dbname': 'UQx_HYPERS301x_1T2014', 'mongoname': 'UQx/HYPERS301x/1T2014', 'discussiontable': 'UQx-HYPERS301x-1T2014-pro... |
def insertion_sort(the_list):
"""
In-place list sorting method
"""
i = 1
while i < len(the_list):
elem = the_list[i]
sorted_iterator = i-1
while elem < the_list[sorted_iterator] and sorted_iterator >= 0:
the_list[sorted_iterator+1] = the_list[sorted_iterator]
... |
# emacs: -*- mode: python-mode; py-indent-offset: 2; tab-width: 2; indent-tabs-mode: nil -*-
# ex: set sts=2 ts=2 sw=2 et:
__all__ = ['classify', 'cluster', 'decode', 'meta', 'network', 'reduce', 'stats']
|
def f1(x, *args):
pass
f1(42, 'spam')
|
{
'includes': [
'./common.gypi'
],
'target_defaults': {
'defines' : [
'PNG_PREFIX',
'PNGPREFIX_H',
'PNG_USE_READ_MACROS',
],
# 'include_dirs': [
# '<(DEPTH)/third_party/pdfium',
# '<(DEPTH)/third_party/pdfium/third_party/freetype/include',
# ],
'conditions': [
... |
def normalizer(x, norm):
if norm == 'l2':
norm_val = sum(xi ** 2 for xi in x) ** .5
elif norm == 'l1':
norm_val = sum(abs(xi) for xi in x)
elif norm == 'max':
norm_val = max(abs(xi) for xi in x)
return [xi / norm_val for xi in x]
def standard_scaler(x, mean_, var_, with_mean, ... |
def pascal_case(text):
"""Returns text converted to PascalCase"""
if text.count('_') == 0:
return text
s1 = text.split('_')
return ''.join([s.lower().capitalize() for s in s1])
def integral_type(member):
type = {
'char': 'char',
'signed char': 'sbyte',
'unsigned ch... |
print('Enter any integer: ')
n = str(input().strip())
num_places = len(n)
for i in range(num_places) :
x = num_places - i
if x >= 10 :
suffix = "Billion "
elif x <= 9 and x >= 7 :
suffix = "Million "
elif x == 6 :
suffix = "Hundred "
elif x == 5 :
suffix = "Thousan... |
def search(arr, d, y):
for m in range(0, d):
if (arr[m] == y):
return m;
return -1;
arr = [4, 8, 26, 30, 13];
p = 30;
k = len(arr);
result = search(arr, k, p)
if (result == -1):
print("Element is not present in array")
else:
print("Element is present at index", result... |
# Turns an RPN expression to normal mathematical notation
_VARIABLES = {
"0": "0",
"1": "1",
"P": "pi",
"a": "x0",
"b": "x1",
"c": "x2",
"d": "x3",
"e": "x4",
"f": "x5",
"g": "x6",
"h": "x7",
"i": "x8",
"j": "x9",
"k": "x10",
"l": "x11",
"m": "x12",
"... |
#converts the pixel bytes to binary
def decToBin(dec):
secret_bin = []
for i in dec:
secret_bin.append(f'{i:08b}')
return secret_bin
#gets the last 2 LSB of each byte
def get2LSB(secret_bin):
last2 = []
for i in secret_bin:
for j in i[6:8]:
last2.append(j... |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def buildfarm():
http_archive(
name="buildfarm" ,
build_file="//bazel/deps/buildfarm:build.BUILD" ,
sha256="de2a18... |
"""
Choose i/o filename here:
- a_example
- b_should_be_easy
- c_no_hurry
- d_metropolis
- e_high_bonus
"""
filename = 'b_should_be_easy' # choose input and output file names here
ride_pool = []
ride_id = 0
with open(filename + '.in', 'r') as file:
args = file.readline().split()
for line in file:
... |
class ReporterInterface(object):
def notify_before_console_output(self):
pass
def notify_after_console_output(self):
pass
def report_session_start(self, session):
pass
def report_session_end(self, session):
pass
def report_file_start(self, filename):
pass... |
def read_as_strings(filename):
f = open(filename, "r")
res = f.read().split("\n")
return res
def read_as_ints(filename):
f = open(filename, "r")
res = map(int, f.read().split("\n"))
return list(res)
|
#num1 = int(input('qual tabuada você deseja?'))
#num2 = 1
#while True:
# if num1 <= 0:
# break
# print(f'{num2} X {num1} ={num2*num1}')
# num2 += 1
# if num2>=11:
# num1 = int(input('qual tabuada você deseja?'))
# num2 = 1
#print('programa encerrado!')
while True:
num1 = int(input('... |
n = int(input("Qual o tamanho do vetor?"))
x = [int(input()) for x in range(n)]
for i in range(0, n, 2):
print(x[i])
|
# Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word.
# That's why he decided to invent an extension for his favorite browser that would change the letters' register
# in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones.... |
# function for merge sort
def merge_sort(arr):
if len(arr) > 1:
# mid element of array
mid = len(arr) // 2
# Dividing the array and calling merge sort on array
left = arr[:mid]
# into 2 halves
right = arr[mid:]
# merge sort for array first
merge_so... |
def test_fake_hash(fake_hash):
assert fake_hash(b'rainstorms') == b"HASH(brainstorms)"
|
"""Constants for Fama
RANKS(list of str): taxonomical ranks, top to bottom
LOWER_RANKS(dict of str): rank as key, child rank as value
ROOT_TAXONOMY_ID (str): taxonomy identifier of root node
UNKNOWN_TAXONOMY_ID (str): taxonomy identifier of 'Unknown' node
ENDS (list of str): identifiers of first and second end for pai... |
supported_browsers = (
"system_default",
"chrome",
"chromium",
"chromium-browser",
"google-chrome",
"safari",
"firefox",
"opera",
"mozilla",
"netscape",
"galeon",
"epiphany",
"skipstone",
"kfmclient",
"konqueror",
"kfm",
"mosaic",
"grail",
"lin... |
class BasePermission:
def __init__(self, user):
self.user = user
def has_permission(self, action):
raise NotImplementedError
class AllowAny:
def has_permission(self, action):
return True
class IsAuthenticated(BasePermission):
def has_permission(self, action):
return ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 17-4-17 下午10:25
# @Author : YANGz1J
# @Site :
# @File : urls_manage.py
# @Software: PyCharm
class Urlmanager(object):
def __init__(self):
self.new_urls = set()
self.old_urls = set()
def add_new_url(self, url):
if url is ... |
# Description: Count number of *.log files in current directory.
# Source: placeHolder
"""
cmd.do('print("Count the number of log image files in current directory.");')
cmd.do('print("Usage: cntlogs");')
cmd.do('myPath = os.getcwd();')
cmd.do('logCounter = len(glob.glob1(myPath,"*.log"));')
cmd.do('print("Number of ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 28 06:33:05 2020
@author: ucobiz
"""
def happy():
print("Happy Bday to you!")
def sing(person, age):
happy()
happy()
print("Happy Bday,", person)
print("You're already", age, "years old")
happy()
def main():
sing("Fred", 30... |
#counter part of inheritance
#inheritance means by this program- a bookself is a book
#composition is -
class Bookself:
def __init__(self, *books):
self.books=books
def __str__(self):
return f"Bookself with {len(self.books)} books."
class Book:
def __init__(self... |
def fake_get_value_from_db():
return 5
def check_outdated():
total = fake_get_value_from_db()
return total > 10
def task_put_more_stuff_in_db():
def put_stuff(): pass
return {'actions': [put_stuff],
'uptodate': [check_outdated],
}
|
#!/usr/bin/env python3
def solution(s: str, p: list, q: list) -> list:
"""
>>> solution('CAGCCTA', [2, 5, 0], [4, 5, 6])
[2, 4, 1]
"""
response = ['T'] * len(p)
for i, s in enumerate(s):
for k, (p, q) in enumerate(zip(p, q)):
if p <= i <= q and s < response[k]:
... |
'''
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0... |
# coding:utf-8
unconfirmed_users = ['liuhanyu', 'luoliuzhou', 'wangyue', 'xiaolizi']
confirmed_users = []
while unconfirmed_users:
user = unconfirmed_users.pop()
confirmed_users.append(user)
print(confirmed_users)
print(unconfirmed_users) |
# link: https://leetcode.com/problems/longest-string-chain/
"""
Sort the words by word's length. (also can apply bucket sort)
For each word, loop on all possible previous word with 1 letter missing.
If we have seen this previous word, update the longest chain for the current word.
Finally return the longest word chain.... |
#
# @lc app=leetcode.cn id=111 lang=python3
#
# [111] 二叉树的最小深度
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if ... |
# Доступ к тренировочным тестам урока без авторизации
def test_opening_TT_without_authorization (app):
app.Button_menu.Test_Button_Videocourses() # кнопка "Видеокурсы"
result = app.List_items_before_autorization.Test_list_of_all_items_for_TT(TEXT='УРОК') # нажимает на тренировочные тесты в предмете по порядку... |
"""typecats"""
__version__ = "1.7.0"
__author__ = "Peter Gaultney"
__author_email__ = "pgaultney@xoi.io"
|
num = int(input("Enter a number: "))
if ((num % 2 == 0) and (num % 3 == 0) and (num % 5 == 0)):
print("Divisible")
else:
print("Not Divisible")
|
"""Environment Variables to be used inside the CloudConvert-Python-REST-SDK"""
CLOUDCONVERT_API_KEY = "API_KEY"
"""Environment variable defining the Cloud Convert REST API default
credentials as Access Token."""
CLOUDCONVERT_SANDBOX = "true"
"""Environment variable defining if the sandbox API is used instead of the l... |
# f[i][j] = f[i - 1][j - 1] where s[i - 1] == p[j - 1] || p[j - 1] == '.' case p[j - 1] != '*'
# f[i][j] = f[i][j - 2] or f[i - 1][j] where s[i - 1] == p[j - 2] || p[j - 2] == '.' case p[j - 1] == '*'
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:r... |
'''
Descripttion:
version:
Author: HuSharp
Date: 2021-02-21 22:59:41
LastEditors: HuSharp
LastEditTime: 2021-02-21 23:12:36
@Email: 8211180515@csu.edu.cn
'''
def countdown_1(k):
if k > 0:
yield k
for i in countdown_1(k-1):
yield i
def countdown(k):
if k > 0:
yield k
... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of lists of integers
def levelOrderBottom(self, root):
x = self.solve(root)
... |
"""
Author: Eda AYDIN
"""
T = int(input())
answer = []
for i in range(T):
size = int(input())
blocks = list(map(int, input().split()))
for j in range(size - 1):
if blocks[0] >= blocks[len(blocks) - 1]:
a = blocks[0]
blocks.pop(0)
elif blocks[0] < blo... |
# THIS FILE IS AUTO-GENERATED. PLEASE DO NOT MODIFY# version file for ldap3
# generated on 2018-08-01 17:55:24.174707
# on system uname_result(system='Windows', node='ELITE10GC', release='10', version='10.0.17134', machine='AMD64', processor='Intel64 Family 6 Model 58 Stepping 9, GenuineIntel')
# with Python 3.7.0 -... |
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
print(min(even))
print(max(even))
print(min(odd))
print(max(odd))
print()
print(len(even))
print(len(odd))
print()
# to count how many times s is repeated in the word
print("mississippi".count("s")) #4
print("mississippi".count("issi")) #1
even.extend(odd)
print(even)
... |
class Solution:
def prefixesDivBy5(self, A: List[int]) -> List[bool]:
val = 0
res = [None] * len(A)
for i, v in enumerate(A):
val = ((val << 1) + v) % 5
res[i] = (val == 0)
return res
|
t=int(input())
for i in range(t):
s=input()
if s[:int(len(s)/2)]==s[int(len(s)/2):]:
print("YES")
else:
print("NO")
|
__all__ = [
'feature_audio_opus', \
'feature_audio_opus_conf'
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.