├── docs ├── __init__.py ├── source │ └── __init__.py └── conf.py ├── graphs ├── __init__.py ├── tests │ ├── __init__.py │ └── test_min_spanning_tree_kruskal.py ├── kahns_algorithm_long.py └── g_topological_sort.py ├── hashes ├── __init__.py ├── elf.py ├── adler32.py └── djb2.py ├── maths ├── __init__.py ├── images │ ├── __init__.py │ └── gaussian.png ├── series │ └── __init__.py ├── polynomials │ └── __init__.py ├── special_numbers │ ├── __init__.py │ └── polygonal_numbers.py ├── numerical_analysis │ ├── __init__.py │ └── secant_method.py ├── test_prime_check.py ├── arc_length.py ├── floor.py ├── ceil.py ├── sock_merchant.py ├── sum_of_arithmetic_series.py ├── average_mean.py ├── radians.py ├── print_multiplication_table.py ├── karatsuba.py ├── pythagoras.py ├── chebyshev_distance.py ├── is_int_palindrome.py ├── addition_without_arithmetic.py ├── base_neg2_conversion.py ├── fermat_little_theorem.py ├── average_median.py ├── factors.py ├── average_absolute_deviation.py ├── sumset.py ├── average_mode.py ├── modular_exponential.py ├── sum_of_geometric_progression.py ├── sigmoid.py ├── quadratic_equations_complex_numbers.py ├── sum_of_harmonic_series.py ├── is_square_free.py ├── mobius_function.py ├── lucas_lehmer_primality_test.py └── remove_digit.py ├── matrix ├── __init__.py ├── tests │ ├── __init__.py │ └── pytest.ini └── median_matrix.py ├── other ├── __init__.py ├── quine.py ├── tower_of_hanoi.py └── fischer_yates_shuffle.py ├── sorts ├── __init__.py ├── recursive_quick_sort.py ├── README.md ├── exchange_sort.py ├── odd_even_transposition_single_threaded.py ├── wiggle_sort.py └── selection_sort.py ├── source └── __init__.py ├── blockchain └── __init__.py ├── ciphers ├── __init__.py ├── README.md ├── cryptomath_module.py ├── a1z26.py └── rot13.py ├── compression ├── __init__.py ├── image_data │ ├── __init__.py │ ├── example_image.jpg │ ├── original_image.png │ ├── compressed_image.png │ ├── PSNR-example-base.png │ ├── PSNR-example-comp-10.jpg │ └── example_wikipedia_image.jpg └── README.md ├── conversions ├── __init__.py ├── README.md ├── excel_title_to_column.py └── rectangular_to_polar.py ├── electronics └── __init__.py ├── financial ├── __init__.py ├── README.md └── price_plus_tax.py ├── fractals └── __init__.py ├── fuzzy_logic └── __init__.py ├── geodesy └── __init__.py ├── geometry └── __init__.py ├── graphics └── __init__.py ├── knapsack ├── __init__.py └── tests │ └── __init__.py ├── physics ├── __init__.py └── image_data │ ├── __init__.py │ ├── 2D_problems.jpg │ └── 2D_problems_1.jpg ├── quantum ├── __init__.py └── quantum_random.py.DISABLED.txt ├── scheduling └── __init__.py ├── scripts ├── __init__.py ├── find_git_conflicts.sh ├── close_pull_requests_with_require_tests.sh ├── close_pull_requests_with_awaiting_changes.sh ├── close_pull_requests_with_require_type_hints.sh ├── close_pull_requests_with_failing_tests.sh └── close_pull_requests_with_require_descriptive_names.sh ├── searches ├── __init__.py ├── tabu_test_data.txt └── double_linear_search_recursion.py ├── strings ├── __init__.py ├── reverse_words.py ├── remove_duplicate.py ├── wave_string.py ├── upper.py ├── dna.py ├── ngram.py ├── lower.py ├── reverse_letters.py ├── count_vowels.py ├── indian_phone_validator.py ├── strip.py ├── word_occurrence.py ├── capitalize.py ├── is_isogram.py ├── is_contains_unique_chars.py ├── is_srilankan_phone_number.py ├── split.py └── alternative_string_arrange.py ├── audio_filters ├── __init__.py ├── README.md └── loudness_curve.json ├── backtracking ├── __init__.py └── README.md ├── bit_manipulation ├── __init__.py ├── excess_3_code.py ├── README.md ├── binary_coded_decimal.py ├── is_even.py ├── highest_set_bit.py ├── numbers_different_signs.py ├── missing_number.py └── find_previous_power_of_two.py ├── boolean_algebra ├── __init__.py ├── README.md ├── not_gate.py ├── and_gate.py ├── or_gate.py ├── xor_gate.py ├── imply_gate.py ├── nand_gate.py ├── xnor_gate.py └── nimply_gate.py ├── computer_vision ├── __init__.py ├── README.md └── mean_threshold.py ├── data_structures ├── __init__.py ├── heap │ └── __init__.py ├── trie │ └── __init__.py ├── arrays │ ├── __init__.py │ ├── pairs_with_given_sum.py │ └── monotonic_array.py ├── hashing │ ├── __init__.py │ ├── tests │ │ └── __init__.py │ ├── number_theory │ │ └── __init__.py │ └── hash_table_with_linked_list.py ├── kd_tree │ ├── __init__.py │ ├── example │ │ ├── __init__.py │ │ └── hypercube_points.py │ └── tests │ │ └── __init__.py ├── queues │ └── __init__.py ├── stacks │ ├── __init__.py │ └── lexicographical_numbers.py ├── binary_tree │ └── __init__.py ├── disjoint_set │ └── __init__.py └── suffix_tree │ ├── __init__.py │ ├── example │ └── __init__.py │ └── tests │ └── __init__.py ├── file_transfer ├── __init__.py ├── tests │ ├── __init__.py │ └── test_send_file.py ├── mytext.txt ├── receive_file.py └── send_file.py ├── greedy_methods └── __init__.py ├── linear_algebra ├── __init__.py └── src │ └── __init__.py ├── machine_learning ├── __init__.py ├── lstm │ └── __init__.py ├── forecasting │ └── __init__.py ├── local_weighted_learning │ └── __init__.py └── multilayer_perceptron_classifier.py ├── networking_flow └── __init__.py ├── neural_network ├── __init__.py └── activation_functions │ ├── __init__.py │ ├── binary_step.py │ └── softplus.py ├── project_euler ├── __init__.py ├── problem_001 │ ├── __init__.py │ ├── sol1.py │ ├── sol5.py │ ├── sol7.py │ ├── sol6.py │ └── sol2.py ├── problem_002 │ ├── __init__.py │ ├── sol1.py │ └── sol2.py ├── problem_003 │ └── __init__.py ├── problem_004 │ ├── __init__.py │ └── sol2.py ├── problem_005 │ └── __init__.py ├── problem_006 │ └── __init__.py ├── problem_007 │ └── __init__.py ├── problem_008 │ └── __init__.py ├── problem_009 │ ├── __init__.py │ └── sol3.py ├── problem_010 │ └── __init__.py ├── problem_011 │ └── __init__.py ├── problem_012 │ └── __init__.py ├── problem_013 │ ├── __init__.py │ └── sol1.py ├── problem_014 │ └── __init__.py ├── problem_015 │ └── __init__.py ├── problem_016 │ ├── __init__.py │ ├── sol2.py │ └── sol1.py ├── problem_017 │ └── __init__.py ├── problem_018 │ ├── __init__.py │ └── triangle.txt ├── problem_019 │ └── __init__.py ├── problem_020 │ ├── __init__.py │ ├── sol2.py │ ├── sol4.py │ └── sol3.py ├── problem_021 │ └── __init__.py ├── problem_022 │ └── __init__.py ├── problem_023 │ └── __init__.py ├── problem_024 │ ├── __init__.py │ └── sol1.py ├── problem_025 │ └── __init__.py ├── problem_026 │ └── __init__.py ├── problem_027 │ └── __init__.py ├── problem_028 │ └── __init__.py ├── problem_029 │ └── __init__.py ├── problem_030 │ └── __init__.py ├── problem_031 │ └── __init__.py ├── problem_032 │ └── __init__.py ├── problem_033 │ └── __init__.py ├── problem_034 │ ├── __init__.py │ └── sol1.py ├── problem_035 │ └── __init__.py ├── problem_036 │ └── __init__.py ├── problem_037 │ └── __init__.py ├── problem_038 │ └── __init__.py ├── problem_039 │ └── __init__.py ├── problem_040 │ ├── __init__.py │ └── sol1.py ├── problem_041 │ └── __init__.py ├── problem_042 │ └── __init__.py ├── problem_043 │ └── __init__.py ├── problem_044 │ └── __init__.py ├── problem_045 │ └── __init__.py ├── problem_046 │ └── __init__.py ├── problem_047 │ └── __init__.py ├── problem_048 │ ├── __init__.py │ └── sol1.py ├── problem_049 │ └── __init__.py ├── problem_050 │ └── __init__.py ├── problem_051 │ └── __init__.py ├── problem_052 │ ├── __init__.py │ └── sol1.py ├── problem_053 │ ├── __init__.py │ └── sol1.py ├── problem_054 │ └── __init__.py ├── problem_055 │ └── __init__.py ├── problem_056 │ └── __init__.py ├── problem_057 │ └── __init__.py ├── problem_058 │ └── __init__.py ├── problem_059 │ ├── __init__.py │ └── test_cipher.txt ├── problem_062 │ └── __init__.py ├── problem_063 │ ├── __init__.py │ └── sol1.py ├── problem_064 │ └── __init__.py ├── problem_065 │ └── __init__.py ├── problem_067 │ └── __init__.py ├── problem_068 │ └── __init__.py ├── problem_069 │ └── __init__.py ├── problem_070 │ └── __init__.py ├── problem_071 │ └── __init__.py ├── problem_072 │ └── __init__.py ├── problem_073 │ └── __init__.py ├── problem_074 │ └── __init__.py ├── problem_075 │ └── __init__.py ├── problem_076 │ └── __init__.py ├── problem_077 │ └── __init__.py ├── problem_078 │ └── __init__.py ├── problem_079 │ ├── __init__.py │ ├── keylog_test.txt │ └── keylog.txt ├── problem_080 │ └── __init__.py ├── problem_081 │ └── __init__.py ├── problem_082 │ ├── __init__.py │ └── test_matrix.txt ├── problem_085 │ └── __init__.py ├── problem_086 │ └── __init__.py ├── problem_087 │ └── __init__.py ├── problem_089 │ ├── __init__.py │ └── numeralcleanup_test.txt ├── problem_091 │ └── __init__.py ├── problem_092 │ └── __init__.py ├── problem_094 │ └── __init__.py ├── problem_097 │ └── __init__.py ├── problem_099 │ ├── __init__.py │ └── sol1.py ├── problem_100 │ └── __init__.py ├── problem_101 │ └── __init__.py ├── problem_102 │ ├── __init__.py │ └── test_triangles.txt ├── problem_104 │ └── __init__.py ├── problem_107 │ ├── __init__.py │ └── test_network.txt ├── problem_109 │ └── __init__.py ├── problem_112 │ └── __init__.py ├── problem_113 │ └── __init__.py ├── problem_114 │ └── __init__.py ├── problem_115 │ └── __init__.py ├── problem_116 │ └── __init__.py ├── problem_117 │ └── __init__.py ├── problem_119 │ └── __init__.py ├── problem_120 │ ├── __init__.py │ └── sol1.py ├── problem_121 │ └── __init__.py ├── problem_123 │ └── __init__.py ├── problem_125 │ └── __init__.py ├── problem_129 │ └── __init__.py ├── problem_131 │ └── __init__.py ├── problem_135 │ └── __init__.py ├── problem_144 │ └── __init__.py ├── problem_145 │ └── __init__.py ├── problem_173 │ └── __init__.py ├── problem_174 │ └── __init__.py ├── problem_180 │ └── __init__.py ├── problem_187 │ └── __init__.py ├── problem_188 │ └── __init__.py ├── problem_191 │ └── __init__.py ├── problem_203 │ └── __init__.py ├── problem_205 │ └── __init__.py ├── problem_206 │ └── __init__.py ├── problem_207 │ └── __init__.py ├── problem_234 │ └── __init__.py ├── problem_301 │ └── __init__.py ├── problem_493 │ └── __init__.py ├── problem_551 │ └── __init__.py ├── problem_587 │ └── __init__.py ├── problem_686 │ └── __init__.py └── problem_800 │ └── __init__.py ├── web_programming ├── __init__.py ├── fetch_bbc_news.py ├── giphy.py ├── instagram_video.py ├── slack_message.py ├── co2_emission.py ├── crawl_google_results.py ├── covid_stats_via_xpath.py ├── test_fetch_github_info.py ├── get_top_hn_posts.py ├── fetch_jobs.py ├── fetch_quotes.py ├── world_covid19_stats.py ├── get_imdb_top_250_movies_csv.py ├── open_google_results.py ├── crawl_google_scholar_citation.py └── daily_horoscope.py ├── .gitattributes ├── cellular_automata ├── __init__.py └── README.md ├── divide_and_conquer └── __init__.py ├── dynamic_programming ├── __init__.py ├── tribonacci.py ├── factorial.py ├── max_non_adjacent_sum.py ├── fast_fibonacci.py ├── minimum_cost_path.py └── abbreviation.py ├── genetic_algorithm └── __init__.py ├── linear_programming └── __init__.py ├── digital_image_processing ├── __init__.py ├── resize │ └── __init__.py ├── dithering │ └── __init__.py ├── filters │ └── __init__.py ├── image_data │ ├── __init__.py │ ├── lena.jpg │ └── lena_small.jpg ├── rotation │ └── __init__.py ├── edge_detection │ └── __init__.py ├── histogram_equalization │ ├── __init__.py │ ├── image_data │ │ ├── __init__.py │ │ └── input.jpg │ └── output_data │ │ ├── __init__.py │ │ └── output.jpg ├── morphological_operations │ └── __init__.py ├── change_brightness.py ├── convert_to_negative.py └── change_contrast.py ├── .gitpod.yml ├── .devcontainer ├── README.md └── Dockerfile ├── .vscode └── settings.json ├── .github ├── ISSUE_TEMPLATE │ ├── config.yml │ ├── other.yml │ └── feature_request.yml ├── dependabot.yml └── workflows │ ├── ruff.yml │ └── directory_writer.yml ├── index.md ├── requirements.txt └── LICENSE.md /docs/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /graphs/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /hashes/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /maths/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /matrix/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /other/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /sorts/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /source/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /blockchain/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ciphers/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /compression/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /conversions/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/source/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /electronics/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /financial/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /fractals/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /fuzzy_logic/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /geodesy/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /geometry/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /graphics/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /knapsack/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /physics/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /quantum/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /scheduling/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /scripts/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /searches/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /strings/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /audio_filters/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /backtracking/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /bit_manipulation/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /boolean_algebra/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /computer_vision/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_structures/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /file_transfer/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /graphs/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /greedy_methods/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /knapsack/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /linear_algebra/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /machine_learning/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /maths/images/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /maths/series/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /matrix/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /networking_flow/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /neural_network/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /web_programming/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto 2 | -------------------------------------------------------------------------------- /cellular_automata/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_structures/heap/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_structures/trie/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /divide_and_conquer/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /dynamic_programming/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /file_transfer/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /genetic_algorithm/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /linear_algebra/src/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /linear_programming/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /machine_learning/lstm/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /maths/polynomials/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /maths/special_numbers/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /physics/image_data/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /compression/image_data/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_structures/arrays/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_structures/hashing/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_structures/kd_tree/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_structures/queues/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_structures/stacks/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /digital_image_processing/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /maths/numerical_analysis/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_001/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_002/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_003/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_004/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_005/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_006/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_007/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_008/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_009/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_010/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_011/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_012/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_013/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_014/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_015/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_016/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_017/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_018/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_019/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_020/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_021/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_022/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_023/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_024/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_025/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_026/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_027/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_028/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_029/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_030/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_031/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_032/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_033/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_034/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_035/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_036/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_037/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_038/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_039/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_040/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_041/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_042/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_043/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_044/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_045/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_046/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_047/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_048/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_049/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_050/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_051/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_052/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_053/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_054/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_055/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_056/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_057/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_058/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_059/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_062/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_063/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_064/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_065/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_067/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_068/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_069/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_070/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_071/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_072/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_073/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_074/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_075/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_076/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_077/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_078/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_079/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_080/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_081/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_082/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_085/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_086/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_087/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_089/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_091/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_092/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_094/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_097/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_099/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_100/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_101/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_102/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_104/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_107/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_109/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_112/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_113/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_114/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_115/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_116/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_117/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_119/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_120/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_121/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_123/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_125/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_129/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_131/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_135/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_144/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_145/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_173/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_174/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_180/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_187/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_188/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_191/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_203/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_205/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_206/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_207/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_234/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_301/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_493/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_551/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_587/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_686/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project_euler/problem_800/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_structures/binary_tree/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_structures/disjoint_set/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_structures/hashing/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_structures/kd_tree/example/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_structures/kd_tree/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_structures/suffix_tree/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /digital_image_processing/resize/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /machine_learning/forecasting/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_structures/suffix_tree/example/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_structures/suffix_tree/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /digital_image_processing/dithering/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /digital_image_processing/filters/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /digital_image_processing/image_data/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /digital_image_processing/rotation/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /neural_network/activation_functions/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data_structures/hashing/number_theory/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /digital_image_processing/edge_detection/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /machine_learning/local_weighted_learning/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /digital_image_processing/histogram_equalization/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /digital_image_processing/morphological_operations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | tasks: 2 | - init: pip3 install -r ./requirements.txt 3 | -------------------------------------------------------------------------------- /digital_image_processing/histogram_equalization/image_data/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /digital_image_processing/histogram_equalization/output_data/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.devcontainer/README.md: -------------------------------------------------------------------------------- 1 | https://code.visualstudio.com/docs/devcontainers/tutorial 2 | -------------------------------------------------------------------------------- /file_transfer/mytext.txt: -------------------------------------------------------------------------------- 1 | Hello 2 | This is sample data 3 | «küßî» 4 | “ЌύБЇ” 5 | 😀😉 6 | 😋 7 | -------------------------------------------------------------------------------- /matrix/tests/pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | markers = 3 | mat_ops: tests for matrix operations 4 | -------------------------------------------------------------------------------- /project_euler/problem_089/numeralcleanup_test.txt: -------------------------------------------------------------------------------- 1 | IIII 2 | IV 3 | IIIIIIIIII 4 | X 5 | VIIIII 6 | -------------------------------------------------------------------------------- /maths/images/gaussian.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hu8813/Python-1/HEAD/maths/images/gaussian.png -------------------------------------------------------------------------------- /project_euler/problem_102/test_triangles.txt: -------------------------------------------------------------------------------- 1 | -340,495,-153,-910,835,-947 2 | -175,41,-421,-714,574,-645 3 | -------------------------------------------------------------------------------- /physics/image_data/2D_problems.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hu8813/Python-1/HEAD/physics/image_data/2D_problems.jpg -------------------------------------------------------------------------------- /physics/image_data/2D_problems_1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hu8813/Python-1/HEAD/physics/image_data/2D_problems_1.jpg -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "githubPullRequests.ignoredPullRequestBranches": [ 3 | "master" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /compression/image_data/example_image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hu8813/Python-1/HEAD/compression/image_data/example_image.jpg -------------------------------------------------------------------------------- /compression/image_data/original_image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hu8813/Python-1/HEAD/compression/image_data/original_image.png -------------------------------------------------------------------------------- /compression/image_data/compressed_image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hu8813/Python-1/HEAD/compression/image_data/compressed_image.png -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | from sphinx_pyproject import SphinxConfig 2 | 3 | project = SphinxConfig("../pyproject.toml", globalns=globals()).name 4 | -------------------------------------------------------------------------------- /compression/image_data/PSNR-example-base.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hu8813/Python-1/HEAD/compression/image_data/PSNR-example-base.png -------------------------------------------------------------------------------- /digital_image_processing/image_data/lena.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hu8813/Python-1/HEAD/digital_image_processing/image_data/lena.jpg -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /compression/image_data/PSNR-example-comp-10.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hu8813/Python-1/HEAD/compression/image_data/PSNR-example-comp-10.jpg -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /compression/image_data/example_wikipedia_image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hu8813/Python-1/HEAD/compression/image_data/example_wikipedia_image.jpg -------------------------------------------------------------------------------- /digital_image_processing/image_data/lena_small.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hu8813/Python-1/HEAD/digital_image_processing/image_data/lena_small.jpg -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /digital_image_processing/histogram_equalization/image_data/input.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hu8813/Python-1/HEAD/digital_image_processing/histogram_equalization/image_data/input.jpg -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /digital_image_processing/histogram_equalization/output_data/output.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hu8813/Python-1/HEAD/digital_image_processing/histogram_equalization/output_data/output.jpg -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | beautifulsoup4 2 | fake-useragent 3 | imageio 4 | keras 5 | lxml 6 | matplotlib 7 | numpy 8 | opencv-python 9 | pandas 10 | pillow 11 | requests 12 | rich 13 | scikit-learn 14 | sphinx-pyproject 15 | statsmodels 16 | sympy 17 | tweepy 18 | typing_extensions 19 | xgboost 20 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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/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@v5 16 | - run: uvx ruff check --output-format=github . 17 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /other/quine.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # ruff: noqa 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /web_programming/fetch_bbc_news.py: -------------------------------------------------------------------------------- 1 | # Created by sarathkaul on 12/11/19 2 | 3 | import requests 4 | 5 | _NEWS_API = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" 6 | 7 | 8 | def fetch_bbc_news(bbc_news_api_key: str) -> None: 9 | # fetching a list of articles in json format 10 | bbc_news_page = requests.get(_NEWS_API + bbc_news_api_key, timeout=10).json() 11 | # each article in the list is a dict 12 | for i, article in enumerate(bbc_news_page["articles"], 1): 13 | print(f"{i}.) {article['title']}") 14 | 15 | 16 | if __name__ == "__main__": 17 | fetch_bbc_news(bbc_news_api_key="") 18 | -------------------------------------------------------------------------------- /web_programming/giphy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import requests 3 | 4 | giphy_api_key = "YOUR API KEY" 5 | # Can be fetched from https://developers.giphy.com/dashboard/ 6 | 7 | 8 | def get_gifs(query: str, api_key: str = giphy_api_key) -> list: 9 | """ 10 | Get a list of URLs of GIFs based on a given query.. 11 | """ 12 | formatted_query = "+".join(query.split()) 13 | url = f"https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}" 14 | gifs = requests.get(url, timeout=10).json()["data"] 15 | return [gif["url"] for gif in gifs] 16 | 17 | 18 | if __name__ == "__main__": 19 | print("\n".join(get_gifs("space ship"))) 20 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /web_programming/instagram_video.py: -------------------------------------------------------------------------------- 1 | from datetime import UTC, datetime 2 | 3 | import requests 4 | 5 | 6 | def download_video(url: str) -> bytes: 7 | base_url = "https://downloadgram.net/wp-json/wppress/video-downloader/video?url=" 8 | video_url = requests.get(base_url + url, timeout=10).json()[0]["urls"][0]["src"] 9 | return requests.get(video_url, timeout=10).content 10 | 11 | 12 | if __name__ == "__main__": 13 | url = input("Enter Video/IGTV url: ").strip() 14 | file_name = f"{datetime.now(tz=UTC).astimezone():%Y-%m-%d_%H:%M:%S}.mp4" 15 | with open(file_name, "wb") as fp: 16 | fp.write(download_video(url)) 17 | print(f"Done. Video saved to disk as {file_name}.") 18 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /web_programming/slack_message.py: -------------------------------------------------------------------------------- 1 | # Created by sarathkaul on 12/11/19 2 | 3 | import requests 4 | 5 | 6 | def send_slack_message(message_body: str, slack_url: str) -> None: 7 | headers = {"Content-Type": "application/json"} 8 | response = requests.post( 9 | slack_url, json={"text": message_body}, headers=headers, timeout=10 10 | ) 11 | if response.status_code != 200: 12 | msg = ( 13 | "Request to slack returned an error " 14 | f"{response.status_code}, the response is:\n{response.text}" 15 | ) 16 | raise ValueError(msg) 17 | 18 | 19 | if __name__ == "__main__": 20 | # Set the slack url to the one provided by Slack when you create the webhook at 21 | # https://my.slack.com/services/new/incoming-webhook/ 22 | send_slack_message("", "") 23 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /web_programming/co2_emission.py: -------------------------------------------------------------------------------- 1 | """ 2 | Get CO2 emission data from the UK CarbonIntensity API 3 | """ 4 | 5 | from datetime import date 6 | 7 | import requests 8 | 9 | BASE_URL = "https://api.carbonintensity.org.uk/intensity" 10 | 11 | 12 | # Emission in the last half hour 13 | def fetch_last_half_hour() -> str: 14 | last_half_hour = requests.get(BASE_URL, timeout=10).json()["data"][0] 15 | return last_half_hour["intensity"]["actual"] 16 | 17 | 18 | # Emissions in a specific date range 19 | def fetch_from_to(start, end) -> list: 20 | return requests.get(f"{BASE_URL}/{start}/{end}", timeout=10).json()["data"] 21 | 22 | 23 | if __name__ == "__main__": 24 | for entry in fetch_from_to(start=date(2020, 10, 1), end=date(2020, 10, 3)): 25 | print("from {from} to {to}: {intensity[actual]}".format(**entry)) 26 | print(f"{fetch_last_half_hour() = }") 27 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /web_programming/crawl_google_results.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import webbrowser 3 | 4 | import requests 5 | from bs4 import BeautifulSoup 6 | from fake_useragent import UserAgent 7 | 8 | if __name__ == "__main__": 9 | print("Googling.....") 10 | url = "https://www.google.com/search?q=" + " ".join(sys.argv[1:]) 11 | res = requests.get(url, headers={"UserAgent": UserAgent().random}, timeout=10) 12 | # res.raise_for_status() 13 | with open("project1a.html", "wb") as out_file: # only for knowing the class 14 | for data in res.iter_content(10000): 15 | out_file.write(data) 16 | soup = BeautifulSoup(res.text, "html.parser") 17 | links = list(soup.select(".eZt8xd"))[:5] 18 | 19 | print(len(links)) 20 | for link in links: 21 | if link.text == "Maps": 22 | webbrowser.open(link.get("href")) 23 | else: 24 | webbrowser.open(f"https://google.com{link.get('href')}") 25 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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_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_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 | -------------------------------------------------------------------------------- /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_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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /web_programming/covid_stats_via_xpath.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is to show simple COVID19 info fetching from worldometers site using lxml 3 | * The main motivation to use lxml in place of bs4 is that it is faster and therefore 4 | more convenient to use in Python web projects (e.g. Django or Flask-based) 5 | """ 6 | 7 | from typing import NamedTuple 8 | 9 | import requests 10 | from lxml import html 11 | 12 | 13 | class CovidData(NamedTuple): 14 | cases: int 15 | deaths: int 16 | recovered: int 17 | 18 | 19 | def covid_stats(url: str = "https://www.worldometers.info/coronavirus/") -> CovidData: 20 | xpath_str = '//div[@class = "maincounter-number"]/span/text()' 21 | return CovidData( 22 | *html.fromstring(requests.get(url, timeout=10).content).xpath(xpath_str) 23 | ) 24 | 25 | 26 | fmt = """Total COVID-19 cases in the world: {} 27 | Total deaths due to COVID-19 in the world: {} 28 | Total COVID-19 patients recovered in the world: {}""" 29 | print(fmt.format(*covid_stats())) 30 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /web_programming/test_fetch_github_info.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | import requests 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(requests, "get", mock_response) 25 | result = fetch_github_info("token") 26 | assert result["login"] == "test" 27 | assert result["id"] == 1 28 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /web_programming/get_top_hn_posts.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import requests 4 | 5 | 6 | def get_hackernews_story(story_id: str) -> dict: 7 | url = f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" 8 | return requests.get(url, timeout=10).json() 9 | 10 | 11 | def hackernews_top_stories(max_stories: int = 10) -> list[dict]: 12 | """ 13 | Get the top max_stories posts from HackerNews - https://news.ycombinator.com/ 14 | """ 15 | url = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty" 16 | story_ids = requests.get(url, timeout=10).json()[:max_stories] 17 | return [get_hackernews_story(story_id) for story_id in story_ids] 18 | 19 | 20 | def hackernews_top_stories_as_markdown(max_stories: int = 10) -> str: 21 | stories = hackernews_top_stories(max_stories) 22 | return "\n".join("* [{title}]({url})".format(**story) for story in stories) 23 | 24 | 25 | if __name__ == "__main__": 26 | print(hackernews_top_stories_as_markdown()) 27 | -------------------------------------------------------------------------------- /boolean_algebra/and_gate.py: -------------------------------------------------------------------------------- 1 | """ 2 | An AND Gate is a logic gate in boolean algebra which results to 1 (True) if both the 3 | inputs are 1, and 0 (False) otherwise. 4 | 5 | Following is the truth table of an AND Gate: 6 | ------------------------------ 7 | | Input 1 | Input 2 | Output | 8 | ------------------------------ 9 | | 0 | 0 | 0 | 10 | | 0 | 1 | 0 | 11 | | 1 | 0 | 0 | 12 | | 1 | 1 | 1 | 13 | ------------------------------ 14 | 15 | Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ 16 | """ 17 | 18 | 19 | def and_gate(input_1: int, input_2: int) -> int: 20 | """ 21 | Calculate AND of the input values 22 | 23 | >>> and_gate(0, 0) 24 | 0 25 | >>> and_gate(0, 1) 26 | 0 27 | >>> and_gate(1, 0) 28 | 0 29 | >>> and_gate(1, 1) 30 | 1 31 | """ 32 | return int(input_1 and input_2) 33 | 34 | 35 | if __name__ == "__main__": 36 | import doctest 37 | 38 | doctest.testmod() 39 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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_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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.github/workflows/directory_writer.yml: -------------------------------------------------------------------------------- 1 | # The objective of this GitHub Action is to update the DIRECTORY.md file (if needed) 2 | # when doing a git push 3 | name: directory_writer 4 | on: [push] 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /web_programming/fetch_jobs.py: -------------------------------------------------------------------------------- 1 | """ 2 | Scraping jobs given job title and location from indeed website 3 | """ 4 | 5 | from __future__ import annotations 6 | 7 | from collections.abc import Generator 8 | 9 | import requests 10 | from bs4 import BeautifulSoup 11 | 12 | url = "https://www.indeed.co.in/jobs?q=mobile+app+development&l=" 13 | 14 | 15 | def fetch_jobs(location: str = "mumbai") -> Generator[tuple[str, str]]: 16 | soup = BeautifulSoup( 17 | requests.get(url + location, timeout=10).content, "html.parser" 18 | ) 19 | # This attribute finds out all the specifics listed in a job 20 | for job in soup.find_all("div", attrs={"data-tn-component": "organicJob"}): 21 | job_title = job.find("a", attrs={"data-tn-element": "jobTitle"}).text.strip() 22 | company_name = job.find("span", {"class": "company"}).text.strip() 23 | yield job_title, company_name 24 | 25 | 26 | if __name__ == "__main__": 27 | for i, job in enumerate(fetch_jobs("Bangalore"), 1): 28 | print(f"Job {i:>2} is {job[0]} at {job[1]}") 29 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /web_programming/fetch_quotes.py: -------------------------------------------------------------------------------- 1 | """ 2 | This file fetches quotes from the " ZenQuotes API ". 3 | It does not require any API key as it uses free tier. 4 | 5 | For more details and premium features visit: 6 | https://zenquotes.io/ 7 | """ 8 | 9 | import pprint 10 | 11 | import requests 12 | 13 | API_ENDPOINT_URL = "https://zenquotes.io/api" 14 | 15 | 16 | def quote_of_the_day() -> list: 17 | return requests.get(API_ENDPOINT_URL + "/today", timeout=10).json() 18 | 19 | 20 | def random_quotes() -> list: 21 | return requests.get(API_ENDPOINT_URL + "/random", timeout=10).json() 22 | 23 | 24 | if __name__ == "__main__": 25 | """ 26 | response object has all the info with the quote 27 | To retrieve the actual quote access the response.json() object as below 28 | response.json() is a list of json object 29 | response.json()[0]['q'] = actual quote. 30 | response.json()[0]['a'] = author name. 31 | response.json()[0]['h'] = in html format. 32 | """ 33 | response = random_quotes() 34 | pprint.pprint(response) 35 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /web_programming/world_covid19_stats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """ 4 | Provide the current worldwide COVID-19 statistics. 5 | This data is being scrapped from 'https://www.worldometers.info/coronavirus/'. 6 | """ 7 | 8 | import requests 9 | from bs4 import BeautifulSoup 10 | 11 | 12 | def world_covid19_stats(url: str = "https://www.worldometers.info/coronavirus") -> dict: 13 | """ 14 | Return a dict of current worldwide COVID-19 statistics 15 | """ 16 | soup = BeautifulSoup(requests.get(url, timeout=10).text, "html.parser") 17 | keys = soup.findAll("h1") 18 | values = soup.findAll("div", {"class": "maincounter-number"}) 19 | keys += soup.findAll("span", {"class": "panel-title"}) 20 | values += soup.findAll("div", {"class": "number-table-main"}) 21 | return {key.text.strip(): value.text.strip() for key, value in zip(keys, values)} 22 | 23 | 24 | if __name__ == "__main__": 25 | print("\033[1m COVID-19 Status of the World \033[0m\n") 26 | print("\n".join(f"{key}\n{value}" for key, value in world_covid19_stats().items())) 27 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/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_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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /web_programming/get_imdb_top_250_movies_csv.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import csv 4 | 5 | import requests 6 | from bs4 import BeautifulSoup 7 | 8 | 9 | def get_imdb_top_250_movies(url: str = "") -> dict[str, float]: 10 | url = url or "https://www.imdb.com/chart/top/?ref_=nv_mv_250" 11 | soup = BeautifulSoup(requests.get(url, timeout=10).text, "html.parser") 12 | titles = soup.find_all("td", attrs="titleColumn") 13 | ratings = soup.find_all("td", class_="ratingColumn imdbRating") 14 | return { 15 | title.a.text: float(rating.strong.text) 16 | for title, rating in zip(titles, ratings) 17 | } 18 | 19 | 20 | def write_movies(filename: str = "IMDb_Top_250_Movies.csv") -> None: 21 | movies = get_imdb_top_250_movies() 22 | with open(filename, "w", newline="") as out_file: 23 | writer = csv.writer(out_file) 24 | writer.writerow(["Movie title", "IMDb rating"]) 25 | for title, rating in movies.items(): 26 | writer.writerow([title, rating]) 27 | 28 | 29 | if __name__ == "__main__": 30 | write_movies() 31 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /web_programming/open_google_results.py: -------------------------------------------------------------------------------- 1 | import webbrowser 2 | from sys import argv 3 | from urllib.parse import parse_qs, quote 4 | 5 | import requests 6 | from bs4 import BeautifulSoup 7 | from fake_useragent import UserAgent 8 | 9 | if __name__ == "__main__": 10 | query = "%20".join(argv[1:]) if len(argv) > 1 else quote(str(input("Search: "))) 11 | 12 | print("Googling.....") 13 | 14 | url = f"https://www.google.com/search?q={query}&num=100" 15 | 16 | res = requests.get( 17 | url, 18 | headers={"User-Agent": str(UserAgent().random)}, 19 | timeout=10, 20 | ) 21 | 22 | try: 23 | link = ( 24 | BeautifulSoup(res.text, "html.parser") 25 | .find("div", attrs={"class": "yuRUbf"}) 26 | .find("a") 27 | .get("href") 28 | ) 29 | 30 | except AttributeError: 31 | link = parse_qs( 32 | BeautifulSoup(res.text, "html.parser") 33 | .find("div", attrs={"class": "kCrYT"}) 34 | .find("a") 35 | .get("href") 36 | )["url"][0] 37 | 38 | webbrowser.open(link) 39 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /web_programming/crawl_google_scholar_citation.py: -------------------------------------------------------------------------------- 1 | """ 2 | Get the citation from google scholar 3 | using title and year of publication, and volume and pages of journal. 4 | """ 5 | 6 | import requests 7 | from bs4 import BeautifulSoup 8 | 9 | 10 | def get_citation(base_url: str, params: dict) -> str: 11 | """ 12 | Return the citation number. 13 | """ 14 | soup = BeautifulSoup( 15 | requests.get(base_url, params=params, timeout=10).content, "html.parser" 16 | ) 17 | div = soup.find("div", attrs={"class": "gs_ri"}) 18 | anchors = div.find("div", attrs={"class": "gs_fl"}).find_all("a") 19 | return anchors[2].get_text() 20 | 21 | 22 | if __name__ == "__main__": 23 | params = { 24 | "title": ( 25 | "Precisely geometry controlled microsupercapacitors for ultrahigh areal " 26 | "capacitance, volumetric capacitance, and energy density" 27 | ), 28 | "journal": "Chem. Mater.", 29 | "volume": 30, 30 | "pages": "3979-3990", 31 | "year": 2018, 32 | "hl": "en", 33 | } 34 | print(get_citation("https://scholar.google.com/scholar_lookup", params=params)) 35 | -------------------------------------------------------------------------------- /data_structures/stacks/lexicographical_numbers.py: -------------------------------------------------------------------------------- 1 | from collections.abc import Iterator 2 | 3 | 4 | def lexical_order(max_number: int) -> Iterator[int]: 5 | """ 6 | Generate numbers in lexical order from 1 to max_number. 7 | 8 | >>> " ".join(map(str, lexical_order(13))) 9 | '1 10 11 12 13 2 3 4 5 6 7 8 9' 10 | >>> list(lexical_order(1)) 11 | [1] 12 | >>> " ".join(map(str, lexical_order(20))) 13 | '1 10 11 12 13 14 15 16 17 18 19 2 20 3 4 5 6 7 8 9' 14 | >>> " ".join(map(str, lexical_order(25))) 15 | '1 10 11 12 13 14 15 16 17 18 19 2 20 21 22 23 24 25 3 4 5 6 7 8 9' 16 | >>> list(lexical_order(12)) 17 | [1, 10, 11, 12, 2, 3, 4, 5, 6, 7, 8, 9] 18 | """ 19 | 20 | stack = [1] 21 | 22 | while stack: 23 | num = stack.pop() 24 | if num > max_number: 25 | continue 26 | 27 | yield num 28 | if (num % 10) != 9: 29 | stack.append(num + 1) 30 | 31 | stack.append(num * 10) 32 | 33 | 34 | if __name__ == "__main__": 35 | from doctest import testmod 36 | 37 | testmod() 38 | print(f"Numbers from 1 to 25 in lexical order: {list(lexical_order(26))}") 39 | -------------------------------------------------------------------------------- /file_transfer/tests/test_send_file.py: -------------------------------------------------------------------------------- 1 | from unittest.mock import Mock, patch 2 | 3 | from file_transfer.send_file import send_file 4 | 5 | 6 | @patch("socket.socket") 7 | @patch("builtins.open") 8 | def test_send_file_running_as_expected(file, sock): 9 | # ===== initialization ===== 10 | conn = Mock() 11 | sock.return_value.accept.return_value = conn, Mock() 12 | f = iter([1, None]) 13 | file.return_value.__enter__.return_value.read.side_effect = lambda _: next(f) 14 | 15 | # ===== invoke ===== 16 | send_file(filename="mytext.txt", testing=True) 17 | 18 | # ===== ensurance ===== 19 | sock.assert_called_once() 20 | sock.return_value.bind.assert_called_once() 21 | sock.return_value.listen.assert_called_once() 22 | sock.return_value.accept.assert_called_once() 23 | conn.recv.assert_called_once() 24 | 25 | file.return_value.__enter__.assert_called_once() 26 | file.return_value.__enter__.return_value.read.assert_called() 27 | 28 | conn.send.assert_called_once() 29 | conn.close.assert_called_once() 30 | sock.return_value.shutdown.assert_called_once() 31 | sock.return_value.close.assert_called_once() 32 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | ## MIT License 2 | 3 | Copyright (c) 2016-2022 TheAlgorithms and contributors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /graphs/g_topological_sort.py: -------------------------------------------------------------------------------- 1 | # Author: Phyllipe Bezerra (https://github.com/pmba) 2 | 3 | clothes = { 4 | 0: "underwear", 5 | 1: "pants", 6 | 2: "belt", 7 | 3: "suit", 8 | 4: "shoe", 9 | 5: "socks", 10 | 6: "shirt", 11 | 7: "tie", 12 | 8: "watch", 13 | } 14 | 15 | graph = [[1, 4], [2, 4], [3], [], [], [4], [2, 7], [3], []] 16 | 17 | visited = [0 for x in range(len(graph))] 18 | stack = [] 19 | 20 | 21 | def print_stack(stack, clothes): 22 | order = 1 23 | while stack: 24 | current_clothing = stack.pop() 25 | print(order, clothes[current_clothing]) 26 | order += 1 27 | 28 | 29 | def depth_first_search(u, visited, graph): 30 | visited[u] = 1 31 | for v in graph[u]: 32 | if not visited[v]: 33 | depth_first_search(v, visited, graph) 34 | 35 | stack.append(u) 36 | 37 | 38 | def topological_sort(graph, visited): 39 | for v in range(len(graph)): 40 | if not visited[v]: 41 | depth_first_search(v, visited, graph) 42 | 43 | 44 | if __name__ == "__main__": 45 | topological_sort(graph, visited) 46 | print(stack) 47 | print_stack(stack, clothes) 48 | -------------------------------------------------------------------------------- /maths/mobius_function.py: -------------------------------------------------------------------------------- 1 | """ 2 | References: https://en.wikipedia.org/wiki/M%C3%B6bius_function 3 | References: wikipedia:square free number 4 | psf/black : True 5 | ruff : True 6 | """ 7 | 8 | from maths.is_square_free import is_square_free 9 | from maths.prime_factors import prime_factors 10 | 11 | 12 | def mobius(n: int) -> int: 13 | """ 14 | Mobius function 15 | >>> mobius(24) 16 | 0 17 | >>> mobius(-1) 18 | 1 19 | >>> mobius('asd') 20 | Traceback (most recent call last): 21 | ... 22 | TypeError: '<=' not supported between instances of 'int' and 'str' 23 | >>> mobius(10**400) 24 | 0 25 | >>> mobius(10**-400) 26 | 1 27 | >>> mobius(-1424) 28 | 1 29 | >>> mobius([1, '2', 2.0]) 30 | Traceback (most recent call last): 31 | ... 32 | TypeError: '<=' not supported between instances of 'int' and 'list' 33 | """ 34 | factors = prime_factors(n) 35 | if is_square_free(factors): 36 | return -1 if len(factors) % 2 else 1 37 | return 0 38 | 39 | 40 | if __name__ == "__main__": 41 | import doctest 42 | 43 | doctest.testmod() 44 | -------------------------------------------------------------------------------- /maths/lucas_lehmer_primality_test.py: -------------------------------------------------------------------------------- 1 | """ 2 | In mathematics, the Lucas-Lehmer test (LLT) is a primality test for Mersenne 3 | numbers. https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test 4 | 5 | A Mersenne number is a number that is one less than a power of two. 6 | That is M_p = 2^p - 1 7 | https://en.wikipedia.org/wiki/Mersenne_prime 8 | 9 | The Lucas-Lehmer test is the primality test used by the 10 | Great Internet Mersenne Prime Search (GIMPS) to locate large primes. 11 | """ 12 | 13 | 14 | # Primality test 2^p - 1 15 | # Return true if 2^p - 1 is prime 16 | def lucas_lehmer_test(p: int) -> bool: 17 | """ 18 | >>> lucas_lehmer_test(p=7) 19 | True 20 | 21 | >>> lucas_lehmer_test(p=11) 22 | False 23 | 24 | # M_11 = 2^11 - 1 = 2047 = 23 * 89 25 | """ 26 | 27 | if p < 2: 28 | raise ValueError("p should not be less than 2!") 29 | elif p == 2: 30 | return True 31 | 32 | s = 4 33 | m = (1 << p) - 1 34 | for _ in range(p - 2): 35 | s = ((s * s) - 2) % m 36 | return s == 0 37 | 38 | 39 | if __name__ == "__main__": 40 | print(lucas_lehmer_test(7)) 41 | print(lucas_lehmer_test(11)) 42 | -------------------------------------------------------------------------------- /project_euler/problem_034/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem 34: https://projecteuler.net/problem=34 3 | 4 | 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. 5 | Find the sum of all numbers which are equal to the sum of the factorial of their digits. 6 | Note: As 1! = 1 and 2! = 2 are not sums they are not included. 7 | """ 8 | 9 | from math import factorial 10 | 11 | DIGIT_FACTORIAL = {str(d): factorial(d) for d in range(10)} 12 | 13 | 14 | def sum_of_digit_factorial(n: int) -> int: 15 | """ 16 | Returns the sum of the factorial of digits in n 17 | >>> sum_of_digit_factorial(15) 18 | 121 19 | >>> sum_of_digit_factorial(0) 20 | 1 21 | """ 22 | return sum(DIGIT_FACTORIAL[d] for d in str(n)) 23 | 24 | 25 | def solution() -> int: 26 | """ 27 | Returns the sum of all numbers whose 28 | sum of the factorials of all digits 29 | add up to the number itself. 30 | >>> solution() 31 | 40730 32 | """ 33 | limit = 7 * factorial(9) + 1 34 | return sum(i for i in range(3, limit) if sum_of_digit_factorial(i) == i) 35 | 36 | 37 | if __name__ == "__main__": 38 | print(f"{solution() = }") 39 | -------------------------------------------------------------------------------- /audio_filters/loudness_curve.json: -------------------------------------------------------------------------------- 1 | { 2 | "_comment": "The following is a representative average of the Equal Loudness Contours as measured by Robinson and Dadson, 1956", 3 | "_doi": "10.1088/0508-3443/7/5/302", 4 | "frequencies": [ 5 | 0, 6 | 20, 7 | 30, 8 | 40, 9 | 50, 10 | 60, 11 | 70, 12 | 80, 13 | 90, 14 | 100, 15 | 200, 16 | 300, 17 | 400, 18 | 500, 19 | 600, 20 | 700, 21 | 800, 22 | 900, 23 | 1000, 24 | 1500, 25 | 2000, 26 | 2500, 27 | 3000, 28 | 3700, 29 | 4000, 30 | 5000, 31 | 6000, 32 | 7000, 33 | 8000, 34 | 9000, 35 | 10000, 36 | 12000, 37 | 15000, 38 | 20000 39 | ], 40 | "gains": [ 41 | 120, 42 | 113, 43 | 103, 44 | 97, 45 | 93, 46 | 91, 47 | 89, 48 | 87, 49 | 86, 50 | 85, 51 | 78, 52 | 76, 53 | 76, 54 | 76, 55 | 76, 56 | 77, 57 | 78, 58 | 79.5, 59 | 80, 60 | 79, 61 | 77, 62 | 74, 63 | 71.5, 64 | 70, 65 | 70.5, 66 | 74, 67 | 79, 68 | 84, 69 | 86, 70 | 86, 71 | 85, 72 | 95, 73 | 110, 74 | 125 75 | ] 76 | } 77 | -------------------------------------------------------------------------------- /web_programming/daily_horoscope.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup 3 | 4 | 5 | def horoscope(zodiac_sign: int, day: str) -> str: 6 | url = ( 7 | "https://www.horoscope.com/us/horoscopes/general/" 8 | f"horoscope-general-daily-{day}.aspx?sign={zodiac_sign}" 9 | ) 10 | soup = BeautifulSoup(requests.get(url, timeout=10).content, "html.parser") 11 | return soup.find("div", class_="main-horoscope").p.text 12 | 13 | 14 | if __name__ == "__main__": 15 | print("Daily Horoscope. \n") 16 | print( 17 | "enter your Zodiac sign number:\n", 18 | "1. Aries\n", 19 | "2. Taurus\n", 20 | "3. Gemini\n", 21 | "4. Cancer\n", 22 | "5. Leo\n", 23 | "6. Virgo\n", 24 | "7. Libra\n", 25 | "8. Scorpio\n", 26 | "9. Sagittarius\n", 27 | "10. Capricorn\n", 28 | "11. Aquarius\n", 29 | "12. Pisces\n", 30 | ) 31 | zodiac_sign = int(input("number> ").strip()) 32 | print("choose some day:\n", "yesterday\n", "today\n", "tomorrow\n") 33 | day = input("enter the day> ") 34 | horoscope_text = horoscope(zodiac_sign, day) 35 | print(horoscope_text) 36 | -------------------------------------------------------------------------------- /project_euler/problem_004/sol2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Project Euler Problem 4: https://projecteuler.net/problem=4 3 | 4 | Largest palindrome product 5 | 6 | A palindromic number reads the same both ways. The largest palindrome made 7 | from the product of two 2-digit numbers is 9009 = 91 x 99. 8 | 9 | Find the largest palindrome made from the product of two 3-digit numbers. 10 | 11 | References: 12 | - https://en.wikipedia.org/wiki/Palindromic_number 13 | """ 14 | 15 | 16 | def solution(n: int = 998001) -> int: 17 | """ 18 | Returns the largest palindrome made from the product of two 3-digit 19 | numbers which is less than n. 20 | 21 | >>> solution(20000) 22 | 19591 23 | >>> solution(30000) 24 | 29992 25 | >>> solution(40000) 26 | 39893 27 | """ 28 | 29 | answer = 0 30 | for i in range(999, 99, -1): # 3 digit numbers range from 999 down to 100 31 | for j in range(999, 99, -1): 32 | product_string = str(i * j) 33 | if product_string == product_string[::-1] and i * j < n: 34 | answer = max(answer, i * j) 35 | return answer 36 | 37 | 38 | if __name__ == "__main__": 39 | print(f"{solution() = }") 40 | -------------------------------------------------------------------------------- /file_transfer/send_file.py: -------------------------------------------------------------------------------- 1 | def send_file(filename: str = "mytext.txt", testing: bool = False) -> None: 2 | import socket 3 | 4 | port = 12312 # Reserve a port for your service. 5 | sock = socket.socket() # Create a socket object 6 | host = socket.gethostname() # Get local machine name 7 | sock.bind((host, port)) # Bind to the port 8 | sock.listen(5) # Now wait for client connection. 9 | 10 | print("Server listening....") 11 | 12 | while True: 13 | conn, addr = sock.accept() # Establish connection with client. 14 | print(f"Got connection from {addr}") 15 | data = conn.recv(1024) 16 | print(f"Server received: {data = }") 17 | 18 | with open(filename, "rb") as in_file: 19 | data = in_file.read(1024) 20 | while data: 21 | conn.send(data) 22 | print(f"Sent {data!r}") 23 | data = in_file.read(1024) 24 | 25 | print("Done sending") 26 | conn.close() 27 | if testing: # Allow the test to complete 28 | break 29 | 30 | sock.shutdown(1) 31 | sock.close() 32 | 33 | 34 | if __name__ == "__main__": 35 | send_file() 36 | -------------------------------------------------------------------------------- /project_euler/problem_002/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Project Euler Problem 2: https://projecteuler.net/problem=2 3 | 4 | Even Fibonacci Numbers 5 | 6 | Each new term in the Fibonacci sequence is generated by adding the previous 7 | two terms. By starting with 1 and 2, the first 10 terms will be: 8 | 9 | 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... 10 | 11 | By considering the terms in the Fibonacci sequence whose values do not exceed 12 | four million, find the sum of the even-valued terms. 13 | 14 | References: 15 | - https://en.wikipedia.org/wiki/Fibonacci_number 16 | """ 17 | 18 | 19 | def solution(n: int = 4000000) -> int: 20 | """ 21 | Returns the sum of all even fibonacci sequence elements that are lower 22 | or equal to n. 23 | 24 | >>> solution(10) 25 | 10 26 | >>> solution(15) 27 | 10 28 | >>> solution(2) 29 | 2 30 | >>> solution(1) 31 | 0 32 | >>> solution(34) 33 | 44 34 | """ 35 | 36 | i = 1 37 | j = 2 38 | total = 0 39 | while j <= n: 40 | if j % 2 == 0: 41 | total += j 42 | i, j = j, i + j 43 | 44 | return total 45 | 46 | 47 | if __name__ == "__main__": 48 | print(f"{solution() = }") 49 | -------------------------------------------------------------------------------- /strings/alternative_string_arrange.py: -------------------------------------------------------------------------------- 1 | def alternative_string_arrange(first_str: str, second_str: str) -> str: 2 | """ 3 | Return the alternative arrangements of the two strings. 4 | :param first_str: 5 | :param second_str: 6 | :return: String 7 | >>> alternative_string_arrange("ABCD", "XY") 8 | 'AXBYCD' 9 | >>> alternative_string_arrange("XY", "ABCD") 10 | 'XAYBCD' 11 | >>> alternative_string_arrange("AB", "XYZ") 12 | 'AXBYZ' 13 | >>> alternative_string_arrange("ABC", "") 14 | 'ABC' 15 | """ 16 | first_str_length: int = len(first_str) 17 | second_str_length: int = len(second_str) 18 | abs_length: int = ( 19 | first_str_length if first_str_length > second_str_length else second_str_length 20 | ) 21 | output_list: list = [] 22 | for char_count in range(abs_length): 23 | if char_count < first_str_length: 24 | output_list.append(first_str[char_count]) 25 | if char_count < second_str_length: 26 | output_list.append(second_str[char_count]) 27 | return "".join(output_list) 28 | 29 | 30 | if __name__ == "__main__": 31 | print(alternative_string_arrange("AB", "XYZ"), end=" ") 32 | -------------------------------------------------------------------------------- /maths/remove_digit.py: -------------------------------------------------------------------------------- 1 | def remove_digit(num: int) -> int: 2 | """ 3 | 4 | returns the biggest possible result 5 | that can be achieved by removing 6 | one digit from the given number 7 | 8 | >>> remove_digit(152) 9 | 52 10 | >>> remove_digit(6385) 11 | 685 12 | >>> remove_digit(-11) 13 | 1 14 | >>> remove_digit(2222222) 15 | 222222 16 | >>> remove_digit("2222222") 17 | Traceback (most recent call last): 18 | TypeError: only integers accepted as input 19 | >>> remove_digit("string input") 20 | Traceback (most recent call last): 21 | TypeError: only integers accepted as input 22 | """ 23 | 24 | if not isinstance(num, int): 25 | raise TypeError("only integers accepted as input") 26 | else: 27 | num_str = str(abs(num)) 28 | num_transpositions = [list(num_str) for char in range(len(num_str))] 29 | for index in range(len(num_str)): 30 | num_transpositions[index].pop(index) 31 | return max( 32 | int("".join(list(transposition))) for transposition in num_transpositions 33 | ) 34 | 35 | 36 | if __name__ == "__main__": 37 | __import__("doctest").testmod() 38 | -------------------------------------------------------------------------------- /project_euler/problem_002/sol2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Project Euler Problem 2: https://projecteuler.net/problem=2 3 | 4 | Even Fibonacci Numbers 5 | 6 | Each new term in the Fibonacci sequence is generated by adding the previous 7 | two terms. By starting with 1 and 2, the first 10 terms will be: 8 | 9 | 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... 10 | 11 | By considering the terms in the Fibonacci sequence whose values do not exceed 12 | four million, find the sum of the even-valued terms. 13 | 14 | References: 15 | - https://en.wikipedia.org/wiki/Fibonacci_number 16 | """ 17 | 18 | 19 | def solution(n: int = 4000000) -> int: 20 | """ 21 | Returns the sum of all even fibonacci sequence elements that are lower 22 | or equal to n. 23 | 24 | >>> solution(10) 25 | 10 26 | >>> solution(15) 27 | 10 28 | >>> solution(2) 29 | 2 30 | >>> solution(1) 31 | 0 32 | >>> solution(34) 33 | 44 34 | """ 35 | 36 | even_fibs = [] 37 | a, b = 0, 1 38 | while b <= n: 39 | if b % 2 == 0: 40 | even_fibs.append(b) 41 | a, b = b, a + b 42 | return sum(even_fibs) 43 | 44 | 45 | if __name__ == "__main__": 46 | print(f"{solution() = }") 47 | -------------------------------------------------------------------------------- /project_euler/problem_099/sol1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: 3 | 4 | Comparing two numbers written in index form like 2'11 and 3'7 is not difficult, as any 5 | calculator would confirm that 2^11 = 2048 < 3^7 = 2187. 6 | 7 | However, confirming that 632382^518061 > 519432^525806 would be much more difficult, as 8 | both numbers contain over three million digits. 9 | 10 | Using base_exp.txt, a 22K text file containing one thousand lines with a base/exponent 11 | pair on each line, determine which line number has the greatest numerical value. 12 | 13 | NOTE: The first two lines in the file represent the numbers in the example given above. 14 | """ 15 | 16 | import os 17 | from math import log10 18 | 19 | 20 | def solution(data_file: str = "base_exp.txt") -> int: 21 | """ 22 | >>> solution() 23 | 709 24 | """ 25 | largest: float = 0 26 | result = 0 27 | for i, line in enumerate(open(os.path.join(os.path.dirname(__file__), data_file))): 28 | a, x = list(map(int, line.split(","))) 29 | if x * log10(a) > largest: 30 | largest = x * log10(a) 31 | result = i + 1 32 | return result 33 | 34 | 35 | if __name__ == "__main__": 36 | print(solution()) 37 | --------------------------------------------------------------------------------