Compare commits

..

No commits in common. "master" and "2" have entirely different histories.
master ... 2

486 changed files with 3808 additions and 30149 deletions

39
.gitignore vendored Normal file
View file

@ -0,0 +1,39 @@
*.py[cod]
*~
# C extensions
*.so
# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg
lib
lib64
# Installer logs
pip-log.txt
# Unit test / coverage reports
.coverage
.tox
nosetests.xml
# Translations
*.mo
# Mr Developer
.mr.developer.cfg
.project
.pydevproject
# PyCharm
.idea

Binary file not shown.

Before

Width:  |  Height:  |  Size: 665 KiB

View file

@ -1,41 +0,0 @@
#!/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])
def find_item(self, item):
pos = self.hash_key(item)
if item in self.table[pos]:
return True
else:
return False
if __name__ == '__main__':
dic = HashTable(5)
for i in range(1, 40, 2):
dic.add_item(i)
dic.print_table()
assert(dic.find_item(20) == False)
assert(dic.find_item(21) == True)

View file

@ -1,47 +0,0 @@
#!/usr/bin/env python
# Time: 5 min
__author__ = "bt3"
class Queue(object):
def __init__(self):
self.enq = []
self.deq = []
def enqueue(self, item):
return self.enq.append(item)
def deque(self):
if not self.deq:
while self.enq:
self.deq.append(self.enq.pop())
return self.deq.pop()
def peak(self):
if not self.deq:
while self.enq:
self.deq.append(self.enq.pop())
if self.deq:
return self.deq[-1]
def size(self):
return len(self.enq) + len(self.deq)
def isempty(self):
return not (self.enq + self.deq)
if __name__ == '__main__':
q = Queue()
for i in range(1,11):
q.enqueue(i)
print 'Size:', q.size()
print 'Is empty?', q.isempty()
print 'Peak: ', q.peak()
print
print 'Dequeuing...'
for i in range(10):
print q.deque()
print 'Size:', q.size()
print 'Is empty?', q.isempty()
print 'Peak: ', q.peak()

View file

@ -1,63 +0,0 @@
#!/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.'
def size(self):
return len(self.content)
def isEmpty(self):
return not bool(self.content)
def peek(self):
if self.content:
return self.content[-1]
else:
print('Stack is empty.')
def __repr__(self):
return '{}'.format(self.content)
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()

View file

@ -1,65 +0,0 @@
#!/usr/bin/env python
# copy of the class ../Stack.py
__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.'
def size(self):
return len(self.content)
def isEmpty(self):
return not bool(self.content)
def peek(self):
if self.content:
return self.content[-1]
else:
print('Stack is empty.')
def __repr__(self):
return '{}'.format(self.content)
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()

View file

@ -1,33 +0,0 @@
BIT-WISE
----------------------
1. To find a number:
11000101 is 2^0+2^2+2^6+2^7 = 197
2. Left shifting:
0010 1011 << 4 ---> 1011 000
3. Right shifting:
0010 1011 >> 4 ---> 0000 0010
or it can be filled with the copy of the first bit, instead of 0:
1011 0010 >> 4 ---> 1111 1011
4. XOR can cancels out:
15 ^ 12 ^ 15 = 12
5. 2^x:
left-shift 1 by x:
0000 0001 << x
so if x = 2, 2^2 = 4 -> 100
0000 0001 << 2 ---> 0000 0100
6. Is power of 2?
just do x&(x-1).
if 0 --> yes!

View file

@ -1,37 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
''' Clear a bit in a binary number.
Like the reverse of set bit:
1) first create a number filled of 1s,
with 0 at i (can create 0001000 and ~)
2) AND the number so it clears the ith bit
'''
def clear_bit(num, i):
mask = ~ (1 << i) # -0b10001
return bin(num & mask)
def clear_all_bits_from_i_to_0(num, i):
mask = ~ ( (1 << (i+1)) - 1)
return bin(num & mask)
def clear_all_bits_from_most_sig_to_1(num, i):
mask = ( 1 << i) -1
return bin(num & mask)
if __name__ == '__main__':
num = int('10010000', 2)
print clear_bit(num, 4) # '0b10000000'
num = int('10010011', 2)
print clear_all_bits_from_i_to_0(num, 2) # '0b10010000'
num = int('1110011', 2)
print clear_all_bits_from_most_sig_to_1(num, 2) #'0b11'

View file

@ -1,27 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
''' Get a bit in a binary number:
1) Shifts 1 over by i bits
2) make an AND with the number
3) all the other than the bit at i are clean, now compare to 0
4) if the new value is not 0, bit i is 1
'''
def get_bit(num, i):
mask = 1 << i
return num & mask != 0
if __name__ == '__main__':
num = int('0100100', 2)
get_bit(num, 0) # 0
get_bit(num, 1) # 0
get_bit(num, 2) # 1
get_bit(num, 3) # 0
get_bit(num, 4) # 0
get_bit(num, 5) # 1
get_bit(num, 6) # 0

View file

