all interview problems organized, and cleaned up repeats

This commit is contained in:
Mari Wahl 2015-01-06 18:19:00 -05:00
parent a4637a3411
commit c2ca11f247
13 changed files with 98 additions and 268 deletions

View File

@ -25,7 +25,24 @@ def is_anagram(s1, s2):
return True
''' verify if words are anagrams by comparing a sum of Unicode code
point of the character'''
def get_unicode_sum(word):
s = 0
for p in word:
s += ord(p)
return s
def is_anagram2(word1, word2):
'''
>>> is_anagram2('cat', 'tac')
True
>>> is_anagram2('cat', 'hat')
False
'''
return get_unicode_sum(word1) == get_unicode_sum(word2)
if __name__ == '__main__':

View File

@ -1,10 +0,0 @@
#!/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).
The O(1) lookup is sorting the query word and searching for the key.

View File

@ -17,17 +17,17 @@ Check whether any element of the array appears in the BST.
It takes O(nlog n) times two.
"""
def check_sum_hash_table(array, k):
from collections import defaultdict, Counter
def check_sum(array, k):
'''
>>> check_sum_hash_table([3, 2, 6, 7, 9, 1], 8)
>>> check_sum([3, 2, 6, 7, 9, 1], 8)
[(6, 2), (1, 7)]
>>> check_sum_hash_table([5, 2, 6, 7, 9, 1], 4)
>>> check_sum([5, 2, 6, 7, 9, 1], 4)
[]
>>>
'''
from collections import defaultdict
dict = defaultdict()
res = []
@ -40,6 +40,32 @@ def check_sum_hash_table(array, k):
return res
def check_sum2(array, k):
'''
>>> check_sum2([1, 4, 2, 7, 1, 3, 10, 15, 3, 1], 6)
set([(3, 3)])
>>> check_sum2([1, 4, 2, 7, 1, 3, 10, 15, 3, 1], 0)
set([])
'''
dict = Counter()
res = set()
for i in array:
dict[i] += 1
for i in array:
if dict[k-i] > 0:
if i == k-i and dict[k-i] > 1:
res.add((i, k-i))
dict[k-i] -= 2
elif i == k-i:
res.add((i, k-i))
dict[k-i] -= 1
return res
if __name__ == '__main__':
import doctest
doctest.testmod()

View File

@ -1,55 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
""" find whether two words are anagrams. Since sets do not count occurrence,
and sorting is O(nlogn) we will use hash tables. We scan the first string
and add all the character occurrences. Then we scan the second trying and
decrease all the character occurrences. If all the counts are zero, it is
an anagram"""
from collections import Counter
def verify_two_strings_are_anagrams(str1, str2):
ana_table = Counter()
for i in str1:
ana_table[i] += 1
for i in str2:
ana_table[i] -= 1
if len(set(ana_table.values())) < 2:
return True
else:
return False
''' verify if words are anagrams by comparing a sum of Unicode code
point of the character'''
def get_unicode_sum(word):
s = 0
for p in word:
s += ord(p)
return s
def find_anagram_get_unicode(word1, word2):
return get_unicode_sum(word1) == get_unicode_sum(word2)
if __name__ == '__main__':
str1 = 'marina'
str2 = 'aniram'
str3 = 'anfaam'
assert(verify_two_strings_are_anagrams(str1, str2) == True)
assert(verify_two_strings_are_anagrams(str1, str3) == False)
assert(find_anagram_get_unicode(str1, str2) == True)
assert(find_anagram_get_unicode(str1, str3) == False)

View File

@ -5,12 +5,38 @@ __author__ = "bt3"
def fib_generator():
a, b = 0, 1
while True:
yield b
a, b = b, a+b
def fib(n):
'''
>>> fib(2)
1
>>> fib(5)
5
>>> fib(7)
13
'''
if n < 3:
return 1
a, b = 0, 1
count = 1
while count < n:
count += 1
a, b = b, a+b
return b
if __name__ == '__main__':
import doctest
doctest.testmod()
fib = fib_generator()
print(next(fib))
print(next(fib))

View File

@ -1,44 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
'''
Given an unsorted array of numbers (that may contain repeated numbers),
* data structure that contains all the pairs w/sum equal to k.
* Do not include pairs that are the same numbers in a different order.
'''
from collections import Counter
def sum_pairs(array, k):
'''
>>> sum_pairs([1, 4, 2, 7, 1, 3, 10, 15, 3, 1], 6)
set([(3, 3)])
>>> sum_pairs([1, 4, 2, 7, 1, 3, 10, 15, 3, 1], 0)
set([])
'''
results = set()
dict = Counter()
for i in array:
dict[i] += 1
for i in array:
if dict[k-i] > 0:
if i == k-i and dict[k-i] > 1:
results.add((i, k-i))
dict[k-i] -= 2
elif i == k-i:
results.add((i, k-i))
dict[k-i] -= 1
return results
if __name__ == '__main__':
import doctest
doctest.testmod()

View File

@ -1,38 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
'''
Write a function to find the nth Fibonacci number.
Optimize your code so that the numbers
don't have to be recalculated on consecutive function call
'''
def fib(n):
'''
>>> fib(2)
1
>>> fib(5)
5
>>> fib(7)
13
'''
if n < 3:
return 1
a, b = 0, 1
count = 1
while count < n:
count += 1
a, b = b, a+b
return b
if __name__ == '__main__':
import doctest
doctest.testmod()

View File

@ -1,61 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
import math
import random
def finding_prime(number):
''' find whether a number is prime in a simple way'''
num = abs(number)
if num < 4 : return True
for x in range(2, num):
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) '''
num = abs(number)
if num < 4 : return True
for x in range(2, int(math.sqrt(num)) + 1):
if number % x == 0:
return False
return True
def finding_prime_fermat(number):
''' find whether a number is prime with Fermat's theorem, using probabilistic tests '''
if number <= 102:
for a in range(2, number):
if pow(a, number- 1, number) != 1:
return False
return True
else:
for i in range(100):
a = random.randint(2, number - 1)
if pow(a, number - 1, number) != 1:
return False
return True
def test_finding_prime():
number1 = 17
number2 = 20
assert(finding_prime(number1) == True)
assert(finding_prime(number2) == False)
assert(finding_prime_sqrt(number1) == True)
assert(finding_prime_sqrt(number2) == False)
assert(finding_prime_fermat(number1) == True)
assert(finding_prime_fermat(number2) == False)
print('Tests passed!')
if __name__ == '__main__':
test_finding_prime()

View File

View File

@ -1,29 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
''' Generate all permutations of an alphanumeric string '''
def permutations(word):
'''
>>> permutations('abc')
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
>>> permutations('')
''
'''
if len(word) < 2:
return word
res = []
for i in range(len(word)):
rest = word[:i] + word[i+1:]
for p in permutations(rest):
res.append(word[i] + p)
return res
if __name__ == '__main__':
import doctest
doctest.testmod()

View File

@ -4,9 +4,9 @@ __author__ = "bt3"
def invert_word(word):
def reversing_words(word):
"""
>>> invert_word('buffy is awesome')
>>> reversing_words('buffy is awesome')
'awesome is buffy'
"""
new_word = []
@ -17,6 +17,28 @@ def invert_word(word):
return " ".join(new_word)
def reversing_words2(s):
"""
>>> reversing_words2('buffy is awesome')
'awesome is buffy'
"""
words = s.split()
return ' '.join(reversed(words))
def reversing_words3(s):
"""
>>> reversing_words('buffy is awesome')
'awesome is buffy'
"""
words = s.split(' ')
words.reverse()
return ' '.join(words)
if __name__ == '__main__':
import doctest
doctest.testmod()

View File

@ -1,24 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
def reversing_words_setence_py(s):
words = s.split()
return ' '.join(reversed(words))
def reversing_words_setence_py2(s):
words = s.split(' ')
words.reverse()
return ' '.join(words)
if __name__ == '__main__':
s = "Buffy is a Vampire Slayer"
print reversing_words_setence_py(s)
print reversing_words_setence_py2(s)