Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,27 @@
Tests for puzzles found on Leetcode and other interview preparation websites.

<h3>Minimum Height Tree</h3>
To run the solution:
Procedure:

1. Enter your input and expected output arguments in testcases/minimumheighttree.json as per schema defined in the file.
2. Run `python3 solutions/python3/minimumheighttree.py`
python3 testharness.py rotatearray.py
1. Write the solution for desired problem in workspace/python3/
2. To check the solution,run `python3 testharness.py filename(without extension)`
Example: `python3 testharness.py rotatearray`

The results can be seen as
Your Answer : [0, 1] True Answer: [0, 1]
Correct answer

For now, it only works for python3.
```Running testcase workspace/python3workspace/rotatearray.py
Correct Answer
Your Answer: [5, 6, 7, 1, 2, 3, 4] Expected Answer: [5, 6, 7, 1, 2, 3, 4]
Correct Answer
Your Answer: [1, 2, 3] Expected Answer: [1, 2, 3]
Correct Answer
Your Answer: [2, 1] Expected Answer: [2, 1]
All testcases passed. Good going.
```

\
For now, it only works for python3.
\
TODO:
Add support for more languages.
Add code for many more leetcode puzzles.
57 changes: 57 additions & 0 deletions createProblem.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
from shutil import copyfile
import os

newfile = 'zigzagconversion'
oldfile = 'dummy'
src = f'./goldFiles/python3/{oldfile}.py'
dst = f'./goldFiles/python3/{newfile}.py'
copyfile(src, dst)

src = f'./testcases/{oldfile}.json'
dst = f'./testcases/{newfile}.json'
copyfile(src, dst)

src = f'./workspace./python3workspace./{oldfile}.py'
dst = f'./workspace./python3workspace./{newfile}.py'
copyfile(src, dst)


########
#populate __init__.py
def py(s):
if s[-3:] == '.py' and s[:2] != '__':
return True

return False

fileslist = os.listdir('./goldFiles/python3/')
print(fileslist)

solsNames = list(filter(py,fileslist))

solsImports = ["import sys","sys.path.insert(0,'./goldFiles/python3')",""]
for s in solsNames:
sol = f"from {s[:-3]} import *"
solsImports.append(sol)

init = open('./goldFiles/python3/__init__.py','w')
init.write('\n'.join(solsImports))
init.close()
print('\n'.join(solsImports))
# print(solsImports)


fileslist = os.listdir('./workspace/python3workspace/')
print(fileslist)

solsNames = list(filter(py,fileslist))

solsImports = ["import sys","sys.path.insert(0,'./workspace/python3workspace')",""]
for s in solsNames:
sol = f"from {s[:-3]} import *"
solsImports.append(sol)

init = open('./workspace/python3workspace/__init__.py','w')
init.write('\n'.join(solsImports))
init.close()
print('\n'.join(solsImports))
45 changes: 45 additions & 0 deletions createTestcase.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import json
import random,string
import numpy as np
import sys
problem_keyword = sys.argv[1]
# problem_keyword is used specifying the program that needs to be run
# problem_keyword = 'permutations'

def genArgUsingDtype(d,type):
# Read the datatype and generate random testcase
if d == "string": # generate a random string of length between 3 and 50
length = random.randint(3,50)
return ''.join(random.choice(string.ascii_letters) for m in range(length))
elif d == "integer": # integer numbers
return random.randint(0,50)
elif d == "array":
if type['items']['type'] == 'number': # generate a random array
return list(np.random.randint(-50,50,random.randint(1,50)))
elif d == "number": #float numbers
return random.random()*random.randint(-100,100)
elif d == "matrix": # generate a square matrix of size matrixSize
matrixSize = random.randint(1,15)
return np.random.randint(0,2,(matrixSize,matrixSize))

testcases = open(f'./testcases/{problem_keyword}.json')
testcases = json.load(testcases)
# print(testcases)


inputArgs = list(testcases['testcases'][0]['args'].keys())
schema = testcases['schema']
args = testcases['testcases'][0]['args'].copy()

if 'checkUnorderedLists' in inputArgs:
inputArgs.remove('checkUnorderedLists')
for i in inputArgs:
"""
pass all the input args types to the generator
function and get random testcase for input argument
"""
dtype = schema['properties']['args']['properties'][i]['type']
arg = genArgUsingDtype(dtype,schema['properties']['args']['properties'][i])
args[i] = arg

print(args)
15 changes: 15 additions & 0 deletions goldFiles/python3/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import sys
sys.path.insert(0,'./goldFiles/python3')

from dummy import *
from firstmissingpositive import *
from medianoftwosortedarrays import *
from minimumheighttree import *
from multiplystrings import *
from palindromepartitioning import *
from permutations import *
from pow_x_n import *
from pythonsolution import *
from rotatearray import *
from rotateimage import *
from zigzagconversion import *
6 changes: 6 additions & 0 deletions goldFiles/python3/dummy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from typing import List
import json
from schema import Schema, And, Use, Optional, SchemaError

class Solution:
"""Add your methods here for gold solution"""
26 changes: 26 additions & 0 deletions goldFiles/python3/firstmissingpositive.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from typing import List
import json
from schema import Schema, And, Use, Optional, SchemaError

