From 2fdaad121cc850edef948c8340e4e2a3a5cfd163 Mon Sep 17 00:00:00 2001 From: Mia Steinkirch Date: Fri, 11 Oct 2019 04:32:02 -0700 Subject: [PATCH] organize Signed-off-by: Mia Steinkirch --- source_code/USEFUL/advanced/lru_cache.py | 18 -- .../basic_examples/example_OrderedDict.py | 31 ---- .../USEFUL/basic_examples/example_args.py | 17 -- .../example_benchmark_decorator.py | 28 --- .../basic_examples/example_comp_lists.py | 37 ---- .../USEFUL/basic_examples/example_counter.py | 32 ---- .../basic_examples/example_decorators.py | 42 ----- .../basic_examples/example_defaultdict.py | 27 --- .../USEFUL/basic_examples/example_doctest.py | 15 -- .../basic_examples/example_fractions.py | 45 ----- .../basic_examples/example_generator.py | 27 --- .../USEFUL/basic_examples/example_lambda.py | 7 - .../USEFUL/basic_examples/example_logging.py | 21 --- .../USEFUL/basic_examples/example_numpy.py | 60 ------- .../basic_examples/example_open_files.py | 10 -- .../USEFUL/basic_examples/example_pickle.py | 58 ------ .../USEFUL/basic_examples/example_queue.py | 13 -- .../USEFUL/basic_examples/example_random.py | 27 --- .../basic_examples/example_setdefault.py | 38 ---- .../USEFUL/basic_examples/example_sets.py | 37 ---- .../USEFUL/basic_examples/example_socket.py | 35 ---- .../basic_examples/example_string_format.py | 11 -- .../basic_examples/example_subprocess.py | 8 - .../USEFUL/basic_examples/example_telnet.py | 22 --- .../USEFUL/basic_examples/example_testing.py | 46 ----- .../USEFUL/basic_examples/example_threads.py | 16 -- .../USEFUL/basic_examples/example_time.py | 24 --- .../USEFUL/dynamic_programming/__init__.py | 0 .../USEFUL/dynamic_programming/memo.py | 42 ----- .../memoized_longest_inc_subseq.py | 85 --------- source_code/USEFUL/oop/ShapeClass.py | 62 ------- source_code/USEFUL/oop/__init__.py | 0 .../useful_with_files/change_ext_file.py | 30 ---- .../count_unique_words_files.py | 28 --- .../count_unique_words_frequency.py | 15 -- .../useful_with_files/grep_word_from_files.py | 27 --- .../useful_with_files/remove_blank_lines.py | 54 ------ source_code/abstract_structures/HashTable.py | 41 ----- source_code/abstract_structures/Queue.py | 47 ----- source_code/abstract_structures/Stack.py | 63 ------- source_code/abstract_structures/__init__.py | 1 - .../abstract_structures/heap/__init__.py | 0 .../heap/find_N_largest_smallest_items_seq.py | 51 ------ .../abstract_structures/heap/heapify.py | 49 ----- .../heap/merge_sorted_seqs.py | 27 --- .../heap/priority_queue.py | 40 ----- .../linked_list/__init__.py | 0 .../linked_list/circular_ll.py | 55 ------ .../linked_list/double_linked_list_fifo.py | 81 --------- .../linked_list/find_kth_from_the_end.py | 42 ----- .../linked_list/linked_list_fifo.py | 90 ---------- .../linked_list/linked_list_lifo.py | 90 ---------- .../abstract_structures/linked_list/node.py | 33 ---- .../linked_list/part_linked_list.py | 57 ------ .../linked_list/sum_linked_list.py | 85 --------- .../abstract_structures/queues/__init__.py | 0 .../queues/animal_shelter.py | 109 ----------- .../abstract_structures/queues/deque.py | 39 ---- .../queues/linked_queue.py | 80 --------- .../queues/palindrome_checker_with_deque.py | 47 ----- .../abstract_structures/queues/queue.py | 63 ------- .../abstract_structures/stacks/__init__.py | 0 .../stacks/dec2bin_with_stack.py | 30 ---- .../stacks/linked_stack.py | 71 -------- .../stacks/reverse_string_with_stack.py | 31 ---- .../stacks/set_of_stacks.py | 56 ------ .../abstract_structures/stacks/stack.py | 65 ------- .../stacks/stack_with_min.py | 77 -------- .../stacks/towers_of_hanoi.py | 41 ----- source_code/bitwise/bit_array.py | 28 --- source_code/bitwise/bitwise.txt | 33 ---- source_code/bitwise/clear_bits.py | 37 ---- source_code/bitwise/find_bit_len.py | 25 --- source_code/bitwise/find_how_many_1_binary.py | 32 ---- source_code/bitwise/get_bit.py | 27 --- source_code/bitwise/get_float_rep_bin.py | 37 ---- .../bitwise/insert_small_bin_into_big_bin.py | 36 ---- source_code/bitwise/next_with_same_num_1s.py | 59 ------ .../bitwise/num_bits_to_convert_2_nums.py | 40 ----- source_code/bitwise/set_bit.py | 26 --- source_code/bitwise/swap_in_place.py | 23 --- source_code/bitwise/swap_odd_even.py | 37 ---- source_code/bitwise/update_bit.py | 22 --- source_code/builtin_structures/__init__.py | 0 source_code/builtin_structures/anagram.py | 51 ------ source_code/builtin_structures/balance.txt | 9 - .../builtin_structures/balance_symbols.py | 40 ----- .../check_if_2_numbers_sum_to_k.py | 71 -------- .../check_if_3_numbers_sum_to_zero.py | 36 ---- .../check_non_overlapping_intervals.py | 35 ---- .../convert_numerical_bases.py | 64 ------- .../builtin_structures/convert_str_2_int.py | 83 --------- .../count_unique_words_On2.py | 26 --- .../delete_duplicate_char_str.py | 49 ----- source_code/builtin_structures/fibonacci.py | 60 ------- .../find_0_MxN_replace_cols_rows.py | 35 ---- .../find_dice_probabilities.py | 32 ---- .../builtin_structures/find_edit_distance.py | 43 ----- .../find_first_non_repetead_char.py | 29 --- source_code/builtin_structures/find_gcd.py | 29 --- .../builtin_structures/find_if_substr.py | 36 ---- .../builtin_structures/find_if_unique_char.py | 32 ---- .../builtin_structures/find_largest_sum.py | 42 ----- .../find_longest_inc_subseq.py | 34 ---- .../find_longest_str_unique_chars.py | 38 ---- .../find_non_repeating_number.py | 33 ---- .../find_product_without_division.py | 42 ----- .../find_top_N_recurring_words.py | 27 --- .../find_two_missing_numbers_in_sequence.py | 56 ------ .../builtin_structures/get_float_rep_bin.py | 29 --- .../interserction_two_arrays.py | 63 ------- .../builtin_structures/max_subarray_stocks.py | 54 ------ .../number_of_zeros_factorial.txt | 15 -- source_code/builtin_structures/palindrome.py | 33 ---- .../builtin_structures/permutations.py | 70 -------- .../permutations_alphanumeric.py | 37 ---- source_code/builtin_structures/primes.py | 47 ----- .../builtin_structures/prod_other_ints.py | 28 --- source_code/builtin_structures/ransom_note.py | 34 ---- .../builtin_structures/reverse_string.py | 37 ---- .../builtin_structures/reverse_words.py | 45 ----- source_code/builtin_structures/rotate_NxN.py | 30 ---- .../runtime_dicts_with_timeit_module.py | 61 ------- .../runtime_lists_with_timeit_module.py | 66 ------- .../builtin_structures/search_entry_matrix.py | 42 ----- .../simple_str_comprension.py | 34 ---- .../sum_two_numbers_as_strings.py | 41 ----- source_code/learning/decorator.py | 19 -- .../searching/__init__.py | 0 .../searching/binary_search.py | 66 ------- .../searching/binary_search_matrix.py | 92 ---------- .../find_item_rotated_sorted_array.py | 51 ------ .../searching/find_max_unimodal_array.py | 35 ---- .../searching/find_sqrt_bin_search.py | 35 ---- .../find_str_array_with_empty_str.py | 54 ------ .../searching/find_time_occurence_list.py | 51 ------ .../searching/ordered_sequential_search.py | 36 ---- .../searching/quick_select.py | 89 --------- .../searching/searching_in_a_matrix.py | 50 ------ .../searching/sequential_search.py | 32 ---- .../searching_and_sorting/sorting/1.dat | 5 - .../searching_and_sorting/sorting/2.dat | 4 - .../searching_and_sorting/sorting/3.dat | 4 - .../searching_and_sorting/sorting/__init__.py | 0 .../sorting/bubble_sort.py | 28 --- .../sorting/count_sort.py | 27 --- .../sorting/gnome_sort.py | 31 ---- .../searching_and_sorting/sorting/heap.py | 45 ----- .../sorting/heap_sort.py | 84 --------- .../sorting/insertion_sort.py | 44 ----- .../sorting/merge_and_sort_two_arrays.py | 46 ----- .../sorting/merge_sort.py | 54 ------ .../sorting/quick_sort.py | 46 ----- .../sorting/selection_sort.py | 30 ---- .../sorting/sort_anagrams_together.py | 34 ---- source_code/trees/__init__.py | 0 source_code/trees/binary_search_tree.py | 120 ------------- source_code/trees/binary_tree.py | 96 ---------- source_code/trees/binary_tree_generators.py | 170 ------------------ source_code/trees/bunchclass.py | 22 --- source_code/trees/check_ancestor.py | 57 ------ source_code/trees/check_if_balanced.py | 31 ---- source_code/trees/check_if_bst.py | 64 ------- source_code/trees/check_largest_item.py | 23 --- source_code/trees/simple_tree.py | 41 ----- source_code/trees/transversal.py | 89 --------- source_code/trees/trie.py | 65 ------- 167 files changed, 6786 deletions(-) delete mode 100644 source_code/USEFUL/advanced/lru_cache.py delete mode 100644 source_code/USEFUL/basic_examples/example_OrderedDict.py delete mode 100755 source_code/USEFUL/basic_examples/example_args.py delete mode 100644 source_code/USEFUL/basic_examples/example_benchmark_decorator.py delete mode 100644 source_code/USEFUL/basic_examples/example_comp_lists.py delete mode 100644 source_code/USEFUL/basic_examples/example_counter.py delete mode 100755 source_code/USEFUL/basic_examples/example_decorators.py delete mode 100644 source_code/USEFUL/basic_examples/example_defaultdict.py delete mode 100644 source_code/USEFUL/basic_examples/example_doctest.py delete mode 100644 source_code/USEFUL/basic_examples/example_fractions.py delete mode 100644 source_code/USEFUL/basic_examples/example_generator.py delete mode 100644 source_code/USEFUL/basic_examples/example_lambda.py delete mode 100644 source_code/USEFUL/basic_examples/example_logging.py delete mode 100644 source_code/USEFUL/basic_examples/example_numpy.py delete mode 100644 source_code/USEFUL/basic_examples/example_open_files.py delete mode 100644 source_code/USEFUL/basic_examples/example_pickle.py delete mode 100755 source_code/USEFUL/basic_examples/example_queue.py delete mode 100644 source_code/USEFUL/basic_examples/example_random.py delete mode 100644 source_code/USEFUL/basic_examples/example_setdefault.py delete mode 100644 source_code/USEFUL/basic_examples/example_sets.py delete mode 100644 source_code/USEFUL/basic_examples/example_socket.py delete mode 100644 source_code/USEFUL/basic_examples/example_string_format.py delete mode 100644 source_code/USEFUL/basic_examples/example_subprocess.py delete mode 100644 source_code/USEFUL/basic_examples/example_telnet.py delete mode 100644 source_code/USEFUL/basic_examples/example_testing.py delete mode 100644 source_code/USEFUL/basic_examples/example_threads.py delete mode 100644 source_code/USEFUL/basic_examples/example_time.py delete mode 100644 source_code/USEFUL/dynamic_programming/__init__.py delete mode 100644 source_code/USEFUL/dynamic_programming/memo.py delete mode 100644 source_code/USEFUL/dynamic_programming/memoized_longest_inc_subseq.py delete mode 100644 source_code/USEFUL/oop/ShapeClass.py delete mode 100644 source_code/USEFUL/oop/__init__.py delete mode 100644 source_code/USEFUL/useful_with_files/change_ext_file.py delete mode 100755 source_code/USEFUL/useful_with_files/count_unique_words_files.py delete mode 100755 source_code/USEFUL/useful_with_files/count_unique_words_frequency.py delete mode 100644 source_code/USEFUL/useful_with_files/grep_word_from_files.py delete mode 100644 source_code/USEFUL/useful_with_files/remove_blank_lines.py delete mode 100755 source_code/abstract_structures/HashTable.py delete mode 100755 source_code/abstract_structures/Queue.py delete mode 100755 source_code/abstract_structures/Stack.py delete mode 100755 source_code/abstract_structures/__init__.py delete mode 100644 source_code/abstract_structures/heap/__init__.py delete mode 100644 source_code/abstract_structures/heap/find_N_largest_smallest_items_seq.py delete mode 100644 source_code/abstract_structures/heap/heapify.py delete mode 100644 source_code/abstract_structures/heap/merge_sorted_seqs.py delete mode 100644 source_code/abstract_structures/heap/priority_queue.py delete mode 100644 source_code/abstract_structures/linked_list/__init__.py delete mode 100644 source_code/abstract_structures/linked_list/circular_ll.py delete mode 100644 source_code/abstract_structures/linked_list/double_linked_list_fifo.py delete mode 100644 source_code/abstract_structures/linked_list/find_kth_from_the_end.py delete mode 100644 source_code/abstract_structures/linked_list/linked_list_fifo.py delete mode 100644 source_code/abstract_structures/linked_list/linked_list_lifo.py delete mode 100644 source_code/abstract_structures/linked_list/node.py delete mode 100644 source_code/abstract_structures/linked_list/part_linked_list.py delete mode 100644 source_code/abstract_structures/linked_list/sum_linked_list.py delete mode 100644 source_code/abstract_structures/queues/__init__.py delete mode 100644 source_code/abstract_structures/queues/animal_shelter.py delete mode 100644 source_code/abstract_structures/queues/deque.py delete mode 100644 source_code/abstract_structures/queues/linked_queue.py delete mode 100644 source_code/abstract_structures/queues/palindrome_checker_with_deque.py delete mode 100644 source_code/abstract_structures/queues/queue.py delete mode 100644 source_code/abstract_structures/stacks/__init__.py delete mode 100644 source_code/abstract_structures/stacks/dec2bin_with_stack.py delete mode 100644 source_code/abstract_structures/stacks/linked_stack.py delete mode 100644 source_code/abstract_structures/stacks/reverse_string_with_stack.py delete mode 100644 source_code/abstract_structures/stacks/set_of_stacks.py delete mode 100755 source_code/abstract_structures/stacks/stack.py delete mode 100644 source_code/abstract_structures/stacks/stack_with_min.py delete mode 100644 source_code/abstract_structures/stacks/towers_of_hanoi.py delete mode 100755 source_code/bitwise/bit_array.py delete mode 100755 source_code/bitwise/bitwise.txt delete mode 100755 source_code/bitwise/clear_bits.py delete mode 100755 source_code/bitwise/find_bit_len.py delete mode 100755 source_code/bitwise/find_how_many_1_binary.py delete mode 100755 source_code/bitwise/get_bit.py delete mode 100755 source_code/bitwise/get_float_rep_bin.py delete mode 100755 source_code/bitwise/insert_small_bin_into_big_bin.py delete mode 100755 source_code/bitwise/next_with_same_num_1s.py delete mode 100755 source_code/bitwise/num_bits_to_convert_2_nums.py delete mode 100755 source_code/bitwise/set_bit.py delete mode 100755 source_code/bitwise/swap_in_place.py delete mode 100755 source_code/bitwise/swap_odd_even.py delete mode 100755 source_code/bitwise/update_bit.py delete mode 100755 source_code/builtin_structures/__init__.py delete mode 100755 source_code/builtin_structures/anagram.py delete mode 100755 source_code/builtin_structures/balance.txt delete mode 100755 source_code/builtin_structures/balance_symbols.py delete mode 100755 source_code/builtin_structures/check_if_2_numbers_sum_to_k.py delete mode 100755 source_code/builtin_structures/check_if_3_numbers_sum_to_zero.py delete mode 100755 source_code/builtin_structures/check_non_overlapping_intervals.py delete mode 100755 source_code/builtin_structures/convert_numerical_bases.py delete mode 100755 source_code/builtin_structures/convert_str_2_int.py delete mode 100755 source_code/builtin_structures/count_unique_words_On2.py delete mode 100755 source_code/builtin_structures/delete_duplicate_char_str.py delete mode 100755 source_code/builtin_structures/fibonacci.py delete mode 100755 source_code/builtin_structures/find_0_MxN_replace_cols_rows.py delete mode 100755 source_code/builtin_structures/find_dice_probabilities.py delete mode 100755 source_code/builtin_structures/find_edit_distance.py delete mode 100755 source_code/builtin_structures/find_first_non_repetead_char.py delete mode 100755 source_code/builtin_structures/find_gcd.py delete mode 100755 source_code/builtin_structures/find_if_substr.py delete mode 100755 source_code/builtin_structures/find_if_unique_char.py delete mode 100755 source_code/builtin_structures/find_largest_sum.py delete mode 100755 source_code/builtin_structures/find_longest_inc_subseq.py delete mode 100755 source_code/builtin_structures/find_longest_str_unique_chars.py delete mode 100755 source_code/builtin_structures/find_non_repeating_number.py delete mode 100755 source_code/builtin_structures/find_product_without_division.py delete mode 100755 source_code/builtin_structures/find_top_N_recurring_words.py delete mode 100755 source_code/builtin_structures/find_two_missing_numbers_in_sequence.py delete mode 100755 source_code/builtin_structures/get_float_rep_bin.py delete mode 100755 source_code/builtin_structures/interserction_two_arrays.py delete mode 100755 source_code/builtin_structures/max_subarray_stocks.py delete mode 100755 source_code/builtin_structures/number_of_zeros_factorial.txt delete mode 100755 source_code/builtin_structures/palindrome.py delete mode 100755 source_code/builtin_structures/permutations.py delete mode 100755 source_code/builtin_structures/permutations_alphanumeric.py delete mode 100755 source_code/builtin_structures/primes.py delete mode 100755 source_code/builtin_structures/prod_other_ints.py delete mode 100755 source_code/builtin_structures/ransom_note.py delete mode 100755 source_code/builtin_structures/reverse_string.py delete mode 100755 source_code/builtin_structures/reverse_words.py delete mode 100755 source_code/builtin_structures/rotate_NxN.py delete mode 100755 source_code/builtin_structures/runtime_dicts_with_timeit_module.py delete mode 100755 source_code/builtin_structures/runtime_lists_with_timeit_module.py delete mode 100755 source_code/builtin_structures/search_entry_matrix.py delete mode 100755 source_code/builtin_structures/simple_str_comprension.py delete mode 100755 source_code/builtin_structures/sum_two_numbers_as_strings.py delete mode 100644 source_code/learning/decorator.py delete mode 100644 source_code/searching_and_sorting/searching/__init__.py delete mode 100644 source_code/searching_and_sorting/searching/binary_search.py delete mode 100644 source_code/searching_and_sorting/searching/binary_search_matrix.py delete mode 100644 source_code/searching_and_sorting/searching/find_item_rotated_sorted_array.py delete mode 100644 source_code/searching_and_sorting/searching/find_max_unimodal_array.py delete mode 100644 source_code/searching_and_sorting/searching/find_sqrt_bin_search.py delete mode 100644 source_code/searching_and_sorting/searching/find_str_array_with_empty_str.py delete mode 100644 source_code/searching_and_sorting/searching/find_time_occurence_list.py delete mode 100644 source_code/searching_and_sorting/searching/ordered_sequential_search.py delete mode 100644 source_code/searching_and_sorting/searching/quick_select.py delete mode 100644 source_code/searching_and_sorting/searching/searching_in_a_matrix.py delete mode 100644 source_code/searching_and_sorting/searching/sequential_search.py delete mode 100644 source_code/searching_and_sorting/sorting/1.dat delete mode 100644 source_code/searching_and_sorting/sorting/2.dat delete mode 100644 source_code/searching_and_sorting/sorting/3.dat delete mode 100644 source_code/searching_and_sorting/sorting/__init__.py delete mode 100644 source_code/searching_and_sorting/sorting/bubble_sort.py delete mode 100644 source_code/searching_and_sorting/sorting/count_sort.py delete mode 100644 source_code/searching_and_sorting/sorting/gnome_sort.py delete mode 100644 source_code/searching_and_sorting/sorting/heap.py delete mode 100644 source_code/searching_and_sorting/sorting/heap_sort.py delete mode 100644 source_code/searching_and_sorting/sorting/insertion_sort.py delete mode 100644 source_code/searching_and_sorting/sorting/merge_and_sort_two_arrays.py delete mode 100644 source_code/searching_and_sorting/sorting/merge_sort.py delete mode 100644 source_code/searching_and_sorting/sorting/quick_sort.py delete mode 100644 source_code/searching_and_sorting/sorting/selection_sort.py delete mode 100644 source_code/searching_and_sorting/sorting/sort_anagrams_together.py delete mode 100755 source_code/trees/__init__.py delete mode 100755 source_code/trees/binary_search_tree.py delete mode 100755 source_code/trees/binary_tree.py delete mode 100644 source_code/trees/binary_tree_generators.py delete mode 100755 source_code/trees/bunchclass.py delete mode 100755 source_code/trees/check_ancestor.py delete mode 100755 source_code/trees/check_if_balanced.py delete mode 100755 source_code/trees/check_if_bst.py delete mode 100755 source_code/trees/check_largest_item.py delete mode 100755 source_code/trees/simple_tree.py delete mode 100755 source_code/trees/transversal.py delete mode 100755 source_code/trees/trie.py diff --git a/source_code/USEFUL/advanced/lru_cache.py b/source_code/USEFUL/advanced/lru_cache.py deleted file mode 100644 index 11b451e..0000000 --- a/source_code/USEFUL/advanced/lru_cache.py +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env python3 - -__author__ = "bt3" - - -from functools import lru_cache - - -@lru_cache(maxsize=20) -def fib(n): - if n < 2: - return n - return fib(n-1) + fib(n-2) - - -if __name__ == '__main__': - print([fib(n) for n in range(10)]) - print(fib.cache_info()) diff --git a/source_code/USEFUL/basic_examples/example_OrderedDict.py b/source_code/USEFUL/basic_examples/example_OrderedDict.py deleted file mode 100644 index 89d3291..0000000 --- a/source_code/USEFUL/basic_examples/example_OrderedDict.py +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -from collections import OrderedDict - -def OrderedDict_example(): - ''' show some examples for OrderedDict ''' - ''' keep the order of insertion. - maintains a doubly linked list, so size is more than twice than normal dict''' - - - pairs = [('a', 1), ('b',2), ('c',3)] - - d1 = {} - for key, value in pairs: - if key not in d1: - d1[key] = [] - d1[key].append(value) - for key in d1: - print(key, d1[key]) - - d2 = OrderedDict(pairs) - for key in d2: - print(key, d2[key]) - - -if __name__ == '__main__': - OrderedDict_example() - - diff --git a/source_code/USEFUL/basic_examples/example_args.py b/source_code/USEFUL/basic_examples/example_args.py deleted file mode 100755 index 299035b..0000000 --- a/source_code/USEFUL/basic_examples/example_args.py +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -def simple2(a, *args): - print args - -def simple(*args): - print args - -def simple3(**kwargs): - print kwargs - - -simple(1, 2, 3) -simple2(1, 2, 3) -simple3(x=1, y=2) diff --git a/source_code/USEFUL/basic_examples/example_benchmark_decorator.py b/source_code/USEFUL/basic_examples/example_benchmark_decorator.py deleted file mode 100644 index 749e403..0000000 --- a/source_code/USEFUL/basic_examples/example_benchmark_decorator.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -import random - -def benchmark(func): - import time - def wrapper(*args, **kwargs): - t = time.clock() - res = func(*args, **kwargs) - print("\t%s" % func.__name__, time.clock()-t) - return res - return wrapper - - -@benchmark -def random_tree(n): - temp = [n for n in range(n)] - for i in range(n+1): - temp[random.choice(temp)] = random.choice(temp) - return temp - - -if __name__ == '__main__': - random_tree(10000) - diff --git a/source_code/USEFUL/basic_examples/example_comp_lists.py b/source_code/USEFUL/basic_examples/example_comp_lists.py deleted file mode 100644 index f5c641c..0000000 --- a/source_code/USEFUL/basic_examples/example_comp_lists.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -a = [3, 4, 5, 6, 7] - - -# Filter elements greater than 4 - -# Bad: - -b = [] -for i in a: - if i > 4: - b.append(i) -print b - -# Good: -print [i for i in a if i > 4] - -# Or: -print filter(lambda x: x > 4, a) - - -# Add three to all list members: - -# Bad -b = [] -for i in range(len(a)): - b.append(a[i] + 3) -print b - -# Good: -print [i + 3 for i in a] - -# Or: -print map(lambda i: i + 3, a) \ No newline at end of file diff --git a/source_code/USEFUL/basic_examples/example_counter.py b/source_code/USEFUL/basic_examples/example_counter.py deleted file mode 100644 index bd233e3..0000000 --- a/source_code/USEFUL/basic_examples/example_counter.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -from collections import Counter - -def Counter_example(): - ''' it is a dictionary that maps the items to the number of occurrences ''' - seq1 = [1, 2, 3, 5, 1, 2, 5, 5, 2, 5, 1, 4] - seq_counts = Counter(seq1) - print(seq_counts) - - ''' we can increment manually or use the update() method ''' - seq2 = [1, 2, 3] - seq_counts.update(seq2) - print(seq_counts) - - seq3 = [1, 4, 3] - for key in seq3: - seq_counts[key] += 1 - print(seq_counts) - - ''' also, we can use set operations such as a-b or a+b ''' - seq_counts_2 = Counter(seq3) - print(seq_counts_2) - print(seq_counts + seq_counts_2) - print(seq_counts - seq_counts_2) - -if __name__ == '__main__': - Counter_example() - - diff --git a/source_code/USEFUL/basic_examples/example_decorators.py b/source_code/USEFUL/basic_examples/example_decorators.py deleted file mode 100755 index a64b299..0000000 --- a/source_code/USEFUL/basic_examples/example_decorators.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - - -def logger(func): - def inner(*args): #1 - print "Arguments were: {0}".format(args) - return func(*args) - return inner - -@logger -def foo(x, y): - return x+y - -print foo(1, 2) - - -def sum(func): - s = 0 - for i in func(): - s += i - return s - -@sum -def interate(): - a = [] - for i in range(10): - a.append(i) - return a - -print interate - -# which is the same as -def interate(): - a = [] - for i in range(10): - a.append(i) - return a - -print sum(interate) \ No newline at end of file diff --git a/source_code/USEFUL/basic_examples/example_defaultdict.py b/source_code/USEFUL/basic_examples/example_defaultdict.py deleted file mode 100644 index 6db52b7..0000000 --- a/source_code/USEFUL/basic_examples/example_defaultdict.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -from collections import defaultdict - -def defaultdict_example(): - ''' show some examples for defaultdicts ''' - pairs = {('a', 1), ('b',2), ('c',3)} - - d1 = {} - for key, value in pairs: - if key not in d1: - d1[key] = [] - d1[key].append(value) - print(d1) - - d2 = defaultdict(list) - for key, value in pairs: - d2[key].append(value) - print(d2) - - -if __name__ == '__main__': - defaultdict_example() - - diff --git a/source_code/USEFUL/basic_examples/example_doctest.py b/source_code/USEFUL/basic_examples/example_doctest.py deleted file mode 100644 index 3c379bc..0000000 --- a/source_code/USEFUL/basic_examples/example_doctest.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python - -__author__ = "bt3" - -''' -The doctest module automatically runs any statement beginning with >>> -and compares the following line with the output from the interpreter. - ->>> 1 == 1 -False -''' - -if __name__ == '__main__': - import doctest - doctest.testmod() \ No newline at end of file diff --git a/source_code/USEFUL/basic_examples/example_fractions.py b/source_code/USEFUL/basic_examples/example_fractions.py deleted file mode 100644 index 9bbff22..0000000 --- a/source_code/USEFUL/basic_examples/example_fractions.py +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -from fractions import Fraction - -def rounding_floats(number1, places): - 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) - return a.numerator - - -def test_testing_floats(module_name='this module'): - number1 = 1.25 - number2 = 1 - number3 = -1 - number4 = 5/4 - number6 = 6 - assert(rounding_floats(number1, number2) == 1.2) - assert(rounding_floats(number1*10, number3) == 10) - 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')) - - -if __name__ == '__main__': - test_testing_floats() - - diff --git a/source_code/USEFUL/basic_examples/example_generator.py b/source_code/USEFUL/basic_examples/example_generator.py deleted file mode 100644 index 8256b90..0000000 --- a/source_code/USEFUL/basic_examples/example_generator.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -def interate(x): - for i in range(x): - yield i - -def gen1(): - a = interate(10) - print a.next() - print a.next() - print a.next() - - -def reverse(data): - for i in range(len(data)-1, -1, -1): - yield data[i] - -def gen2(): - for c in reverse('awesome'): - print c - -if __name__ == '__main__': - gen1() - gen2() diff --git a/source_code/USEFUL/basic_examples/example_lambda.py b/source_code/USEFUL/basic_examples/example_lambda.py deleted file mode 100644 index 34ddec3..0000000 --- a/source_code/USEFUL/basic_examples/example_lambda.py +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -test = lambda x: x**2 -print test(3) \ No newline at end of file diff --git a/source_code/USEFUL/basic_examples/example_logging.py b/source_code/USEFUL/basic_examples/example_logging.py deleted file mode 100644 index 5d483fe..0000000 --- a/source_code/USEFUL/basic_examples/example_logging.py +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -import logging - -LOG_FILENAME = 'logging_example.out' -logging.basicConfig(filename=LOG_FILENAME, - level=logging.DEBUG, - ) - -logging.debug('This message should go to the log file') - -f = open(LOG_FILENAME, 'rt') -try: - body = f.read() -finally: - f.close() - -print 'FILE:' -print body \ No newline at end of file diff --git a/source_code/USEFUL/basic_examples/example_numpy.py b/source_code/USEFUL/basic_examples/example_numpy.py deleted file mode 100644 index a2a90a6..0000000 --- a/source_code/USEFUL/basic_examples/example_numpy.py +++ /dev/null @@ -1,60 +0,0 @@ - -#!/usr/bin/env python - -__author__ = "bt3" - -import time -import numpy as np - -def testing_numpy(): - ''' tests many features of numpy ''' - ax = np.array([1,2,3]) - ay = np.array([3,4,5]) - print(ax) - print(ax*2) - print(ax+10) - print(np.sqrt(ax)) - 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) - print(grid2) - 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/source_code/USEFUL/basic_examples/example_open_files.py b/source_code/USEFUL/basic_examples/example_open_files.py deleted file mode 100644 index 28d03e6..0000000 --- a/source_code/USEFUL/basic_examples/example_open_files.py +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -filename = raw_input('Enter a file name: ') -try: - f = open(filename, "r") -except: - print 'There is no file named', filename - diff --git a/source_code/USEFUL/basic_examples/example_pickle.py b/source_code/USEFUL/basic_examples/example_pickle.py deleted file mode 100644 index 2a863ee..0000000 --- a/source_code/USEFUL/basic_examples/example_pickle.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -import pickle - -def import_pickle(filename): - fh = None - try: - fh = open(filename, "rb") - mydict2 = pickle.load(fh) - return mydict2 - - except (EnvironmentError) as err: - print ("{0}: import error: {0}".format(os.path.basename(sys.arg[0]), err)) - return false - - finally: - if fh is not None: - fh.close() - - -def test_import_pickle(): - pkl_file = 'test.dat' - mydict = import_pickle(pkl_file) - print(mydict) - - - -def export_pickle(data, filename='test.dat', compress=False): - - fh = None - try: - if compress: - fh = gzip.open(filename, "wb") # write binary - else: - fh = open(filename, "wb") # compact binary pickle format - pickle.dump(data, fh, pickle.HIGHEST_PROTOCOL) - - except(EnvironmentError, pickle.PickingError) as err: - print("{0}: export error: {1}".format(os.path.basename(sys.argv[0], err))) - return False - - finally: - if fh is not None: - fh.close() - - -def test_export_pickle(): - mydict = {'a': 1, 'b': 2, 'c': 3} - export_pickle(mydict) - - - -if __name__ == '__main__': - test_export_pickle() - test_import_pickle() diff --git a/source_code/USEFUL/basic_examples/example_queue.py b/source_code/USEFUL/basic_examples/example_queue.py deleted file mode 100755 index b51548f..0000000 --- a/source_code/USEFUL/basic_examples/example_queue.py +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -import Queue - -q = Queue.Queue() - -for i in range(10): - q.put(i) - -for i in range(10): - print q.get(i) diff --git a/source_code/USEFUL/basic_examples/example_random.py b/source_code/USEFUL/basic_examples/example_random.py deleted file mode 100644 index e4dc921..0000000 --- a/source_code/USEFUL/basic_examples/example_random.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -import random - -def testing_random(): - ''' testing the module random''' - values = [1, 2, 3, 4] - print(random.choice(values)) - print(random.choice(values)) - 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)) - - -if __name__ == '__main__': - testing_random() - diff --git a/source_code/USEFUL/basic_examples/example_setdefault.py b/source_code/USEFUL/basic_examples/example_setdefault.py deleted file mode 100644 index 6ad5c56..0000000 --- a/source_code/USEFUL/basic_examples/example_setdefault.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -def usual_dict(dict_data): - newdata = {} - for k, v in dict_data: - if k in newdata: - newdata[k].append(v) - else: - newdata[k] = [v] - return newdata - - -def setdefault_dict(dict_data): - newdata = {} - for k, v in dict_data: - newdata.setdefault(k, []).append(v) - return newdata - - -def test_setdef(module_name='this module'): - dict_data = (('key1', 'value1'), - ('key1', 'value2'), - ('key2', 'value3'), - ('key2', 'value4'), - ('key2', 'value5'),) - print(usual_dict(dict_data)) - print(setdefault_dict(dict_data)) - - s = 'Tests in {name} have {con}!' - print(s.format(name=module_name, con='passed')) - - -if __name__ == '__main__': - test_setdef() - diff --git a/source_code/USEFUL/basic_examples/example_sets.py b/source_code/USEFUL/basic_examples/example_sets.py deleted file mode 100644 index ef621d4..0000000 --- a/source_code/USEFUL/basic_examples/example_sets.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -def difference(l1): - """ return the list with duplicate elements removed """ - return list(set(l1)) - -def intersection(l1, l2): - """ return the intersection of two lists """ - return list(set(l1) & set(l2)) - -def union(l1, l2): - """ return the union of two lists """ - return list(set(l1) | set(l2)) - - -def test_sets_operations_with_lists(): - l1 = [1,2,3,4,5,9,11,15] - l2 = [4,5,6,7,8] - l3 = [] - assert(difference(l1) == [1, 2, 3, 4, 5, 9, 11, 15]) - assert(difference(l2) == [8, 4, 5, 6, 7]) - assert(intersection(l1, l2) == [4,5]) - assert(union(l1, l2) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 15]) - assert(difference(l3) == []) - assert(intersection(l3, l2) == l3) - assert(sorted(union(l3, l2)) == sorted(l2)) - print('Tests passed!') - - -if __name__ == '__main__': - test_sets_operations_with_lists() - - - - diff --git a/source_code/USEFUL/basic_examples/example_socket.py b/source_code/USEFUL/basic_examples/example_socket.py deleted file mode 100644 index 0810498..0000000 --- a/source_code/USEFUL/basic_examples/example_socket.py +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env python - - -__author__ = "bt3" - - -import socket - - -def netcat(hostname, port, content): - - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - - s.connect((hostname, port)) - s.sendall(content) - - adata = [] - while 1: - data = s.recv(1024) - if data == '': - break - adata.append(data) - - s.close() - return adata - - - -if __name__ == '__main__': - - PORT = 12345 - HOSTNAME = '54.209.5.48' - - message = netcat(HOSTNAME, PORT, 'Hello!')[1] - print message \ No newline at end of file diff --git a/source_code/USEFUL/basic_examples/example_string_format.py b/source_code/USEFUL/basic_examples/example_string_format.py deleted file mode 100644 index b13add5..0000000 --- a/source_code/USEFUL/basic_examples/example_string_format.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -foo = 'foo' -bar = 'bar' - -print '%s%s' % (foo, bar) # It is OK -print '{0}{1}'.format(foo, bar) # It is better -print '{foo}{bar}'.format(foo=foo, bar=bar) # It is best \ No newline at end of file diff --git a/source_code/USEFUL/basic_examples/example_subprocess.py b/source_code/USEFUL/basic_examples/example_subprocess.py deleted file mode 100644 index b845ca4..0000000 --- a/source_code/USEFUL/basic_examples/example_subprocess.py +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -import subprocess,os - -os.system('ls') -subprocess.call(['ls', '-1'], shell=True) diff --git a/source_code/USEFUL/basic_examples/example_telnet.py b/source_code/USEFUL/basic_examples/example_telnet.py deleted file mode 100644 index 2c46254..0000000 --- a/source_code/USEFUL/basic_examples/example_telnet.py +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env python - - -__author__ = "bt3" - - -from telnetlib import Telnet - - -# examples of telnet connections -PORT = 12345 -HOST = '54.209.5.48' - -# creating connection -tn = Telnet(HOST ,PORT) - -# reading input -msg_in2 = tn.read_all().dec_msg() -tn.read_until(b'psifer text: ') - -# writing outputs -tn.write(msg.encode() + b'\n') diff --git a/source_code/USEFUL/basic_examples/example_testing.py b/source_code/USEFUL/basic_examples/example_testing.py deleted file mode 100644 index 5e900f2..0000000 --- a/source_code/USEFUL/basic_examples/example_testing.py +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - - -def test_doctest(): - ''' - >>> 1 == 1 - False - ''' - pass - -if __name__ == '__main__': - import doctest - doctest.testmod() - -##### - -import unittest - -class BasicsTestCase(unittest.TestCase): - - def test_find_name(self): - self.assertTrue(1 == 1) - self.assertFalse(1 == 2) - -if __name__ == '__main__': - unittest.main() - - - -##### - -# content of test_example.py, run with $ py.test -# -# run tests over the directory -# $ nosetest - - -def func(x): - return x + 1 - -def test_answer(): - assert func(3) == 4 - diff --git a/source_code/USEFUL/basic_examples/example_threads.py b/source_code/USEFUL/basic_examples/example_threads.py deleted file mode 100644 index 8d44859..0000000 --- a/source_code/USEFUL/basic_examples/example_threads.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -import threading - -def worker(num): - """thread worker function""" - print 'Worker: %s' % num - return - -threads = [] -for i in range(5): - t = threading.Thread(target=worker, args=(i,)) - threads.append(t) - t.start() \ No newline at end of file diff --git a/source_code/USEFUL/basic_examples/example_time.py b/source_code/USEFUL/basic_examples/example_time.py deleted file mode 100644 index 78bada7..0000000 --- a/source_code/USEFUL/basic_examples/example_time.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/python - -__author__ = "bt3" - -''' a simple example of how to time a function ''' - -import time - -def sumOfN2(n): - start = time.time() - theSum = 0 - for i in range(1,n+1): - theSum = theSum + i - end = time.time() - return theSum,end-start - - - -if __name__ == '__main__': - n = 5 - print("Sum is %d and required %10.7f seconds"%sumOfN2(n)) - n = 200 - print("Sum is %d and required %10.7f seconds"%sumOfN2(n)) - diff --git a/source_code/USEFUL/dynamic_programming/__init__.py b/source_code/USEFUL/dynamic_programming/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/source_code/USEFUL/dynamic_programming/memo.py b/source_code/USEFUL/dynamic_programming/memo.py deleted file mode 100644 index adff8e2..0000000 --- a/source_code/USEFUL/dynamic_programming/memo.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/python3 - -__author__ = "bt3" - - -from functools import wraps -from do_benchmark import benchmark - -def memo(func): - ''' an example of dynamic programming using a memoizing decorator ''' - cache = {} - @wraps(func) - def wrap(*args): - if args not in cache: - cache[args] = func(*args) - return cache[args] - return wrap - -@memo -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 test_memo(): - n = 50 - # find_fibonacci_seq_rec = memo(find_fibonacci_seq_rec) - # @benchmark - print(find_fibonacci_seq_rec(n)) - - -if __name__ == '__main__': - test_memo() - - - - - - - - - diff --git a/source_code/USEFUL/dynamic_programming/memoized_longest_inc_subseq.py b/source_code/USEFUL/dynamic_programming/memoized_longest_inc_subseq.py deleted file mode 100644 index 4e6434c..0000000 --- a/source_code/USEFUL/dynamic_programming/memoized_longest_inc_subseq.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/python3 - -__author__ = "bt3" - -from itertools import combinations -from bisect import bisect -from memo import memo -from do_benchmark import benchmark - -def naive_longest_inc_subseq(seq): - ''' naive (exponential) solution to the longest increasing subsequence problem ''' - for length in range(len(seq), 0, -1): - for sub in combinations(seq, length): - if list(sub) == sorted(sub): - return len(sub) - - -def longest_inc_subseq1(seq): - ''' an iterative algorithm for the longest increasing subsequence problem ''' - end = [] - for val in seq: - idx = bisect(end, val) - if idx == len(end): end.append(val) - else: end[idx] = val - return len(end) - - -def longest_inc_subseq2(seq): - ''' another iterative algorithm for the longest increasing subsequence problem ''' - L = [1] * len(seq) - for cur, val in enumerate(seq): - for pre in range(cur): - if seq[pre] <= val: - L[cur] = max(L[cur], 1 + L[pre]) - return max(L) - - -def memoized_longest_inc_subseq(seq): - ''' a memoized recursive solution to find the longest increasing subsequence problem ''' - @memo - def L(cur): - res = 1 - for pre in range(cur): - if seq[pre] <= seq[cur]: - res = max(res, 1 + L(pre)) - return res - return max(L(i) for i in range(len(seq))) - - -@benchmark -def test_naive_longest_inc_subseq(): - print(naive_longest_inc_subseq(s1)) - -benchmark -def test_longest_inc_subseq1(): - print(longest_inc_subseq1(s1)) - -@benchmark -def test_longest_inc_subseq2(): - print(longest_inc_subseq2(s1)) - -@benchmark -def test_memoized_longest_inc_subseq(): - print(memoized_longest_inc_subseq(s1)) - - -if __name__ == '__main__': - from random import randrange - s1 = [randrange(100) for i in range(25)] - print(s1) - test_naive_longest_inc_subseq() - test_longest_inc_subseq1() - test_longest_inc_subseq2() - test_memoized_longest_inc_subseq() - - - - - - - - - - - diff --git a/source_code/USEFUL/oop/ShapeClass.py b/source_code/USEFUL/oop/ShapeClass.py deleted file mode 100644 index 055b726..0000000 --- a/source_code/USEFUL/oop/ShapeClass.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - - -import math - -class Point(object): - def __init__(self, x=0, y=0): # self: object reference to the object itself - self.x = x # data attribute - self.y = y - - def distance_from_origin(self): - return math.hypot(self.x, self.y) - - def __eq__(self, other): - return self.x == other.x and self.y == other.y - - def __repr__(self): - return "point ({0.x!r}, {0.y!r})".format(self) - - def __str__(self): # cannot be passed to eval - return "({0.x!r}, {0.y!r})".format(self) - - -class Circle(Point): - - def __init__(self, radius, x=0, y=0): - super().__init__(x,y) # creates and initializes self.x and self.y - self.radius = radius - - def edge_distance_from_origin(self): - return abs(self.distance_from_origin() - self.radius) - - def area(self): - return math.pi*(self.radius**2) - - def circumference(self): - return 2*math.pi*self.radius - - def __eq__(self, other): # let us avoid infinite recursion - return self.radius == other.radius and super().__eq__(other) - - def __repr__(self): - return "circle ({0.radius!r}, {0.x!r})".format(self) - - def __str__(self): - return repr(self) - - - - -if __name__ == '__main__': - a = Point(3,4) - print(a.distance_from_origin()) - c = Circle(3,2,1) - print(c) - print(c.circumference()) - print(c. edge_distance_from_origin()) - - - diff --git a/source_code/USEFUL/oop/__init__.py b/source_code/USEFUL/oop/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/source_code/USEFUL/useful_with_files/change_ext_file.py b/source_code/USEFUL/useful_with_files/change_ext_file.py deleted file mode 100644 index f114c2e..0000000 --- a/source_code/USEFUL/useful_with_files/change_ext_file.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env python - - -__author__ = "bt3" - - -import os -import sys -import shutil - -def change_file_ext(): - """ read a file and an extension from the command line and produces a copy with its extension changed""" - if len(sys.argv) < 2: - print("Usage: change_ext.py filename.old_ext 'new_ext'") - sys.exit() - - name = os.path.splitext(sys.argv[1])[0] + "." + sys.argv[2] - print (name) - - try: - shutil.copyfile(sys.argv[1], name) - except OSError as err: - print (err) - - - -if __name__ == '__main__': - change_file_ext() - - diff --git a/source_code/USEFUL/useful_with_files/count_unique_words_files.py b/source_code/USEFUL/useful_with_files/count_unique_words_files.py deleted file mode 100755 index e1e3de0..0000000 --- a/source_code/USEFUL/useful_with_files/count_unique_words_files.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/python - -__author__ = "bt3" - - -import collections -import string -import sys - -def count_unique_word_file(): - if len(sys.argv) < 2: - print "Usage: python count_unique_word.py NAMEFILE" - - words = collections.defaultdict(int) - strip = string.whitespace + string.punctuation + string.digits + "\"'" - for filename in sys.argv[1:]: - with open(filename) as file: - for line in file: - for word in line.lower().split(): - word = word.strip(strip) - if len(word) > 2: - words[word] = +1 - for word in sorted(words): - print("'{0}' occurs {1} times.".format(word, words[word])) - - -if __name__ == '__main__': - count_unique_word_file() \ No newline at end of file diff --git a/source_code/USEFUL/useful_with_files/count_unique_words_frequency.py b/source_code/USEFUL/useful_with_files/count_unique_words_frequency.py deleted file mode 100755 index 14162d5..0000000 --- a/source_code/USEFUL/useful_with_files/count_unique_words_frequency.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python - -__author__ = "bt3" - - -import collections -import sys - -def count_unique_word_freq(): - return collections.Counter(\ - sys.stdin.read().lower().split()).most_common(n) - - -if __name__ == '__main__': - count_unique_word_freq() \ No newline at end of file diff --git a/source_code/USEFUL/useful_with_files/grep_word_from_files.py b/source_code/USEFUL/useful_with_files/grep_word_from_files.py deleted file mode 100644 index 7dfa064..0000000 --- a/source_code/USEFUL/useful_with_files/grep_word_from_files.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python - - -__author__ = "bt3" - -import sys - -def grep_word_from_files(): - ''' using iterator enumerate to create a grep command ''' - word = sys.argv[1] - for filename in sys.argv[2:]: - with open(filename) as file: - for lino, line in enumerate(file, start=1): - if word in line: - print("{0}:{1}:{2:.40}".format(filename, lino, line.rstrip())) - - -if __name__ == '__main__': - if len(sys.argv) < 2: - print("Usage: grep_word_from_files.py word infile1 [infile2...]") - sys.exit() - else: - grep_word_from_files() - - - - diff --git a/source_code/USEFUL/useful_with_files/remove_blank_lines.py b/source_code/USEFUL/useful_with_files/remove_blank_lines.py deleted file mode 100644 index e9bad3f..0000000 --- a/source_code/USEFUL/useful_with_files/remove_blank_lines.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python - - -__author__ = "bt3" - - - -import os -import sys - -def read_data(filename): - lines = [] - fh = None - try: - fh = open(filename) - for line in fh: - if line.strip(): - lines.append(line) - except (IOError, OSError) as err: - print(err) - finally: - if fh is not None: - fh.close() - return lines - - -def write_data(lines, filename): - fh = None - try: - fh = open(filename, "w") - for line in lines: - fh.write(line) - except (EnvironmentError) as err: - print(err) - finally: - if fh is not None: - fh.close() - - -def remove_blank_lines(): - """ read a list of filenames on the command line and for each one produces another file with the same content but with no blank lines """ - - if len(sys.argv) < 2: - print ("Usage: noblank.py infile1 [infile2...]") - - for filename in sys.argv[1:]: - lines = read_data(filename) - if lines: - write_data(lines, filename) - - -if __name__ == '__main__': - remove_blank_lines() - diff --git a/source_code/abstract_structures/HashTable.py b/source_code/abstract_structures/HashTable.py deleted file mode 100755 index 2dad275..0000000 --- a/source_code/abstract_structures/HashTable.py +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -class HashTable(object): - def __init__(self, slots=10): - self.slots = slots - self.table = [] - self.create_table() - - def hash_key(self, value): - return hash(value)%self.slots - - def create_table(self): - for i in range(self.slots): - self.table.append([]) - - def add_item(self, value): - key = self.hash_key(value) - self.table[key].append(value) - - def print_table(self): - for key in range(len(self.table)): - print "Key is %s, value is %s." %(key, self.table[key]) - - def find_item(self, item): - pos = self.hash_key(item) - if item in self.table[pos]: - return True - else: - return False - -if __name__ == '__main__': - dic = HashTable(5) - for i in range(1, 40, 2): - dic.add_item(i) - - dic.print_table() - assert(dic.find_item(20) == False) - assert(dic.find_item(21) == True) diff --git a/source_code/abstract_structures/Queue.py b/source_code/abstract_structures/Queue.py deleted file mode 100755 index eff7e91..0000000 --- a/source_code/abstract_structures/Queue.py +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env python -# Time: 5 min - -__author__ = "bt3" - - -class Queue(object): - def __init__(self): - self.enq = [] - self.deq = [] - - def enqueue(self, item): - return self.enq.append(item) - - def deque(self): - if not self.deq: - while self.enq: - self.deq.append(self.enq.pop()) - return self.deq.pop() - - def peak(self): - if not self.deq: - while self.enq: - self.deq.append(self.enq.pop()) - if self.deq: - return self.deq[-1] - - def size(self): - return len(self.enq) + len(self.deq) - - def isempty(self): - return not (self.enq + self.deq) - -if __name__ == '__main__': - q = Queue() - for i in range(1,11): - q.enqueue(i) - print 'Size:', q.size() - print 'Is empty?', q.isempty() - print 'Peak: ', q.peak() - print - print 'Dequeuing...' - for i in range(10): - print q.deque() - print 'Size:', q.size() - print 'Is empty?', q.isempty() - print 'Peak: ', q.peak() \ No newline at end of file diff --git a/source_code/abstract_structures/Stack.py b/source_code/abstract_structures/Stack.py deleted file mode 100755 index ba36110..0000000 --- a/source_code/abstract_structures/Stack.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -class Stack(object): - def __init__(self): - self.content = [] - self.min_array = [] - self.min = float('inf') - - def push(self, value): - if value < self.min: - self.min = value - - self.content.append(value) - self.min_array.append(self.min) - - def pop(self): - if self.content: - value = self.content.pop() - self.min_array.pop() - if self.min_array: - self.min = self.min_array[-1] - return value - else: - return 'Empty List. ' - - def find_min(self): - if self.min_array: - return self.min_array[-1] - else: - return 'No min value for empty list.' - - def size(self): - return len(self.content) - - def isEmpty(self): - return not bool(self.content) - - def peek(self): - if self.content: - return self.content[-1] - else: - print('Stack is empty.') - - - def __repr__(self): - return '{}'.format(self.content) - - -if __name__ == '__main__': - q = Stack() - - for i in range(15,20): - q.push(i) - for i in range(10,5,-1): - q.push(i) - - - - for i in range(1, 13): - print q.pop(), q.find_min() \ No newline at end of file diff --git a/source_code/abstract_structures/__init__.py b/source_code/abstract_structures/__init__.py deleted file mode 100755 index be4c726..0000000 --- a/source_code/abstract_structures/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__all__=["hash_tables", "heap", "linked_list", "queues", "stacks"] \ No newline at end of file diff --git a/source_code/abstract_structures/heap/__init__.py b/source_code/abstract_structures/heap/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/source_code/abstract_structures/heap/find_N_largest_smallest_items_seq.py b/source_code/abstract_structures/heap/find_N_largest_smallest_items_seq.py deleted file mode 100644 index 18042fe..0000000 --- a/source_code/abstract_structures/heap/find_N_largest_smallest_items_seq.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/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) - -def find_smallest_items_seq_heap(seq): - ''' find the smallest items in a sequence using heapify first''' - ''' heap[0] is always the smallest item ''' - ''' 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) - -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:] - - -def test_find_N_largest_smallest_items_seq(module_name='this module'): - seq = [1, 3, 2, 8, 6, 10, 9] - N = 3 - assert(find_N_largest_items_seq(seq, N) == [10, 9, 8]) - assert(find_N_largest_items_seq_sorted(seq, N) == [8, 9, 10]) - assert(find_N_smallest_items_seq(seq, N) == [1,2,3]) - 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')) - - -if __name__ == '__main__': - test_find_N_largest_smallest_items_seq() - diff --git a/source_code/abstract_structures/heap/heapify.py b/source_code/abstract_structures/heap/heapify.py deleted file mode 100644 index aa1d86b..0000000 --- a/source_code/abstract_structures/heap/heapify.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/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) - - def parent(self, i): - return i >> 1 - - def left_child(self, i): - return (i << 1) + 1 - - 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) - 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: - self.data[i], self.data[largest] = self.data[largest], self.data[i] - self.__max_heapify__(largest) - - def extract_max(self): - n = len(self.data) - max_element = self.data[0] - self.data[0] = self.data[n - 1] - self.data = self.data[:n - 1] - self.__max_heapify__(0) - return max_element - - -def test_Heapify(): - l1 = [3, 2, 5, 1, 7, 8, 2] - h = Heapify(l1) - assert(h.extract_max() == 8) - -if __name__ == '__main__': - test_Heapify() diff --git a/source_code/abstract_structures/heap/merge_sorted_seqs.py b/source_code/abstract_structures/heap/merge_sorted_seqs.py deleted file mode 100644 index 1d211b2..0000000 --- a/source_code/abstract_structures/heap/merge_sorted_seqs.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -import heapq - - -def merge_sorted_seq(seq1, seq2): - ''' merge two sorted sequences with little ovehead. the result - will be sorted, which is different of doing just +''' - result = [] - for c in heapq.merge(seq1, seq2): - result.append(c) - return result - - -def test_merge_sorted_seq(module_name='this module'): - seq1 = [1, 2, 3, 8, 9, 10] - seq2 = [2, 3, 4, 5, 6, 7, 9] - seq3 = seq1 + seq2 - assert(merge_sorted_seqseq1, seq2) == sorted(seq3)) - - - -if __name__ == '__main__': - test_merge_sorted_seq() - diff --git a/source_code/abstract_structures/heap/priority_queue.py b/source_code/abstract_structures/heap/priority_queue.py deleted file mode 100644 index 5aed910..0000000 --- a/source_code/abstract_structures/heap/priority_queue.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -import heapq - -class PriorityQueue(object): - ''' implements a priority queue class ''' - 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)) - self._index += 1 - - def pop(self): - return heapq.heappop(self._queue)[-1] - - -class Item: - def __init__(self, name): - self.name = name - def __repr__(self): - return "Item({!r})".format(self.name) - - -def test_PriorityQueue(): - ''' push and pop are all O(logN) ''' - q = PriorityQueue() - q.push(Item('test1'), 1) - q.push(Item('test2'), 4) - q.push(Item('test3'), 3) - assert(str(q.pop()) == "Item('test2')") - - -if __name__ == '__main__': - test_PriorityQueue() - - diff --git a/source_code/abstract_structures/linked_list/__init__.py b/source_code/abstract_structures/linked_list/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/source_code/abstract_structures/linked_list/circular_ll.py b/source_code/abstract_structures/linked_list/circular_ll.py deleted file mode 100644 index fdeb026..0000000 --- a/source_code/abstract_structures/linked_list/circular_ll.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' implement a function to see whether a linked list is circular. - To implement this, we just need two pointers with different - paces (for example, one goes twice faster)''' - -from linked_list_fifo import LinkedListFIFO -from node import Node - - -class cicularLinkedListFIFO(LinkedListFIFO): - def _add(self, value): - self.length += 1 - node = Node(value, self.head) - if self.tail: - self.tail.pointer = node - self.tail = node - - - - -def isCircularll(ll): - p1 = ll.head - p2 = ll.head - - while p2: - try: - p1 = p1.pointer - p2 = p2.pointer.pointer - except: - break - - if p1 == p2: - return True - return False - - - -if __name__ == '__main__': - - ll = LinkedListFIFO() - for i in range(10): - ll.addNode(i) - ll._printList() - - print(isCircularll(ll)) - - lcirc = cicularLinkedListFIFO() - for i in range(10): - lcirc.addNode(i) - print(isCircularll(lcirc)) - diff --git a/source_code/abstract_structures/linked_list/double_linked_list_fifo.py b/source_code/abstract_structures/linked_list/double_linked_list_fifo.py deleted file mode 100644 index 094b283..0000000 --- a/source_code/abstract_structures/linked_list/double_linked_list_fifo.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python - -__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.''' - -from linked_list_fifo import LinkedListFIFO - - -class dNode(object): - def __init__(self, value=None, pointer=None, previous=None): - self.value = value - self.pointer = pointer - self.previous = previous - - -class dLinkList(LinkedListFIFO): - - def printListInverse(self): - node = self.tail - while node: - print(node.value) - try: - node = node.previous - except: - break - - def _add(self, value): - self.length += 1 - node = dNode(value) - if self.tail: - self.tail.pointer = node - node.previous = self.tail - self.tail = node - - def _delete(self, node): - self.length -= 1 - node.previous.pointer = node.pointer - if not node.pointer: - self.tail = node.previous - - def _find(self, index): - node = self.head - i = 0 - while node and i < index: - node = node.pointer - i += 1 - return node, i - - # delete nodes in general - def deleteNode(self, index): - if not self.head or not self.head.pointer: - self._deleteFirst() - else: - node, i = self._find(index) - if i == index: - self._delete(node) - else: - print('Node with index {} not found'.format(index)) - - -if __name__ == '__main__': - - from collections import Counter - - ll = dLinkList() - for i in range(1, 5): - ll.addNode(i) - print('Printing the list...') - ll._printList() - print('Now, printing the list inversely...') - ll.printListInverse() - print('The list after adding node with value 15') - ll._add(15) - ll._printList() - print("The list after deleting everything...") - for i in range(ll.length-1, -1, -1): - ll.deleteNode(i) - ll._printList() - diff --git a/source_code/abstract_structures/linked_list/find_kth_from_the_end.py b/source_code/abstract_structures/linked_list/find_kth_from_the_end.py deleted file mode 100644 index 8fd0cba..0000000 --- a/source_code/abstract_structures/linked_list/find_kth_from_the_end.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' Find the mth-to-last element of a linked list. - One option is having two pointers, separated by m. P1 start at the roots - (p1 = self.root) and p2 is m-behinf pointer, which is created when p1 is at m. - When p1 reach the end, p2 is the node. ''' - -from linked_list_fifo import LinkedListFIFO -from node import Node - - -class LinkedListFIFO_find_kth(LinkedListFIFO): - - - def find_kth_to_last(self, k): - p1, p2 = self.head, self.head - i = 0 - while p1: - if i > k: - try: - p2 = p2.pointer - except: - break - p1 = p1.pointer - i += 1 - return p2.value - - - -if __name__ == '__main__': - ll = LinkedListFIFO_find_kth() - for i in range(1, 11): - ll.addNode(i) - print('The Linked List:') - print(ll._printList()) - k = 3 - k_from_last = ll.find_kth_to_last(k) - print("The %dth element to the last of the LL of size %d is %d" %(k, ll.length, k_from_last)) - diff --git a/source_code/abstract_structures/linked_list/linked_list_fifo.py b/source_code/abstract_structures/linked_list/linked_list_fifo.py deleted file mode 100644 index 9a983a9..0000000 --- a/source_code/abstract_structures/linked_list/linked_list_fifo.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env python - -__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): - self.head = None - self.length = 0 - self.tail = None # this is different from ll lifo - - def _printList(self): - node = self.head - while node: - print(node.value) - node = node.pointer - - def _addFirst(self, value): - self.length = 1 - node = Node(value) - self.head = node - self.tail = node - - def _deleteFirst(self): - self.length = 0 - self.head = None - self.tail = None - print('The list is empty.') - - def _add(self, value): - self.length += 1 - node = Node(value) - if self.tail: - self.tail.pointer = node - self.tail = node - - def addNode(self, value): - if not self.head: - self._addFirst(value) - else: - self._add(value) - - def _find(self, index): - prev = None - node = self.head - i = 0 - while node and i < index: - prev = node - node = node.pointer - i += 1 - return node, prev, i - - def deleteNode(self, index): - if not self.head or not self.head.pointer: - self._deleteFirst() - else: - node, prev, i = self._find(index) - if i == index and node: - self.length -= 1 - if i == 0 or not prev : - self.head = node.pointer - else: - prev.pointer = node.pointer - if not self.tail == node: - self.tail = prev - else: - print('Node with index {} not found'.format(index)) - - -if __name__ == '__main__': - ll = LinkedListFIFO() - for i in range(1, 5): - ll.addNode(i) - print('The list is:') - ll._printList() - print('The list after deleting node with index 2:') - ll.deleteNode(2) - ll._printList() - print('The list after adding node with value 15') - ll._add(15) - ll._printList() - print("The list after deleting everything...") - for i in range(ll.length-1, -1, -1): - ll.deleteNode(i) - ll._printList() diff --git a/source_code/abstract_structures/linked_list/linked_list_lifo.py b/source_code/abstract_structures/linked_list/linked_list_lifo.py deleted file mode 100644 index b75b621..0000000 --- a/source_code/abstract_structures/linked_list/linked_list_lifo.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' Implement a unordered linked list, i.e. a LIFO linked list (like a stack) ''' - -from node import Node - -class LinkedListLIFO(object): - - def __init__(self): - self.head = None - self.length = 0 - - def _printList(self): - node = self.head - while node: - print(node.value) - node = node.pointer - - def _delete(self, prev, node): - self.length -= 1 - if not prev: - self.head = node.pointer - else: - prev.pointer = node.pointer - - def _add(self, value): - self.length += 1 - self.head = Node(value, self.head) - - def _find(self, index): - prev = None - node = self.head - i = 0 - while node and i < index: - prev = node - node = node.pointer - i += 1 - return node, prev, i - - def _find_by_value(self, value): - prev = None - node = self.head - found = 0 - while node and not found: - if node.value == value: - found = True - else: - prev = node - node = node.pointer - return node, prev, found - - def deleteNode(self, index): - node, prev, i = self._find(index) - if index == i: - self._delete(prev, node) - else: - print('Node with index {} not found'.format(index)) - - def deleteNodeByValue(self, value): - node, prev, found = self._find_by_value(value) - if found: - self._delete(prev, node) - else: - print('Node with value {} not found'.format(value)) - - - - -if __name__ == '__main__': - ll = LinkedListLIFO() - for i in range(1, 5): - ll._add(i) - print('The list is:') - ll._printList() - print('The list after deleting node with index 2:') - ll.deleteNode(2) - ll._printList() - print('The list after deleting node with value 3:') - ll.deleteNodeByValue(2) - ll._printList() - print('The list after adding node with value 15') - ll._add(15) - ll._printList() - print("The list after deleting everything...") - for i in range(ll.length-1, -1, -1): - ll.deleteNode(i) - ll._printList() diff --git a/source_code/abstract_structures/linked_list/node.py b/source_code/abstract_structures/linked_list/node.py deleted file mode 100644 index 0a2d459..0000000 --- a/source_code/abstract_structures/linked_list/node.py +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -class Node(object): - def __init__(self, value=None, pointer=None): - self.value = value - self.pointer = pointer - - def getData(self): - return self.value - - def getNext(self): - return self.pointer - - def setData(self, newdata): - self.value = newdata - - def setNext(self, newpointer): - self.pointer = newpointer - - - -if __name__ == '__main__': - L = Node("a", Node("b", Node("c", Node("d")))) - assert(L.pointer.pointer.value=='c') - - print(L.getData()) - print(L.getNext().getData()) - L.setData('aa') - L.setNext(Node('e')) - print(L.getData()) - print(L.getNext().getData()) diff --git a/source_code/abstract_structures/linked_list/part_linked_list.py b/source_code/abstract_structures/linked_list/part_linked_list.py deleted file mode 100644 index d178b27..0000000 --- a/source_code/abstract_structures/linked_list/part_linked_list.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python - -__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:''' - - -from linked_list_fifo import LinkedListFIFO -from node import Node - - -def partList(ll, n): - - more = LinkedListFIFO() - less = LinkedListFIFO() - - node = ll.head - - while node: - item = node.value - - if item < n: - less.addNode(item) - - elif item > n: - more.addNode(item) - - node = node.pointer - - less.addNode(n) - nodemore = more.head - - while nodemore: - less.addNode(nodemore.value) - nodemore = nodemore.pointer - - return less - - - - -if __name__ == '__main__': - - ll = LinkedListFIFO() - l = [6, 7, 3, 4, 9, 5, 1, 2, 8] - for i in l: - ll.addNode(i) - - print('Before Part') - ll._printList() - - print('After Part') - newll = partList(ll, 6) - newll._printList() - - diff --git a/source_code/abstract_structures/linked_list/sum_linked_list.py b/source_code/abstract_structures/linked_list/sum_linked_list.py deleted file mode 100644 index 4cf14cb..0000000 --- a/source_code/abstract_structures/linked_list/sum_linked_list.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python - -__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 - two linked lists represent, returning a third list representing the sum:''' - - -from linked_list_fifo import LinkedListFIFO -from node import Node - - -class LinkedListFIFOYield(LinkedListFIFO): - - # print each node's value, starting from the head - def _printList(self): - node = self.head - while node: - yield(node.value) - node = node.pointer - - - -def sumlls(l1, l2): - - lsum = LinkedListFIFOYield() - dig1 = l1.head - dig2 = l2.head - pointer = 0 - - while dig1 and dig2: - d1 = dig1.value - d2 = dig2.value - sum_d = d1 + d2 + pointer - if sum_d > 9: - pointer = sum_d//10 - lsum.addNode(sum_d%10) - - else: - lsum.addNode(sum_d) - pointer = 0 - - dig1 = dig1.pointer - dig2 = dig2.pointer - - if dig1: - sum_d = pointer + dig1.value - if sum_d > 9: - lsum.addNode(sum_d%10) - else: - lsum.addNode(sum_d) - dig1 = dig1.pointer - - if dig2: - sum_d = pointer + dig2.value - if sum_d > 9: - lsum.addNode(sum_d%10) - else: - lsum.addNode(sum_d) - dig2 = dig2.pointer - - return lsum - - - - - - -if __name__ == '__main__': - l1 = LinkedListFIFOYield() # 2671 - l1.addNode(1) - l1.addNode(7) - l1.addNode(6) - l1.addNode(2) - - l2 = LinkedListFIFOYield() # 455 - l2.addNode(5) - l2.addNode(5) - l2.addNode(4) - - lsum = sumlls(l1, l2) - l = list(lsum._printList()) - for i in reversed(l): - print i diff --git a/source_code/abstract_structures/queues/__init__.py b/source_code/abstract_structures/queues/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/source_code/abstract_structures/queues/animal_shelter.py b/source_code/abstract_structures/queues/animal_shelter.py deleted file mode 100644 index 6208289..0000000 --- a/source_code/abstract_structures/queues/animal_shelter.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -""" A class for an animal shelter with two queues""" - - -class Node(object): - def __init__(self, animalName=None, animalKind=None, pointer=None): - self.animalName = animalName - self.animalKind = animalKind - self.pointer = pointer - self.timestamp = 0 - - - -class AnimalShelter(object): - def __init__(self): - self.headCat = None - self.headDog = None - self.tailCat = None - self.tailDog = None - self.animalNumber = 0 - - - # Queue any animal - - def enqueue(self, animalName, animalKind): - self.animalNumber += 1 - newAnimal = Node(animalName, animalKind) - newAnimal.timestamp = self.animalNumber - - if animalKind == 'cat': - if not self.headCat: - self.headCat = newAnimal - if self.tailCat: - self.tailCat.pointer = newAnimal - self.tailCat = newAnimal - - elif animalKind == 'dog': - if not self.headDog: - self.headDog = newAnimal - if self.tailDog: - self.tailDog.pointer = newAnimal - self.tailDog = newAnimal - - - # Dequeue methods - - def dequeueDog(self): - if self.headDog: - newAnimal = self.headDog - self.headDog = newAnimal.pointer - return str(newAnimal.animalName) - else: - return 'No Dogs!' - - - def dequeueCat(self): - if self.headCat: - newAnimal = self.headCat - self.headCat = newAnimal.pointer - return str(newAnimal.animalName) - else: - return 'No Cats!' - - - def dequeueAny(self): - if self.headCat and not self.headDog: - return self.dequeueCat() - elif self.headDog and not self.headCat: - return self.dequeueDog() - elif self.headDog and self.headCat: - if self.headDog.timestamp < self.headCat.timestamp: - return self.dequeueDog() - else: - return self.dequeueCat() - else: - return ('No Animals!') - - - - def _print(self): - print("Cats:") - cats = self.headCat - while cats: - print(cats.animalName, cats.animalKind) - cats = cats.pointer - print("Dogs:") - dogs = self.headDog - while dogs: - print(dogs.animalName, dogs.animalKind) - dogs = dogs.pointer - - -if __name__ == '__main__': - - qs = AnimalShelter() - qs.enqueue('bob', 'cat') - qs.enqueue('mia', 'cat') - qs.enqueue('yoda', 'dog') - qs.enqueue('wolf', 'dog') - qs._print() - - print("Deque one dog and one cat...") - qs.dequeueDog() - qs.dequeueCat() - qs._print() diff --git a/source_code/abstract_structures/queues/deque.py b/source_code/abstract_structures/queues/deque.py deleted file mode 100644 index ede3e53..0000000 --- a/source_code/abstract_structures/queues/deque.py +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -''' a class for a double ended queue (also inefficient) ''' - -from queue import Queue - -class Deque(Queue): - - def enqueue_back(self, item): - self.items.append(item) - - def dequeue_front(self): - return self.items.pop(0) - - - -if __name__ == '__main__': - queue = Deque() - 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) - - print("\nNow using the dequeue methods...") - print("Dequeue from front...", queue.dequeue_front()) - print("Queue peek: ", queue.peek()) - print(queue) - print("Queue from back...") - queue.enqueue_back(50) - print("Queue peek: ", queue.peek()) - print(queue) diff --git a/source_code/abstract_structures/queues/linked_queue.py b/source_code/abstract_structures/queues/linked_queue.py deleted file mode 100644 index ca2aafd..0000000 --- a/source_code/abstract_structures/queues/linked_queue.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -''' Queue acts as a container for nodes (objects) that are inserted and removed according FIFO''' - - -class Node(object): - def __init__(self, value=None, pointer=None): - self.value = value - self.pointer = None - - -class LinkedQueue(object): - def __init__(self): - self.head = None - self.tail = None - - - def isEmpty(self): - return not bool(self.head) - - - def dequeue(self): - if self.head: - value = self.head.value - self.head = self.head.pointer - return value - else: - print('Queue is empty, cannot dequeue.') - - - def enqueue(self, value): - node = Node(value) - if not self.head: - self.head = node - self.tail = node - else: - if self.tail: - self.tail.pointer = node - self.tail = node - - - def size(self): - node = self.head - num_nodes = 0 - while node: - num_nodes += 1 - node = node.pointer - return num_nodes - - - def peek(self): - return self.head.value - - - def _print(self): - node = self.head - while node: - print(node.value) - node = node.pointer - - - - -if __name__ == '__main__': - queue = LinkedQueue() - print("Is the queue empty? ", queue.isEmpty()) - print("Adding 0 to 10 in the queue...") - for i in range(10): - queue.enqueue(i) - print("Is the queue empty? ", queue.isEmpty()) - queue._print() - - print("Queue size: ", queue.size()) - print("Queue peek : ", queue.peek()) - print("Dequeue...", queue.dequeue()) - print("Queue peek: ", queue.peek()) - queue._print() - diff --git a/source_code/abstract_structures/queues/palindrome_checker_with_deque.py b/source_code/abstract_structures/queues/palindrome_checker_with_deque.py deleted file mode 100644 index af14321..0000000 --- a/source_code/abstract_structures/queues/palindrome_checker_with_deque.py +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -""" Using our deque class and Python's deque class """ - - -import string -import collections - -from deque import Deque - - -STRIP = string.whitespace + string.punctuation + "\"'" - -def palindrome_checker_with_deque(str1): - - d1 = Deque() - d2 = collections.deque() - - for s in str1.lower(): - if s not in STRIP: - d2.append(s) - d1.enqueue(s) - - - eq1 = True - while d1.size() > 1 and eq1: - if d1.dequeue_front() != d1.dequeue(): - eq1 = False - - eq2 = True - while len(d2) > 1 and eq2: - if d2.pop() != d2.popleft(): - eq2 = False - - return eq1, eq2 - - - - -if __name__ == '__main__': - str1 = 'Madam Im Adam' - str2 = 'Buffy is a Slayer' - print(palindrome_checker_with_deque(str1)) - print(palindrome_checker_with_deque(str2)) \ No newline at end of file diff --git a/source_code/abstract_structures/queues/queue.py b/source_code/abstract_structures/queues/queue.py deleted file mode 100644 index f08c8b4..0000000 --- a/source_code/abstract_structures/queues/queue.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -class Queue(object): - - def __init__(self): - self.in_stack = [] - self.out_stack = [] - - 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/source_code/abstract_structures/stacks/__init__.py b/source_code/abstract_structures/stacks/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/source_code/abstract_structures/stacks/dec2bin_with_stack.py b/source_code/abstract_structures/stacks/dec2bin_with_stack.py deleted file mode 100644 index 31dc066..0000000 --- a/source_code/abstract_structures/stacks/dec2bin_with_stack.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -'''transform a decimal number to a binary number with a stack ''' - - -from stack import Stack - -def dec2bin_with_stack(decnum): - - s = Stack() - str_aux = '' - - while decnum > 0: - dig = decnum % 2 - decnum = decnum//2 - s.push(dig) - - while not s.isEmpty(): - str_aux += str(s.pop()) - - return str_aux - - - -if __name__ == '__main__': - decnum = 9 - assert(dec2bin_with_stack(decnum) == '1001') diff --git a/source_code/abstract_structures/stacks/linked_stack.py b/source_code/abstract_structures/stacks/linked_stack.py deleted file mode 100644 index 23a4ad6..0000000 --- a/source_code/abstract_structures/stacks/linked_stack.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -""" A stack made of linked list""" - - -class Node(object): - def __init__(self, value=None, pointer=None): - self.value = value - self.pointer = pointer - - -class Stack(object): - def __init__(self): - self.head = None - - def isEmpty(self): - return not bool(self.head) - - def push(self, item): - self.head = Node(item, self.head) - - - def pop(self): - if self.head: - node = self.head - self.head = node.pointer - return node.value - else: - print('Stack is empty.') - - - def peek(self): - if self.head: - return self.head.value - else: - print('Stack is empty.') - - - def size(self): - node = self.head - count = 0 - while node: - count +=1 - node = node.pointer - return count - - - def _printList(self): - node = self.head - while node: - print(node.value) - node = node.pointer - - - -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) - stack._printList() - 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()) - stack._printList() diff --git a/source_code/abstract_structures/stacks/reverse_string_with_stack.py b/source_code/abstract_structures/stacks/reverse_string_with_stack.py deleted file mode 100644 index 014ab9b..0000000 --- a/source_code/abstract_structures/stacks/reverse_string_with_stack.py +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' Uses a stack to reverse a string ''' - -from stack import Stack - -def reverse_string_with_stack(str1): - - s = Stack() - revStr = '' - - for c in str1: - s.push(c) - - while not s.isEmpty(): - revStr += s.pop() - - return revStr - - - -if __name__ == '__main__': - str1 = 'Buffy is a Slayer!' - print(str1) - print(reverse_string_with_stack(str1)) - - - diff --git a/source_code/abstract_structures/stacks/set_of_stacks.py b/source_code/abstract_structures/stacks/set_of_stacks.py deleted file mode 100644 index bfe5bde..0000000 --- a/source_code/abstract_structures/stacks/set_of_stacks.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -""" define a class for a set of stacks """ - -from stack import Stack - -class SetOfStacks(Stack): - def __init__(self, capacity=4): - self.setofstacks = [] - self.items = [] - self.capacity = capacity - - - def push(self, value): - if self.size() >= self.capacity: - self.setofstacks.append(self.items) - self.items = [] - self.items.append(value) - - - def pop(self): - value = self.items.pop() - if self.isEmpty() and self.setofstacks: - self.items = self.setofstacks.pop() - return value - - - def sizeStack(self): - return len(self.setofstacks)*self.capacity + self.size() - - - def __repr__(self): - aux = [] - for s in self.setofstacks: - aux.extend(s) - aux.extend(self.items) - return '{}'.format(aux) - - - -if __name__ == '__main__': - capacity = 5 - stack = SetOfStacks(capacity) - 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) - print("Stack size: ", stack.sizeStack()) - print("Stack peek : ", stack.peek()) - print("Pop...", stack.pop()) - print("Stack peek: ", stack.peek()) - print("Is the stack empty? ", stack.isEmpty()) - print(stack) diff --git a/source_code/abstract_structures/stacks/stack.py b/source_code/abstract_structures/stacks/stack.py deleted file mode 100755 index 869ecf3..0000000 --- a/source_code/abstract_structures/stacks/stack.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python - -# copy of the class ../Stack.py - -__author__ = "bt3" - - -class Stack(object): - def __init__(self): - self.content = [] - self.min_array = [] - self.min = float('inf') - - def push(self, value): - if value < self.min: - self.min = value - - self.content.append(value) - self.min_array.append(self.min) - - def pop(self): - if self.content: - value = self.content.pop() - self.min_array.pop() - if self.min_array: - self.min = self.min_array[-1] - return value - else: - return 'Empty List. ' - - def find_min(self): - if self.min_array: - return self.min_array[-1] - else: - return 'No min value for empty list.' - - def size(self): - return len(self.content) - - def isEmpty(self): - return not bool(self.content) - - def peek(self): - if self.content: - return self.content[-1] - else: - print('Stack is empty.') - - - def __repr__(self): - return '{}'.format(self.content) - - -if __name__ == '__main__': - q = Stack() - - for i in range(15,20): - q.push(i) - for i in range(10,5,-1): - q.push(i) - - - - for i in range(1, 13): - print q.pop(), q.find_min() \ No newline at end of file diff --git a/source_code/abstract_structures/stacks/stack_with_min.py b/source_code/abstract_structures/stacks/stack_with_min.py deleted file mode 100644 index 83a16ed..0000000 --- a/source_code/abstract_structures/stacks/stack_with_min.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -''' A stack with a minimum lookup ''' - -from stack import Stack - - -class NodeWithMin(object): - def __init__(self, value=None, minimum=None): - self.value = value - self.minimum = minimum - - -class StackMin(Stack): - def __init__(self): - self.items = [] - self.minimum = None - - - def push(self, value): - if self.isEmpty() or self.minimum > value: - self.minimum = value - self.items.append(NodeWithMin(value, self.minimum)) - - - def peek(self): - return self.items[-1].value - - - def peekMinimum(self): - return self.items[-1].minimum - - - def pop(self): - item = self.items.pop() - if item: - if item.value == self.minimum: - self.minimum = self.peekMinimum() - return item.value - else: - print("Stack is empty.") - - def __repr__(self): - aux = [] - for i in self.items: - aux.append(i.value) - return '{}'.format(aux) - - - -if __name__ == '__main__': - stack = StackMin() - print("Is the stack empty? ", stack.isEmpty()) - print("Adding 0 to 10 in the stack...") - for i in range(10,3, -1): - stack.push(i) - print(stack) - - print("Stack size: ", stack.size()) - print("Stack peek and peekMinimum : ", stack.peek(), stack.peekMinimum()) - print("Pop...", stack.pop()) - print("Stack peek and peekMinimum : ", stack.peek(), stack.peekMinimum()) - print("Is the stack empty? ", stack.isEmpty()) - print(stack) - - for i in range(5, 1, -1): - stack.push(i) - print(stack) - - print("Stack size: ", stack.size()) - print("Stack peek and peekMinimum : ", stack.peek(), stack.peekMinimum()) - print("Pop...", stack.pop()) - print("Stack peek and peekMinimum : ", stack.peek(), stack.peekMinimum()) - print("Is the stack empty? ", stack.isEmpty()) - print(stack) diff --git a/source_code/abstract_structures/stacks/towers_of_hanoi.py b/source_code/abstract_structures/stacks/towers_of_hanoi.py deleted file mode 100644 index f424faa..0000000 --- a/source_code/abstract_structures/stacks/towers_of_hanoi.py +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - - -""" Implement the 'towers of hanoi'""" - -from linked_stack import Stack, Node - - -def moveTop(s1, s3): - - s3.append(s1.pop()) - - -def moveDisks(n, s1, s3, s2): - - if n < 1: return - moveDisks(n - 1, s1, s2, s3) - moveTop(s1, s3) - moveDisks(n -1, s2, s3, s1) - - - -def towersOfHanoi(n): - s1 = [x+1 for x in range(n)] - s2 = [] - s3 = [] - print('The first stick is {0} and the third stick has {1}'.format(s1, s3)) - - moveDisks(n, s1, s3, s2) - - print('The first stick is {0} and the third stick has {1}'.format(s1, s3)) - - return s3 - - - -if __name__ == '__main__': - towersOfHanoi(6) diff --git a/source_code/bitwise/bit_array.py b/source_code/bitwise/bit_array.py deleted file mode 100755 index 9e5aa46..0000000 --- a/source_code/bitwise/bit_array.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -''' Example of how to use a bit array in python as a "counter" dict''' - -def print_dupl_ba(l1): - ''' - >>> l1 = [0, 1, 2, 3, 4, 2, 6, 7, 8, 9] - >>> print_dupl_ba(l1) - 2 - ''' - - bs = bytearray(10) - for i in range(len(l1)): - if i == l1[i]: - bs[i] = 1 - for index, bit in enumerate(bs): - if bit == 0: - return l1[index] - return None - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/bitwise/bitwise.txt b/source_code/bitwise/bitwise.txt deleted file mode 100755 index f55d9d1..0000000 --- a/source_code/bitwise/bitwise.txt +++ /dev/null @@ -1,33 +0,0 @@ - BIT-WISE - ---------------------- - -1. To find a number: -11000101 is 2^0+2^2+2^6+2^7 = 197 - - -2. Left shifting: - 0010 1011 << 4 ---> 1011 000 - - -3. Right shifting: - 0010 1011 >> 4 ---> 0000 0010 - or it can be filled with the copy of the first bit, instead of 0: - 1011 0010 >> 4 ---> 1111 1011 - - -4. XOR can cancels out: -15 ^ 12 ^ 15 = 12 - - -5. 2^x: - left-shift 1 by x: - 0000 0001 << x - - so if x = 2, 2^2 = 4 -> 100 - - 0000 0001 << 2 ---> 0000 0100 - - -6. Is power of 2? - just do x&(x-1). - if 0 --> yes! diff --git a/source_code/bitwise/clear_bits.py b/source_code/bitwise/clear_bits.py deleted file mode 100755 index 5297b74..0000000 --- a/source_code/bitwise/clear_bits.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -''' Clear a bit in a binary number. - Like the reverse of set bit: - 1) first create a number filled of 1s, - with 0 at i (can create 0001000 and ~) - 2) AND the number so it clears the ith bit -''' - - - -def clear_bit(num, i): - mask = ~ (1 << i) # -0b10001 - return bin(num & mask) - - -def clear_all_bits_from_i_to_0(num, i): - mask = ~ ( (1 << (i+1)) - 1) - return bin(num & mask) - - -def clear_all_bits_from_most_sig_to_1(num, i): - mask = ( 1 << i) -1 - return bin(num & mask) - - -if __name__ == '__main__': - num = int('10010000', 2) - print clear_bit(num, 4) # '0b10000000' - - num = int('10010011', 2) - print clear_all_bits_from_i_to_0(num, 2) # '0b10010000' - - num = int('1110011', 2) - print clear_all_bits_from_most_sig_to_1(num, 2) #'0b11' diff --git a/source_code/bitwise/find_bit_len.py b/source_code/bitwise/find_bit_len.py deleted file mode 100755 index 81d90f0..0000000 --- a/source_code/bitwise/find_bit_len.py +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -''' Find how many bits a int has: - 1) Start with a mask of 1 - 2) Mask with AND - 3) if result (if true): count += 1 - (obs: to find the int of a bin do int('1001', 2)) and to show in bin - do bin(int)) -''' - - -def find_bit_len(int_num): - lenght = 0 - while int_num: - int_num >>= 1 - lenght += 1 - return lenght - - -if __name__ == '__main__': - for i in range(17): - print(find_bit_len(i)) - print i.bit_length() diff --git a/source_code/bitwise/find_how_many_1_binary.py b/source_code/bitwise/find_how_many_1_binary.py deleted file mode 100755 index 89fc44c..0000000 --- a/source_code/bitwise/find_how_many_1_binary.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -''' Find how many 1s in the binary: - 1) Start with a mask of 1 - 2) Mask with AND - 3) if result (if true): count += 1 - (obs: to find the int of a bin do int('1001', - 2)) and to show in bin do bin(int)) -''' - - -def find_how_many_1_in_a_binary(n): - ''' - >>> find_how_many_1_in_a_binary(9) - 2 - ''' - - counter = 0 - while n: - if n & 1: - counter += 1 - n >>= 1 - return counter - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/bitwise/get_bit.py b/source_code/bitwise/get_bit.py deleted file mode 100755 index b212316..0000000 --- a/source_code/bitwise/get_bit.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -''' Get a bit in a binary number: - 1) Shifts 1 over by i bits - 2) make an AND with the number - 3) all the other than the bit at i are clean, now compare to 0 - 4) if the new value is not 0, bit i is 1 -''' - - -def get_bit(num, i): - mask = 1 << i - return num & mask != 0 - - -if __name__ == '__main__': - num = int('0100100', 2) - get_bit(num, 0) # 0 - get_bit(num, 1) # 0 - get_bit(num, 2) # 1 - get_bit(num, 3) # 0 - get_bit(num, 4) # 0 - get_bit(num, 5) # 1 - get_bit(num, 6) # 0 - diff --git a/source_code/bitwise/get_float_rep_bin.py b/source_code/bitwise/get_float_rep_bin.py deleted file mode 100755 index fb3814d..0000000 --- a/source_code/bitwise/get_float_rep_bin.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -''' Given a real number between 0 and 1 (eg: 0.72), this method print the binary - representation. If the Number cannot be represented accurately in binary, with at - most 32 chars, print error: -''' - -def get_float_rep(num): - ''' - >>> get_float_rep(0.72) - ('Error 2', '.1011100001010001111010111000010') - >>> get_float_rep(0.1) - ('Error 2', '.0001100110011001100110011001100') - >>> get_float_rep(0.5) - '.1' - ''' - - if num >= 1 or num <= 0: return 'Error 1' - result = '.' - while num: - if len(result) >= 32: return 'Error 2', result - r = num*2 - if r >= 1: - result += '1' - num = r - 1 - else: - result += '0' - num = r - return result - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/bitwise/insert_small_bin_into_big_bin.py b/source_code/bitwise/insert_small_bin_into_big_bin.py deleted file mode 100755 index 292b169..0000000 --- a/source_code/bitwise/insert_small_bin_into_big_bin.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' Given two 32-bit numbers, N and M, and two bit positions, i and j, this - method insert M into N such that M starts at bit j and ends at bit i: - 1) clear the bits j thru i in N' - 2) shift M so that it lines up with bits j thru i - 3) merge M and N -''' - -def insert_small_bin_into_big_bin(M, N, i, j): - ''' - >>> N = 0b10000000000 - >>> M = 0b10011 - >>> j = 6 - >>> i = 2 - >>> insert_small_bin_into_big_bin(M, N, i, j) - '0b10001001100' - ''' - - allOnes = ~0 - left = allOnes << (j+1) # 1110000 - right = ( (1 << i) - 1) # 0000111 - mask = left | right # 1110111 - N_cleared = N & mask - M_shifted = M << i - - return bin( N_cleared | M_shifted) - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/bitwise/next_with_same_num_1s.py b/source_code/bitwise/next_with_same_num_1s.py deleted file mode 100755 index 6c2617e..0000000 --- a/source_code/bitwise/next_with_same_num_1s.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' Give a positive int, print the next smallest and next largest ints with - same number of 1 bits. - The brute force is: - 1) find number of 1 bits - 2) loop above and down until find same, checking for each -''' - - - -def print_prev_same_1s(num): - n1s = find_num_1s(num) - # find prev - i = num-1 - while True: - n1s_here = find_num_1s(i) - if n1s_here == n1s: - return bin(i) - i -= 1 - if i < 0: - return None - -def print_next_same_1s(num): - n1s = find_num_1s(num) - # find next - i = num+1 - while True: - n1s_here = find_num_1s(i) - if n1s_here == n1s: - return bin(i) - i += 1 - if i < 0: - return None - - - -def find_num_1s(num): - counter = 0 - while num: - if num & 1: - counter += 1 - num >>= 1 - return counter - - - - - -if __name__ == '__main__': - num = 0b1001 - n = '0b1010' - p = '0b110' - print_prev_same_1s(num) == p - print_next_same_1s(num) == n - diff --git a/source_code/bitwise/num_bits_to_convert_2_nums.py b/source_code/bitwise/num_bits_to_convert_2_nums.py deleted file mode 100755 index 3447d35..0000000 --- a/source_code/bitwise/num_bits_to_convert_2_nums.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' This method returns the number of bits that are necessary to change to convert two - numbers A and B: - 1) XOR - 2) count 1s -''' - -def count_bits_swap2(a, b): - count = 0 - m = a^b - while m: - count +=1 - m = m & (m-1) - return count - - - -def count_bits_swap(a, b): - m = a^b - return count_1s(m) - - -def count_1s(m): - count = 0 - while m: - if m& 1 : - count +=1 - m >>= 1 - return count - - -if __name__ == '__main__': - a = int('10010000', 2) - b = int('01011010', 2) - print count_bits_swap(a, b) #4 - print count_bits_swap2(a, b) #4 diff --git a/source_code/bitwise/set_bit.py b/source_code/bitwise/set_bit.py deleted file mode 100755 index eeb73fb..0000000 --- a/source_code/bitwise/set_bit.py +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - - -''' Set a bit in a binary number: - 1) Shifts 1 over by i bits - 2) make an OR with the number, only the value at bit i will change and all the others bit - of the mask are zero so will not affect the num -''' - - -def set_bit(num, i): - mask = 1 << i - return bin( num | mask ) - - -if __name__ == '__main__': - num = int('0100100', 2) - print set_bit(num, 0) #'0b100101' - print set_bit(num, 1) #'0b100110' - print set_bit(num, 2) # nothing change '0b100100' - print set_bit(num, 3) #'0b101100' - print set_bit(num, 4) #'0b110100' - print set_bit(num, 5) # nothing change '0b100100' diff --git a/source_code/bitwise/swap_in_place.py b/source_code/bitwise/swap_in_place.py deleted file mode 100755 index 5aee66a..0000000 --- a/source_code/bitwise/swap_in_place.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -''' - swapping values in place without extra memory -''' - - -def swap_bit(a, b): - ''' - >>> swap_bit(14, 73) - (73, 14) - ''' - a = a^b - b = a^b - a = a^b - return a, b - - -if __name__ == '__main__': - import doctest - doctest.testmod() \ No newline at end of file diff --git a/source_code/bitwise/swap_odd_even.py b/source_code/bitwise/swap_odd_even.py deleted file mode 100755 index 386627d..0000000 --- a/source_code/bitwise/swap_odd_even.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' Swap odd and even bits in a smart way in a binary: - 1) first for odds, take n and move the odd: - (a) Mask all odd bits with 10101010 (0xAA) - (b) shift by right by 1 - 2) do the same to ints with 01010101 - 3) merge -''' - - - -def swap_odd_even(num): - ''' - >>> num = 0b11011101 - >>> result = '0b1101110' - >>> swap_odd_even(num) == result - True - ''' - - mask_odd = 0xAA # 0b10101010 - mask_even = 0x55 # 0b1010101 - odd = num & mask_odd - odd >>= 1 - even = num & mask_even - even >>= 1 - return bin(odd | even) - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/bitwise/update_bit.py b/source_code/bitwise/update_bit.py deleted file mode 100755 index c31d713..0000000 --- a/source_code/bitwise/update_bit.py +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -''' This method merges set bit and clean bit: - 1) first clear the bit at i using a mask such as 1110111 - 2) then shift the intended value v by i bits - 3) this will create a number with bit i to v and all other to 0 - 4) finally update the ith bit with or -''' - - - -def update_bit(num, i, v): - mask = ~ (1 << i) - return bin( (num & mask) | (v << i) ) - - -if __name__ == '__main__': - num = int('10010000', 2) - print update_bit(num, 2, 1) # '0b10010100' - diff --git a/source_code/builtin_structures/__init__.py b/source_code/builtin_structures/__init__.py deleted file mode 100755 index e69de29..0000000 diff --git a/source_code/builtin_structures/anagram.py b/source_code/builtin_structures/anagram.py deleted file mode 100755 index bffc085..0000000 --- a/source_code/builtin_structures/anagram.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -from collections import Counter - -def is_anagram(s1, s2): - ''' - >>> is_anagram('cat', 'tac') - True - >>> is_anagram('cat', 'hat') - False - ''' - counter = Counter() - for c in s1: - counter[c] += 1 - - for c in s2: - counter[c] -= 1 - - for i in counter.values(): - if i: - return False - - return True - -''' verify if words are anagrams by comparing a sum of Unicode code -point of the character''' - -def get_unicode_sum(word): - s = 0 - for p in word: - s += ord(p) - return s - - -def is_anagram2(word1, word2): - ''' - >>> is_anagram2('cat', 'tac') - True - >>> is_anagram2('cat', 'hat') - False - ''' - return get_unicode_sum(word1) == get_unicode_sum(word2) - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/builtin_structures/balance.txt b/source_code/builtin_structures/balance.txt deleted file mode 100755 index 27df907..0000000 --- a/source_code/builtin_structures/balance.txt +++ /dev/null @@ -1,9 +0,0 @@ -__author__ = "bt3" - - -This is the classic "you have 8 balls/coins, which are the same weight, except for one which is slightly heavier than the others. You also have an old-style balance. What is the fewest number of weighings to find the heavy coin/ball? - -Answer: 2! You need to use every information available: -Weight 3 x 3 balls/coins. -If they weight the same: weight the 2 balls/coins left outside. -Else, measure 2 of the 3 heavier balls/coins. \ No newline at end of file diff --git a/source_code/builtin_structures/balance_symbols.py b/source_code/builtin_structures/balance_symbols.py deleted file mode 100755 index ff65f82..0000000 --- a/source_code/builtin_structures/balance_symbols.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -''' -Given a N different open and close braces in a string "( { [ } ] )". -How do you check whether the string has matching braces. -''' - -from collections import Counter -def check_if_balance(string): - ''' - >>> check_if_balance('{[[(])}]') - True - >>> check_if_balance('{[[()}]') - False - >>> check_if_balance('') - True - ''' - table = Counter() - for i in string: - - index = str(ord(i))[0] - if i in '{[(': - table[index] += 1 - - elif i in ')}]': - table[index] -= 1 - - for i in table.values(): - if i !=-0: - return False - return True - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/builtin_structures/check_if_2_numbers_sum_to_k.py b/source_code/builtin_structures/check_if_2_numbers_sum_to_k.py deleted file mode 100755 index b9d7cbf..0000000 --- a/source_code/builtin_structures/check_if_2_numbers_sum_to_k.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -""" -Given an integer x and an unsorted array of integers, describe an -algorithm to determine whether two of the numbers add up to x. - -1. Using hash tables. -2. Sorting the array and keeping two pointers in the array, one in -the beginning and one in the end. Whenever the sum of the current -two integers is less than x, move the first pointer forwards, and -whenever the sum is greater than x, move the second pointer -backwards. O(nln n). -3. Create a BST with x minus each element in the array. -Check whether any element of the array appears in the BST. -It takes O(nlog n) times two. -""" - -from collections import defaultdict, Counter - -def check_sum(array, k): - ''' - >>> check_sum([3, 2, 6, 7, 9, 1], 8) - [(6, 2), (1, 7)] - >>> check_sum([5, 2, 6, 7, 9, 1], 4) - [] - >>> - ''' - - dict = defaultdict() - res = [] - - for i in array: - if k-i in dict: - res.append((i, k-i)) - del dict[k-i] - else: - dict[i] = 1 - - return res - - -def check_sum2(array, k): - ''' - >>> check_sum2([1, 4, 2, 7, 1, 3, 10, 15, 3, 1], 6) - set([(3, 3)]) - >>> check_sum2([1, 4, 2, 7, 1, 3, 10, 15, 3, 1], 0) - set([]) - ''' - - dict = Counter() - res = set() - - for i in array: - dict[i] += 1 - - for i in array: - if dict[k-i] > 0: - if i == k-i and dict[k-i] > 1: - res.add((i, k-i)) - dict[k-i] -= 2 - elif i == k-i: - res.add((i, k-i)) - dict[k-i] -= 1 - - return res - -if __name__ == '__main__': - import doctest - doctest.testmod() \ No newline at end of file diff --git a/source_code/builtin_structures/check_if_3_numbers_sum_to_zero.py b/source_code/builtin_structures/check_if_3_numbers_sum_to_zero.py deleted file mode 100755 index 33c3e3e..0000000 --- a/source_code/builtin_structures/check_if_3_numbers_sum_to_zero.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' Determine if an Array of integers contains 3 numbers that sum to 0 ''' - -from collections import defaultdict - -def find_3_number(array): - ''' - >>> find_3_number([1,5,56,11,-3,-12]) - 1 11 -12 - True - >>> find_3_number([] ) - False - ''' - hash_ = defaultdict() - for i in array: - hash_[i] = 1 - - for i, x in enumerate(array): - for y in array[i+1:]: - if -(x+y) in hash_: - print x, y, -(x+y) - return True - - return False - - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/builtin_structures/check_non_overlapping_intervals.py b/source_code/builtin_structures/check_non_overlapping_intervals.py deleted file mode 100755 index f8213ef..0000000 --- a/source_code/builtin_structures/check_non_overlapping_intervals.py +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' -given an array of intervals, return max number of non-overlapping intervals -''' - -from collections import defaultdict - -def non_overlapping(array): - ''' - >>> non_overlapping([(1,2), (2,5), (1, 6)]) - [[(1, 2), (2, 5)]] - >>> non_overlapping([(1,4), (2,5), (3, 6)]) - [] - ''' - total = [] - - for i, t in enumerate(array): - start = t[0] - end = t[1] - for tt in array[i+1:] : - if end <= tt[0]: - total.append([(start, end), (tt[0], tt[1])]) - - return total - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/builtin_structures/convert_numerical_bases.py b/source_code/builtin_structures/convert_numerical_bases.py deleted file mode 100755 index 999d40e..0000000 --- a/source_code/builtin_structures/convert_numerical_bases.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -''' convert an integer to a string in any base''' - -def convert_from_dec_to_any_base(number, base): - ''' - >>> number, base = 9, 2 - >>> convert_from_dec_to_any_base(number, base) - '1001' - ''' - - convertString = '012345679ABCDEF' - - if number < base: - return convertString[number] - - else: - return convert_from_dec_to_any_base(number//base, base) + \ - convertString[number%base] - - - -def convert_from_decimal_to_binary(number, base): - ''' - >>> number, base = 9, 2 - >>> convert_from_decimal_to_binary(number, base) - 1001 - ''' - - multiplier, result = 1, 0 - - while number > 0: - result += number%base*multiplier - multiplier *= 10 - number = number//base - - return result - - - -def convert_from_decimal_larger_bases(number, base): - ''' - >>> number, base = 31, 16 - >>> convert_from_decimal_larger_bases(number, base) - '1F' - ''' - strings = "0123456789ABCDEFGHIJ" - result = "" - - while number > 0: - digit = number%base - result = strings[digit] + result - number = number//base - - return result - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/builtin_structures/convert_str_2_int.py b/source_code/builtin_structures/convert_str_2_int.py deleted file mode 100755 index bdf875d..0000000 --- a/source_code/builtin_structures/convert_str_2_int.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -def conv_int2str(int1): - ''' - >>> conv_str2int('367') - 367 - >>> conv_str2int('0') - 0 - >>> conv_str2int('-10') - -10 - >>> conv_str2int('1e5') - 100000 - ''' - - aux_dict = {key:value for key in range(10) for value in '0123456789'[key]} - - if int1 == 0: - return '0' - elif int1 < 0: - sign = '-' - int1 = int1*(-1) - else: - sign = '' - - - aux_ls = [] - - while int1 > 0: - c = int1%10 - int1 = int1//10 - cadd = aux_dict[c] - aux_ls.append(cadd) - - aux_ls.reverse() - - return sign + ''.join(aux_ls) - - - -def conv_str2int(str1): - ''' - >>> conv_int2str(0) - '0' - >>> conv_int2str(1e5) - '100000' - >>> conv_int2str(367) - '367' - >>> conv_int2str(-10) - '-10' - ''' - if not str1: - return None - - aux_dict = {key:value for value in range(10) for key in '0123456789'[value]} - - if str1[0] == '-': - sign = -1 - str1 = str1[1:] - else: - sign = 1 - - dec, result = 1, 0 - - for i in range(len(str1)-1, -1, -1): - aux = str1[i] - if aux == 'e': - exp_num = conv_str2int(str1[i+1:]) - number = conv_str2int(str1[:i]) - result = number*10**exp_num - break - result += aux_dict[aux]*dec - dec *= 10 - - return result*sign - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/builtin_structures/count_unique_words_On2.py b/source_code/builtin_structures/count_unique_words_On2.py deleted file mode 100755 index 7b54490..0000000 --- a/source_code/builtin_structures/count_unique_words_On2.py +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -import collections -import string -import sys - - -def count_unique_word(): - - words = collections.defaultdict(int) - - strip = string.whitespace + string.punctuation + string.digits + "\"'" - - for filename in sys.argv[1:]: - with open(filename) as file: - for line in file: - for word in line.lower().split(): - word = word.strip(strip) - if len(word) > 2: - words[word] = +1 - - for word in sorted(words): - print("'{0}' occurs {1} times.".format(word, words[word])) - diff --git a/source_code/builtin_structures/delete_duplicate_char_str.py b/source_code/builtin_structures/delete_duplicate_char_str.py deleted file mode 100755 index 9f8b9fc..0000000 --- a/source_code/builtin_structures/delete_duplicate_char_str.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -''' find and delete all the duplicate characters in a string ''' - -from collections import Counter - -def delete_unique(str1): - ''' - >>> delete_unique("Trust no one") - 'on' - >>> delete_unique("Mulder?") - '' - ''' - - str_strip = ''.join(str1.split()) - repeat = Counter() - - for c in str_strip: - repeat[c] += 1 - - result = '' - for c, count in repeat.items(): - if count > 1: - result += c - - return result - - -def removing_duplicates_seq(str1): - ''' - >>> delete_unique("Trust no one") - 'on' - >>> delete_unique("Mulder?") - '' - ''' - seq = str1.split() - result = set() - for item in seq: - if item not in result: - #yield item - result.add(item) - return result - - -if __name__ == '__main__': - import doctest - doctest.testmod() diff --git a/source_code/builtin_structures/fibonacci.py b/source_code/builtin_structures/fibonacci.py deleted file mode 100755 index 584b611..0000000 --- a/source_code/builtin_structures/fibonacci.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -def fib_generator(): - a, b = 0, 1 - - while True: - yield b - a, b = b, a+b - - -def fib(n): - ''' - >>> fib(2) - 1 - >>> fib(5) - 5 - >>> fib(7) - 13 - ''' - if n < 3: - return 1 - - a, b = 0, 1 - count = 1 - - while count < n: - count += 1 - a, b = b, a+b - - return b - - -def fib_rec(n): - ''' - >>> fib_rec(2) - 1 - >>> fib_rec(5) - 5 - >>> fib_rec(7) - 13 - ''' - if n < 3: - return 1 - return fib_rec(n - 1) + fib_rec(n - 2) - - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - - fib = fib_generator() - print(next(fib)) - print(next(fib)) - print(next(fib)) - print(next(fib)) diff --git a/source_code/builtin_structures/find_0_MxN_replace_cols_rows.py b/source_code/builtin_structures/find_0_MxN_replace_cols_rows.py deleted file mode 100755 index 9ab67c3..0000000 --- a/source_code/builtin_structures/find_0_MxN_replace_cols_rows.py +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -def find_0_MxN(m): - ''' find 0s in a matrix and replace the col and row to 0s: - >>> m1 = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]] - >>> find_0_MxN(m1) - [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] - >>> m2 = [[1, 2, 3, 4], [0, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] - >>> find_0_MxN(m2) - [[0, 2, 3, 4], [0, 0, 0, 0], [0, 10, 11, 12], [0, 14, 15, 16]] - ''' - index = [] - - for row in range(len(m)): - for col in range(len(m[0])): - if m[row][col] == 0: - index.append((row, col)) - for i in index: - row = i[0] - col = i[1] - for i in range(len(m)): - m[row][i] = 0 - for i in range(len(m[0])): - m[i][col] = 0 - - return m - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/builtin_structures/find_dice_probabilities.py b/source_code/builtin_structures/find_dice_probabilities.py deleted file mode 100755 index 265c9b1..0000000 --- a/source_code/builtin_structures/find_dice_probabilities.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -''' -given 2 dice, determine number of ways to sum S if all dice are rolled -''' - -from collections import Counter, defaultdict - -def find_dice_probabilities(S=5, n_faces=6): - if S > 2*n_faces or S < 2: - return None - - cdict = Counter() - ddict = defaultdict(list) - - for dice1 in range(1, n_faces+1): - for dice2 in range(1, n_faces+1): - t = [dice1, dice2] - cdict[dice1+dice2] += 1 - ddict[dice1+dice2].append( t) - - return [cdict[S], ddict[S]] - - - - - -if __name__ == '__main__': - results = find_dice_probabilities() - assert(results[0] == len(results[1])) diff --git a/source_code/builtin_structures/find_edit_distance.py b/source_code/builtin_structures/find_edit_distance.py deleted file mode 100755 index 6fc6e81..0000000 --- a/source_code/builtin_structures/find_edit_distance.py +++ /dev/null @@ -1,43 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' computes the edit distance between two strings ''' - - -def find_edit_distance(str1, str2): - ''' - >>> s = 'sunday' - >>> t = 'saturday' - >>> find_edit_distance(s, t) - 3 - ''' - - m = len(str1) - n = len(str2) - diff = lambda c1, c2: 0 if c1 == c2 else 1 - - E = [[0] * (n + 1) for i in range(m + 1)] - - for i in range(m + 1): - E[i][0] = i - - for j in range(1, n + 1): - E[0][j] = j - - for i in range(1, m + 1): - for j in range(1, n + 1): - E[i][j] = min(E[i-1][j] + 1, E[i][j-1] + 1, E[i-1][j-1] + diff(str1[i-1], str2[j-1])) - - return E[m][n] - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - - - - diff --git a/source_code/builtin_structures/find_first_non_repetead_char.py b/source_code/builtin_structures/find_first_non_repetead_char.py deleted file mode 100755 index 5489f7d..0000000 --- a/source_code/builtin_structures/find_first_non_repetead_char.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -from collections import Counter - -def find_non_rep_char(s1): - ''' - >>> s1 = 'aabbcceff' - >>> find_non_rep_char(s1) - e - >>> find_non_rep_char('ccc') - ''' - - aux_dict = Counter() - - for i in s1: - aux_dict[i] += 1 - - for k, v in aux_dict.items(): - if v < 2: - print k - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/builtin_structures/find_gcd.py b/source_code/builtin_structures/find_gcd.py deleted file mode 100755 index d9dfa4c..0000000 --- a/source_code/builtin_structures/find_gcd.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - - -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/source_code/builtin_structures/find_if_substr.py b/source_code/builtin_structures/find_if_substr.py deleted file mode 100755 index 8166bda..0000000 --- a/source_code/builtin_structures/find_if_substr.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -def find_substr(s1, s2): - - if len(s1) < len(s2): - bs = s2 - ss = s1 - else: - bs = s1 - ss = s2 - - ps = 0 - - for c in bs: - - if ss[ps] == c: - ps += 1 - else: - ps = 0 - - if ps == len(ss)-1: - return True - - return False - - - -if __name__ == '__main__': - s1 = 'buffy is a vampire slayer' - s2 = 'vampire' - s3 = 'angel' - assert(find_substr(s2, s1) == True) - assert(find_substr(s3, s1) == False) \ No newline at end of file diff --git a/source_code/builtin_structures/find_if_unique_char.py b/source_code/builtin_structures/find_if_unique_char.py deleted file mode 100755 index 3e88c46..0000000 --- a/source_code/builtin_structures/find_if_unique_char.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - - -import collections - -def find_if_unique_chars(word): - """ - >>> find_if_unique_chars('abcde') - True - >>> find_if_unique_chars('abcae') - False - """ - - unique = True - - counter = collections.Counter() - - for c in word: - if not counter[c]: - counter[c] += 1 - else: - unique = False - - return unique - - -if __name__ == '__main__': - import doctest - doctest.testmod() \ No newline at end of file diff --git a/source_code/builtin_structures/find_largest_sum.py b/source_code/builtin_structures/find_largest_sum.py deleted file mode 100755 index 9b79ac8..0000000 --- a/source_code/builtin_structures/find_largest_sum.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - - -''' - You are given an array of integers (both positive and negative). - Find the contiguous sequence with the largest sum. -''' - - -def find_largest_sum(array): - ''' - >>> find_largest_sum([-1, 2, -3, 5, 3, 1, -16, 7, 1, -13, 1]) - 9 - >>> find_largest_sum([]) - 0 - >>> find_largest_sum([1]) - 1 - ''' - - sum_ = 0 - sum_here = 0 - - for i in array: - - sum_here += i - - if sum_here < 0: - sum_here = 0 - - if sum_ < sum_here: - sum_ = sum_here - - return sum_ - - - -if __name__ == '__main__': - import doctest - doctest.testmod() \ No newline at end of file diff --git a/source_code/builtin_structures/find_longest_inc_subseq.py b/source_code/builtin_structures/find_longest_inc_subseq.py deleted file mode 100755 index 38e3b9b..0000000 --- a/source_code/builtin_structures/find_longest_inc_subseq.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -''' find the longest continuous increasing subsequence''' - - -def find_long_con_inc(seq): - ''' - >>> find_long_con_inc([1, -2, 3, 5, 1, -1, 4, -1, 6]) - [-2, 3, 5] - >>> find_long_con_inc([1, 3, -2, 3, 5, 6]) - [-2, 3, 5, 6] - >>> find_long_con_inc([1, 3, 4, -13, 2, 5, 8, -1, 2,-17]) - [-13, 2, 5, 8] - ''' - - res, aux = [], [] - seq.append(-float('infinity')) - - for i, n in enumerate(seq[:-1]): - aux.append(n) - if n > seq[i+1]: - if len(res) < len(aux): - res = aux[:] - aux = [] - - return res - - - -if __name__ == '__main__': - import doctest - doctest.testmod() diff --git a/source_code/builtin_structures/find_longest_str_unique_chars.py b/source_code/builtin_structures/find_longest_str_unique_chars.py deleted file mode 100755 index a73144e..0000000 --- a/source_code/builtin_structures/find_longest_str_unique_chars.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' -given a string, find longest string with unique characters -''' - -def find_longest(string): - ''' - >>> find_longest('abfgrhgtrdsandwejfhdasjcbdsjvrejwghireeej') - 'wejfhdas' - >>> find_longest('abcabcabcabcdefabcccc') - 'defabc' - ''' - maxs = '' - result = '' - - for c in string: - if c in result: - if len(maxs) < len(result): - maxs = result - result = '' - else: - result += c - - if result and len(maxs) < len(result): - maxs = result - - return maxs - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/builtin_structures/find_non_repeating_number.py b/source_code/builtin_structures/find_non_repeating_number.py deleted file mode 100755 index 8d1dc14..0000000 --- a/source_code/builtin_structures/find_non_repeating_number.py +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -from collections import defaultdict - - -def find_unique_number(array): - ''' - >>> find_unique_number([1, 3, 6, 1, 5, 6, 9, 3, 7]) - [1, 6, 3] - >>> find_unique_number([1, 3, 5, 6, 9, 7]) - [] - ''' - - table = defaultdict() - total = [] - - for i in array: - if i in table: - total.append(i) - else: - table[i] = 1 - - return total - - - - -if __name__ == '__main__': - import doctest - doctest.testmod() \ No newline at end of file diff --git a/source_code/builtin_structures/find_product_without_division.py b/source_code/builtin_structures/find_product_without_division.py deleted file mode 100755 index 611842e..0000000 --- a/source_code/builtin_structures/find_product_without_division.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -'''Given an array of numbers, replace each number with the product of all -the numbers in the array except the number itself *without* using division -''' - - -def find_product_without_division(seq): - ''' - >>> seq = [2,3,4] - >>> find_product_without_division(seq) - [12, 8, 6] - ''' - - forw = [] - bacw = [] - - for i in range(len(seq)): - - prod_f, prod_b = 1, 1 - - for next in range(i+1, len(seq)): - prod_f *= seq[next] - - for before in range(0, i): - prod_b *= seq[before] - - forw.append(prod_f) - bacw.append(prod_b) - - for i in range(len(seq)): - seq[i] = forw[i] * bacw[i] - - return seq - - - -if __name__ == '__main__': - import doctest - doctest.testmod() \ No newline at end of file diff --git a/source_code/builtin_structures/find_top_N_recurring_words.py b/source_code/builtin_structures/find_top_N_recurring_words.py deleted file mode 100755 index 91dfc8f..0000000 --- a/source_code/builtin_structures/find_top_N_recurring_words.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -from collections import Counter - -def find_top_N_recurring_words(seq, N): - ''' find the top N recurring words in a file: - 1) use a hash table to find counts - 2) sort the list on base of the maximum counts - 3) return the last N words - ''' - - dcounter = Counter() - for word in seq.split(): - dcounter[word] += 1 - - return dcounter.most_common(N) - - - -if __name__ == '__main__': - seq = 'buffy angel monster xander a willow gg buffy the monster super buffy angel' - N = 3 - assert(find_top_N_recurring_words(seq, N) == [('buffy', 3), ('monster', 2), ('angel', 2)]) - - diff --git a/source_code/builtin_structures/find_two_missing_numbers_in_sequence.py b/source_code/builtin_structures/find_two_missing_numbers_in_sequence.py deleted file mode 100755 index e532a18..0000000 --- a/source_code/builtin_structures/find_two_missing_numbers_in_sequence.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -""" -Two numbers out of n numbers from 1 to n are missing. -The remaining n-2 numbers are in the array but not sorted. -Find the missing numbers The sum1 is the sum of all the elements in n. -The sum2 is the sum of all the elements in n-2. sum1 - sum2 = num1 + num2 = s. -The prod1 is the prod of all the elements in n. The prod2 is the prod of all -the elements in n-2. prod1/prod2 = num1*num2 =p. -Runtime is O(n), because it scan 3 times. Space is O(1) - -In case of finding one integer, Let the missing number be M. We know that -the sum of first N natural numbers is N*(N+1)/2. Traverse through the array -once and calculate the sum. This is the sum of first N natural numbers - -M or S=N*(N+1)/2 - M. Therefore M = N*(N+1)/2 - S. -""" - -import math - -def find_two_missing_numbers(l1): - ''' - >>> l1 = [1, 3, 5] - >>> find_two_missing_numbers(l1) - (4, 2) - ''' - - n_min_2 = len(l1) - n = n_min_2 + 2 - sum1, sum2, prod1, prod2 = 0, 0, 1, 1 - sum2 = sum(l1[:]) - sum1 = sum(range(1,n+1)) - s = sum1 - sum2 - - for i in range(1, n-1): - prod1 = prod1*i - prod2 = prod2*l1[i-1] - - prod1 = prod1*n*(n-1) - p = prod1/prod2 - num1 = (s + math.sqrt(s*s - 4*p))/2 - num2 = (s - math.sqrt(s*s - 4*p))/2 - - return int(num1), int(num2) - - -if __name__ == '__main__': - import doctest - doctest.testmod() - - - - - - diff --git a/source_code/builtin_structures/get_float_rep_bin.py b/source_code/builtin_structures/get_float_rep_bin.py deleted file mode 100755 index 156cb77..0000000 --- a/source_code/builtin_structures/get_float_rep_bin.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' Given a real number between 0 and 1 (eg: 0.72), this method print the - binary representation. If the Number cannot be represented accurately - in binary, with at exit most 32 chars, print error: -''' - -def get_float_rep(num): - if num >= 1 or num <= 0: return 'Error 1' - result = '.' - while num: - if len(result) >= 32: return 'Error 2', result - r = num*2 - if r >= 1: - result += '1' - num = r - 1 - else: - result += '0' - num = r - return result - - -if __name__ == '__main__': - print get_float_rep(0.72) #('Error 2', '.1011100001010001111010111000010') - print get_float_rep(0.1) # ('Error 2', '.0001100110011001100110011001100') - print get_float_rep(0.5) #'.1' diff --git a/source_code/builtin_structures/interserction_two_arrays.py b/source_code/builtin_structures/interserction_two_arrays.py deleted file mode 100755 index b0868ef..0000000 --- a/source_code/builtin_structures/interserction_two_arrays.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -def intersection_two_arrays_sets(seq1, seq2): - ''' - >>> intersection_two_arrays_sets([1,2,3,5,7,8], [3,5,6]) - set([3, 5]) - >>> intersection_two_arrays_sets([1,2,7,8], [3,5,6]) - set([]) - ''' - # O(n) - set1 = set(seq1) - set2 = set(seq2) - - return set1.intersection(set2) #same as list(set1 & set2) - - -def intersection_two_arrays_On2(seq1, seq2): - ''' - >>> intersection_two_arrays_On2([1,2,3,5,7,8], [3,5,6]) - [3, 5] - >>> intersection_two_arrays_On2([1,2,7,8], [3,5,6]) - [] - ''' - - final = [] - - for i in seq1: - for j in seq2: - if i == j: - final.append(i) - - return final - - -def intersection_two_arrays_On(seq1, seq2): - ''' - >>> intersection_two_arrays_On([1,2,3,5,7,8], [3,5,6]) - [5, 3] - >>> intersection_two_arrays_On([1,2,7,8], [3,5,6]) - [] - ''' - - final = [] - - while seq1 and seq2: - - if seq1[-1] == seq2[-1]: - final.append(seq1.pop()) - seq2.pop() - elif seq1[-1] > seq2[-1]: - seq1.pop() - else: - seq2.pop() - - return final - - -if __name__ == '__main__': - import doctest - doctest.testmod() diff --git a/source_code/builtin_structures/max_subarray_stocks.py b/source_code/builtin_structures/max_subarray_stocks.py deleted file mode 100755 index 11bf739..0000000 --- a/source_code/builtin_structures/max_subarray_stocks.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - - -def beating_stock(array): - - imin = 0 - - # first deal is just buying in the next day (1) - deal = [array[1] - array[imin], imin, 1] - - for i, d in enumerate(array): - - deal_here = d - array[imin] - - if deal_here > deal[0]: - deal = [deal_here, imin, i] - - elif d < array[imin]: - imin = i - - return deal[0], array[deal[1]], array[deal[2]] - - -def beating_stock2(array): - - deal = 0 - min_value = array[0] - - for i, d in enumerate(array): - - deal_here = d - min_value - - if deal_here > deal: - deal = deal_here - - else: - if min_value > array[i]: - min_value = array[i] - - return deal - - - -if __name__ == '__main__': - array = [7, 2, 3, 6, 5, 8, 5, 3, 4] - - deal = beating_stock(array) - print("Profit: %d, buying at %d, selling at %d." %(deal[0], deal[1], deal[2])) - - deal = beating_stock2(array) - print "Profit: " + str(deal) \ No newline at end of file diff --git a/source_code/builtin_structures/number_of_zeros_factorial.txt b/source_code/builtin_structures/number_of_zeros_factorial.txt deleted file mode 100755 index 066451c..0000000 --- a/source_code/builtin_structures/number_of_zeros_factorial.txt +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - - -How to know how many 0 are in 100! - -You look for the primes that multiply to 10, i.e. 2 and 5. - -There are more 5 than 2s so you can count the fives. - -there is 100/5 = 20, so 20 5s. However, there are two 5s in 25, 50, 75 and 100. - -result: 20+4 = 24 \ No newline at end of file diff --git a/source_code/builtin_structures/palindrome.py b/source_code/builtin_structures/palindrome.py deleted file mode 100755 index 0002cee..0000000 --- a/source_code/builtin_structures/palindrome.py +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - - -from collections import defaultdict - -def is_palindrome(array): - ''' - >>> is_palindrome('subi no onibus') - True - >>> is_palindrome('helllo there') - False - >>> is_palindrome('h') - True - >>> is_palindrome('') - True - ''' - array = array.strip(' ') - if len(array) < 2: - return True - - if array[0] == array[-1]: - return is_palindrome(array[1:-1]) - else: - return False - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/builtin_structures/permutations.py b/source_code/builtin_structures/permutations.py deleted file mode 100755 index 14c4134..0000000 --- a/source_code/builtin_structures/permutations.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - - -def perm(str1): - ''' - >>> perm('123') - ['123', '132', '231', '213', '312', '321'] - ''' - - if len(str1) < 2: - return str1 - - res = [] - for i, c in enumerate(str1): - for cc in perm(str1[i+1:] + str1[:i]): - res.append(c + cc) - return res - - -def perm2(str1): - ''' - >>> perm2('123') - ['123', '132', '213', '231', '312', '321'] - ''' - from itertools import permutations - return [''.join(p) for p in permutations(str1)] - - -def ispermutation(s1, s2): - ''' - >>> ispermutation('231', '123') - True - >>> ispermutation('231', '153') - False - ''' - - from collections import Counter - aux = Counter() - for i in s1: - aux[i] += 1 - for i in s2: - aux[i] -= 1 - for v in aux.values(): - if v != 0: - return False - return True - - - - -def ispermutation2(s1, s2): - ''' - >>> ispermutation2('231', '123') - True - >>> ispermutation2('231', '153') - False - ''' - if sorted(s1) == sorted(s2): - return True - else: - return False - - - -if __name__ == '__main__': - import doctest - doctest.testmod() diff --git a/source_code/builtin_structures/permutations_alphanumeric.py b/source_code/builtin_structures/permutations_alphanumeric.py deleted file mode 100755 index 1c0ff96..0000000 --- a/source_code/builtin_structures/permutations_alphanumeric.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' Write code to generate all possible case permutations of a given -lower-cased string -''' - -def alpha_permutation(string): - ''' - >>> alpha_permutation('0ab') - ['0Ab', '0Ab', '0ab', '0ab', '0Ba', '0Ba', '0ba', '0ba', 'ab0', 'a0b', 'a0b', 'b0a', 'b0a', 'ba0'] - >>> alpha_permutation('') - '' - ''' - - if len(string) < 2: - return string - - result = [] - - for i, c in enumerate(string): - rest = string[i+1:] + string[:i] - for cc in alpha_permutation(rest): - if cc.isalpha(): - result.append(c.upper() + cc) - result.append(c + cc) - - return result - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/builtin_structures/primes.py b/source_code/builtin_structures/primes.py deleted file mode 100755 index 59dc1ed..0000000 --- a/source_code/builtin_structures/primes.py +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' -find prime factors of a number. -''' - -import math -import random - -def find_prime_factors(n): - ''' - >>> find_prime_factors(14) - [2, 7] - >>> find_prime_factors(19) - [] - ''' - - divisors = [d for d in range(2, n//2 + 1) if n % d == 0] - primes = [d for d in divisors if is_prime(d)] - - return primes - - -def is_prime(n): - for j in range(2, int(math.sqrt(n))): - if (n % j) == 0: - return False - return True - - -''' return a n-bit prime ''' -def generate_prime(number=3): - while 1: - p = random.randint(pow(2, number-2), pow(2, number-1)-1) - p = 2 * p + 1 - if find_prime_factors(p): - return p - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/builtin_structures/prod_other_ints.py b/source_code/builtin_structures/prod_other_ints.py deleted file mode 100755 index 3caa9bf..0000000 --- a/source_code/builtin_structures/prod_other_ints.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -def get_products_of_all_except_at_index(array): - ''' - >>> a = [1, 7, 3, 4] - >>> get_products_of_all_except_at_index(a) - [84, 12, 28, 21] - ''' - total = 1 - for n in array: - total *= n - - new_array = [] - for n in array: - if n is not 0: - item = total/n - new_array.append(item) - else: - new_array.append(n) - - return new_array - -if __name__ == '__main__': - import doctest - doctest.testmod() \ No newline at end of file diff --git a/source_code/builtin_structures/ransom_note.py b/source_code/builtin_structures/ransom_note.py deleted file mode 100755 index 75a07f8..0000000 --- a/source_code/builtin_structures/ransom_note.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - - -from collections import Counter - -def check_if_ransom_note(magazines, note): - count = Counter() - pm, pn = 0, 0 - - while pn < len(note) and pm < len(magazines): - char_note = note[pn] - if count[char_note]>0: - count[char_note] -= 1 - pn += 1 - else: - char_magazine = magazines[pm] - count[char_magazine] += 1 - pm +=1 - - return pn == len(note) - - - -if __name__ == '__main__': - - magazines1 = "avfegthhgrebvkdsvnijnvyijfdmckdsmovkmmfvskumvl;cdkmioswckofjbkreenyukjemjgnmkmvkmnvdkmvkr g gmvdvmldm vldfkmbldkmlvdkm" - magazines2 = "adfsfa" - note = "you should disobey" - - print(check_if_ransom_note(magazines1, note)) - print(check_if_ransom_note(magazines2, note)) diff --git a/source_code/builtin_structures/reverse_string.py b/source_code/builtin_structures/reverse_string.py deleted file mode 100755 index e20d32f..0000000 --- a/source_code/builtin_structures/reverse_string.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -def revert(string): - ''' - >>> s = 'hello' - >>> revert(s) - 'olleh' - >>> revert('') - '' - ''' - return string[::-1] - - - -def reverse_string_inplace(s): - ''' - >>> s = 'hello' - >>> reverse_string_inplace(s) - 'olleh' - >>> reverse_string_inplace('') - '' - ''' - if s: - s = s[-1] + reverse_string_inplace(s[:-1]) - return s - - - - - - -if __name__ == '__main__': - import doctest - doctest.testmod() \ No newline at end of file diff --git a/source_code/builtin_structures/reverse_words.py b/source_code/builtin_structures/reverse_words.py deleted file mode 100755 index 775ad99..0000000 --- a/source_code/builtin_structures/reverse_words.py +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - - -def reversing_words(word): - """ - >>> reversing_words('buffy is awesome') - 'awesome is buffy' - """ - new_word = [] - - words = word.split(' ') - for word in words[::-1]: - new_word.append(word) - - return " ".join(new_word) - - -def reversing_words2(s): - """ - >>> reversing_words2('buffy is awesome') - 'awesome is buffy' - """ - words = s.split() - return ' '.join(reversed(words)) - - -def reversing_words3(s): - """ - >>> reversing_words('buffy is awesome') - 'awesome is buffy' - """ - words = s.split(' ') - words.reverse() - return ' '.join(words) - - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/builtin_structures/rotate_NxN.py b/source_code/builtin_structures/rotate_NxN.py deleted file mode 100755 index f841bad..0000000 --- a/source_code/builtin_structures/rotate_NxN.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -def rotate_NxN(m): - n = len(m) - for layer in range(n//2): - first = layer - last = n - 1 - layer - for i in range(first, last): - offset = i - first - top = m[first][i] - m[first][i] = m[last-offset][first] - m[last-offset][first] = m[last][last-offset] - m[last][last-offset] = m[i][last] - m[i][last] = top - return m - - - -def main(): - m = [[1,2],[3,4]] - mr = [[3,1],[4,2]] - assert(rotate_NxN(m) == mr) - m2 = [[1,2,3],[4,5,6],[7,8,9]] - print(rotate_NxN(m2)) - -if __name__ == '__main__': - main() - diff --git a/source_code/builtin_structures/runtime_dicts_with_timeit_module.py b/source_code/builtin_structures/runtime_dicts_with_timeit_module.py deleted file mode 100755 index b54c637..0000000 --- a/source_code/builtin_structures/runtime_dicts_with_timeit_module.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -'''To use timeit you create a Timer object whose parameters are two Python -statements. The first parameter is a Python statement that you want to time; -the second parameter is a statement that will run once to set up the test. -The timeit module will then time how long it takes to execute the statement -some number of times. By default timeit will try to run the statement one -million times. When its done it returns the time as a floating point value -representing the total number of seconds. However, since it executes the -statement a million times you can read the result as the number of -microseconds to execute the test one time. You can also pass timeit a -named parameter called number that allows you to specify how many times the -test statement is executed. The following session shows how long it takes to -run each of our test functions 1000 times. ''' - - -import timeit -import random - -for i in range(10000,1000001,20000): - ''' this experiment confirm that the contains operator for lists is O(n) and for dict is O(1) ''' - t = timeit.Timer("random.randrange(%d) in x"%i, "from __main__ import random,x") - x = list(range(i)) - lst_time = t.timeit(number=1000) - x = {j:None for j in range(i)} - d_time = t.timeit(number=1000) - print("%d,%10.3f,%10.3f" % (i, lst_time, d_time)) - - -""" There results are: -10000, 0.192, 0.002 -30000, 0.600, 0.002 -50000, 1.000, 0.002 -70000, 1.348, 0.002 -90000, 1.755, 0.002 -110000, 2.194, 0.002 -130000, 2.635, 0.002 -150000, 2.951, 0.002 -170000, 3.405, 0.002 -190000, 3.743, 0.002 -210000, 4.142, 0.002 -230000, 4.577, 0.002 -250000, 4.797, 0.002 -270000, 5.371, 0.002 -290000, 5.690, 0.002 -310000, 5.977, 0.002 - -so we can see the linear tile for lists, and constant for dict! - -Big-O Efficiency of Python Dictionary Operations -Operation Big-O Efficiency -copy O(n) -get item O(1) -set item O(1) -delete item O(1) -contains (in) O(1) -iteration O(n) -""" - diff --git a/source_code/builtin_structures/runtime_lists_with_timeit_module.py b/source_code/builtin_structures/runtime_lists_with_timeit_module.py deleted file mode 100755 index f7da733..0000000 --- a/source_code/builtin_structures/runtime_lists_with_timeit_module.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -'''To use timeit you create a Timer object whose parameters are two Python statements. The first parameter is a Python statement that you want to time; the second parameter is a statement that will run once to set up the test. The timeit module will then time how long it takes to execute the statement some number of times. By default timeit will try to run the statement one million times. When its done it returns the time as a floating point value representing the total number of seconds. However, since it executes the statement a million times you can read the result as the number of microseconds to execute the test one time. You can also pass timeit a named parameter called number that allows you to specify how many times the test statement is executed. The following session shows how long it takes to run each of our test functions 1000 times. ''' - - -def test1(): - l = [] - for i in range(1000): - l = l + [i] - -def test2(): - l = [] - for i in range(1000): - l.append(i) - -def test3(): - l = [i for i in range(1000)] - -def test4(): - l = list(range(1000)) - - - -if __name__ == '__main__': - import timeit - t1 = timeit.Timer("test1()", "from __main__ import test1") - print("concat ",t1.timeit(number=1000), "milliseconds") - t2 = timeit.Timer("test2()", "from __main__ import test2") - print("append ",t2.timeit(number=1000), "milliseconds") - t3 = timeit.Timer("test3()", "from __main__ import test3") - print("comprehension ",t3.timeit(number=1000), "milliseconds") - t4 = timeit.Timer("test4()", "from __main__ import test4") - print("list range ",t4.timeit(number=1000), "milliseconds") - - - -""" The results are: -('concat ', 2.366791009902954, 'milliseconds') -('append ', 0.16743111610412598, 'milliseconds') -('comprehension ', 0.06446194648742676, 'milliseconds') -('list range ', 0.021029949188232422, 'milliseconds') - - -So we see the following pattern for lists: - -Operation Big-O Efficiency -index [] O(1) -index assignment O(1) -append O(1) -pop() O(1) -pop(i) O(n) -insert(i,item) O(n) -del operator O(n) -iteration O(n) -contains (in) O(n) -get slice [x:y] O(k) -del slice O(n) -set slice O(n+k) -reverse O(n) -concatenate O(k) -sort O(n log n) -multiply O(nk) -""" - diff --git a/source_code/builtin_structures/search_entry_matrix.py b/source_code/builtin_structures/search_entry_matrix.py deleted file mode 100755 index 6d70fdd..0000000 --- a/source_code/builtin_structures/search_entry_matrix.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/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): - - found = False - row = 0 - col = len(m1[0]) - 1 - - while row < len(m1) and col >= 0: - - if m1[row][col] == value: - found = True - break - elif m1[row][col] > value: - col-=1 - else: - row+=1 - - return found - - - -def test_find_elem_matrix_bool(module_name='this module'): - m1 = [[1,2,8,9], [2,4,9,12], [4,7,10,13], [6,8,11,15]] - assert(find_elem_matrix_bool(m1,8) == True) - assert(find_elem_matrix_bool(m1,3) == False) - m2 = [[0]] - assert(find_elem_matrix_bool(m2,0) == True) - - -if __name__ == '__main__': - test_find_elem_matrix_bool() - diff --git a/source_code/builtin_structures/simple_str_comprension.py b/source_code/builtin_structures/simple_str_comprension.py deleted file mode 100755 index 6a516df..0000000 --- a/source_code/builtin_structures/simple_str_comprension.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -from collections import Counter - -def str_comp(s): - ''' - >>> s1 = 'aabcccccaaa' - >>> str_comp(s1) - 'a2b1c5a3' - >>> str_comp('') - '' - ''' - - count, last = 1, '' - list_aux = [] - for i, c in enumerate(s): - if last == c: - count += 1 - else: - if i != 0: - list_aux.append(str(count)) - list_aux.append(c) - count = 1 - last = c - list_aux.append(str(count)) - return ''.join(list_aux) - - -if __name__ == '__main__': - import doctest - doctest.testmod() diff --git a/source_code/builtin_structures/sum_two_numbers_as_strings.py b/source_code/builtin_structures/sum_two_numbers_as_strings.py deleted file mode 100755 index ec05a14..0000000 --- a/source_code/builtin_structures/sum_two_numbers_as_strings.py +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' -find the sum of two integers represented as strings, -return the sum as string, i.e "123" and "456" would return "579" -''' - - -def get_number(s): - count = 1 - num = 0 - p = len(s) -1 - while p >= 0: - num = num + int(s[p])*count - count *= 10 - p -= 1 - return num - - -def sum_string(s1, s2): - ''' - >>> sum_string('10', '5') - '15' - >>> sum_string('0', '1') - '1' - >>> sum_string('123', '456') - '579' - ''' - - n1 = get_number(s1) - n2 = get_number(s2) - return str(n2 + n1) - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/learning/decorator.py b/source_code/learning/decorator.py deleted file mode 100644 index 8ef04f3..0000000 --- a/source_code/learning/decorator.py +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/python -# -# An example of Python Decorator -# - -def pretty_sumab(func): - def inner(a,b): - print(str(a) + " + " + str(b) + " is ", end="") - return func(a,b) - - return inner - -@pretty_sumab -def sumab(a,b): - summed = a + b - print(summed) - -if __name__ == "__main__": - sumab(5,3) \ No newline at end of file diff --git a/source_code/searching_and_sorting/searching/__init__.py b/source_code/searching_and_sorting/searching/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/source_code/searching_and_sorting/searching/binary_search.py b/source_code/searching_and_sorting/searching/binary_search.py deleted file mode 100644 index 79570cf..0000000 --- a/source_code/searching_and_sorting/searching/binary_search.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -def binary_search(array, item, hi=None, lo=0): - ''' - >>> binary_search([2,3,5,6,8,10,15,23], 15) - 6 - >>> binary_search([2,3,5,6,8,10,15,23], 4) - False - >>> binary_search([1,3,4,5,7,8 ,10,12,23], 10) - 6 - >>> binary_search([1,3,4,5,7,8 ,10,12,23], 22) - False - ''' - - hi = hi or len(array) - if hi < lo: - return False - - mid = (hi + lo)//2 - if item == array[mid]: - return mid - elif item < array[mid]: - return binary_search(array, item, hi=mid-1, lo=lo) - else: - return binary_search(array, item, hi=hi, lo=mid+1) - - - - -def binary_search_iter(array, item): - ''' - >>> binary_search_iter([2,3,5,6,8,10,15,23], 15) - 6 - >>> binary_search_iter([2,3,5,6,8,10,15,23], 4) - False - >>> binary_search_iter([1,3,4,5,7,8 ,10,12,23], 10) - 6 - >>> binary_search_iter([1,3,4,5,7,8 ,10,12,23], 22) - False - ''' - lo, hi = 0, len(array) - - while lo < hi: - mid = (hi+lo)//2 - if array[mid] == item: - return mid - elif array[mid] > item: - hi = mid - else: - lo=mid+1 - return False - - - - - - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/searching_and_sorting/searching/binary_search_matrix.py b/source_code/searching_and_sorting/searching/binary_search_matrix.py deleted file mode 100644 index 98f3d96..0000000 --- a/source_code/searching_and_sorting/searching/binary_search_matrix.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -def binary_search_matrix_rec(m, key, lo=0, hi=None): - ''' - >>> m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] - >>> binary_search_matrix_rec(m, 6) - (1, 2) - >>> binary_search_matrix_rec(m, 12) - ''' - if not m: - return None - - rows = len(m) - cols = len(m[0]) - hi = hi or rows*cols - - if hi > lo: - - mid = (hi + lo)//2 - row = mid//cols - col = mid%cols - item = m[row][col] - - if key == item: - return row, col - elif key < item: - return binary_search_matrix_rec(m, key, lo, mid-1) - else: - return binary_search_matrix_rec(m, key, mid+1, hi) - - return None - - - -def binary_search_matrix_iter(m, key): - ''' - - ''' - - if not m: - return None - rows = len(m) - cols = len(m[0]) - lo, hi = 0, rows*cols - - while lo < hi: - mid = (hi + lo)//2 - row = mid//rows - col = mid%rows - item = m[row][col] - if key == item: - return (row, col) - elif key < item: - hi = mid - else: - lo = mid +1 - - return None - - -def searching_matrix(m, key): - ''' - >>> m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] - >>> searching_matrix(m, 6) - (1, 2) - >>> searching_matrix(m, 12) - ''' - - if not m: - return None - rows = len(m) - cols = len(m[0]) - i, j = 0, cols -1 - - while i < rows and j > 0: - item = m[i][j] - if key == item: - return (i, j) - elif key < item: - j -= 1 - else: - i += 1 - - return None - - -if __name__ == '__main__': - import doctest - doctest.testmod() diff --git a/source_code/searching_and_sorting/searching/find_item_rotated_sorted_array.py b/source_code/searching_and_sorting/searching/find_item_rotated_sorted_array.py deleted file mode 100644 index 2c5eadd..0000000 --- a/source_code/searching_and_sorting/searching/find_item_rotated_sorted_array.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - - -''' -Given a sorted array that was rotated, find an item with binary search: -''' - -def find_element_rot_array(seq, key, lo=0, hi=None): - - hi = hi or len(seq) - if hi <= lo: - return None # base case: <= for odd and even numbers! - - mid = (hi + lo) // 2 - - if key == seq[mid]: - return mid - - # if left is ordered --> we work here - if seq[lo] <= seq[mid]: - - # now, is the key there? - if key < seq[mid] and key >= seq[lo]: - return find_element_rot_array(seq, key, lo, mid) - else: - # all the other cases - return find_element_rot_array(seq, key, mid+1, hi) - - # right is ordered --> we work here - else: - - # now, is the key there? - if key > seq[mid] and key <= seq[hi-1]: # stupid hi-1!!! - return find_element_rot_array(seq, key, mid+1, hi) - else: - # all the other cases - return find_element_rot_array(seq, key, lo, mid) - - -def test_find_element_rot_array(): - l1 = [3, 4, 5, 6, 7, 1, 2] - assert(find_element_rot_array(l1, 7) == 4 ) - print("Tests passed!") - - -if __name__ == '__main__': - test_find_element_rot_array() - diff --git a/source_code/searching_and_sorting/searching/find_max_unimodal_array.py b/source_code/searching_and_sorting/searching/find_max_unimodal_array.py deleted file mode 100644 index 1a57dd5..0000000 --- a/source_code/searching_and_sorting/searching/find_max_unimodal_array.py +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -def find_max_unimodal_array(A): - if len(A) <= 2 : - return None - left = 0 - right = len(A)-1 - - while right > left +1: - - mid = (left + right)//2 - if A[mid] > A[mid-1] and A[mid] > A[mid+1]: - return A[mid] - elif A[mid] > A[mid-1] and A[mid] < A[mid+1]: - left = mid - else: - right = mid - - return None - - -def test_find_max_unimodal_array(): - seq = [1, 2, 5, 6, 7, 10, 12, 9, 8, 7, 6] - assert(find_max_unimodal_array(seq) == 12) - print('Tests passed!') - - -if __name__ == '__main__': - test_find_max_unimodal_array() - - - - diff --git a/source_code/searching_and_sorting/searching/find_sqrt_bin_search.py b/source_code/searching_and_sorting/searching/find_sqrt_bin_search.py deleted file mode 100644 index 6bef19f..0000000 --- a/source_code/searching_and_sorting/searching/find_sqrt_bin_search.py +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -''' implement square root using binary search ''' - - -def find_sqrt_bin_search(n, error=0.001): - lower = n < 1 and n or 1 - upper = n < 1 and 1 or n - mid = lower + (upper - lower) / 2.0 - square = mid * mid - while abs(square - n) > error: - if square < n: - lower = mid - else: - upper = mid - mid = lower + (upper - lower) / 2.0 - square = mid * mid - return mid - - -def test_ind_sqrt_bin_search(): - number = 9 - assert(find_sqrt_bin_search(number) == 3) - print('Tests passed!') - - -if __name__ == '__main__': - test_ind_sqrt_bin_search() - - - - - diff --git a/source_code/searching_and_sorting/searching/find_str_array_with_empty_str.py b/source_code/searching_and_sorting/searching/find_str_array_with_empty_str.py deleted file mode 100644 index fa66428..0000000 --- a/source_code/searching_and_sorting/searching/find_str_array_with_empty_str.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' Given a sorted an array with empty strings, - we use binary search to find some string (since the list is sorted): - --> we deal with the empty strings with strip and then run to left - and right, or move mid to the closed non-empty str (remember that - the index must be conserved): -''' - - -def find_str_array_with_empty_str(seq, s1): - if not seq or not s1: - return None - hi = len(seq) - lo = 0 - - while hi > lo: - mid = (hi+lo)//2 - - if seq[mid] == '': - while True: - left = mid-1 - right = mid+1 - if left < lo or right > hi: return None - elif right < hi and seq[right]: - mid = right - break - elif left > lo and seq[left]: - mid = left - break - right += 1 - left -= 1 - - if s1 == seq[mid] == s1: - return mid - elif s1 < seq[mid]: - hi = mid - else: - lo = mid + 1 - - - -def test_find_str_array_with_empty_str(): - seq = ['acre', 'ball', '', 'coach', '', 'cut', ''] - key = seq[1] - assert(find_str_array_with_empty_str(seq, key) == 1) - print('Tests passed!') - - -if __name__ == '__main__': - test_find_str_array_with_empty_str() diff --git a/source_code/searching_and_sorting/searching/find_time_occurence_list.py b/source_code/searching_and_sorting/searching/find_time_occurence_list.py deleted file mode 100644 index af26ded..0000000 --- a/source_code/searching_and_sorting/searching/find_time_occurence_list.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -def binary_serch_counting(lst1, k, lo=0, hi=None): - if hi is None: hi = len(lst1) - while lo < hi: - mid = (lo+hi)//2 - midval = lst1[mid] - if midval < k: - lo = mid +1 - elif midval > k: - hi = mid - else: - return mid - return -1 - - -def find_time_occurrence_list(seq, k): - """ find how many times a k element appears in a sorted list. - One way of doing this is using collections.OrderedDict to no - mess with the sorting, and add entries for every count. This - should be O(n). It has a O(1) space complexity since the size of - the dict is fixed. Another way, since the array is sorted, it to - use binary search, since this is only O(logn). - """ - index_some_k = binary_serch_counting(seq, k) - count = 1 - sizet = len(seq) - - for i in range(index_some_k+1, sizet): # go up - if seq[i] == k: count +=1 - else: break - - for i in range(index_some_k-1, -1, -1): # go down - if seq[i] == k: count +=1 - else: break - - return count - - -def test_find_time_occurrence_list(): - seq = [1,2,2,2,2,2,2,5,6,6,7,8,9] - k = 2 - assert(find_time_occurrence_list(seq, k) == 6) - print('Tests passed!') - - -if __name__ == '__main__': - test_find_time_occurrence_list() - diff --git a/source_code/searching_and_sorting/searching/ordered_sequential_search.py b/source_code/searching_and_sorting/searching/ordered_sequential_search.py deleted file mode 100644 index 8f24d20..0000000 --- a/source_code/searching_and_sorting/searching/ordered_sequential_search.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - - -def ordered_sequential_search(seq, n): - ''' an example of sequential search in an ordered seq: - it improves the performance if the item is not present ''' - item = 0 - for item in seq: - if item > n: return False - if item == n: return True - return False - - -def test_ordered_sequential_search(module_name='this module'): - seq = [1, 2, 4, 5, 6, 8, 10] - n1 = 10 - n2 = 7 - assert(ordered_sequential_search(seq, n1) == True) - assert(ordered_sequential_search(seq, n2) == False) - - s = 'Tests in {name} have {con}!' - print(s.format(name=module_name, con='passed')) - - -if __name__ == '__main__': - test_ordered_sequential_search() - - -""" -Case Best Case Worst Case Average Case -item is present 1 n n/2 -item not present 1 n n/2 -""" diff --git a/source_code/searching_and_sorting/searching/quick_select.py b/source_code/searching_and_sorting/searching/quick_select.py deleted file mode 100644 index ef5a629..0000000 --- a/source_code/searching_and_sorting/searching/quick_select.py +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -import random - -''' The simplest way...''' -def quickSelect(seq, k): - # this part is the same as quick sort - len_seq = len(seq) - if len_seq < 2: return seq - - # we could use a random choice here doing - #pivot = random.choice(seq) - ipivot = len_seq // 2 - pivot = seq[ipivot] - - # O(n) - smallerList = [x for i,x in enumerate(seq) if x <= pivot and i != ipivot] - largerList = [x for i,x in enumerate(seq) if x > pivot and i != ipivot] - - # here starts the different part - m = len(smallerList) - if k == m: - return pivot - elif k < m: - return quickSelect(smallerList, k) - else: - return quickSelect(largerList, k-m-1) - - - -''' If you don't want to use pythons feature at all and - also select pivot randomly''' - -def swap(seq, x, y): - tmp = seq[x] - seq[x] = seq[y] - seq[y] = tmp - - -def quickSelectHard(seq, k, left=None, right=None): - left = left or 0 - right = right or len(seq) - 1 - #ipivot = random.randint(left, right) - ipivot = len(seq)//2 - pivot = seq[ipivot] - - # Move pivot out of the sorting range - swap(seq, ipivot, right) - swapIndex, i = left, left - while i < right: - if seq[i] < pivot: - swap(seq, i, swapIndex) - swapIndex += 1 - i += 1 - - # Move pivot to final position - swap(seq, right, swapIndex) - - # Check if pivot matches, else recurse on the correct half - rank = len(seq) - swapIndex - - - if k == rank: - return seq[swapIndex] - elif k < rank: - return quickSelectHard(seq, k, swapIndex+1, right) - else: - return quickSelectHard(seq, k, left, swapIndex-1) - - - - -if __name__ == '__main__': - # Checking the Answer - seq = [10, 60, 100, 50, 60, 75, 31, 50, 30, 20, 120, 170, 200] - #seq = [3, 7, 2, 1, 4, 6, 5, 10, 9, 11] - - # we want the middle element - k = len(seq) // 2 - - # Note that this only work for odd arrays, since median in - # even arrays is the mean of the two middle elements - print(quickSelect(seq, k)) - print(quickSelectHard(seq, k)) - import numpy - print numpy.median(seq) \ No newline at end of file diff --git a/source_code/searching_and_sorting/searching/searching_in_a_matrix.py b/source_code/searching_and_sorting/searching/searching_in_a_matrix.py deleted file mode 100644 index 92a3bdc..0000000 --- a/source_code/searching_and_sorting/searching/searching_in_a_matrix.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -import numpy - -def searching_in_a_matrix(m1, value): - """ searches an element in a matrix where in every row, the values are increasing from left to - right, but the last number in a row is smaller than the first number in the next row. - The naive brute force solution scan all numbers and cost O(nm). However, since the numbers are - already sorted, the matrix can be viewed as a 1D sorted array. The binary search algorithm is - suitable. The efficience is O(logmn).""" - - rows = len(m1) - cols = len(m1[0]) - lo = 0 - hi = rows*cols - while lo < hi: - mid = (lo + hi)//2 - row = mid//cols - col = mid%cols - v = m1[row][col] - if v == value: return True - elif v > value: hi = mid - else: lo = mid+1 - return False - - - -def test_searching_in_a_matrix(): - a = [[1,3,5],[7,9,11],[13,15,17]] - b = numpy.array([(1,2),(3,4)]) - assert(searching_in_a_matrix(a, 13) == True) - assert(searching_in_a_matrix(a, 14) == False) - assert(searching_in_a_matrix(b, 3) == True) - assert(searching_in_a_matrix(b, 5) == False) - print('Tests passed!') - - -if __name__ == '__main__': - test_searching_in_a_matrix() - - - - - - - - diff --git a/source_code/searching_and_sorting/searching/sequential_search.py b/source_code/searching_and_sorting/searching/sequential_search.py deleted file mode 100644 index 6d389ce..0000000 --- a/source_code/searching_and_sorting/searching/sequential_search.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -def sequential_search(seq, n): - ''' an example of sequential search (for items stored in a collection) ''' - for item in seq: - if item == n: return True - return False - - -def test_sequential_search(module_name='this module'): - seq = [1, 5, 6, 8, 3] - n1 = 5 - n2 = 7 - assert(sequential_search(seq, n1) == True) - assert(sequential_search(seq, n2) == False) - - s = 'Tests in {name} have {con}!' - print(s.format(name=module_name, con='passed')) - - -if __name__ == '__main__': - test_sequential_search() - - -""" -Case Best Case Worst Case Average Case -item is present 1 n n2 -item is not present n n n -""" \ No newline at end of file diff --git a/source_code/searching_and_sorting/sorting/1.dat b/source_code/searching_and_sorting/sorting/1.dat deleted file mode 100644 index 8a1218a..0000000 --- a/source_code/searching_and_sorting/sorting/1.dat +++ /dev/null @@ -1,5 +0,0 @@ -1 -2 -3 -4 -5 diff --git a/source_code/searching_and_sorting/sorting/2.dat b/source_code/searching_and_sorting/sorting/2.dat deleted file mode 100644 index 18b0eef..0000000 --- a/source_code/searching_and_sorting/sorting/2.dat +++ /dev/null @@ -1,4 +0,0 @@ -3 -5 -6 -7 diff --git a/source_code/searching_and_sorting/sorting/3.dat b/source_code/searching_and_sorting/sorting/3.dat deleted file mode 100644 index 3a07591..0000000 --- a/source_code/searching_and_sorting/sorting/3.dat +++ /dev/null @@ -1,4 +0,0 @@ -1 -3 -5 -8 diff --git a/source_code/searching_and_sorting/sorting/__init__.py b/source_code/searching_and_sorting/sorting/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/source_code/searching_and_sorting/sorting/bubble_sort.py b/source_code/searching_and_sorting/sorting/bubble_sort.py deleted file mode 100644 index 0d72e77..0000000 --- a/source_code/searching_and_sorting/sorting/bubble_sort.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -def bubble_sort(seq): - """ - Implementation of bubble sort. - O(n2) and thus highly ineffective. - """ - size = len(seq) -1 - for num in range(size, 0, -1): - for i in range(num): - if seq[i] > seq[i+1]: - temp = seq[i] - seq[i] = seq[i+1] - seq[i+1] = temp - return seq - - -def test_bubble_sort(module_name='this module'): - seq = [4, 5, 2, 1, 6, 2, 7, 10, 13, 8] - assert(bubble_sort(seq) == sorted(seq)) - - -if __name__ == '__main__': - test_bubble_sort() - diff --git a/source_code/searching_and_sorting/sorting/count_sort.py b/source_code/searching_and_sorting/sorting/count_sort.py deleted file mode 100644 index 8bdfc23..0000000 --- a/source_code/searching_and_sorting/sorting/count_sort.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - - -from collections import defaultdict - -def count_sort_dict(a): - ''' an example of counting sort using default dictionaries ''' - b, c = [], defaultdict(list) - for x in a: - c[x].append(x) # we could have used key = lambda x:x - for k in range(min(c), max(c) + 1): - b.extend(c[k]) - return b - - -def test_count_sort(): - seq = [3, 5, 2, 6, 8, 1, 0, 3, 5, 6, 2, 5, 4, 1, 5, 3] - assert(count_sort_dict(seq) == sorted(seq)) - - -if __name__ == '__main__': - test_count_sort() - - diff --git a/source_code/searching_and_sorting/sorting/gnome_sort.py b/source_code/searching_and_sorting/sorting/gnome_sort.py deleted file mode 100644 index efad801..0000000 --- a/source_code/searching_and_sorting/sorting/gnome_sort.py +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -def gnome_sort(seq): - ''' sort a sequence using the gnome sort alg ''' - i = 0 - while i < len(seq): - if i ==0 or seq[i-1] <= seq[i]: - i += 1 - else: - seq[i], seq[i-1] = seq[i-1], seq[i] - i -= 1 - return seq - - -def test_gnome_sort(): - seq = [3, 5, 2, 6, 8, 1, 0, 3, 5, 6, 2, 5, 4, 1, 5, 3] - assert(gnome_sort(seq) == sorted(seq)) - - -if __name__ == '__main__': - test_gnome_sort() - - - - - - - diff --git a/source_code/searching_and_sorting/sorting/heap.py b/source_code/searching_and_sorting/sorting/heap.py deleted file mode 100644 index b22326c..0000000 --- a/source_code/searching_and_sorting/sorting/heap.py +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -class Heap(object): - def __init__(self, data): - self.data = data - for i in range(len(data)/2, -1, -1): - self.__max_heapify__(i) - - - def parent(self, i): - return i >> 1 - - - def left_child(self, i): - return (i << 1) + 1 - - - 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) - 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 != largest: - self.data[i], self.data[largest] = self.data[largest], self.data[i] - self.__max_heapify__(largest) - - - def extract_max(self): - n = len(self.data) - max_element = self.data[0] - self.data[0] = self.data[n - 1] - self.data = self.data[:n - 1] - self.__max_heapify__(0) - return max_element - - diff --git a/source_code/searching_and_sorting/sorting/heap_sort.py b/source_code/searching_and_sorting/sorting/heap_sort.py deleted file mode 100644 index bcbf639..0000000 --- a/source_code/searching_and_sorting/sorting/heap_sort.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' Heapsort using Pythons libraries''' - -import heapq - -def heap_sort1(seq): - ''' heap sort with Python's heapq ''' - h = [] - for value in seq: - heapq.heappush(h, value) - return [heapq.heappop(h) for i in range(len(h))] - - -def test_heap_sort1(): - seq = [3, 5, 2, 6, 8, 1, 0, 3, 5, 6, 2] - assert(heap_sort1(seq) == sorted(seq)) - print('Tests passed!') - - - -''' Heapsort using my Heap class ''' - -from heap import Heap - -def heap_sort2(seq): - heap = Heap(seq) - - res = [] - for i in range(len(seq)): - res.insert(0, heap.extract_max()) - - return res - - -def test_heap_sort2(): - seq = [3, 5, 2, 6, 8, 1, 0, 3, 5, 6, 2] - print heap_sort2(seq) - print('Tests passed!') - - -''' A third way of doing heap sort ''' - -def heap_sort3(seq): - for start in range((len(seq)-2)//2, -1, -1): - siftdown(seq, start, len(seq)-1) - for end in range(len(seq)-1, 0, -1): - seq[end], seq[0] = seq[0], seq[end] - siftdown(seq, 0, end - 1) - return seq - -def siftdown(seq, start, end): - root = start - while True: - child = root * 2 + 1 - if child > end: break - if child + 1 <= end and seq[child] < seq[child + 1]: - child += 1 - if seq[root] < seq[child]: - seq[root], seq[child] = seq[child], seq[root] - root = child - else: - break - - - -def test_heap_sort3(): - seq = [3, 5, 2, 6, 8, 1, 0, 3, 5, 6, 2] - assert(heap_sort3(seq) == sorted(seq)) - print('Tests passed!') - - - - - - - -if __name__ == '__main__': - test_heap_sort1() - test_heap_sort2() - test_heap_sort3() diff --git a/source_code/searching_and_sorting/sorting/insertion_sort.py b/source_code/searching_and_sorting/sorting/insertion_sort.py deleted file mode 100644 index 922e3a6..0000000 --- a/source_code/searching_and_sorting/sorting/insertion_sort.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - - - -def insertion_sort(seq): - ''' sort a sequence using the insertion sort alg ''' - for i in range(1, len(seq)): - j = i - while j > 0 and seq[j-1] > seq[j]: - seq[j-1], seq[j] = seq[j], seq[j-1] - j -= 1 - return seq - - -def insertion_sort_rec(seq, i = None): - ''' sort a sequence using the recursive insertion sort alg ''' - if i == None: i = len(seq) -1 - if i == 0: return i - insertion_sort_rec(seq, i-1) - j = i - while j > 0 and seq[j-i] > seq[j]: - seq[j-1], seq[j] = seq[j], seq[j-1] - j -= 1 - return seq - - -def test_insertion_sort(): - seq = [3, 5, 2, 6, 8, 1, 0, 3, 5, 6, 2, 5, 4, 1, 5, 3] - assert(insertion_sort(seq) == sorted(seq)) - assert(insertion_sort_rec(seq) == sorted(seq)) - - -if __name__ == '__main__': - test_insertion_sort() - - - - - - - diff --git a/source_code/searching_and_sorting/sorting/merge_and_sort_two_arrays.py b/source_code/searching_and_sorting/sorting/merge_and_sort_two_arrays.py deleted file mode 100644 index 4af24a8..0000000 --- a/source_code/searching_and_sorting/sorting/merge_and_sort_two_arrays.py +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -''' -You have two arrays with N integers in them. Merge those arrays using a -recursive algorithm so that the integers in the final array are sorted. -''' - -def merge_arrays(a1, a2): - ''' - >>> merge_arrays([5, 4, 3], [6, 2, 9]) - [2, 3, 4, 5, 6, 9] - >>> merge_arrays([2, 6], [6, 2]) - [2, 2, 6, 6] - >>> merge_arrays([], []) - [] - ''' - # if they are not sorted yet - a1.sort() - a2.sort() - - merge = [] - p1, p2 = 0, 0 - - while p1 < len(a1) and p2 < len(a2): - if a1[p1] <= a2[p2]: - merge.append(a1[p1]) - p1 += 1 - else: - merge.append(a2[p2]) - p2 +=1 - - if a1[p1:]: - merge.extend(a1[p1:]) - - if a2[p2:]: - merge.extend(a2[p2:]) - - return merge - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/searching_and_sorting/sorting/merge_sort.py b/source_code/searching_and_sorting/sorting/merge_sort.py deleted file mode 100644 index fd5ac54..0000000 --- a/source_code/searching_and_sorting/sorting/merge_sort.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -def merge_sort(array): - ''' - >>> merge_sort([3 ,5, 1, 2, 10, 6]) - [1, 2, 3, 5, 6, 10] - ''' - if len(array) < 2: - return array - - mid = len(array)//2 - left = merge_sort(array[:mid]) - right = merge_sort(array[mid:]) - - res = [] - i, j = 0, 0 - while i < len(left) and j < len(right): - if left[i] <= right[j]: - res.append(left[i]) - i += 1 - else: - res.append(right[j]) - j += 1 - - if left[i:]: - res.extend(left[i:]) - if right[j:]: - res.extend(right[j:]) - return res - - - -''' Merge sort for files ''' -def merge_files(list_files): - result = [] - final = [] - for filename in list_files: - aux = [] - with open(filename, 'r') as file: - for line in file: - aux.append(int(line)) - result.append(aux) - final.extend(result.pop()) - for l in result: - final = merge(l, final) - return final - - -if __name__ == '__main__': - import doctest - doctest.testmod() \ No newline at end of file diff --git a/source_code/searching_and_sorting/sorting/quick_sort.py b/source_code/searching_and_sorting/sorting/quick_sort.py deleted file mode 100644 index 5596d1a..0000000 --- a/source_code/searching_and_sorting/sorting/quick_sort.py +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -def qs(array): - ''' - >>> qs([4,1,6,2,7,9,3]) - [1, 2, 3, 4, 6, 7, 9] - ''' - if len(array) < 2: - return array - - piv = len(array)//2 - piv_element = array[piv] - new_array = array[:piv] + array[piv+1:] - - left = [a for a in new_array if a <= piv_element] - right = [a for a in new_array if a > piv_element] - - return qs(left) + [array[piv]] + qs(right) - - - -# we can also divide them into two functions -def partition(seq): - pi,seq = seq[0],seq[1:] - lo = [x for x in seq if x <= pi] - hi = [x for x in seq if x > pi] - return lo, pi, hi - -def quick_sort_divided(seq): - ''' - >>> quick_sort_divided([4,1,6,2,7,9,3]) - [1, 2, 3, 4, 6, 7, 9] - ''' - if len(seq) < 2: - return seq - lo, pi, hi = partition(seq) - return quick_sort_divided(lo) + [pi] + quick_sort_divided(hi) - - - -if __name__ == '__main__': - import doctest - doctest.testmod() \ No newline at end of file diff --git a/source_code/searching_and_sorting/sorting/selection_sort.py b/source_code/searching_and_sorting/sorting/selection_sort.py deleted file mode 100644 index 65fc169..0000000 --- a/source_code/searching_and_sorting/sorting/selection_sort.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -def selection_sort(seq): - ''' sort a sequence using the selection sort alg ''' - for i in range(len(seq) -1, 0, -1): - max_j = i - for j in range(max_j): - if seq[j] > seq[max_j]: - max_j = j - seq[i], seq[max_j] = seq[max_j], seq[i] - return seq - - -def test_selection_sort(): - seq = [3, 5, 2, 6, 8, 1, 0, 3, 5, 6, 2] - assert(selection_sort(seq) == sorted(seq)) - - -if __name__ == '__main__': - test_selection_sort() - - - - - - - diff --git a/source_code/searching_and_sorting/sorting/sort_anagrams_together.py b/source_code/searching_and_sorting/sorting/sort_anagrams_together.py deleted file mode 100644 index 1a20417..0000000 --- a/source_code/searching_and_sorting/sorting/sort_anagrams_together.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' A method to sort an array so that all the anagrams are together. - Since we only want the anagrams to be grouped, we can use a - dictionary for this task. This algorithm is O(n). -''' - -from collections import defaultdict - -def sort_anagrams_together(l1): - ''' - >>> l1 = ['hat', 'ball', 'tha', 'cut', 'labl', 'hta', 'cool', 'cuy', 'uct'] - >>> sort_anagrams_together(l1) - ['cuy', 'cut', 'uct', 'cool', 'ball', 'labl', 'hat', 'tha', 'hta'] - ''' - result = [] - - dict_aux = defaultdict(list) - for word in l1: - key = ''.join(sorted(word)) - dict_aux[key].append(word) - - for key in dict_aux: - result.extend(dict_aux[key]) - - return result - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/source_code/trees/__init__.py b/source_code/trees/__init__.py deleted file mode 100755 index e69de29..0000000 diff --git a/source_code/trees/binary_search_tree.py b/source_code/trees/binary_search_tree.py deleted file mode 100755 index 9f82203..0000000 --- a/source_code/trees/binary_search_tree.py +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/python - -__author__ = "bt3" - - -class Node(object): - - def __init__(self, item=None,): - - self.item = item - self.left = None - self.right = None - - def __repr__(self): - return '{}'.format(self.item) - - - def _add(self, value): - new_node = Node(value) - - if not self.item: - self.item = new_node - - else: - if value > self.item: - self.right = self.right and self.right._add(value) or new_node - elif value < self.item: - self.left = self.left and self.left._add(value) or new_node - else: - print("BSTs do not support repeated items.") - - return self # this is necessary!!! - - - def _search(self, value): - if self.item == value: - return True # or self - - elif self.left and value < self.item: - return self.left._search(value) - - elif self.right and value > self.item: - return self.right._search(value) - - else: - return False - - - def _isLeaf(self): - return not self.right and not self.left - - - def _printPreorder(self): - print self.item - - if self.left: - self.left._printPreorder() - - if self.right: - self.right._printPreorder() - - # Another possibility: use an array (a little bit more expensive): - def _preorder_array(self): - nodes = [] - if self.item: - nodes.append(self.item) - if self.left: - nodes.extend(self.left._preorder_array()) - if self.right: - nodes.extend(self.right._preorder_array()) - return nodes - - - - -class BST(object): - - def __init__(self): - self.root = None - - def add(self, value): - if not self.root: - self.root = Node(value) - else: - self.root._add(value) - - def printPreorder(self): - if self.root: - self.root._printPreorder() - - def search(self, value): - if self.root: - return self.root._search(value) - - def preorder_array(self): - if self.root: - return self.root._preorder_array() - else: - return 'Tree is empty.' - - -if __name__ == '__main__': - - bst = BST() - print "Adding nodes 1 to 10 in the tree..." - for i in range(1, 11): - bst.add(i) - - print - print "Searching for nodes 16 and 6" - print bst.search(16) - print bst.search(6) - - print - print "Printing preorder..." - bst.printPreorder() - - - - diff --git a/source_code/trees/binary_tree.py b/source_code/trees/binary_tree.py deleted file mode 100755 index 796f1cc..0000000 --- a/source_code/trees/binary_tree.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/python - -__author__ = "bt3" - - -class Node(object): - - def __init__(self, item=None,): - self.item = item - self.left = None - self.right = None - - def __repr__(self): - return '{}'.format(self.item) - - - def _add(self, value): - new_node = Node(value) - - if not self.item: - self.item = new_node - elif not self.left: - self.left = new_node - elif not self.right: - self.right = new_node - else: - self.left = self.left._add(value) - - return self - - - def _search(self, value): - if self.item == value: - return True # or self - - found = False # or None, thats diff from BST - if self.left: - found = self.left._search(value) - - if self.right: - found = found or self.right._search(value) - - return found - - - def _isLeaf(self): - return not self.right and not self.left - - - def _preorder(self): - print self.item - if self.left: - self.left._preorder() - if self.right: - self.right._preorder() - - - -class BT(object): - - def __init__(self): - self.root = None - - - def add(self, value): - if not self.root: - self.root = Node(value) - else: - self.root._add(value) - - - def search(self, value): - if self.root: - return self.root._search(value) - - - def preorder(self): - if self.root: - return self.root._preorder() - - -if __name__ == '__main__': - - bt = BT() - print "Adding nodes 1 to 10 in the tree..." - for i in range(1, 11): - bt.add(i) - - print - print "Searching for nodes 16 and 6" - print bt.search(16) - print bt.search(6) - - print - print "Printing preorder..." - bt.preorder() diff --git a/source_code/trees/binary_tree_generators.py b/source_code/trees/binary_tree_generators.py deleted file mode 100644 index afafa49..0000000 --- a/source_code/trees/binary_tree_generators.py +++ /dev/null @@ -1,170 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -class Node(object): - def __init__(self, value): - self.value = value - self.right = None - self.left = None - - def add(self, value): - new_node = Node(value) - if not self.value: - self.value = new_node - elif not self.left: - self.left = new_node - elif not self. right: - self.right = new_node - else: - self.left = self.left.add(value) - return self # without this, it doesn't add! - - def search(self, item): - if self.value == item: - return True - found = False - if (self.left and self.left.search(item)) or \ - (self.right and self.right.search(item)): - found = True - return found - - def preorder(self): - yield self.value - if self.left: - for node in self.left.preorder(): - yield node - if self.right: - for node in self.right.preorder(): - yield node - - def postorder(self): - yield self.value - if self.left: - for node in self.left.postorder(): - yield node - if self.right: - for node in self.right.postorder(): - yield node - - def inorder(self): - yield self.value - if self.left: - for node in self.left.inorder(): - yield node - if self.right: - for node in self.right.inorder(): - yield node - - # this is the most basic way to write this function - def preorder_simple(self): - print self.value - if self.left: - self.left.preorder_simple() - if self.right: - self.right.preorder_simple() - - - # Another possibility: use an array (a little bit more expensive): - def preorder_array(self): - nodes = [] - if self.value: - nodes.append(self.value) - if self.left: - nodes.extend(self.left.preorder_array()) - if self.right: - nodes.extend(self.right.preorder_array()) - return nodes - - - -class BT(object): - def __init__(self): - self.root = None - - def add(self, value): - if not self.root: - self.root = Node(value) - else: - self.root.add(value) - - def search(self, item): - if self.root: - return self.root.search(item) - else: - return 'Tree is empty.' - - def preorder(self): - if self.root: - return self.root.preorder() - else: - return 'Tree is empty.' - - def inorder(self): - if self.root: - return self.root.inorder() - else: - return 'Tree is empty.' - - def postorder(self): - if self.root: - return self.root.postorder() - else: - return 'Tree is empty.' - - def preorder_array(self): - if self.root: - return self.root.preorder_array() - else: - return 'Tree is empty.' - - def preorder_simple(self): - if self.root: - return self.root.preorder_simple() - else: - return 'Tree is empty.' - - -if __name__ == '__main__': - tree = BT() - - for i in range(1, 11): - tree.add(i) - - print 'Searching for node 4' - print tree.search(4) - - print 'Searching for node 1' - print tree.search(1) - - print 'Searching for node 12' - print tree.search(12) - - print 'Pre-order generator...' - getree = tree.preorder() - for i in range(10): - print next(getree) - print - print 'Pre-order array...' - - print tree.preorder_array() - - print - print 'Pre-order simple...' - - tree.preorder_simple() - - print - print 'Inorder...' - - getree = tree.inorder() - for i in range(10): - print next(getree) - - print - print 'Postorder...' - - getree = tree.postorder() - for i in range(10): - print next(getree) diff --git a/source_code/trees/bunchclass.py b/source_code/trees/bunchclass.py deleted file mode 100755 index 6e0b440..0000000 --- a/source_code/trees/bunchclass.py +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -class BunchClass(dict): - def __init__(self, *args, **kwds): - super(BunchClass, self).__init__(*args, **kwds) - self.__dict__ = self - - -def main(): - ''' {'right': {'right': 'Xander', 'left': 'Willow'}, 'left': {'right': 'Angel', 'left': 'Buffy'}}''' - bc = BunchClass # notice the absence of () - tree = bc(left = bc(left="Buffy", right="Angel"), right = bc(left="Willow", right="Xander")) - print(tree) - -if __name__ == '__main__': - main() - - - - diff --git a/source_code/trees/check_ancestor.py b/source_code/trees/check_ancestor.py deleted file mode 100755 index a318958..0000000 --- a/source_code/trees/check_ancestor.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -from binary_search_tree import BST, Node - -def find_ancestor(path, low_item, high_item): - while path: - current_item = path[0] - - if current_item < low_item: - try: - path = path[2:] - except: - return current_item - - elif current_item > high_item: - try: - path = path[1:] - except: - return current_item - - elif low_item <= current_item <= high_item: - return current_item - - -def find_ancestor2(tree, n1, n2): - if not tree: - return False - - if n1 <= tree.item and n2 >= tree.item or (not tree.left and not tree.right) : - return tree.item - - if tree.left and (n1 < tree.item and n2 < tree.item): - return find_ancestor(tree.left, n1, n2) or tree.item - - if tree.right and (n1 > tree.item and n2 > tree.item): - return find_ancestor(tree.right, n1, n2) or tree.item - - - -if __name__ == '__main__': - bst = BST() - l = [10, 5, 6, 3, 8, 2, 1, 11, 9, 4] - for i in l: - bst.add(i) - nodes = bst.preorder_array() - - print 'Original: ', l - print 'Preorder: ', nodes - - print 'Method 1: ' - print 'Ancestor for 3, 11:', find_ancestor(nodes, 3, 11) - - print 'Method 2: ' - print 'Ancestor for 3, 11: ', find_ancestor2(bst.root, 3, 11) diff --git a/source_code/trees/check_if_balanced.py b/source_code/trees/check_if_balanced.py deleted file mode 100755 index 3e6d5fb..0000000 --- a/source_code/trees/check_if_balanced.py +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - -from binary_search_tree import BST, Node -from binary_tree import BT, Node - - - -def isBalanced(node, left=0, right=0): - if not node: - return (left - right) < 2 - - return isBalanced(node.left, left+1, right) and \ - isBalanced(node.right, left, right+1) - - - - -if __name__ == '__main__': - bt = BST() - for i in range(1, 10): - bt.add(i) - - assert(isBalanced(bt.root) == True) - - bt = BT() - for i in range(1, 10): - bt.add(i) - - assert(isBalanced(bt.root) == False) diff --git a/source_code/trees/check_if_bst.py b/source_code/trees/check_if_bst.py deleted file mode 100755 index 792013f..0000000 --- a/source_code/trees/check_if_bst.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -from binary_search_tree import BST, Node -from binary_tree import BT, Node - - -def isBST(node, min_node=float("-infinity"), maxVal=float("infinity")): - if not node: - return True - - if not min_node <= node.item <= maxVal: - return False - - return isBST(node.left, min_node, node.item) and \ - isBST(node.right, node.item, maxVal) - - - -def isBST_other_method(node, max_node=None, min_node=None): - - if not node: - return True - - left, right = True, True - min_node = min_node or float('inf') - max_node = max_node or -float('inf') - - if node.left: - if node.left.item > node.item or node.left.item > max_node: - left = False - else: - max_node = node.item - left = isBST(node.left, max_node, min_node) - - if node.right: - if node.right.item < node.item or node.right.item < min_node: - rihjt = False - else: - min_node = node.item - right = isBST(node.right, max_node, min_node) - - return left and right - - - - - -if __name__ == '__main__': - bt = BST() - for i in range(1, 10): - bt.add(i) - - assert(isBST(bt.root) == True) - - bt = BT() - for i in range(1, 10): - bt.add(i) - - assert(isBST(bt.root) == False) - - diff --git a/source_code/trees/check_largest_item.py b/source_code/trees/check_largest_item.py deleted file mode 100755 index 3428d60..0000000 --- a/source_code/trees/check_largest_item.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -from binary_search_tree import BST, Node - -def largest(node): - - if node.right: - return largest(node.right) - return node.item - - -if __name__ == '__main__': - - - bst = BST() - l = [10, 5, 6, 3, 8, 2, 1, 11, 9, 4] - for i in l: - bst.add(i) - - print(largest(bst.root)) diff --git a/source_code/trees/simple_tree.py b/source_code/trees/simple_tree.py deleted file mode 100755 index 90480e2..0000000 --- a/source_code/trees/simple_tree.py +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -""" A class for a simple tree """ - -class SimpleTree(object): - - def __init__(self, value=None, children = None): - self.value = value - self.children = children - if self.children == None: - self.children = [] - - def __repr__(self, level=0): - ret = "\t"*level+repr(self.value)+"\n" - for child in self.children: - ret += child.__repr__(level+1) - return ret - - - -def main(): - """ - 'a' - 'b' - 'd' - 'e' - 'c' - 'h' - 'g' - """ - st = SimpleTree('a', [SimpleTree('b', [SimpleTree('d'), SimpleTree('e')] ), SimpleTree('c', [SimpleTree('h'), SimpleTree('g')]) ]) - print(st) - - -if __name__ == '__main__': - main() - - diff --git a/source_code/trees/transversal.py b/source_code/trees/transversal.py deleted file mode 100755 index d3e3bf2..0000000 --- a/source_code/trees/transversal.py +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -from collections import deque -from binary_search_tree import BST, Node -from binary_tree import BT, Node - - -def BFT(tree): - current = tree.root - nodes = [] - queue = deque() - queue.append(current) - - while queue: - current = queue.popleft() - nodes.append(current.item) - if current.left: - queue.append(current.left) - if current.right: - queue.append(current.right) - - return nodes - - -def preorder(tree, nodes=None): - nodes = nodes or [] - if tree: - nodes.append(tree.item) - if tree.left: - preorder(tree.left, nodes) - if tree.right: - preorder(tree.right, nodes) - return nodes - - -def postorder(tree, nodes=None): - nodes = nodes or [] - if tree: - if tree.left: - nodes = postorder(tree.left, nodes) - if tree.right: - nodes = postorder(tree.right, nodes) - nodes.append(tree.item) - - return nodes - - -def inorder(tree, nodes=None): - nodes = nodes or [] - if tree: - if tree.left: - nodes = inorder(tree.left, nodes) - nodes.append(tree.item) - if tree.right: - nodes = inorder(tree.right, nodes) - return nodes - - -if __name__ == '__main__': - - - # bt - bt = BT() - l = [10, 5, 6, 3, 8, 2, 1, 11, 9, 4] - for i in l: - bt.add(i) - print 'BT...' - print 'Original: ', l - print 'Preorder: ', preorder(bt.root) - print 'Postorder: ', postorder(bt.root) - print 'Inorder: ', inorder(bt.root) - print 'Breath: ', BFT(bt) - - # bst - bst = BST() - l = [10, 5, 6, 3, 8, 2, 1, 11, 9, 4] - for i in l: - bst.add(i) - - print - print 'BST ...' - print 'Original: ', l - print 'Preorder: ', preorder(bst.root) - print 'Postorder: ', postorder(bst.root) - print 'Inorder: ', inorder(bst.root) - print 'Breath: ', BFT(bst) diff --git a/source_code/trees/trie.py b/source_code/trees/trie.py deleted file mode 100755 index a73c531..0000000 --- a/source_code/trees/trie.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - -''' -Implement a trie. (Write the API and code for inserting into a trie). -''' - -def make_trie(*args): - trie = {} - - for word in args: - temp_trie = trie - for letter in word: - temp_trie = temp_trie.setdefault(letter, {}) - temp_trie = temp_trie.setdefault('_end_', '_end_') - - return trie - - -def in_trie(trie, word): - temp_trie = trie - for letter in word: - if letter not in temp_trie: - return False - temp_trie = temp_trie[letter] - return True - - -def remove_from_trie(trie, word, depth): - if word and word[depth] not in trie: - return False - - if len(word) == depth + 1: - del trie[word[depth]] - if not trie: - return True - return False - else: - temp_trie = trie - - if remove_from_trie(temp_trie[word[depth]], word, depth + 1): - if temp_trie: - del temp_trie[word[depth]] - return not temp_trie - return False - - -if __name__ == '__main__': - trie = make_trie('hello', 'abc', 'baz', 'bar', 'barz') - print 'This is the trie:' - print trie - - assert(in_trie(trie, 'hello') == True) - assert(in_trie(trie, 'bar') == True) - assert(in_trie(trie, 'bab') == False) - assert(in_trie(trie, 'zzz') == False) - - remove_from_trie(trie, 'abc', 0) - assert(in_trie(trie, 'abc') == False) - - - -