abstracted structures fixed

This commit is contained in:
Mari Wahl 2015-01-06 21:11:21 -05:00
parent 3fdbc2a605
commit 01703751f1
98 changed files with 305 additions and 856 deletions

View File

@ -1,11 +1,11 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
#!/usr/bin/env python
__author__ = "bt3"
from fractions import Fraction
def rounding_floats(number1, places):
''' some operations with float()'''
return round(number1, places)

View File

@ -1,7 +1,9 @@
#!/usr/bin/python
# mari von steinkirch @2013
# steinkirch at gmail
#!/usr/bin/env python
__author__ = "bt3"
import time
import numpy as np
def testing_numpy():
@ -27,6 +29,32 @@ def testing_numpy():
print(grid1[1]+10)
print(grid2[:,2]*2)
def trad_version():
t1 = time.time()
X = range(10000000)
Y = range(10000000)
Z = []
for i in range(len(X)):
Z.append(X[i] + Y[i])
return time.time() - t1
def numpy_version():
t1 = time.time()
X = np.arange(10000000)
Y = np.arange(10000000)
Z = X + Y
return time.time() - t1
if __name__ == '__main__':
testing_numpy()
print(trad_version())
print(numpy_version())
'''
3.23564291
0.0714290142059
'''

View File

@ -1,6 +1,6 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
#!/usr/bin/env python
__author__ = "bt3"
import random

View File

@ -1,6 +1,6 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
#!/usr/bin/env python
__author__ = "bt3"
def difference(l1):
""" return the list with duplicate elements removed """

17
src/abstract_structures/HashTable.py Normal file → Executable file
View File

@ -7,24 +7,29 @@ class HashTable(object):
def __init__(self, slots=10):
self.slots = slots
self.table = []
self.__create_table()
self.create_table()
def __hash_key(self, value):
def hash_key(self, value):
return hash(value)%self.slots
def __create_table(self):
def create_table(self):
for i in range(self.slots):
self.table.append([])
def add_item(self, value):
key = self.__hash_key(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)
@ -32,3 +37,5 @@ if __name__ == '__main__':
dic.add_item(i)
dic.print_table()
assert(dic.find_item(20) == False)
assert(dic.find_item(21) == True)

View File

@ -17,11 +17,24 @@ class Queue(object):
self.deq.append(self.enq.pop())
return self.deq.pop()
def isEmpty(self):
return not (self.enq + self.deq)
def size(self):
return len(self.enq) + len(self.deq)
if __name__ == '__main__':
q = Queue()
for i in range(1,10):
q.enqueue(i)
assert(q.isEmpty() == False)
assert(q.size() == 9)
for i in range(1, 10):
print q.dequeue()
assert(q.isEmpty() == True)

View File

@ -32,6 +32,21 @@ class Stack(object):
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__':

0
src/abstract_structures/__init__.py Normal file → Executable file
View File

View File

@ -1,61 +0,0 @@
#!/usr/bin/python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
''' design a Hash table using chaining to avoid collisions.'''
#import abstract_structures.linked_list.linked_list_fifo
#import abstract_structures.linked_list.node
from linked_list_fifo import LinkedListFIFO
class HashTableLL(object):
def __init__(self, size):
self.size = size
self.slots = []
self._createHashTable()
def _createHashTable(self):
for i in range(self.size) :
self.slots.append(LinkedListFIFO())
def _find(self, item):
return item%self.size
def _add(self, item):
index = self._find(item)
self.slots[index].addNode(item)
def _delete(self, item):
index = self._find(item)
self.slots[index].deleteNode(item)
def _print(self):
for i in range(self.size):
print('\nSlot {}:'.format(i))
print(self.slots[i]._printList())
def test_hash_tables():
H1 = HashTableLL(3)
for i in range (0, 20):
H1._add(i)
H1._print()
print('\n\nNow deleting:')
H1._delete(0)
H1._delete(1)
H1._delete(2)
H1._delete(0)
H1._print()
if __name__ == '__main__':
test_hash_tables()

View File

@ -1,6 +1,6 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
#!/usr/bin/env python
__author__ = "bt3"
import heapq

View File

