diff --git a/.travis.yml b/.travis.yml index 8676e5127..e67bd431a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,14 @@ language: python dist: xenial # required for Python >= 3.7 python: 3.7 -install: pip install flake8 -script: flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics +cache: pip +install: pip install -r requirements.txt +before_script: + - black --check . || true + - flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics +script: + - mypy --ignore-missing-imports . + - pytest --doctest-modules ./ciphers ./other ./searches ./sorts ./strings +after_success: + - python ./~script.py + - cat DIRECTORY.md diff --git a/README.md b/README.md index a28475791..30eccd361 100644 --- a/README.md +++ b/README.md @@ -12,12 +12,12 @@ These implementations are for learning purposes. They may be less efficient than Anup Kumar Panwar   [[Gmail](mailto:1anuppanwar@gmail.com?Subject=The%20Algorithms%20-%20Python) -  [Gihub](https://github.com/anupkumarpanwar) +  [GitHub](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) +  [GitHub](https://github.com/dynamitechetan)   [LinkedIn](https://www.linkedin.com/in/chetankaushik/)] ## Contribution Guidelines @@ -28,337 +28,6 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. We're on [Gitter](https://gitter.im/TheAlgorithms)! Please join us. -# Algorithms +## 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) +See our [directory](DIRECTORY.md). diff --git a/ciphers/Atbash.py b/ciphers/Atbash.py index 162614c72..5653f0213 100644 --- a/ciphers/Atbash.py +++ b/ciphers/Atbash.py @@ -18,4 +18,6 @@ def Atbash(): output+=i print(output) -Atbash() + +if __name__ == '__main__': + Atbash() diff --git a/ciphers/caesar_cipher.py b/ciphers/caesar_cipher.py index e22f19b48..872b5d819 100644 --- a/ciphers/caesar_cipher.py +++ b/ciphers/caesar_cipher.py @@ -59,4 +59,7 @@ def main(): elif choice == '4': print ("Goodbye.") break -main() + + +if __name__ == '__main__': + main() diff --git a/other/detecting_english_programmatically.py b/other/detecting_english_programmatically.py index 005fd3c10..8b73ff6cf 100644 --- a/other/detecting_english_programmatically.py +++ b/other/detecting_english_programmatically.py @@ -6,7 +6,7 @@ LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + ' \t\n' def loadDictionary(): path = os.path.split(os.path.realpath(__file__)) englishWords = {} - with open(path[0] + '/Dictionary.txt') as dictionaryFile: + with open(path[0] + '/dictionary.txt') as dictionaryFile: for word in dictionaryFile.read().split('\n'): englishWords[word] = None return englishWords diff --git a/other/sierpinski_triangle.py b/other/sierpinski_triangle.py index 329a8ce5c..fc22aad96 100644 --- a/other/sierpinski_triangle.py +++ b/other/sierpinski_triangle.py @@ -27,13 +27,6 @@ Credits: This code was written by editing the code from http://www.riannetrujill import turtle import sys PROGNAME = 'Sierpinski Triangle' -if len(sys.argv) !=2: - raise Exception('right format for using this script: $python fractals.py ') - -myPen = turtle.Turtle() -myPen.ht() -myPen.speed(5) -myPen.pencolor('red') points = [[-175,-125],[0,175],[175,-125]] #size of triangle @@ -64,4 +57,12 @@ def triangle(points,depth): depth-1) -triangle(points,int(sys.argv[1])) +if __name__ == '__main__': + if len(sys.argv) !=2: + raise ValueError('right format for using this script: ' + '$python fractals.py ') + myPen = turtle.Turtle() + myPen.ht() + myPen.speed(5) + myPen.pencolor('red') + triangle(points,int(sys.argv[1])) diff --git a/other/tower_of_hanoi.py b/other/tower_of_hanoi.py index dc15b2ce8..9cc5b9e40 100644 --- a/other/tower_of_hanoi.py +++ b/other/tower_of_hanoi.py @@ -16,10 +16,10 @@ def moveTower(height, fromPole, toPole, withPole): moveTower(height-1, withPole, toPole, fromPole) def moveDisk(fp,tp): - print(('moving disk from', fp, 'to', tp)) + print('moving disk from', fp, 'to', tp) def main(): - height = int(input('Height of hanoi: ')) + height = int(input('Height of hanoi: ').strip()) moveTower(height, 'A', 'B', 'C') if __name__ == '__main__': diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 000000000..30179ac34 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +black +flake8 +matplotlib +mypy +numpy +pytest diff --git a/searches/tabu_search.py b/searches/tabu_search.py index e21ddd53c..ffd84f8ac 100644 --- a/searches/tabu_search.py +++ b/searches/tabu_search.py @@ -38,7 +38,7 @@ def generate_neighbours(path): and the cost (distance) for each neighbor. Example of dict_of_neighbours: - >>> dict_of_neighbours[a] + >>) dict_of_neighbours[a] [[b,20],[c,18],[d,22],[e,26]] This indicates the neighbors of node (city) 'a', which has neighbor the node 'b' with distance 20, @@ -130,7 +130,7 @@ def find_neighborhood(solution, dict_of_neighbours): Example: - >>> find_neighborhood(['a','c','b','d','e','a']) + >>) find_neighborhood(['a','c','b','d','e','a']) [['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',93]] diff --git a/sorts/Bitonic_Sort.py b/sorts/Bitonic_Sort.py index bae95b434..ba40a1f69 100644 --- a/sorts/Bitonic_Sort.py +++ b/sorts/Bitonic_Sort.py @@ -42,15 +42,16 @@ def sort(a, N, up): bitonicSort(a, 0, N, up) -# Driver code to test above -a = [] +if __name__ == "__main__": + # Driver code to test above + a = [] -n = int(input()) -for i in range(n): - a.append(int(input())) -up = 1 + n = int(input().strip()) + for i in range(n): + a.append(int(input().strip())) + up = 1 -sort(a, n, up) -print("\n\nSorted array is") -for i in range(n): - print("%d" % a[i]) + sort(a, n, up) + print("\n\nSorted array is") + for i in range(n): + print("%d" % a[i]) diff --git a/sorts/bubble_sort.py b/sorts/bubble_sort.py index e17fc3358..4e2c19b65 100644 --- a/sorts/bubble_sort.py +++ b/sorts/bubble_sort.py @@ -19,7 +19,7 @@ def bubble_sort(collection): [-45, -5, -2] >>> bubble_sort([-23,0,6,-4,34]) - [-23,-4,0,6,34] + [-23, -4, 0, 6, 34] """ length = len(collection) for i in range(length-1):