├── .devcontainer
├── Dockerfile
├── README.md
└── devcontainer.json
├── .gitattributes
├── .github
├── CODEOWNERS
├── ISSUE_TEMPLATE
│ ├── bug_report.yml
│ ├── config.yml
│ ├── feature_request.yml
│ └── other.yml
├── dependabot.yml
├── pull_request_template.md
├── stale.yml
└── workflows
│ ├── build.yml
│ ├── directory_writer.yml
│ ├── project_euler.yml
│ ├── ruff.yml
│ └── sphinx.yml
├── .gitignore
├── .gitpod.yml
├── .pre-commit-config.yaml
├── .vscode
└── settings.json
├── CONTRIBUTING.md
├── DIRECTORY.md
├── LICENSE.md
├── README.md
├── audio_filters
├── README.md
├── __init__.py
├── butterworth_filter.py
├── equal_loudness_filter.py.broken.txt
├── iir_filter.py
├── loudness_curve.json
└── show_response.py
├── backtracking
├── README.md
├── __init__.py
├── all_combinations.py
├── all_permutations.py
├── all_subsequences.py
├── coloring.py
├── combination_sum.py
├── crossword_puzzle_solver.py
├── generate_parentheses.py
├── hamiltonian_cycle.py
├── knight_tour.py
├── match_word_pattern.py
├── minimax.py
├── n_queens.py
├── n_queens_math.py
├── power_sum.py
├── rat_in_maze.py
├── sudoku.py
├── sum_of_subsets.py
├── word_break.py
├── word_ladder.py
└── word_search.py
├── bit_manipulation
├── README.md
├── __init__.py
├── binary_and_operator.py
├── binary_coded_decimal.py
├── binary_count_setbits.py
├── binary_count_trailing_zeros.py
├── binary_or_operator.py
├── binary_shifts.py
├── binary_twos_complement.py
├── binary_xor_operator.py
├── bitwise_addition_recursive.py
├── count_1s_brian_kernighan_method.py
├── count_number_of_one_bits.py
├── excess_3_code.py
├── find_previous_power_of_two.py
├── find_unique_number.py
├── gray_code_sequence.py
├── highest_set_bit.py
├── index_of_rightmost_set_bit.py
├── is_even.py
├── is_power_of_two.py
├── largest_pow_of_two_le_num.py
├── missing_number.py
├── numbers_different_signs.py
├── power_of_4.py
├── reverse_bits.py
├── single_bit_manipulation_operations.py
└── swap_all_odd_and_even_bits.py
├── blockchain
├── README.md
├── __init__.py
└── diophantine_equation.py
├── boolean_algebra
├── README.md
├── __init__.py
├── and_gate.py
├── imply_gate.py
├── karnaugh_map_simplification.py
├── multiplexer.py
├── nand_gate.py
├── nimply_gate.py
├── nor_gate.py
├── not_gate.py
├── or_gate.py
├── quine_mc_cluskey.py
├── xnor_gate.py
└── xor_gate.py
├── cellular_automata
├── README.md
├── __init__.py
├── conways_game_of_life.py
├── game_of_life.py
├── langtons_ant.py
├── nagel_schrekenberg.py
├── one_dimensional.py
└── wa_tor.py
├── ciphers
├── README.md
├── __init__.py
├── a1z26.py
├── affine_cipher.py
├── atbash.py
├── autokey.py
├── baconian_cipher.py
├── base16.py
├── base32.py
├── base64_cipher.py
├── base85.py
├── beaufort_cipher.py
├── bifid.py
├── brute_force_caesar_cipher.py
├── caesar_cipher.py
├── cryptomath_module.py
├── decrypt_caesar_with_chi_squared.py
├── deterministic_miller_rabin.py
├── diffie.py
├── diffie_hellman.py
├── elgamal_key_generator.py
├── enigma_machine2.py
├── fractionated_morse_cipher.py
├── gronsfeld_cipher.py
├── hill_cipher.py
├── mixed_keyword_cypher.py
├── mono_alphabetic_ciphers.py
├── morse_code.py
├── onepad_cipher.py
├── permutation_cipher.py
├── playfair_cipher.py
├── polybius.py
├── porta_cipher.py
├── prehistoric_men.txt
├── rabin_miller.py
├── rail_fence_cipher.py
├── rot13.py
├── rsa_cipher.py
├── rsa_factorization.py
├── rsa_key_generator.py
├── running_key_cipher.py
├── shuffled_shift_cipher.py
├── simple_keyword_cypher.py
├── simple_substitution_cipher.py
├── transposition_cipher.py
├── transposition_cipher_encrypt_decrypt_file.py
├── trifid_cipher.py
├── vernam_cipher.py
├── vigenere_cipher.py
└── xor_cipher.py
├── computer_vision
├── README.md
├── __init__.py
├── cnn_classification.py
├── flip_augmentation.py
├── haralick_descriptors.py
├── harris_corner.py
├── horn_schunck.py
├── intensity_based_segmentation.py
├── mean_threshold.py
├── mosaic_augmentation.py
└── pooling_functions.py
├── conversions
├── README.md
├── __init__.py
├── astronomical_length_scale_conversion.py
├── binary_to_decimal.py
├── binary_to_hexadecimal.py
├── binary_to_octal.py
├── convert_number_to_words.py
├── decimal_to_any.py
├── decimal_to_binary.py
├── decimal_to_hexadecimal.py
├── decimal_to_octal.py
├── energy_conversions.py
├── excel_title_to_column.py
├── hex_to_bin.py
├── hexadecimal_to_decimal.py
├── ipv4_conversion.py
├── length_conversion.py
├── molecular_chemistry.py
├── octal_to_binary.py
├── octal_to_decimal.py
├── octal_to_hexadecimal.py
├── prefix_conversions.py
├── prefix_conversions_string.py
├── pressure_conversions.py
├── rectangular_to_polar.py
├── rgb_cmyk_conversion.py
├── rgb_hsv_conversion.py
├── roman_numerals.py
├── speed_conversions.py
├── temperature_conversions.py
├── time_conversions.py
├── volume_conversions.py
└── weight_conversion.py
├── data_compression
├── README.md
├── __init__.py
├── burrows_wheeler.py
├── huffman.py
├── image_data
│ ├── PSNR-example-base.png
│ ├── PSNR-example-comp-10.jpg
│ ├── compressed_image.png
│ ├── example_image.jpg
│ ├── example_wikipedia_image.jpg
│ └── original_image.png
├── lempel_ziv.py
├── lempel_ziv_decompress.py
├── lz77.py
├── peak_signal_to_noise_ratio.py
└── run_length_encoding.py
├── data_structures
├── __init__.py
├── arrays
│ ├── __init__.py
│ ├── equilibrium_index_in_array.py
│ ├── find_triplets_with_0_sum.py
│ ├── index_2d_array_in_1d.py
│ ├── kth_largest_element.py
│ ├── median_two_array.py
│ ├── monotonic_array.py
│ ├── pairs_with_given_sum.py
│ ├── permutations.py
│ ├── prefix_sum.py
│ ├── product_sum.py
│ ├── sparse_table.py
│ └── sudoku_solver.py
├── binary_tree
│ ├── README.md
│ ├── __init__.py
│ ├── avl_tree.py
│ ├── basic_binary_tree.py
│ ├── binary_search_tree.py
│ ├── binary_search_tree_recursive.py
│ ├── binary_tree_mirror.py
│ ├── binary_tree_node_sum.py
│ ├── binary_tree_path_sum.py
│ ├── binary_tree_traversals.py
│ ├── diameter_of_binary_tree.py
│ ├── diff_views_of_binary_tree.py
│ ├── distribute_coins.py
│ ├── fenwick_tree.py
│ ├── flatten_binarytree_to_linkedlist.py
│ ├── floor_and_ceiling.py
│ ├── inorder_tree_traversal_2022.py
│ ├── is_sorted.py
│ ├── is_sum_tree.py
│ ├── lazy_segment_tree.py
│ ├── lowest_common_ancestor.py
│ ├── maximum_fenwick_tree.py
│ ├── maximum_sum_bst.py
│ ├── merge_two_binary_trees.py
│ ├── mirror_binary_tree.py
│ ├── non_recursive_segment_tree.py
│ ├── number_of_possible_binary_trees.py
│ ├── red_black_tree.py
│ ├── segment_tree.py
│ ├── segment_tree_other.py
│ ├── serialize_deserialize_binary_tree.py
│ ├── symmetric_tree.py
│ ├── treap.py
│ └── wavelet_tree.py
├── disjoint_set
│ ├── __init__.py
│ ├── alternate_disjoint_set.py
│ └── disjoint_set.py
├── hashing
│ ├── __init__.py
│ ├── bloom_filter.py
│ ├── double_hash.py
│ ├── hash_map.py
│ ├── hash_table.py
│ ├── hash_table_with_linked_list.py
│ ├── number_theory
│ │ ├── __init__.py
│ │ └── prime_numbers.py
│ ├── quadratic_probing.py
│ └── tests
│ │ ├── __init__.py
│ │ └── test_hash_map.py
├── heap
│ ├── __init__.py
│ ├── binomial_heap.py
│ ├── heap.py
│ ├── heap_generic.py
│ ├── max_heap.py
│ ├── min_heap.py
│ ├── randomized_heap.py
│ └── skew_heap.py
├── kd_tree
│ ├── __init__.py
│ ├── build_kdtree.py
│ ├── example
│ │ ├── __init__.py
│ │ ├── example_usage.py
│ │ └── hypercube_points.py
│ ├── kd_node.py
│ ├── nearest_neighbour_search.py
│ └── tests
│ │ ├── __init__.py
│ │ └── test_kdtree.py
├── linked_list
│ ├── __init__.py
│ ├── circular_linked_list.py
│ ├── deque_doubly.py
│ ├── doubly_linked_list.py
│ ├── doubly_linked_list_two.py
│ ├── floyds_cycle_detection.py
│ ├── from_sequence.py
│ ├── has_loop.py
│ ├── is_palindrome.py
│ ├── merge_two_lists.py
│ ├── middle_element_of_linked_list.py
│ ├── print_reverse.py
│ ├── reverse_k_group.py
│ ├── rotate_to_the_right.py
│ ├── singly_linked_list.py
│ ├── skip_list.py
│ └── swap_nodes.py
├── queues
│ ├── __init__.py
│ ├── circular_queue.py
│ ├── circular_queue_linked_list.py
│ ├── double_ended_queue.py
│ ├── linked_queue.py
│ ├── priority_queue_using_list.py
│ ├── queue_by_list.py
│ ├── queue_by_two_stacks.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
│ ├── largest_rectangle_histogram.py
│ ├── lexicographical_numbers.py
│ ├── next_greater_element.py
│ ├── postfix_evaluation.py
│ ├── prefix_evaluation.py
│ ├── stack.py
│ ├── stack_using_two_queues.py
│ ├── stack_with_doubly_linked_list.py
│ ├── stack_with_singly_linked_list.py
│ └── stock_span_problem.py
├── suffix_tree
│ ├── __init__.py
│ ├── example
│ │ ├── __init__.py
│ │ └── example_usage.py
│ ├── suffix_tree.py
│ ├── suffix_tree_node.py
│ └── tests
│ │ ├── __init__.py
│ │ └── test_suffix_tree.py
└── trie
│ ├── __init__.py
│ ├── radix_tree.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
│ ├── gabor_filter.py
│ ├── gaussian_filter.py
│ ├── laplacian_filter.py
│ ├── local_binary_pattern.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
├── morphological_operations
│ ├── __init__.py
│ ├── dilation_operation.py
│ └── erosion_operation.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
├── kth_order_statistic.py
├── max_difference_pair.py
├── max_subarray.py
├── mergesort.py
├── peak.py
├── power.py
└── strassen_matrix_multiplication.py
├── docs
├── __init__.py
├── conf.py
└── source
│ └── __init__.py
├── dynamic_programming
├── __init__.py
├── abbreviation.py
├── all_construct.py
├── bitmask.py
├── catalan_numbers.py
├── climbing_stairs.py
├── combination_sum_iv.py
├── edit_distance.py
├── factorial.py
├── fast_fibonacci.py
├── fibonacci.py
├── fizz_buzz.py
├── floyd_warshall.py
├── integer_partition.py
├── iterating_through_submasks.py
├── k_means_clustering_tensorflow.py
├── knapsack.py
├── largest_divisible_subset.py
├── longest_common_subsequence.py
├── longest_common_substring.py
├── longest_increasing_subsequence.py
├── longest_increasing_subsequence_iterative.py
├── longest_increasing_subsequence_o_nlogn.py
├── longest_palindromic_subsequence.py
├── matrix_chain_multiplication.py
├── matrix_chain_order.py
├── max_non_adjacent_sum.py
├── max_product_subarray.py
├── max_subarray_sum.py
├── min_distance_up_bottom.py
├── minimum_coin_change.py
├── minimum_cost_path.py
├── minimum_partition.py
├── minimum_size_subarray_sum.py
├── minimum_squares_to_represent_a_number.py
├── minimum_steps_to_one.py
├── minimum_tickets_cost.py
├── optimal_binary_search_tree.py
├── palindrome_partitioning.py
├── range_sum_query.py
├── regex_match.py
├── rod_cutting.py
├── smith_waterman.py
├── subset_generation.py
├── sum_of_subset.py
├── trapped_water.py
├── tribonacci.py
├── viterbi.py
├── wildcard_matching.py
└── word_break.py
├── electronics
├── __init__.py
├── apparent_power.py
├── builtin_voltage.py
├── capacitor_equivalence.py
├── carrier_concentration.py
├── charging_capacitor.py
├── charging_inductor.py
├── circular_convolution.py
├── coulombs_law.py
├── electric_conductivity.py
├── electric_power.py
├── electrical_impedance.py
├── ic_555_timer.py
├── ind_reactance.py
├── ohms_law.py
├── real_and_reactive_power.py
├── resistor_color_code.py
├── resistor_equivalence.py
├── resonant_frequency.py
└── wheatstone_bridge.py
├── file_transfer
├── __init__.py
├── mytext.txt
├── receive_file.py
├── send_file.py
└── tests
│ ├── __init__.py
│ └── test_send_file.py
├── financial
├── README.md
├── __init__.py
├── equated_monthly_installments.py
├── exponential_moving_average.py
├── interest.py
├── present_value.py
├── price_plus_tax.py
├── simple_moving_average.py
├── straight_line_depreciation.py
└── time_and_half_pay.py
├── fractals
├── __init__.py
├── julia_sets.py
├── koch_snowflake.py
├── mandelbrot.py
├── sierpinski_triangle.py
└── vicsek.py
├── fuzzy_logic
├── __init__.py
├── fuzzy_operations.py
└── fuzzy_operations.py.DISABLED.txt
├── genetic_algorithm
├── __init__.py
└── basic_string.py
├── geodesy
├── __init__.py
├── haversine_distance.py
└── lamberts_ellipsoidal_distance.py
├── geometry
├── __init__.py
└── geometry.py
├── graphics
├── __init__.py
├── bezier_curve.py
├── butterfly_pattern.py
├── digital_differential_analyzer_line.py
└── vector3_for_2d_rendering.py
├── graphs
├── __init__.py
├── a_star.py
├── ant_colony_optimization_algorithms.py
├── articulation_points.py
├── basic_graphs.py
├── bellman_ford.py
├── bi_directional_dijkstra.py
├── bidirectional_a_star.py
├── bidirectional_breadth_first_search.py
├── bidirectional_search.py
├── boruvka.py
├── breadth_first_search.py
├── breadth_first_search_2.py
├── breadth_first_search_shortest_path.py
├── breadth_first_search_shortest_path_2.py
├── breadth_first_search_zero_one_shortest_path.py
├── check_bipatrite.py
├── check_cycle.py
├── connected_components.py
├── deep_clone_graph.py
├── depth_first_search.py
├── depth_first_search_2.py
├── dijkstra.py
├── dijkstra_2.py
├── dijkstra_algorithm.py
├── dijkstra_alternate.py
├── dijkstra_binary_grid.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_adjacency_list.py
├── graph_adjacency_matrix.py
├── graph_list.py
├── graphs_floyd_warshall.py
├── greedy_best_first.py
├── greedy_min_vertex_cover.py
├── kahns_algorithm_long.py
├── kahns_algorithm_topo.py
├── karger.py
├── lanczos_eigenvectors.py
├── markov_chain.py
├── matching_min_vertex_cover.py
├── minimum_path_sum.py
├── minimum_spanning_tree_boruvka.py
├── minimum_spanning_tree_kruskal.py
├── minimum_spanning_tree_kruskal2.py
├── minimum_spanning_tree_prims.py
├── minimum_spanning_tree_prims2.py
├── multi_heuristic_astar.py
├── page_rank.py
├── prim.py
├── random_graph_generator.py
├── scc_kosaraju.py
├── strongly_connected_components.py
├── tarjans_scc.py
└── tests
│ ├── __init__.py
│ ├── test_min_spanning_tree_kruskal.py
│ └── test_min_spanning_tree_prim.py
├── greedy_methods
├── __init__.py
├── best_time_to_buy_and_sell_stock.py
├── fractional_cover_problem.py
├── fractional_knapsack.py
├── fractional_knapsack_2.py
├── gas_station.py
├── minimum_coin_change.py
├── minimum_waiting_time.py
├── optimal_merge_pattern.py
└── smallest_range.py
├── hashes
├── README.md
├── __init__.py
├── adler32.py
├── chaos_machine.py
├── djb2.py
├── elf.py
├── enigma_machine.py
├── fletcher16.py
├── hamming_code.py
├── luhn.py
├── md5.py
├── sdbm.py
├── sha1.py
└── sha256.py
├── index.md
├── knapsack
├── README.md
├── __init__.py
├── greedy_knapsack.py
├── knapsack.py
├── recursive_approach_knapsack.py
└── tests
│ ├── __init__.py
│ ├── test_greedy_knapsack.py
│ └── test_knapsack.py
├── linear_algebra
├── README.md
├── __init__.py
├── gaussian_elimination.py
├── jacobi_iteration_method.py
├── lu_decomposition.py
├── matrix_inversion.py
└── src
│ ├── __init__.py
│ ├── conjugate_gradient.py
│ ├── gaussian_elimination_pivoting.py
│ ├── lib.py
│ ├── polynom_for_points.py
│ ├── power_iteration.py
│ ├── rank_of_matrix.py
│ ├── rayleigh_quotient.py
│ ├── schur_complement.py
│ ├── test_linear_algebra.py
│ └── transformations_2d.py
├── linear_programming
├── __init__.py
└── simplex.py
├── machine_learning
├── __init__.py
├── apriori_algorithm.py
├── astar.py
├── automatic_differentiation.py
├── data_transformations.py
├── decision_tree.py
├── dimensionality_reduction.py
├── forecasting
│ ├── __init__.py
│ ├── ex_data.csv
│ └── run.py
├── frequent_pattern_growth.py
├── gaussian_naive_bayes.py.broken.txt
├── gradient_boosting_classifier.py
├── gradient_boosting_regressor.py.broken.txt
├── gradient_descent.py
├── k_means_clust.py
├── k_nearest_neighbours.py
├── linear_discriminant_analysis.py
├── linear_regression.py
├── local_weighted_learning
│ ├── README.md
│ ├── __init__.py
│ └── local_weighted_learning.py
├── logistic_regression.py
├── loss_functions.py
├── lstm
│ ├── __init__.py
│ ├── lstm_prediction.py
│ └── sample_data.csv
├── mfcc.py
├── multilayer_perceptron_classifier.py
├── polynomial_regression.py
├── principle_component_analysis.py
├── random_forest_classifier.py.broken.txt
├── random_forest_regressor.py.broken.txt
├── scoring_functions.py
├── self_organizing_map.py
├── sequential_minimum_optimization.py
├── similarity_search.py
├── support_vector_machines.py
├── word_frequency_functions.py
├── xgboost_classifier.py
└── xgboost_regressor.py
├── maths
├── __init__.py
├── abs.py
├── addition_without_arithmetic.py
├── aliquot_sum.py
├── allocation_number.py
├── arc_length.py
├── area.py
├── area_under_curve.py
├── average_absolute_deviation.py
├── average_mean.py
├── average_median.py
├── average_mode.py
├── bailey_borwein_plouffe.py
├── base_neg2_conversion.py
├── basic_maths.py
├── binary_exponentiation.py
├── binary_multiplication.py
├── binomial_coefficient.py
├── binomial_distribution.py
├── ceil.py
├── chebyshev_distance.py
├── check_polygon.py
├── chinese_remainder_theorem.py
├── chudnovsky_algorithm.py
├── collatz_sequence.py
├── combinations.py
├── continued_fraction.py
├── decimal_isolate.py
├── decimal_to_fraction.py
├── dodecahedron.py
├── double_factorial.py
├── dual_number_automatic_differentiation.py
├── entropy.py
├── euclidean_distance.py
├── euler_method.py
├── euler_modified.py
├── eulers_totient.py
├── extended_euclidean_algorithm.py
├── factorial.py
├── factors.py
├── fast_inverse_sqrt.py
├── fermat_little_theorem.py
├── fibonacci.py
├── find_max.py
├── find_min.py
├── floor.py
├── gamma.py
├── gaussian.py
├── gcd_of_n_numbers.py
├── geometric_mean.py
├── germain_primes.py
├── greatest_common_divisor.py
├── hardy_ramanujanalgo.py
├── images
│ ├── __init__.py
│ └── gaussian.png
├── integer_square_root.py
├── interquartile_range.py
├── is_int_palindrome.py
├── is_ip_v4_address_valid.py
├── is_square_free.py
├── jaccard_similarity.py
├── joint_probability_distribution.py
├── josephus_problem.py
├── juggler_sequence.py
├── karatsuba.py
├── kth_lexicographic_permutation.py
├── largest_of_very_large_numbers.py
├── least_common_multiple.py
├── line_length.py
├── liouville_lambda.py
├── lucas_lehmer_primality_test.py
├── lucas_series.py
├── maclaurin_series.py
├── manhattan_distance.py
├── matrix_exponentiation.py
├── max_sum_sliding_window.py
├── minkowski_distance.py
├── mobius_function.py
├── modular_division.py
├── modular_exponential.py
├── monte_carlo.py
├── monte_carlo_dice.py
├── number_of_digits.py
├── numerical_analysis
│ ├── __init__.py
│ ├── adams_bashforth.py
│ ├── bisection.py
│ ├── bisection_2.py
│ ├── integration_by_simpson_approx.py
│ ├── intersection.py
│ ├── nevilles_method.py
│ ├── newton_forward_interpolation.py
│ ├── newton_raphson.py
│ ├── numerical_integration.py
│ ├── proper_fractions.py
│ ├── runge_kutta.py
│ ├── runge_kutta_fehlberg_45.py
│ ├── runge_kutta_gills.py
│ ├── secant_method.py
│ ├── simpson_rule.py
│ └── square_root.py
├── odd_sieve.py
├── perfect_cube.py
├── perfect_number.py
├── perfect_square.py
├── persistence.py
├── pi_generator.py
├── pi_monte_carlo_estimation.py
├── points_are_collinear_3d.py
├── pollard_rho.py
├── polynomial_evaluation.py
├── polynomials
│ ├── __init__.py
│ └── single_indeterminate_operations.py
├── power_using_recursion.py
├── prime_check.py
├── prime_factors.py
├── prime_numbers.py
├── prime_sieve_eratosthenes.py
├── primelib.py
├── print_multiplication_table.py
├── pythagoras.py
├── qr_decomposition.py
├── quadratic_equations_complex_numbers.py
├── radians.py
├── radix2_fft.py
├── remove_digit.py
├── segmented_sieve.py
├── series
│ ├── __init__.py
│ ├── arithmetic.py
│ ├── geometric.py
│ ├── geometric_series.py
│ ├── harmonic.py
│ ├── harmonic_series.py
│ ├── hexagonal_numbers.py
│ └── p_series.py
├── sieve_of_eratosthenes.py
├── sigmoid.py
├── signum.py
├── simultaneous_linear_equation_solver.py
├── sin.py
├── sock_merchant.py
├── softmax.py
├── solovay_strassen_primality_test.py
├── spearman_rank_correlation_coefficient.py
├── special_numbers
│ ├── __init__.py
│ ├── armstrong_numbers.py
│ ├── automorphic_number.py
│ ├── bell_numbers.py
│ ├── carmichael_number.py
│ ├── catalan_number.py
│ ├── hamming_numbers.py
│ ├── happy_number.py
│ ├── harshad_numbers.py
│ ├── hexagonal_number.py
│ ├── krishnamurthy_number.py
│ ├── perfect_number.py
│ ├── polygonal_numbers.py
│ ├── pronic_number.py
│ ├── proth_number.py
│ ├── triangular_numbers.py
│ ├── ugly_numbers.py
│ └── weird_number.py
├── sum_of_arithmetic_series.py
├── sum_of_digits.py
├── sum_of_geometric_progression.py
├── sum_of_harmonic_series.py
├── sumset.py
├── sylvester_sequence.py
├── tanh.py
├── test_prime_check.py
├── three_sum.py
├── trapezoidal_rule.py
├── triplet_sum.py
├── twin_prime.py
├── two_pointer.py
├── two_sum.py
├── volume.py
└── zellers_congruence.py
├── matrix
├── __init__.py
├── binary_search_matrix.py
├── count_islands_in_matrix.py
├── count_negative_numbers_in_sorted_matrix.py
├── count_paths.py
├── cramers_rule_2x2.py
├── inverse_of_matrix.py
├── largest_square_area_in_matrix.py
├── matrix_based_game.py
├── matrix_class.py
├── matrix_equalization.py
├── matrix_multiplication_recursion.py
├── matrix_operation.py
├── max_area_of_island.py
├── median_matrix.py
├── nth_fibonacci_using_matrix_exponentiation.py
├── pascal_triangle.py
├── rotate_matrix.py
├── searching_in_sorted_matrix.py
├── sherman_morrison.py
├── spiral_print.py
├── tests
│ ├── __init__.py
│ ├── pytest.ini
│ └── test_matrix_operation.py
└── validate_sudoku_board.py
├── networking_flow
├── __init__.py
├── ford_fulkerson.py
└── minimum_cut.py
├── neural_network
├── __init__.py
├── activation_functions
│ ├── __init__.py
│ ├── binary_step.py
│ ├── exponential_linear_unit.py
│ ├── gaussian_error_linear_unit.py
│ ├── leaky_rectified_linear_unit.py
│ ├── mish.py
│ ├── rectified_linear_unit.py
│ ├── scaled_exponential_linear_unit.py
│ ├── soboleva_modified_hyperbolic_tangent.py
│ ├── softplus.py
│ ├── squareplus.py
│ └── swish.py
├── back_propagation_neural_network.py
├── convolution_neural_network.py
├── gan.py_tf
├── input_data.py
├── perceptron.py.DISABLED
├── simple_neural_network.py
└── two_hidden_layers_neural_network.py
├── other
├── __init__.py
├── activity_selection.py
├── alternative_list_arrange.py
├── bankers_algorithm.py
├── davis_putnam_logemann_loveland.py
├── doomsday.py
├── fischer_yates_shuffle.py
├── gauss_easter.py
├── graham_scan.py
├── greedy.py
├── guess_the_number_search.py
├── h_index.py
├── least_recently_used.py
├── lfu_cache.py
├── linear_congruential_generator.py
├── lru_cache.py
├── magicdiamondpattern.py
├── majority_vote_algorithm.py
├── maximum_subsequence.py
├── nested_brackets.py
├── number_container_system.py
├── password.py
├── quine.py
├── scoring_algorithm.py
├── sdes.py
├── tower_of_hanoi.py
└── word_search.py
├── physics
├── __init__.py
├── altitude_pressure.py
├── archimedes_principle_of_buoyant_force.py
├── basic_orbital_capture.py
├── casimir_effect.py
├── center_of_mass.py
├── centripetal_force.py
├── coulombs_law.py
├── doppler_frequency.py
├── escape_velocity.py
├── grahams_law.py
├── horizontal_projectile_motion.py
├── hubble_parameter.py
├── ideal_gas_law.py
├── image_data
│ ├── 2D_problems.jpg
│ ├── 2D_problems_1.jpg
│ └── __init__.py
├── in_static_equilibrium.py
├── kinetic_energy.py
├── lens_formulae.py
├── lorentz_transformation_four_vector.py
├── malus_law.py
├── mass_energy_equivalence.py
├── mirror_formulae.py
├── n_body_simulation.py
├── newtons_law_of_gravitation.py
├── newtons_second_law_of_motion.py
├── orbital_transfer_work.py
├── period_of_pendulum.py
├── photoelectric_effect.py
├── potential_energy.py
├── rainfall_intensity.py
├── reynolds_number.py
├── rms_speed_of_molecule.py
├── shear_stress.py
├── speed_of_sound.py
├── speeds_of_gas_molecules.py
└── terminal_velocity.py
├── project_euler
├── README.md
├── __init__.py
├── problem_001
│ ├── __init__.py
│ ├── sol1.py
│ ├── sol2.py
│ ├── sol3.py
│ ├── sol4.py
│ ├── sol5.py
│ ├── sol6.py
│ └── sol7.py
├── problem_002
│ ├── __init__.py
│ ├── sol1.py
│ ├── sol2.py
│ ├── sol3.py
│ ├── sol4.py
│ └── sol5.py
├── problem_003
│ ├── __init__.py
│ ├── sol1.py
│ ├── sol2.py
│ └── sol3.py
├── problem_004
│ ├── __init__.py
│ ├── sol1.py
│ └── sol2.py
├── problem_005
│ ├── __init__.py
│ ├── sol1.py
│ └── sol2.py
├── problem_006
│ ├── __init__.py
│ ├── sol1.py
│ ├── sol2.py
│ ├── sol3.py
│ └── sol4.py
├── problem_007
│ ├── __init__.py
│ ├── sol1.py
│ ├── sol2.py
│ └── sol3.py
├── problem_008
│ ├── __init__.py
│ ├── sol1.py
│ ├── sol2.py
│ └── sol3.py
├── problem_009
│ ├── __init__.py
│ ├── sol1.py
│ ├── sol2.py
│ └── sol3.py
├── problem_010
│ ├── __init__.py
│ ├── sol1.py
│ ├── sol2.py
│ └── sol3.py
├── problem_011
│ ├── __init__.py
│ ├── grid.txt
│ ├── sol1.py
│ └── sol2.py
├── problem_012
│ ├── __init__.py
│ ├── sol1.py
│ └── sol2.py
├── problem_013
│ ├── __init__.py
│ ├── num.txt
│ └── sol1.py
├── problem_014
│ ├── __init__.py
│ ├── sol1.py
│ └── sol2.py
├── problem_015
│ ├── __init__.py
│ └── sol1.py
├── problem_016
│ ├── __init__.py
│ ├── sol1.py
│ └── sol2.py
├── problem_017
│ ├── __init__.py
│ └── sol1.py
├── problem_018
│ ├── __init__.py
│ ├── solution.py
│ └── triangle.txt
├── problem_019
│ ├── __init__.py
│ └── sol1.py
├── problem_020
│ ├── __init__.py
│ ├── sol1.py
│ ├── sol2.py
│ ├── sol3.py
│ └── sol4.py
├── problem_021
│ ├── __init__.py
│ └── sol1.py
├── problem_022
│ ├── __init__.py
│ ├── p022_names.txt
│ ├── sol1.py
│ └── sol2.py
├── problem_023
│ ├── __init__.py
│ └── sol1.py
├── problem_024
│ ├── __init__.py
│ └── sol1.py
├── problem_025
│ ├── __init__.py
│ ├── sol1.py
│ ├── sol2.py
│ └── sol3.py
├── problem_026
│ ├── __init__.py
│ └── sol1.py
├── problem_027
│ ├── __init__.py
│ └── sol1.py
├── problem_028
│ ├── __init__.py
│ └── sol1.py
├── problem_029
│ ├── __init__.py
│ └── sol1.py
├── problem_030
│ ├── __init__.py
│ └── sol1.py
├── problem_031
│ ├── __init__.py
│ ├── sol1.py
│ └── sol2.py
├── problem_032
│ ├── __init__.py
│ └── sol32.py
├── problem_033
│ ├── __init__.py
│ └── sol1.py
├── problem_034
│ ├── __init__.py
│ └── sol1.py
├── problem_035
│ ├── __init__.py
│ └── sol1.py
├── problem_036
│ ├── __init__.py
│ └── sol1.py
├── problem_037
│ ├── __init__.py
│ └── sol1.py
├── problem_038
│ ├── __init__.py
│ └── sol1.py
├── problem_039
│ ├── __init__.py
│ └── sol1.py
├── problem_040
│ ├── __init__.py
│ └── sol1.py
├── problem_041
│ ├── __init__.py
│ └── sol1.py
├── problem_042
│ ├── __init__.py
│ ├── solution42.py
│ └── words.txt
├── problem_043
│ ├── __init__.py
│ └── sol1.py
├── problem_044
│ ├── __init__.py
│ └── sol1.py
├── problem_045
│ ├── __init__.py
│ └── sol1.py
├── problem_046
│ ├── __init__.py
│ └── sol1.py
├── problem_047
│ ├── __init__.py
│ └── sol1.py
├── problem_048
│ ├── __init__.py
│ └── sol1.py
├── problem_049
│ ├── __init__.py
│ └── sol1.py
├── problem_050
│ ├── __init__.py
│ └── sol1.py
├── problem_051
│ ├── __init__.py
│ └── sol1.py
├── problem_052
│ ├── __init__.py
│ └── sol1.py
├── problem_053
│ ├── __init__.py
│ └── sol1.py
├── problem_054
│ ├── __init__.py
│ ├── poker_hands.txt
│ ├── sol1.py
│ └── test_poker_hand.py
├── problem_055
│ ├── __init__.py
│ └── sol1.py
├── problem_056
│ ├── __init__.py
│ └── sol1.py
├── problem_057
│ ├── __init__.py
│ └── sol1.py
├── problem_058
│ ├── __init__.py
│ └── sol1.py
├── problem_059
│ ├── __init__.py
│ ├── p059_cipher.txt
│ ├── sol1.py
│ └── test_cipher.txt
├── problem_062
│ ├── __init__.py
│ └── sol1.py
├── problem_063
│ ├── __init__.py
│ └── sol1.py
├── problem_064
│ ├── __init__.py
│ └── sol1.py
├── problem_065
│ ├── __init__.py
│ └── sol1.py
├── problem_067
│ ├── __init__.py
│ ├── sol1.py
│ ├── sol2.py
│ └── triangle.txt
├── problem_068
│ ├── __init__.py
│ └── sol1.py
├── problem_069
│ ├── __init__.py
│ └── sol1.py
├── problem_070
│ ├── __init__.py
│ └── sol1.py
├── problem_071
│ ├── __init__.py
│ └── sol1.py
├── problem_072
│ ├── __init__.py
│ ├── sol1.py
│ └── sol2.py
├── problem_073
│ ├── __init__.py
│ └── sol1.py
├── problem_074
│ ├── __init__.py
│ ├── sol1.py
│ └── sol2.py
├── problem_075
│ ├── __init__.py
│ └── sol1.py
├── problem_076
│ ├── __init__.py
│ └── sol1.py
├── problem_077
│ ├── __init__.py
│ └── sol1.py
├── problem_078
│ ├── __init__.py
│ └── sol1.py
├── problem_079
│ ├── __init__.py
│ ├── keylog.txt
│ ├── keylog_test.txt
│ └── sol1.py
├── problem_080
│ ├── __init__.py
│ └── sol1.py
├── problem_081
│ ├── __init__.py
│ ├── matrix.txt
│ └── sol1.py
├── problem_082
│ ├── __init__.py
│ ├── input.txt
│ ├── sol1.py
│ └── test_matrix.txt
├── problem_085
│ ├── __init__.py
│ └── sol1.py
├── problem_086
│ ├── __init__.py
│ └── sol1.py
├── problem_087
│ ├── __init__.py
│ └── sol1.py
├── problem_089
│ ├── __init__.py
│ ├── numeralcleanup_test.txt
│ ├── p089_roman.txt
│ └── sol1.py
├── problem_091
│ ├── __init__.py
│ └── sol1.py
├── problem_092
│ ├── __init__.py
│ └── sol1.py
├── problem_094
│ ├── __init__.py
│ └── sol1.py
├── problem_095
│ ├── __init__.py
│ └── sol1.py
├── problem_097
│ ├── __init__.py
│ └── sol1.py
├── problem_099
│ ├── __init__.py
│ ├── base_exp.txt
│ └── sol1.py
├── problem_100
│ ├── __init__.py
│ └── sol1.py
├── problem_101
│ ├── __init__.py
│ └── sol1.py
├── problem_102
│ ├── __init__.py
│ ├── p102_triangles.txt
│ ├── sol1.py
│ └── test_triangles.txt
├── problem_104
│ ├── __init__.py
│ └── sol1.py
├── problem_107
│ ├── __init__.py
│ ├── p107_network.txt
│ ├── sol1.py
│ └── test_network.txt
├── problem_109
│ ├── __init__.py
│ └── sol1.py
├── problem_112
│ ├── __init__.py
│ └── sol1.py
├── problem_113
│ ├── __init__.py
│ └── sol1.py
├── problem_114
│ ├── __init__.py
│ └── sol1.py
├── problem_115
│ ├── __init__.py
│ └── sol1.py
├── problem_116
│ ├── __init__.py
│ └── sol1.py
├── problem_117
│ ├── __init__.py
│ └── sol1.py
├── problem_119
│ ├── __init__.py
│ └── sol1.py
├── problem_120
│ ├── __init__.py
│ └── sol1.py
├── problem_121
│ ├── __init__.py
│ └── sol1.py
├── problem_122
│ ├── __init__.py
│ └── sol1.py
├── problem_123
│ ├── __init__.py
│ └── sol1.py
├── problem_125
│ ├── __init__.py
│ └── sol1.py
├── problem_129
│ ├── __init__.py
│ └── sol1.py
├── problem_131
│ ├── __init__.py
│ └── sol1.py
├── problem_135
│ ├── __init__.py
│ └── sol1.py
├── problem_136
│ ├── __init__.py
│ └── sol1.py
├── problem_144
│ ├── __init__.py
│ └── sol1.py
├── problem_145
│ ├── __init__.py
│ └── sol1.py
├── problem_164
│ ├── __init__.py
│ └── sol1.py
├── problem_173
│ ├── __init__.py
│ └── sol1.py
├── problem_174
│ ├── __init__.py
│ └── sol1.py
├── problem_180
│ ├── __init__.py
│ └── sol1.py
├── problem_187
│ ├── __init__.py
│ └── sol1.py
├── problem_188
│ ├── __init__.py
│ └── sol1.py
├── problem_190
│ ├── __init__.py
│ └── sol1.py
├── problem_191
│ ├── __init__.py
│ └── sol1.py
├── problem_203
│ ├── __init__.py
│ └── sol1.py
├── problem_205
│ ├── __init__.py
│ └── sol1.py
├── problem_206
│ ├── __init__.py
│ └── sol1.py
├── problem_207
│ ├── __init__.py
│ └── sol1.py
├── problem_234
│ ├── __init__.py
│ └── sol1.py
├── problem_301
│ ├── __init__.py
│ └── sol1.py
├── problem_345
│ ├── __init__.py
│ └── sol1.py
├── problem_493
│ ├── __init__.py
│ └── sol1.py
├── problem_551
│ ├── __init__.py
│ └── sol1.py
├── problem_587
│ ├── __init__.py
│ └── sol1.py
├── problem_686
│ ├── __init__.py
│ └── sol1.py
└── problem_800
│ ├── __init__.py
│ └── sol1.py
├── pyproject.toml
├── quantum
├── README.md
├── __init__.py
├── bb84.py.DISABLED.txt
├── deutsch_jozsa.py.DISABLED.txt
├── half_adder.py.DISABLED.txt
├── not_gate.py.DISABLED.txt
├── q_fourier_transform.py
├── q_full_adder.py.DISABLED.txt
├── quantum_entanglement.py.DISABLED.txt
├── quantum_random.py.DISABLED.txt
├── quantum_teleportation.py.DISABLED.txt
├── ripple_adder_classic.py.DISABLED.txt
├── single_qubit_measure.py.DISABLED.txt
└── superdense_coding.py.DISABLED.txt
├── requirements.txt
├── scheduling
├── __init__.py
├── first_come_first_served.py
├── highest_response_ratio_next.py
├── job_sequence_with_deadline.py
├── job_sequencing_with_deadline.py
├── multi_level_feedback_queue.py
├── non_preemptive_shortest_job_first.py
├── round_robin.py
└── shortest_job_first.py
├── scripts
├── __init__.py
├── build_directory_md.py
├── close_pull_requests_with_awaiting_changes.sh
├── close_pull_requests_with_failing_tests.sh
├── close_pull_requests_with_require_descriptive_names.sh
├── close_pull_requests_with_require_tests.sh
├── close_pull_requests_with_require_type_hints.sh
├── find_git_conflicts.sh
├── project_euler_answers.json
├── validate_filenames.py
└── validate_solutions.py
├── searches
├── __init__.py
├── binary_search.py
├── binary_tree_traversal.py
├── double_linear_search.py
├── double_linear_search_recursion.py
├── exponential_search.py
├── fibonacci_search.py
├── hill_climbing.py
├── interpolation_search.py
├── jump_search.py
├── linear_search.py
├── median_of_medians.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
├── README.md
├── __init__.py
├── bead_sort.py
├── binary_insertion_sort.py
├── bitonic_sort.py
├── bogo_sort.py
├── bubble_sort.py
├── bucket_sort.py
├── circle_sort.py
├── cocktail_shaker_sort.py
├── comb_sort.py
├── counting_sort.py
├── cycle_sort.py
├── double_sort.py
├── dutch_national_flag_sort.py
├── exchange_sort.py
├── external_sort.py
├── gnome_sort.py
├── heap_sort.py
├── insertion_sort.py
├── intro_sort.py
├── iterative_merge_sort.py
├── merge_insertion_sort.py
├── merge_sort.py
├── msd_radix_sort.py
├── natural_sort.py
├── normal_distribution_quick_sort.md
├── odd_even_sort.py
├── odd_even_transposition_parallel.py
├── odd_even_transposition_single_threaded.py
├── pancake_sort.py
├── patience_sort.py
├── pigeon_sort.py
├── pigeonhole_sort.py
├── quick_sort.py
├── quick_sort_3_partition.py
├── radix_sort.py
├── recursive_insertion_sort.py
├── recursive_mergesort_array.py
├── recursive_quick_sort.py
├── selection_sort.py
├── shell_sort.py
├── shrink_shell_sort.py
├── slowsort.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
├── alternative_string_arrange.py
├── anagrams.py
├── anagrams.txt
├── autocomplete_using_trie.py
├── barcode_validator.py
├── bitap_string_match.py
├── boyer_moore_search.py
├── camel_case_to_snake_case.py
├── can_string_be_rearranged_as_palindrome.py
├── capitalize.py
├── check_anagrams.py
├── count_vowels.py
├── credit_card_validator.py
├── damerau_levenshtein_distance.py
├── detecting_english_programmatically.py
├── dictionary.txt
├── dna.py
├── edit_distance.py
├── frequency_finder.py
├── hamming_distance.py
├── indian_phone_validator.py
├── is_contains_unique_chars.py
├── is_isogram.py
├── is_pangram.py
├── is_polish_national_id.py
├── is_spain_national_id.py
├── is_srilankan_phone_number.py
├── is_valid_email_address.py
├── jaro_winkler.py
├── join.py
├── knuth_morris_pratt.py
├── levenshtein_distance.py
├── lower.py
├── manacher.py
├── min_cost_string_conversion.py
├── naive_string_search.py
├── ngram.py
├── palindrome.py
├── pig_latin.py
├── prefix_function.py
├── rabin_karp.py
├── remove_duplicate.py
├── reverse_letters.py
├── reverse_words.py
├── snake_case_to_camel_pascal_case.py
├── split.py
├── string_switch_case.py
├── strip.py
├── text_justification.py
├── title.py
├── top_k_frequent_words.py
├── upper.py
├── wave_string.py
├── wildcard_pattern_matching.py
├── word_occurrence.py
├── word_patterns.py
├── words.txt
└── z_function.py
├── uv.lock
└── web_programming
├── __init__.py
├── co2_emission.py
├── covid_stats_via_xpath.py
├── crawl_google_results.py
├── crawl_google_scholar_citation.py
├── currency_converter.py
├── current_stock_price.py
├── current_weather.py
├── daily_horoscope.py
├── download_images_from_google_query.py
├── emails_from_url.py
├── fetch_anime_and_play.py
├── fetch_bbc_news.py
├── fetch_github_info.py
├── fetch_jobs.py
├── fetch_quotes.py
├── fetch_well_rx_price.py
├── get_amazon_product_data.py
├── get_imdb_top_250_movies_csv.py
├── get_imdbtop.py.DISABLED
├── get_ip_geolocation.py
├── get_top_billionaires.py
├── get_top_hn_posts.py
├── get_user_tweets.py.DISABLED
├── giphy.py
├── instagram_crawler.py
├── instagram_pic.py
├── instagram_video.py
├── nasa_data.py
├── open_google_results.py
├── random_anime_character.py
├── recaptcha_verification.py
├── reddit.py
├── search_books_by_isbn.py
├── slack_message.py
├── test_fetch_github_info.py
└── world_covid19_stats.py
/.devcontainer/Dockerfile:
--------------------------------------------------------------------------------
1 | # https://github.com/microsoft/vscode-dev-containers/blob/main/containers/python-3/README.md
2 | ARG VARIANT=3.13-bookworm
3 | FROM mcr.microsoft.com/vscode/devcontainers/python:${VARIANT}
4 | COPY requirements.txt /tmp/pip-tmp/
5 | RUN python3 -m pip install --upgrade pip \
6 | && python3 -m pip install --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \
7 | && pipx install pre-commit ruff \
8 | && pre-commit install
9 |
--------------------------------------------------------------------------------
/.devcontainer/README.md:
--------------------------------------------------------------------------------
1 | https://code.visualstudio.com/docs/devcontainers/tutorial
2 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=auto
2 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/config.yml:
--------------------------------------------------------------------------------
1 | blank_issues_enabled: false
2 | contact_links:
3 | - name: Discord community
4 | url: https://discord.gg/c7MnfGFGa6
5 | about: Have any questions or need any help? Please contact us via Discord
6 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.yml:
--------------------------------------------------------------------------------
1 | name: Feature request
2 | description: Suggest features, propose improvements, discuss new ideas.
3 | labels: [enhancement]
4 | body:
5 | - type: markdown
6 | attributes:
7 | value: >
8 | Before requesting please search [existing issues](https://github.com/TheAlgorithms/Python/labels/enhancement).
9 | Do not create issues to implement new algorithms as these will be closed.
10 | Usage questions such as "How do I...?" belong on the
11 | [Discord](https://discord.gg/c7MnfGFGa6) and will be closed.
12 |
13 | - type: textarea
14 | attributes:
15 | label: "Feature description"
16 | description: >
17 | This could include new topics or improving any existing implementations.
18 | validations:
19 | required: true
20 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/other.yml:
--------------------------------------------------------------------------------
1 | name: Other
2 | description: Use this for any other issues. PLEASE do not create blank issues
3 | labels: ["awaiting triage"]
4 | body:
5 | - type: textarea
6 | id: issuedescription
7 | attributes:
8 | label: What would you like to share?
9 | description: Provide a clear and concise explanation of your issue.
10 | validations:
11 | required: true
12 |
13 | - type: textarea
14 | id: extrainfo
15 | attributes:
16 | label: Additional information
17 | description: Is there anything else we should know about this issue?
18 | validations:
19 | required: false
20 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | # Keep GitHub Actions up to date with Dependabot...
2 | # https://docs.github.com/en/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot
3 | version: 2
4 | updates:
5 | - package-ecosystem: "github-actions"
6 | directory: "/"
7 | schedule:
8 | interval: "daily"
9 |
--------------------------------------------------------------------------------
/.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 | directory_writer:
7 | runs-on: ubuntu-latest
8 | steps:
9 | - uses: actions/checkout@v4
10 | with:
11 | fetch-depth: 0
12 | - uses: actions/setup-python@v5
13 | with:
14 | python-version: 3.x
15 | - name: Write DIRECTORY.md
16 | run: |
17 | scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md
18 | git config --global user.name "$GITHUB_ACTOR"
19 | git config --global user.email "$GITHUB_ACTOR@users.noreply.github.com"
20 | git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY
21 | - name: Update DIRECTORY.md
22 | run: |
23 | git add DIRECTORY.md
24 | git commit -am "updating DIRECTORY.md" || true
25 | git push --force origin HEAD:$GITHUB_REF || true
26 |
--------------------------------------------------------------------------------
/.github/workflows/ruff.yml:
--------------------------------------------------------------------------------
1 | # https://beta.ruff.rs
2 | name: ruff
3 | on:
4 | push:
5 | branches:
6 | - master
7 | pull_request:
8 | branches:
9 | - master
10 | jobs:
11 | ruff:
12 | runs-on: ubuntu-latest
13 | steps:
14 | - uses: actions/checkout@v4
15 | - uses: astral-sh/setup-uv@v6
16 | - run: uvx ruff check --output-format=github .
17 |
--------------------------------------------------------------------------------
/.gitpod.yml:
--------------------------------------------------------------------------------
1 | tasks:
2 | - init: pip3 install -r ./requirements.txt
3 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "githubPullRequests.ignoredPullRequestBranches": [
3 | "master"
4 | ]
5 | }
6 |
--------------------------------------------------------------------------------
/audio_filters/README.md:
--------------------------------------------------------------------------------
1 | # Audio Filter
2 |
3 | Audio filters work on the frequency of an audio signal to attenuate unwanted frequency and amplify wanted ones.
4 | They are used within anything related to sound, whether it is radio communication or a hi-fi system.
5 |
6 | *
7 | *
8 | *
9 | *
10 |
--------------------------------------------------------------------------------
/audio_filters/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/audio_filters/__init__.py
--------------------------------------------------------------------------------
/backtracking/README.md:
--------------------------------------------------------------------------------
1 | # Backtracking
2 |
3 | Backtracking is a way to speed up the search process by removing candidates when they can't be the solution of a problem.
4 |
5 | *
6 | *
7 | *
8 | *
9 |
--------------------------------------------------------------------------------
/backtracking/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/backtracking/__init__.py
--------------------------------------------------------------------------------
/bit_manipulation/README.md:
--------------------------------------------------------------------------------
1 | # Bit manipulation
2 |
3 | Bit manipulation is the act of manipulating bits to detect errors (hamming code), encrypts and decrypts messages (more on that in the 'ciphers' folder) or just do anything at the lowest level of your computer.
4 |
5 | *
6 | *
7 | *
8 | *
9 | *
10 | *
11 | *
12 |
--------------------------------------------------------------------------------
/bit_manipulation/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/bit_manipulation/__init__.py
--------------------------------------------------------------------------------
/bit_manipulation/binary_coded_decimal.py:
--------------------------------------------------------------------------------
1 | def binary_coded_decimal(number: int) -> str:
2 | """
3 | Find binary coded decimal (bcd) of integer base 10.
4 | Each digit of the number is represented by a 4-bit binary.
5 | Example:
6 | >>> binary_coded_decimal(-2)
7 | '0b0000'
8 | >>> binary_coded_decimal(-1)
9 | '0b0000'
10 | >>> binary_coded_decimal(0)
11 | '0b0000'
12 | >>> binary_coded_decimal(3)
13 | '0b0011'
14 | >>> binary_coded_decimal(2)
15 | '0b0010'
16 | >>> binary_coded_decimal(12)
17 | '0b00010010'
18 | >>> binary_coded_decimal(987)
19 | '0b100110000111'
20 | """
21 | return "0b" + "".join(
22 | str(bin(int(digit)))[2:].zfill(4) for digit in str(max(0, number))
23 | )
24 |
25 |
26 | if __name__ == "__main__":
27 | import doctest
28 |
29 | doctest.testmod()
30 |
--------------------------------------------------------------------------------
/bit_manipulation/excess_3_code.py:
--------------------------------------------------------------------------------
1 | def excess_3_code(number: int) -> str:
2 | """
3 | Find excess-3 code of integer base 10.
4 | Add 3 to all digits in a decimal number then convert to a binary-coded decimal.
5 | https://en.wikipedia.org/wiki/Excess-3
6 |
7 | >>> excess_3_code(0)
8 | '0b0011'
9 | >>> excess_3_code(3)
10 | '0b0110'
11 | >>> excess_3_code(2)
12 | '0b0101'
13 | >>> excess_3_code(20)
14 | '0b01010011'
15 | >>> excess_3_code(120)
16 | '0b010001010011'
17 | """
18 | num = ""
19 | for digit in str(max(0, number)):
20 | num += str(bin(int(digit) + 3))[2:].zfill(4)
21 | return "0b" + num
22 |
23 |
24 | if __name__ == "__main__":
25 | import doctest
26 |
27 | doctest.testmod()
28 |
--------------------------------------------------------------------------------
/bit_manipulation/find_previous_power_of_two.py:
--------------------------------------------------------------------------------
1 | def find_previous_power_of_two(number: int) -> int:
2 | """
3 | Find the largest power of two that is less than or equal to a given integer.
4 | https://stackoverflow.com/questions/1322510
5 |
6 | >>> [find_previous_power_of_two(i) for i in range(18)]
7 | [0, 1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16, 16]
8 | >>> find_previous_power_of_two(-5)
9 | Traceback (most recent call last):
10 | ...
11 | ValueError: Input must be a non-negative integer
12 | >>> find_previous_power_of_two(10.5)
13 | Traceback (most recent call last):
14 | ...
15 | ValueError: Input must be a non-negative integer
16 | """
17 | if not isinstance(number, int) or number < 0:
18 | raise ValueError("Input must be a non-negative integer")
19 | if number == 0:
20 | return 0
21 | power = 1
22 | while power <= number:
23 | power <<= 1 # Equivalent to multiplying by 2
24 | return power >> 1 if number > 1 else 1
25 |
26 |
27 | if __name__ == "__main__":
28 | import doctest
29 |
30 | doctest.testmod()
31 |
--------------------------------------------------------------------------------
/bit_manipulation/highest_set_bit.py:
--------------------------------------------------------------------------------
1 | def get_highest_set_bit_position(number: int) -> int:
2 | """
3 | Returns position of the highest set bit of a number.
4 | Ref - https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious
5 | >>> get_highest_set_bit_position(25)
6 | 5
7 | >>> get_highest_set_bit_position(37)
8 | 6
9 | >>> get_highest_set_bit_position(1)
10 | 1
11 | >>> get_highest_set_bit_position(4)
12 | 3
13 | >>> get_highest_set_bit_position(0)
14 | 0
15 | >>> get_highest_set_bit_position(0.8)
16 | Traceback (most recent call last):
17 | ...
18 | TypeError: Input value must be an 'int' type
19 | """
20 | if not isinstance(number, int):
21 | raise TypeError("Input value must be an 'int' type")
22 |
23 | position = 0
24 | while number:
25 | position += 1
26 | number >>= 1
27 |
28 | return position
29 |
30 |
31 | if __name__ == "__main__":
32 | import doctest
33 |
34 | doctest.testmod()
35 |
--------------------------------------------------------------------------------
/bit_manipulation/is_even.py:
--------------------------------------------------------------------------------
1 | def is_even(number: int) -> bool:
2 | """
3 | return true if the input integer is even
4 | Explanation: Lets take a look at the following decimal to binary conversions
5 | 2 => 10
6 | 14 => 1110
7 | 100 => 1100100
8 | 3 => 11
9 | 13 => 1101
10 | 101 => 1100101
11 | from the above examples we can observe that
12 | for all the odd integers there is always 1 set bit at the end
13 | also, 1 in binary can be represented as 001, 00001, or 0000001
14 | so for any odd integer n => n&1 is always equals 1 else the integer is even
15 |
16 | >>> is_even(1)
17 | False
18 | >>> is_even(4)
19 | True
20 | >>> is_even(9)
21 | False
22 | >>> is_even(15)
23 | False
24 | >>> is_even(40)
25 | True
26 | >>> is_even(100)
27 | True
28 | >>> is_even(101)
29 | False
30 | """
31 | return number & 1 == 0
32 |
33 |
34 | if __name__ == "__main__":
35 | import doctest
36 |
37 | doctest.testmod()
38 |
--------------------------------------------------------------------------------
/bit_manipulation/missing_number.py:
--------------------------------------------------------------------------------
1 | def find_missing_number(nums: list[int]) -> int:
2 | """
3 | Finds the missing number in a list of consecutive integers.
4 |
5 | Args:
6 | nums: A list of integers.
7 |
8 | Returns:
9 | The missing number.
10 |
11 | Example:
12 | >>> find_missing_number([0, 1, 3, 4])
13 | 2
14 | >>> find_missing_number([4, 3, 1, 0])
15 | 2
16 | >>> find_missing_number([-4, -3, -1, 0])
17 | -2
18 | >>> find_missing_number([-2, 2, 1, 3, 0])
19 | -1
20 | >>> find_missing_number([1, 3, 4, 5, 6])
21 | 2
22 | >>> find_missing_number([6, 5, 4, 2, 1])
23 | 3
24 | >>> find_missing_number([6, 1, 5, 3, 4])
25 | 2
26 | """
27 | low = min(nums)
28 | high = max(nums)
29 | missing_number = high
30 |
31 | for i in range(low, high):
32 | missing_number ^= i ^ nums[i - low]
33 |
34 | return missing_number
35 |
36 |
37 | if __name__ == "__main__":
38 | import doctest
39 |
40 | doctest.testmod()
41 |
--------------------------------------------------------------------------------
/bit_manipulation/numbers_different_signs.py:
--------------------------------------------------------------------------------
1 | """
2 | Author : Alexander Pantyukhin
3 | Date : November 30, 2022
4 |
5 | Task:
6 | Given two int numbers. Return True these numbers have opposite signs
7 | or False otherwise.
8 |
9 | Implementation notes: Use bit manipulation.
10 | Use XOR for two numbers.
11 | """
12 |
13 |
14 | def different_signs(num1: int, num2: int) -> bool:
15 | """
16 | Return True if numbers have opposite signs False otherwise.
17 |
18 | >>> different_signs(1, -1)
19 | True
20 | >>> different_signs(1, 1)
21 | False
22 | >>> different_signs(1000000000000000000000000000, -1000000000000000000000000000)
23 | True
24 | >>> different_signs(-1000000000000000000000000000, 1000000000000000000000000000)
25 | True
26 | >>> different_signs(50, 278)
27 | False
28 | >>> different_signs(0, 2)
29 | False
30 | >>> different_signs(2, 0)
31 | False
32 | """
33 | return num1 ^ num2 < 0
34 |
35 |
36 | if __name__ == "__main__":
37 | import doctest
38 |
39 | doctest.testmod()
40 |
--------------------------------------------------------------------------------
/blockchain/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/blockchain/__init__.py
--------------------------------------------------------------------------------
/boolean_algebra/README.md:
--------------------------------------------------------------------------------
1 | # Boolean Algebra
2 |
3 | Boolean algebra is used to do arithmetic with bits of values True (1) or False (0).
4 | There are three basic operations: 'and', 'or' and 'not'.
5 |
6 | *
7 | *
8 |
--------------------------------------------------------------------------------
/boolean_algebra/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/boolean_algebra/__init__.py
--------------------------------------------------------------------------------
/boolean_algebra/imply_gate.py:
--------------------------------------------------------------------------------
1 | """
2 | An IMPLY Gate is a logic gate in boolean algebra which results to 1 if
3 | either input 1 is 0, or if input 1 is 1, then the output is 1 only if input 2 is 1.
4 | It is true if input 1 implies input 2.
5 |
6 | Following is the truth table of an IMPLY Gate:
7 | ------------------------------
8 | | Input 1 | Input 2 | Output |
9 | ------------------------------
10 | | 0 | 0 | 1 |
11 | | 0 | 1 | 1 |
12 | | 1 | 0 | 0 |
13 | | 1 | 1 | 1 |
14 | ------------------------------
15 |
16 | Refer - https://en.wikipedia.org/wiki/IMPLY_gate
17 | """
18 |
19 |
20 | def imply_gate(input_1: int, input_2: int) -> int:
21 | """
22 | Calculate IMPLY of the input values
23 |
24 | >>> imply_gate(0, 0)
25 | 1
26 | >>> imply_gate(0, 1)
27 | 1
28 | >>> imply_gate(1, 0)
29 | 0
30 | >>> imply_gate(1, 1)
31 | 1
32 | """
33 | return int(input_1 == 0 or input_2 == 1)
34 |
35 |
36 | if __name__ == "__main__":
37 | import doctest
38 |
39 | doctest.testmod()
40 |
--------------------------------------------------------------------------------
/boolean_algebra/nand_gate.py:
--------------------------------------------------------------------------------
1 | """
2 | A NAND Gate is a logic gate in boolean algebra which results to 0 (False) if both
3 | the inputs are 1, and 1 (True) otherwise. It's similar to adding
4 | a NOT gate along with an AND gate.
5 | Following is the truth table of a NAND Gate:
6 | ------------------------------
7 | | Input 1 | Input 2 | Output |
8 | ------------------------------
9 | | 0 | 0 | 1 |
10 | | 0 | 1 | 1 |
11 | | 1 | 0 | 1 |
12 | | 1 | 1 | 0 |
13 | ------------------------------
14 | Refer - https://www.geeksforgeeks.org/logic-gates-in-python/
15 | """
16 |
17 |
18 | def nand_gate(input_1: int, input_2: int) -> int:
19 | """
20 | Calculate NAND of the input values
21 | >>> nand_gate(0, 0)
22 | 1
23 | >>> nand_gate(0, 1)
24 | 1
25 | >>> nand_gate(1, 0)
26 | 1
27 | >>> nand_gate(1, 1)
28 | 0
29 | """
30 | return int(not (input_1 and input_2))
31 |
32 |
33 | if __name__ == "__main__":
34 | import doctest
35 |
36 | doctest.testmod()
37 |
--------------------------------------------------------------------------------
/boolean_algebra/nimply_gate.py:
--------------------------------------------------------------------------------
1 | """
2 | An NIMPLY Gate is a logic gate in boolean algebra which results to 0 if
3 | either input 1 is 0, or if input 1 is 1, then it is 0 only if input 2 is 1.
4 | It is false if input 1 implies input 2. It is the negated form of imply
5 |
6 | Following is the truth table of an NIMPLY Gate:
7 | ------------------------------
8 | | Input 1 | Input 2 | Output |
9 | ------------------------------
10 | | 0 | 0 | 0 |
11 | | 0 | 1 | 0 |
12 | | 1 | 0 | 1 |
13 | | 1 | 1 | 0 |
14 | ------------------------------
15 |
16 | Refer - https://en.wikipedia.org/wiki/NIMPLY_gate
17 | """
18 |
19 |
20 | def nimply_gate(input_1: int, input_2: int) -> int:
21 | """
22 | Calculate NIMPLY of the input values
23 |
24 | >>> nimply_gate(0, 0)
25 | 0
26 | >>> nimply_gate(0, 1)
27 | 0
28 | >>> nimply_gate(1, 0)
29 | 1
30 | >>> nimply_gate(1, 1)
31 | 0
32 | """
33 | return int(input_1 == 1 and input_2 == 0)
34 |
35 |
36 | if __name__ == "__main__":
37 | import doctest
38 |
39 | doctest.testmod()
40 |
--------------------------------------------------------------------------------
/boolean_algebra/not_gate.py:
--------------------------------------------------------------------------------
1 | """
2 | A NOT Gate is a logic gate in boolean algebra which results to 0 (False) if the
3 | input is high, and 1 (True) if the input is low.
4 | Following is the truth table of a XOR Gate:
5 | ------------------------------
6 | | Input | Output |
7 | ------------------------------
8 | | 0 | 1 |
9 | | 1 | 0 |
10 | ------------------------------
11 | Refer - https://www.geeksforgeeks.org/logic-gates-in-python/
12 | """
13 |
14 |
15 | def not_gate(input_1: int) -> int:
16 | """
17 | Calculate NOT of the input values
18 | >>> not_gate(0)
19 | 1
20 | >>> not_gate(1)
21 | 0
22 | """
23 |
24 | return 1 if input_1 == 0 else 0
25 |
26 |
27 | if __name__ == "__main__":
28 | import doctest
29 |
30 | doctest.testmod()
31 |
--------------------------------------------------------------------------------
/boolean_algebra/or_gate.py:
--------------------------------------------------------------------------------
1 | """
2 | An OR Gate is a logic gate in boolean algebra which results to 0 (False) if both the
3 | inputs are 0, and 1 (True) otherwise.
4 | Following is the truth table of an AND Gate:
5 | ------------------------------
6 | | Input 1 | Input 2 | Output |
7 | ------------------------------
8 | | 0 | 0 | 0 |
9 | | 0 | 1 | 1 |
10 | | 1 | 0 | 1 |
11 | | 1 | 1 | 1 |
12 | ------------------------------
13 | Refer - https://www.geeksforgeeks.org/logic-gates-in-python/
14 | """
15 |
16 |
17 | def or_gate(input_1: int, input_2: int) -> int:
18 | """
19 | Calculate OR of the input values
20 | >>> or_gate(0, 0)
21 | 0
22 | >>> or_gate(0, 1)
23 | 1
24 | >>> or_gate(1, 0)
25 | 1
26 | >>> or_gate(1, 1)
27 | 1
28 | """
29 | return int((input_1, input_2).count(1) != 0)
30 |
31 |
32 | if __name__ == "__main__":
33 | import doctest
34 |
35 | doctest.testmod()
36 |
--------------------------------------------------------------------------------
/boolean_algebra/xnor_gate.py:
--------------------------------------------------------------------------------
1 | """
2 | A XNOR Gate is a logic gate in boolean algebra which results to 0 (False) if both the
3 | inputs are different, and 1 (True), if the inputs are same.
4 | It's similar to adding a NOT gate to an XOR gate
5 |
6 | Following is the truth table of a XNOR Gate:
7 | ------------------------------
8 | | Input 1 | Input 2 | Output |
9 | ------------------------------
10 | | 0 | 0 | 1 |
11 | | 0 | 1 | 0 |
12 | | 1 | 0 | 0 |
13 | | 1 | 1 | 1 |
14 | ------------------------------
15 | Refer - https://www.geeksforgeeks.org/logic-gates-in-python/
16 | """
17 |
18 |
19 | def xnor_gate(input_1: int, input_2: int) -> int:
20 | """
21 | Calculate XOR of the input values
22 | >>> xnor_gate(0, 0)
23 | 1
24 | >>> xnor_gate(0, 1)
25 | 0
26 | >>> xnor_gate(1, 0)
27 | 0
28 | >>> xnor_gate(1, 1)
29 | 1
30 | """
31 | return 1 if input_1 == input_2 else 0
32 |
33 |
34 | if __name__ == "__main__":
35 | import doctest
36 |
37 | doctest.testmod()
38 |
--------------------------------------------------------------------------------
/boolean_algebra/xor_gate.py:
--------------------------------------------------------------------------------
1 | """
2 | A XOR Gate is a logic gate in boolean algebra which results to 1 (True) if only one of
3 | the two inputs is 1, and 0 (False) if an even number of inputs are 1.
4 | Following is the truth table of a XOR Gate:
5 | ------------------------------
6 | | Input 1 | Input 2 | Output |
7 | ------------------------------
8 | | 0 | 0 | 0 |
9 | | 0 | 1 | 1 |
10 | | 1 | 0 | 1 |
11 | | 1 | 1 | 0 |
12 | ------------------------------
13 |
14 | Refer - https://www.geeksforgeeks.org/logic-gates-in-python/
15 | """
16 |
17 |
18 | def xor_gate(input_1: int, input_2: int) -> int:
19 | """
20 | calculate xor of the input values
21 |
22 | >>> xor_gate(0, 0)
23 | 0
24 | >>> xor_gate(0, 1)
25 | 1
26 | >>> xor_gate(1, 0)
27 | 1
28 | >>> xor_gate(1, 1)
29 | 0
30 | """
31 | return (input_1, input_2).count(0) % 2
32 |
33 |
34 | if __name__ == "__main__":
35 | import doctest
36 |
37 | doctest.testmod()
38 |
--------------------------------------------------------------------------------
/cellular_automata/README.md:
--------------------------------------------------------------------------------
1 | # Cellular Automata
2 |
3 | Cellular automata are a way to simulate the behavior of "life", no matter if it is a robot or cell.
4 | They usually follow simple rules but can lead to the creation of complex forms.
5 | The most popular cellular automaton is Conway's [Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life).
6 |
7 | *
8 | *
9 |
--------------------------------------------------------------------------------
/cellular_automata/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/cellular_automata/__init__.py
--------------------------------------------------------------------------------
/ciphers/README.md:
--------------------------------------------------------------------------------
1 | # Ciphers
2 |
3 | Ciphers are used to protect data from people that are not allowed to have it. They are everywhere on the internet to protect your connections.
4 |
5 | *
6 | *
7 | *
8 |
--------------------------------------------------------------------------------
/ciphers/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/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 | from __future__ import annotations
10 |
11 |
12 | def encode(plain: str) -> list[int]:
13 | """
14 | >>> encode("myname")
15 | [13, 25, 14, 1, 13, 5]
16 | """
17 | return [ord(elem) - 96 for elem in plain]
18 |
19 |
20 | def decode(encoded: list[int]) -> str:
21 | """
22 | >>> decode([13, 25, 14, 1, 13, 5])
23 | 'myname'
24 | """
25 | return "".join(chr(elem + 96) for elem in encoded)
26 |
27 |
28 | def main() -> None:
29 | encoded = encode(input("-> ").strip().lower())
30 | print("Encoded: ", encoded)
31 | print("Decoded:", decode(encoded))
32 |
33 |
34 | if __name__ == "__main__":
35 | main()
36 |
--------------------------------------------------------------------------------
/ciphers/cryptomath_module.py:
--------------------------------------------------------------------------------
1 | from maths.greatest_common_divisor import gcd_by_iterative
2 |
3 |
4 | def find_mod_inverse(a: int, m: int) -> int:
5 | if gcd_by_iterative(a, m) != 1:
6 | msg = f"mod inverse of {a!r} and {m!r} does not exist"
7 | raise ValueError(msg)
8 | u1, u2, u3 = 1, 0, a
9 | v1, v2, v3 = 0, 1, m
10 | while v3 != 0:
11 | q = u3 // v3
12 | v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3
13 | return u1 % m
14 |
--------------------------------------------------------------------------------
/ciphers/rot13.py:
--------------------------------------------------------------------------------
1 | def dencrypt(s: str, n: int = 13) -> str:
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() -> None:
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 |
--------------------------------------------------------------------------------
/computer_vision/README.md:
--------------------------------------------------------------------------------
1 | # Computer Vision
2 |
3 | Computer vision is a field of computer science that works on enabling computers to see, identify and process images in the same way that human does, and provide appropriate output.
4 |
5 | It is like imparting human intelligence and instincts to a computer.
6 | Image processing and computer vision are a little different from each other. Image processing means applying some algorithms for transforming image from one form to the other like smoothing, contrasting, stretching, etc.
7 |
8 | While 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 (much like the process of visual reasoning of human vision).
9 |
10 | *
11 |
--------------------------------------------------------------------------------
/computer_vision/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/computer_vision/__init__.py
--------------------------------------------------------------------------------
/computer_vision/mean_threshold.py:
--------------------------------------------------------------------------------
1 | from PIL import Image
2 |
3 | """
4 | Mean thresholding algorithm for image processing
5 | https://en.wikipedia.org/wiki/Thresholding_(image_processing)
6 | """
7 |
8 |
9 | def mean_threshold(image: Image) -> Image:
10 | """
11 | image: is a grayscale PIL image object
12 | """
13 | height, width = image.size
14 | mean = 0
15 | pixels = image.load()
16 | for i in range(width):
17 | for j in range(height):
18 | pixel = pixels[j, i]
19 | mean += pixel
20 | mean //= width * height
21 |
22 | for j in range(width):
23 | for i in range(height):
24 | pixels[i, j] = 255 if pixels[i, j] > mean else 0
25 | return image
26 |
27 |
28 | if __name__ == "__main__":
29 | image = mean_threshold(Image.open("path_to_image").convert("L"))
30 | image.save("output_image_path")
31 |
--------------------------------------------------------------------------------
/conversions/README.md:
--------------------------------------------------------------------------------
1 | # Conversion
2 |
3 | Conversion programs convert a type of data, a number from a numerical base or unit into one of another type, base or unit, e.g. binary to decimal, integer to string or foot to meters.
4 |
5 | *
6 | *
7 |
--------------------------------------------------------------------------------
/conversions/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/conversions/__init__.py
--------------------------------------------------------------------------------
/conversions/excel_title_to_column.py:
--------------------------------------------------------------------------------
1 | def excel_title_to_column(column_title: str) -> int:
2 | """
3 | Given a string column_title that represents
4 | the column title in an Excel sheet, return
5 | its corresponding column number.
6 |
7 | >>> excel_title_to_column("A")
8 | 1
9 | >>> excel_title_to_column("B")
10 | 2
11 | >>> excel_title_to_column("AB")
12 | 28
13 | >>> excel_title_to_column("Z")
14 | 26
15 | """
16 | assert column_title.isupper()
17 | answer = 0
18 | index = len(column_title) - 1
19 | power = 0
20 |
21 | while index >= 0:
22 | value = (ord(column_title[index]) - 64) * pow(26, power)
23 | answer += value
24 | power += 1
25 | index -= 1
26 |
27 | return answer
28 |
29 |
30 | if __name__ == "__main__":
31 | from doctest import testmod
32 |
33 | testmod()
34 |
--------------------------------------------------------------------------------
/conversions/rectangular_to_polar.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 |
4 | def rectangular_to_polar(real: float, img: float) -> tuple[float, float]:
5 | """
6 | https://en.wikipedia.org/wiki/Polar_coordinate_system
7 |
8 | >>> rectangular_to_polar(5,-5)
9 | (7.07, -45.0)
10 | >>> rectangular_to_polar(-1,1)
11 | (1.41, 135.0)
12 | >>> rectangular_to_polar(-1,-1)
13 | (1.41, -135.0)
14 | >>> rectangular_to_polar(1e-10,1e-10)
15 | (0.0, 45.0)
16 | >>> rectangular_to_polar(-1e-10,1e-10)
17 | (0.0, 135.0)
18 | >>> rectangular_to_polar(9.75,5.93)
19 | (11.41, 31.31)
20 | >>> rectangular_to_polar(10000,99999)
21 | (100497.76, 84.29)
22 | """
23 |
24 | mod = round(math.sqrt((real**2) + (img**2)), 2)
25 | ang = round(math.degrees(math.atan2(img, real)), 2)
26 | return (mod, ang)
27 |
28 |
29 | if __name__ == "__main__":
30 | import doctest
31 |
32 | doctest.testmod()
33 |
--------------------------------------------------------------------------------
/data_compression/README.md:
--------------------------------------------------------------------------------
1 | # Compression
2 |
3 | Data compression is everywhere, you need it to store data without taking too much space.
4 | Either the compression loses some data (then we talk about lossy compression, such as .jpg) or it does not (and then it is lossless compression, such as .png)
5 |
6 | Lossless compression is mainly used for archive purpose as it allows storing data without losing information about the file archived. On the other hand, lossy compression is used for transfer of file where quality isn't necessarily what is required (i.e: images on Twitter).
7 |
8 | *
9 | *
10 | *
11 |
--------------------------------------------------------------------------------
/data_compression/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_compression/__init__.py
--------------------------------------------------------------------------------
/data_compression/image_data/PSNR-example-base.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_compression/image_data/PSNR-example-base.png
--------------------------------------------------------------------------------
/data_compression/image_data/PSNR-example-comp-10.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_compression/image_data/PSNR-example-comp-10.jpg
--------------------------------------------------------------------------------
/data_compression/image_data/compressed_image.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_compression/image_data/compressed_image.png
--------------------------------------------------------------------------------
/data_compression/image_data/example_image.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_compression/image_data/example_image.jpg
--------------------------------------------------------------------------------
/data_compression/image_data/example_wikipedia_image.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_compression/image_data/example_wikipedia_image.jpg
--------------------------------------------------------------------------------
/data_compression/image_data/original_image.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_compression/image_data/original_image.png
--------------------------------------------------------------------------------
/data_structures/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_structures/__init__.py
--------------------------------------------------------------------------------
/data_structures/arrays/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_structures/arrays/__init__.py
--------------------------------------------------------------------------------
/data_structures/arrays/monotonic_array.py:
--------------------------------------------------------------------------------
1 | # https://leetcode.com/problems/monotonic-array/
2 | def is_monotonic(nums: list[int]) -> bool:
3 | """
4 | Check if a list is monotonic.
5 |
6 | >>> is_monotonic([1, 2, 2, 3])
7 | True
8 | >>> is_monotonic([6, 5, 4, 4])
9 | True
10 | >>> is_monotonic([1, 3, 2])
11 | False
12 | >>> is_monotonic([1,2,3,4,5,6,5])
13 | False
14 | >>> is_monotonic([-3,-2,-1])
15 | True
16 | >>> is_monotonic([-5,-6,-7])
17 | True
18 | >>> is_monotonic([0,0,0])
19 | True
20 | >>> is_monotonic([-100,0,100])
21 | True
22 | """
23 | return all(nums[i] <= nums[i + 1] for i in range(len(nums) - 1)) or all(
24 | nums[i] >= nums[i + 1] for i in range(len(nums) - 1)
25 | )
26 |
27 |
28 | # Test the function with your examples
29 | if __name__ == "__main__":
30 | # Test the function with your examples
31 | print(is_monotonic([1, 2, 2, 3])) # Output: True
32 | print(is_monotonic([6, 5, 4, 4])) # Output: True
33 | print(is_monotonic([1, 3, 2])) # Output: False
34 |
35 | import doctest
36 |
37 | doctest.testmod()
38 |
--------------------------------------------------------------------------------
/data_structures/arrays/pairs_with_given_sum.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | """
4 | Given an array of integers and an integer req_sum, find the number of pairs of array
5 | elements whose sum is equal to req_sum.
6 |
7 | https://practice.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/0
8 | """
9 |
10 | from itertools import combinations
11 |
12 |
13 | def pairs_with_sum(arr: list, req_sum: int) -> int:
14 | """
15 | Return the no. of pairs with sum "sum"
16 | >>> pairs_with_sum([1, 5, 7, 1], 6)
17 | 2
18 | >>> pairs_with_sum([1, 1, 1, 1, 1, 1, 1, 1], 2)
19 | 28
20 | >>> pairs_with_sum([1, 7, 6, 2, 5, 4, 3, 1, 9, 8], 7)
21 | 4
22 | """
23 | return len([1 for a, b in combinations(arr, 2) if a + b == req_sum])
24 |
25 |
26 | if __name__ == "__main__":
27 | from doctest import testmod
28 |
29 | testmod()
30 |
--------------------------------------------------------------------------------
/data_structures/binary_tree/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_structures/binary_tree/__init__.py
--------------------------------------------------------------------------------
/data_structures/disjoint_set/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_structures/disjoint_set/__init__.py
--------------------------------------------------------------------------------
/data_structures/hashing/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/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/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_structures/hashing/number_theory/__init__.py
--------------------------------------------------------------------------------
/data_structures/hashing/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_structures/hashing/tests/__init__.py
--------------------------------------------------------------------------------
/data_structures/heap/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_structures/heap/__init__.py
--------------------------------------------------------------------------------
/data_structures/kd_tree/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_structures/kd_tree/__init__.py
--------------------------------------------------------------------------------
/data_structures/kd_tree/example/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_structures/kd_tree/example/__init__.py
--------------------------------------------------------------------------------
/data_structures/kd_tree/example/hypercube_points.py:
--------------------------------------------------------------------------------
1 | # Created by: Ramy-Badr-Ahmed (https://github.com/Ramy-Badr-Ahmed)
2 | # in Pull Request: #11532
3 | # https://github.com/TheAlgorithms/Python/pull/11532
4 | #
5 | # Please mention me (@Ramy-Badr-Ahmed) in any issue or pull request
6 | # addressing bugs/corrections to this file.
7 | # Thank you!
8 |
9 | import numpy as np
10 |
11 |
12 | def hypercube_points(
13 | num_points: int, hypercube_size: float, num_dimensions: int
14 | ) -> np.ndarray:
15 | """
16 | Generates random points uniformly distributed within an n-dimensional hypercube.
17 |
18 | Args:
19 | num_points: Number of points to generate.
20 | hypercube_size: Size of the hypercube.
21 | num_dimensions: Number of dimensions of the hypercube.
22 |
23 | Returns:
24 | An array of shape (num_points, num_dimensions)
25 | with generated points.
26 | """
27 | rng = np.random.default_rng()
28 | shape = (num_points, num_dimensions)
29 | return hypercube_size * rng.random(shape)
30 |
--------------------------------------------------------------------------------
/data_structures/kd_tree/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_structures/kd_tree/tests/__init__.py
--------------------------------------------------------------------------------
/data_structures/queues/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_structures/queues/__init__.py
--------------------------------------------------------------------------------
/data_structures/stacks/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_structures/stacks/__init__.py
--------------------------------------------------------------------------------
/data_structures/suffix_tree/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_structures/suffix_tree/__init__.py
--------------------------------------------------------------------------------
/data_structures/suffix_tree/example/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_structures/suffix_tree/example/__init__.py
--------------------------------------------------------------------------------
/data_structures/suffix_tree/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_structures/suffix_tree/tests/__init__.py
--------------------------------------------------------------------------------
/data_structures/trie/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/data_structures/trie/__init__.py
--------------------------------------------------------------------------------
/digital_image_processing/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/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 | psf/black: True
8 | ruff : True
9 | """
10 |
11 | from PIL import Image
12 |
13 |
14 | def change_contrast(img: Image, level: int) -> Image:
15 | """
16 | Function to change contrast
17 | """
18 | factor = (259 * (level + 255)) / (255 * (259 - level))
19 |
20 | def contrast(c: int) -> int:
21 | """
22 | Fundamental Transformation/Operation that'll be performed on
23 | every bit.
24 | """
25 | return int(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 |
5 | from cv2 import destroyAllWindows, imread, imshow, waitKey
6 |
7 |
8 | def convert_to_negative(img):
9 | # getting number of pixels in the image
10 | pixel_h, pixel_v = img.shape[0], img.shape[1]
11 |
12 | # converting each pixel's color to its negative
13 | for i in range(pixel_h):
14 | for j in range(pixel_v):
15 | img[i][j] = [255, 255, 255] - img[i][j]
16 |
17 | return img
18 |
19 |
20 | if __name__ == "__main__":
21 | # read original image
22 | img = imread("image_data/lena.jpg", 1)
23 |
24 | # convert to its negative
25 | neg = convert_to_negative(img)
26 |
27 | # show result image
28 | imshow("negative of original image", img)
29 | waitKey(0)
30 | destroyAllWindows()
31 |
--------------------------------------------------------------------------------
/digital_image_processing/dithering/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/digital_image_processing/dithering/__init__.py
--------------------------------------------------------------------------------
/digital_image_processing/edge_detection/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/digital_image_processing/edge_detection/__init__.py
--------------------------------------------------------------------------------
/digital_image_processing/filters/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/digital_image_processing/filters/__init__.py
--------------------------------------------------------------------------------
/digital_image_processing/histogram_equalization/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/digital_image_processing/histogram_equalization/__init__.py
--------------------------------------------------------------------------------
/digital_image_processing/histogram_equalization/image_data/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/digital_image_processing/histogram_equalization/image_data/__init__.py
--------------------------------------------------------------------------------
/digital_image_processing/histogram_equalization/image_data/input.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/digital_image_processing/histogram_equalization/image_data/input.jpg
--------------------------------------------------------------------------------
/digital_image_processing/histogram_equalization/output_data/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/digital_image_processing/histogram_equalization/output_data/__init__.py
--------------------------------------------------------------------------------
/digital_image_processing/histogram_equalization/output_data/output.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/digital_image_processing/histogram_equalization/output_data/output.jpg
--------------------------------------------------------------------------------
/digital_image_processing/image_data/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/digital_image_processing/image_data/__init__.py
--------------------------------------------------------------------------------
/digital_image_processing/image_data/lena.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/digital_image_processing/image_data/lena.jpg
--------------------------------------------------------------------------------
/digital_image_processing/image_data/lena_small.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/digital_image_processing/image_data/lena_small.jpg
--------------------------------------------------------------------------------
/digital_image_processing/morphological_operations/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/digital_image_processing/morphological_operations/__init__.py
--------------------------------------------------------------------------------
/digital_image_processing/resize/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/digital_image_processing/resize/__init__.py
--------------------------------------------------------------------------------
/digital_image_processing/rotation/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/digital_image_processing/rotation/__init__.py
--------------------------------------------------------------------------------
/divide_and_conquer/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/divide_and_conquer/__init__.py
--------------------------------------------------------------------------------
/docs/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/docs/__init__.py
--------------------------------------------------------------------------------
/docs/conf.py:
--------------------------------------------------------------------------------
1 | from sphinx_pyproject import SphinxConfig
2 |
3 | project = SphinxConfig("../pyproject.toml", globalns=globals()).name
4 |
--------------------------------------------------------------------------------
/docs/source/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/docs/source/__init__.py
--------------------------------------------------------------------------------
/dynamic_programming/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/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/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 |
8 | from __future__ import annotations
9 |
10 | import sys
11 |
12 |
13 | def fibonacci(n: int) -> int:
14 | """
15 | return F(n)
16 | >>> [fibonacci(i) for i in range(13)]
17 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
18 | """
19 | if n < 0:
20 | raise ValueError("Negative arguments are not supported")
21 | return _fib(n)[0]
22 |
23 |
24 | # returns (F(n), F(n-1))
25 | def _fib(n: int) -> tuple[int, int]:
26 | if n == 0: # (F(0), F(1))
27 | return (0, 1)
28 |
29 | # F(2n) = F(n)[2F(n+1) - F(n)]
30 | # F(2n+1) = F(n+1)^2+F(n)^2
31 | a, b = _fib(n // 2)
32 | c = a * (b * 2 - a)
33 | d = a * a + b * b
34 | return (d, c + d) if n % 2 else (c, d)
35 |
36 |
37 | if __name__ == "__main__":
38 | n = int(sys.argv[1])
39 | print(f"fibonacci({n}) is {fibonacci(n)}")
40 |
--------------------------------------------------------------------------------
/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 | >>> 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/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/tribonacci.py:
--------------------------------------------------------------------------------
1 | # Tribonacci sequence using Dynamic Programming
2 |
3 |
4 | def tribonacci(num: int) -> list[int]:
5 | """
6 | Given a number, return first n Tribonacci Numbers.
7 | >>> tribonacci(5)
8 | [0, 0, 1, 1, 2]
9 | >>> tribonacci(8)
10 | [0, 0, 1, 1, 2, 4, 7, 13]
11 | """
12 | dp = [0] * num
13 | dp[2] = 1
14 |
15 | for i in range(3, num):
16 | dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]
17 |
18 | return dp
19 |
20 |
21 | if __name__ == "__main__":
22 | import doctest
23 |
24 | doctest.testmod()
25 |
--------------------------------------------------------------------------------
/electronics/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/electronics/__init__.py
--------------------------------------------------------------------------------
/file_transfer/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/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 | import socket
2 |
3 |
4 | def main():
5 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
6 | host = socket.gethostname()
7 | port = 12312
8 |
9 | sock.connect((host, port))
10 | sock.send(b"Hello server!")
11 |
12 | with open("Received_file", "wb") as out_file:
13 | print("File opened")
14 | print("Receiving data...")
15 | while True:
16 | data = sock.recv(1024)
17 | if not data:
18 | break
19 | out_file.write(data)
20 |
21 | print("Successfully received the file")
22 | sock.close()
23 | print("Connection closed")
24 |
25 |
26 | if __name__ == "__main__":
27 | main()
28 |
--------------------------------------------------------------------------------
/file_transfer/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/file_transfer/tests/__init__.py
--------------------------------------------------------------------------------
/financial/README.md:
--------------------------------------------------------------------------------
1 | # Interest
2 |
3 | * Compound Interest: "Compound interest is calculated by multiplying the initial principal amount by one plus the annual interest rate raised to the number of compound periods minus one." [Compound Interest](https://www.investopedia.com/)
4 | * Simple Interest: "Simple interest paid or received over a certain period is a fixed percentage of the principal amount that was borrowed or lent. " [Simple Interest](https://www.investopedia.com/)
5 |
--------------------------------------------------------------------------------
/financial/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/financial/__init__.py
--------------------------------------------------------------------------------
/financial/price_plus_tax.py:
--------------------------------------------------------------------------------
1 | """
2 | Calculate price plus tax of a good or service given its price and a tax rate.
3 | """
4 |
5 |
6 | def price_plus_tax(price: float, tax_rate: float) -> float:
7 | """
8 | >>> price_plus_tax(100, 0.25)
9 | 125.0
10 | >>> price_plus_tax(125.50, 0.05)
11 | 131.775
12 | """
13 | return price * (1 + tax_rate)
14 |
15 |
16 | if __name__ == "__main__":
17 | print(f"{price_plus_tax(100, 0.25) = }")
18 | print(f"{price_plus_tax(125.50, 0.05) = }")
19 |
--------------------------------------------------------------------------------
/fractals/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/fractals/__init__.py
--------------------------------------------------------------------------------
/fuzzy_logic/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/fuzzy_logic/__init__.py
--------------------------------------------------------------------------------
/genetic_algorithm/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/genetic_algorithm/__init__.py
--------------------------------------------------------------------------------
/geodesy/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/geodesy/__init__.py
--------------------------------------------------------------------------------
/geometry/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/geometry/__init__.py
--------------------------------------------------------------------------------
/graphics/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/graphics/__init__.py
--------------------------------------------------------------------------------
/graphs/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/graphs/__init__.py
--------------------------------------------------------------------------------
/graphs/kahns_algorithm_long.py:
--------------------------------------------------------------------------------
1 | # Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm
2 | def longest_distance(graph):
3 | indegree = [0] * len(graph)
4 | queue = []
5 | long_dist = [1] * len(graph)
6 |
7 | for values in graph.values():
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 | long_dist[x] = max(long_dist[x], long_dist[vertex] + 1)
21 |
22 | if indegree[x] == 0:
23 | queue.append(x)
24 |
25 | print(max(long_dist))
26 |
27 |
28 | # Adjacency list of Graph
29 | graph = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []}
30 | longest_distance(graph)
31 |
--------------------------------------------------------------------------------
/graphs/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/graphs/tests/__init__.py
--------------------------------------------------------------------------------
/graphs/tests/test_min_spanning_tree_kruskal.py:
--------------------------------------------------------------------------------
1 | from graphs.minimum_spanning_tree_kruskal import kruskal
2 |
3 |
4 | def test_kruskal_successful_result():
5 | num_nodes = 9
6 | edges = [
7 | [0, 1, 4],
8 | [0, 7, 8],
9 | [1, 2, 8],
10 | [7, 8, 7],
11 | [7, 6, 1],
12 | [2, 8, 2],
13 | [8, 6, 6],
14 | [2, 3, 7],
15 | [2, 5, 4],
16 | [6, 5, 2],
17 | [3, 5, 14],
18 | [3, 4, 9],
19 | [5, 4, 10],
20 | [1, 7, 11],
21 | ]
22 |
23 | result = kruskal(num_nodes, edges)
24 |
25 | expected = [
26 | [7, 6, 1],
27 | [2, 8, 2],
28 | [6, 5, 2],
29 | [0, 1, 4],
30 | [2, 5, 4],
31 | [2, 3, 7],
32 | [0, 7, 8],
33 | [3, 4, 9],
34 | ]
35 |
36 | assert sorted(expected) == sorted(result)
37 |
--------------------------------------------------------------------------------
/greedy_methods/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/greedy_methods/__init__.py
--------------------------------------------------------------------------------
/hashes/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/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 | MOD_ADLER = 65521
12 |
13 |
14 | def adler32(plain_text: str) -> int:
15 | """
16 | Function implements adler-32 hash.
17 | Iterates and evaluates a new value for each character
18 |
19 | >>> adler32('Algorithms')
20 | 363791387
21 |
22 | >>> adler32('go adler em all')
23 | 708642122
24 | """
25 | a = 1
26 | b = 0
27 | for plain_chr in plain_text:
28 | a = (a + ord(plain_chr)) % MOD_ADLER
29 | b = (b + a) % MOD_ADLER
30 | return (b << 16) | a
31 |
--------------------------------------------------------------------------------
/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_value = 5381
33 | for x in s:
34 | hash_value = ((hash_value << 5) + hash_value) + ord(x)
35 | return hash_value & 0xFFFFFFFF
36 |
--------------------------------------------------------------------------------
/hashes/elf.py:
--------------------------------------------------------------------------------
1 | def elf_hash(data: str) -> int:
2 | """
3 | Implementation of ElfHash Algorithm, a variant of PJW hash function.
4 |
5 | >>> elf_hash('lorem ipsum')
6 | 253956621
7 | """
8 | hash_ = x = 0
9 | for letter in data:
10 | hash_ = (hash_ << 4) + ord(letter)
11 | x = hash_ & 0xF0000000
12 | if x != 0:
13 | hash_ ^= x >> 24
14 | hash_ &= ~x
15 | return hash_
16 |
17 |
18 | if __name__ == "__main__":
19 | import doctest
20 |
21 | doctest.testmod()
22 |
--------------------------------------------------------------------------------
/index.md:
--------------------------------------------------------------------------------
1 | # TheAlgorithms/Python
2 | ```{toctree}
3 | :maxdepth: 2
4 | :caption: index.md
5 |
6 |
7 | CONTRIBUTING.md
8 | README.md
9 | LICENSE.md
10 | ```
11 |
--------------------------------------------------------------------------------
/knapsack/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/knapsack/__init__.py
--------------------------------------------------------------------------------
/knapsack/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/knapsack/tests/__init__.py
--------------------------------------------------------------------------------
/linear_algebra/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/linear_algebra/__init__.py
--------------------------------------------------------------------------------
/linear_algebra/matrix_inversion.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 |
4 | def invert_matrix(matrix: list[list[float]]) -> list[list[float]]:
5 | """
6 | Returns the inverse of a square matrix using NumPy.
7 |
8 | Parameters:
9 | matrix (list[list[float]]): A square matrix.
10 |
11 | Returns:
12 | list[list[float]]: Inverted matrix if invertible, else raises error.
13 |
14 | >>> invert_matrix([[4.0, 7.0], [2.0, 6.0]])
15 | [[0.6000000000000001, -0.7000000000000001], [-0.2, 0.4]]
16 | >>> invert_matrix([[1.0, 2.0], [0.0, 0.0]])
17 | Traceback (most recent call last):
18 | ...
19 | ValueError: Matrix is not invertible
20 | """
21 | np_matrix = np.array(matrix)
22 |
23 | try:
24 | inv_matrix = np.linalg.inv(np_matrix)
25 | except np.linalg.LinAlgError:
26 | raise ValueError("Matrix is not invertible")
27 |
28 | return inv_matrix.tolist()
29 |
30 |
31 | if __name__ == "__main__":
32 | mat = [[4.0, 7.0], [2.0, 6.0]]
33 | print("Original Matrix:")
34 | print(mat)
35 | print("Inverted Matrix:")
36 | print(invert_matrix(mat))
37 |
--------------------------------------------------------------------------------
/linear_algebra/src/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/linear_algebra/src/__init__.py
--------------------------------------------------------------------------------
/linear_programming/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/linear_programming/__init__.py
--------------------------------------------------------------------------------
/machine_learning/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/machine_learning/__init__.py
--------------------------------------------------------------------------------
/machine_learning/forecasting/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/machine_learning/forecasting/__init__.py
--------------------------------------------------------------------------------
/machine_learning/local_weighted_learning/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/machine_learning/local_weighted_learning/__init__.py
--------------------------------------------------------------------------------
/machine_learning/lstm/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/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 | >>> [int(x) for x in 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/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/maths/__init__.py
--------------------------------------------------------------------------------
/maths/addition_without_arithmetic.py:
--------------------------------------------------------------------------------
1 | """
2 | Illustrate how to add the integer without arithmetic operation
3 | Author: suraj Kumar
4 | Time Complexity: 1
5 | https://en.wikipedia.org/wiki/Bitwise_operation
6 | """
7 |
8 |
9 | def add(first: int, second: int) -> int:
10 | """
11 | Implementation of addition of integer
12 |
13 | Examples:
14 | >>> add(3, 5)
15 | 8
16 | >>> add(13, 5)
17 | 18
18 | >>> add(-7, 2)
19 | -5
20 | >>> add(0, -7)
21 | -7
22 | >>> add(-321, 0)
23 | -321
24 | """
25 | while second != 0:
26 | c = first & second
27 | first ^= second
28 | second = c << 1
29 | return first
30 |
31 |
32 | if __name__ == "__main__":
33 | import doctest
34 |
35 | doctest.testmod()
36 |
37 | first = int(input("Enter the first number: ").strip())
38 | second = int(input("Enter the second number: ").strip())
39 | print(f"{add(first, second) = }")
40 |
--------------------------------------------------------------------------------
/maths/arc_length.py:
--------------------------------------------------------------------------------
1 | from math import pi
2 |
3 |
4 | def arc_length(angle: int, radius: int) -> float:
5 | """
6 | >>> arc_length(45, 5)
7 | 3.9269908169872414
8 | >>> arc_length(120, 15)
9 | 31.415926535897928
10 | >>> arc_length(90, 10)
11 | 15.707963267948966
12 | """
13 | return 2 * pi * radius * (angle / 360)
14 |
15 |
16 | if __name__ == "__main__":
17 | print(arc_length(90, 10))
18 |
--------------------------------------------------------------------------------
/maths/average_absolute_deviation.py:
--------------------------------------------------------------------------------
1 | def average_absolute_deviation(nums: list[int]) -> float:
2 | """
3 | Return the average absolute deviation of a list of numbers.
4 | Wiki: https://en.wikipedia.org/wiki/Average_absolute_deviation
5 |
6 | >>> average_absolute_deviation([0])
7 | 0.0
8 | >>> average_absolute_deviation([4, 1, 3, 2])
9 | 1.0
10 | >>> average_absolute_deviation([2, 70, 6, 50, 20, 8, 4, 0])
11 | 20.0
12 | >>> average_absolute_deviation([-20, 0, 30, 15])
13 | 16.25
14 | >>> average_absolute_deviation([])
15 | Traceback (most recent call last):
16 | ...
17 | ValueError: List is empty
18 | """
19 | if not nums: # Makes sure that the list is not empty
20 | raise ValueError("List is empty")
21 |
22 | average = sum(nums) / len(nums) # Calculate the average
23 | return sum(abs(x - average) for x in nums) / len(nums)
24 |
25 |
26 | if __name__ == "__main__":
27 | import doctest
28 |
29 | doctest.testmod()
30 |
--------------------------------------------------------------------------------
/maths/average_mean.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 |
3 |
4 | def mean(nums: list) -> float:
5 | """
6 | Find mean of a list of numbers.
7 | Wiki: https://en.wikipedia.org/wiki/Mean
8 |
9 | >>> mean([3, 6, 9, 12, 15, 18, 21])
10 | 12.0
11 | >>> mean([5, 10, 15, 20, 25, 30, 35])
12 | 20.0
13 | >>> mean([1, 2, 3, 4, 5, 6, 7, 8])
14 | 4.5
15 | >>> mean([])
16 | Traceback (most recent call last):
17 | ...
18 | ValueError: List is empty
19 | """
20 | if not nums:
21 | raise ValueError("List is empty")
22 | return sum(nums) / len(nums)
23 |
24 |
25 | if __name__ == "__main__":
26 | import doctest
27 |
28 | doctest.testmod()
29 |
--------------------------------------------------------------------------------
/maths/average_median.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 |
3 |
4 | def median(nums: list) -> int | float:
5 | """
6 | Find median of a list of numbers.
7 | Wiki: https://en.wikipedia.org/wiki/Median
8 |
9 | >>> median([0])
10 | 0
11 | >>> median([4, 1, 3, 2])
12 | 2.5
13 | >>> median([2, 70, 6, 50, 20, 8, 4])
14 | 8
15 |
16 | Args:
17 | nums: List of nums
18 |
19 | Returns:
20 | Median.
21 | """
22 | # The sorted function returns list[SupportsRichComparisonT@sorted]
23 | # which does not support `+`
24 | sorted_list: list[int] = sorted(nums)
25 | length = len(sorted_list)
26 | mid_index = length >> 1
27 | return (
28 | (sorted_list[mid_index] + sorted_list[mid_index - 1]) / 2
29 | if length % 2 == 0
30 | else sorted_list[mid_index]
31 | )
32 |
33 |
34 | def main():
35 | import doctest
36 |
37 | doctest.testmod()
38 |
39 |
40 | if __name__ == "__main__":
41 | main()
42 |
--------------------------------------------------------------------------------
/maths/average_mode.py:
--------------------------------------------------------------------------------
1 | from typing import Any
2 |
3 |
4 | def mode(input_list: list) -> list[Any]:
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 | >>> mode([2, 3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 2, 2, 2])
11 | [2]
12 | >>> mode([3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 2, 2, 2])
13 | [2]
14 | >>> mode([3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 4, 2, 2, 4, 2])
15 | [2, 4]
16 | >>> mode(["x", "y", "y", "z"])
17 | ['y']
18 | >>> mode(["x", "x" , "y", "y", "z"])
19 | ['x', 'y']
20 | """
21 | if not input_list:
22 | return []
23 | result = [input_list.count(value) for value in input_list]
24 | y = max(result) # Gets the maximum count in the input list.
25 | # Gets values of modes
26 | return sorted({input_list[i] for i, value in enumerate(result) if value == y})
27 |
28 |
29 | if __name__ == "__main__":
30 | import doctest
31 |
32 | doctest.testmod()
33 |
--------------------------------------------------------------------------------
/maths/base_neg2_conversion.py:
--------------------------------------------------------------------------------
1 | def decimal_to_negative_base_2(num: int) -> int:
2 | """
3 | This function returns the number negative base 2
4 | of the decimal number of the input data.
5 |
6 | Args:
7 | int: The decimal number to convert.
8 |
9 | Returns:
10 | int: The negative base 2 number.
11 |
12 | Examples:
13 | >>> decimal_to_negative_base_2(0)
14 | 0
15 | >>> decimal_to_negative_base_2(-19)
16 | 111101
17 | >>> decimal_to_negative_base_2(4)
18 | 100
19 | >>> decimal_to_negative_base_2(7)
20 | 11011
21 | """
22 | if num == 0:
23 | return 0
24 | ans = ""
25 | while num != 0:
26 | num, rem = divmod(num, -2)
27 | if rem < 0:
28 | rem += 2
29 | num += 1
30 | ans = str(rem) + ans
31 | return int(ans)
32 |
33 |
34 | if __name__ == "__main__":
35 | import doctest
36 |
37 | doctest.testmod()
38 |
--------------------------------------------------------------------------------
/maths/ceil.py:
--------------------------------------------------------------------------------
1 | """
2 | https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
3 | """
4 |
5 |
6 | def ceil(x: float) -> int:
7 | """
8 | Return the ceiling of x as an Integral.
9 |
10 | :param x: the number
11 | :return: the smallest integer >= x.
12 |
13 | >>> import math
14 | >>> all(ceil(n) == math.ceil(n) for n
15 | ... in (1, -1, 0, -0, 1.1, -1.1, 1.0, -1.0, 1_000_000_000))
16 | True
17 | """
18 | return int(x) if x - int(x) <= 0 else int(x) + 1
19 |
20 |
21 | if __name__ == "__main__":
22 | import doctest
23 |
24 | doctest.testmod()
25 |
--------------------------------------------------------------------------------
/maths/chebyshev_distance.py:
--------------------------------------------------------------------------------
1 | def chebyshev_distance(point_a: list[float], point_b: list[float]) -> float:
2 | """
3 | This function calculates the Chebyshev distance (also known as the
4 | Chessboard distance) between two n-dimensional points represented as lists.
5 |
6 | https://en.wikipedia.org/wiki/Chebyshev_distance
7 |
8 | >>> chebyshev_distance([1.0, 1.0], [2.0, 2.0])
9 | 1.0
10 | >>> chebyshev_distance([1.0, 1.0, 9.0], [2.0, 2.0, -5.2])
11 | 14.2
12 | >>> chebyshev_distance([1.0], [2.0, 2.0])
13 | Traceback (most recent call last):
14 | ...
15 | ValueError: Both points must have the same dimension.
16 | """
17 | if len(point_a) != len(point_b):
18 | raise ValueError("Both points must have the same dimension.")
19 |
20 | return max(abs(a - b) for a, b in zip(point_a, point_b))
21 |
--------------------------------------------------------------------------------
/maths/factors.py:
--------------------------------------------------------------------------------
1 | from doctest import testmod
2 | from math import sqrt
3 |
4 |
5 | def factors_of_a_number(num: int) -> list:
6 | """
7 | >>> factors_of_a_number(1)
8 | [1]
9 | >>> factors_of_a_number(5)
10 | [1, 5]
11 | >>> factors_of_a_number(24)
12 | [1, 2, 3, 4, 6, 8, 12, 24]
13 | >>> factors_of_a_number(-24)
14 | []
15 | """
16 | facs: list[int] = []
17 | if num < 1:
18 | return facs
19 | facs.append(1)
20 | if num == 1:
21 | return facs
22 | facs.append(num)
23 | for i in range(2, int(sqrt(num)) + 1):
24 | if num % i == 0: # If i is a factor of num
25 | facs.append(i)
26 | d = num // i # num//i is the other factor of num
27 | if d != i: # If d and i are distinct
28 | facs.append(d) # we have found another factor
29 | facs.sort()
30 | return facs
31 |
32 |
33 | if __name__ == "__main__":
34 | testmod(name="factors_of_a_number", verbose=True)
35 |
--------------------------------------------------------------------------------
/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: int, n: float, mod: int) -> int:
9 | if n == 0:
10 | return 1
11 |
12 | elif n % 2 == 1:
13 | return (binary_exponentiation(a, n - 1, mod) * a) % mod
14 |
15 | else:
16 | b = binary_exponentiation(a, n / 2, mod)
17 | return (b * b) % mod
18 |
19 |
20 | # a prime number
21 | p = 701
22 |
23 | a = 1000000000
24 | b = 10
25 |
26 | # using binary exponentiation function, O(log(p)):
27 | print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p)
28 |
29 | # using Python operators:
30 | print((a / b) % p == (a * b ** (p - 2)) % p)
31 |
--------------------------------------------------------------------------------
/maths/floor.py:
--------------------------------------------------------------------------------
1 | """
2 | https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
3 | """
4 |
5 |
6 | def floor(x: float) -> int:
7 | """
8 | Return the floor of x as an Integral.
9 | :param x: the number
10 | :return: the largest integer <= x.
11 | >>> import math
12 | >>> all(floor(n) == math.floor(n) for n
13 | ... in (1, -1, 0, -0, 1.1, -1.1, 1.0, -1.0, 1_000_000_000))
14 | True
15 | """
16 | return int(x) if x - int(x) >= 0 else int(x) - 1
17 |
18 |
19 | if __name__ == "__main__":
20 | import doctest
21 |
22 | doctest.testmod()
23 |
--------------------------------------------------------------------------------
/maths/images/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/maths/images/__init__.py
--------------------------------------------------------------------------------
/maths/images/gaussian.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/maths/images/gaussian.png
--------------------------------------------------------------------------------
/maths/is_int_palindrome.py:
--------------------------------------------------------------------------------
1 | def is_int_palindrome(num: int) -> bool:
2 | """
3 | Returns whether `num` is a palindrome or not
4 | (see for reference https://en.wikipedia.org/wiki/Palindromic_number).
5 |
6 | >>> is_int_palindrome(-121)
7 | False
8 | >>> is_int_palindrome(0)
9 | True
10 | >>> is_int_palindrome(10)
11 | False
12 | >>> is_int_palindrome(11)
13 | True
14 | >>> is_int_palindrome(101)
15 | True
16 | >>> is_int_palindrome(120)
17 | False
18 | """
19 | if num < 0:
20 | return False
21 |
22 | num_copy: int = num
23 | rev_num: int = 0
24 | while num > 0:
25 | rev_num = rev_num * 10 + (num % 10)
26 | num //= 10
27 |
28 | return num_copy == rev_num
29 |
30 |
31 | if __name__ == "__main__":
32 | import doctest
33 |
34 | doctest.testmod()
35 |
--------------------------------------------------------------------------------
/maths/is_square_free.py:
--------------------------------------------------------------------------------
1 | """
2 | References: wikipedia:square free number
3 | psf/black : True
4 | ruff : True
5 | """
6 |
7 | from __future__ import annotations
8 |
9 |
10 | def is_square_free(factors: list[int]) -> bool:
11 | """
12 | # doctest: +NORMALIZE_WHITESPACE
13 | This functions takes a list of prime factors as input.
14 | returns True if the factors are square free.
15 | >>> is_square_free([1, 1, 2, 3, 4])
16 | False
17 |
18 | These are wrong but should return some value
19 | it simply checks for repetition in the numbers.
20 | >>> is_square_free([1, 3, 4, 'sd', 0.0])
21 | True
22 |
23 | >>> is_square_free([1, 0.5, 2, 0.0])
24 | True
25 | >>> is_square_free([1, 2, 2, 5])
26 | False
27 | >>> is_square_free('asd')
28 | True
29 | >>> is_square_free(24)
30 | Traceback (most recent call last):
31 | ...
32 | TypeError: 'int' object is not iterable
33 | """
34 | return len(set(factors)) == len(factors)
35 |
36 |
37 | if __name__ == "__main__":
38 | import doctest
39 |
40 | doctest.testmod()
41 |
--------------------------------------------------------------------------------
/maths/karatsuba.py:
--------------------------------------------------------------------------------
1 | """Multiply two numbers using Karatsuba algorithm"""
2 |
3 |
4 | def karatsuba(a: int, b: int) -> int:
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 |
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/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/numerical_analysis/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/maths/numerical_analysis/__init__.py
--------------------------------------------------------------------------------
/maths/numerical_analysis/secant_method.py:
--------------------------------------------------------------------------------
1 | """
2 | Implementing Secant method in Python
3 | Author: dimgrichr
4 | """
5 |
6 | from math import exp
7 |
8 |
9 | def f(x: float) -> float:
10 | """
11 | >>> f(5)
12 | 39.98652410600183
13 | """
14 | return 8 * x - 2 * exp(-x)
15 |
16 |
17 | def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float:
18 | """
19 | >>> secant_method(1, 3, 2)
20 | 0.2139409276214589
21 | """
22 | x0 = lower_bound
23 | x1 = upper_bound
24 | for _ in range(repeats):
25 | x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0))
26 | return x1
27 |
28 |
29 | if __name__ == "__main__":
30 | print(f"Example: {secant_method(1, 3, 2)}")
31 |
--------------------------------------------------------------------------------
/maths/polynomials/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/maths/polynomials/__init__.py
--------------------------------------------------------------------------------
/maths/print_multiplication_table.py:
--------------------------------------------------------------------------------
1 | def multiplication_table(number: int, number_of_terms: int) -> str:
2 | """
3 | Prints the multiplication table of a given number till the given number of terms
4 |
5 | >>> print(multiplication_table(3, 5))
6 | 3 * 1 = 3
7 | 3 * 2 = 6
8 | 3 * 3 = 9
9 | 3 * 4 = 12
10 | 3 * 5 = 15
11 |
12 | >>> print(multiplication_table(-4, 6))
13 | -4 * 1 = -4
14 | -4 * 2 = -8
15 | -4 * 3 = -12
16 | -4 * 4 = -16
17 | -4 * 5 = -20
18 | -4 * 6 = -24
19 | """
20 | return "\n".join(
21 | f"{number} * {i} = {number * i}" for i in range(1, number_of_terms + 1)
22 | )
23 |
24 |
25 | if __name__ == "__main__":
26 | print(multiplication_table(number=5, number_of_terms=10))
27 |
--------------------------------------------------------------------------------
/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 | """
18 | >>> point1 = Point(2, -1, 7)
19 | >>> point2 = Point(1, -3, 5)
20 | >>> print(f"Distance from {point1} to {point2} is {distance(point1, point2)}")
21 | Distance from Point(2, -1, 7) to Point(1, -3, 5) is 3.0
22 | """
23 | return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2))
24 |
25 |
26 | if __name__ == "__main__":
27 | import doctest
28 |
29 | doctest.testmod()
30 |
--------------------------------------------------------------------------------
/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 | solution1, solution2 = quadratic_roots(a=5, b=6, c=1)
34 | print(f"The solutions are: {solution1} and {solution2}")
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 | Converts 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)) <= 1e-8 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/series/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/maths/series/__init__.py
--------------------------------------------------------------------------------
/maths/sigmoid.py:
--------------------------------------------------------------------------------
1 | """
2 | This script demonstrates the implementation of the Sigmoid function.
3 |
4 | The function takes a vector of K real numbers as input and then 1 / (1 + exp(-x)).
5 | After through Sigmoid, the element of the vector mostly 0 between 1. or 1 between -1.
6 |
7 | Script inspired from its corresponding Wikipedia article
8 | https://en.wikipedia.org/wiki/Sigmoid_function
9 | """
10 |
11 | import numpy as np
12 |
13 |
14 | def sigmoid(vector: np.ndarray) -> np.ndarray:
15 | """
16 | Implements the sigmoid function
17 |
18 | Parameters:
19 | vector (np.array): A numpy array of shape (1,n)
20 | consisting of real values
21 |
22 | Returns:
23 | sigmoid_vec (np.array): The input numpy array, after applying
24 | sigmoid.
25 |
26 | Examples:
27 | >>> sigmoid(np.array([-1.0, 1.0, 2.0]))
28 | array([0.26894142, 0.73105858, 0.88079708])
29 |
30 | >>> sigmoid(np.array([0.0]))
31 | array([0.5])
32 | """
33 | return 1 / (1 + np.exp(-vector))
34 |
35 |
36 | if __name__ == "__main__":
37 | import doctest
38 |
39 | doctest.testmod()
40 |
--------------------------------------------------------------------------------
/maths/sock_merchant.py:
--------------------------------------------------------------------------------
1 | from collections import Counter
2 |
3 |
4 | def sock_merchant(colors: list[int]) -> int:
5 | """
6 | >>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20])
7 | 3
8 | >>> sock_merchant([1, 1, 3, 3])
9 | 2
10 | """
11 | return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values())
12 |
13 |
14 | if __name__ == "__main__":
15 | import doctest
16 |
17 | doctest.testmod()
18 |
19 | colors = [int(x) for x in input("Enter socks by color :").rstrip().split()]
20 | print(f"sock_merchant({colors}) = {sock_merchant(colors)}")
21 |
--------------------------------------------------------------------------------
/maths/special_numbers/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/maths/special_numbers/__init__.py
--------------------------------------------------------------------------------
/maths/special_numbers/polygonal_numbers.py:
--------------------------------------------------------------------------------
1 | def polygonal_num(num: int, sides: int) -> int:
2 | """
3 | Returns the `num`th `sides`-gonal number. It is assumed that `num` >= 0 and
4 | `sides` >= 3 (see for reference https://en.wikipedia.org/wiki/Polygonal_number).
5 |
6 | >>> polygonal_num(0, 3)
7 | 0
8 | >>> polygonal_num(3, 3)
9 | 6
10 | >>> polygonal_num(5, 4)
11 | 25
12 | >>> polygonal_num(2, 5)
13 | 5
14 | >>> polygonal_num(-1, 0)
15 | Traceback (most recent call last):
16 | ...
17 | ValueError: Invalid input: num must be >= 0 and sides must be >= 3.
18 | >>> polygonal_num(0, 2)
19 | Traceback (most recent call last):
20 | ...
21 | ValueError: Invalid input: num must be >= 0 and sides must be >= 3.
22 | """
23 | if num < 0 or sides < 3:
24 | raise ValueError("Invalid input: num must be >= 0 and sides must be >= 3.")
25 |
26 | return ((sides - 2) * num**2 - (sides - 4) * num) // 2
27 |
28 |
29 | if __name__ == "__main__":
30 | import doctest
31 |
32 | doctest.testmod()
33 |
--------------------------------------------------------------------------------
/maths/sum_of_arithmetic_series.py:
--------------------------------------------------------------------------------
1 | # DarkCoder
2 | def sum_of_series(first_term: int, common_diff: int, num_of_terms: int) -> float:
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 | total = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff)
12 | # formula for sum of series
13 | return total
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/sum_of_harmonic_series.py:
--------------------------------------------------------------------------------
1 | def sum_of_harmonic_progression(
2 | first_term: float, common_difference: float, number_of_terms: int
3 | ) -> float:
4 | """
5 | https://en.wikipedia.org/wiki/Harmonic_progression_(mathematics)
6 |
7 | Find the sum of n terms in an harmonic progression. The calculation starts with the
8 | first_term and loops adding the common difference of Arithmetic Progression by which
9 | the given Harmonic Progression is linked.
10 |
11 | >>> sum_of_harmonic_progression(1 / 2, 2, 2)
12 | 0.75
13 | >>> sum_of_harmonic_progression(1 / 5, 5, 5)
14 | 0.45666666666666667
15 | """
16 | arithmetic_progression = [1 / first_term]
17 | first_term = 1 / first_term
18 | for _ in range(number_of_terms - 1):
19 | first_term += common_difference
20 | arithmetic_progression.append(first_term)
21 | harmonic_series = [1 / step for step in arithmetic_progression]
22 | return sum(harmonic_series)
23 |
24 |
25 | if __name__ == "__main__":
26 | import doctest
27 |
28 | doctest.testmod()
29 | print(sum_of_harmonic_progression(1 / 2, 2, 2))
30 |
--------------------------------------------------------------------------------
/maths/sumset.py:
--------------------------------------------------------------------------------
1 | """
2 |
3 | Calculates the SumSet of two sets of numbers (A and B)
4 |
5 | Source:
6 | https://en.wikipedia.org/wiki/Sumset
7 |
8 | """
9 |
10 |
11 | def sumset(set_a: set, set_b: set) -> set:
12 | """
13 | :param first set: a set of numbers
14 | :param second set: a set of numbers
15 | :return: the nth number in Sylvester's sequence
16 |
17 | >>> sumset({1, 2, 3}, {4, 5, 6})
18 | {5, 6, 7, 8, 9}
19 |
20 | >>> sumset({1, 2, 3}, {4, 5, 6, 7})
21 | {5, 6, 7, 8, 9, 10}
22 |
23 | >>> sumset({1, 2, 3, 4}, 3)
24 | Traceback (most recent call last):
25 | ...
26 | AssertionError: The input value of [set_b=3] is not a set
27 | """
28 | assert isinstance(set_a, set), f"The input value of [set_a={set_a}] is not a set"
29 | assert isinstance(set_b, set), f"The input value of [set_b={set_b}] is not a set"
30 |
31 | return {a + b for a in set_a for b in set_b}
32 |
33 |
34 | if __name__ == "__main__":
35 | from doctest import testmod
36 |
37 | testmod()
38 |
--------------------------------------------------------------------------------
/maths/test_prime_check.py:
--------------------------------------------------------------------------------
1 | """
2 | Minimalist file that allows pytest to find and run the Test unittest. For details, see:
3 | https://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/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/matrix/__init__.py
--------------------------------------------------------------------------------
/matrix/median_matrix.py:
--------------------------------------------------------------------------------
1 | """
2 | https://en.wikipedia.org/wiki/Median
3 | """
4 |
5 |
6 | def median(matrix: list[list[int]]) -> int:
7 | """
8 | Calculate the median of a sorted matrix.
9 |
10 | Args:
11 | matrix: A 2D matrix of integers.
12 |
13 | Returns:
14 | The median value of the matrix.
15 |
16 | Examples:
17 | >>> matrix = [[1, 3, 5], [2, 6, 9], [3, 6, 9]]
18 | >>> median(matrix)
19 | 5
20 |
21 | >>> matrix = [[1, 2, 3], [4, 5, 6]]
22 | >>> median(matrix)
23 | 3
24 | """
25 | # Flatten the matrix into a sorted 1D list
26 | linear = sorted(num for row in matrix for num in row)
27 |
28 | # Calculate the middle index
29 | mid = (len(linear) - 1) // 2
30 |
31 | # Return the median
32 | return linear[mid]
33 |
34 |
35 | if __name__ == "__main__":
36 | import doctest
37 |
38 | doctest.testmod()
39 |
--------------------------------------------------------------------------------
/matrix/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/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/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/networking_flow/__init__.py
--------------------------------------------------------------------------------
/neural_network/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/neural_network/__init__.py
--------------------------------------------------------------------------------
/neural_network/activation_functions/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/neural_network/activation_functions/__init__.py
--------------------------------------------------------------------------------
/neural_network/activation_functions/binary_step.py:
--------------------------------------------------------------------------------
1 | """
2 | This script demonstrates the implementation of the Binary Step function.
3 |
4 | It's an activation function in which the neuron is activated if the input is positive
5 | or 0, else it is deactivated
6 |
7 | It's a simple activation function which is mentioned in this wikipedia article:
8 | https://en.wikipedia.org/wiki/Activation_function
9 | """
10 |
11 | import numpy as np
12 |
13 |
14 | def binary_step(vector: np.ndarray) -> np.ndarray:
15 | """
16 | Implements the binary step function
17 |
18 | Parameters:
19 | vector (ndarray): A vector that consists of numeric values
20 |
21 | Returns:
22 | vector (ndarray): Input vector after applying binary step function
23 |
24 | >>> vector = np.array([-1.2, 0, 2, 1.45, -3.7, 0.3])
25 | >>> binary_step(vector)
26 | array([0, 1, 1, 1, 0, 1])
27 | """
28 |
29 | return np.where(vector >= 0, 1, 0)
30 |
31 |
32 | if __name__ == "__main__":
33 | import doctest
34 |
35 | doctest.testmod()
36 |
--------------------------------------------------------------------------------
/neural_network/activation_functions/softplus.py:
--------------------------------------------------------------------------------
1 | """
2 | Softplus Activation Function
3 |
4 | Use Case: The Softplus function is a smooth approximation of the ReLU function.
5 | For more detailed information, you can refer to the following link:
6 | https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Softplus
7 | """
8 |
9 | import numpy as np
10 |
11 |
12 | def softplus(vector: np.ndarray) -> np.ndarray:
13 | """
14 | Implements the Softplus activation function.
15 |
16 | Parameters:
17 | vector (np.ndarray): The input array for the Softplus activation.
18 |
19 | Returns:
20 | np.ndarray: The input array after applying the Softplus activation.
21 |
22 | Formula: f(x) = ln(1 + e^x)
23 |
24 | Examples:
25 | >>> softplus(np.array([2.3, 0.6, -2, -3.8]))
26 | array([2.39554546, 1.03748795, 0.12692801, 0.02212422])
27 |
28 | >>> softplus(np.array([-9.2, -0.3, 0.45, -4.56]))
29 | array([1.01034298e-04, 5.54355244e-01, 9.43248946e-01, 1.04077103e-02])
30 | """
31 | return np.log(1 + np.exp(vector))
32 |
33 |
34 | if __name__ == "__main__":
35 | import doctest
36 |
37 | doctest.testmod()
38 |
--------------------------------------------------------------------------------
/other/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/other/__init__.py
--------------------------------------------------------------------------------
/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 |
9 | import random
10 | from typing import Any
11 |
12 |
13 | def fisher_yates_shuffle(data: list) -> list[Any]:
14 | for _ in range(len(data)):
15 | a = random.randint(0, len(data) - 1)
16 | b = random.randint(0, len(data) - 1)
17 | data[a], data[b] = data[b], data[a]
18 | return data
19 |
20 |
21 | if __name__ == "__main__":
22 | integers = [0, 1, 2, 3, 4, 5, 6, 7]
23 | strings = ["python", "says", "hello", "!"]
24 | print("Fisher-Yates Shuffle:")
25 | print("List", integers, strings)
26 | print("FY Shuffle", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
27 |
--------------------------------------------------------------------------------
/other/quine.py:
--------------------------------------------------------------------------------
1 | #!/bin/python3
2 | # ruff: noqa: PLC3002
3 | """
4 | Quine:
5 |
6 | A quine is a computer program which takes no input and produces a copy of its
7 | own source code as its only output (disregarding this docstring and the shebang).
8 |
9 | More info on: https://en.wikipedia.org/wiki/Quine_(computing)
10 | """
11 |
12 | print((lambda quine: quine % quine)("print((lambda quine: quine %% quine)(%r))"))
13 |
--------------------------------------------------------------------------------
/other/tower_of_hanoi.py:
--------------------------------------------------------------------------------
1 | def move_tower(height, from_pole, to_pole, with_pole):
2 | """
3 | >>> move_tower(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 | move_tower(height - 1, from_pole, with_pole, to_pole)
14 | move_disk(from_pole, to_pole)
15 | move_tower(height - 1, with_pole, to_pole, from_pole)
16 |
17 |
18 | def move_disk(fp, tp):
19 | print("moving disk from", fp, "to", tp)
20 |
21 |
22 | def main():
23 | height = int(input("Height of hanoi: ").strip())
24 | move_tower(height, "A", "B", "C")
25 |
26 |
27 | if __name__ == "__main__":
28 | main()
29 |
--------------------------------------------------------------------------------
/physics/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/physics/__init__.py
--------------------------------------------------------------------------------
/physics/image_data/2D_problems.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/physics/image_data/2D_problems.jpg
--------------------------------------------------------------------------------
/physics/image_data/2D_problems_1.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/physics/image_data/2D_problems_1.jpg
--------------------------------------------------------------------------------
/physics/image_data/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/physics/image_data/__init__.py
--------------------------------------------------------------------------------
/project_euler/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_001/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_001/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_001/sol1.py:
--------------------------------------------------------------------------------
1 | """
2 | Project Euler Problem 1: https://projecteuler.net/problem=1
3 |
4 | Multiples of 3 and 5
5 |
6 | If we list all the natural numbers below 10 that are multiples of 3 or 5,
7 | we get 3, 5, 6 and 9. The sum of these multiples is 23.
8 |
9 | Find the sum of all the multiples of 3 or 5 below 1000.
10 | """
11 |
12 |
13 | def solution(n: int = 1000) -> int:
14 | """
15 | Returns the sum of all the multiples of 3 or 5 below n.
16 |
17 | >>> solution(3)
18 | 0
19 | >>> solution(4)
20 | 3
21 | >>> solution(10)
22 | 23
23 | >>> solution(600)
24 | 83700
25 | >>> solution(-7)
26 | 0
27 | """
28 |
29 | return sum(e for e in range(3, n) if e % 3 == 0 or e % 5 == 0)
30 |
31 |
32 | if __name__ == "__main__":
33 | print(f"{solution() = }")
34 |
--------------------------------------------------------------------------------
/project_euler/problem_001/sol2.py:
--------------------------------------------------------------------------------
1 | """
2 | Project Euler Problem 1: https://projecteuler.net/problem=1
3 |
4 | Multiples of 3 and 5
5 |
6 | If we list all the natural numbers below 10 that are multiples of 3 or 5,
7 | we get 3, 5, 6 and 9. The sum of these multiples is 23.
8 |
9 | Find the sum of all the multiples of 3 or 5 below 1000.
10 | """
11 |
12 |
13 | def solution(n: int = 1000) -> int:
14 | """
15 | Returns the sum of all the multiples of 3 or 5 below n.
16 |
17 | >>> solution(3)
18 | 0
19 | >>> solution(4)
20 | 3
21 | >>> solution(10)
22 | 23
23 | >>> solution(600)
24 | 83700
25 | """
26 |
27 | total = 0
28 | terms = (n - 1) // 3
29 | total += ((terms) * (6 + (terms - 1) * 3)) // 2 # total of an A.P.
30 | terms = (n - 1) // 5
31 | total += ((terms) * (10 + (terms - 1) * 5)) // 2
32 | terms = (n - 1) // 15
33 | total -= ((terms) * (30 + (terms - 1) * 15)) // 2
34 | return total
35 |
36 |
37 | if __name__ == "__main__":
38 | print(f"{solution() = }")
39 |
--------------------------------------------------------------------------------
/project_euler/problem_001/sol5.py:
--------------------------------------------------------------------------------
1 | """
2 | Project Euler Problem 1: https://projecteuler.net/problem=1
3 |
4 | Multiples of 3 and 5
5 |
6 | If we list all the natural numbers below 10 that are multiples of 3 or 5,
7 | we get 3, 5, 6 and 9. The sum of these multiples is 23.
8 |
9 | Find the sum of all the multiples of 3 or 5 below 1000.
10 | """
11 |
12 |
13 | def solution(n: int = 1000) -> int:
14 | """
15 | Returns the sum of all the multiples of 3 or 5 below n.
16 | A straightforward pythonic solution using list comprehension.
17 |
18 | >>> solution(3)
19 | 0
20 | >>> solution(4)
21 | 3
22 | >>> solution(10)
23 | 23
24 | >>> solution(600)
25 | 83700
26 | """
27 |
28 | return sum(i for i in range(n) if i % 3 == 0 or i % 5 == 0)
29 |
30 |
31 | if __name__ == "__main__":
32 | print(f"{solution() = }")
33 |
--------------------------------------------------------------------------------
/project_euler/problem_001/sol6.py:
--------------------------------------------------------------------------------
1 | """
2 | Project Euler Problem 1: https://projecteuler.net/problem=1
3 |
4 | Multiples of 3 and 5
5 |
6 | If we list all the natural numbers below 10 that are multiples of 3 or 5,
7 | we get 3, 5, 6 and 9. The sum of these multiples is 23.
8 |
9 | Find the sum of all the multiples of 3 or 5 below 1000.
10 | """
11 |
12 |
13 | def solution(n: int = 1000) -> int:
14 | """
15 | Returns the sum of all the multiples of 3 or 5 below n.
16 |
17 | >>> solution(3)
18 | 0
19 | >>> solution(4)
20 | 3
21 | >>> solution(10)
22 | 23
23 | >>> solution(600)
24 | 83700
25 | """
26 |
27 | a = 3
28 | result = 0
29 | while a < n:
30 | if a % 3 == 0 or a % 5 == 0:
31 | result += a
32 | elif a % 15 == 0:
33 | result -= a
34 | a += 1
35 | return result
36 |
37 |
38 | if __name__ == "__main__":
39 | print(f"{solution() = }")
40 |
--------------------------------------------------------------------------------
/project_euler/problem_001/sol7.py:
--------------------------------------------------------------------------------
1 | """
2 | Project Euler Problem 1: https://projecteuler.net/problem=1
3 |
4 | Multiples of 3 and 5
5 |
6 | If we list all the natural numbers below 10 that are multiples of 3 or 5,
7 | we get 3, 5, 6 and 9. The sum of these multiples is 23.
8 |
9 | Find the sum of all the multiples of 3 or 5 below 1000.
10 | """
11 |
12 |
13 | def solution(n: int = 1000) -> int:
14 | """
15 | Returns the sum of all the multiples of 3 or 5 below n.
16 |
17 | >>> solution(3)
18 | 0
19 | >>> solution(4)
20 | 3
21 | >>> solution(10)
22 | 23
23 | >>> solution(600)
24 | 83700
25 | """
26 |
27 | result = 0
28 | for i in range(n):
29 | if i % 3 == 0 or i % 5 == 0:
30 | result += i
31 | return result
32 |
33 |
34 | if __name__ == "__main__":
35 | print(f"{solution() = }")
36 |
--------------------------------------------------------------------------------
/project_euler/problem_002/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_002/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_003/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_003/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_004/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_004/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_005/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_005/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_006/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_006/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_007/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_007/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_008/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_008/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_009/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_009/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_009/sol3.py:
--------------------------------------------------------------------------------
1 | """
2 | Project Euler Problem 9: https://projecteuler.net/problem=9
3 |
4 | Special Pythagorean triplet
5 |
6 | A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
7 |
8 | a^2 + b^2 = c^2
9 |
10 | For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
11 |
12 | There exists exactly one Pythagorean triplet for which a + b + c = 1000.
13 | Find the product a*b*c.
14 |
15 | References:
16 | - https://en.wikipedia.org/wiki/Pythagorean_triple
17 | """
18 |
19 |
20 | def solution() -> int:
21 | """
22 | Returns the product of a,b,c which are Pythagorean Triplet that satisfies
23 | the following:
24 | 1. a**2 + b**2 = c**2
25 | 2. a + b + c = 1000
26 |
27 | >>> solution()
28 | 31875000
29 | """
30 |
31 | return next(
32 | iter(
33 | [
34 | a * b * (1000 - a - b)
35 | for a in range(1, 999)
36 | for b in range(a, 999)
37 | if (a * a + b * b == (1000 - a - b) ** 2)
38 | ]
39 | )
40 | )
41 |
42 |
43 | if __name__ == "__main__":
44 | print(f"{solution() = }")
45 |
--------------------------------------------------------------------------------
/project_euler/problem_010/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_010/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_011/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_011/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_012/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_012/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_013/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_013/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_013/sol1.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem 13: https://projecteuler.net/problem=13
3 |
4 | Problem Statement:
5 | Work out the first ten digits of the sum of the following one-hundred 50-digit
6 | numbers.
7 | """
8 |
9 | import os
10 |
11 |
12 | def solution():
13 | """
14 | Returns the first ten digits of the sum of the array elements
15 | from the file num.txt
16 |
17 | >>> solution()
18 | '5537376230'
19 | """
20 | file_path = os.path.join(os.path.dirname(__file__), "num.txt")
21 | with open(file_path) as file_hand:
22 | return str(sum(int(line) for line in file_hand))[:10]
23 |
24 |
25 | if __name__ == "__main__":
26 | print(solution())
27 |
--------------------------------------------------------------------------------
/project_euler/problem_014/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_014/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_015/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_015/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_016/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_016/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_016/sol1.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem 16: https://projecteuler.net/problem=16
3 |
4 | 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
5 |
6 | What is the sum of the digits of the number 2^1000?
7 | """
8 |
9 |
10 | def solution(power: int = 1000) -> int:
11 | """Returns the sum of the digits of the number 2^power.
12 | >>> solution(1000)
13 | 1366
14 | >>> solution(50)
15 | 76
16 | >>> solution(20)
17 | 31
18 | >>> solution(15)
19 | 26
20 | """
21 | num = 2**power
22 | string_num = str(num)
23 | list_num = list(string_num)
24 | sum_of_num = 0
25 |
26 | for i in list_num:
27 | sum_of_num += int(i)
28 |
29 | return sum_of_num
30 |
31 |
32 | if __name__ == "__main__":
33 | power = int(input("Enter the power of 2: ").strip())
34 | print("2 ^ ", power, " = ", 2**power)
35 | result = solution(power)
36 | print("Sum of the digits is: ", result)
37 |
--------------------------------------------------------------------------------
/project_euler/problem_016/sol2.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem 16: https://projecteuler.net/problem=16
3 |
4 | 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
5 |
6 | What is the sum of the digits of the number 2^1000?
7 | """
8 |
9 |
10 | def solution(power: int = 1000) -> int:
11 | """Returns the sum of the digits of the number 2^power.
12 |
13 | >>> solution(1000)
14 | 1366
15 | >>> solution(50)
16 | 76
17 | >>> solution(20)
18 | 31
19 | >>> solution(15)
20 | 26
21 | """
22 | n = 2**power
23 | r = 0
24 | while n:
25 | r, n = r + n % 10, n // 10
26 | return r
27 |
28 |
29 | if __name__ == "__main__":
30 | print(solution(int(str(input()).strip())))
31 |
--------------------------------------------------------------------------------
/project_euler/problem_017/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_017/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_018/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_018/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_018/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_019/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_019/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_020/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_020/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_020/sol2.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem 20: https://projecteuler.net/problem=20
3 |
4 | n! means n x (n - 1) x ... x 3 x 2 x 1
5 |
6 | For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800,
7 | and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
8 |
9 | Find the sum of the digits in the number 100!
10 | """
11 |
12 | from math import factorial
13 |
14 |
15 | def solution(num: int = 100) -> int:
16 | """Returns the sum of the digits in the factorial of num
17 | >>> solution(100)
18 | 648
19 | >>> solution(50)
20 | 216
21 | >>> solution(10)
22 | 27
23 | >>> solution(5)
24 | 3
25 | >>> solution(3)
26 | 6
27 | >>> solution(2)
28 | 2
29 | >>> solution(1)
30 | 1
31 | """
32 | return sum(int(x) for x in str(factorial(num)))
33 |
34 |
35 | if __name__ == "__main__":
36 | print(solution(int(input("Enter the Number: ").strip())))
37 |
--------------------------------------------------------------------------------
/project_euler/problem_020/sol3.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem 20: https://projecteuler.net/problem=20
3 |
4 | n! means n x (n - 1) x ... x 3 x 2 x 1
5 |
6 | For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800,
7 | and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
8 |
9 | Find the sum of the digits in the number 100!
10 | """
11 |
12 | from math import factorial
13 |
14 |
15 | def solution(num: int = 100) -> int:
16 | """Returns the sum of the digits in the factorial of num
17 | >>> solution(1000)
18 | 10539
19 | >>> solution(200)
20 | 1404
21 | >>> solution(100)
22 | 648
23 | >>> solution(50)
24 | 216
25 | >>> solution(10)
26 | 27
27 | >>> solution(5)
28 | 3
29 | >>> solution(3)
30 | 6
31 | >>> solution(2)
32 | 2
33 | >>> solution(1)
34 | 1
35 | >>> solution(0)
36 | 1
37 | """
38 | return sum(map(int, str(factorial(num))))
39 |
40 |
41 | if __name__ == "__main__":
42 | print(solution(int(input("Enter the Number: ").strip())))
43 |
--------------------------------------------------------------------------------
/project_euler/problem_020/sol4.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem 20: https://projecteuler.net/problem=20
3 |
4 | n! means n x (n - 1) x ... x 3 x 2 x 1
5 |
6 | For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800,
7 | and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
8 |
9 | Find the sum of the digits in the number 100!
10 | """
11 |
12 |
13 | def solution(num: int = 100) -> int:
14 | """Returns the sum of the digits in the factorial of num
15 | >>> solution(100)
16 | 648
17 | >>> solution(50)
18 | 216
19 | >>> solution(10)
20 | 27
21 | >>> solution(5)
22 | 3
23 | >>> solution(3)
24 | 6
25 | >>> solution(2)
26 | 2
27 | >>> solution(1)
28 | 1
29 | """
30 | fact = 1
31 | result = 0
32 | for i in range(1, num + 1):
33 | fact *= i
34 |
35 | for j in str(fact):
36 | result += int(j)
37 |
38 | return result
39 |
40 |
41 | if __name__ == "__main__":
42 | print(solution(int(input("Enter the Number: ").strip())))
43 |
--------------------------------------------------------------------------------
/project_euler/problem_021/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_021/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_022/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_022/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_023/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_023/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_024/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_024/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_024/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 |
13 | from itertools import permutations
14 |
15 |
16 | def solution():
17 | """Returns the millionth lexicographic permutation of the digits 0, 1, 2,
18 | 3, 4, 5, 6, 7, 8 and 9.
19 |
20 | >>> solution()
21 | '2783915460'
22 | """
23 | result = list(map("".join, permutations("0123456789")))
24 | return result[999999]
25 |
26 |
27 | if __name__ == "__main__":
28 | print(solution())
29 |
--------------------------------------------------------------------------------
/project_euler/problem_025/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_025/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_026/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_026/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_027/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_027/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_028/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_028/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_029/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_029/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_030/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_030/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_031/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_031/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_032/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_032/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_033/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_033/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_034/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_034/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_035/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_035/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_036/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_036/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_037/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_037/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_038/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_038/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_039/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_039/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_040/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_040/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_040/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 x d10 x d100 x d1000 x d10000 x d100000 x 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_041/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_041/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_042/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_042/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_043/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_043/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_044/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_044/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_045/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_045/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_046/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_046/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_047/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_047/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_048/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_048/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_048/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_049/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_049/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_050/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_050/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_051/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_051/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_052/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_052/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_052/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(str(i))
25 | == sorted(str(2 * i))
26 | == sorted(str(3 * i))
27 | == sorted(str(4 * i))
28 | == sorted(str(5 * i))
29 | == sorted(str(6 * i))
30 | ):
31 | return i
32 |
33 | i += 1
34 |
35 |
36 | if __name__ == "__main__":
37 | print(solution())
38 |
--------------------------------------------------------------------------------
/project_euler/problem_053/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_053/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_053/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! = nx(n-1)x...x3x2x1, 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 |
20 | from math import factorial
21 |
22 |
23 | def combinations(n, r):
24 | return factorial(n) / (factorial(r) * factorial(n - r))
25 |
26 |
27 | def solution():
28 | """Returns the number of values of nCr, for 1 ≤ n ≤ 100, are greater than
29 | one-million
30 |
31 | >>> solution()
32 | 4075
33 | """
34 | total = 0
35 |
36 | for i in range(1, 101):
37 | for j in range(1, i + 1):
38 | if combinations(i, j) > 1e6:
39 | total += 1
40 | return total
41 |
42 |
43 | if __name__ == "__main__":
44 | print(solution())
45 |
--------------------------------------------------------------------------------
/project_euler/problem_054/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_054/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_055/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_055/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_056/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_056/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_057/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_057/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_058/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_058/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_059/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_059/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_059/test_cipher.txt:
--------------------------------------------------------------------------------
1 | 63,13,28,75,0,23,14,8,0,76,22,89,12,4,13,14,69,16,24,69,29,4,18,23,69,69,59,14,69,11,14,4,29,18
2 |
--------------------------------------------------------------------------------
/project_euler/problem_062/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_062/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_063/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_063/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_063/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 solution(max_base: int = 10, max_power: int = 22) -> int:
15 | """
16 | Returns the count of all n-digit numbers which are nth power
17 | >>> solution(10, 22)
18 | 49
19 | >>> solution(0, 0)
20 | 0
21 | >>> solution(1, 1)
22 | 0
23 | >>> solution(-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"{solution(10, 22) = }")
35 |
--------------------------------------------------------------------------------
/project_euler/problem_064/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_064/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_065/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_065/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_067/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_067/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_068/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_068/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_069/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_069/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_070/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_070/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_071/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_071/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_072/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_072/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_073/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_073/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_074/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_074/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_075/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_075/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_076/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_076/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_077/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_077/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_078/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_078/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_079/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_079/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_079/keylog.txt:
--------------------------------------------------------------------------------
1 | 319
2 | 680
3 | 180
4 | 690
5 | 129
6 | 620
7 | 762
8 | 689
9 | 762
10 | 318
11 | 368
12 | 710
13 | 720
14 | 710
15 | 629
16 | 168
17 | 160
18 | 689
19 | 716
20 | 731
21 | 736
22 | 729
23 | 316
24 | 729
25 | 729
26 | 710
27 | 769
28 | 290
29 | 719
30 | 680
31 | 318
32 | 389
33 | 162
34 | 289
35 | 162
36 | 718
37 | 729
38 | 319
39 | 790
40 | 680
41 | 890
42 | 362
43 | 319
44 | 760
45 | 316
46 | 729
47 | 380
48 | 319
49 | 728
50 | 716
51 |
--------------------------------------------------------------------------------
/project_euler/problem_079/keylog_test.txt:
--------------------------------------------------------------------------------
1 | 319
2 | 680
3 | 180
4 | 690
5 | 129
6 | 620
7 | 698
8 | 318
9 | 328
10 | 310
11 | 320
12 | 610
13 | 629
14 | 198
15 | 190
16 | 631
17 |
--------------------------------------------------------------------------------
/project_euler/problem_080/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_080/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_081/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_081/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_082/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_082/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_082/test_matrix.txt:
--------------------------------------------------------------------------------
1 | 131,673,234,103,18
2 | 201,96,342,965,150
3 | 630,803,746,422,111
4 | 537,699,497,121,956
5 | 805,732,524,37,331
6 |
--------------------------------------------------------------------------------
/project_euler/problem_085/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_085/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_086/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_086/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_087/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_087/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_089/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_089/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_089/numeralcleanup_test.txt:
--------------------------------------------------------------------------------
1 | IIII
2 | IV
3 | IIIIIIIIII
4 | X
5 | VIIIII
6 |
--------------------------------------------------------------------------------
/project_euler/problem_091/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_091/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_092/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_092/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_094/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_094/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_095/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_095/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_097/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_097/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_099/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_099/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_100/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_100/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_101/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_101/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_102/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_102/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_102/test_triangles.txt:
--------------------------------------------------------------------------------
1 | -340,495,-153,-910,835,-947
2 | -175,41,-421,-714,574,-645
3 |
--------------------------------------------------------------------------------
/project_euler/problem_104/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_104/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_107/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_107/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_107/test_network.txt:
--------------------------------------------------------------------------------
1 | -,16,12,21,-,-,-
2 | 16,-,-,17,20,-,-
3 | 12,-,-,28,-,31,-
4 | 21,17,28,-,18,19,23
5 | -,20,-,18,-,-,11
6 | -,-,31,19,-,-,27
7 | -,-,-,23,11,27,-
8 |
--------------------------------------------------------------------------------
/project_euler/problem_109/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_109/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_112/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_112/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_113/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_113/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_114/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_114/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_115/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_115/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_116/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_116/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_117/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_117/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_119/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_119/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_120/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_120/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_120/sol1.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem 120 Square remainders: https://projecteuler.net/problem=120
3 |
4 | Description:
5 |
6 | Let r be the remainder when (a-1)^n + (a+1)^n is divided by a^2.
7 | For example, if a = 7 and n = 3, then r = 42: 6^3 + 8^3 = 728 ≡ 42 mod 49.
8 | And as n varies, so too will r, but for a = 7 it turns out that r_max = 42.
9 | For 3 ≤ a ≤ 1000, find ∑ r_max.
10 |
11 | Solution:
12 |
13 | On expanding the terms, we get 2 if n is even and 2an if n is odd.
14 | For maximizing the value, 2an < a*a => n <= (a - 1)/2 (integer division)
15 | """
16 |
17 |
18 | def solution(n: int = 1000) -> int:
19 | """
20 | Returns ∑ r_max for 3 <= a <= n as explained above
21 | >>> solution(10)
22 | 300
23 | >>> solution(100)
24 | 330750
25 | >>> solution(1000)
26 | 333082500
27 | """
28 | return sum(2 * a * ((a - 1) // 2) for a in range(3, n + 1))
29 |
30 |
31 | if __name__ == "__main__":
32 | print(solution())
33 |
--------------------------------------------------------------------------------
/project_euler/problem_121/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_121/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_122/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_122/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_123/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_123/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_125/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_125/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_129/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_129/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_131/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_131/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_135/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_135/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_136/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_136/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_144/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_144/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_145/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_145/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_164/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_164/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_173/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_173/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_174/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_174/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_180/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_180/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_187/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_187/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_188/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_188/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_190/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_190/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_191/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_191/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_203/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_203/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_205/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_205/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_206/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_206/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_207/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_207/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_234/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_234/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_301/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_301/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_345/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_345/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_493/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_493/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_551/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_551/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_587/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_587/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_686/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_686/__init__.py
--------------------------------------------------------------------------------
/project_euler/problem_800/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/project_euler/problem_800/__init__.py
--------------------------------------------------------------------------------
/quantum/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/quantum/__init__.py
--------------------------------------------------------------------------------
/quantum/quantum_random.py.DISABLED.txt:
--------------------------------------------------------------------------------
1 | import doctest
2 |
3 | import projectq
4 | from projectq.ops import H, Measure
5 |
6 |
7 | def get_random_number(quantum_engine: projectq.cengines._main.MainEngine) -> int:
8 | """
9 | >>> isinstance(get_random_number(projectq.MainEngine()), int)
10 | True
11 | """
12 | qubit = quantum_engine.allocate_qubit()
13 | H | qubit
14 | Measure | qubit
15 | return int(qubit)
16 |
17 |
18 | if __name__ == "__main__":
19 | doctest.testmod()
20 |
21 | # initialises a new quantum backend
22 | quantum_engine = projectq.MainEngine()
23 |
24 | # Generate a list of 10 random numbers
25 | random_numbers_list = [get_random_number(quantum_engine) for _ in range(10)]
26 |
27 | # Flushes the quantum engine from memory
28 | quantum_engine.flush()
29 |
30 | print("Random numbers", random_numbers_list)
31 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | beautifulsoup4
2 | fake-useragent
3 | httpx
4 | imageio
5 | keras
6 | lxml
7 | matplotlib
8 | numpy
9 | opencv-python
10 | pandas
11 | pillow
12 | rich
13 | scikit-learn
14 | sphinx-pyproject
15 | statsmodels
16 | sympy
17 | tweepy
18 | typing_extensions
19 | xgboost
20 |
--------------------------------------------------------------------------------
/scheduling/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/scheduling/__init__.py
--------------------------------------------------------------------------------
/scripts/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/scripts/__init__.py
--------------------------------------------------------------------------------
/scripts/close_pull_requests_with_awaiting_changes.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # List all open pull requests
4 | prs=$(gh pr list --state open --json number,title,labels --limit 500)
5 |
6 | # Loop through each pull request
7 | echo "$prs" | jq -c '.[]' | while read -r pr; do
8 | pr_number=$(echo "$pr" | jq -r '.number')
9 | pr_title=$(echo "$pr" | jq -r '.title')
10 | pr_labels=$(echo "$pr" | jq -r '.labels')
11 |
12 | # Check if the "awaiting changes" label is present
13 | awaiting_changes=$(echo "$pr_labels" | jq -r '.[] | select(.name == "awaiting changes")')
14 | echo "Checking PR #$pr_number $pr_title ($awaiting_changes) ($pr_labels)"
15 |
16 | # If awaiting_changes, close the pull request
17 | if [[ -n "$awaiting_changes" ]]; then
18 | echo "Closing PR #$pr_number $pr_title due to awaiting_changes label"
19 | gh pr close "$pr_number" --comment "Closing awaiting_changes PRs to prepare for Hacktoberfest"
20 | sleep 2
21 | fi
22 | done
23 |
--------------------------------------------------------------------------------
/scripts/close_pull_requests_with_failing_tests.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # List all open pull requests
4 | prs=$(gh pr list --state open --json number,title,labels --limit 500)
5 |
6 | # Loop through each pull request
7 | echo "$prs" | jq -c '.[]' | while read -r pr; do
8 | pr_number=$(echo "$pr" | jq -r '.number')
9 | pr_title=$(echo "$pr" | jq -r '.title')
10 | pr_labels=$(echo "$pr" | jq -r '.labels')
11 |
12 | # Check if the "tests are failing" label is present
13 | tests_are_failing=$(echo "$pr_labels" | jq -r '.[] | select(.name == "tests are failing")')
14 | echo "Checking PR #$pr_number $pr_title ($tests_are_failing) ($pr_labels)"
15 |
16 | # If there are failing tests, close the pull request
17 | if [[ -n "$tests_are_failing" ]]; then
18 | echo "Closing PR #$pr_number $pr_title due to tests_are_failing label"
19 | gh pr close "$pr_number" --comment "Closing tests_are_failing PRs to prepare for Hacktoberfest"
20 | sleep 2
21 | fi
22 | done
23 |
--------------------------------------------------------------------------------
/scripts/close_pull_requests_with_require_descriptive_names.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # List all open pull requests
4 | prs=$(gh pr list --state open --json number,title,labels --limit 500)
5 |
6 | # Loop through each pull request
7 | echo "$prs" | jq -c '.[]' | while read -r pr; do
8 | pr_number=$(echo "$pr" | jq -r '.number')
9 | pr_title=$(echo "$pr" | jq -r '.title')
10 | pr_labels=$(echo "$pr" | jq -r '.labels')
11 |
12 | # Check if the "require descriptive names" label is present
13 | require_descriptive_names=$(echo "$pr_labels" | jq -r '.[] | select(.name == "require descriptive names")')
14 | echo "Checking PR #$pr_number $pr_title ($require_descriptive_names) ($pr_labels)"
15 |
16 | # If there are require_descriptive_names, close the pull request
17 | if [[ -n "$require_descriptive_names" ]]; then
18 | echo "Closing PR #$pr_number $pr_title due to require_descriptive_names label"
19 | gh pr close "$pr_number" --comment "Closing require_descriptive_names PRs to prepare for Hacktoberfest"
20 | fi
21 | done
22 |
--------------------------------------------------------------------------------
/scripts/close_pull_requests_with_require_tests.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # List all open pull requests
4 | prs=$(gh pr list --state open --json number,title,labels --limit 500)
5 |
6 | # Loop through each pull request
7 | echo "$prs" | jq -c '.[]' | while read -r pr; do
8 | pr_number=$(echo "$pr" | jq -r '.number')
9 | pr_title=$(echo "$pr" | jq -r '.title')
10 | pr_labels=$(echo "$pr" | jq -r '.labels')
11 |
12 | # Check if the "require_tests" label is present
13 | require_tests=$(echo "$pr_labels" | jq -r '.[] | select(.name == "require tests")')
14 | echo "Checking PR #$pr_number $pr_title ($require_tests) ($pr_labels)"
15 |
16 | # If there require tests, close the pull request
17 | if [[ -n "$require_tests" ]]; then
18 | echo "Closing PR #$pr_number $pr_title due to require_tests label"
19 | gh pr close "$pr_number" --comment "Closing require_tests PRs to prepare for Hacktoberfest"
20 | # sleep 2
21 | fi
22 | done
23 |
--------------------------------------------------------------------------------
/scripts/close_pull_requests_with_require_type_hints.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # List all open pull requests
4 | prs=$(gh pr list --state open --json number,title,labels --limit 500)
5 |
6 | # Loop through each pull request
7 | echo "$prs" | jq -c '.[]' | while read -r pr; do
8 | pr_number=$(echo "$pr" | jq -r '.number')
9 | pr_title=$(echo "$pr" | jq -r '.title')
10 | pr_labels=$(echo "$pr" | jq -r '.labels')
11 |
12 | # Check if the "require type hints" label is present
13 | require_type_hints=$(echo "$pr_labels" | jq -r '.[] | select(.name == "require type hints")')
14 | echo "Checking PR #$pr_number $pr_title ($require_type_hints) ($pr_labels)"
15 |
16 | # If require_type_hints, close the pull request
17 | if [[ -n "$require_type_hints" ]]; then
18 | echo "Closing PR #$pr_number $pr_title due to require_type_hints label"
19 | gh pr close "$pr_number" --comment "Closing require_type_hints PRs to prepare for Hacktoberfest"
20 | fi
21 | done
22 |
--------------------------------------------------------------------------------
/scripts/find_git_conflicts.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Replace with your repository (format: owner/repo)
4 | REPO="TheAlgorithms/Python"
5 |
6 | # Fetch open pull requests with conflicts into a variable
7 | echo "Checking for pull requests with conflicts in $REPO..."
8 |
9 | prs=$(gh pr list --repo "$REPO" --state open --json number,title,mergeable --jq '.[] | select(.mergeable == "CONFLICTING") | {number, title}' --limit 500)
10 |
11 | # Process each conflicting PR
12 | echo "$prs" | jq -c '.[]' | while read -r pr; do
13 | PR_NUMBER=$(echo "$pr" | jq -r '.number')
14 | PR_TITLE=$(echo "$pr" | jq -r '.title')
15 | echo "PR #$PR_NUMBER - $PR_TITLE has conflicts."
16 | done
17 |
--------------------------------------------------------------------------------
/searches/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/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/README.md:
--------------------------------------------------------------------------------
1 | # Sorting Algorithms
2 | Sorting is the process of putting data in a specific order. The way to arrange data in a specific order
3 | is specified by the sorting algorithm. The most typical orders are lexical or numerical. The significance
4 | of sorting lies in the fact that, if data is stored in a sorted manner, data searching can be highly optimised.
5 | Another use for sorting is to represent data in a more readable manner.
6 |
7 | This section contains a lot of important algorithms that help us to use sorting algorithms in various scenarios.
8 | ## References
9 | *
10 | *
11 | *
12 |
--------------------------------------------------------------------------------
/sorts/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/sorts/__init__.py
--------------------------------------------------------------------------------
/sorts/exchange_sort.py:
--------------------------------------------------------------------------------
1 | def exchange_sort(numbers: list[int]) -> list[int]:
2 | """
3 | Uses exchange sort to sort a list of numbers.
4 | Source: https://en.wikipedia.org/wiki/Sorting_algorithm#Exchange_sort
5 | >>> exchange_sort([5, 4, 3, 2, 1])
6 | [1, 2, 3, 4, 5]
7 | >>> exchange_sort([-1, -2, -3])
8 | [-3, -2, -1]
9 | >>> exchange_sort([1, 2, 3, 4, 5])
10 | [1, 2, 3, 4, 5]
11 | >>> exchange_sort([0, 10, -2, 5, 3])
12 | [-2, 0, 3, 5, 10]
13 | >>> exchange_sort([])
14 | []
15 | """
16 | numbers_length = len(numbers)
17 | for i in range(numbers_length):
18 | for j in range(i + 1, numbers_length):
19 | if numbers[j] < numbers[i]:
20 | numbers[i], numbers[j] = numbers[j], numbers[i]
21 | return numbers
22 |
23 |
24 | if __name__ == "__main__":
25 | user_input = input("Enter numbers separated by a comma:\n").strip()
26 | unsorted = [int(item) for item in user_input.split(",")]
27 | print(exchange_sort(unsorted))
28 |
--------------------------------------------------------------------------------
/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 transposition 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/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/selection_sort.py:
--------------------------------------------------------------------------------
1 | def selection_sort(collection: list[int]) -> list[int]:
2 | """
3 | Sorts a list in ascending order using the selection sort algorithm.
4 |
5 | :param collection: A list of integers to be sorted.
6 | :return: The sorted list.
7 |
8 | Examples:
9 | >>> selection_sort([0, 5, 3, 2, 2])
10 | [0, 2, 2, 3, 5]
11 |
12 | >>> selection_sort([])
13 | []
14 |
15 | >>> selection_sort([-2, -5, -45])
16 | [-45, -5, -2]
17 | """
18 |
19 | length = len(collection)
20 | for i in range(length - 1):
21 | min_index = i
22 | for k in range(i + 1, length):
23 | if collection[k] < collection[min_index]:
24 | min_index = k
25 | if min_index != i:
26 | collection[i], collection[min_index] = collection[min_index], collection[i]
27 | return collection
28 |
29 |
30 | if __name__ == "__main__":
31 | user_input = input("Enter numbers separated by a comma:\n").strip()
32 | unsorted = [int(item) for item in user_input.split(",")]
33 | sorted_list = selection_sort(unsorted)
34 | print("Sorted List:", sorted_list)
35 |
--------------------------------------------------------------------------------
/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/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/strings/__init__.py
--------------------------------------------------------------------------------
/strings/capitalize.py:
--------------------------------------------------------------------------------
1 | from string import ascii_lowercase, ascii_uppercase
2 |
3 |
4 | def capitalize(sentence: str) -> str:
5 | """
6 | Capitalizes the first letter of a sentence or word.
7 |
8 | >>> capitalize("hello world")
9 | 'Hello world'
10 | >>> capitalize("123 hello world")
11 | '123 hello world'
12 | >>> capitalize(" hello world")
13 | ' hello world'
14 | >>> capitalize("a")
15 | 'A'
16 | >>> capitalize("")
17 | ''
18 | """
19 | if not sentence:
20 | return ""
21 |
22 | # Create a dictionary that maps lowercase letters to uppercase letters
23 | # Capitalize the first character if it's a lowercase letter
24 | # Concatenate the capitalized character with the rest of the string
25 | lower_to_upper = dict(zip(ascii_lowercase, ascii_uppercase))
26 | return lower_to_upper.get(sentence[0], sentence[0]) + sentence[1:]
27 |
28 |
29 | if __name__ == "__main__":
30 | from doctest import testmod
31 |
32 | testmod()
33 |
--------------------------------------------------------------------------------
/strings/count_vowels.py:
--------------------------------------------------------------------------------
1 | def count_vowels(s: str) -> int:
2 | """
3 | Count the number of vowels in a given string.
4 |
5 | :param s: Input string to count vowels in.
6 | :return: Number of vowels in the input string.
7 |
8 | Examples:
9 | >>> count_vowels("hello world")
10 | 3
11 | >>> count_vowels("HELLO WORLD")
12 | 3
13 | >>> count_vowels("123 hello world")
14 | 3
15 | >>> count_vowels("")
16 | 0
17 | >>> count_vowels("a quick brown fox")
18 | 5
19 | >>> count_vowels("the quick BROWN fox")
20 | 5
21 | >>> count_vowels("PYTHON")
22 | 1
23 | """
24 | if not isinstance(s, str):
25 | raise ValueError("Input must be a string")
26 |
27 | vowels = "aeiouAEIOU"
28 | return sum(1 for char in s if char in vowels)
29 |
30 |
31 | if __name__ == "__main__":
32 | from doctest import testmod
33 |
34 | testmod()
35 |
--------------------------------------------------------------------------------
/strings/dna.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 |
4 | def dna(dna: str) -> str:
5 | """
6 | https://en.wikipedia.org/wiki/DNA
7 | Returns the second side of a DNA strand
8 |
9 | >>> dna("GCTA")
10 | 'CGAT'
11 | >>> dna("ATGC")
12 | 'TACG'
13 | >>> dna("CTGA")
14 | 'GACT'
15 | >>> dna("GFGG")
16 | Traceback (most recent call last):
17 | ...
18 | ValueError: Invalid Strand
19 | """
20 |
21 | if len(re.findall("[ATCG]", dna)) != len(dna):
22 | raise ValueError("Invalid Strand")
23 |
24 | return dna.translate(dna.maketrans("ATCG", "TAGC"))
25 |
26 |
27 | if __name__ == "__main__":
28 | import doctest
29 |
30 | doctest.testmod()
31 |
--------------------------------------------------------------------------------
/strings/indian_phone_validator.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 |
4 | def indian_phone_validator(phone: str) -> bool:
5 | """
6 | Determine whether the string is a valid phone number or not
7 | :param phone:
8 | :return: Boolean
9 | >>> indian_phone_validator("+91123456789")
10 | False
11 | >>> indian_phone_validator("+919876543210")
12 | True
13 | >>> indian_phone_validator("01234567896")
14 | False
15 | >>> indian_phone_validator("919876543218")
16 | True
17 | >>> indian_phone_validator("+91-1234567899")
18 | False
19 | >>> indian_phone_validator("+91-9876543218")
20 | True
21 | """
22 | pat = re.compile(r"^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$")
23 | if match := re.search(pat, phone):
24 | return match.string == phone
25 | return False
26 |
27 |
28 | if __name__ == "__main__":
29 | print(indian_phone_validator("+918827897895"))
30 |
--------------------------------------------------------------------------------
/strings/is_contains_unique_chars.py:
--------------------------------------------------------------------------------
1 | def is_contains_unique_chars(input_str: str) -> bool:
2 | """
3 | Check if all characters in the string is unique or not.
4 | >>> is_contains_unique_chars("I_love.py")
5 | True
6 | >>> is_contains_unique_chars("I don't love Python")
7 | False
8 |
9 | Time complexity: O(n)
10 | Space complexity: O(1) 19320 bytes as we are having 144697 characters in unicode
11 | """
12 |
13 | # Each bit will represent each unicode character
14 | # For example 65th bit representing 'A'
15 | # https://stackoverflow.com/a/12811293
16 | bitmap = 0
17 | for ch in input_str:
18 | ch_unicode = ord(ch)
19 | ch_bit_index_on = pow(2, ch_unicode)
20 |
21 | # If we already turned on bit for current character's unicode
22 | if bitmap >> ch_unicode & 1 == 1:
23 | return False
24 | bitmap |= ch_bit_index_on
25 | return True
26 |
27 |
28 | if __name__ == "__main__":
29 | import doctest
30 |
31 | doctest.testmod()
32 |
--------------------------------------------------------------------------------
/strings/is_isogram.py:
--------------------------------------------------------------------------------
1 | """
2 | wiki: https://en.wikipedia.org/wiki/Heterogram_(literature)#Isograms
3 | """
4 |
5 |
6 | def is_isogram(string: str) -> bool:
7 | """
8 | An isogram is a word in which no letter is repeated.
9 | Examples of isograms are uncopyrightable and ambidextrously.
10 | >>> is_isogram('Uncopyrightable')
11 | True
12 | >>> is_isogram('allowance')
13 | False
14 | >>> is_isogram('copy1')
15 | Traceback (most recent call last):
16 | ...
17 | ValueError: String must only contain alphabetic characters.
18 | """
19 | if not all(x.isalpha() for x in string):
20 | raise ValueError("String must only contain alphabetic characters.")
21 |
22 | letters = sorted(string.lower())
23 | return len(letters) == len(set(letters))
24 |
25 |
26 | if __name__ == "__main__":
27 | input_str = input("Enter a string ").strip()
28 |
29 | isogram = is_isogram(input_str)
30 | print(f"{input_str} is {'an' if isogram else 'not an'} isogram.")
31 |
--------------------------------------------------------------------------------
/strings/is_srilankan_phone_number.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 |
4 | def is_sri_lankan_phone_number(phone: str) -> bool:
5 | """
6 | Determine whether the string is a valid sri lankan mobile phone number or not
7 | References: https://aye.sh/blog/sri-lankan-phone-number-regex
8 |
9 | >>> is_sri_lankan_phone_number("+94773283048")
10 | True
11 | >>> is_sri_lankan_phone_number("+9477-3283048")
12 | True
13 | >>> is_sri_lankan_phone_number("0718382399")
14 | True
15 | >>> is_sri_lankan_phone_number("0094702343221")
16 | True
17 | >>> is_sri_lankan_phone_number("075 3201568")
18 | True
19 | >>> is_sri_lankan_phone_number("07779209245")
20 | False
21 | >>> is_sri_lankan_phone_number("0957651234")
22 | False
23 | """
24 |
25 | pattern = re.compile(r"^(?:0|94|\+94|0{2}94)7(0|1|2|4|5|6|7|8)(-| |)\d{7}$")
26 |
27 | return bool(re.search(pattern, phone))
28 |
29 |
30 | if __name__ == "__main__":
31 | phone = "0094702343221"
32 |
33 | print(is_sri_lankan_phone_number(phone))
34 |
--------------------------------------------------------------------------------
/strings/lower.py:
--------------------------------------------------------------------------------
1 | def lower(word: str) -> str:
2 | """
3 | Will convert the entire string to lowercase 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, obtaining the integer representation
18 | # and checking to see if the character is a capital letter.
19 | # If it is a capital letter, it is shifted by 32, making it a lowercase 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/ngram.py:
--------------------------------------------------------------------------------
1 | """
2 | https://en.wikipedia.org/wiki/N-gram
3 | """
4 |
5 |
6 | def create_ngram(sentence: str, ngram_size: int) -> list[str]:
7 | """
8 | Create ngrams from a sentence
9 |
10 | >>> create_ngram("I am a sentence", 2)
11 | ['I ', ' a', 'am', 'm ', ' a', 'a ', ' s', 'se', 'en', 'nt', 'te', 'en', 'nc', 'ce']
12 | >>> create_ngram("I am an NLPer", 2)
13 | ['I ', ' a', 'am', 'm ', ' a', 'an', 'n ', ' N', 'NL', 'LP', 'Pe', 'er']
14 | >>> create_ngram("This is short", 50)
15 | []
16 | """
17 | return [sentence[i : i + ngram_size] for i in range(len(sentence) - ngram_size + 1)]
18 |
19 |
20 | if __name__ == "__main__":
21 | from doctest import testmod
22 |
23 | testmod()
24 |
--------------------------------------------------------------------------------
/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_letters.py:
--------------------------------------------------------------------------------
1 | def reverse_letters(sentence: str, length: int = 0) -> str:
2 | """
3 | Reverse all words that are longer than the given length of characters in a sentence.
4 | If unspecified, length is taken as 0
5 |
6 | >>> reverse_letters("Hey wollef sroirraw", 3)
7 | 'Hey fellow warriors'
8 | >>> reverse_letters("nohtyP is nohtyP", 2)
9 | 'Python is Python'
10 | >>> reverse_letters("1 12 123 1234 54321 654321", 0)
11 | '1 21 321 4321 12345 123456'
12 | >>> reverse_letters("racecar")
13 | 'racecar'
14 | """
15 | return " ".join(
16 | "".join(word[::-1]) if len(word) > length else word for word in sentence.split()
17 | )
18 |
19 |
20 | if __name__ == "__main__":
21 | import doctest
22 |
23 | doctest.testmod()
24 | print(reverse_letters("Hey wollef sroirraw"))
25 |
--------------------------------------------------------------------------------
/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 | >>> split(";abbb;;c;", separator=';')
19 | ['', 'abbb', '', 'c', '']
20 | """
21 |
22 | split_words = []
23 |
24 | last_index = 0
25 | for index, char in enumerate(string):
26 | if char == separator:
27 | split_words.append(string[last_index:index])
28 | last_index = index + 1
29 | if index + 1 == len(string):
30 | split_words.append(string[last_index : index + 1])
31 | return split_words
32 |
33 |
34 | if __name__ == "__main__":
35 | from doctest import testmod
36 |
37 | testmod()
38 |
--------------------------------------------------------------------------------
/strings/strip.py:
--------------------------------------------------------------------------------
1 | def strip(user_string: str, characters: str = " \t\n\r") -> str:
2 | """
3 | Remove leading and trailing characters (whitespace by default) from a string.
4 |
5 | Args:
6 | user_string (str): The input string to be stripped.
7 | characters (str, optional): Optional characters to be removed
8 | (default is whitespace).
9 |
10 | Returns:
11 | str: The stripped string.
12 |
13 | Examples:
14 | >>> strip(" hello ")
15 | 'hello'
16 | >>> strip("...world...", ".")
17 | 'world'
18 | >>> strip("123hello123", "123")
19 | 'hello'
20 | >>> strip("")
21 | ''
22 | """
23 |
24 | start = 0
25 | end = len(user_string)
26 |
27 | while start < end and user_string[start] in characters:
28 | start += 1
29 |
30 | while end > start and user_string[end - 1] in characters:
31 | end -= 1
32 |
33 | return user_string[start:end]
34 |
--------------------------------------------------------------------------------
/strings/upper.py:
--------------------------------------------------------------------------------
1 | def upper(word: str) -> str:
2 | """
3 | Convert an entire string to ASCII uppercase letters by looking for lowercase ASCII
4 | letters and subtracting 32 from their integer representation to get the uppercase
5 | letter.
6 |
7 | >>> upper("wow")
8 | 'WOW'
9 | >>> upper("Hello")
10 | 'HELLO'
11 | >>> upper("WHAT")
12 | 'WHAT'
13 | >>> upper("wh[]32")
14 | 'WH[]32'
15 | """
16 | return "".join(chr(ord(char) - 32) if "a" <= char <= "z" else char for char in word)
17 |
18 |
19 | if __name__ == "__main__":
20 | from doctest import testmod
21 |
22 | testmod()
23 |
--------------------------------------------------------------------------------
/strings/wave_string.py:
--------------------------------------------------------------------------------
1 | def wave(txt: str) -> list:
2 | """
3 | Returns a so called 'wave' of a given string
4 | >>> wave('cat')
5 | ['Cat', 'cAt', 'caT']
6 | >>> wave('one')
7 | ['One', 'oNe', 'onE']
8 | >>> wave('book')
9 | ['Book', 'bOok', 'boOk', 'booK']
10 | """
11 |
12 | return [
13 | txt[:a] + txt[a].upper() + txt[a + 1 :]
14 | for a in range(len(txt))
15 | if txt[a].isalpha()
16 | ]
17 |
18 |
19 | if __name__ == "__main__":
20 | __import__("doctest").testmod()
21 |
--------------------------------------------------------------------------------
/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_occurrence(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_occurrence(SENTENCE)
11 | >>> all(occurence_dict[word] == count for word, count
12 | ... in Counter(SENTENCE.split()).items())
13 | True
14 | >>> dict(word_occurrence("Two spaces"))
15 | {'Two': 1, 'spaces': 1}
16 | """
17 | occurrence: defaultdict[str, int] = 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_occurrence("INPUT STRING").items():
26 | print(f"{word}: {count}")
27 |
--------------------------------------------------------------------------------
/web_programming/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheAlgorithms/Python/4b077c06b623ea20a90e9e5678e38101a4636584/web_programming/__init__.py
--------------------------------------------------------------------------------
/web_programming/co2_emission.py:
--------------------------------------------------------------------------------
1 | """
2 | Get CO2 emission data from the UK CarbonIntensity API
3 | """
4 |
5 | # /// script
6 | # requires-python = ">=3.13"
7 | # dependencies = [
8 | # "httpx",
9 | # ]
10 | # ///
11 |
12 | from datetime import date
13 |
14 | import httpx
15 |
16 | BASE_URL = "https://api.carbonintensity.org.uk/intensity"
17 |
18 |
19 | # Emission in the last half hour
20 | def fetch_last_half_hour() -> str:
21 | last_half_hour = httpx.get(BASE_URL, timeout=10).json()["data"][0]
22 | return last_half_hour["intensity"]["actual"]
23 |
24 |
25 | # Emissions in a specific date range
26 | def fetch_from_to(start, end) -> list:
27 | return httpx.get(f"{BASE_URL}/{start}/{end}", timeout=10).json()["data"]
28 |
29 |
30 | if __name__ == "__main__":
31 | for entry in fetch_from_to(start=date(2020, 10, 1), end=date(2020, 10, 3)):
32 | print("from {from} to {to}: {intensity[actual]}".format(**entry))
33 | print(f"{fetch_last_half_hour() = }")
34 |
--------------------------------------------------------------------------------
/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 | # /// script
8 | # requires-python = ">=3.13"
9 | # dependencies = [
10 | # "httpx",
11 | # "lxml",
12 | # ]
13 | # ///
14 |
15 | from typing import NamedTuple
16 |
17 | import httpx
18 | from lxml import html
19 |
20 |
21 | class CovidData(NamedTuple):
22 | cases: int
23 | deaths: int
24 | recovered: int
25 |
26 |
27 | def covid_stats(url: str = "https://www.worldometers.info/coronavirus/") -> CovidData:
28 | xpath_str = '//div[@class = "maincounter-number"]/span/text()'
29 | return CovidData(
30 | *html.fromstring(httpx.get(url, timeout=10).content).xpath(xpath_str)
31 | )
32 |
33 |
34 | fmt = """Total COVID-19 cases in the world: {}
35 | Total deaths due to COVID-19 in the world: {}
36 | Total COVID-19 patients recovered in the world: {}"""
37 | print(fmt.format(*covid_stats()))
38 |
--------------------------------------------------------------------------------
/web_programming/fetch_bbc_news.py:
--------------------------------------------------------------------------------
1 | # Created by sarathkaul on 12/11/19
2 |
3 | # /// script
4 | # requires-python = ">=3.13"
5 | # dependencies = [
6 | # "httpx",
7 | # ]
8 | # ///
9 |
10 | import httpx
11 |
12 | _NEWS_API = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey="
13 |
14 |
15 | def fetch_bbc_news(bbc_news_api_key: str) -> None:
16 | # fetching a list of articles in json format
17 | bbc_news_page = httpx.get(_NEWS_API + bbc_news_api_key, timeout=10).json()
18 | # each article in the list is a dict
19 | for i, article in enumerate(bbc_news_page["articles"], 1):
20 | print(f"{i}.) {article['title']}")
21 |
22 |
23 | if __name__ == "__main__":
24 | fetch_bbc_news(bbc_news_api_key="")
25 |
--------------------------------------------------------------------------------
/web_programming/get_top_hn_posts.py:
--------------------------------------------------------------------------------
1 | # /// script
2 | # requires-python = ">=3.13"
3 | # dependencies = [
4 | # "httpx",
5 | # ]
6 | # ///
7 |
8 | from __future__ import annotations
9 |
10 | import httpx
11 |
12 |
13 | def get_hackernews_story(story_id: str) -> dict:
14 | url = f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty"
15 | return httpx.get(url, timeout=10).json()
16 |
17 |
18 | def hackernews_top_stories(max_stories: int = 10) -> list[dict]:
19 | """
20 | Get the top max_stories posts from HackerNews - https://news.ycombinator.com/
21 | """
22 | url = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty"
23 | story_ids = httpx.get(url, timeout=10).json()[:max_stories]
24 | return [get_hackernews_story(story_id) for story_id in story_ids]
25 |
26 |
27 | def hackernews_top_stories_as_markdown(max_stories: int = 10) -> str:
28 | stories = hackernews_top_stories(max_stories)
29 | return "\n".join("* [{title}]({url})".format(**story) for story in stories)
30 |
31 |
32 | if __name__ == "__main__":
33 | print(hackernews_top_stories_as_markdown())
34 |
--------------------------------------------------------------------------------
/web_programming/giphy.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | # /// script
4 | # requires-python = ">=3.13"
5 | # dependencies = [
6 | # "httpx",
7 | # ]
8 | # ///
9 |
10 | import httpx
11 |
12 | giphy_api_key = "YOUR API KEY"
13 | # Can be fetched from https://developers.giphy.com/dashboard/
14 |
15 |
16 | def get_gifs(query: str, api_key: str = giphy_api_key) -> list:
17 | """
18 | Get a list of URLs of GIFs based on a given query..
19 | """
20 | formatted_query = "+".join(query.split())
21 | url = f"https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}"
22 | gifs = httpx.get(url, timeout=10).json()["data"]
23 | return [gif["url"] for gif in gifs]
24 |
25 |
26 | if __name__ == "__main__":
27 | print("\n".join(get_gifs("space ship")))
28 |
--------------------------------------------------------------------------------
/web_programming/instagram_video.py:
--------------------------------------------------------------------------------
1 | # /// script
2 | # requires-python = ">=3.13"
3 | # dependencies = [
4 | # "httpx",
5 | # ]
6 | # ///
7 |
8 | from datetime import UTC, datetime
9 |
10 | import httpx
11 |
12 |
13 | def download_video(url: str) -> bytes:
14 | base_url = "https://downloadgram.net/wp-json/wppress/video-downloader/video?url="
15 | video_url = httpx.get(base_url + url, timeout=10)
16 | return httpx.get(video_url, timeout=10).content
17 |
18 |
19 | if __name__ == "__main__":
20 | url = input("Enter Video/IGTV url: ").strip()
21 | file_name = f"{datetime.now(tz=UTC).astimezone():%Y-%m-%d_%H-%M-%S}.mp4"
22 | with open(file_name, "wb") as fp:
23 | fp.write(download_video(url))
24 | print(f"Done. Video saved to disk as {file_name}.")
25 |
--------------------------------------------------------------------------------
/web_programming/open_google_results.py:
--------------------------------------------------------------------------------
1 | # /// script
2 | # requires-python = ">=3.13"
3 | # dependencies = [
4 | # "beautifulsoup4",
5 | # "fake-useragent",
6 | # "httpx",
7 | # ]
8 | # ///
9 |
10 | import webbrowser
11 | from sys import argv
12 | from urllib.parse import parse_qs, quote
13 |
14 | import httpx
15 | from bs4 import BeautifulSoup
16 | from fake_useragent import UserAgent
17 |
18 | if __name__ == "__main__":
19 | query = "%20".join(argv[1:]) if len(argv) > 1 else quote(str(input("Search: ")))
20 |
21 | print("Googling.....")
22 |
23 | url = f"https://www.google.com/search?q={query}&num=100"
24 |
25 | res = httpx.get(
26 | url,
27 | headers={"User-Agent": str(UserAgent().random)},
28 | timeout=10,
29 | )
30 |
31 | try:
32 | link = BeautifulSoup(res.text, "html.parser").find("div").find("a").get("href")
33 |
34 | except AttributeError:
35 | link = parse_qs(
36 | BeautifulSoup(res.text, "html.parser").find("div").find("a").get("href")
37 | )["url"][0]
38 |
39 | webbrowser.open(link)
40 |
--------------------------------------------------------------------------------
/web_programming/slack_message.py:
--------------------------------------------------------------------------------
1 | # Created by sarathkaul on 12/11/19
2 |
3 | # /// script
4 | # requires-python = ">=3.13"
5 | # dependencies = [
6 | # "httpx",
7 | # ]
8 | # ///
9 |
10 | import httpx
11 |
12 |
13 | def send_slack_message(message_body: str, slack_url: str) -> None:
14 | headers = {"Content-Type": "application/json"}
15 | response = httpx.post(
16 | slack_url, json={"text": message_body}, headers=headers, timeout=10
17 | )
18 | if response.status_code != 200:
19 | msg = (
20 | "Request to slack returned an error "
21 | f"{response.status_code}, the response is:\n{response.text}"
22 | )
23 | raise ValueError(msg)
24 |
25 |
26 | if __name__ == "__main__":
27 | # Set the slack url to the one provided by Slack when you create the webhook at
28 | # https://my.slack.com/services/new/incoming-webhook/
29 | send_slack_message("", "")
30 |
--------------------------------------------------------------------------------
/web_programming/test_fetch_github_info.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 | import httpx
4 |
5 | from .fetch_github_info import AUTHENTICATED_USER_ENDPOINT, fetch_github_info
6 |
7 |
8 | def test_fetch_github_info(monkeypatch):
9 | class FakeResponse:
10 | def __init__(self, content) -> None:
11 | assert isinstance(content, (bytes, str))
12 | self.content = content
13 |
14 | def json(self):
15 | return json.loads(self.content)
16 |
17 | def mock_response(*args, **kwargs):
18 | assert args[0] == AUTHENTICATED_USER_ENDPOINT
19 | assert "Authorization" in kwargs["headers"]
20 | assert kwargs["headers"]["Authorization"].startswith("token ")
21 | assert "Accept" in kwargs["headers"]
22 | return FakeResponse(b'{"login":"test","id":1}')
23 |
24 | monkeypatch.setattr(httpx, "get", mock_response)
25 | result = fetch_github_info("token")
26 | assert result["login"] == "test"
27 | assert result["id"] == 1
28 |
--------------------------------------------------------------------------------