@ -1,6 +1,6 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
#!/usr/bin/env python
__author__ = "bt3"
class Heapify(object):
def __init__(self, data=None):
@ -44,7 +44,6 @@ def test_Heapify():
l1 = [3, 2, 5, 1, 7, 8, 2]
h = Heapify(l1)
assert(h.extract_max() == 8)
print ("Tests Passed!")
if __name__ == '__main__':
test_Heapify()

View File

@ -1,6 +1,6 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
#!/usr/bin/env python
__author__ = "bt3"
import heapq
@ -20,8 +20,6 @@ def test_merge_sorted_seq(module_name='this module'):
seq3 = seq1 + seq2
assert(merge_sorted_seqseq1, seq2) == sorted(seq3))
s = 'Tests in {name} have {con}!'
print(s.format(name=module_name, con='passed'))
if __name__ == '__main__':

View File

@ -1,6 +1,6 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
#!/usr/bin/env python
__author__ = "bt3"
import heapq
@ -32,7 +32,6 @@ def test_PriorityQueue():
q.push(Item('test2'), 4)
q.push(Item('test3'), 3)
assert(str(q.pop()) == "Item('test2')")
print('Tests passed!'.center(20,'*'))
if __name__ == '__main__':

View File

@ -1,49 +0,0 @@
#!/usr/bin/python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
''' Given a linked list, check if the nodes form a palindrome '''
from linked_list_fifo import LinkedListFIFO, Node
from node import Node
def isPal(l):
if len(l1) < 2:
return True
if l1[0] != l1[-1]:
return False
return isPal(l1[1:-1])
def checkllPal(ll):
node = ll.head
l = []
while node:
l.append(node.value)
node = node.pointer
return isPal(l)
if __name__ == '__main__':
ll = LinkedListFIFO()
l1 = [1, 2, 3, 2, 1]
for i in l1:
ll.addNode(i)
assert(checkllPal(ll) == True)
ll.addNode(2)
ll.addNode(3)
assert(checkllPal(ll) == False)

View File

@ -1,8 +1,6 @@
#!/usr/bin/python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
#!/usr/bin/env python
__author__ = "bt3"
''' implement a function to see whether a linked list is circular.

View File

@ -1,7 +1,6 @@
#!/usr/bin/python
#!/usr/bin/env python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
__author__ = "bt3"
''' Implement a double-linked list, which is very simple, we just need inherits
from a Linked List Class and add an attribute for previous.'''
@ -18,7 +17,6 @@ class dNode(object):
class dLinkList(LinkedListFIFO):
# print each node's value, starting from tail
def printListInverse(self):
node = self.tail
while node:
@ -28,8 +26,6 @@ class dLinkList(LinkedListFIFO):
except:
break
# add a node in a position different from head,
# ie, in the end of the list
def _add(self, value):
self.length += 1
node = dNode(value)
@ -38,14 +34,12 @@ class dLinkList(LinkedListFIFO):
node.previous = self.tail
self.tail = node
# delete a node in some position
def _delete(self, node):
self.length -= 1
node.previous.pointer = node.pointer
if not node.pointer:
self.tail = node.previous
# locate node with some index
def _find(self, index):
node = self.head
i = 0
@ -66,11 +60,6 @@ class dLinkList(LinkedListFIFO):
print('Node with index {} not found'.format(index))
if __name__ == '__main__':
from collections import Counter

View File

@ -1,7 +1,7 @@
#!/usr/bin/python
#!/usr/bin/env python
__author__ = "bt3"
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
''' Find the mth-to-last element of a linked list.
One option is having two pointers, separated by m. P1 start at the roots

View File

