diff --git a/.travis.yml b/.travis.yml index 8676e5127334..e67bd431a7c1 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/CONTRIBUTING.md b/CONTRIBUTING.md index 03de387a8acd..02235ee89973 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,6 +28,13 @@ We appreciate any contribution, from fixing a grammar mistake in a comment to im We want your work to be readable by others; therefore, we encourage you to note the following: - Please write in Python 3.x. +- Please consider running [__python/black__](https://github.com/python/black) on your Python file(s) before submitting your pull request. This is not a requirement but it does make your code more readable. There are other code formatters (autopep8, yapf) but the __black__ style is now the recommendation of the Python core team. To use it, + ```bash + pip3 install black # only required the first time + black my-submission.py + ``` + +- All submissions will need to pass the test __flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics__ before they will be accepted so if possible, try this test locally on your Python file(s) before submitting your pull request. - If you know [PEP 8](https://www.python.org/dev/peps/pep-0008/) already, you will have no problem in coding style, though we do not follow it strictly. Read the remaining section and have fun coding! @@ -74,11 +81,17 @@ We want your work to be readable by others; therefore, we encourage you to note The following "testing" approaches are **not** encouraged: - ```python* + ```python input('Enter your input:') # Or even worse... input = eval(raw_input("Enter your input: ")) ``` + + However, if your code uses __input()__ then we encourage you to gracefully deal with leading and trailing whitespace in user input by adding __.strip()__ to the end as in: + + ```python + starting_value = int(input("Please enter a starting value: ").strip()) + ``` Please write down your test case, like the following: @@ -92,8 +105,10 @@ We want your work to be readable by others; therefore, we encourage you to note print("1 + 2 = ", sumab(1,2)) # 1+2 = 3 print("6 + 4 = ", sumab(6,4)) # 6+4 = 10 ``` + + Better yet, if you know how to write [__doctests__](https://docs.python.org/3/library/doctest.html), please consider adding them. -- Avoid importing external libraries for basic algorithms. Use those libraries for complicated algorithms. +- Avoid importing external libraries for basic algorithms. Only use those libraries for complicated algorithms. #### Other Standard While Submitting Your Work @@ -105,15 +120,17 @@ We want your work to be readable by others; therefore, we encourage you to note - If you have modified/added code work, make sure the code compiles before submitting. -- If you have modified/added documentation work, make sure your language is concise and contains no grammar mistake. +- If you have modified/added documentation work, ensure your language is concise and contains no grammar errors. -- 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. +- Do not update the README.md or DIRECTORY.md file which will be periodically autogenerated by our Travis CI processes. - Add a corresponding explanation to [Algorithms-Explanation](https://github.com/TheAlgorithms/Algorithms-Explanation) (Optional but recommended). +- All submissions will be tested with [__mypy__](http://www.mypy-lang.org) so we encourage to add [__Python type hints__](https://docs.python.org/3/library/typing.html) where it makes sense to do so. + - Most importantly, - - **Be consistent with this guidelines while submitting.** + - **Be consistent in the use of these guidelines when submitting.** - **Join** [Gitter](https://gitter.im/TheAlgorithms) **now!** - Happy coding! diff --git a/README.md b/README.md index a28475791432..30eccd361673 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 162614c727ee..5653f0213745 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 e22f19b4851d..872b5d8195c1 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/conversions/decimal_to_hexadecimal.py b/conversions/decimal_to_hexadecimal.py new file mode 100644 index 000000000000..f91fac063adc --- /dev/null +++ b/conversions/decimal_to_hexadecimal.py @@ -0,0 +1,43 @@ +""" Convert Base 10 (Decimal) Values to Hexadecimal Representations """ + +# set decimal value for each hexadecimal digit +values = { + 0:'0', + 1:'1', + 2:'2', + 3:'3', + 4:'4', + 5:'5', + 6:'6', + 7:'7', + 8:'8', + 9:'9', + 10:'a', + 11:'b', + 12:'c', + 13:'d', + 14:'e', + 15:'f' +} + +def decimal_to_hexadecimal(decimal): + """ take decimal value, return hexadecimal representation as str """ + hexadecimal = '' + while decimal > 0: + remainder = decimal % 16 + decimal -= remainder + hexadecimal = values[remainder] + hexadecimal + decimal /= 16 + return hexadecimal + +def main(): + """ print test cases """ + print("5 in hexadecimal is", decimal_to_hexadecimal(5)) + print("15 in hexadecimal is", decimal_to_hexadecimal(15)) + print("37 in hexadecimal is", decimal_to_hexadecimal(37)) + print("255 in hexadecimal is", decimal_to_hexadecimal(255)) + print("4096 in hexadecimal is", decimal_to_hexadecimal(4096)) + print("999098 in hexadecimal is", decimal_to_hexadecimal(999098)) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/digital_image_processing/filters/convolve.py b/digital_image_processing/filters/convolve.py new file mode 100644 index 000000000000..b7600d74c294 --- /dev/null +++ b/digital_image_processing/filters/convolve.py @@ -0,0 +1,49 @@ +# @Author : lightXu +# @File : convolve.py +# @Time : 2019/7/8 0008 下午 16:13 +from cv2 import imread, cvtColor, COLOR_BGR2GRAY, imshow, waitKey +from numpy import array, zeros, ravel, pad, dot, uint8 + + +def im2col(image, block_size): + rows, cols = image.shape + dst_height = cols - block_size[1] + 1 + dst_width = rows - block_size[0] + 1 + image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0])) + row = 0 + for i in range(0, dst_height): + for j in range(0, dst_width): + window = ravel(image[i:i + block_size[0], j:j + block_size[1]]) + image_array[row, :] = window + row += 1 + + return image_array + + +def img_convolve(image, filter_kernel): + height, width = image.shape[0], image.shape[1] + k_size = filter_kernel.shape[0] + pad_size = k_size//2 + # Pads image with the edge values of array. + image_tmp = pad(image, pad_size, mode='edge') + + # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows + image_array = im2col(image_tmp, (k_size, k_size)) + + # turn the kernel into shape(k*k, 1) + kernel_array = ravel(filter_kernel) + # reshape and get the dst image + dst = dot(image_array, kernel_array).reshape(height, width) + 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) + # Laplace operator + Laplace_kernel = array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]) + out = img_convolve(gray, Laplace_kernel).astype(uint8) + imshow('Laplacian', out) + waitKey(0) diff --git a/digital_image_processing/filters/sobel_filter.py b/digital_image_processing/filters/sobel_filter.py new file mode 100644 index 000000000000..0c797320a110 --- /dev/null +++ b/digital_image_processing/filters/sobel_filter.py @@ -0,0 +1,31 @@ +# @Author : lightXu +# @File : sobel_filter.py +# @Time : 2019/7/8 0008 下午 16:26 +import numpy as np +from cv2 import imread, cvtColor, COLOR_BGR2GRAY, imshow, waitKey +from digital_image_processing.filters.convolve import img_convolve + + +def sobel_filter(image): + kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) + kernel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]) + + dst_x = img_convolve(image, kernel_x) + dst_y = img_convolve(image, kernel_y) + dst = np.sqrt((np.square(dst_x)) + (np.square(dst_y))).astype(np.uint8) + degree = np.arctan2(dst_y, dst_x) + return dst, degree + + +if __name__ == '__main__': + # read original image + img = imread('../image_data/lena.jpg') + # turn image in gray scale value + gray = cvtColor(img, COLOR_BGR2GRAY) + + sobel, d = sobel_filter(gray) + + # show result images + imshow('sobel filter', sobel) + imshow('sobel degree', d) + waitKey(0) diff --git a/divide_and_conquer/closest_pair_of_points.py b/divide_and_conquer/closest_pair_of_points.py index cc5be428db79..ee06d27063df 100644 --- a/divide_and_conquer/closest_pair_of_points.py +++ b/divide_and_conquer/closest_pair_of_points.py @@ -1,27 +1,27 @@ """ -The algorithm finds distance btw closest pair of points in the given n points. +The algorithm finds distance between closest pair of points +in the given n points. Approach used -> Divide and conquer -The points are sorted based on Xco-ords -& by applying divide and conquer approach, +The points are sorted based on Xco-ords and +then based on Yco-ords separately. +And by applying divide and conquer approach, minimum distance is obtained recursively. ->> closest points lie on different sides of partition +>> Closest points can lie on different sides of partition. This case handled by forming a strip of points whose Xco-ords distance is less than closest_pair_dis -from mid-point's Xco-ords. +from mid-point's Xco-ords. Points sorted based on Yco-ords +are used in this step to reduce sorting time. Closest pair distance is found in the strip of points. (closest_in_strip) min(closest_pair_dis, closest_in_strip) would be the final answer. -Time complexity: O(n * (logn)^2) +Time complexity: O(n * log n) """ -import math - - def euclidean_distance_sqr(point1, point2): - return pow(point1[0] - point2[0], 2) + pow(point1[1] - point2[1], 2) + return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2 def column_based_sort(array, column = 0): @@ -66,7 +66,7 @@ def dis_between_closest_in_strip(points, points_counts, min_dis = float("inf")): return min_dis -def closest_pair_of_points_sqr(points, points_counts): +def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts): """ divide and conquer approach Parameters : @@ -79,12 +79,16 @@ def closest_pair_of_points_sqr(points, points_counts): # base case if points_counts <= 3: - return dis_between_closest_pair(points, points_counts) + return dis_between_closest_pair(points_sorted_on_x, points_counts) # recursion mid = points_counts//2 - closest_in_left = closest_pair_of_points(points[:mid], mid) - closest_in_right = closest_pair_of_points(points[mid:], points_counts - mid) + closest_in_left = closest_pair_of_points_sqr(points_sorted_on_x, + points_sorted_on_y[:mid], + mid) + closest_in_right = closest_pair_of_points_sqr(points_sorted_on_y, + points_sorted_on_y[mid:], + points_counts - mid) closest_pair_dis = min(closest_in_left, closest_in_right) """ cross_strip contains the points, whose Xcoords are at a @@ -92,22 +96,25 @@ def closest_pair_of_points_sqr(points, points_counts): """ cross_strip = [] - for point in points: - if abs(point[0] - points[mid][0]) < closest_pair_dis: + for point in points_sorted_on_x: + if abs(point[0] - points_sorted_on_x[mid][0]) < closest_pair_dis: cross_strip.append(point) - cross_strip = column_based_sort(cross_strip, 1) closest_in_strip = dis_between_closest_in_strip(cross_strip, len(cross_strip), closest_pair_dis) return min(closest_pair_dis, closest_in_strip) def closest_pair_of_points(points, points_counts): - return math.sqrt(closest_pair_of_points_sqr(points, points_counts)) + points_sorted_on_x = column_based_sort(points, column = 0) + points_sorted_on_y = column_based_sort(points, column = 1) + return (closest_pair_of_points_sqr(points_sorted_on_x, + points_sorted_on_y, + points_counts)) ** 0.5 -points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (0, 2), (5, 6), (1, 2)] -points = column_based_sort(points) -print("Distance:", closest_pair_of_points(points, len(points))) +if __name__ == "__main__": + points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] + print("Distance:", closest_pair_of_points(points, len(points))) diff --git a/other/detecting_english_programmatically.py b/other/detecting_english_programmatically.py index 005fd3c10ca3..8b73ff6cf0c3 100644 --- a/other/detecting_english_programmatically.py +++ b/other/detecting_english_programmatically.py @@ -6,7 +6,7 @@ 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 329a8ce5c43f..fc22aad96059 100644 --- a/other/sierpinski_triangle.py +++ b/other/sierpinski_triangle.py @@ -27,13 +27,6 @@ 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 dc15b2ce8e58..9cc5b9e40543 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/project_euler/problem_13/num.txt b/project_euler/problem_13/num.txt new file mode 100644 index 000000000000..43b568e812a8 --- /dev/null +++ b/project_euler/problem_13/num.txt @@ -0,0 +1,100 @@ +37107287533902102798797998220837590246510135740250 +46376937677490009712648124896970078050417018260538 +74324986199524741059474233309513058123726617309629 +91942213363574161572522430563301811072406154908250 +23067588207539346171171980310421047513778063246676 +89261670696623633820136378418383684178734361726757 +28112879812849979408065481931592621691275889832738 +44274228917432520321923589422876796487670272189318 +47451445736001306439091167216856844588711603153276 +70386486105843025439939619828917593665686757934951 +62176457141856560629502157223196586755079324193331 +64906352462741904929101432445813822663347944758178 +92575867718337217661963751590579239728245598838407 +58203565325359399008402633568948830189458628227828 +80181199384826282014278194139940567587151170094390 +35398664372827112653829987240784473053190104293586 +86515506006295864861532075273371959191420517255829 +71693888707715466499115593487603532921714970056938 +54370070576826684624621495650076471787294438377604 +53282654108756828443191190634694037855217779295145 +36123272525000296071075082563815656710885258350721 +45876576172410976447339110607218265236877223636045 +17423706905851860660448207621209813287860733969412 +81142660418086830619328460811191061556940512689692 +51934325451728388641918047049293215058642563049483 +62467221648435076201727918039944693004732956340691 +15732444386908125794514089057706229429197107928209 +55037687525678773091862540744969844508330393682126 +18336384825330154686196124348767681297534375946515 +80386287592878490201521685554828717201219257766954 +78182833757993103614740356856449095527097864797581 +16726320100436897842553539920931837441497806860984 +48403098129077791799088218795327364475675590848030 +87086987551392711854517078544161852424320693150332 +59959406895756536782107074926966537676326235447210 +69793950679652694742597709739166693763042633987085 +41052684708299085211399427365734116182760315001271 +65378607361501080857009149939512557028198746004375 +35829035317434717326932123578154982629742552737307 +94953759765105305946966067683156574377167401875275 +88902802571733229619176668713819931811048770190271 +25267680276078003013678680992525463401061632866526 +36270218540497705585629946580636237993140746255962 +24074486908231174977792365466257246923322810917141 +91430288197103288597806669760892938638285025333403 +34413065578016127815921815005561868836468420090470 +23053081172816430487623791969842487255036638784583 +11487696932154902810424020138335124462181441773470 +63783299490636259666498587618221225225512486764533 +67720186971698544312419572409913959008952310058822 +95548255300263520781532296796249481641953868218774 +76085327132285723110424803456124867697064507995236 +37774242535411291684276865538926205024910326572967 +23701913275725675285653248258265463092207058596522 +29798860272258331913126375147341994889534765745501 +18495701454879288984856827726077713721403798879715 +38298203783031473527721580348144513491373226651381 +34829543829199918180278916522431027392251122869539 +40957953066405232632538044100059654939159879593635 +29746152185502371307642255121183693803580388584903 +41698116222072977186158236678424689157993532961922 +62467957194401269043877107275048102390895523597457 +23189706772547915061505504953922979530901129967519 +86188088225875314529584099251203829009407770775672 +11306739708304724483816533873502340845647058077308 +82959174767140363198008187129011875491310547126581 +97623331044818386269515456334926366572897563400500 +42846280183517070527831839425882145521227251250327 +55121603546981200581762165212827652751691296897789 +32238195734329339946437501907836945765883352399886 +75506164965184775180738168837861091527357929701337 +62177842752192623401942399639168044983993173312731 +32924185707147349566916674687634660915035914677504 +99518671430235219628894890102423325116913619626622 +73267460800591547471830798392868535206946944540724 +76841822524674417161514036427982273348055556214818 +97142617910342598647204516893989422179826088076852 +87783646182799346313767754307809363333018982642090 +10848802521674670883215120185883543223812876952786 +71329612474782464538636993009049310363619763878039 +62184073572399794223406235393808339651327408011116 +66627891981488087797941876876144230030984490851411 +60661826293682836764744779239180335110989069790714 +85786944089552990653640447425576083659976645795096 +66024396409905389607120198219976047599490197230297 +64913982680032973156037120041377903785566085089252 +16730939319872750275468906903707539413042652315011 +94809377245048795150954100921645863754710598436791 +78639167021187492431995700641917969777599028300699 +15368713711936614952811305876380278410754449733078 +40789923115535562561142322423255033685442488917353 +44889911501440648020369068063960672322193204149535 +41503128880339536053299340368006977710650566631954 +81234880673210146739058568557934581403627822703280 +82616570773948327592232845941706525094512325230608 +22918802058777319719839450180888072429661980811197 +77158542502016545090413245809786882778948721859617 +72107838435069186155435662884062257473692284509516 +20849603980134001723930671666823555245252804609722 +53503534226472524250874054075591789781264330331690 diff --git a/project_euler/problem_13/sol2.py b/project_euler/problem_13/sol2.py new file mode 100644 index 000000000000..c1416bcd6e7d --- /dev/null +++ b/project_euler/problem_13/sol2.py @@ -0,0 +1,5 @@ +sum = 0 +with open("num.txt",'r') as f: + for line in f: + sum += int(line) +print(str(sum)[:10]) diff --git a/project_euler/problem_16/sol2.py b/project_euler/problem_16/sol2.py new file mode 100644 index 000000000000..cce3d2354bb1 --- /dev/null +++ b/project_euler/problem_16/sol2.py @@ -0,0 +1,6 @@ +from __future__ import print_function +n = 2**1000 +r = 0 +while n: + r, n = r + n % 10, n // 10 +print(r) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 000000000000..30179ac345b3 --- /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 e21ddd53cc78..ffd84f8ac031 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 bae95b4346f6..ba40a1f698ee 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 = [] - -n = int(input()) -for i in range(n): - a.append(int(input())) -up = 1 - -sort(a, n, up) -print("\n\nSorted array is") -for i in range(n): - print("%d" % a[i]) +if __name__ == "__main__": + # Driver code to test above + a = [] + + 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]) diff --git a/sorts/bubble_sort.py b/sorts/bubble_sort.py index e17fc3358d53..4e2c19b65e02 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):