text stringlengths 37 1.41M |
|---|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
def plot_confusion_matrix(df_confusion, title='Confusion matrix', cmap=plt.cm.gray_r):
"""
Used to plot confusion matrix.
"""
plt.matshow(df_confusion, cmap=cmap)
plt.title(title)
plt.colorbar(... |
"""
Example of a scraper using the scrapy library
more sophisticated alternative to using requests + BS4
"""
import scrapy
from scrapy.http import Request
class LyricsSpider(scrapy.Spider):
name = 'lyrics'
allowed_domains = ['lyrics.com']
start_urls = ['https://www.lyrics.com/artist/Dire-Straits/4101'] ... |
"""
Scrapes lyrics using BS4
========================
Select how many songs to scrape at a time
catch incorrect artist inputs
allow the user to input more than a sing
"""
import os
import re
import requests
from bs4 import BeautifulSoup as soup
from pyfiglet import Figlet
BASE_URL = 'http://www.lyrics.com'
HEADERS = ... |
import pyttsx3
import speech_recognition as sr
import webbrowser
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
engine = pyttsx3.init("sapi5")
voices = engine.getProperty("voices")
engine.setProperty("voice", voices[4].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()... |
#concatenation
first_name = "John"
last_name = "Smith"
age=45
full_name = first_name + last_name
print(full_name)
#.dotformatting
print("First Name: {} Last Name: {} Age:{} ".format(first_name,last_name,age))
|
import time
import numpy as np
"""
This is a class for keeping time and possible recording it to a file
"""
class time_keeper(object):
def __init__(self, time_keeping_file="time_keeper.txt", max_running_time=9999):
self.start = time.time()
self.max_running_time = max_running_time * 60 * ... |
a=int(input())
b=int(input())
c=int(input())
if(a==b and a>c):
print(a)
elif(b==c and b>a):
print(b)
elif(a==c and a>b):
print(c)
elif(a>b and a>c):
print(a)
elif(b>c and b>a):
print(b)
elif(c>a and c>b10):
print(c)
|
#! /usr/bin/env python3
a = "hello\n" # \n is a newline character
b = "world"
a = a.strip() # this removes white space from both ends
print(f'{a} to the whole {b}.')
file = open("output.txt","a",buffering=1)
file.write(f'{a} to the whole {b}.')
file.close()
|
love_num = {
'ted':[2,6,7],
'tom':[1,9,8],
'bob':[2,3,5],
'brian':[1,2,3]
}
for name,num in love_num.items():
print(f"{name} love {num}") |
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
print(my_foods)
print(f"The first three items in the list are: {my_foods[:3... |
cities = {
'beijing':{
'country':'china',
'population': 22345671,
'fact': 'test'
},
'shanghai':{
'country':'china',
'population': 2271,
'fact': 'tst'
},
'chengdu':{
'country':'china',
'population':12356,
'fact': 'tes'
... |
love_num = {'ted':'2','tom':'5','bob':'7','brian':'8'}
print(f"ted love number is {love_num['ted']} !")
print(f"tom love number is {love_num['tom']} !") |
users_places = {}
poll_status = True
while poll_status:
name = input("What's your name ?")
place = input("If you could visit one place in the world, where would you go?")
users_places[name] = place
end_status = input("To continue or not, enter yes or no")
if end_status.lower() == 'no':
... |
num = input("please enter a number:")
if int(num) % 10 == 0:
print(f"{num} is Multiples of 10 !")
else:
print(f"{num} is not Multiples of 10 !")
|
import utils
import sorts
bookshelf = utils.load_books('books_small.csv')
for book in bookshelf:
print(book['title'])
print(ord('a'), ord(' '), ord('A'))
def by_title_ascending(book_a, book_b):
if book_a['title_lower'] > book_b['title_lower']:
return True
else: return False
sort_1 = sorts.bubble_sort(boo... |
year_of_car = int(input("What year was your favorite car made? "))
born = int(input("What year were you born? "))
street = int(input("What street number did you grow up in? "))
book = input("What's your favorite book?")
# if book :
# print("Nice book!")
# snake casing is : word1_word2_word3
# camel c... |
# http://www.codeskulptor.org/#user21_TWzHFGxbMw_12.py
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui, random, math
# initialize global variables used in your code
m = 0
M = 100
remaining_guess... |
"""
This takes a the ACM signup form excel spreadsheet and translates it into CSV that is importable
into ACM website.
"""
import pandas
# Which columns to drop
columns_to_be_dropped = ["Have you signed up on the SLI page?","Timestamp","Enter your GitHub username to be added to OSU ACM's GitHub (optional):"]
membe... |
"""
You are given two non-empty linked lists representing two non-negative integers.
The digits are stored in reverse order and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Exa... |
"""Given a 2d grid map of '1's (land) and '0's (water), count the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands
horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
"""
class Solution(object):
def get_land_neighbors(se... |
def BooleanProblem(s1, s2, n):
# Create two matrix , one for storing the count for true values
# for each expression and other one for false count
dpf = [[0 for i in range(n + 1)]
for i in range(n + 1)]
dpt = [[0 for i in range(n + 1)]
for i in range(n + 1)]
# Using gap strategy
# For gap = 0 wh... |
num=int(input("Enter number to print its table : "))
last=int(input("Enter limit upto which you want to print the table : "))
for i in range(1,last+1):
result=num*i
print(num," X ",i," = ",result) |
import pylab as pl
import numpy as np
import math
angular_velocity=[0]
angular_velocity_t=[0]
angle=[]
angle_t=[]
t=[0]
dt=0.01*math.pi
angle_0=float(raw_input('enter the initial angle:'))
t_final=20000
l=9.8
q=0.5
force=float(raw_input('enter the amplitude of the driving force:'))
frequency=2./3
angle.append(angle_0)... |
from PIL import Image
from PIL.ExifTags import TAGS
import os, sys, shutil, copy
print("This program can do 2 actions \n1st: change the name of the photos in the folder to the date they were created"
"\n2nd: create copies of all photos in the folder.\nTo make 1st action input 'replace'.\nTo make 2nd"
"actio... |
import pygame
from random import randint
pygame.init()
black = (0, 0, 0)
white = (255, 255, 255)
green = (59, 204, 100)
bg = pygame.image.load("bkgrnd.png")
flappy = pygame.image.load("flappy.png")
size = 700, 500
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Flappy Bird")
done = False
clock = ... |
def find(l,num):
for each in l:
if each != num:
print(each)
else:
break
t = []
for i in range(10):
t.append(i)
find(t,9) |
import random
while 1:
r = random.randint(1,6)
print(r)
if r%2 == 0:
print('Rolling')
break
else:
print("Rolling") |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 22 14:20:07 2019
@author: 1msc11
"""
inventory = {
'gold': 500,
'pouch': [ 'flint','twine','gemstone'],
'backpack' : ['xylophone','dagger','bedroll','bread loaf']
}
inventory['pocket'] = ['seashell','strange berry', 'lint']
print('After Adding... |
from cipher import Cipher
class Keyword(Cipher):
"""From a new cipher parent class, creates a keyword specific cipher class"""
def __init__(self, text, status):
self.alphabet = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
super().__init__(text, status)
def decrypt(self):
"""take an encrypt... |
"""This is a function bank. Here are different functions used to iterate stuff
bla bla
def foo(z, c):
return z + c
"""
import cmath
def power2(z, c):
return z*z + c
def power3(z, c):
return z*z*z + c
def power4(z, c):
return z*z*z*z + c
def power5(z, c):
return z*z*z*z*z + c
def exp_powe... |
class List:
"""
Simple singly-linked list
Exposes iterator, queue and stack functionality
"""
def __init__(self):
self.head = Node(None)
self.length = 0
self.tail = self.head
def __len__(self):
"""
Returns the length of this list without iterating over ... |
# ЗАДАЧА-3
# Написать декоратор который будет кешировать значения аргументов и результаты работы вашей функции и записывать
# его в переменную cache. Если аргумента нет в переменной cache и функция выполняется, вывести сообщение
# «Function executed with counter = {}, function result = {}» и количество раз сколько эта ... |
my_dictionary = {}
for i in range(1, 11):
my_dictionary[i] = i * i
print(my_dictionary)
# Or with checking whether the provided key already exists:
for i in range(1, 11):
if i not in my_dictionary.keys():
my_dictionary[i] = i * i
print(my_dictionary)
# Or just using dictionary comprehensions describe... |
# Auteur: Dina Benkirane
# Zheng Long Yang
import random
import math
class RSA:
def __init__(self, message_clair):
self.message_clair = message_clair
print("Test Function")
# pour efectuer l'algorithme d'exponentiation rapide.
# Peut etre remplacer par une fenetre ... |
# This is just a holding area for high-maintenance, possibly unneeded
# functions that would require dateutil to be
# imported into the ETL virtual environment.
from dateutil.easter import * # pip install python-dateutil
from datetime import date, timedelta
#from dateutil.relativedelta import relativedelta
from calen... |
# python 2 program to calculate the valid combinations of
# n digits in the set n E {1-9} where each n digit does not repeat
# that add up to the total s
from sets import Set
def combinations():
import itertools as iter
n = input("Enter length of combination: ")
s = input("Enter the total value the... |
"""Handles all User-facing questioning."""
from typing import Callable
from typing import Dict
from typing import List
from typing import Union
from loguru import logger
def default_prompt(category: str) -> str:
"""Create the user prompt for selecting categories of options.
Args:
category (str): The... |
from itertools import permutations
v=["홍길동","성춘향","이몽룡","변사또"]
r=3
for result in permutations(v, r):
print(result) |
import copy
def prime_check(num):
if num % 2 == 0:
return False
for i in range(3, int(num ** 0.5) +1 , 2):
if num % i == 0:
return False
return True
def permutation(first, end):
global big
if len(end) == 0:
res = int("".join([str(x) for x in first]))
... |
def square(num):
num = str(num)
sum = 0
for i in num:
i = int(i)
sum += pow(i, 5)
return sum
def main():
res = 0
for i in range(1000, 250000):
if i == square(i):
res += i
print(res)
main() |
def sum_of_num(num):
return sum([int(x) ** 2 for x in str(num)])
def duplication(num):
global count
num_set = set()
while True:
res = sum_of_num(num)
if res in one_set:
one_set.update(num_set)
break
elif res in right_set:
right_set.update(n... |
def multiple(n):
set_n = set(str(n))
for mul in range(2, 7):
compare = set(str(n * mul))
if not compare == set_n:
return False
return True
i = 1
while True:
i += 1
if multiple(i):
break
print(i)
|
'''
import the libraries and download ‘punkt‘
Natural Language Toolkit,自然语言处理工具包,是NLP研究领域常用的一个Python库
'''
import nltk
'''
As we download the nltk packages ourselve,
we need to bypass the ssl check
'''
import ssl
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
p... |
def convert(peso_type, dollar_value):
message = 'How ' + peso_type + ' pesos do you have?: '
pesos = float(input(message))
dollars = pesos / dollar_value
dollars = round(dollars, 2)
dollars = str(dollars)
print(f'You have ${dollars} dollars')
menu = """
Welcome to money convert ✌
1.- Col... |
# age = int(input('Write your age: '))
#
# allowed_age = 18
#
# if age >= allowed_age:
# print('Allowed, welcome')
# else:
# print('Not allowed')
number = int(input('Write a number: '))
if number > 5:
print('Is above')
elif number == 5:
print('Is equal')
else:
print('Is lower')
|
# counter = 0
#
# print('2 to ' + str(counter) + 'is = to: ' + str(2 ** counter))
#
#
# counter = 2
#
# print('2 to ' + str(counter) + 'is = to: ' + str(2 ** counter))
#
def run():
LIMIT = 1000000
counter = 0
potency = 2 ** counter
while potency < LIMIT:
print('2 to ' + str(counter) + ' is =... |
import random
def make_board(size:int, bombs:int) -> list:
""" Creates board and places bombs randomly.
Args:
size (int): the size of the board
bombs (int): the number of bombs
Returns:
list: contains the bombs
"""
board = [[None for i in range (size)] for i in range... |
from tkinter import *
import model
def update():
global map
global labels
global left_button
for r in range(4):
for c in range(4):
labels[r][c].config(text=map[r][c])
def next_step():
if model.win(map):
print("Congrats.")
exit(0)
elif model.lose(map):
... |
from training import Training
thursday = Training()
thursday.add_step("Warm up", 300, 144, 151)
thursday.add_step("Wrong timing", -45, 120, 120) # not added
thursday.add_step("Comfortable run", 1200, 149, 157)
thursday.add_step("Energetic run", 180, 158, 166)
thursday.add_step("Recovery", 120, 146, 153)
thursday.rep... |
class OwnException(Exception):
pass
try:
print("try eleje")
raise ArithmeticError
print("try vege")
except OwnException:
print("OwnException lekezelese")
except (ZeroDivisionError,FileExistsError):
print("Zero, filenoutfound lekezelese")
except:
print("unexpected exception")
else:
prin... |
"""braitenberg_vehicle controller."""
# You may need to import some classes of the controller module. Ex:
# from controller import Robot, Motor, DistanceSensor
from controller import Robot
timestep = 64
maxspeed = 10
def run_robot(robot):
#Enable motors
wheels = []
wheel_names = ['wheel1', 'wheel2'... |
#!/opt/local/bin/python
import datetime
import re
def set_back_date(days_back=28):
'''
Calculates today - days_back
and returns the back date in format yyyymmdd
Default is 4 weeks (28 days) back
'''
try:
back_dt = datetime.datetime.today() - datetime.timedelta(days=int(days_back))
... |
#encoding=utf-8
from config import *
class Box:
#向左旋转
def rotateLeft(self):
for element in self.shape:
element[0], element[1] = -element[1], element[0]
#向右旋转
def rotateRight(self):
for element in self.shape:
element[0], element[1] = element[1], -element[0]... |
print('простое присваивание')
shoplist = ['яблоки', 'манго', 'морковь', 'бананы']
mylist = shoplist # mylist - ссылка на тот же объект в памяти
del shoplist[0]
print('shoplist', shoplist)
print('mylist', mylist)
# копирование при момощи полной вырезки
mylist = shoplist[:]
del shoplist[0]
print('shoplist', shoplist... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @time :2021-02-19 11:15
# @Author :Merle
# @File :test.py
""" """
tuples = (('student',), ('teacher',), ('user',))
for tu in tuples:
if 'user' in tu:
print('True')
else:
print('False') |
numPeople = 2
survey = ["name? ", "age", "favorite color? ", "favorite animal? ", "birthday month?", "favorite music genre? "]
keys = ["name","age","color","animal","birthday","music"]
allAnswers = []
for j in range(numPeople):
answers = {}
for i in range(len(survey)):
answers[keys[i]] = input(survey[i]... |
#should_run = True
"""
bye_count = 0
while bye_count < 3:
should_run = True
while should_run:
user_input = input("What? ")
print("%s" % (user_input,))
if user_input == "bye":
should_run = False
bye_count = bye_count + 1
print(bye_count)
"""
#assignment 1
"""
cou... |
import tkinter
from tkinter import *
from tkinter import Tk, StringVar, ttk
import random
import os
import datetime
import time;
import sys
password = ("1234")
def try_login():
if code.get() == password:
print ("Complete sucsessfull!")
os.startfile('main window.py')
# messag... |
def fib(n):
result = [0,1]
if n<2:
return n
for x in range(2,n+1):
sum = result[0] + result[1]
result.pop(0)
result.append(sum)
return result[-1]
print(fib(8)) |
again = 'y'
count = 0
while again == 'y':
name = input('Enter a name of somebody you want to invite to your party: ')
print(name, 'has now been invited')
count = count + 1
again = input('Do you want to invite somebody else? (Please enter y/n): ')
print('You have', count, 'people coming to your pa... |
placeholdervar = "{}{}{}{}"
print("{}".format("hello!"))
print(f"{placeholdervar}")
print(placeholdervar.format("What if I only specify one will it work?", "NO it wont","But I do have a question","How can I use this with user input to make an array?"))
|
def userinputwhileloop():
i=1
#Accepts user input and determines how long the loop will run for.
loopuntil= int(input("Enter an integer at which the loop will stop: "))
#declares an empty list
numbers = []
increment_value = int(input("Enter a value the code increments by:"))
while i < loopu... |
def scan(raw):
words = raw.split()
directions = ("south", "north", "east", "west", "down", "up", "left", "right", "back")
verbs = ("go","kill","eat","attack","stab","chop","smack","punch")
stops = ("the","of","then","in","from","at","it")
nouns = ("door","bear","princess","cabinet")
numbers = st... |
# List all of the key words and symbols that I now know and write its
# name and what it does next to the code. MAKE A COMPLETE LIST
print("This is my list of code that I now know for Python: ")
print("# is the comment character")
print("print will echo to the terminal")
print("""f can be used in every single functio... |
#Prints a string
print("I will now count my chickens:")
#Prints a string followed by the matimatical solution
print("Hens", 25 + 30 / 6)
#Prints a string followed by the matimatical solution
print("Roosters" , 100 - 25 * 3 % 4)
#Prints a string
print("Now I will count the eggs:")
#Prints the answer to the matematical e... |
"""
Utilities for the affine transformations of the bounding box of the Free Form
Deformation.
"""
import math
import sys
import numpy as np
from functools import reduce
def angles2matrix(rot_z=0, rot_y=0, rot_x=0):
"""
This method returns the rotation matrix for given rotations around z, y and
x axes. T... |
def ball_trajectory(x):
location = 10*x - 5*(x**2)
return (location)
import matplotlib.pyplot as plt
xs= [x/100 for x in list (range(201))]
ys= [ball_trajectory(x) for x in xs]
plt.plot(xs,ys)
plt.title ('The Trajectory of a thrown ball')
plt.xlabel ('Horizontal Position of ball')
plt.ylabel('Vertical Position... |
# Menu GUI
# Create menu , with opportunity to point which meal you prefer
# and to calculate summary payment for it
from tkinter import *
import sys
class Application(Frame):
""" GUI application that makes menu from file."""
def __init__(self, master, table):
""" Initialize Frame. """
# set the init... |
#Пирожок
#Случайным образом отображает один из 5 вариантов начинки пирожков
print("Программа случайным образом выбирает для вас один из 5 вариантов"\
+" начинки пирожка")
import random
filling = random.randint(1,5)
if filling == 1 :
print("О, вам выпал пирожок с вишнёвым вареньем, мммм")
elif fillin... |
# Угадай слово
#
# Компьютер выбирает некое слово (существительное)из внесённого в
# программу списка.
# Игроку сообщается, сколько букв в слове и даётся несколько попыток
# узнать, есть ли какая-либо предложенная игроком буква в слове.
# Программа отвечает только "да" или "нет". После чего игрок должен
# поп... |
# file handles
fhand = open("files/test.txt")
print(fhand)
# \n is newline
# use for to read lines in file
# for line in fhand:
# print(line)
# or use read to read in one go
#inp = fhand.read()
# print(inp)
# use rsytrip to trim extra newline
for line in fhand:
line = line.rstrip()
print(line)
# can use... |
# while loop
n = 5
while n > 0:
print(n)
n -= 1
print("done")
# break
while True:
break
print("broken out")
# continue runs from start of loop
n = 0
while True:
if n < 5:
n += 1
continue
break
print(n)
# for loop
for i in [5, 4, 3, 2, 1]:
print(i)
print("done")
# a for exampl... |
import pandas as pd
import plotly.express as px
df = pd.read_csv("Ice-Cream vs Cold-Drink vs Temperature - Ice Cream Sale vs Temperature data.csv")
fig = px.scatter(df, x="Temperature", y="Ice-cream Sales( ₹ )")
fig.show() |
#encoding: UTF-8
# Autor:Angel Roberto Pesado Bartolo, A01374942
# Descripcion: Elaborar un algoritmo que pida al usuario las coordenadas de un punto y obtener el angulo y la magnitud.
# A partir de aquí escribe tu programa
import math
x=float(input("Dame el valor en x: "))
y=float(input("Dame el valor en y: "))
a... |
# Apple stock trading
import datetime as dt
STOCK_PRICES_YESTERDAY = [10, 7, 5, 8, 11, 9]
# Optimal, provided by IC
def get_max_profit_optimal(stock_prices_yesterday):
best_profit = stock_prices_yesterday[1] - stock_prices_yesterday[0]
lowest_price = stock_prices_yesterday[0]
for index, current... |
# Making change problem
def make_change(amount, denominations):
# in: total number of cents, denominations of currency
# out: all ways to make change
ways = [1]+[0]*amount
for denomination in denominations:
for i in range(denomination, amount+1):
ways[i] += ways[i - denominati... |
import time
import random
class Stats:
def allStats(value):
stats = []
for i in range(3):
stats.append(random.randrange(10,21))
if value == "not scared":
time.sleep(2)
print("\nAgainst your better judgement, you decide to roll the dice.\n")
elif ... |
#!/usr/bin/python3
'''
2 ptr
'''
import random
import string
def maxArea(nums):
result = 0
head = 0
tail = len(nums) - 1
while (tail > head):
new_result = (tail - head) * min(nums[head], nums[tail])
#print("head=%d, tail=%d, new_result=%d" % (head, tail, new_result))#for debug
if (nums[head] >= nu... |
class DFA:
# Creates a new DFA with the alphabet alpha
def __init__(self, alpha):
self.current_state = None
self.start_state = None
self.alphabet = alpha
self.accept_states = []
# Connection list keeps track of connections between states
# con_list[i] contains a ... |
from room import Room
from player import Player
from item import Item
# Declare all the rooms
room = {
'outside': Room("Outside Cave Entrance",
"North of you, the cave mount beckons"),
'foyer': Room("Foyer", """Dim light filters in from the south. Dusty
passages run north and east.""... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
add = 0
temp = l1.v... |
__source__ = 'https://leetcode.com/problems/binary-tree-inorder-traversal/'
#https://github.com/kamyu104/LeetCode/blob/master/Python/binary-tree-inorder-traversal.py
# Time: O(n)
# Space: O(1)
# tree
#
# Description: Leetcode # 94. Binary Tree Inorder Traversal
#
# Given a binary tree, return the inorder traversal of ... |
__source__ = 'https://leetcode.com/problems/implement-stack-using-queues/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/implement-stack-using-queues.py
# Time: push: O(n), pop: O(1), top: O(1)
# Space: O(n)
#
# Description: Leetcode # 225. Implement Stack using Queues
#
# Implement the following operations... |
__source__ = 'https://leetcode.com/problems/valid-mountain-array/'
# Time: O(N)
# Space: O(1)
#
# Description: Leetcode # 941. Valid Mountain Array
#
# Given an array A of integers, return true if and only if it is a valid mountain array.
#
# Recall that A is a mountain array if and only if:
#
# A.length >= 3
# There ... |
__source__ = 'https://leetcode.com/problems/decode-ways-ii/description/'
# Time: O()
# Space: O()
#
# Description: Leetcode # 639. Decode Ways II
#
# A message containing letters from A-Z is being encoded to numbers using the following mapping way:
#
# 'A' -> 1
# 'B' -> 2
# ...
# 'Z' -> 26
# Beyond that, now the encod... |
__source__ = 'https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/'
# Time: O(N^2)
# Space: O(NlogM), where M is the largest element of A.
#
# Description: Leetcode # 873. Length of Longest Fibonacci Subsequence
#
# A sequence X_1, X_2, ..., X_n is fibonacci-like if:
#
# n >= 3
# X_i + X_{i+1} = X_{i... |
__source__ = 'https://leetcode.com/problems/spiral-matrix/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/spiral-matrix.py
# Time: O(m * n)
# Space: O(1)
# Array
#
# Description: Leetcode # 54. Spiral Matrix
#
# Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spir... |
__source__ = 'https://leetcode.com/problems/maximum-average-subarray-ii/'
# Time: O()
# Space: O()
#
# Description: 644. Maximum Average Subarray II
#
# Given an array consisting of n integers, find the contiguous subarray
# whose length is greater than or equal to k that has the maximum average value.
# And you need... |
__source__ = 'https://leetcode.com/problems/minimum-falling-path-sum/'
# Time: O()
# Space: O()
# DP
#
# Description: Leetcode # 931. Minimum Falling Path Sum
#
# Given a square array of integers A, we want the minimum sum of a falling path through A.
#
# A falling path starts at any element in the first row, and choo... |
__source__ = 'https://leetcode.com/problems/buddy-strings/'
# Time: O(N) where NN is the length of A and B
# Space: O(1)
#
# Description: Leetcode # 859. Buddy Strings
#
# Given two strings A and B of lowercase letters,
# return true if and only if we can swap two letters in A so that the result equals B.
#
# Example ... |
__source__ = 'https://leetcode.com/problems/di-string-match/'
# Time: O()
# Space: O()
#
# Description: Leetcode # 942. DI String Match
#
# Given a string S that only contains "I" (increase) or "D" (decrease), let N = S.length.
#
# Return any permutation A of [0, 1, ..., N] such that for all i = 0, ..., N-1:
#
# If S[... |
__source__ = 'https://leetcode.com/problems/moving-average-from-data-stream/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/moving-average-from-data-stream.py
# Time: O(1)
# Space: O(w)
#
# Description: Leetcode # 346. Moving Average from Data Stream
#
# Given a stream of integers and a window size, calcul... |
__source__ = 'https://leetcode.com/problems/valid-parentheses/description/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/valid-parentheses.py
# Time: O(n)
# Space: O(n)
# Stack
#
# Description: Leetcode # 20. Valid Parentheses
#
# Given a string containing just the characters '(', ')', '{', '}', '[' and '... |
__source__ = 'https://leetcode.com/problems/lru-cache/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/lru-cache.py
# Time: O(1)
# Space: O(n)
#
# Description: Leetcode # 146. LRU Cache
#
# Design and implement a data structure for Least Recently Used (LRU) cache.
# It should support the following operation... |
__source__ = 'https://github.com/kamyu104/LeetCode/blob/master/Python/convex-polygon.py'
# Time: O(n)
# Space: O(1)
#
# Description: 469. Convex Polygon
#
# Given a list of points that form a polygon when joined sequentially,
# find if this polygon is convex (Convex polygon definition).
# https://en.wikipedia.org/wiki... |
__source__ = 'https://leetcode.com/problems/design-hashset/'
# Time: O()
# Space: O()
#
# Description: Leetcode # 705. Design HashSet
#
# Design a HashSet without using any built-in hash table libraries.
#
# To be specific, your design should include these functions:
#
# add(value): Insert a value into the HashSet.
# ... |
__source__ = 'https://leetcode.com/problems/path-sum-iii/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/path-sum-iii.py
# Time: O(n^2)
# Space: O(h)
#
# Description: 437. Path Sum III
#
# You are given a binary tree in which each node contains an integer value.
#
# Find the number of paths that sum to a g... |
__source__ = 'https://leetcode.com/problems/basic-calculator-iii/description/'
# Time: O()
# Space: O()
#
# https://leetcode.com/problems/basic-calculator-iii/discuss/113592/Development-of-a-generic-solution-for-the-series-of-the-calculator-problems
#
# Description: Leetcode # 772. Basic Calculator III
#
# Implement a... |
__source__ = 'https://leetcode.com/problems/k-diff-pairs-in-an-array/'
# Time: O(n)
# Space: O(n)
#
# Description: 532. K-diff Pairs in an Array
#
# Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array.
# Here a k-diff pair is defined as an integer pair (i, j),
#... |
__source__ = 'https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/populating-next-right-pointers-in-each-node-ii.py
# Time: O(n)
# Space: O(1)
# BFS
#
# Description: Leetcode # 117. Populating Next Right Pointers in Each Node II
#
# F... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.