@ -1,15 +1,12 @@
#!/usr/bin/python
#!/usr/bin/env python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
__author__ = "bt3"
''' A class for a linked list that has the nodes in a FIFO order (such as a queue)'''
from node import Node
class LinkedListFIFO(object):
def __init__(self):
@ -17,32 +14,24 @@ class LinkedListFIFO(object):
self.length = 0
self.tail = None # this is different from ll lifo
# print each node's value, starting from the head
def _printList(self):
node = self.head
while node:
print(node.value)
node = node.pointer
# add a node in the first position
# read will never be changed again while not empty
def _addFirst(self, value):
self.length = 1
node = Node(value)
self.head = node
self.tail = node
# delete a node in the first position, ie
# when there is no previous node
def _deleteFirst(self):
self.length = 0
self.head = None
self.tail = None
print('The list is empty.')
# add a node in a position different from head,
# ie, in the end of the list
def _add(self, value):
self.length += 1
node = Node(value)
@ -50,15 +39,12 @@ class LinkedListFIFO(object):
self.tail.pointer = node
self.tail = node
# add nodes in general
def addNode(self, value):
if not self.head:
self._addFirst(value)
else:
self._add(value)
# locate node with some index
def _find(self, index):
prev = None
node = self.head
@ -69,7 +55,6 @@ class LinkedListFIFO(object):
i += 1
return node, prev, i
# delete nodes in general
def deleteNode(self, index):
if not self.head or not self.head.pointer:
self._deleteFirst()
@ -87,9 +72,6 @@ class LinkedListFIFO(object):
print('Node with index {} not found'.format(index))
if __name__ == '__main__':
ll = LinkedListFIFO()
for i in range(1, 5):

View File

@ -1,9 +1,6 @@
#!/usr/bin/python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
#!/usr/bin/env python
__author__ = "bt3"
''' Implement a unordered linked list, i.e. a LIFO linked list (like a stack) '''
@ -16,15 +13,12 @@ class LinkedListLIFO(object):
self.head = None
self.length = 0
# print each node's value, starting from the head
def _printList(self):
node = self.head
while node:
print(node.value)
node = node.pointer
# delete a node, given the previous node
def _delete(self, prev, node):
self.length -= 1
if not prev:
@ -32,14 +26,10 @@ class LinkedListLIFO(object):
else:
prev.pointer = node.pointer
# add a new node, pointing to the previous node
# in the head
def _add(self, value):
self.length += 1
self.head = Node(value, self.head)
# locate node with some index
def _find(self, index):
prev = None
node = self.head
@ -50,7 +40,6 @@ class LinkedListLIFO(object):
i += 1
return node, prev, i
# locate node by value
def _find_by_value(self, value):
prev = None
node = self.head
@ -63,8 +52,6 @@ class LinkedListLIFO(object):
node = node.pointer
return node, prev, found
# find and delete a node by index
def deleteNode(self, index):
node, prev, i = self._find(index)
if index == i:
@ -72,8 +59,6 @@ class LinkedListLIFO(object):
else:
print('Node with index {} not found'.format(index))
# find and delete a node by value
def deleteNodeByValue(self, value):
node, prev, found = self._find_by_value(value)
if found:

View File

@ -1,8 +1,6 @@
#!/usr/bin/python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
#!/usr/bin/env python
__author__ = "bt3"
class Node(object):
def __init__(self, value=None, pointer=None):

View File

@ -1,7 +1,6 @@
#!/usr/bin/python
#!/usr/bin/env python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
__author__ = "bt3"
''' This function divides a linked list in a value, where everything smaller than this value
goes to the front, and everything large goes to the back:'''

View File

