mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
organizing 2014 interview problems
This commit is contained in:
parent
4b1fe33f96
commit
d29e0d82ad
17
src/basic_examples/example_args.py
Executable file
17
src/basic_examples/example_args.py
Executable file
@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
def simple2(a, *args):
|
||||
print args
|
||||
|
||||
def simple(*args):
|
||||
print args
|
||||
|
||||
def simple3(**kwargs):
|
||||
print kwargs
|
||||
|
||||
|
||||
simple(1, 2, 3)
|
||||
simple2(1, 2, 3)
|
||||
simple3(x=1, y=2)
|
@ -1,5 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
import random
|
||||
|
37
src/basic_examples/example_comp_lists.py
Normal file
37
src/basic_examples/example_comp_lists.py
Normal file
@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
a = [3, 4, 5, 6, 7]
|
||||
|
||||
|
||||
# Filter elements greater than 4
|
||||
|
||||
# Bad:
|
||||
|
||||
b = []
|
||||
for i in a:
|
||||
if i > 4:
|
||||
b.append(i)
|
||||
print b
|
||||
|
||||
# Good:
|
||||
print [i for i in a if i > 4]
|
||||
|
||||
# Or:
|
||||
print filter(lambda x: x > 4, a)
|
||||
|
||||
|
||||
# Add three to all list members:
|
||||
|
||||
# Bad
|
||||
b = []
|
||||
for i in range(len(a)):
|
||||
b.append(a[i] + 3)
|
||||
print b
|
||||
|
||||
# Good:
|
||||
print [i + 3 for i in a]
|
||||
|
||||
# Or:
|
||||
print map(lambda i: i + 3, a)
|
42
src/basic_examples/example_decorators.py
Executable file
42
src/basic_examples/example_decorators.py
Executable file
@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
|
||||
def logger(func):
|
||||
def inner(*args): #1
|
||||
print "Arguments were: {0}".format(args)
|
||||
return func(*args)
|
||||
return inner
|
||||
|
||||
@logger
|
||||
def foo(x, y):
|
||||
return x+y
|
||||
|
||||
print foo(1, 2)
|
||||
|
||||
|
||||
def sum(func):
|
||||
s = 0
|
||||
for i in func():
|
||||
s += i
|
||||
return s
|
||||
|
||||
@sum
|
||||
def interate():
|
||||
a = []
|
||||
for i in range(10):
|
||||
a.append(i)
|
||||
return a
|
||||
|
||||
print interate
|
||||
|
||||
# which is the same as
|
||||
def interate():
|
||||
a = []
|
||||
for i in range(10):
|
||||
a.append(i)
|
||||
return a
|
||||
|
||||
print sum(interate)
|
27
src/basic_examples/example_generator.py
Normal file
27
src/basic_examples/example_generator.py
Normal file
@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
def interate(x):
|
||||
for i in range(x):
|
||||
yield i
|
||||
|
||||
def gen1():
|
||||
a = interate(10)
|
||||
print a.next()
|
||||
print a.next()
|
||||
print a.next()
|
||||
|
||||
|
||||
def reverse(data):
|
||||
for i in range(len(data)-1, -1, -1):
|
||||
yield data[i]
|
||||
|
||||
def gen2():
|
||||
for c in reverse('awesome'):
|
||||
print c
|
||||
|
||||
if __name__ == '__main__':
|
||||
gen1()
|
||||
gen2()
|
7
src/basic_examples/example_lambda.py
Normal file
7
src/basic_examples/example_lambda.py
Normal file
@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
test = lambda x: x**2
|
||||
print test(3)
|
10
src/basic_examples/example_open_files.py
Normal file
10
src/basic_examples/example_open_files.py
Normal file
@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
filename = raw_input('Enter a file name: ')
|
||||
try:
|
||||
f = open(filename, "r")
|
||||
except:
|
||||
print 'There is no file named', filename
|
||||
|
@ -1,11 +1,33 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
""" simple example of how to use pickle to export files """
|
||||
|
||||
import pickle
|
||||
|
||||
def import_pickle(filename):
|
||||
fh = None
|
||||
try:
|
||||
fh = open(filename, "rb")
|
||||
mydict2 = pickle.load(fh)
|
||||
return mydict2
|
||||
|
||||
except (EnvironmentError) as err:
|
||||
print ("{0}: import error: {0}".format(os.path.basename(sys.arg[0]), err))
|
||||
return false
|
||||
|
||||
finally:
|
||||
if fh is not None:
|
||||
fh.close()
|
||||
|
||||
|
||||
def test_import_pickle():
|
||||
pkl_file = 'test.dat'
|
||||
mydict = import_pickle(pkl_file)
|
||||
print(mydict)
|
||||
|
||||
|
||||
|
||||
def export_pickle(data, filename='test.dat', compress=False):
|
||||
|
||||
fh = None
|
||||
@ -33,3 +55,4 @@ def test_export_pickle():
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_export_pickle()
|
||||
test_import_pickle()
|
@ -1,4 +1,6 @@
|
||||
#!/usr/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
import Queue
|
||||
|
@ -1,3 +1,8 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
foo = 'foo'
|
||||
bar = 'bar'
|
||||
|
8
src/basic_examples/example_subprocess.py
Normal file
8
src/basic_examples/example_subprocess.py
Normal file
@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
import subprocess,os
|
||||
|
||||
os.system('ls')
|
||||
subprocess.call(['ls', '-1'], shell=True)
|
@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
|
||||
__author__ = "bt3gl"
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
from telnetlib import Telnet
|
46
src/basic_examples/example_testing.py
Normal file
46
src/basic_examples/example_testing.py
Normal file
@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
|
||||
def test_doctest():
|
||||
'''
|
||||
>>> 1 == 1
|
||||
False
|
||||
'''
|
||||
pass
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
||||
#####
|
||||
|
||||
import unittest
|
||||
|
||||
class BasicsTestCase(unittest.TestCase):
|
||||
|
||||
def test_find_name(self):
|
||||
self.assertTrue(1 == 1)
|
||||
self.assertFalse(1 == 2)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
|
||||
|
||||
#####
|
||||
|
||||
# content of test_example.py, run with $ py.test
|
||||
#
|
||||
# run tests over the directory
|
||||
# $ nosetest
|
||||
|
||||
|
||||
def func(x):
|
||||
return x + 1
|
||||
|
||||
def test_answer():
|
||||
assert func(3) == 4
|
||||
|
@ -1,25 +1,27 @@
|
||||
class Queue():
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
class Queue(object):
|
||||
def __init__(self):
|
||||
self.in_ = []
|
||||
self.out = []
|
||||
self.enq = []
|
||||
self.deq = []
|
||||
|
||||
def enqueue(self, item):
|
||||
self.in_.append(item)
|
||||
def enqueue(self, value):
|
||||
self.enq.append(value)
|
||||
|
||||
def deque(self):
|
||||
if not self.out:
|
||||
while self.in_:
|
||||
self.out.append(self.in_.pop())
|
||||
def dequeue(self):
|
||||
if not self.deq:
|
||||
while self.enq:
|
||||
self.deq.append(self.enq.pop())
|
||||
return self.deq.pop()
|
||||
|
||||
return self.out.pop()
|
||||
if __name__ == '__main__':
|
||||
q = Queue()
|
||||
|
||||
for i in range(1,10):
|
||||
q.enqueue(i)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
q = Queue()
|
||||
for i in range(10):
|
||||
q.enqueue(i)
|
||||
for i in range(10):
|
||||
print(q.deque())
|
||||
for i in range(1, 10):
|
||||
print q.dequeue()
|
@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
class Stack(object):
|
||||
def __init__(self):
|
||||
self.content = []
|
||||
self.min_array = []
|
||||
self.min = float('inf')
|
||||
|
||||
def push(self, value):
|
||||
if value < self.min:
|
||||
self.min = value
|
||||
|
||||
self.content.append(value)
|
||||
self.min_array.append(self.min)
|
||||
|
||||
def pop(self):
|
||||
if self.content:
|
||||
value = self.content.pop()
|
||||
self.min_array.pop()
|
||||
if self.min_array:
|
||||
self.min = self.min_array[-1]
|
||||
return value
|
||||
else:
|
||||
return 'Empty List. '
|
||||
|
||||
def find_min(self):
|
||||
if self.min_array:
|
||||
return self.min_array[-1]
|
||||
else:
|
||||
return 'No min value for empty list.'
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
q = Stack()
|
||||
|
||||
for i in range(15,20):
|
||||
q.push(i)
|
||||
for i in range(10,5,-1):
|
||||
q.push(i)
|
||||
|
||||
|
||||
|
||||
for i in range(1, 13):
|
||||
print q.pop(), q.find_min()
|
@ -1,9 +0,0 @@
|
||||
Another way:
|
||||
|
||||
Store two stacks, one of which contains all of the items in the stack and one of which is a stack of minima.
|
||||
|
||||
To push an element, push it onto the first stack. Check whether it is smaller than the top item on the second stack, if so, push it onto the second stack.
|
||||
|
||||
To pop an item, pop it from the first stack. If it is the top element, simply return the element on the top of the second stack.
|
||||
|
||||
O(1)...
|
@ -1,4 +1,7 @@
|
||||
#!/bin/python3
|
||||
#!/usr/bin/env python3
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
from functools import lru_cache
|
||||
|
||||
|
@ -1,28 +0,0 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
def simple2(a, *args):
|
||||
print args
|
||||
|
||||
def simple(*args):
|
||||
print args
|
||||
|
||||
def simple3(**kwargs):
|
||||
print kwargs
|
||||
|
||||
|
||||
simple(1, 2, 3)
|
||||
simple2(1, 2, 3)
|
||||
simple3(x=1, y=2)
|
||||
|
||||
|
||||
def logger(func):
|
||||
def inner(*args): #1
|
||||
print "Arguments were: {0}".format(args)
|
||||
return func(*args)
|
||||
return inner
|
||||
|
||||
@logger
|
||||
def foo(x, y):
|
||||
return x+y
|
||||
|
||||
print foo(1, 2)
|
@ -1,26 +0,0 @@
|
||||
Bad:
|
||||
|
||||
# Filter elements greater than 4
|
||||
a = [3, 4, 5]
|
||||
b = []
|
||||
for i in a:
|
||||
if i > 4:
|
||||
b.append(i)
|
||||
Good:
|
||||
|
||||
a = [3, 4, 5]
|
||||
b = [i for i in a if i > 4]
|
||||
# Or:
|
||||
b = filter(lambda x: x > 4, a)
|
||||
Bad:
|
||||
|
||||
# Add three to all list members.
|
||||
a = [3, 4, 5]
|
||||
for i in range(len(a)):
|
||||
a[i] += 3
|
||||
Good:
|
||||
|
||||
a = [3, 4, 5]
|
||||
a = [i + 3 for i in a]
|
||||
# Or:
|
||||
a = map(lambda i: i + 3, a)
|
@ -1,13 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
" Example of generator."
|
||||
|
||||
def reverse(data):
|
||||
for i in range(len(data)-1, -1, -1):
|
||||
yield data[i]
|
||||
|
||||
if __name__ == '__main__':
|
||||
for c in reverse('awesome'):
|
||||
print c
|
@ -1,4 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
teste = lambda x: x**2
|
||||
print teste(3)
|
@ -1,65 +0,0 @@
|
||||
-------------------------------------------
|
||||
'''
|
||||
>>> 1 == 1
|
||||
False
|
||||
'''
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
||||
-------------------------------------------
|
||||
|
||||
import unittest
|
||||
|
||||
class BasicsTestCase(unittest.TestCase):
|
||||
|
||||
def test_find_name(self):
|
||||
self.assertTrue(1 == 1)
|
||||
self.assertFalse(1 == 2)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
-------------------------------------------
|
||||
|
||||
# content of test_example.py, run with $ py.test
|
||||
|
||||
def func(x):
|
||||
return x + 1
|
||||
|
||||
def test_answer():
|
||||
assert func(3) == 4
|
||||
|
||||
-------------------------------------------
|
||||
|
||||
# run tests over the directory
|
||||
$ nosetest
|
||||
|
||||
---------------------------------------------
|
||||
|
||||
filename = raw_input('Enter a file name: ')
|
||||
try:
|
||||
f = open(filename, "r")
|
||||
except:
|
||||
print 'There is no file named', filename
|
||||
|
||||
raise Exception('Invalid config file: expecting keys "aws_access_key", "aws_secret_key", "bucket"')
|
||||
g = lambda x: x ** 2
|
||||
|
||||
try:
|
||||
operation, filename = sys.argv[1:]
|
||||
except ValueError:
|
||||
print __doc__
|
||||
sys.exit(2)
|
||||
|
||||
subprocess.call()
|
||||
try:
|
||||
response = urllib2.urlopen()
|
||||
|
||||
-----------------------------------------------
|
||||
|
||||
import subprocess,os
|
||||
|
||||
os.system('ls')
|
||||
subprocess.call(['ls', '-1'], shell=True)
|
@ -1,36 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
|
||||
__author__ = "Mari Wahl"
|
||||
__email__ = "marina.w4hl@gmail.com"
|
||||
|
||||
|
||||
""" an example of using pickle for importing data from files """
|
||||
|
||||
|
||||
import pickle
|
||||
|
||||
def import_pickle(filename):
|
||||
fh = None
|
||||
try:
|
||||
fh = open(filename, "rb")
|
||||
mydict2 = pickle.load(fh)
|
||||
return mydict2
|
||||
|
||||
except (EnvironmentError) as err:
|
||||
print ("{0}: import error: {0}".format(os.path.basename(sys.arg[0]), err))
|
||||
return false
|
||||
|
||||
finally:
|
||||
if fh is not None:
|
||||
fh.close()
|
||||
|
||||
|
||||
def test_import_pickle():
|
||||
pkl_file = 'test.dat'
|
||||
mydict = import_pickle(pkl_file)
|
||||
print(mydict)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_import_pickle()
|
@ -1,4 +1,6 @@
|
||||
#!/usr/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
''' Clear a bit in a binary number.
|
||||
Like the reverse of set bit:
|
||||
|
@ -1,4 +1,6 @@
|
||||
#!/usr/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
''' Find how many bits a int has:
|
||||
1) Start with a mask of 1
|
||||
|
@ -1,4 +1,6 @@
|
||||
#!/usr/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
''' Get a bit in a binary number:
|
||||
1) Shifts 1 over by i bits
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/usr/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
''' This method returns the number of bits that are necessary to change to convert two
|
||||
numbers A and B:
|
||||
|
@ -1,4 +1,9 @@
|
||||
#!/usr/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
|
||||
''' Set a bit in a binary number:
|
||||
1) Shifts 1 over by i bits
|
||||
2) make an OR with the number, only the value at bit i will change and all the others bit
|
||||
|
@ -1,4 +1,6 @@
|
||||
#!/usr/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
'''
|
||||
swapping values in place without extra memory
|
||||
|
@ -1,4 +1,6 @@
|
||||
#!/usr/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
''' This method merges set bit and clean bit:
|
||||
1) first clear the bit at i using a mask such as 1110111
|
||||
|
@ -1,21 +0,0 @@
|
||||
DESIGN PATTERNS
|
||||
------------------------
|
||||
|
||||
LISTENER/OBSERVER:
|
||||
-----------------
|
||||
|
||||
- Example: a GUI as a listener to several objects. For any change in the state, it would update the display.
|
||||
|
||||
|
||||
SINGLETON PATTERN:
|
||||
-----------------
|
||||
|
||||
- To make sure that there is exactly one instance of something in the program.
|
||||
|
||||
|
||||
MODEL-VIEW-CONTROLLER:
|
||||
----------------------
|
||||
|
||||
- Design commonly used in user interfaces. The goal is to keep the data separate from the interface.
|
||||
- Separate programming entities to store the data (model), display the data (view) and modify the data (controlle).
|
||||
- The view usually makes heavy use of listeners to listen to changes and events in the model or controller.
|
@ -1,8 +0,0 @@
|
||||
DESIGN A TEXT EDITOR
|
||||
-------------------------------------
|
||||
|
||||
- Classes to set up the text editor: classes for the GUI, formatting, saving/loading files, handling input.
|
||||
|
||||
- Use inheritance where it makes sense.
|
||||
|
||||
- Use design patterns (such as MVC, listener, singleton).
|
@ -1,39 +0,0 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
|
||||
# testing generator
|
||||
|
||||
def interate(x):
|
||||
for i in range(x):
|
||||
yield i
|
||||
|
||||
a = interate(10)
|
||||
|
||||
print a.next()
|
||||
print a.next()
|
||||
print a.next()
|
||||
|
||||
# testing decorator
|
||||
|
||||
def sum(func):
|
||||
s = 0
|
||||
for i in func():
|
||||
s += i
|
||||
return s
|
||||
|
||||
@sum
|
||||
def interate():
|
||||
a = []
|
||||
for i in range(10):
|
||||
a.append(i)
|
||||
return a
|
||||
|
||||
print interate
|
||||
|
||||
def interate():
|
||||
a = []
|
||||
for i in range(10):
|
||||
a.append(i)
|
||||
return a
|
||||
|
||||
print sum(interate)
|
@ -1,3 +1,8 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
Given an english word in the form of a string, how can you quickly find all valid anagrams for that string?
|
||||
|
||||
First you go through each word in the dictionary, sort the letters of the word and use this as a key in a Hash Table. O(nln n).
|
||||
|
@ -1,3 +1,8 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
This is the classic "you have 8 balls/coins, which are the same weight, except for one which is slightly heavier than the others. You also have an old-style balance. What is the fewest number of weighings to find the heavy coin/ball?
|
||||
|
||||
Answer: 2! You need to use every information available:
|
||||
|
@ -1,5 +1,6 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
"""
|
||||
Given an integer x and an unsorted array of integers, describe an algorithm to
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/usr/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
""" find whether two words are anagrams. Since sets do not count occurency, and sorting is O(nlogn)
|
||||
we will use hash tables. We scan the first string and add all the character occurences. Then we
|
||||
|
@ -1,38 +0,0 @@
|
||||
#!/bin/python
|
||||
|
||||
''' Check if palindrome'''
|
||||
|
||||
|
||||
def check_pal(string):
|
||||
string = "".join(string.split(' '))
|
||||
p1, p2 = 0, len(string)-1
|
||||
pal = True
|
||||
while p1 < p2:
|
||||
if string[p1] != string[p2]:
|
||||
pal = False
|
||||
break
|
||||
p1+=1
|
||||
p2-=1
|
||||
return pal
|
||||
|
||||
|
||||
def check_pal2(string):
|
||||
string = "".join(string.split(' '))
|
||||
if len(string)<2:
|
||||
return True
|
||||
if string[0] != string[-1]:
|
||||
return False
|
||||
return check_pal2(string[1:-1])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
string1 = "borrow or rob"
|
||||
string2 = " draw ward"
|
||||
string3 = "google is fun"
|
||||
print(check_pal(string1))
|
||||
print(check_pal(string2))
|
||||
print(check_pal(string3))
|
||||
print
|
||||
print(check_pal2(string1))
|
||||
print(check_pal2(string2))
|
||||
print(check_pal2(string3))
|
@ -1,16 +1,19 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
''' give all the combinations of a str or list '''
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
def comb_str(l1):
|
||||
|
||||
if len(l1) < 2:
|
||||
return l1
|
||||
|
||||
result = []
|
||||
for i, c in enumerate(l1):
|
||||
result.append(c)
|
||||
for comb in comb_str(l1[i+1:]):
|
||||
result.append(c + "".join(comb))
|
||||
result.append(c + comb)
|
||||
|
||||
return result
|
||||
|
||||
|
@ -1,22 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
def define_if_permutation(word1, word2):
|
||||
"""
|
||||
>>> define_if_permutation('hello', 'lolhe')
|
||||
True
|
||||
>>> define_if_permutation('stripe', 'triipe')
|
||||
False
|
||||
"""
|
||||
if sorted(word1) == sorted(word2):
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
@ -1,23 +1,36 @@
|
||||
#!/usr/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
''' find and delete all the duplicate characters in a string '''
|
||||
|
||||
|
||||
import string
|
||||
|
||||
def delete_unique_word(str1):
|
||||
table_c = { key : 0 for key in string.ascii_lowercase}
|
||||
for i in str1:
|
||||
table_c[i] += 1
|
||||
for key, value in table_c.items():
|
||||
if value > 1:
|
||||
str1 = str1.replace(key, "")
|
||||
from collections import Counter
|
||||
def delete_unique(str1):
|
||||
'''
|
||||
>>> delete_unique("Trust no one")
|
||||
'on'
|
||||
>>> delete_unique("Mulder?")
|
||||
''
|
||||
'''
|
||||
|
||||
return str1
|
||||
str_strip = ''.join(str1.split())
|
||||
repeat = Counter()
|
||||
|
||||
for c in str_strip:
|
||||
repeat[c] += 1
|
||||
|
||||
result = ''
|
||||
for c, count in repeat.items():
|
||||
if count > 1:
|
||||
result += c
|
||||
|
||||
return result
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
str1 = "google"
|
||||
print delete_unique_word(str1) # == 'le'
|
||||
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
@ -1,9 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
''' understanding generators'''
|
||||
|
||||
def fib_generator():
|
||||
a, b = 0, 1
|
||||
|
@ -1,81 +0,0 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
|
||||
def find_permutations(s):
|
||||
if len(s) < 2: return s
|
||||
res = []
|
||||
for i, c in enumerate(s):
|
||||
for perm in find_permutations(s[:i] + s[i+1:]):
|
||||
res.append(c + "".join(perm))
|
||||
return res
|
||||
|
||||
|
||||
def fpc(s):
|
||||
return [s] if len(s)<2 else [c+p for i,c in enumerate(s) for p in fpc(s[:i]+s[i+1:])]
|
||||
|
||||
|
||||
def find_permutations_stdlib(s):
|
||||
from itertools import permutations
|
||||
return [''.join(p) for p in permutations(s)]
|
||||
|
||||
|
||||
def find_permutations2(s):
|
||||
if len(s) < 2: return s
|
||||
res = []
|
||||
for i in range(len(s)):
|
||||
for perm in find_permutations2(s[:i] + s[i+1:]):
|
||||
res.append(s[i] + perm)
|
||||
return res
|
||||
|
||||
|
||||
def verify_if_perm(s1, s2):
|
||||
if len(s1) != len(s2): return False
|
||||
s1 = sorted(s1)
|
||||
s2 = sorted(s2)
|
||||
return s1 == s2
|
||||
|
||||
|
||||
from collections import Counter
|
||||
def verify_if_perm2(s1, s2): # like anagram
|
||||
if len(s1) != len(s2): return False
|
||||
dict_aux = Counter()
|
||||
for c in s1:
|
||||
dict_aux[c] += 1
|
||||
for c in s2:
|
||||
dict_aux[c] -= 1
|
||||
for item in dict_aux:
|
||||
if dict_aux[item]:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
s1 = 'ufyfbufyfb'
|
||||
s2 = 'buffybuffy'
|
||||
s3 = 'uuyfbuuyfb'
|
||||
s4 = ''
|
||||
|
||||
print(verify_if_perm(s1, s2))
|
||||
print(verify_if_perm(s1, s3))
|
||||
print(verify_if_perm(s1, s4))
|
||||
print
|
||||
print(verify_if_perm2(s1, s2))
|
||||
print(verify_if_perm2(s1, s3))
|
||||
print(verify_if_perm2(s1, s4))
|
||||
|
||||
print
|
||||
|
||||
s = 'hat'
|
||||
print find_permutations(s)
|
||||
print fpc(s)
|
||||
print find_permutations_stdlib(s)
|
||||
print find_permutations2(s)
|
||||
print
|
||||
print find_permutations(s4)
|
||||
print fpc(s4)
|
||||
print find_permutations_stdlib(s4)
|
||||
print find_permutations2(s4)
|
||||
|
||||
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/usr/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
def isSubstr(s1, s2):
|
||||
if s1 in s2 or s2 in s1: return True
|
||||
|
@ -1,5 +1,9 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
|
||||
import collections
|
||||
|
||||
def find_if_unique_chars(word):
|
||||
@ -13,11 +17,13 @@ def find_if_unique_chars(word):
|
||||
unique = True
|
||||
|
||||
counter = collections.Counter()
|
||||
|
||||
for c in word:
|
||||
if not counter[c]:
|
||||
counter[c] += 1
|
||||
else:
|
||||
unique = False
|
||||
|
||||
return unique
|
||||
|
||||
|
||||
|
@ -1,4 +1,8 @@
|
||||
#!/usr/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
|
||||
'''You are given an array of integers (both positive and negative). Find the contiguous
|
||||
sequence with the largest sum. Return the sum.'''
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/usr/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
from collections import defaultdict
|
||||
|
||||
|
@ -1,7 +1,8 @@
|
||||
#!/usr/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
'''Design an algorithm to find all pairs of integers within an array
|
||||
which sum to a specified value.'''
|
||||
|
||||
from collections import defaultdict
|
||||
|
||||
|
@ -1,11 +1,14 @@
|
||||
#!/usr/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
|
||||
def finding_gcd(a, b):
|
||||
''' implements the greatest common divider algorithm '''
|
||||
while(b != 0):
|
||||
result = b
|
||||
a, b = b, a % b
|
||||
a, b = b, a % b
|
||||
return result
|
||||
|
||||
|
||||
@ -20,7 +23,7 @@ if __name__ == '__main__':
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
@ -1,6 +1,8 @@
|
||||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
|
||||
import math
|
||||
import random
|
||||
@ -13,7 +15,7 @@ def finding_prime(number):
|
||||
if num % x == 0:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
|
||||
def finding_prime_sqrt(number):
|
||||
''' find whether a number is prime as soon as it rejects all candidates up to sqrt(n) '''
|
||||
|
@ -1,6 +1,7 @@
|
||||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
import math
|
||||
import random
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/usr/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
''' Given a real number between 0 and 1 (eg: 0.72), this method print the binary
|
||||
representation. If the Number cannot be represented accurately in binary, with at
|
||||
|
@ -1,7 +1,6 @@
|
||||
#!/usr/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "Mari Wahl"
|
||||
__email__ = "marina.w4hl@gmail.com"
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
|
||||
|
@ -1,3 +1,9 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
|
||||
def beating_stock(array):
|
||||
|
||||
imin = 0
|
||||
|
@ -1,3 +1,9 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
|
||||
How to know how many 0 are in 100!
|
||||
|
||||
You look for the primes that multiply to 10, i.e. 2 and 5.
|
||||
|
@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
|
||||
def perm(str1):
|
||||
'''
|
||||
>>> perm('123')
|
||||
['123', '132', '231', '213', '312', '321']
|
||||
'''
|
||||
|
||||
if len(str1) < 2:
|
||||
return str1
|
||||
|
||||
res = []
|
||||
for i, c in enumerate(str1):
|
||||
for cc in perm(str1[i+1:] + str1[:i]):
|
||||
res.append(c + cc)
|
||||
return res
|
||||
|
||||
|
||||
def perm2(str1):
|
||||
'''
|
||||
>>> perm2('123')
|
||||
['123', '132', '213', '231', '312', '321']
|
||||
'''
|
||||
from itertools import permutations
|
||||
return [''.join(p) for p in permutations(str1)]
|
||||
|
||||
|
||||
def ispermutation(s1, s2):
|
||||
'''
|
||||
>>> ispermutation('231', '123')
|
||||
True
|
||||
>>> ispermutation('231', '153')
|
||||
False
|
||||
'''
|
||||
|
||||
from collections import Counter
|
||||
aux = Counter()
|
||||
for i in s1:
|
||||
aux[i] += 1
|
||||
for i in s2:
|
||||
aux[i] -= 1
|
||||
for v in aux.values():
|
||||
if v != 0:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
|
||||
|
||||
def ispermutation2(s1, s2):
|
||||
'''
|
||||
>>> ispermutation2('231', '123')
|
||||
True
|
||||
>>> ispermutation2('231', '153')
|
||||
False
|
||||
'''
|
||||
if sorted(s1) == sorted(s2):
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
@ -1,3 +1,9 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
|
||||
from collections import Counter
|
||||
|
||||
def check_if_ransom_note(magazines, note):
|
||||
|
@ -1,4 +1,8 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
|
||||
''' Reverting a string '''
|
||||
|
||||
|
@ -1,5 +1,9 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
|
||||
def invert_word(word):
|
||||
"""
|
||||
>>> invert_word('stripe is awesome')
|
||||
|
@ -1,5 +1,6 @@
|
||||
#!/usr/bin python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
def reversing_words_setence_py(s):
|
||||
|
@ -1,3 +0,0 @@
|
||||
How to shuffle an array or a deck of cards so each shuffle has the same probability?
|
||||
|
||||
go thru the array shuffling each element with any random element after that.
|
@ -1,17 +1,27 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
''' Quick sort an array '''
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
def quick_sort(arr):
|
||||
if len(arr) < 2: return arr
|
||||
piv = len(arr)//2
|
||||
left = [x for i, x in enumerate(arr) if x <= arr[piv] and i != piv]
|
||||
right = [x for i, x in enumerate(arr) if x > arr[piv] and i != piv]
|
||||
return quick_sort(left) + [arr[piv]] + quick_sort(right)
|
||||
def qs(array):
|
||||
'''
|
||||
>>> qs([4,1,6,2,7,9,3])
|
||||
[1, 2, 3, 4, 6, 7, 9]
|
||||
'''
|
||||
if len(array) < 2:
|
||||
return array
|
||||
|
||||
piv = len(array)//2
|
||||
piv_element = array[piv]
|
||||
new_array = array[:piv] + array[piv+1:]
|
||||
|
||||
left = [a for a in new_array if a <= piv_element]
|
||||
right = [a for a in new_array if a > piv_element]
|
||||
|
||||
|
||||
return qs(left) + [array[piv]] + qs(right)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
arr = [8, 5, 2, 6, 1, 2, 9, 4]
|
||||
print(quick_sort(arr))
|
||||
import doctest
|
||||
doctest.testmod()
|
@ -1,4 +1,7 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
''' Write code to generate all possible case permutations of a given
|
||||
lower-cased string
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
from collections import Counter
|
||||
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
|
||||
def binary_search_rec(array, item, lo=0, hi = None):
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
''' Determine if an Array of integers contains 3 numbers that sum to 0 '''
|
||||
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
'''
|
||||
Given a tree find out whether is a BST or not
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
|
||||
from collections import defaultdict
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
'''
|
||||
given an array of intervals, return max number of non-overlapping intervals
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
'''
|
||||
Given an unsorted array of numbers (that may contain repeated numbers),
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
'''
|
||||
given a string, find longest string with unique characters
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
'''
|
||||
Write a function to find the nth Fibonacci number.
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
'''
|
||||
find prime factors of a number.
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
'''
|
||||
Given two strings, write a function
|
||||
@ -32,6 +35,15 @@ def lcp(s1, s2):
|
||||
|
||||
return len(lcp)
|
||||
|
||||
def lcppy(x):
|
||||
'''
|
||||
>>> lcppy([[3,2,1], [3,2,1,4,5]])
|
||||
[3, 2, 1]
|
||||
'''
|
||||
|
||||
import os
|
||||
return os.path.commonprefix(x)
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
'''
|
||||
You have two arrays with N integers in them. Merge those arrays using a
|
||||
|
@ -1,4 +1,6 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
''' Generate all permutations of an alphanumeric string '''
|
||||
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
'''
|
||||
find the sum of two integers represented as strings,
|
||||
|
@ -1,4 +1,6 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
'''
|
||||
Reconstruct a binary tree given two sequences of node traversals,
|
||||
|
@ -1,4 +1,7 @@
|
||||
#!/bin/python
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
'''
|
||||
Implement a trie. (Write the API and code for inserting into a trie).
|
||||
|
Loading…
x
Reference in New Issue
Block a user