text stringlengths 5 121k |
|---|
n = int(input())
for i in range(0, n):
r, e, c = list(map(int, input().split()))
price = e - c
if r < price:
print('advertise')
elif r == price:
print('does not matter')
elif r > price:
print('do not advertise') |
n = int(input())
num1, num2 = 0, 1
for i in range(0,n):
next = num1 + num2
num1 = num2
num2 = next
print(num1) |
t = int(input())
for _ in range(0, t):
numA_list = list(map(int,input().split()))
numA_list.sort()
print(numA_list[-3]) |
import re
import os
import sys
import csv
def create_list(line_num, data_line):
"gets data information to write record to a file"
global record
global macpat
global ippat
global cameras
if line_num == "0010":
record = data_line
... |
n=int(input())
if(n>0) :
print("The number is +ve")
elif(n==0) :
print("The number is 0")
else :
print("The number is -ve")
|
import cv2
image = cv2.imread("orientation_example.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
rects = detector.detectMultiScale(
gray,
scaleFactor=1.05,
minNeighbors=10,
minSize=(20, 20),
flags=cv2.CASCADE_SCALE_I... |
ordinary = open("ordinary.txt", "r")
ordinary_list = [line.rstrip() for line in ordinary.readlines()]
vip = open("vip.txt", "r")
vip_list = [line.rstrip() for line in vip.readlines()]
singlename = input("Enter single name:")
def registration_checker(singlename):
''' Function that checks if the user exists e... |
a = 5
b = 10
c = a
d = a**2
e = d + 10
print(a)
print(b)
print(c)
print(d)
print(e)
print('Hello World')
print(5, 'birds')
print()
print(10 + 10)
print(20 - 5)
print(9 * 9)
print(5 / 2)
print(5 // 2)
print(10 % 3)
print(5 ** 3)
print(10 - 3 / (5 % 3))
print()
a1 = 5
print(typ... |
"""Python script that converts Business names to lat,lng coordinates using google places API
@author
Shyam Thiagarajan
@requires
output.txt is empty
empty last line in companies.txt
@inputs
Business names from companies.txt
@outputs
lat and lng to output.txt
API KEY CHOICES:
AIzaSyCFfJiEeUo_nX... |
'''
The first part of the program sets the initial parameters for an object thrown at some angle above the horizont, including the air resistance dragging effect.
Then, it solves the differential equation m(dV/dT)=mg-cV, describing the motion ( the numerical solution).
The second part computes the analytical solution a... |
weights=[1,3,6,7,10]
values=[2,4,7,9,12]
n=5
w=10
def knapsack(weights,values,w,n):
if n==0 or w ==0:
return 0
if weights[n-1]<=w:
return max((values[n-1]+ knapsack(weights,values,w-weights[n-1],n-1)),(knapsack(weights,values,w,n-1)))
if weights[n-1]>w:
retur... |
def for_c():
""" Lower case Alphabet letter 'c' pattern using Python for loop"""
for row in range(4):
for col in range(4):
if col==0 and row%3!=0 or col>0 and row%3==0:
print('*', end = ' ')
else:
... |
def for_equilateral_triangle():
"""Shape of 'Equilateral Triangle' using Python for loop"""
for row in range(12):
if row%2!=0:
print(' '*(12-row), '* '*row)
def while_equilateral_triangle():
"""Shape of 'Equilateral Triangle' using Python while l... |
def for_D():
""" Upper case Alphabet letter 'D' pattern using Python for loop"""
for row in range(6):
for col in range(5):
if col==0 or row in (0,5) and col<4 or col==4 and row>0 and row<5:
print('*', end = ' ')
... |
def for_z():
""" Lower case Alphabet letter 'z' pattern using Python for loop"""
for row in range(4):
for col in range(4):
if row==0 or row==3 or row+col==3:
print('*', end = ' ')
else:
... |
def for_reverse_triange():
"""Shape of 'Reverse Triangle' using Python for loop """
for row in range(6,0,-1):
print(' '*(6-row), '* '*row)
def while_reverse_triange():
"""Shape of 'Reverse Triangle' using Python while loop """
row = 6
... |
def for_rectangle():
"""Shape of 'Rectangle' using Python for loop """
for row in range(6):
for col in range(8):
if row==0 or col==0 or row==5 or col==7:
print('*', end = ' ')
else:
... |
from algebra.polynomials import *
from utils.utils import *
import itertools
class ARP:
def __init__(self, instance, size, witness = None):
"""Instance format: The instance x is a tuple (Fq, d, C) where:
* Fq is a finite field of size q.
* d is an integer representing a bound on th... |
"""
F29AI - Artificial Intelligence and Intelligent Agents
Coursework - Part I - A* Search
Big Grid with 3 robots. An example program to show our
'10x10 grid with 3 robots' example.
Ronan Smith & Jamie McCulloch
Last edited: 10.11.2016
"""
from implementation import *
from nodes import *
from... |
import math
def investMoney():
'''
Pyton program to invest money over some years.
Inputs: amount, nrYears
Output: amount, profit and cummulated amount for each year
How to do it:
repeat for each year
calculate profit and cummulated amount print them
???abou... |
'''
input: numbers EG: 1, 2, 3
output: selfDescribe number: 11 12 13 -> 1 one 1 two and 1 three
'''
def group(lst):
acc = []
for c in lst:
if acc != [] and c == acc[-1][0]:
acc[-1] += c
else:
acc.append(c)
return acc
word = input('... |
import math
def pythagorasHyp():
adj = int(input('Adjacent:'))
opp = int(input('Opposite'))
hyp = math.sqrt(adj**2 + opp**2)
print(hyp)
def pythagorasOpp():
adj = int(input('Adjacent:'))
hyp = int(input('Hypotenuse'))
opp = math.sqrt(hyp**2 - adj**2)
print(opp)
... |
import turtle as trt
import numpy as np
trt.shape('turtle')
n = 3
x = 50
def angle(n, x):
a = 360 / n
for i in range(1,n+1):
trt.left(a)
trt.forward(x)
trt.penup()
trt.right(a/2)
trt.forward(200**0.5)
trt.left(a/2 + 5)
trt.pendown()
for i in range(1,11):
angle(n,x)
... |
class Solution:
def subsets(self, S):
return self.subsetsRecur([], sorted(S))
def subsetsRecur(self, cur, S):
if S:
return self.subsetsRecur(cur, S[1:]) + self.subsetsRecur(cur+[S[0]], S[1:])
return [cur] |
class Solution:
def maxArea(self, height):
left = 0
right = len(height)-1
water = 0
while left < right:
water = max(water, (right-left) * min(height[left], height[right]))
if height[left] < height[right]:
left += 1
els... |
class Solution:
def isValidSudoku(self, board):
def isValid(x, y, tmp):
for idx in range(9):
if board[idx][y] == tmp:
return False
for idy in range(9):
if board[x][idy] == tmp:
return ... |
class Solution:
def levelOrder(self, root):
if root is None:
return []
curNodes = [root]
result = []
while curNodes:
curNodeVals = []
nextNodes = []
for node in curNodes... |
class Solution:
def candy(self, ratings):
candy_rcrd = [1 for dummy_index in range(len(ratings))]
for index in range(1, len(ratings)):
if ratings[index] > ratings[index - 1]:
candy_rcrd[index] = candy_rcrd[index - 1] + 1
for index in range(len(ratings) - 2, -1, -1):
if ratings[index... |
class Solution:
def evalRPN(self, tokens):
stack = []
for element in tokens:
if element not in "+-*/":
stack.append(element)
else:
num2 = int(stack.pop())
num1 = int(stack.pop())
if element == "+":
stack.append(s... |
class Solution:
def generateMatrix(self, n):
matrix = [[0 for dummy_idx in range(n)] for dummy_idx in range(n)]
left = 0
right = n - 1
top = 0
bottom = n - 1
num = 1
while left <= right and top <= bottom:
for idx in range(left, rig... |
def BWT(text):
assert "|" not in text
text = text + "|"
table = [text[i:] + text[:i] for i in range(len(text))]
table = sorted(table)
last_column = [row[-1:] for row in table]
bwt = ''.join(last_column)
return bwt
text = input("Введите сообщение: ")
... |
"""
CP1404/CP5632 - Practical
Broken program to determine score status
"""
def main():
score = float(input("Enter score: "))
if score < 0 or score > 100:
print("Invalid score")
else:
text = text_for_scores(score)
print (text)
def text_for_scores(score):
if score >= 90:
... |
COLOUR_TO_HEX = {'aliceblue': '#fof8ff', 'antiquewhite': '#faebd7', 'aquamarine': '#7fffd4', 'azure': '#f0ffff',
'beige': '#f5f5dc', 'bisque': 'ffe4c4', 'black': '#000000', 'blue': '#0000ff', 'blueviolet': '8a2be2'}
colour = input("Enter colour: ").lower()
while colour != "":
if colour in COLOUR_T... |
fruit = 'apple'
fruit = "apple"
frint = 'orange'
sentence = 'She said, "This is a great tasting apple!"'
sentence = "That's a great tasting apple!"
a = 'apple'[0]
e = 'apple'[4]
fruit = "apple"
first_character = fruit[0]
fruit_len = len(fruit)
print(fruit_len)
print(len(fruit))
fruit = "Apple"
print(fruit.lower())
prin... |
numrows=1
while numrows <=6:
print('')
numcolumns=6
while numcolumns >0:
if numcolumns<=numrows:
print(numcolumns,end=' ')
else:
print(' ',end=' ')
numcolumns-=1
numrows += 1
numrows=6
while numrows >=0:
print('')
numcolumns=1
whil... |
num = int(input("请输入任意整数(1-15)\n"))
for numrows in range(1,num+1):
print('')
for numcolumns in range(1,2*num):
if numcolumns>=num-(numrows-1) and numcolumns<=num+(numrows-1):
if numcolumns==num:
print(1,end=' ')
elif numcolumns<num:
print... |
import turtle
screen = turtle.Screen()
screen.title("Pong game")
screen.bgcolor("black")
screen.setup(width=1000, height=600)
left_pad = turtle.Turtle()
left_pad.speed(0)
left_pad.color("white")
left_pad.shape("square")
left_pad.shapesize(stretch_wid=6, stretch_len=2)
left_pad.penup()
left_pad.goto(-400, 0)
ri... |
import string
def part1(data):
reduced = []
for letter in data:
if reduced and abs(ord(letter) - ord(reduced[-1])) == 32:
reduced.pop()
else:
reduced.append(letter)
return len(reduced)
def part2(data):
smallest = len(data)
for letter in string.ascii_lowerc... |
total = 0
for I in range(101):
total = total + I
print('The calculated value is ' + (str(total)) + '.')
|
"""
Created on Mon Aug 3 14:29:27 2015
@author: Arthur
Game Rock-Paper-Scissors-Spock-Lizard:
With the old rules of Rock-Paper-Scissors, but now there are
two more options, Spock and Lizard.
"""
import random
A = ["rock","paper","scissors","spock","lizard"]
B = {"rock":["paper","lizard","spock","scissors"],
... |
print("Please enter your name:")
x=input()
print("Hello,"+x)
import random
words = ["corona","lung","pain","hospital","medicine","doctor","ambulance","nurse","intubation"]
word = random.choice(words)
NumberOfPrediction = 10
harfler = []
x = len(word)
z = list('_' * x)
print(' '.join(z), end='\n')
while Num... |
try:
x = int(input('Insert the number >> '))
except ValueError:
print('Wrong value! Bye-bye!!')
quit()
while True:
print('If you wanna kB press #1')
print('Or press #2 for bytes!')
break
y = int(input('>> '))
if y == 1:
print(x*1024, 'kB')
elif y == 2:
print(x/1024, 'b')
else:
print(... |
import math
from os import path
import numpy as np
import matplotlib.pyplot as plt
class TSPInstance:
'''
file format:
city number
best known tour length
list of city position (index x y)
best known tour (city index starts from 1)
'''
def __init__(self, file_name):
self.__fil... |
'''
ID:
Name:
'''
import math
class Point:
'''
Define a class of objects called Point (in the two-dimensional plane).
A Point is thus a pair of two coordinates (x and y).
Every Point should be able to calculate its distance
to any other Point once the second point is specified.
άƽϵPoint㣩Poi... |
import numpy as np
import matplotlib.pyplot as plt
import math
a = 10
a2 = a ** 2
b = 2
b2 = b ** 2
xm = []
xp = []
yp = []
ym = []
for i in np.linspace(-10, 10, 1000):
x1 = i
xp.append(x1)
yp.append(math.sqrt(b2 - (x1 ** 2 * b2) / a2))
ym.append(-math.sqrt(b2 - (x1 ** 2 * b2) / a2))
plt.plot(xp, yp)
p... |
import json
with open('airports.json') as data_file:
data = json.load(data_file)
def get_iata_num(location):
"Get IATA number for a given city."
for i in data:
city = data[i]['city']
if location == city:
iata = data[i]['iata']
else:
continue
return... |
from life_renderer import LifeWindow
from random import randint
ROWS, COLS = 100, 100
cells = [[]]
def printall():
global cells
for i in range(ROWS):
for j in range(COLS):
if cells[i][j] > 0:
print((i, j, cells[i][j]))
def setup(life_window):
global cells
cells = [[0 for r in range(COLS)] for c in ra... |
from util import direction_to_dx_dy
def display_board(board):
print()
print("Ships left:")
print("X: 2[ ] 3[ ] 3[ ] 4[ ] 5[ ]")
print("O: 2[ ] 3[ ] 3[ ] 4[ ] 5[ ]")
print()
print(" 1 2 3 4 5 6 7 8 9 ")
rows = list("ABCDEFGH")
for letter, row in zip(r... |
class Rank:
def __init__(self):
pass
def rank(self):
"""Stuff
hand is an array of five Cards
"""
hands = [
self.is_royal_flush, self.is_straight_flush,
self.is_four_of_a_kind, self.is_full_house, self.is_flush,
self.is_straight, self.... |
SPADES = 'spades'
CLUBS = 'clubs'
DIAMONDS = 'diamonds'
HEARTS = 'hearts'
SUITS = [SPADES, CLUBS, DIAMONDS, HEARTS]
FACES = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A']
class Card:
def __init__(self, face, suit):
self.face = face
self.suit = suit
@classmethod
def from_str(cls, str):
... |
print("Hello World!!")
print('1')
print("I'm fine.")
print('I"m fine.')
print("""
Hello world!!
How are you doing?
""")
print("Hello \nworld")
print("Hello \tworld")
print("back slash n: \\n")
print('I\'m fine')
print("hello" + "world" + "!!") |
for i in range(7):
print(i)
for _ in range(10):
print("hello")
for i in range(1, 51):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i) |
class Grade:
"""
Grade domain class
"""
def __init__(self, assignment_id, student_id, grade=None):
"""
Constructor for grade domain class
assignment_id - The assignment's ID (integer)
student_id - The student's ID (integer)
grade - The grade's value (integer)
... |
from controllers.controller_exception import ControllerError
class GameValidator:
@staticmethod
def validate_turn(situation, acres_to_buy_sell, units_to_feed_population, acres_to_plant):
land_price = situation.get_land_price()
grain_stocks = situation.get_grain_stocks()
if acres_to_bu... |
from domain.student import Student
class StudentController:
"""
Student controller class
"""
def __init__(self, student_validator, student_repository):
"""
Constructor for student controller class
student_validator - The student validator for validating a student
stude... |
"""
Math function related errors
"""
__author__ = "Kar Epker, karepker@gmail.com"
__copyright__ = "Room 77, Inc. 2013"
class NotDefinedError(Exception):
"""Error to raise when the operation is not defined"""
def __init__(self, operation, arg_dict):
"""Builds a not defined error
Args:
operation (st... |
def make_3D_S_shape_out_of_2D_data(data):
import numpy as np
assert isinstance(data, np.ndarray) and data.ndim == 2, "wrong input data"
X = data
t = (X[:,0] - X[:,0].mean()) * np.pi * 3
x = np.sin(t)
y = (np.cos(t)-1) * np.sign(t)
z = X[:,-1]
X = np.vstack([x,y,z]).T
... |
import math
class ListNode:
def __init__(self, doc_id=None):
self.doc_id = int(doc_id)
self.next = None
self.skip_to = None
class postingList:
def __init__(self, postingStr=None):
self.head = None
self.tail = None
self.length = 0
self.has_sk... |
from Customer import Customer
from Order import Order
from Product import Product
from Staff import Staff
from Store import Store
if __name__ == "__main__":
c1 = Customer("01223", "Peter Parker", "Qo'yliq", 2.2, "90-932-75-98", ["Silver", 'Gold'])
c2 = Customer("01223", "Sherlock Holmes", "Backer street", 314... |
class File(object):
def __init__(self, filename=None):
self.filename = filename
if self.filename is not None:
try:
with open(self.filename, "r") as f:
self.text = f.read()
except FileNotFoundError:
self.text = ""
with open(self.filename, "x"):
pass
else:... |
from itertools import count
from math import isqrt, sqrt, isclose
from fractions import Fraction
def is_square(n):
if isinstance(n, Fraction):
num, denom = n.as_integer_ratio()
if denom != 1:
return False
n = num
if isqrt(n)**2 == n:
return True
return False
def minimal_sol(D: int) -> in... |
import math
from math import e
import tkinter as tk
import list_functions as li
class graph(object):
def __init__(self,func,
scr_width=400,scr_height=400,
xmin=-5,xmax=5,ymin=-5,ymax=5):
def axis(x,y): return(0)
def y1(x,y): return(eval(func))
xfunc = [axis,y1]
yfunc = [axis]
fiel... |
max = 362880
def fact(n: int) -> int:
if n < 0:
raise ValueError("negative value for factorial")
result: int = 1
for i in range(1, n+1):
result *= i
return result
facts = {str(d): fact(d) for d in range(10)}
def fact_digit_sum(n: int) -> int:
total: int = 0
for d in str(n):
total += fact... |
def make_int(i):
if i.is_integer():
return int(i)
else:
return i
class vector(object):
def __init__(self, i=0, j=0, k=0):
self.i = i
self.j = j
self.k = k
def __repr__(self):
return f"vector{self.i, self.j, self.k}"
def __str__(self):
return f"{self.i}i + {self.j}j + {self... |
from turtle import Turtle, Screen
import random
tiny = Turtle()
screen = Screen()
screen.colormode(255)
tiny.speed("fastest")
def get_color():
red = random.randint(0, 255)
green = random.randint(0, 255)
blue = random.randint(0, 255)
return red, green, blue
def draw_spirograph(size_of_gap):
for... |
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: A Tree
@return: Inorder in ArrayList which contains node values.
"""
def inorderTraversal(self, root):
i... |
import numpy as np
from dataset.mnist import load_mnist
from network import TwoLayerNet
(x_train, y_train), (x_test, y_test)= load_mnist(normalize=True, one_hot_label=True)
train_loss_list= []
train_acc_list= []
test_acc_list= []
iters_num= 100
train_size= x_train[0].size
batch_size= 10
learning_rate= 0.1
iter... |
"""
Minimum Domino Rotations For Equal Row
In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the i-th domino, so that A[i] and B[i] swap values.
Return the minimum number of rota... |
"""
Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trappe... |
"""
Twitch Words
You are given a word like hellloooo print all the repeating character index and the number of time it is has been repeated.
Example 1:
Input: "hellloooo"
Output: [[2, 3], [5, 4]]
Explanation: hellloooo has l and o as repeating characters so return index of l which is at 2
and the number of times it ... |
"""
Word Break II
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
Y... |
"""
Give an array of salaries. The total salary has a budget. At the beginning, the total salary of employees is larger than the budget. It is required to find the number k, and reduce all the salaries larger than k to k, such that the total salary is exactly equal to the budget.
Example 1:
Input: salaries = [100, 30... |
"""
Sequence Reconstruction
Check whether the original sequence org can be uniquely reconstructed from the sequences in seqs. The org sequence is a permutation of the integers from 1 to n, with 1 ≤ n ≤ 104. Reconstruction means building a shortest common supersequence of the sequences in seqs (i.e., a shortest sequenc... |
"""
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
... |
"""
Largest Values From Labels
We have a set of items: the i-th item has value values[i] and label labels[i].
Then, we choose a subset S of these items, such that:
|S| <= num_wanted
For every label L, the number of items in S with label L is <= use_limit.
Return the largest possible sum of the subset S.
Example ... |
"""
Greatest Common Divisor of Strings
For strings S and T, we say "T divides S" if and only if S = T + ... + T (T concatenated with itself 1 or more times)
Return the largest string X such that X divides str1 and X divides str2.
Example 1:
Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
Example 2:
Input: s... |
"""
Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,... |
"""
Palindrome Number
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not ... |
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
curr_sum = max_sum = nums[0]
for n in nums[1:]:
curr_sum = max(curr_sum + n, n)
max_sum = max(max_sum, curr_sum)
... |
"""
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You jus... |
"""
Non-overlapping Intervals
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2... |
"""
Implement pow(x, n), which calculates x raised to the power n (x^n).
"""
"""
Not allowed??
"""
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
return x**n
class Solution:
def myPow(self, x: float, n: int) -> ... |
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
queue = [(root, 1)]
while queue:
node, level = queue.pop(0)
if not node.left and not node.right:
... |
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
new_head = None
while head:
head.next, head, new_head = new_head, head.next, head
return new_head
class Solution:
def reverseList(self, ... |
"""
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
"""
"""... |
"""
Given a string s consisting of 0, 1 and ?. The question mark can be either 0 or 1. Find all possible combinations for the string.
Example 1:
Input: s = "001?"
Output: ["0010", "0011"]
"""
def get_string_combinations(s):
res = []
def get_strings(s, res, idx):
if idx == len(s):
res.append(s)
return
if... |
"""
Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Example 2:
Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Note:
1 <= A.length <= 10000
-10000 <= A[i] <= 10... |
"""
Binary Tree Zigzag Level Order Traversal
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
"""
"""
Time: O(N)
Space: O(N) where N are number of nodes
"""
class Solution:
def zigzagLeve... |
"""
Shortest Path In Binary Matrix
n an N by N square grid, each cell is either empty (0) or blocked (1).
A clear path from top-left to bottom-right has length k if and only if it is composed of cells C_1, C_2, ..., C_k such that:
Adjacent cells C_i and C_{i+1} are connected 8-directionally (ie., they are different ... |
"""
Next Greater Element II
Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circula... |
"""
For a given list of integers and integer K, find the number of non-empty subsets S such that min(S) + max(S) <= K.
Example 1:
nums = [2, 4, 5, 7]
k = 8
Output: 5
Explanation: [2], [4], [2, 4], [2, 4, 5], [2, 5]
Example 2:
nums = [1, 4, 3, 2]
k = 8
Output: 15
Explanation: 16 (2^4) - 1 (empty set) = 15
Example 3:
... |
"""
Binary Tree Longest Consecutive Sequence
Given a binary tree, find the length of the longest consecutive sequence path.
The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot ... |
class Solution:
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
left, right = 0, len(numbers)-1
while left < right:
if numbers[left] + numbers[right] == target:
return [left+1,... |
"""
Flip Equivalent Binary Trees
For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees.
A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations.
Write a function that deter... |
def index_equals_value_search(arr):
'''
for i in range(len(arr)):
if i == arr[i]:
return i
return -1
'''
if len(arr) == 1:
if arr[0] == 0:
return 0
start, end = 0, len(arr) - 1
while start <= end:
mid = (start + end) // 2
if mid == arr[mid]:... |
"""
Maximum Product Subarray
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result ca... |
"""
Max Stack
Design a max stack that supports push, pop, top, peekMax and popMax.
push(x) -- Push element x onto stack.
pop() -- Remove the element on top of the stack and return it.
top() -- Get the element on the top.
peekMax() -- Retrieve the maximum element in the stack.
popMax() -- Retrieve the maximum element i... |
import sys
from random import seed, sample
from priority_queue_adt import *
def reset_pq(original):
tempQ = PriorityQueue()
for e in original[1: ]:
tempQ.insert(e)
pq = tempQ
return pq
def remove_largest_possible( target_index,testQ):
global pq
for index in reversed(t... |
"""
Given an N-ary tree and the weight of each edge represented in the value at the child node, now we are pouring water from root node and it gradually coming down through each node traversing one by one. Now time taken by the water to come from parent to child node was written by the value at child node and also root... |
"""
Next Greater Element III
Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive 32-bit integer exists, you need to return -1.
Example 1:
Input: 12
Output: 21
Example 2:
Inp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.