From 3fdbc2a60551ca5785ebdb5e2f2d831f75c8478a Mon Sep 17 00:00:00 2001 From: Mari Wahl Date: Tue, 6 Jan 2015 20:10:48 -0500 Subject: [PATCH] cleaning up and organizing old problems (builtin) --- README.md | 8 +- .../math_arrays_and_strings/rev_string.py | 16 --- .../advanced/lru_cache.py | 0 .../basic_examples/example_OrderedDict.py} | 14 +-- .../basic_examples/example_counter.py} | 21 ++-- .../basic_examples/example_defaultdict.py} | 12 +- .../basic_examples/example_setdefault.py} | 8 +- .../HashTable.py | 0 .../queue_with_stack.py | 0 .../stack_with_minumum.py | 0 .../bitwise/bitwise.txt | 0 .../bitwise/clear_bits.py | 0 .../bitwise/find_bit_len.py | 0 .../bitwise/get_bit.py | 0 .../bitwise/num_bits_to_convert_2_nums.py | 0 .../bitwise/set_bit.py | 0 .../bitwise/swap_in_place.py | 0 .../bitwise/update_bit.py | 0 .../{dicts => }/__init__.py | 0 .../alpha_permutation.py | 0 .../anagram.py | 0 .../balance.txt | 0 .../balance_symbols.py | 0 .../check_if_2_numbers_sum_to_k.py | 0 .../check_if_3_numbers_sum_to_zero.py | 0 .../check_non_overlapping_intervals.py | 0 .../combinations.py | 0 .../conv_str2int.py => convert_str_2_int.py} | 67 ++++++---- ...ue_words_.py => count_unique_words_On2.py} | 17 ++- .../delete_duplicate_char_str.py | 19 ++- .../dicts/delete_duplicate_char_str.py | 32 ----- .../dicts/find_anagram_hash_function.py | 34 ----- .../dicts/find_dice_probabilities.py | 33 ----- .../dicts/veirfy_two_strings_are_anagrams.py | 45 ------- .../fibonacci.py | 0 .../find_0_MxN_replace_cols_rows.py | 12 +- .../find_dice_probabilities.py | 32 +++++ src/builtin_structures/find_edit_distance.py | 43 +++++++ .../find_first_non_repetead_char.py | 29 +++++ .../find_gcd.py | 0 .../find_if_is_substr.py | 2 +- .../find_if_unique_char.py | 0 .../find_largest_sum.py | 0 .../find_long_con_inc_subseq.py | 32 +++++ .../find_longest_str_unique_chars.py | 0 .../find_non_repeating_number.py | 0 .../find_prime_factors.py | 0 .../find_product_without_division.py | 42 +++++++ .../{dicts => }/find_top_N_recurring_words.py | 26 ++-- .../find_two_missing_numbers_in_sequence.py | 56 +++++++++ .../generate_prime.py | 0 .../get_float_rep_bin.py | 0 .../interserction_two_arrays.py | 0 .../lists_and_strings/__init__.py | 0 .../lists_and_strings/comb_str.py | 29 ----- .../lists_and_strings/count_unique_words.py | 24 ---- .../find_all_permutations_string.py | 47 ------- .../lists_and_strings/find_closest_num_seq.py | 47 ------- .../find_duplicate_num_array.py | 44 ------- .../lists_and_strings/find_edit_distance.py | 34 ----- .../find_first_non_repetead_char.py | 30 ----- .../lists_and_strings/find_if_is_substr.py | 38 ------ .../find_if_only_unique_chars.py | 41 ------ .../find_long_con_inc_subseq.py | 30 ----- .../lists_and_strings/find_majority_in_seq.py | 58 --------- .../lists_and_strings/find_max_profit.py | 44 ------- .../lists_and_strings/find_max_subarray.py | 44 ------- .../lists_and_strings/find_palindrome_rec.py | 29 ----- .../find_product_without_division.py | 33 ----- .../lists_and_strings/find_subst_in_str.py | 41 ------ .../find_two_missing_numbers_in_sequence.py | 55 -------- .../greatest_sum_sub_array.py | 27 ---- .../longest_common_substring.py | 32 ----- .../merge_two_sorted_arrays.py | 38 ------ .../lists_and_strings/perm_str.py | 24 ---- .../print_all_seq_with_cont_num.py | 39 ------ .../remove_specified_char_from_str.py | 29 ----- .../removing_duplicates_seq.py | 37 ------ .../lists_and_strings/reverse_str.py | 59 --------- .../reverse_string_inplace_rec.py | 35 ------ .../reverse_words_sentence.py | 117 ------------------ .../sum_two_numbers_sequence.py | 36 ------ .../lists_and_strings/verify_if_perm.py | 49 -------- .../longest_common_prefix.py | 28 ++++- .../max_subarray_stocks.py | 27 +++- .../number_of_zeros_factorial.txt | 0 .../palindrome.py} | 0 .../permutations.py | 0 .../prod_other_ints.py | 0 .../ransom_note.py | 0 src/builtin_structures/reverse_string.py | 37 ++++++ .../reverse_words.py | 0 .../{lists_and_strings => }/rotate_NxN.py | 11 +- .../runtime_dicts_with_timeit_module.py | 20 ++- .../runtime_lists_with_timeit_module.py | 5 +- .../simple_str_comprension.py | 32 ++--- .../sum_two_numbers_as_strings.py | 0 .../binary_search.py | 0 .../merge_and_sort_two_arrays.py | 2 +- .../quick_sort.py | 0 .../trees/binary_search_tree.py | 0 .../trees/binary_tree.py | 0 .../trees/check_if_balanced.py | 0 .../trees/check_if_bst.py | 0 .../trees/transversing_bt.py | 0 .../trees/trie.py | 0 106 files changed, 480 insertions(+), 1472 deletions(-) delete mode 100644 src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/rev_string.py rename src/{EXTRA_INTERVIEW_PROBLEMS => USEFUL}/advanced/lru_cache.py (100%) rename src/{builtin_structures/dicts/OrderedDict_example.py => USEFUL/basic_examples/example_OrderedDict.py} (75%) rename src/{builtin_structures/dicts/Counter_example.py => USEFUL/basic_examples/example_counter.py} (74%) rename src/{builtin_structures/dicts/defaultdict_example.py => USEFUL/basic_examples/example_defaultdict.py} (68%) rename src/{builtin_structures/dicts/setdeault_example.py => USEFUL/basic_examples/example_setdefault.py} (90%) rename src/{EXTRA_INTERVIEW_PROBLEMS/abstract_strucutres => abstract_structures}/HashTable.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/abstract_strucutres => abstract_structures}/queue_with_stack.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/abstract_strucutres => abstract_structures}/stack_with_minumum.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS => }/bitwise/bitwise.txt (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS => }/bitwise/clear_bits.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS => }/bitwise/find_bit_len.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS => }/bitwise/get_bit.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS => }/bitwise/num_bits_to_convert_2_nums.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS => }/bitwise/set_bit.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS => }/bitwise/swap_in_place.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS => }/bitwise/update_bit.py (100%) rename src/builtin_structures/{dicts => }/__init__.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/alpha_permutation.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/anagram.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/balance.txt (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/balance_symbols.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/check_if_2_numbers_sum_to_k.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/check_if_3_numbers_sum_to_zero.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/check_non_overlapping_intervals.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/combinations.py (100%) rename src/builtin_structures/{lists_and_strings/conv_str2int.py => convert_str_2_int.py} (61%) rename src/builtin_structures/{dicts/count_unique_words_.py => count_unique_words_On2.py} (81%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/delete_duplicate_char_str.py (65%) delete mode 100644 src/builtin_structures/dicts/delete_duplicate_char_str.py delete mode 100644 src/builtin_structures/dicts/find_anagram_hash_function.py delete mode 100644 src/builtin_structures/dicts/find_dice_probabilities.py delete mode 100644 src/builtin_structures/dicts/veirfy_two_strings_are_anagrams.py rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/fibonacci.py (100%) rename src/builtin_structures/{lists_and_strings => }/find_0_MxN_replace_cols_rows.py (89%) create mode 100644 src/builtin_structures/find_dice_probabilities.py create mode 100644 src/builtin_structures/find_edit_distance.py create mode 100644 src/builtin_structures/find_first_non_repetead_char.py rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/find_gcd.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/find_if_is_substr.py (92%) mode change 100755 => 100644 rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/find_if_unique_char.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/find_largest_sum.py (100%) create mode 100644 src/builtin_structures/find_long_con_inc_subseq.py rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/find_longest_str_unique_chars.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/find_non_repeating_number.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/find_prime_factors.py (100%) create mode 100644 src/builtin_structures/find_product_without_division.py rename src/builtin_structures/{dicts => }/find_top_N_recurring_words.py (60%) create mode 100644 src/builtin_structures/find_two_missing_numbers_in_sequence.py rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/generate_prime.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/get_float_rep_bin.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/interserction_two_arrays.py (100%) delete mode 100644 src/builtin_structures/lists_and_strings/__init__.py delete mode 100644 src/builtin_structures/lists_and_strings/comb_str.py delete mode 100644 src/builtin_structures/lists_and_strings/count_unique_words.py delete mode 100644 src/builtin_structures/lists_and_strings/find_all_permutations_string.py delete mode 100644 src/builtin_structures/lists_and_strings/find_closest_num_seq.py delete mode 100644 src/builtin_structures/lists_and_strings/find_duplicate_num_array.py delete mode 100644 src/builtin_structures/lists_and_strings/find_edit_distance.py delete mode 100644 src/builtin_structures/lists_and_strings/find_first_non_repetead_char.py delete mode 100644 src/builtin_structures/lists_and_strings/find_if_is_substr.py delete mode 100644 src/builtin_structures/lists_and_strings/find_if_only_unique_chars.py delete mode 100644 src/builtin_structures/lists_and_strings/find_long_con_inc_subseq.py delete mode 100644 src/builtin_structures/lists_and_strings/find_majority_in_seq.py delete mode 100644 src/builtin_structures/lists_and_strings/find_max_profit.py delete mode 100644 src/builtin_structures/lists_and_strings/find_max_subarray.py delete mode 100644 src/builtin_structures/lists_and_strings/find_palindrome_rec.py delete mode 100644 src/builtin_structures/lists_and_strings/find_product_without_division.py delete mode 100644 src/builtin_structures/lists_and_strings/find_subst_in_str.py delete mode 100644 src/builtin_structures/lists_and_strings/find_two_missing_numbers_in_sequence.py delete mode 100644 src/builtin_structures/lists_and_strings/greatest_sum_sub_array.py delete mode 100644 src/builtin_structures/lists_and_strings/longest_common_substring.py delete mode 100644 src/builtin_structures/lists_and_strings/merge_two_sorted_arrays.py delete mode 100644 src/builtin_structures/lists_and_strings/perm_str.py delete mode 100644 src/builtin_structures/lists_and_strings/print_all_seq_with_cont_num.py delete mode 100644 src/builtin_structures/lists_and_strings/remove_specified_char_from_str.py delete mode 100644 src/builtin_structures/lists_and_strings/removing_duplicates_seq.py delete mode 100644 src/builtin_structures/lists_and_strings/reverse_str.py delete mode 100644 src/builtin_structures/lists_and_strings/reverse_string_inplace_rec.py delete mode 100644 src/builtin_structures/lists_and_strings/reverse_words_sentence.py delete mode 100644 src/builtin_structures/lists_and_strings/sum_two_numbers_sequence.py delete mode 100644 src/builtin_structures/lists_and_strings/verify_if_perm.py rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/longest_common_prefix.py (65%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/max_subarray_stocks.py (60%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/number_of_zeros_factorial.txt (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/check_if_palindrome.py => builtin_structures/palindrome.py} (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/permutations.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/prod_other_ints.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/ransom_note.py (100%) create mode 100644 src/builtin_structures/reverse_string.py rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/reverse_words.py (100%) rename src/builtin_structures/{lists_and_strings => }/rotate_NxN.py (85%) rename src/builtin_structures/{dicts => }/runtime_dicts_with_timeit_module.py (58%) rename src/builtin_structures/{lists_and_strings => }/runtime_lists_with_timeit_module.py (97%) rename src/builtin_structures/{lists_and_strings => }/simple_str_comprension.py (54%) rename src/{EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings => builtin_structures}/sum_two_numbers_as_strings.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/sorting_and_searching => searching_and_sorting}/binary_search.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS/sorting_and_searching => searching_and_sorting}/merge_and_sort_two_arrays.py (96%) rename src/{EXTRA_INTERVIEW_PROBLEMS/sorting_and_searching => searching_and_sorting}/quick_sort.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS => trees}/trees/binary_search_tree.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS => trees}/trees/binary_tree.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS => trees}/trees/check_if_balanced.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS => trees}/trees/check_if_bst.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS => trees}/trees/transversing_bt.py (100%) rename src/{EXTRA_INTERVIEW_PROBLEMS => trees}/trees/trie.py (100%) diff --git a/README.md b/README.md index d064bae..0b91b10 100644 --- a/README.md +++ b/README.md @@ -35,14 +35,10 @@ src/ └── trees +└── bitwise + └── searching_and_sorting - ├── searching - - ├── sorting - -└── Extra Interview Problems - └── USEFUL diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/rev_string.py b/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/rev_string.py deleted file mode 100644 index 0079aaf..0000000 --- a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/rev_string.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python - -__author__ = "bt3" - - - -''' Reverting a string ''' - - -def revert(string): - return string[::-1] - - -if __name__ == '__main__': - string = "buffy is fun!" - print(revert(string)) \ No newline at end of file diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/advanced/lru_cache.py b/src/USEFUL/advanced/lru_cache.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/advanced/lru_cache.py rename to src/USEFUL/advanced/lru_cache.py diff --git a/src/builtin_structures/dicts/OrderedDict_example.py b/src/USEFUL/basic_examples/example_OrderedDict.py similarity index 75% rename from src/builtin_structures/dicts/OrderedDict_example.py rename to src/USEFUL/basic_examples/example_OrderedDict.py index b7dbef1..89d3291 100644 --- a/src/builtin_structures/dicts/OrderedDict_example.py +++ b/src/USEFUL/basic_examples/example_OrderedDict.py @@ -1,17 +1,17 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail +#!/usr/bin/env python + +__author__ = "bt3" from collections import OrderedDict def OrderedDict_example(): - ''' show some examples for OrderedDict ''' - ''' keep the order of insertion. + ''' 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: diff --git a/src/builtin_structures/dicts/Counter_example.py b/src/USEFUL/basic_examples/example_counter.py similarity index 74% rename from src/builtin_structures/dicts/Counter_example.py rename to src/USEFUL/basic_examples/example_counter.py index b0f3284..bd233e3 100644 --- a/src/builtin_structures/dicts/Counter_example.py +++ b/src/USEFUL/basic_examples/example_counter.py @@ -1,32 +1,31 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail +#!/usr/bin/env python + +__author__ = "bt3" from collections import Counter def Counter_example(): - ''' show some examples for Counter ''' - ''' it is a dictionary that maps the items to the number of occurences ''' + ''' 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_2) + print(seq_counts + seq_counts_2) print(seq_counts - seq_counts_2) - + if __name__ == '__main__': Counter_example() diff --git a/src/builtin_structures/dicts/defaultdict_example.py b/src/USEFUL/basic_examples/example_defaultdict.py similarity index 68% rename from src/builtin_structures/dicts/defaultdict_example.py rename to src/USEFUL/basic_examples/example_defaultdict.py index cea9d1c..6db52b7 100644 --- a/src/builtin_structures/dicts/defaultdict_example.py +++ b/src/USEFUL/basic_examples/example_defaultdict.py @@ -1,13 +1,13 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail +#!/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)} - + ''' show some examples for defaultdicts ''' + pairs = {('a', 1), ('b',2), ('c',3)} + d1 = {} for key, value in pairs: if key not in d1: diff --git a/src/builtin_structures/dicts/setdeault_example.py b/src/USEFUL/basic_examples/example_setdefault.py similarity index 90% rename from src/builtin_structures/dicts/setdeault_example.py rename to src/USEFUL/basic_examples/example_setdefault.py index 55dbfd4..6ad5c56 100644 --- a/src/builtin_structures/dicts/setdeault_example.py +++ b/src/USEFUL/basic_examples/example_setdefault.py @@ -1,6 +1,6 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail +#!/usr/bin/env python + +__author__ = "bt3" def usual_dict(dict_data): @@ -28,7 +28,7 @@ def test_setdef(module_name='this module'): ('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')) diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/abstract_strucutres/HashTable.py b/src/abstract_structures/HashTable.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/abstract_strucutres/HashTable.py rename to src/abstract_structures/HashTable.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/abstract_strucutres/queue_with_stack.py b/src/abstract_structures/queue_with_stack.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/abstract_strucutres/queue_with_stack.py rename to src/abstract_structures/queue_with_stack.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/abstract_strucutres/stack_with_minumum.py b/src/abstract_structures/stack_with_minumum.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/abstract_strucutres/stack_with_minumum.py rename to src/abstract_structures/stack_with_minumum.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/bitwise/bitwise.txt b/src/bitwise/bitwise.txt similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/bitwise/bitwise.txt rename to src/bitwise/bitwise.txt diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/bitwise/clear_bits.py b/src/bitwise/clear_bits.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/bitwise/clear_bits.py rename to src/bitwise/clear_bits.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/bitwise/find_bit_len.py b/src/bitwise/find_bit_len.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/bitwise/find_bit_len.py rename to src/bitwise/find_bit_len.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/bitwise/get_bit.py b/src/bitwise/get_bit.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/bitwise/get_bit.py rename to src/bitwise/get_bit.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/bitwise/num_bits_to_convert_2_nums.py b/src/bitwise/num_bits_to_convert_2_nums.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/bitwise/num_bits_to_convert_2_nums.py rename to src/bitwise/num_bits_to_convert_2_nums.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/bitwise/set_bit.py b/src/bitwise/set_bit.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/bitwise/set_bit.py rename to src/bitwise/set_bit.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/bitwise/swap_in_place.py b/src/bitwise/swap_in_place.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/bitwise/swap_in_place.py rename to src/bitwise/swap_in_place.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/bitwise/update_bit.py b/src/bitwise/update_bit.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/bitwise/update_bit.py rename to src/bitwise/update_bit.py diff --git a/src/builtin_structures/dicts/__init__.py b/src/builtin_structures/__init__.py similarity index 100% rename from src/builtin_structures/dicts/__init__.py rename to src/builtin_structures/__init__.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/alpha_permutation.py b/src/builtin_structures/alpha_permutation.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/alpha_permutation.py rename to src/builtin_structures/alpha_permutation.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/anagram.py b/src/builtin_structures/anagram.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/anagram.py rename to src/builtin_structures/anagram.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/balance.txt b/src/builtin_structures/balance.txt similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/balance.txt rename to src/builtin_structures/balance.txt diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/balance_symbols.py b/src/builtin_structures/balance_symbols.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/balance_symbols.py rename to src/builtin_structures/balance_symbols.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/check_if_2_numbers_sum_to_k.py b/src/builtin_structures/check_if_2_numbers_sum_to_k.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/check_if_2_numbers_sum_to_k.py rename to src/builtin_structures/check_if_2_numbers_sum_to_k.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/check_if_3_numbers_sum_to_zero.py b/src/builtin_structures/check_if_3_numbers_sum_to_zero.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/check_if_3_numbers_sum_to_zero.py rename to src/builtin_structures/check_if_3_numbers_sum_to_zero.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/check_non_overlapping_intervals.py b/src/builtin_structures/check_non_overlapping_intervals.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/check_non_overlapping_intervals.py rename to src/builtin_structures/check_non_overlapping_intervals.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/combinations.py b/src/builtin_structures/combinations.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/combinations.py rename to src/builtin_structures/combinations.py diff --git a/src/builtin_structures/lists_and_strings/conv_str2int.py b/src/builtin_structures/convert_str_2_int.py similarity index 61% rename from src/builtin_structures/lists_and_strings/conv_str2int.py rename to src/builtin_structures/convert_str_2_int.py index ec7f8c3..bdf875d 100644 --- a/src/builtin_structures/lists_and_strings/conv_str2int.py +++ b/src/builtin_structures/convert_str_2_int.py @@ -1,9 +1,10 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail +#!/usr/bin/env python -''' two routines to convert str to int and int to str: - - bc: negative str, zero, exp numbers (ex. 1e5), other bases, NAN +__author__ = "bt3" + + +def conv_int2str(int1): + ''' >>> conv_str2int('367') 367 >>> conv_str2int('0') @@ -12,46 +13,59 @@ -10 >>> conv_str2int('1e5') 100000 - >>> conv_int2str(0) - '0' - >>> conv_int2str(1e5) - '100000' - >>> conv_int2str(367) - '367' - >>> conv_int2str(-10) - '-10' -''' + ''' -def conv_int2str(int1): aux_dict = {key:value for key in range(10) for value in '0123456789'[key]} - if int1 == 0: return '0' # REMEMBER TO HANDLE 0 - if int1 < 0: # REMEMBER TO HANDLE NEGATIVE + + 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() # REMEMBER TO REVERSE + + aux_ls.reverse() + return sign + ''.join(aux_ls) - + def conv_str2int(str1): - if not str1: return None + ''' + >>> 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] == '-': + + if str1[0] == '-': sign = -1 - str1 = str1[1:] # REMEMBER TO CUT THE SIGN FROM THE STR - else: + str1 = str1[1:] + else: sign = 1 + dec, result = 1, 0 - for i in range(len(str1)-1, -1, -1): # REMEMBER TO FINISH IN -1, NOT 0, AND - aux = str1[i] # AND DO THE STEPS -1 + + 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]) @@ -59,8 +73,9 @@ def conv_str2int(str1): break result += aux_dict[aux]*dec dec *= 10 + return result*sign - + if __name__ == '__main__': import doctest diff --git a/src/builtin_structures/dicts/count_unique_words_.py b/src/builtin_structures/count_unique_words_On2.py similarity index 81% rename from src/builtin_structures/dicts/count_unique_words_.py rename to src/builtin_structures/count_unique_words_On2.py index fdf66c3..7b54490 100644 --- a/src/builtin_structures/dicts/count_unique_words_.py +++ b/src/builtin_structures/count_unique_words_On2.py @@ -1,21 +1,26 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail +#!/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 + "\"'" + + strip = string.whitespace + string.punctuation + string.digits + "\"'" + for filename in sys.argv[1:]: with open(filename) as file: - for line in 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/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/delete_duplicate_char_str.py b/src/builtin_structures/delete_duplicate_char_str.py similarity index 65% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/delete_duplicate_char_str.py rename to src/builtin_structures/delete_duplicate_char_str.py index 898935c..9f8b9fc 100755 --- a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/delete_duplicate_char_str.py +++ b/src/builtin_structures/delete_duplicate_char_str.py @@ -4,10 +4,8 @@ __author__ = "bt3" ''' find and delete all the duplicate characters in a string ''' - -import string - from collections import Counter + def delete_unique(str1): ''' >>> delete_unique("Trust no one") @@ -30,6 +28,21 @@ def delete_unique(str1): 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 diff --git a/src/builtin_structures/dicts/delete_duplicate_char_str.py b/src/builtin_structures/dicts/delete_duplicate_char_str.py deleted file mode 100644 index b186f2b..0000000 --- a/src/builtin_structures/dicts/delete_duplicate_char_str.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - -import string - -def delete_unique_word(str1): - ''' find and delete all the duplicate characters in a string ''' - - # create ordered dict - table_c = { key : 0 for key in string.ascii_lowercase} - - # fill the table with the chars in the string - for i in str1: - table_c[i] += 1 - - # scan the table to find times chars > 1 - for key, value in table_c.items(): - if value > 1: - str1 = str1.replace(key, "") - - return str1 - - -def test_delete_unique_word(): - str1 = "google" - assert(delete_unique_word(str1) == 'le') - print('Tests passed!') - -if __name__ == '__main__': - test_delete_unique_word() - diff --git a/src/builtin_structures/dicts/find_anagram_hash_function.py b/src/builtin_structures/dicts/find_anagram_hash_function.py deleted file mode 100644 index fb2a61b..0000000 --- a/src/builtin_structures/dicts/find_anagram_hash_function.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - - -def hash_func(astring, tablesize): - sum = 0 - for pos in range(len(astring)): - sum = sum + ord(astring[pos]) - return sum%tablesize - - -def find_anagram_hash_function(word1, word2): - ''' verify if words are anagrams by comparying hash functions''' - tablesize = 11 - return hash_func(word1, tablesize) == hash_func(word2, tablesize) - - - - -def test_find_anagram_hash_function(module_name='this module'): - word1 = 'buffy' - word2 = 'bffyu' - word3 = 'bffya' - assert(find_anagram_hash_function(word1, word2) == True) - assert(find_anagram_hash_function(word1, word3) == False) - - s = 'Tests in {name} have {con}!' - print(s.format(name=module_name, con='passed')) - - -if __name__ == '__main__': - test_find_anagram_hash_function() - diff --git a/src/builtin_structures/dicts/find_dice_probabilities.py b/src/builtin_structures/dicts/find_dice_probabilities.py deleted file mode 100644 index 10e2d48..0000000 --- a/src/builtin_structures/dicts/find_dice_probabilities.py +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - -from collections import Counter, defaultdict - -def find_dice_probabilities(S, n_faces=6): - ''' given 2 dice, determine number of ways to sum S if all dice are rolled ''' - - 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]] - - -def test_find_dice_probabilities(module_name='this module'): - n_faces = 6 - S = 5 - results = find_dice_probabilities(S, n_faces) - print(results) - assert(results[0] == len(results[1])) - - -if __name__ == '__main__': - test_find_dice_probabilities() diff --git a/src/builtin_structures/dicts/veirfy_two_strings_are_anagrams.py b/src/builtin_structures/dicts/veirfy_two_strings_are_anagrams.py deleted file mode 100644 index c10266c..0000000 --- a/src/builtin_structures/dicts/veirfy_two_strings_are_anagrams.py +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - -import string - - -def verify_two_strings_are_anagrams(str1, str2): - """ find whether two words are anagrams. Since sets do not count occurency, and sorting is O(nlogn) - we will use hash tables. We scan the first string and add all the character occurences. Then we - scan the second tring and decrease all the caracther occurences. If all the counts are zero, it is - an anagram""" - - # create the hash table - ana_table = {key:0 for key in string.ascii_lowercase} - - # scan first string - for i in str1: - ana_table[i] += 1 - - # scan second string - for i in str2: - ana_table[i] -= 1 - - # verify whether all the entries are 0 - if len(set(ana_table.values())) < 2: return True - else: return False - - -def test_verify_two_strings_are_anagrams(): - str1 = 'marina' - str2 = 'aniram' - assert(verify_two_strings_are_anagrams(str1, str2) == True) - str1 = 'google' - str2 = 'gouglo' - assert(verify_two_strings_are_anagrams(str1, str2) == False) - print('Tests passed!') - - -if __name__ == '__main__': - test_verify_two_strings_are_anagrams() - - - - diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/fibonacci.py b/src/builtin_structures/fibonacci.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/fibonacci.py rename to src/builtin_structures/fibonacci.py diff --git a/src/builtin_structures/lists_and_strings/find_0_MxN_replace_cols_rows.py b/src/builtin_structures/find_0_MxN_replace_cols_rows.py similarity index 89% rename from src/builtin_structures/lists_and_strings/find_0_MxN_replace_cols_rows.py rename to src/builtin_structures/find_0_MxN_replace_cols_rows.py index f306d83..9ab67c3 100644 --- a/src/builtin_structures/lists_and_strings/find_0_MxN_replace_cols_rows.py +++ b/src/builtin_structures/find_0_MxN_replace_cols_rows.py @@ -1,8 +1,8 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail +#!/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]] @@ -13,6 +13,7 @@ def find_0_MxN(m): [[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: @@ -24,9 +25,10 @@ def find_0_MxN(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/src/builtin_structures/find_dice_probabilities.py b/src/builtin_structures/find_dice_probabilities.py new file mode 100644 index 0000000..265c9b1 --- /dev/null +++ b/src/builtin_structures/find_dice_probabilities.py @@ -0,0 +1,32 @@ +#!/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/src/builtin_structures/find_edit_distance.py b/src/builtin_structures/find_edit_distance.py new file mode 100644 index 0000000..6fc6e81 --- /dev/null +++ b/src/builtin_structures/find_edit_distance.py @@ -0,0 +1,43 @@ +#!/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/src/builtin_structures/find_first_non_repetead_char.py b/src/builtin_structures/find_first_non_repetead_char.py new file mode 100644 index 0000000..5489f7d --- /dev/null +++ b/src/builtin_structures/find_first_non_repetead_char.py @@ -0,0 +1,29 @@ +#!/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/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/find_gcd.py b/src/builtin_structures/find_gcd.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/find_gcd.py rename to src/builtin_structures/find_gcd.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/find_if_is_substr.py b/src/builtin_structures/find_if_is_substr.py old mode 100755 new mode 100644 similarity index 92% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/find_if_is_substr.py rename to src/builtin_structures/find_if_is_substr.py index ff3e2ad..8166bda --- a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/find_if_is_substr.py +++ b/src/builtin_structures/find_if_is_substr.py @@ -33,4 +33,4 @@ if __name__ == '__main__': s2 = 'vampire' s3 = 'angel' assert(find_substr(s2, s1) == True) - assert(find_substr(s3, s1) == False) + assert(find_substr(s3, s1) == False) \ No newline at end of file diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/find_if_unique_char.py b/src/builtin_structures/find_if_unique_char.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/find_if_unique_char.py rename to src/builtin_structures/find_if_unique_char.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/find_largest_sum.py b/src/builtin_structures/find_largest_sum.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/find_largest_sum.py rename to src/builtin_structures/find_largest_sum.py diff --git a/src/builtin_structures/find_long_con_inc_subseq.py b/src/builtin_structures/find_long_con_inc_subseq.py new file mode 100644 index 0000000..9b9dabd --- /dev/null +++ b/src/builtin_structures/find_long_con_inc_subseq.py @@ -0,0 +1,32 @@ +#!/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] + ''' + + aux = [] + result = [] + seq.append(-float('infinity')) + + for i, pivot in enumerate(seq[:-1]): + aux.append(pivot) + if pivot > seq[i+1]: + if len(aux) > len(result): + result = aux + aux = [] + + return result + + +if __name__ == '__main__': + import doctest + doctest.testmod() diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/find_longest_str_unique_chars.py b/src/builtin_structures/find_longest_str_unique_chars.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/find_longest_str_unique_chars.py rename to src/builtin_structures/find_longest_str_unique_chars.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/find_non_repeating_number.py b/src/builtin_structures/find_non_repeating_number.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/find_non_repeating_number.py rename to src/builtin_structures/find_non_repeating_number.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/find_prime_factors.py b/src/builtin_structures/find_prime_factors.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/find_prime_factors.py rename to src/builtin_structures/find_prime_factors.py diff --git a/src/builtin_structures/find_product_without_division.py b/src/builtin_structures/find_product_without_division.py new file mode 100644 index 0000000..611842e --- /dev/null +++ b/src/builtin_structures/find_product_without_division.py @@ -0,0 +1,42 @@ +#!/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/src/builtin_structures/dicts/find_top_N_recurring_words.py b/src/builtin_structures/find_top_N_recurring_words.py similarity index 60% rename from src/builtin_structures/dicts/find_top_N_recurring_words.py rename to src/builtin_structures/find_top_N_recurring_words.py index d699fe7..91dfc8f 100644 --- a/src/builtin_structures/dicts/find_top_N_recurring_words.py +++ b/src/builtin_structures/find_top_N_recurring_words.py @@ -1,6 +1,6 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail +#!/usr/bin/env python + +__author__ = "bt3" from collections import Counter @@ -8,24 +8,20 @@ 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 ''' + 3) return the last N words + ''' dcounter = Counter() for word in seq.split(): - dcounter[word] += 1 + dcounter[word] += 1 + return dcounter.most_common(N) - -def test_find_top_N_recurring_words(module_name='this module'): - 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)]) - - s = 'Tests in {name} have {con}!' - print(s.format(name=module_name, con='passed')) - if __name__ == '__main__': - test_find_top_N_recurring_words() + 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/src/builtin_structures/find_two_missing_numbers_in_sequence.py b/src/builtin_structures/find_two_missing_numbers_in_sequence.py new file mode 100644 index 0000000..e532a18 --- /dev/null +++ b/src/builtin_structures/find_two_missing_numbers_in_sequence.py @@ -0,0 +1,56 @@ +#!/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/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/generate_prime.py b/src/builtin_structures/generate_prime.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/generate_prime.py rename to src/builtin_structures/generate_prime.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/get_float_rep_bin.py b/src/builtin_structures/get_float_rep_bin.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/get_float_rep_bin.py rename to src/builtin_structures/get_float_rep_bin.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/interserction_two_arrays.py b/src/builtin_structures/interserction_two_arrays.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/interserction_two_arrays.py rename to src/builtin_structures/interserction_two_arrays.py diff --git a/src/builtin_structures/lists_and_strings/__init__.py b/src/builtin_structures/lists_and_strings/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/src/builtin_structures/lists_and_strings/comb_str.py b/src/builtin_structures/lists_and_strings/comb_str.py deleted file mode 100644 index 9e9f966..0000000 --- a/src/builtin_structures/lists_and_strings/comb_str.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - -''' give all the combinations of a str or list: - >>> l1 = (1, 2, 3) - >>> comb_str(l1) - [[1], [1, [2]], [1, [2, 3]], [1, [3]], [2], [2, 3], [3]] - >>> comb_str([]) - [] -''' - - - -def comb_str(l1): - if len(l1) < 2: return l1 - result = [] - for i in range(len(l1)): - result.append([l1[i]]) - for comb in comb_str(l1[i+1:]): - result.append([l1[i], comb]) - return result - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/src/builtin_structures/lists_and_strings/count_unique_words.py b/src/builtin_structures/lists_and_strings/count_unique_words.py deleted file mode 100644 index 9ab81a2..0000000 --- a/src/builtin_structures/lists_and_strings/count_unique_words.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - -import string -import sys - -def count_unique_word(): - ''' list every word and number of times in alphabetical order for input files ''' - words = {} # create an empty dictionary - 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] = words.get(word,0) +1 - for word in sorted(words): - print("'{0}' occurs {1} times.".format(word, words[word])) - - -count_unique_word() - diff --git a/src/builtin_structures/lists_and_strings/find_all_permutations_string.py b/src/builtin_structures/lists_and_strings/find_all_permutations_string.py deleted file mode 100644 index 4c90e6f..0000000 --- a/src/builtin_structures/lists_and_strings/find_all_permutations_string.py +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - - - -def find_all_permutations_string(str1): - ''' print all the permutations of a given string, recursive so runtime is O(n*(n-1)) ''' - res = [] - if len(str1) == 1: - res = [str1] - else: - for i, c in enumerate(str1): - for perm in find_all_permutations_string(str1[:i] + str1[i+1:]): - res += [c + perm] - return res - - -def find_all_permutations_string_crazy(str1): - ''' crazy simple way of find all the permutations of a string, also using recursion''' - return [str1] if len(str1) == 1 else [c + perm for i, c in enumerate(str1) for perm in find_all_permutations_string_crazy(str1[:i]+str1[i+1:])] - - -def find_all_permutations_string_stdlib(str1): - ''' find all the permutations of a string just using the available packages ''' - from itertools import permutations - perms = [''.join(p) for p in permutations(str1)] - return perms - - -def test_find_all_permutations_string(): - str1 = "abc" - perm_set = {'abc', 'bac', 'cab', 'acb', 'cba', 'bca'} - assert(set(find_all_permutations_string(str1)) == perm_set) - assert(set(find_all_permutations_string_crazy(str1)) == perm_set) - assert(set(find_all_permutations_string_stdlib(str1)) == perm_set) - print('Tests passed!') - - -if __name__ == '__main__': - test_find_all_permutations_string() - - - - - - diff --git a/src/builtin_structures/lists_and_strings/find_closest_num_seq.py b/src/builtin_structures/lists_and_strings/find_closest_num_seq.py deleted file mode 100644 index c3c587c..0000000 --- a/src/builtin_structures/lists_and_strings/find_closest_num_seq.py +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - - - -def find_closest_num_seq_unsorted(seq): - ''' Find the Closest two Numbers in a Sequence. If we do this without sorting - first, the runtime will be O(n^2) ''' - dd = float("inf") - for x in seq: - for y in seq: - if x == y: continue - d = abs(x - y) - if d < dd: - xx, yy, dd = x, y, d - return xx, yy - - -def find_closest_num_seq_sorted(seq): - ''' However, if we sort first, we can achieve it with runtime O(n log n): ''' - seq.sort() - print(seq) - dd = float("inf") - for i in range(len(seq) - 1): - x, y = seq[i], seq[i+1] - if x == y: continue - d = abs(x-y) - if d < dd: - xx, yy, dd = x, y, d - return xx, yy - - -def test_find_closest_num_seq(module_name='this module'): - import random - seq = [random.randrange(100) for i in range(20)] - print(seq) - print(find_closest_num_seq_sorted(seq)) - print(find_closest_num_seq_unsorted(seq)) - - s = 'Tests in {name} have {con}!' - print(s.format(name=module_name, con='passed')) - - -if __name__ == '__main__': - test_find_closest_num_seq() - diff --git a/src/builtin_structures/lists_and_strings/find_duplicate_num_array.py b/src/builtin_structures/lists_and_strings/find_duplicate_num_array.py deleted file mode 100644 index d9330ba..0000000 --- a/src/builtin_structures/lists_and_strings/find_duplicate_num_array.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - -def find_duplicate_num_array(l1): - """ an array contains n numbers ranging from 0 to n-1. there are some numbers duplicated, but it is - not clear how many. this code find a duplicate number in the array. """ - - """ A naive solution is to sort the input array, costing O(nlogn). Another solution is the utilization of a hash set. When the number is scanned, it is either in or not. It costs O(n) auxiliary memory to accomodate a hash set. A third solution, that only costs O(1) is consider that indexes in an array with length n are in the range n-1. If there were no duplication in the n numbers from 0 to n-1, we could rearange them sorted, so that each i has its ith number. Since there are duplicates, some locations are occupied by multiple numbers, other are vacant. So every number is scanned one by one, if it the number is not in the right i, it is compared to that from i, and the duplicate can be found, or we swap. Continue until a duplicate is found.""" - - for i in range(len(l1)): - if l1[i] == i: continue - elif l1[i] < 0 or l1[i] > len(l1)-1: - return None - elif l1[i] == l1[l1[i]]: - return True - else: - aux = l1[l1[i]] - l1[l1[i]] = l1[i] - l1[i] = aux - else: - return False - -def test_find_duplicate_num_array(): - a = [1,3,5,2,4,0] - b = [1,3,5,2,1,0,4] - c = [0,0] - assert(find_duplicate_num_array(b) == True) - assert(find_duplicate_num_array(a) == False) - assert(find_duplicate_num_array(c) == True) - print('Tests passed!') - -if __name__ == '__main__': - test_find_duplicate_num_array() - - - - - - - - - - diff --git a/src/builtin_structures/lists_and_strings/find_edit_distance.py b/src/builtin_structures/lists_and_strings/find_edit_distance.py deleted file mode 100644 index f709424..0000000 --- a/src/builtin_structures/lists_and_strings/find_edit_distance.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - - -def find_edit_distance(str1, str2): - ''' computes the edit distance between two strings ''' - 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] - - -def test_find_edit_distance(): - s = 'sunday' - t = 'saturday' - assert(find_edit_distance(s, t) == 3) - print('Tests passed!') - - -if __name__ == '__main__': - test_find_edit_distance() - - - - diff --git a/src/builtin_structures/lists_and_strings/find_first_non_repetead_char.py b/src/builtin_structures/lists_and_strings/find_first_non_repetead_char.py deleted file mode 100644 index a6b57a0..0000000 --- a/src/builtin_structures/lists_and_strings/find_first_non_repetead_char.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - -''' find the first non-repetead char in a str. - ---> we use a dict to count occurences - >>> find_non_rep_char("cut") - 'c' - >>> s1 = 'google' - >>> find_non_rep_char(s1) - 'l' - >>> find_non_rep_char('ccc') - >>> find_non_rep_char('') -''' - -from collections import Counter -def find_non_rep_char(s1): - aux_dict = Counter() - for i in s1: - aux_dict[i] += 1 - for i in s1: - if aux_dict[i] < 2: return i # remember it's <2 - # not handling anything else: return None - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/src/builtin_structures/lists_and_strings/find_if_is_substr.py b/src/builtin_structures/lists_and_strings/find_if_is_substr.py deleted file mode 100644 index d8fd6d6..0000000 --- a/src/builtin_structures/lists_and_strings/find_if_is_substr.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - -''' Find if a s2 is a substring of a s1 - >>> s1 = 'buffy is a vampire slayer' - >>> s2 = 'vampire' - >>> s3 = 'angel' - >>> isSubstr(s1, s2) - True - >>> isSubstr(s1, s3) - False - >>> s4 = 'pirevam' - >>> find_substr(s2, s4) - True - >>> find_substr(s1, s4) - False -''' - -def isSubstr(s1, s2): - if s1 in s2 or s2 in s1: return True - return False - - -def find_substr(s1, s2): - if s1 == '' or s2 == '': return True #empty str is always substr - for i, c in enumerate(s1): - if c == s2[0]: - test_s1 = s1[i:]+s1[:i] - return isSubstr(s2, test_s1) - return False - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/src/builtin_structures/lists_and_strings/find_if_only_unique_chars.py b/src/builtin_structures/lists_and_strings/find_if_only_unique_chars.py deleted file mode 100644 index fe804bb..0000000 --- a/src/builtin_structures/lists_and_strings/find_if_only_unique_chars.py +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - - -def unique_char(s): - if len(s) > 256: return False - set_chars = set() - for i in s: - if i in set_chars: - return False - else: - set_chars.add(i) - return True - - - -def unique_char_no_add(s): - if len(s) < 2: return True - for i, c in enumerate(s): - for j in s[i+1:]: - if j == c: - return False - return True - - -def main(): - s1 = 'abcdefg' - s2 = 'buffy' - s3 = '' - print(unique_char(s1)) - print(unique_char(s2)) - print(unique_char(s3)) - print(unique_char_no_add(s1) ) - print(unique_char_no_add(s2)) - print(unique_char_no_add(s3)) - - -if __name__ == '__main__': - main() - diff --git a/src/builtin_structures/lists_and_strings/find_long_con_inc_subseq.py b/src/builtin_structures/lists_and_strings/find_long_con_inc_subseq.py deleted file mode 100644 index cb01c54..0000000 --- a/src/builtin_structures/lists_and_strings/find_long_con_inc_subseq.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - -def find_long_con_inc(seq): - ''' find the longest continuous increasing subsequence''' - one_seq = [] - result = [] - - for i in range(0, len(seq)-1): - pivot = seq[i] - if pivot <= seq[i+1]: - one_seq.append(pivot) - else: - one_seq.append(pivot) - if len(one_seq) > len(result): - result = one_seq - one_seq = [] - return result - - -def test_find_long_con_inc(module_name='this module'): - seq = [1, -2, 3, 5, 1, -1, 4, -1, 6] - long_con_inc = [-2,3,5] - - assert(find_long_con_inc(seq) == long_con_inc ) - -if __name__ == '__main__': - test_find_long_con_inc() - diff --git a/src/builtin_structures/lists_and_strings/find_majority_in_seq.py b/src/builtin_structures/lists_and_strings/find_majority_in_seq.py deleted file mode 100644 index da38c11..0000000 --- a/src/builtin_structures/lists_and_strings/find_majority_in_seq.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - -def find_majority_in_seq(seq): - ''' find value which occurrence is greater than the total occurrence of all other elements ''' - times = 1 - result = seq[0] - for i in range(len(seq)): - if times == 0: - result = seq[i] - times = 1 - elif seq[i] == result: - times +=1 - else: - times -=1 - - if times == 0: return None - else: - count = 0 - for i, c in enumerate(seq): - if c == result: - count += 1 - return result, count - - -def test_find_majority_in_seq(): - seq = [1, 1, 2, 3, 3, 3, 4, 4, 4, 4, 5, 6] - seq2 = [1, 2, 3] - assert(find_majority_in_seq(seq) == (4, 4)) - assert(find_majority_in_seq(seq2) == None) - print('Tests passed!') - -if __name__ == '__main__': - test_find_majority_in_seq() - - - - - - - - - -""" ->>> A = [1, 2, 3, 2, 2, 4, 2, 5, 2] ->>> find_majority(A) -(2, 5) ->>> A = [1] ->>> find_majority(A) -(1, 1) ->>> A = [1, 2, 3, 2, 5, 6, 7] ->>> find_majority(A) -No Majority Element. -""" - - - diff --git a/src/builtin_structures/lists_and_strings/find_max_profit.py b/src/builtin_structures/lists_and_strings/find_max_profit.py deleted file mode 100644 index 9b5d583..0000000 --- a/src/builtin_structures/lists_and_strings/find_max_profit.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - - -def find_max_profit_On(seq): - ''' find the most profit from a seq with O(n) ''' - max_profit = 0 - min_value = seq[0] - for i in range(1, len(seq)): - profit_here = seq[i]- min_value - if profit_here > max_profit: - max_profit = profit_here - else: - if min_value > seq[i]: - min_value = seq[i] - - return max_profit - - -def find_max_profit_On2(seq): - ''' find the most profit from a seq with O(n2) ''' - max_profit = 0 - for i in range(len(seq)-1): - for j in range (i, len(seq)-1): - if seq[j] - seq[i] > max_profit: - max_profit = seq[j] - seq[i] - return max_profit - - -def test_find_max_profit(): - seq = [9,11,5,7,16,1] - assert(find_max_profit_On(seq) == 11) - assert(find_max_profit_On2(seq) == 11) - seq = [1,15,2,3,4,3] - assert(find_max_profit_On(seq) == 14) - assert(find_max_profit_On2(seq) == 14) - print('Tests passed!') - - -if __name__ == '__main__': - test_find_max_profit() - - diff --git a/src/builtin_structures/lists_and_strings/find_max_subarray.py b/src/builtin_structures/lists_and_strings/find_max_subarray.py deleted file mode 100644 index 36a9328..0000000 --- a/src/builtin_structures/lists_and_strings/find_max_subarray.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - -def find_max_subarray1(l1): - ''' calculate the greatest sum of subarrays from an array. - An array with n elements has n(n+1)/2 subarrays so force brute cost O(n^2). - What we can do is to check when a sum becomes a negative number or zero, and then discard, since - this will not "add" anything to the new event... When the sum decreases, it gets the previous sum. ''' - sum_new, result = 0, 0 - for c in l1: - result = max(result, sum_new) - sum_new += c - if sum_new <= 0: sum_new = 0 - return result - - - -def find_max_subarray2(l1): - ''' find the contiguous subarray which has the largest sum (Kadane's algorithm in O(n)) - with extra O(n) space ''' - sum_old = [l1[0]] - for c in l1: - sum_old.append(max(c, sum_old [-1] + c)) - return max(sum_old) - - -def test_find_max_subarray(): - l1 = [-2, 1, -3, 4, -1, 2, 1, -5, 4] - l2 = [-1, 3, -5, 4, 6, -1, 2, -7, 13, -3] - assert(find_max_subarray1(l1)) == 6) - assert(find_max_subarray1(l2)) == 17) - assert(find_max_subarray2(l1) == 6) - assert(find_max_subarray2(l2) == 17) - print('Tests passed!') - -if __name__ == '__main__': - test_find_max_subarray() - - - - - - diff --git a/src/builtin_structures/lists_and_strings/find_palindrome_rec.py b/src/builtin_structures/lists_and_strings/find_palindrome_rec.py deleted file mode 100644 index ec79fa0..0000000 --- a/src/builtin_structures/lists_and_strings/find_palindrome_rec.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - - -def find_palindrome_rec(s): - ''' recursive way of checking whether a str is a palindrome ''' - if len(s) > 1: - if s[0] != s[-1]: return False - else: find_palindrome_rec(s[1:-1]) - return True - - -def test_find_palindrome_rec(module_name='this module'): - str1 = 'radar' - str2 = "" - str3 = 'x' - str4 = 'hello' - assert(find_palindrome_rec(str1) == True) - assert(find_palindrome_rec(str2) == True) - assert(find_palindrome_rec(str3) == True) - assert(find_palindrome_rec(str4) == False) - s = 'Tests in {name} have {con}!' - print(s.format(name=module_name, con='passed')) - - -if __name__ == '__main__': - test_find_palindrome_rec() - diff --git a/src/builtin_structures/lists_and_strings/find_product_without_division.py b/src/builtin_structures/lists_and_strings/find_product_without_division.py deleted file mode 100644 index 82bcf0d..0000000 --- a/src/builtin_structures/lists_and_strings/find_product_without_division.py +++ /dev/null @@ -1,33 +0,0 @@ -def find_product_without_division(seq): - '''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 ''' - forw = [] - bacw = [] - - for i in range(len(seq)): - prod_f = 1 - prod_b = 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) - - print(bacw) - print(forw) - for i in range(len(seq)): - seq[i] = forw[i]*bacw[i] - - return seq - - - -def test_find_product_without_division(): - seq = [2,3,4] - result = [12, 8, 6] - print(find_product_without_division(seq)) - - - -if __name__ == '__main__': - test_find_product_without_division() diff --git a/src/builtin_structures/lists_and_strings/find_subst_in_str.py b/src/builtin_structures/lists_and_strings/find_subst_in_str.py deleted file mode 100644 index 6caff9b..0000000 --- a/src/builtin_structures/lists_and_strings/find_subst_in_str.py +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - - -def find_subst_in_str(str1, set1): - sub_str1 = '' - found = False - - while set1: - for c in str1: - if c in set1: - set1.remove(c) - found = True - if found == True: - sub_str1 += c - if len(set1) == 0: found = False - return sub_str1 - - - -def test_find_subst_in_str(module_name='this module'): - str1 = 'ydxahbcscdk' - - set1 = {'a','b','c','d'} - result = 'dxahbc' - - assert( find_subst_in_str(str1, set1)==result) - - set2 = {'a','b','c'} - result2 = 'ahbc' - assert( find_subst_in_str(str1, set2)==result2) - - - s = 'Tests in {name} have {con}!' - print(s.format(name=module_name, con='passed')) - - -if __name__ == '__main__': - test_find_subst_in_str() - diff --git a/src/builtin_structures/lists_and_strings/find_two_missing_numbers_in_sequence.py b/src/builtin_structures/lists_and_strings/find_two_missing_numbers_in_sequence.py deleted file mode 100644 index 24beab5..0000000 --- a/src/builtin_structures/lists_and_strings/find_two_missing_numbers_in_sequence.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - - -import math - -def find_two_missing_numbers(l1): - """ 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. - """ - - 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 num1, num2 - - - -def test_find_two_missing_numbers(): - l1 = [1, 3, 5] - result = find_two_missing_numbers(l1) - assert(result[0] == 2.0 or result[0] == 4.0) - print('Tests passed!') - - -if __name__ == '__main__': - test_find_two_missing_numbers() - - - - - - - diff --git a/src/builtin_structures/lists_and_strings/greatest_sum_sub_array.py b/src/builtin_structures/lists_and_strings/greatest_sum_sub_array.py deleted file mode 100644 index 10bf2f1..0000000 --- a/src/builtin_structures/lists_and_strings/greatest_sum_sub_array.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - - -def greatest_sum_sub_array(l1): - sum_new = 0 - results = [] - for i, c in enumerate(l1): - sum_old = sum_new - sum_new = sum_old + c - if sum_new <= 0 or sum_new < sum_old: - sum_new = 0 - results.append(sum_old) - continue - results.append(sum_new) - results.sort() - return results.pop() - -def test_greatest_sum_sub_array(): - l1 = [1, -4, 20, -4, 5, 15, 3] - assert(greatest_sum_sub_array(l1) == 23) - print('Tests passed!') - -if __name__ == '__main__': - test_greatest_sum_sub_array() - diff --git a/src/builtin_structures/lists_and_strings/longest_common_substring.py b/src/builtin_structures/lists_and_strings/longest_common_substring.py deleted file mode 100644 index 13aa0af..0000000 --- a/src/builtin_structures/lists_and_strings/longest_common_substring.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - - - -def longest_common_substring(str1, str2): - ''' find the largest commom substring from 2 strings ''' - m = [[0 for i in range(len(str2) + 1)] for k in range(len(str1) + 1)] - lcs = None - max_len = 0 - for y in range(1, len(str1) + 1): - for x in range(1, len(str2) + 1): - m[y][x] = m[y - 1][x - 1] + 1 if (str1[y - 1] == str2[x - 1]) else 0 - - if m[y][x] > max_len: - max_len = m[y][x] - lcs = str1[(y - max_len):y] - return max_len, lcs - - -def test_longest_common_substring(): - str1 = 'buffy is a vampire slayer' - str2 = 'aaas bampires vslay' - assert(longest_common_substring(str1, str2) == (6, 'ampire')) - print('Tests passed!') - - -if __name__ == '__main__': - test_longest_common_substring() - - diff --git a/src/builtin_structures/lists_and_strings/merge_two_sorted_arrays.py b/src/builtin_structures/lists_and_strings/merge_two_sorted_arrays.py deleted file mode 100644 index 617d183..0000000 --- a/src/builtin_structures/lists_and_strings/merge_two_sorted_arrays.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - -def merge_two_sorted_arrays(a1, a2): - """ merge two sorted arrays, keeping the final sorted """ - if len(a1) >= len(a2): - biga = a1 - smalla = a2 - else: - biga = a2 - smalla = a1 - final = [] - count = 0 - for i in range(len(biga)): - if count < len(smalla) and smalla[count] < biga[i]: - final.append(smalla[count]) - count+=1 - final.append(biga[i]) - return final - -def test_merge_two_sorted_arrays(): - a1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - a2 = [3, 6, 7] - assert(merge_two_sorted_arrays(a1, a2) == [0, 1, 2, 3, 3, 4, 5, 6, 6, 7, 7, 8, 9, 10]) - print('Tests passed!') - -if __name__ == '__main__': - test_merge_two_sorted_arrays() - - - - - - - - - diff --git a/src/builtin_structures/lists_and_strings/perm_str.py b/src/builtin_structures/lists_and_strings/perm_str.py deleted file mode 100644 index 6c32dfa..0000000 --- a/src/builtin_structures/lists_and_strings/perm_str.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - -''' give all the permutation of a str: - >>> str1 = 'hat' - >>> perm_str(str1) - ['hat', 'hta', 'aht', 'ath', 'tha', 'tah'] - >>> perm_str('') - '' -''' - -def perm_str(str1): - if len(str1) < 2: return str1 - result = [] - for i in range(len(str1)): - for perm in perm_str(str1[:i] + str1[i+1:]): - result.append(str1[i] + perm) - return result - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/src/builtin_structures/lists_and_strings/print_all_seq_with_cont_num.py b/src/builtin_structures/lists_and_strings/print_all_seq_with_cont_num.py deleted file mode 100644 index 1bfa771..0000000 --- a/src/builtin_structures/lists_and_strings/print_all_seq_with_cont_num.py +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - - -def print_all_seq_with_cont_num(s): - ''' print all sequences with cont. numbers (2 at least) whose sum is a given s ''' - if s < 3: return s - small = 1 - big = 2 - sum_here = big + small - result = [] - - while small < (1+s)/2: - sum_here = sum(range(small, big)) - if sum_here < s: - big += 1 - elif sum_here > s: - small +=1 - else: - result.append(list(range(small, big))) - big += 1 - - return result - -def test_print_all_seq_with_cont_num(): - s = 15 - sum_set_for_s = [[1,2,3,4,5], [4,5,6], [7,8]] - assert(print_all_seq_with_cont_num(s) == sum_set_for_s) - s = 1 - assert(print_all_seq_with_cont_num(s)== 1) - s = 0 - assert(print_all_seq_with_cont_num(s) == 0) - print('Tests passed!') - - -if __name__ == '__main__': - test_print_all_seq_with_cont_num() - diff --git a/src/builtin_structures/lists_and_strings/remove_specified_char_from_str.py b/src/builtin_structures/lists_and_strings/remove_specified_char_from_str.py deleted file mode 100644 index 7c7dc36..0000000 --- a/src/builtin_structures/lists_and_strings/remove_specified_char_from_str.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - -''' remove the chars in a list from a string - ---> handle whitespaces!!!! - >>> remove_char_str('I love google', 'oe') - 'I lv ggl' - >>> remove_char_str('google', '') - 'google' - >>> remove_char_str('google', 'google') - '' -''' - - -def remove_char_str(s1, charlist): - set_aux = set(charlist) - lt_aux = [] # we use list intead of concat. strs because it's more efficient - for c in s1: - if c not in set_aux: - lt_aux.append(c) - return ''.join(lt_aux) # IF NON CHARS, RETURN '' not NONE! - - - -if __name__ == '__main__': - import doctest - doctest.testmod() - diff --git a/src/builtin_structures/lists_and_strings/removing_duplicates_seq.py b/src/builtin_structures/lists_and_strings/removing_duplicates_seq.py deleted file mode 100644 index 9399ae3..0000000 --- a/src/builtin_structures/lists_and_strings/removing_duplicates_seq.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - - -def removing_duplicates_seq(seq): - ''' if the values are hashable, we can use set and generators to remove duplicates - in a sequence ''' - seen = set() - for item in seq: - if item not in seen: - yield item - seen.add(item) - -def removing_duplicates_seq_not_hash(seq, key= None): - ''' if the item is not hashable, such as dictionaries ''' - seen = set() - for item in seq: - val = item if key is None else key[item] - if item not in seen: - yield item - seen.add(val) - - - -def test_removing_duplicates_seq(): - seq = [1, 2, 2, 2, 3, 3, 4, 4, 4] - dict = {'a':1, 'b':2, 'a':2, 'a':1} - assert(list(removing_duplicates_seq(seq)) == [1,2,3,4]) - assert(list(removing_duplicates_seq_not_hash(dict)) == ['a', 'b']) - print('Tests passed!'.center(20, '*')) - - -if __name__ == '__main__': - test_removing_duplicates_seq() - - diff --git a/src/builtin_structures/lists_and_strings/reverse_str.py b/src/builtin_structures/lists_and_strings/reverse_str.py deleted file mode 100644 index 5752173..0000000 --- a/src/builtin_structures/lists_and_strings/reverse_str.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python - -author = "Mari Wahl" -email = "marina.w4hl@gmail.com" - - -# timeit is used for benchmarking. -from timeit import timeit - - -def reverse_1(string): - """ - Slowest function. Use a list and str.join to reverse the string. - :param string: the string to be reversed. - :return: a reversed string. - """ - reversed_string = [] - # Iterates from the last to the first character. - for i in range(len(string) - 1, -1, -1): - # Appends the character to the list. - reversed_string.append(string[i]) - return ''.join(reversed_string) - - -def reverse_2(string): - """ - Same principle as reverse_1. One-liner cousin. - :param string: the string to be reversed. - :return: a reversed string. - """ - return ''.join([character for character in [string[i] for i in range(len(string) - 1, -1, -1)]]) - - -def reverse_3(string): - """ - Another one-liner. We make a list from the characters of the string and reverse it. - :param string: the string to be reversed. - :return: a reversed string. - """ - return ''.join([character for character in string][::-1]) - -# Overkill of elegance. A bit too passionate but it defines this lambda function well. -# Simply returns the string backwards. As fast as concise. -reverse_lambda = lambda s: s[::-1] - -# We define some short strings to test our functions. -strings = ('buffy', 'foo', 'bar') -# We announce what we are doing. -print(', '.join(strings), ' should appear reversed if the function is working.\n') -print('{:<30}:'.format('Function name'), 'benchmarking result (lower is better):') -# Iterate over a tuple of functions. -for function in (reverse_1, reverse_2, reverse_3, reverse_lambda): - name = function.__name__ if function.__name__ != "" else 'reverse_lambda' - # We print the function's name and its benchmark result. - print("{:<30}:".format(name), timeit(name + "('string')", setup='from __main__ import ' + name)) - # We print the output so that we can check if the function is working as expected. - print(', '.join(map(function, strings)), '\n') -# We wait until the user wants to quit. -input('Press Return to quit.') diff --git a/src/builtin_structures/lists_and_strings/reverse_string_inplace_rec.py b/src/builtin_structures/lists_and_strings/reverse_string_inplace_rec.py deleted file mode 100644 index f2f164d..0000000 --- a/src/builtin_structures/lists_and_strings/reverse_string_inplace_rec.py +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env python - -author = "Mari Wahl" -email = "marina.w4hl@gmail.com" - - - -def reverse_string_inplace_rec(s): - ''' takes a string and returns its reverse''' - if s: - s = s[-1] + reverse_string_inplace_rec(s[:-1]) - return s - -def reverse_string_inplace(s): - s = s[::-1] - if s[0] == '\0': - s = s[1:] - s += '\0' - return s - - - -def test_reverse_string_inplace_rec(module_name='this module'): - s = 'hello' - s2 = 'buffy\0' - assert(reverse_string_inplace(s) == 'olleh') - assert(reverse_string_inplace(s2) == 'yffub\0') - assert(reverse_string_inplace_rec(s) == 'olleh') - - s = 'Tests in {name} have {con}!' - print(s.format(name=module_name, con='passed')) - -if __name__ == '__main__': - test_reverse_string_inplace_rec() - diff --git a/src/builtin_structures/lists_and_strings/reverse_words_sentence.py b/src/builtin_structures/lists_and_strings/reverse_words_sentence.py deleted file mode 100644 index 5fcee65..0000000 --- a/src/builtin_structures/lists_and_strings/reverse_words_sentence.py +++ /dev/null @@ -1,117 +0,0 @@ - -#!/usr/bin/env python - -author = "Mari Wahl" -email = "marina.w4hl@gmail.com" - -""" Here we want to invert the words in a string, without reverting -the words. - -Important things to remember: - -1. python strings are immutable -2. The last word doesn't not end by a space, so we need to make -sure we get the last word too - -The solution consists of two loops, -1) revert all the characters with 2 pointers -2) search for spaces and revert the words, two pointers too -3) You can represent space as ' ' or as u'\u0020' -4) Do we want to look to ! ; , . etc? - -In the solutions bellow, we show how to do this logic, and how to use -python's methods to do in a few lines -""" - - -# EXAMPLE NUMBER 1 - -def reverser(string1, p1=0, p2=None): - if len(string1) < 2: - return string1 - p2 = p2 or len(string1)-1 - while p1 < p2: - aux = string1[p1] - string1[p1] = string1[p2] - string1[p2] = aux - p1 += 1 - p2 -= 1 - - - -def reversing_words_setence_logic(string1): - reverser(string1) - p = 0 - start = 0 - while p < len(string1): - if string1[p] == u"\u0020": - reverser(string1,start,p-1) - start = p+1 - p += 1 - reverser(string1,start,p-1) - - return "".join(string1) - - - -# EXAMPLE NUMBER 2 AND 3 USING PYTHON AWESOMESAUCE - -def reversing_words_setence_py(str1): - ''' reverse the words in a sentence''' - words = str1.split() - rev_set = " ".join(reversed(words)) - return rev_set - -def reversing_words_setence_py2(str1): - """ - Reverse the order of the words in a sentence. - :param string: the string which words wilL be reversed. - :return: the reversed string. - """ - words = str1.split(' ') - words.reverse() - return ' '.join(words) - - -# EXAMPLE 4, VERY SILLY, USING BRUTE FORCE -# -def reverse_words_brute(string): - """ - Reverse the order of the words in a sentence. - :param string: the string which words wil lbe reversed. - :return: the reversed string. - """ - word, sentence = [], [] - for character in string: - if character != ' ': - word.append(character) - else: - # So we do not keep multiple whitespaces. An empty list evaluates to False. - if word: - sentence.append(''.join(word)) - word = [] - # So we do not keep multiple whitespaces. An empty list evaluates to False. - if word != '': - sentence.append(''.join(word)) - sentence.reverse() - return ' '.join(sentence) - - - -# TESTS - -def test_reversing_words_sentence(): - str1 = "Buffy is a Vampire Slayer" - assert(reversing_words_setence_py(str1) == "Slayer Vampire a is Buffy") - assert(reversing_words_setence_py2(str1) == "Slayer Vampire a is Buffy") - assert(reverse_words_brute(str1) == "Slayer Vampire a is Buffy") - assert(reversing_words_setence_logic(list(str1)) == "Slayer Vampire a is Buffy") - - print("Tests passed!") - - - -if __name__ == '__main__': - test_reversing_words_sentence() - - diff --git a/src/builtin_structures/lists_and_strings/sum_two_numbers_sequence.py b/src/builtin_structures/lists_and_strings/sum_two_numbers_sequence.py deleted file mode 100644 index bee6a8d..0000000 --- a/src/builtin_structures/lists_and_strings/sum_two_numbers_sequence.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - - -def sum_two_numbers_sequence(seq, s): - """ given an increasing sorted array and an integer s, find if there is a pair of two numbers in the array whose sum is s. It takes O(n). """ - l1 = seq[:] - l2 = seq[:] - l2.reverse() - n1 = l1.pop() - n2 = l2.pop() - while l2 and l1: - sum_here = n1 + n2 - if sum_here > s: - n1 = l1.pop() - elif sum_here < s: - n2 = l2.pop() - else: - return True - return False - - - -def test_sum_two_numbers_sequence(): - l1 = [1,2,3,4,5,6,7,8] - s = 7 - assert(sum_two_numbers_sequence(l1, s) == True) - print('Tests passed!') - - -if __name__ == '__main__': - test_sum_two_numbers_sequence() - - - diff --git a/src/builtin_structures/lists_and_strings/verify_if_perm.py b/src/builtin_structures/lists_and_strings/verify_if_perm.py deleted file mode 100644 index b4476be..0000000 --- a/src/builtin_structures/lists_and_strings/verify_if_perm.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail - - -def ver_perm(s1, s2): - ''' worst case O(nlogn + mlogm) = O(NlogN) ''' - if len(s1) != len(s2): return False - s1 = sorted(s1) - s2 = sorted(s2) - return s1 == s2 - -from collections import Counter -def ver_perm_dict(s1, s2): - ''' worst case O(n + n +2n) = O(n)''' - if len(s1) != len(s2): return False - dict_aux = Counter() - for c in s1: - dict_aux[c] += 1 - for c in s2: - dict_aux[c] -= 1 - for item in dict_aux: - if dict_aux[item]: - return False - return True - -import time -def main(): - s1 = 'ufyfbufyfb' - s2 = 'buffybuffy' - s3 = 'uuyfbuuyfb' - s4 = '' - start = time.time() - print(ver_perm(s1, s2)) - print(ver_perm(s1, s3)) - print(ver_perm(s1, s4)) - final1 = time.time() - start - - start = time.time() - print(ver_perm_dict(s1, s2)) - print(ver_perm_dict(s1, s3)) - print(ver_perm_dict(s1, s4)) - final2 = time.time() - start - - print(final2-final1) - -if __name__ == '__main__': - main() - diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/longest_common_prefix.py b/src/builtin_structures/longest_common_prefix.py similarity index 65% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/longest_common_prefix.py rename to src/builtin_structures/longest_common_prefix.py index dc79efe..408c44f 100644 --- a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/longest_common_prefix.py +++ b/src/builtin_structures/longest_common_prefix.py @@ -35,15 +35,41 @@ def lcp(s1, s2): return len(lcp) + + def lcppy(x): ''' >>> lcppy([[3,2,1], [3,2,1,4,5]]) [3, 2, 1] ''' - import os return os.path.commonprefix(x) + +def lcp2(s1, s2): + ''' + >>> lcp2('dabbd', 'aabbaa') + 3 + >>> lcp2('abcd', 'hi') + 0 + ''' + m = [[0 for i in range(len(s2) + 1)] for k in range(len(s1) + 1)] + + lcp = 0 + + for y in range(1, len(s1) + 1): + for x in range(1, len(s2) + 1): + if (s1[y - 1] == s2[x - 1]): + m[y][x] = m[y - 1][x - 1] + 1 + else: + m[y][x] = 0 + + if m[y][x] > lcp: + lcp = m[y][x] + return lcp + + + if __name__ == '__main__': import doctest doctest.testmod() diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/max_subarray_stocks.py b/src/builtin_structures/max_subarray_stocks.py similarity index 60% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/max_subarray_stocks.py rename to src/builtin_structures/max_subarray_stocks.py index e6f5f41..11bf739 100755 --- a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/max_subarray_stocks.py +++ b/src/builtin_structures/max_subarray_stocks.py @@ -23,7 +23,32 @@ def beating_stock(array): 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])) \ No newline at end of file + 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/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/number_of_zeros_factorial.txt b/src/builtin_structures/number_of_zeros_factorial.txt similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/number_of_zeros_factorial.txt rename to src/builtin_structures/number_of_zeros_factorial.txt diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/check_if_palindrome.py b/src/builtin_structures/palindrome.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/check_if_palindrome.py rename to src/builtin_structures/palindrome.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/permutations.py b/src/builtin_structures/permutations.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/permutations.py rename to src/builtin_structures/permutations.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/prod_other_ints.py b/src/builtin_structures/prod_other_ints.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/prod_other_ints.py rename to src/builtin_structures/prod_other_ints.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/ransom_note.py b/src/builtin_structures/ransom_note.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/ransom_note.py rename to src/builtin_structures/ransom_note.py diff --git a/src/builtin_structures/reverse_string.py b/src/builtin_structures/reverse_string.py new file mode 100644 index 0000000..e20d32f --- /dev/null +++ b/src/builtin_structures/reverse_string.py @@ -0,0 +1,37 @@ +#!/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/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/reverse_words.py b/src/builtin_structures/reverse_words.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/reverse_words.py rename to src/builtin_structures/reverse_words.py diff --git a/src/builtin_structures/lists_and_strings/rotate_NxN.py b/src/builtin_structures/rotate_NxN.py similarity index 85% rename from src/builtin_structures/lists_and_strings/rotate_NxN.py rename to src/builtin_structures/rotate_NxN.py index d238a94..f841bad 100644 --- a/src/builtin_structures/lists_and_strings/rotate_NxN.py +++ b/src/builtin_structures/rotate_NxN.py @@ -1,8 +1,7 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail +#!/usr/bin/env python + +__author__ = "bt3" - def rotate_NxN(m): n = len(m) for layer in range(n//2): @@ -16,7 +15,7 @@ def rotate_NxN(m): m[last][last-offset] = m[i][last] m[i][last] = top return m - + def main(): @@ -25,7 +24,7 @@ def main(): 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/src/builtin_structures/dicts/runtime_dicts_with_timeit_module.py b/src/builtin_structures/runtime_dicts_with_timeit_module.py similarity index 58% rename from src/builtin_structures/dicts/runtime_dicts_with_timeit_module.py rename to src/builtin_structures/runtime_dicts_with_timeit_module.py index c8138fc..b54c637 100644 --- a/src/builtin_structures/dicts/runtime_dicts_with_timeit_module.py +++ b/src/builtin_structures/runtime_dicts_with_timeit_module.py @@ -1,9 +1,19 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail +#!/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. ''' +'''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 @@ -19,7 +29,7 @@ for i in range(10000,1000001,20000): print("%d,%10.3f,%10.3f" % (i, lst_time, d_time)) -""" There rersults are: +""" There results are: 10000, 0.192, 0.002 30000, 0.600, 0.002 50000, 1.000, 0.002 diff --git a/src/builtin_structures/lists_and_strings/runtime_lists_with_timeit_module.py b/src/builtin_structures/runtime_lists_with_timeit_module.py similarity index 97% rename from src/builtin_structures/lists_and_strings/runtime_lists_with_timeit_module.py rename to src/builtin_structures/runtime_lists_with_timeit_module.py index c9841bc..f7da733 100644 --- a/src/builtin_structures/lists_and_strings/runtime_lists_with_timeit_module.py +++ b/src/builtin_structures/runtime_lists_with_timeit_module.py @@ -1,7 +1,6 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail +#!/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. ''' diff --git a/src/builtin_structures/lists_and_strings/simple_str_comprension.py b/src/builtin_structures/simple_str_comprension.py similarity index 54% rename from src/builtin_structures/lists_and_strings/simple_str_comprension.py rename to src/builtin_structures/simple_str_comprension.py index d357e69..6a516df 100644 --- a/src/builtin_structures/lists_and_strings/simple_str_comprension.py +++ b/src/builtin_structures/simple_str_comprension.py @@ -1,11 +1,19 @@ -#!/usr/bin/python3 -# mari von steinkirch @2013 -# steinkirch at gmail +#!/usr/bin/env python + +__author__ = "bt3" + - from collections import Counter + def str_comp(s): - ''' basic str compression with counts of repeated char''' + ''' + >>> s1 = 'aabcccccaaa' + >>> str_comp(s1) + 'a2b1c5a3' + >>> str_comp('') + '' + ''' + count, last = 1, '' list_aux = [] for i, c in enumerate(s): @@ -17,16 +25,10 @@ def str_comp(s): list_aux.append(c) count = 1 last = c - list_aux.append(str(count)) + list_aux.append(str(count)) return ''.join(list_aux) - -def main(): - s1 = 'aabcccccaaa' - s2 = '' - print(str_comp(s1)) # 'a2b1c5a3' - print(str_comp(s2)) - + if __name__ == '__main__': - main() - + import doctest + doctest.testmod() diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/sum_two_numbers_as_strings.py b/src/builtin_structures/sum_two_numbers_as_strings.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/math_arrays_and_strings/sum_two_numbers_as_strings.py rename to src/builtin_structures/sum_two_numbers_as_strings.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/sorting_and_searching/binary_search.py b/src/searching_and_sorting/binary_search.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/sorting_and_searching/binary_search.py rename to src/searching_and_sorting/binary_search.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/sorting_and_searching/merge_and_sort_two_arrays.py b/src/searching_and_sorting/merge_and_sort_two_arrays.py similarity index 96% rename from src/EXTRA_INTERVIEW_PROBLEMS/sorting_and_searching/merge_and_sort_two_arrays.py rename to src/searching_and_sorting/merge_and_sort_two_arrays.py index e40d1f1..29490e5 100644 --- a/src/EXTRA_INTERVIEW_PROBLEMS/sorting_and_searching/merge_and_sort_two_arrays.py +++ b/src/searching_and_sorting/merge_and_sort_two_arrays.py @@ -17,7 +17,7 @@ def merge_arrays(a1, a2): >>> merge_arrays([], []) [] ''' - + # if they are not sorted yet a1.sort() a2.sort() diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/sorting_and_searching/quick_sort.py b/src/searching_and_sorting/quick_sort.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/sorting_and_searching/quick_sort.py rename to src/searching_and_sorting/quick_sort.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/trees/binary_search_tree.py b/src/trees/trees/binary_search_tree.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/trees/binary_search_tree.py rename to src/trees/trees/binary_search_tree.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/trees/binary_tree.py b/src/trees/trees/binary_tree.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/trees/binary_tree.py rename to src/trees/trees/binary_tree.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/trees/check_if_balanced.py b/src/trees/trees/check_if_balanced.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/trees/check_if_balanced.py rename to src/trees/trees/check_if_balanced.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/trees/check_if_bst.py b/src/trees/trees/check_if_bst.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/trees/check_if_bst.py rename to src/trees/trees/check_if_bst.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/trees/transversing_bt.py b/src/trees/trees/transversing_bt.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/trees/transversing_bt.py rename to src/trees/trees/transversing_bt.py diff --git a/src/EXTRA_INTERVIEW_PROBLEMS/trees/trie.py b/src/trees/trees/trie.py similarity index 100% rename from src/EXTRA_INTERVIEW_PROBLEMS/trees/trie.py rename to src/trees/trees/trie.py