class Solution:
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
Basic idea:
1. for any array whose length is l, the first missing positive must be in range [1,...,l+1],
so we only have to care about those elements in this range and remove the rest.
2. we can use the array index as the hash to restore the frequency of each number within
the range [1,...,l+1]
"""
nums.append(0)
n = len(nums)
for i in range(len(nums)): #delete those useless elements
if nums[i]<0 or nums[i]>=n:
nums[i]=0
for i in range(len(nums)): #use the index as the hash to record the frequency of each number
nums[nums[i]%n]+=n
for i in range(1,len(nums)):
if nums[i]/n==0:
return i
return n
25 changes: 25 additions & 0 deletions goldFiles/python3/medianoftwosortedarrays.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from typing import List
import json
from schema import Schema, And, Use, Optional, SchemaError

class Solution:
# @return a float
def findMedianSortedArrays(self, A, B):
l=len(A)+len(B)
return self.findKth(A,B,l//2) if l%2==1 else (self.findKth(A,B,l//2-1)+self.findKth(A,B,l//2))/2.0


def findKth(self,A,B,k):
if len(A)>len(B):
A,B=B,A
if not A:
return B[k]
if k==len(A)+len(B)-1:
return max(A[-1],B[-1])
i=len(A)//2
j=k-i
if A[i]>B[j]:
#Here I assume it is O(1) to get A[:i] and B[j:]. In python, it's not but in cpp it is.
return self.findKth(A[:i],B[j:],i)
else:
return self.findKth(A[i:],B[:j],j)
7 changes: 7 additions & 0 deletions goldFiles/python3/minimumheighttree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from typing import List
import json
from schema import Schema, And, Use, Optional, SchemaError

class Solution:
def multiply(self, num1: str, num2: str) -> str:
return str(int(num1)*int(num2))
7 changes: 7 additions & 0 deletions goldFiles/python3/multiplystrings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from typing import List
import json
from schema import Schema, And, Use, Optional, SchemaError

class Solution:
def multiply(self, num1: str, num2: str) -> str:
return str(int(num1)*int(num2))
21 changes: 21 additions & 0 deletions goldFiles/python3/palindromepartitioning.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from typing import List
import json
from schema import Schema, And, Use, Optional, SchemaError

class Solution:
# palindromepartition
def partition(self, s):
res = []
self.dfs(s, [], res)
return res

def dfs(self, s, path, res):
if not s:
res.append(path)
return
for i in range(1, len(s)+1):
if self.isPal(s[:i]):
self.dfs(s[i:], path+[s[:i]], res)

def isPal(self, s):
return s == s[::-1]
9 changes: 9 additions & 0 deletions goldFiles/python3/permutations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from typing import List
import json
from schema import Schema, And, Use, Optional, SchemaError

class Solution:
def permute(self, nums):
return [[n] + p
for i, n in enumerate(nums)
for p in self.permute(nums[:i] + nums[i+1:])] or [[]]
7 changes: 7 additions & 0 deletions goldFiles/python3/pow_x_n.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from typing import List
import json
from schema import Schema, And, Use, Optional, SchemaError

class Solution:
def myPow(self, x: float, n: int) -> float:
return x**n
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
from schema import Schema, And, Use, Optional, SchemaError

class Solution:

#One method for each keyword.
# minimumheighttree
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
try:
n = Schema(int).validate(n)
Expand Down Expand Up @@ -39,6 +39,8 @@ def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
except :
return "Check the format of input variables"


# rotatearray
def reverse(self, nums,start,end):
while start < end:
nums[start],nums[end] = nums[end],nums[start]
Expand All @@ -52,3 +54,37 @@ def rotate(self, nums: List[int], k: int) -> None:
self.reverse(nums,0,k-1)
self.reverse(nums,k,n-1)
# nums[:] = nums[-k:] + nums[:-k]

# rotatematrix
def rotate(self, matrix: List[List[int]]) -> None:
self.transpose(matrix)
self.reflect(matrix)

def transpose(self, matrix):
n = len(matrix)
for i in range(n):
for j in range(i, n):
matrix[j][i], matrix[i][j] = matrix[i][j], matrix[j][i]

def reflect(self, matrix):
n = len(matrix)
for i in range(n):
for j in range(n // 2):
matrix[i][j], matrix[i][-j - 1] = matrix[i][-j - 1], matrix[i][j]

# palindromepartition
def partition(self, s):
res = []
self.dfs(s, [], res)
return res

def dfs(self, s, path, res):
if not s:
res.append(path)
return
for i in range(1, len(s)+1):
if self.isPal(s[:i]):
self.dfs(s[i:], path+[s[:i]], res)

def isPal(self, s):
return s == s[::-1]
20 changes: 20 additions & 0 deletions goldFiles/python3/rotatearray.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from typing import List
import json
from schema import Schema, And, Use, Optional, SchemaError

class Solution:
# rotatearray
def reverse(self, nums,start,end):
while start < end:
nums[start],nums[end] = nums[end],nums[start]
start,end = start+1,end-1

def rotate(self, nums: List[int], k: int) -> None:
n = len(nums)
k %= n

self.reverse(nums,0,n-1)
self.reverse(nums,0,k-1)
self.reverse(nums,k,n-1)
# nums[:] = nums[-k:] + nums[:-k]

23 changes: 23 additions & 0 deletions goldFiles/python3/rotateimage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from typing import List
import json
from schema import Schema, And, Use, Optional, SchemaError

class Solution:
#One method for each keyword.

# rotateimage
def rotate(self, matrix: List[List[int]]) -> None:
self.transpose(matrix)
self.reflect(matrix)

def transpose(self, matrix):
n = len(matrix)
for i in range(n):
for j in range(i, n):
matrix[j][i], matrix[i][j] = matrix[i][j], matrix[j][i]

def reflect(self, matrix):
n = len(matrix)
for i in range(n):
for j in range(n // 2):
matrix[i][j], matrix[i][-j - 1] = matrix[i][-j - 1], matrix[i][j]
Loading