├── .coveragerc ├── .github ├── pull_request_template.md ├── stale.yml └── workflows │ ├── autoblack.yml │ ├── codespell.yml │ ├── directory_writer.yml │ ├── pre-commit.yml │ └── stale.yml ├── .gitignore ├── .gitpod.yml ├── .pre-commit-config.yaml ├── .travis.yml ├── CONTRIBUTING.md ├── DIRECTORY.md ├── LICENSE.md ├── README.md ├── Travis_CI_tests_are_failing.md ├── arithmetic_analysis ├── __init__.py ├── bisection.py ├── gaussian_elimination.py ├── image_data │ ├── 2D_problems.jpg │ ├── 2D_problems_1.jpg │ └── __init__.py ├── in_static_equilibrium.py ├── intersection.py ├── lu_decomposition.py ├── newton_forward_interpolation.py ├── newton_method.py ├── newton_raphson.py └── secant_method.py ├── backtracking ├── __init__.py ├── all_combinations.py ├── all_permutations.py ├── all_subsequences.py ├── coloring.py ├── hamiltonian_cycle.py ├── knight_tour.py ├── minimax.py ├── n_queens.py ├── n_queens_math.py ├── rat_in_maze.py ├── sudoku.py └── sum_of_subsets.py ├── bit_manipulation ├── README.md ├── __init__.py ├── binary_and_operator.py ├── binary_or_operator.py └── binary_xor_operator.py ├── blockchain ├── __init__.py ├── chinese_remainder_theorem.py ├── diophantine_equation.py └── modular_division.py ├── boolean_algebra ├── __init__.py └── quine_mc_cluskey.py ├── cellular_automata ├── README.md ├── __init__.py └── one_dimensional.py ├── ciphers ├── __init__.py ├── a1z26.py ├── affine_cipher.py ├── atbash.py ├── base16.py ├── base32.py ├── base64_cipher.py ├── base85.py ├── brute_force_caesar_cipher.py ├── caesar_cipher.py ├── cryptomath_module.py ├── decrypt_caesar_with_chi_squared.py ├── deterministic_miller_rabin.py ├── diffie.py ├── elgamal_key_generator.py ├── enigma_machine2.py ├── hill_cipher.py ├── mixed_keyword_cypher.py ├── morse_code_implementation.py ├── onepad_cipher.py ├── playfair_cipher.py ├── porta_cipher.py ├── prehistoric_men.txt ├── rabin_miller.py ├── rot13.py ├── rsa_cipher.py ├── rsa_factorization.py ├── rsa_key_generator.py ├── shuffled_shift_cipher.py ├── simple_keyword_cypher.py ├── simple_substitution_cipher.py ├── trafid_cipher.py ├── transposition_cipher.py ├── transposition_cipher_encrypt_decrypt_file.py ├── vigenere_cipher.py └── xor_cipher.py ├── compression ├── __init__.py ├── burrows_wheeler.py ├── huffman.py ├── image_data │ ├── PSNR-example-base.png │ ├── PSNR-example-comp-10.jpg │ ├── __init__.py │ ├── compressed_image.png │ ├── example_image.jpg │ ├── example_wikipedia_image.jpg │ └── original_image.png ├── lempel_ziv.py ├── lempel_ziv_decompress.py └── peak_signal_to_noise_ratio.py ├── computer_vision ├── README.md ├── __init__.py └── harriscorner.py ├── conversions ├── __init__.py ├── binary_to_decimal.py ├── binary_to_octal.py ├── decimal_to_any.py ├── decimal_to_binary.py ├── decimal_to_hexadecimal.py ├── decimal_to_octal.py ├── hexadecimal_to_decimal.py ├── octal_to_decimal ├── prefix_conversions.py ├── roman_to_integer.py └── temperature_conversions.py ├── data_structures ├── __init__.py ├── binary_tree │ ├── __init__.py │ ├── avl_tree.py │ ├── basic_binary_tree.py │ ├── binary_search_tree.py │ ├── binary_search_tree_recursive.py │ ├── fenwick_tree.py │ ├── lazy_segment_tree.py │ ├── lowest_common_ancestor.py │ ├── non_recursive_segment_tree.py │ ├── number_of_possible_binary_trees.py │ ├── red_black_tree.py │ ├── segment_tree.py │ ├── segment_tree_other.py │ └── treap.py ├── disjoint_set │ ├── __init__.py │ ├── alternate_disjoint_set.py │ └── disjoint_set.py ├── hashing │ ├── __init__.py │ ├── double_hash.py │ ├── hash_table.py │ ├── hash_table_with_linked_list.py │ ├── number_theory │ │ ├── __init__.py │ │ └── prime_numbers.py │ └── quadratic_probing.py ├── heap │ ├── __init__.py │ ├── binomial_heap.py │ ├── heap.py │ ├── heap_generic.py │ ├── max_heap.py │ └── min_heap.py ├── linked_list │ ├── __init__.py │ ├── circular_linked_list.py │ ├── deque_doubly.py │ ├── doubly_linked_list.py │ ├── from_sequence.py │ ├── has_loop.py │ ├── is_palindrome.py │ ├── middle_element_of_linked_list.py │ ├── print_reverse.py │ ├── singly_linked_list.py │ ├── skip_list.py │ └── swap_nodes.py ├── queue │ ├── __init__.py │ ├── circular_queue.py │ ├── double_ended_queue.py │ ├── linked_queue.py │ ├── priority_queue_using_list.py │ ├── queue_on_list.py │ └── queue_on_pseudo_stack.py ├── stacks │ ├── __init__.py │ ├── balanced_parentheses.py │ ├── dijkstras_two_stack_algorithm.py │ ├── infix_to_postfix_conversion.py │ ├── infix_to_prefix_conversion.py │ ├── linked_stack.py │ ├── next_greater_element.py │ ├── postfix_evaluation.py │ ├── prefix_evaluation.py │ ├── stack.py │ ├── stack_using_dll.py │ └── stock_span_problem.py └── trie │ ├── __init__.py │ └── trie.py ├── digital_image_processing ├── __init__.py ├── change_brightness.py ├── change_contrast.py ├── convert_to_negative.py ├── dithering │ ├── __init__.py │ └── burkes.py ├── edge_detection │ ├── __init__.py │ └── canny.py ├── filters │ ├── __init__.py │ ├── bilateral_filter.py │ ├── convolve.py │ ├── gaussian_filter.py │ ├── median_filter.py │ └── sobel_filter.py ├── histogram_equalization │ ├── __init__.py │ ├── histogram_stretch.py │ ├── image_data │ │ ├── __init__.py │ │ └── input.jpg │ └── output_data │ │ ├── __init__.py │ │ └── output.jpg ├── image_data │ ├── __init__.py │ ├── lena.jpg │ └── lena_small.jpg ├── index_calculation.py ├── resize │ ├── __init__.py │ └── resize.py ├── rotation │ ├── __init__.py │ └── rotation.py ├── sepia.py └── test_digital_image_processing.py ├── divide_and_conquer ├── __init__.py ├── closest_pair_of_points.py ├── convex_hull.py ├── heaps_algorithm.py ├── heaps_algorithm_iterative.py ├── inversions.py ├── max_subarray_sum.py ├── mergesort.py ├── power.py └── strassen_matrix_multiplication.py ├── dynamic_programming ├── __init__.py ├── abbreviation.py ├── bitmask.py ├── climbing_stairs.py ├── coin_change.py ├── edit_distance.py ├── factorial.py ├── fast_fibonacci.py ├── fibonacci.py ├── floyd_warshall.py ├── fractional_knapsack.py ├── fractional_knapsack_2.py ├── integer_partition.py ├── iterating_through_submasks.py ├── k_means_clustering_tensorflow.py_tf ├── knapsack.py ├── longest_common_subsequence.py ├── longest_increasing_subsequence.py ├── longest_increasing_subsequence_o(nlogn).py ├── longest_sub_array.py ├── matrix_chain_order.py ├── max_non_adjacent_sum.py ├── max_sub_array.py ├── max_sum_contiguous_subsequence.py ├── minimum_cost_path.py ├── minimum_partition.py ├── optimal_binary_search_tree.py ├── rod_cutting.py ├── subset_generation.py └── sum_of_subset.py ├── file_transfer ├── __init__.py ├── mytext.txt ├── receive_file.py ├── send_file.py └── tests │ ├── __init__.py │ └── test_send_file.py ├── fuzzy_logic ├── __init__.py └── fuzzy_operations.py ├── genetic_algorithm ├── __init__.py └── basic_string.py ├── geodesy ├── __init__.py ├── haversine_distance.py └── lamberts_ellipsoidal_distance.py ├── graphics ├── __init__.py ├── bezier_curve.py └── vector3_for_2d_rendering.py ├── graphs ├── __init__.py ├── a_star.py ├── articulation_points.py ├── basic_graphs.py ├── bellman_ford.py ├── bfs_shortest_path.py ├── bidirectional_a_star.py ├── bidirectional_breadth_first_search.py ├── breadth_first_search.py ├── breadth_first_search_2.py ├── breadth_first_search_shortest_path.py ├── check_bipartite_graph_bfs.py ├── check_bipartite_graph_dfs.py ├── connected_components.py ├── depth_first_search.py ├── depth_first_search_2.py ├── dijkstra.py ├── dijkstra_2.py ├── dijkstra_algorithm.py ├── dinic.py ├── directed_and_undirected_(weighted)_graph.py ├── edmonds_karp_multiple_source_and_sink.py ├── eulerian_path_and_circuit_for_undirected_graph.py ├── even_tree.py ├── finding_bridges.py ├── frequent_pattern_graph_miner.py ├── g_topological_sort.py ├── gale_shapley_bigraph.py ├── graph_list.py ├── graph_matrix.py ├── graphs_floyd_warshall.py ├── greedy_best_first.py ├── kahns_algorithm_long.py ├── kahns_algorithm_topo.py ├── karger.py ├── minimum_spanning_tree_boruvka.py ├── minimum_spanning_tree_kruskal.py ├── minimum_spanning_tree_kruskal2.py ├── minimum_spanning_tree_prims.py ├── multi_heuristic_astar.py ├── page_rank.py ├── prim.py ├── scc_kosaraju.py ├── strongly_connected_components.py └── tarjans_scc.py ├── greedy_method ├── __init__.py ├── greedy_knapsack.py └── test_knapsack.py ├── hashes ├── __init__.py ├── adler32.py ├── chaos_machine.py ├── djb2.py ├── enigma_machine.py ├── hamming_code.py ├── md5.py ├── sdbm.py └── sha1.py ├── images ├── Travis_CI_fail_1.png ├── Travis_CI_fail_2.png └── __init__.py ├── linear_algebra ├── README.md ├── __init__.py └── src │ ├── __init__.py │ ├── lib.py │ ├── polynom_for_points.py │ ├── power_iteration.py │ ├── rayleigh_quotient.py │ ├── test_linear_algebra.py │ └── transformations_2d.py ├── machine_learning ├── __init__.py ├── astar.py ├── data_transformations.py ├── decision_tree.py ├── gaussian_naive_bayes.py ├── gradient_boosting_regressor.py ├── gradient_descent.py ├── k_means_clust.py ├── k_nearest_neighbours.py ├── knn_sklearn.py ├── linear_discriminant_analysis.py ├── linear_regression.py ├── logistic_regression.py ├── lstm │ ├── __init__.py │ ├── lstm_prediction.py │ └── sample_data.csv ├── multilayer_perceptron_classifier.py ├── polymonial_regression.py ├── random_forest_classifier.py ├── random_forest_regressor.py ├── scoring_functions.py ├── sequential_minimum_optimization.py ├── support_vector_machines.py └── word_frequency_functions.py ├── maths ├── 3n_plus_1.py ├── __init__.py ├── abs.py ├── abs_max.py ├── abs_min.py ├── add.py ├── aliquot_sum.py ├── allocation_number.py ├── area.py ├── area_under_curve.py ├── armstrong_numbers.py ├── average_mean.py ├── average_median.py ├── average_mode.py ├── bailey_borwein_plouffe.py ├── basic_maths.py ├── binary_exp_mod.py ├── binary_exponentiation.py ├── binomial_coefficient.py ├── binomial_distribution.py ├── bisection.py ├── ceil.py ├── chudnovsky_algorithm.py ├── collatz_sequence.py ├── combinations.py ├── entropy.py ├── eulers_totient.py ├── explicit_euler.py ├── extended_euclidean_algorithm.py ├── factorial_iterative.py ├── factorial_python.py ├── factorial_recursive.py ├── factors.py ├── fermat_little_theorem.py ├── fibonacci.py ├── fibonacci_sequence_recursion.py ├── find_max.py ├── find_max_recursion.py ├── find_min.py ├── find_min_recursion.py ├── floor.py ├── gamma.py ├── gaussian.py ├── greatest_common_divisor.py ├── hardy_ramanujanalgo.py ├── images │ ├── __init__.py │ └── gaussian.png ├── is_square_free.py ├── jaccard_similarity.py ├── kadanes.py ├── karatsuba.py ├── krishnamurthy_number.py ├── kth_lexicographic_permutation.py ├── largest_of_very_large_numbers.py ├── least_common_multiple.py ├── line_length.py ├── lucas_lehmer_primality_test.py ├── lucas_series.py ├── matrix_exponentiation.py ├── miller_rabin.py ├── mobius_function.py ├── modular_exponential.py ├── monte_carlo.py ├── monte_carlo_dice.py ├── newton_raphson.py ├── number_of_digits.py ├── numerical_integration.py ├── perfect_cube.py ├── perfect_number.py ├── perfect_square.py ├── pi_monte_carlo_estimation.py ├── polynomial_evaluation.py ├── power_using_recursion.py ├── prime_check.py ├── prime_factors.py ├── prime_numbers.py ├── prime_sieve_eratosthenes.py ├── pythagoras.py ├── qr_decomposition.py ├── quadratic_equations_complex_numbers.py ├── radians.py ├── radix2_fft.py ├── relu.py ├── runge_kutta.py ├── segmented_sieve.py ├── series │ ├── __init__.py │ ├── geometric_series.py │ ├── harmonic_series.py │ └── p_series.py ├── sieve_of_eratosthenes.py ├── simpson_rule.py ├── softmax.py ├── square_root.py ├── sum_of_arithmetic_series.py ├── sum_of_digits.py ├── sum_of_geometric_progression.py ├── test_prime_check.py ├── trapezoidal_rule.py ├── ugly_numbers.py ├── volume.py └── zellers_congruence.py ├── matrix ├── __init__.py ├── count_islands_in_matrix.py ├── inverse_of_matrix.py ├── matrix_class.py ├── matrix_operation.py ├── nth_fibonacci_using_matrix_exponentiation.py ├── rotate_matrix.py ├── searching_in_sorted_matrix.py ├── sherman_morrison.py ├── spiral_print.py └── tests │ ├── __init__.py │ ├── pytest.ini │ └── test_matrix_operation.py ├── networking_flow ├── __init__.py ├── ford_fulkerson.py └── minimum_cut.py ├── neural_network ├── __init__.py ├── back_propagation_neural_network.py ├── convolution_neural_network.py ├── gan.py_tf ├── input_data.py_tf └── perceptron.py ├── other ├── __init__.py ├── activity_selection.py ├── anagrams.py ├── autocomplete_using_trie.py ├── binary_exponentiation.py ├── binary_exponentiation_2.py ├── detecting_english_programmatically.py ├── dictionary.txt ├── dijkstra_bankers_algorithm.py ├── euclidean_gcd.py ├── fischer_yates_shuffle.py ├── frequency_finder.py ├── game_of_life.py ├── gauss_easter.py ├── greedy.py ├── integeration_by_simpson_approx.py ├── largest_subarray_sum.py ├── least_recently_used.py ├── lfu_cache.py ├── linear_congruential_generator.py ├── lru_cache.py ├── magicdiamondpattern.py ├── markov_chain.py ├── nested_brackets.py ├── palindrome.py ├── password_generator.py ├── primelib.py ├── scoring_algorithm.py ├── sdes.py ├── sierpinski_triangle.py ├── tower_of_hanoi.py ├── triplet_sum.py ├── two_sum.py ├── word_patterns.py └── words ├── project_euler ├── README.md ├── __init__.py ├── problem_01 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ ├── sol3.py │ ├── sol4.py │ ├── sol5.py │ ├── sol6.py │ └── sol7.py ├── problem_02 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ ├── sol3.py │ ├── sol4.py │ └── sol5.py ├── problem_03 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ └── sol3.py ├── problem_04 │ ├── __init__.py │ ├── sol1.py │ └── sol2.py ├── problem_05 │ ├── __init__.py │ ├── sol1.py │ └── sol2.py ├── problem_06 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ ├── sol3.py │ ├── sol4.py │ └── test_solutions.py ├── problem_07 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ └── sol3.py ├── problem_08 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ └── sol3.py ├── problem_09 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ └── sol3.py ├── problem_10 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ └── sol3.py ├── problem_11 │ ├── __init__.py │ ├── grid.txt │ ├── sol1.py │ └── sol2.py ├── problem_12 │ ├── __init__.py │ ├── sol1.py │ └── sol2.py ├── problem_13 │ ├── __init__.py │ ├── num.txt │ └── sol1.py ├── problem_14 │ ├── __init__.py │ ├── sol1.py │ └── sol2.py ├── problem_15 │ ├── __init__.py │ └── sol1.py ├── problem_16 │ ├── __init__.py │ ├── sol1.py │ └── sol2.py ├── problem_17 │ ├── __init__.py │ └── sol1.py ├── problem_18 │ ├── __init__.py │ ├── solution.py │ └── triangle.txt ├── problem_19 │ ├── __init__.py │ └── sol1.py ├── problem_20 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ ├── sol3.py │ └── sol4.py ├── problem_21 │ ├── __init__.py │ └── sol1.py ├── problem_22 │ ├── __init__.py │ ├── p022_names.txt │ ├── sol1.py │ └── sol2.py ├── problem_23 │ ├── __init__.py │ └── sol1.py ├── problem_234 │ ├── __init__.py │ └── sol1.py ├── problem_24 │ ├── __init__.py │ └── sol1.py ├── problem_25 │ ├── __init__.py │ ├── sol1.py │ ├── sol2.py │ └── sol3.py ├── problem_26 │ ├── __init__.py │ └── sol1.py ├── problem_27 │ ├── __init__.py │ └── problem_27_sol1.py ├── problem_28 │ ├── __init__.py │ └── sol1.py ├── problem_29 │ ├── __init__.py │ └── solution.py ├── problem_30 │ ├── __init__.py │ └── soln.py ├── problem_31 │ ├── __init__.py │ ├── sol1.py │ └── sol2.py ├── problem_32 │ ├── __init__.py │ └── sol32.py ├── problem_33 │ ├── __init__.py │ └── sol1.py ├── problem_34 │ ├── __init__.py │ └── sol1.py ├── problem_35 │ ├── __init__.py │ └── sol1.py ├── problem_36 │ ├── __init__.py │ └── sol1.py ├── problem_37 │ ├── __init__.py │ └── sol1.py ├── problem_39 │ ├── __init__.py │ └── sol1.py ├── problem_40 │ ├── __init__.py │ └── sol1.py ├── problem_41 │ ├── __init__.py │ └── sol1.py ├── problem_42 │ ├── __init__.py │ ├── solution42.py │ └── words.txt ├── problem_43 │ ├── __init__.py │ └── sol1.py ├── problem_44 │ ├── __init__.py │ └── sol1.py ├── problem_45 │ ├── __init__.py │ └── sol1.py ├── problem_46 │ ├── __init__.py │ └── sol1.py ├── problem_47 │ ├── __init__.py │ └── sol1.py ├── problem_48 │ ├── __init__.py │ └── sol1.py ├── problem_52 │ ├── __init__.py │ └── sol1.py ├── problem_53 │ ├── __init__.py │ └── sol1.py ├── problem_54 │ ├── __init__.py │ ├── poker_hands.txt │ ├── sol1.py │ └── test_poker_hand.py ├── problem_55 │ ├── __init__.py │ └── sol1.py ├── problem_551 │ ├── __init__.py │ └── sol1.py ├── problem_56 │ ├── __init__.py │ └── sol1.py ├── problem_63 │ ├── __init__.py │ └── sol1.py ├── problem_67 │ ├── __init__.py │ ├── sol1.py │ └── triangle.txt ├── problem_76 │ ├── __init__.py │ └── sol1.py ├── problem_97 │ ├── __init__.py │ └── sol1.py ├── problem_99 │ ├── __init__.py │ ├── base_exp.txt │ └── sol1.py ├── project_euler_answers.json └── validate_solutions.py ├── pytest.ini ├── quantum ├── README.md └── __init__.py ├── requirements.txt ├── scheduling ├── __init__.py ├── first_come_first_served.py ├── round_robin.py └── shortest_job_first.py ├── scripts ├── __init__.py ├── build_directory_md.py └── validate_filenames.py ├── searches ├── __init__.py ├── binary_search.py ├── double_linear_search.py ├── double_linear_search_recursion.py ├── fibonacci_search.py ├── hill_climbing.py ├── interpolation_search.py ├── jump_search.py ├── linear_search.py ├── quick_select.py ├── sentinel_linear_search.py ├── simple_binary_search.py ├── simulated_annealing.py ├── tabu_search.py ├── tabu_test_data.txt └── ternary_search.py ├── sorts ├── __init__.py ├── bead_sort.py ├── bitonic_sort.py ├── bogo_sort.py ├── bubble_sort.py ├── bucket_sort.py ├── cocktail_shaker_sort.py ├── comb_sort.py ├── counting_sort.py ├── cycle_sort.py ├── double_sort.py ├── external_sort.py ├── gnome_sort.py ├── heap_sort.py ├── i_sort.py ├── insertion_sort.py ├── iterative_merge_sort.py ├── merge_insertion_sort.py ├── merge_sort.py ├── normal_distribution_quick_sort.md ├── odd_even_transposition_parallel.py ├── odd_even_transposition_single_threaded.py ├── pancake_sort.py ├── pigeon_sort.py ├── pigeonhole_sort.py ├── quick_sort.py ├── quick_sort_3_partition.py ├── radix_sort.py ├── random_normal_distribution_quicksort.py ├── random_pivot_quick_sort.py ├── recursive_bubble_sort.py ├── recursive_insertion_sort.py ├── recursive_quick_sort.py ├── selection_sort.py ├── shell_sort.py ├── stooge_sort.py ├── strand_sort.py ├── tim_sort.py ├── topological_sort.py ├── tree_sort.py ├── unknown_sort.py └── wiggle_sort.py ├── strings ├── __init__.py ├── aho_corasick.py ├── boyer_moore_search.py ├── can_string_be_rearranged_as_palindrome.py ├── capitalize.py ├── check_anagrams.py ├── check_pangram.py ├── is_palindrome.py ├── jaro_winkler.py ├── knuth_morris_pratt.py ├── levenshtein_distance.py ├── lower.py ├── manacher.py ├── min_cost_string_conversion.py ├── naive_string_search.py ├── prefix_function.py ├── rabin_karp.py ├── remove_duplicate.py ├── reverse_words.py ├── split.py ├── upper.py ├── word_occurrence.py └── z_function.py ├── traversals ├── __init__.py └── binary_tree_traversals.py └── web_programming ├── __init__.py ├── covid_stats_via_xpath.py ├── crawl_google_results.py ├── current_stock_price.py ├── current_weather.py ├── daily_horoscope.py ├── emails_from_url.py ├── fetch_bbc_news.py ├── fetch_github_info.py ├── fetch_jobs.py ├── get_imdb_top_250_movies_csv.py ├── get_imdbtop.py ├── instagram_crawler.py ├── recaptcha_verification.py ├── slack_message.py └── world_covid19_stats.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [report] 2 | sort = Cover 3 | omit = 4 | .env/* 5 | -------------------------------------------------------------------------------- /.github/stale.yml: -------------------------------------------------------------------------------- 1 | # Number of days of inactivity before an issue becomes stale 2 | daysUntilStale: 30 3 | # Number of days of inactivity before a stale issue is closed 4 | daysUntilClose: 7 5 | # Issues with these labels will never be considered stale 6 | exemptLabels: 7 | - bug 8 | - help wanted 9 | - OK to merge 10 | # Label to use when marking an issue as stale 11 | staleLabel: wontfix 12 | # Comment to post when marking an issue as stale. Set to `false` to disable 13 | markComment: > 14 | This issue has been automatically marked as stale because it has not had 15 | recent activity. It will be closed if no further activity occurs. Thank you 16 | for your contributions. 17 | # Comment to post when closing a stale issue. Set to `false` to disable 18 | closeComment: > 19 | Please reopen this issue once you commit the changes requested or 20 | make improvements on the code. Thank you for your contributions. 21 | -------------------------------------------------------------------------------- /.github/workflows/autoblack.yml: -------------------------------------------------------------------------------- 1 | # GitHub Action that uses Black to reformat Python code (if needed) when doing a git push. 2 | # If all Python code in the repo is compliant with Black then this Action does nothing. 3 | # Otherwise, Black is run and its changes are committed to the repo. 4 | # https://github.com/cclauss/autoblack 5 | 6 | name: autoblack_push 7 | on: [push] 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v1 # Use v1, NOT v2 13 | - uses: actions/setup-python@v2 14 | - run: pip install black isort 15 | - run: black --check . 16 | - name: If needed, commit black changes to a new pull request 17 | if: failure() 18 | run: | 19 | black . 20 | isort --profile black . 21 | git config --global user.name github-actions 22 | git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' 23 | git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY 24 | git commit -am "fixup! Format Python code with psf/black push" 25 | git push --force origin HEAD:$GITHUB_REF 26 | -------------------------------------------------------------------------------- /.github/workflows/codespell.yml: -------------------------------------------------------------------------------- 1 | # GitHub Action to automate the identification of common misspellings in text files 2 | # https://github.com/codespell-project/codespell 3 | name: codespell 4 | on: [push, pull_request] 5 | jobs: 6 | codespell: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v2 10 | - uses: actions/setup-python@v2 11 | - run: pip install codespell flake8 12 | - run: | 13 | SKIP="./.*,./other/dictionary.txt,./other/words,./project_euler/problem_22/p022_names.txt" 14 | codespell --ignore-words-list=ans,fo,followings,hist,iff,secant,som,tim --skip=$SKIP --quiet-level=2 15 | - name: Codespell comment 16 | if: ${{ failure() }} 17 | uses: plettich/python_codespell_action@master 18 | -------------------------------------------------------------------------------- /.github/workflows/directory_writer.yml: -------------------------------------------------------------------------------- 1 | # The objective of this GitHub Action is to update the DIRECTORY.md file (if needed) 2 | # when doing a git push 3 | name: directory_writer 4 | on: [push] 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v1 # v1, NOT v2 10 | - uses: actions/setup-python@v2 11 | with: 12 | python-version: 3.x 13 | - name: Write DIRECTORY.md 14 | run: | 15 | scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md 16 | git config --global user.name github-actions 17 | git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' 18 | git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY 19 | - name: Update DIRECTORY.md 20 | run: | 21 | git add DIRECTORY.md 22 | git commit -am "updating DIRECTORY.md" || true 23 | git push --force origin HEAD:$GITHUB_REF || true 24 | -------------------------------------------------------------------------------- /.github/workflows/pre-commit.yml: -------------------------------------------------------------------------------- 1 | name: pre-commit 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | pre-commit: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v2 10 | - uses: actions/setup-python@v2 11 | - name: Install pre-commit 12 | run: | 13 | python -m pip install --upgrade pip 14 | python -m pip install --upgrade pre-commit 15 | - run: pre-commit run --verbose --all-files --show-diff-on-failure 16 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | name: Mark stale issues and pull requests 2 | on: 3 | schedule: 4 | - cron: "0 0 * * *" 5 | jobs: 6 | stale: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/stale@v1 10 | with: 11 | repo-token: ${{ secrets.GITHUB_TOKEN }} 12 | stale-issue-message: > 13 | Please reopen this issue once you add more information and updates here. 14 | If this is not the case and you need some help, feel free to seek help 15 | from our [Gitter](https://gitter.im/TheAlgorithms) or ping one of the 16 | reviewers. Thank you for your contributions! 17 | stale-pr-message: > 18 | Please reopen this pull request once you commit the changes requested 19 | or make improvements on the code. If this is not the case and you need 20 | some help, feel free to seek help from our [Gitter](https://gitter.im/TheAlgorithms) 21 | or ping one of the reviewers. Thank you for your contributions! 22 | stale-issue-label: 'no-issue-activity' 23 | stale-pr-label: 'no-pr-activity' 24 | -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | tasks: 2 | - init: pip3 install -r ./requirements.txt 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | os: linux 2 | dist: focal 3 | language: python 4 | python: 3.8 5 | cache: pip 6 | before_install: pip install --upgrade pip setuptools six 7 | jobs: 8 | include: 9 | - name: Build 10 | install: pip install pytest-cov -r requirements.txt 11 | script: 12 | - pytest --doctest-modules --ignore=project_euler/ --durations=10 --cov-report=term-missing:skip-covered --cov=. . 13 | - name: Project Euler 14 | install: 15 | - pip install pytest-cov pytest-subtests 16 | before_script: 17 | - pytest --tb=no --no-summary --capture=no project_euler/validate_solutions.py || true # fail fast on wrong solution 18 | script: 19 | - pytest --doctest-modules --durations=10 --cov-report=term-missing:skip-covered --cov=project_euler/ project_euler/ 20 | after_success: 21 | - scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md 22 | notifications: 23 | webhooks: https://www.travisbuddy.com/ 24 | on_success: never 25 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 The Algorithms 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Travis_CI_tests_are_failing.md: -------------------------------------------------------------------------------- 1 | # Travis CI test are failing 2 | ### How do I find out what is wrong with my pull request? 3 | 1. In your PR look for the failing test and click the `Details` link: ![Travis_CI_fail_1.png](images/Travis_CI_fail_1.png) 4 | 2. On the next page, click `The build failed` link: ![Travis_CI_fail_2.png](images/Travis_CI_fail_2.png) 5 | 3. Now scroll down and look for `red` text describing the error(s) in the test log. 6 | 7 | Pull requests will __not__ be merged if the Travis CI tests are failing. 8 | 9 | If anything is unclear, please read through [CONTRIBUTING.md](CONTRIBUTING.md) and attempt to run the failing tests on your computer before asking for assistance. 10 | -------------------------------------------------------------------------------- /arithmetic_analysis/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/arithmetic_analysis/__init__.py -------------------------------------------------------------------------------- /arithmetic_analysis/image_data/2D_problems.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/arithmetic_analysis/image_data/2D_problems.jpg -------------------------------------------------------------------------------- /arithmetic_analysis/image_data/2D_problems_1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/arithmetic_analysis/image_data/2D_problems_1.jpg -------------------------------------------------------------------------------- /arithmetic_analysis/image_data/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/arithmetic_analysis/image_data/__init__.py -------------------------------------------------------------------------------- /arithmetic_analysis/lu_decomposition.py: -------------------------------------------------------------------------------- 1 | """Lower-Upper (LU) Decomposition.""" 2 | 3 | # lower–upper (LU) decomposition - https://en.wikipedia.org/wiki/LU_decomposition 4 | import numpy 5 | 6 | 7 | def LUDecompose(table): 8 | # Table that contains our data 9 | # Table has to be a square array so we need to check first 10 | rows, columns = numpy.shape(table) 11 | L = numpy.zeros((rows, columns)) 12 | U = numpy.zeros((rows, columns)) 13 | if rows != columns: 14 | return [] 15 | for i in range(columns): 16 | for j in range(i): 17 | sum = 0 18 | for k in range(j): 19 | sum += L[i][k] * U[k][j] 20 | L[i][j] = (table[i][j] - sum) / U[j][j] 21 | L[i][i] = 1 22 | for j in range(i, columns): 23 | sum1 = 0 24 | for k in range(i): 25 | sum1 += L[i][k] * U[k][j] 26 | U[i][j] = table[i][j] - sum1 27 | return L, U 28 | 29 | 30 | if __name__ == "__main__": 31 | matrix = numpy.array([[2, -2, 1], [0, 1, 2], [5, 3, 1]]) 32 | L, U = LUDecompose(matrix) 33 | print(L) 34 | print(U) 35 | -------------------------------------------------------------------------------- /arithmetic_analysis/secant_method.py: -------------------------------------------------------------------------------- 1 | # Implementing Secant method in Python 2 | # Author: dimgrichr 3 | 4 | 5 | from math import exp 6 | 7 | 8 | def f(x): 9 | """ 10 | >>> f(5) 11 | 39.98652410600183 12 | """ 13 | return 8 * x - 2 * exp(-x) 14 | 15 | 16 | def SecantMethod(lower_bound, upper_bound, repeats): 17 | """ 18 | >>> SecantMethod(1, 3, 2) 19 | 0.2139409276214589 20 | """ 21 | x0 = lower_bound 22 | x1 = upper_bound 23 | for i in range(0, repeats): 24 | x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0)) 25 | return x1 26 | 27 | 28 | print(f"The solution is: {SecantMethod(1, 3, 2)}") 29 | -------------------------------------------------------------------------------- /backtracking/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/backtracking/__init__.py -------------------------------------------------------------------------------- /backtracking/all_combinations.py: -------------------------------------------------------------------------------- 1 | """ 2 | In this problem, we want to determine all possible combinations of k 3 | numbers out of 1 ... n. We use backtracking to solve this problem. 4 | Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!))) 5 | """ 6 | 7 | 8 | def generate_all_combinations(n: int, k: int) -> [[int]]: 9 | """ 10 | >>> generate_all_combinations(n=4, k=2) 11 | [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] 12 | """ 13 | 14 | result = [] 15 | create_all_state(1, n, k, [], result) 16 | return result 17 | 18 | 19 | def create_all_state(increment, total_number, level, current_list, total_list): 20 | if level == 0: 21 | total_list.append(current_list[:]) 22 | return 23 | 24 | for i in range(increment, total_number - level + 2): 25 | current_list.append(i) 26 | create_all_state(i + 1, total_number, level - 1, current_list, total_list) 27 | current_list.pop() 28 | 29 | 30 | def print_all_state(total_list): 31 | for i in total_list: 32 | print(*i) 33 | 34 | 35 | if __name__ == "__main__": 36 | n = 4 37 | k = 2 38 | total_list = generate_all_combinations(n, k) 39 | print_all_state(total_list) 40 | -------------------------------------------------------------------------------- /bit_manipulation/README.md: -------------------------------------------------------------------------------- 1 | https://docs.python.org/3/reference/expressions.html#binary-bitwise-operations 2 | https://docs.python.org/3/reference/expressions.html#unary-arithmetic-and-bitwise-operations 3 | https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types 4 | 5 | https://wiki.python.org/moin/BitManipulation 6 | https://wiki.python.org/moin/BitwiseOperators 7 | https://www.tutorialspoint.com/python3/bitwise_operators_example.htm 8 | -------------------------------------------------------------------------------- /bit_manipulation/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/bit_manipulation/__init__.py -------------------------------------------------------------------------------- /blockchain/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/blockchain/__init__.py -------------------------------------------------------------------------------- /boolean_algebra/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/boolean_algebra/__init__.py -------------------------------------------------------------------------------- /cellular_automata/README.md: -------------------------------------------------------------------------------- 1 | # Cellular Automata 2 | 3 | * https://en.wikipedia.org/wiki/Cellular_automaton 4 | * https://mathworld.wolfram.com/ElementaryCellularAutomaton.html 5 | -------------------------------------------------------------------------------- /cellular_automata/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/cellular_automata/__init__.py -------------------------------------------------------------------------------- /ciphers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/ciphers/__init__.py -------------------------------------------------------------------------------- /ciphers/a1z26.py: -------------------------------------------------------------------------------- 1 | """ 2 | Convert a string of characters to a sequence of numbers 3 | corresponding to the character's position in the alphabet. 4 | 5 | https://www.dcode.fr/letter-number-cipher 6 | http://bestcodes.weebly.com/a1z26.html 7 | """ 8 | 9 | 10 | def encode(plain: str) -> list: 11 | """ 12 | >>> encode("myname") 13 | [13, 25, 14, 1, 13, 5] 14 | """ 15 | return [ord(elem) - 96 for elem in plain] 16 | 17 | 18 | def decode(encoded: list) -> str: 19 | """ 20 | >>> decode([13, 25, 14, 1, 13, 5]) 21 | 'myname' 22 | """ 23 | return "".join(chr(elem + 96) for elem in encoded) 24 | 25 | 26 | def main(): 27 | encoded = encode(input("->").strip().lower()) 28 | print("Encoded: ", encoded) 29 | print("Decoded:", decode(encoded)) 30 | 31 | 32 | if __name__ == "__main__": 33 | main() 34 | -------------------------------------------------------------------------------- /ciphers/base16.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | 4 | def main(): 5 | inp = input("->") 6 | encoded = inp.encode("utf-8") # encoded the input (we need a bytes like object) 7 | b16encoded = base64.b16encode(encoded) # b16encoded the encoded string 8 | print(b16encoded) 9 | print(base64.b16decode(b16encoded).decode("utf-8")) # decoded it 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /ciphers/base32.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | 4 | def main(): 5 | inp = input("->") 6 | encoded = inp.encode("utf-8") # encoded the input (we need a bytes like object) 7 | b32encoded = base64.b32encode(encoded) # b32encoded the encoded string 8 | print(b32encoded) 9 | print(base64.b32decode(b32encoded).decode("utf-8")) # decoded it 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /ciphers/base85.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | 4 | def main(): 5 | inp = input("->") 6 | encoded = inp.encode("utf-8") # encoded the input (we need a bytes like object) 7 | a85encoded = base64.a85encode(encoded) # a85encoded the encoded string 8 | print(a85encoded) 9 | print(base64.a85decode(a85encoded).decode("utf-8")) # decoded it 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /ciphers/cryptomath_module.py: -------------------------------------------------------------------------------- 1 | def gcd(a, b): 2 | while a != 0: 3 | a, b = b % a, a 4 | return b 5 | 6 | 7 | def findModInverse(a, m): 8 | if gcd(a, m) != 1: 9 | return None 10 | u1, u2, u3 = 1, 0, a 11 | v1, v2, v3 = 0, 1, m 12 | while v3 != 0: 13 | q = u3 // v3 14 | v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3 15 | return u1 % m 16 | -------------------------------------------------------------------------------- /ciphers/diffie.py: -------------------------------------------------------------------------------- 1 | def find_primitive(n): 2 | for r in range(1, n): 3 | li = [] 4 | for x in range(n - 1): 5 | val = pow(r, x, n) 6 | if val in li: 7 | break 8 | li.append(val) 9 | else: 10 | return r 11 | 12 | 13 | if __name__ == "__main__": 14 | q = int(input("Enter a prime number q: ")) 15 | a = find_primitive(q) 16 | a_private = int(input("Enter private key of A: ")) 17 | a_public = pow(a, a_private, q) 18 | b_private = int(input("Enter private key of B: ")) 19 | b_public = pow(a, b_private, q) 20 | 21 | a_secret = pow(b_public, a_private, q) 22 | b_secret = pow(a_public, b_private, q) 23 | 24 | print("The key value generated by A is: ", a_secret) 25 | print("The key value generated by B is: ", b_secret) 26 | -------------------------------------------------------------------------------- /ciphers/onepad_cipher.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | class Onepad: 5 | def encrypt(self, text): 6 | """Function to encrypt text using pseudo-random numbers""" 7 | plain = [ord(i) for i in text] 8 | key = [] 9 | cipher = [] 10 | for i in plain: 11 | k = random.randint(1, 300) 12 | c = (i + k) * k 13 | cipher.append(c) 14 | key.append(k) 15 | return cipher, key 16 | 17 | def decrypt(self, cipher, key): 18 | """Function to decrypt text using pseudo-random numbers.""" 19 | plain = [] 20 | for i in range(len(key)): 21 | p = int((cipher[i] - (key[i]) ** 2) / key[i]) 22 | plain.append(chr(p)) 23 | plain = "".join([i for i in plain]) 24 | return plain 25 | 26 | 27 | if __name__ == "__main__": 28 | c, k = Onepad().encrypt("Hello") 29 | print(c, k) 30 | print(Onepad().decrypt(c, k)) 31 | -------------------------------------------------------------------------------- /ciphers/prehistoric_men.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/ciphers/prehistoric_men.txt -------------------------------------------------------------------------------- /ciphers/rot13.py: -------------------------------------------------------------------------------- 1 | def dencrypt(s: str, n: int = 13): 2 | """ 3 | https://en.wikipedia.org/wiki/ROT13 4 | 5 | >>> msg = "My secret bank account number is 173-52946 so don't tell anyone!!" 6 | >>> s = dencrypt(msg) 7 | >>> s 8 | "Zl frperg onax nppbhag ahzore vf 173-52946 fb qba'g gryy nalbar!!" 9 | >>> dencrypt(s) == msg 10 | True 11 | """ 12 | out = "" 13 | for c in s: 14 | if "A" <= c <= "Z": 15 | out += chr(ord("A") + (ord(c) - ord("A") + n) % 26) 16 | elif "a" <= c <= "z": 17 | out += chr(ord("a") + (ord(c) - ord("a") + n) % 26) 18 | else: 19 | out += c 20 | return out 21 | 22 | 23 | def main(): 24 | s0 = input("Enter message: ") 25 | 26 | s1 = dencrypt(s0, 13) 27 | print("Encryption:", s1) 28 | 29 | s2 = dencrypt(s1, 13) 30 | print("Decryption: ", s2) 31 | 32 | 33 | if __name__ == "__main__": 34 | import doctest 35 | 36 | doctest.testmod() 37 | main() 38 | -------------------------------------------------------------------------------- /compression/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/compression/__init__.py -------------------------------------------------------------------------------- /compression/image_data/PSNR-example-base.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/compression/image_data/PSNR-example-base.png -------------------------------------------------------------------------------- /compression/image_data/PSNR-example-comp-10.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/compression/image_data/PSNR-example-comp-10.jpg -------------------------------------------------------------------------------- /compression/image_data/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/compression/image_data/__init__.py -------------------------------------------------------------------------------- /compression/image_data/compressed_image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/compression/image_data/compressed_image.png -------------------------------------------------------------------------------- /compression/image_data/example_image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/compression/image_data/example_image.jpg -------------------------------------------------------------------------------- /compression/image_data/example_wikipedia_image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/compression/image_data/example_wikipedia_image.jpg -------------------------------------------------------------------------------- /compression/image_data/original_image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/compression/image_data/original_image.png -------------------------------------------------------------------------------- /computer_vision/README.md: -------------------------------------------------------------------------------- 1 | ### Computer Vision 2 | 3 | Computer vision is a field of computer science that works on enabling computers to see, 4 | identify and process images in the same way that human vision does, and then provide appropriate output. 5 | It is like imparting human intelligence and instincts to a computer. 6 | Image processing and computer vision and little different from each other.Image processing means applying some algorithms for transforming image from one form to other like smoothing,contrasting, stretching etc 7 | While in computer vision comes from modelling image processing using the techniques of machine learning.Computer vision applies machine learning to recognize patterns for interpretation of images. 8 | Much like the process of visual reasoning of human vision 9 | -------------------------------------------------------------------------------- /computer_vision/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/computer_vision/__init__.py -------------------------------------------------------------------------------- /conversions/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/conversions/__init__.py -------------------------------------------------------------------------------- /conversions/roman_to_integer.py: -------------------------------------------------------------------------------- 1 | def roman_to_int(roman: str) -> int: 2 | """ 3 | LeetCode No. 13 Roman to Integer 4 | Given a roman numeral, convert it to an integer. 5 | Input is guaranteed to be within the range from 1 to 3999. 6 | https://en.wikipedia.org/wiki/Roman_numerals 7 | >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999} 8 | >>> all(roman_to_int(key) == value for key, value in tests.items()) 9 | True 10 | """ 11 | vals = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} 12 | total = 0 13 | place = 0 14 | while place < len(roman): 15 | if (place + 1 < len(roman)) and (vals[roman[place]] < vals[roman[place + 1]]): 16 | total += vals[roman[place + 1]] - vals[roman[place]] 17 | place += 2 18 | else: 19 | total += vals[roman[place]] 20 | place += 1 21 | return total 22 | 23 | 24 | if __name__ == "__main__": 25 | import doctest 26 | 27 | doctest.testmod() 28 | -------------------------------------------------------------------------------- /data_structures/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/data_structures/__init__.py -------------------------------------------------------------------------------- /data_structures/binary_tree/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/data_structures/binary_tree/__init__.py -------------------------------------------------------------------------------- /data_structures/binary_tree/fenwick_tree.py: -------------------------------------------------------------------------------- 1 | class FenwickTree: 2 | def __init__(self, SIZE): # create fenwick tree with size SIZE 3 | self.Size = SIZE 4 | self.ft = [0 for i in range(0, SIZE)] 5 | 6 | def update(self, i, val): # update data (adding) in index i in O(lg N) 7 | while i < self.Size: 8 | self.ft[i] += val 9 | i += i & (-i) 10 | 11 | def query(self, i): # query cumulative data from index 0 to i in O(lg N) 12 | ret = 0 13 | while i > 0: 14 | ret += self.ft[i] 15 | i -= i & (-i) 16 | return ret 17 | 18 | 19 | if __name__ == "__main__": 20 | f = FenwickTree(100) 21 | f.update(1, 20) 22 | f.update(4, 4) 23 | print(f.query(1)) 24 | print(f.query(3)) 25 | print(f.query(4)) 26 | f.update(2, -5) 27 | print(f.query(1)) 28 | print(f.query(3)) 29 | -------------------------------------------------------------------------------- /data_structures/disjoint_set/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/data_structures/disjoint_set/__init__.py -------------------------------------------------------------------------------- /data_structures/hashing/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/data_structures/hashing/__init__.py -------------------------------------------------------------------------------- /data_structures/hashing/hash_table_with_linked_list.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | from .hash_table import HashTable 4 | 5 | 6 | class HashTableWithLinkedList(HashTable): 7 | def __init__(self, *args, **kwargs): 8 | super().__init__(*args, **kwargs) 9 | 10 | def _set_value(self, key, data): 11 | self.values[key] = deque([]) if self.values[key] is None else self.values[key] 12 | self.values[key].appendleft(data) 13 | self._keys[key] = self.values[key] 14 | 15 | def balanced_factor(self): 16 | return ( 17 | sum([self.charge_factor - len(slot) for slot in self.values]) 18 | / self.size_table 19 | * self.charge_factor 20 | ) 21 | 22 | def _collision_resolution(self, key, data=None): 23 | if not ( 24 | len(self.values[key]) == self.charge_factor and self.values.count(None) == 0 25 | ): 26 | return key 27 | return super()._collision_resolution(key, data) 28 | -------------------------------------------------------------------------------- /data_structures/hashing/number_theory/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/data_structures/hashing/number_theory/__init__.py -------------------------------------------------------------------------------- /data_structures/hashing/number_theory/prime_numbers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | module to operations with prime numbers 4 | """ 5 | 6 | 7 | def check_prime(number): 8 | """ 9 | it's not the best solution 10 | """ 11 | special_non_primes = [0, 1, 2] 12 | if number in special_non_primes[:2]: 13 | return 2 14 | elif number == special_non_primes[-1]: 15 | return 3 16 | 17 | return all([number % i for i in range(2, number)]) 18 | 19 | 20 | def next_prime(value, factor=1, **kwargs): 21 | value = factor * value 22 | first_value_val = value 23 | 24 | while not check_prime(value): 25 | value += 1 if not ("desc" in kwargs.keys() and kwargs["desc"] is True) else -1 26 | 27 | if value == first_value_val: 28 | return next_prime(value + 1, **kwargs) 29 | return value 30 | -------------------------------------------------------------------------------- /data_structures/hashing/quadratic_probing.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from .hash_table import HashTable 4 | 5 | 6 | class QuadraticProbing(HashTable): 7 | """ 8 | Basic Hash Table example with open addressing using Quadratic Probing 9 | """ 10 | 11 | def __init__(self, *args, **kwargs): 12 | super().__init__(*args, **kwargs) 13 | 14 | def _collision_resolution(self, key, data=None): 15 | i = 1 16 | new_key = self.hash_function(key + i * i) 17 | 18 | while self.values[new_key] is not None and self.values[new_key] != key: 19 | i += 1 20 | new_key = ( 21 | self.hash_function(key + i * i) 22 | if not self.balanced_factor() >= self.lim_charge 23 | else None 24 | ) 25 | 26 | if new_key is None: 27 | break 28 | 29 | return new_key 30 | -------------------------------------------------------------------------------- /data_structures/heap/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/data_structures/heap/__init__.py -------------------------------------------------------------------------------- /data_structures/linked_list/__init__.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, item, next): 3 | self.item = item 4 | self.next = next 5 | 6 | 7 | class LinkedList: 8 | def __init__(self): 9 | self.head = None 10 | self.size = 0 11 | 12 | def add(self, item): 13 | self.head = Node(item, self.head) 14 | self.size += 1 15 | 16 | def remove(self): 17 | if self.is_empty(): 18 | return None 19 | else: 20 | item = self.head.item 21 | self.head = self.head.next 22 | self.size -= 1 23 | return item 24 | 25 | def is_empty(self): 26 | return self.head is None 27 | 28 | def __len__(self): 29 | """ 30 | >>> linked_list = LinkedList() 31 | >>> len(linked_list) 32 | 0 33 | >>> linked_list.add("a") 34 | >>> len(linked_list) 35 | 1 36 | >>> linked_list.add("b") 37 | >>> len(linked_list) 38 | 2 39 | >>> _ = linked_list.remove() 40 | >>> len(linked_list) 41 | 1 42 | >>> _ = linked_list.remove() 43 | >>> len(linked_list) 44 | 0 45 | """ 46 | return self.size 47 | -------------------------------------------------------------------------------- /data_structures/queue/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/data_structures/queue/__init__.py -------------------------------------------------------------------------------- /data_structures/stacks/__init__.py: -------------------------------------------------------------------------------- 1 | class Stack: 2 | def __init__(self): 3 | self.stack = [] 4 | self.top = 0 5 | 6 | def is_empty(self): 7 | return self.top == 0 8 | 9 | def push(self, item): 10 | if self.top < len(self.stack): 11 | self.stack[self.top] = item 12 | else: 13 | self.stack.append(item) 14 | 15 | self.top += 1 16 | 17 | def pop(self): 18 | if self.is_empty(): 19 | return None 20 | else: 21 | self.top -= 1 22 | return self.stack[self.top] 23 | -------------------------------------------------------------------------------- /data_structures/stacks/balanced_parentheses.py: -------------------------------------------------------------------------------- 1 | from .stack import Stack 2 | 3 | __author__ = "Omkar Pathak" 4 | 5 | 6 | def balanced_parentheses(parentheses): 7 | """ Use a stack to check if a string of parentheses is balanced.""" 8 | stack = Stack(len(parentheses)) 9 | for parenthesis in parentheses: 10 | if parenthesis == "(": 11 | stack.push(parenthesis) 12 | elif parenthesis == ")": 13 | if stack.is_empty(): 14 | return False 15 | stack.pop() 16 | return stack.is_empty() 17 | 18 | 19 | if __name__ == "__main__": 20 | examples = ["((()))", "((())", "(()))"] 21 | print("Balanced parentheses demonstration:\n") 22 | for example in examples: 23 | print(example + ": " + str(balanced_parentheses(example))) 24 | -------------------------------------------------------------------------------- /data_structures/trie/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/data_structures/trie/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/digital_image_processing/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/change_brightness.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | 3 | 4 | def change_brightness(img: Image, level: float) -> Image: 5 | """ 6 | Change the brightness of a PIL Image to a given level. 7 | """ 8 | 9 | def brightness(c: int) -> float: 10 | """ 11 | Fundamental Transformation/Operation that'll be performed on 12 | every bit. 13 | """ 14 | return 128 + level + (c - 128) 15 | 16 | if not -255.0 <= level <= 255.0: 17 | raise ValueError("level must be between -255.0 (black) and 255.0 (white)") 18 | return img.point(brightness) 19 | 20 | 21 | if __name__ == "__main__": 22 | # Load image 23 | with Image.open("image_data/lena.jpg") as img: 24 | # Change brightness to 100 25 | brigt_img = change_brightness(img, 100) 26 | brigt_img.save("image_data/lena_brightness.png", format="png") 27 | -------------------------------------------------------------------------------- /digital_image_processing/change_contrast.py: -------------------------------------------------------------------------------- 1 | """ 2 | Changing contrast with PIL 3 | 4 | This algorithm is used in 5 | https://noivce.pythonanywhere.com/ Python web app. 6 | 7 | python/black: True 8 | flake8 : True 9 | """ 10 | 11 | from PIL import Image 12 | 13 | 14 | def change_contrast(img: Image, level: float) -> Image: 15 | """ 16 | Function to change contrast 17 | """ 18 | factor = (259 * (level + 255)) / (255 * (259 - level)) 19 | 20 | def contrast(c: int) -> float: 21 | """ 22 | Fundamental Transformation/Operation that'll be performed on 23 | every bit. 24 | """ 25 | return 128 + factor * (c - 128) 26 | 27 | return img.point(contrast) 28 | 29 | 30 | if __name__ == "__main__": 31 | # Load image 32 | with Image.open("image_data/lena.jpg") as img: 33 | # Change contrast to 170 34 | cont_img = change_contrast(img, 170) 35 | cont_img.save("image_data/lena_high_contrast.png", format="png") 36 | -------------------------------------------------------------------------------- /digital_image_processing/convert_to_negative.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implemented an algorithm using opencv to convert a colored image into its negative 3 | """ 4 | from cv2 import destroyAllWindows, imread, imshow, waitKey 5 | 6 | 7 | def convert_to_negative(img): 8 | # getting number of pixels in the image 9 | pixel_h, pixel_v = img.shape[0], img.shape[1] 10 | 11 | # converting each pixel's color to its negative 12 | for i in range(pixel_h): 13 | for j in range(pixel_v): 14 | img[i][j] = [255, 255, 255] - img[i][j] 15 | 16 | return img 17 | 18 | 19 | if __name__ == "__main__": 20 | # read original image 21 | img = imread("image_data/lena.jpg", 1) 22 | 23 | # convert to its negative 24 | neg = convert_to_negative(img) 25 | 26 | # show result image 27 | imshow("negative of original image", img) 28 | waitKey(0) 29 | destroyAllWindows() 30 | -------------------------------------------------------------------------------- /digital_image_processing/dithering/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/digital_image_processing/dithering/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/edge_detection/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/digital_image_processing/edge_detection/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/filters/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/digital_image_processing/filters/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/histogram_equalization/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/digital_image_processing/histogram_equalization/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/histogram_equalization/image_data/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/digital_image_processing/histogram_equalization/image_data/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/histogram_equalization/image_data/input.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/digital_image_processing/histogram_equalization/image_data/input.jpg -------------------------------------------------------------------------------- /digital_image_processing/histogram_equalization/output_data/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/digital_image_processing/histogram_equalization/output_data/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/histogram_equalization/output_data/output.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/digital_image_processing/histogram_equalization/output_data/output.jpg -------------------------------------------------------------------------------- /digital_image_processing/image_data/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/digital_image_processing/image_data/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/image_data/lena.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/digital_image_processing/image_data/lena.jpg -------------------------------------------------------------------------------- /digital_image_processing/image_data/lena_small.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/digital_image_processing/image_data/lena_small.jpg -------------------------------------------------------------------------------- /digital_image_processing/resize/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/digital_image_processing/resize/__init__.py -------------------------------------------------------------------------------- /digital_image_processing/rotation/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/digital_image_processing/rotation/__init__.py -------------------------------------------------------------------------------- /divide_and_conquer/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/divide_and_conquer/__init__.py -------------------------------------------------------------------------------- /divide_and_conquer/power.py: -------------------------------------------------------------------------------- 1 | def actual_power(a: int, b: int): 2 | """ 3 | Function using divide and conquer to calculate a^b. 4 | It only works for integer a,b. 5 | """ 6 | if b == 0: 7 | return 1 8 | if (b % 2) == 0: 9 | return actual_power(a, int(b / 2)) * actual_power(a, int(b / 2)) 10 | else: 11 | return a * actual_power(a, int(b / 2)) * actual_power(a, int(b / 2)) 12 | 13 | 14 | def power(a: int, b: int) -> float: 15 | """ 16 | >>> power(4,6) 17 | 4096 18 | >>> power(2,3) 19 | 8 20 | >>> power(-2,3) 21 | -8 22 | >>> power(2,-3) 23 | 0.125 24 | >>> power(-2,-3) 25 | -0.125 26 | """ 27 | if b < 0: 28 | return 1 / actual_power(a, b) 29 | return actual_power(a, b) 30 | 31 | 32 | if __name__ == "__main__": 33 | print(power(-2, -3)) 34 | -------------------------------------------------------------------------------- /dynamic_programming/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/dynamic_programming/__init__.py -------------------------------------------------------------------------------- /dynamic_programming/abbreviation.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://www.hackerrank.com/challenges/abbr/problem 3 | You can perform the following operation on some string, : 4 | 5 | 1. Capitalize zero or more of 's lowercase letters at some index i 6 | (i.e., make them uppercase). 7 | 2. Delete all of the remaining lowercase letters in . 8 | 9 | Example: 10 | a=daBcd and b="ABC" 11 | daBcd -> capitalize a and c(dABCd) -> remove d (ABC) 12 | """ 13 | 14 | 15 | def abbr(a: str, b: str) -> bool: 16 | """ 17 | >>> abbr("daBcd", "ABC") 18 | True 19 | >>> abbr("dBcd", "ABC") 20 | False 21 | """ 22 | n = len(a) 23 | m = len(b) 24 | dp = [[False for _ in range(m + 1)] for _ in range(n + 1)] 25 | dp[0][0] = True 26 | for i in range(n): 27 | for j in range(m + 1): 28 | if dp[i][j]: 29 | if j < m and a[i].upper() == b[j]: 30 | dp[i + 1][j + 1] = True 31 | if a[i].islower(): 32 | dp[i + 1][j] = True 33 | return dp[n][m] 34 | 35 | 36 | if __name__ == "__main__": 37 | import doctest 38 | 39 | doctest.testmod() 40 | -------------------------------------------------------------------------------- /dynamic_programming/climbing_stairs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | 4 | def climb_stairs(n: int) -> int: 5 | """ 6 | LeetCdoe No.70: Climbing Stairs 7 | Distinct ways to climb a n step staircase where 8 | each time you can either climb 1 or 2 steps. 9 | 10 | Args: 11 | n: number of steps of staircase 12 | 13 | Returns: 14 | Distinct ways to climb a n step staircase 15 | 16 | Raises: 17 | AssertionError: n not positive integer 18 | 19 | >>> climb_stairs(3) 20 | 3 21 | >>> climb_stairs(1) 22 | 1 23 | >>> climb_stairs(-7) # doctest: +ELLIPSIS 24 | Traceback (most recent call last): 25 | ... 26 | AssertionError: n needs to be positive integer, your input -7 27 | """ 28 | fmt = "n needs to be positive integer, your input {}" 29 | assert isinstance(n, int) and n > 0, fmt.format(n) 30 | if n == 1: 31 | return 1 32 | dp = [0] * (n + 1) 33 | dp[0], dp[1] = (1, 1) 34 | for i in range(2, n + 1): 35 | dp[i] = dp[i - 1] + dp[i - 2] 36 | return dp[n] 37 | 38 | 39 | if __name__ == "__main__": 40 | import doctest 41 | 42 | doctest.testmod() 43 | -------------------------------------------------------------------------------- /dynamic_programming/coin_change.py: -------------------------------------------------------------------------------- 1 | """ 2 | You have m types of coins available in infinite quantities 3 | where the value of each coins is given in the array S=[S0,... Sm-1] 4 | Can you determine number of ways of making change for n units using 5 | the given types of coins? 6 | https://www.hackerrank.com/challenges/coin-change/problem 7 | """ 8 | 9 | 10 | def dp_count(S, m, n): 11 | """ 12 | >>> dp_count([1, 2, 3], 3, 4) 13 | 4 14 | >>> dp_count([1, 2, 3], 3, 7) 15 | 8 16 | >>> dp_count([2, 5, 3, 6], 4, 10) 17 | 5 18 | >>> dp_count([10], 1, 99) 19 | 0 20 | >>> dp_count([4, 5, 6], 3, 0) 21 | 1 22 | """ 23 | 24 | # table[i] represents the number of ways to get to amount i 25 | table = [0] * (n + 1) 26 | 27 | # There is exactly 1 way to get to zero(You pick no coins). 28 | table[0] = 1 29 | 30 | # Pick all coins one by one and update table[] values 31 | # after the index greater than or equal to the value of the 32 | # picked coin 33 | for coin_val in S: 34 | for j in range(coin_val, n + 1): 35 | table[j] += table[j - coin_val] 36 | 37 | return table[n] 38 | 39 | 40 | if __name__ == "__main__": 41 | import doctest 42 | 43 | doctest.testmod() 44 | -------------------------------------------------------------------------------- /dynamic_programming/factorial.py: -------------------------------------------------------------------------------- 1 | # Factorial of a number using memoization 2 | 3 | from functools import lru_cache 4 | 5 | 6 | @lru_cache 7 | def factorial(num: int) -> int: 8 | """ 9 | >>> factorial(7) 10 | 5040 11 | >>> factorial(-1) 12 | Traceback (most recent call last): 13 | ... 14 | ValueError: Number should not be negative. 15 | >>> [factorial(i) for i in range(10)] 16 | [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] 17 | """ 18 | if num < 0: 19 | raise ValueError("Number should not be negative.") 20 | 21 | return 1 if num in (0, 1) else num * factorial(num - 1) 22 | 23 | 24 | if __name__ == "__main__": 25 | import doctest 26 | 27 | doctest.testmod() 28 | -------------------------------------------------------------------------------- /dynamic_programming/fast_fibonacci.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """ 4 | This program calculates the nth Fibonacci number in O(log(n)). 5 | It's possible to calculate F(1_000_000) in less than a second. 6 | """ 7 | from __future__ import annotations 8 | 9 | import sys 10 | 11 | 12 | def fibonacci(n: int) -> int: 13 | """ 14 | return F(n) 15 | >>> [fibonacci(i) for i in range(13)] 16 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] 17 | """ 18 | if n < 0: 19 | raise ValueError("Negative arguments are not supported") 20 | return _fib(n)[0] 21 | 22 | 23 | # returns (F(n), F(n-1)) 24 | def _fib(n: int) -> tuple[int, int]: 25 | if n == 0: # (F(0), F(1)) 26 | return (0, 1) 27 | 28 | # F(2n) = F(n)[2F(n+1) − F(n)] 29 | # F(2n+1) = F(n+1)^2+F(n)^2 30 | a, b = _fib(n // 2) 31 | c = a * (b * 2 - a) 32 | d = a * a + b * b 33 | return (d, c + d) if n % 2 else (c, d) 34 | 35 | 36 | if __name__ == "__main__": 37 | n = int(sys.argv[1]) 38 | print(f"fibonacci({n}) is {fibonacci(n)}") 39 | -------------------------------------------------------------------------------- /dynamic_programming/fractional_knapsack.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect 2 | from itertools import accumulate 3 | 4 | 5 | def fracKnapsack(vl, wt, W, n): 6 | """ 7 | >>> fracKnapsack([60, 100, 120], [10, 20, 30], 50, 3) 8 | 240.0 9 | """ 10 | 11 | r = list(sorted(zip(vl, wt), key=lambda x: x[0] / x[1], reverse=True)) 12 | vl, wt = [i[0] for i in r], [i[1] for i in r] 13 | acc = list(accumulate(wt)) 14 | k = bisect(acc, W) 15 | return ( 16 | 0 17 | if k == 0 18 | else sum(vl[:k]) + (W - acc[k - 1]) * (vl[k]) / (wt[k]) 19 | if k != n 20 | else sum(vl[:k]) 21 | ) 22 | 23 | 24 | if __name__ == "__main__": 25 | import doctest 26 | 27 | doctest.testmod() 28 | -------------------------------------------------------------------------------- /dynamic_programming/integer_partition.py: -------------------------------------------------------------------------------- 1 | """ 2 | The number of partitions of a number n into at least k parts equals the number of 3 | partitions into exactly k parts plus the number of partitions into at least k-1 parts. 4 | Subtracting 1 from each part of a partition of n into k parts gives a partition of n-k 5 | into k parts. These two facts together are used for this algorithm. 6 | """ 7 | 8 | 9 | def partition(m): 10 | memo = [[0 for _ in range(m)] for _ in range(m + 1)] 11 | for i in range(m + 1): 12 | memo[i][0] = 1 13 | 14 | for n in range(m + 1): 15 | for k in range(1, m): 16 | memo[n][k] += memo[n][k - 1] 17 | if n - k > 0: 18 | memo[n][k] += memo[n - k - 1][k] 19 | 20 | return memo[m][m - 1] 21 | 22 | 23 | if __name__ == "__main__": 24 | import sys 25 | 26 | if len(sys.argv) == 1: 27 | try: 28 | n = int(input("Enter a number: ").strip()) 29 | print(partition(n)) 30 | except ValueError: 31 | print("Please enter a number.") 32 | else: 33 | try: 34 | n = int(sys.argv[1]) 35 | print(partition(n)) 36 | except ValueError: 37 | print("Please pass a number.") 38 | -------------------------------------------------------------------------------- /dynamic_programming/longest_sub_array.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author : Yvonne 3 | 4 | This is a pure Python implementation of Dynamic Programming solution to the 5 | longest_sub_array problem. 6 | 7 | The problem is : 8 | Given an array, to find the longest and continuous sub array and get the max sum of the 9 | sub array in the given array. 10 | """ 11 | 12 | 13 | class SubArray: 14 | def __init__(self, arr): 15 | # we need a list not a string, so do something to change the type 16 | self.array = arr.split(",") 17 | print(("the input array is:", self.array)) 18 | 19 | def solve_sub_array(self): 20 | rear = [int(self.array[0])] * len(self.array) 21 | sum_value = [int(self.array[0])] * len(self.array) 22 | for i in range(1, len(self.array)): 23 | sum_value[i] = max( 24 | int(self.array[i]) + sum_value[i - 1], int(self.array[i]) 25 | ) 26 | rear[i] = max(sum_value[i], rear[i - 1]) 27 | return rear[len(self.array) - 1] 28 | 29 | 30 | if __name__ == "__main__": 31 | whole_array = input("please input some numbers:") 32 | array = SubArray(whole_array) 33 | re = array.solve_sub_array() 34 | print(("the results is:", re)) 35 | -------------------------------------------------------------------------------- /dynamic_programming/max_non_adjacent_sum.py: -------------------------------------------------------------------------------- 1 | # Video Explanation: https://www.youtube.com/watch?v=6w60Zi1NtL8&feature=emb_logo 2 | 3 | from __future__ import annotations 4 | 5 | 6 | def maximum_non_adjacent_sum(nums: list[int]) -> int: 7 | """ 8 | Find the maximum non-adjacent sum of the integers in the nums input list 9 | 10 | >>> print(maximum_non_adjacent_sum([1, 2, 3])) 11 | 4 12 | >>> maximum_non_adjacent_sum([1, 5, 3, 7, 2, 2, 6]) 13 | 18 14 | >>> maximum_non_adjacent_sum([-1, -5, -3, -7, -2, -2, -6]) 15 | 0 16 | >>> maximum_non_adjacent_sum([499, 500, -3, -7, -2, -2, -6]) 17 | 500 18 | """ 19 | if not nums: 20 | return 0 21 | max_including = nums[0] 22 | max_excluding = 0 23 | for num in nums[1:]: 24 | max_including, max_excluding = ( 25 | max_excluding + num, 26 | max(max_including, max_excluding), 27 | ) 28 | return max(max_excluding, max_including) 29 | 30 | 31 | if __name__ == "__main__": 32 | import doctest 33 | 34 | doctest.testmod() 35 | -------------------------------------------------------------------------------- /dynamic_programming/max_sum_contiguous_subsequence.py: -------------------------------------------------------------------------------- 1 | def max_subarray_sum(nums: list) -> int: 2 | """ 3 | >>> max_subarray_sum([6 , 9, -1, 3, -7, -5, 10]) 4 | 17 5 | """ 6 | if not nums: 7 | return 0 8 | n = len(nums) 9 | 10 | res, s, s_pre = nums[0], nums[0], nums[0] 11 | for i in range(1, n): 12 | s = max(nums[i], s_pre + nums[i]) 13 | s_pre = s 14 | res = max(res, s) 15 | return res 16 | 17 | 18 | if __name__ == "__main__": 19 | nums = [6, 9, -1, 3, -7, -5, 10] 20 | print(max_subarray_sum(nums)) 21 | -------------------------------------------------------------------------------- /dynamic_programming/minimum_cost_path.py: -------------------------------------------------------------------------------- 1 | # Youtube Explanation: https://www.youtube.com/watch?v=lBRtnuxg-gU 2 | 3 | from __future__ import annotations 4 | 5 | 6 | def minimum_cost_path(matrix: list[list[int]]) -> int: 7 | """ 8 | Find the minimum cost traced by all possible paths from top left to bottom right in 9 | a given matrix 10 | 11 | >>> minimum_cost_path([[2, 1], [3, 1], [4, 2]]) 12 | 6 13 | 14 | >>> minimum_cost_path([[2, 1, 4], [2, 1, 3], [3, 2, 1]]) 15 | 7 16 | """ 17 | 18 | # preprocessing the first row 19 | for i in range(1, len(matrix[0])): 20 | matrix[0][i] += matrix[0][i - 1] 21 | 22 | # preprocessing the first column 23 | for i in range(1, len(matrix)): 24 | matrix[i][0] += matrix[i - 1][0] 25 | 26 | # updating the path cost for current position 27 | for i in range(1, len(matrix)): 28 | for j in range(1, len(matrix[0])): 29 | matrix[i][j] += min(matrix[i - 1][j], matrix[i][j - 1]) 30 | 31 | return matrix[-1][-1] 32 | 33 | 34 | if __name__ == "__main__": 35 | import doctest 36 | 37 | doctest.testmod() 38 | -------------------------------------------------------------------------------- /dynamic_programming/minimum_partition.py: -------------------------------------------------------------------------------- 1 | """ 2 | Partition a set into two subsets such that the difference of subset sums is minimum 3 | """ 4 | 5 | 6 | def findMin(arr): 7 | n = len(arr) 8 | s = sum(arr) 9 | 10 | dp = [[False for x in range(s + 1)] for y in range(n + 1)] 11 | 12 | for i in range(1, n + 1): 13 | dp[i][0] = True 14 | 15 | for i in range(1, s + 1): 16 | dp[0][i] = False 17 | 18 | for i in range(1, n + 1): 19 | for j in range(1, s + 1): 20 | dp[i][j] = dp[i][j - 1] 21 | 22 | if arr[i - 1] <= j: 23 | dp[i][j] = dp[i][j] or dp[i - 1][j - arr[i - 1]] 24 | 25 | for j in range(int(s / 2), -1, -1): 26 | if dp[n][j] is True: 27 | diff = s - 2 * j 28 | break 29 | 30 | return diff 31 | -------------------------------------------------------------------------------- /file_transfer/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/file_transfer/__init__.py -------------------------------------------------------------------------------- /file_transfer/mytext.txt: -------------------------------------------------------------------------------- 1 | Hello 2 | This is sample data 3 | «küßî» 4 | “ЌύБЇ” 5 | 😀😉 6 | 😋 7 | -------------------------------------------------------------------------------- /file_transfer/receive_file.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | import socket # Import socket module 3 | 4 | sock = socket.socket() # Create a socket object 5 | host = socket.gethostname() # Get local machine name 6 | port = 12312 7 | 8 | sock.connect((host, port)) 9 | sock.send(b"Hello server!") 10 | 11 | with open("Received_file", "wb") as out_file: 12 | print("File opened") 13 | print("Receiving data...") 14 | while True: 15 | data = sock.recv(1024) 16 | print(f"data={data}") 17 | if not data: 18 | break 19 | out_file.write(data) # Write data to a file 20 | 21 | print("Successfully got the file") 22 | sock.close() 23 | print("Connection closed") 24 | -------------------------------------------------------------------------------- /file_transfer/send_file.py: -------------------------------------------------------------------------------- 1 | def send_file(filename: str = "mytext.txt", testing: bool = False) -> None: 2 | import socket 3 | 4 | port = 12312 # Reserve a port for your service. 5 | sock = socket.socket() # Create a socket object 6 | host = socket.gethostname() # Get local machine name 7 | sock.bind((host, port)) # Bind to the port 8 | sock.listen(5) # Now wait for client connection. 9 | 10 | print("Server listening....") 11 | 12 | while True: 13 | conn, addr = sock.accept() # Establish connection with client. 14 | print(f"Got connection from {addr}") 15 | data = conn.recv(1024) 16 | print(f"Server received {data}") 17 | 18 | with open(filename, "rb") as in_file: 19 | data = in_file.read(1024) 20 | while data: 21 | conn.send(data) 22 | print(f"Sent {data!r}") 23 | data = in_file.read(1024) 24 | 25 | print("Done sending") 26 | conn.close() 27 | if testing: # Allow the test to complete 28 | break 29 | 30 | sock.shutdown(1) 31 | sock.close() 32 | 33 | 34 | if __name__ == "__main__": 35 | send_file() 36 | -------------------------------------------------------------------------------- /file_transfer/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/file_transfer/tests/__init__.py -------------------------------------------------------------------------------- /file_transfer/tests/test_send_file.py: -------------------------------------------------------------------------------- 1 | from unittest.mock import Mock, patch 2 | 3 | from file_transfer.send_file import send_file 4 | 5 | 6 | @patch("socket.socket") 7 | @patch("builtins.open") 8 | def test_send_file_running_as_expected(file, sock): 9 | # ===== initialization ===== 10 | conn = Mock() 11 | sock.return_value.accept.return_value = conn, Mock() 12 | f = iter([1, None]) 13 | file.return_value.__enter__.return_value.read.side_effect = lambda _: next(f) 14 | 15 | # ===== invoke ===== 16 | send_file(filename="mytext.txt", testing=True) 17 | 18 | # ===== ensurance ===== 19 | sock.assert_called_once() 20 | sock.return_value.bind.assert_called_once() 21 | sock.return_value.listen.assert_called_once() 22 | sock.return_value.accept.assert_called_once() 23 | conn.recv.assert_called_once() 24 | 25 | file.return_value.__enter__.assert_called_once() 26 | file.return_value.__enter__.return_value.read.assert_called() 27 | 28 | conn.send.assert_called_once() 29 | conn.close.assert_called_once() 30 | sock.return_value.shutdown.assert_called_once() 31 | sock.return_value.close.assert_called_once() 32 | -------------------------------------------------------------------------------- /fuzzy_logic/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/fuzzy_logic/__init__.py -------------------------------------------------------------------------------- /genetic_algorithm/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/genetic_algorithm/__init__.py -------------------------------------------------------------------------------- /geodesy/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/geodesy/__init__.py -------------------------------------------------------------------------------- /graphics/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/graphics/__init__.py -------------------------------------------------------------------------------- /graphs/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/graphs/__init__.py -------------------------------------------------------------------------------- /graphs/check_bipartite_graph_dfs.py: -------------------------------------------------------------------------------- 1 | # Check whether Graph is Bipartite or Not using DFS 2 | 3 | 4 | # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, 5 | # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex 6 | # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, 7 | # or u belongs to V and v to U. We can also say that there is no edge that connects 8 | # vertices of same set. 9 | def check_bipartite_dfs(graph): 10 | visited = [False] * len(graph) 11 | color = [-1] * len(graph) 12 | 13 | def dfs(v, c): 14 | visited[v] = True 15 | color[v] = c 16 | for u in graph[v]: 17 | if not visited[u]: 18 | dfs(u, 1 - c) 19 | 20 | for i in range(len(graph)): 21 | if not visited[i]: 22 | dfs(i, 0) 23 | 24 | for i in range(len(graph)): 25 | for j in graph[i]: 26 | if color[i] == color[j]: 27 | return False 28 | 29 | return True 30 | 31 | 32 | # Adjacency list of graph 33 | graph = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} 34 | print(check_bipartite_dfs(graph)) 35 | -------------------------------------------------------------------------------- /graphs/finding_bridges.py: -------------------------------------------------------------------------------- 1 | # Finding Bridges in Undirected Graph 2 | def computeBridges(graph): 3 | id = 0 4 | n = len(graph) # No of vertices in graph 5 | low = [0] * n 6 | visited = [False] * n 7 | 8 | def dfs(at, parent, bridges, id): 9 | visited[at] = True 10 | low[at] = id 11 | id += 1 12 | for to in graph[at]: 13 | if to == parent: 14 | pass 15 | elif not visited[to]: 16 | dfs(to, at, bridges, id) 17 | low[at] = min(low[at], low[to]) 18 | if at < low[to]: 19 | bridges.append([at, to]) 20 | else: 21 | # This edge is a back edge and cannot be a bridge 22 | low[at] = min(low[at], to) 23 | 24 | bridges = [] 25 | for i in range(n): 26 | if not visited[i]: 27 | dfs(i, -1, bridges, id) 28 | print(bridges) 29 | 30 | 31 | graph = { 32 | 0: [1, 2], 33 | 1: [0, 2], 34 | 2: [0, 1, 3, 5], 35 | 3: [2, 4], 36 | 4: [3], 37 | 5: [2, 6, 8], 38 | 6: [5, 7], 39 | 7: [6, 8], 40 | 8: [5, 7], 41 | } 42 | computeBridges(graph) 43 | -------------------------------------------------------------------------------- /graphs/g_topological_sort.py: -------------------------------------------------------------------------------- 1 | # Author: Phyllipe Bezerra (https://github.com/pmba) 2 | 3 | clothes = { 4 | 0: "underwear", 5 | 1: "pants", 6 | 2: "belt", 7 | 3: "suit", 8 | 4: "shoe", 9 | 5: "socks", 10 | 6: "shirt", 11 | 7: "tie", 12 | 8: "watch", 13 | } 14 | 15 | graph = [[1, 4], [2, 4], [3], [], [], [4], [2, 7], [3], []] 16 | 17 | visited = [0 for x in range(len(graph))] 18 | stack = [] 19 | 20 | 21 | def print_stack(stack, clothes): 22 | order = 1 23 | while stack: 24 | current_clothing = stack.pop() 25 | print(order, clothes[current_clothing]) 26 | order += 1 27 | 28 | 29 | def depth_first_search(u, visited, graph): 30 | visited[u] = 1 31 | for v in graph[u]: 32 | if not visited[v]: 33 | depth_first_search(v, visited, graph) 34 | 35 | stack.append(u) 36 | 37 | 38 | def topological_sort(graph, visited): 39 | for v in range(len(graph)): 40 | if not visited[v]: 41 | depth_first_search(v, visited, graph) 42 | 43 | 44 | if __name__ == "__main__": 45 | topological_sort(graph, visited) 46 | print(stack) 47 | print_stack(stack, clothes) 48 | -------------------------------------------------------------------------------- /graphs/graph_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | # Author: OMKAR PATHAK 4 | 5 | # We can use Python's dictionary for constructing the graph. 6 | 7 | 8 | class AdjacencyList: 9 | def __init__(self): 10 | self.List = {} 11 | 12 | def addEdge(self, fromVertex, toVertex): 13 | # check if vertex is already present 14 | if fromVertex in self.List.keys(): 15 | self.List[fromVertex].append(toVertex) 16 | else: 17 | self.List[fromVertex] = [toVertex] 18 | 19 | def printList(self): 20 | for i in self.List: 21 | print((i, "->", " -> ".join([str(j) for j in self.List[i]]))) 22 | 23 | 24 | if __name__ == "__main__": 25 | al = AdjacencyList() 26 | al.addEdge(0, 1) 27 | al.addEdge(0, 4) 28 | al.addEdge(4, 1) 29 | al.addEdge(4, 3) 30 | al.addEdge(1, 0) 31 | al.addEdge(1, 4) 32 | al.addEdge(1, 3) 33 | al.addEdge(1, 2) 34 | al.addEdge(2, 3) 35 | al.addEdge(3, 4) 36 | 37 | al.printList() 38 | 39 | # OUTPUT: 40 | # 0 -> 1 -> 4 41 | # 1 -> 0 -> 4 -> 3 -> 2 42 | # 2 -> 3 43 | # 3 -> 4 44 | # 4 -> 1 -> 3 45 | -------------------------------------------------------------------------------- /graphs/graph_matrix.py: -------------------------------------------------------------------------------- 1 | class Graph: 2 | def __init__(self, vertex): 3 | self.vertex = vertex 4 | self.graph = [[0] * vertex for i in range(vertex)] 5 | 6 | def add_edge(self, u, v): 7 | self.graph[u - 1][v - 1] = 1 8 | self.graph[v - 1][u - 1] = 1 9 | 10 | def show(self): 11 | 12 | for i in self.graph: 13 | for j in i: 14 | print(j, end=" ") 15 | print(" ") 16 | 17 | 18 | g = Graph(100) 19 | 20 | g.add_edge(1, 4) 21 | g.add_edge(4, 2) 22 | g.add_edge(4, 5) 23 | g.add_edge(2, 5) 24 | g.add_edge(5, 3) 25 | g.show() 26 | -------------------------------------------------------------------------------- /graphs/kahns_algorithm_long.py: -------------------------------------------------------------------------------- 1 | # Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm 2 | def longestDistance(graph): 3 | indegree = [0] * len(graph) 4 | queue = [] 5 | longDist = [1] * len(graph) 6 | 7 | for key, values in graph.items(): 8 | for i in values: 9 | indegree[i] += 1 10 | 11 | for i in range(len(indegree)): 12 | if indegree[i] == 0: 13 | queue.append(i) 14 | 15 | while queue: 16 | vertex = queue.pop(0) 17 | for x in graph[vertex]: 18 | indegree[x] -= 1 19 | 20 | if longDist[vertex] + 1 > longDist[x]: 21 | longDist[x] = longDist[vertex] + 1 22 | 23 | if indegree[x] == 0: 24 | queue.append(x) 25 | 26 | print(max(longDist)) 27 | 28 | 29 | # Adjacency list of Graph 30 | graph = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} 31 | longestDistance(graph) 32 | -------------------------------------------------------------------------------- /graphs/kahns_algorithm_topo.py: -------------------------------------------------------------------------------- 1 | def topologicalSort(graph): 2 | """ 3 | Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph 4 | using BFS 5 | """ 6 | indegree = [0] * len(graph) 7 | queue = [] 8 | topo = [] 9 | cnt = 0 10 | 11 | for key, values in graph.items(): 12 | for i in values: 13 | indegree[i] += 1 14 | 15 | for i in range(len(indegree)): 16 | if indegree[i] == 0: 17 | queue.append(i) 18 | 19 | while queue: 20 | vertex = queue.pop(0) 21 | cnt += 1 22 | topo.append(vertex) 23 | for x in graph[vertex]: 24 | indegree[x] -= 1 25 | if indegree[x] == 0: 26 | queue.append(x) 27 | 28 | if cnt != len(graph): 29 | print("Cycle exists") 30 | else: 31 | print(topo) 32 | 33 | 34 | # Adjacency List of Graph 35 | graph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} 36 | topologicalSort(graph) 37 | -------------------------------------------------------------------------------- /graphs/minimum_spanning_tree_kruskal.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | num_nodes, num_edges = list(map(int, input().strip().split())) 3 | 4 | edges = [] 5 | 6 | for i in range(num_edges): 7 | node1, node2, cost = list(map(int, input().strip().split())) 8 | edges.append((i, node1, node2, cost)) 9 | 10 | edges = sorted(edges, key=lambda edge: edge[3]) 11 | 12 | parent = list(range(num_nodes)) 13 | 14 | def find_parent(i): 15 | if i != parent[i]: 16 | parent[i] = find_parent(parent[i]) 17 | return parent[i] 18 | 19 | minimum_spanning_tree_cost = 0 20 | minimum_spanning_tree = [] 21 | 22 | for edge in edges: 23 | parent_a = find_parent(edge[1]) 24 | parent_b = find_parent(edge[2]) 25 | if parent_a != parent_b: 26 | minimum_spanning_tree_cost += edge[3] 27 | minimum_spanning_tree.append(edge) 28 | parent[parent_a] = parent_b 29 | 30 | print(minimum_spanning_tree_cost) 31 | for edge in minimum_spanning_tree: 32 | print(edge) 33 | -------------------------------------------------------------------------------- /greedy_method/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/greedy_method/__init__.py -------------------------------------------------------------------------------- /hashes/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/hashes/__init__.py -------------------------------------------------------------------------------- /hashes/adler32.py: -------------------------------------------------------------------------------- 1 | """ 2 | Adler-32 is a checksum algorithm which was invented by Mark Adler in 1995. 3 | Compared to a cyclic redundancy check of the same length, it trades reliability for 4 | speed (preferring the latter). 5 | Adler-32 is more reliable than Fletcher-16, and slightly less reliable than 6 | Fletcher-32.[2] 7 | 8 | source: https://en.wikipedia.org/wiki/Adler-32 9 | """ 10 | 11 | 12 | def adler32(plain_text: str) -> str: 13 | """ 14 | Function implements adler-32 hash. 15 | Itterates and evaluates new value for each character 16 | 17 | >>> adler32('Algorithms') 18 | 363791387 19 | 20 | >>> adler32('go adler em all') 21 | 708642122 22 | """ 23 | MOD_ADLER = 65521 24 | a = 1 25 | b = 0 26 | for plain_chr in plain_text: 27 | a = (a + ord(plain_chr)) % MOD_ADLER 28 | b = (b + a) % MOD_ADLER 29 | return (b << 16) | a 30 | -------------------------------------------------------------------------------- /hashes/djb2.py: -------------------------------------------------------------------------------- 1 | """ 2 | This algorithm (k=33) was first reported by Dan Bernstein many years ago in comp.lang.c 3 | Another version of this algorithm (now favored by Bernstein) uses xor: 4 | hash(i) = hash(i - 1) * 33 ^ str[i]; 5 | 6 | First Magic constant 33: 7 | It has never been adequately explained. 8 | It's magic because it works better than many other constants, prime or not. 9 | 10 | Second Magic Constant 5381: 11 | 12 | 1. odd number 13 | 2. prime number 14 | 3. deficient number 15 | 4. 001/010/100/000/101 b 16 | 17 | source: http://www.cse.yorku.ca/~oz/hash.html 18 | """ 19 | 20 | 21 | def djb2(s: str) -> int: 22 | """ 23 | Implementation of djb2 hash algorithm that 24 | is popular because of it's magic constants. 25 | 26 | >>> djb2('Algorithms') 27 | 3782405311 28 | 29 | >>> djb2('scramble bits') 30 | 1609059040 31 | """ 32 | hash = 5381 33 | for x in s: 34 | hash = ((hash << 5) + hash) + ord(x) 35 | return hash & 0xFFFFFFFF 36 | -------------------------------------------------------------------------------- /images/Travis_CI_fail_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/images/Travis_CI_fail_1.png -------------------------------------------------------------------------------- /images/Travis_CI_fail_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/images/Travis_CI_fail_2.png -------------------------------------------------------------------------------- /images/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/images/__init__.py -------------------------------------------------------------------------------- /linear_algebra/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/linear_algebra/__init__.py -------------------------------------------------------------------------------- /linear_algebra/src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/linear_algebra/src/__init__.py -------------------------------------------------------------------------------- /machine_learning/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/machine_learning/__init__.py -------------------------------------------------------------------------------- /machine_learning/knn_sklearn.py: -------------------------------------------------------------------------------- 1 | from sklearn.datasets import load_iris 2 | from sklearn.model_selection import train_test_split 3 | from sklearn.neighbors import KNeighborsClassifier 4 | 5 | # Load iris file 6 | iris = load_iris() 7 | iris.keys() 8 | 9 | 10 | print(f"Target names: \n {iris.target_names} ") 11 | print(f"\n Features: \n {iris.feature_names}") 12 | 13 | # Train set e Test set 14 | X_train, X_test, y_train, y_test = train_test_split( 15 | iris["data"], iris["target"], random_state=4 16 | ) 17 | 18 | # KNN 19 | 20 | knn = KNeighborsClassifier(n_neighbors=1) 21 | knn.fit(X_train, y_train) 22 | 23 | # new array to test 24 | X_new = [[1, 2, 1, 4], [2, 3, 4, 5]] 25 | 26 | prediction = knn.predict(X_new) 27 | 28 | print( 29 | "\nNew array: \n {}" 30 | "\n\nTarget Names Prediction: \n {}".format(X_new, iris["target_names"][prediction]) 31 | ) 32 | -------------------------------------------------------------------------------- /machine_learning/lstm/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/machine_learning/lstm/__init__.py -------------------------------------------------------------------------------- /machine_learning/multilayer_perceptron_classifier.py: -------------------------------------------------------------------------------- 1 | from sklearn.neural_network import MLPClassifier 2 | 3 | X = [[0.0, 0.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0]] 4 | y = [0, 1, 0, 0] 5 | 6 | 7 | clf = MLPClassifier( 8 | solver="lbfgs", alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1 9 | ) 10 | 11 | clf.fit(X, y) 12 | 13 | 14 | test = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0]] 15 | Y = clf.predict(test) 16 | 17 | 18 | def wrapper(Y): 19 | """ 20 | >>> wrapper(Y) 21 | [0, 0, 1] 22 | """ 23 | return list(Y) 24 | 25 | 26 | if __name__ == "__main__": 27 | import doctest 28 | 29 | doctest.testmod() 30 | -------------------------------------------------------------------------------- /maths/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/maths/__init__.py -------------------------------------------------------------------------------- /maths/abs.py: -------------------------------------------------------------------------------- 1 | """Absolute Value.""" 2 | 3 | 4 | def abs_val(num): 5 | """ 6 | Find the absolute value of a number. 7 | 8 | >>> abs_val(-5.1) 9 | 5.1 10 | >>> abs_val(-5) == abs_val(5) 11 | True 12 | >>> abs_val(0) 13 | 0 14 | """ 15 | return -num if num < 0 else num 16 | 17 | 18 | def test_abs_val(): 19 | """ 20 | >>> test_abs_val() 21 | """ 22 | assert 0 == abs_val(0) 23 | assert 34 == abs_val(34) 24 | assert 100000000000 == abs_val(-100000000000) 25 | 26 | 27 | if __name__ == "__main__": 28 | print(abs_val(-34)) # --> 34 29 | -------------------------------------------------------------------------------- /maths/abs_max.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | 4 | def abs_max(x: list[int]) -> int: 5 | """ 6 | >>> abs_max([0,5,1,11]) 7 | 11 8 | >>> abs_max([3,-10,-2]) 9 | -10 10 | """ 11 | j = x[0] 12 | for i in x: 13 | if abs(i) > abs(j): 14 | j = i 15 | return j 16 | 17 | 18 | def abs_max_sort(x): 19 | """ 20 | >>> abs_max_sort([0,5,1,11]) 21 | 11 22 | >>> abs_max_sort([3,-10,-2]) 23 | -10 24 | """ 25 | return sorted(x, key=abs)[-1] 26 | 27 | 28 | def main(): 29 | a = [1, 2, -11] 30 | assert abs_max(a) == -11 31 | assert abs_max_sort(a) == -11 32 | 33 | 34 | if __name__ == "__main__": 35 | main() 36 | -------------------------------------------------------------------------------- /maths/abs_min.py: -------------------------------------------------------------------------------- 1 | from .abs import abs_val 2 | 3 | 4 | def absMin(x): 5 | """ 6 | >>> absMin([0,5,1,11]) 7 | 0 8 | >>> absMin([3,-10,-2]) 9 | -2 10 | """ 11 | j = x[0] 12 | for i in x: 13 | if abs_val(i) < abs_val(j): 14 | j = i 15 | return j 16 | 17 | 18 | def main(): 19 | a = [-3, -1, 2, -11] 20 | print(absMin(a)) # = -1 21 | 22 | 23 | if __name__ == "__main__": 24 | main() 25 | -------------------------------------------------------------------------------- /maths/add.py: -------------------------------------------------------------------------------- 1 | """ 2 | Just to check 3 | """ 4 | 5 | 6 | def add(a, b): 7 | """ 8 | >>> add(2, 2) 9 | 4 10 | >>> add(2, -2) 11 | 0 12 | """ 13 | return a + b 14 | 15 | 16 | if __name__ == "__main__": 17 | a = 5 18 | b = 6 19 | print(f"The sum of {a} + {b} is {add(a, b)}") 20 | -------------------------------------------------------------------------------- /maths/average_mean.py: -------------------------------------------------------------------------------- 1 | """Find mean of a list of numbers.""" 2 | 3 | 4 | def average(nums): 5 | """Find mean of a list of numbers.""" 6 | return sum(nums) / len(nums) 7 | 8 | 9 | def test_average(): 10 | """ 11 | >>> test_average() 12 | """ 13 | assert 12.0 == average([3, 6, 9, 12, 15, 18, 21]) 14 | assert 20 == average([5, 10, 15, 20, 25, 30, 35]) 15 | assert 4.5 == average([1, 2, 3, 4, 5, 6, 7, 8]) 16 | 17 | 18 | if __name__ == "__main__": 19 | """Call average module to find mean of a specific list of numbers.""" 20 | print(average([2, 4, 6, 8, 20, 50, 70])) 21 | -------------------------------------------------------------------------------- /maths/average_median.py: -------------------------------------------------------------------------------- 1 | def median(nums): 2 | """ 3 | Find median of a list of numbers. 4 | 5 | >>> median([0]) 6 | 0 7 | >>> median([4,1,3,2]) 8 | 2.5 9 | >>> median([2, 70, 6, 50, 20, 8, 4]) 10 | 8 11 | 12 | Args: 13 | nums: List of nums 14 | 15 | Returns: 16 | Median. 17 | """ 18 | sorted_list = sorted(nums) 19 | length = len(sorted_list) 20 | mid_index = length >> 1 21 | return ( 22 | (sorted_list[mid_index] + sorted_list[mid_index - 1]) / 2 23 | if length % 2 == 0 24 | else sorted_list[mid_index] 25 | ) 26 | 27 | 28 | def main(): 29 | import doctest 30 | 31 | doctest.testmod() 32 | 33 | 34 | if __name__ == "__main__": 35 | main() 36 | -------------------------------------------------------------------------------- /maths/average_mode.py: -------------------------------------------------------------------------------- 1 | import statistics 2 | 3 | 4 | def mode(input_list): # Defining function "mode." 5 | """This function returns the mode(Mode as in the measures of 6 | central tendency) of the input data. 7 | 8 | The input list may contain any Datastructure or any Datatype. 9 | 10 | >>> input_list = [2, 3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 2, 2, 2] 11 | >>> mode(input_list) 12 | 2 13 | >>> input_list = [2, 3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 2, 2, 2] 14 | >>> mode(input_list) == statistics.mode(input_list) 15 | True 16 | """ 17 | # Copying input_list to check with the index number later. 18 | check_list = input_list.copy() 19 | result = list() # Empty list to store the counts of elements in input_list 20 | for x in input_list: 21 | result.append(input_list.count(x)) 22 | input_list.remove(x) 23 | y = max(result) # Gets the maximum value in the result list. 24 | # Returns the value with the maximum number of repetitions. 25 | return check_list[result.index(y)] 26 | 27 | 28 | if __name__ == "__main__": 29 | data = [2, 3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 2, 2, 2] 30 | print(mode(data)) 31 | print(statistics.mode(data)) 32 | -------------------------------------------------------------------------------- /maths/binary_exp_mod.py: -------------------------------------------------------------------------------- 1 | def bin_exp_mod(a, n, b): 2 | """ 3 | >>> bin_exp_mod(3, 4, 5) 4 | 1 5 | >>> bin_exp_mod(7, 13, 10) 6 | 7 7 | """ 8 | # mod b 9 | assert not (b == 0), "This cannot accept modulo that is == 0" 10 | if n == 0: 11 | return 1 12 | 13 | if n % 2 == 1: 14 | return (bin_exp_mod(a, n - 1, b) * a) % b 15 | 16 | r = bin_exp_mod(a, n / 2, b) 17 | return (r * r) % b 18 | 19 | 20 | if __name__ == "__main__": 21 | try: 22 | BASE = int(input("Enter Base : ").strip()) 23 | POWER = int(input("Enter Power : ").strip()) 24 | MODULO = int(input("Enter Modulo : ").strip()) 25 | except ValueError: 26 | print("Invalid literal for integer") 27 | 28 | print(bin_exp_mod(BASE, POWER, MODULO)) 29 | -------------------------------------------------------------------------------- /maths/binary_exponentiation.py: -------------------------------------------------------------------------------- 1 | """Binary Exponentiation.""" 2 | 3 | # Author : Junth Basnet 4 | # Time Complexity : O(logn) 5 | 6 | 7 | def binary_exponentiation(a, n): 8 | 9 | if n == 0: 10 | return 1 11 | 12 | elif n % 2 == 1: 13 | return binary_exponentiation(a, n - 1) * a 14 | 15 | else: 16 | b = binary_exponentiation(a, n / 2) 17 | return b * b 18 | 19 | 20 | if __name__ == "__main__": 21 | try: 22 | BASE = int(input("Enter Base : ").strip()) 23 | POWER = int(input("Enter Power : ").strip()) 24 | except ValueError: 25 | print("Invalid literal for integer") 26 | 27 | RESULT = binary_exponentiation(BASE, POWER) 28 | print(f"{BASE}^({POWER}) : {RESULT}") 29 | -------------------------------------------------------------------------------- /maths/binomial_coefficient.py: -------------------------------------------------------------------------------- 1 | def binomial_coefficient(n, r): 2 | """ 3 | Find binomial coefficient using pascals triangle. 4 | 5 | >>> binomial_coefficient(10, 5) 6 | 252 7 | """ 8 | C = [0 for i in range(r + 1)] 9 | # nc0 = 1 10 | C[0] = 1 11 | for i in range(1, n + 1): 12 | # to compute current row from previous row. 13 | j = min(i, r) 14 | while j > 0: 15 | C[j] += C[j - 1] 16 | j -= 1 17 | return C[r] 18 | 19 | 20 | print(binomial_coefficient(n=10, r=5)) 21 | -------------------------------------------------------------------------------- /maths/ceil.py: -------------------------------------------------------------------------------- 1 | def ceil(x) -> int: 2 | """ 3 | Return the ceiling of x as an Integral. 4 | 5 | :param x: the number 6 | :return: the smallest integer >= x. 7 | 8 | >>> import math 9 | >>> all(ceil(n) == math.ceil(n) for n 10 | ... in (1, -1, 0, -0, 1.1, -1.1, 1.0, -1.0, 1_000_000_000)) 11 | True 12 | """ 13 | return ( 14 | x if isinstance(x, int) or x - int(x) == 0 else int(x + 1) if x > 0 else int(x) 15 | ) 16 | 17 | 18 | if __name__ == "__main__": 19 | import doctest 20 | 21 | doctest.testmod() 22 | -------------------------------------------------------------------------------- /maths/combinations.py: -------------------------------------------------------------------------------- 1 | from math import factorial 2 | 3 | 4 | def combinations(n, k): 5 | """ 6 | >>> combinations(10,5) 7 | 252 8 | >>> combinations(6,3) 9 | 20 10 | >>> combinations(20,5) 11 | 15504 12 | """ 13 | return int(factorial(n) / ((factorial(k)) * (factorial(n - k)))) 14 | 15 | 16 | if __name__ == "__main__": 17 | from doctest import testmod 18 | 19 | testmod() 20 | -------------------------------------------------------------------------------- /maths/explicit_euler.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def explicit_euler(ode_func, y0, x0, step_size, x_end): 5 | """ 6 | Calculate numeric solution at each step to an ODE using Euler's Method 7 | 8 | https://en.wikipedia.org/wiki/Euler_method 9 | 10 | Arguments: 11 | ode_func -- The ode as a function of x and y 12 | y0 -- the initial value for y 13 | x0 -- the initial value for x 14 | stepsize -- the increment value for x 15 | x_end -- the end value for x 16 | 17 | >>> # the exact solution is math.exp(x) 18 | >>> def f(x, y): 19 | ... return y 20 | >>> y0 = 1 21 | >>> y = explicit_euler(f, y0, 0.0, 0.01, 5) 22 | >>> y[-1] 23 | 144.77277243257308 24 | """ 25 | N = int(np.ceil((x_end - x0) / step_size)) 26 | y = np.zeros((N + 1,)) 27 | y[0] = y0 28 | x = x0 29 | 30 | for k in range(N): 31 | y[k + 1] = y[k] + step_size * ode_func(x, y[k]) 32 | x += step_size 33 | 34 | return y 35 | 36 | 37 | if __name__ == "__main__": 38 | import doctest 39 | 40 | doctest.testmod() 41 | -------------------------------------------------------------------------------- /maths/factorial_iterative.py: -------------------------------------------------------------------------------- 1 | # factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial 2 | 3 | 4 | def factorial(n: int) -> int: 5 | """ 6 | >>> import math 7 | >>> all(factorial(i) == math.factorial(i) for i in range(20)) 8 | True 9 | >>> factorial(0.1) 10 | Traceback (most recent call last): 11 | ... 12 | ValueError: factorial() only accepts integral values 13 | >>> factorial(-1) 14 | Traceback (most recent call last): 15 | ... 16 | ValueError: factorial() not defined for negative values 17 | """ 18 | if n != int(n): 19 | raise ValueError("factorial() only accepts integral values") 20 | if n < 0: 21 | raise ValueError("factorial() not defined for negative values") 22 | value = 1 23 | for i in range(1, n + 1): 24 | value *= i 25 | return value 26 | 27 | 28 | if __name__ == "__main__": 29 | n = int(input("Enter a positive integer: ").strip() or 0) 30 | print(f"factorial{n} is {factorial(n)}") 31 | -------------------------------------------------------------------------------- /maths/factorial_python.py: -------------------------------------------------------------------------------- 1 | def factorial(input_number: int) -> int: 2 | """ 3 | Calculate the factorial of specified number 4 | 5 | >>> factorial(1) 6 | 1 7 | >>> factorial(6) 8 | 720 9 | >>> factorial(0) 10 | 1 11 | >>> factorial(-1) 12 | Traceback (most recent call last): 13 | ... 14 | ValueError: factorial() not defined for negative values 15 | >>> factorial(0.1) 16 | Traceback (most recent call last): 17 | ... 18 | ValueError: factorial() only accepts integral values 19 | """ 20 | 21 | if input_number < 0: 22 | raise ValueError("factorial() not defined for negative values") 23 | if not isinstance(input_number, int): 24 | raise ValueError("factorial() only accepts integral values") 25 | result = 1 26 | for i in range(1, input_number): 27 | result = result * (i + 1) 28 | return result 29 | 30 | 31 | if __name__ == "__main__": 32 | import doctest 33 | 34 | doctest.testmod() 35 | -------------------------------------------------------------------------------- /maths/factorial_recursive.py: -------------------------------------------------------------------------------- 1 | def factorial(n: int) -> int: 2 | """ 3 | Calculate the factorial of a positive integer 4 | https://en.wikipedia.org/wiki/Factorial 5 | 6 | >>> import math 7 | >>> all(factorial(i) == math.factorial(i) for i in range(20)) 8 | True 9 | >>> factorial(0.1) 10 | Traceback (most recent call last): 11 | ... 12 | ValueError: factorial() only accepts integral values 13 | >>> factorial(-1) 14 | Traceback (most recent call last): 15 | ... 16 | ValueError: factorial() not defined for negative values 17 | """ 18 | if not isinstance(n, int): 19 | raise ValueError("factorial() only accepts integral values") 20 | if n < 0: 21 | raise ValueError("factorial() not defined for negative values") 22 | return 1 if n == 0 or n == 1 else n * factorial(n - 1) 23 | 24 | 25 | if __name__ == "__main__": 26 | import doctest 27 | 28 | doctest.testmod() 29 | -------------------------------------------------------------------------------- /maths/factors.py: -------------------------------------------------------------------------------- 1 | def factors_of_a_number(num: int) -> list: 2 | """ 3 | >>> factors_of_a_number(1) 4 | [1] 5 | >>> factors_of_a_number(5) 6 | [1, 5] 7 | >>> factors_of_a_number(24) 8 | [1, 2, 3, 4, 6, 8, 12, 24] 9 | >>> factors_of_a_number(-24) 10 | [] 11 | """ 12 | return [i for i in range(1, num + 1) if num % i == 0] 13 | 14 | 15 | if __name__ == "__main__": 16 | num = int(input("Enter a number to find its factors: ")) 17 | factors = factors_of_a_number(num) 18 | print(f"{num} has {len(factors)} factors: {', '.join(str(f) for f in factors)}") 19 | -------------------------------------------------------------------------------- /maths/fermat_little_theorem.py: -------------------------------------------------------------------------------- 1 | # Python program to show the usage of Fermat's little theorem in a division 2 | # According to Fermat's little theorem, (a / b) mod p always equals 3 | # a * (b ^ (p - 2)) mod p 4 | # Here we assume that p is a prime number, b divides a, and p doesn't divide b 5 | # Wikipedia reference: https://en.wikipedia.org/wiki/Fermat%27s_little_theorem 6 | 7 | 8 | def binary_exponentiation(a, n, mod): 9 | 10 | if n == 0: 11 | return 1 12 | 13 | elif n % 2 == 1: 14 | return (binary_exponentiation(a, n - 1, mod) * a) % mod 15 | 16 | else: 17 | b = binary_exponentiation(a, n / 2, mod) 18 | return (b * b) % mod 19 | 20 | 21 | # a prime number 22 | p = 701 23 | 24 | a = 1000000000 25 | b = 10 26 | 27 | # using binary exponentiation function, O(log(p)): 28 | print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) 29 | 30 | # using Python operators: 31 | print((a / b) % p == (a * b ** (p - 2)) % p) 32 | -------------------------------------------------------------------------------- /maths/fibonacci_sequence_recursion.py: -------------------------------------------------------------------------------- 1 | # Fibonacci Sequence Using Recursion 2 | 3 | 4 | def recur_fibo(n: int) -> int: 5 | """ 6 | >>> [recur_fibo(i) for i in range(12)] 7 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] 8 | """ 9 | return n if n <= 1 else recur_fibo(n - 1) + recur_fibo(n - 2) 10 | 11 | 12 | def main() -> None: 13 | limit = int(input("How many terms to include in fibonacci series: ")) 14 | if limit > 0: 15 | print(f"The first {limit} terms of the fibonacci series are as follows:") 16 | print([recur_fibo(n) for n in range(limit)]) 17 | else: 18 | print("Please enter a positive integer: ") 19 | 20 | 21 | if __name__ == "__main__": 22 | main() 23 | -------------------------------------------------------------------------------- /maths/find_max.py: -------------------------------------------------------------------------------- 1 | # NguyenU 2 | 3 | 4 | def find_max(nums): 5 | """ 6 | >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): 7 | ... find_max(nums) == max(nums) 8 | True 9 | True 10 | True 11 | True 12 | """ 13 | max_num = nums[0] 14 | for x in nums: 15 | if x > max_num: 16 | max_num = x 17 | return max_num 18 | 19 | 20 | def main(): 21 | print(find_max([2, 4, 9, 7, 19, 94, 5])) # 94 22 | 23 | 24 | if __name__ == "__main__": 25 | main() 26 | -------------------------------------------------------------------------------- /maths/find_max_recursion.py: -------------------------------------------------------------------------------- 1 | # Divide and Conquer algorithm 2 | def find_max(nums, left, right): 3 | """ 4 | find max value in list 5 | :param nums: contains elements 6 | :param left: index of first element 7 | :param right: index of last element 8 | :return: max in nums 9 | 10 | >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] 11 | >>> find_max(nums, 0, len(nums) - 1) == max(nums) 12 | True 13 | """ 14 | if left == right: 15 | return nums[left] 16 | mid = (left + right) >> 1 # the middle 17 | left_max = find_max(nums, left, mid) # find max in range[left, mid] 18 | right_max = find_max(nums, mid + 1, right) # find max in range[mid + 1, right] 19 | 20 | return left_max if left_max >= right_max else right_max 21 | 22 | 23 | if __name__ == "__main__": 24 | nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] 25 | assert find_max(nums, 0, len(nums) - 1) == 10 26 | -------------------------------------------------------------------------------- /maths/find_min.py: -------------------------------------------------------------------------------- 1 | def find_min(nums): 2 | """ 3 | Find Minimum Number in a List 4 | :param nums: contains elements 5 | :return: min number in list 6 | 7 | >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): 8 | ... find_min(nums) == min(nums) 9 | True 10 | True 11 | True 12 | True 13 | """ 14 | min_num = nums[0] 15 | for num in nums: 16 | if min_num > num: 17 | min_num = num 18 | return min_num 19 | 20 | 21 | def main(): 22 | assert find_min([0, 1, 2, 3, 4, 5, -3, 24, -56]) == -56 23 | 24 | 25 | if __name__ == "__main__": 26 | main() 27 | -------------------------------------------------------------------------------- /maths/find_min_recursion.py: -------------------------------------------------------------------------------- 1 | # Divide and Conquer algorithm 2 | def find_min(nums, left, right): 3 | """ 4 | find min value in list 5 | :param nums: contains elements 6 | :param left: index of first element 7 | :param right: index of last element 8 | :return: min in nums 9 | 10 | >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] 11 | >>> find_min(nums, 0, len(nums) - 1) == min(nums) 12 | True 13 | """ 14 | if left == right: 15 | return nums[left] 16 | mid = (left + right) >> 1 # the middle 17 | left_min = find_min(nums, left, mid) # find min in range[left, mid] 18 | right_min = find_min(nums, mid + 1, right) # find min in range[mid + 1, right] 19 | 20 | return left_min if left_min <= right_min else right_min 21 | 22 | 23 | if __name__ == "__main__": 24 | nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] 25 | assert find_min(nums, 0, len(nums) - 1) == 1 26 | -------------------------------------------------------------------------------- /maths/floor.py: -------------------------------------------------------------------------------- 1 | def floor(x) -> int: 2 | """ 3 | Return the floor of x as an Integral. 4 | 5 | :param x: the number 6 | :return: the largest integer <= x. 7 | 8 | >>> import math 9 | >>> all(floor(n) == math.floor(n) for n 10 | ... in (1, -1, 0, -0, 1.1, -1.1, 1.0, -1.0, 1_000_000_000)) 11 | True 12 | """ 13 | return ( 14 | x if isinstance(x, int) or x - int(x) == 0 else int(x) if x > 0 else int(x - 1) 15 | ) 16 | 17 | 18 | if __name__ == "__main__": 19 | import doctest 20 | 21 | doctest.testmod() 22 | -------------------------------------------------------------------------------- /maths/hardy_ramanujanalgo.py: -------------------------------------------------------------------------------- 1 | # This theorem states that the number of prime factors of n 2 | # will be approximately log(log(n)) for most natural numbers n 3 | 4 | import math 5 | 6 | 7 | def exactPrimeFactorCount(n): 8 | """ 9 | >>> exactPrimeFactorCount(51242183) 10 | 3 11 | """ 12 | count = 0 13 | if n % 2 == 0: 14 | count += 1 15 | while n % 2 == 0: 16 | n = int(n / 2) 17 | # the n input value must be odd so that 18 | # we can skip one element (ie i += 2) 19 | 20 | i = 3 21 | 22 | while i <= int(math.sqrt(n)): 23 | if n % i == 0: 24 | count += 1 25 | while n % i == 0: 26 | n = int(n / i) 27 | i = i + 2 28 | 29 | # this condition checks the prime 30 | # number n is greater than 2 31 | 32 | if n > 2: 33 | count += 1 34 | return count 35 | 36 | 37 | if __name__ == "__main__": 38 | n = 51242183 39 | print(f"The number of distinct prime factors is/are {exactPrimeFactorCount(n)}") 40 | print("The value of log(log(n)) is {:.4f}".format(math.log(math.log(n)))) 41 | 42 | """ 43 | The number of distinct prime factors is/are 3 44 | The value of log(log(n)) is 2.8765 45 | """ 46 | -------------------------------------------------------------------------------- /maths/images/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/maths/images/__init__.py -------------------------------------------------------------------------------- /maths/images/gaussian.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/maths/images/gaussian.png -------------------------------------------------------------------------------- /maths/is_square_free.py: -------------------------------------------------------------------------------- 1 | """ 2 | References: wikipedia:square free number 3 | python/black : True 4 | flake8 : True 5 | """ 6 | from __future__ import annotations 7 | 8 | 9 | def is_square_free(factors: list[int]) -> bool: 10 | """ 11 | # doctest: +NORMALIZE_WHITESPACE 12 | This functions takes a list of prime factors as input. 13 | returns True if the factors are square free. 14 | >>> is_square_free([1, 1, 2, 3, 4]) 15 | False 16 | 17 | These are wrong but should return some value 18 | it simply checks for repition in the numbers. 19 | >>> is_square_free([1, 3, 4, 'sd', 0.0]) 20 | True 21 | 22 | >>> is_square_free([1, 0.5, 2, 0.0]) 23 | True 24 | >>> is_square_free([1, 2, 2, 5]) 25 | False 26 | >>> is_square_free('asd') 27 | True 28 | >>> is_square_free(24) 29 | Traceback (most recent call last): 30 | ... 31 | TypeError: 'int' object is not iterable 32 | """ 33 | return len(set(factors)) == len(factors) 34 | 35 | 36 | if __name__ == "__main__": 37 | import doctest 38 | 39 | doctest.testmod() 40 | -------------------------------------------------------------------------------- /maths/karatsuba.py: -------------------------------------------------------------------------------- 1 | """ Multiply two numbers using Karatsuba algorithm """ 2 | 3 | 4 | def karatsuba(a, b): 5 | """ 6 | >>> karatsuba(15463, 23489) == 15463 * 23489 7 | True 8 | >>> karatsuba(3, 9) == 3 * 9 9 | True 10 | """ 11 | if len(str(a)) == 1 or len(str(b)) == 1: 12 | return a * b 13 | else: 14 | m1 = max(len(str(a)), len(str(b))) 15 | m2 = m1 // 2 16 | 17 | a1, a2 = divmod(a, 10 ** m2) 18 | b1, b2 = divmod(b, 10 ** m2) 19 | 20 | x = karatsuba(a2, b2) 21 | y = karatsuba((a1 + a2), (b1 + b2)) 22 | z = karatsuba(a1, b1) 23 | 24 | return (z * 10 ** (2 * m2)) + ((y - z - x) * 10 ** (m2)) + (x) 25 | 26 | 27 | def main(): 28 | print(karatsuba(15463, 23489)) 29 | 30 | 31 | if __name__ == "__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /maths/largest_of_very_large_numbers.py: -------------------------------------------------------------------------------- 1 | # Author: Abhijeeth S 2 | 3 | import math 4 | 5 | 6 | def res(x, y): 7 | if 0 not in (x, y): 8 | # We use the relation x^y = y*log10(x), where 10 is the base. 9 | return y * math.log10(x) 10 | else: 11 | if x == 0: # 0 raised to any number is 0 12 | return 0 13 | elif y == 0: 14 | return 1 # any number raised to 0 is 1 15 | 16 | 17 | if __name__ == "__main__": # Main function 18 | # Read two numbers from input and typecast them to int using map function. 19 | # Here x is the base and y is the power. 20 | prompt = "Enter the base and the power separated by a comma: " 21 | x1, y1 = map(int, input(prompt).split(",")) 22 | x2, y2 = map(int, input(prompt).split(",")) 23 | 24 | # We find the log of each number, using the function res(), which takes two 25 | # arguments. 26 | res1 = res(x1, y1) 27 | res2 = res(x2, y2) 28 | 29 | # We check for the largest number 30 | if res1 > res2: 31 | print("Largest number is", x1, "^", y1) 32 | elif res2 > res1: 33 | print("Largest number is", x2, "^", y2) 34 | else: 35 | print("Both are equal") 36 | -------------------------------------------------------------------------------- /maths/lucas_lehmer_primality_test.py: -------------------------------------------------------------------------------- 1 | """ 2 | In mathematics, the Lucas–Lehmer test (LLT) is a primality test for Mersenne 3 | numbers. https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test 4 | 5 | A Mersenne number is a number that is one less than a power of two. 6 | That is M_p = 2^p - 1 7 | https://en.wikipedia.org/wiki/Mersenne_prime 8 | 9 | The Lucas–Lehmer test is the primality test used by the 10 | Great Internet Mersenne Prime Search (GIMPS) to locate large primes. 11 | """ 12 | 13 | 14 | # Primality test 2^p - 1 15 | # Return true if 2^p - 1 is prime 16 | def lucas_lehmer_test(p: int) -> bool: 17 | """ 18 | >>> lucas_lehmer_test(p=7) 19 | True 20 | 21 | >>> lucas_lehmer_test(p=11) 22 | False 23 | 24 | # M_11 = 2^11 - 1 = 2047 = 23 * 89 25 | """ 26 | 27 | if p < 2: 28 | raise ValueError("p should not be less than 2!") 29 | elif p == 2: 30 | return True 31 | 32 | s = 4 33 | M = (1 << p) - 1 34 | for i in range(p - 2): 35 | s = ((s * s) - 2) % M 36 | return s == 0 37 | 38 | 39 | if __name__ == "__main__": 40 | print(lucas_lehmer_test(7)) 41 | print(lucas_lehmer_test(11)) 42 | -------------------------------------------------------------------------------- /maths/lucas_series.py: -------------------------------------------------------------------------------- 1 | # Lucas Sequence Using Recursion 2 | 3 | 4 | def recur_luc(n): 5 | """ 6 | >>> recur_luc(1) 7 | 1 8 | >>> recur_luc(0) 9 | 2 10 | """ 11 | if n == 1: 12 | return n 13 | if n == 0: 14 | return 2 15 | return recur_luc(n - 1) + recur_luc(n - 2) 16 | 17 | 18 | if __name__ == "__main__": 19 | limit = int(input("How many terms to include in Lucas series:")) 20 | print("Lucas series:") 21 | for i in range(limit): 22 | print(recur_luc(i)) 23 | -------------------------------------------------------------------------------- /maths/mobius_function.py: -------------------------------------------------------------------------------- 1 | """ 2 | References: https://en.wikipedia.org/wiki/M%C3%B6bius_function 3 | References: wikipedia:square free number 4 | python/black : True 5 | flake8 : True 6 | """ 7 | 8 | from maths.is_square_free import is_square_free 9 | from maths.prime_factors import prime_factors 10 | 11 | 12 | def mobius(n: int) -> int: 13 | """ 14 | Mobius function 15 | >>> mobius(24) 16 | 0 17 | >>> mobius(-1) 18 | 1 19 | >>> mobius('asd') 20 | Traceback (most recent call last): 21 | ... 22 | TypeError: '<=' not supported between instances of 'int' and 'str' 23 | >>> mobius(10**400) 24 | 0 25 | >>> mobius(10**-400) 26 | 1 27 | >>> mobius(-1424) 28 | 1 29 | >>> mobius([1, '2', 2.0]) 30 | Traceback (most recent call last): 31 | ... 32 | TypeError: '<=' not supported between instances of 'int' and 'list' 33 | """ 34 | factors = prime_factors(n) 35 | if is_square_free(factors): 36 | return -1 if len(factors) % 2 else 1 37 | return 0 38 | 39 | 40 | if __name__ == "__main__": 41 | import doctest 42 | 43 | doctest.testmod() 44 | -------------------------------------------------------------------------------- /maths/modular_exponential.py: -------------------------------------------------------------------------------- 1 | """ 2 | Modular Exponential. 3 | Modular exponentiation is a type of exponentiation performed over a modulus. 4 | For more explanation, please check 5 | https://en.wikipedia.org/wiki/Modular_exponentiation 6 | """ 7 | 8 | """Calculate Modular Exponential.""" 9 | 10 | 11 | def modular_exponential(base: int, power: int, mod: int): 12 | """ 13 | >>> modular_exponential(5, 0, 10) 14 | 1 15 | >>> modular_exponential(2, 8, 7) 16 | 4 17 | >>> modular_exponential(3, -2, 9) 18 | -1 19 | """ 20 | 21 | if power < 0: 22 | return -1 23 | base %= mod 24 | result = 1 25 | 26 | while power > 0: 27 | if power & 1: 28 | result = (result * base) % mod 29 | power = power >> 1 30 | base = (base * base) % mod 31 | 32 | return result 33 | 34 | 35 | def main(): 36 | """Call Modular Exponential Function.""" 37 | print(modular_exponential(3, 200, 13)) 38 | 39 | 40 | if __name__ == "__main__": 41 | import doctest 42 | 43 | doctest.testmod() 44 | 45 | main() 46 | -------------------------------------------------------------------------------- /maths/perfect_cube.py: -------------------------------------------------------------------------------- 1 | def perfect_cube(n: int) -> bool: 2 | """ 3 | Check if a number is a perfect cube or not. 4 | 5 | >>> perfect_cube(27) 6 | True 7 | >>> perfect_cube(4) 8 | False 9 | """ 10 | val = n ** (1 / 3) 11 | return (val * val * val) == n 12 | 13 | 14 | if __name__ == "__main__": 15 | print(perfect_cube(27)) 16 | print(perfect_cube(4)) 17 | -------------------------------------------------------------------------------- /maths/perfect_number.py: -------------------------------------------------------------------------------- 1 | """ 2 | == Perfect Number == 3 | In number theory, a perfect number is a positive integer that is equal to the sum of 4 | its positive divisors, excluding the number itself. 5 | For example: 6 ==> divisors[1, 2, 3, 6] 6 | Excluding 6, the sum(divisors) is 1 + 2 + 3 = 6 7 | So, 6 is a Perfect Number 8 | 9 | Other examples of Perfect Numbers: 28, 486, ... 10 | 11 | https://en.wikipedia.org/wiki/Perfect_number 12 | """ 13 | 14 | 15 | def perfect(number: int) -> bool: 16 | """ 17 | >>> perfect(27) 18 | False 19 | >>> perfect(28) 20 | True 21 | >>> perfect(29) 22 | False 23 | 24 | Start from 1 because dividing by 0 will raise ZeroDivisionError. 25 | A number at most can be divisible by the half of the number except the number 26 | itself. For example, 6 is at most can be divisible by 3 except by 6 itself. 27 | """ 28 | return sum(i for i in range(1, number // 2 + 1) if number % i == 0) == number 29 | 30 | 31 | if __name__ == "__main__": 32 | print("Program to check whether a number is a Perfect number or not...") 33 | number = int(input("Enter number: ").strip()) 34 | print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.") 35 | -------------------------------------------------------------------------------- /maths/power_using_recursion.py: -------------------------------------------------------------------------------- 1 | """ 2 | == Raise base to the power of exponent using recursion == 3 | Input --> 4 | Enter the base: 3 5 | Enter the exponent: 4 6 | Output --> 7 | 3 to the power of 4 is 81 8 | Input --> 9 | Enter the base: 2 10 | Enter the exponent: 0 11 | Output --> 12 | 2 to the power of 0 is 1 13 | """ 14 | 15 | 16 | def power(base: int, exponent: int) -> float: 17 | """ 18 | power(3, 4) 19 | 81 20 | >>> power(2, 0) 21 | 1 22 | >>> all(power(base, exponent) == pow(base, exponent) 23 | ... for base in range(-10, 10) for exponent in range(10)) 24 | True 25 | """ 26 | return base * power(base, (exponent - 1)) if exponent else 1 27 | 28 | 29 | if __name__ == "__main__": 30 | print("Raise base to the power of exponent using recursion...") 31 | base = int(input("Enter the base: ").strip()) 32 | exponent = int(input("Enter the exponent: ").strip()) 33 | result = power(base, abs(exponent)) 34 | if exponent < 0: # power() does not properly deal w/ negative exponents 35 | result = 1 / result 36 | print(f"{base} to the power of {exponent} is {result}") 37 | -------------------------------------------------------------------------------- /maths/prime_sieve_eratosthenes.py: -------------------------------------------------------------------------------- 1 | # flake8: noqa 2 | 3 | """ 4 | Sieve of Eratosthenes 5 | 6 | Input : n =10 7 | Output: 2 3 5 7 8 | 9 | Input : n = 20 10 | Output: 2 3 5 7 11 13 17 19 11 | 12 | you can read in detail about this at 13 | https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes 14 | """ 15 | 16 | 17 | def prime_sieve_eratosthenes(num): 18 | """ 19 | print the prime numbers up to n 20 | 21 | >>> prime_sieve_eratosthenes(10) 22 | 2,3,5,7, 23 | >>> prime_sieve_eratosthenes(20) 24 | 2,3,5,7,11,13,17,19, 25 | """ 26 | 27 | primes = [True for i in range(num + 1)] 28 | p = 2 29 | 30 | while p * p <= num: 31 | if primes[p]: 32 | for i in range(p * p, num + 1, p): 33 | primes[i] = False 34 | p += 1 35 | 36 | for prime in range(2, num + 1): 37 | if primes[prime]: 38 | print(prime, end=",") 39 | 40 | 41 | if __name__ == "__main__": 42 | import doctest 43 | 44 | doctest.testmod() 45 | num = int(input()) 46 | 47 | prime_sieve_eratosthenes(num) 48 | -------------------------------------------------------------------------------- /maths/pythagoras.py: -------------------------------------------------------------------------------- 1 | """Uses Pythagoras theorem to calculate the distance between two points in space.""" 2 | 3 | import math 4 | 5 | 6 | class Point: 7 | def __init__(self, x, y, z): 8 | self.x = x 9 | self.y = y 10 | self.z = z 11 | 12 | def __repr__(self) -> str: 13 | return f"Point({self.x}, {self.y}, {self.z})" 14 | 15 | 16 | def distance(a: Point, b: Point) -> float: 17 | return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2)) 18 | 19 | 20 | def test_distance() -> None: 21 | """ 22 | >>> point1 = Point(2, -1, 7) 23 | >>> point2 = Point(1, -3, 5) 24 | >>> print(f"Distance from {point1} to {point2} is {distance(point1, point2)}") 25 | Distance from Point(2, -1, 7) to Point(1, -3, 5) is 3.0 26 | """ 27 | pass 28 | 29 | 30 | if __name__ == "__main__": 31 | import doctest 32 | 33 | doctest.testmod() 34 | -------------------------------------------------------------------------------- /maths/quadratic_equations_complex_numbers.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from cmath import sqrt 4 | 5 | 6 | def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]: 7 | """ 8 | Given the numerical coefficients a, b and c, 9 | calculates the roots for any quadratic equation of the form ax^2 + bx + c 10 | 11 | >>> quadratic_roots(a=1, b=3, c=-4) 12 | (1.0, -4.0) 13 | >>> quadratic_roots(5, 6, 1) 14 | (-0.2, -1.0) 15 | >>> quadratic_roots(1, -6, 25) 16 | ((3+4j), (3-4j)) 17 | """ 18 | 19 | if a == 0: 20 | raise ValueError("Coefficient 'a' must not be zero.") 21 | delta = b * b - 4 * a * c 22 | 23 | root_1 = (-b + sqrt(delta)) / (2 * a) 24 | root_2 = (-b - sqrt(delta)) / (2 * a) 25 | 26 | return ( 27 | root_1.real if not root_1.imag else root_1, 28 | root_2.real if not root_2.imag else root_2, 29 | ) 30 | 31 | 32 | def main(): 33 | solutions = quadratic_roots(a=5, b=6, c=1) 34 | print("The solutions are: {} and {}".format(*solutions)) 35 | 36 | 37 | if __name__ == "__main__": 38 | main() 39 | -------------------------------------------------------------------------------- /maths/radians.py: -------------------------------------------------------------------------------- 1 | from math import pi 2 | 3 | 4 | def radians(degree: float) -> float: 5 | """ 6 | Coverts the given angle from degrees to radians 7 | https://en.wikipedia.org/wiki/Radian 8 | 9 | >>> radians(180) 10 | 3.141592653589793 11 | >>> radians(92) 12 | 1.6057029118347832 13 | >>> radians(274) 14 | 4.782202150464463 15 | >>> radians(109.82) 16 | 1.9167205845401725 17 | 18 | >>> from math import radians as math_radians 19 | >>> all(abs(radians(i)-math_radians(i)) <= 0.00000001 for i in range(-2, 361)) 20 | True 21 | """ 22 | 23 | return degree / (180 / pi) 24 | 25 | 26 | if __name__ == "__main__": 27 | from doctest import testmod 28 | 29 | testmod() 30 | -------------------------------------------------------------------------------- /maths/relu.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script demonstrates the implementation of the ReLU function. 3 | 4 | It's a kind of activation function defined as the positive part of its argument in the 5 | context of neural network. 6 | The function takes a vector of K real numbers as input and then argmax(x, 0). 7 | After through ReLU, the element of the vector always 0 or real number. 8 | 9 | Script inspired from its corresponding Wikipedia article 10 | https://en.wikipedia.org/wiki/Rectifier_(neural_networks) 11 | """ 12 | from __future__ import annotations 13 | 14 | import numpy as np 15 | 16 | 17 | def relu(vector: list[float]): 18 | """ 19 | Implements the relu function 20 | 21 | Parameters: 22 | vector (np.array,list,tuple): A numpy array of shape (1,n) 23 | consisting of real values or a similar list,tuple 24 | 25 | 26 | Returns: 27 | relu_vec (np.array): The input numpy array, after applying 28 | relu. 29 | 30 | >>> vec = np.array([-1, 0, 5]) 31 | >>> relu(vec) 32 | array([0, 0, 5]) 33 | """ 34 | 35 | # compare two arrays and then return element-wise maxima. 36 | return np.maximum(0, vector) 37 | 38 | 39 | if __name__ == "__main__": 40 | print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5] 41 | -------------------------------------------------------------------------------- /maths/runge_kutta.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def runge_kutta(f, y0, x0, h, x_end): 5 | """ 6 | Calculate the numeric solution at each step to the ODE f(x, y) using RK4 7 | 8 | https://en.wikipedia.org/wiki/Runge-Kutta_methods 9 | 10 | Arguments: 11 | f -- The ode as a function of x and y 12 | y0 -- the initial value for y 13 | x0 -- the initial value for x 14 | h -- the stepsize 15 | x_end -- the end value for x 16 | 17 | >>> # the exact solution is math.exp(x) 18 | >>> def f(x, y): 19 | ... return y 20 | >>> y0 = 1 21 | >>> y = runge_kutta(f, y0, 0.0, 0.01, 5) 22 | >>> y[-1] 23 | 148.41315904125113 24 | """ 25 | N = int(np.ceil((x_end - x0) / h)) 26 | y = np.zeros((N + 1,)) 27 | y[0] = y0 28 | x = x0 29 | 30 | for k in range(N): 31 | k1 = f(x, y[k]) 32 | k2 = f(x + 0.5 * h, y[k] + 0.5 * h * k1) 33 | k3 = f(x + 0.5 * h, y[k] + 0.5 * h * k2) 34 | k4 = f(x + h, y[k] + h * k3) 35 | y[k + 1] = y[k] + (1 / 6) * h * (k1 + 2 * k2 + 2 * k3 + k4) 36 | x += h 37 | 38 | return y 39 | 40 | 41 | if __name__ == "__main__": 42 | import doctest 43 | 44 | doctest.testmod() 45 | -------------------------------------------------------------------------------- /maths/series/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/maths/series/__init__.py -------------------------------------------------------------------------------- /maths/sum_of_arithmetic_series.py: -------------------------------------------------------------------------------- 1 | # DarkCoder 2 | def sum_of_series(first_term, common_diff, num_of_terms): 3 | """ 4 | Find the sum of n terms in an arithmetic progression. 5 | 6 | >>> sum_of_series(1, 1, 10) 7 | 55.0 8 | >>> sum_of_series(1, 10, 100) 9 | 49600.0 10 | """ 11 | sum = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) 12 | # formula for sum of series 13 | return sum 14 | 15 | 16 | def main(): 17 | print(sum_of_series(1, 1, 10)) 18 | 19 | 20 | if __name__ == "__main__": 21 | import doctest 22 | 23 | doctest.testmod() 24 | -------------------------------------------------------------------------------- /maths/sum_of_geometric_progression.py: -------------------------------------------------------------------------------- 1 | def sum_of_geometric_progression( 2 | first_term: int, common_ratio: int, num_of_terms: int 3 | ) -> float: 4 | """ " 5 | Return the sum of n terms in a geometric progression. 6 | >>> sum_of_geometric_progression(1, 2, 10) 7 | 1023.0 8 | >>> sum_of_geometric_progression(1, 10, 5) 9 | 11111.0 10 | >>> sum_of_geometric_progression(0, 2, 10) 11 | 0.0 12 | >>> sum_of_geometric_progression(1, 0, 10) 13 | 1.0 14 | >>> sum_of_geometric_progression(1, 2, 0) 15 | -0.0 16 | >>> sum_of_geometric_progression(-1, 2, 10) 17 | -1023.0 18 | >>> sum_of_geometric_progression(1, -2, 10) 19 | -341.0 20 | >>> sum_of_geometric_progression(1, 2, -10) 21 | -0.9990234375 22 | """ 23 | if common_ratio == 1: 24 | # Formula for sum if common ratio is 1 25 | return num_of_terms * first_term 26 | 27 | # Formula for finding sum of n terms of a GeometricProgression 28 | return (first_term / (1 - common_ratio)) * (1 - common_ratio ** num_of_terms) 29 | -------------------------------------------------------------------------------- /maths/test_prime_check.py: -------------------------------------------------------------------------------- 1 | """ 2 | Minimalist file that allows pytest to find and run the Test unittest. For details, see: 3 | http://doc.pytest.org/en/latest/goodpractices.html#conventions-for-python-test-discovery 4 | """ 5 | 6 | from .prime_check import Test 7 | 8 | Test() 9 | -------------------------------------------------------------------------------- /matrix/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/matrix/__init__.py -------------------------------------------------------------------------------- /matrix/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/matrix/tests/__init__.py -------------------------------------------------------------------------------- /matrix/tests/pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | markers = 3 | mat_ops: tests for matrix operations 4 | -------------------------------------------------------------------------------- /networking_flow/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/networking_flow/__init__.py -------------------------------------------------------------------------------- /neural_network/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/neural_network/__init__.py -------------------------------------------------------------------------------- /other/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/other/__init__.py -------------------------------------------------------------------------------- /other/anagrams.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import os 3 | import pprint 4 | import time 5 | 6 | start_time = time.time() 7 | print("creating word list...") 8 | path = os.path.split(os.path.realpath(__file__)) 9 | with open(path[0] + "/words") as f: 10 | word_list = sorted(list({word.strip().lower() for word in f})) 11 | 12 | 13 | def signature(word): 14 | return "".join(sorted(word)) 15 | 16 | 17 | word_bysig = collections.defaultdict(list) 18 | for word in word_list: 19 | word_bysig[signature(word)].append(word) 20 | 21 | 22 | def anagram(my_word): 23 | return word_bysig[signature(my_word)] 24 | 25 | 26 | print("finding anagrams...") 27 | all_anagrams = {word: anagram(word) for word in word_list if len(anagram(word)) > 1} 28 | 29 | print("writing anagrams to file...") 30 | with open("anagrams.txt", "w") as file: 31 | file.write("all_anagrams = ") 32 | file.write(pprint.pformat(all_anagrams)) 33 | 34 | total_time = round(time.time() - start_time, 2) 35 | print(("Done [", total_time, "seconds ]")) 36 | -------------------------------------------------------------------------------- /other/fischer_yates_shuffle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | The Fisher–Yates shuffle is an algorithm for generating a random permutation of a 4 | finite sequence. 5 | For more details visit 6 | wikipedia/Fischer-Yates-Shuffle. 7 | """ 8 | import random 9 | 10 | 11 | def FYshuffle(list): 12 | for i in range(len(list)): 13 | a = random.randint(0, len(list) - 1) 14 | b = random.randint(0, len(list) - 1) 15 | list[a], list[b] = list[b], list[a] 16 | return list 17 | 18 | 19 | if __name__ == "__main__": 20 | integers = [0, 1, 2, 3, 4, 5, 6, 7] 21 | strings = ["python", "says", "hello", "!"] 22 | print("Fisher-Yates Shuffle:") 23 | print("List", integers, strings) 24 | print("FY Shuffle", FYshuffle(integers), FYshuffle(strings)) 25 | -------------------------------------------------------------------------------- /other/largest_subarray_sum.py: -------------------------------------------------------------------------------- 1 | from sys import maxsize 2 | 3 | 4 | def max_sub_array_sum(a: list, size: int = 0): 5 | """ 6 | >>> max_sub_array_sum([-13, -3, -25, -20, -3, -16, -23, -12, -5, -22, -15, -4, -7]) 7 | -3 8 | """ 9 | size = size or len(a) 10 | max_so_far = -maxsize - 1 11 | max_ending_here = 0 12 | for i in range(0, size): 13 | max_ending_here = max_ending_here + a[i] 14 | if max_so_far < max_ending_here: 15 | max_so_far = max_ending_here 16 | if max_ending_here < 0: 17 | max_ending_here = 0 18 | return max_so_far 19 | 20 | 21 | if __name__ == "__main__": 22 | a = [-13, -3, -25, -20, 1, -16, -23, -12, -5, -22, -15, -4, -7] 23 | print(("Maximum contiguous sum is", max_sub_array_sum(a, len(a)))) 24 | -------------------------------------------------------------------------------- /other/tower_of_hanoi.py: -------------------------------------------------------------------------------- 1 | def moveTower(height, fromPole, toPole, withPole): 2 | """ 3 | >>> moveTower(3, 'A', 'B', 'C') 4 | moving disk from A to B 5 | moving disk from A to C 6 | moving disk from B to C 7 | moving disk from A to B 8 | moving disk from C to A 9 | moving disk from C to B 10 | moving disk from A to B 11 | """ 12 | if height >= 1: 13 | moveTower(height - 1, fromPole, withPole, toPole) 14 | moveDisk(fromPole, toPole) 15 | moveTower(height - 1, withPole, toPole, fromPole) 16 | 17 | 18 | def moveDisk(fp, tp): 19 | print("moving disk from", fp, "to", tp) 20 | 21 | 22 | def main(): 23 | height = int(input("Height of hanoi: ").strip()) 24 | moveTower(height, "A", "B", "C") 25 | 26 | 27 | if __name__ == "__main__": 28 | main() 29 | -------------------------------------------------------------------------------- /project_euler/README.md: -------------------------------------------------------------------------------- 1 | # ProjectEuler 2 | 3 | Problems are taken from https://projecteuler.net/. 4 | 5 | Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical 6 | insights to solve. Project Euler is ideal for mathematicians who are learning to code. 7 | 8 | Here the efficiency of your code is also checked. 9 | I've tried to provide all the best possible solutions. 10 | 11 | For description of the problem statements, kindly visit https://projecteuler.net/show=all 12 | -------------------------------------------------------------------------------- /project_euler/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_01/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_01/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_01/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement: 3 | If we list all the natural numbers below 10 that are multiples of 3 or 5, 4 | we get 3,5,6 and 9. The sum of these multiples is 23. 5 | Find the sum of all the multiples of 3 or 5 below N. 6 | """ 7 | 8 | 9 | def solution(n): 10 | """Returns the sum of all the multiples of 3 or 5 below n. 11 | 12 | >>> solution(3) 13 | 0 14 | >>> solution(4) 15 | 3 16 | >>> solution(10) 17 | 23 18 | >>> solution(600) 19 | 83700 20 | >>> solution(-7) 21 | 0 22 | """ 23 | 24 | return sum([e for e in range(3, n) if e % 3 == 0 or e % 5 == 0]) 25 | 26 | 27 | if __name__ == "__main__": 28 | print(solution(int(input().strip()))) 29 | -------------------------------------------------------------------------------- /project_euler/problem_01/sol2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement: 3 | If we list all the natural numbers below 10 that are multiples of 3 or 5, 4 | we get 3,5,6 and 9. The sum of these multiples is 23. 5 | Find the sum of all the multiples of 3 or 5 below N. 6 | """ 7 | 8 | 9 | def solution(n): 10 | """Returns the sum of all the multiples of 3 or 5 below n. 11 | 12 | >>> solution(3) 13 | 0 14 | >>> solution(4) 15 | 3 16 | >>> solution(10) 17 | 23 18 | >>> solution(600) 19 | 83700 20 | """ 21 | 22 | sum = 0 23 | terms = (n - 1) // 3 24 | sum += ((terms) * (6 + (terms - 1) * 3)) // 2 # sum of an A.P. 25 | terms = (n - 1) // 5 26 | sum += ((terms) * (10 + (terms - 1) * 5)) // 2 27 | terms = (n - 1) // 15 28 | sum -= ((terms) * (30 + (terms - 1) * 15)) // 2 29 | return sum 30 | 31 | 32 | if __name__ == "__main__": 33 | print(solution(int(input().strip()))) 34 | -------------------------------------------------------------------------------- /project_euler/problem_01/sol4.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement: 3 | If we list all the natural numbers below 10 that are multiples of 3 or 5, 4 | we get 3,5,6 and 9. The sum of these multiples is 23. 5 | Find the sum of all the multiples of 3 or 5 below N. 6 | """ 7 | 8 | 9 | def solution(n): 10 | """Returns the sum of all the multiples of 3 or 5 below n. 11 | 12 | >>> solution(3) 13 | 0 14 | >>> solution(4) 15 | 3 16 | >>> solution(10) 17 | 23 18 | >>> solution(600) 19 | 83700 20 | """ 21 | 22 | xmulti = [] 23 | zmulti = [] 24 | z = 3 25 | x = 5 26 | temp = 1 27 | while True: 28 | result = z * temp 29 | if result < n: 30 | zmulti.append(result) 31 | temp += 1 32 | else: 33 | temp = 1 34 | break 35 | while True: 36 | result = x * temp 37 | if result < n: 38 | xmulti.append(result) 39 | temp += 1 40 | else: 41 | break 42 | collection = list(set(xmulti + zmulti)) 43 | return sum(collection) 44 | 45 | 46 | if __name__ == "__main__": 47 | print(solution(int(input().strip()))) 48 | -------------------------------------------------------------------------------- /project_euler/problem_01/sol5.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement: 3 | If we list all the natural numbers below 10 that are multiples of 3 or 5, 4 | we get 3,5,6 and 9. The sum of these multiples is 23. 5 | Find the sum of all the multiples of 3 or 5 below N. 6 | """ 7 | 8 | """A straightforward pythonic solution using list comprehension""" 9 | 10 | 11 | def solution(n): 12 | """Returns the sum of all the multiples of 3 or 5 below n. 13 | 14 | >>> solution(3) 15 | 0 16 | >>> solution(4) 17 | 3 18 | >>> solution(10) 19 | 23 20 | >>> solution(600) 21 | 83700 22 | """ 23 | 24 | return sum([i for i in range(n) if i % 3 == 0 or i % 5 == 0]) 25 | 26 | 27 | if __name__ == "__main__": 28 | print(solution(int(input().strip()))) 29 | -------------------------------------------------------------------------------- /project_euler/problem_01/sol6.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement: 3 | If we list all the natural numbers below 10 that are multiples of 3 or 5, 4 | we get 3,5,6 and 9. The sum of these multiples is 23. 5 | Find the sum of all the multiples of 3 or 5 below N. 6 | """ 7 | 8 | 9 | def solution(n): 10 | """Returns the sum of all the multiples of 3 or 5 below n. 11 | 12 | >>> solution(3) 13 | 0 14 | >>> solution(4) 15 | 3 16 | >>> solution(10) 17 | 23 18 | >>> solution(600) 19 | 83700 20 | """ 21 | 22 | a = 3 23 | result = 0 24 | while a < n: 25 | if a % 3 == 0 or a % 5 == 0: 26 | result += a 27 | elif a % 15 == 0: 28 | result -= a 29 | a += 1 30 | return result 31 | 32 | 33 | if __name__ == "__main__": 34 | print(solution(int(input().strip()))) 35 | -------------------------------------------------------------------------------- /project_euler/problem_01/sol7.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement: 3 | If we list all the natural numbers below 10 that are multiples of 3 or 5, 4 | we get 3,5,6 and 9. The sum of these multiples is 23. 5 | Find the sum of all the multiples of 3 or 5 below N. 6 | """ 7 | 8 | 9 | def solution(n): 10 | """Returns the sum of all the multiples of 3 or 5 below n. 11 | 12 | >>> solution(3) 13 | 0 14 | >>> solution(4) 15 | 3 16 | >>> solution(10) 17 | 23 18 | >>> solution(600) 19 | 83700 20 | """ 21 | 22 | result = 0 23 | for i in range(n): 24 | if i % 3 == 0: 25 | result += i 26 | elif i % 5 == 0: 27 | result += i 28 | return result 29 | 30 | 31 | if __name__ == "__main__": 32 | print(solution(int(input().strip()))) 33 | -------------------------------------------------------------------------------- /project_euler/problem_02/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_02/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_02/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: 3 | Each new term in the Fibonacci sequence is generated by adding the previous two 4 | terms. By starting with 1 and 2, the first 10 terms will be: 5 | 6 | 1,2,3,5,8,13,21,34,55,89,.. 7 | 8 | By considering the terms in the Fibonacci sequence whose values do not exceed 9 | n, find the sum of the even-valued terms. e.g. for n=10, we have {2,8}, sum is 10 | 10. 11 | """ 12 | 13 | 14 | def solution(n): 15 | """Returns the sum of all fibonacci sequence even elements that are lower 16 | or equals to n. 17 | 18 | >>> solution(10) 19 | 10 20 | >>> solution(15) 21 | 10 22 | >>> solution(2) 23 | 2 24 | >>> solution(1) 25 | 0 26 | >>> solution(34) 27 | 44 28 | """ 29 | i = 1 30 | j = 2 31 | sum = 0 32 | while j <= n: 33 | if j % 2 == 0: 34 | sum += j 35 | i, j = j, i + j 36 | 37 | return sum 38 | 39 | 40 | if __name__ == "__main__": 41 | print(solution(int(input().strip()))) 42 | -------------------------------------------------------------------------------- /project_euler/problem_02/sol2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: 3 | Each new term in the Fibonacci sequence is generated by adding the previous two 4 | terms. By starting with 1 and 2, the first 10 terms will be: 5 | 6 | 1,2,3,5,8,13,21,34,55,89,.. 7 | 8 | By considering the terms in the Fibonacci sequence whose values do not exceed 9 | n, find the sum of the even-valued terms. e.g. for n=10, we have {2,8}, sum is 10 | 10. 11 | """ 12 | 13 | 14 | def solution(n): 15 | """Returns the sum of all fibonacci sequence even elements that are lower 16 | or equals to n. 17 | 18 | >>> solution(10) 19 | [2, 8] 20 | >>> solution(15) 21 | [2, 8] 22 | >>> solution(2) 23 | [2] 24 | >>> solution(1) 25 | [] 26 | >>> solution(34) 27 | [2, 8, 34] 28 | """ 29 | ls = [] 30 | a, b = 0, 1 31 | while b <= n: 32 | if b % 2 == 0: 33 | ls.append(b) 34 | a, b = b, a + b 35 | return ls 36 | 37 | 38 | if __name__ == "__main__": 39 | print(solution(int(input().strip()))) 40 | -------------------------------------------------------------------------------- /project_euler/problem_02/sol3.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: 3 | Each new term in the Fibonacci sequence is generated by adding the previous 4 | two terms. By starting with 1 and 2, the first 10 terms will be: 5 | 6 | 1,2,3,5,8,13,21,34,55,89,.. 7 | 8 | By considering the terms in the Fibonacci sequence whose values do not exceed 9 | n, find the sum of the even-valued terms. e.g. for n=10, we have {2,8}, sum is 10 | 10. 11 | """ 12 | 13 | 14 | def solution(n): 15 | """Returns the sum of all fibonacci sequence even elements that are lower 16 | or equals to n. 17 | 18 | >>> solution(10) 19 | 10 20 | >>> solution(15) 21 | 10 22 | >>> solution(2) 23 | 2 24 | >>> solution(1) 25 | 0 26 | >>> solution(34) 27 | 44 28 | """ 29 | if n <= 1: 30 | return 0 31 | a = 0 32 | b = 2 33 | count = 0 34 | while 4 * b + a <= n: 35 | a, b = b, 4 * b + a 36 | count += a 37 | return count + b 38 | 39 | 40 | if __name__ == "__main__": 41 | print(solution(int(input().strip()))) 42 | -------------------------------------------------------------------------------- /project_euler/problem_02/sol5.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: 3 | Each new term in the Fibonacci sequence is generated by adding the previous two 4 | terms. By starting with 1 and 2, the first 10 terms will be: 5 | 6 | 1,2,3,5,8,13,21,34,55,89,.. 7 | 8 | By considering the terms in the Fibonacci sequence whose values do not exceed 9 | n, find the sum of the even-valued terms. e.g. for n=10, we have {2,8}, sum is 10 | 10. 11 | """ 12 | 13 | 14 | def solution(n): 15 | """Returns the sum of all fibonacci sequence even elements that are lower 16 | or equals to n. 17 | 18 | >>> solution(10) 19 | 10 20 | >>> solution(15) 21 | 10 22 | >>> solution(2) 23 | 2 24 | >>> solution(1) 25 | 0 26 | >>> solution(34) 27 | 44 28 | """ 29 | 30 | a = [0, 1] 31 | i = 0 32 | while a[i] <= n: 33 | a.append(a[i] + a[i + 1]) 34 | if a[i + 2] > n: 35 | break 36 | i += 1 37 | sum = 0 38 | for j in range(len(a) - 1): 39 | if a[j] % 2 == 0: 40 | sum += a[j] 41 | 42 | return sum 43 | 44 | 45 | if __name__ == "__main__": 46 | print(solution(int(input().strip()))) 47 | -------------------------------------------------------------------------------- /project_euler/problem_03/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_03/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_04/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_04/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_04/sol2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: 3 | A palindromic number reads the same both ways. The largest palindrome made from 4 | the product of two 2-digit numbers is 9009 = 91 x 99. 5 | 6 | Find the largest palindrome made from the product of two 3-digit numbers which 7 | is less than N. 8 | """ 9 | 10 | 11 | def solution(n): 12 | """Returns the largest palindrome made from the product of two 3-digit 13 | numbers which is less than n. 14 | 15 | >>> solution(20000) 16 | 19591 17 | >>> solution(30000) 18 | 29992 19 | >>> solution(40000) 20 | 39893 21 | """ 22 | answer = 0 23 | for i in range(999, 99, -1): # 3 digit numbers range from 999 down to 100 24 | for j in range(999, 99, -1): 25 | t = str(i * j) 26 | if t == t[::-1] and i * j < n: 27 | answer = max(answer, i * j) 28 | return answer 29 | 30 | 31 | if __name__ == "__main__": 32 | print(solution(int(input().strip()))) 33 | -------------------------------------------------------------------------------- /project_euler/problem_05/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_05/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_05/sol2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: 3 | 2520 is the smallest number that can be divided by each of the numbers from 1 4 | to 10 without any remainder. 5 | 6 | What is the smallest positive number that is evenly divisible(divisible with no 7 | remainder) by all of the numbers from 1 to N? 8 | """ 9 | """ Euclidean GCD Algorithm """ 10 | 11 | 12 | def gcd(x, y): 13 | return x if y == 0 else gcd(y, x % y) 14 | 15 | 16 | """ Using the property lcm*gcd of two numbers = product of them """ 17 | 18 | 19 | def lcm(x, y): 20 | return (x * y) // gcd(x, y) 21 | 22 | 23 | def solution(n): 24 | """Returns the smallest positive number that is evenly divisible(divisible 25 | with no remainder) by all of the numbers from 1 to n. 26 | 27 | >>> solution(10) 28 | 2520 29 | >>> solution(15) 30 | 360360 31 | >>> solution(20) 32 | 232792560 33 | >>> solution(22) 34 | 232792560 35 | """ 36 | g = 1 37 | for i in range(1, n + 1): 38 | g = lcm(g, i) 39 | return g 40 | 41 | 42 | if __name__ == "__main__": 43 | print(solution(int(input().strip()))) 44 | -------------------------------------------------------------------------------- /project_euler/problem_06/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_06/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_06/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: 3 | 4 | The sum of the squares of the first ten natural numbers is, 5 | 1^2 + 2^2 + ... + 10^2 = 385 6 | 7 | The square of the sum of the first ten natural numbers is, 8 | (1 + 2 + ... + 10)^2 = 552 = 3025 9 | 10 | Hence the difference between the sum of the squares of the first ten natural 11 | numbers and the square of the sum is 3025 − 385 = 2640. 12 | 13 | Find the difference between the sum of the squares of the first N natural 14 | numbers and the square of the sum. 15 | """ 16 | 17 | 18 | def solution(n: int) -> int: 19 | """Returns the difference between the sum of the squares of the first n 20 | natural numbers and the square of the sum. 21 | 22 | >>> solution(10) 23 | 2640 24 | >>> solution(15) 25 | 13160 26 | >>> solution(20) 27 | 41230 28 | >>> solution(50) 29 | 1582700 30 | """ 31 | sum_of_squares = 0 32 | sum_of_ints = 0 33 | for i in range(1, n + 1): 34 | sum_of_squares += i ** 2 35 | sum_of_ints += i 36 | return sum_of_ints ** 2 - sum_of_squares 37 | 38 | 39 | if __name__ == "__main__": 40 | import doctest 41 | 42 | doctest.testmod() 43 | print(solution(int(input().strip()))) 44 | -------------------------------------------------------------------------------- /project_euler/problem_06/sol2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: 3 | 4 | The sum of the squares of the first ten natural numbers is, 5 | 1^2 + 2^2 + ... + 10^2 = 385 6 | 7 | The square of the sum of the first ten natural numbers is, 8 | (1 + 2 + ... + 10)^2 = 552 = 3025 9 | 10 | Hence the difference between the sum of the squares of the first ten natural 11 | numbers and the square of the sum is 3025 − 385 = 2640. 12 | 13 | Find the difference between the sum of the squares of the first N natural 14 | numbers and the square of the sum. 15 | """ 16 | 17 | 18 | def solution(n: int) -> int: 19 | """Returns the difference between the sum of the squares of the first n 20 | natural numbers and the square of the sum. 21 | 22 | >>> solution(10) 23 | 2640 24 | >>> solution(15) 25 | 13160 26 | >>> solution(20) 27 | 41230 28 | >>> solution(50) 29 | 1582700 30 | """ 31 | sum_cubes = (n * (n + 1) // 2) ** 2 32 | sum_squares = n * (n + 1) * (2 * n + 1) // 6 33 | return sum_cubes - sum_squares 34 | 35 | 36 | if __name__ == "__main__": 37 | import doctest 38 | 39 | doctest.testmod() 40 | print(solution(int(input().strip()))) 41 | -------------------------------------------------------------------------------- /project_euler/problem_06/sol3.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: 3 | 4 | The sum of the squares of the first ten natural numbers is, 5 | 1^2 + 2^2 + ... + 10^2 = 385 6 | 7 | The square of the sum of the first ten natural numbers is, 8 | (1 + 2 + ... + 10)^2 = 552 = 3025 9 | 10 | Hence the difference between the sum of the squares of the first ten natural 11 | numbers and the square of the sum is 3025 − 385 = 2640. 12 | 13 | Find the difference between the sum of the squares of the first N natural 14 | numbers and the square of the sum. 15 | """ 16 | import math 17 | 18 | 19 | def solution(n: int) -> int: 20 | """Returns the difference between the sum of the squares of the first n 21 | natural numbers and the square of the sum. 22 | 23 | >>> solution(10) 24 | 2640 25 | >>> solution(15) 26 | 13160 27 | >>> solution(20) 28 | 41230 29 | >>> solution(50) 30 | 1582700 31 | """ 32 | sum_of_squares = sum([i * i for i in range(1, n + 1)]) 33 | square_of_sum = int(math.pow(sum(range(1, n + 1)), 2)) 34 | return square_of_sum - sum_of_squares 35 | 36 | 37 | if __name__ == "__main__": 38 | import doctest 39 | 40 | doctest.testmod() 41 | print(solution(int(input().strip()))) 42 | -------------------------------------------------------------------------------- /project_euler/problem_06/sol4.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: 3 | 4 | The sum of the squares of the first ten natural numbers is, 5 | 1^2 + 2^2 + ... + 10^2 = 385 6 | 7 | The square of the sum of the first ten natural numbers is, 8 | (1 + 2 + ... + 10)^2 = 552 = 3025 9 | 10 | Hence the difference between the sum of the squares of the first ten natural 11 | numbers and the square of the sum is 3025 − 385 = 2640. 12 | 13 | Find the difference between the sum of the squares of the first N natural 14 | numbers and the square of the sum. 15 | """ 16 | 17 | 18 | def solution(n: int) -> int: 19 | """Returns the difference between the sum of the squares of the first n 20 | natural numbers and the square of the sum. 21 | 22 | >>> solution(10) 23 | 2640 24 | >>> solution(15) 25 | 13160 26 | >>> solution(20) 27 | 41230 28 | >>> solution(50) 29 | 1582700 30 | >>> solution(100) 31 | 25164150 32 | """ 33 | sum_of_squares = n * (n + 1) * (2 * n + 1) / 6 34 | square_of_sum = (n * (n + 1) / 2) ** 2 35 | return int(square_of_sum - sum_of_squares) 36 | 37 | 38 | if __name__ == "__main__": 39 | import doctest 40 | 41 | doctest.testmod() 42 | print(solution(int(input("Enter a number: ").strip()))) 43 | -------------------------------------------------------------------------------- /project_euler/problem_06/test_solutions.py: -------------------------------------------------------------------------------- 1 | from .sol1 import solution as sol1 2 | from .sol2 import solution as sol2 3 | from .sol3 import solution as sol3 4 | from .sol4 import solution as sol4 5 | 6 | 7 | def test_solutions() -> None: 8 | """ 9 | >>> test_solutions() 10 | """ 11 | assert sol1(10) == sol2(10) == sol3(10) == sol4(10) == 2640 12 | assert sol1(15) == sol2(15) == sol3(15) == sol4(15) == 13160 13 | assert sol1(20) == sol2(20) == sol3(20) == sol4(20) == 41230 14 | assert sol1(50) == sol2(50) == sol3(50) == sol4(50) == 1582700 15 | 16 | 17 | if __name__ == "__main__": 18 | test_solutions() 19 | -------------------------------------------------------------------------------- /project_euler/problem_07/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_07/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_07/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | By listing the first six prime numbers: 3 | 4 | 2, 3, 5, 7, 11, and 13 5 | 6 | We can see that the 6th prime is 13. What is the Nth prime number? 7 | """ 8 | from math import sqrt 9 | 10 | 11 | def is_prime(n): 12 | if n == 2: 13 | return True 14 | elif n % 2 == 0: 15 | return False 16 | else: 17 | sq = int(sqrt(n)) + 1 18 | for i in range(3, sq, 2): 19 | if n % i == 0: 20 | return False 21 | return True 22 | 23 | 24 | def solution(n): 25 | """Returns the n-th prime number. 26 | 27 | >>> solution(6) 28 | 13 29 | >>> solution(1) 30 | 2 31 | >>> solution(3) 32 | 5 33 | >>> solution(20) 34 | 71 35 | >>> solution(50) 36 | 229 37 | >>> solution(100) 38 | 541 39 | """ 40 | i = 0 41 | j = 1 42 | while i != n and j < 3: 43 | j += 1 44 | if is_prime(j): 45 | i += 1 46 | while i != n: 47 | j += 2 48 | if is_prime(j): 49 | i += 1 50 | return j 51 | 52 | 53 | if __name__ == "__main__": 54 | print(solution(int(input().strip()))) 55 | -------------------------------------------------------------------------------- /project_euler/problem_07/sol3.py: -------------------------------------------------------------------------------- 1 | """ 2 | By listing the first six prime numbers: 3 | 4 | 2, 3, 5, 7, 11, and 13 5 | 6 | We can see that the 6th prime is 13. What is the Nth prime number? 7 | """ 8 | import itertools 9 | import math 10 | 11 | 12 | def primeCheck(number): 13 | if number % 2 == 0 and number > 2: 14 | return False 15 | return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2)) 16 | 17 | 18 | def prime_generator(): 19 | num = 2 20 | while True: 21 | if primeCheck(num): 22 | yield num 23 | num += 1 24 | 25 | 26 | def solution(n): 27 | """Returns the n-th prime number. 28 | 29 | >>> solution(6) 30 | 13 31 | >>> solution(1) 32 | 2 33 | >>> solution(3) 34 | 5 35 | >>> solution(20) 36 | 71 37 | >>> solution(50) 38 | 229 39 | >>> solution(100) 40 | 541 41 | """ 42 | return next(itertools.islice(prime_generator(), n - 1, n)) 43 | 44 | 45 | if __name__ == "__main__": 46 | print(solution(int(input().strip()))) 47 | -------------------------------------------------------------------------------- /project_euler/problem_08/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_08/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_09/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_09/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_09/sol2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement: 3 | A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, 4 | a^2 + b^2 = c^2 5 | For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. 6 | 7 | There exists exactly one Pythagorean triplet for which a + b + c = 1000. 8 | Find the product abc. 9 | """ 10 | 11 | 12 | def solution(n): 13 | """ 14 | Return the product of a,b,c which are Pythagorean Triplet that satisfies 15 | the following: 16 | 1. a < b < c 17 | 2. a**2 + b**2 = c**2 18 | 3. a + b + c = 1000 19 | 20 | >>> solution(1000) 21 | 31875000 22 | """ 23 | product = -1 24 | d = 0 25 | for a in range(1, n // 3): 26 | """Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c""" 27 | b = (n * n - 2 * a * n) // (2 * n - 2 * a) 28 | c = n - a - b 29 | if c * c == (a * a + b * b): 30 | d = a * b * c 31 | if d >= product: 32 | product = d 33 | return product 34 | 35 | 36 | if __name__ == "__main__": 37 | print(solution(int(input().strip()))) 38 | -------------------------------------------------------------------------------- /project_euler/problem_09/sol3.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement: 3 | 4 | A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, 5 | 6 | a^2 + b^2 = c^2 7 | 8 | For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. 9 | 10 | There exists exactly one Pythagorean triplet for which a + b + c = 1000. 11 | Find the product abc. 12 | """ 13 | 14 | 15 | def solution(): 16 | """ 17 | Returns the product of a,b,c which are Pythagorean Triplet that satisfies 18 | the following: 19 | 20 | 1. a**2 + b**2 = c**2 21 | 2. a + b + c = 1000 22 | 23 | # The code below has been commented due to slow execution affecting Travis. 24 | # >>> solution() 25 | # 31875000 26 | """ 27 | return [ 28 | a * b * (1000 - a - b) 29 | for a in range(1, 999) 30 | for b in range(a, 999) 31 | if (a * a + b * b == (1000 - a - b) ** 2) 32 | ][0] 33 | 34 | 35 | if __name__ == "__main__": 36 | print(solution()) 37 | -------------------------------------------------------------------------------- /project_euler/problem_10/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_10/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_10/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement: 3 | The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. 4 | 5 | Find the sum of all the primes below two million. 6 | """ 7 | from math import sqrt 8 | 9 | 10 | def is_prime(n): 11 | for i in range(2, int(sqrt(n)) + 1): 12 | if n % i == 0: 13 | return False 14 | 15 | return True 16 | 17 | 18 | def sum_of_primes(n): 19 | if n > 2: 20 | sumOfPrimes = 2 21 | else: 22 | return 0 23 | 24 | for i in range(3, n, 2): 25 | if is_prime(i): 26 | sumOfPrimes += i 27 | 28 | return sumOfPrimes 29 | 30 | 31 | def solution(n): 32 | """Returns the sum of all the primes below n. 33 | 34 | # The code below has been commented due to slow execution affecting Travis. 35 | # >>> solution(2000000) 36 | # 142913828922 37 | >>> solution(1000) 38 | 76127 39 | >>> solution(5000) 40 | 1548136 41 | >>> solution(10000) 42 | 5736396 43 | >>> solution(7) 44 | 10 45 | """ 46 | return sum_of_primes(n) 47 | 48 | 49 | if __name__ == "__main__": 50 | print(solution(int(input().strip()))) 51 | -------------------------------------------------------------------------------- /project_euler/problem_10/sol2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement: 3 | The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. 4 | 5 | Find the sum of all the primes below two million. 6 | """ 7 | import math 8 | from itertools import takewhile 9 | 10 | 11 | def primeCheck(number): 12 | if number % 2 == 0 and number > 2: 13 | return False 14 | return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2)) 15 | 16 | 17 | def prime_generator(): 18 | num = 2 19 | while True: 20 | if primeCheck(num): 21 | yield num 22 | num += 1 23 | 24 | 25 | def solution(n): 26 | """Returns the sum of all the primes below n. 27 | 28 | # The code below has been commented due to slow execution affecting Travis. 29 | # >>> solution(2000000) 30 | # 142913828922 31 | >>> solution(1000) 32 | 76127 33 | >>> solution(5000) 34 | 1548136 35 | >>> solution(10000) 36 | 5736396 37 | >>> solution(7) 38 | 10 39 | """ 40 | return sum(takewhile(lambda x: x < n, prime_generator())) 41 | 42 | 43 | if __name__ == "__main__": 44 | print(solution(int(input().strip()))) 45 | -------------------------------------------------------------------------------- /project_euler/problem_11/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_11/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_12/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_12/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_13/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_13/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_13/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement: 3 | Work out the first ten digits of the sum of the following one-hundred 50-digit 4 | numbers. 5 | """ 6 | 7 | 8 | def solution(array): 9 | """Returns the first ten digits of the sum of the array elements. 10 | 11 | >>> import os 12 | >>> sum = 0 13 | >>> array = [] 14 | >>> with open(os.path.dirname(__file__) + "/num.txt","r") as f: 15 | ... for line in f: 16 | ... array.append(int(line)) 17 | ... 18 | >>> solution(array) 19 | '5537376230' 20 | """ 21 | return str(sum(array))[:10] 22 | 23 | 24 | if __name__ == "__main__": 25 | n = int(input().strip()) 26 | 27 | array = [] 28 | for i in range(n): 29 | array.append(int(input().strip())) 30 | print(solution(array)) 31 | -------------------------------------------------------------------------------- /project_euler/problem_14/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_14/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_15/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_15/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_16/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_16/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_16/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. 3 | 4 | What is the sum of the digits of the number 2^1000? 5 | """ 6 | 7 | 8 | def solution(power): 9 | """Returns the sum of the digits of the number 2^power. 10 | >>> solution(1000) 11 | 1366 12 | >>> solution(50) 13 | 76 14 | >>> solution(20) 15 | 31 16 | >>> solution(15) 17 | 26 18 | """ 19 | num = 2 ** power 20 | string_num = str(num) 21 | list_num = list(string_num) 22 | sum_of_num = 0 23 | 24 | for i in list_num: 25 | sum_of_num += int(i) 26 | 27 | return sum_of_num 28 | 29 | 30 | if __name__ == "__main__": 31 | power = int(input("Enter the power of 2: ").strip()) 32 | print("2 ^ ", power, " = ", 2 ** power) 33 | result = solution(power) 34 | print("Sum of the digits is: ", result) 35 | -------------------------------------------------------------------------------- /project_euler/problem_16/sol2.py: -------------------------------------------------------------------------------- 1 | """ 2 | 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. 3 | 4 | What is the sum of the digits of the number 2^1000? 5 | """ 6 | 7 | 8 | def solution(power): 9 | """Returns the sum of the digits of the number 2^power. 10 | 11 | >>> solution(1000) 12 | 1366 13 | >>> solution(50) 14 | 76 15 | >>> solution(20) 16 | 31 17 | >>> solution(15) 18 | 26 19 | """ 20 | n = 2 ** power 21 | r = 0 22 | while n: 23 | r, n = r + n % 10, n // 10 24 | return r 25 | 26 | 27 | if __name__ == "__main__": 28 | print(solution(int(str(input()).strip()))) 29 | -------------------------------------------------------------------------------- /project_euler/problem_17/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_17/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_18/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_18/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_18/triangle.txt: -------------------------------------------------------------------------------- 1 | 75 2 | 95 64 3 | 17 47 82 4 | 18 35 87 10 5 | 20 04 82 47 65 6 | 19 01 23 75 03 34 7 | 88 02 77 73 07 63 67 8 | 99 65 04 28 06 16 70 92 9 | 41 41 26 56 83 40 80 70 33 10 | 41 48 72 33 47 32 37 16 94 29 11 | 53 71 44 65 25 43 91 52 97 51 14 12 | 70 11 33 28 77 73 17 78 39 68 17 57 13 | 91 71 52 38 17 14 91 43 58 50 27 29 48 14 | 63 66 04 68 89 53 67 30 73 16 69 87 40 31 15 | 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 16 | -------------------------------------------------------------------------------- /project_euler/problem_19/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_19/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_20/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_20/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_20/sol2.py: -------------------------------------------------------------------------------- 1 | """ 2 | n! means n × (n − 1) × ... × 3 × 2 × 1 3 | 4 | For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, 5 | and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. 6 | 7 | Find the sum of the digits in the number 100! 8 | """ 9 | from math import factorial 10 | 11 | 12 | def solution(n): 13 | """Returns the sum of the digits in the number 100! 14 | >>> solution(100) 15 | 648 16 | >>> solution(50) 17 | 216 18 | >>> solution(10) 19 | 27 20 | >>> solution(5) 21 | 3 22 | >>> solution(3) 23 | 6 24 | >>> solution(2) 25 | 2 26 | >>> solution(1) 27 | 1 28 | """ 29 | return sum([int(x) for x in str(factorial(n))]) 30 | 31 | 32 | if __name__ == "__main__": 33 | print(solution(int(input("Enter the Number: ").strip()))) 34 | -------------------------------------------------------------------------------- /project_euler/problem_20/sol3.py: -------------------------------------------------------------------------------- 1 | """ 2 | n! means n × (n − 1) × ... × 3 × 2 × 1 3 | 4 | For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, 5 | and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. 6 | 7 | Find the sum of the digits in the number 100! 8 | """ 9 | from math import factorial 10 | 11 | 12 | def solution(n): 13 | """Returns the sum of the digits in the number 100! 14 | >>> solution(1000) 15 | 10539 16 | >>> solution(200) 17 | 1404 18 | >>> solution(100) 19 | 648 20 | >>> solution(50) 21 | 216 22 | >>> solution(10) 23 | 27 24 | >>> solution(5) 25 | 3 26 | >>> solution(3) 27 | 6 28 | >>> solution(2) 29 | 2 30 | >>> solution(1) 31 | 1 32 | >>> solution(0) 33 | 1 34 | """ 35 | return sum(map(int, str(factorial(n)))) 36 | 37 | 38 | if __name__ == "__main__": 39 | print(solution(int(input("Enter the Number: ").strip()))) 40 | -------------------------------------------------------------------------------- /project_euler/problem_20/sol4.py: -------------------------------------------------------------------------------- 1 | """ 2 | n! means n × (n − 1) × ... × 3 × 2 × 1 3 | 4 | For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, 5 | and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. 6 | 7 | Find the sum of the digits in the number 100! 8 | """ 9 | 10 | 11 | def solution(n): 12 | """Returns the sum of the digits in the number 100! 13 | >>> solution(100) 14 | 648 15 | >>> solution(50) 16 | 216 17 | >>> solution(10) 18 | 27 19 | >>> solution(5) 20 | 3 21 | >>> solution(3) 22 | 6 23 | >>> solution(2) 24 | 2 25 | >>> solution(1) 26 | 1 27 | """ 28 | fact = 1 29 | result = 0 30 | for i in range(1, n + 1): 31 | fact *= i 32 | 33 | for j in str(fact): 34 | result += int(j) 35 | 36 | return result 37 | 38 | 39 | if __name__ == "__main__": 40 | print(solution(int(input("Enter the Number: ").strip()))) 41 | -------------------------------------------------------------------------------- /project_euler/problem_21/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_21/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_22/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_22/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_23/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_23/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_234/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_234/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_24/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_24/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_24/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | A permutation is an ordered arrangement of objects. For example, 3124 is one 3 | possible permutation of the digits 1, 2, 3 and 4. If all of the permutations 4 | are listed numerically or alphabetically, we call it lexicographic order. The 5 | lexicographic permutations of 0, 1 and 2 are: 6 | 7 | 012 021 102 120 201 210 8 | 9 | What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 10 | 6, 7, 8 and 9? 11 | """ 12 | from itertools import permutations 13 | 14 | 15 | def solution(): 16 | """Returns the millionth lexicographic permutation of the digits 0, 1, 2, 17 | 3, 4, 5, 6, 7, 8 and 9. 18 | 19 | >>> solution() 20 | '2783915460' 21 | """ 22 | result = list(map("".join, permutations("0123456789"))) 23 | return result[999999] 24 | 25 | 26 | if __name__ == "__main__": 27 | print(solution()) 28 | -------------------------------------------------------------------------------- /project_euler/problem_25/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_25/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_25/sol2.py: -------------------------------------------------------------------------------- 1 | """ 2 | The Fibonacci sequence is defined by the recurrence relation: 3 | 4 | Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. 5 | 6 | Hence the first 12 terms will be: 7 | 8 | F1 = 1 9 | F2 = 1 10 | F3 = 2 11 | F4 = 3 12 | F5 = 5 13 | F6 = 8 14 | F7 = 13 15 | F8 = 21 16 | F9 = 34 17 | F10 = 55 18 | F11 = 89 19 | F12 = 144 20 | 21 | The 12th term, F12, is the first term to contain three digits. 22 | 23 | What is the index of the first term in the Fibonacci sequence to contain 1000 24 | digits? 25 | """ 26 | 27 | 28 | def fibonacci_generator(): 29 | a, b = 0, 1 30 | while True: 31 | a, b = b, a + b 32 | yield b 33 | 34 | 35 | def solution(n): 36 | """Returns the index of the first term in the Fibonacci sequence to contain 37 | n digits. 38 | 39 | >>> solution(1000) 40 | 4782 41 | >>> solution(100) 42 | 476 43 | >>> solution(50) 44 | 237 45 | >>> solution(3) 46 | 12 47 | """ 48 | answer = 1 49 | gen = fibonacci_generator() 50 | while len(str(next(gen))) < n: 51 | answer += 1 52 | return answer + 1 53 | 54 | 55 | if __name__ == "__main__": 56 | print(solution(int(str(input()).strip()))) 57 | -------------------------------------------------------------------------------- /project_euler/problem_25/sol3.py: -------------------------------------------------------------------------------- 1 | """ 2 | The Fibonacci sequence is defined by the recurrence relation: 3 | 4 | Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. 5 | 6 | Hence the first 12 terms will be: 7 | 8 | F1 = 1 9 | F2 = 1 10 | F3 = 2 11 | F4 = 3 12 | F5 = 5 13 | F6 = 8 14 | F7 = 13 15 | F8 = 21 16 | F9 = 34 17 | F10 = 55 18 | F11 = 89 19 | F12 = 144 20 | 21 | The 12th term, F12, is the first term to contain three digits. 22 | 23 | What is the index of the first term in the Fibonacci sequence to contain 1000 24 | digits? 25 | """ 26 | 27 | 28 | def solution(n): 29 | """Returns the index of the first term in the Fibonacci sequence to contain 30 | n digits. 31 | 32 | >>> solution(1000) 33 | 4782 34 | >>> solution(100) 35 | 476 36 | >>> solution(50) 37 | 237 38 | >>> solution(3) 39 | 12 40 | """ 41 | f1, f2 = 1, 1 42 | index = 2 43 | while True: 44 | i = 0 45 | f = f1 + f2 46 | f1, f2 = f2, f 47 | index += 1 48 | for j in str(f): 49 | i += 1 50 | if i == n: 51 | break 52 | return index 53 | 54 | 55 | if __name__ == "__main__": 56 | print(solution(int(str(input()).strip()))) 57 | -------------------------------------------------------------------------------- /project_euler/problem_26/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_26/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_27/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_27/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_28/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_28/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_29/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_29/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_30/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_30/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_30/soln.py: -------------------------------------------------------------------------------- 1 | """ Problem Statement (Digit Fifth Power ): https://projecteuler.net/problem=30 2 | 3 | Surprisingly there are only three numbers that can be written as the sum of fourth 4 | powers of their digits: 5 | 6 | 1634 = 1^4 + 6^4 + 3^4 + 4^4 7 | 8208 = 8^4 + 2^4 + 0^4 + 8^4 8 | 9474 = 9^4 + 4^4 + 7^4 + 4^4 9 | As 1 = 1^4 is not a sum it is not included. 10 | 11 | The sum of these numbers is 1634 + 8208 + 9474 = 19316. 12 | 13 | Find the sum of all the numbers that can be written as the sum of fifth powers of their 14 | digits. 15 | 16 | (9^5)=59,049‬ 17 | 59049*7=4,13,343 (which is only 6 digit number ) 18 | So, number greater than 9,99,999 are rejected 19 | and also 59049*3=1,77,147 (which exceeds the criteria of number being 3 digit) 20 | So, n>999 21 | and hence a bound between (1000,1000000) 22 | """ 23 | 24 | 25 | def digitsum(s: str) -> int: 26 | """ 27 | >>> all(digitsum(str(i)) == (1 if i == 1 else 0) for i in range(100)) 28 | True 29 | """ 30 | i = sum(pow(int(c), 5) for c in s) 31 | return i if i == int(s) else 0 32 | 33 | 34 | if __name__ == "__main__": 35 | count = sum(digitsum(str(i)) for i in range(1000, 1000000)) 36 | print(count) # --> 443839 37 | -------------------------------------------------------------------------------- /project_euler/problem_31/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_31/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_32/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_32/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_33/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_33/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_34/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_34/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. 3 | Find the sum of all numbers which are equal to the sum of the factorial of their digits. 4 | Note: As 1! = 1 and 2! = 2 are not sums they are not included. 5 | """ 6 | 7 | from math import factorial 8 | 9 | 10 | def sum_of_digit_factorial(n: int) -> int: 11 | """ 12 | Returns the sum of the digits in n 13 | >>> sum_of_digit_factorial(15) 14 | 121 15 | >>> sum_of_digit_factorial(0) 16 | 1 17 | """ 18 | return sum(factorial(int(char)) for char in str(n)) 19 | 20 | 21 | def compute() -> int: 22 | """ 23 | Returns the sum of all numbers whose 24 | sum of the factorials of all digits 25 | add up to the number itself. 26 | >>> compute() 27 | 40730 28 | """ 29 | limit = 7 * factorial(9) + 1 30 | return sum(i for i in range(3, limit) if sum_of_digit_factorial(i) == i) 31 | 32 | 33 | if __name__ == "__main__": 34 | print(f"{compute()} = ") 35 | -------------------------------------------------------------------------------- /project_euler/problem_35/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_36/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_36/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_37/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_39/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_40/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_40/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_40/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Champernowne's constant 3 | Problem 40 4 | An irrational decimal fraction is created by concatenating the positive 5 | integers: 6 | 7 | 0.123456789101112131415161718192021... 8 | 9 | It can be seen that the 12th digit of the fractional part is 1. 10 | 11 | If dn represents the nth digit of the fractional part, find the value of the 12 | following expression. 13 | 14 | d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 15 | """ 16 | 17 | 18 | def solution(): 19 | """Returns 20 | 21 | >>> solution() 22 | 210 23 | """ 24 | constant = [] 25 | i = 1 26 | 27 | while len(constant) < 1e6: 28 | constant.append(str(i)) 29 | i += 1 30 | 31 | constant = "".join(constant) 32 | 33 | return ( 34 | int(constant[0]) 35 | * int(constant[9]) 36 | * int(constant[99]) 37 | * int(constant[999]) 38 | * int(constant[9999]) 39 | * int(constant[99999]) 40 | * int(constant[999999]) 41 | ) 42 | 43 | 44 | if __name__ == "__main__": 45 | print(solution()) 46 | -------------------------------------------------------------------------------- /project_euler/problem_41/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_42/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_42/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_43/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_44/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_45/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_46/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_47/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_47/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_48/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_48/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_48/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Self Powers 3 | Problem 48 4 | 5 | The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. 6 | 7 | Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. 8 | """ 9 | 10 | 11 | def solution(): 12 | """ 13 | Returns the last 10 digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. 14 | 15 | >>> solution() 16 | '9110846700' 17 | """ 18 | total = 0 19 | for i in range(1, 1001): 20 | total += i ** i 21 | return str(total)[-10:] 22 | 23 | 24 | if __name__ == "__main__": 25 | print(solution()) 26 | -------------------------------------------------------------------------------- /project_euler/problem_52/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_52/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_52/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Permuted multiples 3 | Problem 52 4 | 5 | It can be seen that the number, 125874, and its double, 251748, contain exactly 6 | the same digits, but in a different order. 7 | 8 | Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, 9 | contain the same digits. 10 | """ 11 | 12 | 13 | def solution(): 14 | """Returns the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 15 | 6x, contain the same digits. 16 | 17 | >>> solution() 18 | 142857 19 | """ 20 | i = 1 21 | 22 | while True: 23 | if ( 24 | sorted(list(str(i))) 25 | == sorted(list(str(2 * i))) 26 | == sorted(list(str(3 * i))) 27 | == sorted(list(str(4 * i))) 28 | == sorted(list(str(5 * i))) 29 | == sorted(list(str(6 * i))) 30 | ): 31 | return i 32 | 33 | i += 1 34 | 35 | 36 | if __name__ == "__main__": 37 | print(solution()) 38 | -------------------------------------------------------------------------------- /project_euler/problem_53/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_53/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_53/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Combinatoric selections 3 | Problem 53 4 | 5 | There are exactly ten ways of selecting three from five, 12345: 6 | 7 | 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345 8 | 9 | In combinatorics, we use the notation, 5C3 = 10. 10 | 11 | In general, 12 | 13 | nCr = n!/(r!(n−r)!),where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1. 14 | It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066. 15 | 16 | How many, not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100, are greater 17 | than one-million? 18 | """ 19 | from math import factorial 20 | 21 | 22 | def combinations(n, r): 23 | return factorial(n) / (factorial(r) * factorial(n - r)) 24 | 25 | 26 | def solution(): 27 | """Returns the number of values of nCr, for 1 ≤ n ≤ 100, are greater than 28 | one-million 29 | 30 | >>> solution() 31 | 4075 32 | """ 33 | total = 0 34 | 35 | for i in range(1, 101): 36 | for j in range(1, i + 1): 37 | if combinations(i, j) > 1e6: 38 | total += 1 39 | return total 40 | 41 | 42 | if __name__ == "__main__": 43 | print(solution()) 44 | -------------------------------------------------------------------------------- /project_euler/problem_54/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_54/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_55/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_551/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_551/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_56/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_56/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_56/sol1.py: -------------------------------------------------------------------------------- 1 | def maximum_digital_sum(a: int, b: int) -> int: 2 | """ 3 | Considering natural numbers of the form, a**b, where a, b < 100, 4 | what is the maximum digital sum? 5 | :param a: 6 | :param b: 7 | :return: 8 | >>> maximum_digital_sum(10,10) 9 | 45 10 | 11 | >>> maximum_digital_sum(100,100) 12 | 972 13 | 14 | >>> maximum_digital_sum(100,200) 15 | 1872 16 | """ 17 | 18 | # RETURN the MAXIMUM from the list of SUMs of the list of INT converted from STR of 19 | # BASE raised to the POWER 20 | return max( 21 | [ 22 | sum([int(x) for x in str(base ** power)]) 23 | for base in range(a) 24 | for power in range(b) 25 | ] 26 | ) 27 | 28 | 29 | # Tests 30 | if __name__ == "__main__": 31 | import doctest 32 | 33 | doctest.testmod() 34 | -------------------------------------------------------------------------------- /project_euler/problem_63/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_63/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | The 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit number, 3 | 134217728=89, is a ninth power. 4 | How many n-digit positive integers exist which are also an nth power? 5 | """ 6 | 7 | """ 8 | The maximum base can be 9 because all n-digit numbers < 10^n. 9 | Now 9**23 has 22 digits so the maximum power can be 22. 10 | Using these conclusions, we will calculate the result. 11 | """ 12 | 13 | 14 | def compute_nums(max_base: int = 10, max_power: int = 22) -> int: 15 | """ 16 | Returns the count of all n-digit numbers which are nth power 17 | >>> compute_nums(10, 22) 18 | 49 19 | >>> compute_nums(0, 0) 20 | 0 21 | >>> compute_nums(1, 1) 22 | 0 23 | >>> compute_nums(-1, -1) 24 | 0 25 | """ 26 | bases = range(1, max_base) 27 | powers = range(1, max_power) 28 | return sum( 29 | 1 for power in powers for base in bases if len(str((base ** power))) == power 30 | ) 31 | 32 | 33 | if __name__ == "__main__": 34 | print(f"{compute_nums(10, 22) = }") 35 | -------------------------------------------------------------------------------- /project_euler/problem_67/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_67/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_76/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_76/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_97/__init__.py: -------------------------------------------------------------------------------- 1 | # 2 | -------------------------------------------------------------------------------- /project_euler/problem_99/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/project_euler/problem_99/__init__.py -------------------------------------------------------------------------------- /project_euler/problem_99/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: 3 | 4 | Comparing two numbers written in index form like 2'11 and 3'7 is not difficult, as any 5 | calculator would confirm that 2^11 = 2048 < 3^7 = 2187. 6 | 7 | However, confirming that 632382^518061 > 519432^525806 would be much more difficult, as 8 | both numbers contain over three million digits. 9 | 10 | Using base_exp.txt, a 22K text file containing one thousand lines with a base/exponent 11 | pair on each line, determine which line number has the greatest numerical value. 12 | 13 | NOTE: The first two lines in the file represent the numbers in the example given above. 14 | """ 15 | 16 | import os 17 | from math import log10 18 | 19 | 20 | def find_largest(data_file: str = "base_exp.txt") -> int: 21 | """ 22 | >>> find_largest() 23 | 709 24 | """ 25 | largest = [0, 0] 26 | for i, line in enumerate(open(os.path.join(os.path.dirname(__file__), data_file))): 27 | a, x = list(map(int, line.split(","))) 28 | if x * log10(a) > largest[0]: 29 | largest = [x * log10(a), i + 1] 30 | return largest[1] 31 | 32 | 33 | if __name__ == "__main__": 34 | print(find_largest()) 35 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | # Setup for pytest 2 | [pytest] 3 | markers = 4 | mat_ops: mark a test as utilizing matrix operations. 5 | -------------------------------------------------------------------------------- /quantum/README.md: -------------------------------------------------------------------------------- 1 | # Welcome to Quantum Algorithms 2 | 3 | Started at https://github.com/TheAlgorithms/Python/issues/1831 4 | 5 | * D-Wave: https://www.dwavesys.com and https://github.com/dwavesystems 6 | * Google: https://research.google/teams/applied-science/quantum 7 | * IBM: https://qiskit.org and https://github.com/Qiskit 8 | * Rigetti: https://rigetti.com and https://github.com/rigetti 9 | -------------------------------------------------------------------------------- /quantum/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/quantum/__init__.py -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | beautifulsoup4 2 | fake_useragent 3 | keras 4 | lxml 5 | matplotlib 6 | numpy 7 | opencv-python 8 | pandas 9 | pillow 10 | requests 11 | scikit-fuzzy 12 | sklearn 13 | sympy 14 | tensorflow 15 | xgboost 16 | -------------------------------------------------------------------------------- /scheduling/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/scheduling/__init__.py -------------------------------------------------------------------------------- /scripts/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/scripts/__init__.py -------------------------------------------------------------------------------- /searches/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/searches/__init__.py -------------------------------------------------------------------------------- /searches/double_linear_search_recursion.py: -------------------------------------------------------------------------------- 1 | def search(list_data: list, key: int, left: int = 0, right: int = 0) -> int: 2 | """ 3 | Iterate through the array to find the index of key using recursion. 4 | :param list_data: the list to be searched 5 | :param key: the key to be searched 6 | :param left: the index of first element 7 | :param right: the index of last element 8 | :return: the index of key value if found, -1 otherwise. 9 | 10 | >>> search(list(range(0, 11)), 5) 11 | 5 12 | >>> search([1, 2, 4, 5, 3], 4) 13 | 2 14 | >>> search([1, 2, 4, 5, 3], 6) 15 | -1 16 | >>> search([5], 5) 17 | 0 18 | >>> search([], 1) 19 | -1 20 | """ 21 | right = right or len(list_data) - 1 22 | if left > right: 23 | return -1 24 | elif list_data[left] == key: 25 | return left 26 | elif list_data[right] == key: 27 | return right 28 | else: 29 | return search(list_data, key, left + 1, right - 1) 30 | 31 | 32 | if __name__ == "__main__": 33 | import doctest 34 | 35 | doctest.testmod() 36 | -------------------------------------------------------------------------------- /searches/tabu_test_data.txt: -------------------------------------------------------------------------------- 1 | a b 20 2 | a c 18 3 | a d 22 4 | a e 26 5 | b c 10 6 | b d 11 7 | b e 12 8 | c d 23 9 | c e 24 10 | d e 40 11 | -------------------------------------------------------------------------------- /sorts/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/sorts/__init__.py -------------------------------------------------------------------------------- /sorts/i_sort.py: -------------------------------------------------------------------------------- 1 | def insertionSort(arr): 2 | """ 3 | >>> a = arr[:] 4 | >>> insertionSort(a) 5 | >>> a == sorted(a) 6 | True 7 | """ 8 | for i in range(1, len(arr)): 9 | key = arr[i] 10 | j = i - 1 11 | while j >= 0 and key < arr[j]: 12 | arr[j + 1] = arr[j] 13 | j -= 1 14 | arr[j + 1] = key 15 | 16 | 17 | arr = [12, 11, 13, 5, 6] 18 | insertionSort(arr) 19 | print("Sorted array is:") 20 | for i in range(len(arr)): 21 | print("%d" % arr[i]) 22 | -------------------------------------------------------------------------------- /sorts/odd_even_transposition_single_threaded.py: -------------------------------------------------------------------------------- 1 | """ 2 | Source: https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort 3 | 4 | This is a non-parallelized implementation of odd-even transpostiion sort. 5 | 6 | Normally the swaps in each set happen simultaneously, without that the algorithm 7 | is no better than bubble sort. 8 | """ 9 | 10 | 11 | def odd_even_transposition(arr: list) -> list: 12 | """ 13 | >>> odd_even_transposition([5, 4, 3, 2, 1]) 14 | [1, 2, 3, 4, 5] 15 | 16 | >>> odd_even_transposition([13, 11, 18, 0, -1]) 17 | [-1, 0, 11, 13, 18] 18 | 19 | >>> odd_even_transposition([-.1, 1.1, .1, -2.9]) 20 | [-2.9, -0.1, 0.1, 1.1] 21 | """ 22 | arr_size = len(arr) 23 | for _ in range(arr_size): 24 | for i in range(_ % 2, arr_size - 1, 2): 25 | if arr[i + 1] < arr[i]: 26 | arr[i], arr[i + 1] = arr[i + 1], arr[i] 27 | 28 | return arr 29 | 30 | 31 | if __name__ == "__main__": 32 | arr = list(range(10, 0, -1)) 33 | print(f"Original: {arr}. Sorted: {odd_even_transposition(arr)}") 34 | -------------------------------------------------------------------------------- /sorts/radix_sort.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | 4 | def radix_sort(list_of_ints: list[int]) -> list[int]: 5 | """ 6 | radix_sort(range(15)) == sorted(range(15)) 7 | True 8 | radix_sort(reversed(range(15))) == sorted(range(15)) 9 | True 10 | radix_sort([1,100,10,1000]) == sorted([1,100,10,1000]) 11 | True 12 | """ 13 | RADIX = 10 14 | placement = 1 15 | max_digit = max(list_of_ints) 16 | while placement <= max_digit: 17 | # declare and initialize empty buckets 18 | buckets = [list() for _ in range(RADIX)] 19 | # split list_of_ints between the buckets 20 | for i in list_of_ints: 21 | tmp = int((i / placement) % RADIX) 22 | buckets[tmp].append(i) 23 | # put each buckets' contents into list_of_ints 24 | a = 0 25 | for b in range(RADIX): 26 | for i in buckets[b]: 27 | list_of_ints[a] = i 28 | a += 1 29 | # move to next 30 | placement *= RADIX 31 | return list_of_ints 32 | -------------------------------------------------------------------------------- /sorts/recursive_quick_sort.py: -------------------------------------------------------------------------------- 1 | def quick_sort(data: list) -> list: 2 | """ 3 | >>> for data in ([2, 1, 0], [2.2, 1.1, 0], "quick_sort"): 4 | ... quick_sort(data) == sorted(data) 5 | True 6 | True 7 | True 8 | """ 9 | if len(data) <= 1: 10 | return data 11 | else: 12 | return ( 13 | quick_sort([e for e in data[1:] if e <= data[0]]) 14 | + [data[0]] 15 | + quick_sort([e for e in data[1:] if e > data[0]]) 16 | ) 17 | 18 | 19 | if __name__ == "__main__": 20 | import doctest 21 | 22 | doctest.testmod() 23 | -------------------------------------------------------------------------------- /sorts/stooge_sort.py: -------------------------------------------------------------------------------- 1 | def stooge_sort(arr): 2 | """ 3 | Examples: 4 | >>> stooge_sort([18.1, 0, -7.1, -1, 2, 2]) 5 | [-7.1, -1, 0, 2, 2, 18.1] 6 | 7 | >>> stooge_sort([]) 8 | [] 9 | """ 10 | stooge(arr, 0, len(arr) - 1) 11 | return arr 12 | 13 | 14 | def stooge(arr, i, h): 15 | 16 | if i >= h: 17 | return 18 | 19 | # If first element is smaller than the last then swap them 20 | if arr[i] > arr[h]: 21 | arr[i], arr[h] = arr[h], arr[i] 22 | 23 | # If there are more than 2 elements in the array 24 | if h - i + 1 > 2: 25 | t = (int)((h - i + 1) / 3) 26 | 27 | # Recursively sort first 2/3 elements 28 | stooge(arr, i, (h - t)) 29 | 30 | # Recursively sort last 2/3 elements 31 | stooge(arr, i + t, (h)) 32 | 33 | # Recursively sort first 2/3 elements 34 | stooge(arr, i, (h - t)) 35 | 36 | 37 | if __name__ == "__main__": 38 | user_input = input("Enter numbers separated by a comma:\n").strip() 39 | unsorted = [int(item) for item in user_input.split(",")] 40 | print(stooge_sort(unsorted)) 41 | -------------------------------------------------------------------------------- /sorts/topological_sort.py: -------------------------------------------------------------------------------- 1 | """Topological Sort.""" 2 | 3 | # a 4 | # / \ 5 | # b c 6 | # / \ 7 | # d e 8 | edges = {"a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": []} 9 | vertices = ["a", "b", "c", "d", "e"] 10 | 11 | 12 | def topological_sort(start, visited, sort): 13 | """Perform topolical sort on a directed acyclic graph.""" 14 | current = start 15 | # add current to visited 16 | visited.append(current) 17 | neighbors = edges[current] 18 | for neighbor in neighbors: 19 | # if neighbor not in visited, visit 20 | if neighbor not in visited: 21 | sort = topological_sort(neighbor, visited, sort) 22 | # if all neighbors visited add current to sort 23 | sort.append(current) 24 | # if all vertices haven't been visited select a new one to visit 25 | if len(visited) != len(vertices): 26 | for vertice in vertices: 27 | if vertice not in visited: 28 | sort = topological_sort(vertice, visited, sort) 29 | # return sort 30 | return sort 31 | 32 | 33 | if __name__ == "__main__": 34 | sort = topological_sort("a", [], []) 35 | print(sort) 36 | -------------------------------------------------------------------------------- /sorts/wiggle_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Wiggle Sort. 3 | 4 | Given an unsorted array nums, reorder it such 5 | that nums[0] < nums[1] > nums[2] < nums[3].... 6 | For example: 7 | if input numbers = [3, 5, 2, 1, 6, 4] 8 | one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4]. 9 | """ 10 | 11 | 12 | def wiggle_sort(nums: list) -> list: 13 | """ 14 | Python implementation of wiggle. 15 | Example: 16 | >>> wiggle_sort([0, 5, 3, 2, 2]) 17 | [0, 5, 2, 3, 2] 18 | >>> wiggle_sort([]) 19 | [] 20 | >>> wiggle_sort([-2, -5, -45]) 21 | [-45, -2, -5] 22 | >>> wiggle_sort([-2.1, -5.68, -45.11]) 23 | [-45.11, -2.1, -5.68] 24 | """ 25 | for i, _ in enumerate(nums): 26 | if (i % 2 == 1) == (nums[i - 1] > nums[i]): 27 | nums[i - 1], nums[i] = nums[i], nums[i - 1] 28 | 29 | return nums 30 | 31 | 32 | if __name__ == "__main__": 33 | print("Enter the array elements:") 34 | array = list(map(int, input().split())) 35 | print("The unsorted array is:") 36 | print(array) 37 | print("Array after Wiggle sort:") 38 | print(wiggle_sort(array)) 39 | -------------------------------------------------------------------------------- /strings/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/strings/__init__.py -------------------------------------------------------------------------------- /strings/capitalize.py: -------------------------------------------------------------------------------- 1 | from string import ascii_lowercase, ascii_uppercase 2 | 3 | 4 | def capitalize(sentence: str) -> str: 5 | """ 6 | This function will capitalize the first letter of a sentence or a word 7 | >>> capitalize("hello world") 8 | 'Hello world' 9 | >>> capitalize("123 hello world") 10 | '123 hello world' 11 | >>> capitalize(" hello world") 12 | ' hello world' 13 | >>> capitalize("a") 14 | 'A' 15 | >>> capitalize("") 16 | '' 17 | """ 18 | if not sentence: 19 | return "" 20 | lower_to_upper = {lc: uc for lc, uc in zip(ascii_lowercase, ascii_uppercase)} 21 | return lower_to_upper.get(sentence[0], sentence[0]) + sentence[1:] 22 | 23 | 24 | if __name__ == "__main__": 25 | from doctest import testmod 26 | 27 | testmod() 28 | -------------------------------------------------------------------------------- /strings/check_anagrams.py: -------------------------------------------------------------------------------- 1 | """ 2 | wiki: https://en.wikipedia.org/wiki/Anagram 3 | """ 4 | 5 | 6 | def check_anagrams(first_str: str, second_str: str) -> bool: 7 | """ 8 | Two strings are anagrams if they are made of the same letters 9 | arranged differently (ignoring the case). 10 | >>> check_anagrams('Silent', 'Listen') 11 | True 12 | >>> check_anagrams('This is a string', 'Is this a string') 13 | True 14 | >>> check_anagrams('This is a string', 'Is this a string') 15 | True 16 | >>> check_anagrams('There', 'Their') 17 | False 18 | """ 19 | return ( 20 | "".join(sorted(first_str.lower())).strip() 21 | == "".join(sorted(second_str.lower())).strip() 22 | ) 23 | 24 | 25 | if __name__ == "__main__": 26 | from doctest import testmod 27 | 28 | testmod() 29 | input_A = input("Enter the first string ").strip() 30 | input_B = input("Enter the second string ").strip() 31 | 32 | status = check_anagrams(input_A, input_B) 33 | print(f"{input_A} and {input_B} are {'' if status else 'not '}anagrams.") 34 | -------------------------------------------------------------------------------- /strings/is_palindrome.py: -------------------------------------------------------------------------------- 1 | def is_palindrome(s: str) -> bool: 2 | """ 3 | Determine whether the string is palindrome 4 | :param s: 5 | :return: Boolean 6 | >>> is_palindrome("a man a plan a canal panama".replace(" ", "")) 7 | True 8 | >>> is_palindrome("Hello") 9 | False 10 | >>> is_palindrome("Able was I ere I saw Elba") 11 | True 12 | >>> is_palindrome("racecar") 13 | True 14 | >>> is_palindrome("Mr. Owl ate my metal worm?") 15 | True 16 | """ 17 | # Since Punctuation, capitalization, and spaces are usually ignored while checking 18 | # Palindrome, we first remove them from our string. 19 | s = "".join([character for character in s.lower() if character.isalnum()]) 20 | return s == s[::-1] 21 | 22 | 23 | if __name__ == "__main__": 24 | s = input("Enter string to determine whether its palindrome or not: ").strip() 25 | if is_palindrome(s): 26 | print("Given string is palindrome") 27 | else: 28 | print("Given string is not palindrome") 29 | -------------------------------------------------------------------------------- /strings/lower.py: -------------------------------------------------------------------------------- 1 | def lower(word: str) -> str: 2 | """ 3 | Will convert the entire string to lowecase letters 4 | 5 | >>> lower("wow") 6 | 'wow' 7 | >>> lower("HellZo") 8 | 'hellzo' 9 | >>> lower("WHAT") 10 | 'what' 11 | >>> lower("wh[]32") 12 | 'wh[]32' 13 | >>> lower("whAT") 14 | 'what' 15 | """ 16 | 17 | # converting to ascii value int value and checking to see if char is a capital 18 | # letter if it is a capital letter it is getting shift by 32 which makes it a lower 19 | # case letter 20 | return "".join(chr(ord(char) + 32) if "A" <= char <= "Z" else char for char in word) 21 | 22 | 23 | if __name__ == "__main__": 24 | from doctest import testmod 25 | 26 | testmod() 27 | -------------------------------------------------------------------------------- /strings/remove_duplicate.py: -------------------------------------------------------------------------------- 1 | def remove_duplicates(sentence: str) -> str: 2 | """ 3 | Remove duplicates from sentence 4 | >>> remove_duplicates("Python is great and Java is also great") 5 | 'Java Python also and great is' 6 | >>> remove_duplicates("Python is great and Java is also great") 7 | 'Java Python also and great is' 8 | """ 9 | return " ".join(sorted(set(sentence.split()))) 10 | 11 | 12 | if __name__ == "__main__": 13 | import doctest 14 | 15 | doctest.testmod() 16 | -------------------------------------------------------------------------------- /strings/reverse_words.py: -------------------------------------------------------------------------------- 1 | def reverse_words(input_str: str) -> str: 2 | """ 3 | Reverses words in a given string 4 | >>> reverse_words("I love Python") 5 | 'Python love I' 6 | >>> reverse_words("I Love Python") 7 | 'Python Love I' 8 | """ 9 | return " ".join(input_str.split()[::-1]) 10 | 11 | 12 | if __name__ == "__main__": 13 | import doctest 14 | 15 | doctest.testmod() 16 | -------------------------------------------------------------------------------- /strings/split.py: -------------------------------------------------------------------------------- 1 | def split(string: str, separator: str = " ") -> list: 2 | """ 3 | Will split the string up into all the values separated by the separator 4 | (defaults to spaces) 5 | 6 | >>> split("apple#banana#cherry#orange",separator='#') 7 | ['apple', 'banana', 'cherry', 'orange'] 8 | 9 | >>> split("Hello there") 10 | ['Hello', 'there'] 11 | 12 | >>> split("11/22/63",separator = '/') 13 | ['11', '22', '63'] 14 | 15 | >>> split("12:43:39",separator = ":") 16 | ['12', '43', '39'] 17 | """ 18 | 19 | split_words = [] 20 | 21 | last_index = 0 22 | for index, char in enumerate(string): 23 | if char == separator: 24 | split_words.append(string[last_index:index]) 25 | last_index = index + 1 26 | elif index + 1 == len(string): 27 | split_words.append(string[last_index : index + 1]) 28 | return split_words 29 | 30 | 31 | if __name__ == "__main__": 32 | from doctest import testmod 33 | 34 | testmod() 35 | -------------------------------------------------------------------------------- /strings/upper.py: -------------------------------------------------------------------------------- 1 | def upper(word: str) -> str: 2 | """ 3 | Will convert the entire string to uppercase letters 4 | 5 | >>> upper("wow") 6 | 'WOW' 7 | >>> upper("Hello") 8 | 'HELLO' 9 | >>> upper("WHAT") 10 | 'WHAT' 11 | >>> upper("wh[]32") 12 | 'WH[]32' 13 | """ 14 | 15 | # converting to ascii value int value and checking to see if char is a lower letter 16 | # if it is a capital letter it is getting shift by 32 which makes it a capital case 17 | # letter 18 | return "".join(chr(ord(char) - 32) if "a" <= char <= "z" else char for char in word) 19 | 20 | 21 | if __name__ == "__main__": 22 | from doctest import testmod 23 | 24 | testmod() 25 | -------------------------------------------------------------------------------- /strings/word_occurrence.py: -------------------------------------------------------------------------------- 1 | # Created by sarathkaul on 17/11/19 2 | # Modified by Arkadip Bhattacharya(@darkmatter18) on 20/04/2020 3 | from collections import defaultdict 4 | 5 | 6 | def word_occurence(sentence: str) -> dict: 7 | """ 8 | >>> from collections import Counter 9 | >>> SENTENCE = "a b A b c b d b d e f e g e h e i e j e 0" 10 | >>> occurence_dict = word_occurence(SENTENCE) 11 | >>> all(occurence_dict[word] == count for word, count 12 | ... in Counter(SENTENCE.split()).items()) 13 | True 14 | >>> dict(word_occurence("Two spaces")) 15 | {'Two': 1, 'spaces': 1} 16 | """ 17 | occurrence = defaultdict(int) 18 | # Creating a dictionary containing count of each word 19 | for word in sentence.split(): 20 | occurrence[word] += 1 21 | return occurrence 22 | 23 | 24 | if __name__ == "__main__": 25 | for word, count in word_occurence("INPUT STRING").items(): 26 | print(f"{word}: {count}") 27 | -------------------------------------------------------------------------------- /traversals/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/traversals/__init__.py -------------------------------------------------------------------------------- /web_programming/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ishan7390/Python/2388bf4e17935a9860319831473e6a2e0f801b71/web_programming/__init__.py -------------------------------------------------------------------------------- /web_programming/covid_stats_via_xpath.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is to show simple COVID19 info fetching from worldometers site using lxml 3 | * The main motivation to use lxml in place of bs4 is that it is faster and therefore 4 | more convenient to use in Python web projects (e.g. Django or Flask-based) 5 | """ 6 | 7 | from collections import namedtuple 8 | 9 | import requests 10 | from lxml import html 11 | 12 | covid_data = namedtuple("covid_data", "cases deaths recovered") 13 | 14 | 15 | def covid_stats(url: str = "https://www.worldometers.info/coronavirus/") -> covid_data: 16 | xpath_str = '//div[@class = "maincounter-number"]/span/text()' 17 | return covid_data(*html.fromstring(requests.get(url).content).xpath(xpath_str)) 18 | 19 | 20 | fmt = """Total COVID-19 cases in the world: {} 21 | Total deaths due to COVID-19 in the world: {} 22 | Total COVID-19 patients recovered in the world: {}""" 23 | print(fmt.format(*covid_stats())) 24 | -------------------------------------------------------------------------------- /web_programming/crawl_google_results.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import webbrowser 3 | 4 | import requests 5 | from bs4 import BeautifulSoup 6 | from fake_useragent import UserAgent 7 | 8 | if __name__ == "__main__": 9 | print("Googling.....") 10 | url = "https://www.google.com/search?q=" + " ".join(sys.argv[1:]) 11 | res = requests.get(url, headers={"UserAgent": UserAgent().random}) 12 | # res.raise_for_status() 13 | with open("project1a.html", "wb") as out_file: # only for knowing the class 14 | for data in res.iter_content(10000): 15 | out_file.write(data) 16 | soup = BeautifulSoup(res.text, "html.parser") 17 | links = list(soup.select(".eZt8xd"))[:5] 18 | 19 | print(len(links)) 20 | for link in links: 21 | if link.text == "Maps": 22 | webbrowser.open(link.get("href")) 23 | else: 24 | webbrowser.open(f"http://google.com{link.get('href')}") 25 | -------------------------------------------------------------------------------- /web_programming/current_stock_price.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup 3 | 4 | 5 | def stock_price(symbol: str = "AAPL") -> str: 6 | url = f"https://in.finance.yahoo.com/quote/{symbol}?s={symbol}" 7 | soup = BeautifulSoup(requests.get(url).text, "html.parser") 8 | class_ = "My(6px) Pos(r) smartphone_Mt(6px)" 9 | return soup.find("div", class_=class_).find("span").text 10 | 11 | 12 | if __name__ == "__main__": 13 | for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): 14 | print(f"Current {symbol:<4} stock price is {stock_price(symbol):>8}") 15 | -------------------------------------------------------------------------------- /web_programming/current_weather.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | APPID = "" # <-- Put your OpenWeatherMap appid here! 4 | URL_BASE = "http://api.openweathermap.org/data/2.5/" 5 | 6 | 7 | def current_weather(q: str = "Chicago", appid: str = APPID) -> dict: 8 | """https://openweathermap.org/api""" 9 | return requests.get(URL_BASE + "weather", params=locals()).json() 10 | 11 | 12 | def weather_forecast(q: str = "Kolkata, India", appid: str = APPID) -> dict: 13 | """https://openweathermap.org/forecast5""" 14 | return requests.get(URL_BASE + "forecast", params=locals()).json() 15 | 16 | 17 | def weather_onecall(lat: float = 55.68, lon: float = 12.57, appid: str = APPID) -> dict: 18 | """https://openweathermap.org/api/one-call-api""" 19 | return requests.get(URL_BASE + "onecall", params=locals()).json() 20 | 21 | 22 | if __name__ == "__main__": 23 | from pprint import pprint 24 | 25 | while True: 26 | location = input("Enter a location:").strip() 27 | if location: 28 | pprint(current_weather(location)) 29 | else: 30 | break 31 | -------------------------------------------------------------------------------- /web_programming/daily_horoscope.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup 3 | 4 | 5 | def horoscope(zodiac_sign: int, day: str) -> str: 6 | url = ( 7 | "https://www.horoscope.com/us/horoscopes/general/" 8 | f"horoscope-general-daily-{day}.aspx?sign={zodiac_sign}" 9 | ) 10 | soup = BeautifulSoup(requests.get(url).content, "html.parser") 11 | return soup.find("div", class_="main-horoscope").p.text 12 | 13 | 14 | if __name__ == "__main__": 15 | print("Daily Horoscope. \n") 16 | print( 17 | "enter your Zodiac sign number:\n", 18 | "1. Aries\n", 19 | "2. Taurus\n", 20 | "3. Gemini\n", 21 | "4. Cancer\n", 22 | "5. Leo\n", 23 | "6. Virgo\n", 24 | "7. Libra\n", 25 | "8. Scorpio\n", 26 | "9. Sagittarius\n", 27 | "10. Capricorn\n", 28 | "11. Aquarius\n", 29 | "12. Pisces\n", 30 | ) 31 | zodiac_sign = int(input("number> ").strip()) 32 | print("choose some day:\n", "yesterday\n", "today\n", "tomorrow\n") 33 | day = input("enter the day> ") 34 | horoscope_text = horoscope(zodiac_sign, day) 35 | print(horoscope_text) 36 | -------------------------------------------------------------------------------- /web_programming/fetch_bbc_news.py: -------------------------------------------------------------------------------- 1 | # Created by sarathkaul on 12/11/19 2 | 3 | import requests 4 | 5 | _NEWS_API = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" 6 | 7 | 8 | def fetch_bbc_news(bbc_news_api_key: str) -> None: 9 | # fetching a list of articles in json format 10 | bbc_news_page = requests.get(_NEWS_API + bbc_news_api_key).json() 11 | # each article in the list is a dict 12 | for i, article in enumerate(bbc_news_page["articles"], 1): 13 | print(f"{i}.) {article['title']}") 14 | 15 | 16 | if __name__ == "__main__": 17 | fetch_bbc_news(bbc_news_api_key="") 18 | -------------------------------------------------------------------------------- /web_programming/fetch_github_info.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """ 4 | Created by sarathkaul on 14/11/19 5 | 6 | Basic authentication using an API password is deprecated and will soon no longer work. 7 | Visit https://developer.github.com/changes/2020-02-14-deprecating-password-auth 8 | for more information around suggested workarounds and removal dates. 9 | """ 10 | 11 | 12 | import requests 13 | 14 | _GITHUB_API = "https://api.github.com/user" 15 | 16 | 17 | def fetch_github_info(auth_user: str, auth_pass: str) -> dict: 18 | """ 19 | Fetch GitHub info of a user using the requests module 20 | """ 21 | return requests.get(_GITHUB_API, auth=(auth_user, auth_pass)).json() 22 | 23 | 24 | if __name__ == "__main__": 25 | for key, value in fetch_github_info("", "").items(): 26 | print(f"{key}: {value}") 27 | -------------------------------------------------------------------------------- /web_programming/fetch_jobs.py: -------------------------------------------------------------------------------- 1 | """ 2 | Scraping jobs given job title and location from indeed website 3 | """ 4 | from __future__ import annotations 5 | 6 | from typing import Generator 7 | 8 | import requests 9 | from bs4 import BeautifulSoup 10 | 11 | url = "https://www.indeed.co.in/jobs?q=mobile+app+development&l=" 12 | 13 | 14 | def fetch_jobs(location: str = "mumbai") -> Generator[tuple[str, str], None, None]: 15 | soup = BeautifulSoup(requests.get(url + location).content, "html.parser") 16 | # This attribute finds out all the specifics listed in a job 17 | for job in soup.find_all("div", attrs={"data-tn-component": "organicJob"}): 18 | job_title = job.find("a", attrs={"data-tn-element": "jobTitle"}).text.strip() 19 | company_name = job.find("span", {"class": "company"}).text.strip() 20 | yield job_title, company_name 21 | 22 | 23 | if __name__ == "__main__": 24 | for i, job in enumerate(fetch_jobs("Bangalore"), 1): 25 | print(f"Job {i:>2} is {job[0]} at {job[1]}") 26 | -------------------------------------------------------------------------------- /web_programming/get_imdb_top_250_movies_csv.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import csv 4 | 5 | import requests 6 | from bs4 import BeautifulSoup 7 | 8 | 9 | def get_imdb_top_250_movies(url: str = "") -> dict[str, float]: 10 | url = url or "https://www.imdb.com/chart/top/?ref_=nv_mv_250" 11 | soup = BeautifulSoup(requests.get(url).text, "html.parser") 12 | titles = soup.find_all("td", attrs="titleColumn") 13 | ratings = soup.find_all("td", class_="ratingColumn imdbRating") 14 | return { 15 | title.a.text: float(rating.strong.text) 16 | for title, rating in zip(titles, ratings) 17 | } 18 | 19 | 20 | def write_movies(filename: str = "IMDb_Top_250_Movies.csv") -> None: 21 | movies = get_imdb_top_250_movies() 22 | with open(filename, "w", newline="") as out_file: 23 | writer = csv.writer(out_file) 24 | writer.writerow(["Movie title", "IMDb rating"]) 25 | for title, rating in movies.items(): 26 | writer.writerow([title, rating]) 27 | 28 | 29 | if __name__ == "__main__": 30 | write_movies() 31 | -------------------------------------------------------------------------------- /web_programming/get_imdbtop.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup 3 | 4 | 5 | def imdb_top(imdb_top_n): 6 | base_url = ( 7 | f"https://www.imdb.com/search/title?title_type=" 8 | f"feature&sort=num_votes,desc&count={imdb_top_n}" 9 | ) 10 | source = BeautifulSoup(requests.get(base_url).content, "html.parser") 11 | for m in source.findAll("div", class_="lister-item mode-advanced"): 12 | print("\n" + m.h3.a.text) # movie's name 13 | print(m.find("span", attrs={"class": "genre"}).text) # genre 14 | print(m.strong.text) # movie's rating 15 | print(f"https://www.imdb.com{m.a.get('href')}") # movie's page link 16 | print("*" * 40) 17 | 18 | 19 | if __name__ == "__main__": 20 | imdb_top(input("How many movies would you like to see? ")) 21 | -------------------------------------------------------------------------------- /web_programming/slack_message.py: -------------------------------------------------------------------------------- 1 | # Created by sarathkaul on 12/11/19 2 | 3 | import requests 4 | 5 | 6 | def send_slack_message(message_body: str, slack_url: str) -> None: 7 | headers = {"Content-Type": "application/json"} 8 | response = requests.post(slack_url, json={"text": message_body}, headers=headers) 9 | if response.status_code != 200: 10 | raise ValueError( 11 | f"Request to slack returned an error {response.status_code}, " 12 | f"the response is:\n{response.text}" 13 | ) 14 | 15 | 16 | if __name__ == "main": 17 | # Set the slack url to the one provided by Slack when you create the webhook at 18 | # https://my.slack.com/services/new/incoming-webhook/ 19 | send_slack_message("", "") 20 | -------------------------------------------------------------------------------- /web_programming/world_covid19_stats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """ 4 | Provide the current worldwide COVID-19 statistics. 5 | This data is being scrapped from 'https://www.worldometers.info/coronavirus/'. 6 | """ 7 | 8 | import requests 9 | from bs4 import BeautifulSoup 10 | 11 | 12 | def world_covid19_stats(url: str = "https://www.worldometers.info/coronavirus") -> dict: 13 | """ 14 | Return a dict of current worldwide COVID-19 statistics 15 | """ 16 | soup = BeautifulSoup(requests.get(url).text, "html.parser") 17 | keys = soup.findAll("h1") 18 | values = soup.findAll("div", {"class": "maincounter-number"}) 19 | keys += soup.findAll("span", {"class": "panel-title"}) 20 | values += soup.findAll("div", {"class": "number-table-main"}) 21 | return {key.text.strip(): value.text.strip() for key, value in zip(keys, values)} 22 | 23 | 24 | if __name__ == "__main__": 25 | print("\033[1m" + "COVID-19 Status of the World" + "\033[0m\n") 26 | for key, value in world_covid19_stats().items(): 27 | print(f"{key}\n{value}\n") 28 | --------------------------------------------------------------------------------