@ -1,26 +0,0 @@
#!/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
of the mask are zero so will not affect the num
'''
def set_bit(num, i):
mask = 1 << i
return bin( num | mask )
if __name__ == '__main__':
num = int('0100100', 2)
print set_bit(num, 0) #'0b100101'
print set_bit(num, 1) #'0b100110'
print set_bit(num, 2) # nothing change '0b100100'
print set_bit(num, 3) #'0b101100'
print set_bit(num, 4) #'0b110100'
print set_bit(num, 5) # nothing change '0b100100'

View file

@ -1,23 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
'''
swapping values in place without extra memory
'''
def swap_bit(a, b):
'''
>>> swap_bit(14, 73)
(73, 14)
'''
a = a^b
b = a^b
a = a^b
return a, b
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -1,51 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
from collections import Counter
def is_anagram(s1, s2):
'''
>>> is_anagram('cat', 'tac')
True
>>> is_anagram('cat', 'hat')
False
'''
counter = Counter()
for c in s1:
counter[c] += 1
for c in s2:
counter[c] -= 1
for i in counter.values():
if i:
return False
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__':
import doctest
doctest.testmod()

View file

@ -1,9 +0,0 @@
__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:
Weight 3 x 3 balls/coins.
If they weight the same: weight the 2 balls/coins left outside.
Else, measure 2 of the 3 heavier balls/coins.

View file

@ -1,40 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
'''
Given a N different open and close braces in a string "( { [ } ] )".
How do you check whether the string has matching braces.
'''
from collections import Counter
def check_if_balance(string):
'''
>>> check_if_balance('{[[(])}]')
True
>>> check_if_balance('{[[()}]')
False
>>> check_if_balance('')
True
'''
table = Counter()
for i in string:
index = str(ord(i))[0]
if i in '{[(':
table[index] += 1
elif i in ')}]':
table[index] -= 1
for i in table.values():
if i !=-0:
return False
return True
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -1,71 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
"""
Given an integer x and an unsorted array of integers, describe an
algorithm to determine whether two of the numbers add up to x.
1. Using hash tables.
2. Sorting the array and keeping two pointers in the array, one in
the beginning and one in the end. Whenever the sum of the current
two integers is less than x, move the first pointer forwards, and
whenever the sum is greater than x, move the second pointer
backwards. O(nln n).
3. Create a BST with x minus each element in the array.
Check whether any element of the array appears in the BST.
It takes O(nlog n) times two.
"""
from collections import defaultdict, Counter
def check_sum(array, k):
'''
>>> check_sum([3, 2, 6, 7, 9, 1], 8)
[(6, 2), (1, 7)]
>>> check_sum([5, 2, 6, 7, 9, 1], 4)
[]
>>>
'''
dict = defaultdict()
res = []
for i in array:
if k-i in dict:
res.append((i, k-i))
del dict[k-i]
else:
dict[i] = 1
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,36 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
''' Determine if an Array of integers contains 3 numbers that sum to 0 '''
from collections import defaultdict
def find_3_number(array):
'''
>>> find_3_number([1,5,56,11,-3,-12])
1 11 -12
True
>>> find_3_number([] )
False
'''
hash_ = defaultdict()
for i in array:
hash_[i] = 1
for i, x in enumerate(array):
for y in array[i+1:]:
if -(x+y) in hash_:
print x, y, -(x+y)
return True
return False
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -1,35 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
'''
given an array of intervals, return max number of non-overlapping intervals
'''
from collections import defaultdict
def non_overlapping(array):
'''
>>> non_overlapping([(1,2), (2,5), (1, 6)])
[[(1, 2), (2, 5)]]
>>> non_overlapping([(1,4), (2,5), (3, 6)])
[]
'''
total = []
for i, t in enumerate(array):
start = t[0]
end = t[1]
for tt in array[i+1:] :
if end <= tt[0]:
total.append([(start, end), (tt[0], tt[1])])
return total
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -1,64 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
''' convert an integer to a string in any base'''
def convert_from_dec_to_any_base(number, base):
'''
>>> number, base = 9, 2
>>> convert_from_dec_to_any_base(number, base)
'1001'
'''
convertString = '012345679ABCDEF'
if number < base:
return convertString[number]
else:
return convert_from_dec_to_any_base(number//base, base) + \
convertString[number%base]
def convert_from_decimal_to_binary(number, base):
'''
>>> number, base = 9, 2
>>> convert_from_decimal_to_binary(number, base)
1001
'''
multiplier, result = 1, 0
while number > 0:
result += number%base*multiplier
multiplier *= 10
number = number//base
return result
def convert_from_decimal_larger_bases(number, base):
'''
>>> number, base = 31, 16
>>> convert_from_decimal_larger_bases(number, base)
'1F'
'''
strings = "0123456789ABCDEFGHIJ"
result = ""
while number > 0:
digit = number%base
result = strings[digit] + result
number = number//base
return result
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -1,49 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
''' find and delete all the duplicate characters in a string '''
from collections import Counter
def delete_unique(str1):
'''
>>> delete_unique("Trust no one")
'on'
>>> delete_unique("Mulder?")
''
'''
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
def removing_duplicates_seq(str1):
'''
>>> delete_unique("Trust no one")
'on'
>>> delete_unique("Mulder?")
''
'''
seq = str1.split()
result = set()
for item in seq:
if item not in result:
#yield item
result.add(item)
return result
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -1,60 +0,0 @@
#!/usr/bin/env python
__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
def fib_rec(n):
'''
>>> fib_rec(2)
1
>>> fib_rec(5)
5
>>> fib_rec(7)
13
'''
if n < 3:
return 1
return fib_rec(n - 1) + fib_rec(n - 2)
if __name__ == '__main__':
import doctest
doctest.testmod()
fib = fib_generator()
print(next(fib))
print(next(fib))
print(next(fib))
print(next(fib))

View file

@ -1,32 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
'''
given 2 dice, determine number of ways to sum S if all dice are rolled
'''
from collections import Counter, defaultdict
def find_dice_probabilities(S=5, n_faces=6):
if S > 2*n_faces or S < 2:
return None
cdict = Counter()
ddict = defaultdict(list)
for dice1 in range(1, n_faces+1):
for dice2 in range(1, n_faces+1):
t = [dice1, dice2]
cdict[dice1+dice2] += 1
ddict[dice1+dice2].append( t)
return [cdict[S], ddict[S]]
if __name__ == '__main__':
results = find_dice_probabilities()
assert(results[0] == len(results[1]))

View file

@ -1,43 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
''' computes the edit distance between two strings '''
def find_edit_distance(str1, str2):
'''
>>> s = 'sunday'
>>> t = 'saturday'
>>> find_edit_distance(s, t)
3
'''
m = len(str1)
n = len(str2)
diff = lambda c1, c2: 0 if c1 == c2 else 1
E = [[0] * (n + 1) for i in range(m + 1)]
for i in range(m + 1):
E[i][0] = i
for j in range(1, n + 1):
E[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
E[i][j] = min(E[i-1][j] + 1, E[i][j-1] + 1, E[i-1][j-1] + diff(str1[i-1], str2[j-1]))
return E[m][n]
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -1,29 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
from collections import Counter
def find_non_rep_char(s1):
'''
>>> s1 = 'aabbcceff'
>>> find_non_rep_char(s1)
e
>>> find_non_rep_char('ccc')
'''
aux_dict = Counter()
for i in s1:
aux_dict[i] += 1
for k, v in aux_dict.items():
if v < 2:
print k
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -1,36 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
def find_substr(s1, s2):
if len(s1) < len(s2):
bs = s2
ss = s1
else:
bs = s1
ss = s2
ps = 0
for c in bs:
if ss[ps] == c:
ps += 1
else:
ps = 0
if ps == len(ss)-1:
return True
return False
if __name__ == '__main__':
s1 = 'buffy is a vampire slayer'
s2 = 'vampire'
s3 = 'angel'
assert(find_substr(s2, s1) == True)
assert(find_substr(s3, s1) == False)

View file

@ -1,32 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
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

@ -1,42 +0,0 @@
#!/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.
'''
def find_largest_sum(array):
'''
>>> find_largest_sum([-1, 2, -3, 5, 3, 1, -16, 7, 1, -13, 1])
9
>>> find_largest_sum([])
0
>>> find_largest_sum([1])
1
'''
sum_ = 0
sum_here = 0
for i in array:
sum_here += i
if sum_here < 0:
sum_here = 0
if sum_ < sum_here:
sum_ = sum_here
return sum_
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -1,34 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
''' find the longest continuous increasing subsequence'''
def find_long_con_inc(seq):
'''
>>> find_long_con_inc([1, -2, 3, 5, 1, -1, 4, -1, 6])
[-2, 3, 5]
>>> find_long_con_inc([1, 3, -2, 3, 5, 6])
[-2, 3, 5, 6]
>>> find_long_con_inc([1, 3, 4, -13, 2, 5, 8, -1, 2,-17])
[-13, 2, 5, 8]
'''
res, aux = [], []
seq.append(-float('infinity'))
for i, n in enumerate(seq[:-1]):
aux.append(n)
if n > seq[i+1]:
if len(res) < len(aux):
res = aux[:]
aux = []
return res
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -1,38 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
'''
given a string, find longest string with unique characters
'''
def find_longest(string):
'''
>>> find_longest('abfgrhgtrdsandwejfhdasjcbdsjvrejwghireeej')
'wejfhdas'
>>> find_longest('abcabcabcabcdefabcccc')
'defabc'
'''
maxs = ''
result = ''
for c in string:
if c in result:
if len(maxs) < len(result):
maxs = result
result = ''
else:
result += c
if result and len(maxs) < len(result):
maxs = result
return maxs
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -1,33 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
from collections import defaultdict
def find_unique_number(array):
'''
>>> find_unique_number([1, 3, 6, 1, 5, 6, 9, 3, 7])
[1, 6, 3]
>>> find_unique_number([1, 3, 5, 6, 9, 7])
[]
'''
table = defaultdict()
total = []
for i in array:
if i in table:
total.append(i)
else:
table[i] = 1
return total
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -1,42 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
'''Given an array of numbers, replace each number with the product of all
the numbers in the array except the number itself *without* using division
'''
def find_product_without_division(seq):
'''
>>> seq = [2,3,4]
>>> find_product_without_division(seq)
[12, 8, 6]
'''
forw = []
bacw = []
for i in range(len(seq)):
prod_f, prod_b = 1, 1
for next in range(i+1, len(seq)):
prod_f *= seq[next]
for before in range(0, i):
prod_b *= seq[before]
forw.append(prod_f)
bacw.append(prod_b)
for i in range(len(seq)):
seq[i] = forw[i] * bacw[i]
return seq
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -1,56 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
"""
Two numbers out of n numbers from 1 to n are missing.
The remaining n-2 numbers are in the array but not sorted.
Find the missing numbers The sum1 is the sum of all the elements in n.
The sum2 is the sum of all the elements in n-2. sum1 - sum2 = num1 + num2 = s.
The prod1 is the prod of all the elements in n. The prod2 is the prod of all
the elements in n-2. prod1/prod2 = num1*num2 =p.
Runtime is O(n), because it scan 3 times. Space is O(1)
In case of finding one integer, Let the missing number be M. We know that
the sum of first N natural numbers is N*(N+1)/2. Traverse through the array
once and calculate the sum. This is the sum of first N natural numbers -
M or S=N*(N+1)/2 - M. Therefore M = N*(N+1)/2 - S.
"""
import math
def find_two_missing_numbers(l1):
'''
>>> l1 = [1, 3, 5]
>>> find_two_missing_numbers(l1)
(4, 2)
'''
n_min_2 = len(l1)
n = n_min_2 + 2
sum1, sum2, prod1, prod2 = 0, 0, 1, 1
sum2 = sum(l1[:])
sum1 = sum(range(1,n+1))
s = sum1 - sum2
for i in range(1, n-1):
prod1 = prod1*i
prod2 = prod2*l1[i-1]
prod1 = prod1*n*(n-1)
p = prod1/prod2
num1 = (s + math.sqrt(s*s - 4*p))/2
num2 = (s - math.sqrt(s*s - 4*p))/2
return int(num1), int(num2)
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -1,29 +0,0 @@
#!/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 exit most 32 chars, print error:
'''
def get_float_rep(num):
if num >= 1 or num <= 0: return 'Error 1'
result = '.'
while num:
if len(result) >= 32: return 'Error 2', result
r = num*2
if r >= 1:
result += '1'
num = r - 1
else:
result += '0'
num = r
return result
if __name__ == '__main__':
print get_float_rep(0.72) #('Error 2', '.1011100001010001111010111000010')
print get_float_rep(0.1) # ('Error 2', '.0001100110011001100110011001100')
print get_float_rep(0.5) #'.1'

View file

@ -1,63 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
def intersection_two_arrays_sets(seq1, seq2):
'''
>>> intersection_two_arrays_sets([1,2,3,5,7,8], [3,5,6])
set([3, 5])
>>> intersection_two_arrays_sets([1,2,7,8], [3,5,6])
set([])
'''
# O(n)
set1 = set(seq1)
set2 = set(seq2)
return set1.intersection(set2) #same as list(set1 & set2)
def intersection_two_arrays_On2(seq1, seq2):
'''
>>> intersection_two_arrays_On2([1,2,3,5,7,8], [3,5,6])
[3, 5]
>>> intersection_two_arrays_On2([1,2,7,8], [3,5,6])
[]
'''
final = []
for i in seq1:
for j in seq2:
if i == j:
final.append(i)
return final
def intersection_two_arrays_On(seq1, seq2):
'''
>>> intersection_two_arrays_On([1,2,3,5,7,8], [3,5,6])
[5, 3]
>>> intersection_two_arrays_On([1,2,7,8], [3,5,6])
[]
'''
final = []
while seq1 and seq2:
if seq1[-1] == seq2[-1]:
final.append(seq1.pop())
seq2.pop()
elif seq1[-1] > seq2[-1]:
seq1.pop()
else:
seq2.pop()
return final
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -1,54 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
def beating_stock(array):
imin = 0
# first deal is just buying in the next day (1)
deal = [array[1] - array[imin], imin, 1]
for i, d in enumerate(array):
deal_here = d - array[imin]
if deal_here > deal[0]:
deal = [deal_here, imin, i]
elif d < array[imin]:
imin = i
return deal[0], array[deal[1]], array[deal[2]]
def beating_stock2(array):
deal = 0
min_value = array[0]
for i, d in enumerate(array):
deal_here = d - min_value
if deal_here > deal:
deal = deal_here
else:
if min_value > array[i]:
min_value = array[i]
return deal
if __name__ == '__main__':
array = [7, 2, 3, 6, 5, 8, 5, 3, 4]
deal = beating_stock(array)
print("Profit: %d, buying at %d, selling at %d." %(deal[0], deal[1], deal[2]))
deal = beating_stock2(array)
print "Profit: " + str(deal)

View file

@ -1,15 +0,0 @@
#!/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.
There are more 5 than 2s so you can count the fives.
there is 100/5 = 20, so 20 5s. However, there are two 5s in 25, 50, 75 and 100.
result: 20+4 = 24

View file

@ -1,33 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
from collections import defaultdict
def is_palindrome(array):
'''
>>> is_palindrome('subi no onibus')
True
>>> is_palindrome('helllo there')
False
>>> is_palindrome('h')
True
>>> is_palindrome('')
True
'''
array = array.strip(' ')
if len(array) < 2:
return True
if array[0] == array[-1]:
return is_palindrome(array[1:-1])
else:
return False
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

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

View file

@ -1,37 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
''' Write code to generate all possible case permutations of a given
lower-cased string
'''
def alpha_permutation(string):
'''
>>> alpha_permutation('0ab')
['0Ab', '0Ab', '0ab', '0ab', '0Ba', '0Ba', '0ba', '0ba', 'ab0', 'a0b', 'a0b', 'b0a', 'b0a', 'ba0']
>>> alpha_permutation('')
''
'''
if len(string) < 2:
return string
result = []
for i, c in enumerate(string):
rest = string[i+1:] + string[:i]
for cc in alpha_permutation(rest):
if cc.isalpha():
result.append(c.upper() + cc)
result.append(c + cc)
return result
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -1,47 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
'''
find prime factors of a number.
'''
import math
import random
def find_prime_factors(n):
'''
>>> find_prime_factors(14)
[2, 7]
>>> find_prime_factors(19)
[]
'''
divisors = [d for d in range(2, n//2 + 1) if n % d == 0]
primes = [d for d in divisors if is_prime(d)]
return primes
def is_prime(n):
for j in range(2, int(math.sqrt(n))):
if (n % j) == 0:
return False
return True
''' return a n-bit prime '''
def generate_prime(number=3):
while 1:
p = random.randint(pow(2, number-2), pow(2, number-1)-1)
p = 2 * p + 1
if find_prime_factors(p):
return p
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

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

@ -1,34 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
from collections import Counter
def check_if_ransom_note(magazines, note):
count = Counter()
pm, pn = 0, 0
while pn < len(note) and pm < len(magazines):
char_note = note[pn]
if count[char_note]>0:
count[char_note] -= 1
pn += 1
else:
char_magazine = magazines[pm]
count[char_magazine] += 1
pm +=1
return pn == len(note)
if __name__ == '__main__':
magazines1 = "avfegthhgrebvkdsvnijnvyijfdmckdsmovkmmfvskumvl;cdkmioswckofjbkreenyukjemjgnmkmvkmnvdkmvkr g gmvdvmldm vldfkmbldkmlvdkm"
magazines2 = "adfsfa"
note = "you should disobey"
print(check_if_ransom_note(magazines1, note))
print(check_if_ransom_note(magazines2, note))

View file

@ -1,37 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
def revert(string):
'''
>>> s = 'hello'
>>> revert(s)
'olleh'
>>> revert('')
''
'''
return string[::-1]
def reverse_string_inplace(s):
'''
>>> s = 'hello'
>>> reverse_string_inplace(s)
'olleh'
>>> reverse_string_inplace('')
''
'''
if s:
s = s[-1] + reverse_string_inplace(s[:-1])
return s
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -1,45 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
def reversing_words(word):
"""
>>> reversing_words('buffy is awesome')
'awesome is buffy'
"""
new_word = []
words = word.split(' ')
for word in words[::-1]:
new_word.append(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,41 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
'''
find the sum of two integers represented as strings,
return the sum as string, i.e "123" and "456" would return "579"
'''
def get_number(s):
count = 1
num = 0
p = len(s) -1
while p >= 0:
num = num + int(s[p])*count
count *= 10
p -= 1
return num
def sum_string(s1, s2):
'''
>>> sum_string('10', '5')
'15'
>>> sum_string('0', '1')
'1'
>>> sum_string('123', '456')
'579'
'''
n1 = get_number(s1)
n2 = get_number(s2)
return str(n2 + n1)
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

@ -1,15 +0,0 @@
#!/usr/bin/python
__author__ = "bt3"
import collections
import sys
def count_unique_word_freq():
return collections.Counter(\
sys.stdin.read().lower().split()).most_common(n)
if __name__ == '__main__':
count_unique_word_freq()

View file

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

View file

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

View file

@ -1,19 +0,0 @@
#!/bin/python
#
# An example of Python Decorator
#
def pretty_sumab(func):
def inner(a,b):
print(str(a) + " + " + str(b) + " is ", end="")
return func(a,b)
return inner
@pretty_sumab
def sumab(a,b):
summed = a + b
print(summed)
if __name__ == "__main__":
sumab(5,3)

View file

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

View file

@ -1,15 +0,0 @@
#!/usr/bin/python
__author__ = "bt3"
'''
The doctest module automatically runs any statement beginning with >>>
and compares the following line with the output from the interpreter.
>>> 1 == 1
False
'''
if __name__ == '__main__':
import doctest
doctest.testmod()

View file

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

View file

@ -1,7 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
test = lambda x: x**2
print test(3)

View file

@ -1,21 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
import logging
LOG_FILENAME = 'logging_example.out'
logging.basicConfig(filename=LOG_FILENAME,
level=logging.DEBUG,
)
logging.debug('This message should go to the log file')
f = open(LOG_FILENAME, 'rt')
try:
body = f.read()
finally:
f.close()
print 'FILE:'
print body

View file

@ -1,18 +0,0 @@
#!/usr/bin/env python3
__author__ = "bt3"
from functools import lru_cache
@lru_cache(maxsize=20)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
if __name__ == '__main__':
print([fib(n) for n in range(10)])
print(fib.cache_info())

View file

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

View file

@ -1,13 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
import Queue
q = Queue.Queue()
for i in range(10):
q.put(i)
for i in range(10):
print q.get(i)

View file

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

@ -1,11 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
foo = 'foo'
bar = 'bar'
print '%s%s' % (foo, bar) # It is OK
print '{0}{1}'.format(foo, bar) # It is better
print '{foo}{bar}'.format(foo=foo, bar=bar) # It is best

View file

@ -1,8 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
import subprocess,os
os.system('ls')
subprocess.call(['ls', '-1'], shell=True)

View file

@ -1,22 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
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

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

View file

@ -1,16 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
import threading
def worker(num):
"""thread worker function"""
print 'Worker: %s' % num
return
threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()

View file

@ -1,41 +0,0 @@
#!/bin/python
import math
import os
import random
import re
import sys
# Complete the 'largestRepackaged' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts INTEGER_ARRAY arrivingPackets as parameter.
#
def largestRepackaged(arrivingPackets):
packet_size = arrivingPackets[0]
packets = arrivingPackets[1:]
largest_packet = 0
remaining = 0
for packet in packets:
print packet
if remaining:
packet += remaining
remaining = 0
if packet % 2 != 0:
remaining = packet % 2
packet -= remaining
if packet > largest_packet:
largest_packet = packet
return largest_packet
if __name__ == '__main__':
arrivingPackets= [5, 1, 2, 4, 7, 5]
print(largestRepackaged(arrivingPackets))

View file

@ -1,22 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
def balance_par_str_with_stack(str1):
i, stack = 0, []
while i < len(str1):
symbol = str1[i]
if symbol == "(":
stack.append(symbol)
elif symbol == ")":
stack.pop()
i += 1
return not stack
if __name__ == '__main__':
print(balance_par_str_with_stack('((()))'))
print(balance_par_str_with_stack('(()'))

View file

@ -1,50 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
def binary_search(array, value):
last, first = len(array), 0
while first < last:
mid = (last - first)//2
item = array[mid]
if item == value:
return True
elif item < value:
last = mid
else:
first = mid
return False
def binary_search_rec(array, value, first=0, last=None):
last = last or len(array)
if len(array[first:last]) < 1:
return False
mid = (last - first)//2
if array[mid] == value:
return True
elif array[mid] < value:
return binary_search_rec(array, value, first=first, last=mid)
else:
return binary_search_rec(array, value, first=mid, last=last)
if __name__ == '__main__':
array = [3, 4, 6, 7, 10, 11, 34, 67, 84]
value = 6
assert(binary_search(array, value) == True)
assert(binary_search_rec(array, value) == True)
value = 8
assert(binary_search(array, value) == False)
assert(binary_search_rec(array, value) == False)
array = [8]
assert(binary_search(array, value) == True)
assert(binary_search_rec(array, value) == True)
array = []
assert(binary_search(array, value) == False)
assert(binary_search_rec(array, value) == False)

View file

@ -1,165 +0,0 @@
#!/usr/bin/python
__author__ = "bt3"
from collections import deque
class Node(object):
def __init__(self, item=None):
self.item = item
self.left = None
self.right = None
def _add(self, value):
new_node = Node(value)
if not self.item:
self.item = new_node
else:
if value > self.item:
self.right = self.right and self.right._add(value) or new_node
elif value < self.item:
self.left = self.left and self.left._add(value) or new_node
else:
print("BSTs do not support repeated items.")
return self
def _search(self, value):
if self.item == value:
return True
elif self.left and value < self.item:
return self.left._search(value)
elif self.right and value > self.item:
return self.right._search(value)
else:
return False
def _isLeaf(self):
return not self.right and not self.left
def _printPreorder(self):
print self.item
if self.left:
self.left._printPreorder()
if self.right:
self.right._printPreorder()
def _preorder_array(self):
nodes = []
if self.item:
nodes.append(self.item)
if self.left:
nodes.extend(self.left._preorder_array())
if self.right:
nodes.extend(self.right._preorder_array())
return nodes
class BST(object):
def __init__(self):
self.root = None
def add(self, value):
if not self.root:
self.root = Node(value)
else:
self.root._add(value)
def printPreorder(self):
if self.root:
self.root._printPreorder()
def search(self, value):
if self.root:
return self.root._search(value)
def preorder_array(self):
if self.root:
return self.root._preorder_array()
else:
return 'Tree is empty.'
def BFT(tree):
current = tree.root
nodes = []
queue = deque()
queue.append(current)
while queue:
current = queue.popleft()
nodes.append(current.item)
if current.left:
queue.append(current.left)
if current.right:
queue.append(current.right)
return nodes
def preorder(tree, nodes=None):
nodes = nodes or []
if tree:
nodes.append(tree.item)
if tree.left:
preorder(tree.left, nodes)
if tree.right:
preorder(tree.right, nodes)
return nodes
def postorder(tree, nodes=None):
nodes = nodes or []
if tree:
if tree.left:
nodes = postorder(tree.left, nodes)
if tree.right:
nodes = postorder(tree.right, nodes)
nodes.append(tree.item)
return nodes
def inorder(tree, nodes=None):
nodes = nodes or []
if tree:
if tree.left:
nodes = inorder(tree.left, nodes)
nodes.append(tree.item)
if tree.right:
nodes = inorder(tree.right, nodes)
return nodes
if __name__ == '__main__':
bst = BST()
l = [10, 5, 6, 3, 8, 2, 1, 11, 9, 4]
for i in l:
bst.add(i)
print
print "Searching for nodes 16 and 6:"
print bst.search(16)
print bst.search(6)
print
print 'Traversals:'
print 'Original: ', l
print 'Preorder: ', preorder(bst.root)
print 'Postorder: ', postorder(bst.root)
print 'Inorder: ', inorder(bst.root)
print 'BSF: ', BFT(bst)

View file

@ -1,38 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
from collections import Counter
def check_if_anagram(word1, word2):
counter = Counter()
for c in word1:
counter[c] += 1
for c in word2:
counter[c] -= 1
for values in counter.values():
if values != 0:
return False
return True
if __name__ == '__main__':
word1 = 'abc'
word2 = 'bca'
assert(check_if_anagram(word1, word2) == True)
word2 = 'bcd'
assert(check_if_anagram(word1, word2) == False)
word1 = ''
word2 = ''
assert(check_if_anagram(word1, word2) == True)
word1 = 'a'
word2 = 'a'
assert(check_if_anagram(word1, word2) == True)

View file

@ -1,32 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
def combination(array):
if len(array) < 2:
return set(array)
result = set()
for index, item in enumerate(array):
new_array = array[:index] + array[index+1:]
result.add(item)
for perm in combination(new_array):
new_item = ''.join(sorted(item + perm))
result.add(new_item)
return result
if __name__ == '__main__':
array = ['a', 'b', 'c']
result = set(['a', 'ac', 'ab', 'abc', 'bc', 'c', 'b'])
assert(combination(array) == result)
array = ['']
result = set([''])
assert(combination(array) == result)
array = ['a']
result = set(['a'])
assert(combination(array) == result)

View file

@ -1,45 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
class HashTable(object):
def __init__(self, slots=10):
self.slots = slots
self.table = []
self.create_table()
# Get the slot
def hash_key(self, value):
return hash(value)%self.slots
# When creating the table, add list struct
# to each slot
def create_table(self):
for i in range(self.slots):
self.table.append([])
# Method to add a item in the right slot
def add_item(self, value):
key = self.hash_key(value)
self.table[key].append(value)
# Aux: print table
def print_table(self):
for key in range(self.slots):
print "Key is {0}, value is {1}.".format(key, self.table[key])
# Aux: find item
def find_item(self, item):
item_hash = self.hash_key(item)
return item in self.table[item_hash]
if __name__ == '__main__':
dic = HashTable(5)
for i in range(1, 40, 2):
dic.add_item(i)
dic.print_table()
assert(dic.find_item(20) == False)
assert(dic.find_item(21) == True)

View file

@ -1,60 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
class Node(object):
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedList(object):
def __init__(self):
self.head = None
def _add(self, value):
self.head = Node(value, self.head)
def _printList(self):
node = self.head
while node:
print node.value
node = node.next
def _find(self, index):
prev = None
node = self.head
i = 0
while node and i < index:
prev = node
node = node.next
i += 1
return node, prev, i
def _delete(self, prev, node):
if not prev:
self.head = node.next
else:
prev.next = node.next
def deleteNode(self, index):
node, prev, i = self._find(index)
if index == i:
self._delete(prev, node)
else:
print('Node with index {} not found'.format(index))
if __name__ == '__main__':
ll = LinkedList()
for i in range(1, 5):
ll._add(i)
print('The list is:')
ll._printList()
print('The list after deleting node with index 2:')
ll.deleteNode(2)
ll._printList()

View file

@ -1,32 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
def longest_common_substring(s1, s2):
p1 = 0
aux, lcp = '', ''
string1 = max(s1, s2)
string2 = min(s1, s2)
while p1 < len(string1):
p2 = 0
while p2 < len(string2) and p1+p2 < len(string1):
if string1[p1+p2] == string2[p2]:
aux += string1[p1+p2]
else:
if len(lcp) < len(aux):
lcp = aux
aux = ''
p2 += 1
p1 += 1
return lcp
if __name__ == '__main__':
str1 = 'hasfgeaae'
str2 = 'bafgekk'
result = 'fge'
assert(longest_common_substring(str1, str2) == result)

View file

@ -1,31 +0,0 @@
#!/usr/bin/env python
__author__ = "bt3"
def longest_increasing_subsequence(seq):
result, aux = [], []
seq.append(-float('infinity'))
for i, value in enumerate(seq[:-1]):
aux.append(value)
if value > seq[i+1]:
if len(result) < len(aux):
result = aux[:]
aux = []
return result
if __name__ == '__main__':
seq = [10, -12, 2, 3, -3, 5, -1, 2, -10]
result = [-12, 2, 3]
assert(longest_increasing_subsequence(seq) == result)
seq = [2]
result = [2]
assert(longest_increasing_subsequence(seq) == result)
seq = []
result = []
assert(longest_increasing_subsequence(seq) == result)

View file

@ -1,47 +0,0 @@
#!/usr/bin/env python
# AKA: do you believe in magic?
__author__ = "bt3"
def merge_sort(array):
if len(array) < 2:
return array
# divide
mid = len(array)//2
left = merge_sort(array[:mid])
right = merge_sort(array[mid:])
# merge
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j+= 1
# make sure nothing is left behind
if left[i:]:
result.extend(left[i:])
if right[j:]:
result.extend(right[j:])
return result
if __name__ == '__main__':
array = [3, 1, 6, 0, 7, 19, 7, 2, 22]
sorted = [0, 1, 2, 3, 6, 7, 7, 19, 22]
assert(merge_sort(array) == sorted)
array = []
assert(merge_sort(array) == array)
array = [1]
assert(merge_sort(array) == array)

View file

@ -1,281 +0,0 @@
## Python General Questions & Answers
Python is a programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source.
#### What is PEP 8?
PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable.
#### What is pickling and unpickling?
Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using a dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
#### How Python is interpreted?
Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.
#### How memory is managed in Python?
Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap and interpreter takes care of this Python private heap.
The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code.
Python also has an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.
#### What are the tools that help to find bugs or perform static analysis?
PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.
#### What are Python decorators?
A Python decorator is a specific change that we make in Python syntax to alter functions easily.
#### What is the difference between list and tuple?
The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries.
#### How are arguments passed by value or by reference?
Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result, you cannot change the value of the references. However, you can change the objects if it is mutable.
#### What are the built-in type does python provides?
There are mutable and Immutable types of Pythons built-in types Mutable built-in types
List
Sets
Dictionaries
Immutable built-in types
Strings
Tuples
Numbers
#### What is namespace in Python?
In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get the corresponding object.
#### What is lambda in Python?
It is a single expression anonymous function often used as an inline function.
#### Why lambda forms in python do not have statements?
A lambda form in python does not have statements as it is used to make new function object and then return them at runtime.
#### What is pass in Python?
Pass means, no-operation Python statement, or in other words, it is a place holder in a compound statement, where there should be a blank left and nothing has to be written there.
#### In Python what are iterators?
In Python, iterators are used to iterate a group of elements, containers like list.
#### What is unittest in Python?
A unit testing framework in Python is known as unittest. It supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections, etc.
#### In Python what is slicing?
A mechanism to select a range of items from sequence types like list, tuple, strings, etc. is known as slicing.
#### What are generators in Python?
The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function.
#### What is docstring in Python?
A Python documentation string is known as docstring, it is a way of documenting Python functions, modules and classes.
#### How can you copy an object in Python?
To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general case. You cannot copy all objects but most of them.
#### What is the difference between deep and shallow copy?
Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Whereas, a deep copy is used to store the values that are already copied.
#### What is a negative index in Python?
Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth.
#### How you can convert a number to a string?
In order to convert a number into a string, use the inbuilt function str(). If you want a octal or hexadecimal representation, use the inbuilt function oct() or hex().
#### What is the difference between Xrange and range?
Xrange returns the xrange object while range returns the list, and uses the same memory no matter what the range size is.
#### What is module and package in Python?
In Python, a module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes.
The folder of Python program is a package of modules. A package can have modules or subfolders.
#### What are the rules for local and global variables in Python?
Local variables: If a variable is assigned a new value anywhere within the function's body, it's assumed to be local.
Global variables: Those variables that are only referenced inside a function are implicitly global.
#### How can you share global variables across modules?
To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.
#### Explain how can you make a Python Script executable on Unix?
To make a Python Script executable on Unix, you need to do two things,
Script file's mode must be executable and
the first line must begin with # (`#!/usr/local/bin/python`).
#### Explain how to delete a file in Python?
By using a command `os.remove (filename)` or `os.unlink(filename)`.
#### Explain how can you generate random numbers in Python?
To generate random numbers in Python, you need to import command as
```
import random
random.random()
```
This returns a random floating point number in the range [0,1)
#### Explain how can you access a module written in Python from C?
You can access a module written in Python from C by following method,
```
Module = =PyImport_ImportModule("<modulename>");
```
#### Mention the use of // operator in Python?
It is a Floor Division operator, which is used for dividing two operands with the result as quotient showing only digits before the decimal point. For instance, `10//5 = 2 and 10.0//5.0 = 2.0`.
#### Explain what is Flask & its benefits?
Flask is a web microframework for Python based on "Werkzeug, Jinja 2 and good intentions" BSD licensed. Werkzeug and jingja are two of its dependencies.
Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries. It makes the framework light while there is a little dependency to update and fewer security bugs.
#### What is the difference between Django, Pyramid, and Flask?
Flask is a "microframework" primarily build for a small application with simpler requirements. In Flask, you have to use external libraries. Flask is ready to use.
Pyramid is built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.
Like Pyramid, Django can also be used for larger applications. It includes an ORM.
#### Explain how you can access sessions in Flask?
A session basically allows you to remember information from one request to another. In a flask, it uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.
#### Is Flask an MVC model and if yes give an example showing MVC pattern for your application?
Basically, Flask is a minimalistic framework which behaves the same as MVC framework. So MVC is a perfect fit for Flask, and the pattern for MVC we will consider for the following example:
```python
from flask import Flask
app = Flask(_name_)
@app.route("/")
Def hello():
return "Hello World"
app.run(debug = True)
```
#### Explain database connection in Python Flask?
Flask supports database powered application (RDBS). Such a system requires creating a schema, which requires piping the shema.sql file into a sqlite3 command. So you need to install sqlite3 command in order to create or initiate the database in Flask.
Flask allows requesting database in three ways
* before_request() : They are called before a request and pass no arguments.
* after_request() : They are called after a request and pass the response that will be sent to the client.
* teardown_request(): They are called in a situation when an exception is raised, and response is not guaranteed. They are called after the response been constructed. They are not allowed to modify the request, and their values are ignored.
#### You are having multiple Memcache servers running Python, in which one of the Memcache server fails, and it has your data, will it ever try to get key data from that one failed server?
The data in the failed server won't get removed, but there is a provision for auto-failure, which you can configure for multiple nodes. Fail-over can be triggered during any kind of socket or Memcached server level errors and not during normal client errors like adding an existing key, etc.
#### Explain how you can minimize the Memcached server outages in your Python Development?
When one instance fails, several of them goes down, this will put a larger load on the database server when lost data is reloaded as the client make a request. To avoid this, if your code has been written to minimize cache stampedes then it will leave a minimal impact.
Another way is to bring up an instance of Memcached on a new machine using the lost machines IP address.
#### Explain how Memcached should not be used in your Python project?
Memcached common misuse is to use it as a data store, and not as a cache. Never use Memcached as the only source of the information you need to run your application. Data should always be available through another source as well. Memcached is just a key or value store and cannot perform query over the data or iterate over the contents to extract information. Memcached does not offer any form of security either in encryption or authentication.
#### What's a metaclass in Python?
This type of class holds the instructions about the behind-the-scenes code generation that you want to take place when another piece of code is being executed. With a metaclass, we can define properties that should be added to new classes that are defined in our code.
#### Why isn't all memory freed when Python exits?
Objects referenced from the global namespaces of Python modules are not always deallocated when Python exits. This may happen if there are circular references. There are also certain bits of memory that are allocated by the C library that are impossible to free/ Python is, however, aggressive about cleaning up memory on exit and does try to destroy every single object.
If you want to force Python to delete certain things on deallocation, you can use the atexit module to register one or more exit functions to handle those deletions.
#### Usage of `__slots__`?
The special attribute `__slots__` allows you to explicitly state which instance attributes you expect your object instances to have, with the expected results:
* faster attribute access.
* space savings in memory.
#### What id() function in Python is for?
`id()` function accepts a single parameter and is used to return the identity of an object. This identity has to be unique and constant for this object during the lifetime. Two objects with non-overlapping lifetimes may have the same `id()` value.
#### Is Python call-by-value or call-by-reference?
Neither. In Python, (almost) everything is an object. What we commonly refer to as "variables" in Python are more properly called names. Likewise, "assignment" is really the binding of a name to an object. Each binding has a scope that defines its visibility, usually the block in which the name originates.
In Python a variable is not an alias for a location in memory. Rather, it is simply binding to a Python object.ext post.
----

View file

@ -1,44 +0,0 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.cache
nosetests.xml
coverage.xml
# Translations
*.mo
*.pot
# Django stuff:
*.log
# Sphinx documentation
docs/_build/

View file

@ -1,22 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def mul3and5(n):
result = 0
for num in range(1, n):
if num%3 == 0 or num%5 == 0:
result += num
return result
def test_():
assert(mul3and5(10) == 23)
print(mul3and5(1000))
print('Tests Passed!')
if __name__ == '__main__':
test_()

View file

@ -1,18 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def even_fib_num(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
def main():
print(sum(n for n in even_fib_num(4e6) if not (n & 1)))
print('Tests Passed!')
if __name__ == '__main__':
main()

View file

@ -1,41 +0,0 @@
#!/usr/bin/python3
#!/usr/bin/python3
def is_prime(n):
if n < 4 : return True
for i in range(2, int(n**0.5 + 1)):
if not n%i: return False
return True
def largest_prime_factor(n):
i = int(n**0.5 +1)
while i > 1 :
if not n%i and i&1:
if is_prime(i): return i
i -= 1
return None
def largest_prime_factor_optimized(n):
factor = 2
lastfactor = 1
while n > 1:
if not n%factor:
lastfactor = factor
n = n//factor
while n%factor == 0:
n = n//factor
factor += 1
return lastfactor
def test_largest_prime_factor():
assert(largest_prime_factor(13195)== 29)
print(largest_prime_factor(600851475143))
assert(largest_prime_factor_optimized(13195) == 29)
print(largest_prime_factor_optimized(600851475143))
print('Tests Passed!')
if __name__ == '__main__':
test_largest_prime_factor()

View file

@ -1,47 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def is_palindrome(s):
return s == reverse(s)
def reverse(s):
rev = 0
while s > 0:
rev = 10*rev + s%10
s = s//10
return rev
def is_palindrome_2(s):
# to use it you need to cast str() first
while s:
if s[0] != s[-1]: return False
else:
s = s[1:-1]
is_palindrome(s)
return True
def larg_palind_product(n):
nmax, largpal = 9, 0
for i in range(1, n):
nmax += 9*10**i
for i in range(nmax, nmax//2, -1):
for j in range(i -1, (i -1)//2, -1):
candidate = i*j
if is_palindrome(candidate) and candidate > largpal:
largpal = candidate
return largpal
def test_larg_palind_product():
assert(larg_palind_product(2)== 9009)
print(larg_palind_product(3))
print('Tests Passed!')
if __name__ == '__main__':
test_larg_palind_product()

View file

@ -1,32 +0,0 @@
#!/usr/bin/python3
def smallest_multiple(n):
set1 = set([x for x in range(1, n+1)])
set2 = set()
for i in range(len(set1), 0, -1):
for j in range(1, i):
if i%j == 0:
set2.add(j)
set1 = set1 - set2
res_num = n*n
while True:
for i in set1:
missing_div = False
if res_num%i:
missing_div = True
shift = res_num%i
break
if not missing_div: return res_num
res_num += 1 or shift
shift = 0
def test_():
assert(smallest_multiple(10) == 2520)
print(smallest_multiple(20))
print('Tests Passed!')
if __name__ == '__main__':
test_()

View file

@ -1,21 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def sum_square_diff(n):
sq_sum, sum_sq = 0, 0
for i in range(1, n+1):
sum_sq += i**2
sq_sum += i
sq_sum = sq_sum **2
return sq_sum - sum_sq
def main():
assert(sum_square_diff(10) == 2640)
print(sum_square_diff(100))
print('Tests Passed!')
if __name__ == '__main__':
main()

View file

@ -1,32 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
import math
def is_prime(number, prime_set):
if number in prime_set: return True
for i in range(2, int(math.sqrt(number)) + 1):
if not number%i: return False
return True
def findstprime(n):
count = 0
candidate = 1
prime_set = set()
while count < n:
candidate +=1
if is_prime(candidate, prime_set):
prime_set.add(candidate)
count += 1
return candidate
def main():
assert(findstprime(6 == 13))
print(findstprime(10001))
print('Tests Passed!')
if __name__ == '__main__':
main()

View file

@ -1,28 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def largest_prod_seq(n):
result = 0
for i in range(0, len(n)-4):
first = int(n[i])
second = int(n[i+1])
third = int(n[i+2])
fourth = int(n[i+3])
fifth = int(n[i+4])
result_here = first*second*third*fourth*fifth
if result < result_here:
result = result_here
return result
def main():
n = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'
print(largest_prod_seq(n))
print('Tests Passed!')
if __name__ == '__main__':
main()

View file

@ -1,26 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def special_pyt(n):
for i in range(3, n):
for j in range(i+1, n):
c = calc_c(i,j)
if i + j + c == n:
return i*j*c
def calc_c(a, b):
return (a**2 + b**2)**0.5
def main():
assert(special_pyt(3+4+5) == (3*4*5))
print(special_pyt(1000))
print('Tests Passed!')
if __name__ == '__main__':
main()

View file

@ -1,24 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
from findstprime import is_prime
def summation_primes(n):
candidate = 2
prime_set = set()
while candidate < n:
if is_prime(candidate, prime_set):
prime_set.add(candidate)
candidate +=1
return sum(prime_set)
def main():
assert(summation_primes(10) == 17)
print(summation_primes(2000000))
print('Tests Passed!')
if __name__ == '__main__':
main()

View file

@ -1,66 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
import string
def get_grid(filename):
grid = [ [ 0 for i in range(20) ] for j in range(20) ]
with open(filename) as file:
for row, line in enumerate(file):
line.strip('\n')
for collumn, number in enumerate(line.split(' ')):
grid[row][collumn] = int(number)
return grid
def larg_prod_grid(grid):
row, col, larg_prod = 0, 0, 0
up, down, left, right, diag1, diag2, diag3, diag4 = 0, 0, 0, 0, 0, 0, 0, 0
while row < len(grid):
while col < len(grid[0]):
if col > 2:
up = grid[row][col] * grid[row][col-1] * grid[row][col-2] * grid[row][col-3]
if col < len(grid[0]) - 3:
down = grid[row][col] * grid[row][col+1] * grid[row][col+2] * grid[row][col+3]
if row > 2:
left = grid[row][col] * grid[row-1][col] * grid[row-2][col] * grid[row-3][col]
if row < len(grid) - 3:
right = grid[row][col] * grid[row+1][col] * grid[row+2][col] * grid[row+3][col]
if col > 2 and row > 2:
diag1 = grid[row][col] * grid[row-1][col-1] * grid[row-2][col-2] * grid[row-3][col-3]
if col > 2 and row < len(grid) - 3:
diag2 = grid[row][col] * grid[row+1][col-1] * grid[row+2][col-2] * grid[row+3][col-3]
if col < len(grid[0]) - 3 and row > 2:
diag3 = grid[row][col] * grid[row-1][col+1] * grid[row-2][col+2] * grid[row-3][col+3]
if col < len(grid[0]) -3 and row < len(grid) - 3:
down = grid[row][col] * grid[row+1][col+1] * grid[row+1][col+2] * grid[row+1][col+3]
l1 = [up, down, left, right, diag1, diag2, diag3, diag4]
largest_prod_here = max(l1)
if largest_prod_here > larg_prod:
larg_prod = largest_prod_here
col += 1
col = 0
row += 1
return larg_prod
def main():
import time
start = time.time()
filename = 'larg_prod_grid.dat'
grid = get_grid(filename)
assert((grid[6][8], grid[7][9], grid[8][10], grid[9][11]) == (26, 63, 78, 14))
print(larg_prod_grid(grid))
elapsed = (time.time() - start)
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
if __name__ == '__main__':
main()

View file

@ -1,43 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
import math
def find_div(n):
''' find the divisor of a given n'''
set_div = {1, n}
for i in range(2, int(math.sqrt(n))+ 1):
if not n % i:
set_div.add(i)
set_div.add(n//i)
l1 = list(set_div)
return len(l1)
def find_trian(l):
''' find the lth trian number'''
return sum(range(1, l+1))
def highly_divisible_trian_num(d):
thtriangle, n_div, count = 1, 0, 1
while n_div < d:
count += 1
thtriangle += count
n_div = find_div(thtriangle)
return (thtriangle, count)
def main():
import time
start = time.time()
assert(highly_divisible_trian_num(6) == (28, 7))
print(highly_divisible_trian_num(500))
elapsed = (time.time() - start)
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
if __name__ == '__main__':
main()

View file

@ -1,25 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def large_sum(filename):
sum_total, lines, numbers = 0, 0, 0
with open(filename) as file:
for line in file:
sum_total += int(line.strip('\n'))
return str(sum_total)[0:10]
def main():
import time
start = time.time()
filename = 'large_sum.dat'
print(large_sum(filename))
elapsed = (time.time() - start)
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
if __name__ == '__main__':
main()

View file

@ -1,43 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def find_coll_seq(n):
count = 1
while n > 1:
if n%2 == 0:
n = n//2
else:
n = 3*n +1
count += 1
return count
def find_longest_chain(limit):
longest, number = 0, 0
start = 0
while start <= limit:
size_chain = find_coll_seq(start)
if size_chain > longest:
longest = size_chain
number = start
start += 1
return (longest, number)
def main():
import time
start = time.time()
#print(find_longest_chain(13))
print(find_longest_chain(10**6))
elapsed = (time.time() - start)
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
if __name__ == '__main__':
main()

View file

@ -1,42 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def lattice_paths(squares):
gridsize = squares+1
grid = [[0 for i in range(gridsize)] for j in range(gridsize)]
row, col = 0, 0
while col < gridsize:
while row < gridsize:
if row == 0 and col == 0:
grid[row][col] = 1
else:
if row == 0 and col != 0:
grid[row][col] += grid[row][col-1]
elif row != 0 and col == 0:
grid[row][col] += grid[row-1][col]
else:
grid[row][col] += grid[row][col-1] + grid[row-1][col]
row += 1
row = 0
col += 1
return grid[gridsize-1][gridsize-1]
def main():
import time
start = time.time()
assert(lattice_paths(2) == 6)
print(lattice_paths(20))
elapsed = (time.time() - start)
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
if __name__ == '__main__':
main()

View file

@ -1,22 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def power_digit_sum(n):
number = str(2**n)
sum_res = 0
for i in number:
sum_res += int(i)
return sum_res
def test_():
assert(power_digit_sum(15) == 26)
print(power_digit_sum(1000))
print('Tests Passed!')
if __name__ == '__main__':
test_()

View file

@ -1,63 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def number_letter_counts(n):
dict_lett = build_dict(n)
sum_letter = 0
for item in dict_lett:
sum_letter += dict_lett[item]
return sum_letter
def build_dict(n):
lett_dict = {}
numbers = (x for x in range(1, n+1))
dec = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
ties = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
for number in numbers:
if 1 <= number < 20:
lett_dict[number] = len(dec[number-1])
elif 20 <= number < 100:
index_dec = number//10
index_num = number%10
if index_num == 0:
lett_dict[number] = len(ties[index_dec-2])
else:
lett_dict[number] = len(ties[index_dec-2]) + len(dec[index_num-1])
elif 100 <= number < 1000:
index_hun = number//100
index_dec = number%100
if index_dec == 0:
lett_dict[number] = len(dec[index_hun-1]) + len('hundred')
else:
if 1 <= index_dec < 20:
lett_dict[number] = len(dec[index_hun-1]) + len('hundred') + len('and') + len(dec[index_dec-1])
elif 20 <= index_dec < 100:
index_dec2 = index_dec//10
index_num = index_dec%10
if index_num == 0:
lett_dict[number] = len(dec[index_hun-1]) + len('hundred') + len('and') + len(ties[index_dec2-2])
else:
lett_dict[number] = len(dec[index_hun-1]) + len('hundred') + len('and') + len(ties[index_dec2-2]) + len(dec[index_num-1])
elif number == 1000:
lett_dict[number] = len('onethousand')
return lett_dict
def main():
import time
start = time.time()
assert(number_letter_counts(5) == 19)
print(number_letter_counts(1000))
elapsed = (time.time() - start)
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
if __name__ == '__main__':
main()

View file

@ -1,55 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def max_path_sum(t):
root = t[0][0]
height, width, index, large_num = 1, 0, 0, 0
max_sum = root
heights = len(t[:])
while height < heights:
values_here = t[height][index:index+2]
if values_here[0] > values_here[1]:
large_num = values_here[0]
else:
large_num = values_here[1]
index += 1
max_sum += large_num
pivot = large_num
width, large_num = 0, 0
height += 1
return max_sum
def edit_input(filename):
output = []
with open(filename) as file:
for line in file:
line = line.rstrip('\n')
output.append(line.split(' '))
for i, l1 in enumerate(output):
for j, c in enumerate(output[i]):
output[i][j] = int(c)
return(output)
def main():
import time
start = time.time()
filename = 'max_path_sum0.dat'
t1 = edit_input(filename)
print('Little pir: ',max_path_sum(t1))
filename = 'max_path_sum.dat'
t2 = edit_input(filename)
print('Big pir: ', max_path_sum(t2))
elapsed = (time.time() - start)
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
if __name__ == '__main__':
main()

View file

@ -1,65 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
'''
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
'''
def find_if_leap_year(y):
if (y%4 == 0 and y%100 != 0) or (y%400 == 0):
return True
return False
def counting_sundays():
''' define variables '''
days_year = 7*31 + 4*30 + 28
count_sundays = 0
days_week = 7
dict_week = {0: 'mon', 1:'tue', 2:'wed', 3:'thu', 4:'fri', 5:'sat', 6:'sun'}
''' with info from 1900 find first day for 1901 '''
first_day = days_year%days_week # not a leap year
for y in range (1901, 2001):
leap_year = find_if_leap_year(y)
days_count = first_day
for m in range(1, 13):
if days_count%7 == 6:
count_sundays += 1
if m == 2:
if leap_year:
days_count += 29
else:
days_count += 28
elif m == 4 or m == 6 or m == 9 or m == 11:
days_count += 30
else:
days_count += 31
if leap_year: first_day = (first_day +2)%days_week
else: first_day = (first_day +1)%days_week
return count_sundays
def main():
print(counting_sundays())
print('Tests Passed!')
if __name__ == '__main__':
main()

View file

@ -1,32 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def factorial(n):
prod = 1
for i in range(1,n):
prod *= i
return prod
def find_sum(n):
sum_ = 0
fact = factorial(n)
number = str(fact)
for i in number:
sum_ += int(i)
return sum_
def main():
import time
start = time.time()
assert(find_sum(10) == 27)
print(find_sum(100))
elapsed = (time.time() - start)
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
if __name__ == '__main__':
main()

View file

@ -1,44 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
'''
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.
'''
def find_sum_proper_divisors(n):
sum_proper_div = 0
for i in range(1, n):
if n%i == 0:
sum_proper_div += i
return sum_proper_div
def amicable_numbers(N):
sum_div_list = [find_sum_proper_divisors(i) for i in range(1, N+1)]
sum_amicable_numbers = 0
set_div = set()
for a in range(1, N):
da = sum_div_list[a-1]
if da < N:
b = da
db = sum_div_list[b-1]
if a != b and db == a and a not in set_div and b not in set_div:
sum_amicable_numbers += a + b
set_div.add(a)
set_div.add(b)
return sum_amicable_numbers
def main():
print(amicable_numbers(10000))
print('Tests Passed!')
if __name__ == '__main__':
main()

View file

@ -1,33 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def calculate_score(name, dict_letters):
sum_letters = 0
for letter in name:
sum_letters += dict_letters[letter]
return sum_letters
def names_score(filename):
dict_letters ={'A':1,'B':2,'C':3,'D':4,'E':5,'F':6,'G':7,'H':8,'I':9,'J':10,'K':11,'L':12,'M':13,'N':14,'O':15,'P':16,'Q':17,'R':18,'S':19, 'T':20,'U':21,'V':22,'W':23,'X':24,'Y':25,'Z':26}
total_score = 0
with open(filename) as file:
for line in file:
names = [name.strip('"') for name in line.split(',')]
names.sort()
for i, name in enumerate(names):
total_score += (i+1)* calculate_score(name, dict_letters)
return total_score
def main():
filename = 'names.txt'
print(names_score(filename))
if __name__ == '__main__':
main()

View file

@ -1,44 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def find_sum_proper_div(n):
sum_proper_div = 0
for i in range(1, n):
if n%i == 0:
sum_proper_div += i
return sum_proper_div
def find_all_abund(n):
sum_div_list = [find_sum_proper_div(i) for i in range(n)]
abu = set()
for i in range(n):
if i < sum_div_list[i]:
abu.add(i)
return abu
def non_abund_sums(n):
abu = find_all_abund(n)
sum_nom_abu = 0
for i in range(n):
if not any( (i-a in abu) for a in abu):
sum_nom_abu += i
return sum_nom_abu
def test_():
r = set([i for i in range(25)])
r_abu = {24}
r = r - r_abu
assert(non_abund_sums(25) == sum(r))
print(non_abund_sums(28123))
print('Tests Passed!')
if __name__ == '__main__':
test_()

View file

@ -1,33 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def perm_item(elements):
if len(elements) <= 1:
yield elements
else:
for (index, elmt) in enumerate(elements):
other_elmts = elements[:index]+elements[index+1:]
for permutation in perm_item(other_elmts):
yield [elmt] + permutation
def lex_perm(l1, n):
perm_list = list(perm_item(l1))
return sorted(perm_list)[n-1]
def main():
import time
start = time.time()
l1 = [0,1,2,3,4,5,6,7,8,9]
n = 10**6
print(lex_perm(l1, n))
elapsed = (time.time() - start)
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
if __name__ == '__main__':
main()

Some files were not shown because too many files have changed in this diff Show more