some simple interview problems

This commit is contained in:
Mari Wahl 2014-12-30 14:21:58 -05:00
parent 3536f80ca0
commit 045e2cc061
15 changed files with 367 additions and 0 deletions

View File

@ -0,0 +1,34 @@
#!/usr/bin/env python
__author__ = "bt3"
class HashTable(object):
def __init__(self, slots=10):
self.slots = slots
self.table = []
self.__create_table()
def __hash_key(self, value):
return hash(value)%self.slots
def __create_table(self):
for i in range(self.slots):
self.table.append([])
def add_item(self, value):
key = self.__hash_key(value)
self.table[key].append(value)
def print_table(self):
for key in range(len(self.table)):
print "Key is %s, value is %s." %(key, self.table[key])
if __name__ == '__main__':
dic = HashTable(5)
for i in range(1, 40, 2):
dic.add_item(i)
dic.print_table()

View File

@ -0,0 +1,26 @@
#!/usr/bin/env python
import random
def benchmark(func):
import time
def wrapper(*args, **kwargs):
t = time.clock()
res = func(*args, **kwargs)
print("\t%s" % func.__name__, time.clock()-t)
return res
return wrapper
@benchmark
def random_tree(n):
temp = [n for n in range(n)]
for i in range(n+1):
temp[random.choice(temp)] = random.choice(temp)
return temp
if __name__ == '__main__':
random_tree(10000)

View File

@ -0,0 +1,13 @@
#!/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

View File

@ -0,0 +1,4 @@
#!/usr/bin/env python
teste = lambda x: x**2
print teste(3)

View File

@ -0,0 +1,35 @@
#!/usr/bin/env python
""" simple example of how to use pickle to export files """
import pickle
def export_pickle(data, filename='test.dat', compress=False):
fh = None
try:
if compress:
fh = gzip.open(filename, "wb") # write binary
else:
fh = open(filename, "wb") # compact binary pickle format
pickle.dump(data, fh, pickle.HIGHEST_PROTOCOL)
except(EnvironmentError, pickle.PickingError) as err:
print("{0}: export error: {1}".format(os.path.basename(sys.argv[0], err)))
return False
finally:
if fh is not None:
fh.close()
def test_export_pickle():
mydict = {'a': 1, 'b': 2, 'c': 3}
export_pickle(mydict)
if __name__ == '__main__':
test_export_pickle()

View File

@ -0,0 +1,36 @@
#!/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()

View File

@ -0,0 +1,35 @@
#!/usr/bin/env python
__author__ = "bt3"
import socket
def netcat(hostname, port, content):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, port))
s.sendall(content)
adata = []
while 1:
data = s.recv(1024)
if data == '':
break
adata.append(data)
s.close()
return adata
if __name__ == '__main__':
PORT = 12345
HOSTNAME = '54.209.5.48'
message = netcat(HOSTNAME, PORT, 'Hello!')[1]
print message

View File

@ -0,0 +1,22 @@
#!/usr/bin/env python
__author__ = "bt3gl"
from telnetlib import Telnet
# examples of telnet connections
PORT = 12345
HOST = '54.209.5.48'
# creating connection
tn = Telnet(HOST ,PORT)
# reading input
msg_in2 = tn.read_all().dec_msg()
tn.read_until(b'psifer text: ')
# writing outputs
tn.write(msg.encode() + b'\n')

View File

@ -0,0 +1,65 @@
-------------------------------------------
'''
>>> 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)

View File

@ -0,0 +1,22 @@
#!/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()

View File

@ -0,0 +1,26 @@
#!/usr/bin/env python
import collections
def find_if_unique_chars(word):
"""
>>> find_if_unique_chars('abcde')
True
>>> find_if_unique_chars('abcae')
False
"""
unique = True
counter = collections.Counter()
for c in word:
if not counter[c]:
counter[c] += 1
else:
unique = False
return unique
if __name__ == '__main__':
import doctest
doctest.testmod()

View File

@ -0,0 +1,28 @@
#!/usr/bin/env python
__author__ = "bt3"
def get_products_of_all_except_at_index(array):
'''
>>> a = [1, 7, 3, 4]
>>> get_products_of_all_except_at_index(a)
[84, 12, 28, 21]
'''
total = 1
for n in array:
total *= n
new_array = []
for n in array:
if n is not 0:
item = total/n
new_array.append(item)
else:
new_array.append(n)
return new_array
if __name__ == '__main__':
import doctest
doctest.testmod()

View File

@ -0,0 +1,21 @@
#!/usr/bin/env python
def invert_word(word):
"""
>>> invert_word('stripe is awesome')
'awesome is stripe'
"""
new_word = []
words = word.split(' ')
for word in words[::-1]:
new_word.append(word)
return " ".join(new_word)
if __name__ == '__main__':
import doctest
doctest.testmod()
#word = 'stripe is awesome'
#print invert_word(word)