diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000000..514c9327e231 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: TheAlgorithms +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: ['http://paypal.me/TheAlgorithms/1000', 'https://donorbox.org/thealgorithms'] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 19b928c187f9..03de387a8acd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -72,9 +72,9 @@ We want your work to be readable by others; therefore, we encourage you to note - Write tests to illustrate your work. - The following "testing" approaches are not encouraged: + The following "testing" approaches are **not** encouraged: - ```python + ```python* input('Enter your input:') # Or even worse... input = eval(raw_input("Enter your input: ")) @@ -97,13 +97,9 @@ We want your work to be readable by others; therefore, we encourage you to note #### Other Standard While Submitting Your Work -- File extension for code should be `.py`. - -- Please file your work to let others use it in the future. Here are the examples that are acceptable: +- File extension for code should be `.py`. Jupiter notebook files are acceptable in machine learning algorithms. - - Camel cases - - `-` Hyphenated names - - `_` Underscore-separated names +- Strictly use snake case (underscore separated) in your file name, as it will be easy to parse in future using scripts. If possible, follow the standard *within* the folder you are submitting to. @@ -111,6 +107,8 @@ We want your work to be readable by others; therefore, we encourage you to note - If you have modified/added documentation work, make sure your language is concise and contains no grammar mistake. +- Update the README file if you have added any new algorithm. Only entry corresponding to the algorithm is to be made, not need to add sample data, test files or solutions to problems like Project Euler, in the README. + - Add a corresponding explanation to [Algorithms-Explanation](https://github.com/TheAlgorithms/Algorithms-Explanation) (Optional but recommended). - Most importantly, diff --git a/DIRECTORY.md b/DIRECTORY.md index ad25772b56b6..befd634c1eb0 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1,6 +1,3 @@ -## Analysis - * Compression Analysis - * [psnr](https://github.com/TheAlgorithms/Python/blob/master/analysis/compression_analysis/psnr.py) ## Arithmetic Analysis * [bisection](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/bisection.py) * [intersection](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/intersection.py) @@ -39,17 +36,19 @@ * [xor cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/xor_cipher.py) ## Compression * [huffman](https://github.com/TheAlgorithms/Python/blob/master/compression/huffman.py) +## Compression Analysis + * [psnr](https://github.com/TheAlgorithms/Python/blob/master/compression_analysis/psnr.py) ## Data Structures * [arrays](https://github.com/TheAlgorithms/Python/blob/master/data_structures/arrays.py) * [avl](https://github.com/TheAlgorithms/Python/blob/master/data_structures/avl.py) * [LCA](https://github.com/TheAlgorithms/Python/blob/master/data_structures/LCA.py) * Binary Tree - * [AVL tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary%20tree/AVL_tree.py) - * [binary search tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary%20tree/binary_search_tree.py) - * [fenwick tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary%20tree/fenwick_tree.py) - * [lazy segment tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary%20tree/lazy_segment_tree.py) - * [segment tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary%20tree/segment_tree.py) - * [treap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary%20tree/treap.py) + * [AVL tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/AVL_tree.py) + * [binary search tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_search_tree.py) + * [fenwick tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/fenwick_tree.py) + * [lazy segment tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/lazy_segment_tree.py) + * [segment tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/segment_tree.py) + * [treap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/treap.py) * Hashing * [double hash](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/double_hash.py) * [hash table](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/hash_table.py) @@ -192,8 +191,9 @@ * Tests * [test fibonacci](https://github.com/TheAlgorithms/Python/blob/master/maths/tests/test_fibonacci.py) ## Matrix - * [matrix multiplication addition](https://github.com/TheAlgorithms/Python/blob/master/matrix/matrix_multiplication_addition.py) + * [matrix operation](https://github.com/TheAlgorithms/Python/blob/master/matrix/matrix_operation.py) * [searching in sorted matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/searching_in_sorted_matrix.py) + * [spiralPrint](https://github.com/TheAlgorithms/Python/blob/master/matrix/spiralPrint.py) ## Networking Flow * [ford fulkerson](https://github.com/TheAlgorithms/Python/blob/master/networking_flow/ford_fulkerson.py) * [minimum cut](https://github.com/TheAlgorithms/Python/blob/master/networking_flow/minimum_cut.py) @@ -294,6 +294,8 @@ * [p022 names](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_22/p022_names.txt) * [sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_22/sol1.py) * [sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_22/sol2.py) + * Problem 234 + * [sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_234/sol1.py) * Problem 24 * [sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_24/sol1.py) * Problem 25 diff --git a/README.md b/README.md index 527b80269fdc..a28475791432 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # The Algorithms - Python + [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/TheAlgorithms/100)   [![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/TheAlgorithms)   [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/TheAlgorithms/Python) @@ -7,6 +8,17 @@ These implementations are for learning purposes. They may be less efficient than the implementations in the Python standard library. +## Owners + +Anup Kumar Panwar +  [[Gmail](mailto:1anuppanwar@gmail.com?Subject=The%20Algorithms%20-%20Python) +  [Gihub](https://github.com/anupkumarpanwar) +  [LinkedIn](https://www.linkedin.com/in/anupkumarpanwar/)] + +Chetan Kaushik +  [[Gmail](mailto:dynamitechetan@gmail.com?Subject=The%20Algorithms%20-%20Python) +  [Gihub](https://github.com/dynamitechetan) +  [LinkedIn](https://www.linkedin.com/in/chetankaushik/)] ## Contribution Guidelines @@ -15,3 +27,338 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ## Community Channel We're on [Gitter](https://gitter.im/TheAlgorithms)! Please join us. + +# Algorithms + +## Hashes + +- [Md5](./hashes/md5.py) +- [Chaos Machine](./hashes/chaos_machine.py) +- [Sha1](./hashes/sha1.py) + +## File Transfer Protocol + +- [Ftp Client Server](./file_transfer_protocol/ftp_client_server.py) +- [Ftp Send Receive](./file_transfer_protocol/ftp_send_receive.py) + +## Backtracking + +- [N Queens](./backtracking/n_queens.py) +- [Sum Of Subsets](./backtracking/sum_of_subsets.py) +- [All Subsequences](./backtracking/all_subsequences.py) +- [All Permutations](./backtracking/all_permutations.py) + +## Ciphers + +- [Transposition Cipher](./ciphers/transposition_cipher.py) +- [Atbash](./ciphers/Atbash.py) +- [Rot13](./ciphers/rot13.py) +- [Rabin Miller](./ciphers/rabin_miller.py) +- [Transposition Cipher Encrypt Decrypt File](./ciphers/transposition_cipher_encrypt_decrypt_file.py) +- [Affine Cipher](./ciphers/affine_cipher.py) +- [Trafid Cipher](./ciphers/trafid_cipher.py) +- [Base16](./ciphers/base16.py) +- [Elgamal Key Generator](./ciphers/elgamal_key_generator.py) +- [Rsa Cipher](./ciphers/rsa_cipher.py) +- [Prehistoric Men.txt](./ciphers/prehistoric_men.txt) +- [Vigenere Cipher](./ciphers/vigenere_cipher.py) +- [Xor Cipher](./ciphers/xor_cipher.py) +- [Brute Force Caesar Cipher](./ciphers/brute_force_caesar_cipher.py) +- [Rsa Key Generator](./ciphers/rsa_key_generator.py) +- [Simple Substitution Cipher](./ciphers/simple_substitution_cipher.py) +- [Playfair Cipher](./ciphers/playfair_cipher.py) +- [Morse Code Implementation](./ciphers/morse_Code_implementation.py) +- [Base32](./ciphers/base32.py) +- [Base85](./ciphers/base85.py) +- [Base64 Cipher](./ciphers/base64_cipher.py) +- [Onepad Cipher](./ciphers/onepad_cipher.py) +- [Caesar Cipher](./ciphers/caesar_cipher.py) +- [Hill Cipher](./ciphers/hill_cipher.py) +- [Cryptomath Module](./ciphers/cryptomath_module.py) + +## Arithmetic Analysis + +- [Bisection](./arithmetic_analysis/bisection.py) +- [Newton Method](./arithmetic_analysis/newton_method.py) +- [Newton Raphson Method](./arithmetic_analysis/newton_raphson_method.py) +- [Intersection](./arithmetic_analysis/intersection.py) +- [Lu Decomposition](./arithmetic_analysis/lu_decomposition.py) + +## Boolean Algebra + +- [Quine Mc Cluskey](./boolean_algebra/quine_mc_cluskey.py) + +## Traversals + +- [Binary Tree Traversals](./traversals/binary_tree_traversals.py) + +## Maths + +- [Average](./maths/average.py) +- [Abs Max](./maths/abs_Max.py) +- [Average Median](./maths/average_median.py) +- [Trapezoidal Rule](./maths/trapezoidal_rule.py) +- [Prime Check](./maths/Prime_Check.py) +- [Modular Exponential](./maths/modular_exponential.py) +- [Newton Raphson](./maths/newton_raphson.py) +- [Factorial Recursive](./maths/factorial_recursive.py) +- [Extended Euclidean Algorithm](./maths/extended_euclidean_algorithm.py) +- [Greater Common Divisor](./maths/greater_common_divisor.py) +- [Fibonacci](./maths/fibonacci.py) +- [Find Lcm](./maths/find_lcm.py) +- [Find Max](./maths/Find_Max.py) +- [Fermat Little Theorem](./maths/fermat_little_theorem.py) +- [Factorial Python](./maths/factorial_python.py) +- [Fibonacci Sequence Recursion](./maths/fibonacci_sequence_recursion.py) +- [Sieve Of Eratosthenes](./maths/sieve_of_eratosthenes.py) +- [Abs Min](./maths/abs_Min.py) +- [Lucas Series](./maths/lucasSeries.py) +- [Segmented Sieve](./maths/segmented_sieve.py) +- [Find Min](./maths/Find_Min.py) +- [Abs](./maths/abs.py) +- [Simpson Rule](./maths/simpson_rule.py) +- [Basic Maths](./maths/basic_maths.py) +- [3n+1](./maths/3n+1.py) +- [Binary Exponentiation](./maths/Binary_Exponentiation.py) + +## Digital Image Processing + +- ## Filters + + - [Median Filter](./digital_image_processing/filters/median_filter.py) + - [Gaussian Filter](./digital_image_processing/filters/gaussian_filter.py) + + +## Compression + +- [Peak Signal To Noise Ratio](./compression/peak_signal_to_noise_ratio.py) +- [Huffman](./compression/huffman.py) + +## Graphs + +- [BFS Shortest Path](./graphs/bfs_shortest_path.py) +- [Directed And Undirected (Weighted) Graph](<./graphs/Directed_and_Undirected_(Weighted)_Graph.py>) +- [Minimum Spanning Tree Prims](./graphs/minimum_spanning_tree_prims.py) +- [Graph Matrix](./graphs/graph_matrix.py) +- [Basic Graphs](./graphs/basic_graphs.py) +- [Dijkstra 2](./graphs/dijkstra_2.py) +- [Tarjans Strongly Connected Components](./graphs/tarjans_scc.py) +- [Check Bipartite Graph BFS](./graphs/check_bipartite_graph_bfs.py) +- [Depth First Search](./graphs/depth_first_search.py) +- [Kahns Algorithm Long](./graphs/kahns_algorithm_long.py) +- [Breadth First Search](./graphs/breadth_first_search.py) +- [Dijkstra](./graphs/dijkstra.py) +- [Articulation Points](./graphs/articulation_points.py) +- [Bellman Ford](./graphs/bellman_ford.py) +- [Check Bipartite Graph Dfs](./graphs/check_bipartite_graph_dfs.py) +- [Strongly Connected Components Kosaraju](./graphs/scc_kosaraju.py) +- [Multi Hueristic Astar](./graphs/multi_hueristic_astar.py) +- [Page Rank](./graphs/page_rank.py) +- [Eulerian Path And Circuit For Undirected Graph](./graphs/Eulerian_path_and_circuit_for_undirected_graph.py) +- [Edmonds Karp Multiple Source And Sink](./graphs/edmonds_karp_multiple_source_and_sink.py) +- [Floyd Warshall](./graphs/floyd_warshall.py) +- [Minimum Spanning Tree Kruskal](./graphs/minimum_spanning_tree_kruskal.py) +- [Prim](./graphs/prim.py) +- [Kahns Algorithm Topo](./graphs/kahns_algorithm_topo.py) +- [BFS](./graphs/BFS.py) +- [Finding Bridges](./graphs/finding_bridges.py) +- [Graph List](./graphs/graph_list.py) +- [Dijkstra Algorithm](./graphs/dijkstra_algorithm.py) +- [A Star](./graphs/a_star.py) +- [Even Tree](./graphs/even_tree.py) +- [DFS](./graphs/DFS.py) + +## Networking Flow + +- [Minimum Cut](./networking_flow/minimum_cut.py) +- [Ford Fulkerson](./networking_flow/ford_fulkerson.py) + +## Matrix + +- [Matrix Operation](./matrix/matrix_operation.py) +- [Searching In Sorted Matrix](./matrix/searching_in_sorted_matrix.py) +- [Spiral Print](./matrix/spiral_print.py) + +## Searches + +- [Quick Select](./searches/quick_select.py) +- [Binary Search](./searches/binary_search.py) +- [Interpolation Search](./searches/interpolation_search.py) +- [Jump Search](./searches/jump_search.py) +- [Linear Search](./searches/linear_search.py) +- [Ternary Search](./searches/ternary_search.py) +- [Tabu Search](./searches/tabu_search.py) +- [Sentinel Linear Search](./searches/sentinel_linear_search.py) + +## Conversions + +- [Decimal To Binary](./conversions/decimal_to_binary.py) +- [Decimal To Octal](./conversions/decimal_to_octal.py) + +## Dynamic Programming + +- [Fractional Knapsack](./dynamic_programming/Fractional_Knapsack.py) +- [Sum Of Subset](./dynamic_programming/sum_of_subset.py) +- [Fast Fibonacci](./dynamic_programming/fast_fibonacci.py) +- [Bitmask](./dynamic_programming/bitmask.py) +- [Abbreviation](./dynamic_programming/abbreviation.py) +- [Rod Cutting](./dynamic_programming/rod_cutting.py) +- [Knapsack](./dynamic_programming/knapsack.py) +- [Max Sub Array](./dynamic_programming/max_sub_array.py) +- [Fibonacci](./dynamic_programming/fibonacci.py) +- [Minimum Partition](./dynamic_programming/minimum_partition.py) +- [K Means Clustering Tensorflow](./dynamic_programming/k_means_clustering_tensorflow.py) +- [Coin Change](./dynamic_programming/coin_change.py) +- [Subset Generation](./dynamic_programming/subset_generation.py) +- [Floyd Warshall](./dynamic_programming/floyd_warshall.py) +- [Longest Sub Array](./dynamic_programming/longest_sub_array.py) +- [Integer Partition](./dynamic_programming/integer_partition.py) +- [Matrix Chain Order](./dynamic_programming/matrix_chain_order.py) +- [Edit Distance](./dynamic_programming/edit_distance.py) +- [Longest Common Subsequence](./dynamic_programming/longest_common_subsequence.py) +- [Longest Increasing Subsequence O(nlogn)](<./dynamic_programming/longest_increasing_subsequence_O(nlogn).py>) +- [Longest Increasing Subsequence](./dynamic_programming/longest_increasing_subsequence.py) + +## Divide And Conquer + +- [Max Subarray Sum](./divide_and_conquer/max_subarray_sum.py) +- [Closest Pair Of Points](./divide_and_conquer/closest_pair_of_points.py) + +## Strings + +- [Knuth Morris Pratt](./strings/knuth_morris_pratt.py) +- [Rabin Karp](./strings/rabin_karp.py) +- [Naive String Search](./strings/naive_String_Search.py) +- [Levenshtein Distance](./strings/levenshtein_distance.py) +- [Min Cost String Conversion](./strings/min_cost_string_conversion.py) +- [Boyer Moore Search](./strings/Boyer_Moore_Search.py) +- [Manacher](./strings/manacher.py) + +## Sorts + +- [Quick Sort](./sorts/quick_sort.py) +- [Selection Sort](./sorts/selection_sort.py) +- [Bitonic Sort](./sorts/Bitonic_Sort.py) +- [Cycle Sort](./sorts/cycle_sort.py) +- [Comb Sort](./sorts/comb_sort.py) +- [Topological Sort](./sorts/topological_sort.py) +- [Merge Sort Fastest](./sorts/merge_sort_fastest.py) +- [Random Pivot Quick Sort](./sorts/random_pivot_quick_sort.py) +- [Heap Sort](./sorts/heap_sort.py) +- [Insertion Sort](./sorts/insertion_sort.py) +- [Counting Sort](./sorts/counting_sort.py) +- [Bucket Sort](./sorts/bucket_sort.py) +- [Quick Sort 3 Partition](./sorts/quick_sort_3_partition.py) +- [Bogo Sort](./sorts/bogo_sort.py) +- [Shell Sort](./sorts/shell_sort.py) +- [Pigeon Sort](./sorts/pigeon_sort.py) +- [Odd-Even Transposition Parallel](./sorts/Odd-Even_transposition_parallel.py) +- [Tree Sort](./sorts/tree_sort.py) +- [Cocktail Shaker Sort](./sorts/cocktail_shaker_sort.py) +- [Random Normal Distribution Quicksort](./sorts/random_normal_distribution_quicksort.py) +- [Wiggle Sort](./sorts/wiggle_sort.py) +- [Pancake Sort](./sorts/pancake_sort.py) +- [External Sort](./sorts/external_sort.py) +- [Tim Sort](./sorts/tim_sort.py) +- [Sorting Graphs.png](./sorts/sorting_graphs.png) +- [Radix Sort](./sorts/radix_sort.py) +- [Odd-Even Transposition Single-threaded](./sorts/Odd-Even_transposition_single-threaded.py) +- [Bubble Sort](./sorts/bubble_sort.py) +- [Gnome Sort](./sorts/gnome_sort.py) +- [Merge Sort](./sorts/merge_sort.py) + +## Machine Learning + +- [Perceptron](./machine_learning/perceptron.py) +- [Random Forest Classifier](./machine_learning/random_forest_classification/random_forest_classifier.ipynb) +- [NaiveBayes.ipynb](./machine_learning/NaiveBayes.ipynb) +- [Scoring Functions](./machine_learning/scoring_functions.py) +- [Logistic Regression](./machine_learning/logistic_regression.py) +- [Gradient Descent](./machine_learning/gradient_descent.py) +- [Linear Regression](./machine_learning/linear_regression.py) +- [Random Forest Regression](./machine_learning/random_forest_regression/random_forest_regression.py) +- [Random Forest Regression](./machine_learning/random_forest_regression/random_forest_regression.ipynb) +- [Reuters One Vs Rest Classifier.ipynb](./machine_learning/reuters_one_vs_rest_classifier.ipynb) +- [Decision Tree](./machine_learning/decision_tree.py) +- [Knn Sklearn](./machine_learning/knn_sklearn.py) +- [K Means Clust](./machine_learning/k_means_clust.py) + +## Neural Network + +- [Perceptron](./neural_network/perceptron.py) +- [Fully Connected Neural Network](./neural_network/fully_connected_neural_network.ipynb) +- [Convolution Neural Network](./neural_network/convolution_neural_network.py) +- [Back Propagation Neural Network](./neural_network/back_propagation_neural_network.py) + +## Data Structures + +- ## Binary Tree + + - [Basic Binary Tree](./data_structures/binary_tree/basic_binary_tree.py) + - [Red Black Tree](./data_structures/binary_tree/red_black_tree.py) + - [Fenwick Tree](./data_structures/binary_tree/fenwick_tree.py) + - [Treap](./data_structures/binary_tree/treap.py) + - [AVL Tree](./data_structures/binary_tree/AVL_tree.py) + - [Segment Tree](./data_structures/binary_tree/segment_tree.py) + - [Lazy Segment Tree](./data_structures/binary_tree/lazy_segment_tree.py) + - [Binary Search Tree](./data_structures/binary_tree/binary_search_tree.py) + +- ## Trie + + - [Trie](./data_structures/trie/trie.py) + +- ## Linked List + + - [Swap Nodes](./data_structures/linked_list/swap_nodes.py) + - [Doubly Linked List](./data_structures/linked_list/doubly_linked_list.py) + - [Singly Linked List](./data_structures/linked_list/singly_linked_list.py) + - [Is Palindrome](./data_structures/linked_list/is_Palindrome.py) + +- ## Stacks + + - [Postfix Evaluation](./data_structures/stacks/postfix_evaluation.py) + - [Balanced Parentheses](./data_structures/stacks/balanced_parentheses.py) + - [Infix To Prefix Conversion](./data_structures/stacks/infix_to_prefix_conversion.py) + - [Stack](./data_structures/stacks/stack.py) + - [Infix To Postfix Conversion](./data_structures/stacks/infix_to_postfix_conversion.py) + - [Next Greater Element](./data_structures/stacks/next_greater_element.py) + - [Stock Span Problem](./data_structures/stacks/stock_span_problem.py) + +- ## Queue + + - [Queue On Pseudo Stack](./data_structures/queue/queue_on_pseudo_stack.py) + - [Double Ended Queue](./data_structures/queue/double_ended_queue.py) + - [Queue On List](./data_structures/queue/queue_on_list.py) + +- ## Heap + + - [Heap](./data_structures/heap/heap.py) + +- ## Hashing + + - [Hash Table With Linked List](./data_structures/hashing/hash_table_with_linked_list.py) + - [Quadratic Probing](./data_structures/hashing/quadratic_probing.py) + - [Hash Table](./data_structures/hashing/hash_table.py) + - [Double Hash](./data_structures/hashing/double_hash.py) + + +## Other + +- [Detecting English Programmatically](./other/detecting_english_programmatically.py) +- [Fischer Yates Shuffle](./other/fischer_yates_shuffle.py) +- [Primelib](./other/primelib.py) +- [Binary Exponentiation 2](./other/binary_exponentiation_2.py) +- [Anagrams](./other/anagrams.py) +- [Palindrome](./other/palindrome.py) +- [Finding Primes](./other/finding_Primes.py) +- [Two Sum](./other/two_sum.py) +- [Password Generator](./other/password_generator.py) +- [Linear Congruential Generator](./other/linear_congruential_generator.py) +- [Frequency Finder](./other/frequency_finder.py) +- [Euclidean Gcd](./other/euclidean_gcd.py) +- [Word Patterns](./other/word_patterns.py) +- [Nested Brackets](./other/nested_brackets.py) +- [Binary Exponentiation](./other/binary_exponentiation.py) +- [Sierpinski Triangle](./other/sierpinski_triangle.py) +- [Game Of Life](./other/game_of_life.py) +- [Tower Of Hanoi](./other/tower_of_hanoi.py) diff --git a/backtracking/all_permutations.py b/backtracking/all_permutations.py new file mode 100644 index 000000000000..299b708fef4e --- /dev/null +++ b/backtracking/all_permutations.py @@ -0,0 +1,45 @@ +''' + In this problem, we want to determine all possible permutations + of the given sequence. We use backtracking to solve this problem. + + Time complexity: O(n! * n), + where n denotes the length of the given sequence. +''' + + +def generate_all_permutations(sequence): + create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))]) + + +def create_state_space_tree(sequence, current_sequence, index, index_used): + ''' + Creates a state space tree to iterate through each branch using DFS. + We know that each state has exactly len(sequence) - index children. + It terminates when it reaches the end of the given sequence. + ''' + + if index == len(sequence): + print(current_sequence) + return + + for i in range(len(sequence)): + if not index_used[i]: + current_sequence.append(sequence[i]) + index_used[i] = True + create_state_space_tree(sequence, current_sequence, index + 1, index_used) + current_sequence.pop() + index_used[i] = False + + +''' +remove the comment to take an input from the user + +print("Enter the elements") +sequence = list(map(int, input().split())) +''' + +sequence = [3, 1, 2, 4] +generate_all_permutations(sequence) + +sequence = ["A", "B", "C"] +generate_all_permutations(sequence) diff --git a/backtracking/all_subsequences.py b/backtracking/all_subsequences.py new file mode 100644 index 000000000000..d868377234a8 --- /dev/null +++ b/backtracking/all_subsequences.py @@ -0,0 +1,42 @@ +''' + In this problem, we want to determine all possible subsequences + of the given sequence. We use backtracking to solve this problem. + + Time complexity: O(2^n), + where n denotes the length of the given sequence. +''' + + +def generate_all_subsequences(sequence): + create_state_space_tree(sequence, [], 0) + + +def create_state_space_tree(sequence, current_subsequence, index): + ''' + Creates a state space tree to iterate through each branch using DFS. + We know that each state has exactly two children. + It terminates when it reaches the end of the given sequence. + ''' + + if index == len(sequence): + print(current_subsequence) + return + + create_state_space_tree(sequence, current_subsequence, index + 1) + current_subsequence.append(sequence[index]) + create_state_space_tree(sequence, current_subsequence, index + 1) + current_subsequence.pop() + + +''' +remove the comment to take an input from the user + +print("Enter the elements") +sequence = list(map(int, input().split())) +''' + +sequence = [3, 1, 2, 4] +generate_all_subsequences(sequence) + +sequence = ["A", "B", "C"] +generate_all_subsequences(sequence) diff --git a/backtracking/minimax.py b/backtracking/minimax.py new file mode 100644 index 000000000000..5168306e71fc --- /dev/null +++ b/backtracking/minimax.py @@ -0,0 +1,28 @@ +import math + +''' Minimax helps to achieve maximum score in a game by checking all possible moves + depth is current depth in game tree. + nodeIndex is index of current node in scores[]. + if move is of maximizer return true else false + leaves of game tree is stored in scores[] + height is maximum height of Game tree +''' + +def minimax (Depth, nodeIndex, isMax, scores, height): + + if Depth == height: + return scores[nodeIndex] + + if isMax: + return (max(minimax(Depth + 1, nodeIndex * 2, False, scores, height), + minimax(Depth + 1, nodeIndex * 2 + 1, False, scores, height))) + return (min(minimax(Depth + 1, nodeIndex * 2, True, scores, height), + minimax(Depth + 1, nodeIndex * 2 + 1, True, scores, height))) + +if __name__ == "__main__": + + scores = [90, 23, 6, 33, 21, 65, 123, 34423] + height = math.log(len(scores), 2) + + print("Optimal value : ", end = "") + print(minimax(0, 0, True, scores, height)) diff --git a/backtracking/n_queens.py b/backtracking/n_queens.py new file mode 100644 index 000000000000..dfd4498b166b --- /dev/null +++ b/backtracking/n_queens.py @@ -0,0 +1,84 @@ +''' + + The nqueens problem is of placing N queens on a N * N + chess board such that no queen can attack any other queens placed + on that chess board. + This means that one queen cannot have any other queen on its horizontal, vertical and + diagonal lines. + +''' +solution = [] + +def isSafe(board, row, column): + ''' + This function returns a boolean value True if it is safe to place a queen there considering + the current state of the board. + + Parameters : + board(2D matrix) : board + row ,column : coordinates of the cell on a board + + Returns : + Boolean Value + + ''' + for i in range(len(board)): + if board[row][i] == 1: + return False + for i in range(len(board)): + if board[i][column] == 1: + return False + for i,j in zip(range(row,-1,-1),range(column,-1,-1)): + if board[i][j] == 1: + return False + for i,j in zip(range(row,-1,-1),range(column,len(board))): + if board[i][j] == 1: + return False + return True + +def solve(board, row): + ''' + It creates a state space tree and calls the safe function untill it receives a + False Boolean and terminates that brach and backtracks to the next + poosible solution branch. + ''' + if row >= len(board): + ''' + If the row number exceeds N we have board with a successful combination + and that combination is appended to the solution list and the board is printed. + + ''' + solution.append(board) + printboard(board) + print() + return + for i in range(len(board)): + ''' + For every row it iterates through each column to check if it is feesible to place a + queen there. + If all the combinations for that particaular branch are successfull the board is + reinitialized for the next possible combination. + ''' + if isSafe(board,row,i): + board[row][i] = 1 + solve(board,row+1) + board[row][i] = 0 + return False + +def printboard(board): + ''' + Prints the boards that have a successfull combination. + ''' + for i in range(len(board)): + for j in range(len(board)): + if board[i][j] == 1: + print("Q", end = " ") + else : + print(".", end = " ") + print() + +#n=int(input("The no. of queens")) +n = 8 +board = [[0 for i in range(n)]for j in range(n)] +solve(board, 0) +print("The total no. of solutions are :", len(solution)) diff --git a/backtracking/sum_of_subsets.py b/backtracking/sum_of_subsets.py new file mode 100644 index 000000000000..b01bffbb651d --- /dev/null +++ b/backtracking/sum_of_subsets.py @@ -0,0 +1,45 @@ +''' + The sum-of-subsetsproblem states that a set of non-negative integers, and a value M, + determine all possible subsets of the given set whose summation sum equal to given M. + + Summation of the chosen numbers must be equal to given number M and one number can + be used only once. +''' + +def generate_sum_of_subsets_soln(nums, max_sum): + result = [] + path = [] + num_index = 0 + remaining_nums_sum = sum(nums) + create_state_space_tree(nums, max_sum, num_index, path,result, remaining_nums_sum) + return result + +def create_state_space_tree(nums,max_sum,num_index,path,result, remaining_nums_sum): + ''' + Creates a state space tree to iterate through each branch using DFS. + It terminates the branching of a node when any of the two conditions + given below satisfy. + This algorithm follows depth-fist-search and backtracks when the node is not branchable. + + ''' + if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum: + return + if sum(path) == max_sum: + result.append(path) + return + for num_index in range(num_index,len(nums)): + create_state_space_tree(nums, max_sum, num_index + 1, path + [nums[num_index]], result, remaining_nums_sum - nums[num_index]) + +''' +remove the comment to take an input from the user + +print("Enter the elements") +nums = list(map(int, input().split())) +print("Enter max_sum sum") +max_sum = int(input()) + +''' +nums = [3, 34, 4, 12, 5, 2] +max_sum = 9 +result = generate_sum_of_subsets_soln(nums,max_sum) +print(*result) \ No newline at end of file diff --git a/ciphers/caesar_cipher.py b/ciphers/caesar_cipher.py index 39c069c95a7c..e22f19b4851d 100644 --- a/ciphers/caesar_cipher.py +++ b/ciphers/caesar_cipher.py @@ -1,4 +1,3 @@ -import sys def encrypt(strng, key): encrypted = '' for x in strng: diff --git a/compression_analysis/PSNR-example-base.png b/compression/image_data/PSNR-example-base.png similarity index 100% rename from compression_analysis/PSNR-example-base.png rename to compression/image_data/PSNR-example-base.png diff --git a/compression_analysis/PSNR-example-comp-10.jpg b/compression/image_data/PSNR-example-comp-10.jpg similarity index 100% rename from compression_analysis/PSNR-example-comp-10.jpg rename to compression/image_data/PSNR-example-comp-10.jpg diff --git a/compression_analysis/compressed_image.png b/compression/image_data/compressed_image.png similarity index 100% rename from compression_analysis/compressed_image.png rename to compression/image_data/compressed_image.png diff --git a/compression_analysis/example_image.jpg b/compression/image_data/example_image.jpg similarity index 100% rename from compression_analysis/example_image.jpg rename to compression/image_data/example_image.jpg diff --git a/compression_analysis/example_wikipedia_image.jpg b/compression/image_data/example_wikipedia_image.jpg similarity index 100% rename from compression_analysis/example_wikipedia_image.jpg rename to compression/image_data/example_wikipedia_image.jpg diff --git a/compression_analysis/original_image.png b/compression/image_data/original_image.png similarity index 100% rename from compression_analysis/original_image.png rename to compression/image_data/original_image.png diff --git a/compression_analysis/psnr.py b/compression/peak_signal_to_noise_ratio.py similarity index 71% rename from compression_analysis/psnr.py rename to compression/peak_signal_to_noise_ratio.py index 0f21aac07d34..b0efb1462dcc 100644 --- a/compression_analysis/psnr.py +++ b/compression/peak_signal_to_noise_ratio.py @@ -21,11 +21,11 @@ def psnr(original, contrast): def main(): dir_path = os.path.dirname(os.path.realpath(__file__)) # Loading images (original image and compressed image) - original = cv2.imread(os.path.join(dir_path, 'original_image.png')) - contrast = cv2.imread(os.path.join(dir_path, 'compressed_image.png'), 1) + original = cv2.imread(os.path.join(dir_path, 'image_data/original_image.png')) + contrast = cv2.imread(os.path.join(dir_path, 'image_data/compressed_image.png'), 1) - original2 = cv2.imread(os.path.join(dir_path, 'PSNR-example-base.png')) - contrast2 = cv2.imread(os.path.join(dir_path, 'PSNR-example-comp-10.jpg'), 1) + original2 = cv2.imread(os.path.join(dir_path, 'image_data/PSNR-example-base.png')) + contrast2 = cv2.imread(os.path.join(dir_path, 'image_data/PSNR-example-comp-10.jpg'), 1) # Value expected: 29.73dB print("-- First Test --") diff --git a/conversions/decimal_to_binary.py b/conversions/decimal_to_binary.py new file mode 100644 index 000000000000..43ceee61a388 --- /dev/null +++ b/conversions/decimal_to_binary.py @@ -0,0 +1,25 @@ +"""Convert a Decimal Number to a Binary Number.""" + + +def decimal_to_binary(num): + """Convert a Decimal Number to a Binary Number.""" + binary = [] + while num > 0: + binary.insert(0, num % 2) + num >>= 1 + return "".join(str(e) for e in binary) + + +def main(): + """Print binary equivelents of decimal numbers.""" + print("\n2 in binary is:") + print(decimal_to_binary(2)) # = 10 + print("\n7 in binary is:") + print(decimal_to_binary(7)) # = 111 + print("\n35 in binary is:") + print(decimal_to_binary(35)) # = 100011 + print("\n") + + +if __name__ == '__main__': + main() diff --git a/conversions/decimal_to_octal.py b/conversions/decimal_to_octal.py new file mode 100644 index 000000000000..187a0300e33a --- /dev/null +++ b/conversions/decimal_to_octal.py @@ -0,0 +1,38 @@ +"""Convert a Decimal Number to an Octal Number.""" + +import math + +# Modified from: +# https://github.com/TheAlgorithms/Javascript/blob/master/Conversions/DecimalToOctal.js + + +def decimal_to_octal(num): + """Convert a Decimal Number to an Octal Number.""" + octal = 0 + counter = 0 + while num > 0: + remainder = num % 8 + octal = octal + (remainder * math.pow(10, counter)) + counter += 1 + num = math.floor(num / 8) # basically /= 8 without remainder if any + # This formatting removes trailing '.0' from `octal`. + return'{0:g}'.format(float(octal)) + + +def main(): + """Print octal equivelents of decimal numbers.""" + print("\n2 in octal is:") + print(decimal_to_octal(2)) # = 2 + print("\n8 in octal is:") + print(decimal_to_octal(8)) # = 10 + print("\n65 in octal is:") + print(decimal_to_octal(65)) # = 101 + print("\n216 in octal is:") + print(decimal_to_octal(216)) # = 330 + print("\n512 in octal is:") + print(decimal_to_octal(512)) # = 1000 + print("\n") + + +if __name__ == '__main__': + main() diff --git a/data_structures/__init__.py b/data_structures/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/data_structures/arrays.py b/data_structures/arrays.py deleted file mode 100644 index feb061013556..000000000000 --- a/data_structures/arrays.py +++ /dev/null @@ -1,3 +0,0 @@ -arr = [10, 20, 30, 40] -arr[1] = 30 # set element 1 (20) of array to 30 -print(arr) diff --git a/data_structures/avl.py b/data_structures/avl.py deleted file mode 100644 index d01e8f825368..000000000000 --- a/data_structures/avl.py +++ /dev/null @@ -1,181 +0,0 @@ -""" -An AVL tree -""" -from __future__ import print_function - - -class Node: - - def __init__(self, label): - self.label = label - self._parent = None - self._left = None - self._right = None - self.height = 0 - - @property - def right(self): - return self._right - - @right.setter - def right(self, node): - if node is not None: - node._parent = self - self._right = node - - @property - def left(self): - return self._left - - @left.setter - def left(self, node): - if node is not None: - node._parent = self - self._left = node - - @property - def parent(self): - return self._parent - - @parent.setter - def parent(self, node): - if node is not None: - self._parent = node - self.height = self.parent.height + 1 - else: - self.height = 0 - - -class AVL: - - def __init__(self): - self.root = None - self.size = 0 - - def insert(self, value): - node = Node(value) - - if self.root is None: - self.root = node - self.root.height = 0 - self.size = 1 - else: - # Same as Binary Tree - dad_node = None - curr_node = self.root - - while True: - if curr_node is not None: - - dad_node = curr_node - - if node.label < curr_node.label: - curr_node = curr_node.left - else: - curr_node = curr_node.right - else: - node.height = dad_node.height - dad_node.height += 1 - if node.label < dad_node.label: - dad_node.left = node - else: - dad_node.right = node - self.rebalance(node) - self.size += 1 - break - - def rebalance(self, node): - n = node - - while n is not None: - height_right = n.height - height_left = n.height - - if n.right is not None: - height_right = n.right.height - - if n.left is not None: - height_left = n.left.height - - if abs(height_left - height_right) > 1: - if height_left > height_right: - left_child = n.left - if left_child is not None: - h_right = (left_child.right.height - if (left_child.right is not None) else 0) - h_left = (left_child.left.height - if (left_child.left is not None) else 0) - if (h_left > h_right): - self.rotate_left(n) - break - else: - self.double_rotate_right(n) - break - else: - right_child = n.right - if right_child is not None: - h_right = (right_child.right.height - if (right_child.right is not None) else 0) - h_left = (right_child.left.height - if (right_child.left is not None) else 0) - if (h_left > h_right): - self.double_rotate_left(n) - break - else: - self.rotate_right(n) - break - n = n.parent - - def rotate_left(self, node): - aux = node.parent.label - node.parent.label = node.label - node.parent.right = Node(aux) - node.parent.right.height = node.parent.height + 1 - node.parent.left = node.right - - - def rotate_right(self, node): - aux = node.parent.label - node.parent.label = node.label - node.parent.left = Node(aux) - node.parent.left.height = node.parent.height + 1 - node.parent.right = node.right - - def double_rotate_left(self, node): - self.rotate_right(node.getRight().getRight()) - self.rotate_left(node) - - def double_rotate_right(self, node): - self.rotate_left(node.getLeft().getLeft()) - self.rotate_right(node) - - def empty(self): - if self.root is None: - return True - return False - - def preShow(self, curr_node): - if curr_node is not None: - self.preShow(curr_node.left) - print(curr_node.label, end=" ") - self.preShow(curr_node.right) - - def preorder(self, curr_node): - if curr_node is not None: - self.preShow(curr_node.left) - self.preShow(curr_node.right) - print(curr_node.label, end=" ") - - def getRoot(self): - return self.root - -t = AVL() -t.insert(1) -t.insert(2) -t.insert(3) -# t.preShow(t.root) -# print("\n") -# t.insert(4) -# t.insert(5) -# t.preShow(t.root) -# t.preorden(t.root) diff --git a/data_structures/LCA.py b/data_structures/binary_tree/LCA.py similarity index 100% rename from data_structures/LCA.py rename to data_structures/binary_tree/LCA.py diff --git a/binary_tree/basic_binary_tree.py b/data_structures/binary_tree/basic_binary_tree.py similarity index 100% rename from binary_tree/basic_binary_tree.py rename to data_structures/binary_tree/basic_binary_tree.py diff --git a/data_structures/binary_tree/red_black_tree.py b/data_structures/binary_tree/red_black_tree.py new file mode 100644 index 000000000000..4ca1301dd8fe --- /dev/null +++ b/data_structures/binary_tree/red_black_tree.py @@ -0,0 +1,665 @@ +class RedBlackTree: + """ + A Red-Black tree, which is a self-balancing BST (binary search + tree). + + This tree has similar performance to AVL trees, but the balancing is + less strict, so it will perform faster for writing/deleting nodes + and slower for reading in the average case, though, because they're + both balanced binary search trees, both will get the same asymptotic + perfomance. + + To read more about them, https://en.wikipedia.org/wiki/Red–black_tree + + Unless otherwise specified, all asymptotic runtimes are specified in + terms of the size of the tree. + """ + def __init__(self, label=None, color=0, parent=None, left=None, right=None): + """Initialize a new Red-Black Tree node with the given values: + label: The value associated with this node + color: 0 if black, 1 if red + parent: The parent to this node + left: This node's left child + right: This node's right child + """ + self.label = label + self.parent = parent + self.left = left + self.right = right + self.color = color + + # Here are functions which are specific to red-black trees + + def rotate_left(self): + """Rotate the subtree rooted at this node to the left and + returns the new root to this subtree. + + Perfoming one rotation can be done in O(1). + """ + parent = self.parent + right = self.right + self.right = right.left + if self.right: + self.right.parent = self + self.parent = right + right.left = self + if parent is not None: + if parent.left is self: + parent.left = right + else: + parent.right = right + right.parent = parent + return right + + def rotate_right(self): + """Rotate the subtree rooted at this node to the right and + returns the new root to this subtree. + + Performing one rotation can be done in O(1). + """ + parent = self.parent + left = self.left + self.left = left.right + if self.left: + self.left.parent = self + self.parent = left + left.right = self + if parent is not None: + if parent.right is self: + parent.right = left + else: + parent.left = left + left.parent = parent + return left + + def insert(self, label): + """Inserts label into the subtree rooted at self, performs any + rotations necessary to maintain balance, and then returns the + new root to this subtree (likely self). + + This is guaranteed to run in O(log(n)) time. + """ + if self.label is None: + # Only possible with an empty tree + self.label = label + return self + if self.label == label: + return self + elif self.label > label: + if self.left: + self.left.insert(label) + else: + self.left = RedBlackTree(label, 1, self) + self.left._insert_repair() + else: + if self.right: + self.right.insert(label) + else: + self.right = RedBlackTree(label, 1, self) + self.right._insert_repair() + return self.parent or self + + def _insert_repair(self): + """Repair the coloring from inserting into a tree.""" + if self.parent is None: + # This node is the root, so it just needs to be black + self.color = 0 + elif color(self.parent) == 0: + # If the parent is black, then it just needs to be red + self.color = 1 + else: + uncle = self.parent.sibling + if color(uncle) == 0: + if self.is_left() and self.parent.is_right(): + self.parent.rotate_right() + self.right._insert_repair() + elif self.is_right() and self.parent.is_left(): + self.parent.rotate_left() + self.left._insert_repair() + elif self.is_left(): + self.grandparent.rotate_right() + self.parent.color = 0 + self.parent.right.color = 1 + else: + self.grandparent.rotate_left() + self.parent.color = 0 + self.parent.left.color = 1 + else: + self.parent.color = 0 + uncle.color = 0 + self.grandparent.color = 1 + self.grandparent._insert_repair() + + def remove(self, label): + """Remove label from this tree.""" + if self.label == label: + if self.left and self.right: + # It's easier to balance a node with at most one child, + # so we replace this node with the greatest one less than + # it and remove that. + value = self.left.get_max() + self.label = value + self.left.remove(value) + else: + # This node has at most one non-None child, so we don't + # need to replace + child = self.left or self.right + if self.color == 1: + # This node is red, and its child is black + # The only way this happens to a node with one child + # is if both children are None leaves. + # We can just remove this node and call it a day. + if self.is_left(): + self.parent.left = None + else: + self.parent.right = None + else: + # The node is black + if child is None: + # This node and its child are black + if self.parent is None: + # The tree is now empty + return RedBlackTree(None) + else: + self._remove_repair() + if self.is_left(): + self.parent.left = None + else: + self.parent.right = None + self.parent = None + else: + # This node is black and its child is red + # Move the child node here and make it black + self.label = child.label + self.left = child.left + self.right = child.right + if self.left: + self.left.parent = self + if self.right: + self.right.parent = self + elif self.label > label: + if self.left: + self.left.remove(label) + else: + if self.right: + self.right.remove(label) + return self.parent or self + + def _remove_repair(self): + """Repair the coloring of the tree that may have been messed up.""" + if color(self.sibling) == 1: + self.sibling.color = 0 + self.parent.color = 1 + if self.is_left(): + self.parent.rotate_left() + else: + self.parent.rotate_right() + if color(self.parent) == 0 and color(self.sibling) == 0 \ + and color(self.sibling.left) == 0 \ + and color(self.sibling.right) == 0: + self.sibling.color = 1 + self.parent._remove_repair() + return + if color(self.parent) == 1 and color(self.sibling) == 0 \ + and color(self.sibling.left) == 0 \ + and color(self.sibling.right) == 0: + self.sibling.color = 1 + self.parent.color = 0 + return + if (self.is_left() + and color(self.sibling) == 0 + and color(self.sibling.right) == 0 + and color(self.sibling.left) == 1): + self.sibling.rotate_right() + self.sibling.color = 0 + self.sibling.right.color = 1 + if (self.is_right() + and color(self.sibling) == 0 + and color(self.sibling.right) == 1 + and color(self.sibling.left) == 0): + self.sibling.rotate_left() + self.sibling.color = 0 + self.sibling.left.color = 1 + if (self.is_left() + and color(self.sibling) == 0 + and color(self.sibling.right) == 1): + self.parent.rotate_left() + self.grandparent.color = self.parent.color + self.parent.color = 0 + self.parent.sibling.color = 0 + if (self.is_right() + and color(self.sibling) == 0 + and color(self.sibling.left) == 1): + self.parent.rotate_right() + self.grandparent.color = self.parent.color + self.parent.color = 0 + self.parent.sibling.color = 0 + + def check_color_properties(self): + """Check the coloring of the tree, and return True iff the tree + is colored in a way which matches these five properties: + (wording stolen from wikipedia article) + 1. Each node is either red or black. + 2. The root node is black. + 3. All leaves are black. + 4. If a node is red, then both its children are black. + 5. Every path from any node to all of its descendent NIL nodes + has the same number of black nodes. + + This function runs in O(n) time, because properties 4 and 5 take + that long to check. + """ + # I assume property 1 to hold because there is nothing that can + # make the color be anything other than 0 or 1. + + # Property 2 + if self.color: + # The root was red + print('Property 2') + return False; + + # Property 3 does not need to be checked, because None is assumed + # to be black and is all the leaves. + + # Property 4 + if not self.check_coloring(): + print('Property 4') + return False + + # Property 5 + if self.black_height() is None: + print('Property 5') + return False + # All properties were met + return True + + def check_coloring(self): + """A helper function to recursively check Property 4 of a + Red-Black Tree. See check_color_properties for more info. + """ + if self.color == 1: + if color(self.left) == 1 or color(self.right) == 1: + return False + if self.left and not self.left.check_coloring(): + return False + if self.right and not self.right.check_coloring(): + return False + return True + + def black_height(self): + """Returns the number of black nodes from this node to the + leaves of the tree, or None if there isn't one such value (the + tree is color incorrectly). + """ + if self is None: + # If we're already at a leaf, there is no path + return 1 + left = RedBlackTree.black_height(self.left) + right = RedBlackTree.black_height(self.right) + if left is None or right is None: + # There are issues with coloring below children nodes + return None + if left != right: + # The two children have unequal depths + return None + # Return the black depth of children, plus one if this node is + # black + return left + (1-self.color) + + # Here are functions which are general to all binary search trees + + def __contains__(self, label): + """Search through the tree for label, returning True iff it is + found somewhere in the tree. + + Guaranteed to run in O(log(n)) time. + """ + return self.search(label) is not None + + def search(self, label): + """Search through the tree for label, returning its node if + it's found, and None otherwise. + + This method is guaranteed to run in O(log(n)) time. + """ + if self.label == label: + return self + elif label > self.label: + if self.right is None: + return None + else: + return self.right.search(label) + else: + if self.left is None: + return None + else: + return self.left.search(label) + + def floor(self, label): + """Returns the largest element in this tree which is at most label. + + This method is guaranteed to run in O(log(n)) time.""" + if self.label == label: + return self.label + elif self.label > label: + if self.left: + return self.left.floor(label) + else: + return None + else: + if self.right: + attempt = self.right.floor(label) + if attempt is not None: + return attempt + return self.label + + def ceil(self, label): + """Returns the smallest element in this tree which is at least label. + + This method is guaranteed to run in O(log(n)) time. + """ + if self.label == label: + return self.label + elif self.label < label: + if self.right: + return self.right.ceil(label) + else: + return None + else: + if self.left: + attempt = self.left.ceil(label) + if attempt is not None: + return attempt + return self.label + + def get_max(self): + """Returns the largest element in this tree. + + This method is guaranteed to run in O(log(n)) time. + """ + if self.right: + # Go as far right as possible + return self.right.get_max() + else: + return self.label + + def get_min(self): + """Returns the smallest element in this tree. + + This method is guaranteed to run in O(log(n)) time. + """ + if self.left: + # Go as far left as possible + return self.left.get_min() + else: + return self.label + + @property + def grandparent(self): + """Get the current node's grandparent, or None if it doesn't exist.""" + if self.parent is None: + return None + else: + return self.parent.parent + + @property + def sibling(self): + """Get the current node's sibling, or None if it doesn't exist.""" + if self.parent is None: + return None + elif self.parent.left is self: + return self.parent.right + else: + return self.parent.left + + def is_left(self): + """Returns true iff this node is the left child of its parent.""" + return self.parent and self.parent.left is self + + def is_right(self): + """Returns true iff this node is the right child of its parent.""" + return self.parent and self.parent.right is self + + def __bool__(self): + return True + + def __len__(self): + """ + Return the number of nodes in this tree. + """ + ln = 1 + if self.left: + ln += len(self.left) + if self.right: + ln += len(self.right) + return ln + + def preorder_traverse(self): + yield self.label + if self.left: + yield from self.left.preorder_traverse() + if self.right: + yield from self.right.preorder_traverse() + + def inorder_traverse(self): + if self.left: + yield from self.left.inorder_traverse() + yield self.label + if self.right: + yield from self.right.inorder_traverse() + + + def postorder_traverse(self): + if self.left: + yield from self.left.postorder_traverse() + if self.right: + yield from self.right.postorder_traverse() + yield self.label + + def __repr__(self): + from pprint import pformat + if self.left is None and self.right is None: + return "'%s %s'" % (self.label, (self.color and 'red') or 'blk') + return pformat({'%s %s' % (self.label, (self.color and 'red') or 'blk'): + (self.left, self.right)}, + indent=1) + + def __eq__(self, other): + """Test if two trees are equal.""" + if self.label == other.label: + return self.left == other.left and self.right == other.right + else: + return False + +def color(node): + """Returns the color of a node, allowing for None leaves.""" + if node is None: + return 0 + else: + return node.color + +""" +Code for testing the various functions of the red-black tree. +""" + +def test_rotations(): + """Test that the rotate_left and rotate_right functions work.""" + # Make a tree to test on + tree = RedBlackTree(0) + tree.left = RedBlackTree(-10, parent=tree) + tree.right = RedBlackTree(10, parent=tree) + tree.left.left = RedBlackTree(-20, parent=tree.left) + tree.left.right = RedBlackTree(-5, parent=tree.left) + tree.right.left = RedBlackTree(5, parent=tree.right) + tree.right.right = RedBlackTree(20, parent=tree.right) + # Make the right rotation + left_rot = RedBlackTree(10) + left_rot.left = RedBlackTree(0, parent=left_rot) + left_rot.left.left = RedBlackTree(-10, parent=left_rot.left) + left_rot.left.right = RedBlackTree(5, parent=left_rot.left) + left_rot.left.left.left = RedBlackTree(-20, parent=left_rot.left.left) + left_rot.left.left.right = RedBlackTree(-5, parent=left_rot.left.left) + left_rot.right = RedBlackTree(20, parent=left_rot) + tree = tree.rotate_left() + if tree != left_rot: + return False + tree = tree.rotate_right() + tree = tree.rotate_right() + # Make the left rotation + right_rot = RedBlackTree(-10) + right_rot.left = RedBlackTree(-20, parent=right_rot) + right_rot.right = RedBlackTree(0, parent=right_rot) + right_rot.right.left = RedBlackTree(-5, parent=right_rot.right) + right_rot.right.right = RedBlackTree(10, parent=right_rot.right) + right_rot.right.right.left = RedBlackTree(5, parent=right_rot.right.right) + right_rot.right.right.right = RedBlackTree(20, parent=right_rot.right.right) + if tree != right_rot: + return False + return True + +def test_insertion_speed(): + """Test that the tree balances inserts to O(log(n)) by doing a lot + of them. + """ + tree = RedBlackTree(-1) + for i in range(300000): + tree = tree.insert(i) + return True + +def test_insert(): + """Test the insert() method of the tree correctly balances, colors, + and inserts. + """ + tree = RedBlackTree(0) + tree.insert(8) + tree.insert(-8) + tree.insert(4) + tree.insert(12) + tree.insert(10) + tree.insert(11) + ans = RedBlackTree(0, 0) + ans.left = RedBlackTree(-8, 0, ans) + ans.right = RedBlackTree(8, 1, ans) + ans.right.left = RedBlackTree(4, 0, ans.right) + ans.right.right = RedBlackTree(11, 0, ans.right) + ans.right.right.left = RedBlackTree(10, 1, ans.right.right) + ans.right.right.right = RedBlackTree(12, 1, ans.right.right) + return tree == ans + +def test_insert_and_search(): + """Tests searching through the tree for values.""" + tree = RedBlackTree(0) + tree.insert(8) + tree.insert(-8) + tree.insert(4) + tree.insert(12) + tree.insert(10) + tree.insert(11) + if 5 in tree or -6 in tree or -10 in tree or 13 in tree: + # Found something not in there + return False + if not (11 in tree and 12 in tree and -8 in tree and 0 in tree): + # Didn't find something in there + return False + return True + +def test_insert_delete(): + """Test the insert() and delete() method of the tree, verifying the + insertion and removal of elements, and the balancing of the tree. + """ + tree = RedBlackTree(0) + tree = tree.insert(-12) + tree = tree.insert(8) + tree = tree.insert(-8) + tree = tree.insert(15) + tree = tree.insert(4) + tree = tree.insert(12) + tree = tree.insert(10) + tree = tree.insert(9) + tree = tree.insert(11) + tree = tree.remove(15) + tree = tree.remove(-12) + tree = tree.remove(9) + if not tree.check_color_properties(): + return False + if list(tree.inorder_traverse()) != [-8, 0, 4, 8, 10, 11, 12]: + return False + return True + +def test_floor_ceil(): + """Tests the floor and ceiling functions in the tree.""" + tree = RedBlackTree(0) + tree.insert(-16) + tree.insert(16) + tree.insert(8) + tree.insert(24) + tree.insert(20) + tree.insert(22) + tuples = [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)] + for val, floor, ceil in tuples: + if tree.floor(val) != floor or tree.ceil(val) != ceil: + return False + return True + +def test_min_max(): + """Tests the min and max functions in the tree.""" + tree = RedBlackTree(0) + tree.insert(-16) + tree.insert(16) + tree.insert(8) + tree.insert(24) + tree.insert(20) + tree.insert(22) + if tree.get_max() != 22 or tree.get_min() != -16: + return False + return True + +def test_tree_traversal(): + """Tests the three different tree traversal functions.""" + tree = RedBlackTree(0) + tree.insert(-16) + tree.insert(16) + tree.insert(8) + tree.insert(24) + tree.insert(20) + tree.insert(22) + if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: + return False + if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: + return False + if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: + return False + return True + +def main(): + if test_rotations(): + print('Rotating right and left works!') + else: + print('Rotating right and left doesn\'t work. :(') + if test_insert(): + print('Inserting works!') + else: + print('Inserting doesn\'t work :(') + if test_insert_and_search(): + print('Searching works!') + else: + print('Searching doesn\'t work :(') + if test_insert_delete(): + print('Deleting works!') + else: + print('Deleting doesn\'t work :(') + if test_floor_ceil(): + print('Floor and ceil work!') + else: + print('Floor and ceil don\'t work :(') + if test_tree_traversal(): + print('Tree traversal works!') + else: + print('Tree traversal doesn\'t work :(') + print('Testing tree balancing...') + print('This should only be a few seconds.') + test_insertion_speed() + print('Done!') + +if __name__ == '__main__': + main() diff --git a/data_structures/hashing/__init__.py b/data_structures/hashing/__init__.py deleted file mode 100644 index b96ddd478458..000000000000 --- a/data_structures/hashing/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -from .hash_table import HashTable - -class QuadraticProbing(HashTable): - - def __init__(self): - super(self.__class__, self).__init__() diff --git a/data_structures/hashing/number_theory/__init__.py b/data_structures/hashing/number_theory/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/data_structures/linked_list/swapNodes.py b/data_structures/linked_list/swap_nodes.py similarity index 100% rename from data_structures/linked_list/swapNodes.py rename to data_structures/linked_list/swap_nodes.py diff --git a/data_structures/queue/__init__.py b/data_structures/queue/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/data_structures/stacks/next.py b/data_structures/stacks/next_greater_element.py similarity index 100% rename from data_structures/stacks/next.py rename to data_structures/stacks/next_greater_element.py diff --git a/data_structures/union_find/__init__.py b/data_structures/union_find/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/data_structures/union_find/tests_union_find.py b/data_structures/union_find/tests_union_find.py deleted file mode 100644 index b0708778ddbd..000000000000 --- a/data_structures/union_find/tests_union_find.py +++ /dev/null @@ -1,78 +0,0 @@ -from __future__ import absolute_import -from .union_find import UnionFind -import unittest - - -class TestUnionFind(unittest.TestCase): - def test_init_with_valid_size(self): - uf = UnionFind(5) - self.assertEqual(uf.size, 5) - - def test_init_with_invalid_size(self): - with self.assertRaises(ValueError): - uf = UnionFind(0) - - with self.assertRaises(ValueError): - uf = UnionFind(-5) - - def test_union_with_valid_values(self): - uf = UnionFind(10) - - for i in range(11): - for j in range(11): - uf.union(i, j) - - def test_union_with_invalid_values(self): - uf = UnionFind(10) - - with self.assertRaises(ValueError): - uf.union(-1, 1) - - with self.assertRaises(ValueError): - uf.union(11, 1) - - def test_same_set_with_valid_values(self): - uf = UnionFind(10) - - for i in range(11): - for j in range(11): - if i == j: - self.assertTrue(uf.same_set(i, j)) - else: - self.assertFalse(uf.same_set(i, j)) - - uf.union(1, 2) - self.assertTrue(uf.same_set(1, 2)) - - uf.union(3, 4) - self.assertTrue(uf.same_set(3, 4)) - - self.assertFalse(uf.same_set(1, 3)) - self.assertFalse(uf.same_set(1, 4)) - self.assertFalse(uf.same_set(2, 3)) - self.assertFalse(uf.same_set(2, 4)) - - uf.union(1, 3) - self.assertTrue(uf.same_set(1, 3)) - self.assertTrue(uf.same_set(1, 4)) - self.assertTrue(uf.same_set(2, 3)) - self.assertTrue(uf.same_set(2, 4)) - - uf.union(4, 10) - self.assertTrue(uf.same_set(1, 10)) - self.assertTrue(uf.same_set(2, 10)) - self.assertTrue(uf.same_set(3, 10)) - self.assertTrue(uf.same_set(4, 10)) - - def test_same_set_with_invalid_values(self): - uf = UnionFind(10) - - with self.assertRaises(ValueError): - uf.same_set(-1, 1) - - with self.assertRaises(ValueError): - uf.same_set(11, 0) - - -if __name__ == '__main__': - unittest.main() diff --git a/data_structures/union_find/union_find.py b/data_structures/union_find/union_find.py deleted file mode 100644 index 40eea67ac944..000000000000 --- a/data_structures/union_find/union_find.py +++ /dev/null @@ -1,87 +0,0 @@ -class UnionFind(): - """ - https://en.wikipedia.org/wiki/Disjoint-set_data_structure - - The union-find is a disjoint-set data structure - - You can merge two sets and tell if one set belongs to - another one. - - It's used on the Kruskal Algorithm - (https://en.wikipedia.org/wiki/Kruskal%27s_algorithm) - - The elements are in range [0, size] - """ - def __init__(self, size): - if size <= 0: - raise ValueError("size should be greater than 0") - - self.size = size - - # The below plus 1 is because we are using elements - # in range [0, size]. It makes more sense. - - # Every set begins with only itself - self.root = [i for i in range(size+1)] - - # This is used for heuristic union by rank - self.weight = [0 for i in range(size+1)] - - def union(self, u, v): - """ - Union of the sets u and v. - Complexity: log(n). - Amortized complexity: < 5 (it's very fast). - """ - - self._validate_element_range(u, "u") - self._validate_element_range(v, "v") - - if u == v: - return - - # Using union by rank will guarantee the - # log(n) complexity - rootu = self._root(u) - rootv = self._root(v) - weight_u = self.weight[rootu] - weight_v = self.weight[rootv] - if weight_u >= weight_v: - self.root[rootv] = rootu - if weight_u == weight_v: - self.weight[rootu] += 1 - else: - self.root[rootu] = rootv - - def same_set(self, u, v): - """ - Return true if the elements u and v belongs to - the same set - """ - - self._validate_element_range(u, "u") - self._validate_element_range(v, "v") - - return self._root(u) == self._root(v) - - def _root(self, u): - """ - Get the element set root. - This uses the heuristic path compression - See wikipedia article for more details. - """ - - if u != self.root[u]: - self.root[u] = self._root(self.root[u]) - - return self.root[u] - - def _validate_element_range(self, u, element_name): - """ - Raises ValueError if element is not in range - """ - if u < 0 or u > self.size: - msg = ("element {0} with value {1} " - "should be in range [0~{2}]")\ - .format(element_name, u, self.size) - raise ValueError(msg) diff --git a/digital_image_processing/filters/gaussian_filter.py b/digital_image_processing/filters/gaussian_filter.py new file mode 100644 index 000000000000..ff85ce047220 --- /dev/null +++ b/digital_image_processing/filters/gaussian_filter.py @@ -0,0 +1,53 @@ +""" +Implementation of gaussian filter algorithm +""" +from cv2 import imread, cvtColor, COLOR_BGR2GRAY, imshow, waitKey +from numpy import pi, mgrid, exp, square, zeros, ravel, dot, uint8 + + +def gen_gaussian_kernel(k_size, sigma): + center = k_size // 2 + x, y = mgrid[0-center:k_size-center, 0-center:k_size-center] + g = 1/(2*pi*sigma) * exp(-(square(x) + square(y))/(2*square(sigma))) + return g + + +def gaussian_filter(image, k_size, sigma): + height, width = image.shape[0], image.shape[1] + # dst image height and width + dst_height = height-k_size+1 + dst_width = width-k_size+1 + + # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows + image_array = zeros((dst_height*dst_width, k_size*k_size)) + row = 0 + for i in range(0, dst_height): + for j in range(0, dst_width): + window = ravel(image[i:i + k_size, j:j + k_size]) + image_array[row, :] = window + row += 1 + + # turn the kernel into shape(k*k, 1) + gaussian_kernel = gen_gaussian_kernel(k_size, sigma) + filter_array = ravel(gaussian_kernel) + + # reshape and get the dst image + dst = dot(image_array, filter_array).reshape(dst_height, dst_width).astype(uint8) + + return dst + + +if __name__ == '__main__': + # read original image + img = imread(r'../image_data/lena.jpg') + # turn image in gray scale value + gray = cvtColor(img, COLOR_BGR2GRAY) + + # get values with two different mask size + gaussian3x3 = gaussian_filter(gray, 3, sigma=1) + gaussian5x5 = gaussian_filter(gray, 5, sigma=0.8) + + # show result images + imshow('gaussian filter with 3x3 mask', gaussian3x3) + imshow('gaussian filter with 5x5 mask', gaussian5x5) + waitKey() diff --git a/digital_image_processing/filters/median_filter.py b/digital_image_processing/filters/median_filter.py index eea4295632a1..ed20b1ab7f78 100644 --- a/digital_image_processing/filters/median_filter.py +++ b/digital_image_processing/filters/median_filter.py @@ -28,7 +28,7 @@ def median_filter(gray_img, mask=3): if __name__ == '__main__': # read original image - img = imread('lena.jpg') + img = imread('../image_data/lena.jpg') # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) diff --git a/digital_image_processing/image_data/lena.jpg b/digital_image_processing/image_data/lena.jpg new file mode 100644 index 000000000000..15c4d9764eff Binary files /dev/null and b/digital_image_processing/image_data/lena.jpg differ diff --git a/divide_and_conquer/max_sub_array_sum.py b/divide_and_conquer/max_sub_array_sum.py deleted file mode 100644 index 531a45abca6f..000000000000 --- a/divide_and_conquer/max_sub_array_sum.py +++ /dev/null @@ -1,72 +0,0 @@ -""" -Given a array of length n, max_sub_array_sum() finds the maximum of sum of contiguous sub-array using divide and conquer method. - -Time complexity : O(n log n) - -Ref : INTRODUCTION TO ALGORITHMS THIRD EDITION (section : 4, sub-section : 4.1, page : 70) - -""" - - -def max_sum_from_start(array): - """ This function finds the maximum contiguous sum of array from 0 index - - Parameters : - array (list[int]) : given array - - Returns : - max_sum (int) : maximum contiguous sum of array from 0 index - - """ - array_sum = 0 - max_sum = float("-inf") - for num in array: - array_sum += num - if array_sum > max_sum: - max_sum = array_sum - return max_sum - - -def max_cross_array_sum(array, left, mid, right): - """ This function finds the maximum contiguous sum of left and right arrays - - Parameters : - array, left, mid, right (list[int], int, int, int) - - Returns : - (int) : maximum of sum of contiguous sum of left and right arrays - - """ - - max_sum_of_left = max_sum_from_start(array[left:mid+1][::-1]) - max_sum_of_right = max_sum_from_start(array[mid+1: right+1]) - return max_sum_of_left + max_sum_of_right - - -def max_sub_array_sum(array, left, right): - """ This function finds the maximum of sum of contiguous sub-array using divide and conquer method - - Parameters : - array, left, right (list[int], int, int) : given array, current left index and current right index - - Returns : - int : maximum of sum of contiguous sub-array - - """ - - # base case: array has only one element - if left == right: - return array[right] - - # Recursion - mid = (left + right) // 2 - left_half_sum = max_sub_array_sum(array, left, mid) - right_half_sum = max_sub_array_sum(array, mid + 1, right) - cross_sum = max_cross_array_sum(array, left, mid, right) - return max(left_half_sum, right_half_sum, cross_sum) - - -array = [-2, -5, 6, -2, -3, 1, 5, -6] -array_length = len(array) -print("Maximum sum of contiguous subarray:", max_sub_array_sum(array, 0, array_length - 1)) - diff --git a/hashes/enigma_machine.py b/hashes/enigma_machine.py new file mode 100644 index 000000000000..bd410c5cb21d --- /dev/null +++ b/hashes/enigma_machine.py @@ -0,0 +1,61 @@ +from __future__ import print_function + +alphabets = [chr(i) for i in range(32, 126)] +gear_one = [i for i in range(len(alphabets))] +gear_two = [i for i in range(len(alphabets))] +gear_three = [i for i in range(len(alphabets))] +reflector = [i for i in reversed(range(len(alphabets)))] +code = [] +gear_one_pos = gear_two_pos = gear_three_pos = 0 + + +def rotator(): + global gear_one_pos + global gear_two_pos + global gear_three_pos + i = gear_one[0] + gear_one.append(i) + del gear_one[0] + gear_one_pos += 1 + if gear_one_pos % int(len(alphabets)) == 0: + i = gear_two[0] + gear_two.append(i) + del gear_two[0] + gear_two_pos += 1 + if gear_two_pos % int(len(alphabets)) == 0: + i = gear_three[0] + gear_three.append(i) + del gear_three[0] + gear_three_pos += 1 + + +def engine(input_character): + target = alphabets.index(input_character) + target = gear_one[target] + target = gear_two[target] + target = gear_three[target] + target = reflector[target] + target = gear_three.index(target) + target = gear_two.index(target) + target = gear_one.index(target) + code.append(alphabets[target]) + rotator() + + +if __name__ == '__main__': + decode = input("Type your message:\n") + decode = list(decode) + while True: + try: + token = int(input("Please set token:(must be only digits)\n")) + break + except Exception as error: + print(error) + for i in range(token): + rotator() + for i in decode: + engine(i) + print("\n" + "".join(code)) + print( + f"\nYour Token is {token} please write it down.\nIf you want to decode " + f"this message again you should input same digits as token!") diff --git a/machine_learning/knn_sklearn.py b/machine_learning/knn_sklearn.py new file mode 100644 index 000000000000..64582564304f --- /dev/null +++ b/machine_learning/knn_sklearn.py @@ -0,0 +1,28 @@ +from sklearn.model_selection import train_test_split +from sklearn.datasets import load_iris +from sklearn.neighbors import KNeighborsClassifier + +#Load iris file +iris = load_iris() +iris.keys() + + +print('Target names: \n {} '.format(iris.target_names)) +print('\n Features: \n {}'.format(iris.feature_names)) + +#Train set e Test set +X_train, X_test, y_train, y_test = train_test_split(iris['data'],iris['target'], random_state=4) + +#KNN + +knn = KNeighborsClassifier (n_neighbors = 1) +knn.fit(X_train, y_train) + +#new array to test +X_new = [[1,2,1,4], + [2,3,4,5]] + +prediction = knn.predict(X_new) + +print('\nNew array: \n {}' + '\n\nTarget Names Prediction: \n {}'.format(X_new, iris['target_names'][prediction])) diff --git a/machine_learning/Random Forest Classification/Social_Network_Ads.csv b/machine_learning/random_forest_classification/Social_Network_Ads.csv similarity index 100% rename from machine_learning/Random Forest Classification/Social_Network_Ads.csv rename to machine_learning/random_forest_classification/Social_Network_Ads.csv diff --git a/machine_learning/Random Forest Classification/random_forest_classification.py b/machine_learning/random_forest_classification/random_forest_classification.py similarity index 100% rename from machine_learning/Random Forest Classification/random_forest_classification.py rename to machine_learning/random_forest_classification/random_forest_classification.py diff --git a/machine_learning/Random Forest Classification/Random Forest Classifier.ipynb b/machine_learning/random_forest_classification/random_forest_classifier.ipynb similarity index 100% rename from machine_learning/Random Forest Classification/Random Forest Classifier.ipynb rename to machine_learning/random_forest_classification/random_forest_classifier.ipynb diff --git a/machine_learning/Random Forest Regression/Position_Salaries.csv b/machine_learning/random_forest_regression/Position_Salaries.csv similarity index 100% rename from machine_learning/Random Forest Regression/Position_Salaries.csv rename to machine_learning/random_forest_regression/Position_Salaries.csv diff --git a/machine_learning/Random Forest Regression/Random Forest Regression.ipynb b/machine_learning/random_forest_regression/random_forest_regression.ipynb similarity index 100% rename from machine_learning/Random Forest Regression/Random Forest Regression.ipynb rename to machine_learning/random_forest_regression/random_forest_regression.ipynb diff --git a/machine_learning/Random Forest Regression/random_forest_regression.py b/machine_learning/random_forest_regression/random_forest_regression.py similarity index 100% rename from machine_learning/Random Forest Regression/random_forest_regression.py rename to machine_learning/random_forest_regression/random_forest_regression.py diff --git a/maths/Hanoi.py b/maths/Hanoi.py deleted file mode 100644 index c7b435a8fe3e..000000000000 --- a/maths/Hanoi.py +++ /dev/null @@ -1,29 +0,0 @@ -"""Tower of Hanoi.""" - -# @author willx75 -# Tower of Hanoi recursion game algorithm is a game, it consists of three rods -# and a number of disks of different sizes, which can slide onto any rod - -import logging - -log = logging.getLogger() -logging.basicConfig(level=logging.DEBUG) - - -def Tower_Of_Hanoi(n, source, dest, by, movement): - """Tower of Hanoi - Move plates to different rods.""" - if n == 0: - return n - elif n == 1: - movement += 1 - # no print statement - # (you could make it an optional flag for printing logs) - logging.debug('Move the plate from', source, 'to', dest) - return movement - else: - - movement = movement + Tower_Of_Hanoi(n - 1, source, by, dest, 0) - logging.debug('Move the plate from', source, 'to', dest) - - movement = movement + 1 + Tower_Of_Hanoi(n - 1, by, dest, source, 0) - return movement diff --git a/maths/average_median.py b/maths/average_median.py new file mode 100644 index 000000000000..565bb4afd112 --- /dev/null +++ b/maths/average_median.py @@ -0,0 +1,41 @@ +""" +Find median of a list of numbers. + +Read more about medians: + https://en.wikipedia.org/wiki/Median +""" + + +def median(nums): + """Find median of a list of numbers.""" + # Sort list + sorted_list = sorted(nums) + print("List of numbers:") + print(sorted_list) + + # Is number of items in list even? + if len(sorted_list) % 2 == 0: + # Find index for first middle value. + mid_index_1 = len(sorted_list) / 2 + # Find index for second middle value. + mid_index_2 = -(len(sorted_list) / 2) - 1 + # Divide middle values by 2 to get average (mean). + med = (sorted_list[mid_index_1] + sorted_list[mid_index_2]) / float(2) + return med # Return makes `else:` unnecessary. + # Number of items is odd. + mid_index = (len(sorted_list) - 1) / 2 + # Middle index is median. + med = sorted_list[mid_index] + return med + + +def main(): + """Call average module to find median of a specific list of numbers.""" + print("Odd number of numbers:") + print(median([2, 4, 6, 8, 20, 50, 70])) + print("Even number of numbers:") + print(median([2, 4, 6, 8, 20, 50])) + + +if __name__ == '__main__': + main() diff --git a/maths/lucasSeries.py b/maths/lucas series.py similarity index 100% rename from maths/lucasSeries.py rename to maths/lucas series.py diff --git a/maths/newton_raphson.py b/maths/newton_raphson.py index cc6c92734fd4..d89f264acdd8 100644 --- a/maths/newton_raphson.py +++ b/maths/newton_raphson.py @@ -29,7 +29,6 @@ def newton_raphson(f, x0=0, maxiter=100, step=0.0001, maxerror=1e-6,logsteps=Fal a = a - f(a)/f1(a) #Calculate the next estimate if logsteps: steps.append(a) - error = abs(f(a)) if error < maxerror: break else: diff --git a/maths/tests/__init__.py b/maths/tests/__init__.py deleted file mode 100644 index 2c4a6048556c..000000000000 --- a/maths/tests/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .. import fibonacci diff --git a/maths/tests/test_fibonacci.py b/maths/tests/test_fibonacci.py deleted file mode 100644 index 7d36c755e346..000000000000 --- a/maths/tests/test_fibonacci.py +++ /dev/null @@ -1,34 +0,0 @@ -""" -To run with slash: -1. run pip install slash (may need to install C++ builds from Visual Studio website) -2. In the command prompt navigate to your project folder -3. then type--> slash run -vv -k tags:fibonacci .. - -vv indicates the level of verbosity (how much stuff you want the test to spit out after running) - -k is a way to select the tests you want to run. This becomes much more important in large scale projects. -""" - -import slash -from .. import fibonacci - -default_fib = [0, 1, 1, 2, 3, 5, 8] - - -@slash.tag('fibonacci') -@slash.parametrize(('n', 'seq'), [(2, [0, 1]), (3, [0, 1, 1]), (9, [0, 1, 1, 2, 3, 5, 8, 13, 21])]) -def test_different_sequence_lengths(n, seq): - """Test output of varying fibonacci sequence lengths""" - iterative = fibonacci.fib_iterative(n) - formula = fibonacci.fib_formula(n) - assert iterative == seq - assert formula == seq - - -@slash.tag('fibonacci') -@slash.parametrize('n', [7.3, 7.8, 7.0]) -def test_float_input_iterative(n): - """Test when user enters a float value""" - iterative = fibonacci.fib_iterative(n) - formula = fibonacci.fib_formula(n) - assert iterative == default_fib - assert formula == default_fib - diff --git a/matrix/spiralPrint.py b/matrix/spiral_print.py similarity index 100% rename from matrix/spiralPrint.py rename to matrix/spiral_print.py diff --git a/neural_network/bpnn.py b/neural_network/back_propagation_neural_network.py similarity index 100% rename from neural_network/bpnn.py rename to neural_network/back_propagation_neural_network.py diff --git a/neural_network/fcn.ipynb b/neural_network/fully_connected_neural_network.ipynb similarity index 100% rename from neural_network/fcn.ipynb rename to neural_network/fully_connected_neural_network.ipynb diff --git a/other/game_of_life/game_o_life.py b/other/game_of_life.py similarity index 100% rename from other/game_of_life/game_o_life.py rename to other/game_of_life.py diff --git a/other/game_of_life/sample.gif b/other/game_of_life/sample.gif deleted file mode 100644 index 0bf2ae1f95e4..000000000000 Binary files a/other/game_of_life/sample.gif and /dev/null differ diff --git a/other/n_queens.py b/other/n_queens.py deleted file mode 100644 index 0e80a0cff5e9..000000000000 --- a/other/n_queens.py +++ /dev/null @@ -1,77 +0,0 @@ -#! /usr/bin/python3 -import sys - -def nqueens(board_width): - board = [0] - current_row = 0 - while True: - conflict = False - - for review_index in range(0, current_row): - left = board[review_index] - (current_row - review_index) - right = board[review_index] + (current_row - review_index); - if (board[current_row] == board[review_index] or (left >= 0 and left == board[current_row]) or (right < board_width and right == board[current_row])): - conflict = True; - break - - if (current_row == 0 and conflict == False): - board.append(0) - current_row = 1 - continue - - if (conflict == True): - board[current_row] += 1 - - if (current_row == 0 and board[current_row] == board_width): - print("No solution exists for specificed board size.") - return None - - while True: - if (board[current_row] == board_width): - board[current_row] = 0 - if (current_row == 0): - print("No solution exists for specificed board size.") - return None - - board.pop() - current_row -= 1 - board[current_row] += 1 - - if board[current_row] != board_width: - break - else: - current_row += 1 - if (current_row == board_width): - break - - board.append(0) - return board - -def print_board(board): - if (board == None): - return - - board_width = len(board) - for row in range(board_width): - line_print = [] - for column in range(board_width): - if column == board[row]: - line_print.append("Q") - else: - line_print.append(".") - print(line_print) - - -if __name__ == '__main__': - default_width = 8 - for arg in sys.argv: - if (arg.isdecimal() and int(arg) > 3): - default_width = int(arg) - break - - if (default_width == 8): - print("Running algorithm with board size of 8. Specify an alternative Chess board size for N-Queens as a command line argument.") - - board = nqueens(default_width) - print(board) - print_board(board) diff --git a/other/password_generator.py b/other/password_generator.py index 8916079fc758..fd0701041240 100644 --- a/other/password_generator.py +++ b/other/password_generator.py @@ -1,35 +1,53 @@ +"""Password generator allows you to generate a random password of length N.""" from __future__ import print_function -import string -import random - -letters = [letter for letter in string.ascii_letters] -digits = [digit for digit in string.digits] -symbols = [symbol for symbol in string.punctuation] -chars = letters + digits + symbols -random.shuffle(chars) - -min_length = 8 -max_length = 16 -password = ''.join(random.choice(chars) for x in range(random.randint(min_length, max_length))) -print('Password: ' + password) -print('[ If you are thinking of using this passsword, You better save it. ]') - - -# ALTERNATIVE METHODS +from random import choice +from string import ascii_letters, digits, punctuation + + +def password_generator(length=8): + """ + >>> len(password_generator()) + 8 + >>> len(password_generator(length=16)) + 16 + >>> len(password_generator(257)) + 257 + >>> len(password_generator(length=0)) + 0 + >>> len(password_generator(-1)) + 0 + """ + chars = tuple(ascii_letters) + tuple(digits) + tuple(punctuation) + return ''.join(choice(chars) for x in range(length)) + + +# ALTERNATIVE METHODS # ctbi= characters that must be in password -# i= how many letters or characters the password length will be -def password_generator(ctbi, i): - # Password generator = full boot with random_number, random_letters, and random_character FUNCTIONS - pass # Put your code here... +# i= how many letters or characters the password length will be +def alternative_password_generator(ctbi, i): + # Password generator = full boot with random_number, random_letters, and + # random_character FUNCTIONS + pass # Put your code here... def random_number(ctbi, i): - pass # Put your code here... + pass # Put your code here... def random_letters(ctbi, i): - pass # Put your code here... + pass # Put your code here... def random_characters(ctbi, i): - pass # Put your code here... + pass # Put your code here... + + +def main(): + length = int( + input('Please indicate the max length of your password: ').strip()) + print('Password generated:', password_generator(length)) + print('[If you are thinking of using this passsword, You better save it.]') + + +if __name__ == '__main__': + main() diff --git a/searches/test_interpolation_search.py b/searches/test_interpolation_search.py deleted file mode 100644 index 60bb3af22e0f..000000000000 --- a/searches/test_interpolation_search.py +++ /dev/null @@ -1,93 +0,0 @@ -import unittest -from interpolation_search import interpolation_search, interpolation_search_by_recursion - -class Test_interpolation_search(unittest.TestCase): - def setUp(self): - # un-sorted case - self.collection1 = [5,3,4,6,7] - self.item1 = 4 - # sorted case, result exists - self.collection2 = [10,30,40,45,50,66,77,93] - self.item2 = 66 - # sorted case, result doesn't exist - self.collection3 = [10,30,40,45,50,66,77,93] - self.item3 = 67 - # equal elements case, result exists - self.collection4 = [10,10,10,10,10] - self.item4 = 10 - # equal elements case, result doesn't exist - self.collection5 = [10,10,10,10,10] - self.item5 = 3 - # 1 element case, result exists - self.collection6 = [10] - self.item6 = 10 - # 1 element case, result doesn't exists - self.collection7 = [10] - self.item7 = 1 - - def tearDown(self): - pass - - def test_interpolation_search(self): - self.assertEqual(interpolation_search(self.collection1, self.item1), None) - - self.assertEqual(interpolation_search(self.collection2, self.item2), self.collection2.index(self.item2)) - - self.assertEqual(interpolation_search(self.collection3, self.item3), None) - - self.assertEqual(interpolation_search(self.collection4, self.item4), self.collection4.index(self.item4)) - - self.assertEqual(interpolation_search(self.collection5, self.item5), None) - - self.assertEqual(interpolation_search(self.collection6, self.item6), self.collection6.index(self.item6)) - - self.assertEqual(interpolation_search(self.collection7, self.item7), None) - - - -class Test_interpolation_search_by_recursion(unittest.TestCase): - def setUp(self): - # un-sorted case - self.collection1 = [5,3,4,6,7] - self.item1 = 4 - # sorted case, result exists - self.collection2 = [10,30,40,45,50,66,77,93] - self.item2 = 66 - # sorted case, result doesn't exist - self.collection3 = [10,30,40,45,50,66,77,93] - self.item3 = 67 - # equal elements case, result exists - self.collection4 = [10,10,10,10,10] - self.item4 = 10 - # equal elements case, result doesn't exist - self.collection5 = [10,10,10,10,10] - self.item5 = 3 - # 1 element case, result exists - self.collection6 = [10] - self.item6 = 10 - # 1 element case, result doesn't exists - self.collection7 = [10] - self.item7 = 1 - - def tearDown(self): - pass - - def test_interpolation_search_by_recursion(self): - self.assertEqual(interpolation_search_by_recursion(self.collection1, self.item1, 0, len(self.collection1)-1), None) - - self.assertEqual(interpolation_search_by_recursion(self.collection2, self.item2, 0, len(self.collection2)-1), self.collection2.index(self.item2)) - - self.assertEqual(interpolation_search_by_recursion(self.collection3, self.item3, 0, len(self.collection3)-1), None) - - self.assertEqual(interpolation_search_by_recursion(self.collection4, self.item4, 0, len(self.collection4)-1), self.collection4.index(self.item4)) - - self.assertEqual(interpolation_search_by_recursion(self.collection5, self.item5, 0, len(self.collection5)-1), None) - - self.assertEqual(interpolation_search_by_recursion(self.collection6, self.item6, 0, len(self.collection6)-1), self.collection6.index(self.item6)) - - self.assertEqual(interpolation_search_by_recursion(self.collection7, self.item7, 0, len(self.collection7)-1), None) - - - -if __name__ == '__main__': - unittest.main() diff --git a/searches/test_tabu_search.py b/searches/test_tabu_search.py deleted file mode 100644 index e6f73e6a9002..000000000000 --- a/searches/test_tabu_search.py +++ /dev/null @@ -1,46 +0,0 @@ -import unittest -import os -from tabu_search import generate_neighbours, generate_first_solution, find_neighborhood, tabu_search - -TEST_FILE = os.path.join(os.path.dirname(__file__), './tabu_test_data.txt') - -NEIGHBOURS_DICT = {'a': [['b', '20'], ['c', '18'], ['d', '22'], ['e', '26']], - 'c': [['a', '18'], ['b', '10'], ['d', '23'], ['e', '24']], - 'b': [['a', '20'], ['c', '10'], ['d', '11'], ['e', '12']], - 'e': [['a', '26'], ['b', '12'], ['c', '24'], ['d', '40']], - 'd': [['a', '22'], ['b', '11'], ['c', '23'], ['e', '40']]} - -FIRST_SOLUTION = ['a', 'c', 'b', 'd', 'e', 'a'] - -DISTANCE = 105 - -NEIGHBOURHOOD_OF_SOLUTIONS = [['a', 'e', 'b', 'd', 'c', 'a', 90], - ['a', 'c', 'd', 'b', 'e', 'a', 90], - ['a', 'd', 'b', 'c', 'e', 'a', 93], - ['a', 'c', 'b', 'e', 'd', 'a', 102], - ['a', 'c', 'e', 'd', 'b', 'a', 113], - ['a', 'b', 'c', 'd', 'e', 'a', 119]] - - -class TestClass(unittest.TestCase): - def test_generate_neighbours(self): - neighbours = generate_neighbours(TEST_FILE) - - self.assertEqual(NEIGHBOURS_DICT, neighbours) - - def test_generate_first_solutions(self): - first_solution, distance = generate_first_solution(TEST_FILE, NEIGHBOURS_DICT) - - self.assertEqual(FIRST_SOLUTION, first_solution) - self.assertEqual(DISTANCE, distance) - - def test_find_neighbours(self): - neighbour_of_solutions = find_neighborhood(FIRST_SOLUTION, NEIGHBOURS_DICT) - - self.assertEqual(NEIGHBOURHOOD_OF_SOLUTIONS, neighbour_of_solutions) - - def test_tabu_search(self): - best_sol, best_cost = tabu_search(FIRST_SOLUTION, DISTANCE, NEIGHBOURS_DICT, 4, 3) - - self.assertEqual(['a', 'd', 'b', 'e', 'c', 'a'], best_sol) - self.assertEqual(87, best_cost) diff --git a/simple_client/README.md b/simple_client/README.md deleted file mode 100644 index f51947f2105a..000000000000 --- a/simple_client/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# simple client server - -#### Note: -- Run **`server.py`** first. -- Now, run **`client.py`**. -- verify the output. diff --git a/simple_client/client.py b/simple_client/client.py deleted file mode 100644 index db162f43c78a..000000000000 --- a/simple_client/client.py +++ /dev/null @@ -1,29 +0,0 @@ -# client.py - -import socket - -HOST, PORT = '127.0.0.1', 1400 - -s = socket.socket( - - socket.AF_INET, # ADDRESS FAMILIES - #Name Purpose - #AF_UNIX, AF_LOCAL Local communication - #AF_INET IPv4 Internet protocols - #AF_INET6 IPv6 Internet protocols - #AF_APPLETALK Appletalk - #AF_BLUETOOTH Bluetooth - - - socket.SOCK_STREAM # SOCKET TYPES - #Name Way of Interaction - #SOCK_STREAM TCP - #SOCK_DGRAM UDP -) -s.connect((HOST, PORT)) - -s.send('Hello World'.encode('ascii'))#in UDP use sendto() -data = s.recv(1024)#in UDP use recvfrom() - -s.close()#end the connection -print(repr(data.decode('ascii'))) diff --git a/simple_client/server.py b/simple_client/server.py deleted file mode 100644 index c23075608a90..000000000000 --- a/simple_client/server.py +++ /dev/null @@ -1,21 +0,0 @@ -# server.py - -import socket - -HOST, PORT = '127.0.0.1', 1400 - -s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#refer to client.py -s.bind((HOST, PORT)) -s.listen(1)#listen for 1 connection - -conn, addr = s.accept()#start the actual data flow - -print('connected to:', addr) - -while 1: - data = conn.recv(1024).decode('ascii')#receive 1024 bytes and decode using ascii - if not data: - break - conn.send((data + ' [ addition by server ]').encode('ascii')) - -conn.close() diff --git a/sorts/Odd-Even_transposition_parallel.py b/sorts/Odd-Even_transposition_parallel.py index d7f983fc0469..9bf81a39e27a 100644 --- a/sorts/Odd-Even_transposition_parallel.py +++ b/sorts/Odd-Even_transposition_parallel.py @@ -70,13 +70,11 @@ def oeProcess(position, value, LSend, RSend, LRcv, RRcv, resultPipe): def OddEvenTransposition(arr): processArray = [] - tempRrcv = None - tempLrcv = None resultPipe = [] #initialize the list of pipes where the values will be retrieved - for a in arr: + for _ in arr: resultPipe.append(Pipe()) #creates the processes diff --git a/sorts/sorting_graphs.png b/sorts/sorting_graphs.png deleted file mode 100644 index 628245f3eb39..000000000000 Binary files a/sorts/sorting_graphs.png and /dev/null differ diff --git a/sorts/tests.py b/sorts/tests.py deleted file mode 100644 index ec8c8361912f..000000000000 --- a/sorts/tests.py +++ /dev/null @@ -1,76 +0,0 @@ -"""Test Sort Algorithms for Errors.""" - -from bogo_sort import bogo_sort -from bubble_sort import bubble_sort -from bucket_sort import bucket_sort -from cocktail_shaker_sort import cocktail_shaker_sort -from comb_sort import comb_sort -from counting_sort import counting_sort -from cycle_sort import cycle_sort -from gnome_sort import gnome_sort -from heap_sort import heap_sort -from insertion_sort import insertion_sort -from merge_sort_fastest import merge_sort as merge_sort_fastest -from merge_sort import merge_sort -from pancake_sort import pancake_sort -from quick_sort_3_partition import quick_sort_3partition -from quick_sort import quick_sort -from radix_sort import radix_sort -from random_pivot_quick_sort import quick_sort_random -from selection_sort import selection_sort -from shell_sort import shell_sort -from tim_sort import tim_sort -from topological_sort import topological_sort -from tree_sort import tree_sort -from wiggle_sort import wiggle_sort - - -TEST_CASES = [ - {'input': [8, 7, 6, 5, 4, 3, -2, -5], 'expected': [-5, -2, 3, 4, 5, 6, 7, 8]}, - {'input': [-5, -2, 3, 4, 5, 6, 7, 8], 'expected': [-5, -2, 3, 4, 5, 6, 7, 8]}, - {'input': [5, 6, 1, 4, 0, 1, -2, -5, 3, 7], 'expected': [-5, -2, 0, 1, 1, 3, 4, 5, 6, 7]}, - {'input': [2, -2], 'expected': [-2, 2]}, - {'input': [1], 'expected': [1]}, - {'input': [], 'expected': []}, -] - -''' - TODO: - - Fix some broken tests in particular cases (as [] for example), - - Unify the input format: should always be function(input_collection) (no additional args) - - Unify the output format: should always be a collection instead of - updating input elements and returning None - - Rewrite some algorithms in function format (in case there is no function definition) -''' - -TEST_FUNCTIONS = [ - bogo_sort, - bubble_sort, - bucket_sort, - cocktail_shaker_sort, - comb_sort, - counting_sort, - cycle_sort, - gnome_sort, - heap_sort, - insertion_sort, - merge_sort_fastest, - merge_sort, - pancake_sort, - quick_sort_3partition, - quick_sort, - radix_sort, - quick_sort_random, - selection_sort, - shell_sort, - tim_sort, - topological_sort, - tree_sort, - wiggle_sort, -] - - -for function in TEST_FUNCTIONS: - for case in TEST_CASES: - result = function(case['input']) - assert result == case['expected'], 'Executed function: {}, {} != {}'.format(function.__name__, result, case['expected']) diff --git a/~script.py b/~script.py index 4a2c61c83563..c44f3436fcec 100644 --- a/~script.py +++ b/~script.py @@ -52,7 +52,7 @@ def _markdown(parent, ignores, ignores_ext, depth): ignores = [".vs", ".gitignore", ".git", - "script.py", + "~script.py", "__init__.py", ] # Files with given entensions will be ignored