From 01703751f16d0fc94615547b9c4ca23756dc3181 Mon Sep 17 00:00:00 2001 From: Mari Wahl Date: Tue, 6 Jan 2015 21:11:21 -0500 Subject: [PATCH] abstracted structures fixed --- .../basic_examples/example_fractions.py} | 14 ++-- .../basic_examples/example_numpy.py} | 38 ++++++++-- .../basic_examples/example_random.py} | 10 +-- .../basic_examples/example_sets.py} | 6 +- src/abstract_structures/HashTable.py | 19 +++-- .../{queue_with_stack.py => Queue.py} | 15 +++- .../{stack_with_minumum.py => Stack.py} | 15 ++++ src/abstract_structures/__init__.py | 0 .../hash_tables/__init__.py | 0 .../hash_tables/hash_table.py | 61 --------------- .../heap/find_N_largest_smallest_items_seq.py | 14 ++-- src/abstract_structures/heap/heapify.py | 13 ++-- .../heap/merge_sorted_seqs.py | 10 +-- .../heap/priority_queue.py | 13 ++-- .../linked_list/check_pal.py | 49 ------------ .../linked_list/circular_ll.py | 6 +- .../linked_list/double_linked_list_fifo.py | 15 +--- .../linked_list/find_kth_from_the_end.py | 6 +- .../linked_list/linked_list_fifo.py | 22 +----- .../linked_list/linked_list_lifo.py | 19 +---- src/abstract_structures/linked_list/node.py | 6 +- .../linked_list/part_linked_list.py | 5 +- .../linked_list/sum_linked_list.py | 5 +- .../queues/animal_shelter.py | 5 +- src/abstract_structures/queues/deque.py | 5 +- .../queues/linked_queue.py | 5 +- .../queues/palindrome_checker_with_deque.py | 12 +-- src/abstract_structures/queues/queue.py | 43 ----------- .../queues/queue_from_two_stacks.py | 75 ------------------- ...is_str_stack.py => balance_parenthesis.py} | 5 +- .../stacks/dec2bin_with_stack.py | 6 +- .../stacks/linked_stack.py | 6 +- .../stacks/reverse_string_with_stack.py | 6 +- .../stacks/set_of_stacks.py | 5 +- src/abstract_structures/stacks/stack.py | 72 ++++++++++-------- .../stacks/stack_with_min.py | 5 +- .../stacks/towers_of_hanoi.py | 6 +- .../bit_operations/bit_array.py | 0 .../bit_operations/clear_bits.py | 0 .../bit_operations/find_bit_len.py | 0 .../bit_operations/find_how_many_1_binary.py | 0 .../bit_operations/get_bit.py | 0 .../bit_operations/get_float_rep_bin.py | 0 .../insert_small_bin_into_big_bin.py | 0 .../bit_operations/next_with_same_num_1s.py | 0 .../num_bits_to_convert_2_nums.py | 0 .../bit_operations/set_bit.py | 0 .../bit_operations/swap_odd_even.py | 0 .../bit_operations/update_bit.py | 0 src/builtin_structures/__init__.py | 0 src/builtin_structures/alpha_permutation.py | 0 src/builtin_structures/anagram.py | 0 src/builtin_structures/balance_symbols.py | 0 .../check_if_3_numbers_sum_to_zero.py | 0 .../check_non_overlapping_intervals.py | 0 .../convert_numerical_bases.py | 64 ++++++++++++++++ src/builtin_structures/convert_str_2_int.py | 0 .../count_unique_words_On2.py | 0 src/builtin_structures/fibonacci.py | 16 ++++ .../find_0_MxN_replace_cols_rows.py | 0 .../find_dice_probabilities.py | 0 src/builtin_structures/find_edit_distance.py | 0 .../find_first_non_repetead_char.py | 0 src/builtin_structures/find_if_is_substr.py | 0 src/builtin_structures/find_if_unique_char.py | 0 .../find_long_con_inc_subseq.py | 0 .../find_longest_str_unique_chars.py | 0 .../find_product_without_division.py | 0 .../find_top_N_recurring_words.py | 0 .../find_two_missing_numbers_in_sequence.py | 0 .../longest_common_prefix.py | 0 src/builtin_structures/numbers/__init__.py | 0 .../numbers/convert_dec_to_any_base_rec.py | 27 ------- .../numbers/convert_from_decimal.py | 24 ------ .../convert_from_decimal_larger_bases.py | 24 ------ .../numbers/convert_to_decimal.py | 25 ------- .../numbers/find_fibonacci_seq.py | 44 ----------- src/builtin_structures/numbers/finding_gcd.py | 28 ------- .../numbers/finding_if_prime.py | 59 --------------- .../numbers/generate_prime.py | 35 --------- .../numbers/testing_numpy_speed.py | 32 -------- src/builtin_structures/palindrome.py | 0 src/builtin_structures/permutations.py | 0 .../{find_prime_factors.py => primes.py} | 10 +++ src/builtin_structures/prod_other_ints.py | 0 src/builtin_structures/reverse_string.py | 0 src/builtin_structures/reverse_words.py | 0 src/builtin_structures/rotate_NxN.py | 0 .../runtime_dicts_with_timeit_module.py | 0 .../runtime_lists_with_timeit_module.py | 0 .../{numbers => }/search_entry_matrix.py | 24 +++--- src/builtin_structures/sets/__init__.py | 0 .../sets/removing_duplicates_seq_.py | 37 --------- .../sets/set_operations_dict.py | 39 ---------- .../sets/set_operations_with_dict.py | 39 ---------- .../simple_str_comprension.py | 0 .../sum_two_numbers_as_strings.py | 0 .../tuples/namedtuple_example.py | 17 ----- 98 files changed, 305 insertions(+), 856 deletions(-) rename src/{builtin_structures/numbers/testing_floats.py => USEFUL/basic_examples/example_fractions.py} (88%) rename src/{builtin_structures/numbers/testing_numpy.py => USEFUL/basic_examples/example_numpy.py} (54%) rename src/{builtin_structures/numbers/testing_random.py => USEFUL/basic_examples/example_random.py} (86%) rename src/{builtin_structures/sets/set_operations_with_lists.py => USEFUL/basic_examples/example_sets.py} (92%) mode change 100644 => 100755 src/abstract_structures/HashTable.py rename src/abstract_structures/{queue_with_stack.py => Queue.py} (65%) rename src/abstract_structures/{stack_with_minumum.py => Stack.py} (75%) mode change 100644 => 100755 src/abstract_structures/__init__.py delete mode 100644 src/abstract_structures/hash_tables/__init__.py delete mode 100644 src/abstract_structures/hash_tables/hash_table.py delete mode 100644 src/abstract_structures/linked_list/check_pal.py delete mode 100644 src/abstract_structures/queues/queue.py delete mode 100644 src/abstract_structures/queues/queue_from_two_stacks.py rename src/abstract_structures/stacks/{banlance_parenthesis_str_stack.py => balance_parenthesis.py} (89%) mode change 100644 => 100755 src/abstract_structures/stacks/stack.py rename src/{builtin_structures/sets => bitwise}/bit_operations/bit_array.py (100%) rename src/{builtin_structures/sets => bitwise}/bit_operations/clear_bits.py (100%) rename src/{builtin_structures/sets => bitwise}/bit_operations/find_bit_len.py (100%) rename src/{builtin_structures/sets => bitwise}/bit_operations/find_how_many_1_binary.py (100%) rename src/{builtin_structures/sets => bitwise}/bit_operations/get_bit.py (100%) rename src/{builtin_structures/sets => bitwise}/bit_operations/get_float_rep_bin.py (100%) rename src/{builtin_structures/sets => bitwise}/bit_operations/insert_small_bin_into_big_bin.py (100%) rename src/{builtin_structures/sets => bitwise}/bit_operations/next_with_same_num_1s.py (100%) rename src/{builtin_structures/sets => bitwise}/bit_operations/num_bits_to_convert_2_nums.py (100%) rename src/{builtin_structures/sets => bitwise}/bit_operations/set_bit.py (100%) rename src/{builtin_structures/sets => bitwise}/bit_operations/swap_odd_even.py (100%) rename src/{builtin_structures/sets => bitwise}/bit_operations/update_bit.py (100%) mode change 100644 => 100755 src/builtin_structures/__init__.py mode change 100644 => 100755 src/builtin_structures/alpha_permutation.py mode change 100644 => 100755 src/builtin_structures/anagram.py mode change 100644 => 100755 src/builtin_structures/balance_symbols.py mode change 100644 => 100755 src/builtin_structures/check_if_3_numbers_sum_to_zero.py mode change 100644 => 100755 src/builtin_structures/check_non_overlapping_intervals.py create mode 100755 src/builtin_structures/convert_numerical_bases.py mode change 100644 => 100755 src/builtin_structures/convert_str_2_int.py mode change 100644 => 100755 src/builtin_structures/count_unique_words_On2.py mode change 100644 => 100755 src/builtin_structures/fibonacci.py mode change 100644 => 100755 src/builtin_structures/find_0_MxN_replace_cols_rows.py mode change 100644 => 100755 src/builtin_structures/find_dice_probabilities.py mode change 100644 => 100755 src/builtin_structures/find_edit_distance.py mode change 100644 => 100755 src/builtin_structures/find_first_non_repetead_char.py mode change 100644 => 100755 src/builtin_structures/find_if_is_substr.py mode change 100644 => 100755 src/builtin_structures/find_if_unique_char.py mode change 100644 => 100755 src/builtin_structures/find_long_con_inc_subseq.py mode change 100644 => 100755 src/builtin_structures/find_longest_str_unique_chars.py mode change 100644 => 100755 src/builtin_structures/find_product_without_division.py mode change 100644 => 100755 src/builtin_structures/find_top_N_recurring_words.py mode change 100644 => 100755 src/builtin_structures/find_two_missing_numbers_in_sequence.py mode change 100644 => 100755 src/builtin_structures/longest_common_prefix.py delete mode 100644 src/builtin_structures/numbers/__init__.py delete mode 100644 src/builtin_structures/numbers/convert_dec_to_any_base_rec.py delete mode 100644 src/builtin_structures/numbers/convert_from_decimal.py delete mode 100644 src/builtin_structures/numbers/convert_from_decimal_larger_bases.py delete mode 100644 src/builtin_structures/numbers/convert_to_decimal.py delete mode 100644 src/builtin_structures/numbers/find_fibonacci_seq.py delete mode 100644 src/builtin_structures/numbers/finding_gcd.py delete mode 100644 src/builtin_structures/numbers/finding_if_prime.py delete mode 100644 src/builtin_structures/numbers/generate_prime.py delete mode 100644 src/builtin_structures/numbers/testing_numpy_speed.py mode change 100644 => 100755 src/builtin_structures/palindrome.py mode change 100644 => 100755 src/builtin_structures/permutations.py rename src/builtin_structures/{find_prime_factors.py => primes.py} (70%) mode change 100644 => 100755 mode change 100644 => 100755 src/builtin_structures/prod_other_ints.py mode change 100644 => 100755 src/builtin_structures/reverse_string.py mode change 100644 => 100755 src/builtin_structures/reverse_words.py mode change 100644 => 100755 src/builtin_structures/rotate_NxN.py mode change 100644 => 100755 src/builtin_structures/runtime_dicts_with_timeit_module.py mode change 100644 => 100755 src/builtin_structures/runtime_lists_with_timeit_module.py rename src/builtin_structures/{numbers => }/search_entry_matrix.py (72%) mode change 100644 => 100755 delete mode 100644 src/builtin_structures/sets/__init__.py delete mode 100644 src/builtin_structures/sets/removing_duplicates_seq_.py delete mode 100644 src/builtin_structures/sets/set_operations_dict.py delete mode 100644 src/builtin_structures/sets/set_operations_with_dict.py mode change 100644 => 100755 src/builtin_structures/simple_str_comprension.py mode change 100644 => 100755 src/builtin_structures/sum_two_numbers_as_strings.py delete mode 100644 src/builtin_structures/tuples/namedtuple_example.py diff --git a/src/builtin_structures/numbers/testing_floats.py b/src/USEFUL/basic_examples/example_fractions.py similarity index 88% rename from src/builtin_structures/numbers/testing_floats.py rename to src/USEFUL/basic_examples/example_fractions.py index 5734170..9bbff22 100644 --- a/src/builtin_structures/numbers/testing_floats.py +++ b/src/USEFUL/basic_examples/example_fractions.py @@ -1,22 +1,22 @@ -#!/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) def float_to_fractions(number): return Fraction(*number.as_integer_ratio()) - + def get_denominator(number1, number2): a = Fraction(number1, number2) return a.denominator - + def get_numerator(number1, number2): a = Fraction(number1, number2) @@ -34,7 +34,7 @@ def test_testing_floats(module_name='this module'): assert(float_to_fractions(number1) == number4) assert(get_denominator(number2, number6) == number6) assert(get_numerator(number2, number6) == number2) - + s = 'Tests in {name} have {con}!' print(s.format(name=module_name, con='passed')) diff --git a/src/builtin_structures/numbers/testing_numpy.py b/src/USEFUL/basic_examples/example_numpy.py similarity index 54% rename from src/builtin_structures/numbers/testing_numpy.py rename to src/USEFUL/basic_examples/example_numpy.py index bbd3fae..a2a90a6 100644 --- a/src/builtin_structures/numbers/testing_numpy.py +++ b/src/USEFUL/basic_examples/example_numpy.py @@ -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(): @@ -15,11 +17,11 @@ def testing_numpy(): print(np.cos(ax)) print(ax-ay) print(np.where(ax<2, ax, 10)) - + m = np.matrix([ax, ay, ax]) print(m) print(m.T) - + grid1 = np.zeros(shape=(10,10), dtype=float) grid2 = np.ones(shape=(10,10), dtype=float) print(grid1) @@ -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 +''' diff --git a/src/builtin_structures/numbers/testing_random.py b/src/USEFUL/basic_examples/example_random.py similarity index 86% rename from src/builtin_structures/numbers/testing_random.py rename to src/USEFUL/basic_examples/example_random.py index dae8767..e4dc921 100644 --- a/src/builtin_structures/numbers/testing_random.py +++ b/src/USEFUL/basic_examples/example_random.py @@ -1,6 +1,6 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail +#!/usr/bin/env python + +__author__ = "bt3" import random @@ -12,11 +12,11 @@ def testing_random(): print(random.choice(values)) print(random.sample(values, 2)) print(random.sample(values, 3)) - + ''' shuffle in place ''' random.shuffle(values) print(values) - + ''' create random integers ''' print(random.randint(0,10)) print(random.randint(0,10)) diff --git a/src/builtin_structures/sets/set_operations_with_lists.py b/src/USEFUL/basic_examples/example_sets.py similarity index 92% rename from src/builtin_structures/sets/set_operations_with_lists.py rename to src/USEFUL/basic_examples/example_sets.py index f836d21..ef621d4 100644 --- a/src/builtin_structures/sets/set_operations_with_lists.py +++ b/src/USEFUL/basic_examples/example_sets.py @@ -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 """ diff --git a/src/abstract_structures/HashTable.py b/src/abstract_structures/HashTable.py old mode 100644 new mode 100755 index 726e1b3..2dad275 --- a/src/abstract_structures/HashTable.py +++ b/src/abstract_structures/HashTable.py @@ -7,28 +7,35 @@ 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) for i in range(1, 40, 2): dic.add_item(i) - dic.print_table() \ No newline at end of file + dic.print_table() + assert(dic.find_item(20) == False) + assert(dic.find_item(21) == True) diff --git a/src/abstract_structures/queue_with_stack.py b/src/abstract_structures/Queue.py similarity index 65% rename from src/abstract_structures/queue_with_stack.py rename to src/abstract_structures/Queue.py index d74ccf8..612b499 100755 --- a/src/abstract_structures/queue_with_stack.py +++ b/src/abstract_structures/Queue.py @@ -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() \ No newline at end of file + print q.dequeue() + + assert(q.isEmpty() == True) + diff --git a/src/abstract_structures/stack_with_minumum.py b/src/abstract_structures/Stack.py similarity index 75% rename from src/abstract_structures/stack_with_minumum.py rename to src/abstract_structures/Stack.py index 873ab55..ba36110 100755 --- a/src/abstract_structures/stack_with_minumum.py +++ b/src/abstract_structures/Stack.py @@ -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__': diff --git a/src/abstract_structures/__init__.py b/src/abstract_structures/__init__.py old mode 100644 new mode 100755 diff --git a/src/abstract_structures/hash_tables/__init__.py b/src/abstract_structures/hash_tables/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/src/abstract_structures/hash_tables/hash_table.py b/src/abstract_structures/hash_tables/hash_table.py deleted file mode 100644 index 61c41a4..0000000 --- a/src/abstract_structures/hash_tables/hash_table.py +++ /dev/null @@ -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() diff --git a/src/abstract_structures/heap/find_N_largest_smallest_items_seq.py b/src/abstract_structures/heap/find_N_largest_smallest_items_seq.py index 11bde95..18042fe 100644 --- a/src/abstract_structures/heap/find_N_largest_smallest_items_seq.py +++ b/src/abstract_structures/heap/find_N_largest_smallest_items_seq.py @@ -1,13 +1,13 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail +#!/usr/bin/env python + +__author__ = "bt3" import heapq def find_N_largest_items_seq(seq, N): ''' find the N largest items in a sequence ''' return heapq.nlargest(N,seq) - + def find_N_smallest_items_seq(seq, N): ''' find the N smallest items in a sequence ''' return heapq.nsmallest(N, seq) @@ -18,7 +18,7 @@ def find_smallest_items_seq_heap(seq): ''' pops the smallest item, O(logN) ''' heapq.heapify(seq) return heapq.heappop(seq) - + def find_smallest_items_seq(seq): ''' if it is only one item, min() is faster ''' return min(seq) @@ -26,7 +26,7 @@ def find_smallest_items_seq(seq): def find_N_smallest_items_seq_sorted(seq, N): ''' N ~ len(seq), better sort instead''' return sorted(seq)[:N] - + def find_N_largest_items_seq_sorted(seq, N): ''' N ~ len(seq), better sort instead''' return sorted(seq)[len(seq)-N:] @@ -41,7 +41,7 @@ def test_find_N_largest_smallest_items_seq(module_name='this module'): assert(find_N_smallest_items_seq_sorted(seq, N) == [1,2,3]) assert(find_smallest_items_seq(seq) == 1) assert(find_smallest_items_seq_heap(seq) == 1) - + s = 'Tests in {name} have {con}!' print(s.format(name=module_name, con='passed')) diff --git a/src/abstract_structures/heap/heapify.py b/src/abstract_structures/heap/heapify.py index 8c39c0e..aa1d86b 100644 --- a/src/abstract_structures/heap/heapify.py +++ b/src/abstract_structures/heap/heapify.py @@ -1,13 +1,13 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail +#!/usr/bin/env python + +__author__ = "bt3" class Heapify(object): def __init__(self, data=None): self.data = data or [] for i in range(len(data)//2, -1, -1): self.__max_heapify__(i) - + def __repr__(self): return '{}'.format(self.data) @@ -19,12 +19,12 @@ class Heapify(object): def right_child(self, i): return (i << 1) + 2 # +2 instead of +1 because it's 0-indexed. - + def __max_heapify__(self, i): largest = i left = self.left_child(i) right = self.right_child(i) - n = len(self.data) + n = len(self.data) largest = (left < n and self.data[left] > self.data[i]) and left or i largest = (right < n and self.data[right] > self.data[largest]) and right or largest if i is not largest: @@ -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() diff --git a/src/abstract_structures/heap/merge_sorted_seqs.py b/src/abstract_structures/heap/merge_sorted_seqs.py index 861ca07..1d211b2 100644 --- a/src/abstract_structures/heap/merge_sorted_seqs.py +++ b/src/abstract_structures/heap/merge_sorted_seqs.py @@ -1,6 +1,6 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail +#!/usr/bin/env python + +__author__ = "bt3" import heapq @@ -19,9 +19,7 @@ def test_merge_sorted_seq(module_name='this module'): seq2 = [2, 3, 4, 5, 6, 7, 9] 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__': diff --git a/src/abstract_structures/heap/priority_queue.py b/src/abstract_structures/heap/priority_queue.py index 605f78d..5aed910 100644 --- a/src/abstract_structures/heap/priority_queue.py +++ b/src/abstract_structures/heap/priority_queue.py @@ -1,6 +1,6 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail +#!/usr/bin/env python + +__author__ = "bt3" import heapq @@ -9,11 +9,11 @@ class PriorityQueue(object): def __init__(self): self._queue = [] self._index = 0 # comparying same priority level - + def push(self, item, priority): - heapq.heappush(self._queue, (-priority, self._index, item)) + heapq.heappush(self._queue, (-priority, self._index, item)) self._index += 1 - + def pop(self): return heapq.heappop(self._queue)[-1] @@ -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__': diff --git a/src/abstract_structures/linked_list/check_pal.py b/src/abstract_structures/linked_list/check_pal.py deleted file mode 100644 index 4e8eb76..0000000 --- a/src/abstract_structures/linked_list/check_pal.py +++ /dev/null @@ -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) diff --git a/src/abstract_structures/linked_list/circular_ll.py b/src/abstract_structures/linked_list/circular_ll.py index 1330701..fdeb026 100644 --- a/src/abstract_structures/linked_list/circular_ll.py +++ b/src/abstract_structures/linked_list/circular_ll.py @@ -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. diff --git a/src/abstract_structures/linked_list/double_linked_list_fifo.py b/src/abstract_structures/linked_list/double_linked_list_fifo.py index 8546164..094b283 100644 --- a/src/abstract_structures/linked_list/double_linked_list_fifo.py +++ b/src/abstract_structures/linked_list/double_linked_list_fifo.py @@ -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 diff --git a/src/abstract_structures/linked_list/find_kth_from_the_end.py b/src/abstract_structures/linked_list/find_kth_from_the_end.py index 4937bc4..8fd0cba 100644 --- a/src/abstract_structures/linked_list/find_kth_from_the_end.py +++ b/src/abstract_structures/linked_list/find_kth_from_the_end.py @@ -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 diff --git a/src/abstract_structures/linked_list/linked_list_fifo.py b/src/abstract_structures/linked_list/linked_list_fifo.py index 1492795..9a983a9 100644 --- a/src/abstract_structures/linked_list/linked_list_fifo.py +++ b/src/abstract_structures/linked_list/linked_list_fifo.py @@ -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): diff --git a/src/abstract_structures/linked_list/linked_list_lifo.py b/src/abstract_structures/linked_list/linked_list_lifo.py index 186af83..b75b621 100644 --- a/src/abstract_structures/linked_list/linked_list_lifo.py +++ b/src/abstract_structures/linked_list/linked_list_lifo.py @@ -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: diff --git a/src/abstract_structures/linked_list/node.py b/src/abstract_structures/linked_list/node.py index 92908fb..0a2d459 100644 --- a/src/abstract_structures/linked_list/node.py +++ b/src/abstract_structures/linked_list/node.py @@ -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): diff --git a/src/abstract_structures/linked_list/part_linked_list.py b/src/abstract_structures/linked_list/part_linked_list.py index f38cd62..d178b27 100644 --- a/src/abstract_structures/linked_list/part_linked_list.py +++ b/src/abstract_structures/linked_list/part_linked_list.py @@ -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:''' diff --git a/src/abstract_structures/linked_list/sum_linked_list.py b/src/abstract_structures/linked_list/sum_linked_list.py index 1c48c43..4cf14cb 100644 --- a/src/abstract_structures/linked_list/sum_linked_list.py +++ b/src/abstract_structures/linked_list/sum_linked_list.py @@ -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 diff --git a/src/abstract_structures/queues/animal_shelter.py b/src/abstract_structures/queues/animal_shelter.py index 938b0c0..6208289 100644 --- a/src/abstract_structures/queues/animal_shelter.py +++ b/src/abstract_structures/queues/animal_shelter.py @@ -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""" diff --git a/src/abstract_structures/queues/deque.py b/src/abstract_structures/queues/deque.py index a6bb95a..ede3e53 100644 --- a/src/abstract_structures/queues/deque.py +++ b/src/abstract_structures/queues/deque.py @@ -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) ''' diff --git a/src/abstract_structures/queues/linked_queue.py b/src/abstract_structures/queues/linked_queue.py index 9df6d88..ca2aafd 100644 --- a/src/abstract_structures/queues/linked_queue.py +++ b/src/abstract_structures/queues/linked_queue.py @@ -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''' diff --git a/src/abstract_structures/queues/palindrome_checker_with_deque.py b/src/abstract_structures/queues/palindrome_checker_with_deque.py index ed8f591..af14321 100644 --- a/src/abstract_structures/queues/palindrome_checker_with_deque.py +++ b/src/abstract_structures/queues/palindrome_checker_with_deque.py @@ -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() diff --git a/src/abstract_structures/queues/queue.py b/src/abstract_structures/queues/queue.py deleted file mode 100644 index 68995fb..0000000 --- a/src/abstract_structures/queues/queue.py +++ /dev/null @@ -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) \ No newline at end of file diff --git a/src/abstract_structures/queues/queue_from_two_stacks.py b/src/abstract_structures/queues/queue_from_two_stacks.py deleted file mode 100644 index e1bf63e..0000000 --- a/src/abstract_structures/queues/queue_from_two_stacks.py +++ /dev/null @@ -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) \ No newline at end of file diff --git a/src/abstract_structures/stacks/banlance_parenthesis_str_stack.py b/src/abstract_structures/stacks/balance_parenthesis.py similarity index 89% rename from src/abstract_structures/stacks/banlance_parenthesis_str_stack.py rename to src/abstract_structures/stacks/balance_parenthesis.py index 7892be1..a54c13d 100644 --- a/src/abstract_structures/stacks/banlance_parenthesis_str_stack.py +++ b/src/abstract_structures/stacks/balance_parenthesis.py @@ -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 ''' diff --git a/src/abstract_structures/stacks/dec2bin_with_stack.py b/src/abstract_structures/stacks/dec2bin_with_stack.py index 4df7e09..31dc066 100644 --- a/src/abstract_structures/stacks/dec2bin_with_stack.py +++ b/src/abstract_structures/stacks/dec2bin_with_stack.py @@ -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 ''' diff --git a/src/abstract_structures/stacks/linked_stack.py b/src/abstract_structures/stacks/linked_stack.py index 1ccafb9..23a4ad6 100644 --- a/src/abstract_structures/stacks/linked_stack.py +++ b/src/abstract_structures/stacks/linked_stack.py @@ -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 diff --git a/src/abstract_structures/stacks/reverse_string_with_stack.py b/src/abstract_structures/stacks/reverse_string_with_stack.py index 2a56573..014ab9b 100644 --- a/src/abstract_structures/stacks/reverse_string_with_stack.py +++ b/src/abstract_structures/stacks/reverse_string_with_stack.py @@ -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 ''' diff --git a/src/abstract_structures/stacks/set_of_stacks.py b/src/abstract_structures/stacks/set_of_stacks.py index 9b1a38a..bfe5bde 100644 --- a/src/abstract_structures/stacks/set_of_stacks.py +++ b/src/abstract_structures/stacks/set_of_stacks.py @@ -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 """ diff --git a/src/abstract_structures/stacks/stack.py b/src/abstract_structures/stacks/stack.py old mode 100644 new mode 100755 index 87134a7..869ecf3 --- a/src/abstract_structures/stacks/stack.py +++ b/src/abstract_structures/stacks/stack.py @@ -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) \ No newline at end of file + 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() \ No newline at end of file diff --git a/src/abstract_structures/stacks/stack_with_min.py b/src/abstract_structures/stacks/stack_with_min.py index ce64fc8..83a16ed 100644 --- a/src/abstract_structures/stacks/stack_with_min.py +++ b/src/abstract_structures/stacks/stack_with_min.py @@ -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 ''' diff --git a/src/abstract_structures/stacks/towers_of_hanoi.py b/src/abstract_structures/stacks/towers_of_hanoi.py index 5d90372..f424faa 100644 --- a/src/abstract_structures/stacks/towers_of_hanoi.py +++ b/src/abstract_structures/stacks/towers_of_hanoi.py @@ -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'""" diff --git a/src/builtin_structures/sets/bit_operations/bit_array.py b/src/bitwise/bit_operations/bit_array.py similarity index 100% rename from src/builtin_structures/sets/bit_operations/bit_array.py rename to src/bitwise/bit_operations/bit_array.py diff --git a/src/builtin_structures/sets/bit_operations/clear_bits.py b/src/bitwise/bit_operations/clear_bits.py similarity index 100% rename from src/builtin_structures/sets/bit_operations/clear_bits.py rename to src/bitwise/bit_operations/clear_bits.py diff --git a/src/builtin_structures/sets/bit_operations/find_bit_len.py b/src/bitwise/bit_operations/find_bit_len.py similarity index 100% rename from src/builtin_structures/sets/bit_operations/find_bit_len.py rename to src/bitwise/bit_operations/find_bit_len.py diff --git a/src/builtin_structures/sets/bit_operations/find_how_many_1_binary.py b/src/bitwise/bit_operations/find_how_many_1_binary.py similarity index 100% rename from src/builtin_structures/sets/bit_operations/find_how_many_1_binary.py rename to src/bitwise/bit_operations/find_how_many_1_binary.py diff --git a/src/builtin_structures/sets/bit_operations/get_bit.py b/src/bitwise/bit_operations/get_bit.py similarity index 100% rename from src/builtin_structures/sets/bit_operations/get_bit.py rename to src/bitwise/bit_operations/get_bit.py diff --git a/src/builtin_structures/sets/bit_operations/get_float_rep_bin.py b/src/bitwise/bit_operations/get_float_rep_bin.py similarity index 100% rename from src/builtin_structures/sets/bit_operations/get_float_rep_bin.py rename to src/bitwise/bit_operations/get_float_rep_bin.py diff --git a/src/builtin_structures/sets/bit_operations/insert_small_bin_into_big_bin.py b/src/bitwise/bit_operations/insert_small_bin_into_big_bin.py similarity index 100% rename from src/builtin_structures/sets/bit_operations/insert_small_bin_into_big_bin.py rename to src/bitwise/bit_operations/insert_small_bin_into_big_bin.py diff --git a/src/builtin_structures/sets/bit_operations/next_with_same_num_1s.py b/src/bitwise/bit_operations/next_with_same_num_1s.py similarity index 100% rename from src/builtin_structures/sets/bit_operations/next_with_same_num_1s.py rename to src/bitwise/bit_operations/next_with_same_num_1s.py diff --git a/src/builtin_structures/sets/bit_operations/num_bits_to_convert_2_nums.py b/src/bitwise/bit_operations/num_bits_to_convert_2_nums.py similarity index 100% rename from src/builtin_structures/sets/bit_operations/num_bits_to_convert_2_nums.py rename to src/bitwise/bit_operations/num_bits_to_convert_2_nums.py diff --git a/src/builtin_structures/sets/bit_operations/set_bit.py b/src/bitwise/bit_operations/set_bit.py similarity index 100% rename from src/builtin_structures/sets/bit_operations/set_bit.py rename to src/bitwise/bit_operations/set_bit.py diff --git a/src/builtin_structures/sets/bit_operations/swap_odd_even.py b/src/bitwise/bit_operations/swap_odd_even.py similarity index 100% rename from src/builtin_structures/sets/bit_operations/swap_odd_even.py rename to src/bitwise/bit_operations/swap_odd_even.py diff --git a/src/builtin_structures/sets/bit_operations/update_bit.py b/src/bitwise/bit_operations/update_bit.py similarity index 100% rename from src/builtin_structures/sets/bit_operations/update_bit.py rename to src/bitwise/bit_operations/update_bit.py diff --git a/src/builtin_structures/__init__.py b/src/builtin_structures/__init__.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/alpha_permutation.py b/src/builtin_structures/alpha_permutation.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/anagram.py b/src/builtin_structures/anagram.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/balance_symbols.py b/src/builtin_structures/balance_symbols.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/check_if_3_numbers_sum_to_zero.py b/src/builtin_structures/check_if_3_numbers_sum_to_zero.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/check_non_overlapping_intervals.py b/src/builtin_structures/check_non_overlapping_intervals.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/convert_numerical_bases.py b/src/builtin_structures/convert_numerical_bases.py new file mode 100755 index 0000000..999d40e --- /dev/null +++ b/src/builtin_structures/convert_numerical_bases.py @@ -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() + diff --git a/src/builtin_structures/convert_str_2_int.py b/src/builtin_structures/convert_str_2_int.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/count_unique_words_On2.py b/src/builtin_structures/count_unique_words_On2.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/fibonacci.py b/src/builtin_structures/fibonacci.py old mode 100644 new mode 100755 index d378c1f..584b611 --- a/src/builtin_structures/fibonacci.py +++ b/src/builtin_structures/fibonacci.py @@ -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() diff --git a/src/builtin_structures/find_0_MxN_replace_cols_rows.py b/src/builtin_structures/find_0_MxN_replace_cols_rows.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/find_dice_probabilities.py b/src/builtin_structures/find_dice_probabilities.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/find_edit_distance.py b/src/builtin_structures/find_edit_distance.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/find_first_non_repetead_char.py b/src/builtin_structures/find_first_non_repetead_char.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/find_if_is_substr.py b/src/builtin_structures/find_if_is_substr.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/find_if_unique_char.py b/src/builtin_structures/find_if_unique_char.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/find_long_con_inc_subseq.py b/src/builtin_structures/find_long_con_inc_subseq.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/find_longest_str_unique_chars.py b/src/builtin_structures/find_longest_str_unique_chars.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/find_product_without_division.py b/src/builtin_structures/find_product_without_division.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/find_top_N_recurring_words.py b/src/builtin_structures/find_top_N_recurring_words.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/find_two_missing_numbers_in_sequence.py b/src/builtin_structures/find_two_missing_numbers_in_sequence.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/longest_common_prefix.py b/src/builtin_structures/longest_common_prefix.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/numbers/__init__.py b/src/builtin_structures/numbers/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/src/builtin_structures/numbers/convert_dec_to_any_base_rec.py b/src/builtin_structures/numbers/convert_dec_to_any_base_rec.py deleted file mode 100644 index 63240b8..0000000 --- a/src/builtin_structures/numbers/convert_dec_to_any_base_rec.py +++ /dev/null @@ -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() - diff --git a/src/builtin_structures/numbers/convert_from_decimal.py b/src/builtin_structures/numbers/convert_from_decimal.py deleted file mode 100644 index 6c2c8ed..0000000 --- a/src/builtin_structures/numbers/convert_from_decimal.py +++ /dev/null @@ -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() - - diff --git a/src/builtin_structures/numbers/convert_from_decimal_larger_bases.py b/src/builtin_structures/numbers/convert_from_decimal_larger_bases.py deleted file mode 100644 index f8a7d71..0000000 --- a/src/builtin_structures/numbers/convert_from_decimal_larger_bases.py +++ /dev/null @@ -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() - - diff --git a/src/builtin_structures/numbers/convert_to_decimal.py b/src/builtin_structures/numbers/convert_to_decimal.py deleted file mode 100644 index 6c7af35..0000000 --- a/src/builtin_structures/numbers/convert_to_decimal.py +++ /dev/null @@ -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() - - diff --git a/src/builtin_structures/numbers/find_fibonacci_seq.py b/src/builtin_structures/numbers/find_fibonacci_seq.py deleted file mode 100644 index 911714d..0000000 --- a/src/builtin_structures/numbers/find_fibonacci_seq.py +++ /dev/null @@ -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() - - diff --git a/src/builtin_structures/numbers/finding_gcd.py b/src/builtin_structures/numbers/finding_gcd.py deleted file mode 100644 index dd7cb82..0000000 --- a/src/builtin_structures/numbers/finding_gcd.py +++ /dev/null @@ -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() - - - - - - - diff --git a/src/builtin_structures/numbers/finding_if_prime.py b/src/builtin_structures/numbers/finding_if_prime.py deleted file mode 100644 index 2c2c447..0000000 --- a/src/builtin_structures/numbers/finding_if_prime.py +++ /dev/null @@ -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() - - diff --git a/src/builtin_structures/numbers/generate_prime.py b/src/builtin_structures/numbers/generate_prime.py deleted file mode 100644 index a008b4c..0000000 --- a/src/builtin_structures/numbers/generate_prime.py +++ /dev/null @@ -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)) - - - - - - - - - diff --git a/src/builtin_structures/numbers/testing_numpy_speed.py b/src/builtin_structures/numbers/testing_numpy_speed.py deleted file mode 100644 index 714b3b4..0000000 --- a/src/builtin_structures/numbers/testing_numpy_speed.py +++ /dev/null @@ -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 -''' diff --git a/src/builtin_structures/palindrome.py b/src/builtin_structures/palindrome.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/permutations.py b/src/builtin_structures/permutations.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/find_prime_factors.py b/src/builtin_structures/primes.py old mode 100644 new mode 100755 similarity index 70% rename from src/builtin_structures/find_prime_factors.py rename to src/builtin_structures/primes.py index c7649b8..59dc1ed --- a/src/builtin_structures/find_prime_factors.py +++ b/src/builtin_structures/primes.py @@ -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 diff --git a/src/builtin_structures/prod_other_ints.py b/src/builtin_structures/prod_other_ints.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/reverse_string.py b/src/builtin_structures/reverse_string.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/reverse_words.py b/src/builtin_structures/reverse_words.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/rotate_NxN.py b/src/builtin_structures/rotate_NxN.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/runtime_dicts_with_timeit_module.py b/src/builtin_structures/runtime_dicts_with_timeit_module.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/runtime_lists_with_timeit_module.py b/src/builtin_structures/runtime_lists_with_timeit_module.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/numbers/search_entry_matrix.py b/src/builtin_structures/search_entry_matrix.py old mode 100644 new mode 100755 similarity index 72% rename from src/builtin_structures/numbers/search_entry_matrix.py rename to src/builtin_structures/search_entry_matrix.py index 0ddd73b..6d70fdd --- a/src/builtin_structures/numbers/search_entry_matrix.py +++ b/src/builtin_structures/search_entry_matrix.py @@ -1,18 +1,22 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail +#!/usr/bin/env python + +__author__ = "bt3" +''' 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). +''' def find_elem_matrix_bool(m1, value): - ''' 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). ''' + 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,8 +24,9 @@ def find_elem_matrix_bool(m1, value): col-=1 else: row+=1 + return found - + def test_find_elem_matrix_bool(module_name='this module'): @@ -30,9 +35,6 @@ def test_find_elem_matrix_bool(module_name='this module'): assert(find_elem_matrix_bool(m1,3) == False) 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__': diff --git a/src/builtin_structures/sets/__init__.py b/src/builtin_structures/sets/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/src/builtin_structures/sets/removing_duplicates_seq_.py b/src/builtin_structures/sets/removing_duplicates_seq_.py deleted file mode 100644 index 9399ae3..0000000 --- a/src/builtin_structures/sets/removing_duplicates_seq_.py +++ /dev/null @@ -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() - - diff --git a/src/builtin_structures/sets/set_operations_dict.py b/src/builtin_structures/sets/set_operations_dict.py deleted file mode 100644 index af68b31..0000000 --- a/src/builtin_structures/sets/set_operations_dict.py +++ /dev/null @@ -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() - diff --git a/src/builtin_structures/sets/set_operations_with_dict.py b/src/builtin_structures/sets/set_operations_with_dict.py deleted file mode 100644 index af68b31..0000000 --- a/src/builtin_structures/sets/set_operations_with_dict.py +++ /dev/null @@ -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() - diff --git a/src/builtin_structures/simple_str_comprension.py b/src/builtin_structures/simple_str_comprension.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/sum_two_numbers_as_strings.py b/src/builtin_structures/sum_two_numbers_as_strings.py old mode 100644 new mode 100755 diff --git a/src/builtin_structures/tuples/namedtuple_example.py b/src/builtin_structures/tuples/namedtuple_example.py deleted file mode 100644 index c2b23d1..0000000 --- a/src/builtin_structures/tuples/namedtuple_example.py +++ /dev/null @@ -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() - -