text stringlengths 37 1.41M |
|---|
#!/usr/bin/python3
"""
A module that test differents behaviors
of the Base class
"""
import unittest
import pep8
from models.base import Base
from models.rectangle import Rectangle
class TestRectangle(unittest.TestCase):
"""
A class to test the Rectangle Class
"""
def test_pep8_base(self):
"""... |
#Kate Cough
#May 25 2017
#Homework 2, part 2
#1) Make a list called "countries" - it should contain seven different countries and NOT be in alphabetical order
countries = ["zimbabwe", "algeria", "malawi", "congo", "egypt", "burundi", "rwanda"]
print(countries)
#2) Using a for loop, print each element of the list
for ... |
# ALL ABOUT APIs
# darkskynet/dev/account
# https://api.darksky.net/forecast/13d3600a5cd0883a0f7c94181a175dd3/37.8267,-122.4233
#endpoint :: is a URL. the list of URLs you can talk to
#first, bring in the requests library
import requests
#module = library = package they're all the same
#use PIP to install packages... |
#! /usr/bin/python3
def count_vowel(s):
vowels = ['u', 'e', 'o', 'a', 'i']
ret = 0
for i in s:
if i in vowels:
ret += 1
return ret
msg = input('Enter a String: ')
print('The number of vowels : {}'.format(countVowel(msg)))
|
'''
Created on May 23, 2016
Simulated Annealing
When the cost is higher, the new solution can still become the current solution with certain probability.
This aims at avoiding local optimum.
The temperature - willingness to accept a worse solution
When the temperature decreases, the probability of accepting a worse sol... |
"""
This script is parsing data exported from Apple Health app in order to count steps made per day. The number of steps is then writen into a CSV file. Some mock data could be found on my GitHub: github.com/hsarka
A blog post with visualization could be seen on my blog sarka.hubacek.uk
"""
import xmltodict
imp... |
#!/bin/python3
adhoc=[1,2,3,1,4,5,66,22,2,6,0,9]
x=[]
y=[]
print("1. Numbers greater than 5 :")
for i in adhoc:
if i>5:
print(i)
x.append(i)
print("2. Numbers less than or equal to 2 : ")
for i in adhoc :
if i <=2 :
print(i)
y.append(i)
print("List 1 is :",x)
print("List 2 is :",y)
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
def vector_add(v1: list, v2: list):
"""Vector addition"""
assert len(v1) == len(v2)
return [x + y for x, y in zip(v1, v2)]
def vector_scal(scalar, v: list):
"""Scalar multiplication of a vector"""
return [scalar * x for x in v]
def vector_is_zero(v):
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from elliptic_curves.elliptic_curve import EllipticCurve
from structures.fields.finite import FiniteField
from maths.math_lib import gcd
from maths.primes import primes_range
from math import log
from IFP.primepower import isprimepower
from primality.prime import is_prime
fro... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from maths.math_lib import gcd
from primality.prime import is_prime
def pollard_rho_search_floyd(f, n: int, x0=2):
"""Pollard's-rho algorithm to find a non-trivial
factor of `n` using Floyd's cycle detection algorithm."""
d = 1
tortoise = x0
hare = x0
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from structures.rings import CommutativeRingElement
class FieldElement(CommutativeRingElement):
"""
A base class for field elements that provides default operator overloading.
"""
def __truediv__(self, other):
other = self.field()(other)
ret... |
"""
Challenge #4:
Create a function that takes length and width and finds the perimeter of a
rectangle.
Examples:
- find_perimeter(6, 7) ➞ 26
- find_perimeter(20, 10) ➞ 60
- find_perimeter(2, 9) ➞ 22
"""
# Input, Output both int, no type conversion
# length and width of a rectangle, 4 sides, 2 length, 2 widt... |
# Program to send emails from python
# Written in Python 3.3
import smtplib
import getpass
def send_mail(username, password, serv):
# Asks for the from email address, the to email address and then the
# messages
from_email = input('From Email : ')
to_email = input('To Email : ')
message = input('Message: ')
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
s = 'hi hello, world.'
b = list(s)
# print('b=',b)
# to remove , and . (nutzlich mit Worter, die mit /def/ anfangen, damit g nicht , oder . sein)
a = s.split(' ')
# print('a=',a)
c = ' '.join(a)
# print(c)
# for i in a:
# if (i.endswith(',')) or (i.endswith('.')):
#... |
##Recursive Function to print out the digits of a number in English
## By: Piranaven Selva
##NumToEng.py
def Numtoeng(Number):
English = {0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"}
Number=str(Number)
if len(Number) == 0: ... |
# calculator.py
# A program that asks the user for an expression
# and then prints out the value of the expression
# by: Piranaven Selvathayabaran
def main():
x=eval(raw_input("Give me an expression:"))
print("The value is: "+ x)
main()
|
# distance.py
# Program that computes the distance between two points
from math import*
def main():
print("This program calculates th distance between two coordinates.")
cx1,cy1=eval(input("Please enter the first coordinate point (x1,y1): "))
cx2,cy2=eval(input("Please enter the second coordinate point (x... |
"""
File: stack.py
Stack implementations
"""
from arrays import Array
class ArrayStack(object):
""" Array-based stack implementation."""
DEFAULT_CAPACITY = 10 # Class variable for all array stacks
def __init__(self):
self._items = Array(ArrayStack.DEFAULT_CAPACITY)
self._top = -1
... |
#!/usr/bin/env python
class BinarySearch():
def chop(self, value, array):
if len(array) == 0:
return -1
i = 0
k = len(array) - 1
while k - i > 1:
mid = i + (k - i) / 2
if array[mid] == value:
return mid
... |
#!/usr/bin/env python3
import argparse
import math
def ms10(x):
return math.floor(x * x / 100000) % int(math.pow(10, 10))
def neumann(n):
succ = n * n
succ_str = str(succ)
if len(succ_str) < 20:
succ_str = '0'*(20-len(succ_str)) + succ_str
if len(succ_str) == 20:
succ = int(succ... |
import hashlib
mystring = input('Enter String to hash: ')
# Assumes the default UTF-8
hash_object = hashlib.md5(mystring.encode())
print(hash_object.hexdigest()) |
def CheckVowels(s):
if s=='a' or s== 'e' or s== 'i' or s== 'o' or s== 'u':
return True
else:
return False
vchar=input('Enter any character ')
Ans=CheckVowels(vchar)
print(Ans)
|
import sys
# 算个税
class TaxCalculator:
def __init__(self):
self.degree_array = [0, 3000, 12000, 25000, 35000, 55000, 80000]
self.tax_rate_array = [0.03, 0.1, 0.2, 0.25, 0.3, 0.35, 0.45]
def calculate_tax(self, salary):
if salary <= 5000:
return 0
else:
t... |
"""
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[... |
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
tmpNode1 = pHead1
tmpNode2 = pHead2
count1 = count2 = 0
while tmpNode1:
... |
"""
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
"""
#coding=utf-8
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 迭代 60ms
# def reverseList(self, head):
# ... |
"""
判断5张扑克牌是否为顺子,大小王为0,可以代替任意数字
"""
# -*- coding:utf-8 -*-
import Sort_QuickSort
class Solution:
def IsContinuous(self, numbers):
# write code here
if not numbers:
return False
Sort_QuickSort.quick_sort(numbers)
zero_count = 0
diff_count = 0
for i in ran... |
'''
直接插入排序
时间复杂度:O(n²)
空间复杂度:O(1)
稳定性:稳定
基本操作是将后面一个记录插入到前面已经排好序的有序表中
'''
def insert_sort(array):
for i in range(1, len(array)):
if array[i] < array[i-1]:
j = i-1
tmp = array[i]
while j >= 0 and tmp < array[j]:
array[j+1] = array[j]
j -= 1... |
def Move(direction, current_position):
"""
args: direction - contains the letter for the direction the user wanted to move to.
current_postion - x and y for the current postion the user is at
feat: updates the user position according to the user's input
"""
if direction =='n' and cu... |
from Course import Course
from Student import Student
from DILevel import Level_3_Students
import os
class School(Course,Level_3_Students ,Student):
def __init__(self):
self.file1_data = []
self.file2_data = []
self.file3_data = []
''' Section 1: PASS Level
Read from a file sp... |
# -*- coding:utf-8 -*-
'''获取文件中存储的cookie'''
def read_cookie():
with open('cookie_file', 'r', encoding='utf-8') as f: # 打开文件
line = f.readline() # 读取所有行
f.close()
return line
'''更新文件中存储的cookie'''
def write_cookie():
temp = input("请更新在谷歌浏览器登录weibo.cn时所获取的cookie(输入n/N不更新cookie):")
if (... |
from modules.Geometry import Point
from modules.Utils import vector
import math
class Line2D:
# general Equation of line ax + by +c =0
def __init__ (self):
self.a = 0
self.b = 0
self.c = 0
def newLine ( a, b, c):
ln = Line2D()
ln.a = a
ln.b = b
ln.c = c
return ln
def getLine( pt1 , pt2):
li... |
import math
class vector:
def __init__(self, x = 0, y =0 ):
self.x = (x)
self.y = (y)
def unitVector(self):
mag = self.getModulus()
if mag == float(0):
return (vector2D())
return vector2D(self.x/mag, self.y/mag)
def getModulus(self):
return math.sqrt( self.x **2 + self.y **2)
## return vector... |
def list_of_words(file_name):
"""Returns: the words in a text file in a list format"""
with open(file_name, 'r') as file :
words = file.read()
split_words = words.split()
return split_words
def hist_dictionary(words):
""" Retruns: the dictionary histogram
representation of ... |
import random
from histogram import hist_dictionary, hist_list, list_of_words
import sys
def sample_by_frequency(histogram):
"""
Input: Histogram of text file
Return : a random word based on the weight(occurence)
"""
tokens = sum(histogram.values())
rand = random.randrange(tokens)
for key,... |
nr_stari = int(input("Introduceti numarul de stari: "))
nr_tranz = int(input("Introduceti numarul de tranzitii: "))
alf = input("Introduceti alfabetul (fara spatiu): ")
v_fin = input("Introduceti starile finale (cu virgula): ")
st_in = input("Introduceti starea initiala: ")
matrix = [""]*100
lista = []
# citim... |
# First type of approach that came to mind
def solution1():
total = 0
for i in range(3, 1000):
if i % 3 == 0 or i % 5 == 0:
total += i
return total
# An approach using list comprehension
def solution2():
return sum(x for x in range(1000) if (x %3 == 0 or x % 5 == 0))
|
class Queue:
def __init__(self,max=10):
self.queue = []
self.max = max
self.rear = -1
def enqueue(self,data):
if self.rear == self.max - 1:
raise Exception("Queue is full")
self.queue.append(data)
self.rear += 1
return self.rear
def dequeue(self):
... |
import unittest
from warehouse import Warehouse
from inventory_allocator import InventoryAllocator
# Assumptions:
# 1. I assume that in the list of warehouses as the second input, warehouses cannot have the same name
class TestInventoryAllocator(unittest.TestCase):
def test_not_enough_inventory_for_single_item(s... |
def is_substring(st, sb):
i = 0
lsb = len(sb)
while i < len(st):
j = lsb
while j > 0 and (i+j-1) < len(st):
if sb[j-1] != st[i+j-1]:
break
j -= 1
if j == 0:
return i+1
i+=1
return -1
if __name__=='__main__':
print... |
import random
def selection_sort(a, N):
for i in range(N):
pos = i
for j in range(i+1, N):
if a[j] < a[pos]:
pos = j
tmp = a[pos]
a[pos] = a[i]
a[i] = tmp
def bubble_sort(a, N):
for i in range(N):
flag = 0
for j in ra... |
import random
def negate(a):
neg = 0
if a > 0:
sign = -1
else:
sign = 1
delta = sign
while a != 0:
newsign = (a+delta > 0) != (a > 0)
if newsign and a+delta != 0:
delta = sign
a += delta
neg += delta
delta += delta
return neg
... |
from binarytree import Node, pprint
class dnode(Node):
def __init__(self, val):
Node.__init__(self, val)
self.depth = 0
class BStree:
def __init__(self):
self.root = None
def insert(self, node):
if self.root == None:
self.root = node
e... |
import random
max_width = 16
class HashTable:
def __init__(self, size):
self.lt = [None]*size
self.size = size
def insert(self,value):
rem = value%self.size
if self.lt[rem] == None:
self.lt[rem]= list()
self.lt[rem].append(value)
id = len(self.lt[r... |
from binarytree import Node, pprint
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, node):
if self.root == None:
self.root = node
else:
cur = self.root
prev = cur
while cur!= None:
if nod... |
import random
def extract_array(a,m,n):
lt =list()
for i in range(m,n):
lt.append(a[i])
return lt
def equal_array(a, m, n):
count = 0
for i in range(m, n):
if a[i] ==0:
count+=1
else:
count-=1
return (count == 0)
def ge... |
import random
def max_order(ar, index, n, order,memo):
if index >= n:
return 0
if index < len(memo):
return memo[index]
t1 = ar[index]+max_order(ar,index+2,n,order,memo)
t2 = max_order(ar,index+1,n,order,memo)
if t1 > t2:
memo.append(t1)
if index not in order:
... |
class node:
def __init__(self,value):
self.value = value
self.next = None
def add(first , node):
if( first == None):
first = node
return first
cur = first
while (cur.next != None):
cur = cur.next
else:
cur.next = node
return first
def delet... |
import random
class heapsort:
def __init__(self):
pass
def heapfiy(self, a, N):
for i in range(1, N, 1):
item = a[i]
j = i//2
while j >= 0 and item > a[j]:
a[i] = a[j]
i = j
if j:
... |
def rotate_one(mat,r, c, N):
temp = [None]*4
for i in range(N-1):
# move right the first row
temp[0] = mat[r][c+N-1]
for j in range(N-2, 0, -1):
mat[r][j+1]= mat[r][j]
#move down the last colum
temp[1] = mat[r+N-1][c+N-1]
... |
import random
def find_pair(ar,sum):
ar.sort()
size = len(ar)
last = size-1
first = 0
lt=list()
while first < last:
tmp = ar[first]+ar[last]
if tmp == sum:
lt.append([ar[first],ar[last]])
first+=1
last-=1
elif tmp < sum:
fi... |
import random
def find_next(big, element, index):
for i in range(index, len(big)):
if big[i] == element:
return i
return -1
def find_closure(big,small, index):
max = -1
for item in small:
next = find_next(big, item, index)
if next == -1:
return nex... |
import numpy as np
# First some linear algebra
a = np.array([[1,2,3], [1,2,3]])
b = np.array([1,2,3])
print(a)
print(b)
print ('Numpy dot product of a and b: {}'.format(np.dot(a, b)))
print('''\n-------------------\nSection 2\n-------------------\n''')
input = np.array([1])
weight = np.array([0.6])
def binary_th... |
def num(number):
if number % 100 < 10:
return number
else:
check = number % 10
return check + num(number//10)
a = num(99)
if a >10:
print(num(a))
else:
print(a)
|
from collections import deque
graph = {'Ruslan':[]}
def person_is_seller(person):
pass
def serch_graph(name):
serch_deque = deque()
serch_deque += graph[name]
check_list = []
while serch_deque:
person = serch_deque.popleft()
if not person in check_list:
i... |
"""
This code is taken from the epydemic advanced tutorial.
It creates a network with a powerlaw distribution of connectivity, cutoff at a certain maximum node degree.
"""
import networkx as nx
import math
import numpy as np
from mpmath import polylog as Li # use standard name
def make_powerlaw_with_cutoff(alpha, ... |
# A simple Finch dance in Python
from finch import Finch
from time import sleep
print("Finch's First Python program.")
# Instantiate the Finch object
snakyFinch = Finch()
# Do a six step dance
snakyFinch.led(254,0,0)
snakyFinch.wheels(1,1)
sleep(2)
print("second line")
snakyFinch.led(0,254,0)
snakyFinch.wheel... |
def addup(num):
if num == 2:
return 2
else:
return num + addup(num - 2)
print(addup(10))
def factorial(number, times):
if number == 1:
return 1
else:
return number * factorial(number - 1, times - 1)
print(factorial(4, 4))
|
def partition(array, low, high):
i = low - 1
pivot = array[high]
for j in range(low, high):
if array[j] <= pivot:
i = i + 1
array[i], array[j] = array[j], array[i]
array[i + 1], array[high] = array[high], array[i + 1]
return i + 1
def quick_sort(array, low, hi... |
#L2-Password-Safe: V6
#Daniel Herbert
#28th March 2019
#
# This program is the first stage of a password manager - which provides an interface to remember the multitude of passwords use across various web sites and/or applications
# which require a user name and password combination, to provide authentication access.
#... |
# filename = "test.txt"
#
#
# for each_line in open(filename):
# print each_line
# for each_word in each_line.split():
# print each_word
# print "=============="
import csv
csv_file = "test.csv"
csv_obj = csv.reader(csv_file)
for row in csv_obj:
print row
|
def quick_sort(input_list):
if len(input_list) == 0 or len(input_list) == 1:
return input_list
else:
pivot = input_list[0]
i = 0
for j in range(len(input_list) - 1):
if input_list[j+1] < pivot:
temp = input_list[j+1]
input_list[j+1] = i... |
import math
def find_factorial(n):
"""
Returns the factorial of a given number (n!)
:param n: integer input
:return: integer or error if n is negative
"""
if n < 0:
return "Error: enter positive integer"
elif n == 0 or n == 1:
return 1
else:
return n * find_fact... |
"""
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 a palindrome.
Examp... |
"""
Given a pyramid of consecutive integers:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
......
Find the sum of all the integers in the row number N.
For example:
The row #3: 4 + 5 + 6 = 15
The row #5: 11 + 12 + 13 + 14 + 15 = 65
"""
def sum_pyramid_numbers(row):
i = 1
last_number = 0
while i <= ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 29 16:53:19 2020
@author: hihyun
"""
def solution(s:str):
suffix=[]
for c in range (len(s)):
suffix.append(s[c:])
return sorted(list(suffix))
s=input()
for i in solution(s):
print(i) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 21 19:02:41 2020
@author: hihyun
"""
from collections import defaultdict
class graph:
def __init__(self):
self.graph=defaultdict(list)
def add(self,node1,node2):
self.graph[node1].append(node2)
def show(self):
pri... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 2 15:05:13 2019
@author: hihyun
"""
def solution(priorities, location):
print_data=[]
for i in enumerate(priorities):
print_data.append(i)
x=-1
count=0
while x != location:
check=print_data.pop(0)
if a... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 15 13:29:55 2019
@author: hihyun
"""
#__ --> 특별한 메소드
class Human():
def __init__(self,name,weight):
"""초기화"""
print("__init start")
self.name=name
self.weight=weight
print("name is {}, weight is {}".forma... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 21 17:22:44 2020
@author: hihyun
"""
def partition(arr,l,r):
pivot=arr[r]
p_idx=l-1
for j in range(l,r):
if arr[j]<pivot:
p_idx+=1
arr[j],arr[p_idx]=arr[p_idx],arr[j] #swap
arr[r],arr[p_idx+1]=arr[p_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 17 20:44:55 2020
@author: hihyun
"""
def merge(list):
length=len(list)
if length<=1: #itialize
return list
#divide
g1=merge(list[:length//2])
g2=merge(list[length//2:])
#conquer
sorted=[]
while g1 and g2... |
#!/usr/bin/python3
'''
Criar um dicionario de frutas e amarzenar nome e valor
'''
frutas = [
{'nome':'abacaxi','preco':10},
{'nome':'abacate','preco':5},
{'nome':'melao','preco':12},
{'nome':'melancia','preco':20},
{'nome':'mamao','preco':7}
]
frutas2 = []
for fruta in frutas:
fruta['preco'] += 0.5
frutas2.a... |
#!/usr/bin/python3
# pip3 install psycopg2
import psycopg2
import os
os.system('clear')
try:
con = psycopg2.connect('host=localhost dbname=projeto user=admin password=4linux port=5432')
cur = con.cursor()
print('Conectado com sucesso')
resp = input("Deseja inserir Dados; Sim ou Nao ? ")
if res... |
#!/usr/bin/python3
while True:
try:
num = int(input("Digite um numero: "))
print(num)
break
except ValueError as e:
print("Nao e um inteiro:{}".format(e))
pass
except Exception as e:
print("Nao e um inteiro:{}".format(e)) |
#!/usr/bin/python
"""See if I can implement Quick Sort."""
import random
def qsort(a):
"""Quick Sort array "a" in place."""
def sort_part(first, last):
"""First and last point to the first and last elements (inclusive) in
"a" to be sorted."""
if last <= first:
# A zero- ... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Read input values from CSV file
data = pd.read_csv('input1.txt', names = ['x', 'y'])
X_col = pd.DataFrame(data.x)
y_col = pd.DataFrame(data.y)
m = len(y_col) #Size of input values
iterations = 400 #Number of iterations
alpha = 0.001 #D... |
# Modification of pong: Squash
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
LEFT = False
RIGHT = True
bounce_record = 0
p... |
from HelperMethods import *
from WordCounter import WordCounter
import random
# Create WordCounters with nonsense words and a random word count
wc = WordCounter(makeNonsenseWord(), random.randint(1,45))
print(wc)
wc = WordCounter(makeNonsenseWord(), random.randint(1,45))
print(wc)
wc = WordCounter(mak... |
n = int(input())
fibo = [0, 1]
for i in range(2, n+1):
fibo.append(fibo[i-2]+fibo[i-1])
if n == 0:
print(fibo[0])
else:
print(fibo[-1]) |
N = int(input())
# 소수
prime = [True for _ in range(N+1)]
prime[0] = False
prime[1] = False
for i in range(2, N+1):
if prime[i]:
for j in range(i*2, N+1, i):
prime[j] = False
data = [i for i, boolean in enumerate(prime) if boolean]
# 투포인터
output = 0
end_idx = 0
for i in rang... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the repeatedString function below.
def repeatedString(s, n):
numOfA = 0
if(len(s) >= n):
for i in range(n):
if s[i] == 'a':
numOfA += 1
return numOfA
# truncate division (returns floor)
reps = n // len(s)
... |
"""
T: O(NlogN)
S: O(N)
Remember the initial position of athlete's scores, sort scores, map places to
medal names.
"""
from typing import List
class Solution:
def findRelativeRanks(self, nums: List[int]) -> List[str]:
num_positions = {num: i for i, num in enumerate(nums)}
nums.sort(reverse=True... |
from typing import List
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
prev = float('inf')
write = -1
for num in nums:
if num != prev:
prev = num
write += 1
nums[write] = num
return write+1
|
from typing import List
class Solution:
def distanceBetweenBusStops(self,
distance: List[int],
start: int,
destination: int) -> int:
start, destination = sorted([start, destination])
direct_route = det... |
from typing import List
class Solution:
NUM_OF_COLORS = 3
def shortestDistanceColor(self,
colors: List[int],
queries: List[List[int]]) -> List[int]:
lefts = self.get_left_positions(colors)
rights = self.get_right_positions(colors)
... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def helper(self, node: TreeNode, add_sum: int) -> int:
if not node:
return 0
original = node.val
right_sum = self.helper(node.right, add_sum)
... |
"""
T: O(N)
S: O(N)
We need to only store one mapping using this scheme. Also, the performance of
the encoding method can be treated as O(1) due to the total number of short
URLs being quite large - 62**6.
"""
import random
import string
class Codec:
ALPHABET = string.digits + string.ascii_letters
def __i... |
class Solution:
DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def dayOfYear(self, date: str) -> int:
year, month, day = map(int, date.split('-'))
day += sum(self.DAYS_IN_MONTH[:month-1])
february_index = 2
if self.is_leap(year) and month > february_index:
... |
"""
T: O(N)
S: O(1)
Time to travel between two points is the maximum of their coordinate
differences. Firstly, we can move diagonally, and cover MIN(D1, D2) distance.
After that, we start moving horizontally or vertically for ABS(D1, D2) units.
Combining these two measurements gives as MAX(D1, D2).
"""
from typing i... |
"""
T: O(N)
S: O(N)
A good example of making a recursive solution into an iterative one.
For each node, we need to get to know the depths of their left and right
branches. Using this information, we find the diameter for the current node
and current node depth. The maximum seen diameter is the maximum diameter
of the ... |
class Solution:
def validPalindrome(self, s: str) -> bool:
left, right = 0, len(s)-1
while left < right:
if s[left] != s[right]:
no_left = s[left+1:right+1]
no_right = s[left:right]
return self.is_palindrome(no_left) or \
... |
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
forest = []
nodes_to_delete = set(to_delete)
def delet... |
"""
T: O(N)
S: O(1)
Move two pointers from the ends of both arrays. If we reach the beginning of
either array, we should if it is the first pointer. If so, we still have more
elements to copy using the second pointer.
"""
from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: ... |
"""
T: O(N**3)
S: O(N) -> does not consider output space
We move through the text and collect prefixes that are present in words.
When we seen an actual word, we add its position to the result.
"""
from typing import List
class Trie:
WORD_MARK = '*'
def __init__(self):
self.trie = {}
def inse... |
import random
class RandomizedCollection:
def __init__(self):
self.L = {}
self.N = []
def insert(self, val: int) -> bool:
result = val not in self.L
if result:
self.L[val] = set()
self.L[val].add(len(self.N))
self.N.append(val)
return resul... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def twoSumBSTs(self,
root1: TreeNode,
root2: TreeNode,
target: int) -> bool:
min_stack, max_stack = [], []
w... |
"""
T: O(N)
S: O(N)
Remember numbers we have seen so far alongside their indices.
Return a sorted pair of indices when we see a number that is complement to the
previously seen one.
"""
from typing import Dict, List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
seen_nums ... |
from typing import List
"""
This is the interface that allows for creating nested lists.
You should not implement it, or speculate about its implementation
"""
class NestedInteger:
def __init__(self, value=None):
pass
def isInteger(self):
pass
def add(self, elem):
pass
def... |
"""
T: O(N)
S: O(1)
To figure out the next number, we can observe that is it just a previous number
shifted to the left by one-bit with one bit value added to the right. The code
also demonstrates how to deal with the overflow issue using modulo.
"""
from typing import List
class Solution:
def prefixesDivBy5(s... |
"""
T: O(N)
S: O(1)
Iterate from the back, remember the max element to right, reassign the current
element before updating the max.
"""
from typing import List
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
max_right, N = -1, len(arr)
for i in reversed(range(N)):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.