@ -1,7 +1,6 @@
#!/usr/bin/python
#!/usr/bin/env python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
__author__ = "bt3"
''' Supposing two linked lists representing numbers, such that in each of their
nodes they carry one digit. This function sums the two numbers that these

View File

@ -1,7 +1,6 @@
#!/usr/bin/python
#!/usr/bin/env python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
__author__ = "bt3"
""" A class for an animal shelter with two queues"""

View File

@ -1,7 +1,6 @@
#!/usr/bin/python
#!/usr/bin/env python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
__author__ = "bt3"
''' a class for a double ended queue (also inefficient) '''

View File

@ -1,7 +1,6 @@
#!/usr/bin/python
#!/usr/bin/env python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
__author__ = "bt3"
''' Queue acts as a container for nodes (objects) that are inserted and removed according FIFO'''

View File

@ -1,17 +1,19 @@
#!/usr/bin/python
#!/usr/bin/env python
__author__ = "bt3"
""" Using our deque class and Python's deque class """
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
import string
import collections
from deque import Deque
STRIP = string.whitespace + string.punctuation + "\"'"
""" Using our deque class and Python's deque class """
def palindrome_checker_with_deque(str1):
d1 = Deque()

View File

@ -1,43 +0,0 @@
#!/usr/bin/python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
''' an (inefficient) class for a queue '''
class Queue(object):
def __init__(self):
self.items = []
def isEmpty(self):
return not bool(self.items)
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def peek(self):
return self.items[-1]
def __repr__(self):
return '{}'.format(self.items)
if __name__ == '__main__':
queue = Queue()
print("Is the queue empty? ", queue.isEmpty())
print("Adding 0 to 10 in the queue...")
for i in range(10):
queue.enqueue(i)
print("Queue size: ", queue.size())
print("Queue peek : ", queue.peek())
print("Dequeue...", queue.dequeue())
print("Queue peek: ", queue.peek())
print("Is the queue empty? ", queue.isEmpty())
print(queue)

View File

@ -1,75 +0,0 @@
#!/usr/bin/python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
''' an example of a queue implemented from 2 stacks '''
class Queue(object):
def __init__(self):
self.in_stack = []
self.out_stack = []
# basic methods
def _transfer(self):
while self.in_stack:
self.out_stack.append(self.in_stack.pop())
def enqueue(self, item):
return self.in_stack.append(item)
def dequeue(self):
if not self.out_stack:
self._transfer()
if self.out_stack:
return self.out_stack.pop()
else:
return "Queue empty!"
def size(self):
return len(self.in_stack) + len(self.out_stack)
def peek(self):
if not self.out_stack:
self._transfer()
if self.out_stack:
return self.out_stack[-1]
else:
return "Queue empty!"
def __repr__(self):
if not self.out_stack:
self._transfer()
if self.out_stack:
return '{}'.format(self.out_stack)
else:
return "Queue empty!"
def isEmpty(self):
return not ((bool(self.in_stack) or bool(self.out_stack)))
if __name__ == '__main__':
queue = Queue()
print("Is the queue empty? ", queue.isEmpty())
print("Adding 0 to 10 in the queue...")
for i in range(10):
queue.enqueue(i)
print("Queue size: ", queue.size())
print("Queue peek : ", queue.peek())
print("Dequeue...", queue.dequeue())
print("Queue peek: ", queue.peek())
print("Is the queue empty? ", queue.isEmpty())
print("Printing the queue...")
print(queue)

View File

@ -1,7 +1,6 @@
#!/usr/bin/python
#!/usr/bin/env python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
__author__ = "bt3"
''' use a stack to balance the parenteses of a string '''

View File

@ -1,7 +1,7 @@
#!/usr/bin/python
#!/usr/bin/env python
__author__ = "bt3"
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
'''transform a decimal number to a binary number with a stack '''

View File

@ -1,13 +1,11 @@
#!/usr/bin/python
#!/usr/bin/env python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
__author__ = "bt3"
""" A stack made of linked list"""
class Node(object):
def __init__(self, value=None, pointer=None):
self.value = value

View File

@ -1,7 +1,7 @@
#!/usr/bin/python
#!/usr/bin/env python
__author__ = "bt3"
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
''' Uses a stack to reverse a string '''

View File

@ -1,7 +1,6 @@
#!/usr/bin/python
#!/usr/bin/env python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
__author__ = "bt3"
""" define a class for a set of stacks """

72
src/abstract_structures/stacks/stack.py Normal file → Executable file
View File

@ -1,53 +1,65 @@
#!/usr/bin/python
#!/usr/bin/env python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
# copy of the class ../Stack.py
''' define the stack class '''
__author__ = "bt3"
class Stack(object):
def __init__(self):
self.items = []
def isEmpty(self):
return not bool(self.items)
self.content = []
self.min_array = []
self.min = float('inf')
def push(self, value):
self.items.append(value)
if value < self.min:
self.min = value
self.content.append(value)
self.min_array.append(self.min)
def pop(self):
value = self.items.pop()
if value:
if self.content:
value = self.content.pop()
self.min_array.pop()
if self.min_array:
self.min = self.min_array[-1]
return value
else:
print("Stack is empty.")
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.items)
return len(self.content)
def isEmpty(self):
return not bool(self.content)
def peek(self):
if self.items:
return self.items[-1]
if self.content:
return self.content[-1]
else:
print('Stack is empty.')
def __repr__(self):
return '{}'.format(self.items)
return '{}'.format(self.content)
if __name__ == '__main__':
stack = Stack()
print("Is the stack empty? ", stack.isEmpty())
print("Adding 0 to 10 in the stack...")
for i in range(10):
stack.push(i)
print("Stack size: ", stack.size())
print("Stack peek : ", stack.peek())
print("Pop...", stack.pop())
print("Stack peek: ", stack.peek())
print("Is the stack empty? ", stack.isEmpty())
print(stack)
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,7 +1,6 @@
#!/usr/bin/python
#!/usr/bin/env python
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
__author__ = "bt3"
''' A stack with a minimum lookup '''

View File

@ -1,7 +1,7 @@
#!/usr/bin/python
#!/usr/bin/env python
__author__ = "bt3"
__author__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
""" Implement the 'towers of hanoi'"""

0
src/builtin_structures/__init__.py Normal file → Executable file
View File

0
src/builtin_structures/alpha_permutation.py Normal file → Executable file
View File

0
src/builtin_structures/anagram.py Normal file → Executable file
View File

0
src/builtin_structures/balance_symbols.py Normal file → Executable file
View File

View File

View File

View File

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

0
src/builtin_structures/convert_str_2_int.py Normal file → Executable file
View File

0
src/builtin_structures/count_unique_words_On2.py Normal file → Executable file
View File

16
src/builtin_structures/fibonacci.py Normal file → Executable file
View File

@ -33,6 +33,22 @@ def fib(n):
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()

0
src/builtin_structures/find_0_MxN_replace_cols_rows.py Normal file → Executable file
View File

0
src/builtin_structures/find_dice_probabilities.py Normal file → Executable file
View File

0
src/builtin_structures/find_edit_distance.py Normal file → Executable file
View File

0
src/builtin_structures/find_first_non_repetead_char.py Normal file → Executable file
View File

0
src/builtin_structures/find_if_is_substr.py Normal file → Executable file
View File

0
src/builtin_structures/find_if_unique_char.py Normal file → Executable file
View File

0
src/builtin_structures/find_long_con_inc_subseq.py Normal file → Executable file
View File

View File

View File

0
src/builtin_structures/find_top_N_recurring_words.py Normal file → Executable file
View File

View File

0
src/builtin_structures/longest_common_prefix.py Normal file → Executable file
View File

View File

@ -1,27 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def convert_dec_to_any_base_rec(number, base):
''' convert an integer to a string in any base'''
convertString = '012345679ABCDEF'
if number < base: return convertString[number]
else:
return convert_dec_to_any_base_rec(number//base, base) + convertString[number%base]
def test_convert_dec_to_any_base_rec(module_name='this module'):
number = 9
base = 2
assert(convert_dec_to_any_base_rec(number, base) == '1001')
s = 'Tests in {name} have {con}!'
print(s.format(name=module_name, con='passed'))
if __name__ == '__main__':
test_convert_dec_to_any_base_rec()

View File

@ -1,24 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def convert_from_decimal(number, base):
''' convert any decimal number to another base. '''
multiplier, result = 1, 0
while number > 0:
result += number%base*multiplier
multiplier *= 10
number = number//base
return result
def test_convert_from_decimal():
number, base = 9, 2
assert(convert_from_decimal(number, base) == 1001)
print('Tests passed!')
if __name__ == '__main__':
test_convert_from_decimal()

View File

@ -1,24 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def convert_from_decimal_larger_bases(number, base):
''' convert any decimal number to a number in a base up to 20'''
strings = "0123456789ABCDEFGHIJ"
result = ""
while number > 0:
digit = number%base
result = strings[digit] + result
number = number//base
return result
def test_convert_from_decimal_larger_bases():
number, base = 31, 16
assert(convert_from_decimal_larger_bases(number, base) == '1F')
print('Tests passed!')
if __name__ == '__main__':
test_convert_from_decimal_larger_bases()

View File

@ -1,25 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def convert_to_decimal(number, base):
''' convert any number in another base to the decimal base'''
multiplier, result = 1, 0
while number > 0:
result += number%10*multiplier
multiplier *= base
number = number//10
return result
def test_convert_to_decimal():
number, base = 1001, 2
assert(convert_to_decimal(number, base) == 9)
print('Tests passed!')
if __name__ == '__main__':
test_convert_to_decimal()

View File

@ -1,44 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
import math
def find_fibonacci_seq_rec(n):
''' implements the nth fibonacci value in a recursive exponential runtime '''
if n < 2: return n
return find_fibonacci_seq_rec(n - 1) + find_fibonacci_seq_rec(n - 2)
def find_fibonacci_seq_iter(n):
''' return the nth fibonacci value in a iterative O(n^2) runtime '''
if n < 2: return n
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
def find_fibonacci_seq_form(n):
''' return the nth fibonacci value implemented by the formula, nearly constant-time algorithm,
but, it has a poor precise (after 72 it starts to become wrong) '''
sq5 = math.sqrt(5)
phi = (1 + sq5) / 2
return int(math.floor(phi ** n / sq5))
def test_find_fib():
n = 10
assert(find_fibonacci_seq_rec(n) == 55)
assert(find_fibonacci_seq_iter(n) == 55)
assert(find_fibonacci_seq_form(n) == 55)
print('Tests passed!')
if __name__ == '__main__':
test_find_fib()

View File

@ -1,28 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def finding_gcd(a, b):
''' implements the greatest common divider algorithm '''
while(b != 0):
result = b
a, b = b, a % b
return result
def test_finding_gcd():
number1 = 21
number2 = 12
assert(finding_gcd(number1, number2) == 3)
print('Tests passed!')
if __name__ == '__main__':
test_finding_gcd()

View File

@ -1,59 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
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

@ -1,35 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
import math
import random
import sys
from finding_prime import finding_prime_sqrt
def generate_prime(number=3):
''' return a n-bit prime '''
while 1:
p = random.randint(pow(2, number-2), pow(2, number-1)-1)
p = 2 * p + 1
if finding_prime_sqrt(p):
return p
if __name__ == '__main__':
if len(sys.argv) < 2:
print ("Usage: generate_prime.py number")
sys.exit()
else:
number = int(sys.argv[1])
print(generate_prime(number))

View File

@ -1,32 +0,0 @@
#!/usr/bin/python
# mari von steinkirch @2013
# steinkirch at gmail
import numpy
import time
def trad_version():
t1 = time.time()
X = range(10000000)
Y = range(10000000)
Z = []
for i in range(len(X)):
Z.append(X[i] + Y[i])
return time.time() - t1
def numpy_version():
t1 = time.time()
X = numpy.arange(10000000)
Y = numpy.arange(10000000)
Z = X + Y
return time.time() - t1
if __name__ == '__main__':
print(trad_version())
print(numpy_version())
'''
3.23564291
0.0714290142059
'''

0
src/builtin_structures/palindrome.py Normal file → Executable file
View File

0
src/builtin_structures/permutations.py Normal file → Executable file
View File

View File

@ -8,6 +8,7 @@ find prime factors of a number.
'''
import math
import random
def find_prime_factors(n):
'''
@ -30,6 +31,15 @@ def is_prime(n):
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

0
src/builtin_structures/prod_other_ints.py Normal file → Executable file
View File

0
src/builtin_structures/reverse_string.py Normal file → Executable file
View File

0
src/builtin_structures/reverse_words.py Normal file → Executable file
View File

0
src/builtin_structures/rotate_NxN.py Normal file → Executable file
View File

View File

View File

View File

@ -1,18 +1,22 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
#!/usr/bin/env python
__author__ = "bt3"
def find_elem_matrix_bool(m1, value):
''' Search an Entry in a Matrix where the Rows and columns are Sorted
''' Search an Entry in a Matrix where the Rows and columns are Sorted
In this 2D matrix, every row is increasingly sorted from left to right,
and every column is increasingly sorted from top to bottom.
The runtime is O(m+n). '''
The runtime is O(m+n).
'''
def find_elem_matrix_bool(m1, value):
found = False
row = 0
col = len(m1[0]) - 1
while row < len(m1) and col >= 0:
if m1[row][col] == value:
found = True
break
@ -20,6 +24,7 @@ def find_elem_matrix_bool(m1, value):
col-=1
else:
row+=1
return found
@ -31,9 +36,6 @@ def test_find_elem_matrix_bool(module_name='this module'):
m2 = [[0]]
assert(find_elem_matrix_bool(m2,0) == True)
s = 'Tests in {name} have {con}!'
print(s.format(name=module_name, con='passed'))
if __name__ == '__main__':
test_find_elem_matrix_bool()

View File

@ -1,37 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def removing_duplicates_seq(seq):
''' if the values are hashable, we can use set and generators to remove duplicates
in a sequence '''
seen = set()
for item in seq:
if item not in seen:
yield item
seen.add(item)
def removing_duplicates_seq_not_hash(seq, key= None):
''' if the item is not hashable, such as dictionaries '''
seen = set()
for item in seq:
val = item if key is None else key[item]
if item not in seen:
yield item
seen.add(val)
def test_removing_duplicates_seq():
seq = [1, 2, 2, 2, 3, 3, 4, 4, 4]
dict = {'a':1, 'b':2, 'a':2, 'a':1}
assert(list(removing_duplicates_seq(seq)) == [1,2,3,4])
assert(list(removing_duplicates_seq_not_hash(dict)) == ['a', 'b'])
print('Tests passed!'.center(20, '*'))
if __name__ == '__main__':
test_removing_duplicates_seq()

View File

@ -1,39 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
from collections import OrderedDict
def set_operations_with_dict():
''' find common in 2 dictionaries '''
''' values() do not support set operations!'''
pairs = [('a', 1), ('b',2), ('c',3)]
d1 = OrderedDict(pairs)
print(d1) # ('a', 1), ('b', 2), ('c', 3)
d2 = {'a':1, 'c':2, 'd':3, 'e':4}
print(d2) # {'a': 1, 'c': 2, 'e': 4, 'd': 3}
union = d1.keys() & d2.keys()
print(union) # {'a', 'c'}
union_items = d1.items() & d2.items()
print(union_items) # {('a', 1)}
subtraction1 = d1.keys() - d2.keys()
print(subtraction1) # {'b'}
subtraction2 = d2.keys() - d1.keys()
print(subtraction2) # {'d', 'e'}
subtraction_items = d1.items() - d2.items()
print(subtraction_items) # {('b', 2), ('c', 3)}
''' we can remove keys from a dict doing: '''
d3 = {key:d2[key] for key in d2.keys() - {'c', 'd'}}
print(d3) {'a': 1, 'e': 4}
if __name__ == '__main__':
set_operations_with_dict()

View File

@ -1,39 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
from collections import OrderedDict
def set_operations_with_dict():
''' find common in 2 dictionaries '''
''' values() do not support set operations!'''
pairs = [('a', 1), ('b',2), ('c',3)]
d1 = OrderedDict(pairs)
print(d1) # ('a', 1), ('b', 2), ('c', 3)
d2 = {'a':1, 'c':2, 'd':3, 'e':4}
print(d2) # {'a': 1, 'c': 2, 'e': 4, 'd': 3}
union = d1.keys() & d2.keys()
print(union) # {'a', 'c'}
union_items = d1.items() & d2.items()
print(union_items) # {('a', 1)}
subtraction1 = d1.keys() - d2.keys()
print(subtraction1) # {'b'}
subtraction2 = d2.keys() - d1.keys()
print(subtraction2) # {'d', 'e'}
subtraction_items = d1.items() - d2.items()
print(subtraction_items) # {('b', 2), ('c', 3)}
''' we can remove keys from a dict doing: '''
d3 = {key:d2[key] for key in d2.keys() - {'c', 'd'}}
print(d3) {'a': 1, 'e': 4}
if __name__ == '__main__':
set_operations_with_dict()

0
src/builtin_structures/simple_str_comprension.py Normal file → Executable file
View File

0
src/builtin_structures/sum_two_numbers_as_strings.py Normal file → Executable file
View File

View File

@ -1,17 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
from collections import namedtuple
def namedtuple_example():
''' show some examples for namedtuple '''
sunnydale = namedtuple('name', ['job', 'age'])
buffy = sunnydale('slayer', '17')
print(buffy.job)
if __name__ == '__main__':
namedtuple_example()